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