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;
62 IDeckLinkDisplayMode* getDisplayMode()
64 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( getConsumer() ) );
65 IDeckLinkDisplayModeIterator* iter;
66 IDeckLinkDisplayMode* mode;
67 IDeckLinkDisplayMode* result = 0;
69 if ( m_deckLinkOutput->GetDisplayModeIterator( &iter ) == S_OK )
71 while ( !result && iter->Next( &mode ) == S_OK )
73 m_width = mode->GetWidth();
74 m_height = mode->GetHeight();
75 mode->GetFrameRate( &m_duration, &m_timescale );
76 m_fps = (double) m_timescale / m_duration;
77 int p = mode->GetFieldDominance() == bmdProgressiveFrame;
78 mlt_log_verbose( getConsumer(), "BMD mode %dx%d %.3f fps prog %d\n", m_width, m_height, m_fps, p );
80 if ( m_width == profile->width && m_height == profile->height && p == profile->progressive
81 && m_fps == mlt_profile_fps( profile ) )
90 mlt_consumer getConsumer()
91 { return &m_consumer; }
95 if ( m_deckLinkKeyer )
96 m_deckLinkKeyer->Release();
97 if ( m_deckLinkOutput )
98 m_deckLinkOutput->Release();
100 m_deckLink->Release();
103 bool open( unsigned card = 0 )
107 IDeckLinkIterator* deckLinkIterator = NULL;
108 HRESULT result = CoInitialize( NULL );
109 if ( FAILED( result ) )
111 mlt_log_error( getConsumer(), "COM initialization failed\n" );
114 result = CoCreateInstance( CLSID_CDeckLinkIterator, NULL, CLSCTX_ALL, IID_IDeckLinkIterator, (void**) &deckLinkIterator );
115 if ( FAILED( result ) )
117 mlt_log_error( getConsumer(), "The DeckLink drivers not installed.\n" );
121 IDeckLinkIterator* deckLinkIterator = CreateDeckLinkIteratorInstance();
123 if ( !deckLinkIterator )
125 mlt_log_error( getConsumer(), "The DeckLink drivers not installed.\n" );
130 // Connect to the Nth DeckLink instance
132 if ( deckLinkIterator->Next( &m_deckLink ) != S_OK )
134 mlt_log_error( getConsumer(), "DeckLink card not found\n" );
135 deckLinkIterator->Release();
138 } while ( ++i <= card );
139 deckLinkIterator->Release();
141 // Obtain the audio/video output interface (IDeckLinkOutput)
142 if ( m_deckLink->QueryInterface( IID_IDeckLinkOutput, (void**)&m_deckLinkOutput ) != S_OK )
144 mlt_log_error( getConsumer(), "No DeckLink cards support output\n" );
145 m_deckLink->Release();
150 // Get the keyer interface
151 IDeckLinkAttributes *deckLinkAttributes = 0;
153 if ( m_deckLink->QueryInterface( IID_IDeckLinkAttributes, (void**) &deckLinkAttributes ) == S_OK )
160 if ( deckLinkAttributes->GetFlag( BMDDeckLinkSupportsInternalKeying, &flag ) == S_OK && flag )
162 if ( m_deckLink->QueryInterface( IID_IDeckLinkKeyer, (void**) &m_deckLinkKeyer ) != S_OK )
164 mlt_log_error( getConsumer(), "Failed to get keyer\n" );
165 m_deckLinkOutput->Release();
166 m_deckLinkOutput = 0;
167 m_deckLink->Release();
172 deckLinkAttributes->Release();
175 // Provide this class as a delegate to the audio and video output interfaces
176 m_deckLinkOutput->SetScheduledFrameCompletionCallback( this );
181 bool start( unsigned preroll )
184 mlt_properties properties = MLT_CONSUMER_PROPERTIES( getConsumer() );
186 // Initialize members
189 m_decklinkFrame = NULL;
190 preroll = preroll < PREROLL_MINIMUM ? PREROLL_MINIMUM : preroll;
191 m_channels = mlt_properties_get_int( properties, "channels" );
192 m_isAudio = !mlt_properties_get_int( properties, "audio_off" );
193 m_terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
196 m_displayMode = getDisplayMode();
197 if ( !m_displayMode )
199 mlt_log_error( getConsumer(), "Profile is not compatible with decklink.\n" );
204 if ( m_deckLinkKeyer && ( m_isKeyer = mlt_properties_get_int( properties, "keyer" ) ) )
206 bool external = ( m_isKeyer == 2 );
207 double level = mlt_properties_get_double( properties, "keyer_level" );
209 if ( m_deckLinkKeyer->Enable( external ) != S_OK )
210 mlt_log_error( getConsumer(), "Failed to enable %s keyer\n",
211 external ? "external" : "internal" );
212 m_deckLinkKeyer->SetLevel( level <= 1 ? ( level > 0 ? 255 * level : 255 ) : 255 );
214 else if ( m_deckLinkKeyer )
216 m_deckLinkKeyer->Disable();
219 // Set the video output mode
220 if ( S_OK != m_deckLinkOutput->EnableVideoOutput( m_displayMode->GetDisplayMode(), bmdVideoOutputFlagDefault ) )
222 mlt_log_error( getConsumer(), "Failed to enable video output\n" );
226 // Set the audio output mode
229 m_deckLinkOutput->DisableAudioOutput();
232 if ( S_OK != m_deckLinkOutput->EnableAudioOutput( bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger,
233 m_channels, bmdAudioOutputStreamTimestamped ) )
235 mlt_log_error( getConsumer(), "Failed to enable audio output\n" );
244 for( i = 0; i < preroll; i++ )
245 ScheduleNextFrame( true );
247 // start scheduled playback
248 m_deckLinkOutput->StartScheduledPlayback( 0, m_timescale, 1.0 );
250 // Set the running state
251 mlt_properties_set_int( properties, "running", 1 );
258 mlt_properties properties = MLT_CONSUMER_PROPERTIES( getConsumer() );
260 // set running state is 0
261 mlt_properties_set_int( properties, "running", 0 );
262 mlt_consumer_stopped( getConsumer() );
264 // release decklink frame
265 if ( m_decklinkFrame )
266 m_decklinkFrame->Release();
267 m_decklinkFrame = NULL;
269 // Stop the audio and video output streams immediately
270 if ( m_deckLinkOutput )
272 m_deckLinkOutput->StopScheduledPlayback( 0, 0, 0 );
273 m_deckLinkOutput->DisableAudioOutput();
274 m_deckLinkOutput->DisableVideoOutput();
280 void renderAudio( mlt_frame frame )
282 mlt_audio_format format = mlt_audio_s16;
283 int frequency = bmdAudioSampleRate48kHz;
284 int samples = mlt_sample_calculator( m_fps, frequency, m_count );
287 if ( !mlt_frame_get_audio( frame, (void**) &pcm, &format, &frequency, &m_channels, &samples ) )
289 uint32_t written = 0;
290 BMDTimeValue streamTime = m_count * frequency * m_duration / m_timescale;
291 m_deckLinkOutput->GetBufferedAudioSampleFrameCount( &written );
292 if ( written > (m_preroll + 1) * samples )
294 mlt_log_verbose( getConsumer(), "renderAudio: will flush %d audiosamples\n", written );
295 m_deckLinkOutput->FlushBufferedAudioSamples();
298 m_deckLinkOutput->ScheduleAudioSamples( pcm, samples, streamTime, frequency, (unsigned long*) &written );
300 m_deckLinkOutput->ScheduleAudioSamples( pcm, samples, streamTime, frequency, &written );
303 if ( written != (uint32_t) samples )
304 mlt_log_verbose( getConsumer(), "renderAudio: samples=%d, written=%u\n", samples, written );
308 bool createFrame( IDeckLinkMutableVideoFrame** decklinkFrame )
310 BMDPixelFormat format = m_isKeyer? bmdFormat8BitARGB : bmdFormat8BitYUV;
311 IDeckLinkMutableVideoFrame* frame = 0;
313 int stride = m_width * ( m_isKeyer? 4 : 2 );
315 *decklinkFrame = NULL;
317 // Generate a DeckLink video frame
318 if ( S_OK != m_deckLinkOutput->CreateVideoFrame( m_width, m_height,
319 stride, format, bmdFrameFlagDefault, &frame ) )
321 mlt_log_verbose( getConsumer(), "Failed to create video frame\n" );
326 // Make the first line black for field order correction.
327 if ( S_OK == frame->GetBytes( (void**) &buffer ) && buffer )
331 memset( buffer, 0, stride );
333 else for ( int i = 0; i < m_width; i++ )
340 *decklinkFrame = frame;
345 void renderVideo( mlt_frame frame )
347 mlt_image_format format = m_isKeyer? mlt_image_rgb24a : mlt_image_yuv422;
349 int rendered = mlt_properties_get_int( MLT_FRAME_PROPERTIES(frame), "rendered");
351 if ( rendered && !mlt_frame_get_image( frame, &image, &format, &m_width, &m_height, 0 ) )
354 int stride = m_width * ( m_isKeyer? 4 : 2 );
356 if ( m_decklinkFrame )
357 m_decklinkFrame->Release();
358 if ( createFrame( &m_decklinkFrame ) )
359 m_decklinkFrame->GetBytes( (void**) &buffer );
363 int progressive = mlt_properties_get_int( MLT_FRAME_PROPERTIES( frame ), "progressive" );
367 // Normal non-keyer playout - needs byte swapping
368 if ( !progressive && m_displayMode->GetFieldDominance() == bmdUpperFieldFirst )
369 // convert lower field first to top field first
370 swab( (char*) image, (char*) buffer + stride, stride * ( m_height - 1 ) );
372 swab( (char*) image, (char*) buffer, stride * m_height );
374 else if ( !mlt_properties_get_int( MLT_FRAME_PROPERTIES( frame ), "test_image" ) )
376 // Normal keyer output
377 int y = m_height + 1;
378 uint32_t* s = (uint32_t*) image;
379 uint32_t* d = (uint32_t*) buffer;
381 if ( !progressive && m_displayMode->GetFieldDominance() == bmdUpperFieldFirst )
383 // Correct field order
389 // Need to relocate alpha channel RGBA => ARGB
395 *d++ = ( *s << 8 ) | ( *s >> 24 );
402 // Keying blank frames - nullify alpha
403 memset( buffer, 0, stride * m_height );
407 if ( m_decklinkFrame )
408 m_deckLinkOutput->ScheduleVideoFrame( m_decklinkFrame, m_count * m_duration, m_duration, m_timescale );
411 mlt_log_verbose( getConsumer(), "dropped video frame %u\n", ++m_dropped );
414 HRESULT render( mlt_frame frame )
416 HRESULT result = S_OK;
419 double speed = mlt_properties_get_double( MLT_FRAME_PROPERTIES(frame), "_speed" );
420 if ( m_isAudio && speed == 1.0 )
421 renderAudio( frame );
424 renderVideo( frame );
430 // *** DeckLink API implementation of IDeckLinkVideoOutputCallback IDeckLinkAudioOutputCallback *** //
432 // IUnknown needs only a dummy implementation
433 virtual HRESULT STDMETHODCALLTYPE QueryInterface( REFIID iid, LPVOID *ppv )
434 { return E_NOINTERFACE; }
435 virtual ULONG STDMETHODCALLTYPE AddRef()
437 virtual ULONG STDMETHODCALLTYPE Release()
440 /************************* DeckLink API Delegate Methods *****************************/
442 virtual HRESULT STDMETHODCALLTYPE ScheduledFrameCompleted( IDeckLinkVideoFrame* completedFrame, BMDOutputFrameCompletionResult completed )
446 mlt_properties properties = MLT_CONSUMER_PROPERTIES( getConsumer() );
448 if ( mlt_properties_get( properties, "priority" ) )
452 pthread_attr_t tattr;
453 struct sched_param param;
455 pthread_attr_init(&tattr);
456 pthread_attr_setschedpolicy(&tattr, SCHED_FIFO);
458 if ( !strcmp( "max", mlt_properties_get( properties, "priority" ) ) )
459 param.sched_priority = sched_get_priority_max(SCHED_FIFO) - 1;
460 else if ( !strcmp( "min", mlt_properties_get( properties, "priority" ) ) )
461 param.sched_priority = sched_get_priority_min(SCHED_FIFO) + 1;
463 param.sched_priority = mlt_properties_get_int( properties, "priority" );
465 pthread_attr_setschedparam(&tattr, ¶m);
467 thread = pthread_self();
469 r = pthread_setschedparam(thread, SCHED_FIFO, ¶m);
471 mlt_log_verbose( getConsumer(),
472 "ScheduledFrameCompleted: pthread_setschedparam retured %d\n", r);
474 mlt_log_verbose( getConsumer(),
475 "ScheduledFrameCompleted: param.sched_priority=%d\n", param.sched_priority);
482 m_deckLinkOutput->GetBufferedAudioSampleFrameCount( &cnt );
485 mlt_log_verbose( getConsumer(),
486 "ScheduledFrameCompleted: GetBufferedAudioSampleFrameCount %u -> %u, m_count=%"PRIu64"\n",
487 m_acnt, cnt, m_count );
491 // When a video frame has been released by the API, schedule another video frame to be output
493 // ignore handler if frame was flushed
494 if ( bmdOutputFrameFlushed == completed )
497 // schedule next frame
498 ScheduleNextFrame( false );
500 // step forward frames counter if underrun
501 if ( bmdOutputFrameDisplayedLate == completed )
503 mlt_log_verbose( getConsumer(), "ScheduledFrameCompleted: bmdOutputFrameDisplayedLate == completed\n" );
506 if ( bmdOutputFrameDropped == completed )
508 mlt_log_verbose( getConsumer(), "ScheduledFrameCompleted: bmdOutputFrameDropped == completed\n" );
515 virtual HRESULT STDMETHODCALLTYPE ScheduledPlaybackHasStopped()
517 return mlt_consumer_is_stopped( getConsumer() ) ? S_FALSE : S_OK;
521 void ScheduleNextFrame( bool preroll )
524 mlt_consumer consumer = getConsumer();
526 // Get the properties
527 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
530 mlt_frame frame = NULL;
532 if( mlt_properties_get_int( properties, "running" ) || preroll )
534 frame = mlt_consumer_rt_frame( consumer );
539 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
541 // terminate on pause
542 if ( m_terminate_on_pause &&
543 mlt_properties_get_double( MLT_FRAME_PROPERTIES( frame ), "_speed" ) == 0.0 )
546 mlt_frame_close( frame );
552 /** Start the consumer.
555 static int start( mlt_consumer consumer )
557 // Get the properties
558 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
559 DeckLinkConsumer* decklink = (DeckLinkConsumer*) consumer->child;
560 return decklink->start( mlt_properties_get_int( properties, "preroll" ) ) ? 0 : 1;
563 /** Stop the consumer.
566 static int stop( mlt_consumer consumer )
568 // Get the properties
569 DeckLinkConsumer* decklink = (DeckLinkConsumer*) consumer->child;
570 return decklink->stop();
573 /** Determine if the consumer is stopped.
576 static int is_stopped( mlt_consumer consumer )
578 // Get the properties
579 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
580 return !mlt_properties_get_int( properties, "running" );
583 /** Close the consumer.
586 static void close( mlt_consumer consumer )
589 mlt_consumer_stop( consumer );
592 consumer->close = NULL;
593 mlt_consumer_close( consumer );
596 delete (DeckLinkConsumer*) consumer->child;
601 /** Initialise the consumer.
604 mlt_consumer consumer_decklink_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
606 // Allocate the consumer
607 DeckLinkConsumer* decklink = new DeckLinkConsumer();
608 mlt_consumer consumer = NULL;
611 if ( decklink && !mlt_consumer_init( decklink->getConsumer(), decklink, profile ) )
613 // If initialises without error
614 if ( decklink->open( arg? atoi(arg) : 0 ) )
616 consumer = decklink->getConsumer();
619 consumer->close = close;
620 consumer->start = start;
621 consumer->stop = stop;
622 consumer->is_stopped = is_stopped;
623 mlt_properties_set( MLT_CONSUMER_PROPERTIES(consumer), "deinterlace_method", "onefield" );
631 extern mlt_producer producer_decklink_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg );
633 static mlt_properties metadata( mlt_service_type type, const char *id, void *data )
635 char file[ PATH_MAX ];
636 const char *service_type = NULL;
640 service_type = "consumer";
643 service_type = "producer";
648 snprintf( file, PATH_MAX, "%s/decklink/%s_%s.yml", mlt_environment( "MLT_DATA" ), service_type, id );
649 return mlt_properties_parse_yaml( file );
654 MLT_REGISTER( consumer_type, "decklink", consumer_decklink_init );
655 MLT_REGISTER( producer_type, "decklink", producer_decklink_init );
656 MLT_REGISTER_METADATA( consumer_type, "decklink", metadata, NULL );
657 MLT_REGISTER_METADATA( producer_type, "decklink", metadata, NULL );