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