]> git.sesse.net Git - mlt/blob - src/modules/decklink/producer_decklink.cpp
fix regression when using producer 'consumer' with decklink
[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_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "preview" ) &&
361                         mlt_producer_get_speed( getProducer() ) == 0.0 && !mlt_deque_count( m_queue ))
362                 {
363                         pthread_cond_broadcast( &m_condition );
364                         return S_OK;
365                 }
366
367                 // Create mlt_frame
368                 mlt_frame frame = mlt_frame_init( MLT_PRODUCER_SERVICE( getProducer() ) );
369
370                 // Copy video
371                 if ( video )
372                 {
373                         if ( !( video->GetFlags() & bmdFrameHasNoInputSource ) )
374                         {
375                                 int size = video->GetRowBytes() * ( video->GetHeight() + m_vancLines );
376                                 void* image = mlt_pool_alloc( size );
377                                 void* buffer = 0;
378                                 unsigned char* p = (unsigned char*) image;
379                                 int n = size / 2;
380 \
381                                 // Initialize VANC lines to nominal black
382                                 while ( --n )
383                                 {
384                                         *p ++ = 16;
385                                         *p ++ = 128;
386                                 }
387
388                                 // Capture VANC
389                                 if ( m_vancLines > 0 )
390                                 {
391                                         IDeckLinkVideoFrameAncillary* vanc = 0;
392                                         if ( video->GetAncillaryData( &vanc ) == S_OK && vanc )
393                                         {
394                                                 for ( int i = 1; i < m_vancLines + 1; i++ )
395                                                 {
396                                                         if ( vanc->GetBufferForVerticalBlankingLine( i, &buffer ) == S_OK )
397                                                                 swab( (char*) buffer, (char*) image + ( i - 1 ) * video->GetRowBytes(), video->GetRowBytes() );
398                                                         else
399                                                                 mlt_log_debug( getProducer(), "failed capture vanc line %d\n", i );
400                                                 }
401                                                 vanc->Release();
402                                         }
403                                 }
404
405                                 // Capture image
406                                 video->GetBytes( &buffer );
407                                 if ( image && buffer )
408                                 {
409                                         size =  video->GetRowBytes() * video->GetHeight();
410                                         swab( (char*) buffer, (char*) image + m_vancLines * video->GetRowBytes(), size );
411                                         mlt_frame_set_image( frame, (uint8_t*) image, size, mlt_pool_release );
412                                 }
413                                 else if ( image )
414                                 {
415                                         mlt_log_verbose( getProducer(), "no video\n" );
416                                         mlt_pool_release( image );
417                                 }
418                         }
419                         else
420                         {
421                                 mlt_log_verbose( getProducer(), "no signal\n" );
422                                 mlt_frame_close( frame );
423                                 frame = 0;
424                         }
425
426                         // Get timecode
427                         IDeckLinkTimecode* timecode = 0;
428                         if ( video->GetTimecode( bmdTimecodeVITC, &timecode ) == S_OK && timecode )
429                         {
430                                 const char* timecodeString = 0;
431
432 #ifdef WIN32
433                                 if ( timecode->GetString( (BSTR*) &timecodeString ) == S_OK )
434 #else
435                                 if ( timecode->GetString( &timecodeString ) == S_OK )
436 #endif
437                                 {
438                                         mlt_properties_set( MLT_FRAME_PROPERTIES( frame ), "meta.attr.vitc.markup", timecodeString );
439                                         mlt_log_debug( getProducer(), "timecode %s\n", timecodeString );
440                                 }
441                                 if ( timecodeString )
442                                         free( (void*) timecodeString );
443                                 timecode->Release();
444                         }
445                 }
446                 else
447                 {
448                         mlt_log_verbose( getProducer(), "no video\n" );
449                         mlt_frame_close( frame );
450                         frame = 0;
451                 }
452
453                 // Copy audio
454                 if ( frame && audio )
455                 {
456                         int channels = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "channels" );
457                         int size = audio->GetSampleFrameCount() * channels * sizeof(int16_t);
458                         mlt_audio_format format = mlt_audio_s16;
459                         void* pcm = mlt_pool_alloc( size );
460                         void* buffer = 0;
461
462                         audio->GetBytes( &buffer );
463                         if ( buffer )
464                         {
465                                 memcpy( pcm, buffer, size );
466                                 mlt_frame_set_audio( frame, pcm, format, size, mlt_pool_release );
467                                 mlt_properties_set_int( MLT_FRAME_PROPERTIES(frame), "audio_samples", audio->GetSampleFrameCount() );
468                         }
469                         else
470                         {
471                                 mlt_log_verbose( getProducer(), "no audio\n" );
472                                 mlt_pool_release( pcm );
473                         }
474                 }
475                 else
476                 {
477                         mlt_log_verbose( getProducer(), "no audio\n" );
478                 }
479
480                 // Put frame in queue
481                 if ( frame )
482                 {
483                         int queueMax = mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "buffer" );
484                         pthread_mutex_lock( &m_mutex );
485                         if ( mlt_deque_count( m_queue ) < queueMax )
486                         {
487                                 mlt_deque_push_back( m_queue, frame );
488                                 pthread_cond_broadcast( &m_condition );
489                         }
490                         else
491                         {
492                                 mlt_frame_close( frame );
493                                 mlt_properties_set_int( MLT_PRODUCER_PROPERTIES( getProducer() ), "dropped", ++m_dropped );
494                                 mlt_log_warning( getProducer(), "frame dropped %d\n", m_dropped );
495                         }
496                         pthread_mutex_unlock( &m_mutex );
497                 }
498
499                 return S_OK;
500         }
501
502         virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(
503                         BMDVideoInputFormatChangedEvents events,
504                         IDeckLinkDisplayMode* mode,
505                         BMDDetectedVideoInputFormatFlags flags )
506         {
507                 mlt_profile profile = mlt_service_profile( MLT_PRODUCER_SERVICE( getProducer() ) );
508                 if ( events & bmdVideoInputDisplayModeChanged )
509                 {
510                         BMDTimeValue duration;
511                         BMDTimeScale timescale;
512                         mode->GetFrameRate( &duration, &timescale );
513                         profile->width = mode->GetWidth();
514                         profile->height = mode->GetHeight() + m_vancLines;
515                         profile->frame_rate_num = timescale;
516                         profile->frame_rate_den = duration;
517                         if ( profile->width == 720 )
518                         {
519                                 if ( profile->height == 576 )
520                                 {
521                                         profile->sample_aspect_num = 16;
522                                         profile->sample_aspect_den = 15;
523                                 }
524                                 else
525                                 {
526                                         profile->sample_aspect_num = 8;
527                                         profile->sample_aspect_den = 9;
528                                 }
529                                 profile->display_aspect_num = 4;
530                                 profile->display_aspect_den = 3;
531                         }
532                         else
533                         {
534                                 profile->sample_aspect_num = 1;
535                                 profile->sample_aspect_den = 1;
536                                 profile->display_aspect_num = 16;
537                                 profile->display_aspect_den = 9;
538                         }
539                         free( profile->description );
540                         profile->description = strdup( "decklink" );
541                         mlt_log_verbose( getProducer(), "format changed %dx%d %.3f fps\n",
542                                 profile->width, profile->height, (double) profile->frame_rate_num / profile->frame_rate_den );
543                 }
544                 if ( events & bmdVideoInputFieldDominanceChanged )
545                 {
546                         profile->progressive = mode->GetFieldDominance() == bmdProgressiveFrame;
547                         m_topFieldFirst = mode->GetFieldDominance() == bmdUpperFieldFirst;
548                         mlt_log_verbose( getProducer(), "field dominance changed prog %d tff %d\n",
549                                 profile->progressive, m_topFieldFirst );
550                 }
551                 if ( events & bmdVideoInputColorspaceChanged )
552                 {
553                         profile->colorspace = m_colorspace =
554                                 ( mode->GetFlags() & bmdDisplayModeColorspaceRec709 ) ? 709 : 601;
555                         mlt_log_verbose( getProducer(), "colorspace changed %d\n", profile->colorspace );
556                 }
557                 return S_OK;
558         }
559 };
560
561 static int get_audio( mlt_frame frame, int16_t **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
562 {
563         return mlt_frame_get_audio( frame, (void**) buffer, format, frequency, channels, samples );
564 }
565
566 static int get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
567 {
568         return mlt_frame_get_image( frame, buffer, format, width, height, writable );
569 }
570
571 static int get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
572 {
573         DeckLinkProducer* decklink = (DeckLinkProducer*) producer->child;
574         mlt_position pos = mlt_producer_position( producer );
575         mlt_position end = mlt_producer_get_playtime( producer );
576         end = ( mlt_producer_get_length( producer ) < end ? mlt_producer_get_length( producer ) : end ) - 1;
577
578         // Re-open if needed
579         if ( !decklink && pos < end )
580         {
581                 producer->child = decklink = new DeckLinkProducer();
582                 decklink->setProducer( producer );
583                 decklink->open( mlt_properties_get_int( MLT_PRODUCER_PROPERTIES(producer), "resource" ) );
584         }
585
586         // Start if needed
587         if ( decklink )
588         {
589                 decklink->start( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) );
590
591                 // Get the next frame from the decklink object
592                 if ( ( *frame = decklink->getFrame() ))
593                 {
594                         // Add audio and video getters
595                         mlt_frame_push_audio( *frame, (void*) get_audio );
596                         mlt_frame_push_get_image( *frame, get_image );
597                 }
598         }
599         if ( !*frame )
600                 *frame = mlt_frame_init( MLT_PRODUCER_SERVICE(producer) );
601
602         // Calculate the next timecode
603         mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
604         mlt_producer_prepare_next( producer );
605
606         // Close DeckLink if at end
607         if ( pos >= end && decklink )
608         {
609                 decklink->stop();
610                 delete decklink;
611                 producer->child = NULL;
612         }
613
614         return 0;
615 }
616
617 static void producer_close( mlt_producer producer )
618 {
619         delete (DeckLinkProducer*) producer->child;
620         producer->close = NULL;
621         mlt_producer_close( producer );
622 }
623
624 extern "C" {
625
626 /** Initialise the producer.
627  */
628
629 mlt_producer producer_decklink_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
630 {
631         // Allocate the producer
632         DeckLinkProducer* decklink = new DeckLinkProducer();
633         mlt_producer producer = (mlt_producer) calloc( 1, sizeof( *producer ) );
634
635         // If allocated and initializes
636         if ( decklink && !mlt_producer_init( producer, decklink ) )
637         {
638                 if ( decklink->open( arg? atoi( arg ) : 0 ) )
639                 {
640                         mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
641
642                         // Close DeckLink and defer re-open to get_frame
643                         delete decklink;
644                         producer->child = NULL;
645
646                         // Set callbacks
647                         producer->close = (mlt_destructor) producer_close;
648                         producer->get_frame = get_frame;
649
650                         // Set properties
651                         mlt_properties_set( properties, "resource", (arg && strcmp( arg, ""))? arg : "0" );
652                         mlt_properties_set_int( properties, "channels", 2 );
653                         mlt_properties_set_int( properties, "buffer", 25 );
654                         mlt_properties_set_int( properties, "prefill", 25 );
655
656                         // These properties effectively make it infinite.
657                         mlt_properties_set_int( properties, "length", INT_MAX );
658                         mlt_properties_set_int( properties, "out", INT_MAX - 1 );
659                         mlt_properties_set( properties, "eof", "loop" );
660                 }
661         }
662
663         return producer;
664 }
665
666 }