]> git.sesse.net Git - nageru/blob - decklink_capture.cpp
Support interlaced inputs with the official DeckLink driver.
[nageru] / decklink_capture.cpp
1 #include "decklink_capture.h"
2
3 #include <DeckLinkAPI.h>
4 #include <DeckLinkAPIConfiguration.h>
5 #include <DeckLinkAPIDiscovery.h>
6 #include <DeckLinkAPIModes.h>
7 #include <assert.h>
8 #ifdef __SSE2__
9 #include <immintrin.h>
10 #endif
11 #include <stdint.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <chrono>
16 #include <cstdint>
17 #include <utility>
18 #include <vector>
19
20 #include "bmusb/bmusb.h"
21
22 #define FRAME_SIZE (8 << 20)  // 8 MB.
23
24 using namespace std;
25 using namespace std::chrono;
26 using namespace std::placeholders;
27 using namespace bmusb;
28
29 namespace {
30
31 // TODO: Support stride.
32 void memcpy_interleaved(uint8_t *dest1, uint8_t *dest2, const uint8_t *src, size_t n)
33 {
34         assert(n % 2 == 0);
35         uint8_t *dptr1 = dest1;
36         uint8_t *dptr2 = dest2;
37
38         for (size_t i = 0; i < n; i += 2) {
39                 *dptr1++ = *src++;
40                 *dptr2++ = *src++;
41         }
42 }
43
44 #ifdef __SSE2__
45
46 // Returns the number of bytes consumed.
47 size_t memcpy_interleaved_fastpath(uint8_t *dest1, uint8_t *dest2, const uint8_t *src, size_t n)
48 {
49         const uint8_t *limit = src + n;
50         size_t consumed = 0;
51
52         // Align end to 32 bytes.
53         limit = (const uint8_t *)(intptr_t(limit) & ~31);
54
55         if (src >= limit) {
56                 return 0;
57         }
58
59         // Process [0,31] bytes, such that start gets aligned to 32 bytes.
60         const uint8_t *aligned_src = (const uint8_t *)(intptr_t(src + 31) & ~31);
61         if (aligned_src != src) {
62                 size_t n2 = aligned_src - src;
63                 memcpy_interleaved(dest1, dest2, src, n2);
64                 dest1 += n2 / 2;
65                 dest2 += n2 / 2;
66                 if (n2 % 2) {
67                         swap(dest1, dest2);
68                 }
69                 src = aligned_src;
70                 consumed += n2;
71         }
72
73         // Make the length a multiple of 64.
74         if (((limit - src) % 64) != 0) {
75                 limit -= 32;
76         }
77         assert(((limit - src) % 64) == 0);
78
79 #if __AVX2__
80         const __m256i * __restrict in = (const __m256i *)src;
81         __m256i * __restrict out1 = (__m256i *)dest1;
82         __m256i * __restrict out2 = (__m256i *)dest2;
83
84         __m256i shuffle_cw = _mm256_set_epi8(
85                 15, 13, 11, 9, 7, 5, 3, 1, 14, 12, 10, 8, 6, 4, 2, 0,
86                 15, 13, 11, 9, 7, 5, 3, 1, 14, 12, 10, 8, 6, 4, 2, 0);
87         while (in < (const __m256i *)limit) {
88                 // Note: For brevity, comments show lanes as if they were 2x64-bit (they're actually 2x128).
89                 __m256i data1 = _mm256_stream_load_si256(in);         // AaBbCcDd EeFfGgHh
90                 __m256i data2 = _mm256_stream_load_si256(in + 1);     // IiJjKkLl MmNnOoPp
91
92                 data1 = _mm256_shuffle_epi8(data1, shuffle_cw);       // ABCDabcd EFGHefgh
93                 data2 = _mm256_shuffle_epi8(data2, shuffle_cw);       // IJKLijkl MNOPmnop
94         
95                 data1 = _mm256_permute4x64_epi64(data1, 0b11011000);  // ABCDEFGH abcdefgh
96                 data2 = _mm256_permute4x64_epi64(data2, 0b11011000);  // IJKLMNOP ijklmnop
97
98                 __m256i lo = _mm256_permute2x128_si256(data1, data2, 0b00100000);
99                 __m256i hi = _mm256_permute2x128_si256(data1, data2, 0b00110001);
100
101                 _mm256_storeu_si256(out1, lo);
102                 _mm256_storeu_si256(out2, hi);
103
104                 in += 2;
105                 ++out1;
106                 ++out2;
107                 consumed += 64;
108         }
109 #else
110         const __m128i * __restrict in = (const __m128i *)src;
111         __m128i * __restrict out1 = (__m128i *)dest1;
112         __m128i * __restrict out2 = (__m128i *)dest2;
113
114         __m128i mask_lower_byte = _mm_set1_epi16(0x00ff);
115         while (in < (const __m128i *)limit) {
116                 __m128i data1 = _mm_load_si128(in);
117                 __m128i data2 = _mm_load_si128(in + 1);
118                 __m128i data1_lo = _mm_and_si128(data1, mask_lower_byte);
119                 __m128i data2_lo = _mm_and_si128(data2, mask_lower_byte);
120                 __m128i data1_hi = _mm_srli_epi16(data1, 8);
121                 __m128i data2_hi = _mm_srli_epi16(data2, 8);
122                 __m128i lo = _mm_packus_epi16(data1_lo, data2_lo);
123                 _mm_storeu_si128(out1, lo);
124                 __m128i hi = _mm_packus_epi16(data1_hi, data2_hi);
125                 _mm_storeu_si128(out2, hi);
126
127                 in += 2;
128                 ++out1;
129                 ++out2;
130                 consumed += 32;
131         }
132 #endif
133
134         return consumed;
135 }
136
137 #endif  // __SSE2__
138
139 }  // namespace
140
141 DeckLinkCapture::DeckLinkCapture(IDeckLink *card, int card_index)
142         : card_index(card_index), card(card)
143 {
144         {
145                 const char *model_name;
146                 char buf[256];
147                 if (card->GetModelName(&model_name) == S_OK) {
148                         snprintf(buf, sizeof(buf), "PCI card %d: %s", card_index, model_name);
149                 } else {
150                         snprintf(buf, sizeof(buf), "PCI card %d: Unknown DeckLink card", card_index);
151                 }
152                 description = buf;
153         }
154
155         if (card->QueryInterface(IID_IDeckLinkInput, (void**)&input) != S_OK) {
156                 fprintf(stderr, "Card %d has no inputs\n", card_index);
157                 exit(1);
158         }
159
160         IDeckLinkAttributes *attr;
161         if (card->QueryInterface(IID_IDeckLinkAttributes, (void**)&attr) != S_OK) {
162                 fprintf(stderr, "Card %d has no attributes\n", card_index);
163                 exit(1);
164         }
165
166         // Get the list of available video inputs.
167         int64_t video_input_mask;
168         if (attr->GetInt(BMDDeckLinkVideoInputConnections, &video_input_mask) != S_OK) {
169                 fprintf(stderr, "Failed to enumerate video inputs for card %d\n", card_index);
170                 exit(1);
171         }
172         const vector<pair<BMDVideoConnection, string>> video_input_types = {
173                 { bmdVideoConnectionSDI, "SDI" },
174                 { bmdVideoConnectionHDMI, "HDMI" },
175                 { bmdVideoConnectionOpticalSDI, "Optical SDI" },
176                 { bmdVideoConnectionComponent, "Component" },
177                 { bmdVideoConnectionComposite, "Composite" },
178                 { bmdVideoConnectionSVideo, "S-Video" }
179         };
180         for (const auto &video_input : video_input_types) {
181                 if (video_input_mask & video_input.first) {
182                         video_inputs.emplace(video_input.first, video_input.second);
183                 }
184         }
185
186         // And then the available audio inputs.
187         int64_t audio_input_mask;
188         if (attr->GetInt(BMDDeckLinkAudioInputConnections, &audio_input_mask) != S_OK) {
189                 fprintf(stderr, "Failed to enumerate audio inputs for card %d\n", card_index);
190                 exit(1);
191         }
192         const vector<pair<BMDAudioConnection, string>> audio_input_types = {
193                 { bmdAudioConnectionEmbedded, "Embedded" },
194                 { bmdAudioConnectionAESEBU, "AES/EBU" },
195                 { bmdAudioConnectionAnalog, "Analog" },
196                 { bmdAudioConnectionAnalogXLR, "Analog XLR" },
197                 { bmdAudioConnectionAnalogRCA, "Analog RCA" },
198                 { bmdAudioConnectionMicrophone, "Microphone" },
199                 { bmdAudioConnectionHeadphones, "Headphones" }
200         };
201         for (const auto &audio_input : audio_input_types) {
202                 if (audio_input_mask & audio_input.first) {
203                         audio_inputs.emplace(audio_input.first, audio_input.second);
204                 }
205         }
206
207         attr->Release();
208
209         /* Set up the video and audio sources. */
210         if (card->QueryInterface(IID_IDeckLinkConfiguration, (void**)&config) != S_OK) {
211                 fprintf(stderr, "Failed to get configuration interface for card %d\n", card_index);
212                 exit(1);
213         }
214
215         set_video_input(bmdVideoConnectionHDMI);
216         set_audio_input(bmdAudioConnectionEmbedded);
217
218         IDeckLinkDisplayModeIterator *mode_it;
219         if (input->GetDisplayModeIterator(&mode_it) != S_OK) {
220                 fprintf(stderr, "Failed to enumerate display modes for card %d\n", card_index);
221                 exit(1);
222         }
223
224         for (IDeckLinkDisplayMode *mode_ptr; mode_it->Next(&mode_ptr) == S_OK; mode_ptr->Release()) {
225                 VideoMode mode;
226
227                 const char *mode_name;
228                 if (mode_ptr->GetName(&mode_name) != S_OK) {
229                         mode.name = "Unknown mode";
230                 } else {
231                         mode.name = mode_name;
232                 }
233
234                 mode.autodetect = false;
235
236                 mode.width = mode_ptr->GetWidth();
237                 mode.height = mode_ptr->GetHeight();
238
239                 BMDTimeScale frame_rate_num;
240                 BMDTimeValue frame_rate_den;
241                 if (mode_ptr->GetFrameRate(&frame_rate_den, &frame_rate_num) != S_OK) {
242                         fprintf(stderr, "Could not get frame rate for mode '%s' on card %d\n", mode.name.c_str(), card_index);
243                         exit(1);
244                 }
245                 mode.frame_rate_num = frame_rate_num;
246                 mode.frame_rate_den = frame_rate_den;
247
248                 // TODO: Respect the TFF/BFF flag.
249                 mode.interlaced = (mode_ptr->GetFieldDominance() == bmdLowerFieldFirst || mode_ptr->GetFieldDominance() == bmdUpperFieldFirst);
250
251                 uint32_t id = mode_ptr->GetDisplayMode();
252                 video_modes.insert(make_pair(id, mode));
253         }
254
255         set_video_mode_no_restart(bmdModeHD720p5994);
256
257         input->SetCallback(this);
258 }
259
260 DeckLinkCapture::~DeckLinkCapture()
261 {
262         if (has_dequeue_callbacks) {
263                 dequeue_cleanup_callback();
264         }
265         input->Release();
266         config->Release();
267         card->Release();
268 }
269
270 HRESULT STDMETHODCALLTYPE DeckLinkCapture::QueryInterface(REFIID, LPVOID *)
271 {
272         return E_NOINTERFACE;
273 }
274
275 ULONG STDMETHODCALLTYPE DeckLinkCapture::AddRef(void)
276 {
277         return refcount.fetch_add(1) + 1;
278 }
279
280 ULONG STDMETHODCALLTYPE DeckLinkCapture::Release(void)
281 {
282         int new_ref = refcount.fetch_sub(1) - 1;
283         if (new_ref == 0)
284                 delete this;
285         return new_ref;
286 }
287
288 HRESULT STDMETHODCALLTYPE DeckLinkCapture::VideoInputFormatChanged(
289         BMDVideoInputFormatChangedEvents,
290         IDeckLinkDisplayMode* display_mode,
291         BMDDetectedVideoInputFormatFlags)
292 {
293         if (display_mode->GetFrameRate(&frame_duration, &time_scale) != S_OK) {
294                 fprintf(stderr, "Could not get new frame rate\n");
295                 exit(1);
296         }
297         field_dominance = display_mode->GetFieldDominance();
298         return S_OK;
299 }
300
301 HRESULT STDMETHODCALLTYPE DeckLinkCapture::VideoInputFrameArrived(
302         IDeckLinkVideoInputFrame *video_frame,
303         IDeckLinkAudioInputPacket *audio_frame)
304 {
305         if (!done_init) {
306                 if (has_dequeue_callbacks) {
307                         dequeue_init_callback();
308                 }
309                 done_init = true;
310         }
311
312         FrameAllocator::Frame current_video_frame, current_audio_frame;
313         VideoFormat video_format;
314         AudioFormat audio_format;
315
316         video_format.frame_rate_nom = time_scale;
317         video_format.frame_rate_den = frame_duration;
318         // TODO: Respect the TFF/BFF flag.
319         video_format.interlaced = (field_dominance == bmdLowerFieldFirst || field_dominance == bmdUpperFieldFirst);
320         video_format.second_field_start = 1;
321
322         if (video_frame) {
323                 video_format.has_signal = !(video_frame->GetFlags() & bmdFrameHasNoInputSource);
324
325                 int width = video_frame->GetWidth();
326                 int height = video_frame->GetHeight();
327                 const int stride = video_frame->GetRowBytes();
328                 assert(stride == width * 2);
329
330                 current_video_frame = video_frame_allocator->alloc_frame();
331                 if (current_video_frame.data != nullptr) {
332                         const uint8_t *frame_bytes;
333                         video_frame->GetBytes((void **)&frame_bytes);
334
335                         uint8_t *data = current_video_frame.data;
336                         uint8_t *data2 = current_video_frame.data2;
337                         size_t num_bytes = width * height * 2;
338 #ifdef __SSE2__
339                         size_t consumed = memcpy_interleaved_fastpath(data, data2, frame_bytes, num_bytes);
340                         frame_bytes += consumed;
341                         data += consumed / 2;
342                         data2 += consumed / 2;
343                         if (num_bytes % 2) {
344                                 swap(data, data2);
345                         }
346                         current_video_frame.len += consumed;
347                         num_bytes -= consumed;
348 #endif
349
350                         if (num_bytes > 0) {
351                                 memcpy_interleaved(data, data2, frame_bytes, num_bytes);
352                         }
353                         current_video_frame.len += num_bytes;
354
355                         video_format.width = width;
356                         video_format.height = height;
357
358                         current_video_frame.received_timestamp = steady_clock::now();
359                 }
360         }
361
362         if (audio_frame) {
363                 int num_samples = audio_frame->GetSampleFrameCount();
364
365                 current_audio_frame = audio_frame_allocator->alloc_frame();
366                 if (current_audio_frame.data != nullptr) {
367                         const uint8_t *frame_bytes;
368                         audio_frame->GetBytes((void **)&frame_bytes);
369                         current_audio_frame.len = sizeof(int32_t) * 2 * num_samples;
370
371                         memcpy(current_audio_frame.data, frame_bytes, current_audio_frame.len);
372
373                         audio_format.bits_per_sample = 32;
374                         audio_format.num_channels = 2;
375
376                         current_audio_frame.received_timestamp = steady_clock::now();
377                 }
378         }
379
380         if (current_video_frame.data != nullptr || current_audio_frame.data != nullptr) {
381                 // TODO: Put into a queue and put into a dequeue thread, if the
382                 // BlackMagic drivers don't already do that for us?
383                 frame_callback(timecode,
384                         current_video_frame, /*video_offset=*/0, video_format,
385                         current_audio_frame, /*audio_offset=*/0, audio_format);
386         }
387
388         timecode++;
389         return S_OK;
390 }
391
392 void DeckLinkCapture::configure_card()
393 {
394         if (video_frame_allocator == nullptr) {
395                 owned_video_frame_allocator.reset(new MallocFrameAllocator(FRAME_SIZE, NUM_QUEUED_VIDEO_FRAMES));
396                 set_video_frame_allocator(owned_video_frame_allocator.get());
397         }
398         if (audio_frame_allocator == nullptr) {
399                 owned_audio_frame_allocator.reset(new MallocFrameAllocator(65536, NUM_QUEUED_AUDIO_FRAMES));
400                 set_audio_frame_allocator(owned_audio_frame_allocator.get());
401         }
402 }
403
404 void DeckLinkCapture::start_bm_capture()
405 {
406         if (running) {
407                 return;
408         }
409         if (input->EnableVideoInput(current_video_mode, bmdFormat8BitYUV, 0) != S_OK) {
410                 fprintf(stderr, "Failed to set video mode 0x%04x for card %d\n", current_video_mode, card_index);
411                 exit(1);
412         }
413         if (input->EnableAudioInput(48000, bmdAudioSampleType32bitInteger, 2) != S_OK) {
414                 fprintf(stderr, "Failed to enable audio input for card %d\n", card_index);
415                 exit(1);
416         }
417
418         if (input->StartStreams() != S_OK) {
419                 fprintf(stderr, "StartStreams failed\n");
420                 exit(1);
421         }
422         running = true;
423 }
424
425 void DeckLinkCapture::stop_dequeue_thread()
426 {
427         if (!running) {
428                 return;
429         }
430         HRESULT result = input->StopStreams();
431         if (result != S_OK) {
432                 fprintf(stderr, "StopStreams failed with error 0x%x\n", result);
433                 exit(1);
434         }
435         if (input->DisableVideoInput() != S_OK) {
436                 fprintf(stderr, "Failed to disable video input for card %d\n", card_index);
437                 exit(1);
438         }
439         if (input->DisableAudioInput() != S_OK) {
440                 fprintf(stderr, "Failed to disable audio input for card %d\n", card_index);
441                 exit(1);
442         }
443         running = false;
444 }
445
446 void DeckLinkCapture::set_video_mode(uint32_t video_mode_id)
447 {
448         if (input->StopStreams() != S_OK) {
449                 fprintf(stderr, "StopStreams failed\n");
450                 exit(1);
451         }
452
453         set_video_mode_no_restart(video_mode_id);
454
455         if (input->StartStreams() != S_OK) {
456                 fprintf(stderr, "StartStreams failed\n");
457                 exit(1);
458         }
459 }
460
461 void DeckLinkCapture::set_video_mode_no_restart(uint32_t video_mode_id)
462 {
463         BMDDisplayModeSupport support;
464         IDeckLinkDisplayMode *display_mode;
465         if (input->DoesSupportVideoMode(video_mode_id, bmdFormat8BitYUV, /*flags=*/0, &support, &display_mode)) {
466                 fprintf(stderr, "Failed to query display mode for card %d\n", card_index);
467                 exit(1);
468         }
469
470         if (support == bmdDisplayModeNotSupported) {
471                 fprintf(stderr, "Card %d does not support display mode\n", card_index);
472                 exit(1);
473         }
474
475         if (display_mode->GetFrameRate(&frame_duration, &time_scale) != S_OK) {
476                 fprintf(stderr, "Could not get frame rate for card %d\n", card_index);
477                 exit(1);
478         }
479
480         field_dominance = display_mode->GetFieldDominance();
481
482         if (running) {
483                 if (input->EnableVideoInput(video_mode_id, bmdFormat8BitYUV, 0) != S_OK) {
484                         fprintf(stderr, "Failed to set video mode 0x%04x for card %d\n", video_mode_id, card_index);
485                         exit(1);
486                 }
487         }
488
489         current_video_mode = video_mode_id;
490 }
491
492 void DeckLinkCapture::set_video_input(uint32_t video_input_id)
493 {
494         if (config->SetInt(bmdDeckLinkConfigVideoInputConnection, video_input_id) != S_OK) {
495                 fprintf(stderr, "Failed to set video input connection for card %d\n", card_index);
496                 exit(1);
497         }
498
499         current_video_input = video_input_id;
500 }
501
502 void DeckLinkCapture::set_audio_input(uint32_t audio_input_id)
503 {
504         if (config->SetInt(bmdDeckLinkConfigAudioInputConnection, audio_input_id) != S_OK) {
505                 fprintf(stderr, "Failed to set audio input connection for card %d\n", card_index);
506                 exit(1);
507         }
508
509         current_audio_input = audio_input_id;
510 }