]> git.sesse.net Git - vlc/blob - modules/access/decklink.cpp
3aaf8ef0641e80effcf73d84ea6cb40cee0801c9
[vlc] / modules / access / decklink.cpp
1 /*****************************************************************************
2  * decklink.cpp: BlackMagic DeckLink SDI input module
3  *****************************************************************************
4  * Copyright (C) 2010 Steinar H. Gunderson
5  *
6  * Authors: Steinar H. Gunderson <steinar+vlc@gunderson.no>
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
21  *
22  *****************************************************************************/
23
24 #define __STDC_CONSTANT_MACROS 1
25
26 #ifdef HAVE_CONFIG_H
27 # include "config.h"
28 #endif
29
30 #include <vlc_common.h>
31 #include <vlc_plugin.h>
32 #include <vlc_demux.h>
33 #include <vlc_atomic.h>
34
35 #include <arpa/inet.h>
36
37 #include <DeckLinkAPI.h>
38 #include <DeckLinkAPIDispatch.cpp>
39
40 static int  Open ( vlc_object_t * );
41 static void Close( vlc_object_t * );
42
43 #define CARD_INDEX_TEXT N_("Input card to use")
44 #define CARD_INDEX_LONGTEXT N_( \
45     "DeckLink capture card to use, if multiple exist. " \
46     "The cards are numbered from 0." )
47
48 #define MODE_TEXT N_("Desired input video mode")
49 #define MODE_LONGTEXT N_( \
50     "Desired input video mode for DeckLink captures. " \
51     "This value should be a FOURCC code in textual " \
52     "form, e.g. \"ntsc\"." )
53
54 #define CACHING_TEXT N_("Caching value in ms")
55 #define CACHING_LONGTEXT N_( \
56     "Caching value for DeckLink captures. This " \
57     "value should be set in milliseconds." )
58
59 #define AUDIO_CONNECTION_TEXT N_("Audio connection")
60 #define AUDIO_CONNECTION_LONGTEXT N_( \
61     "Audio connection to use for DeckLink captures. " \
62     "Valid choices: embedded, aesebu, analog. " \
63     "Leave blank for card default." )
64
65 #define RATE_TEXT N_("Audio sampling rate in Hz")
66 #define RATE_LONGTEXT N_( \
67     "Audio sampling rate (in hertz) for DeckLink captures. " \
68     "0 disables audio input." )
69
70 #define CHANNELS_TEXT N_("Number of audio channels")
71 #define CHANNELS_LONGTEXT N_( \
72     "Number of input audio channels for DeckLink captures. " \
73     "Must be 2, 8 or 16. 0 disables audio input." )
74
75 #define VIDEO_CONNECTION_TEXT N_("Video connection")
76 #define VIDEO_CONNECTION_LONGTEXT N_( \
77     "Video connection to use for DeckLink captures. " \
78     "Valid choices: sdi, hdmi, opticalsdi, component, " \
79     "composite, svideo. " \
80     "Leave blank for card default." )
81
82 #define ASPECT_RATIO_TEXT N_("Aspect ratio")
83 #define ASPECT_RATIO_LONGTEXT N_( \
84     "Aspect ratio (4:3, 16:9). Default assumes square pixels." )
85
86 vlc_module_begin ()
87     set_shortname( N_("DeckLink") )
88     set_description( N_("Blackmagic DeckLink SDI input") )
89     set_category( CAT_INPUT )
90     set_subcategory( SUBCAT_INPUT_ACCESS )
91
92     add_integer( "decklink-card-index", 0, NULL,
93                  CARD_INDEX_TEXT, CARD_INDEX_LONGTEXT, true )
94     add_string( "decklink-mode", "pal ", NULL,
95                  MODE_TEXT, MODE_LONGTEXT, true )
96     add_integer( "decklink-caching", DEFAULT_PTS_DELAY / 1000, NULL,
97                  CACHING_TEXT, CACHING_LONGTEXT, true )
98     add_string( "decklink-audio-connection", 0, NULL,
99                  AUDIO_CONNECTION_TEXT, AUDIO_CONNECTION_LONGTEXT, true )
100     add_integer( "decklink-audio-rate", 48000, NULL,
101                  RATE_TEXT, RATE_LONGTEXT, true )
102     add_integer( "decklink-audio-channels", 2, NULL,
103                  CHANNELS_TEXT, CHANNELS_LONGTEXT, true )
104     add_string( "decklink-video-connection", 0, NULL,
105                  VIDEO_CONNECTION_TEXT, VIDEO_CONNECTION_LONGTEXT, true )
106     add_string( "decklink-aspect-ratio", NULL, NULL,
107                 ASPECT_RATIO_TEXT, ASPECT_RATIO_LONGTEXT, true )
108
109     add_shortcut( "decklink" )
110     set_capability( "access_demux", 10 )
111     set_callbacks( Open, Close )
112 vlc_module_end ()
113
114 static int Demux  ( demux_t * );
115 static int Control( demux_t *, int, va_list );
116
117 class DeckLinkCaptureDelegate;
118
119 struct demux_sys_t
120 {
121     IDeckLink *p_card;
122     IDeckLinkInput *p_input;
123     DeckLinkCaptureDelegate *p_delegate;
124
125     es_out_id_t *p_video_es;
126     es_out_id_t *p_audio_es;
127     bool b_first_frame;
128     int i_last_pts;
129
130     uint32_t i_dominance_flags;
131     int i_channels;
132
133     vlc_mutex_t frame_lock;
134     block_t *p_video_frame;  /* protected by <frame_lock> */
135     block_t *p_audio_frame;  /* protected by <frame_lock> */
136     vlc_cond_t has_frame;  /* related to <frame_lock> */
137 };
138
139 class DeckLinkCaptureDelegate : public IDeckLinkInputCallback
140 {
141 public:
142     DeckLinkCaptureDelegate( demux_t *p_demux ) : p_demux_(p_demux)
143     {
144         vlc_atomic_set( &m_ref_, 1 );
145     }
146
147     virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
148
149     virtual ULONG STDMETHODCALLTYPE AddRef(void)
150     {
151         return vlc_atomic_inc( &m_ref_ );
152     }
153
154     virtual ULONG STDMETHODCALLTYPE Release(void)
155     {
156         uintptr_t new_ref = vlc_atomic_dec( &m_ref_ );
157         if ( new_ref == 0 )
158             delete this;
159         return new_ref;
160     }
161
162     virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents, IDeckLinkDisplayMode*, BMDDetectedVideoInputFormatFlags)
163     {
164         msg_Dbg( p_demux_, "Video input format changed" );
165         return S_OK;
166     }
167
168     virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame*, IDeckLinkAudioInputPacket*);
169
170 private:
171     vlc_atomic_t m_ref_;
172     demux_t *p_demux_;
173 };
174
175 HRESULT DeckLinkCaptureDelegate::VideoInputFrameArrived(IDeckLinkVideoInputFrame* videoFrame, IDeckLinkAudioInputPacket* audioFrame)
176 {
177     demux_sys_t *p_sys = p_demux_->p_sys;
178     block_t *p_video_frame = NULL;
179     block_t *p_audio_frame = NULL;
180
181     if( videoFrame )
182     {
183         if( videoFrame->GetFlags() & bmdFrameHasNoInputSource )
184         {
185             msg_Warn( p_demux_, "No input signal detected" );
186             return S_OK;
187         }
188
189         const int i_width = videoFrame->GetWidth();
190         const int i_height = videoFrame->GetHeight();
191         const int i_stride = videoFrame->GetRowBytes();
192         const int i_bpp = 2;
193
194         p_video_frame = block_New( p_demux_, i_width * i_height * i_bpp );
195         if( !p_video_frame )
196         {
197             msg_Err( p_demux_, "Could not allocate memory for video frame" );
198             return S_OK;
199         }
200
201         void *frame_bytes;
202         videoFrame->GetBytes( &frame_bytes );
203         for( int y = 0; y < i_height; ++y )
204         {
205             const uint8_t *src = (const uint8_t *)frame_bytes + i_stride * y;
206             uint8_t *dst = (uint8_t *)p_video_frame->p_buffer + i_width * i_bpp * y;
207             memcpy( dst, src, i_width * i_bpp );
208         }
209
210         BMDTimeValue stream_time, frame_duration;
211         videoFrame->GetStreamTime( &stream_time, &frame_duration, CLOCK_FREQ );
212         p_video_frame->i_flags = BLOCK_FLAG_TYPE_I | p_sys->i_dominance_flags;
213         if( p_sys->b_first_frame )
214         {
215             p_video_frame->i_flags |= BLOCK_FLAG_DISCONTINUITY;
216             p_sys->b_first_frame = false;
217         }
218         p_video_frame->i_pts = p_video_frame->i_dts = VLC_TS_0 + stream_time;
219     }
220
221     if( audioFrame )
222     {
223         const int i_bytes = audioFrame->GetSampleFrameCount() * sizeof(int16_t) * p_sys->i_channels;
224
225         p_audio_frame = block_New( p_demux_, i_bytes );
226         if( !p_audio_frame )
227         {
228             msg_Err( p_demux_, "Could not allocate memory for audio frame" );
229             if( p_video_frame )
230                 block_Release( p_video_frame );
231             return S_OK;
232         }
233
234         void *frame_bytes;
235         audioFrame->GetBytes( &frame_bytes );
236         memcpy( p_audio_frame->p_buffer, frame_bytes, i_bytes );
237
238         BMDTimeValue packet_time;
239         audioFrame->GetPacketTime( &packet_time, CLOCK_FREQ );
240         p_audio_frame->i_pts = p_audio_frame->i_dts = VLC_TS_0 + packet_time;
241     }
242
243     if( p_video_frame || p_audio_frame )
244     {
245         vlc_mutex_lock( &p_sys->frame_lock );
246         if( p_video_frame )
247         {
248             if( p_sys->p_video_frame )
249                 block_Release( p_sys->p_video_frame );
250             p_sys->p_video_frame = p_video_frame;
251         }
252         if( p_audio_frame )
253         {
254             if( p_sys->p_audio_frame )
255                 block_Release( p_sys->p_audio_frame );
256             p_sys->p_audio_frame = p_audio_frame;
257         }
258         vlc_cond_signal( &p_sys->has_frame );
259         vlc_mutex_unlock( &p_sys->frame_lock );
260     }
261
262     return S_OK;
263 }
264
265 static int Open( vlc_object_t *p_this )
266 {
267     demux_t     *p_demux = (demux_t*)p_this;
268     demux_sys_t *p_sys;
269     int         ret = VLC_SUCCESS;
270     char        *psz_aspect;
271     char        *psz_display_mode = NULL;
272     char        *psz_video_connection = NULL;
273     char        *psz_audio_connection = NULL;
274     bool        b_found_mode;
275     int         i_card_index;
276     int         i_width, i_height, i_fps_num, i_fps_den;
277     int         i_rate;
278
279     /* Only when selected */
280     if( *p_demux->psz_access == '\0' )
281         return VLC_EGENERIC;
282
283     /* Set up p_demux */
284     p_demux->pf_demux = Demux;
285     p_demux->pf_control = Control;
286     p_demux->info.i_update = 0;
287     p_demux->info.i_title = 0;
288     p_demux->info.i_seekpoint = 0;
289     p_demux->p_sys = p_sys = (demux_sys_t*)calloc( 1, sizeof( demux_sys_t ) );
290     if( !p_sys )
291         return VLC_ENOMEM;
292
293     vlc_mutex_init( &p_sys->frame_lock );
294     vlc_cond_init( &p_sys->has_frame );
295     p_sys->b_first_frame = true;
296
297     IDeckLinkIterator *decklink_iterator = CreateDeckLinkIteratorInstance();
298     if( !decklink_iterator )
299     {
300         msg_Err( p_demux, "DeckLink drivers not found." );
301         ret = VLC_EGENERIC;
302         goto finish;
303     }
304
305     HRESULT result;
306
307     i_card_index = var_InheritInteger( p_demux, "decklink-card-index" );
308     for( int i = 0; i <= i_card_index; ++i )
309     {
310         if( p_sys->p_card )
311             p_sys->p_card->Release();
312         result = decklink_iterator->Next( &p_sys->p_card );
313         if( result != S_OK )
314             break;
315     }
316
317     if( result != S_OK )
318     {
319         msg_Err( p_demux, "DeckLink PCI card %d not found", i_card_index );
320         ret = VLC_EGENERIC;
321         goto finish;
322     }
323
324     const char *psz_model_name;
325     result = p_sys->p_card->GetModelName( &psz_model_name );
326
327     if( result != S_OK )
328     {
329         msg_Err( p_demux, "Could not get model name" );
330         ret = VLC_EGENERIC;
331         goto finish;
332     }
333
334     msg_Dbg( p_demux, "Opened DeckLink PCI card %d (%s)", i_card_index, psz_model_name );
335
336     if( p_sys->p_card->QueryInterface( IID_IDeckLinkInput, (void**)&p_sys->p_input) != S_OK )
337     {
338         msg_Err( p_demux, "Card has no inputs" );
339         ret = VLC_EGENERIC;
340         goto finish;
341     }
342
343     /* Set up the video and audio sources. */
344     IDeckLinkConfiguration *p_config;
345     if( p_sys->p_card->QueryInterface( IID_IDeckLinkConfiguration, (void**)&p_config) != S_OK )
346     {
347         msg_Err( p_demux, "Failed to get configuration interface" );
348         ret = VLC_EGENERIC;
349         goto finish;
350     }
351
352     psz_video_connection = var_CreateGetNonEmptyString( p_demux, "decklink-video-connection" );
353     if( psz_video_connection )
354     {
355         BMDVideoConnection conn;
356         if ( !strcmp( psz_video_connection, "sdi" ) )
357             conn = bmdVideoConnectionSDI;
358         else if ( !strcmp( psz_video_connection, "hdmi" ) )
359             conn = bmdVideoConnectionHDMI;
360         else if ( !strcmp( psz_video_connection, "opticalsdi" ) )
361             conn = bmdVideoConnectionOpticalSDI;
362         else if ( !strcmp( psz_video_connection, "component" ) )
363             conn = bmdVideoConnectionComponent;
364         else if ( !strcmp( psz_video_connection, "composite" ) )
365             conn = bmdVideoConnectionComposite;
366         else if ( !strcmp( psz_video_connection, "svideo" ) )
367             conn = bmdVideoConnectionSVideo;
368         else
369         {
370             msg_Err( p_demux, "Invalid --decklink-video-connection specified; choose one of " \
371                               "sdi, hdmi, opticalsdi, component, composite, or svideo." );
372             ret = VLC_EGENERIC;
373             goto finish;
374         }
375
376         msg_Dbg( p_demux, "Setting video input format to 0x%x", conn);
377         result = p_config->SetVideoInputFormat( conn );
378         if( result != S_OK )
379         {
380             msg_Err( p_demux, "Failed to set video input connection" );
381             ret = VLC_EGENERIC;
382             goto finish;
383         }
384     }
385
386     psz_audio_connection = var_CreateGetNonEmptyString( p_demux, "decklink-audio-connection" );
387     if( psz_audio_connection )
388     {
389         BMDAudioConnection conn;
390         if ( !strcmp( psz_audio_connection, "embedded" ) )
391             conn = bmdAudioConnectionEmbedded;
392         else if ( !strcmp( psz_audio_connection, "aesebu" ) )
393             conn = bmdAudioConnectionAESEBU;
394         else if ( !strcmp( psz_audio_connection, "analog" ) )
395             conn = bmdAudioConnectionAnalog;
396         else
397         {
398             msg_Err( p_demux, "Invalid --decklink-audio-connection specified; choose one of " \
399                               "embedded, aesebu, or analog." );
400             ret = VLC_EGENERIC;
401             goto finish;
402         }
403
404         msg_Dbg( p_demux, "Setting audio input format to 0x%x", conn);
405         result = p_config->SetAudioInputFormat( conn );
406         if( result != S_OK )
407         {
408             msg_Err( p_demux, "Failed to set audio input connection" );
409             ret = VLC_EGENERIC;
410             goto finish;
411         }
412     }
413
414     /* Get the list of display modes. */
415     IDeckLinkDisplayModeIterator *p_display_iterator;
416     result = p_sys->p_input->GetDisplayModeIterator( &p_display_iterator );
417     if( result != S_OK )
418     {
419         msg_Err( p_demux, "Failed to enumerate display modes" );
420         ret = VLC_EGENERIC;
421         goto finish;
422     }
423
424     psz_display_mode = var_InheritString( p_demux, "decklink-mode" );
425     if( !psz_display_mode || strlen( psz_display_mode ) == 0 || strlen( psz_display_mode ) > 4 ) {
426         msg_Err( p_demux, "Missing or invalid --decklink-mode string" );
427         ret = VLC_EGENERIC;
428         goto finish;
429     }
430
431     /*
432      * Pad the --decklink-mode string to four characters, so the user can specify e.g. "pal"
433      * without having to add the trailing space.
434      */
435     char sz_display_mode_padded[5];
436     strcpy(sz_display_mode_padded, "    ");
437     for( int i = 0; i < strlen( psz_display_mode ); ++i )
438         sz_display_mode_padded[i] = psz_display_mode[i];
439
440     BMDDisplayMode wanted_mode_id;
441     memcpy( &wanted_mode_id, &sz_display_mode_padded, sizeof(wanted_mode_id) );
442
443     b_found_mode = false;
444
445     for (;;)
446     {
447         IDeckLinkDisplayMode *p_display_mode;
448         result = p_display_iterator->Next( &p_display_mode );
449         if( result != S_OK || !p_display_mode )
450             break;
451
452         char sz_mode_id_text[5] = {0};
453         BMDDisplayMode mode_id = ntohl( p_display_mode->GetDisplayMode() );
454         memcpy( sz_mode_id_text, &mode_id, sizeof(mode_id) );
455
456         const char *psz_mode_name;
457         result = p_display_mode->GetName( &psz_mode_name );
458         if( result != S_OK )
459         {
460             msg_Err( p_demux, "Failed to get display mode name" );
461             p_display_mode->Release();
462             ret = VLC_EGENERIC;
463             goto finish;
464         }
465
466         BMDTimeValue frame_duration, time_scale;
467         result = p_display_mode->GetFrameRate( &frame_duration, &time_scale );
468         if( result != S_OK )
469         {
470             msg_Err( p_demux, "Failed to get frame rate" );
471             p_display_mode->Release();
472             ret = VLC_EGENERIC;
473             goto finish;
474         }
475
476         const char *psz_field_dominance;
477         uint32_t i_dominance_flags = 0;
478         switch( p_display_mode->GetFieldDominance() )
479         {
480         case bmdProgressiveFrame:
481             psz_field_dominance = "";
482             break;
483         case bmdProgressiveSegmentedFrame:
484             psz_field_dominance = ", segmented";
485             break;
486         case bmdLowerFieldFirst:
487             psz_field_dominance = ", interlaced [BFF]";
488             i_dominance_flags = BLOCK_FLAG_BOTTOM_FIELD_FIRST;
489             break;
490         case bmdUpperFieldFirst:
491             psz_field_dominance = ", interlaced [TFF]";
492             i_dominance_flags = BLOCK_FLAG_TOP_FIELD_FIRST;
493             break;
494         case bmdUnknownFieldDominance:
495         default:
496             psz_field_dominance = ", unknown field dominance";
497             break;
498         }
499
500         msg_Dbg( p_demux, "Found mode '%s': %s (%dx%d, %.3f fps%s)",
501                  sz_mode_id_text, psz_mode_name,
502                  p_display_mode->GetWidth(), p_display_mode->GetHeight(),
503                  double(time_scale) / frame_duration, psz_field_dominance );
504
505         if( wanted_mode_id == mode_id )
506         {
507             b_found_mode = true;
508             i_width = p_display_mode->GetWidth();
509             i_height = p_display_mode->GetHeight();
510             i_fps_num = time_scale;
511             i_fps_den = frame_duration;
512             p_sys->i_dominance_flags = i_dominance_flags;
513         }
514
515         p_display_mode->Release();
516     }
517
518     if( !b_found_mode )
519     {
520         msg_Err( p_demux, "Unknown video mode specified. " \
521                           "Run VLC with -v --verbose-objects=-all,+decklink " \
522                           "to get a list of supported modes." );
523         ret = VLC_EGENERIC;
524         goto finish;
525     }
526
527     result = p_sys->p_input->EnableVideoInput( htonl( wanted_mode_id ), bmdFormat8BitYUV, 0 );
528     if( result != S_OK )
529     {
530         msg_Err( p_demux, "Failed to enable video input" );
531         ret = VLC_EGENERIC;
532         goto finish;
533     }
534
535     /* Set up audio. */
536     p_sys->i_channels = var_InheritInteger( p_demux, "decklink-audio-channels" );
537     i_rate = var_InheritInteger( p_demux, "decklink-audio-rate" );
538     if( i_rate > 0 && p_sys->i_channels > 0 )
539     {
540         result = p_sys->p_input->EnableAudioInput( i_rate, bmdAudioSampleType16bitInteger, p_sys->i_channels );
541         if( result != S_OK )
542         {
543             msg_Err( p_demux, "Failed to enable audio input" );
544             ret = VLC_EGENERIC;
545             goto finish;
546         }
547     }
548
549     p_sys->p_delegate = new DeckLinkCaptureDelegate( p_demux );
550     p_sys->p_input->SetCallback( p_sys->p_delegate );
551
552     result = p_sys->p_input->StartStreams();
553     if( result != S_OK )
554     {
555         msg_Err( p_demux, "Could not start streaming from SDI card. This could be caused "
556                           "by invalid video mode or flags, access denied, or card already in use." );
557         ret = VLC_EGENERIC;
558         goto finish;
559     }
560
561     /* Declare elementary streams */
562     es_format_t video_fmt;
563     es_format_Init( &video_fmt, VIDEO_ES, VLC_CODEC_UYVY );
564     video_fmt.video.i_width = i_width;
565     video_fmt.video.i_height = i_height;
566     video_fmt.video.i_sar_num = 1;
567     video_fmt.video.i_sar_den = 1;
568     video_fmt.video.i_frame_rate = i_fps_num;
569     video_fmt.video.i_frame_rate_base = i_fps_den;
570     video_fmt.i_bitrate = video_fmt.video.i_width * video_fmt.video.i_height * video_fmt.video.i_frame_rate * 2 * 8;
571
572     psz_aspect = var_CreateGetNonEmptyString( p_demux, "decklink-aspect-ratio" );
573     if( psz_aspect )
574     {
575         char *psz_denominator = strchr( psz_aspect, ':' );
576         if( psz_denominator )
577         {
578             *psz_denominator++ = '\0';
579             video_fmt.video.i_sar_num = atoi( psz_aspect )      * video_fmt.video.i_height;
580             video_fmt.video.i_sar_den = atoi( psz_denominator ) * video_fmt.video.i_width;
581         }
582         free( psz_aspect );
583     }
584
585     msg_Dbg( p_demux, "added new video es %4.4s %dx%d",
586              (char*)&video_fmt.i_codec, video_fmt.video.i_width, video_fmt.video.i_height );
587     p_sys->p_video_es = es_out_Add( p_demux->out, &video_fmt );
588
589     es_format_t audio_fmt;
590     es_format_Init( &audio_fmt, AUDIO_ES, VLC_CODEC_S16N );
591     audio_fmt.audio.i_channels = p_sys->i_channels;
592     audio_fmt.audio.i_rate = i_rate;
593     audio_fmt.audio.i_bitspersample = 16;
594     audio_fmt.audio.i_blockalign = audio_fmt.audio.i_channels * audio_fmt.audio.i_bitspersample / 8;
595     audio_fmt.i_bitrate = audio_fmt.audio.i_channels * audio_fmt.audio.i_rate * audio_fmt.audio.i_bitspersample;
596
597     msg_Dbg( p_demux, "added new audio es %4.4s %dHz %dbpp %dch",
598              (char*)&audio_fmt.i_codec, audio_fmt.audio.i_rate, audio_fmt.audio.i_bitspersample, audio_fmt.audio.i_channels);
599     p_sys->p_audio_es = es_out_Add( p_demux->out, &audio_fmt );
600
601     /* Update default_pts to a suitable value for access */
602     var_Create( p_demux, "decklink-caching", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
603
604 finish:
605     if( decklink_iterator )
606         decklink_iterator->Release();
607
608     if( p_config )
609         p_config->Release();
610
611     free( psz_video_connection );
612     free( psz_audio_connection );
613     free( psz_display_mode );
614
615     if( p_display_iterator )
616         p_display_iterator->Release();
617
618     if( ret != VLC_SUCCESS )
619         Close( p_this );
620
621     return ret;
622 }
623
624 static void Close( vlc_object_t *p_this )
625 {
626     demux_t     *p_demux = (demux_t *)p_this;
627     demux_sys_t *p_sys   = p_demux->p_sys;
628
629     if( p_sys->p_input )
630     {
631         p_sys->p_input->StopStreams();
632         p_sys->p_input->Release();
633     }
634
635     if( p_sys->p_card )
636         p_sys->p_card->Release();
637
638     if( p_sys->p_delegate )
639         p_sys->p_delegate->Release();
640
641     if( p_sys->p_video_frame )
642         block_Release( p_sys->p_video_frame );
643
644     if( p_sys->p_audio_frame )
645         block_Release( p_sys->p_audio_frame );
646
647     free( p_sys );
648 }
649
650 static int Control( demux_t *p_demux, int i_query, va_list args )
651 {
652     demux_sys_t *p_sys = p_demux->p_sys;
653     bool *pb;
654     int64_t    *pi64;
655
656     switch( i_query )
657     {
658         /* Special for access_demux */
659         case DEMUX_CAN_PAUSE:
660         case DEMUX_CAN_SEEK:
661         case DEMUX_CAN_CONTROL_PACE:
662             pb = (bool*)va_arg( args, bool * );
663             *pb = false;
664             return VLC_SUCCESS;
665
666         case DEMUX_GET_PTS_DELAY:
667             pi64 = (int64_t*)va_arg( args, int64_t * );
668             *pi64 = var_GetInteger( p_demux, "decklink-caching" ) * 1000;
669             return VLC_SUCCESS;
670
671         case DEMUX_GET_TIME:
672             pi64 = (int64_t*)va_arg( args, int64_t * );
673             *pi64 = p_sys->i_last_pts;
674             return VLC_SUCCESS;
675
676         /* TODO implement others */
677         default:
678             return VLC_EGENERIC;
679     }
680
681     return VLC_EGENERIC;
682 }
683
684 static int Demux( demux_t *p_demux )
685 {
686     demux_sys_t *p_sys = p_demux->p_sys;
687     block_t *p_video_block = NULL;
688     block_t *p_audio_block = NULL;
689
690     vlc_mutex_lock( &p_sys->frame_lock );
691
692     while( !p_sys->p_video_frame && !p_sys->p_audio_frame )
693         vlc_cond_wait( &p_sys->has_frame, &p_sys->frame_lock );
694
695     p_video_block = p_sys->p_video_frame;
696     p_sys->p_video_frame = NULL;
697
698     p_audio_block = p_sys->p_audio_frame;
699     p_sys->p_audio_frame = NULL;
700
701     vlc_mutex_unlock( &p_sys->frame_lock );
702
703     if( p_video_block )
704     {
705         if( p_video_block->i_pts > p_sys->i_last_pts )
706             p_sys->i_last_pts = p_video_block->i_pts;
707         es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_video_block->i_pts );
708         es_out_Send( p_demux->out, p_sys->p_video_es, p_video_block );
709     }
710
711     if( p_audio_block )
712     {
713         if( p_audio_block->i_pts > p_sys->i_last_pts )
714             p_sys->i_last_pts = p_audio_block->i_pts;
715         es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_audio_block->i_pts );
716         es_out_Send( p_demux->out, p_sys->p_audio_es, p_audio_block );
717     }
718
719     return 1;
720 }
721