2 * consumer_decklink.c -- output through Blackmagic Design DeckLink
3 * Copyright (C) 2010 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 #define __STDC_FORMAT_MACROS /* see inttypes.h */
21 #include <framework/mlt.h>
31 static const unsigned PREROLL_MINIMUM = 3;
33 class DeckLinkConsumer
34 : public IDeckLinkVideoOutputCallback
37 mlt_consumer_s m_consumer;
38 IDeckLink* m_deckLink;
39 IDeckLinkOutput* m_deckLinkOutput;
40 IDeckLinkDisplayMode* m_displayMode;
43 BMDTimeValue m_duration;
44 BMDTimeScale m_timescale;
49 IDeckLinkMutableVideoFrame* m_decklinkFrame;
52 IDeckLinkKeyer* m_deckLinkKeyer;
53 bool m_terminate_on_pause;
57 pthread_t m_prerollThread;
59 IDeckLinkDisplayMode* getDisplayMode()
61 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( getConsumer() ) );
62 IDeckLinkDisplayModeIterator* iter = NULL;
63 IDeckLinkDisplayMode* mode = NULL;
64 IDeckLinkDisplayMode* result = 0;
66 if ( m_deckLinkOutput->GetDisplayModeIterator( &iter ) == S_OK )
68 while ( !result && iter->Next( &mode ) == S_OK )
70 m_width = mode->GetWidth();
71 m_height = mode->GetHeight();
72 mode->GetFrameRate( &m_duration, &m_timescale );
73 m_fps = (double) m_timescale / m_duration;
74 int p = mode->GetFieldDominance() == bmdProgressiveFrame;
75 mlt_log_verbose( getConsumer(), "BMD mode %dx%d %.3f fps prog %d\n", m_width, m_height, m_fps, p );
77 if ( m_width == profile->width && p == profile->progressive
78 && (int) m_fps == (int) mlt_profile_fps( profile )
79 && ( m_height == profile->height || ( m_height == 486 && profile->height == 480 ) ) )
91 mlt_consumer getConsumer()
92 { return &m_consumer; }
97 m_deckLinkKeyer = NULL;
98 m_deckLinkOutput = NULL;
100 m_decklinkFrame = NULL;
105 SAFE_RELEASE( m_displayMode );
106 SAFE_RELEASE( m_deckLinkKeyer );
107 SAFE_RELEASE( m_deckLinkOutput );
108 SAFE_RELEASE( m_deckLink );
111 bool open( unsigned card = 0 )
115 IDeckLinkIterator* deckLinkIterator = NULL;
116 HRESULT result = CoInitialize( NULL );
117 if ( FAILED( result ) )
119 mlt_log_error( getConsumer(), "COM initialization failed\n" );
122 result = CoCreateInstance( CLSID_CDeckLinkIterator, NULL, CLSCTX_ALL, IID_IDeckLinkIterator, (void**) &deckLinkIterator );
123 if ( FAILED( result ) )
125 mlt_log_error( getConsumer(), "The DeckLink drivers not installed.\n" );
129 IDeckLinkIterator* deckLinkIterator = CreateDeckLinkIteratorInstance();
131 if ( !deckLinkIterator )
133 mlt_log_error( getConsumer(), "The DeckLink drivers not installed.\n" );
138 // Connect to the Nth DeckLink instance
139 for ( i = 0; deckLinkIterator->Next( &m_deckLink ) == S_OK ; i++)
144 SAFE_RELEASE( m_deckLink );
146 SAFE_RELEASE( deckLinkIterator );
149 mlt_log_error( getConsumer(), "DeckLink card not found\n" );
153 // Obtain the audio/video output interface (IDeckLinkOutput)
154 if ( m_deckLink->QueryInterface( IID_IDeckLinkOutput, (void**)&m_deckLinkOutput ) != S_OK )
156 mlt_log_error( getConsumer(), "No DeckLink cards support output\n" );
157 SAFE_RELEASE( m_deckLink );
161 // Get the keyer interface
162 IDeckLinkAttributes *deckLinkAttributes = 0;
163 if ( m_deckLink->QueryInterface( IID_IDeckLinkAttributes, (void**) &deckLinkAttributes ) == S_OK )
170 if ( deckLinkAttributes->GetFlag( BMDDeckLinkSupportsInternalKeying, &flag ) == S_OK && flag )
172 if ( m_deckLink->QueryInterface( IID_IDeckLinkKeyer, (void**) &m_deckLinkKeyer ) != S_OK )
174 mlt_log_error( getConsumer(), "Failed to get keyer\n" );
175 SAFE_RELEASE( m_deckLinkOutput );
176 SAFE_RELEASE( m_deckLink );
180 SAFE_RELEASE( deckLinkAttributes );
183 // Provide this class as a delegate to the audio and video output interfaces
184 m_deckLinkOutput->SetScheduledFrameCompletionCallback( this );
190 void* preroll_thread()
192 mlt_properties properties = MLT_CONSUMER_PROPERTIES( getConsumer() );
195 for ( unsigned i = 0; i < m_preroll && mlt_properties_get_int( properties, "running" ); i++ )
196 ScheduleNextFrame( true );
198 // start scheduled playback
199 if ( mlt_properties_get_int( properties, "running" ) )
200 m_deckLinkOutput->StartScheduledPlayback( 0, m_timescale, 1.0 );
205 static void* preroll_thread_proxy( void* arg )
207 DeckLinkConsumer* self = static_cast< DeckLinkConsumer* >( arg );
208 return self->preroll_thread();
211 bool start( unsigned preroll )
213 mlt_properties properties = MLT_CONSUMER_PROPERTIES( getConsumer() );
215 // Initialize members
218 m_decklinkFrame = NULL;
219 preroll = preroll < PREROLL_MINIMUM ? PREROLL_MINIMUM : preroll;
220 m_channels = mlt_properties_get_int( properties, "channels" );
221 m_isAudio = !mlt_properties_get_int( properties, "audio_off" );
222 m_terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
225 m_displayMode = getDisplayMode();
226 if ( !m_displayMode )
228 mlt_log_error( getConsumer(), "Profile is not compatible with decklink.\n" );
233 if ( m_deckLinkKeyer && ( m_isKeyer = mlt_properties_get_int( properties, "keyer" ) ) )
235 bool external = ( m_isKeyer == 2 );
236 double level = mlt_properties_get_double( properties, "keyer_level" );
238 if ( m_deckLinkKeyer->Enable( external ) != S_OK )
239 mlt_log_error( getConsumer(), "Failed to enable %s keyer\n",
240 external ? "external" : "internal" );
241 m_deckLinkKeyer->SetLevel( level <= 1 ? ( level > 0 ? 255 * level : 255 ) : 255 );
243 else if ( m_deckLinkKeyer )
245 m_deckLinkKeyer->Disable();
248 // Set the video output mode
249 if ( S_OK != m_deckLinkOutput->EnableVideoOutput( m_displayMode->GetDisplayMode(), bmdVideoOutputFlagDefault ) )
251 mlt_log_error( getConsumer(), "Failed to enable video output\n" );
255 // Set the audio output mode
258 m_deckLinkOutput->DisableAudioOutput();
261 if ( S_OK != m_deckLinkOutput->EnableAudioOutput( bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger,
262 m_channels, bmdAudioOutputStreamTimestamped ) )
264 mlt_log_error( getConsumer(), "Failed to enable audio output\n" );
272 // Set the running state
273 mlt_properties_set_int( properties, "running", 1 );
275 // Do preroll in thread to ensure asynchronicity of mlt_consumer_start().
276 pthread_create( &m_prerollThread, NULL, preroll_thread_proxy, this );
283 mlt_properties properties = MLT_CONSUMER_PROPERTIES( getConsumer() );
284 bool wasRunning = !!mlt_properties_get_int( properties, "running" );
286 // set running state is 0
287 mlt_properties_set_int( properties, "running", 0 );
290 pthread_join( m_prerollThread, NULL );
292 // Stop the audio and video output streams immediately
293 if ( m_deckLinkOutput )
295 m_deckLinkOutput->StopScheduledPlayback( 0, 0, 0 );
296 m_deckLinkOutput->DisableAudioOutput();
297 m_deckLinkOutput->DisableVideoOutput();
300 // release decklink frame
301 SAFE_RELEASE( m_decklinkFrame );
303 mlt_consumer_stopped( getConsumer() );
308 void renderAudio( mlt_frame frame )
310 mlt_audio_format format = mlt_audio_s16;
311 int frequency = bmdAudioSampleRate48kHz;
312 int samples = mlt_sample_calculator( m_fps, frequency, m_count );
315 if ( !mlt_frame_get_audio( frame, (void**) &pcm, &format, &frequency, &m_channels, &samples ) )
318 unsigned long written = 0;
320 uint32_t written = 0;
322 BMDTimeValue streamTime = m_count * frequency * m_duration / m_timescale;
323 m_deckLinkOutput->GetBufferedAudioSampleFrameCount( &written );
324 if ( written > (m_preroll + 1) * samples )
326 mlt_log_verbose( getConsumer(), "renderAudio: will flush %lu audiosamples\n", written );
327 m_deckLinkOutput->FlushBufferedAudioSamples();
330 m_deckLinkOutput->ScheduleAudioSamples( pcm, samples, streamTime, frequency, (unsigned long*) &written );
332 m_deckLinkOutput->ScheduleAudioSamples( pcm, samples, streamTime, frequency, &written );
335 if ( written != (uint32_t) samples )
336 mlt_log_verbose( getConsumer(), "renderAudio: samples=%d, written=%lu\n", samples, written );
340 bool createFrame( IDeckLinkMutableVideoFrame** decklinkFrame )
342 BMDPixelFormat format = m_isKeyer? bmdFormat8BitARGB : bmdFormat8BitYUV;
343 IDeckLinkMutableVideoFrame* frame = 0;
345 int stride = m_width * ( m_isKeyer? 4 : 2 );
347 *decklinkFrame = NULL;
349 // Generate a DeckLink video frame
350 if ( S_OK != m_deckLinkOutput->CreateVideoFrame( m_width, m_height,
351 stride, format, bmdFrameFlagDefault, &frame ) )
353 mlt_log_verbose( getConsumer(), "Failed to create video frame\n" );
358 // Make the first line black for field order correction.
359 if ( S_OK == frame->GetBytes( (void**) &buffer ) && buffer )
363 memset( buffer, 0, stride );
365 else for ( int i = 0; i < m_width; i++ )
372 *decklinkFrame = frame;
377 void renderVideo( mlt_frame frame )
379 mlt_image_format format = m_isKeyer? mlt_image_rgb24a : mlt_image_yuv422;
381 int rendered = mlt_properties_get_int( MLT_FRAME_PROPERTIES(frame), "rendered");
382 int height = m_height;
384 if ( rendered && !mlt_frame_get_image( frame, &image, &format, &m_width, &height, 0 ) )
387 int stride = m_width * ( m_isKeyer? 4 : 2 );
389 SAFE_RELEASE( m_decklinkFrame );
390 if ( createFrame( &m_decklinkFrame ) )
391 m_decklinkFrame->GetBytes( (void**) &buffer );
395 int progressive = mlt_properties_get_int( MLT_FRAME_PROPERTIES( frame ), "progressive" );
397 // NTSC SDI is always 486 lines
398 if ( m_height == 486 && height == 480 )
400 // blank first 6 lines
403 memset( buffer, 0, stride * 6 );
404 buffer += stride * 6;
406 else for ( int i = 0; i < m_width * 6; i++ )
414 // Normal non-keyer playout - needs byte swapping
415 if ( !progressive && m_displayMode->GetFieldDominance() == bmdUpperFieldFirst )
416 // convert lower field first to top field first
417 swab( (char*) image, (char*) buffer + stride, stride * ( height - 1 ) );
419 swab( (char*) image, (char*) buffer, stride * height );
421 else if ( !mlt_properties_get_int( MLT_FRAME_PROPERTIES( frame ), "test_image" ) )
423 // Normal keyer output
425 uint32_t* s = (uint32_t*) image;
426 uint32_t* d = (uint32_t*) buffer;
428 if ( !progressive && m_displayMode->GetFieldDominance() == bmdUpperFieldFirst )
430 // Correct field order
436 // Need to relocate alpha channel RGBA => ARGB
442 *d++ = ( *s << 8 ) | ( *s >> 24 );
449 // Keying blank frames - nullify alpha
450 memset( buffer, 0, stride * height );
454 if ( m_decklinkFrame )
455 m_deckLinkOutput->ScheduleVideoFrame( m_decklinkFrame, m_count * m_duration, m_duration, m_timescale );
458 mlt_log_verbose( getConsumer(), "dropped video frame %u\n", ++m_dropped );
461 HRESULT render( mlt_frame frame )
463 HRESULT result = S_OK;
466 double speed = mlt_properties_get_double( MLT_FRAME_PROPERTIES(frame), "_speed" );
467 if ( m_isAudio && speed == 1.0 )
468 renderAudio( frame );
471 renderVideo( frame );
477 // *** DeckLink API implementation of IDeckLinkVideoOutputCallback IDeckLinkAudioOutputCallback *** //
479 // IUnknown needs only a dummy implementation
480 virtual HRESULT STDMETHODCALLTYPE QueryInterface( REFIID iid, LPVOID *ppv )
481 { return E_NOINTERFACE; }
482 virtual ULONG STDMETHODCALLTYPE AddRef()
484 virtual ULONG STDMETHODCALLTYPE Release()
487 /************************* DeckLink API Delegate Methods *****************************/
489 virtual HRESULT STDMETHODCALLTYPE ScheduledFrameCompleted( IDeckLinkVideoFrame* completedFrame, BMDOutputFrameCompletionResult completed )
493 mlt_properties properties = MLT_CONSUMER_PROPERTIES( getConsumer() );
495 if ( mlt_properties_get( properties, "priority" ) )
499 pthread_attr_t tattr;
500 struct sched_param param;
502 pthread_attr_init(&tattr);
503 pthread_attr_setschedpolicy(&tattr, SCHED_FIFO);
505 if ( !strcmp( "max", mlt_properties_get( properties, "priority" ) ) )
506 param.sched_priority = sched_get_priority_max(SCHED_FIFO) - 1;
507 else if ( !strcmp( "min", mlt_properties_get( properties, "priority" ) ) )
508 param.sched_priority = sched_get_priority_min(SCHED_FIFO) + 1;
510 param.sched_priority = mlt_properties_get_int( properties, "priority" );
512 pthread_attr_setschedparam(&tattr, ¶m);
514 thread = pthread_self();
516 r = pthread_setschedparam(thread, SCHED_FIFO, ¶m);
518 mlt_log_verbose( getConsumer(),
519 "ScheduledFrameCompleted: pthread_setschedparam returned %d\n", r);
521 mlt_log_verbose( getConsumer(),
522 "ScheduledFrameCompleted: param.sched_priority=%d\n", param.sched_priority);
533 m_deckLinkOutput->GetBufferedAudioSampleFrameCount( &cnt );
536 mlt_log_debug( getConsumer(),
537 "ScheduledFrameCompleted: GetBufferedAudioSampleFrameCount %u -> %lu, m_count=%"PRIu64"\n",
538 m_acnt, cnt, m_count );
542 // When a video frame has been released by the API, schedule another video frame to be output
544 // ignore handler if frame was flushed
545 if ( bmdOutputFrameFlushed == completed )
548 // schedule next frame
549 ScheduleNextFrame( false );
551 // step forward frames counter if underrun
552 if ( bmdOutputFrameDisplayedLate == completed )
554 mlt_log_verbose( getConsumer(), "ScheduledFrameCompleted: bmdOutputFrameDisplayedLate == completed\n" );
557 if ( bmdOutputFrameDropped == completed )
559 mlt_log_verbose( getConsumer(), "ScheduledFrameCompleted: bmdOutputFrameDropped == completed\n" );
566 virtual HRESULT STDMETHODCALLTYPE ScheduledPlaybackHasStopped()
568 return mlt_consumer_is_stopped( getConsumer() ) ? S_FALSE : S_OK;
572 void ScheduleNextFrame( bool preroll )
575 mlt_consumer consumer = getConsumer();
577 // Get the properties
578 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
581 mlt_frame frame = NULL;
583 if( mlt_properties_get_int( properties, "running" ) || preroll )
585 frame = mlt_consumer_rt_frame( consumer );
590 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
592 // terminate on pause
593 if ( m_terminate_on_pause &&
594 mlt_properties_get_double( MLT_FRAME_PROPERTIES( frame ), "_speed" ) == 0.0 )
597 mlt_frame_close( frame );
603 /** Start the consumer.
606 static int start( mlt_consumer consumer )
608 // Get the properties
609 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
610 DeckLinkConsumer* decklink = (DeckLinkConsumer*) consumer->child;
611 return decklink->start( mlt_properties_get_int( properties, "preroll" ) ) ? 0 : 1;
614 /** Stop the consumer.
617 static int stop( mlt_consumer consumer )
619 // Get the properties
620 DeckLinkConsumer* decklink = (DeckLinkConsumer*) consumer->child;
621 return decklink->stop();
624 /** Determine if the consumer is stopped.
627 static int is_stopped( mlt_consumer consumer )
629 // Get the properties
630 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
631 return !mlt_properties_get_int( properties, "running" );
634 /** Close the consumer.
637 static void close( mlt_consumer consumer )
640 mlt_consumer_stop( consumer );
643 consumer->close = NULL;
644 mlt_consumer_close( consumer );
647 delete (DeckLinkConsumer*) consumer->child;
652 // Listen for the list_devices property to be set
653 static void on_property_changed( void*, mlt_properties properties, const char *name )
655 IDeckLinkIterator* decklinkIterator = NULL;
656 IDeckLink* decklink = NULL;
657 IDeckLinkInput* decklinkOutput = NULL;
660 if ( name && !strcmp( name, "list_devices" ) )
661 mlt_event_block( (mlt_event) mlt_properties_get_data( properties, "list-devices-event", NULL ) );
666 if ( FAILED( CoInitialize( NULL ) ) )
668 if ( FAILED( CoCreateInstance( CLSID_CDeckLinkIterator, NULL, CLSCTX_ALL, IID_IDeckLinkIterator, (void**) &decklinkIterator ) ) )
671 if ( !( decklinkIterator = CreateDeckLinkIteratorInstance() ) )
674 for ( ; decklinkIterator->Next( &decklink ) == S_OK; i++ )
676 if ( decklink->QueryInterface( IID_IDeckLinkOutput, (void**) &decklinkOutput ) == S_OK )
678 DLString name = NULL;
679 if ( decklink->GetModelName( &name ) == S_OK )
681 char *name_cstr = getCString( name );
682 const char *format = "device.%d";
683 char *key = (char*) calloc( 1, strlen( format ) + 1 );
685 sprintf( key, format, i );
686 mlt_properties_set( properties, key, name_cstr );
688 freeDLString( name );
689 freeCString( name_cstr );
691 SAFE_RELEASE( decklinkOutput );
693 SAFE_RELEASE( decklink );
695 SAFE_RELEASE( decklinkIterator );
696 mlt_properties_set_int( properties, "devices", i );
699 /** Initialise the consumer.
702 mlt_consumer consumer_decklink_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
704 // Allocate the consumer
705 DeckLinkConsumer* decklink = new DeckLinkConsumer();
706 mlt_consumer consumer = NULL;
709 if ( decklink && !mlt_consumer_init( decklink->getConsumer(), decklink, profile ) )
711 // If initialises without error
712 if ( decklink->open( arg? atoi(arg) : 0 ) )
714 consumer = decklink->getConsumer();
715 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
718 consumer->close = close;
719 consumer->start = start;
720 consumer->stop = stop;
721 consumer->is_stopped = is_stopped;
722 mlt_properties_set( properties, "deinterlace_method", "onefield" );
724 mlt_event event = mlt_events_listen( properties, properties, "property-changed", (mlt_listener) on_property_changed );
725 mlt_properties_set_data( properties, "list-devices-event", event, 0, NULL, NULL );
733 extern mlt_producer producer_decklink_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg );
735 static mlt_properties metadata( mlt_service_type type, const char *id, void *data )
737 char file[ PATH_MAX ];
738 const char *service_type = NULL;
742 service_type = "consumer";
745 service_type = "producer";
750 snprintf( file, PATH_MAX, "%s/decklink/%s_%s.yml", mlt_environment( "MLT_DATA" ), service_type, id );
751 return mlt_properties_parse_yaml( file );
756 MLT_REGISTER( consumer_type, "decklink", consumer_decklink_init );
757 MLT_REGISTER( producer_type, "decklink", producer_decklink_init );
758 MLT_REGISTER_METADATA( consumer_type, "decklink", metadata, NULL );
759 MLT_REGISTER_METADATA( producer_type, "decklink", metadata, NULL );