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