1 #include "decklink_capture.h"
3 #include <DeckLinkAPI.h>
4 #include <DeckLinkAPIConfiguration.h>
5 #include <DeckLinkAPIDiscovery.h>
6 #include <DeckLinkAPIModes.h>
21 #include "bmusb/bmusb.h"
22 #include "decklink_util.h"
24 #include "shared/memcpy_interleaved.h"
25 #include "v210_converter.h"
28 using namespace std::chrono;
29 using namespace std::placeholders;
30 using namespace bmusb;
34 BMDPixelFormat pixel_format_to_bmd(PixelFormat pixel_format)
36 switch (pixel_format) {
37 case PixelFormat_8BitYCbCr:
38 return bmdFormat8BitYUV;
39 case PixelFormat_10BitYCbCr:
40 return bmdFormat10BitYUV;
48 DeckLinkCapture::DeckLinkCapture(IDeckLink *card, int card_index)
49 : card_index(card_index), card(card)
52 const char *model_name;
54 if (card->GetModelName(&model_name) == S_OK) {
55 snprintf(buf, sizeof(buf), "PCI card %d: %s", card_index, model_name);
57 snprintf(buf, sizeof(buf), "PCI card %d: Unknown DeckLink card", card_index);
62 if (card->QueryInterface(IID_IDeckLinkInput, (void**)&input) != S_OK) {
63 fprintf(stderr, "Card %d has no inputs\n", card_index);
67 IDeckLinkAttributes *attr;
68 if (card->QueryInterface(IID_IDeckLinkAttributes, (void**)&attr) != S_OK) {
69 fprintf(stderr, "Card %d has no attributes\n", card_index);
73 // Get the list of available video inputs.
74 int64_t video_input_mask;
75 if (attr->GetInt(BMDDeckLinkVideoInputConnections, &video_input_mask) != S_OK) {
76 fprintf(stderr, "Failed to enumerate video inputs for card %d\n", card_index);
79 const vector<pair<BMDVideoConnection, string>> video_input_types = {
80 { bmdVideoConnectionSDI, "SDI" },
81 { bmdVideoConnectionHDMI, "HDMI" },
82 { bmdVideoConnectionOpticalSDI, "Optical SDI" },
83 { bmdVideoConnectionComponent, "Component" },
84 { bmdVideoConnectionComposite, "Composite" },
85 { bmdVideoConnectionSVideo, "S-Video" }
87 for (const auto &video_input : video_input_types) {
88 if (video_input_mask & video_input.first) {
89 video_inputs.emplace(video_input.first, video_input.second);
93 // And then the available audio inputs.
94 int64_t audio_input_mask;
95 if (attr->GetInt(BMDDeckLinkAudioInputConnections, &audio_input_mask) != S_OK) {
96 fprintf(stderr, "Failed to enumerate audio inputs for card %d\n", card_index);
99 const vector<pair<BMDAudioConnection, string>> audio_input_types = {
100 { bmdAudioConnectionEmbedded, "Embedded" },
101 { bmdAudioConnectionAESEBU, "AES/EBU" },
102 { bmdAudioConnectionAnalog, "Analog" },
103 { bmdAudioConnectionAnalogXLR, "Analog XLR" },
104 { bmdAudioConnectionAnalogRCA, "Analog RCA" },
105 { bmdAudioConnectionMicrophone, "Microphone" },
106 { bmdAudioConnectionHeadphones, "Headphones" }
108 for (const auto &audio_input : audio_input_types) {
109 if (audio_input_mask & audio_input.first) {
110 audio_inputs.emplace(audio_input.first, audio_input.second);
114 // Check if we the card supports input autodetection.
115 if (attr->GetFlag(BMDDeckLinkSupportsInputFormatDetection, &supports_autodetect) != S_OK) {
116 fprintf(stderr, "Warning: Failed to ask card %d whether it supports input format autodetection\n", card_index);
117 supports_autodetect = false;
120 // If there's more than one subdevice on this card, label them.
121 int64_t num_subdevices, subdevice_idx;
122 if (attr->GetInt(BMDDeckLinkNumberOfSubDevices, &num_subdevices) == S_OK && num_subdevices > 1) {
123 if (attr->GetInt(BMDDeckLinkSubDeviceIndex, &subdevice_idx) == S_OK) {
125 snprintf(buf, sizeof(buf), " (subdevice %d)", int(subdevice_idx));
132 /* Set up the video and audio sources. */
133 if (card->QueryInterface(IID_IDeckLinkConfiguration, (void**)&config) != S_OK) {
134 fprintf(stderr, "Failed to get configuration interface for card %d\n", card_index);
138 BMDVideoConnection connection = pick_default_video_connection(card, BMDDeckLinkVideoInputConnections, card_index);
140 set_video_input(connection);
141 set_audio_input(bmdAudioConnectionEmbedded);
143 IDeckLinkDisplayModeIterator *mode_it;
144 if (input->GetDisplayModeIterator(&mode_it) != S_OK) {
145 fprintf(stderr, "Failed to enumerate display modes for card %d\n", card_index);
149 video_modes = summarize_video_modes(mode_it, card_index);
152 set_video_mode_no_restart(bmdModeHD720p5994);
154 input->SetCallback(this);
157 DeckLinkCapture::~DeckLinkCapture()
159 if (has_dequeue_callbacks) {
160 dequeue_cleanup_callback();
167 HRESULT STDMETHODCALLTYPE DeckLinkCapture::QueryInterface(REFIID, LPVOID *)
169 return E_NOINTERFACE;
172 ULONG STDMETHODCALLTYPE DeckLinkCapture::AddRef(void)
174 return refcount.fetch_add(1) + 1;
177 ULONG STDMETHODCALLTYPE DeckLinkCapture::Release(void)
179 int new_ref = refcount.fetch_sub(1) - 1;
185 HRESULT STDMETHODCALLTYPE DeckLinkCapture::VideoInputFormatChanged(
186 BMDVideoInputFormatChangedEvents,
187 IDeckLinkDisplayMode* display_mode,
188 BMDDetectedVideoInputFormatFlags format_flags)
190 if (format_flags & bmdDetectedVideoInputRGB444) {
191 fprintf(stderr, "WARNING: Input detected as 4:4:4 RGB, but Nageru can't consume that yet.\n");
192 fprintf(stderr, "Doing hardware conversion to 4:2:2 Y'CbCr.\n");
194 if (supports_autodetect && display_mode->GetDisplayMode() != current_video_mode) {
195 set_video_mode(display_mode->GetDisplayMode());
197 if (display_mode->GetFrameRate(&frame_duration, &time_scale) != S_OK) {
198 fprintf(stderr, "Could not get new frame rate\n");
201 field_dominance = display_mode->GetFieldDominance();
205 HRESULT STDMETHODCALLTYPE DeckLinkCapture::VideoInputFrameArrived(
206 IDeckLinkVideoInputFrame *video_frame,
207 IDeckLinkAudioInputPacket *audio_frame)
210 char thread_name[16];
211 snprintf(thread_name, sizeof(thread_name), "DeckLink_C_%d", card_index);
212 pthread_setname_np(pthread_self(), thread_name);
215 memset(¶m, 0, sizeof(param));
216 param.sched_priority = 1;
217 if (sched_setscheduler(0, SCHED_RR, ¶m) == -1) {
218 printf("couldn't set realtime priority for DeckLink thread: %s\n", strerror(errno));
221 if (has_dequeue_callbacks) {
222 dequeue_init_callback();
227 steady_clock::time_point now = steady_clock::now();
229 FrameAllocator::Frame current_video_frame, current_audio_frame;
230 VideoFormat video_format;
231 AudioFormat audio_format;
233 video_format.frame_rate_nom = time_scale;
234 video_format.frame_rate_den = frame_duration;
235 // TODO: Respect the TFF/BFF flag.
236 video_format.interlaced = (field_dominance == bmdLowerFieldFirst || field_dominance == bmdUpperFieldFirst);
237 video_format.second_field_start = 1;
240 video_format.has_signal = !(video_frame->GetFlags() & bmdFrameHasNoInputSource);
242 const int width = video_frame->GetWidth();
243 const int height = video_frame->GetHeight();
244 const int stride = video_frame->GetRowBytes();
245 const BMDPixelFormat format = video_frame->GetPixelFormat();
246 assert(format == pixel_format_to_bmd(current_pixel_format));
247 if (global_flags.bit_depth > 8) {
248 assert(stride == int(v210Converter::get_v210_stride(width)));
250 assert(stride == width * 2);
253 current_video_frame = video_frame_allocator->create_frame(width, height, stride);
254 if (current_video_frame.data != nullptr) {
256 video_frame->GetBytes((void **)&src);
257 size_t num_bytes = stride * height;
259 if (current_video_frame.interleaved) {
260 uint8_t *data = current_video_frame.data;
261 uint8_t *data2 = current_video_frame.data2;
262 memcpy_interleaved(data, data2, src, num_bytes);
264 memcpy(current_video_frame.data, src, num_bytes);
266 if (current_video_frame.data_copy != nullptr) {
267 memcpy(current_video_frame.data_copy, src, num_bytes);
269 current_video_frame.len += num_bytes;
271 video_format.width = width;
272 video_format.height = height;
273 video_format.stride = stride;
278 int num_samples = audio_frame->GetSampleFrameCount();
280 current_audio_frame = audio_frame_allocator->alloc_frame();
281 if (current_audio_frame.data != nullptr) {
283 audio_frame->GetBytes((void **)&src);
284 current_audio_frame.len = sizeof(int32_t) * 8 * num_samples;
286 memcpy(current_audio_frame.data, src, current_audio_frame.len);
288 audio_format.bits_per_sample = 32;
289 audio_format.num_channels = 8;
293 current_video_frame.received_timestamp = now;
294 current_audio_frame.received_timestamp = now;
296 if (current_video_frame.data != nullptr || current_audio_frame.data != nullptr) {
297 // TODO: Put into a queue and put into a dequeue thread, if the
298 // BlackMagic drivers don't already do that for us?
299 frame_callback(timecode,
300 current_video_frame, /*video_offset=*/0, video_format,
301 current_audio_frame, /*audio_offset=*/0, audio_format);
308 void DeckLinkCapture::configure_card()
310 if (video_frame_allocator == nullptr) {
311 owned_video_frame_allocator.reset(new MallocFrameAllocator(FRAME_SIZE, NUM_QUEUED_VIDEO_FRAMES));
312 set_video_frame_allocator(owned_video_frame_allocator.get());
314 if (audio_frame_allocator == nullptr) {
315 owned_audio_frame_allocator.reset(new MallocFrameAllocator(65536, NUM_QUEUED_AUDIO_FRAMES));
316 set_audio_frame_allocator(owned_audio_frame_allocator.get());
320 void DeckLinkCapture::start_bm_capture()
325 if (input->EnableVideoInput(current_video_mode, pixel_format_to_bmd(current_pixel_format), supports_autodetect ? bmdVideoInputEnableFormatDetection : 0) != S_OK) {
326 fprintf(stderr, "Failed to set video mode 0x%04x for card %d\n", current_video_mode, card_index);
329 if (input->EnableAudioInput(48000, bmdAudioSampleType32bitInteger, 8) != S_OK) {
330 fprintf(stderr, "Failed to enable audio input for card %d\n", card_index);
334 if (input->StartStreams() != S_OK) {
335 fprintf(stderr, "StartStreams failed\n");
341 void DeckLinkCapture::stop_dequeue_thread()
346 HRESULT result = input->StopStreams();
347 if (result != S_OK) {
348 fprintf(stderr, "StopStreams failed with error 0x%x\n", result);
352 // We could call DisableVideoInput() and DisableAudioInput() here,
353 // but they seem to be taking a really long time, and we only do this
354 // during shutdown anyway (except when switching to output mode,
355 // where DeckLinkOutput does the disabling), so StopStreams() will suffice.
360 void DeckLinkCapture::set_video_mode(uint32_t video_mode_id)
363 if (input->PauseStreams() != S_OK) {
364 fprintf(stderr, "PauseStreams failed\n");
367 if (input->FlushStreams() != S_OK) {
368 fprintf(stderr, "FlushStreams failed\n");
373 set_video_mode_no_restart(video_mode_id);
376 if (input->StartStreams() != S_OK) {
377 fprintf(stderr, "StartStreams failed\n");
383 void DeckLinkCapture::set_pixel_format(PixelFormat pixel_format)
385 current_pixel_format = pixel_format;
386 set_video_mode(current_video_mode);
389 void DeckLinkCapture::set_video_mode_no_restart(uint32_t video_mode_id)
391 BMDDisplayModeSupport support;
392 IDeckLinkDisplayMode *display_mode;
393 if (input->DoesSupportVideoMode(video_mode_id, pixel_format_to_bmd(current_pixel_format), /*flags=*/0, &support, &display_mode)) {
394 fprintf(stderr, "Failed to query display mode for card %d\n", card_index);
398 if (support == bmdDisplayModeNotSupported) {
399 fprintf(stderr, "Card %d does not support display mode\n", card_index);
403 if (display_mode->GetFrameRate(&frame_duration, &time_scale) != S_OK) {
404 fprintf(stderr, "Could not get frame rate for card %d\n", card_index);
408 field_dominance = display_mode->GetFieldDominance();
411 if (input->EnableVideoInput(video_mode_id, pixel_format_to_bmd(current_pixel_format), supports_autodetect ? bmdVideoInputEnableFormatDetection : 0) != S_OK) {
412 fprintf(stderr, "Failed to set video mode 0x%04x for card %d\n", video_mode_id, card_index);
417 current_video_mode = video_mode_id;
420 void DeckLinkCapture::set_video_input(uint32_t video_input_id)
422 if (config->SetInt(bmdDeckLinkConfigVideoInputConnection, video_input_id) != S_OK) {
423 fprintf(stderr, "Failed to set video input connection for card %d\n", card_index);
427 current_video_input = video_input_id;
430 void DeckLinkCapture::set_audio_input(uint32_t audio_input_id)
432 if (config->SetInt(bmdDeckLinkConfigAudioInputConnection, audio_input_id) != S_OK) {
433 fprintf(stderr, "Failed to set audio input connection for card %d\n", card_index);
437 current_audio_input = audio_input_id;