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"
34 #define SAFE_RELEASE(V) if (V) { V->Release(); V = NULL; }
36 class DeckLinkProducer
37 : public IDeckLinkInputCallback
40 mlt_producer m_producer;
41 IDeckLink* m_decklink;
42 IDeckLinkInput* m_decklinkInput;
44 pthread_mutex_t m_mutex;
45 pthread_cond_t m_condition;
54 BMDDisplayMode getDisplayMode( mlt_profile profile, int vancLines )
56 IDeckLinkDisplayModeIterator* iter = NULL;
57 IDeckLinkDisplayMode* mode = NULL;
58 BMDDisplayMode result = (BMDDisplayMode) bmdDisplayModeNotSupported;
60 if ( m_decklinkInput->GetDisplayModeIterator( &iter ) == S_OK )
62 while ( !result && iter->Next( &mode ) == S_OK )
64 int width = mode->GetWidth();
65 int height = mode->GetHeight();
66 BMDTimeValue duration;
67 BMDTimeScale timescale;
68 mode->GetFrameRate( &duration, ×cale );
69 double fps = (double) timescale / duration;
70 int p = mode->GetFieldDominance() == bmdProgressiveFrame;
71 m_topFieldFirst = mode->GetFieldDominance() == bmdUpperFieldFirst;
72 m_colorspace = ( mode->GetFlags() & bmdDisplayModeColorspaceRec709 ) ? 709 : 601;
73 mlt_log_verbose( getProducer(), "BMD mode %dx%d %.3f fps prog %d tff %d\n", width, height, fps, p, m_topFieldFirst );
75 if ( width == profile->width && p == profile->progressive
76 && ( height + vancLines == profile->height || ( height == 486 && profile->height == 480 + vancLines ) )
77 && fps == mlt_profile_fps( profile ) )
78 result = mode->GetDisplayMode();
89 void setProducer( mlt_producer producer )
90 { m_producer = producer; }
92 mlt_producer getProducer() const
93 { return m_producer; }
98 m_decklinkInput = NULL;
106 mlt_deque_close( m_queue );
107 pthread_mutex_destroy( &m_mutex );
108 pthread_cond_destroy( &m_condition );
109 mlt_cache_close( m_cache );
111 SAFE_RELEASE( m_decklinkInput );
112 SAFE_RELEASE( m_decklink );
115 bool listDevices( mlt_properties properties )
117 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 for ( ; decklinkIterator->Next( &m_decklink ) == S_OK; i++ )
135 if ( m_decklink->QueryInterface( IID_IDeckLinkInput, (void**) &m_decklinkInput ) == S_OK )
138 if ( m_decklink->GetModelName( (const char**) &name ) == S_OK )
140 const char *format = "device.%d";
141 char *key = (char*) calloc( 1, strlen( format ) + 1 );
143 sprintf( key, format, i );
144 mlt_properties_set( properties, key, name );
148 SAFE_RELEASE( m_decklinkInput );
150 SAFE_RELEASE( m_decklink );
152 SAFE_RELEASE( decklinkIterator );
153 mlt_properties_set_int( properties, "devices", i );
156 catch ( const char *error )
158 SAFE_RELEASE( decklinkIterator );
159 mlt_log_error( getProducer(), "%s\n", error );
164 bool open( unsigned card = 0 )
166 IDeckLinkIterator* decklinkIterator = NULL;
170 HRESULT result = CoInitialize( NULL );
171 if ( FAILED( result ) )
172 throw "COM initialization failed";
173 result = CoCreateInstance( CLSID_CDeckLinkIterator, NULL, CLSCTX_ALL, IID_IDeckLinkIterator, (void**) &decklinkIterator );
174 if ( FAILED( result ) )
175 throw "The DeckLink drivers are not installed.";
177 decklinkIterator = CreateDeckLinkIteratorInstance();
178 if ( !decklinkIterator )
179 throw "The DeckLink drivers are not installed.";
182 // Connect to the Nth DeckLink instance
183 for ( unsigned i = 0; decklinkIterator->Next( &m_decklink ) == S_OK ; i++)
188 SAFE_RELEASE( m_decklink );
190 SAFE_RELEASE( decklinkIterator );
192 throw "DeckLink card not found.";
194 // Get the input interface
195 if ( m_decklink->QueryInterface( IID_IDeckLinkInput, (void**) &m_decklinkInput ) != S_OK )
196 throw "No DeckLink cards support input.";
198 // Provide this class as a delegate to the input callback
199 m_decklinkInput->SetCallback( this );
201 // Initialize other members
202 pthread_mutex_init( &m_mutex, NULL );
203 pthread_cond_init( &m_condition, NULL );
204 m_queue = mlt_deque_init();
207 m_isBuffering = true;
208 m_cache = mlt_cache_init();
210 // 3 covers YADIF and increasing framerate use cases
211 mlt_cache_set_size( m_cache, 3 );
213 catch ( const char *error )
215 SAFE_RELEASE( m_decklinkInput );
216 SAFE_RELEASE( m_decklink );
217 mlt_log_error( getProducer(), "%s\n", error );
223 bool start( mlt_profile profile = 0 )
229 // Initialize some members
230 m_vancLines = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "vanc" );
231 if ( m_vancLines == -1 )
232 m_vancLines = profile->height <= 512 ? 26 : 32;
235 profile = mlt_service_profile( MLT_PRODUCER_SERVICE( getProducer() ) );
237 // Get the display mode
238 BMDDisplayMode displayMode = getDisplayMode( profile, m_vancLines );
239 if ( displayMode == (BMDDisplayMode) bmdDisplayModeNotSupported )
241 mlt_log_info( getProducer(), "profile = %dx%d %f fps %s\n", profile->width, profile->height,
242 mlt_profile_fps( profile ), profile->progressive? "progressive" : "interlace" );
243 throw "Profile is not compatible with decklink.";
246 // Determine if supports input format detection
248 BOOL doesDetectFormat = FALSE;
250 bool doesDetectFormat = false;
252 IDeckLinkAttributes *decklinkAttributes = 0;
253 if ( m_decklink->QueryInterface( IID_IDeckLinkAttributes, (void**) &decklinkAttributes ) == S_OK )
255 if ( decklinkAttributes->GetFlag( BMDDeckLinkSupportsInputFormatDetection, &doesDetectFormat ) != S_OK )
256 doesDetectFormat = false;
257 SAFE_RELEASE( decklinkAttributes );
259 mlt_log_verbose( getProducer(), "%s format detection\n", doesDetectFormat ? "supports" : "does not support" );
261 // Enable video capture
262 BMDPixelFormat pixelFormat = bmdFormat8BitYUV;
263 BMDVideoInputFlags flags = doesDetectFormat ? bmdVideoInputEnableFormatDetection : bmdVideoInputFlagDefault;
264 if ( S_OK != m_decklinkInput->EnableVideoInput( displayMode, pixelFormat, flags ) )
265 throw "Failed to enable video capture.";
267 // Enable audio capture
268 BMDAudioSampleRate sampleRate = bmdAudioSampleRate48kHz;
269 BMDAudioSampleType sampleType = bmdAudioSampleType16bitInteger;
270 int channels = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "channels" );
271 if ( S_OK != m_decklinkInput->EnableAudioInput( sampleRate, sampleType, channels ) )
272 throw "Failed to enable audio capture.";
276 mlt_properties_set_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "dropped", m_dropped );
277 m_started = m_decklinkInput->StartStreams() == S_OK;
279 throw "Failed to start capture.";
281 catch ( const char *error )
283 m_decklinkInput->DisableVideoInput();
284 mlt_log_error( getProducer(), "%s\n", error );
296 // Release the wait in getFrame
297 pthread_mutex_lock( &m_mutex );
298 pthread_cond_broadcast( &m_condition );
299 pthread_mutex_unlock( &m_mutex );
301 m_decklinkInput->StopStreams();
304 pthread_mutex_lock( &m_mutex );
305 while ( mlt_frame frame = (mlt_frame) mlt_deque_pop_back( m_queue ) )
306 mlt_frame_close( frame );
307 pthread_mutex_unlock( &m_mutex );
312 mlt_frame frame = NULL;
315 double fps = mlt_producer_get_fps( getProducer() );
316 mlt_position position = mlt_producer_position( getProducer() );
317 mlt_cache_item cached = mlt_cache_get( m_cache, (void*) position );
319 // Allow the buffer to fill to the requested initial buffer level.
322 int prefill = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "prefill" );
323 int buffer = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "buffer" );
325 m_isBuffering = false;
326 prefill = prefill > buffer ? buffer : prefill;
327 pthread_mutex_lock( &m_mutex );
328 while ( mlt_deque_count( m_queue ) < prefill )
330 // Wait up to buffer/fps seconds
331 gettimeofday( &now, NULL );
332 long usec = now.tv_sec * 1000000 + now.tv_usec;
333 usec += 1000000 * buffer / fps;
334 tm.tv_sec = usec / 1000000;
335 tm.tv_nsec = (usec % 1000000) * 1000;
336 if ( pthread_cond_timedwait( &m_condition, &m_mutex, &tm ) )
339 pthread_mutex_unlock( &m_mutex );
344 // Copy cached frame instead of pulling from queue
345 frame = mlt_frame_clone( (mlt_frame) mlt_cache_item_data( cached, NULL ), 0 );
346 mlt_cache_item_close( cached );
350 // Wait if queue is empty
351 pthread_mutex_lock( &m_mutex );
352 while ( mlt_deque_count( m_queue ) < 1 )
354 // Wait up to twice frame duration
355 gettimeofday( &now, NULL );
356 long usec = now.tv_sec * 1000000 + now.tv_usec;
357 usec += 2000000 / fps;
358 tm.tv_sec = usec / 1000000;
359 tm.tv_nsec = (usec % 1000000) * 1000;
360 if ( pthread_cond_timedwait( &m_condition, &m_mutex, &tm ) )
361 // Stop waiting if error (timed out)
364 frame = ( mlt_frame ) mlt_deque_pop_front( m_queue );
365 pthread_mutex_unlock( &m_mutex );
369 mlt_cache_put( m_cache, (void*) position, mlt_frame_clone( frame, 1 ), 0,
370 (mlt_destructor) mlt_frame_close );
373 // Set frame timestamp and properties
376 mlt_profile profile = mlt_service_profile( MLT_PRODUCER_SERVICE( getProducer() ) );
377 mlt_properties properties = MLT_FRAME_PROPERTIES( frame );
378 mlt_properties_set_int( properties, "progressive", profile->progressive );
379 mlt_properties_set_int( properties, "meta.media.progressive", profile->progressive );
380 mlt_properties_set_int( properties, "top_field_first", m_topFieldFirst );
381 mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
382 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", profile->sample_aspect_num );
383 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", profile->sample_aspect_den );
384 mlt_properties_set_int( properties, "meta.media.frame_rate_num", profile->frame_rate_num );
385 mlt_properties_set_int( properties, "meta.media.frame_rate_den", profile->frame_rate_den );
386 mlt_properties_set_int( properties, "width", profile->width );
387 mlt_properties_set_int( properties, "meta.media.width", profile->width );
388 mlt_properties_set_int( properties, "height", profile->height );
389 mlt_properties_set_int( properties, "meta.media.height", profile->height );
390 mlt_properties_set_int( properties, "format", mlt_image_yuv422 );
391 mlt_properties_set_int( properties, "colorspace", m_colorspace );
392 mlt_properties_set_int( properties, "meta.media.colorspace", m_colorspace );
393 mlt_properties_set_int( properties, "audio_frequency", 48000 );
394 mlt_properties_set_int( properties, "audio_channels",
395 mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "channels" ) );
398 mlt_log_warning( getProducer(), "buffer underrun\n" );
403 // *** DeckLink API implementation of IDeckLinkInputCallback *** //
405 // IUnknown needs only a dummy implementation
406 virtual HRESULT STDMETHODCALLTYPE QueryInterface( REFIID iid, LPVOID *ppv )
407 { return E_NOINTERFACE; }
408 virtual ULONG STDMETHODCALLTYPE AddRef()
410 virtual ULONG STDMETHODCALLTYPE Release()
413 /************************* DeckLink API Delegate Methods *****************************/
415 virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(
416 IDeckLinkVideoInputFrame* video,
417 IDeckLinkAudioInputPacket* audio )
419 if ( mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "preview" ) &&
420 mlt_producer_get_speed( getProducer() ) == 0.0 && !mlt_deque_count( m_queue ))
422 pthread_cond_broadcast( &m_condition );
427 mlt_frame frame = mlt_frame_init( MLT_PRODUCER_SERVICE( getProducer() ) );
432 if ( !( video->GetFlags() & bmdFrameHasNoInputSource ) )
434 int size = video->GetRowBytes() * ( video->GetHeight() + m_vancLines );
435 void* image = mlt_pool_alloc( size );
437 unsigned char* p = (unsigned char*) image;
440 // Initialize VANC lines to nominal black
448 if ( m_vancLines > 0 )
450 IDeckLinkVideoFrameAncillary* vanc = 0;
451 if ( video->GetAncillaryData( &vanc ) == S_OK && vanc )
453 for ( int i = 1; i < m_vancLines + 1; i++ )
455 if ( vanc->GetBufferForVerticalBlankingLine( i, &buffer ) == S_OK )
456 swab( (char*) buffer, (char*) image + ( i - 1 ) * video->GetRowBytes(), video->GetRowBytes() );
458 mlt_log_debug( getProducer(), "failed capture vanc line %d\n", i );
465 video->GetBytes( &buffer );
466 if ( image && buffer )
468 size = video->GetRowBytes() * video->GetHeight();
469 swab( (char*) buffer, (char*) image + m_vancLines * video->GetRowBytes(), size );
470 mlt_frame_set_image( frame, (uint8_t*) image, size, mlt_pool_release );
474 mlt_log_verbose( getProducer(), "no video\n" );
475 mlt_pool_release( image );
480 mlt_log_verbose( getProducer(), "no signal\n" );
481 mlt_frame_close( frame );
486 IDeckLinkTimecode* timecode = 0;
487 if ( video->GetTimecode( bmdTimecodeVITC, &timecode ) == S_OK && timecode )
489 const char* timecodeString = 0;
492 if ( timecode->GetString( (BSTR*) &timecodeString ) == S_OK )
494 if ( timecode->GetString( &timecodeString ) == S_OK )
497 mlt_properties_set( MLT_FRAME_PROPERTIES( frame ), "meta.attr.vitc.markup", timecodeString );
498 mlt_log_debug( getProducer(), "timecode %s\n", timecodeString );
500 if ( timecodeString )
501 free( (void*) timecodeString );
502 SAFE_RELEASE( timecode );
507 mlt_log_verbose( getProducer(), "no video\n" );
508 mlt_frame_close( frame );
513 if ( frame && audio )
515 int channels = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "channels" );
516 int size = audio->GetSampleFrameCount() * channels * sizeof(int16_t);
517 mlt_audio_format format = mlt_audio_s16;
518 void* pcm = mlt_pool_alloc( size );
521 audio->GetBytes( &buffer );
524 memcpy( pcm, buffer, size );
525 mlt_frame_set_audio( frame, pcm, format, size, mlt_pool_release );
526 mlt_properties_set_int( MLT_FRAME_PROPERTIES(frame), "audio_samples", audio->GetSampleFrameCount() );
530 mlt_log_verbose( getProducer(), "no audio\n" );
531 mlt_pool_release( pcm );
536 mlt_log_verbose( getProducer(), "no audio\n" );
539 // Put frame in queue
542 int queueMax = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "buffer" );
543 pthread_mutex_lock( &m_mutex );
544 if ( mlt_deque_count( m_queue ) < queueMax )
546 mlt_deque_push_back( m_queue, frame );
547 pthread_cond_broadcast( &m_condition );
551 mlt_frame_close( frame );
552 mlt_properties_set_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "dropped", ++m_dropped );
553 mlt_log_warning( getProducer(), "frame dropped %d\n", m_dropped );
555 pthread_mutex_unlock( &m_mutex );
561 virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(
562 BMDVideoInputFormatChangedEvents events,
563 IDeckLinkDisplayMode* mode,
564 BMDDetectedVideoInputFormatFlags flags )
566 mlt_profile profile = mlt_service_profile( MLT_PRODUCER_SERVICE( getProducer() ) );
567 if ( events & bmdVideoInputDisplayModeChanged )
569 BMDTimeValue duration;
570 BMDTimeScale timescale;
571 mode->GetFrameRate( &duration, ×cale );
572 profile->width = mode->GetWidth();
573 profile->height = mode->GetHeight() + m_vancLines;
574 profile->frame_rate_num = timescale;
575 profile->frame_rate_den = duration;
576 if ( profile->width == 720 )
578 if ( profile->height == 576 )
580 profile->sample_aspect_num = 16;
581 profile->sample_aspect_den = 15;
585 profile->sample_aspect_num = 8;
586 profile->sample_aspect_den = 9;
588 profile->display_aspect_num = 4;
589 profile->display_aspect_den = 3;
593 profile->sample_aspect_num = 1;
594 profile->sample_aspect_den = 1;
595 profile->display_aspect_num = 16;
596 profile->display_aspect_den = 9;
598 free( profile->description );
599 profile->description = strdup( "decklink" );
600 mlt_log_verbose( getProducer(), "format changed %dx%d %.3f fps\n",
601 profile->width, profile->height, (double) profile->frame_rate_num / profile->frame_rate_den );
603 if ( events & bmdVideoInputFieldDominanceChanged )
605 profile->progressive = mode->GetFieldDominance() == bmdProgressiveFrame;
606 m_topFieldFirst = mode->GetFieldDominance() == bmdUpperFieldFirst;
607 mlt_log_verbose( getProducer(), "field dominance changed prog %d tff %d\n",
608 profile->progressive, m_topFieldFirst );
610 if ( events & bmdVideoInputColorspaceChanged )
612 profile->colorspace = m_colorspace =
613 ( mode->GetFlags() & bmdDisplayModeColorspaceRec709 ) ? 709 : 601;
614 mlt_log_verbose( getProducer(), "colorspace changed %d\n", profile->colorspace );
620 static int get_audio( mlt_frame frame, int16_t **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
622 return mlt_frame_get_audio( frame, (void**) buffer, format, frequency, channels, samples );
625 static int get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
627 return mlt_frame_get_image( frame, buffer, format, width, height, writable );
630 static int get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
632 DeckLinkProducer* decklink = (DeckLinkProducer*) producer->child;
633 mlt_position pos = mlt_producer_position( producer );
634 mlt_position end = mlt_producer_get_playtime( producer );
635 end = ( mlt_producer_get_length( producer ) < end ? mlt_producer_get_length( producer ) : end ) - 1;
638 if ( !decklink && pos < end )
640 producer->child = decklink = new DeckLinkProducer();
641 decklink->setProducer( producer );
642 decklink->open( mlt_properties_get_int( MLT_PRODUCER_PROPERTIES(producer), "resource" ) );
648 decklink->start( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) );
650 // Get the next frame from the decklink object
651 if ( ( *frame = decklink->getFrame() ))
653 // Add audio and video getters
654 mlt_frame_push_audio( *frame, (void*) get_audio );
655 mlt_frame_push_get_image( *frame, get_image );
659 *frame = mlt_frame_init( MLT_PRODUCER_SERVICE(producer) );
661 // Calculate the next timecode
662 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
663 mlt_producer_prepare_next( producer );
665 // Close DeckLink if at end
666 if ( pos >= end && decklink )
670 producer->child = NULL;
676 static void producer_close( mlt_producer producer )
678 delete (DeckLinkProducer*) producer->child;
679 producer->close = NULL;
680 mlt_producer_close( producer );
685 /** Initialise the producer.
688 mlt_producer producer_decklink_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
690 // Allocate the producer
691 DeckLinkProducer* decklink = new DeckLinkProducer();
692 mlt_producer producer = (mlt_producer) calloc( 1, sizeof( *producer ) );
694 // If allocated and initializes
695 if ( decklink && !mlt_producer_init( producer, decklink ) )
697 if ( decklink->listDevices( MLT_PRODUCER_PROPERTIES( producer ) ) &&
698 decklink->open( arg? atoi( arg ) : 0 ) )
700 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
702 // Close DeckLink and defer re-open to get_frame
704 producer->child = NULL;
707 producer->close = (mlt_destructor) producer_close;
708 producer->get_frame = get_frame;
711 mlt_properties_set( properties, "resource", (arg && strcmp( arg, ""))? arg : "0" );
712 mlt_properties_set_int( properties, "channels", 2 );
713 mlt_properties_set_int( properties, "buffer", 25 );
714 mlt_properties_set_int( properties, "prefill", 25 );
716 // These properties effectively make it infinite.
717 mlt_properties_set_int( properties, "length", INT_MAX );
718 mlt_properties_set_int( properties, "out", INT_MAX - 1 );
719 mlt_properties_set( properties, "eof", "loop" );