1 #include "decklink_capture.h"
4 #include <DeckLinkAPI.h>
5 #include <DeckLinkAPIConfiguration.h>
6 #include <DeckLinkAPIDiscovery.h>
7 #include <DeckLinkAPIModes.h>
8 #include <DeckLinkAPITypes.h>
15 #include <immintrin.h>
27 #include "bmusb/bmusb.h"
28 #include "decklink_util.h"
30 #include "shared/memcpy_interleaved.h"
31 #include "v210_converter.h"
34 using namespace std::chrono;
35 using namespace std::placeholders;
36 using namespace bmusb;
40 BMDPixelFormat pixel_format_to_bmd(PixelFormat pixel_format)
42 switch (pixel_format) {
43 case PixelFormat_8BitYCbCr:
44 return bmdFormat8BitYUV;
45 case PixelFormat_10BitYCbCr:
46 return bmdFormat10BitYUV;
54 DeckLinkCapture::DeckLinkCapture(IDeckLink *card, int card_index)
55 : card_index(card_index), card(card)
58 const char *model_name;
60 if (card->GetModelName(&model_name) == S_OK) {
61 snprintf(buf, sizeof(buf), "PCI card %d: %s", card_index, model_name);
63 snprintf(buf, sizeof(buf), "PCI card %d: Unknown DeckLink card", card_index);
68 if (card->QueryInterface(IID_IDeckLinkInput, (void**)&input) != S_OK) {
69 fprintf(stderr, "Card %d has no inputs\n", card_index);
73 IDeckLinkAttributes *attr;
74 if (card->QueryInterface(IID_IDeckLinkAttributes, (void**)&attr) != S_OK) {
75 fprintf(stderr, "Card %d has no attributes\n", card_index);
79 // Get the list of available video inputs.
80 int64_t video_input_mask;
81 if (attr->GetInt(BMDDeckLinkVideoInputConnections, &video_input_mask) != S_OK) {
82 fprintf(stderr, "Failed to enumerate video inputs for card %d\n", card_index);
85 const vector<pair<BMDVideoConnection, string>> video_input_types = {
86 { bmdVideoConnectionSDI, "SDI" },
87 { bmdVideoConnectionHDMI, "HDMI" },
88 { bmdVideoConnectionOpticalSDI, "Optical SDI" },
89 { bmdVideoConnectionComponent, "Component" },
90 { bmdVideoConnectionComposite, "Composite" },
91 { bmdVideoConnectionSVideo, "S-Video" }
93 for (const auto &video_input : video_input_types) {
94 if (video_input_mask & video_input.first) {
95 video_inputs.emplace(video_input.first, video_input.second);
99 // And then the available audio inputs.
100 int64_t audio_input_mask;
101 if (attr->GetInt(BMDDeckLinkAudioInputConnections, &audio_input_mask) != S_OK) {
102 fprintf(stderr, "Failed to enumerate audio inputs for card %d\n", card_index);
105 const vector<pair<BMDAudioConnection, string>> audio_input_types = {
106 { bmdAudioConnectionEmbedded, "Embedded" },
107 { bmdAudioConnectionAESEBU, "AES/EBU" },
108 { bmdAudioConnectionAnalog, "Analog" },
109 { bmdAudioConnectionAnalogXLR, "Analog XLR" },
110 { bmdAudioConnectionAnalogRCA, "Analog RCA" },
111 { bmdAudioConnectionMicrophone, "Microphone" },
112 { bmdAudioConnectionHeadphones, "Headphones" }
114 for (const auto &audio_input : audio_input_types) {
115 if (audio_input_mask & audio_input.first) {
116 audio_inputs.emplace(audio_input.first, audio_input.second);
120 // Check if we the card supports input autodetection.
121 if (attr->GetFlag(BMDDeckLinkSupportsInputFormatDetection, &supports_autodetect) != S_OK) {
122 fprintf(stderr, "Warning: Failed to ask card %d whether it supports input format autodetection\n", card_index);
123 supports_autodetect = false;
126 // If there's more than one subdevice on this card, label them.
127 int64_t num_subdevices, subdevice_idx;
128 if (attr->GetInt(BMDDeckLinkNumberOfSubDevices, &num_subdevices) == S_OK && num_subdevices > 1) {
129 if (attr->GetInt(BMDDeckLinkSubDeviceIndex, &subdevice_idx) == S_OK) {
131 snprintf(buf, sizeof(buf), " (subdevice %d)", int(subdevice_idx));
138 /* Set up the video and audio sources. */
139 if (card->QueryInterface(IID_IDeckLinkConfiguration, (void**)&config) != S_OK) {
140 fprintf(stderr, "Failed to get configuration interface for card %d\n", card_index);
144 BMDVideoConnection connection = pick_default_video_connection(card, BMDDeckLinkVideoInputConnections, card_index);
146 set_video_input(connection);
147 set_audio_input(bmdAudioConnectionEmbedded);
149 IDeckLinkDisplayModeIterator *mode_it;
150 if (input->GetDisplayModeIterator(&mode_it) != S_OK) {
151 fprintf(stderr, "Failed to enumerate display modes for card %d\n", card_index);
155 video_modes = summarize_video_modes(mode_it, card_index);
158 set_video_mode_no_restart(bmdModeHD720p5994);
160 input->SetCallback(this);
163 DeckLinkCapture::~DeckLinkCapture()
165 if (has_dequeue_callbacks) {
166 dequeue_cleanup_callback();
173 HRESULT STDMETHODCALLTYPE DeckLinkCapture::QueryInterface(REFIID, LPVOID *)
175 return E_NOINTERFACE;
178 ULONG STDMETHODCALLTYPE DeckLinkCapture::AddRef(void)
180 return refcount.fetch_add(1) + 1;
183 ULONG STDMETHODCALLTYPE DeckLinkCapture::Release(void)
185 int new_ref = refcount.fetch_sub(1) - 1;
191 HRESULT STDMETHODCALLTYPE DeckLinkCapture::VideoInputFormatChanged(
192 BMDVideoInputFormatChangedEvents,
193 IDeckLinkDisplayMode* display_mode,
194 BMDDetectedVideoInputFormatFlags format_flags)
196 if (format_flags & bmdDetectedVideoInputRGB444) {
197 fprintf(stderr, "WARNING: Input detected as 4:4:4 RGB, but Nageru can't consume that yet.\n");
198 fprintf(stderr, "Doing hardware conversion to 4:2:2 Y'CbCr.\n");
200 if (supports_autodetect && display_mode->GetDisplayMode() != current_video_mode) {
201 set_video_mode(display_mode->GetDisplayMode());
203 if (display_mode->GetFrameRate(&frame_duration, &time_scale) != S_OK) {
204 fprintf(stderr, "Could not get new frame rate\n");
207 field_dominance = display_mode->GetFieldDominance();
211 HRESULT STDMETHODCALLTYPE DeckLinkCapture::VideoInputFrameArrived(
212 IDeckLinkVideoInputFrame *video_frame,
213 IDeckLinkAudioInputPacket *audio_frame)
216 char thread_name[16];
217 snprintf(thread_name, sizeof(thread_name), "DeckLink_C_%d", card_index);
218 pthread_setname_np(pthread_self(), thread_name);
221 memset(¶m, 0, sizeof(param));
222 param.sched_priority = 1;
223 if (sched_setscheduler(0, SCHED_RR, ¶m) == -1) {
224 printf("couldn't set realtime priority for DeckLink thread: %s\n", strerror(errno));
227 if (has_dequeue_callbacks) {
228 dequeue_init_callback();
233 steady_clock::time_point now = steady_clock::now();
235 FrameAllocator::Frame current_video_frame, current_audio_frame;
236 VideoFormat video_format;
237 AudioFormat audio_format;
239 video_format.frame_rate_nom = time_scale;
240 video_format.frame_rate_den = frame_duration;
241 // TODO: Respect the TFF/BFF flag.
242 video_format.interlaced = (field_dominance == bmdLowerFieldFirst || field_dominance == bmdUpperFieldFirst);
243 video_format.second_field_start = 1;
246 video_format.has_signal = !(video_frame->GetFlags() & bmdFrameHasNoInputSource);
248 const int width = video_frame->GetWidth();
249 const int height = video_frame->GetHeight();
250 const int stride = video_frame->GetRowBytes();
251 const BMDPixelFormat format = video_frame->GetPixelFormat();
252 assert(format == pixel_format_to_bmd(current_pixel_format));
253 if (global_flags.bit_depth > 8) {
254 assert(stride == int(v210Converter::get_v210_stride(width)));
256 assert(stride == width * 2);
259 if (width * stride > FRAME_SIZE) {
260 // TODO: If we had an OpenGL context here, calling create_frame()
261 // would be completely fine.
262 fprintf(stderr, "Card %u: Captured frame %d x %d (stride %d) would be larger than supported frame size (%d > %d), skipping.\n",
263 card_index, width, height, stride, width * stride, FRAME_SIZE);
265 current_video_frame = video_frame_allocator->create_frame(width, height, stride);
267 if (current_video_frame.data != nullptr) {
269 video_frame->GetBytes((void **)&src);
270 size_t num_bytes = stride * height;
272 if (current_video_frame.interleaved) {
273 uint8_t *data = current_video_frame.data;
274 uint8_t *data2 = current_video_frame.data2;
275 memcpy_interleaved(data, data2, src, num_bytes);
277 memcpy(current_video_frame.data, src, num_bytes);
279 if (current_video_frame.data_copy != nullptr) {
280 memcpy(current_video_frame.data_copy, src, num_bytes);
282 current_video_frame.len += num_bytes;
284 video_format.width = width;
285 video_format.height = height;
286 video_format.stride = stride;
291 int num_samples = audio_frame->GetSampleFrameCount();
293 current_audio_frame = audio_frame_allocator->alloc_frame();
294 if (current_audio_frame.data != nullptr) {
296 audio_frame->GetBytes((void **)&src);
297 current_audio_frame.len = sizeof(int32_t) * 8 * num_samples;
299 memcpy(current_audio_frame.data, src, current_audio_frame.len);
301 audio_format.bits_per_sample = 32;
302 audio_format.num_channels = 8;
306 current_video_frame.received_timestamp = now;
307 current_audio_frame.received_timestamp = now;
309 if (current_video_frame.data != nullptr || current_audio_frame.data != nullptr) {
310 // TODO: Put into a queue and put into a dequeue thread, if the
311 // BlackMagic drivers don't already do that for us?
312 frame_callback(timecode,
313 current_video_frame, /*video_offset=*/0, video_format,
314 current_audio_frame, /*audio_offset=*/0, audio_format);
321 void DeckLinkCapture::configure_card()
323 if (video_frame_allocator == nullptr) {
324 owned_video_frame_allocator.reset(new MallocFrameAllocator(FRAME_SIZE, NUM_QUEUED_VIDEO_FRAMES));
325 set_video_frame_allocator(owned_video_frame_allocator.get());
327 if (audio_frame_allocator == nullptr) {
328 owned_audio_frame_allocator.reset(new MallocFrameAllocator(65536, NUM_QUEUED_AUDIO_FRAMES));
329 set_audio_frame_allocator(owned_audio_frame_allocator.get());
333 void DeckLinkCapture::start_bm_capture()
338 if (input->EnableVideoInput(current_video_mode, pixel_format_to_bmd(current_pixel_format), supports_autodetect ? bmdVideoInputEnableFormatDetection : 0) != S_OK) {
339 fprintf(stderr, "Failed to set video mode 0x%04x for card %d\n", current_video_mode, card_index);
342 if (input->EnableAudioInput(48000, bmdAudioSampleType32bitInteger, 8) != S_OK) {
343 fprintf(stderr, "Failed to enable audio input for card %d\n", card_index);
347 if (input->StartStreams() != S_OK) {
348 fprintf(stderr, "StartStreams failed\n");
354 void DeckLinkCapture::stop_dequeue_thread()
359 HRESULT result = input->StopStreams();
360 if (result != S_OK) {
361 fprintf(stderr, "StopStreams failed with error 0x%x\n", result);
365 // We could call DisableVideoInput() and DisableAudioInput() here,
366 // but they seem to be taking a really long time, and we only do this
367 // during shutdown anyway (except when switching to output mode,
368 // where DeckLinkOutput does the disabling), so StopStreams() will suffice.
373 void DeckLinkCapture::set_video_mode(uint32_t video_mode_id)
376 if (input->PauseStreams() != S_OK) {
377 fprintf(stderr, "PauseStreams failed\n");
380 if (input->FlushStreams() != S_OK) {
381 fprintf(stderr, "FlushStreams failed\n");
386 set_video_mode_no_restart(video_mode_id);
389 if (input->StartStreams() != S_OK) {
390 fprintf(stderr, "StartStreams failed\n");
396 void DeckLinkCapture::set_pixel_format(PixelFormat pixel_format)
398 current_pixel_format = pixel_format;
399 set_video_mode(current_video_mode);
402 void DeckLinkCapture::set_video_mode_no_restart(uint32_t video_mode_id)
404 BMDDisplayModeSupport support;
405 IDeckLinkDisplayMode *display_mode;
406 if (input->DoesSupportVideoMode(video_mode_id, pixel_format_to_bmd(current_pixel_format), /*flags=*/0, &support, &display_mode)) {
407 fprintf(stderr, "Failed to query display mode for card %d\n", card_index);
411 if (support == bmdDisplayModeNotSupported) {
412 fprintf(stderr, "Card %d does not support display mode\n", card_index);
416 if (display_mode->GetFrameRate(&frame_duration, &time_scale) != S_OK) {
417 fprintf(stderr, "Could not get frame rate for card %d\n", card_index);
421 field_dominance = display_mode->GetFieldDominance();
424 if (input->EnableVideoInput(video_mode_id, pixel_format_to_bmd(current_pixel_format), supports_autodetect ? bmdVideoInputEnableFormatDetection : 0) != S_OK) {
425 fprintf(stderr, "Failed to set video mode 0x%04x for card %d\n", video_mode_id, card_index);
430 current_video_mode = video_mode_id;
433 void DeckLinkCapture::set_video_input(uint32_t video_input_id)
435 if (config->SetInt(bmdDeckLinkConfigVideoInputConnection, video_input_id) != S_OK) {
436 fprintf(stderr, "Failed to set video input connection for card %d\n", card_index);
440 current_video_input = video_input_id;
443 void DeckLinkCapture::set_audio_input(uint32_t audio_input_id)
445 if (config->SetInt(bmdDeckLinkConfigAudioInputConnection, audio_input_id) != S_OK) {
446 fprintf(stderr, "Failed to set audio input connection for card %d\n", card_index);
450 current_audio_input = audio_input_id;