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