]> git.sesse.net Git - nageru/blob - decklink_capture.cpp
Fix an off-by-one copy in memcpy_interleaved_fastpath().
[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
24 namespace {
25
26 // TODO: Support stride.
27 void memcpy_interleaved(uint8_t *dest1, uint8_t *dest2, const uint8_t *src, size_t n)
28 {
29         assert(n % 2 == 0);
30         uint8_t *dptr1 = dest1;
31         uint8_t *dptr2 = dest2;
32
33         for (size_t i = 0; i < n; i += 2) {
34                 *dptr1++ = *src++;
35                 *dptr2++ = *src++;
36         }
37 }
38
39 #ifdef __SSE2__
40
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)
43 {
44         const uint8_t *limit = src + n;
45         size_t consumed = 0;
46
47         // Align end to 32 bytes.
48         limit = (const uint8_t *)(intptr_t(limit) & ~31);
49
50         if (src >= limit) {
51                 return 0;
52         }
53
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);
59                 dest1 += n2 / 2;
60                 dest2 += n2 / 2;
61                 if (n2 % 2) {
62                         swap(dest1, dest2);
63                 }
64                 src = aligned_src;
65                 consumed += n2;
66         }
67
68         // Make the length a multiple of 64.
69         if (((limit - src) % 64) != 0) {
70                 limit -= 32;
71         }
72         assert(((limit - src) % 64) == 0);
73
74 #if __AVX2__
75         const __m256i * __restrict in = (const __m256i *)src;
76         __m256i * __restrict out1 = (__m256i *)dest1;
77         __m256i * __restrict out2 = (__m256i *)dest2;
78
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
86
87                 data1 = _mm256_shuffle_epi8(data1, shuffle_cw);       // ABCDabcd EFGHefgh
88                 data2 = _mm256_shuffle_epi8(data2, shuffle_cw);       // IJKLijkl MNOPmnop
89         
90                 data1 = _mm256_permute4x64_epi64(data1, 0b11011000);  // ABCDEFGH abcdefgh
91                 data2 = _mm256_permute4x64_epi64(data2, 0b11011000);  // IJKLMNOP ijklmnop
92
93                 __m256i lo = _mm256_permute2x128_si256(data1, data2, 0b00100000);
94                 __m256i hi = _mm256_permute2x128_si256(data1, data2, 0b00110001);
95
96                 _mm256_storeu_si256(out1, lo);
97                 _mm256_storeu_si256(out2, hi);
98
99                 in += 2;
100                 ++out1;
101                 ++out2;
102                 consumed += 64;
103         }
104 #else
105         const __m128i * __restrict in = (const __m128i *)src;
106         __m128i * __restrict out1 = (__m128i *)dest1;
107         __m128i * __restrict out2 = (__m128i *)dest2;
108
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);
121
122                 in += 2;
123                 ++out1;
124                 ++out2;
125                 consumed += 32;
126         }
127 #endif
128
129         return consumed;
130 }
131
132 #endif  // __SSE2__
133
134 }  // namespace
135
136 DeckLinkCapture::DeckLinkCapture(IDeckLink *card, int card_index)
137         : card_index(card_index), card(card)
138 {
139         {
140                 const char *model_name;
141                 char buf[256];
142                 if (card->GetModelName(&model_name) == S_OK) {
143                         snprintf(buf, sizeof(buf), "PCI card %d: %s", card_index, model_name);
144                 } else {
145                         snprintf(buf, sizeof(buf), "PCI card %d: Unknown DeckLink card", card_index);
146                 }
147                 description = buf;
148         }
149
150         if (card->QueryInterface(IID_IDeckLinkInput, (void**)&input) != S_OK) {
151                 fprintf(stderr, "Card %d has no inputs\n", card_index);
152                 exit(1);
153         }
154
155         IDeckLinkAttributes *attr;
156         if (card->QueryInterface(IID_IDeckLinkAttributes, (void**)&attr) != S_OK) {
157                 fprintf(stderr, "Card %d has no attributes\n", card_index);
158                 exit(1);
159         }
160
161         // Get the list of available video inputs.
162         int64_t video_input_mask;
163         if (attr->GetInt(BMDDeckLinkVideoInputConnections, &video_input_mask) != S_OK) {
164                 fprintf(stderr, "Failed to enumerate video inputs for card %d\n", card_index);
165                 exit(1);
166         }
167         const vector<pair<BMDVideoConnection, string>> video_input_types = {
168                 { bmdVideoConnectionSDI, "SDI" },
169                 { bmdVideoConnectionHDMI, "HDMI" },
170                 { bmdVideoConnectionOpticalSDI, "Optical SDI" },
171                 { bmdVideoConnectionComponent, "Component" },
172                 { bmdVideoConnectionComposite, "Composite" },
173                 { bmdVideoConnectionSVideo, "S-Video" }
174         };
175         for (const auto &video_input : video_input_types) {
176                 if (video_input_mask & video_input.first) {
177                         video_inputs.emplace(video_input.first, video_input.second);
178                 }
179         }
180
181         // And then the available audio inputs.
182         int64_t audio_input_mask;
183         if (attr->GetInt(BMDDeckLinkAudioInputConnections, &audio_input_mask) != S_OK) {
184                 fprintf(stderr, "Failed to enumerate audio inputs for card %d\n", card_index);
185                 exit(1);
186         }
187         const vector<pair<BMDAudioConnection, string>> audio_input_types = {
188                 { bmdAudioConnectionEmbedded, "Embedded" },
189                 { bmdAudioConnectionAESEBU, "AES/EBU" },
190                 { bmdAudioConnectionAnalog, "Analog" },
191                 { bmdAudioConnectionAnalogXLR, "Analog XLR" },
192                 { bmdAudioConnectionAnalogRCA, "Analog RCA" },
193                 { bmdAudioConnectionMicrophone, "Microphone" },
194                 { bmdAudioConnectionHeadphones, "Headphones" }
195         };
196         for (const auto &audio_input : audio_input_types) {
197                 if (audio_input_mask & audio_input.first) {
198                         audio_inputs.emplace(audio_input.first, audio_input.second);
199                 }
200         }
201
202         attr->Release();
203
204         /* Set up the video and audio sources. */
205         if (card->QueryInterface(IID_IDeckLinkConfiguration, (void**)&config) != S_OK) {
206                 fprintf(stderr, "Failed to get configuration interface for card %d\n", card_index);
207                 exit(1);
208         }
209
210         set_video_input(bmdVideoConnectionHDMI);
211         set_audio_input(bmdAudioConnectionEmbedded);
212
213         IDeckLinkDisplayModeIterator *mode_it;
214         if (input->GetDisplayModeIterator(&mode_it) != S_OK) {
215                 fprintf(stderr, "Failed to enumerate display modes for card %d\n", card_index);
216                 exit(1);
217         }
218
219         for (IDeckLinkDisplayMode *mode_ptr; mode_it->Next(&mode_ptr) == S_OK; mode_ptr->Release()) {
220                 VideoMode mode;
221
222                 const char *mode_name;
223                 if (mode_ptr->GetName(&mode_name) != S_OK) {
224                         mode.name = "Unknown mode";
225                 } else {
226                         mode.name = mode_name;
227                 }
228
229                 mode.autodetect = false;
230
231                 mode.width = mode_ptr->GetWidth();
232                 mode.height = mode_ptr->GetHeight();
233
234                 BMDTimeScale frame_rate_num;
235                 BMDTimeValue frame_rate_den;
236                 if (mode_ptr->GetFrameRate(&frame_rate_den, &frame_rate_num) != S_OK) {
237                         fprintf(stderr, "Could not get frame rate for mode '%s' on card %d\n", mode.name.c_str(), card_index);
238                         exit(1);
239                 }
240                 mode.frame_rate_num = frame_rate_num;
241                 mode.frame_rate_den = frame_rate_den;
242
243                 // TODO: Respect the TFF/BFF flag.
244                 mode.interlaced = (mode_ptr->GetFieldDominance() == bmdLowerFieldFirst || mode_ptr->GetFieldDominance() == bmdUpperFieldFirst);
245
246                 uint32_t id = mode_ptr->GetDisplayMode();
247                 video_modes.insert(make_pair(id, mode));
248         }
249
250         set_video_mode_no_restart(bmdModeHD720p5994);
251
252         if (input->EnableAudioInput(48000, bmdAudioSampleType32bitInteger, 2) != S_OK) {
253                 fprintf(stderr, "Failed to enable audio input for card %d\n", card_index);
254                 exit(1);
255         }
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         return S_OK;
298 }
299
300 HRESULT STDMETHODCALLTYPE DeckLinkCapture::VideoInputFrameArrived(
301         IDeckLinkVideoInputFrame *video_frame,
302         IDeckLinkAudioInputPacket *audio_frame)
303 {
304         if (!done_init) {
305                 if (has_dequeue_callbacks) {
306                         dequeue_init_callback();
307                 }
308                 done_init = true;
309         }
310
311         FrameAllocator::Frame current_video_frame, current_audio_frame;
312         VideoFormat video_format;
313         AudioFormat audio_format;
314
315         video_format.frame_rate_nom = time_scale;
316         video_format.frame_rate_den = frame_duration;
317
318         if (video_frame) {
319                 video_format.has_signal = !(video_frame->GetFlags() & bmdFrameHasNoInputSource);
320
321                 int width = video_frame->GetWidth();
322                 int height = video_frame->GetHeight();
323                 const int stride = video_frame->GetRowBytes();
324                 assert(stride == width * 2);
325
326                 current_video_frame = video_frame_allocator->alloc_frame();
327                 if (current_video_frame.data != nullptr) {
328                         const uint8_t *frame_bytes;
329                         video_frame->GetBytes((void **)&frame_bytes);
330
331                         uint8_t *data = current_video_frame.data;
332                         uint8_t *data2 = current_video_frame.data2;
333                         size_t num_bytes = width * height * 2;
334 #ifdef __SSE2__
335                         size_t consumed = memcpy_interleaved_fastpath(data, data2, frame_bytes, num_bytes);
336                         frame_bytes += consumed;
337                         data += consumed / 2;
338                         data2 += consumed / 2;
339                         if (num_bytes % 2) {
340                                 swap(data, data2);
341                         }
342                         current_video_frame.len += consumed;
343                         num_bytes -= consumed;
344 #endif
345
346                         if (num_bytes > 0) {
347                                 memcpy_interleaved(data, data2, frame_bytes, num_bytes);
348                         }
349                         current_video_frame.len += num_bytes;
350
351                         video_format.width = width;
352                         video_format.height = height;
353                 }
354         }
355
356         if (audio_frame) {
357                 int num_samples = audio_frame->GetSampleFrameCount();
358
359                 current_audio_frame = audio_frame_allocator->alloc_frame();
360                 if (current_audio_frame.data != nullptr) {
361                         const uint8_t *frame_bytes;
362                         audio_frame->GetBytes((void **)&frame_bytes);
363                         current_audio_frame.len = sizeof(int32_t) * 2 * num_samples;
364
365                         memcpy(current_audio_frame.data, frame_bytes, current_audio_frame.len);
366
367                         audio_format.bits_per_sample = 32;
368                         audio_format.num_channels = 2;
369                 }
370         }
371
372         if (current_video_frame.data != nullptr || current_audio_frame.data != nullptr) {
373                 // TODO: Put into a queue and put into a dequeue thread, if the
374                 // BlackMagic drivers don't already do that for us?
375                 frame_callback(timecode,
376                         current_video_frame, /*video_offset=*/0, video_format,
377                         current_audio_frame, /*audio_offset=*/0, audio_format);
378         }
379
380         timecode++;
381         return S_OK;
382 }
383
384 void DeckLinkCapture::configure_card()
385 {
386         if (video_frame_allocator == nullptr) {
387                 owned_video_frame_allocator.reset(new MallocFrameAllocator(FRAME_SIZE, NUM_QUEUED_VIDEO_FRAMES));
388                 set_video_frame_allocator(owned_video_frame_allocator.get());
389         }
390         if (audio_frame_allocator == nullptr) {
391                 owned_audio_frame_allocator.reset(new MallocFrameAllocator(65536, NUM_QUEUED_AUDIO_FRAMES));
392                 set_audio_frame_allocator(owned_audio_frame_allocator.get());
393         }
394 }
395
396 void DeckLinkCapture::start_bm_capture()
397 {
398         if (input->StartStreams() != S_OK) {
399                 fprintf(stderr, "StartStreams failed\n");
400                 exit(1);
401         }
402 }
403
404 void DeckLinkCapture::stop_dequeue_thread()
405 {
406         if (input->StopStreams() != S_OK) {
407                 fprintf(stderr, "StopStreams failed\n");
408                 exit(1);
409         }
410 }
411
412 void DeckLinkCapture::set_video_mode(uint32_t video_mode_id)
413 {
414         if (input->StopStreams() != S_OK) {
415                 fprintf(stderr, "StopStreams failed\n");
416                 exit(1);
417         }
418
419         set_video_mode_no_restart(video_mode_id);
420
421         if (input->StartStreams() != S_OK) {
422                 fprintf(stderr, "StartStreams failed\n");
423                 exit(1);
424         }
425 }
426
427 void DeckLinkCapture::set_video_mode_no_restart(uint32_t video_mode_id)
428 {
429         BMDDisplayModeSupport support;
430         IDeckLinkDisplayMode *display_mode;
431         if (input->DoesSupportVideoMode(video_mode_id, bmdFormat8BitYUV, /*flags=*/0, &support, &display_mode)) {
432                 fprintf(stderr, "Failed to query display mode for card %d\n", card_index);
433                 exit(1);
434         }
435
436         if (support == bmdDisplayModeNotSupported) {
437                 fprintf(stderr, "Card %d does not support display mode\n", card_index);
438                 exit(1);
439         }
440
441         if (display_mode->GetFrameRate(&frame_duration, &time_scale) != S_OK) {
442                 fprintf(stderr, "Could not get frame rate for card %d\n", card_index);
443                 exit(1);
444         }
445
446         if (input->EnableVideoInput(video_mode_id, bmdFormat8BitYUV, 0) != S_OK) {
447                 fprintf(stderr, "Failed to set video mode 0x%04x for card %d\n", video_mode_id, card_index);
448                 exit(1);
449         }
450
451         current_video_mode = video_mode_id;
452 }
453
454 void DeckLinkCapture::set_video_input(uint32_t video_input_id)
455 {
456         if (config->SetInt(bmdDeckLinkConfigVideoInputConnection, video_input_id) != S_OK) {
457                 fprintf(stderr, "Failed to set video input connection for card %d\n", card_index);
458                 exit(1);
459         }
460
461         current_video_input = video_input_id;
462 }
463
464 void DeckLinkCapture::set_audio_input(uint32_t audio_input_id)
465 {
466         if (config->SetInt(bmdDeckLinkConfigAudioInputConnection, audio_input_id) != S_OK) {
467                 fprintf(stderr, "Failed to set audio input connection for card %d\n", card_index);
468                 exit(1);
469         }
470
471         current_audio_input = audio_input_id;
472 }