]> git.sesse.net Git - mlt/blob - src/modules/decklink/consumer_decklink.cpp
reorder startup/stopping preroll thread
[mlt] / src / modules / decklink / consumer_decklink.cpp
1 /*
2  * consumer_decklink.c -- output through Blackmagic Design DeckLink
3  * Copyright (C) 2010 Dan Dennedy <dan@dennedy.org>
4  *
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.
9  *
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.
14  *
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
18  */
19
20 #define __STDC_FORMAT_MACROS  /* see inttypes.h */
21 #include <framework/mlt.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <pthread.h>
25 #include <unistd.h>
26 #include <sys/time.h>
27 #include <limits.h>
28 #include <pthread.h>
29 #include "common.h"
30
31 static const unsigned PREROLL_MINIMUM = 3;
32
33 class DeckLinkConsumer
34         : public IDeckLinkVideoOutputCallback
35 {
36 private:
37         mlt_consumer_s              m_consumer;
38         IDeckLink*                  m_deckLink;
39         IDeckLinkOutput*            m_deckLinkOutput;
40         IDeckLinkDisplayMode*       m_displayMode;
41         int                         m_width;
42         int                         m_height;
43         BMDTimeValue                m_duration;
44         BMDTimeScale                m_timescale;
45         double                      m_fps;
46         uint64_t                    m_count;
47         int                         m_channels;
48         unsigned                    m_dropped;
49         IDeckLinkMutableVideoFrame* m_decklinkFrame;
50         bool                        m_isAudio;
51         int                         m_isKeyer;
52         IDeckLinkKeyer*             m_deckLinkKeyer;
53         bool                        m_terminate_on_pause;
54         uint32_t                    m_preroll;
55         uint32_t                    m_acnt;
56         bool                        m_reprio;
57         pthread_t                   m_prerollThread;
58
59         IDeckLinkDisplayMode* getDisplayMode()
60         {
61                 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( getConsumer() ) );
62                 IDeckLinkDisplayModeIterator* iter = NULL;
63                 IDeckLinkDisplayMode* mode = NULL;
64                 IDeckLinkDisplayMode* result = 0;
65
66                 if ( m_deckLinkOutput->GetDisplayModeIterator( &iter ) == S_OK )
67                 {
68                         while ( !result && iter->Next( &mode ) == S_OK )
69                         {
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 );
76
77                                 if ( m_width == profile->width && p == profile->progressive
78                                          && m_fps == mlt_profile_fps( profile )
79                                          && ( m_height == profile->height || ( m_height == 486 && profile->height == 480 ) ) )
80                                         result = mode;
81                                 else
82                                         SAFE_RELEASE( mode );
83                         }
84                         SAFE_RELEASE( iter );
85                 }
86
87                 return result;
88         }
89
90 public:
91         mlt_consumer getConsumer()
92                 { return &m_consumer; }
93
94         DeckLinkConsumer()
95         {
96                 m_displayMode = NULL;
97                 m_deckLinkKeyer = NULL;
98                 m_deckLinkOutput = NULL;
99                 m_deckLink = NULL;
100                 m_decklinkFrame = NULL;
101         }
102
103         ~DeckLinkConsumer()
104         {
105                 SAFE_RELEASE( m_displayMode );
106                 SAFE_RELEASE( m_deckLinkKeyer );
107                 SAFE_RELEASE( m_deckLinkOutput );
108                 SAFE_RELEASE( m_deckLink );
109         }
110
111         bool open( unsigned card = 0 )
112         {
113                 unsigned i = 0;
114 #ifdef WIN32
115                 IDeckLinkIterator* deckLinkIterator = NULL;
116                 HRESULT result =  CoInitialize( NULL );
117                 if ( FAILED( result ) )
118                 {
119                         mlt_log_error( getConsumer(), "COM initialization failed\n" );
120                         return false;
121                 }
122                 result = CoCreateInstance( CLSID_CDeckLinkIterator, NULL, CLSCTX_ALL, IID_IDeckLinkIterator, (void**) &deckLinkIterator );
123                 if ( FAILED( result ) )
124                 {
125                         mlt_log_error( getConsumer(), "The DeckLink drivers not installed.\n" );
126                         return false;
127                 }
128 #else
129                 IDeckLinkIterator* deckLinkIterator = CreateDeckLinkIteratorInstance();
130
131                 if ( !deckLinkIterator )
132                 {
133                         mlt_log_error( getConsumer(), "The DeckLink drivers not installed.\n" );
134                         return false;
135                 }
136 #endif
137
138                 // Connect to the Nth DeckLink instance
139                 for ( i = 0; deckLinkIterator->Next( &m_deckLink ) == S_OK ; i++)
140                 {
141                         if( i == card )
142                                 break;
143                         else
144                                 SAFE_RELEASE( m_deckLink );
145                 }
146                 SAFE_RELEASE( deckLinkIterator );
147                 if ( !m_deckLink )
148                 {
149                         mlt_log_error( getConsumer(), "DeckLink card not found\n" );
150                         return false;
151                 }
152
153                 // Obtain the audio/video output interface (IDeckLinkOutput)
154                 if ( m_deckLink->QueryInterface( IID_IDeckLinkOutput, (void**)&m_deckLinkOutput ) != S_OK )
155                 {
156                         mlt_log_error( getConsumer(), "No DeckLink cards support output\n" );
157                         SAFE_RELEASE( m_deckLink );
158                         return false;
159                 }
160
161                 // Get the keyer interface
162                 IDeckLinkAttributes *deckLinkAttributes = 0;
163                 if ( m_deckLink->QueryInterface( IID_IDeckLinkAttributes, (void**) &deckLinkAttributes ) == S_OK )
164                 {
165 #ifdef WIN32
166                         BOOL flag = FALSE;
167 #else
168                         bool flag = false;
169 #endif
170                         if ( deckLinkAttributes->GetFlag( BMDDeckLinkSupportsInternalKeying, &flag ) == S_OK && flag )
171                         {
172                                 if ( m_deckLink->QueryInterface( IID_IDeckLinkKeyer, (void**) &m_deckLinkKeyer ) != S_OK )
173                                 {
174                                         mlt_log_error( getConsumer(), "Failed to get keyer\n" );
175                                         SAFE_RELEASE( m_deckLinkOutput );
176                                         SAFE_RELEASE( m_deckLink );
177                                         return false;
178                                 }
179                         }
180                         SAFE_RELEASE( deckLinkAttributes );
181                 }
182
183                 // Provide this class as a delegate to the audio and video output interfaces
184                 m_deckLinkOutput->SetScheduledFrameCompletionCallback( this );
185
186                 return true;
187         }
188
189
190         void* preroll_thread()
191         {
192                 mlt_properties properties = MLT_CONSUMER_PROPERTIES( getConsumer() );
193
194                 // preroll frames
195                 for ( unsigned i = 0; i < m_preroll && mlt_properties_get_int( properties, "running" ); i++ )
196                         ScheduleNextFrame( true );
197
198                 // start scheduled playback
199                 if ( mlt_properties_get_int( properties, "running" ) )
200                         m_deckLinkOutput->StartScheduledPlayback( 0, m_timescale, 1.0 );
201
202                 return 0;
203         }
204
205         static void* preroll_thread_proxy( void* arg )
206         {
207                 DeckLinkConsumer* self = static_cast< DeckLinkConsumer* >( arg );
208                 return self->preroll_thread();
209         }
210
211         bool start( unsigned preroll )
212         {
213                 mlt_properties properties = MLT_CONSUMER_PROPERTIES( getConsumer() );
214
215                 // Initialize members
216                 m_count = 0;
217                 m_dropped = 0;
218                 m_decklinkFrame = NULL;
219                 preroll = preroll < PREROLL_MINIMUM ? PREROLL_MINIMUM : preroll;
220                 m_channels = mlt_properties_get_int( properties, "channels" );
221                 m_isAudio = !mlt_properties_get_int( properties, "audio_off" );
222                 m_terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
223
224
225                 m_displayMode = getDisplayMode();
226                 if ( !m_displayMode )
227                 {
228                         mlt_log_error( getConsumer(), "Profile is not compatible with decklink.\n" );
229                         return false;
230                 }
231
232                 // Set the keyer
233                 if ( m_deckLinkKeyer && ( m_isKeyer = mlt_properties_get_int( properties, "keyer" ) ) )
234                 {
235                         bool external = ( m_isKeyer == 2 );
236                         double level = mlt_properties_get_double( properties, "keyer_level" );
237
238                         if ( m_deckLinkKeyer->Enable( external ) != S_OK )
239                                 mlt_log_error( getConsumer(), "Failed to enable %s keyer\n",
240                                         external ? "external" : "internal" );
241                         m_deckLinkKeyer->SetLevel( level <= 1 ? ( level > 0 ? 255 * level : 255 ) : 255 );
242                 }
243                 else if ( m_deckLinkKeyer )
244                 {
245                         m_deckLinkKeyer->Disable();
246                 }
247
248                 // Set the video output mode
249                 if ( S_OK != m_deckLinkOutput->EnableVideoOutput( m_displayMode->GetDisplayMode(), bmdVideoOutputFlagDefault ) )
250                 {
251                         mlt_log_error( getConsumer(), "Failed to enable video output\n" );
252                         return false;
253                 }
254
255                 // Set the audio output mode
256                 if ( !m_isAudio )
257                 {
258                         m_deckLinkOutput->DisableAudioOutput();
259                         return true;
260                 }
261                 if ( S_OK != m_deckLinkOutput->EnableAudioOutput( bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger,
262                         m_channels, bmdAudioOutputStreamTimestamped ) )
263                 {
264                         mlt_log_error( getConsumer(), "Failed to enable audio output\n" );
265                         stop();
266                         return false;
267                 }
268
269                 m_preroll = preroll;
270                 m_reprio = false;
271
272                 // Set the running state
273                 mlt_properties_set_int( properties, "running", 1 );
274
275                 // Do preroll in thread to ensure asynchronicity of mlt_consumer_start().
276                 pthread_create( &m_prerollThread, NULL, preroll_thread_proxy, this );
277
278                 return true;
279         }
280
281         bool stop()
282         {
283                 mlt_properties properties = MLT_CONSUMER_PROPERTIES( getConsumer() );
284                 bool wasRunning = !!mlt_properties_get_int( properties, "running" );
285
286                 // set running state is 0
287                 mlt_properties_set_int( properties, "running", 0 );
288
289                 if ( wasRunning )
290                         pthread_join( m_prerollThread, NULL );
291
292                 // Stop the audio and video output streams immediately
293                 if ( m_deckLinkOutput )
294                 {
295                         m_deckLinkOutput->StopScheduledPlayback( 0, 0, 0 );
296                         m_deckLinkOutput->DisableAudioOutput();
297                         m_deckLinkOutput->DisableVideoOutput();
298                 }
299
300                 // release decklink frame
301                 SAFE_RELEASE( m_decklinkFrame );
302
303                 mlt_consumer_stopped( getConsumer() );
304
305                 return true;
306         }
307
308         void renderAudio( mlt_frame frame )
309         {
310                 mlt_audio_format format = mlt_audio_s16;
311                 int frequency = bmdAudioSampleRate48kHz;
312                 int samples = mlt_sample_calculator( m_fps, frequency, m_count );
313                 int16_t *pcm = 0;
314
315                 if ( !mlt_frame_get_audio( frame, (void**) &pcm, &format, &frequency, &m_channels, &samples ) )
316                 {
317 #ifdef WIN32
318                         unsigned long written = 0;
319 #else
320                         uint32_t written = 0;
321 #endif
322                         BMDTimeValue streamTime = m_count * frequency * m_duration / m_timescale;
323                         m_deckLinkOutput->GetBufferedAudioSampleFrameCount( &written );
324                         if ( written > (m_preroll + 1) * samples )
325                         {
326                                 mlt_log_verbose( getConsumer(), "renderAudio: will flush %lu audiosamples\n", written );
327                                 m_deckLinkOutput->FlushBufferedAudioSamples();
328                         };
329 #ifdef WIN32
330                         m_deckLinkOutput->ScheduleAudioSamples( pcm, samples, streamTime, frequency, (unsigned long*) &written );
331 #else
332                         m_deckLinkOutput->ScheduleAudioSamples( pcm, samples, streamTime, frequency, &written );
333 #endif
334
335                         if ( written != (uint32_t) samples )
336                                 mlt_log_verbose( getConsumer(), "renderAudio: samples=%d, written=%lu\n", samples, written );
337                 }
338         }
339
340         bool createFrame( IDeckLinkMutableVideoFrame** decklinkFrame )
341         {
342                 BMDPixelFormat format = m_isKeyer? bmdFormat8BitARGB : bmdFormat8BitYUV;
343                 IDeckLinkMutableVideoFrame* frame = 0;
344                 uint8_t *buffer = 0;
345                 int stride = m_width * ( m_isKeyer? 4 : 2 );
346
347                 *decklinkFrame = NULL;
348
349                 // Generate a DeckLink video frame
350                 if ( S_OK != m_deckLinkOutput->CreateVideoFrame( m_width, m_height,
351                         stride, format, bmdFrameFlagDefault, &frame ) )
352                 {
353                         mlt_log_verbose( getConsumer(), "Failed to create video frame\n" );
354                         stop();
355                         return false;
356                 }
357
358                 // Make the first line black for field order correction.
359                 if ( S_OK == frame->GetBytes( (void**) &buffer ) && buffer )
360                 {
361                         if ( m_isKeyer )
362                         {
363                                 memset( buffer, 0, stride );
364                         }
365                         else for ( int i = 0; i < m_width; i++ )
366                         {
367                                 *buffer++ = 128;
368                                 *buffer++ = 16;
369                         }
370                 }
371
372                 *decklinkFrame = frame;
373
374                 return true;
375         }
376
377         void renderVideo( mlt_frame frame )
378         {
379                 mlt_image_format format = m_isKeyer? mlt_image_rgb24a : mlt_image_yuv422;
380                 uint8_t* image = 0;
381                 int rendered = mlt_properties_get_int( MLT_FRAME_PROPERTIES(frame), "rendered");
382                 int height = m_height;
383
384                 if ( rendered && !mlt_frame_get_image( frame, &image, &format, &m_width, &height, 0 ) )
385                 {
386                         uint8_t* buffer = 0;
387                         int stride = m_width * ( m_isKeyer? 4 : 2 );
388
389                         SAFE_RELEASE( m_decklinkFrame );
390                         if ( createFrame( &m_decklinkFrame ) )
391                                 m_decklinkFrame->GetBytes( (void**) &buffer );
392
393                         if ( buffer )
394                         {
395                                 int progressive = mlt_properties_get_int( MLT_FRAME_PROPERTIES( frame ), "progressive" );
396
397                                 // NTSC SDI is always 486 lines
398                                 if ( m_height == 486 && height == 480 )
399                                 {
400                                         // blank first 6 lines
401                                         if ( m_isKeyer )
402                                         {
403                                                 memset( buffer, 0, stride * 6 );
404                                                 buffer += stride * 6;
405                                         }
406                                         else for ( int i = 0; i < m_width * 6; i++ )
407                                         {
408                                                 *buffer++ = 128;
409                                                 *buffer++ = 16;
410                                         }
411                                 }
412                                 if ( !m_isKeyer )
413                                 {
414                                         // Normal non-keyer playout - needs byte swapping
415                                         if ( !progressive && m_displayMode->GetFieldDominance() == bmdUpperFieldFirst )
416                                                 // convert lower field first to top field first
417                                                 swab( (char*) image, (char*) buffer + stride, stride * ( height - 1 ) );
418                                         else
419                                                 swab( (char*) image, (char*) buffer, stride * height );
420                                 }
421                                 else if ( !mlt_properties_get_int( MLT_FRAME_PROPERTIES( frame ), "test_image" ) )
422                                 {
423                                         // Normal keyer output
424                                         int y = height + 1;
425                                         uint32_t* s = (uint32_t*) image;
426                                         uint32_t* d = (uint32_t*) buffer;
427
428                                         if ( !progressive && m_displayMode->GetFieldDominance() == bmdUpperFieldFirst )
429                                         {
430                                                 // Correct field order
431                                                 height--;
432                                                 y--;
433                                                 d += m_width;
434                                         }
435
436                                         // Need to relocate alpha channel RGBA => ARGB
437                                         while ( --y )
438                                         {
439                                                 int x = m_width + 1;
440                                                 while ( --x )
441                                                 {
442                                                         *d++ = ( *s << 8 ) | ( *s >> 24 );
443                                                         s++;
444                                                 }
445                                         }
446                                 }
447                                 else
448                                 {
449                                         // Keying blank frames - nullify alpha
450                                         memset( buffer, 0, stride * height );
451                                 }
452                         }
453                 }
454                 if ( m_decklinkFrame )
455                         m_deckLinkOutput->ScheduleVideoFrame( m_decklinkFrame, m_count * m_duration, m_duration, m_timescale );
456
457                 if ( !rendered )
458                         mlt_log_verbose( getConsumer(), "dropped video frame %u\n", ++m_dropped );
459         }
460
461         HRESULT render( mlt_frame frame )
462         {
463                 HRESULT result = S_OK;
464
465                 // Get the audio
466                 double speed = mlt_properties_get_double( MLT_FRAME_PROPERTIES(frame), "_speed" );
467                 if ( m_isAudio && speed == 1.0 )
468                         renderAudio( frame );
469
470                 // Get the video
471                 renderVideo( frame );
472                 ++m_count;
473
474                 return result;
475         }
476
477         // *** DeckLink API implementation of IDeckLinkVideoOutputCallback IDeckLinkAudioOutputCallback *** //
478
479         // IUnknown needs only a dummy implementation
480         virtual HRESULT STDMETHODCALLTYPE QueryInterface( REFIID iid, LPVOID *ppv )
481                 { return E_NOINTERFACE; }
482         virtual ULONG STDMETHODCALLTYPE AddRef()
483                 { return 1; }
484         virtual ULONG STDMETHODCALLTYPE Release()
485                 { return 1; }
486
487         /************************* DeckLink API Delegate Methods *****************************/
488
489         virtual HRESULT STDMETHODCALLTYPE ScheduledFrameCompleted( IDeckLinkVideoFrame* completedFrame, BMDOutputFrameCompletionResult completed )
490         {
491                 if( !m_reprio )
492                 {
493                         mlt_properties properties = MLT_CONSUMER_PROPERTIES( getConsumer() );
494
495                         if ( mlt_properties_get( properties, "priority" ) )
496                         {
497                                 int r;
498                                 pthread_t thread;
499                                 pthread_attr_t tattr;
500                                 struct sched_param param;
501
502                                 pthread_attr_init(&tattr);
503                                 pthread_attr_setschedpolicy(&tattr, SCHED_FIFO);
504
505                                 if ( !strcmp( "max", mlt_properties_get( properties, "priority" ) ) )
506                                         param.sched_priority = sched_get_priority_max(SCHED_FIFO) - 1;
507                                 else if ( !strcmp( "min", mlt_properties_get( properties, "priority" ) ) )
508                                         param.sched_priority = sched_get_priority_min(SCHED_FIFO) + 1;
509                                 else
510                                         param.sched_priority = mlt_properties_get_int( properties, "priority" );
511
512                                 pthread_attr_setschedparam(&tattr, &param);
513
514                                 thread = pthread_self();
515
516                                 r = pthread_setschedparam(thread, SCHED_FIFO, &param);
517                                 if( r )
518                                         mlt_log_verbose( getConsumer(),
519                                                 "ScheduledFrameCompleted: pthread_setschedparam returned %d\n", r);
520                                 else
521                                         mlt_log_verbose( getConsumer(),
522                                                 "ScheduledFrameCompleted: param.sched_priority=%d\n", param.sched_priority);
523                         };
524
525                         m_reprio = true;
526                 };
527
528 #ifdef WIN32
529                 unsigned long cnt;
530 #else
531                 uint32_t cnt;
532 #endif
533                 m_deckLinkOutput->GetBufferedAudioSampleFrameCount( &cnt );
534                 if ( cnt != m_acnt )
535                 {
536                         mlt_log_debug( getConsumer(),
537                                 "ScheduledFrameCompleted: GetBufferedAudioSampleFrameCount %u -> %lu, m_count=%"PRIu64"\n",
538                                 m_acnt, cnt, m_count );
539                         m_acnt = cnt;
540                 }
541
542                 // When a video frame has been released by the API, schedule another video frame to be output
543
544                 // ignore handler if frame was flushed
545                 if ( bmdOutputFrameFlushed == completed )
546                         return S_OK;
547
548                 // schedule next frame
549                 ScheduleNextFrame( false );
550
551                 // step forward frames counter if underrun
552                 if ( bmdOutputFrameDisplayedLate == completed )
553                 {
554                         mlt_log_verbose( getConsumer(), "ScheduledFrameCompleted: bmdOutputFrameDisplayedLate == completed\n" );
555                         m_count++;
556                 }
557                 if ( bmdOutputFrameDropped == completed )
558                 {
559                         mlt_log_verbose( getConsumer(), "ScheduledFrameCompleted: bmdOutputFrameDropped == completed\n" );
560                         m_count++;
561                 }
562
563                 return S_OK;
564         }
565
566         virtual HRESULT STDMETHODCALLTYPE ScheduledPlaybackHasStopped()
567         {
568                 return mlt_consumer_is_stopped( getConsumer() ) ? S_FALSE : S_OK;
569         }
570
571
572         void ScheduleNextFrame( bool preroll )
573         {
574                 // get the consumer
575                 mlt_consumer consumer = getConsumer();
576
577                 // Get the properties
578                 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
579
580                 // Frame and size
581                 mlt_frame frame = NULL;
582
583                 if( mlt_properties_get_int( properties, "running" ) || preroll )
584                 {
585                         frame = mlt_consumer_rt_frame( consumer );
586                         if ( frame != NULL )
587                         {
588                                 render( frame );
589
590                                 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
591
592                                 // terminate on pause
593                                 if ( m_terminate_on_pause &&
594                                         mlt_properties_get_double( MLT_FRAME_PROPERTIES( frame ), "_speed" ) == 0.0 )
595                                         stop();
596
597                                 mlt_frame_close( frame );
598                         }
599                 }
600         }
601 };
602
603 /** Start the consumer.
604  */
605
606 static int start( mlt_consumer consumer )
607 {
608         // Get the properties
609         mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
610         DeckLinkConsumer* decklink = (DeckLinkConsumer*) consumer->child;
611         return decklink->start( mlt_properties_get_int( properties, "preroll" ) ) ? 0 : 1;
612 }
613
614 /** Stop the consumer.
615  */
616
617 static int stop( mlt_consumer consumer )
618 {
619         // Get the properties
620         DeckLinkConsumer* decklink = (DeckLinkConsumer*) consumer->child;
621         return decklink->stop();
622 }
623
624 /** Determine if the consumer is stopped.
625  */
626
627 static int is_stopped( mlt_consumer consumer )
628 {
629         // Get the properties
630         mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
631         return !mlt_properties_get_int( properties, "running" );
632 }
633
634 /** Close the consumer.
635  */
636
637 static void close( mlt_consumer consumer )
638 {
639         // Stop the consumer
640         mlt_consumer_stop( consumer );
641
642         // Close the parent
643         consumer->close = NULL;
644         mlt_consumer_close( consumer );
645
646         // Free the memory
647         delete (DeckLinkConsumer*) consumer->child;
648 }
649
650 extern "C" {
651
652 // Listen for the list_devices property to be set
653 static void on_property_changed( void*, mlt_properties properties, const char *name )
654 {
655         IDeckLinkIterator* decklinkIterator = NULL;
656         IDeckLink* decklink = NULL;
657         IDeckLinkInput* decklinkOutput = NULL;
658         int i = 0;
659
660         if ( name && !strcmp( name, "list_devices" ) )
661                 mlt_event_block( (mlt_event) mlt_properties_get_data( properties, "list-devices-event", NULL ) );
662         else
663                 return;
664
665 #ifdef WIN32
666         if ( FAILED( CoInitialize( NULL ) ) )
667                 return;
668         if ( FAILED( CoCreateInstance( CLSID_CDeckLinkIterator, NULL, CLSCTX_ALL, IID_IDeckLinkIterator, (void**) &decklinkIterator ) ) )
669                 return;
670 #else
671         if ( !( decklinkIterator = CreateDeckLinkIteratorInstance() ) )
672                 return;
673 #endif
674         for ( ; decklinkIterator->Next( &decklink ) == S_OK; i++ )
675         {
676                 if ( decklink->QueryInterface( IID_IDeckLinkOutput, (void**) &decklinkOutput ) == S_OK )
677                 {
678                         DLString name = NULL;
679                         if ( decklink->GetModelName( &name ) == S_OK )
680                         {
681                                 char *name_cstr = getCString( name );
682                                 const char *format = "device.%d";
683                                 char *key = (char*) calloc( 1, strlen( format ) + 1 );
684
685                                 sprintf( key, format, i );
686                                 mlt_properties_set( properties, key, name_cstr );
687                                 free( key );
688                                 freeDLString( name );
689                                 freeCString( name_cstr );
690                         }
691                         SAFE_RELEASE( decklinkOutput );
692                 }
693                 SAFE_RELEASE( decklink );
694         }
695         SAFE_RELEASE( decklinkIterator );
696         mlt_properties_set_int( properties, "devices", i );
697 }
698
699 /** Initialise the consumer.
700  */
701
702 mlt_consumer consumer_decklink_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
703 {
704         // Allocate the consumer
705         DeckLinkConsumer* decklink = new DeckLinkConsumer();
706         mlt_consumer consumer = NULL;
707
708         // If allocated
709         if ( decklink && !mlt_consumer_init( decklink->getConsumer(), decklink, profile ) )
710         {
711                 // If initialises without error
712                 if ( decklink->open( arg? atoi(arg) : 0 ) )
713                 {
714                         consumer = decklink->getConsumer();
715                         mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
716
717                         // Setup callbacks
718                         consumer->close = close;
719                         consumer->start = start;
720                         consumer->stop = stop;
721                         consumer->is_stopped = is_stopped;
722                         mlt_properties_set( properties, "deinterlace_method", "onefield" );
723
724                         mlt_event event = mlt_events_listen( properties, properties, "property-changed", (mlt_listener) on_property_changed );
725                         mlt_properties_set_data( properties, "list-devices-event", event, 0, NULL, NULL );
726                 }
727         }
728
729         // Return consumer
730         return consumer;
731 }
732
733 extern mlt_producer producer_decklink_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg );
734
735 static mlt_properties metadata( mlt_service_type type, const char *id, void *data )
736 {
737         char file[ PATH_MAX ];
738         const char *service_type = NULL;
739         switch ( type )
740         {
741                 case consumer_type:
742                         service_type = "consumer";
743                         break;
744                 case producer_type:
745                         service_type = "producer";
746                         break;
747                 default:
748                         return NULL;
749         }
750         snprintf( file, PATH_MAX, "%s/decklink/%s_%s.yml", mlt_environment( "MLT_DATA" ), service_type, id );
751         return mlt_properties_parse_yaml( file );
752 }
753
754 MLT_REPOSITORY
755 {
756         MLT_REGISTER( consumer_type, "decklink", consumer_decklink_init );
757         MLT_REGISTER( producer_type, "decklink", producer_decklink_init );
758         MLT_REGISTER_METADATA( consumer_type, "decklink", metadata, NULL );
759         MLT_REGISTER_METADATA( producer_type, "decklink", metadata, NULL );
760 }
761
762 } // extern C