]> git.sesse.net Git - mlt/blob - src/modules/decklink/consumer_decklink.cpp
Fix crash in decklink with keyer and interlaced clips (3310104).
[mlt] / src / modules / decklink / consumer_decklink.cpp
1 /*
2  * consumer_decklink.c -- output through Blackmagic Design DeckLink
3  * Copyright (C) 2010 Dan Dennedy <dan@dennedy.org>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with consumer library; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  */
19
20 #include <framework/mlt.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <pthread.h>
24 #include <unistd.h>
25 #include <sys/time.h>
26 #include <limits.h>
27 #include "DeckLinkAPI.h"
28
29 static const unsigned PREROLL_MINIMUM = 3;
30
31 typedef struct
32 {
33         int16_t *buffer;
34         int size;
35         int used;
36         pthread_mutex_t mutex;
37 } *sample_fifo;
38
39 static sample_fifo sample_fifo_init()
40 {
41         sample_fifo fifo = (sample_fifo) calloc( 1, sizeof( *fifo ) );
42         pthread_mutex_init( &fifo->mutex, NULL );
43         return fifo;
44 }
45
46 static void sample_fifo_append( sample_fifo fifo, int16_t *samples, int count )
47 {
48         pthread_mutex_lock( &fifo->mutex );
49         if ( ( fifo->size - fifo->used ) < count )
50         {
51                 fifo->size += count * 5;
52                 fifo->buffer = (int16_t*) realloc( fifo->buffer, fifo->size * sizeof( int16_t ) );
53         }
54         memcpy( fifo->buffer + fifo->used, samples, count * sizeof( int16_t ) );
55         fifo->used += count;
56         pthread_mutex_unlock( &fifo->mutex );
57 }
58
59 static void sample_fifo_remove( sample_fifo fifo, int count )
60 {
61         pthread_mutex_lock( &fifo->mutex );
62         if ( count > fifo->used )
63                 count = fifo->used;
64         fifo->used -= count;
65         memmove( fifo->buffer, fifo->buffer + count, fifo->used * sizeof( int16_t ) );
66         pthread_mutex_unlock( &fifo->mutex );
67 }
68
69 static void sample_fifo_close( sample_fifo fifo )
70 {
71         free( fifo->buffer );
72         pthread_mutex_destroy( &fifo->mutex );
73         free( fifo );
74 }
75
76
77 class DeckLinkConsumer
78         : public IDeckLinkVideoOutputCallback
79         , public IDeckLinkAudioOutputCallback
80 {
81 private:
82         mlt_consumer_s              m_consumer;
83         IDeckLink*                  m_deckLink;
84         IDeckLinkOutput*            m_deckLinkOutput;
85         IDeckLinkDisplayMode*       m_displayMode;
86         pthread_mutex_t             m_mutex;
87         pthread_cond_t              m_condition;
88         int                         m_width;
89         int                         m_height;
90         BMDTimeValue                m_duration;
91         BMDTimeScale                m_timescale;
92         double                      m_fps;
93         uint64_t                    m_count;
94         sample_fifo                 m_fifo;
95         unsigned                    m_preroll;
96         bool                        m_isPrerolling;
97         unsigned                    m_prerollCounter;
98         int                         m_channels;
99         uint32_t                    m_maxAudioBuffer;
100         mlt_deque                   m_videoFrameQ;
101         mlt_frame                   m_frame;
102         unsigned                    m_dropped;
103         bool                        m_isAudio;
104         bool                        m_isKeyer;
105         IDeckLinkKeyer*             m_deckLinkKeyer;
106
107         IDeckLinkDisplayMode* getDisplayMode()
108         {
109                 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( getConsumer() ) );
110                 IDeckLinkDisplayModeIterator* iter;
111                 IDeckLinkDisplayMode* mode;
112                 IDeckLinkDisplayMode* result = 0;
113                 
114                 if ( m_deckLinkOutput->GetDisplayModeIterator( &iter ) == S_OK )
115                 {
116                         while ( !result && iter->Next( &mode ) == S_OK )
117                         {
118                                 m_width = mode->GetWidth();
119                                 m_height = mode->GetHeight();
120                                 mode->GetFrameRate( &m_duration, &m_timescale );
121                                 m_fps = (double) m_timescale / m_duration;
122                                 int p = mode->GetFieldDominance() == bmdProgressiveFrame;
123                                 mlt_log_verbose( getConsumer(), "BMD mode %dx%d %.3f fps prog %d\n", m_width, m_height, m_fps, p );
124                                 
125                                 if ( m_width == profile->width && m_height == profile->height && p == profile->progressive
126                                          && m_fps == mlt_profile_fps( profile ) )
127                                         result = mode;
128                         }
129                 }
130                 
131                 return result;
132         }
133         
134 public:
135         mlt_consumer getConsumer()
136                 { return &m_consumer; }
137         uint64_t isBuffering() const
138                 { return m_prerollCounter < m_preroll; }
139         
140         ~DeckLinkConsumer()
141         {
142                 if ( m_deckLinkKeyer )
143                         m_deckLinkKeyer->Release();
144                 if ( m_deckLinkOutput )
145                         m_deckLinkOutput->Release();
146                 if ( m_deckLink )
147                         m_deckLink->Release();
148                 if ( m_videoFrameQ )
149                 {
150                         mlt_deque_close( m_videoFrameQ );
151                         pthread_mutex_destroy( &m_mutex );
152                         pthread_cond_destroy( &m_condition );
153                 }
154         }
155         
156         bool open( unsigned card = 0 )
157         {
158                 IDeckLinkIterator* deckLinkIterator = CreateDeckLinkIteratorInstance();
159                 unsigned i = 0;
160                 
161                 if ( !deckLinkIterator )
162                 {
163                         mlt_log_error( getConsumer(), "The DeckLink drivers not installed.\n" );
164                         return false;
165                 }
166                 
167                 // Connect to the Nth DeckLink instance
168                 do {
169                         if ( deckLinkIterator->Next( &m_deckLink ) != S_OK )
170                         {
171                                 mlt_log_error( getConsumer(), "DeckLink card not found\n" );
172                                 deckLinkIterator->Release();
173                                 return false;
174                         }
175                 } while ( ++i <= card );
176                 deckLinkIterator->Release();
177                 
178                 // Obtain the audio/video output interface (IDeckLinkOutput)
179                 if ( m_deckLink->QueryInterface( IID_IDeckLinkOutput, (void**)&m_deckLinkOutput ) != S_OK )
180                 {
181                         mlt_log_error( getConsumer(), "No DeckLink cards support output\n" );
182                         m_deckLink->Release();
183                         m_deckLink = 0;
184                         return false;
185                 }
186                 
187                 // Get the keyer interface
188                 IDeckLinkAttributes *deckLinkAttributes = 0;
189                 m_deckLinkKeyer = 0;
190                 if ( m_deckLink->QueryInterface( IID_IDeckLinkAttributes, (void**) &deckLinkAttributes ) == S_OK )
191                 {
192                         bool flag = false;
193                         if ( deckLinkAttributes->GetFlag( BMDDeckLinkSupportsInternalKeying, &flag ) == S_OK && flag )
194                         {
195                                 if ( m_deckLink->QueryInterface( IID_IDeckLinkKeyer, (void**) &m_deckLinkKeyer ) != S_OK )
196                                 {
197                                         mlt_log_error( getConsumer(), "Failed to get keyer\n" );
198                                         m_deckLinkOutput->Release();
199                                         m_deckLinkOutput = 0;
200                                         m_deckLink->Release();
201                                         m_deckLink = 0;
202                                         return false;
203                                 }
204                         }
205                         deckLinkAttributes->Release();
206                 }
207
208                 // Provide this class as a delegate to the audio and video output interfaces
209                 m_deckLinkOutput->SetScheduledFrameCompletionCallback( this );
210                 m_deckLinkOutput->SetAudioCallback( this );
211                 
212                 pthread_mutex_init( &m_mutex, NULL );
213                 pthread_cond_init( &m_condition, NULL );
214                 m_maxAudioBuffer = bmdAudioSampleRate48kHz;
215                 m_videoFrameQ = mlt_deque_init();
216                 
217                 return true;
218         }
219         
220         bool start( unsigned preroll )
221         {
222                 mlt_properties properties = MLT_CONSUMER_PROPERTIES( getConsumer() );
223
224                 // Initialize members
225                 m_count = 0;
226                 m_frame = 0;
227                 m_dropped = 0;
228                 m_isPrerolling = true;
229                 m_prerollCounter = 0;
230                 m_preroll = preroll < PREROLL_MINIMUM ? PREROLL_MINIMUM : preroll;
231                 m_channels = mlt_properties_get_int( properties, "channels" );
232                 m_isAudio = !mlt_properties_get_int( properties, "audio_off" );
233
234                 m_displayMode = getDisplayMode();
235                 if ( !m_displayMode )
236                 {
237                         mlt_log_error( getConsumer(), "Profile is not compatible with decklink.\n" );
238                         return false;
239                 }
240                 
241                 // Set the keyer
242                 if ( m_deckLinkKeyer && ( m_isKeyer = mlt_properties_get_int( properties, "keyer" ) ) )
243                 {
244                         bool external = false;
245                         double level = mlt_properties_get_double( properties, "keyer_level" );
246
247                         if ( m_deckLinkKeyer->Enable( external ) != S_OK )
248                                 mlt_log_error( getConsumer(), "Failed to enable keyer\n" );
249                         m_deckLinkKeyer->SetLevel( level <= 1 ? ( level > 0 ? 255 * level : 255 ) : 255 );
250                         m_preroll = 0;
251                         m_isAudio = false;
252                 }
253                 else if ( m_deckLinkKeyer )
254                 {
255                         m_deckLinkKeyer->Disable();
256                 }
257
258                 // Set the video output mode
259                 if ( S_OK != m_deckLinkOutput->EnableVideoOutput( m_displayMode->GetDisplayMode(), bmdVideoOutputFlagDefault) )
260                 {
261                         mlt_log_error( getConsumer(), "Failed to enable video output\n" );
262                         return false;
263                 }
264
265                 // Set the audio output mode
266                 if ( !m_isAudio )
267                 {
268                         m_deckLinkOutput->DisableAudioOutput();
269                         return true;
270                 }
271                 if ( S_OK != m_deckLinkOutput->EnableAudioOutput( bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger,
272                         m_channels, bmdAudioOutputStreamContinuous ) )
273                 {
274                         mlt_log_error( getConsumer(), "Failed to enable audio output\n" );
275                         stop();
276                         return false;
277                 }
278                 m_fifo = sample_fifo_init();
279                 m_deckLinkOutput->BeginAudioPreroll();
280                 
281                 return true;
282         }
283         
284         void wakeup()
285         {
286                 pthread_mutex_lock( &m_mutex );
287                 pthread_cond_broadcast( &m_condition );
288                 pthread_mutex_unlock( &m_mutex );
289         }
290         
291         void wait()
292         {
293                 struct timeval tv;
294                 struct timespec ts;
295                 
296                 gettimeofday( &tv, NULL );
297                 ts.tv_sec = tv.tv_sec + 1;
298                 ts.tv_nsec = tv.tv_usec * 1000;
299                 pthread_mutex_lock( &m_mutex );
300                 pthread_cond_timedwait( &m_condition, &m_mutex, &ts );
301                 pthread_mutex_unlock( &m_mutex );
302         }
303         
304         void stop()
305         {
306                 // Stop the audio and video output streams immediately
307                 if ( m_deckLinkOutput )
308                 {
309                         m_deckLinkOutput->StopScheduledPlayback( 0, 0, 0 );
310                         m_deckLinkOutput->DisableAudioOutput();
311                         m_deckLinkOutput->DisableVideoOutput();
312                 }
313                 while ( mlt_deque_count( m_videoFrameQ ) )
314                 {
315                         IDeckLinkMutableVideoFrame* frame = (IDeckLinkMutableVideoFrame*) mlt_deque_pop_back( m_videoFrameQ );
316                         frame->Release();
317                 }
318                 if ( m_fifo ) sample_fifo_close( m_fifo );
319                 mlt_frame_close( m_frame );
320         }
321
322         void renderAudio( mlt_frame frame )
323         {
324                 mlt_audio_format format = mlt_audio_s16;
325                 int frequency = bmdAudioSampleRate48kHz;
326                 int samples = mlt_sample_calculator( m_fps, frequency, m_count );
327                 int16_t *pcm = 0;
328
329                 if ( !mlt_frame_get_audio( frame, (void**) &pcm, &format, &frequency, &m_channels, &samples ) )
330                 {
331                         int count = samples;
332
333                         if ( !m_isPrerolling )
334                         {
335                                 uint32_t audioCount = 0;
336                                 uint32_t videoCount = 0;
337
338                                 // Check for resync
339                                 m_deckLinkOutput->GetBufferedAudioSampleFrameCount( &audioCount );
340                                 m_deckLinkOutput->GetBufferedVideoFrameCount( &videoCount );
341
342                                 // Underflow typically occurs during non-normal speed playback.
343                                 if ( audioCount < 1 || videoCount < 1 )
344                                 {
345                                         // Upon switching to normal playback, buffer some frames faster than realtime.
346                                         mlt_log_info( getConsumer(), "buffer underrun: audio buf %u video buf %u frames\n", audioCount, videoCount );
347                                         m_prerollCounter = 0;
348                                 }
349
350                                 // While rebuffering
351                                 if ( videoCount == 0 && isBuffering() )
352                                 {
353                                         // Only append audio to reach the ideal level and not overbuffer.
354                                         int ideal = ( m_preroll - 1 ) * bmdAudioSampleRate48kHz / m_fps;
355                                         int actual = m_fifo->used / m_channels + audioCount;
356                                         int diff = ideal / 2 - actual;
357                                         count = diff < 0 ? 0 : diff < count ? diff : count;
358                                 }
359                         }
360                         if ( count > 0 )
361                                 sample_fifo_append( m_fifo, pcm, count * m_channels );
362                 }
363         }
364
365         bool createFrame()
366         {
367                 BMDPixelFormat format = m_isKeyer? bmdFormat8BitARGB : bmdFormat8BitYUV;
368                 IDeckLinkMutableVideoFrame* frame = 0;
369                 uint8_t *buffer = 0;
370                 int stride = m_width * ( m_isKeyer? 4 : 2 );
371
372                 // Generate a DeckLink video frame
373                 if ( S_OK != m_deckLinkOutput->CreateVideoFrame( m_width, m_height,
374                         stride, format, bmdFrameFlagDefault, &frame ) )
375                 {
376                         mlt_log_verbose( getConsumer(), "Failed to create video frame\n" );
377                         stop();
378                         return false;
379                 }
380                 
381                 // Make the first line black for field order correction.
382                 if ( S_OK == frame->GetBytes( (void**) &buffer ) && buffer )
383                 {
384                         if ( m_isKeyer )
385                         {
386                                 memset( buffer, 0, stride );
387                         }
388                         else for ( int i = 0; i < m_width; i++ )
389                         {
390                                 *buffer++ = 128;
391                                 *buffer++ = 16;
392                         }
393                 }
394                 mlt_log_debug( getConsumer(), "created video frame\n" );
395                 mlt_deque_push_back( m_videoFrameQ, frame );
396
397                 return true;
398         }
399
400         void renderVideo()
401         {
402                 mlt_image_format format = m_isKeyer? mlt_image_rgb24a : mlt_image_yuv422;
403                 uint8_t* image = 0;
404
405                 if ( !mlt_frame_get_image( m_frame, &image, &format, &m_width, &m_height, 0 ) )
406                 {
407                         IDeckLinkMutableVideoFrame* decklinkFrame = (IDeckLinkMutableVideoFrame*) mlt_deque_pop_back( m_videoFrameQ );
408                         uint8_t* buffer = 0;
409                         int stride = m_width * ( m_isKeyer? 4 : 2 );
410
411                         decklinkFrame->GetBytes( (void**) &buffer );
412                         if ( buffer )
413                         {
414                                 int progressive = mlt_properties_get_int( MLT_FRAME_PROPERTIES( m_frame ), "progressive" );
415
416                                 if ( !m_isKeyer )
417                                 {
418                                         // Normal non-keyer playout - needs byte swapping
419                                         if ( !progressive && m_displayMode->GetFieldDominance() == bmdUpperFieldFirst )
420                                                 // convert lower field first to top field first
421                                                 swab( image, buffer + stride, stride * ( m_height - 1 ) );
422                                         else
423                                                 swab( image, buffer, stride * m_height );
424                                 }
425                                 else if ( !mlt_properties_get_int( MLT_FRAME_PROPERTIES( m_frame ), "test_image" ) )
426                                 {
427                                         // Normal keyer output
428                                         int y = m_height + 1;
429                                         uint32_t* s = (uint32_t*) image;
430                                         uint32_t* d = (uint32_t*) buffer;
431
432                                         if ( !progressive && m_displayMode->GetFieldDominance() == bmdUpperFieldFirst )
433                                         {
434                                                 // Correct field order
435                                                 m_height--;
436                                                 y--;
437                                                 d += m_width;
438                                         }
439
440                                         // Need to relocate alpha channel RGBA => ARGB
441                                         while ( --y )
442                                         {
443                                                 int x = m_width + 1;
444                                                 while ( --x )
445                                                 {
446                                                         *d++ = ( *s << 8 ) | ( *s >> 24 );
447                                                         s++;
448                                                 }
449                                         }
450                                 }
451                                 else
452                                 {
453                                         // Keying blank frames - nullify alpha
454                                         memset( buffer, 0, stride * m_height );
455                                 }
456                                 m_deckLinkOutput->ScheduleVideoFrame( decklinkFrame, m_count * m_duration, m_duration, m_timescale );
457                         }
458                         mlt_deque_push_front( m_videoFrameQ, decklinkFrame );
459                 }
460         }
461
462         HRESULT render( mlt_frame frame )
463         {
464                 HRESULT result = S_OK;
465
466                 // Get the audio
467                 double speed = mlt_properties_get_double( MLT_FRAME_PROPERTIES(frame), "_speed" );
468                 if ( m_isAudio && speed == 1.0 )
469                         renderAudio( frame );
470                 
471                 // Create video frames while pre-rolling
472                 if ( m_isPrerolling )
473                 {
474                         if ( !createFrame() )
475                         {
476                                 mlt_log_error( getConsumer(), "failed to create video frame\n" );
477                                 return S_FALSE;
478                         }
479                 }
480                 
481                 if ( mlt_properties_get_int( MLT_FRAME_PROPERTIES( frame ), "rendered") )
482                 {
483                         // Close the previous frame and use the new one
484                         mlt_frame_close( m_frame );
485                         m_frame = frame;
486                 }
487                 else
488                 {
489                         if ( !m_frame )
490                                 m_frame = frame;
491                         // Reuse the last frame
492                         mlt_log_verbose( getConsumer(), "dropped video frame %u\n", ++m_dropped );
493                 }
494
495                 // Get the video
496                 renderVideo();
497                 ++m_count;
498
499                 // Check for end of pre-roll
500                 if ( ++m_prerollCounter > m_preroll && m_isPrerolling )
501                 {
502                         // Start audio and video output
503                         if ( m_isAudio )
504                                 m_deckLinkOutput->EndAudioPreroll();
505                         m_deckLinkOutput->StartScheduledPlayback( 0, m_timescale, 1.0 );
506                         m_isPrerolling = false;
507                 }
508
509                 return result;
510         }
511         
512         // *** DeckLink API implementation of IDeckLinkVideoOutputCallback IDeckLinkAudioOutputCallback *** //
513
514         // IUnknown needs only a dummy implementation
515         virtual HRESULT STDMETHODCALLTYPE QueryInterface( REFIID iid, LPVOID *ppv )
516                 { return E_NOINTERFACE; }
517         virtual ULONG STDMETHODCALLTYPE AddRef()
518                 { return 1; }
519         virtual ULONG STDMETHODCALLTYPE Release()
520                 { return 1; }
521         
522         /************************* DeckLink API Delegate Methods *****************************/
523         
524         virtual HRESULT STDMETHODCALLTYPE ScheduledFrameCompleted( IDeckLinkVideoFrame* completedFrame, BMDOutputFrameCompletionResult completed )
525         {
526                 // When a video frame has been released by the API, schedule another video frame to be output
527                 wakeup();
528                 
529                 return S_OK;
530         }
531
532         virtual HRESULT STDMETHODCALLTYPE ScheduledPlaybackHasStopped()
533         {
534                 return mlt_consumer_is_stopped( getConsumer() ) ? S_FALSE : S_OK;
535         }
536         
537         virtual HRESULT STDMETHODCALLTYPE RenderAudioSamples( bool preroll )
538         {
539                 // Provide more audio samples to the DeckLink API
540                 HRESULT result = S_OK;
541
542                 uint32_t count = m_fifo->used / m_channels;
543                 uint32_t buffered = count;
544
545                 if ( count
546                         // Stay under preferred buffer level
547                         && ( S_OK == m_deckLinkOutput->GetBufferedAudioSampleFrameCount( &buffered ) )
548                         && buffered < m_maxAudioBuffer )
549                 {
550                         uint32_t written = 0;
551                         
552                         buffered = m_maxAudioBuffer - buffered;
553                         count = buffered > count ? count : buffered;
554                         result = m_deckLinkOutput->ScheduleAudioSamples( m_fifo->buffer, count, 0, 0, &written );
555                         if ( written )
556                                 sample_fifo_remove( m_fifo, written * m_channels );
557                 }
558
559                 return result;
560         }
561 };
562
563 /** The main thread.
564  */
565
566 static void *run( void *arg )
567 {
568         // Map the argument to the object
569         DeckLinkConsumer* decklink = (DeckLinkConsumer*) arg;
570         mlt_consumer consumer = decklink->getConsumer();
571         
572         // Get the properties
573         mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
574
575         // Convenience functionality
576         int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
577         int terminated = 0;
578
579         // Frame and size
580         mlt_frame frame = NULL;
581         
582         // Loop while running
583         while ( !terminated && mlt_properties_get_int( properties, "running" ) )
584         {
585                 // Get the frame
586                 if ( ( frame = mlt_consumer_rt_frame( consumer ) ) )
587                 {
588                         // Check for termination
589                         if ( terminate_on_pause )
590                                 terminated = mlt_properties_get_double( MLT_FRAME_PROPERTIES( frame ), "_speed" ) == 0.0;
591
592                         decklink->render( frame );
593                         if ( !decklink->isBuffering() )
594                                 decklink->wait();
595                         mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
596                 }
597         }
598
599         // Indicate that the consumer is stopped
600         decklink->stop();
601         mlt_properties_set_int( properties, "running", 0 );
602         mlt_consumer_stopped( consumer );
603
604         return NULL;
605 }
606
607 /** Start the consumer.
608  */
609
610 static int start( mlt_consumer consumer )
611 {
612         // Get the properties
613         mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
614         DeckLinkConsumer* decklink = (DeckLinkConsumer*) consumer->child;
615         int result = decklink->start( mlt_properties_get_int( properties, "preroll" ) ) ? 0 : 1;
616
617         // Check that we're not already running
618         if ( !result && !mlt_properties_get_int( properties, "running" ) )
619         {
620                 // Allocate a thread
621                 pthread_t *pthread = (pthread_t*) calloc( 1, sizeof( pthread_t ) );
622
623                 // Assign the thread to properties
624                 mlt_properties_set_data( properties, "pthread", pthread, sizeof( pthread_t ), free, NULL );
625
626                 // Set the running state
627                 mlt_properties_set_int( properties, "running", 1 );
628                 mlt_properties_set_int( properties, "joined", 0 );
629
630                 // Create the thread
631                 pthread_create( pthread, NULL, run, consumer->child );
632         }
633         return result;
634 }
635
636 /** Stop the consumer.
637  */
638
639 static int stop( mlt_consumer consumer )
640 {
641         // Get the properties
642         mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
643
644         // Check that we're running
645         if ( !mlt_properties_get_int( properties, "joined" ) )
646         {
647                 // Get the thread
648                 pthread_t *pthread = (pthread_t*) mlt_properties_get_data( properties, "pthread", NULL );
649                 
650                 if ( pthread )
651                 {
652                         // Stop the thread
653                         mlt_properties_set_int( properties, "running", 0 );
654                         mlt_properties_set_int( properties, "joined", 1 );
655         
656                         // Wait for termination
657                         pthread_join( *pthread, NULL );
658                 }
659         }
660
661         return 0;
662 }
663
664 /** Determine if the consumer is stopped.
665  */
666
667 static int is_stopped( mlt_consumer consumer )
668 {
669         // Get the properties
670         mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
671         return !mlt_properties_get_int( properties, "running" );
672 }
673
674 /** Close the consumer.
675  */
676
677 static void close( mlt_consumer consumer )
678 {
679         // Stop the consumer
680         mlt_consumer_stop( consumer );
681
682         // Close the parent
683         consumer->close = NULL;
684         mlt_consumer_close( consumer );
685
686         // Free the memory
687         delete (DeckLinkConsumer*) consumer->child;
688 }
689
690 extern "C" {
691
692 /** Initialise the consumer.
693  */
694
695 mlt_consumer consumer_decklink_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
696 {
697         // Allocate the consumer
698         DeckLinkConsumer* decklink = new DeckLinkConsumer();
699         mlt_consumer consumer = NULL;
700
701         // If allocated
702         if ( decklink && !mlt_consumer_init( decklink->getConsumer(), decklink, profile ) )
703         {
704                 // If initialises without error
705                 if ( decklink->open( arg? atoi(arg) : 0 ) )
706                 {
707                         consumer = decklink->getConsumer();
708                         
709                         // Setup callbacks
710                         consumer->close = close;
711                         consumer->start = start;
712                         consumer->stop = stop;
713                         consumer->is_stopped = is_stopped;
714                 }
715         }
716
717         // Return consumer
718         return consumer;
719 }
720
721 extern mlt_producer producer_decklink_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg );
722
723 static mlt_properties metadata( mlt_service_type type, const char *id, void *data )
724 {
725         char file[ PATH_MAX ];
726         const char *service_type = NULL;
727         switch ( type )
728         {
729                 case consumer_type:
730                         service_type = "consumer";
731                         break;
732                 case producer_type:
733                         service_type = "producer";
734                         break;
735                 default:
736                         return NULL;
737         }
738         snprintf( file, PATH_MAX, "%s/decklink/%s_%s.yml", mlt_environment( "MLT_DATA" ), service_type, id );
739         return mlt_properties_parse_yaml( file );
740 }
741
742 MLT_REPOSITORY
743 {
744         MLT_REGISTER( consumer_type, "decklink", consumer_decklink_init );
745         MLT_REGISTER( producer_type, "decklink", producer_decklink_init );
746         MLT_REGISTER_METADATA( consumer_type, "decklink", metadata, NULL );
747         MLT_REGISTER_METADATA( producer_type, "decklink", metadata, NULL );
748 }
749
750 } // extern C