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