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