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"
27 #define FRAME_SIZE (8 << 20) // 8 MB.
30 using namespace std::chrono;
31 using namespace std::placeholders;
32 using namespace bmusb;
36 BMDPixelFormat pixel_format_to_bmd(PixelFormat pixel_format)
38 switch (pixel_format) {
39 case PixelFormat_8BitYCbCr:
40 return bmdFormat8BitYUV;
41 case PixelFormat_10BitYCbCr:
42 return bmdFormat10BitYUV;
50 DeckLinkCapture::DeckLinkCapture(IDeckLink *card, int card_index)
51 : card_index(card_index), card(card)
54 const char *model_name;
56 if (card->GetModelName(&model_name) == S_OK) {
57 snprintf(buf, sizeof(buf), "PCI card %d: %s", card_index, model_name);
59 snprintf(buf, sizeof(buf), "PCI card %d: Unknown DeckLink card", card_index);
64 if (card->QueryInterface(IID_IDeckLinkInput, (void**)&input) != S_OK) {
65 fprintf(stderr, "Card %d has no inputs\n", card_index);
69 IDeckLinkAttributes *attr;
70 if (card->QueryInterface(IID_IDeckLinkAttributes, (void**)&attr) != S_OK) {
71 fprintf(stderr, "Card %d has no attributes\n", card_index);
75 // Get the list of available video inputs.
76 int64_t video_input_mask;
77 if (attr->GetInt(BMDDeckLinkVideoInputConnections, &video_input_mask) != S_OK) {
78 fprintf(stderr, "Failed to enumerate video inputs for card %d\n", card_index);
81 const vector<pair<BMDVideoConnection, string>> video_input_types = {
82 { bmdVideoConnectionSDI, "SDI" },
83 { bmdVideoConnectionHDMI, "HDMI" },
84 { bmdVideoConnectionOpticalSDI, "Optical SDI" },
85 { bmdVideoConnectionComponent, "Component" },
86 { bmdVideoConnectionComposite, "Composite" },
87 { bmdVideoConnectionSVideo, "S-Video" }
89 for (const auto &video_input : video_input_types) {
90 if (video_input_mask & video_input.first) {
91 video_inputs.emplace(video_input.first, video_input.second);
95 // And then the available audio inputs.
96 int64_t audio_input_mask;
97 if (attr->GetInt(BMDDeckLinkAudioInputConnections, &audio_input_mask) != S_OK) {
98 fprintf(stderr, "Failed to enumerate audio inputs for card %d\n", card_index);
101 const vector<pair<BMDAudioConnection, string>> audio_input_types = {
102 { bmdAudioConnectionEmbedded, "Embedded" },
103 { bmdAudioConnectionAESEBU, "AES/EBU" },
104 { bmdAudioConnectionAnalog, "Analog" },
105 { bmdAudioConnectionAnalogXLR, "Analog XLR" },
106 { bmdAudioConnectionAnalogRCA, "Analog RCA" },
107 { bmdAudioConnectionMicrophone, "Microphone" },
108 { bmdAudioConnectionHeadphones, "Headphones" }
110 for (const auto &audio_input : audio_input_types) {
111 if (audio_input_mask & audio_input.first) {
112 audio_inputs.emplace(audio_input.first, audio_input.second);
116 // Check if we the card supports input autodetection.
117 if (attr->GetFlag(BMDDeckLinkSupportsInputFormatDetection, &supports_autodetect) != S_OK) {
118 fprintf(stderr, "Warning: Failed to ask card %d whether it supports input format autodetection\n", card_index);
119 supports_autodetect = false;
122 // If there's more than one subdevice on this card, label them.
123 int64_t num_subdevices, subdevice_idx;
124 if (attr->GetInt(BMDDeckLinkNumberOfSubDevices, &num_subdevices) == S_OK && num_subdevices > 1) {
125 if (attr->GetInt(BMDDeckLinkSubDeviceIndex, &subdevice_idx) == S_OK) {
127 snprintf(buf, sizeof(buf), " (subdevice %d)", int(subdevice_idx));
134 /* Set up the video and audio sources. */
135 if (card->QueryInterface(IID_IDeckLinkConfiguration, (void**)&config) != S_OK) {
136 fprintf(stderr, "Failed to get configuration interface for card %d\n", card_index);
140 BMDVideoConnection connection = pick_default_video_connection(card, BMDDeckLinkVideoInputConnections, card_index);
142 set_video_input(connection);
143 set_audio_input(bmdAudioConnectionEmbedded);
145 IDeckLinkDisplayModeIterator *mode_it;
146 if (input->GetDisplayModeIterator(&mode_it) != S_OK) {
147 fprintf(stderr, "Failed to enumerate display modes for card %d\n", card_index);
151 video_modes = summarize_video_modes(mode_it, card_index);
154 set_video_mode_no_restart(bmdModeHD720p5994);
156 input->SetCallback(this);
159 DeckLinkCapture::~DeckLinkCapture()
161 if (has_dequeue_callbacks) {
162 dequeue_cleanup_callback();
169 HRESULT STDMETHODCALLTYPE DeckLinkCapture::QueryInterface(REFIID, LPVOID *)
171 return E_NOINTERFACE;
174 ULONG STDMETHODCALLTYPE DeckLinkCapture::AddRef(void)
176 return refcount.fetch_add(1) + 1;
179 ULONG STDMETHODCALLTYPE DeckLinkCapture::Release(void)
181 int new_ref = refcount.fetch_sub(1) - 1;
187 HRESULT STDMETHODCALLTYPE DeckLinkCapture::VideoInputFormatChanged(
188 BMDVideoInputFormatChangedEvents,
189 IDeckLinkDisplayMode* display_mode,
190 BMDDetectedVideoInputFormatFlags format_flags)
192 if (format_flags & bmdDetectedVideoInputRGB444) {
193 fprintf(stderr, "WARNING: Input detected as 4:4:4 RGB, but Nageru can't consume that yet.\n");
194 fprintf(stderr, "Doing hardware conversion to 4:2:2 Y'CbCr.\n");
196 if (supports_autodetect && display_mode->GetDisplayMode() != current_video_mode) {
197 set_video_mode(display_mode->GetDisplayMode());
199 if (display_mode->GetFrameRate(&frame_duration, &time_scale) != S_OK) {
200 fprintf(stderr, "Could not get new frame rate\n");
203 field_dominance = display_mode->GetFieldDominance();
207 HRESULT STDMETHODCALLTYPE DeckLinkCapture::VideoInputFrameArrived(
208 IDeckLinkVideoInputFrame *video_frame,
209 IDeckLinkAudioInputPacket *audio_frame)
212 char thread_name[16];
213 snprintf(thread_name, sizeof(thread_name), "DeckLink_C_%d", card_index);
214 pthread_setname_np(pthread_self(), thread_name);
217 memset(¶m, 0, sizeof(param));
218 param.sched_priority = 1;
219 if (sched_setscheduler(0, SCHED_RR, ¶m) == -1) {
220 printf("couldn't set realtime priority for DeckLink thread: %s\n", strerror(errno));
223 if (has_dequeue_callbacks) {
224 dequeue_init_callback();
229 steady_clock::time_point now = steady_clock::now();
231 FrameAllocator::Frame current_video_frame, current_audio_frame;
232 VideoFormat video_format;
233 AudioFormat audio_format;
235 video_format.frame_rate_nom = time_scale;
236 video_format.frame_rate_den = frame_duration;
237 // TODO: Respect the TFF/BFF flag.
238 video_format.interlaced = (field_dominance == bmdLowerFieldFirst || field_dominance == bmdUpperFieldFirst);
239 video_format.second_field_start = 1;
242 video_format.has_signal = !(video_frame->GetFlags() & bmdFrameHasNoInputSource);
244 const int width = video_frame->GetWidth();
245 const int height = video_frame->GetHeight();
246 const int stride = video_frame->GetRowBytes();
247 const BMDPixelFormat format = video_frame->GetPixelFormat();
248 assert(format == pixel_format_to_bmd(current_pixel_format));
249 if (global_flags.ten_bit_input) {
250 assert(stride == int(v210Converter::get_v210_stride(width)));
252 assert(stride == width * 2);
255 current_video_frame = video_frame_allocator->create_frame(width, height, stride);
256 if (current_video_frame.data != nullptr) {
258 video_frame->GetBytes((void **)&src);
259 size_t num_bytes = stride * height;
261 if (current_video_frame.interleaved) {
262 uint8_t *data = current_video_frame.data;
263 uint8_t *data2 = current_video_frame.data2;
264 memcpy_interleaved(data, data2, src, num_bytes);
266 memcpy(current_video_frame.data, src, num_bytes);
268 if (current_video_frame.data_copy != nullptr) {
269 memcpy(current_video_frame.data_copy, src, num_bytes);
271 current_video_frame.len += num_bytes;
273 video_format.width = width;
274 video_format.height = height;
275 video_format.stride = stride;
280 int num_samples = audio_frame->GetSampleFrameCount();
282 current_audio_frame = audio_frame_allocator->alloc_frame();
283 if (current_audio_frame.data != nullptr) {
285 audio_frame->GetBytes((void **)&src);
286 current_audio_frame.len = sizeof(int32_t) * 8 * num_samples;
288 memcpy(current_audio_frame.data, src, current_audio_frame.len);
290 audio_format.bits_per_sample = 32;
291 audio_format.num_channels = 8;
295 current_video_frame.received_timestamp = now;
296 current_audio_frame.received_timestamp = now;
298 if (current_video_frame.data != nullptr || current_audio_frame.data != nullptr) {
299 // TODO: Put into a queue and put into a dequeue thread, if the
300 // BlackMagic drivers don't already do that for us?
301 frame_callback(timecode,
302 current_video_frame, /*video_offset=*/0, video_format,
303 current_audio_frame, /*audio_offset=*/0, audio_format);
310 void DeckLinkCapture::configure_card()
312 if (video_frame_allocator == nullptr) {
313 owned_video_frame_allocator.reset(new MallocFrameAllocator(FRAME_SIZE, NUM_QUEUED_VIDEO_FRAMES));
314 set_video_frame_allocator(owned_video_frame_allocator.get());
316 if (audio_frame_allocator == nullptr) {
317 owned_audio_frame_allocator.reset(new MallocFrameAllocator(65536, NUM_QUEUED_AUDIO_FRAMES));
318 set_audio_frame_allocator(owned_audio_frame_allocator.get());
322 void DeckLinkCapture::start_bm_capture()
327 if (input->EnableVideoInput(current_video_mode, pixel_format_to_bmd(current_pixel_format), supports_autodetect ? bmdVideoInputEnableFormatDetection : 0) != S_OK) {
328 fprintf(stderr, "Failed to set video mode 0x%04x for card %d\n", current_video_mode, card_index);
331 if (input->EnableAudioInput(48000, bmdAudioSampleType32bitInteger, 8) != S_OK) {
332 fprintf(stderr, "Failed to enable audio input for card %d\n", card_index);
336 if (input->StartStreams() != S_OK) {
337 fprintf(stderr, "StartStreams failed\n");
343 void DeckLinkCapture::stop_dequeue_thread()
348 HRESULT result = input->StopStreams();
349 if (result != S_OK) {
350 fprintf(stderr, "StopStreams failed with error 0x%x\n", result);
353 if (input->DisableVideoInput() != S_OK) {
354 fprintf(stderr, "Failed to disable video input for card %d\n", card_index);
357 if (input->DisableAudioInput() != S_OK) {
358 fprintf(stderr, "Failed to disable audio input for card %d\n", card_index);
364 void DeckLinkCapture::set_video_mode(uint32_t video_mode_id)
367 if (input->PauseStreams() != S_OK) {
368 fprintf(stderr, "PauseStreams failed\n");
371 if (input->FlushStreams() != S_OK) {
372 fprintf(stderr, "FlushStreams failed\n");
377 set_video_mode_no_restart(video_mode_id);
380 if (input->StartStreams() != S_OK) {
381 fprintf(stderr, "StartStreams failed\n");
387 void DeckLinkCapture::set_pixel_format(PixelFormat pixel_format)
389 current_pixel_format = pixel_format;
390 set_video_mode(current_video_mode);
393 void DeckLinkCapture::set_video_mode_no_restart(uint32_t video_mode_id)
395 BMDDisplayModeSupport support;
396 IDeckLinkDisplayMode *display_mode;
397 if (input->DoesSupportVideoMode(video_mode_id, pixel_format_to_bmd(current_pixel_format), /*flags=*/0, &support, &display_mode)) {
398 fprintf(stderr, "Failed to query display mode for card %d\n", card_index);
402 if (support == bmdDisplayModeNotSupported) {
403 fprintf(stderr, "Card %d does not support display mode\n", card_index);
407 if (display_mode->GetFrameRate(&frame_duration, &time_scale) != S_OK) {
408 fprintf(stderr, "Could not get frame rate for card %d\n", card_index);
412 field_dominance = display_mode->GetFieldDominance();
415 if (input->EnableVideoInput(video_mode_id, pixel_format_to_bmd(current_pixel_format), supports_autodetect ? bmdVideoInputEnableFormatDetection : 0) != S_OK) {
416 fprintf(stderr, "Failed to set video mode 0x%04x for card %d\n", video_mode_id, card_index);
421 current_video_mode = video_mode_id;
424 void DeckLinkCapture::set_video_input(uint32_t video_input_id)
426 if (config->SetInt(bmdDeckLinkConfigVideoInputConnection, video_input_id) != S_OK) {
427 fprintf(stderr, "Failed to set video input connection for card %d\n", card_index);
431 current_video_input = video_input_id;
434 void DeckLinkCapture::set_audio_input(uint32_t audio_input_id)
436 if (config->SetInt(bmdDeckLinkConfigAudioInputConnection, audio_input_id) != S_OK) {
437 fprintf(stderr, "Failed to set audio input connection for card %d\n", card_index);
441 current_audio_input = audio_input_id;