]> git.sesse.net Git - mlt/blob - src/modules/sdl/consumer_sdl_audio.c
31e71829edc5a3cd725edaefeb008a31aaaec1e4
[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                 if ( self->refresh_count < 2 )
148                         self->refresh_count = self->refresh_count <= 0 ? 1 : self->refresh_count + 1;
149                 pthread_cond_broadcast( &self->refresh_cond );
150                 pthread_mutex_unlock( &self->refresh_mutex );
151         }
152 }
153
154 int consumer_start( mlt_consumer parent )
155 {
156         consumer_sdl self = parent->child;
157
158         if ( !self->running )
159         {
160                 consumer_stop( parent );
161
162                 pthread_mutex_lock( &mlt_sdl_mutex );
163                 int ret = SDL_Init( SDL_INIT_AUDIO | SDL_INIT_NOPARACHUTE );
164                 pthread_mutex_unlock( &mlt_sdl_mutex );
165                 if ( ret < 0 )
166                 {
167                         mlt_log_error( MLT_CONSUMER_SERVICE(parent), "Failed to initialize SDL: %s\n", SDL_GetError() );
168                         return -1;
169                 }
170
171                 self->running = 1;
172                 self->joined = 0;
173                 pthread_create( &self->thread, NULL, consumer_thread, self );
174         }
175
176         return 0;
177 }
178
179 int consumer_stop( mlt_consumer parent )
180 {
181         // Get the actual object
182         consumer_sdl self = parent->child;
183
184         if ( self->running && !self->joined )
185         {
186                 // Kill the thread and clean up
187                 self->joined = 1;
188                 self->running = 0;
189
190                 // Unlatch the consumer thread
191                 pthread_mutex_lock( &self->refresh_mutex );
192                 pthread_cond_broadcast( &self->refresh_cond );
193                 pthread_mutex_unlock( &self->refresh_mutex );
194
195                 // Cleanup the main thread
196 #ifndef WIN32
197                 if ( self->thread )
198 #endif
199                         pthread_join( self->thread, NULL );
200
201                 // Unlatch the video thread
202                 pthread_mutex_lock( &self->video_mutex );
203                 pthread_cond_broadcast( &self->video_cond );
204                 pthread_mutex_unlock( &self->video_mutex );
205
206                 // Unlatch the audio callback
207                 pthread_mutex_lock( &self->audio_mutex );
208                 pthread_cond_broadcast( &self->audio_cond );
209                 pthread_mutex_unlock( &self->audio_mutex );
210
211                 SDL_QuitSubSystem( SDL_INIT_AUDIO );
212         }
213
214         return 0;
215 }
216
217 int consumer_is_stopped( mlt_consumer parent )
218 {
219         consumer_sdl self = parent->child;
220         return !self->running;
221 }
222
223 static void sdl_fill_audio( void *udata, uint8_t *stream, int len )
224 {
225         consumer_sdl self = udata;
226
227         // Get the volume
228         double volume = mlt_properties_get_double( self->properties, "volume" );
229
230         pthread_mutex_lock( &self->audio_mutex );
231
232         // Block until audio received
233 #ifdef __DARWIN__
234         while ( self->running && len > self->audio_avail )
235                 pthread_cond_wait( &self->audio_cond, &self->audio_mutex );
236 #endif
237
238         if ( self->audio_avail >= len )
239         {
240                 // Place in the audio buffer
241                 if ( volume != 1.0 )
242                         SDL_MixAudio( stream, self->audio_buffer, len, ( int )( ( float )SDL_MIX_MAXVOLUME * volume ) );
243                 else
244                         memcpy( stream, self->audio_buffer, len );
245
246                 // Remove len from the audio available
247                 self->audio_avail -= len;
248
249                 // Remove the samples
250                 memmove( self->audio_buffer, self->audio_buffer + len, self->audio_avail );
251         }
252         else
253         {
254                 // Just to be safe, wipe the stream first
255                 memset( stream, 0, len );
256
257                 // Mix the audio
258                 SDL_MixAudio( stream, self->audio_buffer, self->audio_avail,
259                         ( int )( ( float )SDL_MIX_MAXVOLUME * volume ) );
260
261                 // No audio left
262                 self->audio_avail = 0;
263         }
264
265         // We're definitely playing now
266         self->playing = 1;
267
268         pthread_cond_broadcast( &self->audio_cond );
269         pthread_mutex_unlock( &self->audio_mutex );
270 }
271
272 static int consumer_play_audio( consumer_sdl self, mlt_frame frame, int init_audio, int *duration )
273 {
274         // Get the properties of this consumer
275         mlt_properties properties = self->properties;
276         mlt_audio_format afmt = mlt_audio_s16;
277
278         // Set the preferred params of the test card signal
279         int channels = mlt_properties_get_int( properties, "channels" );
280         int frequency = mlt_properties_get_int( properties, "frequency" );
281         int scrub = mlt_properties_get_int( properties, "scrub_audio" );
282         static int counter = 0;
283
284         int samples = mlt_sample_calculator( mlt_properties_get_double( self->properties, "fps" ), frequency, counter++ );
285         
286         int16_t *pcm;
287         int bytes;
288
289         mlt_frame_get_audio( frame, (void**) &pcm, &afmt, &frequency, &channels, &samples );
290         *duration = ( ( samples * 1000 ) / frequency );
291
292         if ( mlt_properties_get_int( properties, "audio_off" ) )
293         {
294                 self->playing = 1;
295                 init_audio = 1;
296                 return init_audio;
297         }
298
299         if ( init_audio == 1 )
300         {
301                 SDL_AudioSpec request;
302                 SDL_AudioSpec got;
303
304                 int audio_buffer = mlt_properties_get_int( properties, "audio_buffer" );
305
306                 // specify audio format
307                 memset( &request, 0, sizeof( SDL_AudioSpec ) );
308                 self->playing = 0;
309                 request.freq = frequency;
310                 request.format = AUDIO_S16SYS;
311                 request.channels = channels;
312                 request.samples = audio_buffer;
313                 request.callback = sdl_fill_audio;
314                 request.userdata = (void *)self;
315                 if ( SDL_OpenAudio( &request, &got ) != 0 )
316                 {
317                         mlt_log_error( MLT_CONSUMER_SERVICE( self ), "SDL failed to open audio: %s\n", SDL_GetError() );
318                         init_audio = 2;
319                 }
320                 else if ( got.size != 0 )
321                 {
322                         SDL_PauseAudio( 0 );
323                         init_audio = 0;
324                 }
325         }
326
327         if ( init_audio == 0 )
328         {
329                 mlt_properties properties = MLT_FRAME_PROPERTIES( frame );
330                 bytes = ( samples * channels * 2 );
331                 pthread_mutex_lock( &self->audio_mutex );
332                 while ( self->running && bytes > ( sizeof( self->audio_buffer) - self->audio_avail ) )
333                         pthread_cond_wait( &self->audio_cond, &self->audio_mutex );
334                 if ( self->running )
335                 {
336                         if ( scrub || mlt_properties_get_double( properties, "_speed" ) == 1 )
337                                 memcpy( &self->audio_buffer[ self->audio_avail ], pcm, bytes );
338                         else
339                                 memset( &self->audio_buffer[ self->audio_avail ], 0, bytes );
340                         self->audio_avail += bytes;
341                 }
342                 pthread_cond_broadcast( &self->audio_cond );
343                 pthread_mutex_unlock( &self->audio_mutex );
344         }
345         else
346         {
347                 self->playing = 1;
348         }
349
350         return init_audio;
351 }
352
353 static int consumer_play_video( consumer_sdl self, mlt_frame frame )
354 {
355         // Get the properties of this consumer
356         mlt_properties properties = self->properties;
357         if ( self->running && !mlt_consumer_is_stopped( &self->parent ) )
358                 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
359
360         return 0;
361 }
362
363 static void *video_thread( void *arg )
364 {
365         // Identify the arg
366         consumer_sdl self = arg;
367
368         // Obtain time of thread start
369         struct timeval now;
370         int64_t start = 0;
371         int64_t elapsed = 0;
372         struct timespec tm;
373         mlt_frame next = NULL;
374         mlt_properties properties = NULL;
375         double speed = 0;
376
377         // Get real time flag
378         int real_time = mlt_properties_get_int( self->properties, "real_time" );
379
380         // Get the current time
381         gettimeofday( &now, NULL );
382
383         // Determine start time
384         start = ( int64_t )now.tv_sec * 1000000 + now.tv_usec;
385
386         while ( self->running )
387         {
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 )
392                 {
393                         pthread_cond_wait( &self->video_cond, &self->video_mutex );
394                         next = mlt_deque_pop_front( self->queue );
395                 }
396                 pthread_mutex_unlock( &self->video_mutex );
397
398                 if ( !self->running || next == NULL ) break;
399
400                 // Get the properties
401                 properties =  MLT_FRAME_PROPERTIES( next );
402
403                 // Get the speed of the frame
404                 speed = mlt_properties_get_double( properties, "_speed" );
405
406                 // Get the current time
407                 gettimeofday( &now, NULL );
408
409                 // Get the elapsed time
410                 elapsed = ( ( int64_t )now.tv_sec * 1000000 + now.tv_usec ) - start;
411
412                 // See if we have to delay the display of the current frame
413                 if ( mlt_properties_get_int( properties, "rendered" ) == 1 && self->running )
414                 {
415                         // Obtain the scheduled playout time
416                         int64_t scheduled = mlt_properties_get_int( properties, "playtime" );
417
418                         // Determine the difference between the elapsed time and the scheduled playout time
419                         int64_t difference = scheduled - elapsed;
420
421                         // Smooth playback a bit
422                         if ( real_time && ( difference > 20000 && speed == 1.0 ) )
423                         {
424                                 tm.tv_sec = difference / 1000000;
425                                 tm.tv_nsec = ( difference % 1000000 ) * 500;
426                                 nanosleep( &tm, NULL );
427                         }
428
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 );
432
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 ) )
435                         {
436                                 gettimeofday( &now, NULL );
437                                 start = ( ( int64_t )now.tv_sec * 1000000 + now.tv_usec ) - scheduled + 20000;
438                         }
439                 }
440
441                 // This frame can now be closed
442                 mlt_frame_close( next );
443                 next = NULL;
444         }
445
446         if ( next != NULL )
447                 mlt_frame_close( next );
448
449         mlt_consumer_stopped( &self->parent );
450
451         return NULL;
452 }
453
454 /** Threaded wrapper for pipe.
455 */
456
457 static void *consumer_thread( void *arg )
458 {
459         // Identify the arg
460         consumer_sdl self = arg;
461
462         // Get the consumer
463         mlt_consumer consumer = &self->parent;
464
465         // Get the properties
466         mlt_properties consumer_props = MLT_CONSUMER_PROPERTIES( consumer );
467
468         // Video thread
469         pthread_t thread;
470
471         // internal intialization
472         int init_audio = 1;
473         int init_video = 1;
474         mlt_frame frame = NULL;
475         mlt_properties properties = NULL;
476         int duration = 0;
477         int64_t playtime = 0;
478         struct timespec tm = { 0, 100000 };
479 //      int last_position = -1;
480
481         pthread_mutex_lock( &self->refresh_mutex );
482         self->refresh_count = 0;
483         pthread_mutex_unlock( &self->refresh_mutex );
484
485         // Loop until told not to
486         while( self->running )
487         {
488                 // Get a frame from the attached producer
489                 frame = mlt_consumer_rt_frame( consumer );
490
491                 // Ensure that we have a frame
492                 if ( frame )
493                 {
494                         // Get the frame properties
495                         properties =  MLT_FRAME_PROPERTIES( frame );
496
497                         // Get the speed of the frame
498                         double speed = mlt_properties_get_double( properties, "_speed" );
499
500                         // Get refresh request for the current frame
501                         int refresh = mlt_properties_get_int( consumer_props, "refresh" );
502
503                         // Clear refresh
504                         mlt_events_block( consumer_props, consumer_props );
505                         mlt_properties_set_int( consumer_props, "refresh", 0 );
506                         mlt_events_unblock( consumer_props, consumer_props );
507
508                         // Play audio
509                         init_audio = consumer_play_audio( self, frame, init_audio, &duration );
510
511                         // Determine the start time now
512                         if ( self->playing && init_video )
513                         {
514                                 // Create the video thread
515                                 pthread_create( &thread, NULL, video_thread, self );
516
517                                 // Video doesn't need to be initialised any more
518                                 init_video = 0;
519                         }
520
521                         // Set playtime for this frame
522                         mlt_properties_set_int( properties, "playtime", playtime );
523
524                         while ( self->running && speed != 0 && mlt_deque_count( self->queue ) > 15 )
525                                 nanosleep( &tm, NULL );
526
527                         // Push this frame to the back of the queue
528                         if ( self->running && speed )
529                         {
530                                 pthread_mutex_lock( &self->video_mutex );
531                                 mlt_deque_push_back( self->queue, frame );
532                                 pthread_cond_broadcast( &self->video_cond );
533                                 pthread_mutex_unlock( &self->video_mutex );
534
535                                 // Calculate the next playtime
536                                 playtime += ( duration * 1000 );
537                         }
538                         else if ( self->running )
539                         {
540                                 pthread_mutex_lock( &self->refresh_mutex );
541                                 if ( ( refresh == 0 && self->refresh_count <= 0 ) || self->refresh_count > 1 )
542                                 {
543                                         consumer_play_video( self, frame );
544                                         pthread_cond_wait( &self->refresh_cond, &self->refresh_mutex );
545                                 }
546                                 mlt_frame_close( frame );
547                                 self->refresh_count --;
548                                 pthread_mutex_unlock( &self->refresh_mutex );
549                         }
550                         else
551                         {
552                                 mlt_frame_close( frame );
553                                 frame = NULL;
554                         }
555
556                         // Optimisation to reduce latency
557                         if ( frame && speed == 1.0 )
558                         {
559                 // TODO: disabled due to misbehavior on parallel-consumer
560 //                              if ( last_position != -1 && last_position + 1 != mlt_frame_get_position( frame ) )
561 //                                      mlt_consumer_purge( consumer );
562 //                              last_position = mlt_frame_get_position( frame );
563                         }
564                         else
565                         {
566                                 mlt_consumer_purge( consumer );
567 //                              last_position = -1;
568                         }
569                 }
570         }
571
572         // Kill the video thread
573         if ( init_video == 0 )
574         {
575                 pthread_mutex_lock( &self->video_mutex );
576                 pthread_cond_broadcast( &self->video_cond );
577                 pthread_mutex_unlock( &self->video_mutex );
578                 pthread_join( thread, NULL );
579         }
580
581         while( mlt_deque_count( self->queue ) )
582                 mlt_frame_close( mlt_deque_pop_back( self->queue ) );
583
584         self->audio_avail = 0;
585
586         return NULL;
587 }
588
589 /** Callback to allow override of the close method.
590 */
591
592 static void consumer_close( mlt_consumer parent )
593 {
594         // Get the actual object
595         consumer_sdl self = parent->child;
596
597         // Stop the consumer
598         mlt_consumer_stop( parent );
599
600         // Now clean up the rest
601         mlt_consumer_close( parent );
602
603         // Close the queue
604         mlt_deque_close( self->queue );
605
606         // Destroy mutexes
607         pthread_mutex_destroy( &self->audio_mutex );
608         pthread_cond_destroy( &self->audio_cond );
609         pthread_mutex_destroy( &self->video_mutex );
610         pthread_cond_destroy( &self->video_cond );
611         pthread_mutex_destroy( &self->refresh_mutex );
612         pthread_cond_destroy( &self->refresh_cond );
613
614         // Finally clean up this
615         free( self );
616 }