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