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>
29 #include "DeckLinkAPI_h.h"
31 #include "DeckLinkAPI.h"
32 typedef const char* BSTR;
35 #define SAFE_RELEASE(V) if (V) { V->Release(); V = NULL; }
37 class DeckLinkProducer
38 : public IDeckLinkInputCallback
41 mlt_producer m_producer;
42 IDeckLink* m_decklink;
43 IDeckLinkInput* m_decklinkInput;
45 pthread_mutex_t m_mutex;
46 pthread_cond_t m_condition;
55 BMDDisplayMode getDisplayMode( mlt_profile profile, int vancLines )
57 IDeckLinkDisplayModeIterator* iter = NULL;
58 IDeckLinkDisplayMode* mode = NULL;
59 BMDDisplayMode result = (BMDDisplayMode) bmdDisplayModeNotSupported;
61 if ( m_decklinkInput->GetDisplayModeIterator( &iter ) == S_OK )
63 while ( !result && iter->Next( &mode ) == S_OK )
65 int width = mode->GetWidth();
66 int height = mode->GetHeight();
67 BMDTimeValue duration;
68 BMDTimeScale timescale;
69 mode->GetFrameRate( &duration, ×cale );
70 double fps = (double) timescale / duration;
71 int p = mode->GetFieldDominance() == bmdProgressiveFrame;
72 m_topFieldFirst = mode->GetFieldDominance() == bmdUpperFieldFirst;
73 m_colorspace = ( mode->GetFlags() & bmdDisplayModeColorspaceRec709 ) ? 709 : 601;
74 mlt_log_verbose( getProducer(), "BMD mode %dx%d %.3f fps prog %d tff %d\n", width, height, fps, p, m_topFieldFirst );
76 if ( width == profile->width && p == profile->progressive
77 && ( height + vancLines == profile->height || ( height == 486 && profile->height == 480 + vancLines ) )
78 && fps == mlt_profile_fps( profile ) )
79 result = mode->GetDisplayMode();
90 void setProducer( mlt_producer producer )
91 { m_producer = producer; }
93 mlt_producer getProducer() const
94 { return m_producer; }
99 m_decklinkInput = NULL;
107 mlt_deque_close( m_queue );
108 pthread_mutex_destroy( &m_mutex );
109 pthread_cond_destroy( &m_condition );
110 mlt_cache_close( m_cache );
112 SAFE_RELEASE( m_decklinkInput );
113 SAFE_RELEASE( m_decklink );
116 bool open( unsigned card = 0 )
118 IDeckLinkIterator* decklinkIterator = NULL;
122 HRESULT result = CoInitialize( NULL );
123 if ( FAILED( result ) )
124 throw "COM initialization failed";
125 result = CoCreateInstance( CLSID_CDeckLinkIterator, NULL, CLSCTX_ALL, IID_IDeckLinkIterator, (void**) &decklinkIterator );
126 if ( FAILED( result ) )
127 throw "The DeckLink drivers are not installed.";
129 decklinkIterator = CreateDeckLinkIteratorInstance();
130 if ( !decklinkIterator )
131 throw "The DeckLink drivers are not installed.";
133 // Connect to the Nth DeckLink instance
134 for ( unsigned i = 0; decklinkIterator->Next( &m_decklink ) == S_OK ; i++)
139 SAFE_RELEASE( m_decklink );
141 SAFE_RELEASE( decklinkIterator );
143 throw "DeckLink card not found.";
145 // Get the input interface
146 if ( m_decklink->QueryInterface( IID_IDeckLinkInput, (void**) &m_decklinkInput ) != S_OK )
147 throw "No DeckLink cards support input.";
149 // Provide this class as a delegate to the input callback
150 m_decklinkInput->SetCallback( this );
152 // Initialize other members
153 pthread_mutex_init( &m_mutex, NULL );
154 pthread_cond_init( &m_condition, NULL );
155 m_queue = mlt_deque_init();
158 m_isBuffering = true;
159 m_cache = mlt_cache_init();
161 // 3 covers YADIF and increasing framerate use cases
162 mlt_cache_set_size( m_cache, 3 );
164 catch ( const char *error )
166 SAFE_RELEASE( m_decklinkInput );
167 SAFE_RELEASE( m_decklink );
168 mlt_log_error( getProducer(), "%s\n", error );
174 bool start( mlt_profile profile = 0 )
180 // Initialize some members
181 m_vancLines = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "vanc" );
182 if ( m_vancLines == -1 )
183 m_vancLines = profile->height <= 512 ? 26 : 32;
186 profile = mlt_service_profile( MLT_PRODUCER_SERVICE( getProducer() ) );
188 // Get the display mode
189 BMDDisplayMode displayMode = getDisplayMode( profile, m_vancLines );
190 if ( displayMode == (BMDDisplayMode) bmdDisplayModeNotSupported )
192 mlt_log_info( getProducer(), "profile = %dx%d %f fps %s\n", profile->width, profile->height,
193 mlt_profile_fps( profile ), profile->progressive? "progressive" : "interlace" );
194 throw "Profile is not compatible with decklink.";
197 // Determine if supports input format detection
199 BOOL doesDetectFormat = FALSE;
201 bool doesDetectFormat = false;
203 IDeckLinkAttributes *decklinkAttributes = 0;
204 if ( m_decklink->QueryInterface( IID_IDeckLinkAttributes, (void**) &decklinkAttributes ) == S_OK )
206 if ( decklinkAttributes->GetFlag( BMDDeckLinkSupportsInputFormatDetection, &doesDetectFormat ) != S_OK )
207 doesDetectFormat = false;
208 SAFE_RELEASE( decklinkAttributes );
210 mlt_log_verbose( getProducer(), "%s format detection\n", doesDetectFormat ? "supports" : "does not support" );
212 // Enable video capture
213 BMDPixelFormat pixelFormat = bmdFormat8BitYUV;
214 BMDVideoInputFlags flags = doesDetectFormat ? bmdVideoInputEnableFormatDetection : bmdVideoInputFlagDefault;
215 if ( S_OK != m_decklinkInput->EnableVideoInput( displayMode, pixelFormat, flags ) )
216 throw "Failed to enable video capture.";
218 // Enable audio capture
219 BMDAudioSampleRate sampleRate = bmdAudioSampleRate48kHz;
220 BMDAudioSampleType sampleType = bmdAudioSampleType16bitInteger;
221 int channels = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "channels" );
222 if ( S_OK != m_decklinkInput->EnableAudioInput( sampleRate, sampleType, channels ) )
223 throw "Failed to enable audio capture.";
227 mlt_properties_set_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "dropped", m_dropped );
228 m_started = m_decklinkInput->StartStreams() == S_OK;
230 throw "Failed to start capture.";
232 catch ( const char *error )
234 m_decklinkInput->DisableVideoInput();
235 mlt_log_error( getProducer(), "%s\n", error );
247 // Release the wait in getFrame
248 pthread_mutex_lock( &m_mutex );
249 pthread_cond_broadcast( &m_condition );
250 pthread_mutex_unlock( &m_mutex );
252 m_decklinkInput->StopStreams();
255 pthread_mutex_lock( &m_mutex );
256 while ( mlt_frame frame = (mlt_frame) mlt_deque_pop_back( m_queue ) )
257 mlt_frame_close( frame );
258 pthread_mutex_unlock( &m_mutex );
263 mlt_frame frame = NULL;
266 double fps = mlt_producer_get_fps( getProducer() );
267 mlt_position position = mlt_producer_position( getProducer() );
268 mlt_cache_item cached = mlt_cache_get( m_cache, (void*) position );
270 // Allow the buffer to fill to the requested initial buffer level.
273 int prefill = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "prefill" );
274 int buffer = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "buffer" );
276 m_isBuffering = false;
277 prefill = prefill > buffer ? buffer : prefill;
278 pthread_mutex_lock( &m_mutex );
279 while ( mlt_deque_count( m_queue ) < prefill )
281 // Wait up to buffer/fps seconds
282 gettimeofday( &now, NULL );
283 long usec = now.tv_sec * 1000000 + now.tv_usec;
284 usec += 1000000 * buffer / fps;
285 tm.tv_sec = usec / 1000000;
286 tm.tv_nsec = (usec % 1000000) * 1000;
287 if ( pthread_cond_timedwait( &m_condition, &m_mutex, &tm ) )
290 pthread_mutex_unlock( &m_mutex );
295 // Copy cached frame instead of pulling from queue
296 frame = mlt_frame_clone( (mlt_frame) mlt_cache_item_data( cached, NULL ), 0 );
297 mlt_cache_item_close( cached );
301 // Wait if queue is empty
302 pthread_mutex_lock( &m_mutex );
303 while ( mlt_deque_count( m_queue ) < 1 )
305 // Wait up to twice frame duration
306 gettimeofday( &now, NULL );
307 long usec = now.tv_sec * 1000000 + now.tv_usec;
308 usec += 2000000 / fps;
309 tm.tv_sec = usec / 1000000;
310 tm.tv_nsec = (usec % 1000000) * 1000;
311 if ( pthread_cond_timedwait( &m_condition, &m_mutex, &tm ) )
312 // Stop waiting if error (timed out)
315 frame = ( mlt_frame ) mlt_deque_pop_front( m_queue );
316 pthread_mutex_unlock( &m_mutex );
320 mlt_cache_put( m_cache, (void*) position, mlt_frame_clone( frame, 1 ), 0,
321 (mlt_destructor) mlt_frame_close );
324 // Set frame timestamp and properties
327 mlt_profile profile = mlt_service_profile( MLT_PRODUCER_SERVICE( getProducer() ) );
328 mlt_properties properties = MLT_FRAME_PROPERTIES( frame );
329 mlt_properties_set_int( properties, "progressive", profile->progressive );
330 mlt_properties_set_int( properties, "meta.media.progressive", profile->progressive );
331 mlt_properties_set_int( properties, "top_field_first", m_topFieldFirst );
332 mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
333 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", profile->sample_aspect_num );
334 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", profile->sample_aspect_den );
335 mlt_properties_set_int( properties, "meta.media.frame_rate_num", profile->frame_rate_num );
336 mlt_properties_set_int( properties, "meta.media.frame_rate_den", profile->frame_rate_den );
337 mlt_properties_set_int( properties, "width", profile->width );
338 mlt_properties_set_int( properties, "meta.media.width", profile->width );
339 mlt_properties_set_int( properties, "height", profile->height );
340 mlt_properties_set_int( properties, "meta.media.height", profile->height );
341 mlt_properties_set_int( properties, "format", mlt_image_yuv422 );
342 mlt_properties_set_int( properties, "colorspace", m_colorspace );
343 mlt_properties_set_int( properties, "meta.media.colorspace", m_colorspace );
344 mlt_properties_set_int( properties, "audio_frequency", 48000 );
345 mlt_properties_set_int( properties, "audio_channels",
346 mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "channels" ) );
349 mlt_log_warning( getProducer(), "buffer underrun\n" );
354 // *** DeckLink API implementation of IDeckLinkInputCallback *** //
356 // IUnknown needs only a dummy implementation
357 virtual HRESULT STDMETHODCALLTYPE QueryInterface( REFIID iid, LPVOID *ppv )
358 { return E_NOINTERFACE; }
359 virtual ULONG STDMETHODCALLTYPE AddRef()
361 virtual ULONG STDMETHODCALLTYPE Release()
364 /************************* DeckLink API Delegate Methods *****************************/
366 virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(
367 IDeckLinkVideoInputFrame* video,
368 IDeckLinkAudioInputPacket* audio )
370 if ( mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "preview" ) &&
371 mlt_producer_get_speed( getProducer() ) == 0.0 && !mlt_deque_count( m_queue ))
373 pthread_cond_broadcast( &m_condition );
378 mlt_frame frame = mlt_frame_init( MLT_PRODUCER_SERVICE( getProducer() ) );
383 if ( !( video->GetFlags() & bmdFrameHasNoInputSource ) )
385 int size = video->GetRowBytes() * ( video->GetHeight() + m_vancLines );
386 void* image = mlt_pool_alloc( size );
388 unsigned char* p = (unsigned char*) image;
391 // Initialize VANC lines to nominal black
399 if ( m_vancLines > 0 )
401 IDeckLinkVideoFrameAncillary* vanc = 0;
402 if ( video->GetAncillaryData( &vanc ) == S_OK && vanc )
404 for ( int i = 1; i < m_vancLines + 1; i++ )
406 if ( vanc->GetBufferForVerticalBlankingLine( i, &buffer ) == S_OK )
407 swab( (char*) buffer, (char*) image + ( i - 1 ) * video->GetRowBytes(), video->GetRowBytes() );
409 mlt_log_debug( getProducer(), "failed capture vanc line %d\n", i );
416 video->GetBytes( &buffer );
417 if ( image && buffer )
419 size = video->GetRowBytes() * video->GetHeight();
420 swab( (char*) buffer, (char*) image + m_vancLines * video->GetRowBytes(), size );
421 mlt_frame_set_image( frame, (uint8_t*) image, size, mlt_pool_release );
425 mlt_log_verbose( getProducer(), "no video\n" );
426 mlt_pool_release( image );
431 mlt_log_verbose( getProducer(), "no signal\n" );
432 mlt_frame_close( frame );
437 IDeckLinkTimecode* timecode = 0;
438 if ( video->GetTimecode( bmdTimecodeVITC, &timecode ) == S_OK && timecode )
440 const char* timecodeString = 0;
442 if ( timecode->GetString( (BSTR*) &timecodeString ) == S_OK )
444 mlt_properties_set( MLT_FRAME_PROPERTIES( frame ), "meta.attr.vitc.markup", timecodeString );
445 mlt_log_debug( getProducer(), "timecode %s\n", timecodeString );
447 if ( timecodeString )
448 free( (void*) timecodeString );
449 SAFE_RELEASE( timecode );
454 mlt_log_verbose( getProducer(), "no video\n" );
455 mlt_frame_close( frame );
460 if ( frame && audio )
462 int channels = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "channels" );
463 int size = audio->GetSampleFrameCount() * channels * sizeof(int16_t);
464 mlt_audio_format format = mlt_audio_s16;
465 void* pcm = mlt_pool_alloc( size );
468 audio->GetBytes( &buffer );
471 memcpy( pcm, buffer, size );
472 mlt_frame_set_audio( frame, pcm, format, size, mlt_pool_release );
473 mlt_properties_set_int( MLT_FRAME_PROPERTIES(frame), "audio_samples", audio->GetSampleFrameCount() );
477 mlt_log_verbose( getProducer(), "no audio\n" );
478 mlt_pool_release( pcm );
483 mlt_log_verbose( getProducer(), "no audio\n" );
486 // Put frame in queue
489 int queueMax = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "buffer" );
490 pthread_mutex_lock( &m_mutex );
491 if ( mlt_deque_count( m_queue ) < queueMax )
493 mlt_deque_push_back( m_queue, frame );
494 pthread_cond_broadcast( &m_condition );
498 mlt_frame_close( frame );
499 mlt_properties_set_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "dropped", ++m_dropped );
500 mlt_log_warning( getProducer(), "frame dropped %d\n", m_dropped );
502 pthread_mutex_unlock( &m_mutex );
508 virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(
509 BMDVideoInputFormatChangedEvents events,
510 IDeckLinkDisplayMode* mode,
511 BMDDetectedVideoInputFormatFlags flags )
513 mlt_profile profile = mlt_service_profile( MLT_PRODUCER_SERVICE( getProducer() ) );
514 if ( events & bmdVideoInputDisplayModeChanged )
516 BMDTimeValue duration;
517 BMDTimeScale timescale;
518 mode->GetFrameRate( &duration, ×cale );
519 profile->width = mode->GetWidth();
520 profile->height = mode->GetHeight() + m_vancLines;
521 profile->frame_rate_num = timescale;
522 profile->frame_rate_den = duration;
523 if ( profile->width == 720 )
525 if ( profile->height == 576 )
527 profile->sample_aspect_num = 16;
528 profile->sample_aspect_den = 15;
532 profile->sample_aspect_num = 8;
533 profile->sample_aspect_den = 9;
535 profile->display_aspect_num = 4;
536 profile->display_aspect_den = 3;
540 profile->sample_aspect_num = 1;
541 profile->sample_aspect_den = 1;
542 profile->display_aspect_num = 16;
543 profile->display_aspect_den = 9;
545 free( profile->description );
546 profile->description = strdup( "decklink" );
547 mlt_log_verbose( getProducer(), "format changed %dx%d %.3f fps\n",
548 profile->width, profile->height, (double) profile->frame_rate_num / profile->frame_rate_den );
550 if ( events & bmdVideoInputFieldDominanceChanged )
552 profile->progressive = mode->GetFieldDominance() == bmdProgressiveFrame;
553 m_topFieldFirst = mode->GetFieldDominance() == bmdUpperFieldFirst;
554 mlt_log_verbose( getProducer(), "field dominance changed prog %d tff %d\n",
555 profile->progressive, m_topFieldFirst );
557 if ( events & bmdVideoInputColorspaceChanged )
559 profile->colorspace = m_colorspace =
560 ( mode->GetFlags() & bmdDisplayModeColorspaceRec709 ) ? 709 : 601;
561 mlt_log_verbose( getProducer(), "colorspace changed %d\n", profile->colorspace );
567 static int get_audio( mlt_frame frame, int16_t **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
569 return mlt_frame_get_audio( frame, (void**) buffer, format, frequency, channels, samples );
572 static int get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
574 return mlt_frame_get_image( frame, buffer, format, width, height, writable );
577 static int get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
579 DeckLinkProducer* decklink = (DeckLinkProducer*) producer->child;
580 mlt_position pos = mlt_producer_position( producer );
581 mlt_position end = mlt_producer_get_playtime( producer );
582 end = ( mlt_producer_get_length( producer ) < end ? mlt_producer_get_length( producer ) : end ) - 1;
585 if ( !decklink && pos < end )
587 producer->child = decklink = new DeckLinkProducer();
588 decklink->setProducer( producer );
589 decklink->open( mlt_properties_get_int( MLT_PRODUCER_PROPERTIES(producer), "resource" ) );
595 decklink->start( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) );
597 // Get the next frame from the decklink object
598 if ( ( *frame = decklink->getFrame() ))
600 // Add audio and video getters
601 mlt_frame_push_audio( *frame, (void*) get_audio );
602 mlt_frame_push_get_image( *frame, get_image );
606 *frame = mlt_frame_init( MLT_PRODUCER_SERVICE(producer) );
608 // Calculate the next timecode
609 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
610 mlt_producer_prepare_next( producer );
612 // Close DeckLink if at end
613 if ( pos >= end && decklink )
617 producer->child = NULL;
623 static void producer_close( mlt_producer producer )
625 delete (DeckLinkProducer*) producer->child;
626 producer->close = NULL;
627 mlt_producer_close( producer );
632 // Listen for the list_devices property to be set
633 static void on_property_changed( void*, mlt_properties properties, const char *name )
635 IDeckLinkIterator* decklinkIterator = NULL;
636 IDeckLink* decklink = NULL;
637 IDeckLinkInput* decklinkInput = NULL;
640 if ( name && !strcmp( name, "list_devices" ) )
641 mlt_event_block( (mlt_event) mlt_properties_get_data( properties, "list-devices-event", NULL ) );
646 if ( FAILED( CoInitialize( NULL ) ) )
648 if ( FAILED( CoCreateInstance( CLSID_CDeckLinkIterator, NULL, CLSCTX_ALL, IID_IDeckLinkIterator, (void**) &decklinkIterator ) ) )
651 if ( !( decklinkIterator = CreateDeckLinkIteratorInstance() ) )
654 for ( ; decklinkIterator->Next( &decklink ) == S_OK; i++ )
656 if ( decklink->QueryInterface( IID_IDeckLinkInput, (void**) &decklinkInput ) == S_OK )
659 if ( decklink->GetModelName( (BSTR*) &name ) == S_OK )
661 const char *format = "device.%d";
662 char *key = (char*) calloc( 1, strlen( format ) + 1 );
664 sprintf( key, format, i );
665 mlt_properties_set( properties, key, name );
669 SAFE_RELEASE( decklinkInput );
671 SAFE_RELEASE( decklink );
673 SAFE_RELEASE( decklinkIterator );
674 mlt_properties_set_int( properties, "devices", i );
677 /** Initialise the producer.
680 mlt_producer producer_decklink_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
682 // Allocate the producer
683 DeckLinkProducer* decklink = new DeckLinkProducer();
684 mlt_producer producer = (mlt_producer) calloc( 1, sizeof( *producer ) );
686 // If allocated and initializes
687 if ( decklink && !mlt_producer_init( producer, decklink ) )
689 if ( decklink->open( arg? atoi( arg ) : 0 ) )
691 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
693 // Close DeckLink and defer re-open to get_frame
695 producer->child = NULL;
698 producer->close = (mlt_destructor) producer_close;
699 producer->get_frame = get_frame;
702 mlt_properties_set( properties, "resource", (arg && strcmp( arg, ""))? arg : "0" );
703 mlt_properties_set_int( properties, "channels", 2 );
704 mlt_properties_set_int( properties, "buffer", 25 );
705 mlt_properties_set_int( properties, "prefill", 25 );
707 // These properties effectively make it infinite.
708 mlt_properties_set_int( properties, "length", INT_MAX );
709 mlt_properties_set_int( properties, "out", INT_MAX - 1 );
710 mlt_properties_set( properties, "eof", "loop" );
712 mlt_event event = mlt_events_listen( properties, properties, "property-changed", (mlt_listener) on_property_changed );
713 mlt_properties_set_data( properties, "list-devices-event", event, 0, NULL, NULL );