2 * producer_decklink.c -- input from Blackmagic Design DeckLink
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 #include "DeckLinkAPI.h"
29 class DeckLinkProducer
30 : public IDeckLinkInputCallback
33 mlt_producer_s m_producer;
34 IDeckLink* m_decklink;
35 IDeckLinkInput* m_decklinkInput;
37 pthread_mutex_t m_mutex;
38 pthread_cond_t m_condition;
45 BMDDisplayMode getDisplayMode( mlt_profile profile )
47 IDeckLinkDisplayModeIterator* iter;
48 IDeckLinkDisplayMode* mode;
49 BMDDisplayMode result = bmdDisplayModeNotSupported;
51 if ( m_decklinkInput->GetDisplayModeIterator( &iter ) == S_OK )
53 while ( !result && iter->Next( &mode ) == S_OK )
55 int width = mode->GetWidth();
56 int height = mode->GetHeight();
57 BMDTimeValue duration;
58 BMDTimeScale timescale;
59 mode->GetFrameRate( &duration, ×cale );
60 double fps = (double) timescale / duration;
61 int p = mode->GetFieldDominance() == bmdProgressiveFrame;
62 m_topFieldFirst = mode->GetFieldDominance() == bmdUpperFieldFirst;
63 m_colorspace = ( mode->GetFlags() & bmdDisplayModeColorspaceRec709 ) ? 709 : 601;
64 mlt_log_verbose( getProducer(), "BMD mode %dx%d %.3f fps prog %d tff %d\n", width, height, fps, p, m_topFieldFirst );
66 if ( width == profile->width && p == profile->progressive
67 && ( height == profile->height || ( height == 486 && profile->height == 480 ) )
68 && fps == mlt_profile_fps( profile ) )
69 result = mode->GetDisplayMode();
78 mlt_producer getProducer()
79 { return &m_producer; }
83 if ( m_decklinkInput )
84 m_decklinkInput->Release();
86 m_decklink->Release();
90 mlt_deque_close( m_queue );
91 pthread_mutex_destroy( &m_mutex );
92 pthread_cond_destroy( &m_condition );
96 bool open( mlt_profile profile, unsigned card = 0 )
98 IDeckLinkIterator* decklinkIterator = CreateDeckLinkIteratorInstance();
101 if ( !decklinkIterator )
102 throw "The DeckLink drivers are not installed.";
104 // Connect to the Nth DeckLink instance
107 if ( decklinkIterator->Next( &m_decklink ) != S_OK )
108 throw "DeckLink card not found.";
109 } while ( ++i <= card );
110 decklinkIterator->Release();
112 // Get the input interface
113 if ( m_decklink->QueryInterface( IID_IDeckLinkInput, (void**) &m_decklinkInput ) != S_OK )
114 throw "No DeckLink cards support input.";
116 // Provide this class as a delegate to the input callback
117 m_decklinkInput->SetCallback( this );
119 // Initialize other members
120 pthread_mutex_init( &m_mutex, NULL );
121 pthread_cond_init( &m_condition, NULL );
122 m_queue = mlt_deque_init();
125 m_isBuffering = true;
127 catch ( const char *error )
129 if ( decklinkIterator )
130 decklinkIterator->Release();
131 mlt_log_error( getProducer(), "%s\n", error );
137 bool start( mlt_profile profile = 0 )
144 profile = mlt_service_profile( MLT_PRODUCER_SERVICE( getProducer() ) );
146 // Get the display mode
147 BMDDisplayMode displayMode = getDisplayMode( profile );
148 if ( displayMode == bmdDisplayModeNotSupported )
149 throw "Profile is not compatible with decklink.";
151 // Determine if supports input format detection
152 bool doesDetectFormat = false;
153 IDeckLinkAttributes *decklinkAttributes = 0;
154 if ( m_decklink->QueryInterface( IID_IDeckLinkAttributes, (void**) &decklinkAttributes ) == S_OK )
156 if ( decklinkAttributes->GetFlag( BMDDeckLinkSupportsInputFormatDetection, &doesDetectFormat ) != S_OK )
157 doesDetectFormat = false;
158 decklinkAttributes->Release();
160 mlt_log_verbose( getProducer(), "%s format detection\n", doesDetectFormat ? "supports" : "does not support" );
162 // Enable video capture
163 BMDPixelFormat pixelFormat = bmdFormat8BitYUV;
164 BMDVideoInputFlags flags = doesDetectFormat ? bmdVideoInputEnableFormatDetection : bmdVideoInputFlagDefault;
165 if ( S_OK != m_decklinkInput->EnableVideoInput( displayMode, pixelFormat, flags ) )
166 throw "Failed to enable video capture.";
168 // Enable audio capture
169 BMDAudioSampleRate sampleRate = bmdAudioSampleRate48kHz;
170 BMDAudioSampleType sampleType = bmdAudioSampleType16bitInteger;
171 int channels = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "channels" );
172 if ( S_OK != m_decklinkInput->EnableAudioInput( sampleRate, sampleType, channels ) )
173 throw "Failed to enable audio capture.";
177 mlt_properties_set_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "dropped", m_dropped );
178 m_started = m_decklinkInput->StartStreams() == S_OK;
180 throw "Failed to start capture.";
182 catch ( const char *error )
184 m_decklinkInput->DisableVideoInput();
185 mlt_log_error( getProducer(), "%s\n", error );
196 // Release the wait in getFrame
197 pthread_mutex_lock( &m_mutex );
198 pthread_cond_broadcast( &m_condition );
199 pthread_mutex_unlock( &m_mutex );
201 m_decklinkInput->StopStreams();
204 pthread_mutex_lock( &m_mutex );
205 while ( mlt_frame frame = (mlt_frame) mlt_deque_pop_back( m_queue ) )
206 mlt_frame_close( frame );
207 pthread_mutex_unlock( &m_mutex );
214 mlt_frame frame = NULL;
217 double fps = mlt_producer_get_fps( getProducer() );
219 // Allow the buffer to fill to the requested initial buffer level.
222 int prefill = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "prefill" );
223 int buffer = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "buffer" );
225 m_isBuffering = false;
226 prefill = prefill > buffer ? buffer : prefill;
227 pthread_mutex_lock( &m_mutex );
228 while ( mlt_deque_count( m_queue ) < prefill )
230 // Wait up to buffer/fps seconds
231 gettimeofday( &now, NULL );
232 long usec = now.tv_sec * 1000000 + now.tv_usec;
233 usec += 1000000 * buffer / fps;
234 tm.tv_sec = usec / 1000000;
235 tm.tv_nsec = (usec % 1000000) * 1000;
236 if ( pthread_cond_timedwait( &m_condition, &m_mutex, &tm ) )
239 pthread_mutex_unlock( &m_mutex );
242 // Wait if queue is empty
243 pthread_mutex_lock( &m_mutex );
244 while ( mlt_deque_count( m_queue ) < 1 )
246 // Wait up to twice frame duration
247 gettimeofday( &now, NULL );
248 long usec = now.tv_sec * 1000000 + now.tv_usec;
249 usec += 2000000 / fps;
250 tm.tv_sec = usec / 1000000;
251 tm.tv_nsec = (usec % 1000000) * 1000;
252 if ( pthread_cond_timedwait( &m_condition, &m_mutex, &tm ) )
253 // Stop waiting if error (timed out)
257 // Get the first frame from the queue
258 frame = ( mlt_frame ) mlt_deque_pop_front( m_queue );
259 pthread_mutex_unlock( &m_mutex );
261 // Set frame timestamp and properties
264 mlt_profile profile = mlt_service_profile( MLT_PRODUCER_SERVICE( getProducer() ) );
265 mlt_properties properties = MLT_FRAME_PROPERTIES( frame );
266 mlt_properties_set_int( properties, "progressive", profile->progressive );
267 mlt_properties_set_int( properties, "meta.media.progressive", profile->progressive );
268 mlt_properties_set_int( properties, "top_field_first", m_topFieldFirst );
269 mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
270 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", profile->sample_aspect_num );
271 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", profile->sample_aspect_den );
272 mlt_properties_set_int( properties, "meta.media.frame_rate_num", profile->frame_rate_num );
273 mlt_properties_set_int( properties, "meta.media.frame_rate_den", profile->frame_rate_den );
274 mlt_properties_set_int( properties, "width", profile->width );
275 mlt_properties_set_int( properties, "real_width", profile->width );
276 mlt_properties_set_int( properties, "meta.media.width", profile->width );
277 mlt_properties_set_int( properties, "height", profile->height );
278 mlt_properties_set_int( properties, "real_height", profile->height );
279 mlt_properties_set_int( properties, "meta.media.height", profile->height );
280 mlt_properties_set_int( properties, "format", mlt_image_yuv422 );
281 mlt_properties_set_int( properties, "colorspace", m_colorspace );
282 mlt_properties_set_int( properties, "meta.media.colorspace", m_colorspace );
283 mlt_properties_set_int( properties, "audio_frequency", 48000 );
284 mlt_properties_set_int( properties, "audio_channels",
285 mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "channels" ) );
290 // *** DeckLink API implementation of IDeckLinkInputCallback *** //
292 // IUnknown needs only a dummy implementation
293 virtual HRESULT STDMETHODCALLTYPE QueryInterface( REFIID iid, LPVOID *ppv )
294 { return E_NOINTERFACE; }
295 virtual ULONG STDMETHODCALLTYPE AddRef()
297 virtual ULONG STDMETHODCALLTYPE Release()
300 /************************* DeckLink API Delegate Methods *****************************/
302 virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(
303 IDeckLinkVideoInputFrame* video,
304 IDeckLinkAudioInputPacket* audio )
307 mlt_frame frame = mlt_frame_init( MLT_PRODUCER_SERVICE( getProducer() ) );
312 if ( !( video->GetFlags() & bmdFrameHasNoInputSource ) )
314 int size = video->GetRowBytes() * video->GetHeight();
315 void* image = mlt_pool_alloc( size );
318 video->GetBytes( &buffer );
319 if ( image && buffer )
321 swab( buffer, image, size );
322 mlt_frame_set_image( frame, (uint8_t*) image, size, mlt_pool_release );
326 mlt_log_verbose( getProducer(), "no video\n" );
327 mlt_pool_release( image );
332 mlt_log_verbose( getProducer(), "no signal\n" );
333 mlt_frame_close( frame );
339 mlt_log_verbose( getProducer(), "no video\n" );
340 mlt_frame_close( frame );
345 if ( frame && audio )
347 int channels = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "channels" );
348 int size = audio->GetSampleFrameCount() * channels * sizeof(int16_t);
349 mlt_audio_format format = mlt_audio_s16;
350 void* pcm = mlt_pool_alloc( size );
353 audio->GetBytes( &buffer );
356 memcpy( pcm, buffer, size );
357 mlt_frame_set_audio( frame, pcm, format, size, mlt_pool_release );
358 mlt_properties_set_int( MLT_FRAME_PROPERTIES(frame), "audio_samples", audio->GetSampleFrameCount() );
362 mlt_log_verbose( getProducer(), "no audio\n" );
363 mlt_pool_release( pcm );
368 mlt_log_verbose( getProducer(), "no audio\n" );
371 // Put frame in queue
374 int queueMax = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "buffer" );
375 pthread_mutex_lock( &m_mutex );
376 if ( mlt_deque_count( m_queue ) < queueMax )
378 mlt_deque_push_back( m_queue, frame );
379 pthread_cond_broadcast( &m_condition );
383 mlt_frame_close( frame );
384 mlt_properties_set_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "dropped", ++m_dropped );
385 mlt_log_warning( getProducer(), "frame dropped %d\n", m_dropped );
387 pthread_mutex_unlock( &m_mutex );
393 virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(
394 BMDVideoInputFormatChangedEvents events,
395 IDeckLinkDisplayMode* mode,
396 BMDDetectedVideoInputFormatFlags flags )
398 mlt_profile profile = mlt_service_profile( MLT_PRODUCER_SERVICE( getProducer() ) );
399 if ( events & bmdVideoInputDisplayModeChanged )
401 BMDTimeValue duration;
402 BMDTimeScale timescale;
403 mode->GetFrameRate( &duration, ×cale );
404 profile->width = mode->GetWidth();
405 profile->height = mode->GetHeight();
406 profile->height = profile->height == 486 ? 480 : profile->height;
407 profile->frame_rate_num = timescale;
408 profile->frame_rate_den = duration;
409 if ( profile->width == 720 )
411 if ( profile->height == 576 )
413 profile->sample_aspect_num = 16;
414 profile->sample_aspect_den = 15;
418 profile->sample_aspect_num = 8;
419 profile->sample_aspect_den = 9;
421 profile->display_aspect_num = 4;
422 profile->display_aspect_den = 3;
426 profile->sample_aspect_num = 1;
427 profile->sample_aspect_den = 1;
428 profile->display_aspect_num = 16;
429 profile->display_aspect_den = 9;
431 free( profile->description );
432 profile->description = strdup( "decklink" );
433 mlt_log_verbose( getProducer(), "format changed %dx%d %.3f fps\n",
434 profile->width, profile->height, (double) profile->frame_rate_num / profile->frame_rate_den );
436 if ( events & bmdVideoInputFieldDominanceChanged )
438 profile->progressive = mode->GetFieldDominance() == bmdProgressiveFrame;
439 m_topFieldFirst = mode->GetFieldDominance() == bmdUpperFieldFirst;
440 mlt_log_verbose( getProducer(), "field dominance changed prog %d tff %d\n",
441 profile->progressive, m_topFieldFirst );
443 if ( events & bmdVideoInputColorspaceChanged )
445 profile->colorspace = m_colorspace =
446 ( mode->GetFlags() & bmdDisplayModeColorspaceRec709 ) ? 709 : 601;
447 mlt_log_verbose( getProducer(), "colorspace changed %d\n", profile->colorspace );
453 static int get_audio( mlt_frame frame, int16_t **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
455 return mlt_frame_get_audio( frame, (void**) buffer, format, frequency, channels, samples );
458 static int get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
460 return mlt_frame_get_image( frame, buffer, format, width, height, writable );
463 static int get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
465 DeckLinkProducer* decklink = (DeckLinkProducer*) producer->child;
467 // Get the next frame from the decklink object
468 *frame = decklink->getFrame();
470 *frame = mlt_frame_init( MLT_PRODUCER_SERVICE( producer ) );
472 // Calculate the next timecode
473 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
474 mlt_producer_prepare_next( producer );
476 // Add audio and video getters
477 mlt_frame_push_audio( *frame, (void*) get_audio );
478 mlt_frame_push_get_image( *frame, get_image );
483 static void producer_close( mlt_producer producer )
485 producer->close = NULL;
486 mlt_producer_close( producer );
487 delete (DeckLinkProducer*) producer->child;
492 /** Initialise the producer.
495 mlt_producer producer_decklink_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
497 // Allocate the producer
498 DeckLinkProducer* decklink = new DeckLinkProducer();
499 mlt_producer producer = NULL;
501 // If allocated and initializes
502 if ( decklink && !mlt_producer_init( decklink->getProducer(), decklink ) )
504 if ( decklink->open( profile, arg? atoi( arg ) : 0 ) )
506 producer = decklink->getProducer();
507 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
510 producer->close = (mlt_destructor) producer_close;
511 producer->get_frame = get_frame;
514 mlt_properties_set( properties, "resource", arg? arg : "0" );
515 mlt_properties_set_int( properties, "channels", 2 );
516 mlt_properties_set_int( properties, "buffer", 25 );
517 mlt_properties_set_int( properties, "prefill", 25 );
519 // These properties effectively make it infinite.
520 mlt_properties_set_int( properties, "length", INT_MAX );
521 mlt_properties_set_int( properties, "out", INT_MAX - 1 );
522 mlt_properties_set( properties, "eof", "loop" );
525 if ( !decklink->start( profile ) )
527 producer_close( producer );