]> git.sesse.net Git - mlt/blob - src/modules/sdl/consumer_sdl_audio.c
revert setting mlt_image_format to yuv420p
[mlt] / src / modules / sdl / consumer_sdl_audio.c
1 /*
2  * consumer_sdl_audio.c -- A Simple DirectMedia Layer audio-only consumer
3  * Copyright (C) 2009-2012 Ushodaya Enterprises Limited
4  * Author: Dan Dennedy <dan@dennedy.org>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 #include <framework/mlt_consumer.h>
22 #include <framework/mlt_frame.h>
23 #include <framework/mlt_deque.h>
24 #include <framework/mlt_factory.h>
25 #include <framework/mlt_filter.h>
26 #include <framework/mlt_log.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <pthread.h>
31 #include <SDL.h>
32 #include <sys/time.h>
33
34 extern pthread_mutex_t mlt_sdl_mutex;
35
36 /** This classes definition.
37 */
38
39 typedef struct consumer_sdl_s *consumer_sdl;
40
41 struct consumer_sdl_s
42 {
43         struct mlt_consumer_s parent;
44         mlt_properties properties;
45         mlt_deque queue;
46         pthread_t thread;
47         int joined;
48         int running;
49         uint8_t audio_buffer[ 4096 * 10 ];
50         int audio_avail;
51         pthread_mutex_t audio_mutex;
52         pthread_cond_t audio_cond;
53         pthread_mutex_t video_mutex;
54         pthread_cond_t video_cond;
55         int playing;
56
57         pthread_cond_t refresh_cond;
58         pthread_mutex_t refresh_mutex;
59         int refresh_count;
60 };
61
62 /** Forward references to static functions.
63 */
64
65 static int consumer_start( mlt_consumer parent );
66 static int consumer_stop( mlt_consumer parent );
67 static int consumer_is_stopped( mlt_consumer parent );
68 static void consumer_close( mlt_consumer parent );
69 static void *consumer_thread( void * );
70 static void consumer_refresh_cb( mlt_consumer sdl, mlt_consumer self, char *name );
71
72 /** This is what will be called by the factory - anything can be passed in
73         via the argument, but keep it simple.
74 */
75
76 mlt_consumer consumer_sdl_audio_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
77 {
78         // Create the consumer object
79         consumer_sdl self = calloc( 1, sizeof( struct consumer_sdl_s ) );
80
81         // If no malloc'd and consumer init ok
82         if ( self != NULL && mlt_consumer_init( &self->parent, self, profile ) == 0 )
83         {
84                 // Create the queue
85                 self->queue = mlt_deque_init( );
86
87                 // Get the parent consumer object
88                 mlt_consumer parent = &self->parent;
89
90                 // We have stuff to clean up, so override the close method
91                 parent->close = consumer_close;
92
93                 // get a handle on properties
94                 mlt_service service = MLT_CONSUMER_SERVICE( parent );
95                 self->properties = MLT_SERVICE_PROPERTIES( service );
96
97                 // Set the default volume
98                 mlt_properties_set_double( self->properties, "volume", 1.0 );
99
100                 // This is the initialisation of the consumer
101                 pthread_mutex_init( &self->audio_mutex, NULL );
102                 pthread_cond_init( &self->audio_cond, NULL);
103                 pthread_mutex_init( &self->video_mutex, NULL );
104                 pthread_cond_init( &self->video_cond, NULL);
105
106                 // Default scaler (for now we'll use nearest)
107                 mlt_properties_set( self->properties, "rescale", "nearest" );
108                 mlt_properties_set( self->properties, "deinterlace_method", "onefield" );
109                 mlt_properties_set_int( self->properties, "top_field_first", -1 );
110
111                 // Default buffer for low latency
112                 mlt_properties_set_int( self->properties, "buffer", 1 );
113
114                 // Default audio buffer
115                 mlt_properties_set_int( self->properties, "audio_buffer", 2048 );
116
117                 // Ensure we don't join on a non-running object
118                 self->joined = 1;
119                 
120                 // Allow thread to be started/stopped
121                 parent->start = consumer_start;
122                 parent->stop = consumer_stop;
123                 parent->is_stopped = consumer_is_stopped;
124
125                 // Initialize the refresh handler
126                 pthread_cond_init( &self->refresh_cond, NULL );
127                 pthread_mutex_init( &self->refresh_mutex, NULL );
128                 mlt_events_listen( MLT_CONSUMER_PROPERTIES( parent ), self, "property-changed", ( mlt_listener )consumer_refresh_cb );
129
130                 // Return the consumer produced
131                 return parent;
132         }
133
134         // malloc or consumer init failed
135         free( self );
136
137         // Indicate failure
138         return NULL;
139 }
140
141 static void consumer_refresh_cb( mlt_consumer sdl, mlt_consumer parent, char *name )
142 {
143         if ( !strcmp( name, "refresh" ) )
144         {
145                 consumer_sdl self = parent->child;
146                 pthread_mutex_lock( &self->refresh_mutex );
147                 self->refresh_count = self->refresh_count <= 0 ? 1 : self->refresh_count + 1;
148                 pthread_cond_broadcast( &self->refresh_cond );
149                 pthread_mutex_unlock( &self->refresh_mutex );
150         }
151 }
152
153 int consumer_start( mlt_consumer parent )
154 {
155         consumer_sdl self = parent->child;
156
157         if ( !self->running )
158         {
159                 consumer_stop( parent );
160
161                 pthread_mutex_lock( &mlt_sdl_mutex );
162                 int ret = SDL_Init( SDL_INIT_AUDIO | SDL_INIT_NOPARACHUTE );
163                 pthread_mutex_unlock( &mlt_sdl_mutex );
164                 if ( ret < 0 )
165                 {
166                         mlt_log_error( MLT_CONSUMER_SERVICE(parent), "Failed to initialize SDL: %s\n", SDL_GetError() );
167                         return -1;
168                 }
169
170                 self->running = 1;
171                 self->joined = 0;
172                 pthread_create( &self->thread, NULL, consumer_thread, self );
173         }
174
175         return 0;
176 }
177
178 int consumer_stop( mlt_consumer parent )
179 {
180         // Get the actual object
181         consumer_sdl self = parent->child;
182
183         if ( self->running && !self->joined )
184         {
185                 // Kill the thread and clean up
186                 self->joined = 1;
187                 self->running = 0;
188
189                 // Unlatch the consumer thread
190                 pthread_mutex_lock( &self->refresh_mutex );
191                 pthread_cond_broadcast( &self->refresh_cond );
192                 pthread_mutex_unlock( &self->refresh_mutex );
193
194                 // Cleanup the main thread
195 #ifndef WIN32
196                 if ( self->thread )
197 #endif
198                         pthread_join( self->thread, NULL );
199
200                 // Unlatch the video thread
201                 pthread_mutex_lock( &self->video_mutex );
202                 pthread_cond_broadcast( &self->video_cond );
203                 pthread_mutex_unlock( &self->video_mutex );
204
205                 // Unlatch the audio callback
206                 pthread_mutex_lock( &self->audio_mutex );
207                 pthread_cond_broadcast( &self->audio_cond );
208                 pthread_mutex_unlock( &self->audio_mutex );
209
210                 SDL_QuitSubSystem( SDL_INIT_AUDIO );
211         }
212
213         return 0;
214 }
215
216 int consumer_is_stopped( mlt_consumer parent )
217 {
218         consumer_sdl self = parent->child;
219         return !self->running;
220 }
221
222 static void sdl_fill_audio( void *udata, uint8_t *stream, int len )
223 {
224         consumer_sdl self = udata;
225
226         // Get the volume
227         double volume = mlt_properties_get_double( self->properties, "volume" );
228
229         pthread_mutex_lock( &self->audio_mutex );
230
231         // Block until audio received
232 #ifdef __DARWIN__
233         while ( self->running && len > self->audio_avail )
234                 pthread_cond_wait( &self->audio_cond, &self->audio_mutex );
235 #endif
236
237         if ( self->audio_avail >= len )
238         {
239                 // Place in the audio buffer
240                 if ( volume != 1.0 )
241                         SDL_MixAudio( stream, self->audio_buffer, len, ( int )( ( float )SDL_MIX_MAXVOLUME * volume ) );
242                 else
243                         memcpy( stream, self->audio_buffer, len );
244
245                 // Remove len from the audio available
246                 self->audio_avail -= len;
247
248                 // Remove the samples
249                 memmove( self->audio_buffer, self->audio_buffer + len, self->audio_avail );
250         }
251         else
252         {
253                 // Just to be safe, wipe the stream first
254                 memset( stream, 0, len );
255
256                 // Mix the audio
257                 SDL_MixAudio( stream, self->audio_buffer, self->audio_avail,
258                         ( int )( ( float )SDL_MIX_MAXVOLUME * volume ) );
259
260                 // No audio left
261                 self->audio_avail = 0;
262         }
263
264         // We're definitely playing now
265         self->playing = 1;
266
267         pthread_cond_broadcast( &self->audio_cond );
268         pthread_mutex_unlock( &self->audio_mutex );
269 }
270
271 static int consumer_play_audio( consumer_sdl self, mlt_frame frame, int init_audio, int *duration )
272 {
273         // Get the properties of this consumer
274         mlt_properties properties = self->properties;
275         mlt_audio_format afmt = mlt_audio_s16;
276
277         // Set the preferred params of the test card signal
278         int channels = mlt_properties_get_int( properties, "channels" );
279         int frequency = mlt_properties_get_int( properties, "frequency" );
280         int scrub = mlt_properties_get_int( properties, "scrub_audio" );
281         static int counter = 0;
282
283         int samples = mlt_sample_calculator( mlt_properties_get_double( self->properties, "fps" ), frequency, counter++ );
284         
285         int16_t *pcm;
286         int bytes;
287
288         mlt_frame_get_audio( frame, (void**) &pcm, &afmt, &frequency, &channels, &samples );
289         *duration = ( ( samples * 1000 ) / frequency );
290
291         if ( mlt_properties_get_int( properties, "audio_off" ) )
292         {
293                 self->playing = 1;
294                 init_audio = 1;
295                 return init_audio;
296         }
297
298         if ( init_audio == 1 )
299         {
300                 SDL_AudioSpec request;
301                 SDL_AudioSpec got;
302
303                 int audio_buffer = mlt_properties_get_int( properties, "audio_buffer" );
304
305                 // specify audio format
306                 memset( &request, 0, sizeof( SDL_AudioSpec ) );
307                 self->playing = 0;
308                 request.freq = frequency;
309                 request.format = AUDIO_S16SYS;
310                 request.channels = channels;
311                 request.samples = audio_buffer;
312                 request.callback = sdl_fill_audio;
313                 request.userdata = (void *)self;
314                 if ( SDL_OpenAudio( &request, &got ) != 0 )
315                 {
316                         mlt_log_error( MLT_CONSUMER_SERVICE( self ), "SDL failed to open audio: %s\n", SDL_GetError() );
317                         init_audio = 2;
318                 }
319                 else if ( got.size != 0 )
320                 {
321                         SDL_PauseAudio( 0 );
322                         init_audio = 0;
323                 }
324         }
325
326         if ( init_audio == 0 )
327         {
328                 mlt_properties properties = MLT_FRAME_PROPERTIES( frame );
329                 bytes = ( samples * channels * 2 );
330                 pthread_mutex_lock( &self->audio_mutex );
331                 while ( self->running && bytes > ( sizeof( self->audio_buffer) - self->audio_avail ) )
332                         pthread_cond_wait( &self->audio_cond, &self->audio_mutex );
333                 if ( self->running )
334                 {
335                         if ( scrub || mlt_properties_get_double( properties, "_speed" ) == 1 )
336                                 memcpy( &self->audio_buffer[ self->audio_avail ], pcm, bytes );
337                         else
338                                 memset( &self->audio_buffer[ self->audio_avail ], 0, bytes );
339                         self->audio_avail += bytes;
340                 }
341                 pthread_cond_broadcast( &self->audio_cond );
342                 pthread_mutex_unlock( &self->audio_mutex );
343         }
344         else
345         {
346                 self->playing = 1;
347         }
348
349         return init_audio;
350 }
351
352 static int consumer_play_video( consumer_sdl self, mlt_frame frame )
353 {
354         // Get the properties of this consumer
355         mlt_properties properties = self->properties;
356         if ( self->running && !mlt_consumer_is_stopped( &self->parent ) )
357                 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
358
359         return 0;
360 }
361
362 static void *video_thread( void *arg )
363 {
364         // Identify the arg
365         consumer_sdl self = arg;
366
367         // Obtain time of thread start
368         struct timeval now;
369         int64_t start = 0;
370         int64_t elapsed = 0;
371         struct timespec tm;
372         mlt_frame next = NULL;
373         mlt_properties properties = NULL;
374         double speed = 0;
375
376         // Get real time flag
377         int real_time = mlt_properties_get_int( self->properties, "real_time" );
378
379         // Get the current time
380         gettimeofday( &now, NULL );
381
382         // Determine start time
383         start = ( int64_t )now.tv_sec * 1000000 + now.tv_usec;
384
385         while ( self->running )
386         {
387                 // Pop the next frame
388                 pthread_mutex_lock( &self->video_mutex );
389                 next = mlt_deque_pop_front( self->queue );
390                 while ( next == NULL && self->running )
391                 {
392                         pthread_cond_wait( &self->video_cond, &self->video_mutex );
393                         next = mlt_deque_pop_front( self->queue );
394                 }
395                 pthread_mutex_unlock( &self->video_mutex );
396
397                 if ( !self->running || next == NULL ) break;
398
399                 // Get the properties
400                 properties =  MLT_FRAME_PROPERTIES( next );
401
402                 // Get the speed of the frame
403                 speed = mlt_properties_get_double( properties, "_speed" );
404
405                 // Get the current time
406                 gettimeofday( &now, NULL );
407
408                 // Get the elapsed time
409                 elapsed = ( ( int64_t )now.tv_sec * 1000000 + now.tv_usec ) - start;
410
411                 // See if we have to delay the display of the current frame
412                 if ( mlt_properties_get_int( properties, "rendered" ) == 1 && self->running )
413                 {
414                         // Obtain the scheduled playout time
415                         int64_t scheduled = mlt_properties_get_int( properties, "playtime" );
416
417                         // Determine the difference between the elapsed time and the scheduled playout time
418                         int64_t difference = scheduled - elapsed;
419
420                         // Smooth playback a bit
421                         if ( real_time && ( difference > 20000 && speed == 1.0 ) )
422                         {
423                                 tm.tv_sec = difference / 1000000;
424                                 tm.tv_nsec = ( difference % 1000000 ) * 500;
425                                 nanosleep( &tm, NULL );
426                         }
427
428                         // Show current frame if not too old
429                         if ( !real_time || ( difference > -10000 || speed != 1.0 || mlt_deque_count( self->queue ) < 2 ) )
430                                 consumer_play_video( self, next );
431
432                         // If the queue is empty, recalculate start to allow build up again
433                         if ( real_time && ( mlt_deque_count( self->queue ) == 0 && speed == 1.0 ) )
434                         {
435                                 gettimeofday( &now, NULL );
436                                 start = ( ( int64_t )now.tv_sec * 1000000 + now.tv_usec ) - scheduled + 20000;
437                         }
438                 }
439
440                 // This frame can now be closed
441                 mlt_frame_close( next );
442                 next = NULL;
443         }
444
445         if ( next != NULL )
446                 mlt_frame_close( next );
447
448         mlt_consumer_stopped( &self->parent );
449
450         return NULL;
451 }
452
453 /** Threaded wrapper for pipe.
454 */
455
456 static void *consumer_thread( void *arg )
457 {
458         // Identify the arg
459         consumer_sdl self = arg;
460
461         // Get the consumer
462         mlt_consumer consumer = &self->parent;
463
464         // Get the properties
465         mlt_properties consumer_props = MLT_CONSUMER_PROPERTIES( consumer );
466
467         // Video thread
468         pthread_t thread;
469
470         // internal intialization
471         int init_audio = 1;
472         int init_video = 1;
473         mlt_frame frame = NULL;
474         mlt_properties properties = NULL;
475         int duration = 0;
476         int64_t playtime = 0;
477         struct timespec tm = { 0, 100000 };
478 //      int last_position = -1;
479
480         pthread_mutex_lock( &self->refresh_mutex );
481         self->refresh_count = 0;
482         pthread_mutex_unlock( &self->refresh_mutex );
483
484         // Loop until told not to
485         while( self->running )
486         {
487                 // Get a frame from the attached producer
488                 frame = mlt_consumer_rt_frame( consumer );
489
490                 // Ensure that we have a frame
491                 if ( frame )
492                 {
493                         // Get the frame properties
494                         properties =  MLT_FRAME_PROPERTIES( frame );
495
496                         // Get the speed of the frame
497                         double speed = mlt_properties_get_double( properties, "_speed" );
498
499                         // Get refresh request for the current frame
500                         int refresh = mlt_properties_get_int( consumer_props, "refresh" );
501
502                         // Clear refresh
503                         mlt_events_block( consumer_props, consumer_props );
504                         mlt_properties_set_int( consumer_props, "refresh", 0 );
505                         mlt_events_unblock( consumer_props, consumer_props );
506
507                         // Play audio
508                         init_audio = consumer_play_audio( self, frame, init_audio, &duration );
509
510                         // Determine the start time now
511                         if ( self->playing && init_video )
512                         {
513                                 // Create the video thread
514                                 pthread_create( &thread, NULL, video_thread, self );
515
516                                 // Video doesn't need to be initialised any more
517                                 init_video = 0;
518                         }
519
520                         // Set playtime for this frame
521                         mlt_properties_set_int( properties, "playtime", playtime );
522
523                         while ( self->running && speed != 0 && mlt_deque_count( self->queue ) > 15 )
524                                 nanosleep( &tm, NULL );
525
526                         // Push this frame to the back of the queue
527                         if ( self->running && speed )
528                         {
529                                 pthread_mutex_lock( &self->video_mutex );
530                                 mlt_deque_push_back( self->queue, frame );
531                                 pthread_cond_broadcast( &self->video_cond );
532                                 pthread_mutex_unlock( &self->video_mutex );
533
534                                 // Calculate the next playtime
535                                 playtime += ( duration * 1000 );
536                         }
537                         else if ( self->running )
538                         {
539                                 pthread_mutex_lock( &self->refresh_mutex );
540                                 if ( refresh == 0 && self->refresh_count <= 0 )
541                                 {
542                                         consumer_play_video( self, frame );
543                                         pthread_cond_wait( &self->refresh_cond, &self->refresh_mutex );
544                                 }
545                                 mlt_frame_close( frame );
546                                 self->refresh_count --;
547                                 pthread_mutex_unlock( &self->refresh_mutex );
548                         }
549                         else
550                         {
551                                 mlt_frame_close( frame );
552                                 frame = NULL;
553                         }
554
555                         // Optimisation to reduce latency
556                         if ( frame && speed == 1.0 )
557                         {
558                 // TODO: disabled due to misbehavior on parallel-consumer
559 //                              if ( last_position != -1 && last_position + 1 != mlt_frame_get_position( frame ) )
560 //                                      mlt_consumer_purge( consumer );
561 //                              last_position = mlt_frame_get_position( frame );
562                         }
563                         else
564                         {
565                                 mlt_consumer_purge( consumer );
566 //                              last_position = -1;
567                         }
568                 }
569         }
570
571         // Kill the video thread
572         if ( init_video == 0 )
573         {
574                 pthread_mutex_lock( &self->video_mutex );
575                 pthread_cond_broadcast( &self->video_cond );
576                 pthread_mutex_unlock( &self->video_mutex );
577                 pthread_join( thread, NULL );
578         }
579
580         while( mlt_deque_count( self->queue ) )
581                 mlt_frame_close( mlt_deque_pop_back( self->queue ) );
582
583         self->audio_avail = 0;
584
585         return NULL;
586 }
587
588 /** Callback to allow override of the close method.
589 */
590
591 static void consumer_close( mlt_consumer parent )
592 {
593         // Get the actual object
594         consumer_sdl self = parent->child;
595
596         // Stop the consumer
597         mlt_consumer_stop( parent );
598
599         // Now clean up the rest
600         mlt_consumer_close( parent );
601
602         // Close the queue
603         mlt_deque_close( self->queue );
604
605         // Destroy mutexes
606         pthread_mutex_destroy( &self->audio_mutex );
607         pthread_cond_destroy( &self->audio_cond );
608         pthread_mutex_destroy( &self->video_mutex );
609         pthread_cond_destroy( &self->video_cond );
610         pthread_mutex_destroy( &self->refresh_mutex );
611         pthread_cond_destroy( &self->refresh_cond );
612
613         // Finally clean up this
614         free( self );
615 }