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>
30 #include "DeckLinkAPI_h.h"
32 #include "DeckLinkAPI.h"
35 static const unsigned PREROLL_MINIMUM = 3;
37 class DeckLinkConsumer
38 : public IDeckLinkVideoOutputCallback
41 mlt_consumer_s m_consumer;
42 IDeckLink* m_deckLink;
43 IDeckLinkOutput* m_deckLinkOutput;
44 IDeckLinkDisplayMode* m_displayMode;
47 BMDTimeValue m_duration;
48 BMDTimeScale m_timescale;
53 IDeckLinkMutableVideoFrame* m_decklinkFrame;
56 IDeckLinkKeyer* m_deckLinkKeyer;
57 bool m_terminate_on_pause;
61 IDeckLinkDisplayMode* getDisplayMode()
63 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( getConsumer() ) );
64 IDeckLinkDisplayModeIterator* iter;
65 IDeckLinkDisplayMode* mode;
66 IDeckLinkDisplayMode* result = 0;
68 if ( m_deckLinkOutput->GetDisplayModeIterator( &iter ) == S_OK )
70 while ( !result && iter->Next( &mode ) == S_OK )
72 m_width = mode->GetWidth();
73 m_height = mode->GetHeight();
74 mode->GetFrameRate( &m_duration, &m_timescale );
75 m_fps = (double) m_timescale / m_duration;
76 int p = mode->GetFieldDominance() == bmdProgressiveFrame;
77 mlt_log_verbose( getConsumer(), "BMD mode %dx%d %.3f fps prog %d\n", m_width, m_height, m_fps, p );
79 if ( m_width == profile->width && m_height == profile->height && p == profile->progressive
80 && m_fps == mlt_profile_fps( profile ) )
89 mlt_consumer getConsumer()
90 { return &m_consumer; }
94 if ( m_deckLinkKeyer )
95 m_deckLinkKeyer->Release();
96 if ( m_deckLinkOutput )
97 m_deckLinkOutput->Release();
99 m_deckLink->Release();
102 bool open( unsigned card = 0 )
106 IDeckLinkIterator* deckLinkIterator = NULL;
107 HRESULT result = CoInitialize( NULL );
108 if ( FAILED( result ) )
110 mlt_log_error( getConsumer(), "COM initialization failed\n" );
113 result = CoCreateInstance( CLSID_CDeckLinkIterator, NULL, CLSCTX_ALL, IID_IDeckLinkIterator, (void**) &deckLinkIterator );
114 if ( FAILED( result ) )
116 mlt_log_error( getConsumer(), "The DeckLink drivers not installed.\n" );
120 IDeckLinkIterator* deckLinkIterator = CreateDeckLinkIteratorInstance();
122 if ( !deckLinkIterator )
124 mlt_log_error( getConsumer(), "The DeckLink drivers not installed.\n" );
129 // Connect to the Nth DeckLink instance
131 if ( deckLinkIterator->Next( &m_deckLink ) != S_OK )
133 mlt_log_error( getConsumer(), "DeckLink card not found\n" );
134 deckLinkIterator->Release();
137 } while ( ++i <= card );
138 deckLinkIterator->Release();
140 // Obtain the audio/video output interface (IDeckLinkOutput)
141 if ( m_deckLink->QueryInterface( IID_IDeckLinkOutput, (void**)&m_deckLinkOutput ) != S_OK )
143 mlt_log_error( getConsumer(), "No DeckLink cards support output\n" );
144 m_deckLink->Release();
149 // Get the keyer interface
150 IDeckLinkAttributes *deckLinkAttributes = 0;
152 if ( m_deckLink->QueryInterface( IID_IDeckLinkAttributes, (void**) &deckLinkAttributes ) == S_OK )
159 if ( deckLinkAttributes->GetFlag( BMDDeckLinkSupportsInternalKeying, &flag ) == S_OK && flag )
161 if ( m_deckLink->QueryInterface( IID_IDeckLinkKeyer, (void**) &m_deckLinkKeyer ) != S_OK )
163 mlt_log_error( getConsumer(), "Failed to get keyer\n" );
164 m_deckLinkOutput->Release();
165 m_deckLinkOutput = 0;
166 m_deckLink->Release();
171 deckLinkAttributes->Release();
174 // Provide this class as a delegate to the audio and video output interfaces
175 m_deckLinkOutput->SetScheduledFrameCompletionCallback( this );
180 bool start( unsigned preroll )
183 mlt_properties properties = MLT_CONSUMER_PROPERTIES( getConsumer() );
185 // Initialize members
188 m_decklinkFrame = NULL;
189 preroll = preroll < PREROLL_MINIMUM ? PREROLL_MINIMUM : preroll;
190 m_channels = mlt_properties_get_int( properties, "channels" );
191 m_isAudio = !mlt_properties_get_int( properties, "audio_off" );
192 m_terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
195 m_displayMode = getDisplayMode();
196 if ( !m_displayMode )
198 mlt_log_error( getConsumer(), "Profile is not compatible with decklink.\n" );
203 if ( m_deckLinkKeyer && ( m_isKeyer = mlt_properties_get_int( properties, "keyer" ) ) )
205 bool external = (m_isKeyer == 2);
206 double level = mlt_properties_get_double( properties, "keyer_level" );
208 if ( m_deckLinkKeyer->Enable( external ) != S_OK )
209 mlt_log_error( getConsumer(), "Failed to enable %s keyer\n",
210 external ? "external" : "internal" );
211 m_deckLinkKeyer->SetLevel( level <= 1 ? ( level > 0 ? 255 * level : 255 ) : 255 );
213 else if ( m_deckLinkKeyer )
215 m_deckLinkKeyer->Disable();
218 // Set the video output mode
219 if ( S_OK != m_deckLinkOutput->EnableVideoOutput( m_displayMode->GetDisplayMode(), bmdVideoOutputFlagDefault) )
221 mlt_log_error( getConsumer(), "Failed to enable video output\n" );
225 // Set the audio output mode
228 m_deckLinkOutput->DisableAudioOutput();
231 if ( S_OK != m_deckLinkOutput->EnableAudioOutput( bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger,
232 m_channels, bmdAudioOutputStreamTimestamped ) )
234 mlt_log_error( getConsumer(), "Failed to enable audio output\n" );
242 for( i = 0; i < preroll; i++ )
243 ScheduleNextFrame( true );
245 // start scheduled playback
246 m_deckLinkOutput->StartScheduledPlayback( 0, m_timescale, 1.0 );
248 // Set the running state
249 mlt_properties_set_int( properties, "running", 1 );
256 mlt_properties properties = MLT_CONSUMER_PROPERTIES( getConsumer() );
258 // set running state is 0
259 mlt_properties_set_int( properties, "running", 0 );
260 mlt_consumer_stopped( getConsumer() );
262 // release decklink frame
263 if ( m_decklinkFrame )
264 m_decklinkFrame->Release();
265 m_decklinkFrame = NULL;
267 // Stop the audio and video output streams immediately
268 if ( m_deckLinkOutput )
270 m_deckLinkOutput->StopScheduledPlayback( 0, 0, 0 );
271 m_deckLinkOutput->DisableAudioOutput();
272 m_deckLinkOutput->DisableVideoOutput();
278 void renderAudio( mlt_frame frame )
280 mlt_audio_format format = mlt_audio_s16;
281 int frequency = bmdAudioSampleRate48kHz;
282 int samples = mlt_sample_calculator( m_fps, frequency, m_count );
285 if ( !mlt_frame_get_audio( frame, (void**) &pcm, &format, &frequency, &m_channels, &samples ) )
287 uint32_t written = 0;
288 BMDTimeValue streamTime = m_count * frequency * m_duration / m_timescale;
289 m_deckLinkOutput->GetBufferedAudioSampleFrameCount(&written);
290 if ( written > (m_preroll + 1) * samples )
292 mlt_log_verbose( getConsumer(), "renderAudio: will flush %d audiosamples\n", written);
293 m_deckLinkOutput->FlushBufferedAudioSamples();
296 m_deckLinkOutput->ScheduleAudioSamples( pcm, samples, streamTime, frequency, (unsigned long*) &written );
298 m_deckLinkOutput->ScheduleAudioSamples( pcm, samples, streamTime, frequency, &written );
301 if ( written != (uint32_t) samples )
302 mlt_log_verbose( getConsumer(), "renderAudio: samples=%d, written=%u\n", samples, written );
306 bool createFrame( IDeckLinkMutableVideoFrame** decklinkFrame )
308 BMDPixelFormat format = m_isKeyer? bmdFormat8BitARGB : bmdFormat8BitYUV;
309 IDeckLinkMutableVideoFrame* frame = 0;
311 int stride = m_width * ( m_isKeyer? 4 : 2 );
313 *decklinkFrame = NULL;
315 // Generate a DeckLink video frame
316 if ( S_OK != m_deckLinkOutput->CreateVideoFrame( m_width, m_height,
317 stride, format, bmdFrameFlagDefault, &frame ) )
319 mlt_log_verbose( getConsumer(), "Failed to create video frame\n" );
324 // Make the first line black for field order correction.
325 if ( S_OK == frame->GetBytes( (void**) &buffer ) && buffer )
329 memset( buffer, 0, stride );
331 else for ( int i = 0; i < m_width; i++ )
338 *decklinkFrame = frame;
343 void renderVideo( mlt_frame frame )
345 mlt_image_format format = m_isKeyer? mlt_image_rgb24a : mlt_image_yuv422;
347 int rendered = mlt_properties_get_int( MLT_FRAME_PROPERTIES(frame), "rendered");
349 if ( rendered && !mlt_frame_get_image( frame, &image, &format, &m_width, &m_height, 0 ) )
352 int stride = m_width * ( m_isKeyer? 4 : 2 );
354 if ( m_decklinkFrame )
355 m_decklinkFrame->Release();
356 if ( createFrame( &m_decklinkFrame ) )
357 m_decklinkFrame->GetBytes( (void**) &buffer );
361 int progressive = mlt_properties_get_int( MLT_FRAME_PROPERTIES( frame ), "progressive" );
365 // Normal non-keyer playout - needs byte swapping
366 if ( !progressive && m_displayMode->GetFieldDominance() == bmdUpperFieldFirst )
367 // convert lower field first to top field first
368 swab( (char*) image, (char*) buffer + stride, stride * ( m_height - 1 ) );
370 swab( (char*) image, (char*) buffer, stride * m_height );
372 else if ( !mlt_properties_get_int( MLT_FRAME_PROPERTIES( frame ), "test_image" ) )
374 // Normal keyer output
375 int y = m_height + 1;
376 uint32_t* s = (uint32_t*) image;
377 uint32_t* d = (uint32_t*) buffer;
379 if ( !progressive && m_displayMode->GetFieldDominance() == bmdUpperFieldFirst )
381 // Correct field order
387 // Need to relocate alpha channel RGBA => ARGB
393 *d++ = ( *s << 8 ) | ( *s >> 24 );
400 // Keying blank frames - nullify alpha
401 memset( buffer, 0, stride * m_height );
405 if ( m_decklinkFrame )
406 m_deckLinkOutput->ScheduleVideoFrame( m_decklinkFrame, m_count * m_duration, m_duration, m_timescale );
409 mlt_log_verbose( getConsumer(), "dropped video frame %u\n", ++m_dropped );
412 HRESULT render( mlt_frame frame )
414 HRESULT result = S_OK;
417 double speed = mlt_properties_get_double( MLT_FRAME_PROPERTIES(frame), "_speed" );
418 if ( m_isAudio && speed == 1.0 )
419 renderAudio( frame );
422 renderVideo( frame );
428 // *** DeckLink API implementation of IDeckLinkVideoOutputCallback IDeckLinkAudioOutputCallback *** //
430 // IUnknown needs only a dummy implementation
431 virtual HRESULT STDMETHODCALLTYPE QueryInterface( REFIID iid, LPVOID *ppv )
432 { return E_NOINTERFACE; }
433 virtual ULONG STDMETHODCALLTYPE AddRef()
435 virtual ULONG STDMETHODCALLTYPE Release()
438 /************************* DeckLink API Delegate Methods *****************************/
440 virtual HRESULT STDMETHODCALLTYPE ScheduledFrameCompleted( IDeckLinkVideoFrame* completedFrame, BMDOutputFrameCompletionResult completed )
443 m_deckLinkOutput->GetBufferedAudioSampleFrameCount(&cnt);
446 mlt_log_verbose( getConsumer(),
447 "ScheduledFrameCompleted: GetBufferedAudioSampleFrameCount %u -> %u, m_count=%"PRIu64"\n",
448 m_acnt, cnt, m_count );
452 // When a video frame has been released by the API, schedule another video frame to be output
454 // ignore handler if frame was flushed
455 if(bmdOutputFrameFlushed == completed)
458 // schedule next frame
459 ScheduleNextFrame(false);
461 // step forward frames counter if underrun
462 if(bmdOutputFrameDisplayedLate == completed)
464 mlt_log_verbose( getConsumer(), "ScheduledFrameCompleted: bmdOutputFrameDisplayedLate == completed\n");
467 if(bmdOutputFrameDropped == completed)
469 mlt_log_verbose( getConsumer(), "ScheduledFrameCompleted: bmdOutputFrameDropped == completed\n");
476 virtual HRESULT STDMETHODCALLTYPE ScheduledPlaybackHasStopped()
478 return mlt_consumer_is_stopped( getConsumer() ) ? S_FALSE : S_OK;
482 void ScheduleNextFrame(bool preroll)
485 mlt_consumer consumer = getConsumer();
487 // Get the properties
488 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
491 mlt_frame frame = NULL;
493 if( mlt_properties_get_int( properties, "running" ) || preroll )
495 frame = mlt_consumer_rt_frame( consumer );
500 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
502 // terminate on pause
503 if (m_terminate_on_pause &&
504 mlt_properties_get_double( MLT_FRAME_PROPERTIES( frame ), "_speed" ) == 0.0)
507 mlt_frame_close( frame );
513 /** Start the consumer.
516 static int start( mlt_consumer consumer )
518 // Get the properties
519 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
520 DeckLinkConsumer* decklink = (DeckLinkConsumer*) consumer->child;
521 return decklink->start( mlt_properties_get_int( properties, "preroll" ) ) ? 0 : 1;
524 /** Stop the consumer.
527 static int stop( mlt_consumer consumer )
529 // Get the properties
530 DeckLinkConsumer* decklink = (DeckLinkConsumer*) consumer->child;
531 return decklink->stop();
534 /** Determine if the consumer is stopped.
537 static int is_stopped( mlt_consumer consumer )
539 // Get the properties
540 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
541 return !mlt_properties_get_int( properties, "running" );
544 /** Close the consumer.
547 static void close( mlt_consumer consumer )
550 mlt_consumer_stop( consumer );
553 consumer->close = NULL;
554 mlt_consumer_close( consumer );
557 delete (DeckLinkConsumer*) consumer->child;
562 /** Initialise the consumer.
565 mlt_consumer consumer_decklink_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
567 // Allocate the consumer
568 DeckLinkConsumer* decklink = new DeckLinkConsumer();
569 mlt_consumer consumer = NULL;
572 if ( decklink && !mlt_consumer_init( decklink->getConsumer(), decklink, profile ) )
574 // If initialises without error
575 if ( decklink->open( arg? atoi(arg) : 0 ) )
577 consumer = decklink->getConsumer();
580 consumer->close = close;
581 consumer->start = start;
582 consumer->stop = stop;
583 consumer->is_stopped = is_stopped;
584 mlt_properties_set( MLT_CONSUMER_PROPERTIES(consumer), "deinterlace_method", "onefield" );
592 extern mlt_producer producer_decklink_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg );
594 static mlt_properties metadata( mlt_service_type type, const char *id, void *data )
596 char file[ PATH_MAX ];
597 const char *service_type = NULL;
601 service_type = "consumer";
604 service_type = "producer";
609 snprintf( file, PATH_MAX, "%s/decklink/%s_%s.yml", mlt_environment( "MLT_DATA" ), service_type, id );
610 return mlt_properties_parse_yaml( file );
615 MLT_REGISTER( consumer_type, "decklink", consumer_decklink_init );
616 MLT_REGISTER( producer_type, "decklink", producer_decklink_init );
617 MLT_REGISTER_METADATA( consumer_type, "decklink", metadata, NULL );
618 MLT_REGISTER_METADATA( producer_type, "decklink", metadata, NULL );