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 #include "DeckLinkAPI_h.h"
33 #include "DeckLinkAPI.h"
34 typedef const char* BSTR;
37 #define SAFE_RELEASE(V) if (V) { V->Release(); V = NULL; }
39 static const unsigned PREROLL_MINIMUM = 3;
41 class DeckLinkConsumer
42 : public IDeckLinkVideoOutputCallback
45 mlt_consumer_s m_consumer;
46 IDeckLink* m_deckLink;
47 IDeckLinkOutput* m_deckLinkOutput;
48 IDeckLinkDisplayMode* m_displayMode;
51 BMDTimeValue m_duration;
52 BMDTimeScale m_timescale;
57 IDeckLinkMutableVideoFrame* m_decklinkFrame;
60 IDeckLinkKeyer* m_deckLinkKeyer;
61 bool m_terminate_on_pause;
65 pthread_t m_prerollThread;
67 IDeckLinkDisplayMode* getDisplayMode()
69 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( getConsumer() ) );
70 IDeckLinkDisplayModeIterator* iter = NULL;
71 IDeckLinkDisplayMode* mode = NULL;
72 IDeckLinkDisplayMode* result = 0;
74 if ( m_deckLinkOutput->GetDisplayModeIterator( &iter ) == S_OK )
76 while ( !result && iter->Next( &mode ) == S_OK )
78 m_width = mode->GetWidth();
79 m_height = mode->GetHeight();
80 mode->GetFrameRate( &m_duration, &m_timescale );
81 m_fps = (double) m_timescale / m_duration;
82 int p = mode->GetFieldDominance() == bmdProgressiveFrame;
83 mlt_log_verbose( getConsumer(), "BMD mode %dx%d %.3f fps prog %d\n", m_width, m_height, m_fps, p );
85 if ( m_width == profile->width && p == profile->progressive
86 && m_fps == mlt_profile_fps( profile )
87 && ( m_height == profile->height || ( m_height == 486 && profile->height == 480 ) ) )
99 mlt_consumer getConsumer()
100 { return &m_consumer; }
104 m_displayMode = NULL;
105 m_deckLinkKeyer = NULL;
106 m_deckLinkOutput = NULL;
112 SAFE_RELEASE( m_displayMode );
113 SAFE_RELEASE( m_deckLinkKeyer );
114 SAFE_RELEASE( m_deckLinkOutput );
115 SAFE_RELEASE( m_deckLink );
118 bool open( unsigned card = 0 )
122 IDeckLinkIterator* deckLinkIterator = NULL;
123 HRESULT result = CoInitialize( NULL );
124 if ( FAILED( result ) )
126 mlt_log_error( getConsumer(), "COM initialization failed\n" );
129 result = CoCreateInstance( CLSID_CDeckLinkIterator, NULL, CLSCTX_ALL, IID_IDeckLinkIterator, (void**) &deckLinkIterator );
130 if ( FAILED( result ) )
132 mlt_log_error( getConsumer(), "The DeckLink drivers not installed.\n" );
136 IDeckLinkIterator* deckLinkIterator = CreateDeckLinkIteratorInstance();
138 if ( !deckLinkIterator )
140 mlt_log_error( getConsumer(), "The DeckLink drivers not installed.\n" );
145 // Connect to the Nth DeckLink instance
146 for ( i = 0; deckLinkIterator->Next( &m_deckLink ) == S_OK ; i++)
151 SAFE_RELEASE( m_deckLink );
153 SAFE_RELEASE( deckLinkIterator );
156 mlt_log_error( getConsumer(), "DeckLink card not found\n" );
160 // Obtain the audio/video output interface (IDeckLinkOutput)
161 if ( m_deckLink->QueryInterface( IID_IDeckLinkOutput, (void**)&m_deckLinkOutput ) != S_OK )
163 mlt_log_error( getConsumer(), "No DeckLink cards support output\n" );
164 SAFE_RELEASE( m_deckLink );
168 // Get the keyer interface
169 IDeckLinkAttributes *deckLinkAttributes = 0;
170 if ( m_deckLink->QueryInterface( IID_IDeckLinkAttributes, (void**) &deckLinkAttributes ) == S_OK )
177 if ( deckLinkAttributes->GetFlag( BMDDeckLinkSupportsInternalKeying, &flag ) == S_OK && flag )
179 if ( m_deckLink->QueryInterface( IID_IDeckLinkKeyer, (void**) &m_deckLinkKeyer ) != S_OK )
181 mlt_log_error( getConsumer(), "Failed to get keyer\n" );
182 SAFE_RELEASE( m_deckLinkOutput );
183 SAFE_RELEASE( m_deckLink );
187 SAFE_RELEASE( deckLinkAttributes );
190 // Provide this class as a delegate to the audio and video output interfaces
191 m_deckLinkOutput->SetScheduledFrameCompletionCallback( this );
197 void* preroll_thread()
200 for ( unsigned i = 0; i < m_preroll; i++ )
201 ScheduleNextFrame( true );
203 // start scheduled playback
204 m_deckLinkOutput->StartScheduledPlayback( 0, m_timescale, 1.0 );
209 static void* preroll_thread_proxy( void* arg )
211 DeckLinkConsumer* self = static_cast< DeckLinkConsumer* >( arg );
212 return self->preroll_thread();
215 bool start( unsigned preroll )
217 mlt_properties properties = MLT_CONSUMER_PROPERTIES( getConsumer() );
219 // Initialize members
222 m_decklinkFrame = NULL;
223 preroll = preroll < PREROLL_MINIMUM ? PREROLL_MINIMUM : preroll;
224 m_channels = mlt_properties_get_int( properties, "channels" );
225 m_isAudio = !mlt_properties_get_int( properties, "audio_off" );
226 m_terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
229 m_displayMode = getDisplayMode();
230 if ( !m_displayMode )
232 mlt_log_error( getConsumer(), "Profile is not compatible with decklink.\n" );
237 if ( m_deckLinkKeyer && ( m_isKeyer = mlt_properties_get_int( properties, "keyer" ) ) )
239 bool external = ( m_isKeyer == 2 );
240 double level = mlt_properties_get_double( properties, "keyer_level" );
242 if ( m_deckLinkKeyer->Enable( external ) != S_OK )
243 mlt_log_error( getConsumer(), "Failed to enable %s keyer\n",
244 external ? "external" : "internal" );
245 m_deckLinkKeyer->SetLevel( level <= 1 ? ( level > 0 ? 255 * level : 255 ) : 255 );
247 else if ( m_deckLinkKeyer )
249 m_deckLinkKeyer->Disable();
252 // Set the video output mode
253 if ( S_OK != m_deckLinkOutput->EnableVideoOutput( m_displayMode->GetDisplayMode(), bmdVideoOutputFlagDefault ) )
255 mlt_log_error( getConsumer(), "Failed to enable video output\n" );
259 // Set the audio output mode
262 m_deckLinkOutput->DisableAudioOutput();
265 if ( S_OK != m_deckLinkOutput->EnableAudioOutput( bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger,
266 m_channels, bmdAudioOutputStreamTimestamped ) )
268 mlt_log_error( getConsumer(), "Failed to enable audio output\n" );
276 // Do preroll in thread to ensure asynchronicity of mlt_consumer_start().
277 pthread_create( &m_prerollThread, NULL, preroll_thread_proxy, this );
279 // Set the running state
280 mlt_properties_set_int( properties, "running", 1 );
287 mlt_properties properties = MLT_CONSUMER_PROPERTIES( getConsumer() );
288 bool wasRunning = !!mlt_properties_get_int( properties, "running" );
290 // set running state is 0
291 mlt_properties_set_int( properties, "running", 0 );
292 mlt_consumer_stopped( getConsumer() );
294 // Stop the audio and video output streams immediately
295 if ( m_deckLinkOutput )
297 m_deckLinkOutput->StopScheduledPlayback( 0, 0, 0 );
298 m_deckLinkOutput->DisableAudioOutput();
299 m_deckLinkOutput->DisableVideoOutput();
302 // release decklink frame
303 SAFE_RELEASE( m_decklinkFrame );
306 pthread_join( m_prerollThread, NULL );
311 void renderAudio( mlt_frame frame )
313 mlt_audio_format format = mlt_audio_s16;
314 int frequency = bmdAudioSampleRate48kHz;
315 int samples = mlt_sample_calculator( m_fps, frequency, m_count );
318 if ( !mlt_frame_get_audio( frame, (void**) &pcm, &format, &frequency, &m_channels, &samples ) )
321 unsigned long written = 0;
323 uint32_t written = 0;
325 BMDTimeValue streamTime = m_count * frequency * m_duration / m_timescale;
326 m_deckLinkOutput->GetBufferedAudioSampleFrameCount( &written );
327 if ( written > (m_preroll + 1) * samples )
329 mlt_log_verbose( getConsumer(), "renderAudio: will flush %lu audiosamples\n", written );
330 m_deckLinkOutput->FlushBufferedAudioSamples();
333 m_deckLinkOutput->ScheduleAudioSamples( pcm, samples, streamTime, frequency, (unsigned long*) &written );
335 m_deckLinkOutput->ScheduleAudioSamples( pcm, samples, streamTime, frequency, &written );
338 if ( written != (uint32_t) samples )
339 mlt_log_verbose( getConsumer(), "renderAudio: samples=%d, written=%lu\n", samples, written );
343 bool createFrame( IDeckLinkMutableVideoFrame** decklinkFrame )
345 BMDPixelFormat format = m_isKeyer? bmdFormat8BitARGB : bmdFormat8BitYUV;
346 IDeckLinkMutableVideoFrame* frame = 0;
348 int stride = m_width * ( m_isKeyer? 4 : 2 );
350 *decklinkFrame = NULL;
352 // Generate a DeckLink video frame
353 if ( S_OK != m_deckLinkOutput->CreateVideoFrame( m_width, m_height,
354 stride, format, bmdFrameFlagDefault, &frame ) )
356 mlt_log_verbose( getConsumer(), "Failed to create video frame\n" );
361 // Make the first line black for field order correction.
362 if ( S_OK == frame->GetBytes( (void**) &buffer ) && buffer )
366 memset( buffer, 0, stride );
368 else for ( int i = 0; i < m_width; i++ )
375 *decklinkFrame = frame;
380 void renderVideo( mlt_frame frame )
382 mlt_image_format format = m_isKeyer? mlt_image_rgb24a : mlt_image_yuv422;
384 int rendered = mlt_properties_get_int( MLT_FRAME_PROPERTIES(frame), "rendered");
385 int height = m_height;
387 if ( rendered && !mlt_frame_get_image( frame, &image, &format, &m_width, &height, 0 ) )
390 int stride = m_width * ( m_isKeyer? 4 : 2 );
392 SAFE_RELEASE( m_decklinkFrame );
393 if ( createFrame( &m_decklinkFrame ) )
394 m_decklinkFrame->GetBytes( (void**) &buffer );
398 int progressive = mlt_properties_get_int( MLT_FRAME_PROPERTIES( frame ), "progressive" );
400 // NTSC SDI is always 486 lines
401 if ( m_height == 486 && height == 480 )
403 // blank first 6 lines
406 memset( buffer, 0, stride * 6 );
407 buffer += stride * 6;
409 else for ( int i = 0; i < m_width * 6; i++ )
417 // Normal non-keyer playout - needs byte swapping
418 if ( !progressive && m_displayMode->GetFieldDominance() == bmdUpperFieldFirst )
419 // convert lower field first to top field first
420 swab( (char*) image, (char*) buffer + stride, stride * ( height - 1 ) );
422 swab( (char*) image, (char*) buffer, stride * height );
424 else if ( !mlt_properties_get_int( MLT_FRAME_PROPERTIES( frame ), "test_image" ) )
426 // Normal keyer output
428 uint32_t* s = (uint32_t*) image;
429 uint32_t* d = (uint32_t*) buffer;
431 if ( !progressive && m_displayMode->GetFieldDominance() == bmdUpperFieldFirst )
433 // Correct field order
439 // Need to relocate alpha channel RGBA => ARGB
445 *d++ = ( *s << 8 ) | ( *s >> 24 );
452 // Keying blank frames - nullify alpha
453 memset( buffer, 0, stride * height );
457 if ( m_decklinkFrame )
458 m_deckLinkOutput->ScheduleVideoFrame( m_decklinkFrame, m_count * m_duration, m_duration, m_timescale );
461 mlt_log_verbose( getConsumer(), "dropped video frame %u\n", ++m_dropped );
464 HRESULT render( mlt_frame frame )
466 HRESULT result = S_OK;
469 double speed = mlt_properties_get_double( MLT_FRAME_PROPERTIES(frame), "_speed" );
470 if ( m_isAudio && speed == 1.0 )
471 renderAudio( frame );
474 renderVideo( frame );
480 // *** DeckLink API implementation of IDeckLinkVideoOutputCallback IDeckLinkAudioOutputCallback *** //
482 // IUnknown needs only a dummy implementation
483 virtual HRESULT STDMETHODCALLTYPE QueryInterface( REFIID iid, LPVOID *ppv )
484 { return E_NOINTERFACE; }
485 virtual ULONG STDMETHODCALLTYPE AddRef()
487 virtual ULONG STDMETHODCALLTYPE Release()
490 /************************* DeckLink API Delegate Methods *****************************/
492 virtual HRESULT STDMETHODCALLTYPE ScheduledFrameCompleted( IDeckLinkVideoFrame* completedFrame, BMDOutputFrameCompletionResult completed )
496 mlt_properties properties = MLT_CONSUMER_PROPERTIES( getConsumer() );
498 if ( mlt_properties_get( properties, "priority" ) )
502 pthread_attr_t tattr;
503 struct sched_param param;
505 pthread_attr_init(&tattr);
506 pthread_attr_setschedpolicy(&tattr, SCHED_FIFO);
508 if ( !strcmp( "max", mlt_properties_get( properties, "priority" ) ) )
509 param.sched_priority = sched_get_priority_max(SCHED_FIFO) - 1;
510 else if ( !strcmp( "min", mlt_properties_get( properties, "priority" ) ) )
511 param.sched_priority = sched_get_priority_min(SCHED_FIFO) + 1;
513 param.sched_priority = mlt_properties_get_int( properties, "priority" );
515 pthread_attr_setschedparam(&tattr, ¶m);
517 thread = pthread_self();
519 r = pthread_setschedparam(thread, SCHED_FIFO, ¶m);
521 mlt_log_verbose( getConsumer(),
522 "ScheduledFrameCompleted: pthread_setschedparam returned %d\n", r);
524 mlt_log_verbose( getConsumer(),
525 "ScheduledFrameCompleted: param.sched_priority=%d\n", param.sched_priority);
536 m_deckLinkOutput->GetBufferedAudioSampleFrameCount( &cnt );
539 mlt_log_debug( getConsumer(),
540 "ScheduledFrameCompleted: GetBufferedAudioSampleFrameCount %u -> %lu, m_count=%"PRIu64"\n",
541 m_acnt, cnt, m_count );
545 // When a video frame has been released by the API, schedule another video frame to be output
547 // ignore handler if frame was flushed
548 if ( bmdOutputFrameFlushed == completed )
551 // schedule next frame
552 ScheduleNextFrame( false );
554 // step forward frames counter if underrun
555 if ( bmdOutputFrameDisplayedLate == completed )
557 mlt_log_verbose( getConsumer(), "ScheduledFrameCompleted: bmdOutputFrameDisplayedLate == completed\n" );
560 if ( bmdOutputFrameDropped == completed )
562 mlt_log_verbose( getConsumer(), "ScheduledFrameCompleted: bmdOutputFrameDropped == completed\n" );
569 virtual HRESULT STDMETHODCALLTYPE ScheduledPlaybackHasStopped()
571 return mlt_consumer_is_stopped( getConsumer() ) ? S_FALSE : S_OK;
575 void ScheduleNextFrame( bool preroll )
578 mlt_consumer consumer = getConsumer();
580 // Get the properties
581 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
584 mlt_frame frame = NULL;
586 if( mlt_properties_get_int( properties, "running" ) || preroll )
588 frame = mlt_consumer_rt_frame( consumer );
593 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
595 // terminate on pause
596 if ( m_terminate_on_pause &&
597 mlt_properties_get_double( MLT_FRAME_PROPERTIES( frame ), "_speed" ) == 0.0 )
600 mlt_frame_close( frame );
606 /** Start the consumer.
609 static int start( mlt_consumer consumer )
611 // Get the properties
612 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
613 DeckLinkConsumer* decklink = (DeckLinkConsumer*) consumer->child;
614 return decklink->start( mlt_properties_get_int( properties, "preroll" ) ) ? 0 : 1;
617 /** Stop the consumer.
620 static int stop( mlt_consumer consumer )
622 // Get the properties
623 DeckLinkConsumer* decklink = (DeckLinkConsumer*) consumer->child;
624 return decklink->stop();
627 /** Determine if the consumer is stopped.
630 static int is_stopped( mlt_consumer consumer )
632 // Get the properties
633 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
634 return !mlt_properties_get_int( properties, "running" );
637 /** Close the consumer.
640 static void close( mlt_consumer consumer )
643 mlt_consumer_stop( consumer );
646 consumer->close = NULL;
647 mlt_consumer_close( consumer );
650 delete (DeckLinkConsumer*) consumer->child;
655 // Listen for the list_devices property to be set
656 static void on_property_changed( void*, mlt_properties properties, const char *name )
658 IDeckLinkIterator* decklinkIterator = NULL;
659 IDeckLink* decklink = NULL;
660 IDeckLinkInput* decklinkOutput = NULL;
663 if ( name && !strcmp( name, "list_devices" ) )
664 mlt_event_block( (mlt_event) mlt_properties_get_data( properties, "list-devices-event", NULL ) );
669 if ( FAILED( CoInitialize( NULL ) ) )
671 if ( FAILED( CoCreateInstance( CLSID_CDeckLinkIterator, NULL, CLSCTX_ALL, IID_IDeckLinkIterator, (void**) &decklinkIterator ) ) )
674 if ( !( decklinkIterator = CreateDeckLinkIteratorInstance() ) )
677 for ( ; decklinkIterator->Next( &decklink ) == S_OK; i++ )
679 if ( decklink->QueryInterface( IID_IDeckLinkOutput, (void**) &decklinkOutput ) == S_OK )
682 if ( decklink->GetModelName( (BSTR*) &name ) == S_OK )
684 const char *format = "device.%d";
685 char *key = (char*) calloc( 1, strlen( format ) + 1 );
687 sprintf( key, format, i );
688 mlt_properties_set( properties, key, name );
692 SAFE_RELEASE( decklinkOutput );
694 SAFE_RELEASE( decklink );
696 SAFE_RELEASE( decklinkIterator );
697 mlt_properties_set_int( properties, "devices", i );
700 /** Initialise the consumer.
703 mlt_consumer consumer_decklink_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
705 // Allocate the consumer
706 DeckLinkConsumer* decklink = new DeckLinkConsumer();
707 mlt_consumer consumer = NULL;
710 if ( decklink && !mlt_consumer_init( decklink->getConsumer(), decklink, profile ) )
712 // If initialises without error
713 if ( decklink->open( arg? atoi(arg) : 0 ) )
715 consumer = decklink->getConsumer();
716 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
719 consumer->close = close;
720 consumer->start = start;
721 consumer->stop = stop;
722 consumer->is_stopped = is_stopped;
723 mlt_properties_set( properties, "deinterlace_method", "onefield" );
725 mlt_event event = mlt_events_listen( properties, properties, "property-changed", (mlt_listener) on_property_changed );
726 mlt_properties_set_data( properties, "list-devices-event", event, 0, NULL, NULL );
734 extern mlt_producer producer_decklink_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg );
736 static mlt_properties metadata( mlt_service_type type, const char *id, void *data )
738 char file[ PATH_MAX ];
739 const char *service_type = NULL;
743 service_type = "consumer";
746 service_type = "producer";
751 snprintf( file, PATH_MAX, "%s/decklink/%s_%s.yml", mlt_environment( "MLT_DATA" ), service_type, id );
752 return mlt_properties_parse_yaml( file );
757 MLT_REGISTER( consumer_type, "decklink", consumer_decklink_init );
758 MLT_REGISTER( producer_type, "decklink", producer_decklink_init );
759 MLT_REGISTER_METADATA( consumer_type, "decklink", metadata, NULL );
760 MLT_REGISTER_METADATA( producer_type, "decklink", metadata, NULL );