2 * consumer_decklink.c -- output through Blackmagic Design DeckLink
3 * Copyright (C) 2010 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>
26 #include "DeckLinkAPI.h"
28 const unsigned PREROLL_MINIMUM = 3;
35 pthread_mutex_t mutex;
38 static sample_fifo sample_fifo_init()
40 sample_fifo fifo = (sample_fifo) calloc( 1, sizeof( *fifo ) );
41 pthread_mutex_init( &fifo->mutex, NULL );
45 static void sample_fifo_append( sample_fifo fifo, int16_t *samples, int count )
47 pthread_mutex_lock( &fifo->mutex );
48 if ( ( fifo->size - fifo->used ) < count )
50 fifo->size += count * 5;
51 fifo->buffer = (int16_t*) realloc( fifo->buffer, fifo->size * sizeof( int16_t ) );
53 memcpy( fifo->buffer + fifo->used, samples, count * sizeof( int16_t ) );
55 pthread_mutex_unlock( &fifo->mutex );
58 static void sample_fifo_remove( sample_fifo fifo, int count )
60 pthread_mutex_lock( &fifo->mutex );
61 if ( count > fifo->used )
64 memmove( fifo->buffer, fifo->buffer + count, fifo->used * sizeof( int16_t ) );
65 pthread_mutex_unlock( &fifo->mutex );
68 static void sample_fifo_close( sample_fifo fifo )
71 pthread_mutex_destroy( &fifo->mutex );
76 class DeckLinkConsumer
77 : public IDeckLinkVideoOutputCallback
78 , public IDeckLinkAudioOutputCallback
81 mlt_consumer_s m_consumer;
82 IDeckLink* m_deckLink;
83 IDeckLinkOutput* m_deckLinkOutput;
84 IDeckLinkMutableVideoFrame* m_videoFrame;
85 IDeckLinkDisplayMode* m_displayMode;
86 pthread_mutex_t m_mutex;
87 pthread_cond_t m_condition;
90 BMDTimeValue m_duration;
91 BMDTimeScale m_timescale;
97 unsigned m_prerollCounter;
99 uint32_t m_maxAudioBuffer;
100 mlt_deque m_videoFrameQ;
102 IDeckLinkDisplayMode* getDisplayMode()
104 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( &m_consumer ) );
105 IDeckLinkDisplayModeIterator* iter;
106 IDeckLinkDisplayMode* mode;
107 IDeckLinkDisplayMode* result = 0;
109 if ( m_deckLinkOutput->GetDisplayModeIterator( &iter ) == S_OK )
111 while ( !result && iter->Next( &mode ) == S_OK )
113 m_width = mode->GetWidth();
114 m_height = mode->GetHeight();
115 mode->GetFrameRate( &m_duration, &m_timescale );
116 m_fps = (double) m_timescale / m_duration;
117 int p = mode->GetFieldDominance() == bmdProgressiveFrame;
118 mlt_log_verbose( &m_consumer, "BMD mode %dx%d %.3f fps prog %d\n", m_width, m_height, m_fps, p );
120 if ( m_width == profile->width && m_height == profile->height && p == profile->progressive
121 && m_fps == mlt_profile_fps( profile ) )
130 mlt_consumer getConsumer()
131 { return &m_consumer; }
132 uint64_t isBuffering() const
133 { return m_prerollCounter < m_preroll; }
137 if ( m_deckLinkOutput )
138 m_deckLinkOutput->Release();
140 m_deckLink->Release();
142 mlt_deque_close( m_videoFrameQ );
145 bool open( unsigned card = 0 )
147 IDeckLinkIterator* deckLinkIterator = CreateDeckLinkIteratorInstance();
150 if ( !deckLinkIterator )
152 mlt_log_verbose( NULL, "The DeckLink drivers not installed.\n" );
156 // Connect to the Nth DeckLink instance
158 if ( deckLinkIterator->Next( &m_deckLink ) != S_OK )
160 mlt_log_verbose( NULL, "DeckLink card not found\n" );
161 deckLinkIterator->Release();
164 } while ( ++i <= card );
166 // Obtain the audio/video output interface (IDeckLinkOutput)
167 if ( m_deckLink->QueryInterface( IID_IDeckLinkOutput, (void**)&m_deckLinkOutput ) != S_OK )
169 mlt_log_verbose( NULL, "No DeckLink cards support output\n" );
170 m_deckLink->Release();
172 deckLinkIterator->Release();
176 // Provide this class as a delegate to the audio and video output interfaces
177 m_deckLinkOutput->SetScheduledFrameCompletionCallback( this );
178 m_deckLinkOutput->SetAudioCallback( this );
180 pthread_mutex_init( &m_mutex, NULL );
181 pthread_cond_init( &m_condition, NULL );
182 m_maxAudioBuffer = bmdAudioSampleRate48kHz;
183 m_videoFrameQ = mlt_deque_init();
188 bool start( unsigned preroll )
190 m_displayMode = getDisplayMode();
191 if ( !m_displayMode )
193 mlt_log_error( &m_consumer, "Profile is not compatible with decklink.\n" );
197 // Set the video output mode
198 if ( S_OK != m_deckLinkOutput->EnableVideoOutput( m_displayMode->GetDisplayMode(), bmdVideoOutputFlagDefault) )
200 mlt_log_error( &m_consumer, "Failed to enable video output\n" );
204 // Set the audio output mode
206 if ( S_OK != m_deckLinkOutput->EnableAudioOutput( bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger,
207 m_channels, bmdAudioOutputStreamContinuous ) )
209 mlt_log_error( &m_consumer, "Failed to enable audio output\n" );
213 m_fifo = sample_fifo_init();
216 m_isPrerolling = true;
217 m_prerollCounter = 0;
218 m_preroll = preroll < PREROLL_MINIMUM ? PREROLL_MINIMUM : preroll;
220 m_deckLinkOutput->BeginAudioPreroll();
227 pthread_mutex_lock( &m_mutex );
228 pthread_cond_broadcast( &m_condition );
229 pthread_mutex_unlock( &m_mutex );
237 gettimeofday( &tv, NULL );
238 ts.tv_sec = tv.tv_sec + 1;
239 ts.tv_nsec = tv.tv_usec * 1000;
240 pthread_mutex_lock( &m_mutex );
241 pthread_cond_timedwait( &m_condition, &m_mutex, &ts );
242 pthread_mutex_unlock( &m_mutex );
247 // Stop the audio and video output streams immediately
248 if ( m_deckLinkOutput )
250 m_deckLinkOutput->StopScheduledPlayback( 0, 0, 0 );
251 m_deckLinkOutput->DisableAudioOutput();
252 m_deckLinkOutput->DisableVideoOutput();
254 while ( mlt_deque_count( m_videoFrameQ ) )
256 m_videoFrame = (IDeckLinkMutableVideoFrame*) mlt_deque_pop_back( m_videoFrameQ );
257 m_videoFrame->Release();
260 if ( m_fifo ) sample_fifo_close( m_fifo );
266 // Generate a DeckLink video frame
267 if ( S_OK != m_deckLinkOutput->CreateVideoFrame( m_width, m_height,
268 m_width * 2, bmdFormat8BitYUV, bmdFrameFlagDefault, &m_videoFrame ) )
270 mlt_log_verbose( &m_consumer, "Failed to create video frame\n" );
275 // Make the first line black for field order correction.
277 if ( S_OK == m_videoFrame->GetBytes( (void**) &buffer ) && buffer )
279 for ( int i = 0; i < m_width; i++ )
285 mlt_log_debug( &m_consumer, "created video frame\n" );
286 mlt_deque_push_back( m_videoFrameQ, m_videoFrame );
289 HRESULT render( mlt_frame frame )
291 HRESULT result = S_OK;
293 double speed = mlt_properties_get_double( MLT_FRAME_PROPERTIES(frame), "_speed" );
296 mlt_audio_format format = mlt_audio_s16;
297 int frequency = bmdAudioSampleRate48kHz;
298 int samples = mlt_sample_calculator( m_fps, frequency, m_count );
301 if ( !mlt_frame_get_audio( frame, (void**) &pcm, &format, &frequency, &m_channels, &samples ) )
305 if ( !m_isPrerolling )
307 uint32_t audioCount = 0;
308 uint32_t videoCount = 0;
311 m_deckLinkOutput->GetBufferedAudioSampleFrameCount( &audioCount );
312 m_deckLinkOutput->GetBufferedVideoFrameCount( &videoCount );
314 // Underflow typically occurs during non-normal speed playback.
315 if ( audioCount < 1 || videoCount < 1 )
317 // Upon switching to normal playback, buffer some frames faster than realtime.
318 mlt_log_info( &m_consumer, "buffer underrun: audio buf %u video buf %u frames\n", audioCount, videoCount );
319 m_prerollCounter = 0;
325 // Only append audio to reach the ideal level and not overbuffer.
326 int ideal = ( m_preroll - 1 ) * bmdAudioSampleRate48kHz / m_fps;
327 int actual = m_fifo->used / m_channels + audioCount;
328 int diff = ideal / 2 - actual;
329 count = diff < 0 ? 0 : diff < count ? diff : count;
333 sample_fifo_append( m_fifo, pcm, count * m_channels );
337 // Create video frames while pre-rolling
338 if ( m_isPrerolling )
343 mlt_log_error( &m_consumer, "failed to create video frame\n" );
349 if ( mlt_properties_get_int( MLT_FRAME_PROPERTIES( frame ), "rendered") )
351 mlt_image_format format = mlt_image_yuv422;
355 if ( !mlt_frame_get_image( frame, &image, &format, &m_width, &m_height, 0 ) )
357 m_videoFrame = (IDeckLinkMutableVideoFrame*) mlt_deque_pop_back( m_videoFrameQ );
358 m_videoFrame->GetBytes( (void**) &buffer );
359 if ( m_displayMode->GetFieldDominance() == bmdUpperFieldFirst )
360 // convert lower field first to top field first
361 swab( image, buffer + m_width * 2, m_width * ( m_height - 1 ) * 2 );
363 swab( image, buffer, m_width * m_height * 2 );
364 m_deckLinkOutput->ScheduleVideoFrame( m_videoFrame, m_count * m_duration, m_duration, m_timescale );
365 mlt_deque_push_front( m_videoFrameQ, m_videoFrame );
370 mlt_log_verbose( &m_consumer, "dropped video frame\n" );
374 // Check for end of pre-roll
375 if ( ++m_prerollCounter > m_preroll && m_isPrerolling )
377 // Start audio and video output
378 m_deckLinkOutput->EndAudioPreroll();
379 m_deckLinkOutput->StartScheduledPlayback( 0, m_timescale, 1.0 );
380 m_isPrerolling = false;
386 // *** DeckLink API implementation of IDeckLinkVideoOutputCallback IDeckLinkAudioOutputCallback *** //
388 // IUnknown needs only a dummy implementation
389 virtual HRESULT STDMETHODCALLTYPE QueryInterface( REFIID iid, LPVOID *ppv )
390 { return E_NOINTERFACE; }
391 virtual ULONG STDMETHODCALLTYPE AddRef()
393 virtual ULONG STDMETHODCALLTYPE Release()
396 /************************* DeckLink API Delegate Methods *****************************/
398 virtual HRESULT STDMETHODCALLTYPE ScheduledFrameCompleted( IDeckLinkVideoFrame* completedFrame, BMDOutputFrameCompletionResult completed )
400 // When a video frame has been released by the API, schedule another video frame to be output
406 virtual HRESULT STDMETHODCALLTYPE ScheduledPlaybackHasStopped()
408 return mlt_consumer_is_stopped( &m_consumer ) ? S_FALSE : S_OK;
411 virtual HRESULT STDMETHODCALLTYPE RenderAudioSamples( bool preroll )
413 // Provide more audio samples to the DeckLink API
414 HRESULT result = S_OK;
416 uint32_t count = m_fifo->used / m_channels;
417 uint32_t buffered = count;
420 // Stay under preferred buffer level
421 && ( S_OK == m_deckLinkOutput->GetBufferedAudioSampleFrameCount( &buffered ) )
422 && buffered < m_maxAudioBuffer )
424 uint32_t written = 0;
426 buffered = m_maxAudioBuffer - buffered;
427 count = buffered > count ? count : buffered;
428 result = m_deckLinkOutput->ScheduleAudioSamples( m_fifo->buffer, count, 0, 0, &written );
430 sample_fifo_remove( m_fifo, written * m_channels );
440 static void *run( void *arg )
442 // Map the argument to the object
443 DeckLinkConsumer* decklink = (DeckLinkConsumer*) arg;
444 mlt_consumer consumer = decklink->getConsumer();
446 // Get the properties
447 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
449 // Convenience functionality
450 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
454 mlt_frame frame = NULL;
456 // Loop while running
457 while ( !terminated && mlt_properties_get_int( properties, "running" ) )
460 frame = mlt_consumer_rt_frame( consumer );
462 // Check for termination
463 if ( terminate_on_pause && frame )
464 terminated = mlt_properties_get_double( MLT_FRAME_PROPERTIES( frame ), "_speed" ) == 0.0;
466 // Check that we have a frame to work with
469 decklink->render( frame );
470 if ( !decklink->isBuffering() )
474 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
475 mlt_frame_close( frame );
479 // Indicate that the consumer is stopped
481 mlt_properties_set_int( properties, "running", 0 );
482 mlt_consumer_stopped( consumer );
487 /** Start the consumer.
490 static int start( mlt_consumer consumer )
492 // Get the properties
493 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
494 DeckLinkConsumer* decklink = (DeckLinkConsumer*) consumer->child;
495 int result = decklink->start( mlt_properties_get_int( properties, "preroll" ) ) ? 0 : 1;
497 // Check that we're not already running
498 if ( !result && !mlt_properties_get_int( properties, "running" ) )
501 pthread_t *pthread = (pthread_t*) calloc( 1, sizeof( pthread_t ) );
503 // Assign the thread to properties
504 mlt_properties_set_data( properties, "pthread", pthread, sizeof( pthread_t ), free, NULL );
506 // Set the running state
507 mlt_properties_set_int( properties, "running", 1 );
508 mlt_properties_set_int( properties, "joined", 0 );
511 pthread_create( pthread, NULL, run, consumer->child );
516 /** Stop the consumer.
519 static int stop( mlt_consumer consumer )
521 // Get the properties
522 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
524 // Check that we're running
525 if ( !mlt_properties_get_int( properties, "joined" ) )
528 pthread_t *pthread = (pthread_t*) mlt_properties_get_data( properties, "pthread", NULL );
533 mlt_properties_set_int( properties, "running", 0 );
534 mlt_properties_set_int( properties, "joined", 1 );
536 // Wait for termination
537 pthread_join( *pthread, NULL );
544 /** Determine if the consumer is stopped.
547 static int is_stopped( mlt_consumer consumer )
549 // Get the properties
550 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
551 return !mlt_properties_get_int( properties, "running" );
554 /** Close the consumer.
557 static void close( mlt_consumer consumer )
560 mlt_consumer_stop( consumer );
563 consumer->close = NULL;
564 mlt_consumer_close( consumer );
567 delete (DeckLinkConsumer*) consumer->child;
572 /** Initialise the consumer.
575 mlt_consumer consumer_decklink_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
577 // Allocate the consumer
578 DeckLinkConsumer* decklink = new DeckLinkConsumer();
579 mlt_consumer consumer = NULL;
582 if ( decklink && !mlt_consumer_init( decklink->getConsumer(), decklink, profile ) )
584 // If initialises without error
585 if ( decklink->open( arg? atoi(arg) : 0 ) )
587 consumer = decklink->getConsumer();
590 consumer->close = close;
591 consumer->start = start;
592 consumer->stop = stop;
593 consumer->is_stopped = is_stopped;
604 MLT_REGISTER( consumer_type, "decklink", consumer_decklink_init );