]> git.sesse.net Git - nageru/blob - decklink_output.cpp
Support DeckLink cards that don't have an HDMI connector.
[nageru] / decklink_output.cpp
1 #include <movit/effect_util.h>
2 #include <movit/util.h>
3 #include <movit/resource_pool.h>  // Must be above the Xlib includes.
4
5 #include <epoxy/egl.h>
6
7 #include "chroma_subsampler.h"
8 #include "decklink_output.h"
9 #include "decklink_util.h"
10 #include "flags.h"
11 #include "print_latency.h"
12 #include "resource_pool.h"
13 #include "timebase.h"
14
15 using namespace movit;
16 using namespace std;
17 using namespace std::chrono;
18
19 DeckLinkOutput::DeckLinkOutput(ResourcePool *resource_pool, QSurface *surface, unsigned width, unsigned height, unsigned card_index)
20         : resource_pool(resource_pool), surface(surface), width(width), height(height), card_index(card_index)
21 {
22         chroma_subsampler.reset(new ChromaSubsampler(resource_pool));
23 }
24
25 void DeckLinkOutput::set_device(IDeckLink *decklink)
26 {
27         if (decklink->QueryInterface(IID_IDeckLinkOutput, (void**)&output) != S_OK) {
28                 fprintf(stderr, "Card %u has no outputs\n", card_index);
29                 exit(1);
30         }
31
32         IDeckLinkDisplayModeIterator *mode_it;
33         if (output->GetDisplayModeIterator(&mode_it) != S_OK) {
34                 fprintf(stderr, "Failed to enumerate output display modes for card %u\n", card_index);
35                 exit(1);
36         }
37
38         video_modes.clear();
39
40         for (const auto &it : summarize_video_modes(mode_it, card_index)) {
41                 if (it.second.width != width || it.second.height != height) {
42                         continue;
43                 }
44
45                 // We could support interlaced modes, but let's stay out of it for now,
46                 // since we don't have interlaced stream output.
47                 if (it.second.interlaced) {
48                         continue;
49                 }
50
51                 video_modes.insert(it);
52         }
53
54         mode_it->Release();
55
56         // HDMI or SDI generally mean “both HDMI and SDI at the same time” on DeckLink cards
57         // that support both; pick_default_video_connection() will generally pick one of those
58         // if they exist. We're not very likely to need analog outputs, so we don't need a way
59         // to change beyond that.
60         video_connection = pick_default_video_connection(decklink, BMDDeckLinkVideoOutputConnections, card_index);
61 }
62
63 void DeckLinkOutput::start_output(uint32_t mode, int64_t base_pts)
64 {
65         assert(output);
66
67         should_quit = false;
68         playback_started = false;
69         this->base_pts = base_pts;
70
71         IDeckLinkConfiguration *config = nullptr;
72         if (output->QueryInterface(IID_IDeckLinkConfiguration, (void**)&config) != S_OK) {
73                 fprintf(stderr, "Failed to get configuration interface for output card\n");
74                 exit(1);
75         }
76         if (config->SetFlag(bmdDeckLinkConfigLowLatencyVideoOutput, true) != S_OK) {
77                 fprintf(stderr, "Failed to set low latency output\n");
78                 exit(1);
79         }
80         if (config->SetInt(bmdDeckLinkConfigVideoOutputConnection, video_connection) != S_OK) {
81                 fprintf(stderr, "Failed to set video output connection for card %u\n", card_index);
82                 exit(1);
83         }
84         if (config->SetFlag(bmdDeckLinkConfigUse1080pNotPsF, true) != S_OK) {
85                 fprintf(stderr, "Failed to set PsF flag for card\n");
86                 exit(1);
87         }
88
89         BMDDisplayModeSupport support;
90         IDeckLinkDisplayMode *display_mode;
91         if (output->DoesSupportVideoMode(mode, bmdFormat8BitYUV, bmdVideoOutputFlagDefault,
92                                          &support, &display_mode) != S_OK) {
93                 fprintf(stderr, "Couldn't ask for format support\n");
94                 exit(1);
95         }
96
97         if (support == bmdDisplayModeNotSupported) {
98                 fprintf(stderr, "Requested display mode not supported\n");
99                 exit(1);
100         }
101
102         BMDDisplayModeFlags flags = display_mode->GetFlags();
103         if ((flags & bmdDisplayModeColorspaceRec601) && global_flags.ycbcr_rec709_coefficients) {
104                 fprintf(stderr, "WARNING: Chosen output mode expects Rec. 601 Y'CbCr coefficients.\n");
105                 fprintf(stderr, "         Consider --output-ycbcr-coefficients=rec601 (or =auto).\n");
106         } else if ((flags & bmdDisplayModeColorspaceRec709) && !global_flags.ycbcr_rec709_coefficients) {
107                 fprintf(stderr, "WARNING: Chosen output mode expects Rec. 709 Y'CbCr coefficients.\n");
108                 fprintf(stderr, "         Consider --output-ycbcr-coefficients=rec709 (or =auto).\n");
109         }
110
111         BMDTimeValue time_value;
112         BMDTimeScale time_scale;
113         if (display_mode->GetFrameRate(&time_value, &time_scale) != S_OK) {
114                 fprintf(stderr, "Couldn't get frame rate\n");
115                 exit(1);
116         }
117
118         frame_duration = time_value * TIMEBASE / time_scale;
119
120         display_mode->Release();
121
122         HRESULT result = output->EnableVideoOutput(mode, bmdVideoOutputFlagDefault);
123         if (result != S_OK) {
124                 fprintf(stderr, "Couldn't enable output with error 0x%x\n", result);
125                 exit(1);
126         }
127         if (output->SetScheduledFrameCompletionCallback(this) != S_OK) {
128                 fprintf(stderr, "Couldn't set callback\n");
129                 exit(1);
130         }
131         assert(OUTPUT_FREQUENCY == 48000);
132         if (output->EnableAudioOutput(bmdAudioSampleRate48kHz, bmdAudioSampleType32bitInteger, 2, bmdAudioOutputStreamTimestamped) != S_OK) {
133                 fprintf(stderr, "Couldn't enable audio output\n");
134                 exit(1);
135         }
136         if (output->BeginAudioPreroll() != S_OK) {
137                 fprintf(stderr, "Couldn't begin audio preroll\n");
138                 exit(1);
139         }
140
141         present_thread = thread([this]{
142                 QOpenGLContext *context = create_context(this->surface);
143                 eglBindAPI(EGL_OPENGL_API);
144                 if (!make_current(context, this->surface)) {
145                         printf("display=%p surface=%p context=%p curr=%p err=%d\n", eglGetCurrentDisplay(), this->surface, context, eglGetCurrentContext(),
146                                 eglGetError());
147                         exit(1);
148                 }
149                 present_thread_func();
150                 delete_context(context);
151         });
152 }
153
154 void DeckLinkOutput::end_output()
155 {
156         should_quit = true;
157         frame_queues_changed.notify_all();
158         present_thread.join();
159
160         output->StopScheduledPlayback(0, nullptr, 0);
161         output->DisableVideoOutput();
162         output->DisableAudioOutput();
163
164         // Wait until all frames are accounted for, and free them.
165         {
166                 unique_lock<mutex> lock(frame_queue_mutex);
167                 while (!(frame_freelist.empty() && num_frames_in_flight == 0)) {
168                         frame_queues_changed.wait(lock, [this]{ return !frame_freelist.empty(); });
169                         frame_freelist.pop();
170                 }
171         }
172 }
173
174 void DeckLinkOutput::send_frame(GLuint y_tex, GLuint cbcr_tex, const vector<RefCountedFrame> &input_frames, int64_t pts, int64_t duration)
175 {
176         unique_ptr<Frame> frame = move(get_frame());
177         chroma_subsampler->create_uyvy(y_tex, cbcr_tex, width, height, frame->uyvy_tex);
178
179         // Download the UYVY texture to the PBO.
180         glPixelStorei(GL_PACK_ROW_LENGTH, 0);
181         check_error();
182
183         glBindBuffer(GL_PIXEL_PACK_BUFFER, frame->pbo);
184         check_error();
185
186         glBindTexture(GL_TEXTURE_2D, frame->uyvy_tex);
187         check_error();
188         glGetTexImage(GL_TEXTURE_2D, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, BUFFER_OFFSET(0));
189         check_error();
190
191         glBindTexture(GL_TEXTURE_2D, 0);
192         check_error();
193         glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
194         check_error();
195
196         glMemoryBarrier(GL_TEXTURE_UPDATE_BARRIER_BIT | GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT);
197         check_error();
198
199         frame->fence = RefCountedGLsync(GL_SYNC_GPU_COMMANDS_COMPLETE, /*flags=*/0);
200         check_error();
201         glFlush();  // Make the DeckLink thread see the fence as soon as possible.
202         check_error();
203
204         frame->input_frames = input_frames;
205         frame->received_ts = find_received_timestamp(input_frames);
206         frame->pts = pts;
207         frame->duration = duration;
208
209         {
210                 unique_lock<mutex> lock(frame_queue_mutex);
211                 pending_video_frames.push(move(frame));
212         }
213         frame_queues_changed.notify_all();
214 }
215
216 void DeckLinkOutput::send_audio(int64_t pts, const std::vector<float> &samples)
217 {
218         unique_ptr<int32_t[]> int_samples(new int32_t[samples.size()]);
219         for (size_t i = 0; i < samples.size(); ++i) {
220                 int_samples[i] = lrintf(samples[i] * 2147483648.0f);
221         }
222
223         uint32_t frames_written;
224         HRESULT result = output->ScheduleAudioSamples(int_samples.get(), samples.size() / 2,
225                 pts, TIMEBASE, &frames_written);
226         if (result != S_OK) {
227                 fprintf(stderr, "ScheduleAudioSamples(pts=%ld) failed (result=0x%08x)\n", pts, result);
228         } else {
229                 if (frames_written != samples.size() / 2) {
230                         fprintf(stderr, "ScheduleAudioSamples() returned short write (%u/%ld)\n", frames_written, samples.size() / 2);
231                 }
232         }
233 }
234
235 void DeckLinkOutput::wait_for_frame(int64_t pts, int *dropped_frames, int64_t *frame_duration)
236 {
237         *dropped_frames = 0;
238         *frame_duration = this->frame_duration;
239
240         const BMDTimeValue buffer = lrint(*frame_duration * global_flags.output_buffer_frames);
241         const BMDTimeValue max_overshoot = lrint(*frame_duration * global_flags.output_slop_frames);
242         BMDTimeValue target_time = pts - buffer;
243
244         // While prerolling, we send out frames as quickly as we can.
245         if (target_time < base_pts) {
246                 return;
247         }
248
249         if (!playback_started) {
250                 if (output->EndAudioPreroll() != S_OK) {
251                         fprintf(stderr, "Could not end audio preroll\n");
252                         exit(1);  // TODO
253                 }
254                 if (output->StartScheduledPlayback(base_pts, TIMEBASE, 1.0) != S_OK) {
255                         fprintf(stderr, "Could not start playback\n");
256                         exit(1);  // TODO
257                 }
258                 playback_started = true;
259         }
260
261         BMDTimeValue stream_frame_time;
262         double playback_speed;
263         output->GetScheduledStreamTime(TIMEBASE, &stream_frame_time, &playback_speed);
264
265         // If we're ahead of time, wait for the frame to (approximately) start.
266         if (stream_frame_time < target_time) {
267                 steady_clock::time_point t = steady_clock::now() +
268                         nanoseconds((target_time - stream_frame_time) * 1000000000 / TIMEBASE);
269                 this_thread::sleep_until(t);
270                 return;
271         }
272
273         // If we overshot the previous frame by just a little,
274         // fire off one immediately.
275         if (stream_frame_time < target_time + max_overshoot) {
276                 fprintf(stderr, "Warning: Frame was %ld ms late (but not skipping it due to --output-slop-frames).\n",
277                         lrint((stream_frame_time - target_time) * 1000.0 / TIMEBASE));
278                 return;
279         }
280
281         // Oops, we missed by more than one frame. Return immediately,
282         // but drop so that we catch up.
283         *dropped_frames = (stream_frame_time - target_time + *frame_duration - 1) / *frame_duration;
284         fprintf(stderr, "Dropped %d output frames; skipping.\n", *dropped_frames);
285 }
286
287 HRESULT DeckLinkOutput::ScheduledFrameCompleted(/* in */ IDeckLinkVideoFrame *completedFrame, /* in */ BMDOutputFrameCompletionResult result)
288 {
289         Frame *frame = static_cast<Frame *>(completedFrame);
290         switch (result) {
291         case bmdOutputFrameCompleted:
292                 break;
293         case bmdOutputFrameDisplayedLate:
294                 fprintf(stderr, "Output frame displayed late (pts=%ld)\n", frame->pts);
295                 fprintf(stderr, "Consider increasing --output-buffer-frames if this persists.\n");
296                 break;
297         case bmdOutputFrameDropped:
298                 fprintf(stderr, "Output frame was dropped (pts=%ld)\n", frame->pts);
299                 fprintf(stderr, "Consider increasing --output-buffer-frames if this persists.\n");
300                 break;
301         case bmdOutputFrameFlushed:
302                 fprintf(stderr, "Output frame was flushed (pts=%ld)\n", frame->pts);
303                 break;
304         default:
305                 fprintf(stderr, "Output frame completed with unknown status %d\n", result);
306                 break;
307         }
308
309         static int hei = 0;
310         print_latency("DeckLink output latency (frame received → output on HDMI):", frame->received_ts, false, &hei);
311
312         {
313                 lock_guard<mutex> lock(frame_queue_mutex);
314                 frame_freelist.push(unique_ptr<Frame>(frame));
315                 --num_frames_in_flight;
316         }
317
318         return S_OK;
319 }
320
321 HRESULT DeckLinkOutput::ScheduledPlaybackHasStopped()
322 {
323         printf("playback stopped!\n");
324         return S_OK;
325 }
326
327 unique_ptr<DeckLinkOutput::Frame> DeckLinkOutput::get_frame()
328 {
329         lock_guard<mutex> lock(frame_queue_mutex);
330
331         if (!frame_freelist.empty()) {
332                 unique_ptr<Frame> frame = move(frame_freelist.front());
333                 frame_freelist.pop();
334                 return frame;
335         }
336
337         unique_ptr<Frame> frame(new Frame);
338
339         frame->uyvy_tex = resource_pool->create_2d_texture(GL_RGBA8, width / 2, height);
340
341         glGenBuffers(1, &frame->pbo);
342         check_error();
343         glBindBuffer(GL_PIXEL_PACK_BUFFER, frame->pbo);
344         check_error();
345         glBufferStorage(GL_PIXEL_PACK_BUFFER, width * height * 2, NULL, GL_MAP_READ_BIT | GL_MAP_PERSISTENT_BIT);
346         check_error();
347         frame->uyvy_ptr = (uint8_t *)glMapBufferRange(GL_PIXEL_PACK_BUFFER, 0, width * height * 2, GL_MAP_READ_BIT | GL_MAP_PERSISTENT_BIT);
348         check_error();
349         frame->uyvy_ptr_local.reset(new uint8_t[width * height * 2]);
350         frame->resource_pool = resource_pool;
351
352         return frame;
353 }
354
355 void DeckLinkOutput::present_thread_func()
356 {
357         for ( ;; ) {
358                 unique_ptr<Frame> frame;
359                 {
360                         unique_lock<mutex> lock(frame_queue_mutex);
361                         frame_queues_changed.wait(lock, [this]{
362                                 return should_quit || !pending_video_frames.empty();
363                         });
364                         if (should_quit) {
365                                 return;
366                         }
367                         frame = move(pending_video_frames.front());
368                         pending_video_frames.pop();
369                         ++num_frames_in_flight;
370                 }
371
372                 glWaitSync(frame->fence.get(), /*flags=*/0, GL_TIMEOUT_IGNORED);
373                 check_error();
374                 frame->fence.reset();
375
376                 memcpy(frame->uyvy_ptr_local.get(), frame->uyvy_ptr, width * height * 2);
377
378                 // Release any input frames we needed to render this frame.
379                 frame->input_frames.clear();
380
381                 BMDTimeValue pts = frame->pts;
382                 BMDTimeValue duration = frame->duration;
383                 HRESULT res = output->ScheduleVideoFrame(frame.get(), pts, duration, TIMEBASE);
384                 if (res == S_OK) {
385                         frame.release();  // Owned by the driver now.
386                 } else {
387                         fprintf(stderr, "Could not schedule video frame! (error=0x%08x)\n", res);
388
389                         lock_guard<mutex> lock(frame_queue_mutex);
390                         frame_freelist.push(move(frame));
391                         --num_frames_in_flight;
392                 }
393         }
394 }
395
396 HRESULT STDMETHODCALLTYPE DeckLinkOutput::QueryInterface(REFIID, LPVOID *)
397 {
398         return E_NOINTERFACE;
399 }
400
401 ULONG STDMETHODCALLTYPE DeckLinkOutput::AddRef()
402 {
403         return refcount.fetch_add(1) + 1;
404 }
405
406 ULONG STDMETHODCALLTYPE DeckLinkOutput::Release()
407 {
408         int new_ref = refcount.fetch_sub(1) - 1;
409         if (new_ref == 0)
410                 delete this;
411         return new_ref;
412 }
413
414 DeckLinkOutput::Frame::~Frame()
415 {
416         glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo);
417         check_error();
418         glUnmapBuffer(GL_PIXEL_PACK_BUFFER);
419         check_error();
420         glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
421         check_error();
422         glDeleteBuffers(1, &pbo);
423         check_error();
424         resource_pool->release_2d_texture(uyvy_tex);
425         check_error();
426 }
427
428 HRESULT STDMETHODCALLTYPE DeckLinkOutput::Frame::QueryInterface(REFIID, LPVOID *)
429 {
430         return E_NOINTERFACE;
431 }
432
433 ULONG STDMETHODCALLTYPE DeckLinkOutput::Frame::AddRef()
434 {
435         return refcount.fetch_add(1) + 1;
436 }
437
438 ULONG STDMETHODCALLTYPE DeckLinkOutput::Frame::Release()
439 {
440         int new_ref = refcount.fetch_sub(1) - 1;
441         if (new_ref == 0)
442                 delete this;
443         return new_ref;
444 }
445
446 long DeckLinkOutput::Frame::GetWidth()
447 {
448         return global_flags.width;
449 }
450
451 long DeckLinkOutput::Frame::GetHeight()
452 {
453         return global_flags.height;
454 }
455
456 long DeckLinkOutput::Frame::GetRowBytes()
457 {
458         return global_flags.width * 2;
459 }
460
461 BMDPixelFormat DeckLinkOutput::Frame::GetPixelFormat()
462 {
463         return bmdFormat8BitYUV;
464 }
465
466 BMDFrameFlags DeckLinkOutput::Frame::GetFlags()
467 {
468         return bmdFrameFlagDefault;
469 }
470
471 HRESULT DeckLinkOutput::Frame::GetBytes(/* out */ void **buffer)
472 {
473         *buffer = uyvy_ptr_local.get();
474         return S_OK;
475 }
476
477 HRESULT DeckLinkOutput::Frame::GetTimecode(/* in */ BMDTimecodeFormat format, /* out */ IDeckLinkTimecode **timecode)
478 {
479         fprintf(stderr, "STUB: GetTimecode()\n");
480         return E_NOTIMPL;
481 }
482
483 HRESULT DeckLinkOutput::Frame::GetAncillaryData(/* out */ IDeckLinkVideoFrameAncillary **ancillary)
484 {
485         fprintf(stderr, "STUB: GetAncillaryData()\n");
486         return E_NOTIMPL;
487 }