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 );
259 double fps = mlt_producer_get_fps( getProducer() );
260 mlt_position position = mlt_producer_position( getProducer() );
261 mlt_frame frame = mlt_cache_get_frame( m_cache, position );
263 // Allow the buffer to fill to the requested initial buffer level.
266 int prefill = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "prefill" );
267 int buffer = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "buffer" );
269 m_isBuffering = false;
270 prefill = prefill > buffer ? buffer : prefill;
271 pthread_mutex_lock( &m_mutex );
272 while ( mlt_deque_count( m_queue ) < prefill )
274 // Wait up to buffer/fps seconds
275 gettimeofday( &now, NULL );
276 long usec = now.tv_sec * 1000000 + now.tv_usec;
277 usec += 1000000 * buffer / fps;
278 tm.tv_sec = usec / 1000000;
279 tm.tv_nsec = (usec % 1000000) * 1000;
280 if ( pthread_cond_timedwait( &m_condition, &m_mutex, &tm ) )
283 pthread_mutex_unlock( &m_mutex );
288 // Wait if queue is empty
289 pthread_mutex_lock( &m_mutex );
290 while ( mlt_deque_count( m_queue ) < 1 )
292 // Wait up to twice frame duration
293 gettimeofday( &now, NULL );
294 long usec = now.tv_sec * 1000000 + now.tv_usec;
295 usec += 2000000 / fps;
296 tm.tv_sec = usec / 1000000;
297 tm.tv_nsec = (usec % 1000000) * 1000;
298 if ( pthread_cond_timedwait( &m_condition, &m_mutex, &tm ) )
299 // Stop waiting if error (timed out)
302 frame = ( mlt_frame ) mlt_deque_pop_front( m_queue );
303 pthread_mutex_unlock( &m_mutex );
308 mlt_frame_set_position( frame, position );
309 mlt_cache_put_frame( m_cache, frame );
313 // Set frame timestamp and properties
316 mlt_profile profile = mlt_service_profile( MLT_PRODUCER_SERVICE( getProducer() ) );
317 mlt_properties properties = MLT_FRAME_PROPERTIES( frame );
318 mlt_properties_set_int( properties, "progressive", profile->progressive );
319 mlt_properties_set_int( properties, "meta.media.progressive", profile->progressive );
320 mlt_properties_set_int( properties, "top_field_first", m_topFieldFirst );
321 mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
322 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", profile->sample_aspect_num );
323 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", profile->sample_aspect_den );
324 mlt_properties_set_int( properties, "meta.media.frame_rate_num", profile->frame_rate_num );
325 mlt_properties_set_int( properties, "meta.media.frame_rate_den", profile->frame_rate_den );
326 mlt_properties_set_int( properties, "width", profile->width );
327 mlt_properties_set_int( properties, "meta.media.width", profile->width );
328 mlt_properties_set_int( properties, "height", profile->height );
329 mlt_properties_set_int( properties, "meta.media.height", profile->height );
330 mlt_properties_set_int( properties, "format", mlt_image_yuv422 );
331 mlt_properties_set_int( properties, "colorspace", m_colorspace );
332 mlt_properties_set_int( properties, "meta.media.colorspace", m_colorspace );
333 mlt_properties_set_int( properties, "audio_frequency", 48000 );
334 mlt_properties_set_int( properties, "audio_channels",
335 mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "channels" ) );
338 mlt_log_warning( getProducer(), "buffer underrun\n" );
343 // *** DeckLink API implementation of IDeckLinkInputCallback *** //
345 // IUnknown needs only a dummy implementation
346 virtual HRESULT STDMETHODCALLTYPE QueryInterface( REFIID iid, LPVOID *ppv )
347 { return E_NOINTERFACE; }
348 virtual ULONG STDMETHODCALLTYPE AddRef()
350 virtual ULONG STDMETHODCALLTYPE Release()
353 /************************* DeckLink API Delegate Methods *****************************/
355 virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(
356 IDeckLinkVideoInputFrame* video,
357 IDeckLinkAudioInputPacket* audio )
359 if ( mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "preview" ) &&
360 mlt_producer_get_speed( getProducer() ) == 0.0 && !mlt_deque_count( m_queue ))
362 pthread_cond_broadcast( &m_condition );
367 mlt_frame frame = mlt_frame_init( MLT_PRODUCER_SERVICE( getProducer() ) );
372 if ( !( video->GetFlags() & bmdFrameHasNoInputSource ) )
374 int size = video->GetRowBytes() * ( video->GetHeight() + m_vancLines );
375 void* image = mlt_pool_alloc( size );
377 unsigned char* p = (unsigned char*) image;
380 // Initialize VANC lines to nominal black
388 if ( m_vancLines > 0 )
390 IDeckLinkVideoFrameAncillary* vanc = 0;
391 if ( video->GetAncillaryData( &vanc ) == S_OK && vanc )
393 for ( int i = 1; i < m_vancLines + 1; i++ )
395 if ( vanc->GetBufferForVerticalBlankingLine( i, &buffer ) == S_OK )
396 swab( (char*) buffer, (char*) image + ( i - 1 ) * video->GetRowBytes(), video->GetRowBytes() );
398 mlt_log_debug( getProducer(), "failed capture vanc line %d\n", i );
405 video->GetBytes( &buffer );
406 if ( image && buffer )
408 size = video->GetRowBytes() * video->GetHeight();
409 swab( (char*) buffer, (char*) image + m_vancLines * video->GetRowBytes(), size );
410 mlt_frame_set_image( frame, (uint8_t*) image, size, mlt_pool_release );
414 mlt_log_verbose( getProducer(), "no video\n" );
415 mlt_pool_release( image );
420 mlt_log_verbose( getProducer(), "no signal\n" );
421 mlt_frame_close( frame );
426 IDeckLinkTimecode* timecode = 0;
427 if ( video->GetTimecode( bmdTimecodeVITC, &timecode ) == S_OK && timecode )
429 DLString timecodeString = 0;
431 if ( timecode->GetString( &timecodeString ) == S_OK )
433 char* s = getCString( timecodeString );
434 mlt_properties_set( MLT_FRAME_PROPERTIES( frame ), "meta.attr.vitc.markup", s );
435 mlt_log_debug( getProducer(), "timecode %s\n", s );
438 freeDLString( timecodeString );
439 SAFE_RELEASE( timecode );
444 mlt_log_verbose( getProducer(), "no video\n" );
445 mlt_frame_close( frame );
450 if ( frame && audio )
452 int channels = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "channels" );
453 int size = audio->GetSampleFrameCount() * channels * sizeof(int16_t);
454 mlt_audio_format format = mlt_audio_s16;
455 void* pcm = mlt_pool_alloc( size );
458 audio->GetBytes( &buffer );
461 memcpy( pcm, buffer, size );
462 mlt_frame_set_audio( frame, pcm, format, size, mlt_pool_release );
463 mlt_properties_set_int( MLT_FRAME_PROPERTIES(frame), "audio_samples", audio->GetSampleFrameCount() );
467 mlt_log_verbose( getProducer(), "no audio\n" );
468 mlt_pool_release( pcm );
473 mlt_log_verbose( getProducer(), "no audio\n" );
476 // Put frame in queue
479 int queueMax = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "buffer" );
480 pthread_mutex_lock( &m_mutex );
481 if ( mlt_deque_count( m_queue ) < queueMax )
483 mlt_deque_push_back( m_queue, frame );
484 pthread_cond_broadcast( &m_condition );
488 mlt_frame_close( frame );
489 mlt_properties_set_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "dropped", ++m_dropped );
490 mlt_log_warning( getProducer(), "frame dropped %d\n", m_dropped );
492 pthread_mutex_unlock( &m_mutex );
498 virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(
499 BMDVideoInputFormatChangedEvents events,
500 IDeckLinkDisplayMode* mode,
501 BMDDetectedVideoInputFormatFlags flags )
503 mlt_profile profile = mlt_service_profile( MLT_PRODUCER_SERVICE( getProducer() ) );
504 if ( events & bmdVideoInputDisplayModeChanged )
506 BMDTimeValue duration;
507 BMDTimeScale timescale;
508 mode->GetFrameRate( &duration, ×cale );
509 profile->width = mode->GetWidth();
510 profile->height = mode->GetHeight() + m_vancLines;
511 profile->frame_rate_num = timescale;
512 profile->frame_rate_den = duration;
513 if ( profile->width == 720 )
515 if ( profile->height == 576 )
517 profile->sample_aspect_num = 16;
518 profile->sample_aspect_den = 15;
522 profile->sample_aspect_num = 8;
523 profile->sample_aspect_den = 9;
525 profile->display_aspect_num = 4;
526 profile->display_aspect_den = 3;
530 profile->sample_aspect_num = 1;
531 profile->sample_aspect_den = 1;
532 profile->display_aspect_num = 16;
533 profile->display_aspect_den = 9;
535 free( profile->description );
536 profile->description = strdup( "decklink" );
537 mlt_log_verbose( getProducer(), "format changed %dx%d %.3f fps\n",
538 profile->width, profile->height, (double) profile->frame_rate_num / profile->frame_rate_den );
540 if ( events & bmdVideoInputFieldDominanceChanged )
542 profile->progressive = mode->GetFieldDominance() == bmdProgressiveFrame;
543 m_topFieldFirst = mode->GetFieldDominance() == bmdUpperFieldFirst;
544 mlt_log_verbose( getProducer(), "field dominance changed prog %d tff %d\n",
545 profile->progressive, m_topFieldFirst );
547 if ( events & bmdVideoInputColorspaceChanged )
549 profile->colorspace = m_colorspace =
550 ( mode->GetFlags() & bmdDisplayModeColorspaceRec709 ) ? 709 : 601;
551 mlt_log_verbose( getProducer(), "colorspace changed %d\n", profile->colorspace );
557 static int get_audio( mlt_frame frame, int16_t **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
559 return mlt_frame_get_audio( frame, (void**) buffer, format, frequency, channels, samples );
562 static int get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
564 return mlt_frame_get_image( frame, buffer, format, width, height, writable );
567 static int get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
569 DeckLinkProducer* decklink = (DeckLinkProducer*) producer->child;
570 mlt_position pos = mlt_producer_position( producer );
571 mlt_position end = mlt_producer_get_playtime( producer );
572 end = ( mlt_producer_get_length( producer ) < end ? mlt_producer_get_length( producer ) : end ) - 1;
575 if ( !decklink && pos < end )
577 producer->child = decklink = new DeckLinkProducer();
578 decklink->setProducer( producer );
579 decklink->open( mlt_properties_get_int( MLT_PRODUCER_PROPERTIES(producer), "resource" ) );
585 decklink->start( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) );
587 // Get the next frame from the decklink object
588 if ( ( *frame = decklink->getFrame() ))
590 // Add audio and video getters
591 mlt_frame_push_audio( *frame, (void*) get_audio );
592 mlt_frame_push_get_image( *frame, get_image );
596 *frame = mlt_frame_init( MLT_PRODUCER_SERVICE(producer) );
598 // Calculate the next timecode
599 mlt_producer_prepare_next( producer );
601 // Close DeckLink if at end
602 if ( pos >= end && decklink )
606 producer->child = NULL;
612 static void producer_close( mlt_producer producer )
614 delete (DeckLinkProducer*) producer->child;
615 producer->close = NULL;
616 mlt_producer_close( producer );
621 // Listen for the list_devices property to be set
622 static void on_property_changed( void*, mlt_properties properties, const char *name )
624 IDeckLinkIterator* decklinkIterator = NULL;
625 IDeckLink* decklink = NULL;
626 IDeckLinkInput* decklinkInput = NULL;
629 if ( name && !strcmp( name, "list_devices" ) )
630 mlt_event_block( (mlt_event) mlt_properties_get_data( properties, "list-devices-event", NULL ) );
635 if ( FAILED( CoInitialize( NULL ) ) )
637 if ( FAILED( CoCreateInstance( CLSID_CDeckLinkIterator, NULL, CLSCTX_ALL, IID_IDeckLinkIterator, (void**) &decklinkIterator ) ) )
640 if ( !( decklinkIterator = CreateDeckLinkIteratorInstance() ) )
643 for ( ; decklinkIterator->Next( &decklink ) == S_OK; i++ )
645 if ( decklink->QueryInterface( IID_IDeckLinkInput, (void**) &decklinkInput ) == S_OK )
647 DLString name = NULL;
648 if ( decklink->GetModelName( &name ) == S_OK )
650 char *name_cstr = getCString( name );
651 const char *format = "device.%d";
652 char *key = (char*) calloc( 1, strlen( format ) + 1 );
654 sprintf( key, format, i );
655 mlt_properties_set( properties, key, name_cstr );
657 freeDLString( name );
658 freeCString( name_cstr );
660 SAFE_RELEASE( decklinkInput );
662 SAFE_RELEASE( decklink );
664 SAFE_RELEASE( decklinkIterator );
665 mlt_properties_set_int( properties, "devices", i );
668 /** Initialise the producer.
671 mlt_producer producer_decklink_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
673 // Allocate the producer
674 DeckLinkProducer* decklink = new DeckLinkProducer();
675 mlt_producer producer = (mlt_producer) calloc( 1, sizeof( *producer ) );
677 // If allocated and initializes
678 if ( decklink && !mlt_producer_init( producer, decklink ) )
680 if ( decklink->open( arg? atoi( arg ) : 0 ) )
682 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
684 // Close DeckLink and defer re-open to get_frame
686 producer->child = NULL;
689 producer->close = (mlt_destructor) producer_close;
690 producer->get_frame = get_frame;
693 mlt_properties_set( properties, "resource", (arg && strcmp( arg, ""))? arg : "0" );
694 mlt_properties_set_int( properties, "channels", 2 );
695 mlt_properties_set_int( properties, "buffer", 25 );
696 mlt_properties_set_int( properties, "prefill", 25 );
698 // These properties effectively make it infinite.
699 mlt_properties_set_int( properties, "length", INT_MAX );
700 mlt_properties_set_int( properties, "out", INT_MAX - 1 );
701 mlt_properties_set( properties, "eof", "loop" );
703 mlt_event event = mlt_events_listen( properties, properties, "property-changed", (mlt_listener) on_property_changed );
704 mlt_properties_set_data( properties, "list-devices-event", event, 0, NULL, NULL );