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;
58 IDeckLinkDisplayMode* getDisplayMode()
60 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( getConsumer() ) );
61 IDeckLinkDisplayModeIterator* iter;
62 IDeckLinkDisplayMode* mode;
63 IDeckLinkDisplayMode* result = 0;
65 if ( m_deckLinkOutput->GetDisplayModeIterator( &iter ) == S_OK )
67 while ( !result && iter->Next( &mode ) == S_OK )
69 m_width = mode->GetWidth();
70 m_height = mode->GetHeight();
71 mode->GetFrameRate( &m_duration, &m_timescale );
72 m_fps = (double) m_timescale / m_duration;
73 int p = mode->GetFieldDominance() == bmdProgressiveFrame;
74 mlt_log_verbose( getConsumer(), "BMD mode %dx%d %.3f fps prog %d\n", m_width, m_height, m_fps, p );
76 if ( m_width == profile->width && m_height == profile->height && p == profile->progressive
77 && m_fps == mlt_profile_fps( profile ) )
86 mlt_consumer getConsumer()
87 { return &m_consumer; }
91 if ( m_deckLinkKeyer )
92 m_deckLinkKeyer->Release();
93 if ( m_deckLinkOutput )
94 m_deckLinkOutput->Release();
96 m_deckLink->Release();
99 bool open( unsigned card = 0 )
103 IDeckLinkIterator* deckLinkIterator = NULL;
104 HRESULT result = CoInitialize( NULL );
105 if ( FAILED( result ) )
107 mlt_log_error( getConsumer(), "COM initialization failed\n" );
110 result = CoCreateInstance( CLSID_CDeckLinkIterator, NULL, CLSCTX_ALL, IID_IDeckLinkIterator, (void**) &deckLinkIterator );
111 if ( FAILED( result ) )
113 mlt_log_error( getConsumer(), "The DeckLink drivers not installed.\n" );
117 IDeckLinkIterator* deckLinkIterator = CreateDeckLinkIteratorInstance();
119 if ( !deckLinkIterator )
121 mlt_log_error( getConsumer(), "The DeckLink drivers not installed.\n" );
126 // Connect to the Nth DeckLink instance
128 if ( deckLinkIterator->Next( &m_deckLink ) != S_OK )
130 mlt_log_error( getConsumer(), "DeckLink card not found\n" );
131 deckLinkIterator->Release();
134 } while ( ++i <= card );
135 deckLinkIterator->Release();
137 // Obtain the audio/video output interface (IDeckLinkOutput)
138 if ( m_deckLink->QueryInterface( IID_IDeckLinkOutput, (void**)&m_deckLinkOutput ) != S_OK )
140 mlt_log_error( getConsumer(), "No DeckLink cards support output\n" );
141 m_deckLink->Release();
146 // Get the keyer interface
147 IDeckLinkAttributes *deckLinkAttributes = 0;
149 if ( m_deckLink->QueryInterface( IID_IDeckLinkAttributes, (void**) &deckLinkAttributes ) == S_OK )
156 if ( deckLinkAttributes->GetFlag( BMDDeckLinkSupportsInternalKeying, &flag ) == S_OK && flag )
158 if ( m_deckLink->QueryInterface( IID_IDeckLinkKeyer, (void**) &m_deckLinkKeyer ) != S_OK )
160 mlt_log_error( getConsumer(), "Failed to get keyer\n" );
161 m_deckLinkOutput->Release();
162 m_deckLinkOutput = 0;
163 m_deckLink->Release();
168 deckLinkAttributes->Release();
171 // Provide this class as a delegate to the audio and video output interfaces
172 m_deckLinkOutput->SetScheduledFrameCompletionCallback( this );
177 bool start( unsigned preroll )
180 mlt_properties properties = MLT_CONSUMER_PROPERTIES( getConsumer() );
182 // Initialize members
185 m_decklinkFrame = NULL;
186 preroll = preroll < PREROLL_MINIMUM ? PREROLL_MINIMUM : preroll;
187 m_channels = mlt_properties_get_int( properties, "channels" );
188 m_isAudio = !mlt_properties_get_int( properties, "audio_off" );
189 m_terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
192 m_displayMode = getDisplayMode();
193 if ( !m_displayMode )
195 mlt_log_error( getConsumer(), "Profile is not compatible with decklink.\n" );
200 if ( m_deckLinkKeyer && ( m_isKeyer = mlt_properties_get_int( properties, "keyer" ) ) )
202 bool external = (m_isKeyer == 2);
203 double level = mlt_properties_get_double( properties, "keyer_level" );
205 if ( m_deckLinkKeyer->Enable( external ) != S_OK )
206 mlt_log_error( getConsumer(), "Failed to enable %s keyer\n",
207 external ? "external" : "internal" );
208 m_deckLinkKeyer->SetLevel( level <= 1 ? ( level > 0 ? 255 * level : 255 ) : 255 );
210 else if ( m_deckLinkKeyer )
212 m_deckLinkKeyer->Disable();
215 // Set the video output mode
216 if ( S_OK != m_deckLinkOutput->EnableVideoOutput( m_displayMode->GetDisplayMode(), bmdVideoOutputFlagDefault) )
218 mlt_log_error( getConsumer(), "Failed to enable video output\n" );
222 // Set the audio output mode
225 m_deckLinkOutput->DisableAudioOutput();
228 if ( S_OK != m_deckLinkOutput->EnableAudioOutput( bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger,
229 m_channels, bmdAudioOutputStreamTimestamped ) )
231 mlt_log_error( getConsumer(), "Failed to enable audio output\n" );
237 for( i = 0; i < preroll; i++ )
238 ScheduleNextFrame( true );
240 // start scheduled playback
241 m_deckLinkOutput->StartScheduledPlayback( 0, m_timescale, 1.0 );
243 // Set the running state
244 mlt_properties_set_int( properties, "running", 1 );
251 mlt_properties properties = MLT_CONSUMER_PROPERTIES( getConsumer() );
253 // set running state is 0
254 mlt_properties_set_int( properties, "running", 0 );
255 mlt_consumer_stopped( getConsumer() );
257 // release decklink frame
258 if ( m_decklinkFrame )
259 m_decklinkFrame->Release();
260 m_decklinkFrame = NULL;
262 // Stop the audio and video output streams immediately
263 if ( m_deckLinkOutput )
265 m_deckLinkOutput->StopScheduledPlayback( 0, 0, 0 );
266 m_deckLinkOutput->DisableAudioOutput();
267 m_deckLinkOutput->DisableVideoOutput();
273 void renderAudio( mlt_frame frame )
275 mlt_audio_format format = mlt_audio_s16;
276 int frequency = bmdAudioSampleRate48kHz;
277 int samples = mlt_sample_calculator( m_fps, frequency, m_count );
280 if ( !mlt_frame_get_audio( frame, (void**) &pcm, &format, &frequency, &m_channels, &samples ) )
282 uint32_t written = 0;
285 m_deckLinkOutput->ScheduleAudioSamples( pcm, samples, m_count * frequency / m_fps, frequency, (unsigned long*) &written );
287 m_deckLinkOutput->ScheduleAudioSamples( pcm, samples, m_count * frequency / m_fps, frequency, &written );
290 if ( written != (uint32_t) samples )
291 mlt_log_verbose( getConsumer(), "renderAudio: samples=%d, written=%u\n", samples, written );
295 bool createFrame( IDeckLinkMutableVideoFrame** decklinkFrame )
297 BMDPixelFormat format = m_isKeyer? bmdFormat8BitARGB : bmdFormat8BitYUV;
298 IDeckLinkMutableVideoFrame* frame = 0;
300 int stride = m_width * ( m_isKeyer? 4 : 2 );
302 *decklinkFrame = NULL;
304 // Generate a DeckLink video frame
305 if ( S_OK != m_deckLinkOutput->CreateVideoFrame( m_width, m_height,
306 stride, format, bmdFrameFlagDefault, &frame ) )
308 mlt_log_verbose( getConsumer(), "Failed to create video frame\n" );
313 // Make the first line black for field order correction.
314 if ( S_OK == frame->GetBytes( (void**) &buffer ) && buffer )
318 memset( buffer, 0, stride );
320 else for ( int i = 0; i < m_width; i++ )
327 *decklinkFrame = frame;
332 void renderVideo( mlt_frame frame )
334 mlt_image_format format = m_isKeyer? mlt_image_rgb24a : mlt_image_yuv422;
336 int rendered = mlt_properties_get_int( MLT_FRAME_PROPERTIES(frame), "rendered");
338 if ( rendered && !mlt_frame_get_image( frame, &image, &format, &m_width, &m_height, 0 ) )
341 int stride = m_width * ( m_isKeyer? 4 : 2 );
343 if ( m_decklinkFrame )
344 m_decklinkFrame->Release();
345 if ( createFrame( &m_decklinkFrame ) )
346 m_decklinkFrame->GetBytes( (void**) &buffer );
350 int progressive = mlt_properties_get_int( MLT_FRAME_PROPERTIES( frame ), "progressive" );
354 // Normal non-keyer playout - needs byte swapping
355 if ( !progressive && m_displayMode->GetFieldDominance() == bmdUpperFieldFirst )
356 // convert lower field first to top field first
357 swab( (char*) image, (char*) buffer + stride, stride * ( m_height - 1 ) );
359 swab( (char*) image, (char*) buffer, stride * m_height );
361 else if ( !mlt_properties_get_int( MLT_FRAME_PROPERTIES( frame ), "test_image" ) )
363 // Normal keyer output
364 int y = m_height + 1;
365 uint32_t* s = (uint32_t*) image;
366 uint32_t* d = (uint32_t*) buffer;
368 if ( !progressive && m_displayMode->GetFieldDominance() == bmdUpperFieldFirst )
370 // Correct field order
376 // Need to relocate alpha channel RGBA => ARGB
382 *d++ = ( *s << 8 ) | ( *s >> 24 );
389 // Keying blank frames - nullify alpha
390 memset( buffer, 0, stride * m_height );
394 if ( m_decklinkFrame )
395 m_deckLinkOutput->ScheduleVideoFrame( m_decklinkFrame, m_count * m_duration, m_duration, m_timescale );
398 mlt_log_verbose( getConsumer(), "dropped video frame %u\n", ++m_dropped );
401 HRESULT render( mlt_frame frame )
403 HRESULT result = S_OK;
406 double speed = mlt_properties_get_double( MLT_FRAME_PROPERTIES(frame), "_speed" );
407 if ( m_isAudio && speed == 1.0 )
408 renderAudio( frame );
411 renderVideo( frame );
417 // *** DeckLink API implementation of IDeckLinkVideoOutputCallback IDeckLinkAudioOutputCallback *** //
419 // IUnknown needs only a dummy implementation
420 virtual HRESULT STDMETHODCALLTYPE QueryInterface( REFIID iid, LPVOID *ppv )
421 { return E_NOINTERFACE; }
422 virtual ULONG STDMETHODCALLTYPE AddRef()
424 virtual ULONG STDMETHODCALLTYPE Release()
427 /************************* DeckLink API Delegate Methods *****************************/
429 virtual HRESULT STDMETHODCALLTYPE ScheduledFrameCompleted( IDeckLinkVideoFrame* completedFrame, BMDOutputFrameCompletionResult completed )
431 // When a video frame has been released by the API, schedule another video frame to be output
433 // ignore handler if frame was flushed
434 if(bmdOutputFrameFlushed == completed)
437 // schedule next frame
438 ScheduleNextFrame(false);
440 // step forward frames counter if underrun
441 if(bmdOutputFrameDisplayedLate == completed)
443 mlt_log_verbose( getConsumer(), "ScheduledFrameCompleted: bmdOutputFrameDisplayedLate == completed\n");
450 virtual HRESULT STDMETHODCALLTYPE ScheduledPlaybackHasStopped()
452 return mlt_consumer_is_stopped( getConsumer() ) ? S_FALSE : S_OK;
456 void ScheduleNextFrame(bool preroll)
459 mlt_consumer consumer = getConsumer();
461 // Get the properties
462 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
465 mlt_frame frame = NULL;
467 if( mlt_properties_get_int( properties, "running" ) || preroll )
469 frame = mlt_consumer_rt_frame( consumer );
474 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
476 // terminate on pause
477 if (m_terminate_on_pause &&
478 mlt_properties_get_double( MLT_FRAME_PROPERTIES( frame ), "_speed" ) == 0.0)
481 mlt_frame_close( frame );
487 /** Start the consumer.
490 static int start( mlt_consumer consumer )
492 // Get the properties
493 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
494 DeckLinkConsumer* decklink = (DeckLinkConsumer*) consumer->child;
495 return decklink->start( mlt_properties_get_int( properties, "preroll" ) ) ? 0 : 1;
498 /** Stop the consumer.
501 static int stop( mlt_consumer consumer )
503 // Get the properties
504 DeckLinkConsumer* decklink = (DeckLinkConsumer*) consumer->child;
505 return decklink->stop();
508 /** Determine if the consumer is stopped.
511 static int is_stopped( mlt_consumer consumer )
513 // Get the properties
514 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
515 return !mlt_properties_get_int( properties, "running" );
518 /** Close the consumer.
521 static void close( mlt_consumer consumer )
524 mlt_consumer_stop( consumer );
527 consumer->close = NULL;
528 mlt_consumer_close( consumer );
531 delete (DeckLinkConsumer*) consumer->child;
536 /** Initialise the consumer.
539 mlt_consumer consumer_decklink_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
541 // Allocate the consumer
542 DeckLinkConsumer* decklink = new DeckLinkConsumer();
543 mlt_consumer consumer = NULL;
546 if ( decklink && !mlt_consumer_init( decklink->getConsumer(), decklink, profile ) )
548 // If initialises without error
549 if ( decklink->open( arg? atoi(arg) : 0 ) )
551 consumer = decklink->getConsumer();
554 consumer->close = close;
555 consumer->start = start;
556 consumer->stop = stop;
557 consumer->is_stopped = is_stopped;
558 mlt_properties_set( MLT_CONSUMER_PROPERTIES(consumer), "deinterlace_method", "onefield" );
566 extern mlt_producer producer_decklink_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg );
568 static mlt_properties metadata( mlt_service_type type, const char *id, void *data )
570 char file[ PATH_MAX ];
571 const char *service_type = NULL;
575 service_type = "consumer";
578 service_type = "producer";
583 snprintf( file, PATH_MAX, "%s/decklink/%s_%s.yml", mlt_environment( "MLT_DATA" ), service_type, id );
584 return mlt_properties_parse_yaml( file );
589 MLT_REGISTER( consumer_type, "decklink", consumer_decklink_init );
590 MLT_REGISTER( producer_type, "decklink", producer_decklink_init );
591 MLT_REGISTER_METADATA( consumer_type, "decklink", metadata, NULL );
592 MLT_REGISTER_METADATA( producer_type, "decklink", metadata, NULL );