]> git.sesse.net Git - nageru/blob - nageru/decklink_capture.cpp
Unify all the FRAME_SIZE #defines.
[nageru] / 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 "shared/memcpy_interleaved.h"
25 #include "v210_converter.h"
26
27 using namespace std;
28 using namespace std::chrono;
29 using namespace std::placeholders;
30 using namespace bmusb;
31
32 namespace {
33
34 BMDPixelFormat pixel_format_to_bmd(PixelFormat pixel_format)
35 {
36         switch (pixel_format) {
37         case PixelFormat_8BitYCbCr:
38                 return bmdFormat8BitYUV;
39         case PixelFormat_10BitYCbCr:
40                 return bmdFormat10BitYUV;
41         default:
42                 assert(false);
43         }
44 }
45
46 }  // namespace
47
48 DeckLinkCapture::DeckLinkCapture(IDeckLink *card, int card_index)
49         : card_index(card_index), card(card)
50 {
51         {
52                 const char *model_name;
53                 char buf[256];
54                 if (card->GetModelName(&model_name) == S_OK) {
55                         snprintf(buf, sizeof(buf), "PCI card %d: %s", card_index, model_name);
56                 } else {
57                         snprintf(buf, sizeof(buf), "PCI card %d: Unknown DeckLink card", card_index);
58                 }
59                 description = buf;
60         }
61
62         if (card->QueryInterface(IID_IDeckLinkInput, (void**)&input) != S_OK) {
63                 fprintf(stderr, "Card %d has no inputs\n", card_index);
64                 abort();
65         }
66
67         IDeckLinkAttributes *attr;
68         if (card->QueryInterface(IID_IDeckLinkAttributes, (void**)&attr) != S_OK) {
69                 fprintf(stderr, "Card %d has no attributes\n", card_index);
70                 abort();
71         }
72
73         // Get the list of available video inputs.
74         int64_t video_input_mask;
75         if (attr->GetInt(BMDDeckLinkVideoInputConnections, &video_input_mask) != S_OK) {
76                 fprintf(stderr, "Failed to enumerate video inputs for card %d\n", card_index);
77                 abort();
78         }
79         const vector<pair<BMDVideoConnection, string>> video_input_types = {
80                 { bmdVideoConnectionSDI, "SDI" },
81                 { bmdVideoConnectionHDMI, "HDMI" },
82                 { bmdVideoConnectionOpticalSDI, "Optical SDI" },
83                 { bmdVideoConnectionComponent, "Component" },
84                 { bmdVideoConnectionComposite, "Composite" },
85                 { bmdVideoConnectionSVideo, "S-Video" }
86         };
87         for (const auto &video_input : video_input_types) {
88                 if (video_input_mask & video_input.first) {
89                         video_inputs.emplace(video_input.first, video_input.second);
90                 }
91         }
92
93         // And then the available audio inputs.
94         int64_t audio_input_mask;
95         if (attr->GetInt(BMDDeckLinkAudioInputConnections, &audio_input_mask) != S_OK) {
96                 fprintf(stderr, "Failed to enumerate audio inputs for card %d\n", card_index);
97                 abort();
98         }
99         const vector<pair<BMDAudioConnection, string>> audio_input_types = {
100                 { bmdAudioConnectionEmbedded, "Embedded" },
101                 { bmdAudioConnectionAESEBU, "AES/EBU" },
102                 { bmdAudioConnectionAnalog, "Analog" },
103                 { bmdAudioConnectionAnalogXLR, "Analog XLR" },
104                 { bmdAudioConnectionAnalogRCA, "Analog RCA" },
105                 { bmdAudioConnectionMicrophone, "Microphone" },
106                 { bmdAudioConnectionHeadphones, "Headphones" }
107         };
108         for (const auto &audio_input : audio_input_types) {
109                 if (audio_input_mask & audio_input.first) {
110                         audio_inputs.emplace(audio_input.first, audio_input.second);
111                 }
112         }
113
114         // Check if we the card supports input autodetection.
115         if (attr->GetFlag(BMDDeckLinkSupportsInputFormatDetection, &supports_autodetect) != S_OK) {
116                 fprintf(stderr, "Warning: Failed to ask card %d whether it supports input format autodetection\n", card_index);
117                 supports_autodetect = false;
118         }
119
120         // If there's more than one subdevice on this card, label them.
121         int64_t num_subdevices, subdevice_idx;
122         if (attr->GetInt(BMDDeckLinkNumberOfSubDevices, &num_subdevices) == S_OK && num_subdevices > 1) {
123                 if (attr->GetInt(BMDDeckLinkSubDeviceIndex, &subdevice_idx) == S_OK) {
124                         char buf[256];
125                         snprintf(buf, sizeof(buf), " (subdevice %d)", int(subdevice_idx));
126                         description += buf;
127                 }
128         }
129
130         attr->Release();
131
132         /* Set up the video and audio sources. */
133         if (card->QueryInterface(IID_IDeckLinkConfiguration, (void**)&config) != S_OK) {
134                 fprintf(stderr, "Failed to get configuration interface for card %d\n", card_index);
135                 abort();
136         }
137
138         BMDVideoConnection connection = pick_default_video_connection(card, BMDDeckLinkVideoInputConnections, card_index);
139
140         set_video_input(connection);
141         set_audio_input(bmdAudioConnectionEmbedded);
142
143         IDeckLinkDisplayModeIterator *mode_it;
144         if (input->GetDisplayModeIterator(&mode_it) != S_OK) {
145                 fprintf(stderr, "Failed to enumerate display modes for card %d\n", card_index);
146                 abort();
147         }
148
149         video_modes = summarize_video_modes(mode_it, card_index);
150         mode_it->Release();
151
152         set_video_mode_no_restart(bmdModeHD720p5994);
153
154         input->SetCallback(this);
155 }
156
157 DeckLinkCapture::~DeckLinkCapture()
158 {
159         if (has_dequeue_callbacks) {
160                 dequeue_cleanup_callback();
161         }
162         input->Release();
163         config->Release();
164         card->Release();
165 }
166
167 HRESULT STDMETHODCALLTYPE DeckLinkCapture::QueryInterface(REFIID, LPVOID *)
168 {
169         return E_NOINTERFACE;
170 }
171
172 ULONG STDMETHODCALLTYPE DeckLinkCapture::AddRef(void)
173 {
174         return refcount.fetch_add(1) + 1;
175 }
176
177 ULONG STDMETHODCALLTYPE DeckLinkCapture::Release(void)
178 {
179         int new_ref = refcount.fetch_sub(1) - 1;
180         if (new_ref == 0)
181                 delete this;
182         return new_ref;
183 }
184
185 HRESULT STDMETHODCALLTYPE DeckLinkCapture::VideoInputFormatChanged(
186         BMDVideoInputFormatChangedEvents,
187         IDeckLinkDisplayMode* display_mode,
188         BMDDetectedVideoInputFormatFlags format_flags)
189 {
190         if (format_flags & bmdDetectedVideoInputRGB444) {
191                 fprintf(stderr, "WARNING: Input detected as 4:4:4 RGB, but Nageru can't consume that yet.\n");
192                 fprintf(stderr, "Doing hardware conversion to 4:2:2 Y'CbCr.\n");
193         }
194         if (supports_autodetect && display_mode->GetDisplayMode() != current_video_mode) {
195                 set_video_mode(display_mode->GetDisplayMode());
196         }
197         if (display_mode->GetFrameRate(&frame_duration, &time_scale) != S_OK) {
198                 fprintf(stderr, "Could not get new frame rate\n");
199                 abort();
200         }
201         field_dominance = display_mode->GetFieldDominance();
202         return S_OK;
203 }
204
205 HRESULT STDMETHODCALLTYPE DeckLinkCapture::VideoInputFrameArrived(
206         IDeckLinkVideoInputFrame *video_frame,
207         IDeckLinkAudioInputPacket *audio_frame)
208 {
209         if (!done_init) {
210                 char thread_name[16];
211                 snprintf(thread_name, sizeof(thread_name), "DeckLink_C_%d", card_index);
212                 pthread_setname_np(pthread_self(), thread_name);
213
214                 sched_param param;
215                 memset(&param, 0, sizeof(param));
216                 param.sched_priority = 1;
217                 if (sched_setscheduler(0, SCHED_RR, &param) == -1) {
218                         printf("couldn't set realtime priority for DeckLink thread: %s\n", strerror(errno));
219                 }
220
221                 if (has_dequeue_callbacks) {
222                         dequeue_init_callback();
223                 }
224                 done_init = true;
225         }
226
227         steady_clock::time_point now = steady_clock::now();
228
229         FrameAllocator::Frame current_video_frame, current_audio_frame;
230         VideoFormat video_format;
231         AudioFormat audio_format;
232
233         video_format.frame_rate_nom = time_scale;
234         video_format.frame_rate_den = frame_duration;
235         // TODO: Respect the TFF/BFF flag.
236         video_format.interlaced = (field_dominance == bmdLowerFieldFirst || field_dominance == bmdUpperFieldFirst);
237         video_format.second_field_start = 1;
238
239         if (video_frame) {
240                 video_format.has_signal = !(video_frame->GetFlags() & bmdFrameHasNoInputSource);
241
242                 const int width = video_frame->GetWidth();
243                 const int height = video_frame->GetHeight();
244                 const int stride = video_frame->GetRowBytes();
245                 const BMDPixelFormat format = video_frame->GetPixelFormat();
246                 assert(format == pixel_format_to_bmd(current_pixel_format));
247                 if (global_flags.bit_depth > 8) {
248                         assert(stride == int(v210Converter::get_v210_stride(width)));
249                 } else {
250                         assert(stride == width * 2);
251                 }
252
253                 current_video_frame = video_frame_allocator->create_frame(width, height, stride);
254                 if (current_video_frame.data != nullptr) {
255                         const uint8_t *src;
256                         video_frame->GetBytes((void **)&src);
257                         size_t num_bytes = stride * height;
258
259                         if (current_video_frame.interleaved) {
260                                 uint8_t *data = current_video_frame.data;
261                                 uint8_t *data2 = current_video_frame.data2;
262                                 memcpy_interleaved(data, data2, src, num_bytes);
263                         } else {
264                                 memcpy(current_video_frame.data, src, num_bytes);
265                         }
266                         if (current_video_frame.data_copy != nullptr) {
267                                 memcpy(current_video_frame.data_copy, src, num_bytes);
268                         }
269                         current_video_frame.len += num_bytes;
270
271                         video_format.width = width;
272                         video_format.height = height;
273                         video_format.stride = stride;
274                 }
275         }
276
277         if (audio_frame) {
278                 int num_samples = audio_frame->GetSampleFrameCount();
279
280                 current_audio_frame = audio_frame_allocator->alloc_frame();
281                 if (current_audio_frame.data != nullptr) {
282                         const uint8_t *src;
283                         audio_frame->GetBytes((void **)&src);
284                         current_audio_frame.len = sizeof(int32_t) * 8 * num_samples;
285
286                         memcpy(current_audio_frame.data, src, current_audio_frame.len);
287
288                         audio_format.bits_per_sample = 32;
289                         audio_format.num_channels = 8;
290                 }
291         }
292
293         current_video_frame.received_timestamp = now;
294         current_audio_frame.received_timestamp = now;
295
296         if (current_video_frame.data != nullptr || current_audio_frame.data != nullptr) {
297                 // TODO: Put into a queue and put into a dequeue thread, if the
298                 // BlackMagic drivers don't already do that for us?
299                 frame_callback(timecode,
300                         current_video_frame, /*video_offset=*/0, video_format,
301                         current_audio_frame, /*audio_offset=*/0, audio_format);
302         }
303
304         timecode++;
305         return S_OK;
306 }
307
308 void DeckLinkCapture::configure_card()
309 {
310         if (video_frame_allocator == nullptr) {
311                 owned_video_frame_allocator.reset(new MallocFrameAllocator(FRAME_SIZE, NUM_QUEUED_VIDEO_FRAMES));
312                 set_video_frame_allocator(owned_video_frame_allocator.get());
313         }
314         if (audio_frame_allocator == nullptr) {
315                 owned_audio_frame_allocator.reset(new MallocFrameAllocator(65536, NUM_QUEUED_AUDIO_FRAMES));
316                 set_audio_frame_allocator(owned_audio_frame_allocator.get());
317         }
318 }
319
320 void DeckLinkCapture::start_bm_capture()
321 {
322         if (running) {
323                 return;
324         }
325         if (input->EnableVideoInput(current_video_mode, pixel_format_to_bmd(current_pixel_format), supports_autodetect ? bmdVideoInputEnableFormatDetection : 0) != S_OK) {
326                 fprintf(stderr, "Failed to set video mode 0x%04x for card %d\n", current_video_mode, card_index);
327                 abort();
328         }
329         if (input->EnableAudioInput(48000, bmdAudioSampleType32bitInteger, 8) != S_OK) {
330                 fprintf(stderr, "Failed to enable audio input for card %d\n", card_index);
331                 abort();
332         }
333
334         if (input->StartStreams() != S_OK) {
335                 fprintf(stderr, "StartStreams failed\n");
336                 abort();
337         }
338         running = true;
339 }
340
341 void DeckLinkCapture::stop_dequeue_thread()
342 {
343         if (!running) {
344                 return;
345         }
346         HRESULT result = input->StopStreams();
347         if (result != S_OK) {
348                 fprintf(stderr, "StopStreams failed with error 0x%x\n", result);
349                 abort();
350         }
351
352         // We could call DisableVideoInput() and DisableAudioInput() here,
353         // but they seem to be taking a really long time, and we only do this
354         // during shutdown anyway (except when switching to output mode,
355         // where DeckLinkOutput does the disabling), so StopStreams() will suffice.
356
357         running = false;
358 }
359
360 void DeckLinkCapture::set_video_mode(uint32_t video_mode_id)
361 {
362         if (running) {
363                 if (input->PauseStreams() != S_OK) {
364                         fprintf(stderr, "PauseStreams failed\n");
365                         abort();
366                 }
367                 if (input->FlushStreams() != S_OK) {
368                         fprintf(stderr, "FlushStreams failed\n");
369                         abort();
370                 }
371         }
372
373         set_video_mode_no_restart(video_mode_id);
374
375         if (running) {
376                 if (input->StartStreams() != S_OK) {
377                         fprintf(stderr, "StartStreams failed\n");
378                         abort();
379                 }
380         }
381 }
382
383 void DeckLinkCapture::set_pixel_format(PixelFormat pixel_format)
384 {
385         current_pixel_format = pixel_format;
386         set_video_mode(current_video_mode);
387 }
388
389 void DeckLinkCapture::set_video_mode_no_restart(uint32_t video_mode_id)
390 {
391         BMDDisplayModeSupport support;
392         IDeckLinkDisplayMode *display_mode;
393         if (input->DoesSupportVideoMode(video_mode_id, pixel_format_to_bmd(current_pixel_format), /*flags=*/0, &support, &display_mode)) {
394                 fprintf(stderr, "Failed to query display mode for card %d\n", card_index);
395                 abort();
396         }
397
398         if (support == bmdDisplayModeNotSupported) {
399                 fprintf(stderr, "Card %d does not support display mode\n", card_index);
400                 abort();
401         }
402
403         if (display_mode->GetFrameRate(&frame_duration, &time_scale) != S_OK) {
404                 fprintf(stderr, "Could not get frame rate for card %d\n", card_index);
405                 abort();
406         }
407
408         field_dominance = display_mode->GetFieldDominance();
409
410         if (running) {
411                 if (input->EnableVideoInput(video_mode_id, pixel_format_to_bmd(current_pixel_format), supports_autodetect ? bmdVideoInputEnableFormatDetection : 0) != S_OK) {
412                         fprintf(stderr, "Failed to set video mode 0x%04x for card %d\n", video_mode_id, card_index);
413                         abort();
414                 }
415         }
416
417         current_video_mode = video_mode_id;
418 }
419
420 void DeckLinkCapture::set_video_input(uint32_t video_input_id)
421 {
422         if (config->SetInt(bmdDeckLinkConfigVideoInputConnection, video_input_id) != S_OK) {
423                 fprintf(stderr, "Failed to set video input connection for card %d\n", card_index);
424                 abort();
425         }
426
427         current_video_input = video_input_id;
428 }
429
430 void DeckLinkCapture::set_audio_input(uint32_t audio_input_id)
431 {
432         if (config->SetInt(bmdDeckLinkConfigAudioInputConnection, audio_input_id) != S_OK) {
433                 fprintf(stderr, "Failed to set audio input connection for card %d\n", card_index);
434                 abort();
435         }
436
437         current_audio_input = audio_input_id;
438 }