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_CUTOFF = 2;
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 uint32_t m_maxAudioBuffer;
98 unsigned m_prerollCount;
100 IDeckLinkDisplayMode* getDisplayMode()
102 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( &m_consumer ) );
103 IDeckLinkDisplayModeIterator* iter;
104 IDeckLinkDisplayMode* mode;
105 IDeckLinkDisplayMode* result = 0;
107 if ( m_deckLinkOutput->GetDisplayModeIterator( &iter ) == S_OK )
109 while ( !result && iter->Next( &mode ) == S_OK )
111 m_width = mode->GetWidth();
112 m_height = mode->GetHeight();
113 mode->GetFrameRate( &m_duration, &m_timescale );
114 m_fps = (double) m_timescale / m_duration;
115 int p = mode->GetFieldDominance() == bmdProgressiveFrame;
116 fprintf(stderr, "BMD mode %dx%d %.3f fps prog %d\n", m_width, m_height, m_fps, p );
118 if ( m_width == profile->width && m_height == profile->height && p == profile->progressive
119 && m_fps == mlt_profile_fps( profile ) )
128 mlt_consumer getConsumer()
129 { return &m_consumer; }
130 uint64_t isPreroll() const
131 { return m_prerollCount <= PREROLL_CUTOFF; }
135 if ( m_deckLinkOutput )
136 m_deckLinkOutput->Release();
138 m_deckLink->Release();
141 bool open( unsigned card = 0 )
143 IDeckLinkIterator* deckLinkIterator = CreateDeckLinkIteratorInstance();
146 if ( !deckLinkIterator )
148 mlt_log_verbose( NULL, "The DeckLink drivers not installed.\n" );
152 // Connect to the Nth DeckLink instance
154 if ( deckLinkIterator->Next( &m_deckLink ) != S_OK )
156 mlt_log_verbose( NULL, "DeckLink card not found\n" );
157 deckLinkIterator->Release();
160 } while ( ++i <= card );
162 // Obtain the audio/video output interface (IDeckLinkOutput)
163 if ( m_deckLink->QueryInterface( IID_IDeckLinkOutput, (void**)&m_deckLinkOutput ) != S_OK )
165 mlt_log_verbose( NULL, "No DeckLink cards support output\n" );
166 m_deckLink->Release();
168 deckLinkIterator->Release();
172 // Provide this class as a delegate to the audio and video output interfaces
173 m_deckLinkOutput->SetScheduledFrameCompletionCallback( this );
174 m_deckLinkOutput->SetAudioCallback( this );
176 pthread_mutex_init( &m_mutex, NULL );
177 pthread_cond_init( &m_condition, NULL );
178 m_maxAudioBuffer = bmdAudioSampleRate48kHz;
185 m_displayMode = getDisplayMode();
187 // Set the video output mode
188 if ( S_OK != m_deckLinkOutput->EnableVideoOutput( m_displayMode->GetDisplayMode(), bmdVideoOutputFlagDefault) )
190 mlt_log_verbose( &m_consumer, "Failed to enable video output\n" );
194 // Generate a DeckLink video frame
195 if ( S_OK != m_deckLinkOutput->CreateVideoFrame( m_width, m_height,
196 m_width * 2, bmdFormat8BitYUV, bmdFrameFlagDefault, &m_videoFrame ) )
198 mlt_log_verbose( &m_consumer, "Failed to create video frame\n" );
203 // Make the first line black for field order correction.
205 if ( S_OK == m_videoFrame->GetBytes( (void**) &buffer ) && buffer )
207 for ( int i = 0; i < m_width; i++ )
214 // Set the audio output mode
216 if ( S_OK != m_deckLinkOutput->EnableAudioOutput( bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger,
217 m_channels, bmdAudioOutputStreamContinuous ) )
219 mlt_log_verbose( &m_consumer, "Failed to enable audio output\n" );
223 m_fifo = sample_fifo_init();
229 m_deckLinkOutput->BeginAudioPreroll();
234 pthread_mutex_lock( &m_mutex );
235 pthread_cond_broadcast( &m_condition );
236 pthread_mutex_unlock( &m_mutex );
241 pthread_mutex_lock( &m_mutex );
242 pthread_cond_wait( &m_condition, &m_mutex );
243 pthread_mutex_unlock( &m_mutex );
248 // Stop the audio and video output streams immediately
249 if ( m_deckLinkOutput )
251 m_deckLinkOutput->StopScheduledPlayback( 0, 0, 0 );
252 m_deckLinkOutput->DisableAudioOutput();
253 m_deckLinkOutput->DisableVideoOutput();
255 if ( m_videoFrame ) m_videoFrame->Release();
257 if ( m_fifo ) sample_fifo_close( m_fifo );
260 HRESULT render( mlt_frame frame )
262 HRESULT result = S_OK;
265 double speed = mlt_properties_get_double( MLT_FRAME_PROPERTIES(frame), "_speed" );
268 mlt_audio_format format = mlt_audio_s16;
269 int frequency = bmdAudioSampleRate48kHz;
270 int samples = mlt_sample_calculator( m_fps, frequency, m_count );
273 if ( !mlt_frame_get_audio( frame, (void**) &pcm, &format, &frequency, &m_channels, &samples ) )
279 uint32_t audioCount = 0;
280 uint32_t videoCount = 0;
283 m_deckLinkOutput->GetBufferedAudioSampleFrameCount( &audioCount );
284 m_deckLinkOutput->GetBufferedVideoFrameCount( &videoCount );
285 mlt_log_debug( &m_consumer, "audio buf %u video buf %u frames\n", audioCount, videoCount );
287 // Underflow typically occurs during non-normal speed playback.
288 if ( audioCount < 1 || videoCount < 1 )
289 // Upon switching to normal playback, buffer some frames faster than realtime.
293 if ( m_prerollCount <= PREROLL_CUTOFF )
295 // Only append audio to reach the ideal level and not overbuffer.
296 int ideal = ( PREROLL_CUTOFF - 1 ) * bmdAudioSampleRate48kHz / m_fps;
297 int actual = m_fifo->used / m_channels + audioCount;
298 int diff = ideal / 2 - actual;
299 count = diff < 0 ? 0 : diff < count ? diff : count;
303 sample_fifo_append( m_fifo, pcm, count * m_channels );
307 if ( mlt_properties_get_int( MLT_FRAME_PROPERTIES( frame ), "rendered") )
309 mlt_image_format format = mlt_image_yuv422;
313 if ( !mlt_frame_get_image( frame, &image, &format, &m_width, &m_height, 0 ) )
315 m_videoFrame->GetBytes( (void**) &buffer );
316 if ( m_displayMode->GetFieldDominance() == bmdUpperFieldFirst )
317 // convert lower field first to top field first
318 swab( image, buffer + m_width * 2, m_width * ( m_height - 1 ) * 2 );
320 swab( image, buffer, m_width * m_height * 2 );
321 result = m_deckLinkOutput->ScheduleVideoFrame( m_videoFrame, m_count * m_duration, m_duration, m_timescale );
327 if ( ++m_prerollCount > PREROLL_CUTOFF && m_preroll )
329 // Start audio and video output
330 m_deckLinkOutput->EndAudioPreroll();
331 m_deckLinkOutput->StartScheduledPlayback( 0, m_timescale, 1.0 );
338 // *** DeckLink API implementation of IDeckLinkVideoOutputCallback IDeckLinkAudioOutputCallback *** //
340 // IUnknown needs only a dummy implementation
341 virtual HRESULT STDMETHODCALLTYPE QueryInterface( REFIID iid, LPVOID *ppv )
342 { return E_NOINTERFACE; }
343 virtual ULONG STDMETHODCALLTYPE AddRef()
345 virtual ULONG STDMETHODCALLTYPE Release()
348 /************************* DeckLink API Delegate Methods *****************************/
350 virtual HRESULT STDMETHODCALLTYPE ScheduledFrameCompleted( IDeckLinkVideoFrame* completedFrame, BMDOutputFrameCompletionResult completed )
352 // When a video frame has been released by the API, schedule another video frame to be output
358 virtual HRESULT STDMETHODCALLTYPE ScheduledPlaybackHasStopped()
360 return mlt_consumer_is_stopped( &m_consumer ) ? S_FALSE : S_OK;
363 virtual HRESULT STDMETHODCALLTYPE RenderAudioSamples( bool preroll )
365 // Provide more audio samples to the DeckLink API
366 HRESULT result = S_OK;
368 uint32_t count = m_fifo->used / m_channels;
369 uint32_t buffered = count;
372 // Stay under preferred buffer level
373 && ( S_OK == m_deckLinkOutput->GetBufferedAudioSampleFrameCount( &buffered ) )
374 && buffered < m_maxAudioBuffer )
376 uint32_t written = 0;
378 buffered = m_maxAudioBuffer - buffered;
379 count = buffered > count ? count : buffered;
381 result = m_deckLinkOutput->ScheduleAudioSamples( m_fifo->buffer, count, 0, 0, &written );
383 sample_fifo_remove( m_fifo, written * m_channels );
393 static void *run( void *arg )
395 // Map the argument to the object
396 DeckLinkConsumer* decklink = (DeckLinkConsumer*) arg;
397 mlt_consumer consumer = decklink->getConsumer();
399 // Get the properties
400 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
402 // Convenience functionality
403 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
407 mlt_frame frame = NULL;
411 // Loop while running
412 while ( !terminated && mlt_properties_get_int( properties, "running" ) )
415 frame = mlt_consumer_rt_frame( consumer );
417 // Check for termination
418 if ( terminate_on_pause && frame )
419 terminated = mlt_properties_get_double( MLT_FRAME_PROPERTIES( frame ), "_speed" ) == 0.0;
421 // Check that we have a frame to work with
424 decklink->render( frame );
425 if ( !decklink->isPreroll() )
429 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
430 mlt_frame_close( frame );
434 // Indicate that the consumer is stopped
435 mlt_properties_set_int( properties, "running", 0 );
436 mlt_consumer_stopped( consumer );
441 /** Start the consumer.
444 static int start( mlt_consumer consumer )
446 // Get the properties
447 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
449 // Check that we're not already running
450 if ( !mlt_properties_get_int( properties, "running" ) )
453 pthread_t *pthread = (pthread_t*) calloc( 1, sizeof( pthread_t ) );
455 // Assign the thread to properties
456 mlt_properties_set_data( properties, "pthread", pthread, sizeof( pthread_t ), free, NULL );
458 // Set the running state
459 mlt_properties_set_int( properties, "running", 1 );
460 mlt_properties_set_int( properties, "joined", 0 );
463 pthread_create( pthread, NULL, run, consumer->child );
468 /** Stop the consumer.
471 static int stop( mlt_consumer consumer )
473 // Get the properties
474 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
476 // Check that we're running
477 if ( !mlt_properties_get_int( properties, "joined" ) )
480 pthread_t *pthread = (pthread_t*) mlt_properties_get_data( properties, "pthread", NULL );
485 mlt_properties_set_int( properties, "running", 0 );
486 mlt_properties_set_int( properties, "joined", 1 );
488 // Wait for termination
489 pthread_join( *pthread, NULL );
496 /** Determine if the consumer is stopped.
499 static int is_stopped( mlt_consumer consumer )
501 // Get the properties
502 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
503 return !mlt_properties_get_int( properties, "running" );
506 /** Close the consumer.
509 static void close( mlt_consumer consumer )
512 mlt_consumer_stop( consumer );
515 consumer->close = NULL;
516 mlt_consumer_close( consumer );
519 delete (DeckLinkConsumer*) consumer->child;
524 /** Initialise the consumer.
527 mlt_consumer consumer_decklink_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
529 // Allocate the consumer
530 DeckLinkConsumer* decklink = new DeckLinkConsumer();
531 mlt_consumer consumer = NULL;
534 if ( decklink && !mlt_consumer_init( decklink->getConsumer(), decklink, profile ) )
536 // If initialises without error
537 if ( decklink->open( arg? atoi(arg) : 0 ) )
539 consumer = decklink->getConsumer();
542 consumer->close = close;
543 consumer->start = start;
544 consumer->stop = stop;
545 consumer->is_stopped = is_stopped;
556 MLT_REGISTER( consumer_type, "decklink", consumer_decklink_init );