2 * consumer_jack.c -- a JACK audio consumer
3 * Copyright (C) 2011 Dan Dennedy <dan@dennedy.org>
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
10 * This library 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 GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 #include <framework/mlt.h>
27 #include <jack/jack.h>
28 #include <jack/ringbuffer.h>
30 #define BUFFER_LEN (204800 * 6)
32 pthread_mutex_t g_activate_mutex = PTHREAD_MUTEX_INITIALIZER;
34 /** This classes definition.
37 typedef struct consumer_jack_s *consumer_jack;
39 struct consumer_jack_s
41 struct mlt_consumer_s parent;
47 pthread_mutex_t video_mutex;
48 pthread_cond_t video_cond;
51 pthread_cond_t refresh_cond;
52 pthread_mutex_t refresh_mutex;
55 jack_ringbuffer_t **ringbuffers;
59 /** Forward references to static functions.
62 static int consumer_start( mlt_consumer parent );
63 static int consumer_stop( mlt_consumer parent );
64 static int consumer_is_stopped( mlt_consumer parent );
65 static void consumer_close( mlt_consumer parent );
66 static void *consumer_thread( void * );
67 static void consumer_refresh_cb( mlt_consumer sdl, mlt_consumer parent, char *name );
68 static int jack_process( jack_nframes_t frames, void * data );
73 mlt_consumer consumer_jack_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
75 // Create the consumer object
76 consumer_jack self = calloc( 1, sizeof( struct consumer_jack_s ) );
78 // If no malloc'd and consumer init ok
79 if ( self != NULL && mlt_consumer_init( &self->parent, self, profile ) == 0 )
83 snprintf( name, sizeof( name ), "mlt%d", getpid() );
84 if (( self->jack = jack_client_open( name, JackNullOption, NULL ) ))
86 jack_set_process_callback( self->jack, jack_process, self );
89 self->queue = mlt_deque_init( );
91 // Get the parent consumer object
92 mlt_consumer parent = &self->parent;
94 // We have stuff to clean up, so override the close method
95 parent->close = consumer_close;
97 // get a handle on properties
98 mlt_service service = MLT_CONSUMER_SERVICE( parent );
99 mlt_properties properties = MLT_SERVICE_PROPERTIES( service );
101 // This is the initialisation of the consumer
102 pthread_mutex_init( &self->video_mutex, NULL );
103 pthread_cond_init( &self->video_cond, NULL);
105 // Default scaler (for now we'll use nearest)
106 mlt_properties_set( properties, "rescale", "nearest" );
107 mlt_properties_set( properties, "deinterlace_method", "onefield" );
109 // Default buffer for low latency
110 mlt_properties_set_int( properties, "buffer", 1 );
112 // Set frequency from JACK
113 mlt_properties_set_int( properties, "frequency", (int) jack_get_sample_rate( self->jack ) );
115 // Set default volume
116 mlt_properties_set_double( properties, "volume", 1.0 );
118 // Ensure we don't join on a non-running object
121 // Allow thread to be started/stopped
122 parent->start = consumer_start;
123 parent->stop = consumer_stop;
124 parent->is_stopped = consumer_is_stopped;
126 // Initialize the refresh handler
127 pthread_cond_init( &self->refresh_cond, NULL );
128 pthread_mutex_init( &self->refresh_mutex, NULL );
129 mlt_events_listen( MLT_CONSUMER_PROPERTIES( parent ), self, "property-changed", ( mlt_listener )consumer_refresh_cb );
131 // Return the consumer produced
136 // malloc or consumer init failed
143 static void consumer_refresh_cb( mlt_consumer sdl, mlt_consumer parent, char *name )
145 if ( !strcmp( name, "refresh" ) )
147 consumer_jack self = parent->child;
148 pthread_mutex_lock( &self->refresh_mutex );
149 self->refresh_count = self->refresh_count <= 0 ? 1 : self->refresh_count + 1;
150 pthread_cond_broadcast( &self->refresh_cond );
151 pthread_mutex_unlock( &self->refresh_mutex );
155 static int consumer_start( mlt_consumer parent )
157 consumer_jack self = parent->child;
159 if ( !self->running )
161 consumer_stop( parent );
164 pthread_create( &self->thread, NULL, consumer_thread, self );
170 static int consumer_stop( mlt_consumer parent )
172 // Get the actual object
173 consumer_jack self = parent->child;
175 if ( self->running && !self->joined )
177 // Kill the thread and clean up
181 // Unlatch the consumer thread
182 pthread_mutex_lock( &self->refresh_mutex );
183 pthread_cond_broadcast( &self->refresh_cond );
184 pthread_mutex_unlock( &self->refresh_mutex );
186 // Cleanup the main thread
190 pthread_join( self->thread, NULL );
192 // Unlatch the video thread
193 pthread_mutex_lock( &self->video_mutex );
194 pthread_cond_broadcast( &self->video_cond );
195 pthread_mutex_unlock( &self->video_mutex );
199 jack_deactivate( self->jack );
200 if ( self->ringbuffers )
202 int n = mlt_properties_get_int( MLT_CONSUMER_PROPERTIES( parent ), "channels" );
205 jack_ringbuffer_free( self->ringbuffers[n] );
206 jack_port_unregister( self->jack, self->ports[n] );
208 mlt_pool_release( self->ringbuffers );
210 self->ringbuffers = NULL;
212 mlt_pool_release( self->ports );
219 static int consumer_is_stopped( mlt_consumer parent )
221 consumer_jack self = parent->child;
222 return !self->running;
225 static int jack_process( jack_nframes_t frames, void * data )
228 consumer_jack self = (consumer_jack) data;
229 mlt_properties properties = MLT_CONSUMER_PROPERTIES( &self->parent );
230 int channels = mlt_properties_get_int( properties, "channels" );
233 if ( !self->ringbuffers )
236 for ( i = 0; i < channels; i++ )
238 size_t jack_size = ( frames * sizeof(float) );
239 size_t ring_size = jack_ringbuffer_read_space( self->ringbuffers[i] );
240 char *dest = jack_port_get_buffer( self->ports[i], frames );
242 jack_ringbuffer_read( self->ringbuffers[i], dest, ring_size < jack_size ? ring_size : jack_size );
248 static void initialise_jack_ports( consumer_jack self )
251 char mlt_name[20], con_name[30];
252 mlt_properties properties = MLT_CONSUMER_PROPERTIES( &self->parent );
253 const char **ports = NULL;
255 // Propogate these for the Jack processing callback
256 int channels = mlt_properties_get_int( properties, "channels" );
258 // Allocate buffers and ports
259 self->ringbuffers = mlt_pool_alloc( sizeof( jack_ringbuffer_t *) * channels );
260 self->ports = mlt_pool_alloc( sizeof(jack_port_t *) * channels );
262 // Start Jack processing - required before registering ports
263 pthread_mutex_lock( &g_activate_mutex );
264 jack_activate( self->jack );
265 pthread_mutex_unlock( &g_activate_mutex );
268 // Register Jack ports
269 for ( i = 0; i < channels; i++ )
271 self->ringbuffers[i] = jack_ringbuffer_create( BUFFER_LEN * sizeof(float) );
272 snprintf( mlt_name, sizeof( mlt_name ), "out_%d", i + 1 );
273 self->ports[i] = jack_port_register( self->jack, mlt_name, JACK_DEFAULT_AUDIO_TYPE,
274 JackPortIsOutput | JackPortIsTerminal, 0 );
277 // Establish connections
278 for ( i = 0; i < channels; i++ )
280 snprintf( mlt_name, sizeof( mlt_name ), "%s", jack_port_name( self->ports[i] ) );
281 if ( mlt_properties_get( properties, con_name ) )
282 snprintf( con_name, sizeof( con_name ), "%s", mlt_properties_get( properties, con_name ) );
286 ports = jack_get_ports( self->jack, NULL, NULL, JackPortIsPhysical | JackPortIsInput );
288 strcpy( con_name, ports[i] );
290 snprintf( con_name, sizeof( con_name ), "system:playback_%d", i + 1);
292 mlt_log_verbose( NULL, "JACK connect %s to %s\n", mlt_name, con_name );
293 jack_connect( self->jack, mlt_name, con_name );
299 static int consumer_play_audio( consumer_jack self, mlt_frame frame, int init_audio, int *duration )
301 // Get the properties of this consumer
302 mlt_properties properties = MLT_CONSUMER_PROPERTIES( &self->parent );
303 mlt_audio_format afmt = mlt_audio_float;
305 // Set the preferred params of the test card signal
306 int channels = mlt_properties_get_int( properties, "channels" );
307 int frequency = mlt_properties_get_int( properties, "frequency" );
308 int samples = mlt_sample_calculator( mlt_properties_get_double( properties, "fps" ), frequency, self->counter++ );
311 mlt_frame_get_audio( frame, (void**) &buffer, &afmt, &frequency, &channels, &samples );
312 *duration = ( ( samples * 1000 ) / frequency );
314 if ( mlt_properties_get_int( properties, "audio_off" ) )
320 if ( init_audio == 1 )
323 initialise_jack_ports( self );
327 if ( init_audio == 0 )
330 size_t mlt_size = samples * sizeof(float);
331 float volume = mlt_properties_get_double( properties, "volume" );
336 i = samples * channels + 1;
341 // Write into output ringbuffer
342 for ( i = 0; i < channels; i++ )
344 size_t ring_size = jack_ringbuffer_write_space( self->ringbuffers[i] );
345 if ( ring_size >= mlt_size )
346 jack_ringbuffer_write( self->ringbuffers[i], (char*)( buffer + i * samples ), mlt_size );
353 static int consumer_play_video( consumer_jack self, mlt_frame frame )
355 // Get the properties of this consumer
356 mlt_properties properties = MLT_CONSUMER_PROPERTIES( &self->parent );
357 if ( self->running && !mlt_consumer_is_stopped( &self->parent ) )
358 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
363 static void *video_thread( void *arg )
366 consumer_jack self = arg;
368 // Obtain time of thread start
373 mlt_frame next = NULL;
374 mlt_properties properties = NULL;
377 // Get real time flag
378 int real_time = mlt_properties_get_int( MLT_CONSUMER_PROPERTIES( &self->parent ), "real_time" );
380 // Get the current time
381 gettimeofday( &now, NULL );
383 // Determine start time
384 start = ( int64_t )now.tv_sec * 1000000 + now.tv_usec;
386 while ( self->running )
388 // Pop the next frame
389 pthread_mutex_lock( &self->video_mutex );
390 next = mlt_deque_pop_front( self->queue );
391 while ( next == NULL && self->running )
393 pthread_cond_wait( &self->video_cond, &self->video_mutex );
394 next = mlt_deque_pop_front( self->queue );
396 pthread_mutex_unlock( &self->video_mutex );
398 if ( !self->running || next == NULL ) break;
400 // Get the properties
401 properties = MLT_FRAME_PROPERTIES( next );
403 // Get the speed of the frame
404 speed = mlt_properties_get_double( properties, "_speed" );
406 // Get the current time
407 gettimeofday( &now, NULL );
409 // Get the elapsed time
410 elapsed = ( ( int64_t )now.tv_sec * 1000000 + now.tv_usec ) - start;
412 // See if we have to delay the display of the current frame
413 if ( mlt_properties_get_int( properties, "rendered" ) == 1 && self->running )
415 // Obtain the scheduled playout time
416 int64_t scheduled = mlt_properties_get_int( properties, "playtime" );
418 // Determine the difference between the elapsed time and the scheduled playout time
419 int64_t difference = scheduled - elapsed;
421 // Smooth playback a bit
422 if ( real_time && ( difference > 20000 && speed == 1.0 ) )
424 tm.tv_sec = difference / 1000000;
425 tm.tv_nsec = ( difference % 1000000 ) * 500;
426 nanosleep( &tm, NULL );
429 // Show current frame if not too old
430 if ( !real_time || ( difference > -10000 || speed != 1.0 || mlt_deque_count( self->queue ) < 2 ) )
431 consumer_play_video( self, next );
433 // If the queue is empty, recalculate start to allow build up again
434 if ( real_time && ( mlt_deque_count( self->queue ) == 0 && speed == 1.0 ) )
436 gettimeofday( &now, NULL );
437 start = ( ( int64_t )now.tv_sec * 1000000 + now.tv_usec ) - scheduled + 20000;
441 // This frame can now be closed
442 mlt_frame_close( next );
447 mlt_frame_close( next );
449 mlt_consumer_stopped( &self->parent );
454 /** Threaded wrapper for pipe.
457 static void *consumer_thread( void *arg )
460 consumer_jack self = arg;
463 mlt_consumer consumer = &self->parent;
465 // Get the properties
466 mlt_properties consumer_props = MLT_CONSUMER_PROPERTIES( consumer );
471 // internal intialization
474 mlt_frame frame = NULL;
475 mlt_properties properties = NULL;
477 int64_t playtime = 0;
478 struct timespec tm = { 0, 100000 };
479 // int last_position = -1;
480 self->refresh_count = 0;
482 // Loop until told not to
483 while( self->running )
485 // Get a frame from the attached producer
486 frame = mlt_consumer_rt_frame( consumer );
488 // Ensure that we have a frame
491 // Get the frame properties
492 properties = MLT_FRAME_PROPERTIES( frame );
494 // Get the speed of the frame
495 double speed = mlt_properties_get_double( properties, "_speed" );
497 // Get refresh request for the current frame
498 int refresh = mlt_properties_get_int( consumer_props, "refresh" );
501 mlt_events_block( consumer_props, consumer_props );
502 mlt_properties_set_int( consumer_props, "refresh", 0 );
503 mlt_events_unblock( consumer_props, consumer_props );
506 init_audio = consumer_play_audio( self, frame, init_audio, &duration );
508 // Determine the start time now
509 if ( self->playing && init_video )
511 // Create the video thread
512 pthread_create( &thread, NULL, video_thread, self );
514 // Video doesn't need to be initialised any more
518 // Set playtime for this frame
519 mlt_properties_set_int( properties, "playtime", playtime );
521 while ( self->running && speed != 0 && mlt_deque_count( self->queue ) > 15 )
522 nanosleep( &tm, NULL );
524 // Push this frame to the back of the queue
525 if ( self->running && speed )
527 pthread_mutex_lock( &self->video_mutex );
528 mlt_deque_push_back( self->queue, frame );
529 pthread_cond_broadcast( &self->video_cond );
530 pthread_mutex_unlock( &self->video_mutex );
532 // Calculate the next playtime
533 playtime += ( duration * 1000 );
535 else if ( self->running )
537 pthread_mutex_lock( &self->refresh_mutex );
538 if ( refresh == 0 && self->refresh_count <= 0 )
540 consumer_play_video( self, frame );
541 pthread_cond_wait( &self->refresh_cond, &self->refresh_mutex );
543 mlt_frame_close( frame );
544 self->refresh_count --;
545 pthread_mutex_unlock( &self->refresh_mutex );
549 mlt_frame_close( frame );
553 // Optimisation to reduce latency
554 if ( frame && speed == 1.0 )
556 // TODO: disabled due to misbehavior on parallel-consumer
557 // if ( last_position != -1 && last_position + 1 != mlt_frame_get_position( frame ) )
558 // mlt_consumer_purge( consumer );
559 // last_position = mlt_frame_get_position( frame );
563 mlt_consumer_purge( consumer );
564 // last_position = -1;
569 // Kill the video thread
570 if ( init_video == 0 )
572 pthread_mutex_lock( &self->video_mutex );
573 pthread_cond_broadcast( &self->video_cond );
574 pthread_mutex_unlock( &self->video_mutex );
575 pthread_join( thread, NULL );
578 while( mlt_deque_count( self->queue ) )
579 mlt_frame_close( mlt_deque_pop_back( self->queue ) );
584 /** Callback to allow override of the close method.
587 static void consumer_close( mlt_consumer parent )
589 // Get the actual object
590 consumer_jack self = parent->child;
593 mlt_consumer_stop( parent );
595 // Now clean up the rest
596 mlt_consumer_close( parent );
599 mlt_deque_close( self->queue );
602 pthread_mutex_destroy( &self->video_mutex );
603 pthread_cond_destroy( &self->video_cond );
604 pthread_mutex_destroy( &self->refresh_mutex );
605 pthread_cond_destroy( &self->refresh_cond );
607 // Disconnect from JACK
608 jack_client_close( self->jack );
610 // Finally deallocate self