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>
8 * Authors: Steinar H. Gunderson <steinar+vlc@gunderson.no>
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>
41 static int Open (vlc_object_t *);
42 static void Close(vlc_object_t *);
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.")
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\".")
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.")
61 #define RATE_TEXT N_("Audio sampling rate in Hz")
62 #define RATE_LONGTEXT N_( \
63 "Audio sampling rate (in hertz) for DeckLink captures. " \
64 "0 disables audio input.")
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.")
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.")
78 static const char *const ppsz_videoconns[] = {
79 "sdi", "hdmi", "opticalsdi", "component", "composite", "svideo"
81 static const char *const ppsz_videoconns_text[] = {
82 N_("SDI"), N_("HDMI"), N_("Optical SDI"), N_("Component"), N_("Composite"), N_("S-video")
85 static const char *const ppsz_audioconns[] = {
86 "embedded", "aesebu", "analog"
88 static const char *const ppsz_audioconns_text[] = {
89 N_("Embedded"), N_("AES/EBU"), N_("Analog")
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.")
97 set_shortname(N_("DeckLink"))
98 set_description(N_("Blackmagic DeckLink SDI input"))
99 set_category(CAT_INPUT)
100 set_subcategory(SUBCAT_INPUT_ACCESS)
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)
120 add_shortcut("decklink")
121 set_capability("access_demux", 10)
122 set_callbacks(Open, Close)
125 static int Control(demux_t *, int, va_list);
127 class DeckLinkCaptureDelegate;
132 IDeckLinkInput *input;
133 DeckLinkCaptureDelegate *delegate;
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;
139 es_out_id_t *video_es;
140 es_out_id_t *audio_es;
142 vlc_mutex_t pts_lock;
143 int last_pts; /* protected by <pts_lock> */
145 uint32_t dominance_flags;
151 class DeckLinkCaptureDelegate : public IDeckLinkInputCallback
154 DeckLinkCaptureDelegate(demux_t *demux) : demux_(demux)
156 vlc_atomic_set(&m_ref_, 1);
159 virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID, LPVOID *) { return E_NOINTERFACE; }
161 virtual ULONG STDMETHODCALLTYPE AddRef(void)
163 return vlc_atomic_inc(&m_ref_);
166 virtual ULONG STDMETHODCALLTYPE Release(void)
168 uintptr_t new_ref = vlc_atomic_dec(&m_ref_);
174 virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents, IDeckLinkDisplayMode*, BMDDetectedVideoInputFormatFlags)
176 msg_Dbg(demux_, "Video input format changed");
180 virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame*, IDeckLinkAudioInputPacket*);
187 static uint32_t av_le2ne32(uint32_t val)
194 return (u.b[0] << 0) | (u.b[1] << 8) | (u.b[2] << 16) | (u.b[3] << 24);
197 HRESULT DeckLinkCaptureDelegate::VideoInputFrameArrived(IDeckLinkVideoInputFrame* videoFrame, IDeckLinkAudioInputPacket* audioFrame)
199 demux_sys_t *sys = demux_->p_sys;
202 if (videoFrame->GetFlags() & bmdFrameHasNoInputSource) {
203 msg_Warn(demux_, "No input signal detected");
207 const int width = videoFrame->GetWidth();
208 const int height = videoFrame->GetHeight();
209 const int stride = videoFrame->GetRowBytes();
211 block_t *video_frame = block_New(demux_, width * height * 4);
215 uint8_t *frame_bytes;
216 videoFrame->GetBytes((void**)&frame_bytes);
222 int stride = ((width + 47) / 48) * 48 * 8 / 3;
224 uint16_t *y = (uint16_t*)(&video_frame->p_buffer[0]);
225 uint16_t *u = (uint16_t*)(&video_frame->p_buffer[width * height * 2]);
226 uint16_t *v = (uint16_t*)(&video_frame->p_buffer[width * height * 3]);
228 #define READ_PIXELS(a, b, c) \
230 val = av_le2ne32(*src++); \
231 *a++ = val & 0x3FF; \
232 *b++ = (val >> 10) & 0x3FF; \
233 *c++ = (val >> 20) & 0x3FF; \
236 for (int h = 0; h < height; h++) {
237 const uint32_t *src = (const uint32_t*)frame_bytes;
240 for (w = 0; w < width - 5; w += 6) {
241 READ_PIXELS(u, y, v);
242 READ_PIXELS(y, u, y);
243 READ_PIXELS(v, y, u);
244 READ_PIXELS(y, v, y);
247 READ_PIXELS(u, y, v);
249 val = av_le2ne32(*src++);
253 *u++ = (val >> 10) & 0x3FF;
254 *y++ = (val >> 20) & 0x3FF;
256 val = av_le2ne32(*src++);
258 *y++ = (val >> 10) & 0x3FF;
261 frame_bytes += stride;
264 for (int y = 0; y < height; ++y) {
265 const uint8_t *src = (const uint8_t *)frame_bytes + stride * y;
266 uint8_t *dst = video_frame->p_buffer + width * 2 * y;
267 memcpy(dst, src, width * 2);
271 BMDTimeValue stream_time, frame_duration;
272 videoFrame->GetStreamTime(&stream_time, &frame_duration, CLOCK_FREQ);
273 video_frame->i_flags = BLOCK_FLAG_TYPE_I | sys->dominance_flags;
274 video_frame->i_pts = video_frame->i_dts = VLC_TS_0 + stream_time;
276 vlc_mutex_lock(&sys->pts_lock);
277 if (video_frame->i_pts > sys->last_pts)
278 sys->last_pts = video_frame->i_pts;
279 vlc_mutex_unlock(&sys->pts_lock);
281 es_out_Control(demux_->out, ES_OUT_SET_PCR, video_frame->i_pts);
282 es_out_Send(demux_->out, sys->video_es, video_frame);
286 const int bytes = audioFrame->GetSampleFrameCount() * sizeof(int16_t) * sys->channels;
288 block_t *audio_frame = block_New(demux_, bytes);
293 audioFrame->GetBytes(&frame_bytes);
294 memcpy(audio_frame->p_buffer, frame_bytes, bytes);
296 BMDTimeValue packet_time;
297 audioFrame->GetPacketTime(&packet_time, CLOCK_FREQ);
298 audio_frame->i_pts = audio_frame->i_dts = VLC_TS_0 + packet_time;
300 vlc_mutex_lock(&sys->pts_lock);
301 if (audio_frame->i_pts > sys->last_pts)
302 sys->last_pts = audio_frame->i_pts;
303 vlc_mutex_unlock(&sys->pts_lock);
304 if (audio_frame->i_pts > sys->last_pts)
306 es_out_Control(demux_->out, ES_OUT_SET_PCR, audio_frame->i_pts);
307 es_out_Send(demux_->out, sys->audio_es, audio_frame);
314 static int GetAudioConn(demux_t *demux)
316 demux_sys_t *sys = demux->p_sys;
318 char *opt = var_CreateGetNonEmptyString(demux, "decklink-audio-connection");
322 BMDAudioConnection c;
323 if (!strcmp(opt, "embedded"))
324 c = bmdAudioConnectionEmbedded;
325 else if (!strcmp(opt, "aesebu"))
326 c = bmdAudioConnectionAESEBU;
327 else if (!strcmp(opt, "analog"))
328 c = bmdAudioConnectionAnalog;
330 msg_Err(demux, "Invalid audio-connection: `%s\' specified", opt);
335 if (sys->config->SetInt(bmdDeckLinkConfigAudioInputConnection, c) != S_OK) {
336 msg_Err(demux, "Failed to set audio input connection");
343 static int GetVideoConn(demux_t *demux)
345 demux_sys_t *sys = demux->p_sys;
347 char *opt = var_InheritString(demux, "decklink-video-connection");
351 BMDVideoConnection c;
352 if (!strcmp(opt, "sdi"))
353 c = bmdVideoConnectionSDI;
354 else if (!strcmp(opt, "hdmi"))
355 c = bmdVideoConnectionHDMI;
356 else if (!strcmp(opt, "opticalsdi"))
357 c = bmdVideoConnectionOpticalSDI;
358 else if (!strcmp(opt, "component"))
359 c = bmdVideoConnectionComponent;
360 else if (!strcmp(opt, "composite"))
361 c = bmdVideoConnectionComposite;
362 else if (!strcmp(opt, "svideo"))
363 c = bmdVideoConnectionSVideo;
365 msg_Err(demux, "Invalid video-connection: `%s\' specified", opt);
371 if (sys->config->SetInt(bmdDeckLinkConfigVideoInputConnection, c) != S_OK) {
372 msg_Err(demux, "Failed to set video input connection");
379 static const char *GetFieldDominance(BMDFieldDominance dom, uint32_t *flags)
383 case bmdProgressiveFrame:
385 case bmdProgressiveSegmentedFrame:
386 return ", segmented";
387 case bmdLowerFieldFirst:
388 *flags = BLOCK_FLAG_BOTTOM_FIELD_FIRST;
389 return ", interlaced [BFF]";
390 case bmdUpperFieldFirst:
391 *flags = BLOCK_FLAG_TOP_FIELD_FIRST;
392 return ", interlaced [TFF]";
393 case bmdUnknownFieldDominance:
395 return ", unknown field dominance";
399 static int Open(vlc_object_t *p_this)
401 demux_t *demux = (demux_t*)p_this;
403 int ret = VLC_EGENERIC;
405 int width = 0, height, fps_num, fps_den;
407 unsigned aspect_num, aspect_den;
409 /* Only when selected */
410 if (*demux->psz_access == '\0')
414 demux->pf_demux = NULL;
415 demux->pf_control = Control;
416 demux->info.i_update = 0;
417 demux->info.i_title = 0;
418 demux->info.i_seekpoint = 0;
419 demux->p_sys = sys = (demux_sys_t*)calloc(1, sizeof(demux_sys_t));
423 vlc_mutex_init(&sys->pts_lock);
425 sys->tenbits = var_InheritBool(p_this, "decklink-tenbits");
427 IDeckLinkIterator *decklink_iterator = CreateDeckLinkIteratorInstance();
428 if (!decklink_iterator) {
429 msg_Err(demux, "DeckLink drivers not found.");
433 card_index = var_InheritInteger(demux, "decklink-card-index");
434 if (card_index < 0) {
435 msg_Err(demux, "Invalid card index %d", card_index);
439 for (int i = 0; i <= card_index; i++) {
441 sys->card->Release();
442 if (decklink_iterator->Next(&sys->card) != S_OK) {
443 msg_Err(demux, "DeckLink PCI card %d not found", card_index);
448 const char *model_name;
449 if (sys->card->GetModelName(&model_name) != S_OK)
450 model_name = "unknown";
452 msg_Dbg(demux, "Opened DeckLink PCI card %d (%s)", card_index, model_name);
454 if (sys->card->QueryInterface(IID_IDeckLinkInput, (void**)&sys->input) != S_OK) {
455 msg_Err(demux, "Card has no inputs");
459 /* Set up the video and audio sources. */
460 if (sys->card->QueryInterface(IID_IDeckLinkConfiguration, (void**)&sys->config) != S_OK) {
461 msg_Err(demux, "Failed to get configuration interface");
465 if (GetVideoConn(demux) || GetAudioConn(demux))
469 mode = var_CreateGetNonEmptyString(demux, "decklink-mode");
470 if (!mode || strlen(mode) < 3 || strlen(mode) > 4) {
471 msg_Err(demux, "Invalid mode: `%s\'", mode ? mode : "");
475 /* Get the list of display modes. */
476 IDeckLinkDisplayModeIterator *mode_it;
477 if (sys->input->GetDisplayModeIterator(&mode_it) != S_OK) {
478 msg_Err(demux, "Failed to enumerate display modes");
487 memcpy(u.str, mode, 4);
488 if (u.str[3] == '\0')
489 u.str[3] = ' '; /* 'pal'\0 -> 'pal ' */
492 for (IDeckLinkDisplayMode *m;; m->Release()) {
493 if ((mode_it->Next(&m) != S_OK) || !m)
496 const char *mode_name;
497 BMDTimeValue frame_duration, time_scale;
499 const char *field = GetFieldDominance(m->GetFieldDominance(), &flags);
500 BMDDisplayMode id = ntohl(m->GetDisplayMode());
502 if (m->GetName(&mode_name) != S_OK)
503 mode_name = "unknown";
504 if (m->GetFrameRate(&frame_duration, &time_scale) != S_OK) {
509 msg_Dbg(demux, "Found mode '%4.4s': %s (%dx%d, %.3f fps%s)",
510 (char*)&id, mode_name,
511 (int)m->GetWidth(), (int)m->GetHeight(),
512 double(time_scale) / frame_duration, field);
515 width = m->GetWidth();
516 height = m->GetHeight();
517 fps_num = time_scale;
518 fps_den = frame_duration;
519 sys->dominance_flags = flags;
526 msg_Err(demux, "Unknown video mode `%4.4s\' specified.", (char*)&u.id);
530 BMDPixelFormat fmt; fmt = sys->tenbits ? bmdFormat10BitYUV : bmdFormat8BitYUV;
531 if (sys->input->EnableVideoInput(htonl(u.id), fmt, 0) != S_OK) {
532 msg_Err(demux, "Failed to enable video input");
537 sys->channels = var_InheritInteger(demux, "decklink-audio-channels");
538 rate = var_InheritInteger(demux, "decklink-audio-rate");
539 if (rate > 0 && sys->channels > 0) {
540 if (sys->input->EnableAudioInput(rate, bmdAudioSampleType16bitInteger, sys->channels) != S_OK) {
541 msg_Err(demux, "Failed to enable audio input");
546 sys->delegate = new DeckLinkCaptureDelegate(demux);
547 sys->input->SetCallback(sys->delegate);
549 if (sys->input->StartStreams() != S_OK) {
550 msg_Err(demux, "Could not start streaming from SDI card. This could be caused "
551 "by invalid video mode or flags, access denied, or card already in use.");
555 /* Declare elementary streams */
556 es_format_t video_fmt;
557 vlc_fourcc_t chroma; chroma = sys->tenbits ? VLC_CODEC_I422_10L : VLC_CODEC_UYVY;
558 es_format_Init(&video_fmt, VIDEO_ES, chroma);
559 video_fmt.video.i_width = width;
560 video_fmt.video.i_height = height;
561 video_fmt.video.i_sar_num = 1;
562 video_fmt.video.i_sar_den = 1;
563 video_fmt.video.i_frame_rate = fps_num;
564 video_fmt.video.i_frame_rate_base = fps_den;
565 video_fmt.i_bitrate = video_fmt.video.i_width * video_fmt.video.i_height * video_fmt.video.i_frame_rate * 2 * 8;
567 if (!var_InheritURational(demux, &aspect_num, &aspect_den, "decklink-aspect-ratio") &&
568 aspect_num > 0 && aspect_den > 0) {
569 video_fmt.video.i_sar_num = aspect_num * video_fmt.video.i_height;
570 video_fmt.video.i_sar_den = aspect_den * video_fmt.video.i_width;
573 msg_Dbg(demux, "added new video es %4.4s %dx%d",
574 (char*)&video_fmt.i_codec, video_fmt.video.i_width, video_fmt.video.i_height);
575 sys->video_es = es_out_Add(demux->out, &video_fmt);
577 es_format_t audio_fmt;
578 es_format_Init(&audio_fmt, AUDIO_ES, VLC_CODEC_S16N);
579 audio_fmt.audio.i_channels = sys->channels;
580 audio_fmt.audio.i_rate = rate;
581 audio_fmt.audio.i_bitspersample = 16;
582 audio_fmt.audio.i_blockalign = audio_fmt.audio.i_channels * audio_fmt.audio.i_bitspersample / 8;
583 audio_fmt.i_bitrate = audio_fmt.audio.i_channels * audio_fmt.audio.i_rate * audio_fmt.audio.i_bitspersample;
585 msg_Dbg(demux, "added new audio es %4.4s %dHz %dbpp %dch",
586 (char*)&audio_fmt.i_codec, audio_fmt.audio.i_rate, audio_fmt.audio.i_bitspersample, audio_fmt.audio.i_channels);
587 sys->audio_es = es_out_Add(demux->out, &audio_fmt);
592 if (decklink_iterator)
593 decklink_iterator->Release();
595 if (ret != VLC_SUCCESS)
601 static void Close(vlc_object_t *p_this)
603 demux_t *demux = (demux_t *)p_this;
604 demux_sys_t *sys = demux->p_sys;
607 sys->config->Release();
610 sys->input->StopStreams();
611 sys->input->Release();
615 sys->card->Release();
618 sys->delegate->Release();
620 vlc_mutex_destroy(&sys->pts_lock);
624 static int Control(demux_t *demux, int query, va_list args)
626 demux_sys_t *sys = demux->p_sys;
632 /* Special for access_demux */
633 case DEMUX_CAN_PAUSE:
635 case DEMUX_CAN_CONTROL_PACE:
636 pb = (bool*)va_arg(args, bool *);
640 case DEMUX_GET_PTS_DELAY:
641 pi64 = (int64_t*)va_arg(args, int64_t *);
642 *pi64 = INT64_C(1000) * var_InheritInteger(demux, "live-caching");
646 pi64 = (int64_t*)va_arg(args, int64_t *);
647 vlc_mutex_lock(&sys->pts_lock);
648 *pi64 = sys->last_pts;
649 vlc_mutex_unlock(&sys->pts_lock);