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