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