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;
26 // TODO: Support stride.
27 void memcpy_interleaved(uint8_t *dest1, uint8_t *dest2, const uint8_t *src, size_t n)
30 uint8_t *dptr1 = dest1;
31 uint8_t *dptr2 = dest2;
33 for (size_t i = 0; i < n; i += 2) {
41 // Returns the number of bytes consumed.
42 size_t memcpy_interleaved_fastpath(uint8_t *dest1, uint8_t *dest2, const uint8_t *src, size_t n)
44 const uint8_t *limit = src + n;
47 // Align end to 32 bytes.
48 limit = (const uint8_t *)(intptr_t(limit) & ~31);
54 // Process [0,31] bytes, such that start gets aligned to 32 bytes.
55 const uint8_t *aligned_src = (const uint8_t *)(intptr_t(src + 31) & ~31);
56 if (aligned_src != src) {
57 size_t n2 = aligned_src - src;
58 memcpy_interleaved(dest1, dest2, src, n2);
68 // Make the length a multiple of 64.
69 if (((limit - src) % 64) != 0) {
72 assert(((limit - src) % 64) == 0);
75 const __restrict __m256i *in = (const __m256i *)src;
76 __restrict __m256i *out1 = (__m256i *)dest1;
77 __restrict __m256i *out2 = (__m256i *)dest2;
79 __m256i shuffle_cw = _mm256_set_epi8(
80 15, 13, 11, 9, 7, 5, 3, 1, 14, 12, 10, 8, 6, 4, 2, 0,
81 15, 13, 11, 9, 7, 5, 3, 1, 14, 12, 10, 8, 6, 4, 2, 0);
82 while (in < (const __m256i *)limit) {
83 // Note: For brevity, comments show lanes as if they were 2x64-bit (they're actually 2x128).
84 __m256i data1 = _mm256_stream_load_si256(in); // AaBbCcDd EeFfGgHh
85 __m256i data2 = _mm256_stream_load_si256(in + 1); // IiJjKkLl MmNnOoPp
87 data1 = _mm256_shuffle_epi8(data1, shuffle_cw); // ABCDabcd EFGHefgh
88 data2 = _mm256_shuffle_epi8(data2, shuffle_cw); // IJKLijkl MNOPmnop
90 data1 = _mm256_permute4x64_epi64(data1, 0b11011000); // ABCDEFGH abcdefgh
91 data2 = _mm256_permute4x64_epi64(data2, 0b11011000); // IJKLMNOP ijklmnop
93 __m256i lo = _mm256_permute2x128_si256(data1, data2, 0b00100000);
94 __m256i hi = _mm256_permute2x128_si256(data1, data2, 0b00110001);
96 _mm256_storeu_si256(out1, lo);
97 _mm256_storeu_si256(out2, hi);
105 const __restrict __m128i *in = (const __m128i *)src;
106 __restrict __m128i *out1 = (__m128i *)dest1;
107 __restrict __m128i *out2 = (__m128i *)dest2;
109 __m128i mask_lower_byte = _mm_set1_epi16(0x00ff);
110 while (in < (const __m128i *)limit) {
111 __m128i data1 = _mm_load_si128(in);
112 __m128i data2 = _mm_load_si128(in + 1);
113 __m128i data1_lo = _mm_and_si128(data1, mask_lower_byte);
114 __m128i data2_lo = _mm_and_si128(data2, mask_lower_byte);
115 __m128i data1_hi = _mm_srli_epi16(data1, 8);
116 __m128i data2_hi = _mm_srli_epi16(data2, 8);
117 __m128i lo = _mm_packus_epi16(data1_lo, data2_lo);
118 _mm_storeu_si128(out1, lo);
119 __m128i hi = _mm_packus_epi16(data1_hi, data2_hi);
120 _mm_storeu_si128(out2, hi);
136 DeckLinkCapture::DeckLinkCapture(IDeckLink *card, int card_index)
137 : card_index(card_index)
140 const char *model_name;
142 if (card->GetModelName(&model_name) == S_OK) {
143 snprintf(buf, sizeof(buf), "Card %d: %s", card_index, model_name);
145 snprintf(buf, sizeof(buf), "Card %d: Unknown DeckLink card", card_index);
150 if (card->QueryInterface(IID_IDeckLinkInput, (void**)&input) != S_OK) {
151 fprintf(stderr, "Card %d has no inputs\n", card_index);
155 /* Set up the video and audio sources. */
156 IDeckLinkConfiguration *config;
157 if (card->QueryInterface(IID_IDeckLinkConfiguration, (void**)&config) != S_OK) {
158 fprintf(stderr, "Failed to get configuration interface for card %d\n", card_index);
162 if (config->SetInt(bmdDeckLinkConfigVideoInputConnection, bmdVideoConnectionHDMI) != S_OK) {
163 fprintf(stderr, "Failed to set video input connection for card %d\n", card_index);
167 if (config->SetInt(bmdDeckLinkConfigAudioInputConnection, bmdAudioConnectionEmbedded) != S_OK) {
168 fprintf(stderr, "Failed to set video input connection for card %d\n", card_index);
172 IDeckLinkDisplayModeIterator *mode_it;
173 if (input->GetDisplayModeIterator(&mode_it) != S_OK) {
174 fprintf(stderr, "Failed to enumerate display modes for card %d\n", card_index);
178 for (IDeckLinkDisplayMode *mode_ptr; mode_it->Next(&mode_ptr) == S_OK; mode_ptr->Release()) {
181 const char *mode_name;
182 if (mode_ptr->GetName(&mode_name) != S_OK) {
183 mode.name = "Unknown mode";
185 mode.name = mode_name;
188 mode.autodetect = false;
190 mode.width = mode_ptr->GetWidth();
191 mode.height = mode_ptr->GetHeight();
193 BMDTimeScale frame_rate_num;
194 BMDTimeValue frame_rate_den;
195 if (mode_ptr->GetFrameRate(&frame_rate_den, &frame_rate_num) != S_OK) {
196 fprintf(stderr, "Could not get frame rate for mode '%s' on card %d\n", mode.name.c_str(), card_index);
199 mode.frame_rate_num = frame_rate_num;
200 mode.frame_rate_den = frame_rate_den;
202 // TODO: Respect the TFF/BFF flag.
203 mode.interlaced = (mode_ptr->GetFieldDominance() == bmdLowerFieldFirst || mode_ptr->GetFieldDominance() == bmdUpperFieldFirst);
205 uint32_t id = mode_ptr->GetDisplayMode();
206 video_modes.insert(make_pair(id, mode));
209 set_video_mode_no_restart(bmdModeHD720p5994);
211 if (input->EnableAudioInput(48000, bmdAudioSampleType32bitInteger, 2) != S_OK) {
212 fprintf(stderr, "Failed to enable audio input for card %d\n", card_index);
216 input->SetCallback(this);
219 DeckLinkCapture::~DeckLinkCapture()
221 if (has_dequeue_callbacks) {
222 dequeue_cleanup_callback();
226 HRESULT STDMETHODCALLTYPE DeckLinkCapture::QueryInterface(REFIID, LPVOID *)
228 return E_NOINTERFACE;
231 ULONG STDMETHODCALLTYPE DeckLinkCapture::AddRef(void)
233 return refcount.fetch_add(1) + 1;
236 ULONG STDMETHODCALLTYPE DeckLinkCapture::Release(void)
238 int new_ref = refcount.fetch_sub(1) - 1;
244 HRESULT STDMETHODCALLTYPE DeckLinkCapture::VideoInputFormatChanged(
245 BMDVideoInputFormatChangedEvents,
246 IDeckLinkDisplayMode* display_mode,
247 BMDDetectedVideoInputFormatFlags)
249 if (display_mode->GetFrameRate(&frame_duration, &time_scale) != S_OK) {
250 fprintf(stderr, "Could not get new frame rate\n");
256 HRESULT STDMETHODCALLTYPE DeckLinkCapture::VideoInputFrameArrived(
257 IDeckLinkVideoInputFrame *video_frame,
258 IDeckLinkAudioInputPacket *audio_frame)
261 if (has_dequeue_callbacks) {
262 dequeue_init_callback();
267 FrameAllocator::Frame current_video_frame, current_audio_frame;
268 VideoFormat video_format;
269 AudioFormat audio_format;
271 video_format.frame_rate_nom = time_scale;
272 video_format.frame_rate_den = frame_duration;
275 video_format.has_signal = !(video_frame->GetFlags() & bmdFrameHasNoInputSource);
277 int width = video_frame->GetWidth();
278 int height = video_frame->GetHeight();
279 const int stride = video_frame->GetRowBytes();
280 assert(stride == width * 2);
282 current_video_frame = video_frame_allocator->alloc_frame();
283 if (current_video_frame.data != nullptr) {
284 const uint8_t *frame_bytes;
285 video_frame->GetBytes((void **)&frame_bytes);
287 uint8_t *data = current_video_frame.data;
288 uint8_t *data2 = current_video_frame.data2;
289 size_t num_bytes = width * height * 2;
291 size_t consumed = memcpy_interleaved_fastpath(data, data2, frame_bytes, num_bytes);
292 frame_bytes += consumed;
293 data += consumed / 2;
294 data2 += consumed / 2;
298 current_video_frame.len += consumed;
299 num_bytes -= consumed;
303 memcpy_interleaved(data, data2, frame_bytes, num_bytes);
305 current_video_frame.len += num_bytes;
307 video_format.width = width;
308 video_format.height = height;
313 int num_samples = audio_frame->GetSampleFrameCount();
315 current_audio_frame = audio_frame_allocator->alloc_frame();
316 if (current_audio_frame.data != nullptr) {
317 const uint8_t *frame_bytes;
318 audio_frame->GetBytes((void **)&frame_bytes);
319 current_audio_frame.len = sizeof(int32_t) * 2 * num_samples;
321 memcpy(current_audio_frame.data, frame_bytes, current_audio_frame.len);
323 audio_format.bits_per_sample = 32;
324 audio_format.num_channels = 2;
328 if (current_video_frame.data != nullptr || current_audio_frame.data != nullptr) {
329 // TODO: Put into a queue and put into a dequeue thread, if the
330 // BlackMagic drivers don't already do that for us?
331 frame_callback(timecode,
332 current_video_frame, /*video_offset=*/0, video_format,
333 current_audio_frame, /*audio_offset=*/0, audio_format);
340 void DeckLinkCapture::configure_card()
342 if (video_frame_allocator == nullptr) {
343 set_video_frame_allocator(new MallocFrameAllocator(FRAME_SIZE, NUM_QUEUED_VIDEO_FRAMES)); // FIXME: leak.
345 if (audio_frame_allocator == nullptr) {
346 set_audio_frame_allocator(new MallocFrameAllocator(65536, NUM_QUEUED_AUDIO_FRAMES)); // FIXME: leak.
350 void DeckLinkCapture::start_bm_capture()
352 if (input->StartStreams() != S_OK) {
353 fprintf(stderr, "StartStreams failed\n");
358 void DeckLinkCapture::stop_dequeue_thread()
360 if (input->StopStreams() != S_OK) {
361 fprintf(stderr, "StopStreams failed\n");
366 void DeckLinkCapture::set_video_mode(uint32_t video_mode_id)
368 if (input->StopStreams() != S_OK) {
369 fprintf(stderr, "StopStreams failed\n");
373 set_video_mode_no_restart(video_mode_id);
375 if (input->StartStreams() != S_OK) {
376 fprintf(stderr, "StartStreams failed\n");
381 void DeckLinkCapture::set_video_mode_no_restart(uint32_t video_mode_id)
383 BMDDisplayModeSupport support;
384 IDeckLinkDisplayMode *display_mode;
385 if (input->DoesSupportVideoMode(video_mode_id, bmdFormat8BitYUV, /*flags=*/0, &support, &display_mode)) {
386 fprintf(stderr, "Failed to query display mode for card %d\n", card_index);
390 if (support == bmdDisplayModeNotSupported) {
391 fprintf(stderr, "Card %d does not support display mode\n", card_index);
395 if (display_mode->GetFrameRate(&frame_duration, &time_scale) != S_OK) {
396 fprintf(stderr, "Could not get frame rate for card %d\n", card_index);
400 if (input->EnableVideoInput(video_mode_id, bmdFormat8BitYUV, 0) != S_OK) {
401 fprintf(stderr, "Failed to set video mode 0x%04x for card %d\n", video_mode_id, card_index);
405 current_video_mode = video_mode_id;