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