]> git.sesse.net Git - nageru/blob - decklink_capture.cpp
Let settings follow buses when editing the mapping.
[nageru] / decklink_capture.cpp
1 #include "decklink_capture.h"
2
3 #include <assert.h>
4 #include <stdint.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <cstddef>
9 #ifdef __SSE2__
10 #include <immintrin.h>
11 #endif
12
13 #include <DeckLinkAPI.h>
14 #include <DeckLinkAPIConfiguration.h>
15 #include <DeckLinkAPIDiscovery.h>
16 #include <DeckLinkAPIModes.h>
17 #include "bmusb/bmusb.h"
18
19 #define FRAME_SIZE (8 << 20)  // 8 MB.
20
21 using namespace std;
22 using namespace std::placeholders;
23 using namespace bmusb;
24
25 namespace {
26
27 // TODO: Support stride.
28 void memcpy_interleaved(uint8_t *dest1, uint8_t *dest2, const uint8_t *src, size_t n)
29 {
30         assert(n % 2 == 0);
31         uint8_t *dptr1 = dest1;
32         uint8_t *dptr2 = dest2;
33
34         for (size_t i = 0; i < n; i += 2) {
35                 *dptr1++ = *src++;
36                 *dptr2++ = *src++;
37         }
38 }
39
40 #ifdef __SSE2__
41
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)
44 {
45         const uint8_t *limit = src + n;
46         size_t consumed = 0;
47
48         // Align end to 32 bytes.
49         limit = (const uint8_t *)(intptr_t(limit) & ~31);
50
51         if (src >= limit) {
52                 return 0;
53         }
54
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);
60                 dest1 += n2 / 2;
61                 dest2 += n2 / 2;
62                 if (n2 % 2) {
63                         swap(dest1, dest2);
64                 }
65                 src = aligned_src;
66                 consumed += n2;
67         }
68
69         // Make the length a multiple of 64.
70         if (((limit - src) % 64) != 0) {
71                 limit -= 32;
72         }
73         assert(((limit - src) % 64) == 0);
74
75 #if __AVX2__
76         const __m256i * __restrict in = (const __m256i *)src;
77         __m256i * __restrict out1 = (__m256i *)dest1;
78         __m256i * __restrict out2 = (__m256i *)dest2;
79
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
87
88                 data1 = _mm256_shuffle_epi8(data1, shuffle_cw);       // ABCDabcd EFGHefgh
89                 data2 = _mm256_shuffle_epi8(data2, shuffle_cw);       // IJKLijkl MNOPmnop
90         
91                 data1 = _mm256_permute4x64_epi64(data1, 0b11011000);  // ABCDEFGH abcdefgh
92                 data2 = _mm256_permute4x64_epi64(data2, 0b11011000);  // IJKLMNOP ijklmnop
93
94                 __m256i lo = _mm256_permute2x128_si256(data1, data2, 0b00100000);
95                 __m256i hi = _mm256_permute2x128_si256(data1, data2, 0b00110001);
96
97                 _mm256_storeu_si256(out1, lo);
98                 _mm256_storeu_si256(out2, hi);
99
100                 in += 2;
101                 ++out1;
102                 ++out2;
103                 consumed += 64;
104         }
105 #else
106         const __m128i * __restrict in = (const __m128i *)src;
107         __m128i * __restrict out1 = (__m128i *)dest1;
108         __m128i * __restrict out2 = (__m128i *)dest2;
109
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);
122
123                 in += 2;
124                 ++out1;
125                 ++out2;
126                 consumed += 32;
127         }
128 #endif
129
130         return consumed;
131 }
132
133 #endif  // __SSE2__
134
135 }  // namespace
136
137 DeckLinkCapture::DeckLinkCapture(IDeckLink *card, int card_index)
138         : card_index(card_index), card(card)
139 {
140         {
141                 const char *model_name;
142                 char buf[256];
143                 if (card->GetModelName(&model_name) == S_OK) {
144                         snprintf(buf, sizeof(buf), "PCI card %d: %s", card_index, model_name);
145                 } else {
146                         snprintf(buf, sizeof(buf), "PCI card %d: Unknown DeckLink card", card_index);
147                 }
148                 description = buf;
149         }
150
151         if (card->QueryInterface(IID_IDeckLinkInput, (void**)&input) != S_OK) {
152                 fprintf(stderr, "Card %d has no inputs\n", card_index);
153                 exit(1);
154         }
155
156         IDeckLinkAttributes *attr;
157         if (card->QueryInterface(IID_IDeckLinkAttributes, (void**)&attr) != S_OK) {
158                 fprintf(stderr, "Card %d has no attributes\n", card_index);
159                 exit(1);
160         }
161
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);
166                 exit(1);
167         }
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" }
175         };
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);
179                 }
180         }
181
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);
186                 exit(1);
187         }
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" }
196         };
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);
200                 }
201         }
202
203         attr->Release();
204
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);
208                 exit(1);
209         }
210
211         set_video_input(bmdVideoConnectionHDMI);
212         set_audio_input(bmdAudioConnectionEmbedded);
213
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);
217                 exit(1);
218         }
219
220         for (IDeckLinkDisplayMode *mode_ptr; mode_it->Next(&mode_ptr) == S_OK; mode_ptr->Release()) {
221                 VideoMode mode;
222
223                 const char *mode_name;
224                 if (mode_ptr->GetName(&mode_name) != S_OK) {
225                         mode.name = "Unknown mode";
226                 } else {
227                         mode.name = mode_name;
228                 }
229
230                 mode.autodetect = false;
231
232                 mode.width = mode_ptr->GetWidth();
233                 mode.height = mode_ptr->GetHeight();
234
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);
239                         exit(1);
240                 }
241                 mode.frame_rate_num = frame_rate_num;
242                 mode.frame_rate_den = frame_rate_den;
243
244                 // TODO: Respect the TFF/BFF flag.
245                 mode.interlaced = (mode_ptr->GetFieldDominance() == bmdLowerFieldFirst || mode_ptr->GetFieldDominance() == bmdUpperFieldFirst);
246
247                 uint32_t id = mode_ptr->GetDisplayMode();
248                 video_modes.insert(make_pair(id, mode));
249         }
250
251         set_video_mode_no_restart(bmdModeHD720p5994);
252
253         if (input->EnableAudioInput(48000, bmdAudioSampleType32bitInteger, 2) != S_OK) {
254                 fprintf(stderr, "Failed to enable audio input for card %d\n", card_index);
255                 exit(1);
256         }
257
258         input->SetCallback(this);
259 }
260
261 DeckLinkCapture::~DeckLinkCapture()
262 {
263         if (has_dequeue_callbacks) {
264                 dequeue_cleanup_callback();
265         }
266         input->Release();
267         config->Release();
268         card->Release();
269 }
270
271 HRESULT STDMETHODCALLTYPE DeckLinkCapture::QueryInterface(REFIID, LPVOID *)
272 {
273         return E_NOINTERFACE;
274 }
275
276 ULONG STDMETHODCALLTYPE DeckLinkCapture::AddRef(void)
277 {
278         return refcount.fetch_add(1) + 1;
279 }
280
281 ULONG STDMETHODCALLTYPE DeckLinkCapture::Release(void)
282 {
283         int new_ref = refcount.fetch_sub(1) - 1;
284         if (new_ref == 0)
285                 delete this;
286         return new_ref;
287 }
288
289 HRESULT STDMETHODCALLTYPE DeckLinkCapture::VideoInputFormatChanged(
290         BMDVideoInputFormatChangedEvents,
291         IDeckLinkDisplayMode* display_mode,
292         BMDDetectedVideoInputFormatFlags)
293 {
294         if (display_mode->GetFrameRate(&frame_duration, &time_scale) != S_OK) {
295                 fprintf(stderr, "Could not get new frame rate\n");
296                 exit(1);
297         }
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
319         if (video_frame) {
320                 video_format.has_signal = !(video_frame->GetFlags() & bmdFrameHasNoInputSource);
321
322                 int width = video_frame->GetWidth();
323                 int height = video_frame->GetHeight();
324                 const int stride = video_frame->GetRowBytes();
325                 assert(stride == width * 2);
326
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);
331
332                         uint8_t *data = current_video_frame.data;
333                         uint8_t *data2 = current_video_frame.data2;
334                         size_t num_bytes = width * height * 2;
335 #ifdef __SSE2__
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;
340                         if (num_bytes % 2) {
341                                 swap(data, data2);
342                         }
343                         current_video_frame.len += consumed;
344                         num_bytes -= consumed;
345 #endif
346
347                         if (num_bytes > 0) {
348                                 memcpy_interleaved(data, data2, frame_bytes, num_bytes);
349                         }
350                         current_video_frame.len += num_bytes;
351
352                         video_format.width = width;
353                         video_format.height = height;
354                 }
355         }
356
357         if (audio_frame) {
358                 int num_samples = audio_frame->GetSampleFrameCount();
359
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;
365
366                         memcpy(current_audio_frame.data, frame_bytes, current_audio_frame.len);
367
368                         audio_format.bits_per_sample = 32;
369                         audio_format.num_channels = 2;
370                 }
371         }
372
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);
379         }
380
381         timecode++;
382         return S_OK;
383 }
384
385 void DeckLinkCapture::configure_card()
386 {
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());
390         }
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());
394         }
395 }
396
397 void DeckLinkCapture::start_bm_capture()
398 {
399         if (input->StartStreams() != S_OK) {
400                 fprintf(stderr, "StartStreams failed\n");
401                 exit(1);
402         }
403 }
404
405 void DeckLinkCapture::stop_dequeue_thread()
406 {
407         if (input->StopStreams() != S_OK) {
408                 fprintf(stderr, "StopStreams failed\n");
409                 exit(1);
410         }
411 }
412
413 void DeckLinkCapture::set_video_mode(uint32_t video_mode_id)
414 {
415         if (input->StopStreams() != S_OK) {
416                 fprintf(stderr, "StopStreams failed\n");
417                 exit(1);
418         }
419
420         set_video_mode_no_restart(video_mode_id);
421
422         if (input->StartStreams() != S_OK) {
423                 fprintf(stderr, "StartStreams failed\n");
424                 exit(1);
425         }
426 }
427
428 void DeckLinkCapture::set_video_mode_no_restart(uint32_t video_mode_id)
429 {
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);
434                 exit(1);
435         }
436
437         if (support == bmdDisplayModeNotSupported) {
438                 fprintf(stderr, "Card %d does not support display mode\n", card_index);
439                 exit(1);
440         }
441
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);
444                 exit(1);
445         }
446
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);
449                 exit(1);
450         }
451
452         current_video_mode = video_mode_id;
453 }
454
455 void DeckLinkCapture::set_video_input(uint32_t video_input_id)
456 {
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);
459                 exit(1);
460         }
461
462         current_video_input = video_input_id;
463 }
464
465 void DeckLinkCapture::set_audio_input(uint32_t audio_input_id)
466 {
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);
469                 exit(1);
470         }
471
472         current_audio_input = audio_input_id;
473 }