1 /*
2  * filter_jackrack.c -- filter audio through Jack and/or LADSPA plugins
3  * Copyright (C) 2004-2014 Meltytech, LLC
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18  */
19 
20 #include <framework/mlt.h>
21 
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <sys/types.h>
25 #include <unistd.h>
26 
27 #include <pthread.h>
28 #include <jack/jack.h>
29 #include <jack/ringbuffer.h>
30 #include <string.h>
31 
32 #include "jack_rack.h"
33 
34 extern pthread_mutex_t g_activate_mutex;
35 
36 #define BUFFER_LEN 204800 * 6
37 
jack_started_transmitter(mlt_listener listener,mlt_properties owner,mlt_service service,void ** args)38 static void jack_started_transmitter( mlt_listener listener, mlt_properties owner, mlt_service service, void **args )
39 {
40 	listener( owner, service, (mlt_position*) args[0] );
41 }
42 
jack_stopped_transmitter(mlt_listener listener,mlt_properties owner,mlt_service service,void ** args)43 static void jack_stopped_transmitter( mlt_listener listener, mlt_properties owner, mlt_service service, void **args )
44 {
45 	listener( owner, service, (mlt_position*) args[0] );
46 }
47 
jack_seek_transmitter(mlt_listener listener,mlt_properties owner,mlt_service service,void ** args)48 static void jack_seek_transmitter( mlt_listener listener, mlt_properties owner, mlt_service service, void **args )
49 {
50 	listener( owner, service, (mlt_position*) args[0] );
51 }
52 
53 #define JACKSTATE(x) (x==JackTransportStopped?"stopped":x==JackTransportStarting?"starting":x==JackTransportRolling?"rolling":"unknown")
54 
jack_sync(jack_transport_state_t state,jack_position_t * jack_pos,void * arg)55 static int jack_sync( jack_transport_state_t state, jack_position_t *jack_pos, void *arg )
56 {
57 	mlt_filter filter = (mlt_filter) arg;
58 	mlt_properties properties = MLT_FILTER_PROPERTIES( filter );
59 	mlt_profile profile = mlt_service_profile( MLT_FILTER_SERVICE(filter) );
60 	mlt_position position = mlt_profile_fps( profile ) * jack_pos->frame / jack_pos->frame_rate + 0.5;
61 	int result = 1;
62 
63 	mlt_log_debug( MLT_FILTER_SERVICE(filter), "%s frame %u rate %u pos %d last_pos %d\n",
64 		JACKSTATE(state), jack_pos->frame, jack_pos->frame_rate, position,
65 		mlt_properties_get_position( properties, "_last_pos" ) );
66 	if ( state == JackTransportStopped )
67 	{
68 		mlt_events_fire( properties, "jack-stopped", &position, NULL );
69 		mlt_properties_set_int( properties, "_sync_guard", 0 );
70 	}
71 	else if ( state == JackTransportStarting )
72 	{
73 		result = 0;
74 		if ( !mlt_properties_get_int( properties, "_sync_guard" ) )
75 		{
76 			mlt_properties_set_int( properties, "_sync_guard", 1 );
77 			mlt_events_fire( properties, "jack-started", &position, NULL );
78 		}
79 		else if ( position >= mlt_properties_get_position( properties, "_last_pos" ) - 2 )
80 		{
81 			mlt_properties_set_int( properties, "_sync_guard", 0 );
82 			result = 1;
83 		}
84 	}
85 	else
86 	{
87 		mlt_properties_set_int( properties, "_sync_guard", 0 );
88 	}
89 
90 	return result;
91 }
92 
on_jack_start(mlt_properties owner,mlt_properties properties)93 static void on_jack_start( mlt_properties owner, mlt_properties properties )
94 {
95 	mlt_log_verbose( NULL, "%s\n", __FUNCTION__ );
96 	jack_client_t *jack_client = mlt_properties_get_data( properties, "jack_client", NULL );
97 	jack_transport_start( jack_client );
98 }
99 
on_jack_stop(mlt_properties owner,mlt_properties properties)100 static void on_jack_stop( mlt_properties owner, mlt_properties properties )
101 {
102 	mlt_log_verbose( NULL, "%s\n", __FUNCTION__ );
103 	jack_client_t *jack_client = mlt_properties_get_data( properties, "jack_client", NULL );
104 	jack_transport_stop( jack_client );
105 }
106 
on_jack_seek(mlt_properties owner,mlt_filter filter,mlt_position * position)107 static void on_jack_seek( mlt_properties owner, mlt_filter filter, mlt_position *position )
108 {
109 	mlt_properties properties = MLT_FILTER_PROPERTIES( filter );
110 	mlt_log_verbose( MLT_FILTER_SERVICE(filter), "%s: %d\n", __FUNCTION__, *position );
111 	mlt_properties_set_int( properties, "_sync_guard", 1 );
112 	mlt_profile profile = mlt_service_profile( MLT_FILTER_SERVICE( filter ) );
113 	jack_client_t *jack_client = mlt_properties_get_data( properties, "jack_client", NULL );
114 	jack_nframes_t jack_frame = jack_get_sample_rate( jack_client );
115 	jack_frame *= *position / mlt_profile_fps( profile );
116 	jack_transport_locate( jack_client, jack_frame );
117 }
118 
initialise_jack_ports(mlt_properties properties)119 static void initialise_jack_ports( mlt_properties properties )
120 {
121 	int i;
122 	char mlt_name[67], rack_name[30];
123 	jack_port_t **port = NULL;
124 	jack_client_t *jack_client = mlt_properties_get_data( properties, "jack_client", NULL );
125 	jack_nframes_t jack_buffer_size = jack_get_buffer_size( jack_client );
126 
127 	// Propagate these for the Jack processing callback
128 	int channels = mlt_properties_get_int( properties, "channels" );
129 
130 	// Start JackRack
131 	if ( mlt_properties_get( properties, "src" ) )
132 	{
133 		snprintf( rack_name, sizeof( rack_name ), "jackrack%d", getpid() );
134 		jack_rack_t *jackrack = jack_rack_new( rack_name, mlt_properties_get_int( properties, "channels" ) );
135 		jack_rack_open_file( jackrack, mlt_properties_get( properties, "src" ) );
136 
137 		mlt_properties_set_data( properties, "jackrack", jackrack, 0,
138 			(mlt_destructor) jack_rack_destroy, NULL );
139 		mlt_properties_set( properties, "_rack_client_name", rack_name );
140 	}
141 	else
142 	{
143 		// We have to set this to something to prevent re-initialization.
144 		mlt_properties_set_data( properties, "jackrack", jack_client, 0, NULL, NULL );
145 	}
146 
147 	// Allocate buffers and ports
148 	jack_ringbuffer_t **output_buffers = mlt_pool_alloc( sizeof( jack_ringbuffer_t *) * channels );
149 	jack_ringbuffer_t **input_buffers = mlt_pool_alloc( sizeof( jack_ringbuffer_t *) * channels );
150 	jack_port_t **jack_output_ports = mlt_pool_alloc( sizeof(jack_port_t *) * channels );
151 	jack_port_t **jack_input_ports = mlt_pool_alloc( sizeof(jack_port_t *) * channels );
152 	float **jack_output_buffers = mlt_pool_alloc( sizeof(float *) * jack_buffer_size );
153 	float **jack_input_buffers = mlt_pool_alloc( sizeof(float *) * jack_buffer_size );
154 
155 	// Set properties - released inside filter_close
156 	mlt_properties_set_data( properties, "output_buffers", output_buffers,
157 		sizeof( jack_ringbuffer_t *) * channels, mlt_pool_release, NULL );
158 	mlt_properties_set_data( properties, "input_buffers", input_buffers,
159 		sizeof( jack_ringbuffer_t *) * channels, mlt_pool_release, NULL );
160 	mlt_properties_set_data( properties, "jack_output_ports", jack_output_ports,
161 		sizeof( jack_port_t *) * channels, mlt_pool_release, NULL );
162 	mlt_properties_set_data( properties, "jack_input_ports", jack_input_ports,
163 		sizeof( jack_port_t *) * channels, mlt_pool_release, NULL );
164 	mlt_properties_set_data( properties, "jack_output_buffers", jack_output_buffers,
165 		sizeof( float *) * channels, mlt_pool_release, NULL );
166 	mlt_properties_set_data( properties, "jack_input_buffers", jack_input_buffers,
167 		sizeof( float *) * channels, mlt_pool_release, NULL );
168 
169 	// Register Jack ports
170 	for ( i = 0; i < channels; i++ )
171 	{
172 		int in;
173 
174 		output_buffers[i] = jack_ringbuffer_create( BUFFER_LEN * sizeof(float) );
175 		input_buffers[i] = jack_ringbuffer_create( BUFFER_LEN * sizeof(float) );
176 		snprintf( mlt_name, sizeof( mlt_name ), "obuf%d", i );
177 		mlt_properties_set_data( properties, mlt_name, output_buffers[i],
178 			BUFFER_LEN * sizeof(float), (mlt_destructor) jack_ringbuffer_free, NULL );
179 		snprintf( mlt_name, sizeof( mlt_name ), "ibuf%d", i );
180 		mlt_properties_set_data( properties, mlt_name, input_buffers[i],
181 			BUFFER_LEN * sizeof(float), (mlt_destructor) jack_ringbuffer_free, NULL );
182 
183 		for ( in = 0; in < 2; in++ )
184 		{
185 			snprintf( mlt_name, sizeof( mlt_name ), "%s_%d", in ? "in" : "out", i + 1);
186 			port = ( in ? &jack_input_ports[i] : &jack_output_ports[i] );
187 
188 			*port =  jack_port_register( jack_client, mlt_name, JACK_DEFAULT_AUDIO_TYPE,
189 				( in ? JackPortIsInput : JackPortIsOutput ) | JackPortIsTerminal, 0 );
190 		}
191 	}
192 
193 	// Start Jack processing
194 	pthread_mutex_lock( &g_activate_mutex );
195 	jack_activate( jack_client );
196 	pthread_mutex_unlock( &g_activate_mutex  );
197 
198 	// Establish connections
199 	for ( i = 0; i < channels; i++ )
200 	{
201 		int in;
202 		for ( in = 0; in < 2; in++ )
203 		{
204 			port = ( in ? &jack_input_ports[i] : &jack_output_ports[i] );
205 			snprintf( mlt_name, sizeof( mlt_name ), "%s", jack_port_name( *port ) );
206 
207 			snprintf( rack_name, sizeof( rack_name ), "%s_%d", in ? "in" : "out", i + 1 );
208 			if ( mlt_properties_get( properties, "_rack_client_name" ) )
209 				snprintf( rack_name, sizeof( rack_name ), "%s:%s_%d", mlt_properties_get( properties, "_rack_client_name" ), in ? "out" : "in", i + 1);
210 			else if ( mlt_properties_get( properties, rack_name ) )
211 				snprintf( rack_name, sizeof( rack_name ), "%s", mlt_properties_get( properties, rack_name ) );
212 			else
213 				snprintf( rack_name, sizeof( rack_name ), "%s:%s_%d", mlt_properties_get( properties, "client_name" ), in ? "out" : "in", i + 1);
214 
215 			if ( in )
216 			{
217 				mlt_log_verbose( NULL, "JACK connect %s to %s\n", rack_name, mlt_name );
218 				jack_connect( jack_client, rack_name, mlt_name );
219 			}
220 			else
221 			{
222 				mlt_log_verbose( NULL, "JACK connect %s to %s\n", mlt_name, rack_name );
223 				jack_connect( jack_client, mlt_name, rack_name );
224 			}
225 		}
226 	}
227 }
228 
jack_process(jack_nframes_t frames,void * data)229 static int jack_process (jack_nframes_t frames, void * data)
230 {
231 	mlt_filter filter = (mlt_filter) data;
232  	mlt_properties properties = MLT_FILTER_PROPERTIES( filter );
233 	int channels = mlt_properties_get_int( properties, "channels" );
234 	int frame_size = mlt_properties_get_int( properties, "_samples" ) * sizeof(float);
235 	int sync = mlt_properties_get_int( properties, "_sync" );
236 	int err = 0;
237 	int i;
238 	static int total_size = 0;
239 
240 	jack_ringbuffer_t **output_buffers = mlt_properties_get_data( properties, "output_buffers", NULL );
241 	if ( output_buffers == NULL )
242 		return 0;
243 	jack_ringbuffer_t **input_buffers = mlt_properties_get_data( properties, "input_buffers", NULL );
244 	jack_port_t **jack_output_ports = mlt_properties_get_data( properties, "jack_output_ports", NULL );
245 	jack_port_t **jack_input_ports = mlt_properties_get_data( properties, "jack_input_ports", NULL );
246 	float **jack_output_buffers = mlt_properties_get_data( properties, "jack_output_buffers", NULL );
247 	float **jack_input_buffers = mlt_properties_get_data( properties, "jack_input_buffers", NULL );
248 	pthread_mutex_t *output_lock = mlt_properties_get_data( properties, "output_lock", NULL );
249 	pthread_cond_t *output_ready = mlt_properties_get_data( properties, "output_ready", NULL );
250 
251 	for ( i = 0; i < channels; i++ )
252 	{
253 		size_t jack_size = ( frames * sizeof(float) );
254 		size_t ring_size;
255 
256 		// Send audio through out port
257 		jack_output_buffers[i] = jack_port_get_buffer( jack_output_ports[i], frames );
258 		if ( ! jack_output_buffers[i] )
259 		{
260 			mlt_log_error( MLT_FILTER_SERVICE(filter), "no buffer for output port %d\n", i );
261 			err = 1;
262 			break;
263 		}
264 		ring_size = jack_ringbuffer_read_space( output_buffers[i] );
265 		jack_ringbuffer_read( output_buffers[i], ( char * )jack_output_buffers[i], ring_size < jack_size ? ring_size : jack_size );
266 		if ( ring_size < jack_size )
267 			memset( &jack_output_buffers[i][ring_size], 0, jack_size - ring_size );
268 
269 		// Return audio through in port
270 		jack_input_buffers[i] = jack_port_get_buffer( jack_input_ports[i], frames );
271 		if ( ! jack_input_buffers[i] )
272 		{
273 			mlt_log_error( MLT_FILTER_SERVICE(filter), "no buffer for input port %d\n", i );
274 			err = 1;
275 			break;
276 		}
277 
278 		// Do not start returning audio until we have sent first mlt frame
279 		if ( sync && i == 0 && frame_size > 0 )
280 			total_size += ring_size;
281 		mlt_log_debug( MLT_FILTER_SERVICE(filter), "sync %d frame_size %d ring_size %zu jack_size %zu\n", sync, frame_size, ring_size, jack_size );
282 
283 		if ( ! sync || ( frame_size > 0  && total_size >= frame_size ) )
284 		{
285 			ring_size = jack_ringbuffer_write_space( input_buffers[i] );
286 			jack_ringbuffer_write( input_buffers[i], ( char * )jack_input_buffers[i], ring_size < jack_size ? ring_size : jack_size );
287 
288 			if ( sync )
289 			{
290 				// Tell mlt that audio is available
291 				pthread_mutex_lock( output_lock);
292 				pthread_cond_signal( output_ready );
293 				pthread_mutex_unlock( output_lock);
294 
295 				// Clear sync phase
296 				mlt_properties_set_int( properties, "_sync", 0 );
297 			}
298 		}
299 	}
300 
301 	// Often jackd does not send the stopped event through the JackSyncCallback
302 	jack_client_t *jack_client = mlt_properties_get_data( properties, "jack_client", NULL );
303 	jack_position_t jack_pos;
304 	jack_transport_state_t state = jack_transport_query( jack_client, &jack_pos );
305 	int transport_state = mlt_properties_get_int( properties, "_transport_state" );
306 	if ( state != transport_state )
307 	{
308 		mlt_properties_set_int( properties, "_transport_state", state );
309 		if ( state == JackTransportStopped )
310 			jack_sync( state, &jack_pos, filter );
311 	}
312 
313 	return err;
314 }
315 
316 
317 /** Get the audio.
318 */
319 
jackrack_get_audio(mlt_frame frame,void ** buffer,mlt_audio_format * format,int * frequency,int * channels,int * samples)320 static int jackrack_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
321 {
322 	// Get the filter service
323 	mlt_filter filter = mlt_frame_pop_audio( frame );
324 
325 	// Get the filter properties
326 	mlt_properties filter_properties = MLT_FILTER_PROPERTIES( filter );
327 
328 	int jack_frequency = mlt_properties_get_int( filter_properties, "_sample_rate" );
329 
330 	// Get the producer's audio
331 	*format = mlt_audio_float;
332 	mlt_frame_get_audio( frame, buffer, format, &jack_frequency, channels, samples );
333 
334 	// TODO: Deal with sample rate differences
335 	if ( *frequency != jack_frequency )
336 		mlt_log_error( MLT_FILTER_SERVICE( filter ), "mismatching frequencies JACK = %d actual = %d\n",
337 			jack_frequency, *frequency );
338 	*frequency = jack_frequency;
339 
340 	// Initialise Jack ports and connections if needed
341 	if ( mlt_properties_get_int( filter_properties, "_samples" ) == 0 )
342 		mlt_properties_set_int( filter_properties, "_samples", *samples );
343 
344 	// Get the filter-specific properties
345 	jack_ringbuffer_t **output_buffers = mlt_properties_get_data( filter_properties, "output_buffers", NULL );
346 	jack_ringbuffer_t **input_buffers = mlt_properties_get_data( filter_properties, "input_buffers", NULL );
347 //	pthread_mutex_t *output_lock = mlt_properties_get_data( filter_properties, "output_lock", NULL );
348 //	pthread_cond_t *output_ready = mlt_properties_get_data( filter_properties, "output_ready", NULL );
349 
350 	// Process the audio
351 	float *q = (float*) *buffer;
352 	size_t size = *samples * sizeof(float);
353 	int j;
354 //	struct timespec tm = { 0, 0 };
355 
356 	// Write into output ringbuffer
357 	for ( j = 0; j < *channels; j++ )
358 	{
359 		if ( jack_ringbuffer_write_space( output_buffers[j] ) >= size )
360 			jack_ringbuffer_write( output_buffers[j], (char*)( q + j * *samples ), size );
361 	}
362 
363 	// Synchronization phase - wait for signal from Jack process
364 	while ( jack_ringbuffer_read_space( input_buffers[ *channels - 1 ] ) < size ) ;
365 		//pthread_cond_wait( output_ready, output_lock );
366 
367 	// Read from input ringbuffer
368 	for ( j = 0; j < *channels; j++, q++ )
369 	{
370 		if ( jack_ringbuffer_read_space( input_buffers[j] ) >= size )
371 			jack_ringbuffer_read( input_buffers[j], (char*)( q + j * *samples ), size );
372 	}
373 
374 	// help jack_sync() indicate when we are rolling
375 	mlt_position pos = mlt_frame_get_position( frame );
376 	mlt_properties_set_position( filter_properties, "_last_pos", pos );
377 
378 	return 0;
379 }
380 
381 
382 /** Filter processing.
383 */
384 
filter_process(mlt_filter this,mlt_frame frame)385 static mlt_frame filter_process( mlt_filter this, mlt_frame frame )
386 {
387 	{
388 		mlt_properties properties = MLT_FILTER_PROPERTIES( this );
389 		mlt_frame_push_audio( frame, this );
390 		mlt_frame_push_audio( frame, jackrack_get_audio );
391 
392 		if ( !mlt_properties_get_data( properties, "jackrack", NULL ) )
393 			initialise_jack_ports( properties );
394 	}
395 
396 	return frame;
397 }
398 
399 
filter_close(mlt_filter this)400 static void filter_close( mlt_filter this )
401 {
402 	mlt_properties properties = MLT_FILTER_PROPERTIES( this );
403 	jack_client_t *jack_client = mlt_properties_get_data( properties, "jack_client", NULL );
404 	jack_deactivate( jack_client );
405 	jack_client_close( jack_client );
406 	this->parent.close = NULL;
407 	mlt_service_close( &this->parent );
408 }
409 
410 /** Constructor for the filter.
411 */
412 
filter_jackrack_init(mlt_profile profile,mlt_service_type type,const char * id,char * arg)413 mlt_filter filter_jackrack_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
414 {
415 	mlt_filter this = mlt_filter_new( );
416 	if ( this != NULL )
417 	{
418 		char name[61];
419 		char *jack_client_name;
420 		const char *src;
421 		jack_status_t status = 0;
422 
423 		if ( id && arg && !strcmp( id, "jack" ) )
424 		{
425 			snprintf( name, sizeof( name ), "%s", arg );
426 			src = NULL;
427 		}
428 		else
429 		{
430 			snprintf( name, sizeof( name ), "mlt%d", getpid() );
431 			src = arg;
432 		}
433 		jack_client_t *jack_client = jack_client_open( arg, JackNullOption, &status, NULL );
434 		if ( jack_client )
435 		{
436 			if ( status & JackNameNotUnique )
437 			{
438 				jack_client_name = jack_get_client_name ( jack_client );
439 				strcpy( name, jack_client_name );
440 			}
441 
442 			mlt_properties properties = MLT_FILTER_PROPERTIES( this );
443 			pthread_mutex_t *output_lock = mlt_pool_alloc( sizeof( pthread_mutex_t ) );
444 			pthread_cond_t  *output_ready = mlt_pool_alloc( sizeof( pthread_cond_t ) );
445 
446 			jack_set_process_callback( jack_client, jack_process, this );
447 			jack_set_sync_callback( jack_client, jack_sync, this );
448 			jack_set_sync_timeout( jack_client, 5000000 );
449 			//TODO: jack_on_shutdown( jack_client, jack_shutdown_cb, this );
450 			this->process = filter_process;
451 			this->close = filter_close;
452 			pthread_mutex_init( output_lock, NULL );
453 			pthread_cond_init( output_ready, NULL );
454 
455 			mlt_properties_set( properties, "src", src );
456 			mlt_properties_set( properties, "client_name", name );
457 			mlt_properties_set_data( properties, "jack_client", jack_client, 0, NULL, NULL );
458 			mlt_properties_set_int( properties, "_sample_rate", jack_get_sample_rate( jack_client ) );
459 			mlt_properties_set_data( properties, "output_lock", output_lock, 0, mlt_pool_release, NULL );
460 			mlt_properties_set_data( properties, "output_ready", output_ready, 0, mlt_pool_release, NULL );
461 			mlt_properties_set_int( properties, "_sync", 1 );
462 			mlt_properties_set_int( properties, "channels", 2 );
463 
464 			mlt_events_register( properties, "jack-started", (mlt_transmitter) jack_started_transmitter );
465 			mlt_events_register( properties, "jack-stopped", (mlt_transmitter) jack_stopped_transmitter );
466 			mlt_events_register( properties, "jack-start", NULL );
467 			mlt_events_register( properties, "jack-stop", NULL );
468 			mlt_events_register( properties, "jack-seek", (mlt_transmitter) jack_seek_transmitter );
469 			mlt_events_listen( properties, properties, "jack-start", (mlt_listener) on_jack_start );
470 			mlt_events_listen( properties, properties, "jack-stop", (mlt_listener) on_jack_stop );
471 			mlt_events_listen( properties, this, "jack-seek", (mlt_listener) on_jack_seek );
472 			mlt_properties_set_position( properties, "_jack_seek", -1 );
473 		}
474 		else
475 		{
476 			mlt_log_error( NULL, "Failed to connect to JACK server\n" );
477 			mlt_filter_close( this );
478 			this = NULL;
479 		}
480 	}
481 	return this;
482 }
483