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