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é
7 * Authors: Steinar H. Gunderson <steinar+vlc@gunderson.no>
8 Rafaël Carré <funman@videolanorg>
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.
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.
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 *****************************************************************************/
25 #define __STDC_CONSTANT_MACROS 1
31 #include <vlc_common.h>
32 #include <vlc_plugin.h>
33 #include <vlc_demux.h>
34 #include <vlc_atomic.h>
36 #include <arpa/inet.h>
38 #include <DeckLinkAPI.h>
39 #include <DeckLinkAPIDispatch.cpp>
43 static int Open (vlc_object_t *);
44 static void Close(vlc_object_t *);
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.")
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\".")
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.")
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.")
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.")
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.")
80 static const char *const ppsz_videoconns[] = {
81 "sdi", "hdmi", "opticalsdi", "component", "composite", "svideo"
83 static const char *const ppsz_videoconns_text[] = {
84 N_("SDI"), N_("HDMI"), N_("Optical SDI"), N_("Component"), N_("Composite"), N_("S-video")
87 static const char *const ppsz_audioconns[] = {
88 "embedded", "aesebu", "analog"
90 static const char *const ppsz_audioconns_text[] = {
91 N_("Embedded"), N_("AES/EBU"), N_("Analog")
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.")
99 set_shortname(N_("DeckLink"))
100 set_description(N_("Blackmagic DeckLink SDI input"))
101 set_category(CAT_INPUT)
102 set_subcategory(SUBCAT_INPUT_ACCESS)
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)
122 add_shortcut("decklink")
123 set_capability("access_demux", 10)
124 set_callbacks(Open, Close)
127 static int Control(demux_t *, int, va_list);
129 class DeckLinkCaptureDelegate;
134 IDeckLinkInput *input;
135 DeckLinkCaptureDelegate *delegate;
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;
144 es_out_id_t *video_es;
145 es_out_id_t *audio_es;
148 vlc_mutex_t pts_lock;
149 int last_pts; /* protected by <pts_lock> */
151 uint32_t dominance_flags;
157 static const char *GetFieldDominance(BMDFieldDominance dom, uint32_t *flags)
161 case bmdProgressiveFrame:
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:
173 return ", unknown field dominance";
177 static es_format_t GetModeSettings(demux_t *demux, IDeckLinkDisplayMode *m)
179 demux_sys_t *sys = demux->p_sys;
181 (void)GetFieldDominance(m->GetFieldDominance(), &flags);
183 BMDTimeValue frame_duration, time_scale;
184 if (m->GetFrameRate(&frame_duration, &time_scale) != S_OK) {
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);
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;
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;
208 sys->dominance_flags = flags;
213 class DeckLinkCaptureDelegate : public IDeckLinkInputCallback
216 DeckLinkCaptureDelegate(demux_t *demux) : demux_(demux)
218 atomic_store(&m_ref_, 1);
221 virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID, LPVOID *) { return E_NOINTERFACE; }
223 virtual ULONG STDMETHODCALLTYPE AddRef(void)
225 return atomic_fetch_add(&m_ref_, 1);
228 virtual ULONG STDMETHODCALLTYPE Release(void)
230 uintptr_t new_ref = atomic_fetch_sub(&m_ref_, 1);
236 virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode *mode, BMDDetectedVideoInputFormatFlags)
238 demux_sys_t *sys = demux_->p_sys;
240 if( !(events & bmdVideoInputDisplayModeChanged ))
243 const char *mode_name;
244 if (mode->GetName(&mode_name) != S_OK)
245 mode_name = "unknown";
247 msg_Dbg(demux_, "Video input format changed to %s", mode_name);
248 if (!sys->autodetect) {
249 msg_Err(demux_, "Video format detection disabled");
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);
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();
266 virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame*, IDeckLinkAudioInputPacket*);
273 HRESULT DeckLinkCaptureDelegate::VideoInputFrameArrived(IDeckLinkVideoInputFrame* videoFrame, IDeckLinkAudioInputPacket* audioFrame)
275 demux_sys_t *sys = demux_->p_sys;
278 if (videoFrame->GetFlags() & bmdFrameHasNoInputSource) {
279 msg_Warn(demux_, "No input signal detected");
283 const int width = videoFrame->GetWidth();
284 const int height = videoFrame->GetHeight();
285 const int stride = videoFrame->GetRowBytes();
287 int bpp = sys->tenbits ? 4 : 2;
288 block_t *video_frame = block_Alloc(width * height * bpp);
292 const uint32_t *frame_bytes;
293 videoFrame->GetBytes((void**)&frame_bytes);
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;
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++) {
306 if (vanc->GetBufferForVerticalBlankingLine(i, (void**)&buf) != S_OK)
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);
313 cc->i_pts = cc->i_dts = VLC_TS_0 + stream_time;
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");
326 es_out_Send(demux_->out, sys->cc_es, cc);
329 break; // we found the line with Closed Caption data
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);
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);
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);
351 const int bytes = audioFrame->GetSampleFrameCount() * sizeof(int16_t) * sys->channels;
353 block_t *audio_frame = block_Alloc(bytes);
358 audioFrame->GetBytes(&frame_bytes);
359 memcpy(audio_frame->p_buffer, frame_bytes, bytes);
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;
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);
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);
378 static int GetAudioConn(demux_t *demux)
380 demux_sys_t *sys = demux->p_sys;
382 char *opt = var_CreateGetNonEmptyString(demux, "decklink-audio-connection");
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;
394 msg_Err(demux, "Invalid audio-connection: `%s\' specified", opt);
399 if (sys->config->SetInt(bmdDeckLinkConfigAudioInputConnection, c) != S_OK) {
400 msg_Err(demux, "Failed to set audio input connection");
407 static int GetVideoConn(demux_t *demux)
409 demux_sys_t *sys = demux->p_sys;
411 char *opt = var_InheritString(demux, "decklink-video-connection");
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;
429 msg_Err(demux, "Invalid video-connection: `%s\' specified", opt);
435 if (sys->config->SetInt(bmdDeckLinkConfigVideoInputConnection, c) != S_OK) {
436 msg_Err(demux, "Failed to set video input connection");
443 static int Open(vlc_object_t *p_this)
445 demux_t *demux = (demux_t*)p_this;
447 int ret = VLC_EGENERIC;
449 int physical_channels = 0;
451 BMDVideoInputFlags flags = bmdVideoInputFlagDefault;
453 /* Only when selected */
454 if (*demux->psz_access == '\0')
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));
467 vlc_mutex_init(&sys->pts_lock);
469 sys->tenbits = var_InheritBool(p_this, "decklink-tenbits");
471 IDeckLinkIterator *decklink_iterator = CreateDeckLinkIteratorInstance();
472 if (!decklink_iterator) {
473 msg_Err(demux, "DeckLink drivers not found.");
477 card_index = var_InheritInteger(demux, "decklink-card-index");
478 if (card_index < 0) {
479 msg_Err(demux, "Invalid card index %d", card_index);
483 for (int i = 0; i <= card_index; i++) {
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);
492 const char *model_name;
493 if (sys->card->GetModelName(&model_name) != S_OK)
494 model_name = "unknown";
496 msg_Dbg(demux, "Opened DeckLink PCI card %d (%s)", card_index, model_name);
498 if (sys->card->QueryInterface(IID_IDeckLinkInput, (void**)&sys->input) != S_OK) {
499 msg_Err(demux, "Card has no inputs");
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");
509 if (sys->card->QueryInterface(IID_IDeckLinkAttributes, (void**)&sys->attributes) != S_OK) {
510 msg_Err(demux, "Failed to get attributes interface");
514 if (GetVideoConn(demux) || GetAudioConn(demux))
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");
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");
539 mode = var_CreateGetNonEmptyString(demux, "decklink-mode");
541 sys->autodetect = false; // disable autodetection if mode was set
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);
549 if (!mode || strlen(mode) < 3 || strlen(mode) > 4) {
550 msg_Err(demux, "Invalid mode: \'%s\'", mode ? mode : "");
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 ' */
562 es_format_t video_fmt;
563 video_fmt.video.i_width = 0;
565 for (IDeckLinkDisplayMode *m;; m->Release()) {
566 if ((mode_it->Next(&m) != S_OK) || !m)
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());
575 if (m->GetName(&mode_name) != S_OK)
576 mode_name = "unknown";
577 if (m->GetFrameRate(&frame_duration, &time_scale) != S_OK) {
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);
588 video_fmt = GetModeSettings(demux, m);
589 msg_Dbg(demux, "Using that mode");
595 if (video_fmt.video.i_width == 0) {
596 msg_Err(demux, "Unknown video mode `%4.4s\' specified.", (char*)&u.id);
600 if (sys->input->EnableVideoInput(htonl(u.id), fmt, flags) != S_OK) {
601 msg_Err(demux, "Failed to enable video input");
606 sys->channels = var_InheritInteger(demux, "decklink-audio-channels");
607 switch (sys->channels) {
611 physical_channels = AOUT_CHANS_STEREO;
614 physical_channels = AOUT_CHANS_7_1;
618 msg_Err(demux, "Invalid number of channels (%d), disabling audio", sys->channels);
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");
629 sys->delegate = new DeckLinkCaptureDelegate(demux);
630 sys->input->SetCallback(sys->delegate);
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.");
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);
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;
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);
658 if (decklink_iterator)
659 decklink_iterator->Release();
661 if (ret != VLC_SUCCESS)
667 static void Close(vlc_object_t *p_this)
669 demux_t *demux = (demux_t *)p_this;
670 demux_sys_t *sys = demux->p_sys;
673 sys->attributes->Release();
676 sys->config->Release();
679 sys->input->StopStreams();
680 sys->input->Release();
684 sys->card->Release();
687 sys->delegate->Release();
689 vlc_mutex_destroy(&sys->pts_lock);
693 static int Control(demux_t *demux, int query, va_list args)
695 demux_sys_t *sys = demux->p_sys;
701 /* Special for access_demux */
702 case DEMUX_CAN_PAUSE:
704 case DEMUX_CAN_CONTROL_PACE:
705 pb = (bool*)va_arg(args, bool *);
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");
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);