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 class DeckLinkProducer
35 : public IDeckLinkInputCallback
38 mlt_producer m_producer;
39 IDeckLink* m_decklink;
40 IDeckLinkInput* m_decklinkInput;
42 pthread_mutex_t m_mutex;
43 pthread_cond_t m_condition;
52 BMDDisplayMode getDisplayMode( mlt_profile profile, int vancLines )
54 IDeckLinkDisplayModeIterator* iter;
55 IDeckLinkDisplayMode* mode;
56 BMDDisplayMode result = (BMDDisplayMode) bmdDisplayModeNotSupported;
58 if ( m_decklinkInput->GetDisplayModeIterator( &iter ) == S_OK )
60 while ( !result && iter->Next( &mode ) == S_OK )
62 int width = mode->GetWidth();
63 int height = mode->GetHeight();
64 BMDTimeValue duration;
65 BMDTimeScale timescale;
66 mode->GetFrameRate( &duration, ×cale );
67 double fps = (double) timescale / duration;
68 int p = mode->GetFieldDominance() == bmdProgressiveFrame;
69 m_topFieldFirst = mode->GetFieldDominance() == bmdUpperFieldFirst;
70 m_colorspace = ( mode->GetFlags() & bmdDisplayModeColorspaceRec709 ) ? 709 : 601;
71 mlt_log_verbose( getProducer(), "BMD mode %dx%d %.3f fps prog %d tff %d\n", width, height, fps, p, m_topFieldFirst );
73 if ( width == profile->width && p == profile->progressive
74 && ( height + vancLines == profile->height || ( height == 486 && profile->height == 480 + vancLines ) )
75 && fps == mlt_profile_fps( profile ) )
76 result = mode->GetDisplayMode();
85 void setProducer( mlt_producer producer )
86 { m_producer = producer; }
88 mlt_producer getProducer() const
89 { return m_producer; }
96 mlt_deque_close( m_queue );
97 pthread_mutex_destroy( &m_mutex );
98 pthread_cond_destroy( &m_condition );
99 mlt_cache_close( m_cache );
101 if ( m_decklinkInput )
102 m_decklinkInput->Release();
104 m_decklink->Release();
107 bool open( unsigned card = 0 )
109 IDeckLinkIterator* decklinkIterator = NULL;
113 HRESULT result = CoInitialize( NULL );
114 if ( FAILED( result ) )
115 throw "COM initialization failed";
116 result = CoCreateInstance( CLSID_CDeckLinkIterator, NULL, CLSCTX_ALL, IID_IDeckLinkIterator, (void**) &decklinkIterator );
117 if ( FAILED( result ) )
118 throw "The DeckLink drivers are not installed.";
120 decklinkIterator = CreateDeckLinkIteratorInstance();
121 if ( !decklinkIterator )
122 throw "The DeckLink drivers are not installed.";
125 // Connect to the Nth DeckLink instance
128 if ( decklinkIterator->Next( &m_decklink ) != S_OK )
129 throw "DeckLink card not found.";
130 } while ( ++i <= card );
131 decklinkIterator->Release();
133 // Get the input interface
134 if ( m_decklink->QueryInterface( IID_IDeckLinkInput, (void**) &m_decklinkInput ) != S_OK )
135 throw "No DeckLink cards support input.";
137 // Provide this class as a delegate to the input callback
138 m_decklinkInput->SetCallback( this );
140 // Initialize other members
141 pthread_mutex_init( &m_mutex, NULL );
142 pthread_cond_init( &m_condition, NULL );
143 m_queue = mlt_deque_init();
146 m_isBuffering = true;
147 m_cache = mlt_cache_init();
149 // 3 covers YADIF and increasing framerate use cases
150 mlt_cache_set_size( m_cache, 3 );
152 catch ( const char *error )
154 if ( decklinkIterator )
155 decklinkIterator->Release();
156 mlt_log_error( getProducer(), "%s\n", error );
162 bool start( mlt_profile profile = 0 )
168 // Initialize some members
169 m_vancLines = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "vanc" );
170 if ( m_vancLines == -1 )
171 m_vancLines = profile->height <= 512 ? 26 : 32;
174 profile = mlt_service_profile( MLT_PRODUCER_SERVICE( getProducer() ) );
176 // Get the display mode
177 BMDDisplayMode displayMode = getDisplayMode( profile, m_vancLines );
178 if ( displayMode == (BMDDisplayMode) bmdDisplayModeNotSupported )
180 mlt_log_info( getProducer(), "profile = %dx%d %f fps %s\n", profile->width, profile->height,
181 mlt_profile_fps( profile ), profile->progressive? "progressive" : "interlace" );
182 throw "Profile is not compatible with decklink.";
185 // Determine if supports input format detection
187 BOOL doesDetectFormat = FALSE;
189 bool doesDetectFormat = false;
191 IDeckLinkAttributes *decklinkAttributes = 0;
192 if ( m_decklink->QueryInterface( IID_IDeckLinkAttributes, (void**) &decklinkAttributes ) == S_OK )
194 if ( decklinkAttributes->GetFlag( BMDDeckLinkSupportsInputFormatDetection, &doesDetectFormat ) != S_OK )
195 doesDetectFormat = false;
196 decklinkAttributes->Release();
198 mlt_log_verbose( getProducer(), "%s format detection\n", doesDetectFormat ? "supports" : "does not support" );
200 // Enable video capture
201 BMDPixelFormat pixelFormat = bmdFormat8BitYUV;
202 BMDVideoInputFlags flags = doesDetectFormat ? bmdVideoInputEnableFormatDetection : bmdVideoInputFlagDefault;
203 if ( S_OK != m_decklinkInput->EnableVideoInput( displayMode, pixelFormat, flags ) )
204 throw "Failed to enable video capture.";
206 // Enable audio capture
207 BMDAudioSampleRate sampleRate = bmdAudioSampleRate48kHz;
208 BMDAudioSampleType sampleType = bmdAudioSampleType16bitInteger;
209 int channels = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "channels" );
210 if ( S_OK != m_decklinkInput->EnableAudioInput( sampleRate, sampleType, channels ) )
211 throw "Failed to enable audio capture.";
215 mlt_properties_set_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "dropped", m_dropped );
216 m_started = m_decklinkInput->StartStreams() == S_OK;
218 throw "Failed to start capture.";
220 catch ( const char *error )
222 m_decklinkInput->DisableVideoInput();
223 mlt_log_error( getProducer(), "%s\n", error );
235 // Release the wait in getFrame
236 pthread_mutex_lock( &m_mutex );
237 pthread_cond_broadcast( &m_condition );
238 pthread_mutex_unlock( &m_mutex );
240 m_decklinkInput->StopStreams();
243 pthread_mutex_lock( &m_mutex );
244 while ( mlt_frame frame = (mlt_frame) mlt_deque_pop_back( m_queue ) )
245 mlt_frame_close( frame );
246 pthread_mutex_unlock( &m_mutex );
251 mlt_frame frame = NULL;
254 double fps = mlt_producer_get_fps( getProducer() );
255 mlt_position position = mlt_producer_position( getProducer() );
256 mlt_cache_item cached = mlt_cache_get( m_cache, (void*) position );
258 // Allow the buffer to fill to the requested initial buffer level.
261 int prefill = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "prefill" );
262 int buffer = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "buffer" );
264 m_isBuffering = false;
265 prefill = prefill > buffer ? buffer : prefill;
266 pthread_mutex_lock( &m_mutex );
267 while ( mlt_deque_count( m_queue ) < prefill )
269 // Wait up to buffer/fps seconds
270 gettimeofday( &now, NULL );
271 long usec = now.tv_sec * 1000000 + now.tv_usec;
272 usec += 1000000 * buffer / fps;
273 tm.tv_sec = usec / 1000000;
274 tm.tv_nsec = (usec % 1000000) * 1000;
275 if ( pthread_cond_timedwait( &m_condition, &m_mutex, &tm ) )
278 pthread_mutex_unlock( &m_mutex );
283 // Copy cached frame instead of pulling from queue
284 frame = mlt_frame_clone( (mlt_frame) mlt_cache_item_data( cached, NULL ), 0 );
285 mlt_cache_item_close( cached );
289 // Wait if queue is empty
290 pthread_mutex_lock( &m_mutex );
291 while ( mlt_deque_count( m_queue ) < 1 )
293 // Wait up to twice frame duration
294 gettimeofday( &now, NULL );
295 long usec = now.tv_sec * 1000000 + now.tv_usec;
296 usec += 2000000 / fps;
297 tm.tv_sec = usec / 1000000;
298 tm.tv_nsec = (usec % 1000000) * 1000;
299 if ( pthread_cond_timedwait( &m_condition, &m_mutex, &tm ) )
300 // Stop waiting if error (timed out)
303 frame = ( mlt_frame ) mlt_deque_pop_front( m_queue );
304 pthread_mutex_unlock( &m_mutex );
308 mlt_cache_put( m_cache, (void*) position, mlt_frame_clone( frame, 1 ), 0,
309 (mlt_destructor) mlt_frame_close );
312 // Set frame timestamp and properties
315 mlt_profile profile = mlt_service_profile( MLT_PRODUCER_SERVICE( getProducer() ) );
316 mlt_properties properties = MLT_FRAME_PROPERTIES( frame );
317 mlt_properties_set_int( properties, "progressive", profile->progressive );
318 mlt_properties_set_int( properties, "meta.media.progressive", profile->progressive );
319 mlt_properties_set_int( properties, "top_field_first", m_topFieldFirst );
320 mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
321 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", profile->sample_aspect_num );
322 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", profile->sample_aspect_den );
323 mlt_properties_set_int( properties, "meta.media.frame_rate_num", profile->frame_rate_num );
324 mlt_properties_set_int( properties, "meta.media.frame_rate_den", profile->frame_rate_den );
325 mlt_properties_set_int( properties, "width", profile->width );
326 mlt_properties_set_int( properties, "real_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, "real_height", profile->height );
330 mlt_properties_set_int( properties, "meta.media.height", profile->height );
331 mlt_properties_set_int( properties, "format", mlt_image_yuv422 );
332 mlt_properties_set_int( properties, "colorspace", m_colorspace );
333 mlt_properties_set_int( properties, "meta.media.colorspace", m_colorspace );
334 mlt_properties_set_int( properties, "audio_frequency", 48000 );
335 mlt_properties_set_int( properties, "audio_channels",
336 mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "channels" ) );
339 mlt_log_warning( getProducer(), "buffer underrun\n" );
344 // *** DeckLink API implementation of IDeckLinkInputCallback *** //
346 // IUnknown needs only a dummy implementation
347 virtual HRESULT STDMETHODCALLTYPE QueryInterface( REFIID iid, LPVOID *ppv )
348 { return E_NOINTERFACE; }
349 virtual ULONG STDMETHODCALLTYPE AddRef()
351 virtual ULONG STDMETHODCALLTYPE Release()
354 /************************* DeckLink API Delegate Methods *****************************/
356 virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(
357 IDeckLinkVideoInputFrame* video,
358 IDeckLinkAudioInputPacket* audio )
360 if ( 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 const char* timecodeString = 0;
432 if ( timecode->GetString( (BSTR*) &timecodeString ) == S_OK )
434 if ( timecode->GetString( &timecodeString ) == S_OK )
437 mlt_properties_set( MLT_FRAME_PROPERTIES( frame ), "meta.attr.vitc.markup", timecodeString );
438 mlt_log_debug( getProducer(), "timecode %s\n", timecodeString );
440 if ( timecodeString )
441 free( (void*) timecodeString );
447 mlt_log_verbose( getProducer(), "no video\n" );
448 mlt_frame_close( frame );
453 if ( frame && audio )
455 int channels = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "channels" );
456 int size = audio->GetSampleFrameCount() * channels * sizeof(int16_t);
457 mlt_audio_format format = mlt_audio_s16;
458 void* pcm = mlt_pool_alloc( size );
461 audio->GetBytes( &buffer );
464 memcpy( pcm, buffer, size );
465 mlt_frame_set_audio( frame, pcm, format, size, mlt_pool_release );
466 mlt_properties_set_int( MLT_FRAME_PROPERTIES(frame), "audio_samples", audio->GetSampleFrameCount() );
470 mlt_log_verbose( getProducer(), "no audio\n" );
471 mlt_pool_release( pcm );
476 mlt_log_verbose( getProducer(), "no audio\n" );
479 // Put frame in queue
482 int queueMax = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "buffer" );
483 pthread_mutex_lock( &m_mutex );
484 if ( mlt_deque_count( m_queue ) < queueMax )
486 mlt_deque_push_back( m_queue, frame );
487 pthread_cond_broadcast( &m_condition );
491 mlt_frame_close( frame );
492 mlt_properties_set_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "dropped", ++m_dropped );
493 mlt_log_warning( getProducer(), "frame dropped %d\n", m_dropped );
495 pthread_mutex_unlock( &m_mutex );
501 virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(
502 BMDVideoInputFormatChangedEvents events,
503 IDeckLinkDisplayMode* mode,
504 BMDDetectedVideoInputFormatFlags flags )
506 mlt_profile profile = mlt_service_profile( MLT_PRODUCER_SERVICE( getProducer() ) );
507 if ( events & bmdVideoInputDisplayModeChanged )
509 BMDTimeValue duration;
510 BMDTimeScale timescale;
511 mode->GetFrameRate( &duration, ×cale );
512 profile->width = mode->GetWidth();
513 profile->height = mode->GetHeight() + m_vancLines;
514 profile->frame_rate_num = timescale;
515 profile->frame_rate_den = duration;
516 if ( profile->width == 720 )
518 if ( profile->height == 576 )
520 profile->sample_aspect_num = 16;
521 profile->sample_aspect_den = 15;
525 profile->sample_aspect_num = 8;
526 profile->sample_aspect_den = 9;
528 profile->display_aspect_num = 4;
529 profile->display_aspect_den = 3;
533 profile->sample_aspect_num = 1;
534 profile->sample_aspect_den = 1;
535 profile->display_aspect_num = 16;
536 profile->display_aspect_den = 9;
538 free( profile->description );
539 profile->description = strdup( "decklink" );
540 mlt_log_verbose( getProducer(), "format changed %dx%d %.3f fps\n",
541 profile->width, profile->height, (double) profile->frame_rate_num / profile->frame_rate_den );
543 if ( events & bmdVideoInputFieldDominanceChanged )
545 profile->progressive = mode->GetFieldDominance() == bmdProgressiveFrame;
546 m_topFieldFirst = mode->GetFieldDominance() == bmdUpperFieldFirst;
547 mlt_log_verbose( getProducer(), "field dominance changed prog %d tff %d\n",
548 profile->progressive, m_topFieldFirst );
550 if ( events & bmdVideoInputColorspaceChanged )
552 profile->colorspace = m_colorspace =
553 ( mode->GetFlags() & bmdDisplayModeColorspaceRec709 ) ? 709 : 601;
554 mlt_log_verbose( getProducer(), "colorspace changed %d\n", profile->colorspace );
560 static int get_audio( mlt_frame frame, int16_t **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
562 return mlt_frame_get_audio( frame, (void**) buffer, format, frequency, channels, samples );
565 static int get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
567 return mlt_frame_get_image( frame, buffer, format, width, height, writable );
570 static int get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
572 DeckLinkProducer* decklink = (DeckLinkProducer*) producer->child;
573 mlt_position pos = mlt_producer_position( producer );
574 mlt_position end = mlt_producer_get_playtime( producer );
575 end = ( mlt_producer_get_length( producer ) < end ? mlt_producer_get_length( producer ) : end ) - 1;
578 if ( !decklink && pos < end )
580 producer->child = decklink = new DeckLinkProducer();
581 decklink->setProducer( producer );
582 decklink->open( mlt_properties_get_int( MLT_PRODUCER_PROPERTIES(producer), "resource" ) );
588 decklink->start( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) );
590 // Get the next frame from the decklink object
591 if ( ( *frame = decklink->getFrame() ))
593 // Add audio and video getters
594 mlt_frame_push_audio( *frame, (void*) get_audio );
595 mlt_frame_push_get_image( *frame, get_image );
599 *frame = mlt_frame_init( MLT_PRODUCER_SERVICE(producer) );
601 // Calculate the next timecode
602 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
603 mlt_producer_prepare_next( producer );
605 // Close DeckLink if at end
606 if ( pos >= end && decklink )
610 producer->child = NULL;
616 static void producer_close( mlt_producer producer )
618 delete (DeckLinkProducer*) producer->child;
619 producer->close = NULL;
620 mlt_producer_close( producer );
625 /** Initialise the producer.
628 mlt_producer producer_decklink_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
630 // Allocate the producer
631 DeckLinkProducer* decklink = new DeckLinkProducer();
632 mlt_producer producer = (mlt_producer) calloc( 1, sizeof( *producer ) );
634 // If allocated and initializes
635 if ( decklink && !mlt_producer_init( producer, decklink ) )
637 if ( decklink->open( arg? atoi( arg ) : 0 ) )
639 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
641 // Close DeckLink and defer re-open to get_frame
643 producer->child = NULL;
646 producer->close = (mlt_destructor) producer_close;
647 producer->get_frame = get_frame;
650 mlt_properties_set( properties, "resource", (arg && strcmp( arg, ""))? arg : "0" );
651 mlt_properties_set_int( properties, "channels", 2 );
652 mlt_properties_set_int( properties, "buffer", 25 );
653 mlt_properties_set_int( properties, "prefill", 25 );
655 // These properties effectively make it infinite.
656 mlt_properties_set_int( properties, "length", INT_MAX );
657 mlt_properties_set_int( properties, "out", INT_MAX - 1 );
658 mlt_properties_set( properties, "eof", "loop" );