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