]> git.sesse.net Git - mlt/blob - src/modules/decklink/producer_decklink.cpp
allow start decklink producer from pause
[mlt] / src / modules / decklink / producer_decklink.cpp
1 /*
2  * producer_decklink.c -- input from Blackmagic Design DeckLink
3  * Copyright (C) 2011 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 #include <framework/mlt.h>
21 #include <stdlib.h>
22 #include <pthread.h>
23 #include <string.h>
24 #include <unistd.h>
25 #include <limits.h>
26 #include <sys/time.h>
27 #ifdef WIN32
28 #include <objbase.h>
29 #include "DeckLinkAPI_h.h"
30 #else
31 #include "DeckLinkAPI.h"
32 #endif
33
34 class DeckLinkProducer
35         : public IDeckLinkInputCallback
36 {
37 private:
38         mlt_producer     m_producer;
39         IDeckLink*       m_decklink;
40         IDeckLinkInput*  m_decklinkInput;
41         mlt_deque        m_queue;
42         pthread_mutex_t  m_mutex;
43         pthread_cond_t   m_condition;
44         bool             m_started;
45         int              m_dropped;
46         bool             m_isBuffering;
47         int              m_topFieldFirst;
48         int              m_colorspace;
49         int              m_vancLines;
50         mlt_cache        m_cache;
51
52         BMDDisplayMode getDisplayMode( mlt_profile profile, int vancLines )
53         {
54                 IDeckLinkDisplayModeIterator* iter;
55                 IDeckLinkDisplayMode* mode;
56                 BMDDisplayMode result = (BMDDisplayMode) bmdDisplayModeNotSupported;
57
58                 if ( m_decklinkInput->GetDisplayModeIterator( &iter ) == S_OK )
59                 {
60                         while ( !result && iter->Next( &mode ) == S_OK )
61                         {
62                                 int width = mode->GetWidth();
63                                 int height = mode->GetHeight();
64                                 BMDTimeValue duration;
65                                 BMDTimeScale timescale;
66                                 mode->GetFrameRate( &duration, &timescale );
67                                 double fps = (double) timescale / duration;
68                                 int p = mode->GetFieldDominance() == bmdProgressiveFrame;
69                                 m_topFieldFirst = mode->GetFieldDominance() == bmdUpperFieldFirst;
70                                 m_colorspace = ( mode->GetFlags() & bmdDisplayModeColorspaceRec709 ) ? 709 : 601;
71                                 mlt_log_verbose( getProducer(), "BMD mode %dx%d %.3f fps prog %d tff %d\n", width, height, fps, p, m_topFieldFirst );
72
73                                 if ( width == profile->width && p == profile->progressive
74                                          && ( height + vancLines == profile->height || ( height == 486 && profile->height == 480 + vancLines ) )
75                                          && fps == mlt_profile_fps( profile ) )
76                                         result = mode->GetDisplayMode();
77                         }
78                 }
79
80                 return result;
81         }
82
83 public:
84
85         void setProducer( mlt_producer producer )
86                 { m_producer = producer; }
87
88         mlt_producer getProducer() const
89                 { return m_producer; }
90
91         ~DeckLinkProducer()
92         {
93                 if ( m_queue )
94                 {
95                         stop();
96                         mlt_deque_close( m_queue );
97                         pthread_mutex_destroy( &m_mutex );
98                         pthread_cond_destroy( &m_condition );
99                         mlt_cache_close( m_cache );
100                 }
101                 if ( m_decklinkInput )
102                         m_decklinkInput->Release();
103                 if ( m_decklink )
104                         m_decklink->Release();
105         }
106
107         bool open( unsigned card =  0 )
108         {
109                 IDeckLinkIterator* decklinkIterator = NULL;
110                 try
111                 {
112 #ifdef WIN32
113                         HRESULT result =  CoInitialize( NULL );
114                         if ( FAILED( result ) )
115                                 throw "COM initialization failed";
116                         result = CoCreateInstance( CLSID_CDeckLinkIterator, NULL, CLSCTX_ALL, IID_IDeckLinkIterator, (void**) &decklinkIterator );
117                         if ( FAILED( result ) )
118                                 throw "The DeckLink drivers are not installed.";
119 #else
120                         decklinkIterator = CreateDeckLinkIteratorInstance();
121                         if ( !decklinkIterator )
122                                 throw "The DeckLink drivers are not installed.";
123 #endif
124
125                         // Connect to the Nth DeckLink instance
126                         unsigned i = 0;
127                         do {
128                                 if ( decklinkIterator->Next( &m_decklink ) != S_OK )
129                                         throw "DeckLink card not found.";
130                         } while ( ++i <= card );
131                         decklinkIterator->Release();
132
133                         // Get the input interface
134                         if ( m_decklink->QueryInterface( IID_IDeckLinkInput, (void**) &m_decklinkInput ) != S_OK )
135                                 throw "No DeckLink cards support input.";
136
137                         // Provide this class as a delegate to the input callback
138                         m_decklinkInput->SetCallback( this );
139
140                         // Initialize other members
141                         pthread_mutex_init( &m_mutex, NULL );
142                         pthread_cond_init( &m_condition, NULL );
143                         m_queue = mlt_deque_init();
144                         m_started = false;
145                         m_dropped = 0;
146                         m_isBuffering = true;
147                         m_cache = mlt_cache_init();
148
149                         // 3 covers YADIF and increasing framerate use cases
150                         mlt_cache_set_size( m_cache, 3 );
151                 }
152                 catch ( const char *error )
153                 {
154                         if ( decklinkIterator )
155                                 decklinkIterator->Release();
156                         mlt_log_error( getProducer(), "%s\n", error );
157                         return false;
158                 }
159                 return true;
160         }
161
162         bool start( mlt_profile profile = 0 )
163         {
164                 if ( m_started )
165                         return false;
166                 try
167                 {
168                         // Initialize some members
169                         m_vancLines = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "vanc" );
170                         if ( m_vancLines == -1 )
171                                 m_vancLines = profile->height <= 512 ? 26 : 32;
172
173                         if ( !profile )
174                                 profile = mlt_service_profile( MLT_PRODUCER_SERVICE( getProducer() ) );
175
176                         // Get the display mode
177                         BMDDisplayMode displayMode = getDisplayMode( profile, m_vancLines );
178                         if ( displayMode == (BMDDisplayMode) bmdDisplayModeNotSupported )
179                         {
180                                 mlt_log_info( getProducer(), "profile = %dx%d %f fps %s\n", profile->width, profile->height,
181                                                           mlt_profile_fps( profile ), profile->progressive? "progressive" : "interlace" );
182                                 throw "Profile is not compatible with decklink.";
183                         }
184
185                         // Determine if supports input format detection
186 #ifdef WIN32
187                         BOOL doesDetectFormat = FALSE;
188 #else
189                         bool doesDetectFormat = false;
190 #endif
191                         IDeckLinkAttributes *decklinkAttributes = 0;
192                         if ( m_decklink->QueryInterface( IID_IDeckLinkAttributes, (void**) &decklinkAttributes ) == S_OK )
193                         {
194                                 if ( decklinkAttributes->GetFlag( BMDDeckLinkSupportsInputFormatDetection, &doesDetectFormat ) != S_OK )
195                                         doesDetectFormat = false;
196                                 decklinkAttributes->Release();
197                         }
198                         mlt_log_verbose( getProducer(), "%s format detection\n", doesDetectFormat ? "supports" : "does not support" );
199
200                         // Enable video capture
201                         BMDPixelFormat pixelFormat = bmdFormat8BitYUV;
202                         BMDVideoInputFlags flags = doesDetectFormat ? bmdVideoInputEnableFormatDetection : bmdVideoInputFlagDefault;
203                         if ( S_OK != m_decklinkInput->EnableVideoInput( displayMode, pixelFormat, flags ) )
204                                 throw "Failed to enable video capture.";
205
206                         // Enable audio capture
207                         BMDAudioSampleRate sampleRate = bmdAudioSampleRate48kHz;
208                         BMDAudioSampleType sampleType = bmdAudioSampleType16bitInteger;
209                         int channels = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "channels" );
210                         if ( S_OK != m_decklinkInput->EnableAudioInput( sampleRate, sampleType, channels ) )
211                                 throw "Failed to enable audio capture.";
212
213                         // Start capture
214                         m_dropped = 0;
215                         mlt_properties_set_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "dropped", m_dropped );
216                         m_started = m_decklinkInput->StartStreams() == S_OK;
217                         if ( !m_started )
218                                 throw "Failed to start capture.";
219                 }
220                 catch ( const char *error )
221                 {
222                         m_decklinkInput->DisableVideoInput();
223                         mlt_log_error( getProducer(), "%s\n", error );
224                         return false;
225                 }
226                 return true;
227         }
228
229         void stop()
230         {
231                 if ( !m_started )
232                         return;
233                 m_started = false;
234
235                 // Release the wait in getFrame
236                 pthread_mutex_lock( &m_mutex );
237                 pthread_cond_broadcast( &m_condition );
238                 pthread_mutex_unlock( &m_mutex );
239
240                 m_decklinkInput->StopStreams();
241
242                 // Cleanup queue
243                 pthread_mutex_lock( &m_mutex );
244                 while ( mlt_frame frame = (mlt_frame) mlt_deque_pop_back( m_queue ) )
245                         mlt_frame_close( frame );
246                 pthread_mutex_unlock( &m_mutex );
247         }
248
249         mlt_frame getFrame()
250         {
251                 mlt_frame frame = NULL;
252                 struct timeval now;
253                 struct timespec tm;
254                 double fps = mlt_producer_get_fps( getProducer() );
255                 mlt_position position = mlt_producer_position( getProducer() );
256                 mlt_cache_item cached = mlt_cache_get( m_cache, (void*) position );
257
258                 // Allow the buffer to fill to the requested initial buffer level.
259                 if ( m_isBuffering )
260                 {
261                         int prefill = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "prefill" );
262                         int buffer = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "buffer" );
263
264                         m_isBuffering = false;
265                         prefill = prefill > buffer ? buffer : prefill;
266                         pthread_mutex_lock( &m_mutex );
267                         while ( mlt_deque_count( m_queue ) < prefill )
268                         {
269                                 // Wait up to buffer/fps seconds
270                                 gettimeofday( &now, NULL );
271                                 long usec = now.tv_sec * 1000000 + now.tv_usec;
272                                 usec += 1000000 * buffer / fps;
273                                 tm.tv_sec = usec / 1000000;
274                                 tm.tv_nsec = (usec % 1000000) * 1000;
275                                 if ( pthread_cond_timedwait( &m_condition, &m_mutex, &tm ) )
276                                         break;
277                         }
278                         pthread_mutex_unlock( &m_mutex );
279                 }
280
281                 if ( cached )
282                 {
283                         // Copy cached frame instead of pulling from queue
284                         frame = mlt_frame_clone( (mlt_frame) mlt_cache_item_data( cached, NULL ), 0 );
285                         mlt_cache_item_close( cached );
286                 }
287                 else
288                 {
289                         // Wait if queue is empty
290                         pthread_mutex_lock( &m_mutex );
291                         while ( mlt_deque_count( m_queue ) < 1 )
292                         {
293                                 // Wait up to twice frame duration
294                                 gettimeofday( &now, NULL );
295                                 long usec = now.tv_sec * 1000000 + now.tv_usec;
296                                 usec += 2000000 / fps;
297                                 tm.tv_sec = usec / 1000000;
298                                 tm.tv_nsec = (usec % 1000000) * 1000;
299                                 if ( pthread_cond_timedwait( &m_condition, &m_mutex, &tm ) )
300                                         // Stop waiting if error (timed out)
301                                         break;
302                         }
303                         frame = ( mlt_frame ) mlt_deque_pop_front( m_queue );
304                         pthread_mutex_unlock( &m_mutex );
305
306                         // add to cache
307                         if ( frame )
308                                 mlt_cache_put( m_cache, (void*) position, mlt_frame_clone( frame, 1 ), 0,
309                                         (mlt_destructor) mlt_frame_close );
310                 }
311
312                 // Set frame timestamp and properties
313                 if ( frame )
314                 {
315                         mlt_profile profile = mlt_service_profile( MLT_PRODUCER_SERVICE( getProducer() ) );
316                         mlt_properties properties = MLT_FRAME_PROPERTIES( frame );
317                         mlt_properties_set_int( properties, "progressive", profile->progressive );
318                         mlt_properties_set_int( properties, "meta.media.progressive", profile->progressive );
319                         mlt_properties_set_int( properties, "top_field_first", m_topFieldFirst );
320                         mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
321                         mlt_properties_set_int( properties, "meta.media.sample_aspect_num", profile->sample_aspect_num );
322                         mlt_properties_set_int( properties, "meta.media.sample_aspect_den", profile->sample_aspect_den );
323                         mlt_properties_set_int( properties, "meta.media.frame_rate_num", profile->frame_rate_num );
324                         mlt_properties_set_int( properties, "meta.media.frame_rate_den", profile->frame_rate_den );
325                         mlt_properties_set_int( properties, "width", profile->width );
326                         mlt_properties_set_int( properties, "real_width", profile->width );
327                         mlt_properties_set_int( properties, "meta.media.width", profile->width );
328                         mlt_properties_set_int( properties, "height", profile->height );
329                         mlt_properties_set_int( properties, "real_height", profile->height );
330                         mlt_properties_set_int( properties, "meta.media.height", profile->height );
331                         mlt_properties_set_int( properties, "format", mlt_image_yuv422 );
332                         mlt_properties_set_int( properties, "colorspace", m_colorspace );
333                         mlt_properties_set_int( properties, "meta.media.colorspace", m_colorspace );
334                         mlt_properties_set_int( properties, "audio_frequency", 48000 );
335                         mlt_properties_set_int( properties, "audio_channels",
336                                 mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "channels" ) );
337                 }
338                 else
339                         mlt_log_warning( getProducer(), "buffer underrun\n" );
340
341                 return frame;
342         }
343
344         // *** DeckLink API implementation of IDeckLinkInputCallback *** //
345
346         // IUnknown needs only a dummy implementation
347         virtual HRESULT STDMETHODCALLTYPE QueryInterface( REFIID iid, LPVOID *ppv )
348                 { return E_NOINTERFACE; }
349         virtual ULONG STDMETHODCALLTYPE AddRef()
350                 { return 1; }
351         virtual ULONG STDMETHODCALLTYPE Release()
352                 { return 1; }
353
354         /************************* DeckLink API Delegate Methods *****************************/
355
356         virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(
357                         IDeckLinkVideoInputFrame* video,
358                         IDeckLinkAudioInputPacket* audio )
359         {
360                 if ( mlt_producer_get_speed( getProducer() ) == 0.0 && !mlt_deque_count( m_queue ))
361                 {
362                         pthread_cond_broadcast( &m_condition );
363                         return S_OK;
364                 }
365
366                 // Create mlt_frame
367                 mlt_frame frame = mlt_frame_init( MLT_PRODUCER_SERVICE( getProducer() ) );
368
369                 // Copy video
370                 if ( video )
371                 {
372                         if ( !( video->GetFlags() & bmdFrameHasNoInputSource ) )
373                         {
374                                 int size = video->GetRowBytes() * ( video->GetHeight() + m_vancLines );
375                                 void* image = mlt_pool_alloc( size );
376                                 void* buffer = 0;
377                                 unsigned char* p = (unsigned char*) image;
378                                 int n = size / 2;
379 \
380                                 // Initialize VANC lines to nominal black
381                                 while ( --n )
382                                 {
383                                         *p ++ = 16;
384                                         *p ++ = 128;
385                                 }
386
387                                 // Capture VANC
388                                 if ( m_vancLines > 0 )
389                                 {
390                                         IDeckLinkVideoFrameAncillary* vanc = 0;
391                                         if ( video->GetAncillaryData( &vanc ) == S_OK && vanc )
392                                         {
393                                                 for ( int i = 1; i < m_vancLines + 1; i++ )
394                                                 {
395                                                         if ( vanc->GetBufferForVerticalBlankingLine( i, &buffer ) == S_OK )
396                                                                 swab( (char*) buffer, (char*) image + ( i - 1 ) * video->GetRowBytes(), video->GetRowBytes() );
397                                                         else
398                                                                 mlt_log_debug( getProducer(), "failed capture vanc line %d\n", i );
399                                                 }
400                                                 vanc->Release();
401                                         }
402                                 }
403
404                                 // Capture image
405                                 video->GetBytes( &buffer );
406                                 if ( image && buffer )
407                                 {
408                                         size =  video->GetRowBytes() * video->GetHeight();
409                                         swab( (char*) buffer, (char*) image + m_vancLines * video->GetRowBytes(), size );
410                                         mlt_frame_set_image( frame, (uint8_t*) image, size, mlt_pool_release );
411                                 }
412                                 else if ( image )
413                                 {
414                                         mlt_log_verbose( getProducer(), "no video\n" );
415                                         mlt_pool_release( image );
416                                 }
417                         }
418                         else
419                         {
420                                 mlt_log_verbose( getProducer(), "no signal\n" );
421                                 mlt_frame_close( frame );
422                                 frame = 0;
423                         }
424
425                         // Get timecode
426                         IDeckLinkTimecode* timecode = 0;
427                         if ( video->GetTimecode( bmdTimecodeVITC, &timecode ) == S_OK && timecode )
428                         {
429                                 const char* timecodeString = 0;
430
431 #ifdef WIN32
432                                 if ( timecode->GetString( (BSTR*) &timecodeString ) == S_OK )
433 #else
434                                 if ( timecode->GetString( &timecodeString ) == S_OK )
435 #endif
436                                 {
437                                         mlt_properties_set( MLT_FRAME_PROPERTIES( frame ), "meta.attr.vitc.markup", timecodeString );
438                                         mlt_log_debug( getProducer(), "timecode %s\n", timecodeString );
439                                 }
440                                 if ( timecodeString )
441                                         free( (void*) timecodeString );
442                                 timecode->Release();
443                         }
444                 }
445                 else
446                 {
447                         mlt_log_verbose( getProducer(), "no video\n" );
448                         mlt_frame_close( frame );
449                         frame = 0;
450                 }
451
452                 // Copy audio
453                 if ( frame && audio )
454                 {
455                         int channels = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "channels" );
456                         int size = audio->GetSampleFrameCount() * channels * sizeof(int16_t);
457                         mlt_audio_format format = mlt_audio_s16;
458                         void* pcm = mlt_pool_alloc( size );
459                         void* buffer = 0;
460
461                         audio->GetBytes( &buffer );
462                         if ( buffer )
463                         {
464                                 memcpy( pcm, buffer, size );
465                                 mlt_frame_set_audio( frame, pcm, format, size, mlt_pool_release );
466                                 mlt_properties_set_int( MLT_FRAME_PROPERTIES(frame), "audio_samples", audio->GetSampleFrameCount() );
467                         }
468                         else
469                         {
470                                 mlt_log_verbose( getProducer(), "no audio\n" );
471                                 mlt_pool_release( pcm );
472                         }
473                 }
474                 else
475                 {
476                         mlt_log_verbose( getProducer(), "no audio\n" );
477                 }
478
479                 // Put frame in queue
480                 if ( frame )
481                 {
482                         int queueMax = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "buffer" );
483                         pthread_mutex_lock( &m_mutex );
484                         if ( mlt_deque_count( m_queue ) < queueMax )
485                         {
486                                 mlt_deque_push_back( m_queue, frame );
487                                 pthread_cond_broadcast( &m_condition );
488                         }
489                         else
490                         {
491                                 mlt_frame_close( frame );
492                                 mlt_properties_set_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "dropped", ++m_dropped );
493                                 mlt_log_warning( getProducer(), "frame dropped %d\n", m_dropped );
494                         }
495                         pthread_mutex_unlock( &m_mutex );
496                 }
497
498                 return S_OK;
499         }
500
501         virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(
502                         BMDVideoInputFormatChangedEvents events,
503                         IDeckLinkDisplayMode* mode,
504                         BMDDetectedVideoInputFormatFlags flags )
505         {
506                 mlt_profile profile = mlt_service_profile( MLT_PRODUCER_SERVICE( getProducer() ) );
507                 if ( events & bmdVideoInputDisplayModeChanged )
508                 {
509                         BMDTimeValue duration;
510                         BMDTimeScale timescale;
511                         mode->GetFrameRate( &duration, &timescale );
512                         profile->width = mode->GetWidth();
513                         profile->height = mode->GetHeight() + m_vancLines;
514                         profile->frame_rate_num = timescale;
515                         profile->frame_rate_den = duration;
516                         if ( profile->width == 720 )
517                         {
518                                 if ( profile->height == 576 )
519                                 {
520                                         profile->sample_aspect_num = 16;
521                                         profile->sample_aspect_den = 15;
522                                 }
523                                 else
524                                 {
525                                         profile->sample_aspect_num = 8;
526                                         profile->sample_aspect_den = 9;
527                                 }
528                                 profile->display_aspect_num = 4;
529                                 profile->display_aspect_den = 3;
530                         }
531                         else
532                         {
533                                 profile->sample_aspect_num = 1;
534                                 profile->sample_aspect_den = 1;
535                                 profile->display_aspect_num = 16;
536                                 profile->display_aspect_den = 9;
537                         }
538                         free( profile->description );
539                         profile->description = strdup( "decklink" );
540                         mlt_log_verbose( getProducer(), "format changed %dx%d %.3f fps\n",
541                                 profile->width, profile->height, (double) profile->frame_rate_num / profile->frame_rate_den );
542                 }
543                 if ( events & bmdVideoInputFieldDominanceChanged )
544                 {
545                         profile->progressive = mode->GetFieldDominance() == bmdProgressiveFrame;
546                         m_topFieldFirst = mode->GetFieldDominance() == bmdUpperFieldFirst;
547                         mlt_log_verbose( getProducer(), "field dominance changed prog %d tff %d\n",
548                                 profile->progressive, m_topFieldFirst );
549                 }
550                 if ( events & bmdVideoInputColorspaceChanged )
551                 {
552                         profile->colorspace = m_colorspace =
553                                 ( mode->GetFlags() & bmdDisplayModeColorspaceRec709 ) ? 709 : 601;
554                         mlt_log_verbose( getProducer(), "colorspace changed %d\n", profile->colorspace );
555                 }
556                 return S_OK;
557         }
558 };
559
560 static int get_audio( mlt_frame frame, int16_t **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
561 {
562         return mlt_frame_get_audio( frame, (void**) buffer, format, frequency, channels, samples );
563 }
564
565 static int get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
566 {
567         return mlt_frame_get_image( frame, buffer, format, width, height, writable );
568 }
569
570 static int get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
571 {
572         DeckLinkProducer* decklink = (DeckLinkProducer*) producer->child;
573         mlt_position pos = mlt_producer_position( producer );
574         mlt_position end = mlt_producer_get_playtime( producer );
575         end = ( mlt_producer_get_length( producer ) < end ? mlt_producer_get_length( producer ) : end ) - 1;
576
577         // Re-open if needed
578         if ( !decklink && pos < end )
579         {
580                 producer->child = decklink = new DeckLinkProducer();
581                 decklink->setProducer( producer );
582                 decklink->open( mlt_properties_get_int( MLT_PRODUCER_PROPERTIES(producer), "resource" ) );
583         }
584
585         // Start if needed
586         if ( decklink )
587         {
588                 decklink->start( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) );
589
590                 // Get the next frame from the decklink object
591                 if ( ( *frame = decklink->getFrame() ))
592                 {
593                         // Add audio and video getters
594                         mlt_frame_push_audio( *frame, (void*) get_audio );
595                         mlt_frame_push_get_image( *frame, get_image );
596                 }
597         }
598         if ( !*frame )
599                 *frame = mlt_frame_init( MLT_PRODUCER_SERVICE(producer) );
600
601         // Calculate the next timecode
602         mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
603         mlt_producer_prepare_next( producer );
604
605         // Close DeckLink if at end
606         if ( pos >= end && decklink )
607         {
608                 decklink->stop();
609                 delete decklink;
610                 producer->child = NULL;
611         }
612
613         return 0;
614 }
615
616 static void producer_close( mlt_producer producer )
617 {
618         delete (DeckLinkProducer*) producer->child;
619         producer->close = NULL;
620         mlt_producer_close( producer );
621 }
622
623 extern "C" {
624
625 /** Initialise the producer.
626  */
627
628 mlt_producer producer_decklink_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
629 {
630         // Allocate the producer
631         DeckLinkProducer* decklink = new DeckLinkProducer();
632         mlt_producer producer = (mlt_producer) calloc( 1, sizeof( *producer ) );
633
634         // If allocated and initializes
635         if ( decklink && !mlt_producer_init( producer, decklink ) )
636         {
637                 if ( decklink->open( arg? atoi( arg ) : 0 ) )
638                 {
639                         mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
640
641                         // Close DeckLink and defer re-open to get_frame
642                         delete decklink;
643                         producer->child = NULL;
644
645                         // Set callbacks
646                         producer->close = (mlt_destructor) producer_close;
647                         producer->get_frame = get_frame;
648
649                         // Set properties
650                         mlt_properties_set( properties, "resource", (arg && strcmp( arg, ""))? arg : "0" );
651                         mlt_properties_set_int( properties, "channels", 2 );
652                         mlt_properties_set_int( properties, "buffer", 25 );
653                         mlt_properties_set_int( properties, "prefill", 25 );
654
655                         // These properties effectively make it infinite.
656                         mlt_properties_set_int( properties, "length", INT_MAX );
657                         mlt_properties_set_int( properties, "out", INT_MAX - 1 );
658                         mlt_properties_set( properties, "eof", "loop" );
659                 }
660         }
661
662         return producer;
663 }
664
665 }