]> git.sesse.net Git - nageru/blob - nageru/decklink_capture.cpp
Set CEF autoplay policy to be more lenient.
[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                 current_video_frame = video_frame_allocator->create_frame(width, height, stride);
260                 if (current_video_frame.data != nullptr) {
261                         const uint8_t *src;
262                         video_frame->GetBytes((void **)&src);
263                         size_t num_bytes = stride * height;
264
265                         if (current_video_frame.interleaved) {
266                                 uint8_t *data = current_video_frame.data;
267                                 uint8_t *data2 = current_video_frame.data2;
268                                 memcpy_interleaved(data, data2, src, num_bytes);
269                         } else {
270                                 memcpy(current_video_frame.data, src, num_bytes);
271                         }
272                         if (current_video_frame.data_copy != nullptr) {
273                                 memcpy(current_video_frame.data_copy, src, num_bytes);
274                         }
275                         current_video_frame.len += num_bytes;
276
277                         video_format.width = width;
278                         video_format.height = height;
279                         video_format.stride = stride;
280                 }
281         }
282
283         if (audio_frame) {
284                 int num_samples = audio_frame->GetSampleFrameCount();
285
286                 current_audio_frame = audio_frame_allocator->alloc_frame();
287                 if (current_audio_frame.data != nullptr) {
288                         const uint8_t *src;
289                         audio_frame->GetBytes((void **)&src);
290                         current_audio_frame.len = sizeof(int32_t) * 8 * num_samples;
291
292                         memcpy(current_audio_frame.data, src, current_audio_frame.len);
293
294                         audio_format.bits_per_sample = 32;
295                         audio_format.num_channels = 8;
296                 }
297         }
298
299         current_video_frame.received_timestamp = now;
300         current_audio_frame.received_timestamp = now;
301
302         if (current_video_frame.data != nullptr || current_audio_frame.data != nullptr) {
303                 // TODO: Put into a queue and put into a dequeue thread, if the
304                 // BlackMagic drivers don't already do that for us?
305                 frame_callback(timecode,
306                         current_video_frame, /*video_offset=*/0, video_format,
307                         current_audio_frame, /*audio_offset=*/0, audio_format);
308         }
309
310         timecode++;
311         return S_OK;
312 }
313
314 void DeckLinkCapture::configure_card()
315 {
316         if (video_frame_allocator == nullptr) {
317                 owned_video_frame_allocator.reset(new MallocFrameAllocator(FRAME_SIZE, NUM_QUEUED_VIDEO_FRAMES));
318                 set_video_frame_allocator(owned_video_frame_allocator.get());
319         }
320         if (audio_frame_allocator == nullptr) {
321                 owned_audio_frame_allocator.reset(new MallocFrameAllocator(65536, NUM_QUEUED_AUDIO_FRAMES));
322                 set_audio_frame_allocator(owned_audio_frame_allocator.get());
323         }
324 }
325
326 void DeckLinkCapture::start_bm_capture()
327 {
328         if (running) {
329                 return;
330         }
331         if (input->EnableVideoInput(current_video_mode, pixel_format_to_bmd(current_pixel_format), supports_autodetect ? bmdVideoInputEnableFormatDetection : 0) != S_OK) {
332                 fprintf(stderr, "Failed to set video mode 0x%04x for card %d\n", current_video_mode, card_index);
333                 abort();
334         }
335         if (input->EnableAudioInput(48000, bmdAudioSampleType32bitInteger, 8) != S_OK) {
336                 fprintf(stderr, "Failed to enable audio input for card %d\n", card_index);
337                 abort();
338         }
339
340         if (input->StartStreams() != S_OK) {
341                 fprintf(stderr, "StartStreams failed\n");
342                 abort();
343         }
344         running = true;
345 }
346
347 void DeckLinkCapture::stop_dequeue_thread()
348 {
349         if (!running) {
350                 return;
351         }
352         HRESULT result = input->StopStreams();
353         if (result != S_OK) {
354                 fprintf(stderr, "StopStreams failed with error 0x%x\n", result);
355                 abort();
356         }
357
358         // We could call DisableVideoInput() and DisableAudioInput() here,
359         // but they seem to be taking a really long time, and we only do this
360         // during shutdown anyway (except when switching to output mode,
361         // where DeckLinkOutput does the disabling), so StopStreams() will suffice.
362
363         running = false;
364 }
365
366 void DeckLinkCapture::set_video_mode(uint32_t video_mode_id)
367 {
368         if (running) {
369                 if (input->PauseStreams() != S_OK) {
370                         fprintf(stderr, "PauseStreams failed\n");
371                         abort();
372                 }
373                 if (input->FlushStreams() != S_OK) {
374                         fprintf(stderr, "FlushStreams failed\n");
375                         abort();
376                 }
377         }
378
379         set_video_mode_no_restart(video_mode_id);
380
381         if (running) {
382                 if (input->StartStreams() != S_OK) {
383                         fprintf(stderr, "StartStreams failed\n");
384                         abort();
385                 }
386         }
387 }
388
389 void DeckLinkCapture::set_pixel_format(PixelFormat pixel_format)
390 {
391         current_pixel_format = pixel_format;
392         set_video_mode(current_video_mode);
393 }
394
395 void DeckLinkCapture::set_video_mode_no_restart(uint32_t video_mode_id)
396 {
397         BMDDisplayModeSupport support;
398         IDeckLinkDisplayMode *display_mode;
399         if (input->DoesSupportVideoMode(video_mode_id, pixel_format_to_bmd(current_pixel_format), /*flags=*/0, &support, &display_mode)) {
400                 fprintf(stderr, "Failed to query display mode for card %d\n", card_index);
401                 abort();
402         }
403
404         if (support == bmdDisplayModeNotSupported) {
405                 fprintf(stderr, "Card %d does not support display mode\n", card_index);
406                 abort();
407         }
408
409         if (display_mode->GetFrameRate(&frame_duration, &time_scale) != S_OK) {
410                 fprintf(stderr, "Could not get frame rate for card %d\n", card_index);
411                 abort();
412         }
413
414         field_dominance = display_mode->GetFieldDominance();
415
416         if (running) {
417                 if (input->EnableVideoInput(video_mode_id, pixel_format_to_bmd(current_pixel_format), supports_autodetect ? bmdVideoInputEnableFormatDetection : 0) != S_OK) {
418                         fprintf(stderr, "Failed to set video mode 0x%04x for card %d\n", video_mode_id, card_index);
419                         abort();
420                 }
421         }
422
423         current_video_mode = video_mode_id;
424 }
425
426 void DeckLinkCapture::set_video_input(uint32_t video_input_id)
427 {
428         if (config->SetInt(bmdDeckLinkConfigVideoInputConnection, video_input_id) != S_OK) {
429                 fprintf(stderr, "Failed to set video input connection for card %d\n", card_index);
430                 abort();
431         }
432
433         current_video_input = video_input_id;
434 }
435
436 void DeckLinkCapture::set_audio_input(uint32_t audio_input_id)
437 {
438         if (config->SetInt(bmdDeckLinkConfigAudioInputConnection, audio_input_id) != S_OK) {
439                 fprintf(stderr, "Failed to set audio input connection for card %d\n", card_index);
440                 abort();
441         }
442
443         current_audio_input = audio_input_id;
444 }