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 #include <framework/mlt.h>
29 #include "DeckLinkAPI_h.h"
31 #include "DeckLinkAPI.h"
34 static const unsigned PREROLL_MINIMUM = 3;
36 class DeckLinkConsumer
37 : public IDeckLinkVideoOutputCallback
40 mlt_consumer_s m_consumer;
41 IDeckLink* m_deckLink;
42 IDeckLinkOutput* m_deckLinkOutput;
43 IDeckLinkDisplayMode* m_displayMode;
46 BMDTimeValue m_duration;
47 BMDTimeScale m_timescale;
52 IDeckLinkMutableVideoFrame* m_decklinkFrame;
55 IDeckLinkKeyer* m_deckLinkKeyer;
56 bool m_terminate_on_pause;
59 IDeckLinkDisplayMode* getDisplayMode()
61 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( getConsumer() ) );
62 IDeckLinkDisplayModeIterator* iter;
63 IDeckLinkDisplayMode* mode;
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 && m_height == profile->height && p == profile->progressive
78 && m_fps == mlt_profile_fps( profile ) )
87 mlt_consumer getConsumer()
88 { return &m_consumer; }
92 if ( m_deckLinkKeyer )
93 m_deckLinkKeyer->Release();
94 if ( m_deckLinkOutput )
95 m_deckLinkOutput->Release();
97 m_deckLink->Release();
100 bool open( unsigned card = 0 )
104 IDeckLinkIterator* deckLinkIterator = NULL;
105 HRESULT result = CoInitialize( NULL );
106 if ( FAILED( result ) )
108 mlt_log_error( getConsumer(), "COM initialization failed\n" );
111 result = CoCreateInstance( CLSID_CDeckLinkIterator, NULL, CLSCTX_ALL, IID_IDeckLinkIterator, (void**) &deckLinkIterator );
112 if ( FAILED( result ) )
114 mlt_log_error( getConsumer(), "The DeckLink drivers not installed.\n" );
118 IDeckLinkIterator* deckLinkIterator = CreateDeckLinkIteratorInstance();
120 if ( !deckLinkIterator )
122 mlt_log_error( getConsumer(), "The DeckLink drivers not installed.\n" );
127 // Connect to the Nth DeckLink instance
129 if ( deckLinkIterator->Next( &m_deckLink ) != S_OK )
131 mlt_log_error( getConsumer(), "DeckLink card not found\n" );
132 deckLinkIterator->Release();
135 } while ( ++i <= card );
136 deckLinkIterator->Release();
138 // Obtain the audio/video output interface (IDeckLinkOutput)
139 if ( m_deckLink->QueryInterface( IID_IDeckLinkOutput, (void**)&m_deckLinkOutput ) != S_OK )
141 mlt_log_error( getConsumer(), "No DeckLink cards support output\n" );
142 m_deckLink->Release();
147 // Get the keyer interface
148 IDeckLinkAttributes *deckLinkAttributes = 0;
150 if ( m_deckLink->QueryInterface( IID_IDeckLinkAttributes, (void**) &deckLinkAttributes ) == S_OK )
157 if ( deckLinkAttributes->GetFlag( BMDDeckLinkSupportsInternalKeying, &flag ) == S_OK && flag )
159 if ( m_deckLink->QueryInterface( IID_IDeckLinkKeyer, (void**) &m_deckLinkKeyer ) != S_OK )
161 mlt_log_error( getConsumer(), "Failed to get keyer\n" );
162 m_deckLinkOutput->Release();
163 m_deckLinkOutput = 0;
164 m_deckLink->Release();
169 deckLinkAttributes->Release();
172 // Provide this class as a delegate to the audio and video output interfaces
173 m_deckLinkOutput->SetScheduledFrameCompletionCallback( this );
178 bool start( unsigned preroll )
181 mlt_properties properties = MLT_CONSUMER_PROPERTIES( getConsumer() );
183 // Initialize members
186 m_decklinkFrame = NULL;
187 preroll = preroll < PREROLL_MINIMUM ? PREROLL_MINIMUM : preroll;
188 m_channels = mlt_properties_get_int( properties, "channels" );
189 m_isAudio = !mlt_properties_get_int( properties, "audio_off" );
190 m_terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
193 m_displayMode = getDisplayMode();
194 if ( !m_displayMode )
196 mlt_log_error( getConsumer(), "Profile is not compatible with decklink.\n" );
201 if ( m_deckLinkKeyer && ( m_isKeyer = mlt_properties_get_int( properties, "keyer" ) ) )
203 bool external = (m_isKeyer == 2);
204 double level = mlt_properties_get_double( properties, "keyer_level" );
206 if ( m_deckLinkKeyer->Enable( external ) != S_OK )
207 mlt_log_error( getConsumer(), "Failed to enable %s keyer\n",
208 external ? "external" : "internal" );
209 m_deckLinkKeyer->SetLevel( level <= 1 ? ( level > 0 ? 255 * level : 255 ) : 255 );
211 else if ( m_deckLinkKeyer )
213 m_deckLinkKeyer->Disable();
216 // Set the video output mode
217 if ( S_OK != m_deckLinkOutput->EnableVideoOutput( m_displayMode->GetDisplayMode(), bmdVideoOutputFlagDefault) )
219 mlt_log_error( getConsumer(), "Failed to enable video output\n" );
223 // Set the audio output mode
226 m_deckLinkOutput->DisableAudioOutput();
229 if ( S_OK != m_deckLinkOutput->EnableAudioOutput( bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger,
230 m_channels, bmdAudioOutputStreamTimestamped ) )
232 mlt_log_error( getConsumer(), "Failed to enable audio output\n" );
240 for( i = 0; i < preroll; i++ )
241 ScheduleNextFrame( true );
243 // start scheduled playback
244 m_deckLinkOutput->StartScheduledPlayback( 0, m_timescale, 1.0 );
246 // Set the running state
247 mlt_properties_set_int( properties, "running", 1 );
254 mlt_properties properties = MLT_CONSUMER_PROPERTIES( getConsumer() );
256 // set running state is 0
257 mlt_properties_set_int( properties, "running", 0 );
258 mlt_consumer_stopped( getConsumer() );
260 // release decklink frame
261 if ( m_decklinkFrame )
262 m_decklinkFrame->Release();
263 m_decklinkFrame = NULL;
265 // Stop the audio and video output streams immediately
266 if ( m_deckLinkOutput )
268 m_deckLinkOutput->StopScheduledPlayback( 0, 0, 0 );
269 m_deckLinkOutput->DisableAudioOutput();
270 m_deckLinkOutput->DisableVideoOutput();
276 void renderAudio( mlt_frame frame )
278 mlt_audio_format format = mlt_audio_s16;
279 int frequency = bmdAudioSampleRate48kHz;
280 int samples = mlt_sample_calculator( m_fps, frequency, m_count );
283 if ( !mlt_frame_get_audio( frame, (void**) &pcm, &format, &frequency, &m_channels, &samples ) )
285 uint32_t written = 0;
286 BMDTimeValue streamTime = m_count * frequency * m_duration / m_timescale;
287 m_deckLinkOutput->GetBufferedAudioSampleFrameCount(&written);
288 if ( written > (m_preroll + 1) * samples )
290 mlt_log_verbose( getConsumer(), "renderAudio: will flush %d audiosamples\n", written);
291 m_deckLinkOutput->FlushBufferedAudioSamples();
294 m_deckLinkOutput->ScheduleAudioSamples( pcm, samples, streamTime, frequency, (unsigned long*) &written );
296 m_deckLinkOutput->ScheduleAudioSamples( pcm, samples, streamTime, frequency, &written );
299 if ( written != (uint32_t) samples )
300 mlt_log_verbose( getConsumer(), "renderAudio: samples=%d, written=%u\n", samples, written );
304 bool createFrame( IDeckLinkMutableVideoFrame** decklinkFrame )
306 BMDPixelFormat format = m_isKeyer? bmdFormat8BitARGB : bmdFormat8BitYUV;
307 IDeckLinkMutableVideoFrame* frame = 0;
309 int stride = m_width * ( m_isKeyer? 4 : 2 );
311 *decklinkFrame = NULL;
313 // Generate a DeckLink video frame
314 if ( S_OK != m_deckLinkOutput->CreateVideoFrame( m_width, m_height,
315 stride, format, bmdFrameFlagDefault, &frame ) )
317 mlt_log_verbose( getConsumer(), "Failed to create video frame\n" );
322 // Make the first line black for field order correction.
323 if ( S_OK == frame->GetBytes( (void**) &buffer ) && buffer )
327 memset( buffer, 0, stride );
329 else for ( int i = 0; i < m_width; i++ )
336 *decklinkFrame = frame;
341 void renderVideo( mlt_frame frame )
343 mlt_image_format format = m_isKeyer? mlt_image_rgb24a : mlt_image_yuv422;
345 int rendered = mlt_properties_get_int( MLT_FRAME_PROPERTIES(frame), "rendered");
347 if ( rendered && !mlt_frame_get_image( frame, &image, &format, &m_width, &m_height, 0 ) )
350 int stride = m_width * ( m_isKeyer? 4 : 2 );
352 if ( m_decklinkFrame )
353 m_decklinkFrame->Release();
354 if ( createFrame( &m_decklinkFrame ) )
355 m_decklinkFrame->GetBytes( (void**) &buffer );
359 int progressive = mlt_properties_get_int( MLT_FRAME_PROPERTIES( frame ), "progressive" );
363 // Normal non-keyer playout - needs byte swapping
364 if ( !progressive && m_displayMode->GetFieldDominance() == bmdUpperFieldFirst )
365 // convert lower field first to top field first
366 swab( (char*) image, (char*) buffer + stride, stride * ( m_height - 1 ) );
368 swab( (char*) image, (char*) buffer, stride * m_height );
370 else if ( !mlt_properties_get_int( MLT_FRAME_PROPERTIES( frame ), "test_image" ) )
372 // Normal keyer output
373 int y = m_height + 1;
374 uint32_t* s = (uint32_t*) image;
375 uint32_t* d = (uint32_t*) buffer;
377 if ( !progressive && m_displayMode->GetFieldDominance() == bmdUpperFieldFirst )
379 // Correct field order
385 // Need to relocate alpha channel RGBA => ARGB
391 *d++ = ( *s << 8 ) | ( *s >> 24 );
398 // Keying blank frames - nullify alpha
399 memset( buffer, 0, stride * m_height );
403 if ( m_decklinkFrame )
404 m_deckLinkOutput->ScheduleVideoFrame( m_decklinkFrame, m_count * m_duration, m_duration, m_timescale );
407 mlt_log_verbose( getConsumer(), "dropped video frame %u\n", ++m_dropped );
410 HRESULT render( mlt_frame frame )
412 HRESULT result = S_OK;
415 double speed = mlt_properties_get_double( MLT_FRAME_PROPERTIES(frame), "_speed" );
416 if ( m_isAudio && speed == 1.0 )
417 renderAudio( frame );
420 renderVideo( frame );
426 // *** DeckLink API implementation of IDeckLinkVideoOutputCallback IDeckLinkAudioOutputCallback *** //
428 // IUnknown needs only a dummy implementation
429 virtual HRESULT STDMETHODCALLTYPE QueryInterface( REFIID iid, LPVOID *ppv )
430 { return E_NOINTERFACE; }
431 virtual ULONG STDMETHODCALLTYPE AddRef()
433 virtual ULONG STDMETHODCALLTYPE Release()
436 /************************* DeckLink API Delegate Methods *****************************/
438 virtual HRESULT STDMETHODCALLTYPE ScheduledFrameCompleted( IDeckLinkVideoFrame* completedFrame, BMDOutputFrameCompletionResult completed )
440 // When a video frame has been released by the API, schedule another video frame to be output
442 // ignore handler if frame was flushed
443 if(bmdOutputFrameFlushed == completed)
446 // schedule next frame
447 ScheduleNextFrame(false);
449 // step forward frames counter if underrun
450 if(bmdOutputFrameDisplayedLate == completed)
452 mlt_log_verbose( getConsumer(), "ScheduledFrameCompleted: bmdOutputFrameDisplayedLate == completed\n");
455 if(bmdOutputFrameDropped == completed)
457 mlt_log_verbose( getConsumer(), "ScheduledFrameCompleted: bmdOutputFrameDropped == completed\n");
464 virtual HRESULT STDMETHODCALLTYPE ScheduledPlaybackHasStopped()
466 return mlt_consumer_is_stopped( getConsumer() ) ? S_FALSE : S_OK;
470 void ScheduleNextFrame(bool preroll)
473 mlt_consumer consumer = getConsumer();
475 // Get the properties
476 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
479 mlt_frame frame = NULL;
481 if( mlt_properties_get_int( properties, "running" ) || preroll )
483 frame = mlt_consumer_rt_frame( consumer );
488 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
490 // terminate on pause
491 if (m_terminate_on_pause &&
492 mlt_properties_get_double( MLT_FRAME_PROPERTIES( frame ), "_speed" ) == 0.0)
495 mlt_frame_close( frame );
501 /** Start the consumer.
504 static int start( mlt_consumer consumer )
506 // Get the properties
507 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
508 DeckLinkConsumer* decklink = (DeckLinkConsumer*) consumer->child;
509 return decklink->start( mlt_properties_get_int( properties, "preroll" ) ) ? 0 : 1;
512 /** Stop the consumer.
515 static int stop( mlt_consumer consumer )
517 // Get the properties
518 DeckLinkConsumer* decklink = (DeckLinkConsumer*) consumer->child;
519 return decklink->stop();
522 /** Determine if the consumer is stopped.
525 static int is_stopped( mlt_consumer consumer )
527 // Get the properties
528 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
529 return !mlt_properties_get_int( properties, "running" );
532 /** Close the consumer.
535 static void close( mlt_consumer consumer )
538 mlt_consumer_stop( consumer );
541 consumer->close = NULL;
542 mlt_consumer_close( consumer );
545 delete (DeckLinkConsumer*) consumer->child;
550 /** Initialise the consumer.
553 mlt_consumer consumer_decklink_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
555 // Allocate the consumer
556 DeckLinkConsumer* decklink = new DeckLinkConsumer();
557 mlt_consumer consumer = NULL;
560 if ( decklink && !mlt_consumer_init( decklink->getConsumer(), decklink, profile ) )
562 // If initialises without error
563 if ( decklink->open( arg? atoi(arg) : 0 ) )
565 consumer = decklink->getConsumer();
568 consumer->close = close;
569 consumer->start = start;
570 consumer->stop = stop;
571 consumer->is_stopped = is_stopped;
572 mlt_properties_set( MLT_CONSUMER_PROPERTIES(consumer), "deinterlace_method", "onefield" );
580 extern mlt_producer producer_decklink_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg );
582 static mlt_properties metadata( mlt_service_type type, const char *id, void *data )
584 char file[ PATH_MAX ];
585 const char *service_type = NULL;
589 service_type = "consumer";
592 service_type = "producer";
597 snprintf( file, PATH_MAX, "%s/decklink/%s_%s.yml", mlt_environment( "MLT_DATA" ), service_type, id );
598 return mlt_properties_parse_yaml( file );
603 MLT_REGISTER( consumer_type, "decklink", consumer_decklink_init );
604 MLT_REGISTER( producer_type, "decklink", producer_decklink_init );
605 MLT_REGISTER_METADATA( consumer_type, "decklink", metadata, NULL );
606 MLT_REGISTER_METADATA( producer_type, "decklink", metadata, NULL );