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 class DeckLinkProducer
30 : public IDeckLinkInputCallback
33 mlt_producer m_producer;
34 IDeckLink* m_decklink;
35 IDeckLinkInput* m_decklinkInput;
37 pthread_mutex_t m_mutex;
38 pthread_cond_t m_condition;
47 BMDDisplayMode getDisplayMode( mlt_profile profile, int vancLines )
49 IDeckLinkDisplayModeIterator* iter = NULL;
50 IDeckLinkDisplayMode* mode = NULL;
51 BMDDisplayMode result = (BMDDisplayMode) bmdDisplayModeNotSupported;
53 if ( m_decklinkInput->GetDisplayModeIterator( &iter ) == S_OK )
55 while ( !result && iter->Next( &mode ) == S_OK )
57 int width = mode->GetWidth();
58 int height = mode->GetHeight();
59 BMDTimeValue duration;
60 BMDTimeScale timescale;
61 mode->GetFrameRate( &duration, ×cale );
62 double fps = (double) timescale / duration;
63 int p = mode->GetFieldDominance() == bmdProgressiveFrame;
64 m_topFieldFirst = mode->GetFieldDominance() == bmdUpperFieldFirst;
65 m_colorspace = ( mode->GetFlags() & bmdDisplayModeColorspaceRec709 ) ? 709 : 601;
66 mlt_log_verbose( getProducer(), "BMD mode %dx%d %.3f fps prog %d tff %d\n", width, height, fps, p, m_topFieldFirst );
68 if ( width == profile->width && p == profile->progressive
69 && ( height + vancLines == profile->height || ( height == 486 && profile->height == 480 + vancLines ) )
70 && fps == mlt_profile_fps( profile ) )
71 result = mode->GetDisplayMode();
82 void setProducer( mlt_producer producer )
83 { m_producer = producer; }
85 mlt_producer getProducer() const
86 { return m_producer; }
91 m_decklinkInput = NULL;
99 mlt_deque_close( m_queue );
100 pthread_mutex_destroy( &m_mutex );
101 pthread_cond_destroy( &m_condition );
102 mlt_cache_close( m_cache );
104 SAFE_RELEASE( m_decklinkInput );
105 SAFE_RELEASE( m_decklink );
108 bool open( unsigned card = 0 )
110 IDeckLinkIterator* decklinkIterator = NULL;
114 HRESULT result = CoInitialize( NULL );
115 if ( FAILED( result ) )
116 throw "COM initialization failed";
117 result = CoCreateInstance( CLSID_CDeckLinkIterator, NULL, CLSCTX_ALL, IID_IDeckLinkIterator, (void**) &decklinkIterator );
118 if ( FAILED( result ) )
119 throw "The DeckLink drivers are not installed.";
121 decklinkIterator = CreateDeckLinkIteratorInstance();
122 if ( !decklinkIterator )
123 throw "The DeckLink drivers are not installed.";
125 // Connect to the Nth DeckLink instance
126 for ( unsigned i = 0; decklinkIterator->Next( &m_decklink ) == S_OK ; i++)
131 SAFE_RELEASE( m_decklink );
133 SAFE_RELEASE( decklinkIterator );
135 throw "DeckLink card not found.";
137 // Get the input interface
138 if ( m_decklink->QueryInterface( IID_IDeckLinkInput, (void**) &m_decklinkInput ) != S_OK )
139 throw "No DeckLink cards support input.";
141 // Provide this class as a delegate to the input callback
142 m_decklinkInput->SetCallback( this );
144 // Initialize other members
145 pthread_mutex_init( &m_mutex, NULL );
146 pthread_cond_init( &m_condition, NULL );
147 m_queue = mlt_deque_init();
150 m_isBuffering = true;
151 m_cache = mlt_cache_init();
153 // 3 covers YADIF and increasing framerate use cases
154 mlt_cache_set_size( m_cache, 3 );
156 catch ( const char *error )
158 SAFE_RELEASE( m_decklinkInput );
159 SAFE_RELEASE( m_decklink );
160 mlt_log_error( getProducer(), "%s\n", error );
166 bool start( mlt_profile profile = 0 )
172 // Initialize some members
173 m_vancLines = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "vanc" );
174 if ( m_vancLines == -1 )
175 m_vancLines = profile->height <= 512 ? 26 : 32;
178 profile = mlt_service_profile( MLT_PRODUCER_SERVICE( getProducer() ) );
180 // Get the display mode
181 BMDDisplayMode displayMode = getDisplayMode( profile, m_vancLines );
182 if ( displayMode == (BMDDisplayMode) bmdDisplayModeNotSupported )
184 mlt_log_info( getProducer(), "profile = %dx%d %f fps %s\n", profile->width, profile->height,
185 mlt_profile_fps( profile ), profile->progressive? "progressive" : "interlace" );
186 throw "Profile is not compatible with decklink.";
189 // Determine if supports input format detection
191 BOOL doesDetectFormat = FALSE;
193 bool doesDetectFormat = false;
195 IDeckLinkAttributes *decklinkAttributes = 0;
196 if ( m_decklink->QueryInterface( IID_IDeckLinkAttributes, (void**) &decklinkAttributes ) == S_OK )
198 if ( decklinkAttributes->GetFlag( BMDDeckLinkSupportsInputFormatDetection, &doesDetectFormat ) != S_OK )
199 doesDetectFormat = false;
200 SAFE_RELEASE( decklinkAttributes );
202 mlt_log_verbose( getProducer(), "%s format detection\n", doesDetectFormat ? "supports" : "does not support" );
204 // Enable video capture
205 BMDPixelFormat pixelFormat = bmdFormat8BitYUV;
206 BMDVideoInputFlags flags = doesDetectFormat ? bmdVideoInputEnableFormatDetection : bmdVideoInputFlagDefault;
207 if ( S_OK != m_decklinkInput->EnableVideoInput( displayMode, pixelFormat, flags ) )
208 throw "Failed to enable video capture.";
210 // Enable audio capture
211 BMDAudioSampleRate sampleRate = bmdAudioSampleRate48kHz;
212 BMDAudioSampleType sampleType = bmdAudioSampleType16bitInteger;
213 int channels = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "channels" );
214 if ( S_OK != m_decklinkInput->EnableAudioInput( sampleRate, sampleType, channels ) )
215 throw "Failed to enable audio capture.";
219 mlt_properties_set_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "dropped", m_dropped );
220 m_started = m_decklinkInput->StartStreams() == S_OK;
222 throw "Failed to start capture.";
224 catch ( const char *error )
226 m_decklinkInput->DisableVideoInput();
227 mlt_log_error( getProducer(), "%s\n", error );
239 // Release the wait in getFrame
240 pthread_mutex_lock( &m_mutex );
241 pthread_cond_broadcast( &m_condition );
242 pthread_mutex_unlock( &m_mutex );
244 m_decklinkInput->StopStreams();
245 m_decklinkInput->DisableVideoInput();
246 m_decklinkInput->DisableAudioInput();
249 pthread_mutex_lock( &m_mutex );
250 while ( mlt_frame frame = (mlt_frame) mlt_deque_pop_back( m_queue ) )
251 mlt_frame_close( frame );
252 pthread_mutex_unlock( &m_mutex );
257 mlt_frame frame = NULL;
260 double fps = mlt_producer_get_fps( getProducer() );
261 mlt_position position = mlt_producer_position( getProducer() );
262 mlt_cache_item cached = mlt_cache_get( m_cache, (void*) position );
264 // Allow the buffer to fill to the requested initial buffer level.
267 int prefill = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "prefill" );
268 int buffer = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "buffer" );
270 m_isBuffering = false;
271 prefill = prefill > buffer ? buffer : prefill;
272 pthread_mutex_lock( &m_mutex );
273 while ( mlt_deque_count( m_queue ) < prefill )
275 // Wait up to buffer/fps seconds
276 gettimeofday( &now, NULL );
277 long usec = now.tv_sec * 1000000 + now.tv_usec;
278 usec += 1000000 * buffer / fps;
279 tm.tv_sec = usec / 1000000;
280 tm.tv_nsec = (usec % 1000000) * 1000;
281 if ( pthread_cond_timedwait( &m_condition, &m_mutex, &tm ) )
284 pthread_mutex_unlock( &m_mutex );
289 // Copy cached frame instead of pulling from queue
290 frame = mlt_frame_clone( (mlt_frame) mlt_cache_item_data( cached, NULL ), 0 );
291 mlt_cache_item_close( cached );
295 // Wait if queue is empty
296 pthread_mutex_lock( &m_mutex );
297 while ( mlt_deque_count( m_queue ) < 1 )
299 // Wait up to twice frame duration
300 gettimeofday( &now, NULL );
301 long usec = now.tv_sec * 1000000 + now.tv_usec;
302 usec += 2000000 / fps;
303 tm.tv_sec = usec / 1000000;
304 tm.tv_nsec = (usec % 1000000) * 1000;
305 if ( pthread_cond_timedwait( &m_condition, &m_mutex, &tm ) )
306 // Stop waiting if error (timed out)
309 frame = ( mlt_frame ) mlt_deque_pop_front( m_queue );
310 pthread_mutex_unlock( &m_mutex );
314 mlt_cache_put( m_cache, (void*) position, mlt_frame_clone( frame, 1 ), 0,
315 (mlt_destructor) mlt_frame_close );
318 // Set frame timestamp and properties
321 mlt_profile profile = mlt_service_profile( MLT_PRODUCER_SERVICE( getProducer() ) );
322 mlt_properties properties = MLT_FRAME_PROPERTIES( frame );
323 mlt_properties_set_int( properties, "progressive", profile->progressive );
324 mlt_properties_set_int( properties, "meta.media.progressive", profile->progressive );
325 mlt_properties_set_int( properties, "top_field_first", m_topFieldFirst );
326 mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
327 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", profile->sample_aspect_num );
328 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", profile->sample_aspect_den );
329 mlt_properties_set_int( properties, "meta.media.frame_rate_num", profile->frame_rate_num );
330 mlt_properties_set_int( properties, "meta.media.frame_rate_den", profile->frame_rate_den );
331 mlt_properties_set_int( properties, "width", profile->width );
332 mlt_properties_set_int( properties, "meta.media.width", profile->width );
333 mlt_properties_set_int( properties, "height", profile->height );
334 mlt_properties_set_int( properties, "meta.media.height", profile->height );
335 mlt_properties_set_int( properties, "format", mlt_image_yuv422 );
336 mlt_properties_set_int( properties, "colorspace", m_colorspace );
337 mlt_properties_set_int( properties, "meta.media.colorspace", m_colorspace );
338 mlt_properties_set_int( properties, "audio_frequency", 48000 );
339 mlt_properties_set_int( properties, "audio_channels",
340 mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "channels" ) );
343 mlt_log_warning( getProducer(), "buffer underrun\n" );
348 // *** DeckLink API implementation of IDeckLinkInputCallback *** //
350 // IUnknown needs only a dummy implementation
351 virtual HRESULT STDMETHODCALLTYPE QueryInterface( REFIID iid, LPVOID *ppv )
352 { return E_NOINTERFACE; }
353 virtual ULONG STDMETHODCALLTYPE AddRef()
355 virtual ULONG STDMETHODCALLTYPE Release()
358 /************************* DeckLink API Delegate Methods *****************************/
360 virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(
361 IDeckLinkVideoInputFrame* video,
362 IDeckLinkAudioInputPacket* audio )
364 if ( mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "preview" ) &&
365 mlt_producer_get_speed( getProducer() ) == 0.0 && !mlt_deque_count( m_queue ))
367 pthread_cond_broadcast( &m_condition );
372 mlt_frame frame = mlt_frame_init( MLT_PRODUCER_SERVICE( getProducer() ) );
377 if ( !( video->GetFlags() & bmdFrameHasNoInputSource ) )
379 int size = video->GetRowBytes() * ( video->GetHeight() + m_vancLines );
380 void* image = mlt_pool_alloc( size );
382 unsigned char* p = (unsigned char*) image;
385 // Initialize VANC lines to nominal black
393 if ( m_vancLines > 0 )
395 IDeckLinkVideoFrameAncillary* vanc = 0;
396 if ( video->GetAncillaryData( &vanc ) == S_OK && vanc )
398 for ( int i = 1; i < m_vancLines + 1; i++ )
400 if ( vanc->GetBufferForVerticalBlankingLine( i, &buffer ) == S_OK )
401 swab( (char*) buffer, (char*) image + ( i - 1 ) * video->GetRowBytes(), video->GetRowBytes() );
403 mlt_log_debug( getProducer(), "failed capture vanc line %d\n", i );
410 video->GetBytes( &buffer );
411 if ( image && buffer )
413 size = video->GetRowBytes() * video->GetHeight();
414 swab( (char*) buffer, (char*) image + m_vancLines * video->GetRowBytes(), size );
415 mlt_frame_set_image( frame, (uint8_t*) image, size, mlt_pool_release );
419 mlt_log_verbose( getProducer(), "no video\n" );
420 mlt_pool_release( image );
425 mlt_log_verbose( getProducer(), "no signal\n" );
426 mlt_frame_close( frame );
431 IDeckLinkTimecode* timecode = 0;
432 if ( video->GetTimecode( bmdTimecodeVITC, &timecode ) == S_OK && timecode )
434 DLString timecodeString = 0;
436 if ( timecode->GetString( &timecodeString ) == S_OK )
438 char* s = getCString( timecodeString );
439 mlt_properties_set( MLT_FRAME_PROPERTIES( frame ), "meta.attr.vitc.markup", s );
440 mlt_log_debug( getProducer(), "timecode %s\n", s );
443 freeDLString( timecodeString );
444 SAFE_RELEASE( timecode );
449 mlt_log_verbose( getProducer(), "no video\n" );
450 mlt_frame_close( frame );
455 if ( frame && audio )
457 int channels = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "channels" );
458 int size = audio->GetSampleFrameCount() * channels * sizeof(int16_t);
459 mlt_audio_format format = mlt_audio_s16;
460 void* pcm = mlt_pool_alloc( size );
463 audio->GetBytes( &buffer );
466 memcpy( pcm, buffer, size );
467 mlt_frame_set_audio( frame, pcm, format, size, mlt_pool_release );
468 mlt_properties_set_int( MLT_FRAME_PROPERTIES(frame), "audio_samples", audio->GetSampleFrameCount() );
472 mlt_log_verbose( getProducer(), "no audio\n" );
473 mlt_pool_release( pcm );
478 mlt_log_verbose( getProducer(), "no audio\n" );
481 // Put frame in queue
484 int queueMax = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "buffer" );
485 pthread_mutex_lock( &m_mutex );
486 if ( mlt_deque_count( m_queue ) < queueMax )
488 mlt_deque_push_back( m_queue, frame );
489 pthread_cond_broadcast( &m_condition );
493 mlt_frame_close( frame );
494 mlt_properties_set_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "dropped", ++m_dropped );
495 mlt_log_warning( getProducer(), "frame dropped %d\n", m_dropped );
497 pthread_mutex_unlock( &m_mutex );
503 virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(
504 BMDVideoInputFormatChangedEvents events,
505 IDeckLinkDisplayMode* mode,
506 BMDDetectedVideoInputFormatFlags flags )
508 mlt_profile profile = mlt_service_profile( MLT_PRODUCER_SERVICE( getProducer() ) );
509 if ( events & bmdVideoInputDisplayModeChanged )
511 BMDTimeValue duration;
512 BMDTimeScale timescale;
513 mode->GetFrameRate( &duration, ×cale );
514 profile->width = mode->GetWidth();
515 profile->height = mode->GetHeight() + m_vancLines;
516 profile->frame_rate_num = timescale;
517 profile->frame_rate_den = duration;
518 if ( profile->width == 720 )
520 if ( profile->height == 576 )
522 profile->sample_aspect_num = 16;
523 profile->sample_aspect_den = 15;
527 profile->sample_aspect_num = 8;
528 profile->sample_aspect_den = 9;
530 profile->display_aspect_num = 4;
531 profile->display_aspect_den = 3;
535 profile->sample_aspect_num = 1;
536 profile->sample_aspect_den = 1;
537 profile->display_aspect_num = 16;
538 profile->display_aspect_den = 9;
540 free( profile->description );
541 profile->description = strdup( "decklink" );
542 mlt_log_verbose( getProducer(), "format changed %dx%d %.3f fps\n",
543 profile->width, profile->height, (double) profile->frame_rate_num / profile->frame_rate_den );
545 if ( events & bmdVideoInputFieldDominanceChanged )
547 profile->progressive = mode->GetFieldDominance() == bmdProgressiveFrame;
548 m_topFieldFirst = mode->GetFieldDominance() == bmdUpperFieldFirst;
549 mlt_log_verbose( getProducer(), "field dominance changed prog %d tff %d\n",
550 profile->progressive, m_topFieldFirst );
552 if ( events & bmdVideoInputColorspaceChanged )
554 profile->colorspace = m_colorspace =
555 ( mode->GetFlags() & bmdDisplayModeColorspaceRec709 ) ? 709 : 601;
556 mlt_log_verbose( getProducer(), "colorspace changed %d\n", profile->colorspace );
562 static int get_audio( mlt_frame frame, int16_t **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
564 return mlt_frame_get_audio( frame, (void**) buffer, format, frequency, channels, samples );
567 static int get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
569 return mlt_frame_get_image( frame, buffer, format, width, height, writable );
572 static int get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
574 DeckLinkProducer* decklink = (DeckLinkProducer*) producer->child;
575 mlt_position pos = mlt_producer_position( producer );
576 mlt_position end = mlt_producer_get_playtime( producer );
577 end = ( mlt_producer_get_length( producer ) < end ? mlt_producer_get_length( producer ) : end ) - 1;
580 if ( !decklink && pos < end )
582 producer->child = decklink = new DeckLinkProducer();
583 decklink->setProducer( producer );
584 decklink->open( mlt_properties_get_int( MLT_PRODUCER_PROPERTIES(producer), "resource" ) );
590 decklink->start( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) );
592 // Get the next frame from the decklink object
593 if ( ( *frame = decklink->getFrame() ))
595 // Add audio and video getters
596 mlt_frame_push_audio( *frame, (void*) get_audio );
597 mlt_frame_push_get_image( *frame, get_image );
601 *frame = mlt_frame_init( MLT_PRODUCER_SERVICE(producer) );
603 // Calculate the next timecode
604 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
605 mlt_producer_prepare_next( producer );
607 // Close DeckLink if at end
608 if ( pos >= end && decklink )
612 producer->child = NULL;
618 static void producer_close( mlt_producer producer )
620 delete (DeckLinkProducer*) producer->child;
621 producer->close = NULL;
622 mlt_producer_close( producer );
627 // Listen for the list_devices property to be set
628 static void on_property_changed( void*, mlt_properties properties, const char *name )
630 IDeckLinkIterator* decklinkIterator = NULL;
631 IDeckLink* decklink = NULL;
632 IDeckLinkInput* decklinkInput = NULL;
635 if ( name && !strcmp( name, "list_devices" ) )
636 mlt_event_block( (mlt_event) mlt_properties_get_data( properties, "list-devices-event", NULL ) );
641 if ( FAILED( CoInitialize( NULL ) ) )
643 if ( FAILED( CoCreateInstance( CLSID_CDeckLinkIterator, NULL, CLSCTX_ALL, IID_IDeckLinkIterator, (void**) &decklinkIterator ) ) )
646 if ( !( decklinkIterator = CreateDeckLinkIteratorInstance() ) )
649 for ( ; decklinkIterator->Next( &decklink ) == S_OK; i++ )
651 if ( decklink->QueryInterface( IID_IDeckLinkInput, (void**) &decklinkInput ) == S_OK )
653 DLString name = NULL;
654 if ( decklink->GetModelName( &name ) == S_OK )
656 char *name_cstr = getCString( name );
657 const char *format = "device.%d";
658 char *key = (char*) calloc( 1, strlen( format ) + 1 );
660 sprintf( key, format, i );
661 mlt_properties_set( properties, key, name_cstr );
663 freeDLString( name );
664 freeCString( name_cstr );
666 SAFE_RELEASE( decklinkInput );
668 SAFE_RELEASE( decklink );
670 SAFE_RELEASE( decklinkIterator );
671 mlt_properties_set_int( properties, "devices", i );
674 /** Initialise the producer.
677 mlt_producer producer_decklink_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
679 // Allocate the producer
680 DeckLinkProducer* decklink = new DeckLinkProducer();
681 mlt_producer producer = (mlt_producer) calloc( 1, sizeof( *producer ) );
683 // If allocated and initializes
684 if ( decklink && !mlt_producer_init( producer, decklink ) )
686 if ( decklink->open( arg? atoi( arg ) : 0 ) )
688 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
690 // Close DeckLink and defer re-open to get_frame
692 producer->child = NULL;
695 producer->close = (mlt_destructor) producer_close;
696 producer->get_frame = get_frame;
699 mlt_properties_set( properties, "resource", (arg && strcmp( arg, ""))? arg : "0" );
700 mlt_properties_set_int( properties, "channels", 2 );
701 mlt_properties_set_int( properties, "buffer", 25 );
702 mlt_properties_set_int( properties, "prefill", 25 );
704 // These properties effectively make it infinite.
705 mlt_properties_set_int( properties, "length", INT_MAX );
706 mlt_properties_set_int( properties, "out", INT_MAX - 1 );
707 mlt_properties_set( properties, "eof", "loop" );
709 mlt_event event = mlt_events_listen( properties, properties, "property-changed", (mlt_listener) on_property_changed );
710 mlt_properties_set_data( properties, "list-devices-event", event, 0, NULL, NULL );