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