2 * consumer_rtaudio.c -- output through RtAudio audio wrapper
3 * Copyright (C) 2011 Dan Dennedy <dan@dennedy.org>
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with consumer library; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 #include <framework/mlt.h>
27 static void consumer_refresh_cb( mlt_consumer sdl, mlt_consumer consumer, char *name );
28 static int rtaudio_callback( void *outputBuffer, void *inputBuffer,
29 unsigned int nFrames, double streamTime, RtAudioStreamStatus status, void *userData );
30 static void *consumer_thread_proxy( void *arg );
31 static void *video_thread_proxy( void *arg );
36 struct mlt_consumer_s consumer;
43 uint8_t audio_buffer[4096 * 10];
45 pthread_mutex_t audio_mutex;
46 pthread_cond_t audio_cond;
47 pthread_mutex_t video_mutex;
48 pthread_cond_t video_cond;
50 pthread_cond_t refresh_cond;
51 pthread_mutex_t refresh_mutex;
54 mlt_consumer getConsumer()
66 memset( &consumer, 0, sizeof( consumer ) );
72 mlt_deque_close( queue );
75 pthread_mutex_destroy( &audio_mutex );
76 pthread_cond_destroy( &audio_cond );
77 pthread_mutex_destroy( &video_mutex );
78 pthread_cond_destroy( &video_cond );
79 pthread_mutex_destroy( &refresh_mutex );
80 pthread_cond_destroy( &refresh_cond );
82 if ( rt.isStreamOpen() )
86 bool open( const char* arg )
88 if ( rt.getDeviceCount() < 1 )
90 mlt_log_warning( getConsumer(), "no audio devices found\n" );
94 #ifndef __LINUX_ALSA__
95 device_id = rt.getDefaultOutputDevice();
97 if ( arg && strcmp( arg, "" ) && strcmp( arg, "default" ) )
99 // Get device ID by name
100 unsigned int n = rt.getDeviceCount();
101 RtAudio::DeviceInfo info;
104 for ( i = 0; i < n; i++ )
106 info = rt.getDeviceInfo( i );
107 mlt_log_verbose( NULL, "RtAudio device %d = %s\n",
108 i, info.name.c_str() );
109 if ( info.probed && info.name == arg )
115 // Name selection failed, try arg as numeric
117 device_id = (int) strtol( arg, NULL, 0 );
121 queue = mlt_deque_init( );
123 // get a handle on properties
124 mlt_properties properties = MLT_CONSUMER_PROPERTIES( &consumer );
126 // Set the default volume
127 mlt_properties_set_double( properties, "volume", 1.0 );
129 // This is the initialisation of the consumer
130 pthread_mutex_init( &audio_mutex, NULL );
131 pthread_cond_init( &audio_cond, NULL);
132 pthread_mutex_init( &video_mutex, NULL );
133 pthread_cond_init( &video_cond, NULL);
135 // Default scaler (for now we'll use nearest)
136 mlt_properties_set( properties, "rescale", "nearest" );
137 mlt_properties_set( properties, "deinterlace_method", "onefield" );
139 // Default buffer for low latency
140 mlt_properties_set_int( properties, "buffer", 1 );
142 // Default audio buffer
143 mlt_properties_set_int( properties, "audio_buffer", 1024 );
145 // Set the resource to the device name arg
146 mlt_properties_set( properties, "resource", arg );
148 // Ensure we don't join on a non-running object
151 // Initialize the refresh handler
152 pthread_cond_init( &refresh_cond, NULL );
153 pthread_mutex_init( &refresh_mutex, NULL );
154 mlt_events_listen( properties, this, "property-changed", ( mlt_listener )consumer_refresh_cb );
166 pthread_create( &thread, NULL, consumer_thread_proxy, this );
174 if ( running && !joined )
176 // Kill the thread and clean up
180 // Unlatch the consumer thread
181 pthread_mutex_lock( &refresh_mutex );
182 pthread_cond_broadcast( &refresh_cond );
183 pthread_mutex_unlock( &refresh_mutex );
185 // Cleanup the main thread
186 pthread_join( thread, NULL );
188 // Unlatch the video thread
189 pthread_mutex_lock( &video_mutex );
190 pthread_cond_broadcast( &video_cond );
191 pthread_mutex_unlock( &video_mutex );
193 // Unlatch the audio callback
194 pthread_mutex_lock( &audio_mutex );
195 pthread_cond_broadcast( &audio_cond );
196 pthread_mutex_unlock( &audio_mutex );
198 if ( rt.isStreamOpen() )
203 catch ( RtError& e ) {
204 mlt_log_error( getConsumer(), "%s\n", e.getMessage().c_str() );
211 void consumer_thread()
213 // Get the properties
214 mlt_properties consumer_props = MLT_CONSUMER_PROPERTIES( getConsumer() );
219 // internal intialization
222 mlt_frame frame = NULL;
223 mlt_properties properties = NULL;
225 int64_t playtime = 0;
226 struct timespec tm = { 0, 100000 };
227 // int last_position = -1;
229 pthread_mutex_lock( &refresh_mutex );
231 pthread_mutex_unlock( &refresh_mutex );
233 // Loop until told not to
236 // Get a frame from the attached producer
237 frame = mlt_consumer_rt_frame( getConsumer() );
239 // Ensure that we have a frame
242 // Get the frame properties
243 properties = MLT_FRAME_PROPERTIES( frame );
245 // Get the speed of the frame
246 double speed = mlt_properties_get_double( properties, "_speed" );
248 // Get refresh request for the current frame
249 int refresh = mlt_properties_get_int( consumer_props, "refresh" );
252 mlt_events_block( consumer_props, consumer_props );
253 mlt_properties_set_int( consumer_props, "refresh", 0 );
254 mlt_events_unblock( consumer_props, consumer_props );
257 init_audio = play_audio( frame, init_audio, &duration );
259 // Determine the start time now
260 if ( playing && init_video )
262 // Create the video thread
263 pthread_create( &thread, NULL, video_thread_proxy, this );
265 // Video doesn't need to be initialised any more
269 // Set playtime for this frame
270 mlt_properties_set_int( properties, "playtime", playtime );
272 while ( running && speed != 0 && mlt_deque_count( queue ) > 15 )
273 nanosleep( &tm, NULL );
275 // Push this frame to the back of the queue
276 if ( running && speed )
278 pthread_mutex_lock( &video_mutex );
279 mlt_deque_push_back( queue, frame );
280 pthread_cond_broadcast( &video_cond );
281 pthread_mutex_unlock( &video_mutex );
283 // Calculate the next playtime
284 playtime += ( duration * 1000 );
288 pthread_mutex_lock( &refresh_mutex );
289 if ( refresh == 0 && refresh_count <= 0 )
292 pthread_cond_wait( &refresh_cond, &refresh_mutex );
294 mlt_frame_close( frame );
296 pthread_mutex_unlock( &refresh_mutex );
300 mlt_frame_close( frame );
304 // Optimisation to reduce latency
305 if ( frame && speed == 1.0 )
307 // TODO: disabled due to misbehavior on parallel-consumer
308 // if ( last_position != -1 && last_position + 1 != mlt_frame_get_position( frame ) )
309 // mlt_consumer_purge( consumer );
310 // last_position = mlt_frame_get_position( frame );
314 mlt_consumer_purge( getConsumer() );
315 // last_position = -1;
320 // Kill the video thread
321 if ( init_video == 0 )
323 pthread_mutex_lock( &video_mutex );
324 pthread_cond_broadcast( &video_cond );
325 pthread_mutex_unlock( &video_mutex );
326 pthread_join( thread, NULL );
329 while( mlt_deque_count( queue ) )
330 mlt_frame_close( (mlt_frame) mlt_deque_pop_back( queue ) );
335 int callback( int16_t *outbuf, int16_t *inbuf,
336 unsigned int samples, double streamTime, RtAudioStreamStatus status )
338 mlt_properties properties = MLT_CONSUMER_PROPERTIES( getConsumer() );
339 double volume = mlt_properties_get_double( properties, "volume" );
340 int channels = mlt_properties_get_int( properties, "channels" );
341 int len = mlt_audio_format_size( mlt_audio_s16, samples, channels );
343 pthread_mutex_lock( &audio_mutex );
345 // Block until audio received
346 while ( running && len > audio_avail )
347 pthread_cond_wait( &audio_cond, &audio_mutex );
349 if ( audio_avail >= len )
351 // Place in the audio buffer
352 memcpy( outbuf, audio_buffer, len );
354 // Remove len from the audio available
357 // Remove the samples
358 memmove( audio_buffer, audio_buffer + len, audio_avail );
362 // Just to be safe, wipe the stream first
363 memset( outbuf, 0, len );
366 memcpy( outbuf, audio_buffer, audio_avail );
375 int i = samples * channels + 1;
380 // We're definitely playing now
383 pthread_cond_broadcast( &audio_cond );
384 pthread_mutex_unlock( &audio_mutex );
389 int play_audio( mlt_frame frame, int init_audio, int *duration )
391 // Get the properties of this consumer
392 mlt_properties properties = MLT_CONSUMER_PROPERTIES( getConsumer() );
393 mlt_audio_format afmt = mlt_audio_s16;
395 // Set the preferred params of the test card signal
396 int channels = mlt_properties_get_int( properties, "channels" );
397 int frequency = mlt_properties_get_int( properties, "frequency" );
398 int scrub = mlt_properties_get_int( properties, "scrub_audio" );
399 static int counter = 0;
400 int samples = mlt_sample_calculator( mlt_properties_get_double( properties, "fps" ), frequency, counter++ );
403 mlt_frame_get_audio( frame, (void**) &pcm, &afmt, &frequency, &channels, &samples );
404 *duration = ( ( samples * 1000 ) / frequency );
406 if ( mlt_properties_get_int( properties, "audio_off" ) )
412 if ( init_audio == 1 )
414 RtAudio::StreamParameters parameters;
415 parameters.deviceId = device_id;
416 parameters.nChannels = channels;
417 parameters.firstChannel = 0;
418 RtAudio::StreamOptions options;
419 unsigned int bufferFrames = mlt_properties_get_int( properties, "audio_buffer" );
421 if ( device_id == -1 )
423 options.flags = RTAUDIO_ALSA_USE_DEFAULT;
424 parameters.deviceId = 0;
426 if ( mlt_properties_get( properties, "resource" ) )
427 parameters.deviceName = mlt_properties_get( properties, "resource" );
430 rt.openStream( ¶meters, NULL, RTAUDIO_SINT16,
431 frequency, &bufferFrames, &rtaudio_callback, this, &options );
436 catch ( RtError& e ) {
437 mlt_log_error( getConsumer(), "%s\n", e.getMessage().c_str() );
442 if ( init_audio == 0 )
444 mlt_properties properties = MLT_FRAME_PROPERTIES( frame );
445 size_t bytes = ( samples * channels * 2 );
446 pthread_mutex_lock( &audio_mutex );
447 while ( running && bytes > ( sizeof( audio_buffer) - audio_avail ) )
448 pthread_cond_wait( &audio_cond, &audio_mutex );
451 if ( scrub || mlt_properties_get_double( properties, "_speed" ) == 1 )
452 memcpy( &audio_buffer[ audio_avail ], pcm, bytes );
454 memset( &audio_buffer[ audio_avail ], 0, bytes );
455 audio_avail += bytes;
457 pthread_cond_broadcast( &audio_cond );
458 pthread_mutex_unlock( &audio_mutex );
464 int play_video( mlt_frame frame )
466 // Get the properties of this consumer
467 mlt_properties properties = MLT_CONSUMER_PROPERTIES( getConsumer() );
468 if ( running && !mlt_consumer_is_stopped( getConsumer() ) )
469 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
476 // Obtain time of thread start
481 mlt_frame next = NULL;
482 mlt_properties properties = MLT_CONSUMER_PROPERTIES( getConsumer() );
485 // Get real time flag
486 int real_time = mlt_properties_get_int( properties, "real_time" );
488 // Get the current time
489 gettimeofday( &now, NULL );
491 // Determine start time
492 start = ( int64_t )now.tv_sec * 1000000 + now.tv_usec;
496 // Pop the next frame
497 pthread_mutex_lock( &video_mutex );
498 next = (mlt_frame) mlt_deque_pop_front( queue );
499 while ( next == NULL && running )
501 pthread_cond_wait( &video_cond, &video_mutex );
502 next = (mlt_frame) mlt_deque_pop_front( queue );
504 pthread_mutex_unlock( &video_mutex );
506 if ( !running || next == NULL ) break;
508 // Get the properties
509 properties = MLT_FRAME_PROPERTIES( next );
511 // Get the speed of the frame
512 speed = mlt_properties_get_double( properties, "_speed" );
514 // Get the current time
515 gettimeofday( &now, NULL );
517 // Get the elapsed time
518 elapsed = ( ( int64_t )now.tv_sec * 1000000 + now.tv_usec ) - start;
520 // See if we have to delay the display of the current frame
521 if ( mlt_properties_get_int( properties, "rendered" ) == 1 && running )
523 // Obtain the scheduled playout time
524 int64_t scheduled = mlt_properties_get_int( properties, "playtime" );
526 // Determine the difference between the elapsed time and the scheduled playout time
527 int64_t difference = scheduled - elapsed;
529 // Smooth playback a bit
530 if ( real_time && ( difference > 20000 && speed == 1.0 ) )
532 tm.tv_sec = difference / 1000000;
533 tm.tv_nsec = ( difference % 1000000 ) * 500;
534 nanosleep( &tm, NULL );
537 // Show current frame if not too old
538 if ( !real_time || ( difference > -10000 || speed != 1.0 || mlt_deque_count( queue ) < 2 ) )
541 // If the queue is empty, recalculate start to allow build up again
542 if ( real_time && ( mlt_deque_count( queue ) == 0 && speed == 1.0 ) )
544 gettimeofday( &now, NULL );
545 start = ( ( int64_t )now.tv_sec * 1000000 + now.tv_usec ) - scheduled + 20000;
549 // This frame can now be closed
550 mlt_frame_close( next );
555 mlt_frame_close( next );
557 mlt_consumer_stopped( getConsumer() );
562 static void consumer_refresh_cb( mlt_consumer sdl, mlt_consumer consumer, char *name )
564 if ( !strcmp( name, "refresh" ) )
566 RtAudioConsumer* rtaudio = (RtAudioConsumer*) consumer->child;
567 pthread_mutex_lock( &rtaudio->refresh_mutex );
568 rtaudio->refresh_count = rtaudio->refresh_count <= 0 ? 1 : rtaudio->refresh_count + 1;
569 pthread_cond_broadcast( &rtaudio->refresh_cond );
570 pthread_mutex_unlock( &rtaudio->refresh_mutex );
574 static int rtaudio_callback( void *outputBuffer, void *inputBuffer,
575 unsigned int nFrames, double streamTime, RtAudioStreamStatus status, void *userData )
577 RtAudioConsumer* rtaudio = (RtAudioConsumer*) userData;
578 return rtaudio->callback( (int16_t*) outputBuffer, (int16_t*) inputBuffer, nFrames, streamTime, status );
581 static void *consumer_thread_proxy( void *arg )
583 RtAudioConsumer* rtaudio = (RtAudioConsumer*) arg;
584 rtaudio->consumer_thread();
588 static void *video_thread_proxy( void *arg )
590 RtAudioConsumer* rtaudio = (RtAudioConsumer*) arg;
591 rtaudio->video_thread();
595 /** Start the consumer.
598 static int start( mlt_consumer consumer )
600 RtAudioConsumer* rtaudio = (RtAudioConsumer*) consumer->child;
601 return rtaudio->start();
604 /** Stop the consumer.
607 static int stop( mlt_consumer consumer )
609 RtAudioConsumer* rtaudio = (RtAudioConsumer*) consumer->child;
610 return rtaudio->stop();
613 /** Determine if the consumer is stopped.
616 static int is_stopped( mlt_consumer consumer )
618 RtAudioConsumer* rtaudio = (RtAudioConsumer*) consumer->child;
619 return !rtaudio->running;
622 /** Close the consumer.
625 static void close( mlt_consumer consumer )
628 mlt_consumer_stop( consumer );
631 consumer->close = NULL;
632 mlt_consumer_close( consumer );
635 delete (RtAudioConsumer*) consumer->child;
640 mlt_consumer consumer_rtaudio_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
642 // Allocate the consumer
643 RtAudioConsumer* rtaudio = new RtAudioConsumer();
644 mlt_consumer consumer = NULL;
647 if ( rtaudio && !mlt_consumer_init( rtaudio->getConsumer(), rtaudio, profile ) )
649 // If initialises without error
650 if ( rtaudio->open( arg? arg : getenv( "AUDIODEV" ) ) )
653 consumer = rtaudio->getConsumer();
654 consumer->close = close;
655 consumer->start = start;
656 consumer->stop = stop;
657 consumer->is_stopped = is_stopped;
661 mlt_consumer_close( rtaudio->getConsumer() );
670 static mlt_properties metadata( mlt_service_type type, const char *id, void *data )
672 char file[ PATH_MAX ];
673 const char *service_type = "consumer";
674 snprintf( file, PATH_MAX, "%s/rtaudio/%s_%s.yml", mlt_environment( "MLT_DATA" ), service_type, id );
675 return mlt_properties_parse_yaml( file );
680 MLT_REGISTER( consumer_type, "rtaudio", consumer_rtaudio_init );
681 MLT_REGISTER_METADATA( consumer_type, "rtaudio", metadata, NULL );