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 current_video_frame = video_frame_allocator->create_frame(width, height, stride);
260 if (current_video_frame.data != nullptr) {
262 video_frame->GetBytes((void **)&src);
263 size_t num_bytes = stride * height;
265 if (current_video_frame.interleaved) {
266 uint8_t *data = current_video_frame.data;
267 uint8_t *data2 = current_video_frame.data2;
268 memcpy_interleaved(data, data2, src, num_bytes);
270 memcpy(current_video_frame.data, src, num_bytes);
272 if (current_video_frame.data_copy != nullptr) {
273 memcpy(current_video_frame.data_copy, src, num_bytes);
275 current_video_frame.len += num_bytes;
277 video_format.width = width;
278 video_format.height = height;
279 video_format.stride = stride;
284 int num_samples = audio_frame->GetSampleFrameCount();
286 current_audio_frame = audio_frame_allocator->alloc_frame();
287 if (current_audio_frame.data != nullptr) {
289 audio_frame->GetBytes((void **)&src);
290 current_audio_frame.len = sizeof(int32_t) * 8 * num_samples;
292 memcpy(current_audio_frame.data, src, current_audio_frame.len);
294 audio_format.bits_per_sample = 32;
295 audio_format.num_channels = 8;
299 current_video_frame.received_timestamp = now;
300 current_audio_frame.received_timestamp = now;
302 if (current_video_frame.data != nullptr || current_audio_frame.data != nullptr) {
303 // TODO: Put into a queue and put into a dequeue thread, if the
304 // BlackMagic drivers don't already do that for us?
305 frame_callback(timecode,
306 current_video_frame, /*video_offset=*/0, video_format,
307 current_audio_frame, /*audio_offset=*/0, audio_format);
314 void DeckLinkCapture::configure_card()
316 if (video_frame_allocator == nullptr) {
317 owned_video_frame_allocator.reset(new MallocFrameAllocator(FRAME_SIZE, NUM_QUEUED_VIDEO_FRAMES));
318 set_video_frame_allocator(owned_video_frame_allocator.get());
320 if (audio_frame_allocator == nullptr) {
321 owned_audio_frame_allocator.reset(new MallocFrameAllocator(65536, NUM_QUEUED_AUDIO_FRAMES));
322 set_audio_frame_allocator(owned_audio_frame_allocator.get());
326 void DeckLinkCapture::start_bm_capture()
331 if (input->EnableVideoInput(current_video_mode, pixel_format_to_bmd(current_pixel_format), supports_autodetect ? bmdVideoInputEnableFormatDetection : 0) != S_OK) {
332 fprintf(stderr, "Failed to set video mode 0x%04x for card %d\n", current_video_mode, card_index);
335 if (input->EnableAudioInput(48000, bmdAudioSampleType32bitInteger, 8) != S_OK) {
336 fprintf(stderr, "Failed to enable audio input for card %d\n", card_index);
340 if (input->StartStreams() != S_OK) {
341 fprintf(stderr, "StartStreams failed\n");
347 void DeckLinkCapture::stop_dequeue_thread()
352 HRESULT result = input->StopStreams();
353 if (result != S_OK) {
354 fprintf(stderr, "StopStreams failed with error 0x%x\n", result);
358 // We could call DisableVideoInput() and DisableAudioInput() here,
359 // but they seem to be taking a really long time, and we only do this
360 // during shutdown anyway (except when switching to output mode,
361 // where DeckLinkOutput does the disabling), so StopStreams() will suffice.
366 void DeckLinkCapture::set_video_mode(uint32_t video_mode_id)
369 if (input->PauseStreams() != S_OK) {
370 fprintf(stderr, "PauseStreams failed\n");
373 if (input->FlushStreams() != S_OK) {
374 fprintf(stderr, "FlushStreams failed\n");
379 set_video_mode_no_restart(video_mode_id);
382 if (input->StartStreams() != S_OK) {
383 fprintf(stderr, "StartStreams failed\n");
389 void DeckLinkCapture::set_pixel_format(PixelFormat pixel_format)
391 current_pixel_format = pixel_format;
392 set_video_mode(current_video_mode);
395 void DeckLinkCapture::set_video_mode_no_restart(uint32_t video_mode_id)
397 BMDDisplayModeSupport support;
398 IDeckLinkDisplayMode *display_mode;
399 if (input->DoesSupportVideoMode(video_mode_id, pixel_format_to_bmd(current_pixel_format), /*flags=*/0, &support, &display_mode)) {
400 fprintf(stderr, "Failed to query display mode for card %d\n", card_index);
404 if (support == bmdDisplayModeNotSupported) {
405 fprintf(stderr, "Card %d does not support display mode\n", card_index);
409 if (display_mode->GetFrameRate(&frame_duration, &time_scale) != S_OK) {
410 fprintf(stderr, "Could not get frame rate for card %d\n", card_index);
414 field_dominance = display_mode->GetFieldDominance();
417 if (input->EnableVideoInput(video_mode_id, pixel_format_to_bmd(current_pixel_format), supports_autodetect ? bmdVideoInputEnableFormatDetection : 0) != S_OK) {
418 fprintf(stderr, "Failed to set video mode 0x%04x for card %d\n", video_mode_id, card_index);
423 current_video_mode = video_mode_id;
426 void DeckLinkCapture::set_video_input(uint32_t video_input_id)
428 if (config->SetInt(bmdDeckLinkConfigVideoInputConnection, video_input_id) != S_OK) {
429 fprintf(stderr, "Failed to set video input connection for card %d\n", card_index);
433 current_video_input = video_input_id;
436 void DeckLinkCapture::set_audio_input(uint32_t audio_input_id)
438 if (config->SetInt(bmdDeckLinkConfigAudioInputConnection, audio_input_id) != S_OK) {
439 fprintf(stderr, "Failed to set audio input connection for card %d\n", card_index);
443 current_audio_input = audio_input_id;