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