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