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