1 #include "decklink_capture.h"
10 #include <immintrin.h>
13 #include <DeckLinkAPI.h>
14 #include <DeckLinkAPIConfiguration.h>
15 #include <DeckLinkAPIDiscovery.h>
16 #include <DeckLinkAPIModes.h>
17 #include "bmusb/bmusb.h"
19 #define FRAME_SIZE (8 << 20) // 8 MB.
22 using namespace std::placeholders;
23 using namespace bmusb;
27 // TODO: Support stride.
28 void memcpy_interleaved(uint8_t *dest1, uint8_t *dest2, const uint8_t *src, size_t n)
31 uint8_t *dptr1 = dest1;
32 uint8_t *dptr2 = dest2;
34 for (size_t i = 0; i < n; i += 2) {
42 // Returns the number of bytes consumed.
43 size_t memcpy_interleaved_fastpath(uint8_t *dest1, uint8_t *dest2, const uint8_t *src, size_t n)
45 const uint8_t *limit = src + n;
48 // Align end to 32 bytes.
49 limit = (const uint8_t *)(intptr_t(limit) & ~31);
55 // Process [0,31] bytes, such that start gets aligned to 32 bytes.
56 const uint8_t *aligned_src = (const uint8_t *)(intptr_t(src + 31) & ~31);
57 if (aligned_src != src) {
58 size_t n2 = aligned_src - src;
59 memcpy_interleaved(dest1, dest2, src, n2);
69 // Make the length a multiple of 64.
70 if (((limit - src) % 64) != 0) {
73 assert(((limit - src) % 64) == 0);
76 const __m256i * __restrict in = (const __m256i *)src;
77 __m256i * __restrict out1 = (__m256i *)dest1;
78 __m256i * __restrict out2 = (__m256i *)dest2;
80 __m256i shuffle_cw = _mm256_set_epi8(
81 15, 13, 11, 9, 7, 5, 3, 1, 14, 12, 10, 8, 6, 4, 2, 0,
82 15, 13, 11, 9, 7, 5, 3, 1, 14, 12, 10, 8, 6, 4, 2, 0);
83 while (in < (const __m256i *)limit) {
84 // Note: For brevity, comments show lanes as if they were 2x64-bit (they're actually 2x128).
85 __m256i data1 = _mm256_stream_load_si256(in); // AaBbCcDd EeFfGgHh
86 __m256i data2 = _mm256_stream_load_si256(in + 1); // IiJjKkLl MmNnOoPp
88 data1 = _mm256_shuffle_epi8(data1, shuffle_cw); // ABCDabcd EFGHefgh
89 data2 = _mm256_shuffle_epi8(data2, shuffle_cw); // IJKLijkl MNOPmnop
91 data1 = _mm256_permute4x64_epi64(data1, 0b11011000); // ABCDEFGH abcdefgh
92 data2 = _mm256_permute4x64_epi64(data2, 0b11011000); // IJKLMNOP ijklmnop
94 __m256i lo = _mm256_permute2x128_si256(data1, data2, 0b00100000);
95 __m256i hi = _mm256_permute2x128_si256(data1, data2, 0b00110001);
97 _mm256_storeu_si256(out1, lo);
98 _mm256_storeu_si256(out2, hi);
106 const __m128i * __restrict in = (const __m128i *)src;
107 __m128i * __restrict out1 = (__m128i *)dest1;
108 __m128i * __restrict out2 = (__m128i *)dest2;
110 __m128i mask_lower_byte = _mm_set1_epi16(0x00ff);
111 while (in < (const __m128i *)limit) {
112 __m128i data1 = _mm_load_si128(in);
113 __m128i data2 = _mm_load_si128(in + 1);
114 __m128i data1_lo = _mm_and_si128(data1, mask_lower_byte);
115 __m128i data2_lo = _mm_and_si128(data2, mask_lower_byte);
116 __m128i data1_hi = _mm_srli_epi16(data1, 8);
117 __m128i data2_hi = _mm_srli_epi16(data2, 8);
118 __m128i lo = _mm_packus_epi16(data1_lo, data2_lo);
119 _mm_storeu_si128(out1, lo);
120 __m128i hi = _mm_packus_epi16(data1_hi, data2_hi);
121 _mm_storeu_si128(out2, hi);
137 DeckLinkCapture::DeckLinkCapture(IDeckLink *card, int card_index)
138 : card_index(card_index), card(card)
141 const char *model_name;
143 if (card->GetModelName(&model_name) == S_OK) {
144 snprintf(buf, sizeof(buf), "PCI card %d: %s", card_index, model_name);
146 snprintf(buf, sizeof(buf), "PCI card %d: Unknown DeckLink card", card_index);
151 if (card->QueryInterface(IID_IDeckLinkInput, (void**)&input) != S_OK) {
152 fprintf(stderr, "Card %d has no inputs\n", card_index);
156 IDeckLinkAttributes *attr;
157 if (card->QueryInterface(IID_IDeckLinkAttributes, (void**)&attr) != S_OK) {
158 fprintf(stderr, "Card %d has no attributes\n", card_index);
162 // Get the list of available video inputs.
163 int64_t video_input_mask;
164 if (attr->GetInt(BMDDeckLinkVideoInputConnections, &video_input_mask) != S_OK) {
165 fprintf(stderr, "Failed to enumerate video inputs for card %d\n", card_index);
168 const vector<pair<BMDVideoConnection, string>> video_input_types = {
169 { bmdVideoConnectionSDI, "SDI" },
170 { bmdVideoConnectionHDMI, "HDMI" },
171 { bmdVideoConnectionOpticalSDI, "Optical SDI" },
172 { bmdVideoConnectionComponent, "Component" },
173 { bmdVideoConnectionComposite, "Composite" },
174 { bmdVideoConnectionSVideo, "S-Video" }
176 for (const auto &video_input : video_input_types) {
177 if (video_input_mask & video_input.first) {
178 video_inputs.emplace(video_input.first, video_input.second);
182 // And then the available audio inputs.
183 int64_t audio_input_mask;
184 if (attr->GetInt(BMDDeckLinkAudioInputConnections, &audio_input_mask) != S_OK) {
185 fprintf(stderr, "Failed to enumerate audio inputs for card %d\n", card_index);
188 const vector<pair<BMDAudioConnection, string>> audio_input_types = {
189 { bmdAudioConnectionEmbedded, "Embedded" },
190 { bmdAudioConnectionAESEBU, "AES/EBU" },
191 { bmdAudioConnectionAnalog, "Analog" },
192 { bmdAudioConnectionAnalogXLR, "Analog XLR" },
193 { bmdAudioConnectionAnalogRCA, "Analog RCA" },
194 { bmdAudioConnectionMicrophone, "Microphone" },
195 { bmdAudioConnectionHeadphones, "Headphones" }
197 for (const auto &audio_input : audio_input_types) {
198 if (audio_input_mask & audio_input.first) {
199 audio_inputs.emplace(audio_input.first, audio_input.second);
205 /* Set up the video and audio sources. */
206 if (card->QueryInterface(IID_IDeckLinkConfiguration, (void**)&config) != S_OK) {
207 fprintf(stderr, "Failed to get configuration interface for card %d\n", card_index);
211 set_video_input(bmdVideoConnectionHDMI);
212 set_audio_input(bmdAudioConnectionEmbedded);
214 IDeckLinkDisplayModeIterator *mode_it;
215 if (input->GetDisplayModeIterator(&mode_it) != S_OK) {
216 fprintf(stderr, "Failed to enumerate display modes for card %d\n", card_index);
220 for (IDeckLinkDisplayMode *mode_ptr; mode_it->Next(&mode_ptr) == S_OK; mode_ptr->Release()) {
223 const char *mode_name;
224 if (mode_ptr->GetName(&mode_name) != S_OK) {
225 mode.name = "Unknown mode";
227 mode.name = mode_name;
230 mode.autodetect = false;
232 mode.width = mode_ptr->GetWidth();
233 mode.height = mode_ptr->GetHeight();
235 BMDTimeScale frame_rate_num;
236 BMDTimeValue frame_rate_den;
237 if (mode_ptr->GetFrameRate(&frame_rate_den, &frame_rate_num) != S_OK) {
238 fprintf(stderr, "Could not get frame rate for mode '%s' on card %d\n", mode.name.c_str(), card_index);
241 mode.frame_rate_num = frame_rate_num;
242 mode.frame_rate_den = frame_rate_den;
244 // TODO: Respect the TFF/BFF flag.
245 mode.interlaced = (mode_ptr->GetFieldDominance() == bmdLowerFieldFirst || mode_ptr->GetFieldDominance() == bmdUpperFieldFirst);
247 uint32_t id = mode_ptr->GetDisplayMode();
248 video_modes.insert(make_pair(id, mode));
251 set_video_mode_no_restart(bmdModeHD720p5994);
253 if (input->EnableAudioInput(48000, bmdAudioSampleType32bitInteger, 2) != S_OK) {
254 fprintf(stderr, "Failed to enable audio input for card %d\n", card_index);
258 input->SetCallback(this);
261 DeckLinkCapture::~DeckLinkCapture()
263 if (has_dequeue_callbacks) {
264 dequeue_cleanup_callback();
271 HRESULT STDMETHODCALLTYPE DeckLinkCapture::QueryInterface(REFIID, LPVOID *)
273 return E_NOINTERFACE;
276 ULONG STDMETHODCALLTYPE DeckLinkCapture::AddRef(void)
278 return refcount.fetch_add(1) + 1;
281 ULONG STDMETHODCALLTYPE DeckLinkCapture::Release(void)
283 int new_ref = refcount.fetch_sub(1) - 1;
289 HRESULT STDMETHODCALLTYPE DeckLinkCapture::VideoInputFormatChanged(
290 BMDVideoInputFormatChangedEvents,
291 IDeckLinkDisplayMode* display_mode,
292 BMDDetectedVideoInputFormatFlags)
294 if (display_mode->GetFrameRate(&frame_duration, &time_scale) != S_OK) {
295 fprintf(stderr, "Could not get new frame rate\n");
301 HRESULT STDMETHODCALLTYPE DeckLinkCapture::VideoInputFrameArrived(
302 IDeckLinkVideoInputFrame *video_frame,
303 IDeckLinkAudioInputPacket *audio_frame)
306 if (has_dequeue_callbacks) {
307 dequeue_init_callback();
312 FrameAllocator::Frame current_video_frame, current_audio_frame;
313 VideoFormat video_format;
314 AudioFormat audio_format;
316 video_format.frame_rate_nom = time_scale;
317 video_format.frame_rate_den = frame_duration;
320 video_format.has_signal = !(video_frame->GetFlags() & bmdFrameHasNoInputSource);
322 int width = video_frame->GetWidth();
323 int height = video_frame->GetHeight();
324 const int stride = video_frame->GetRowBytes();
325 assert(stride == width * 2);
327 current_video_frame = video_frame_allocator->alloc_frame();
328 if (current_video_frame.data != nullptr) {
329 const uint8_t *frame_bytes;
330 video_frame->GetBytes((void **)&frame_bytes);
332 uint8_t *data = current_video_frame.data;
333 uint8_t *data2 = current_video_frame.data2;
334 size_t num_bytes = width * height * 2;
336 size_t consumed = memcpy_interleaved_fastpath(data, data2, frame_bytes, num_bytes);
337 frame_bytes += consumed;
338 data += consumed / 2;
339 data2 += consumed / 2;
343 current_video_frame.len += consumed;
344 num_bytes -= consumed;
348 memcpy_interleaved(data, data2, frame_bytes, num_bytes);
350 current_video_frame.len += num_bytes;
352 video_format.width = width;
353 video_format.height = height;
358 int num_samples = audio_frame->GetSampleFrameCount();
360 current_audio_frame = audio_frame_allocator->alloc_frame();
361 if (current_audio_frame.data != nullptr) {
362 const uint8_t *frame_bytes;
363 audio_frame->GetBytes((void **)&frame_bytes);
364 current_audio_frame.len = sizeof(int32_t) * 2 * num_samples;
366 memcpy(current_audio_frame.data, frame_bytes, current_audio_frame.len);
368 audio_format.bits_per_sample = 32;
369 audio_format.num_channels = 2;
373 if (current_video_frame.data != nullptr || current_audio_frame.data != nullptr) {
374 // TODO: Put into a queue and put into a dequeue thread, if the
375 // BlackMagic drivers don't already do that for us?
376 frame_callback(timecode,
377 current_video_frame, /*video_offset=*/0, video_format,
378 current_audio_frame, /*audio_offset=*/0, audio_format);
385 void DeckLinkCapture::configure_card()
387 if (video_frame_allocator == nullptr) {
388 owned_video_frame_allocator.reset(new MallocFrameAllocator(FRAME_SIZE, NUM_QUEUED_VIDEO_FRAMES));
389 set_video_frame_allocator(owned_video_frame_allocator.get());
391 if (audio_frame_allocator == nullptr) {
392 owned_audio_frame_allocator.reset(new MallocFrameAllocator(65536, NUM_QUEUED_AUDIO_FRAMES));
393 set_audio_frame_allocator(owned_audio_frame_allocator.get());
397 void DeckLinkCapture::start_bm_capture()
399 if (input->StartStreams() != S_OK) {
400 fprintf(stderr, "StartStreams failed\n");
405 void DeckLinkCapture::stop_dequeue_thread()
407 if (input->StopStreams() != S_OK) {
408 fprintf(stderr, "StopStreams failed\n");
413 void DeckLinkCapture::set_video_mode(uint32_t video_mode_id)
415 if (input->StopStreams() != S_OK) {
416 fprintf(stderr, "StopStreams failed\n");
420 set_video_mode_no_restart(video_mode_id);
422 if (input->StartStreams() != S_OK) {
423 fprintf(stderr, "StartStreams failed\n");
428 void DeckLinkCapture::set_video_mode_no_restart(uint32_t video_mode_id)
430 BMDDisplayModeSupport support;
431 IDeckLinkDisplayMode *display_mode;
432 if (input->DoesSupportVideoMode(video_mode_id, bmdFormat8BitYUV, /*flags=*/0, &support, &display_mode)) {
433 fprintf(stderr, "Failed to query display mode for card %d\n", card_index);
437 if (support == bmdDisplayModeNotSupported) {
438 fprintf(stderr, "Card %d does not support display mode\n", card_index);
442 if (display_mode->GetFrameRate(&frame_duration, &time_scale) != S_OK) {
443 fprintf(stderr, "Could not get frame rate for card %d\n", card_index);
447 if (input->EnableVideoInput(video_mode_id, bmdFormat8BitYUV, 0) != S_OK) {
448 fprintf(stderr, "Failed to set video mode 0x%04x for card %d\n", video_mode_id, card_index);
452 current_video_mode = video_mode_id;
455 void DeckLinkCapture::set_video_input(uint32_t video_input_id)
457 if (config->SetInt(bmdDeckLinkConfigVideoInputConnection, video_input_id) != S_OK) {
458 fprintf(stderr, "Failed to set video input connection for card %d\n", card_index);
462 current_video_input = video_input_id;
465 void DeckLinkCapture::set_audio_input(uint32_t audio_input_id)
467 if (config->SetInt(bmdDeckLinkConfigAudioInputConnection, audio_input_id) != S_OK) {
468 fprintf(stderr, "Failed to set audio input connection for card %d\n", card_index);
472 current_audio_input = audio_input_id;