]> git.sesse.net Git - mlt/blob - src/modules/jackrack/consumer_jack.c
Fail gracefully when unable to connect to JACK.
[mlt] / src / modules / jackrack / consumer_jack.c
1 /*
2  * consumer_jack.c -- a JACK audio consumer
3  * Copyright (C) 2011 Dan Dennedy <dan@dennedy.org>
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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 #include <framework/mlt.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <pthread.h>
25 #include <sys/time.h>
26 #include <unistd.h>
27 #include <jack/jack.h>
28 #include <jack/ringbuffer.h>
29
30 #define BUFFER_LEN (204800 * 6)
31
32 /** This classes definition.
33 */
34
35 typedef struct consumer_jack_s *consumer_jack;
36
37 struct consumer_jack_s
38 {
39         struct mlt_consumer_s parent;
40         jack_client_t *jack;
41         mlt_deque queue;
42         pthread_t thread;
43         int joined;
44         int running;
45         pthread_mutex_t video_mutex;
46         pthread_cond_t video_cond;
47         int playing;
48
49         pthread_cond_t refresh_cond;
50         pthread_mutex_t refresh_mutex;
51         int refresh_count;
52         int counter;
53         jack_ringbuffer_t **ringbuffers;
54         jack_port_t **ports;
55 };
56
57 /** Forward references to static functions.
58 */
59
60 static int consumer_start( mlt_consumer parent );
61 static int consumer_stop( mlt_consumer parent );
62 static int consumer_is_stopped( mlt_consumer parent );
63 static void consumer_close( mlt_consumer parent );
64 static void *consumer_thread( void * );
65 static void consumer_refresh_cb( mlt_consumer sdl, mlt_consumer parent, char *name );
66 static int jack_process( jack_nframes_t frames, void * data );
67
68 /** Constructor
69 */
70
71 mlt_consumer consumer_jack_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
72 {
73         // Create the consumer object
74         consumer_jack self = calloc( 1, sizeof( struct consumer_jack_s ) );
75
76         // If no malloc'd and consumer init ok
77         if ( self != NULL && mlt_consumer_init( &self->parent, self, profile ) == 0 )
78         {
79                 char name[14];
80
81                 snprintf( name, sizeof( name ), "mlt%d", getpid() );
82                 if (( self->jack = jack_client_open( name, JackNullOption, NULL ) ))
83                 {
84                         jack_set_process_callback( self->jack, jack_process, self );
85
86                         // Create the queue
87                         self->queue = mlt_deque_init( );
88
89                         // Get the parent consumer object
90                         mlt_consumer parent = &self->parent;
91
92                         // We have stuff to clean up, so override the close method
93                         parent->close = consumer_close;
94
95                         // get a handle on properties
96                         mlt_service service = MLT_CONSUMER_SERVICE( parent );
97                         mlt_properties properties = MLT_SERVICE_PROPERTIES( service );
98
99                         // This is the initialisation of the consumer
100                         pthread_mutex_init( &self->video_mutex, NULL );
101                         pthread_cond_init( &self->video_cond, NULL);
102
103                         // Default scaler (for now we'll use nearest)
104                         mlt_properties_set( properties, "rescale", "nearest" );
105                         mlt_properties_set( properties, "deinterlace_method", "onefield" );
106
107                         // Default buffer for low latency
108                         mlt_properties_set_int( properties, "buffer", 1 );
109
110                         // Set frequency from JACK
111                         mlt_properties_set_int( properties, "frequency", (int) jack_get_sample_rate( self->jack ) );
112
113                         // Ensure we don't join on a non-running object
114                         self->joined = 1;
115
116                         // Allow thread to be started/stopped
117                         parent->start = consumer_start;
118                         parent->stop = consumer_stop;
119                         parent->is_stopped = consumer_is_stopped;
120
121                         // Initialize the refresh handler
122                         pthread_cond_init( &self->refresh_cond, NULL );
123                         pthread_mutex_init( &self->refresh_mutex, NULL );
124                         mlt_events_listen( MLT_CONSUMER_PROPERTIES( parent ), self, "property-changed", ( mlt_listener )consumer_refresh_cb );
125
126                         // Return the consumer produced
127                         return parent;
128                 }
129         }
130
131         // malloc or consumer init failed
132         free( self );
133
134         // Indicate failure
135         return NULL;
136 }
137
138 static void consumer_refresh_cb( mlt_consumer sdl, mlt_consumer parent, char *name )
139 {
140         if ( !strcmp( name, "refresh" ) )
141         {
142                 consumer_jack self = parent->child;
143                 pthread_mutex_lock( &self->refresh_mutex );
144                 self->refresh_count = self->refresh_count <= 0 ? 1 : self->refresh_count + 1;
145                 pthread_cond_broadcast( &self->refresh_cond );
146                 pthread_mutex_unlock( &self->refresh_mutex );
147         }
148 }
149
150 static int consumer_start( mlt_consumer parent )
151 {
152         consumer_jack self = parent->child;
153
154         if ( !self->running )
155         {
156                 consumer_stop( parent );
157                 self->running = 1;
158                 self->joined = 0;
159                 pthread_create( &self->thread, NULL, consumer_thread, self );
160         }
161
162         return 0;
163 }
164
165 static int consumer_stop( mlt_consumer parent )
166 {
167         // Get the actual object
168         consumer_jack self = parent->child;
169
170         if ( self->running && !self->joined )
171         {
172                 // Kill the thread and clean up
173                 self->joined = 1;
174                 self->running = 0;
175
176                 // Unlatch the consumer thread
177                 pthread_mutex_lock( &self->refresh_mutex );
178                 pthread_cond_broadcast( &self->refresh_cond );
179                 pthread_mutex_unlock( &self->refresh_mutex );
180
181                 // Cleanup the main thread
182 #ifndef WIN32
183                 if ( self->thread )
184 #endif
185                         pthread_join( self->thread, NULL );
186
187                 // Unlatch the video thread
188                 pthread_mutex_lock( &self->video_mutex );
189                 pthread_cond_broadcast( &self->video_cond );
190                 pthread_mutex_unlock( &self->video_mutex );
191
192                 // Cleanup JACK
193                 if ( self->playing )
194                         jack_deactivate( self->jack );
195                 if ( self->ringbuffers )
196                 {
197                         int n = mlt_properties_get_int( MLT_CONSUMER_PROPERTIES( parent ), "channels" );
198                         while ( n-- )
199                         {
200                                 jack_ringbuffer_free( self->ringbuffers[n] );
201                                 jack_port_unregister( self->jack, self->ports[n] );
202                         }
203                         mlt_pool_release( self->ringbuffers );
204                 }
205                 self->ringbuffers = NULL;
206                 if ( self->ports )
207                         mlt_pool_release( self->ports );
208                 self->ports = NULL;
209         }
210
211         return 0;
212 }
213
214 static int consumer_is_stopped( mlt_consumer parent )
215 {
216         consumer_jack self = parent->child;
217         return !self->running;
218 }
219
220 static int jack_process( jack_nframes_t frames, void * data )
221 {
222         int error = 0;
223         consumer_jack self = (consumer_jack) data;
224         mlt_properties properties = MLT_CONSUMER_PROPERTIES( &self->parent );
225         int channels = mlt_properties_get_int( properties, "channels" );
226         int i;
227
228         if ( !self->ringbuffers )
229                 return 1;
230
231         for ( i = 0; i < channels; i++ )
232         {
233                 size_t jack_size = ( frames * sizeof(float) );
234                 size_t ring_size = jack_ringbuffer_read_space( self->ringbuffers[i] );
235                 char *dest = jack_port_get_buffer( self->ports[i], frames );
236
237                 jack_ringbuffer_read( self->ringbuffers[i], dest, ring_size < jack_size ? ring_size : jack_size );
238         }
239
240         return error;
241 }
242
243 static void initialise_jack_ports( consumer_jack self )
244 {
245         int i;
246         char mlt_name[20], con_name[30];
247         mlt_properties properties = MLT_CONSUMER_PROPERTIES( &self->parent );
248
249         // Propogate these for the Jack processing callback
250         int channels = mlt_properties_get_int( properties, "channels" );
251
252         // Allocate buffers and ports
253         self->ringbuffers = mlt_pool_alloc( sizeof( jack_ringbuffer_t *) * channels );
254         self->ports = mlt_pool_alloc( sizeof(jack_port_t *) * channels );
255
256         // Start Jack processing - required before registering ports
257         jack_activate( self->jack );
258         self->playing = 1;
259
260         // Register Jack ports
261         for ( i = 0; i < channels; i++ )
262         {
263                 self->ringbuffers[i] = jack_ringbuffer_create( BUFFER_LEN * sizeof(float) );
264                 snprintf( mlt_name, sizeof( mlt_name ), "out_%d", i + 1 );
265                 self->ports[i] = jack_port_register( self->jack, mlt_name, JACK_DEFAULT_AUDIO_TYPE,
266                                 JackPortIsOutput | JackPortIsTerminal, 0 );
267         }
268
269         // Establish connections
270         for ( i = 0; i < channels; i++ )
271         {
272                 snprintf( mlt_name, sizeof( mlt_name ), "%s", jack_port_name( self->ports[i] ) );
273                 if ( mlt_properties_get( properties, con_name ) )
274                         snprintf( con_name, sizeof( con_name ), "%s", mlt_properties_get( properties, con_name ) );
275                 else
276                         snprintf( con_name, sizeof( con_name ), "system:playback_%d", i + 1);
277
278                 mlt_log_verbose( NULL, "JACK connect %s to %s\n", mlt_name, con_name );
279                 jack_connect( self->jack, mlt_name, con_name );
280         }
281 }
282
283 static int consumer_play_audio( consumer_jack self, mlt_frame frame, int init_audio, int *duration )
284 {
285         // Get the properties of this consumer
286         mlt_properties properties = MLT_CONSUMER_PROPERTIES( &self->parent );
287         mlt_audio_format afmt = mlt_audio_float;
288
289         // Set the preferred params of the test card signal
290         int channels = mlt_properties_get_int( properties, "channels" );
291         int frequency = mlt_properties_get_int( properties, "frequency" );
292         int samples = mlt_sample_calculator( mlt_properties_get_double( properties, "fps" ), frequency, self->counter++ );
293         float *buffer;
294
295         mlt_frame_get_audio( frame, (void**) &buffer, &afmt, &frequency, &channels, &samples );
296         *duration = ( ( samples * 1000 ) / frequency );
297
298         if ( mlt_properties_get_int( properties, "audio_off" ) )
299         {
300                 init_audio = 1;
301                 return init_audio;
302         }
303
304         if ( init_audio == 1 )
305         {
306                 self->playing = 0;
307                 initialise_jack_ports( self );
308                 init_audio = 0;
309         }
310
311         if ( init_audio == 0 )
312         {
313                 int i;
314                 size_t mlt_size = samples * sizeof(float);
315
316                 // Write into output ringbuffer
317                 for ( i = 0; i < channels; i++ )
318                 {
319                         size_t ring_size = jack_ringbuffer_write_space( self->ringbuffers[i] );
320                         if ( ring_size >= mlt_size )
321                                 jack_ringbuffer_write( self->ringbuffers[i], (char*)( buffer + i * samples ), mlt_size );
322                 }
323         }
324
325         return init_audio;
326 }
327
328 static int consumer_play_video( consumer_jack self, mlt_frame frame )
329 {
330         // Get the properties of this consumer
331         mlt_properties properties = MLT_CONSUMER_PROPERTIES( &self->parent );
332         if ( self->running && !mlt_consumer_is_stopped( &self->parent ) )
333                 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
334
335         return 0;
336 }
337
338 static void *video_thread( void *arg )
339 {
340         // Identify the arg
341         consumer_jack self = arg;
342
343         // Obtain time of thread start
344         struct timeval now;
345         int64_t start = 0;
346         int64_t elapsed = 0;
347         struct timespec tm;
348         mlt_frame next = NULL;
349         mlt_properties properties = NULL;
350         double speed = 0;
351
352         // Get real time flag
353         int real_time = mlt_properties_get_int( MLT_CONSUMER_PROPERTIES( &self->parent ), "real_time" );
354
355         // Get the current time
356         gettimeofday( &now, NULL );
357
358         // Determine start time
359         start = ( int64_t )now.tv_sec * 1000000 + now.tv_usec;
360
361         while ( self->running )
362         {
363                 // Pop the next frame
364                 pthread_mutex_lock( &self->video_mutex );
365                 next = mlt_deque_pop_front( self->queue );
366                 while ( next == NULL && self->running )
367                 {
368                         pthread_cond_wait( &self->video_cond, &self->video_mutex );
369                         next = mlt_deque_pop_front( self->queue );
370                 }
371                 pthread_mutex_unlock( &self->video_mutex );
372
373                 if ( !self->running || next == NULL ) break;
374
375                 // Get the properties
376                 properties =  MLT_FRAME_PROPERTIES( next );
377
378                 // Get the speed of the frame
379                 speed = mlt_properties_get_double( properties, "_speed" );
380
381                 // Get the current time
382                 gettimeofday( &now, NULL );
383
384                 // Get the elapsed time
385                 elapsed = ( ( int64_t )now.tv_sec * 1000000 + now.tv_usec ) - start;
386
387                 // See if we have to delay the display of the current frame
388                 if ( mlt_properties_get_int( properties, "rendered" ) == 1 && self->running )
389                 {
390                         // Obtain the scheduled playout time
391                         int64_t scheduled = mlt_properties_get_int( properties, "playtime" );
392
393                         // Determine the difference between the elapsed time and the scheduled playout time
394                         int64_t difference = scheduled - elapsed;
395
396                         // Smooth playback a bit
397                         if ( real_time && ( difference > 20000 && speed == 1.0 ) )
398                         {
399                                 tm.tv_sec = difference / 1000000;
400                                 tm.tv_nsec = ( difference % 1000000 ) * 500;
401                                 nanosleep( &tm, NULL );
402                         }
403
404                         // Show current frame if not too old
405                         if ( !real_time || ( difference > -10000 || speed != 1.0 || mlt_deque_count( self->queue ) < 2 ) )
406                                 consumer_play_video( self, next );
407
408                         // If the queue is empty, recalculate start to allow build up again
409                         if ( real_time && ( mlt_deque_count( self->queue ) == 0 && speed == 1.0 ) )
410                         {
411                                 gettimeofday( &now, NULL );
412                                 start = ( ( int64_t )now.tv_sec * 1000000 + now.tv_usec ) - scheduled + 20000;
413                         }
414                 }
415
416                 // This frame can now be closed
417                 mlt_frame_close( next );
418                 next = NULL;
419         }
420
421         if ( next != NULL )
422                 mlt_frame_close( next );
423
424         mlt_consumer_stopped( &self->parent );
425
426         return NULL;
427 }
428
429 /** Threaded wrapper for pipe.
430 */
431
432 static void *consumer_thread( void *arg )
433 {
434         // Identify the arg
435         consumer_jack self = arg;
436
437         // Get the consumer
438         mlt_consumer consumer = &self->parent;
439
440         // Get the properties
441         mlt_properties consumer_props = MLT_CONSUMER_PROPERTIES( consumer );
442
443         // Video thread
444         pthread_t thread;
445
446         // internal intialization
447         int init_audio = 1;
448         int init_video = 1;
449         mlt_frame frame = NULL;
450         mlt_properties properties = NULL;
451         int duration = 0;
452         int64_t playtime = 0;
453         struct timespec tm = { 0, 100000 };
454 //      int last_position = -1;
455         self->refresh_count = 0;
456
457         // Loop until told not to
458         while( self->running )
459         {
460                 // Get a frame from the attached producer
461                 frame = mlt_consumer_rt_frame( consumer );
462
463                 // Ensure that we have a frame
464                 if ( frame )
465                 {
466                         // Get the frame properties
467                         properties =  MLT_FRAME_PROPERTIES( frame );
468
469                         // Get the speed of the frame
470                         double speed = mlt_properties_get_double( properties, "_speed" );
471
472                         // Get refresh request for the current frame
473                         int refresh = mlt_properties_get_int( consumer_props, "refresh" );
474
475                         // Clear refresh
476                         mlt_events_block( consumer_props, consumer_props );
477                         mlt_properties_set_int( consumer_props, "refresh", 0 );
478                         mlt_events_unblock( consumer_props, consumer_props );
479
480                         // Play audio
481                         init_audio = consumer_play_audio( self, frame, init_audio, &duration );
482
483                         // Determine the start time now
484                         if ( self->playing && init_video )
485                         {
486                                 // Create the video thread
487                                 pthread_create( &thread, NULL, video_thread, self );
488
489                                 // Video doesn't need to be initialised any more
490                                 init_video = 0;
491                         }
492
493                         // Set playtime for this frame
494                         mlt_properties_set_int( properties, "playtime", playtime );
495
496                         while ( self->running && speed != 0 && mlt_deque_count( self->queue ) > 15 )
497                                 nanosleep( &tm, NULL );
498
499                         // Push this frame to the back of the queue
500                         if ( self->running && speed )
501                         {
502                                 pthread_mutex_lock( &self->video_mutex );
503                                 mlt_deque_push_back( self->queue, frame );
504                                 pthread_cond_broadcast( &self->video_cond );
505                                 pthread_mutex_unlock( &self->video_mutex );
506
507                                 // Calculate the next playtime
508                                 playtime += ( duration * 1000 );
509                         }
510                         else if ( self->running )
511                         {
512                                 pthread_mutex_lock( &self->refresh_mutex );
513                                 if ( refresh == 0 && self->refresh_count <= 0 )
514                                 {
515                                         consumer_play_video( self, frame );
516                                         pthread_cond_wait( &self->refresh_cond, &self->refresh_mutex );
517                                 }
518                                 mlt_frame_close( frame );
519                                 self->refresh_count --;
520                                 pthread_mutex_unlock( &self->refresh_mutex );
521                         }
522                         else
523                         {
524                                 mlt_frame_close( frame );
525                                 frame = NULL;
526                         }
527
528                         // Optimisation to reduce latency
529                         if ( frame && speed == 1.0 )
530                         {
531                                 // TODO: disabled due to misbehavior on parallel-consumer
532 //                              if ( last_position != -1 && last_position + 1 != mlt_frame_get_position( frame ) )
533 //                                      mlt_consumer_purge( consumer );
534 //                              last_position = mlt_frame_get_position( frame );
535                         }
536                         else
537                         {
538                                 mlt_consumer_purge( consumer );
539 //                              last_position = -1;
540                         }
541                 }
542         }
543
544         // Kill the video thread
545         if ( init_video == 0 )
546         {
547                 pthread_mutex_lock( &self->video_mutex );
548                 pthread_cond_broadcast( &self->video_cond );
549                 pthread_mutex_unlock( &self->video_mutex );
550                 pthread_join( thread, NULL );
551         }
552
553         while( mlt_deque_count( self->queue ) )
554                 mlt_frame_close( mlt_deque_pop_back( self->queue ) );
555
556         return NULL;
557 }
558
559 /** Callback to allow override of the close method.
560 */
561
562 static void consumer_close( mlt_consumer parent )
563 {
564         // Get the actual object
565         consumer_jack self = parent->child;
566
567         // Stop the consumer
568         mlt_consumer_stop( parent );
569
570         // Now clean up the rest
571         mlt_consumer_close( parent );
572
573         // Close the queue
574         mlt_deque_close( self->queue );
575
576         // Destroy mutexes
577         pthread_mutex_destroy( &self->video_mutex );
578         pthread_cond_destroy( &self->video_cond );
579         pthread_mutex_destroy( &self->refresh_mutex );
580         pthread_cond_destroy( &self->refresh_cond );
581
582         // Disconnect from JACK
583         jack_client_close( self->jack );
584
585         // Finally deallocate self
586         free( self );
587 }