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