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 && p == profile->progressive
81 && m_fps == mlt_profile_fps( profile )
82 && ( m_height == profile->height || ( m_height == 486 && profile->height == 480 ) ) )
91 mlt_consumer getConsumer()
92 { return &m_consumer; }
96 if ( m_deckLinkKeyer )
97 m_deckLinkKeyer->Release();
98 if ( m_deckLinkOutput )
99 m_deckLinkOutput->Release();
101 m_deckLink->Release();
104 bool open( unsigned card = 0 )
108 IDeckLinkIterator* deckLinkIterator = NULL;
109 HRESULT result = CoInitialize( NULL );
110 if ( FAILED( result ) )
112 mlt_log_error( getConsumer(), "COM initialization failed\n" );
115 result = CoCreateInstance( CLSID_CDeckLinkIterator, NULL, CLSCTX_ALL, IID_IDeckLinkIterator, (void**) &deckLinkIterator );
116 if ( FAILED( result ) )
118 mlt_log_error( getConsumer(), "The DeckLink drivers not installed.\n" );
122 IDeckLinkIterator* deckLinkIterator = CreateDeckLinkIteratorInstance();
124 if ( !deckLinkIterator )
126 mlt_log_error( getConsumer(), "The DeckLink drivers not installed.\n" );
131 // Connect to the Nth DeckLink instance
133 if ( deckLinkIterator->Next( &m_deckLink ) != S_OK )
135 mlt_log_error( getConsumer(), "DeckLink card not found\n" );
136 deckLinkIterator->Release();
139 } while ( ++i <= card );
140 deckLinkIterator->Release();
142 // Obtain the audio/video output interface (IDeckLinkOutput)
143 if ( m_deckLink->QueryInterface( IID_IDeckLinkOutput, (void**)&m_deckLinkOutput ) != S_OK )
145 mlt_log_error( getConsumer(), "No DeckLink cards support output\n" );
146 m_deckLink->Release();
151 // Get the keyer interface
152 IDeckLinkAttributes *deckLinkAttributes = 0;
154 if ( m_deckLink->QueryInterface( IID_IDeckLinkAttributes, (void**) &deckLinkAttributes ) == S_OK )
161 if ( deckLinkAttributes->GetFlag( BMDDeckLinkSupportsInternalKeying, &flag ) == S_OK && flag )
163 if ( m_deckLink->QueryInterface( IID_IDeckLinkKeyer, (void**) &m_deckLinkKeyer ) != S_OK )
165 mlt_log_error( getConsumer(), "Failed to get keyer\n" );
166 m_deckLinkOutput->Release();
167 m_deckLinkOutput = 0;
168 m_deckLink->Release();
173 deckLinkAttributes->Release();
176 // Provide this class as a delegate to the audio and video output interfaces
177 m_deckLinkOutput->SetScheduledFrameCompletionCallback( this );
182 bool start( unsigned preroll )
185 mlt_properties properties = MLT_CONSUMER_PROPERTIES( getConsumer() );
187 // Initialize members
190 m_decklinkFrame = NULL;
191 preroll = preroll < PREROLL_MINIMUM ? PREROLL_MINIMUM : preroll;
192 m_channels = mlt_properties_get_int( properties, "channels" );
193 m_isAudio = !mlt_properties_get_int( properties, "audio_off" );
194 m_terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
197 m_displayMode = getDisplayMode();
198 if ( !m_displayMode )
200 mlt_log_error( getConsumer(), "Profile is not compatible with decklink.\n" );
205 if ( m_deckLinkKeyer && ( m_isKeyer = mlt_properties_get_int( properties, "keyer" ) ) )
207 bool external = ( m_isKeyer == 2 );
208 double level = mlt_properties_get_double( properties, "keyer_level" );
210 if ( m_deckLinkKeyer->Enable( external ) != S_OK )
211 mlt_log_error( getConsumer(), "Failed to enable %s keyer\n",
212 external ? "external" : "internal" );
213 m_deckLinkKeyer->SetLevel( level <= 1 ? ( level > 0 ? 255 * level : 255 ) : 255 );
215 else if ( m_deckLinkKeyer )
217 m_deckLinkKeyer->Disable();
220 // Set the video output mode
221 if ( S_OK != m_deckLinkOutput->EnableVideoOutput( m_displayMode->GetDisplayMode(), bmdVideoOutputFlagDefault ) )
223 mlt_log_error( getConsumer(), "Failed to enable video output\n" );
227 // Set the audio output mode
230 m_deckLinkOutput->DisableAudioOutput();
233 if ( S_OK != m_deckLinkOutput->EnableAudioOutput( bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger,
234 m_channels, bmdAudioOutputStreamTimestamped ) )
236 mlt_log_error( getConsumer(), "Failed to enable audio output\n" );
245 for( i = 0; i < preroll; i++ )
246 ScheduleNextFrame( true );
248 // start scheduled playback
249 m_deckLinkOutput->StartScheduledPlayback( 0, m_timescale, 1.0 );
251 // Set the running state
252 mlt_properties_set_int( properties, "running", 1 );
259 mlt_properties properties = MLT_CONSUMER_PROPERTIES( getConsumer() );
261 // set running state is 0
262 mlt_properties_set_int( properties, "running", 0 );
263 mlt_consumer_stopped( getConsumer() );
265 // release decklink frame
266 if ( m_decklinkFrame )
267 m_decklinkFrame->Release();
268 m_decklinkFrame = NULL;
270 // Stop the audio and video output streams immediately
271 if ( m_deckLinkOutput )
273 m_deckLinkOutput->StopScheduledPlayback( 0, 0, 0 );
274 m_deckLinkOutput->DisableAudioOutput();
275 m_deckLinkOutput->DisableVideoOutput();
281 void renderAudio( mlt_frame frame )
283 mlt_audio_format format = mlt_audio_s16;
284 int frequency = bmdAudioSampleRate48kHz;
285 int samples = mlt_sample_calculator( m_fps, frequency, m_count );
288 if ( !mlt_frame_get_audio( frame, (void**) &pcm, &format, &frequency, &m_channels, &samples ) )
291 unsigned long written = 0;
293 uint32_t written = 0;
295 BMDTimeValue streamTime = m_count * frequency * m_duration / m_timescale;
296 m_deckLinkOutput->GetBufferedAudioSampleFrameCount( &written );
297 if ( written > (m_preroll + 1) * samples )
299 mlt_log_verbose( getConsumer(), "renderAudio: will flush %lu audiosamples\n", written );
300 m_deckLinkOutput->FlushBufferedAudioSamples();
303 m_deckLinkOutput->ScheduleAudioSamples( pcm, samples, streamTime, frequency, (unsigned long*) &written );
305 m_deckLinkOutput->ScheduleAudioSamples( pcm, samples, streamTime, frequency, &written );
308 if ( written != (uint32_t) samples )
309 mlt_log_verbose( getConsumer(), "renderAudio: samples=%d, written=%lu\n", samples, written );
313 bool createFrame( IDeckLinkMutableVideoFrame** decklinkFrame )
315 BMDPixelFormat format = m_isKeyer? bmdFormat8BitARGB : bmdFormat8BitYUV;
316 IDeckLinkMutableVideoFrame* frame = 0;
318 int stride = m_width * ( m_isKeyer? 4 : 2 );
320 *decklinkFrame = NULL;
322 // Generate a DeckLink video frame
323 if ( S_OK != m_deckLinkOutput->CreateVideoFrame( m_width, m_height,
324 stride, format, bmdFrameFlagDefault, &frame ) )
326 mlt_log_verbose( getConsumer(), "Failed to create video frame\n" );
331 // Make the first line black for field order correction.
332 if ( S_OK == frame->GetBytes( (void**) &buffer ) && buffer )
336 memset( buffer, 0, stride );
338 else for ( int i = 0; i < m_width; i++ )
345 *decklinkFrame = frame;
350 void renderVideo( mlt_frame frame )
352 mlt_image_format format = m_isKeyer? mlt_image_rgb24a : mlt_image_yuv422;
354 int rendered = mlt_properties_get_int( MLT_FRAME_PROPERTIES(frame), "rendered");
355 int height = m_height;
357 if ( rendered && !mlt_frame_get_image( frame, &image, &format, &m_width, &height, 0 ) )
360 int stride = m_width * ( m_isKeyer? 4 : 2 );
362 if ( m_decklinkFrame )
363 m_decklinkFrame->Release();
364 if ( createFrame( &m_decklinkFrame ) )
365 m_decklinkFrame->GetBytes( (void**) &buffer );
369 int progressive = mlt_properties_get_int( MLT_FRAME_PROPERTIES( frame ), "progressive" );
371 // NTSC SDI is always 486 lines
372 if ( m_height == 486 && height == 480 )
374 // blank first 6 lines
377 memset( buffer, 0, stride * 6 );
378 buffer += stride * 6;
380 else for ( int i = 0; i < m_width * 6; i++ )
388 // Normal non-keyer playout - needs byte swapping
389 if ( !progressive && m_displayMode->GetFieldDominance() == bmdUpperFieldFirst )
390 // convert lower field first to top field first
391 swab( (char*) image, (char*) buffer + stride, stride * ( height - 1 ) );
393 swab( (char*) image, (char*) buffer, stride * height );
395 else if ( !mlt_properties_get_int( MLT_FRAME_PROPERTIES( frame ), "test_image" ) )
397 // Normal keyer output
399 uint32_t* s = (uint32_t*) image;
400 uint32_t* d = (uint32_t*) buffer;
402 if ( !progressive && m_displayMode->GetFieldDominance() == bmdUpperFieldFirst )
404 // Correct field order
410 // Need to relocate alpha channel RGBA => ARGB
416 *d++ = ( *s << 8 ) | ( *s >> 24 );
423 // Keying blank frames - nullify alpha
424 memset( buffer, 0, stride * height );
428 if ( m_decklinkFrame )
429 m_deckLinkOutput->ScheduleVideoFrame( m_decklinkFrame, m_count * m_duration, m_duration, m_timescale );
432 mlt_log_verbose( getConsumer(), "dropped video frame %u\n", ++m_dropped );
435 HRESULT render( mlt_frame frame )
437 HRESULT result = S_OK;
440 double speed = mlt_properties_get_double( MLT_FRAME_PROPERTIES(frame), "_speed" );
441 if ( m_isAudio && speed == 1.0 )
442 renderAudio( frame );
445 renderVideo( frame );
451 // *** DeckLink API implementation of IDeckLinkVideoOutputCallback IDeckLinkAudioOutputCallback *** //
453 // IUnknown needs only a dummy implementation
454 virtual HRESULT STDMETHODCALLTYPE QueryInterface( REFIID iid, LPVOID *ppv )
455 { return E_NOINTERFACE; }
456 virtual ULONG STDMETHODCALLTYPE AddRef()
458 virtual ULONG STDMETHODCALLTYPE Release()
461 /************************* DeckLink API Delegate Methods *****************************/
463 virtual HRESULT STDMETHODCALLTYPE ScheduledFrameCompleted( IDeckLinkVideoFrame* completedFrame, BMDOutputFrameCompletionResult completed )
467 mlt_properties properties = MLT_CONSUMER_PROPERTIES( getConsumer() );
469 if ( mlt_properties_get( properties, "priority" ) )
473 pthread_attr_t tattr;
474 struct sched_param param;
476 pthread_attr_init(&tattr);
477 pthread_attr_setschedpolicy(&tattr, SCHED_FIFO);
479 if ( !strcmp( "max", mlt_properties_get( properties, "priority" ) ) )
480 param.sched_priority = sched_get_priority_max(SCHED_FIFO) - 1;
481 else if ( !strcmp( "min", mlt_properties_get( properties, "priority" ) ) )
482 param.sched_priority = sched_get_priority_min(SCHED_FIFO) + 1;
484 param.sched_priority = mlt_properties_get_int( properties, "priority" );
486 pthread_attr_setschedparam(&tattr, ¶m);
488 thread = pthread_self();
490 r = pthread_setschedparam(thread, SCHED_FIFO, ¶m);
492 mlt_log_verbose( getConsumer(),
493 "ScheduledFrameCompleted: pthread_setschedparam retured %d\n", r);
495 mlt_log_verbose( getConsumer(),
496 "ScheduledFrameCompleted: param.sched_priority=%d\n", param.sched_priority);
507 m_deckLinkOutput->GetBufferedAudioSampleFrameCount( &cnt );
510 mlt_log_verbose( getConsumer(),
511 "ScheduledFrameCompleted: GetBufferedAudioSampleFrameCount %u -> %lu, m_count=%"PRIu64"\n",
512 m_acnt, cnt, m_count );
516 // When a video frame has been released by the API, schedule another video frame to be output
518 // ignore handler if frame was flushed
519 if ( bmdOutputFrameFlushed == completed )
522 // schedule next frame
523 ScheduleNextFrame( false );
525 // step forward frames counter if underrun
526 if ( bmdOutputFrameDisplayedLate == completed )
528 mlt_log_verbose( getConsumer(), "ScheduledFrameCompleted: bmdOutputFrameDisplayedLate == completed\n" );
531 if ( bmdOutputFrameDropped == completed )
533 mlt_log_verbose( getConsumer(), "ScheduledFrameCompleted: bmdOutputFrameDropped == completed\n" );
540 virtual HRESULT STDMETHODCALLTYPE ScheduledPlaybackHasStopped()
542 return mlt_consumer_is_stopped( getConsumer() ) ? S_FALSE : S_OK;
546 void ScheduleNextFrame( bool preroll )
549 mlt_consumer consumer = getConsumer();
551 // Get the properties
552 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
555 mlt_frame frame = NULL;
557 if( mlt_properties_get_int( properties, "running" ) || preroll )
559 frame = mlt_consumer_rt_frame( consumer );
564 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
566 // terminate on pause
567 if ( m_terminate_on_pause &&
568 mlt_properties_get_double( MLT_FRAME_PROPERTIES( frame ), "_speed" ) == 0.0 )
571 mlt_frame_close( frame );
577 /** Start the consumer.
580 static int start( mlt_consumer consumer )
582 // Get the properties
583 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
584 DeckLinkConsumer* decklink = (DeckLinkConsumer*) consumer->child;
585 return decklink->start( mlt_properties_get_int( properties, "preroll" ) ) ? 0 : 1;
588 /** Stop the consumer.
591 static int stop( mlt_consumer consumer )
593 // Get the properties
594 DeckLinkConsumer* decklink = (DeckLinkConsumer*) consumer->child;
595 return decklink->stop();
598 /** Determine if the consumer is stopped.
601 static int is_stopped( mlt_consumer consumer )
603 // Get the properties
604 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
605 return !mlt_properties_get_int( properties, "running" );
608 /** Close the consumer.
611 static void close( mlt_consumer consumer )
614 mlt_consumer_stop( consumer );
617 consumer->close = NULL;
618 mlt_consumer_close( consumer );
621 delete (DeckLinkConsumer*) consumer->child;
626 /** Initialise the consumer.
629 mlt_consumer consumer_decklink_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
631 // Allocate the consumer
632 DeckLinkConsumer* decklink = new DeckLinkConsumer();
633 mlt_consumer consumer = NULL;
636 if ( decklink && !mlt_consumer_init( decklink->getConsumer(), decklink, profile ) )
638 // If initialises without error
639 if ( decklink->open( arg? atoi(arg) : 0 ) )
641 consumer = decklink->getConsumer();
644 consumer->close = close;
645 consumer->start = start;
646 consumer->stop = stop;
647 consumer->is_stopped = is_stopped;
648 mlt_properties_set( MLT_CONSUMER_PROPERTIES(consumer), "deinterlace_method", "onefield" );
656 extern mlt_producer producer_decklink_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg );
658 static mlt_properties metadata( mlt_service_type type, const char *id, void *data )
660 char file[ PATH_MAX ];
661 const char *service_type = NULL;
665 service_type = "consumer";
668 service_type = "producer";
673 snprintf( file, PATH_MAX, "%s/decklink/%s_%s.yml", mlt_environment( "MLT_DATA" ), service_type, id );
674 return mlt_properties_parse_yaml( file );
679 MLT_REGISTER( consumer_type, "decklink", consumer_decklink_init );
680 MLT_REGISTER( producer_type, "decklink", producer_decklink_init );
681 MLT_REGISTER_METADATA( consumer_type, "decklink", metadata, NULL );
682 MLT_REGISTER_METADATA( producer_type, "decklink", metadata, NULL );