]> git.sesse.net Git - vlc/blob - modules/access/decklink.cpp
79f1d958b99a1c833e0127484505e1516228062d
[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     int i_width, i_height, i_fps_num, i_fps_den;
131     uint32_t i_dominance_flags;
132
133     int i_rate, i_channels;
134
135     vlc_mutex_t frame_lock;
136     block_t *p_video_frame;  /* protected by <frame_lock> */
137     block_t *p_audio_frame;  /* protected by <frame_lock> */
138     vlc_cond_t has_frame;  /* related to <frame_lock> */
139 };
140
141 class DeckLinkCaptureDelegate : public IDeckLinkInputCallback
142 {
143 public:
144     DeckLinkCaptureDelegate( demux_t *p_demux ) : p_demux_(p_demux)
145     {
146         vlc_atomic_set( &m_ref_, 1 );
147     }
148
149     virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
150
151     virtual ULONG STDMETHODCALLTYPE AddRef(void)
152     {
153         return vlc_atomic_inc( &m_ref_ );
154     }
155
156     virtual ULONG STDMETHODCALLTYPE Release(void)
157     {
158         uintptr_t new_ref = vlc_atomic_dec( &m_ref_ );
159         if ( new_ref == 0 )
160             delete this;
161         return new_ref;
162     }
163
164     virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents, IDeckLinkDisplayMode*, BMDDetectedVideoInputFormatFlags);
165     virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame*, IDeckLinkAudioInputPacket*);
166
167 private:
168     vlc_atomic_t m_ref_;
169     demux_t *p_demux_;
170 };
171
172 HRESULT DeckLinkCaptureDelegate::VideoInputFormatChanged(BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode *mode, BMDDetectedVideoInputFormatFlags)
173 {
174     msg_Dbg( p_demux_, "Video input format changed" );
175     return S_OK;
176 }
177
178 HRESULT DeckLinkCaptureDelegate::VideoInputFrameArrived(IDeckLinkVideoInputFrame* videoFrame, IDeckLinkAudioInputPacket* audioFrame)
179 {
180     demux_sys_t *p_sys = p_demux_->p_sys;
181     block_t *p_video_frame = NULL;
182     block_t *p_audio_frame = NULL;
183
184     if( videoFrame )
185     {
186         if( videoFrame->GetFlags() & bmdFrameHasNoInputSource )
187         {
188             msg_Warn( p_demux_, "No input signal detected" );
189             return S_OK;
190         }
191
192         const int i_width = videoFrame->GetWidth();
193         const int i_height = videoFrame->GetHeight();
194         const int i_stride = videoFrame->GetRowBytes();
195         const int i_bpp = 2;
196
197         p_video_frame = block_New( p_demux_, i_width * i_height * i_bpp );
198         if( !p_video_frame )
199         {
200             msg_Err( p_demux_, "Could not allocate memory for video frame" );
201             return S_OK;
202         }
203
204         void *frame_bytes;
205         videoFrame->GetBytes( &frame_bytes );
206         for( int y = 0; y < i_height; ++y )
207         {
208             const uint8_t *src = (const uint8_t *)frame_bytes + i_stride * y;
209             uint8_t *dst = (uint8_t *)p_video_frame->p_buffer + i_width * i_bpp * y;
210             memcpy( dst, src, i_width * i_bpp );
211         }
212
213         BMDTimeValue stream_time, frame_duration;
214         videoFrame->GetStreamTime( &stream_time, &frame_duration, CLOCK_FREQ );
215         p_video_frame->i_flags = BLOCK_FLAG_TYPE_I | p_sys->i_dominance_flags;
216         if( p_sys->b_first_frame )
217         {
218             p_video_frame->i_flags |= BLOCK_FLAG_DISCONTINUITY;
219             p_sys->b_first_frame = false;
220         }
221         p_video_frame->i_pts = p_video_frame->i_dts = VLC_TS_0 + stream_time;
222     }
223
224     if( audioFrame )
225     {
226         const int i_bytes = audioFrame->GetSampleFrameCount() * sizeof(int16_t) * p_sys->i_channels;
227
228         p_audio_frame = block_New( p_demux_, i_bytes );
229         if( !p_audio_frame )
230         {
231             msg_Err( p_demux_, "Could not allocate memory for audio frame" );
232             if( p_video_frame )
233                 block_Release( p_video_frame );
234             return S_OK;
235         }
236
237         void *frame_bytes;
238         audioFrame->GetBytes( &frame_bytes );
239         memcpy( p_audio_frame->p_buffer, frame_bytes, i_bytes );
240
241         BMDTimeValue packet_time;
242         audioFrame->GetPacketTime( &packet_time, CLOCK_FREQ );
243         p_audio_frame->i_pts = p_audio_frame->i_dts = VLC_TS_0 + packet_time;
244     }
245
246     if( p_video_frame || p_audio_frame )
247     {
248         vlc_mutex_lock( &p_sys->frame_lock );
249         if( p_video_frame )
250         {
251             if( p_sys->p_video_frame )
252                 block_Release( p_sys->p_video_frame );
253             p_sys->p_video_frame = p_video_frame;
254         }
255         if( p_audio_frame )
256         {
257             if( p_sys->p_audio_frame )
258                 block_Release( p_sys->p_audio_frame );
259             p_sys->p_audio_frame = p_audio_frame;
260         }
261         vlc_cond_signal( &p_sys->has_frame );
262         vlc_mutex_unlock( &p_sys->frame_lock );
263     }
264
265     return S_OK;
266 }
267
268 static int Open( vlc_object_t *p_this )
269 {
270     demux_t     *p_demux = (demux_t*)p_this;
271     demux_sys_t *p_sys;
272     int         ret = VLC_SUCCESS;
273     char        *psz_aspect;
274     char        *psz_display_mode = NULL;
275     char        *psz_video_connection = NULL;
276     char        *psz_audio_connection = NULL;
277     bool        b_found_mode;
278     int         i_card_index;
279
280     /* Only when selected */
281     if( *p_demux->psz_access == '\0' )
282         return VLC_EGENERIC;
283
284     /* Set up p_demux */
285     p_demux->pf_demux = Demux;
286     p_demux->pf_control = Control;
287     p_demux->info.i_update = 0;
288     p_demux->info.i_title = 0;
289     p_demux->info.i_seekpoint = 0;
290     p_demux->p_sys = p_sys = (demux_sys_t*)calloc( 1, sizeof( demux_sys_t ) );
291     if( !p_sys )
292         return VLC_ENOMEM;
293
294     vlc_mutex_init( &p_sys->frame_lock );
295     vlc_cond_init( &p_sys->has_frame );
296     p_sys->b_first_frame = true;
297
298     IDeckLinkIterator *decklink_iterator = CreateDeckLinkIteratorInstance();
299     if( !decklink_iterator )
300     {
301         msg_Err( p_demux, "DeckLink drivers not found." );
302         ret = VLC_EGENERIC;
303         goto finish;
304     }
305
306     HRESULT result;
307
308     i_card_index = var_InheritInteger( p_demux, "decklink-card-index" );
309     for( int i = 0; i <= i_card_index; ++i )
310     {
311         if( p_sys->p_card )
312             p_sys->p_card->Release();
313         result = decklink_iterator->Next( &p_sys->p_card );
314         if( result != S_OK )
315             break;
316     }
317
318     if( result != S_OK )
319     {
320         msg_Err( p_demux, "DeckLink PCI card %d not found", i_card_index );
321         ret = VLC_EGENERIC;
322         goto finish;
323     }
324
325     const char *psz_model_name;
326     result = p_sys->p_card->GetModelName( &psz_model_name );
327
328     if( result != S_OK )
329     {
330         msg_Err( p_demux, "Could not get model name" );
331         ret = VLC_EGENERIC;
332         goto finish;
333     }
334
335     msg_Dbg( p_demux, "Opened DeckLink PCI card %d (%s)", i_card_index, psz_model_name );
336
337     if( p_sys->p_card->QueryInterface( IID_IDeckLinkInput, (void**)&p_sys->p_input) != S_OK )
338     {
339         msg_Err( p_demux, "Card has no inputs" );
340         ret = VLC_EGENERIC;
341         goto finish;
342     }
343
344     /* Set up the video and audio sources. */
345     IDeckLinkConfiguration *p_config;
346     if( p_sys->p_card->QueryInterface( IID_IDeckLinkConfiguration, (void**)&p_config) != S_OK )
347     {
348         msg_Err( p_demux, "Failed to get configuration interface" );
349         ret = VLC_EGENERIC;
350         goto finish;
351     }
352
353     psz_video_connection = var_CreateGetNonEmptyString( p_demux, "decklink-video-connection" );
354     if( psz_video_connection )
355     {
356         BMDVideoConnection conn;
357         if ( !strcmp( psz_video_connection, "sdi" ) )
358             conn = bmdVideoConnectionSDI;
359         else if ( !strcmp( psz_video_connection, "hdmi" ) )
360             conn = bmdVideoConnectionHDMI;
361         else if ( !strcmp( psz_video_connection, "opticalsdi" ) )
362             conn = bmdVideoConnectionOpticalSDI;
363         else if ( !strcmp( psz_video_connection, "component" ) )
364             conn = bmdVideoConnectionComponent;
365         else if ( !strcmp( psz_video_connection, "composite" ) )
366             conn = bmdVideoConnectionComposite;
367         else if ( !strcmp( psz_video_connection, "svideo" ) )
368             conn = bmdVideoConnectionSVideo;
369         else
370         {
371             msg_Err( p_demux, "Invalid --decklink-video-connection specified; choose one of " \
372                               "sdi, hdmi, opticalsdi, component, composite, or svideo." );
373             ret = VLC_EGENERIC;
374             goto finish;
375         }
376
377         msg_Dbg( p_demux, "Setting video input format to 0x%x", conn);
378         result = p_config->SetVideoInputFormat( conn );
379         if( result != S_OK )
380         {
381             msg_Err( p_demux, "Failed to set video input connection" );
382             ret = VLC_EGENERIC;
383             goto finish;
384         }
385     }
386
387     psz_audio_connection = var_CreateGetNonEmptyString( p_demux, "decklink-audio-connection" );
388     if( psz_audio_connection )
389     {
390         BMDAudioConnection conn;
391         if ( !strcmp( psz_audio_connection, "embedded" ) )
392             conn = bmdAudioConnectionEmbedded;
393         else if ( !strcmp( psz_audio_connection, "aesebu" ) )
394             conn = bmdAudioConnectionAESEBU;
395         else if ( !strcmp( psz_audio_connection, "analog" ) )
396             conn = bmdAudioConnectionAnalog;
397         else
398         {
399             msg_Err( p_demux, "Invalid --decklink-audio-connection specified; choose one of " \
400                               "embedded, aesebu, or analog." );
401             ret = VLC_EGENERIC;
402             goto finish;
403         }
404
405         msg_Dbg( p_demux, "Setting audio input format to 0x%x", conn);
406         result = p_config->SetAudioInputFormat( conn );
407         if( result != S_OK )
408         {
409             msg_Err( p_demux, "Failed to set audio input connection" );
410             ret = VLC_EGENERIC;
411             goto finish;
412         }
413     }
414
415     /* Get the list of display modes. */
416     IDeckLinkDisplayModeIterator *p_display_iterator;
417     result = p_sys->p_input->GetDisplayModeIterator( &p_display_iterator );
418     if( result != S_OK )
419     {
420         msg_Err( p_demux, "Failed to enumerate display modes" );
421         ret = VLC_EGENERIC;
422         goto finish;
423     }
424
425     psz_display_mode = var_InheritString( p_demux, "decklink-mode" );
426     if( !psz_display_mode || strlen( psz_display_mode ) == 0 || strlen( psz_display_mode ) > 4 ) {
427         msg_Err( p_demux, "Missing or invalid --decklink-mode string" );
428         ret = VLC_EGENERIC;
429         goto finish;
430     }
431
432     /*
433      * Pad the --decklink-mode string to four characters, so the user can specify e.g. "pal"
434      * without having to add the trailing space.
435      */
436     char sz_display_mode_padded[5];
437     strcpy(sz_display_mode_padded, "    ");
438     for( int i = 0; i < strlen( psz_display_mode ); ++i )
439         sz_display_mode_padded[i] = psz_display_mode[i];
440
441     BMDDisplayMode wanted_mode_id;
442     memcpy( &wanted_mode_id, &sz_display_mode_padded, sizeof(wanted_mode_id) );
443
444     b_found_mode = false;
445
446     for (;;)
447     {
448         IDeckLinkDisplayMode *p_display_mode;
449         result = p_display_iterator->Next( &p_display_mode );
450         if( result != S_OK || !p_display_mode )
451             break;
452
453         char sz_mode_id_text[5] = {0};
454         BMDDisplayMode mode_id = ntohl( p_display_mode->GetDisplayMode() );
455         memcpy( sz_mode_id_text, &mode_id, sizeof(mode_id) );
456
457         const char *psz_mode_name;
458         result = p_display_mode->GetName( &psz_mode_name );
459         if( result != S_OK )
460         {
461             msg_Err( p_demux, "Failed to get display mode name" );
462             p_display_mode->Release();
463             ret = VLC_EGENERIC;
464             goto finish;
465         }
466
467         BMDTimeValue frame_duration, time_scale;
468         result = p_display_mode->GetFrameRate( &frame_duration, &time_scale );
469         if( result != S_OK )
470         {
471             msg_Err( p_demux, "Failed to get frame rate" );
472             p_display_mode->Release();
473             ret = VLC_EGENERIC;
474             goto finish;
475         }
476
477         const char *psz_field_dominance;
478         uint32_t i_dominance_flags = 0;
479         switch( p_display_mode->GetFieldDominance() )
480         {
481         case bmdProgressiveFrame:
482             psz_field_dominance = "";
483             break;
484         case bmdProgressiveSegmentedFrame:
485             psz_field_dominance = ", segmented";
486             break;
487         case bmdLowerFieldFirst:
488             psz_field_dominance = ", interlaced [BFF]";
489             i_dominance_flags = BLOCK_FLAG_BOTTOM_FIELD_FIRST;
490             break;
491         case bmdUpperFieldFirst:
492             psz_field_dominance = ", interlaced [TFF]";
493             i_dominance_flags = BLOCK_FLAG_TOP_FIELD_FIRST;
494             break;
495         case bmdUnknownFieldDominance:
496         default:
497             psz_field_dominance = ", unknown field dominance";
498             break;
499         }
500
501         msg_Dbg( p_demux, "Found mode '%s': %s (%dx%d, %.3f fps%s)",
502                  sz_mode_id_text, psz_mode_name,
503                  p_display_mode->GetWidth(), p_display_mode->GetHeight(),
504                  double(time_scale) / frame_duration, psz_field_dominance );
505
506         if( wanted_mode_id == mode_id )
507         {
508             b_found_mode = true;
509             p_sys->i_width = p_display_mode->GetWidth();
510             p_sys->i_height = p_display_mode->GetHeight();
511             p_sys->i_fps_num = time_scale;
512             p_sys->i_fps_den = frame_duration;
513             p_sys->i_dominance_flags = i_dominance_flags;
514         }
515
516         p_display_mode->Release();
517     }
518
519     if( !b_found_mode )
520     {
521         msg_Err( p_demux, "Unknown video mode specified. " \
522                           "Run VLC with -v --verbose-objects=-all,+decklink " \
523                           "to get a list of supported modes." );
524         ret = VLC_EGENERIC;
525         goto finish;
526     }
527
528     result = p_sys->p_input->EnableVideoInput( htonl( wanted_mode_id ), bmdFormat8BitYUV, 0 );
529     if( result != S_OK )
530     {
531         msg_Err( p_demux, "Failed to enable video input" );
532         ret = VLC_EGENERIC;
533         goto finish;
534     }
535
536     /* Set up audio. */
537     p_sys->i_rate = var_InheritInteger( p_demux, "decklink-audio-rate" );
538     p_sys->i_channels = var_InheritInteger( p_demux, "decklink-audio-channels" );
539     if( p_sys->i_rate > 0 && p_sys->i_channels > 0 )
540     {
541         result = p_sys->p_input->EnableAudioInput( p_sys->i_rate, bmdAudioSampleType16bitInteger, p_sys->i_channels );
542         if( result != S_OK )
543         {
544             msg_Err( p_demux, "Failed to enable audio input" );
545             ret = VLC_EGENERIC;
546             goto finish;
547         }
548     }
549
550     p_sys->p_delegate = new DeckLinkCaptureDelegate( p_demux );
551     p_sys->p_input->SetCallback( p_sys->p_delegate );
552
553     result = p_sys->p_input->StartStreams();
554     if( result != S_OK )
555     {
556         msg_Err( p_demux, "Could not start streaming from SDI card. This could be caused "
557                           "by invalid video mode or flags, access denied, or card already in use." );
558         ret = VLC_EGENERIC;
559         goto finish;
560     }
561
562     /* Declare elementary streams */
563     es_format_t video_fmt;
564     es_format_Init( &video_fmt, VIDEO_ES, VLC_CODEC_UYVY );
565     video_fmt.video.i_width = p_sys->i_width;
566     video_fmt.video.i_height = p_sys->i_height;
567     video_fmt.video.i_sar_num = 1;
568     video_fmt.video.i_sar_den = 1;
569     video_fmt.video.i_frame_rate = p_sys->i_fps_num;
570     video_fmt.video.i_frame_rate_base = p_sys->i_fps_den;
571     video_fmt.i_bitrate = video_fmt.video.i_width * video_fmt.video.i_height * video_fmt.video.i_frame_rate * 2 * 8;
572
573     psz_aspect = var_CreateGetNonEmptyString( p_demux, "decklink-aspect-ratio" );
574     if( psz_aspect )
575     {
576         char *psz_denominator = strchr( psz_aspect, ':' );
577         if( psz_denominator )
578         {
579             *psz_denominator++ = '\0';
580             video_fmt.video.i_sar_num = atoi( psz_aspect )      * video_fmt.video.i_height;
581             video_fmt.video.i_sar_den = atoi( psz_denominator ) * video_fmt.video.i_width;
582         }
583         free( psz_aspect );
584     }
585
586     msg_Dbg( p_demux, "added new video es %4.4s %dx%d",
587              (char*)&video_fmt.i_codec, video_fmt.video.i_width, video_fmt.video.i_height );
588     p_sys->p_video_es = es_out_Add( p_demux->out, &video_fmt );
589
590     es_format_t audio_fmt;
591     es_format_Init( &audio_fmt, AUDIO_ES, VLC_CODEC_S16N );
592     audio_fmt.audio.i_channels = p_sys->i_channels;
593     audio_fmt.audio.i_rate = p_sys->i_rate;
594     audio_fmt.audio.i_bitspersample = 16;
595     audio_fmt.audio.i_blockalign = audio_fmt.audio.i_channels * audio_fmt.audio.i_bitspersample / 8;
596     audio_fmt.i_bitrate = audio_fmt.audio.i_channels * audio_fmt.audio.i_rate * audio_fmt.audio.i_bitspersample;
597
598     msg_Dbg( p_demux, "added new audio es %4.4s %dHz %dbpp %dch",
599              (char*)&audio_fmt.i_codec, audio_fmt.audio.i_rate, audio_fmt.audio.i_bitspersample, audio_fmt.audio.i_channels);
600     p_sys->p_audio_es = es_out_Add( p_demux->out, &audio_fmt );
601
602     /* Update default_pts to a suitable value for access */
603     var_Create( p_demux, "decklink-caching", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
604
605 finish:
606     if( decklink_iterator )
607         decklink_iterator->Release();
608
609     if( p_config )
610         p_config->Release();
611
612     free( psz_video_connection );
613     free( psz_audio_connection );
614     free( psz_display_mode );
615
616     if( p_display_iterator )
617         p_display_iterator->Release();
618
619     if( ret != VLC_SUCCESS )
620         Close( p_this );
621
622     return ret;
623 }
624
625 static void Close( vlc_object_t *p_this )
626 {
627     demux_t     *p_demux = (demux_t *)p_this;
628     demux_sys_t *p_sys   = p_demux->p_sys;
629
630     if( p_sys->p_input )
631     {
632         p_sys->p_input->StopStreams();
633         p_sys->p_input->Release();
634     }
635
636     if( p_sys->p_card )
637         p_sys->p_card->Release();
638
639     if( p_sys->p_delegate )
640         p_sys->p_delegate->Release();
641
642     if( p_sys->p_video_frame )
643         block_Release( p_sys->p_video_frame );
644
645     if( p_sys->p_audio_frame )
646         block_Release( p_sys->p_audio_frame );
647
648     free( p_sys );
649 }
650
651 static int Control( demux_t *p_demux, int i_query, va_list args )
652 {
653     demux_sys_t *p_sys = p_demux->p_sys;
654     bool *pb;
655     int64_t    *pi64;
656
657     switch( i_query )
658     {
659         /* Special for access_demux */
660         case DEMUX_CAN_PAUSE:
661         case DEMUX_CAN_SEEK:
662         case DEMUX_CAN_CONTROL_PACE:
663             pb = (bool*)va_arg( args, bool * );
664             *pb = false;
665             return VLC_SUCCESS;
666
667         case DEMUX_GET_PTS_DELAY:
668             pi64 = (int64_t*)va_arg( args, int64_t * );
669             *pi64 = var_GetInteger( p_demux, "decklink-caching" ) * 1000;
670             return VLC_SUCCESS;
671
672         case DEMUX_GET_TIME:
673             pi64 = (int64_t*)va_arg( args, int64_t * );
674             *pi64 = p_sys->i_last_pts;
675             return VLC_SUCCESS;
676
677         /* TODO implement others */
678         default:
679             return VLC_EGENERIC;
680     }
681
682     return VLC_EGENERIC;
683 }
684
685 static int Demux( demux_t *p_demux )
686 {
687     demux_sys_t *p_sys = p_demux->p_sys;
688     block_t *p_video_block = NULL;
689     block_t *p_audio_block = NULL;
690
691     vlc_mutex_lock( &p_sys->frame_lock );
692
693     while( !p_sys->p_video_frame && !p_sys->p_audio_frame )
694         vlc_cond_wait( &p_sys->has_frame, &p_sys->frame_lock );
695
696     p_video_block = p_sys->p_video_frame;
697     p_sys->p_video_frame = NULL;
698
699     p_audio_block = p_sys->p_audio_frame;
700     p_sys->p_audio_frame = NULL;
701
702     vlc_mutex_unlock( &p_sys->frame_lock );
703
704     if( p_video_block )
705     {
706         if( p_video_block->i_pts > p_sys->i_last_pts )
707             p_sys->i_last_pts = p_video_block->i_pts;
708         es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_video_block->i_pts );
709         es_out_Send( p_demux->out, p_sys->p_video_es, p_video_block );
710     }
711
712     if( p_audio_block )
713     {
714         if( p_audio_block->i_pts > p_sys->i_last_pts )
715             p_sys->i_last_pts = p_audio_block->i_pts;
716         es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_audio_block->i_pts );
717         es_out_Send( p_demux->out, p_sys->p_audio_es, p_audio_block );
718     }
719
720     return 1;
721 }
722