]> git.sesse.net Git - nageru/blob - nageru/decklink_output.cpp
Small indent fix.
[nageru] / 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 #include <pthread.h>
5 #include <unistd.h>
6
7 #include <mutex>
8
9 #include <epoxy/egl.h>
10
11 #include "chroma_subsampler.h"
12 #include "decklink_output.h"
13 #include "decklink_util.h"
14 #include "flags.h"
15 #include "shared/metrics.h"
16 #include "print_latency.h"
17 #include "shared/timebase.h"
18 #include "v210_converter.h"
19
20 using namespace movit;
21 using namespace std;
22 using namespace std::chrono;
23
24 namespace {
25
26 // This class can be deleted during regular use, so make all the metrics static.
27 once_flag decklink_metrics_inited;
28 LatencyHistogram latency_histogram;
29 atomic<int64_t> metric_decklink_output_width_pixels{-1};
30 atomic<int64_t> metric_decklink_output_height_pixels{-1};
31 atomic<int64_t> metric_decklink_output_frame_rate_den{-1};
32 atomic<int64_t> metric_decklink_output_frame_rate_nom{-1};
33 atomic<int64_t> metric_decklink_output_inflight_frames{0};
34 atomic<int64_t> metric_decklink_output_color_mismatch_frames{0};
35
36 atomic<int64_t> metric_decklink_output_scheduled_frames_dropped{0};
37 atomic<int64_t> metric_decklink_output_scheduled_frames_late{0};
38 atomic<int64_t> metric_decklink_output_scheduled_frames_normal{0};
39 atomic<int64_t> metric_decklink_output_scheduled_frames_preroll{0};
40
41 atomic<int64_t> metric_decklink_output_completed_frames_completed{0};
42 atomic<int64_t> metric_decklink_output_completed_frames_dropped{0};
43 atomic<int64_t> metric_decklink_output_completed_frames_flushed{0};
44 atomic<int64_t> metric_decklink_output_completed_frames_late{0};
45 atomic<int64_t> metric_decklink_output_completed_frames_unknown{0};
46
47 atomic<int64_t> metric_decklink_output_scheduled_samples{0};
48
49 Summary metric_decklink_output_margin_seconds;
50
51 }  // namespace
52
53 DeckLinkOutput::DeckLinkOutput(ResourcePool *resource_pool, QSurface *surface, unsigned width, unsigned height, unsigned card_index)
54         : resource_pool(resource_pool), surface(surface), width(width), height(height), card_index(card_index)
55 {
56         chroma_subsampler.reset(new ChromaSubsampler(resource_pool));
57
58         call_once(decklink_metrics_inited, [](){
59                 latency_histogram.init("decklink_output");
60                 global_metrics.add("decklink_output_width_pixels", &metric_decklink_output_width_pixels, Metrics::TYPE_GAUGE);
61                 global_metrics.add("decklink_output_height_pixels", &metric_decklink_output_height_pixels, Metrics::TYPE_GAUGE);
62                 global_metrics.add("decklink_output_frame_rate_den", &metric_decklink_output_frame_rate_den, Metrics::TYPE_GAUGE);
63                 global_metrics.add("decklink_output_frame_rate_nom", &metric_decklink_output_frame_rate_nom, Metrics::TYPE_GAUGE);
64                 global_metrics.add("decklink_output_inflight_frames", &metric_decklink_output_inflight_frames, Metrics::TYPE_GAUGE);
65                 global_metrics.add("decklink_output_color_mismatch_frames", &metric_decklink_output_color_mismatch_frames);
66
67                 global_metrics.add("decklink_output_scheduled_frames", {{ "status", "dropped" }}, &metric_decklink_output_scheduled_frames_dropped);
68                 global_metrics.add("decklink_output_scheduled_frames", {{ "status", "late" }}, &metric_decklink_output_scheduled_frames_late);
69                 global_metrics.add("decklink_output_scheduled_frames", {{ "status", "normal" }}, &metric_decklink_output_scheduled_frames_normal);
70                 global_metrics.add("decklink_output_scheduled_frames", {{ "status", "preroll" }}, &metric_decklink_output_scheduled_frames_preroll);
71
72                 global_metrics.add("decklink_output_completed_frames", {{ "status", "completed" }}, &metric_decklink_output_completed_frames_completed);
73                 global_metrics.add("decklink_output_completed_frames", {{ "status", "dropped" }}, &metric_decklink_output_completed_frames_dropped);
74                 global_metrics.add("decklink_output_completed_frames", {{ "status", "flushed" }}, &metric_decklink_output_completed_frames_flushed);
75                 global_metrics.add("decklink_output_completed_frames", {{ "status", "late" }}, &metric_decklink_output_completed_frames_late);
76                 global_metrics.add("decklink_output_completed_frames", {{ "status", "unknown" }}, &metric_decklink_output_completed_frames_unknown);
77
78                 global_metrics.add("decklink_output_scheduled_samples", &metric_decklink_output_scheduled_samples);
79                 vector<double> quantiles{0.01, 0.1, 0.25, 0.5, 0.75, 0.9, 0.99};
80                 metric_decklink_output_margin_seconds.init(quantiles, 60.0);
81                 global_metrics.add("decklink_output_margin_seconds", &metric_decklink_output_margin_seconds);
82         });
83 }
84
85 bool DeckLinkOutput::set_device(IDeckLink *decklink)
86 {
87         if (decklink->QueryInterface(IID_IDeckLinkInput, (void**)&input) != S_OK) {
88                 input = nullptr;
89         }
90         if (decklink->QueryInterface(IID_IDeckLinkOutput, (void**)&output) != S_OK) {
91                 fprintf(stderr, "Warning: Card %u has no outputs\n", card_index);
92                 return false;
93         }
94
95         IDeckLinkDisplayModeIterator *mode_it;
96         if (output->GetDisplayModeIterator(&mode_it) != S_OK) {
97                 fprintf(stderr, "Warning: Failed to enumerate output display modes for card %u\n", card_index);
98                 return false;
99         }
100
101         video_modes.clear();
102
103         for (const auto &it : summarize_video_modes(mode_it, card_index)) {
104                 if (it.second.width != width || it.second.height != height) {
105                         continue;
106                 }
107
108                 // We could support interlaced modes, but let's stay out of it for now,
109                 // since we don't have interlaced stream output.
110                 if (it.second.interlaced) {
111                         continue;
112                 }
113
114                 video_modes.insert(it);
115         }
116
117         mode_it->Release();
118
119         // HDMI or SDI generally mean “both HDMI and SDI at the same time” on DeckLink cards
120         // that support both; pick_default_video_connection() will generally pick one of those
121         // if they exist. (--prefer-hdmi-input would also affect the selection despite the name
122         // of the option, but since either generally means both, it's inconsequential.)
123         // We're not very likely to need analog outputs, so we don't need a way to change
124         // beyond that.
125         video_connection = pick_default_video_connection(decklink, BMDDeckLinkVideoOutputConnections, card_index);
126         return true;
127 }
128
129 void DeckLinkOutput::start_output(uint32_t mode, int64_t base_pts)
130 {
131         assert(output);
132         assert(!playback_initiated);
133
134         if (video_modes.empty()) {
135                 fprintf(stderr, "ERROR: No matching output modes for %dx%d found\n", width, height);
136                 abort();
137         }
138
139         should_quit.unquit();
140         playback_initiated = true;
141         playback_started = false;
142         this->base_pts = base_pts;
143
144         IDeckLinkConfiguration *config = nullptr;
145         if (output->QueryInterface(IID_IDeckLinkConfiguration, (void**)&config) != S_OK) {
146                 fprintf(stderr, "Failed to get configuration interface for output card\n");
147                 abort();
148         }
149         if (config->SetFlag(bmdDeckLinkConfigLowLatencyVideoOutput, true) != S_OK) {
150                 fprintf(stderr, "Failed to set low latency output\n");
151                 abort();
152         }
153         if (config->SetInt(bmdDeckLinkConfigVideoOutputConnection, video_connection) != S_OK) {
154                 fprintf(stderr, "Failed to set video output connection for card %u\n", card_index);
155                 abort();
156         }
157         if (config->SetFlag(bmdDeckLinkConfigOutput1080pAsPsF, true) != S_OK) {
158                 fprintf(stderr, "Failed to set PsF flag for card\n");
159                 abort();
160         }
161         if (config->SetFlag(bmdDeckLinkConfigSMPTELevelAOutput, true) != S_OK) {
162                 // This affects at least some no-name SDI->HDMI converters.
163                 // Warn, but don't die.
164                 fprintf(stderr, "WARNING: Failed to enable SMTPE Level A; resolutions like 1080p60 might have issues.\n");
165         }
166
167         BMDDisplayModeSupport support;
168         IDeckLinkDisplayMode *display_mode;
169         BMDPixelFormat pixel_format = global_flags.ten_bit_output ? bmdFormat10BitYUV : bmdFormat8BitYUV;
170         if (output->DoesSupportVideoMode(mode, pixel_format, bmdVideoOutputFlagDefault,
171                                          &support, &display_mode) != S_OK) {
172                 fprintf(stderr, "Couldn't ask for format support\n");
173                 abort();
174         }
175
176         if (support == bmdDisplayModeNotSupported) {
177                 fprintf(stderr, "Requested display mode not supported\n");
178                 abort();
179         }
180
181         current_mode_flags = display_mode->GetFlags();
182
183         BMDTimeValue time_value;
184         BMDTimeScale time_scale;
185         if (display_mode->GetFrameRate(&time_value, &time_scale) != S_OK) {
186                 fprintf(stderr, "Couldn't get frame rate\n");
187                 abort();
188         }
189
190         metric_decklink_output_width_pixels = width;
191         metric_decklink_output_height_pixels = height;
192         metric_decklink_output_frame_rate_nom = time_value;
193         metric_decklink_output_frame_rate_den = time_scale;
194
195         frame_duration = time_value * TIMEBASE / time_scale;
196
197         display_mode->Release();
198
199         if (input != nullptr) {
200                 if (input->DisableVideoInput() != S_OK) {
201                         fprintf(stderr, "Warning: Failed to disable video input for card %d\n", card_index);
202                 }
203                 if (input->DisableAudioInput() != S_OK) {
204                         fprintf(stderr, "Warning: Failed to disable audio input for card %d\n", card_index);
205                 }
206         }
207
208         HRESULT result = output->EnableVideoOutput(mode, bmdVideoOutputFlagDefault);
209         if (result != S_OK) {
210                 fprintf(stderr, "Couldn't enable output with error 0x%x\n", result);
211                 abort();
212         }
213         if (output->SetScheduledFrameCompletionCallback(this) != S_OK) {
214                 fprintf(stderr, "Couldn't set callback\n");
215                 abort();
216         }
217         assert(OUTPUT_FREQUENCY == 48000);
218         if (output->EnableAudioOutput(bmdAudioSampleRate48kHz, bmdAudioSampleType32bitInteger, 2, bmdAudioOutputStreamTimestamped) != S_OK) {
219                 fprintf(stderr, "Couldn't enable audio output\n");
220                 abort();
221         }
222         if (output->BeginAudioPreroll() != S_OK) {
223                 fprintf(stderr, "Couldn't begin audio preroll\n");
224                 abort();
225         }
226
227         present_thread = thread([this]{
228                 QOpenGLContext *context = create_context(this->surface);
229                 eglBindAPI(EGL_OPENGL_API);
230                 if (!make_current(context, this->surface)) {
231                         printf("display=%p surface=%p context=%p curr=%p err=%d\n", eglGetCurrentDisplay(), this->surface, context, eglGetCurrentContext(),
232                                 eglGetError());
233                         abort();
234                 }
235                 present_thread_func();
236                 delete_context(context);
237         });
238 }
239
240 void DeckLinkOutput::end_output()
241 {
242         if (!playback_initiated) {
243                 return;
244         }
245
246         should_quit.quit();
247         frame_queues_changed.notify_all();
248         present_thread.join();
249         playback_initiated = false;
250
251         output->StopScheduledPlayback(0, nullptr, 0);
252         output->DisableVideoOutput();
253         output->DisableAudioOutput();
254
255         // Wait until all frames are accounted for, and free them.
256         {
257                 unique_lock<mutex> lock(frame_queue_mutex);
258                 while (!(frame_freelist.empty() && num_frames_in_flight == 0)) {
259                         frame_queues_changed.wait(lock, [this]{ return !frame_freelist.empty(); });
260                         frame_freelist.pop();
261                 }
262         }
263
264         if (input != nullptr) {
265                 input->Release();
266                 input = nullptr;
267         }
268         if (output != nullptr) {
269                 output->Release();
270                 output = nullptr;
271         }
272 }
273
274 void DeckLinkOutput::send_frame(GLuint y_tex, GLuint cbcr_tex, YCbCrLumaCoefficients output_ycbcr_coefficients, const vector<RefCountedFrame> &input_frames, int64_t pts, int64_t duration)
275 {
276         assert(!should_quit.should_quit());
277
278         if ((current_mode_flags & bmdDisplayModeColorspaceRec601) && output_ycbcr_coefficients == YCBCR_REC_709) {
279                 if (!last_frame_had_mode_mismatch) {
280                         fprintf(stderr, "WARNING: Chosen output mode expects Rec. 601 Y'CbCr coefficients.\n");
281                         fprintf(stderr, "         Consider --output-ycbcr-coefficients=rec601 (or =auto).\n");
282                 }
283                 last_frame_had_mode_mismatch = true;
284                 ++metric_decklink_output_color_mismatch_frames;
285         } else if ((current_mode_flags & bmdDisplayModeColorspaceRec709) && output_ycbcr_coefficients == YCBCR_REC_601) {
286                 if (!last_frame_had_mode_mismatch) {
287                         fprintf(stderr, "WARNING: Chosen output mode expects Rec. 709 Y'CbCr coefficients.\n");
288                         fprintf(stderr, "         Consider --output-ycbcr-coefficients=rec709 (or =auto).\n");
289                 }
290                 last_frame_had_mode_mismatch = true;
291                 ++metric_decklink_output_color_mismatch_frames;
292         } else {
293                 last_frame_had_mode_mismatch = false;
294         }
295
296         unique_ptr<Frame> frame = get_frame();
297         if (global_flags.ten_bit_output) {
298                 chroma_subsampler->create_v210(y_tex, cbcr_tex, width, height, frame->uyvy_tex);
299         } else {
300                 chroma_subsampler->create_uyvy(y_tex, cbcr_tex, width, height, frame->uyvy_tex);
301         }
302
303         // Download the UYVY texture to the PBO.
304         glPixelStorei(GL_PACK_ROW_LENGTH, 0);
305         check_error();
306
307         glBindBuffer(GL_PIXEL_PACK_BUFFER, frame->pbo);
308         check_error();
309
310         if (global_flags.ten_bit_output) {
311                 glBindTexture(GL_TEXTURE_2D, frame->uyvy_tex);
312                 check_error();
313                 glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, BUFFER_OFFSET(0));
314                 check_error();
315         } else {
316                 glBindTexture(GL_TEXTURE_2D, frame->uyvy_tex);
317                 check_error();
318                 glGetTexImage(GL_TEXTURE_2D, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, BUFFER_OFFSET(0));
319                 check_error();
320         }
321
322         glBindTexture(GL_TEXTURE_2D, 0);
323         check_error();
324         glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
325         check_error();
326
327         glMemoryBarrier(GL_TEXTURE_UPDATE_BARRIER_BIT | GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT);
328         check_error();
329
330         frame->fence = RefCountedGLsync(GL_SYNC_GPU_COMMANDS_COMPLETE, /*flags=*/0);
331         check_error();
332         glFlush();  // Make the DeckLink thread see the fence as soon as possible.
333         check_error();
334
335         frame->input_frames = input_frames;
336         frame->received_ts = find_received_timestamp(input_frames);
337         frame->pts = pts;
338         frame->duration = duration;
339
340         {
341                 lock_guard<mutex> lock(frame_queue_mutex);
342                 pending_video_frames.push(move(frame));
343         }
344         frame_queues_changed.notify_all();
345 }
346
347 void DeckLinkOutput::send_audio(int64_t pts, const std::vector<float> &samples)
348 {
349         unique_ptr<int32_t[]> int_samples(new int32_t[samples.size()]);
350         for (size_t i = 0; i < samples.size(); ++i) {
351                 int_samples[i] = lrintf(samples[i] * 2147483648.0f);
352         }
353
354         uint32_t frames_written;
355         HRESULT result = output->ScheduleAudioSamples(int_samples.get(), samples.size() / 2,
356                 pts, TIMEBASE, &frames_written);
357         if (result != S_OK) {
358                 fprintf(stderr, "ScheduleAudioSamples(pts=%" PRId64 ") failed (result=0x%08x)\n", pts, result);
359         } else {
360                 if (frames_written != samples.size() / 2) {
361                         fprintf(stderr, "ScheduleAudioSamples() returned short write (%u/%zu)\n", frames_written, samples.size() / 2);
362                 }
363         }
364         metric_decklink_output_scheduled_samples += samples.size() / 2;
365 }
366
367 void DeckLinkOutput::wait_for_frame(int64_t pts, int *dropped_frames, int64_t *frame_duration, bool *is_preroll, steady_clock::time_point *frame_timestamp)
368 {
369         assert(!should_quit.should_quit());
370
371         *dropped_frames = 0;
372         *frame_duration = this->frame_duration;
373
374         const BMDTimeValue buffer = lrint(*frame_duration * global_flags.output_buffer_frames);
375         const BMDTimeValue max_overshoot = lrint(*frame_duration * global_flags.output_slop_frames);
376         BMDTimeValue target_time = pts - buffer;
377
378         // While prerolling, we send out frames as quickly as we can.
379         if (target_time < base_pts) {
380                 *is_preroll = true;
381                 ++metric_decklink_output_scheduled_frames_preroll;
382                 return;
383         }
384
385         *is_preroll = !playback_started;
386
387         if (!playback_started) {
388                 if (output->EndAudioPreroll() != S_OK) {
389                         fprintf(stderr, "Could not end audio preroll\n");
390                         abort();  // TODO
391                 }
392                 if (output->StartScheduledPlayback(base_pts, TIMEBASE, 1.0) != S_OK) {
393                         fprintf(stderr, "Could not start playback\n");
394                         abort();  // TODO
395                 }
396                 playback_started = true;
397         }
398
399         BMDTimeValue stream_frame_time;
400         double playback_speed;
401         output->GetScheduledStreamTime(TIMEBASE, &stream_frame_time, &playback_speed);
402
403         *frame_timestamp = steady_clock::now() +
404                 nanoseconds((target_time - stream_frame_time) * 1000000000 / TIMEBASE);
405
406         metric_decklink_output_margin_seconds.count_event(
407                 (target_time - stream_frame_time) / double(TIMEBASE));
408
409         // If we're ahead of time, wait for the frame to (approximately) start.
410         if (stream_frame_time < target_time) {
411                 should_quit.sleep_until(*frame_timestamp);
412                 ++metric_decklink_output_scheduled_frames_normal;
413                 return;
414         }
415
416         // If we overshot the previous frame by just a little,
417         // fire off one immediately.
418         if (stream_frame_time < target_time + max_overshoot) {
419                 fprintf(stderr, "Warning: Frame was %ld ms late (but not skipping it due to --output-slop-frames).\n",
420                         lrint((stream_frame_time - target_time) * 1000.0 / TIMEBASE));
421                 ++metric_decklink_output_scheduled_frames_late;
422                 return;
423         }
424
425         // Oops, we missed by more than one frame. Return immediately,
426         // but drop so that we catch up.
427         *dropped_frames = (stream_frame_time - target_time + *frame_duration - 1) / *frame_duration;
428         const int64_t ns_per_frame = this->frame_duration * 1000000000 / TIMEBASE;
429         *frame_timestamp += nanoseconds(*dropped_frames * ns_per_frame);
430         fprintf(stderr, "Dropped %d output frames; skipping.\n", *dropped_frames);
431         metric_decklink_output_scheduled_frames_dropped += *dropped_frames;
432         ++metric_decklink_output_scheduled_frames_normal;
433 }
434
435 uint32_t DeckLinkOutput::pick_video_mode(uint32_t mode) const
436 {
437         if (video_modes.count(mode)) {
438                 return mode;
439         }
440
441         // Prioritize 59.94 > 60 > 29.97. If none of those are found, then pick the highest one.
442         for (const pair<int, int> &desired : vector<pair<int, int>>{ { 60000, 1001 }, { 60, 1 }, { 30000, 1001 } }) {
443                 for (const auto &it : video_modes) {
444                         if (it.second.frame_rate_num * desired.second == desired.first * it.second.frame_rate_den) {
445                                 return it.first;
446                         }
447                 }
448         }
449
450         uint32_t best_mode = 0;
451         double best_fps = 0.0;
452         for (const auto &it : video_modes) {
453                 double fps = double(it.second.frame_rate_num) / it.second.frame_rate_den;
454                 if (fps > best_fps) {
455                         best_mode = it.first;
456                         best_fps = fps;
457                 }
458         }
459         return best_mode;
460 }
461
462 YCbCrLumaCoefficients DeckLinkOutput::preferred_ycbcr_coefficients() const
463 {
464         if (current_mode_flags & bmdDisplayModeColorspaceRec601) {
465                 return YCBCR_REC_601;
466         } else {
467                 // Don't bother checking bmdDisplayModeColorspaceRec709;
468                 // if none is set, 709 is a good default anyway.
469                 return YCBCR_REC_709;
470         }
471 }
472
473 HRESULT DeckLinkOutput::ScheduledFrameCompleted(/* in */ IDeckLinkVideoFrame *completedFrame, /* in */ BMDOutputFrameCompletionResult result)
474 {
475         Frame *frame = static_cast<Frame *>(completedFrame);
476         switch (result) {
477         case bmdOutputFrameCompleted:
478                 ++metric_decklink_output_completed_frames_completed;
479                 break;
480         case bmdOutputFrameDisplayedLate:
481                 fprintf(stderr, "Output frame displayed late (pts=%" PRId64 ")\n", frame->pts);
482                 fprintf(stderr, "Consider increasing --output-buffer-frames if this persists.\n");
483                 ++metric_decklink_output_completed_frames_late;
484                 break;
485         case bmdOutputFrameDropped:
486                 fprintf(stderr, "Output frame was dropped (pts=%" PRId64 ")\n", frame->pts);
487                 fprintf(stderr, "Consider increasing --output-buffer-frames if this persists.\n");
488                 ++metric_decklink_output_completed_frames_dropped;
489                 break;
490         case bmdOutputFrameFlushed:
491                 fprintf(stderr, "Output frame was flushed (pts=%" PRId64 ")\n", frame->pts);
492                 ++metric_decklink_output_completed_frames_flushed;
493                 break;
494         default:
495                 fprintf(stderr, "Output frame completed with unknown status %d\n", result);
496                 ++metric_decklink_output_completed_frames_unknown;
497                 break;
498         }
499
500         static int frameno = 0;
501         print_latency("DeckLink output latency (frame received → output on HDMI):", frame->received_ts, false, &frameno, &latency_histogram);
502
503         {
504                 lock_guard<mutex> lock(frame_queue_mutex);
505                 frame_freelist.push(unique_ptr<Frame>(frame));
506                 --num_frames_in_flight;
507                 --metric_decklink_output_inflight_frames;
508         }
509
510         return S_OK;
511 }
512
513 HRESULT DeckLinkOutput::ScheduledPlaybackHasStopped()
514 {
515         printf("playback stopped!\n");
516         return S_OK;
517 }
518
519 unique_ptr<DeckLinkOutput::Frame> DeckLinkOutput::get_frame()
520 {
521         lock_guard<mutex> lock(frame_queue_mutex);
522
523         if (!frame_freelist.empty()) {
524                 unique_ptr<Frame> frame = move(frame_freelist.front());
525                 frame_freelist.pop();
526                 return frame;
527         }
528
529         unique_ptr<Frame> frame(new Frame);
530
531         size_t stride;
532         if (global_flags.ten_bit_output) {
533                 stride = v210Converter::get_v210_stride(width);
534                 GLint v210_width = stride / sizeof(uint32_t);
535                 frame->uyvy_tex = resource_pool->create_2d_texture(GL_RGB10_A2, v210_width, height);
536
537                 // We need valid texture state, or NVIDIA won't allow us to write to the texture.
538                 glBindTexture(GL_TEXTURE_2D, frame->uyvy_tex);
539                 check_error();
540                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
541                 check_error();
542         } else {
543                 stride = width * 2;
544                 frame->uyvy_tex = resource_pool->create_2d_texture(GL_RGBA8, width / 2, height);
545         }
546
547         glGenBuffers(1, &frame->pbo);
548         check_error();
549         glBindBuffer(GL_PIXEL_PACK_BUFFER, frame->pbo);
550         check_error();
551         glBufferStorage(GL_PIXEL_PACK_BUFFER, stride * height, nullptr, GL_MAP_READ_BIT | GL_MAP_PERSISTENT_BIT);
552         check_error();
553         frame->uyvy_ptr = (uint8_t *)glMapBufferRange(GL_PIXEL_PACK_BUFFER, 0, stride * height, GL_MAP_READ_BIT | GL_MAP_PERSISTENT_BIT);
554         check_error();
555         frame->uyvy_ptr_local.reset(new uint8_t[stride * height]);
556         frame->resource_pool = resource_pool;
557
558         return frame;
559 }
560
561 void DeckLinkOutput::present_thread_func()
562 {
563         pthread_setname_np(pthread_self(), "DeckLinkOutput");
564         for ( ;; ) {
565                 unique_ptr<Frame> frame;
566                 {
567                         unique_lock<mutex> lock(frame_queue_mutex);
568                         frame_queues_changed.wait(lock, [this]{
569                                 return should_quit.should_quit() || !pending_video_frames.empty();
570                         });
571                         if (should_quit.should_quit()) {
572                                 return;
573                         }
574                         frame = move(pending_video_frames.front());
575                         pending_video_frames.pop();
576                         ++num_frames_in_flight;
577                         ++metric_decklink_output_inflight_frames;
578                 }
579
580                 for ( ;; ) {
581                         int err = glClientWaitSync(frame->fence.get(), /*flags=*/0, 0);
582                         if (err == GL_TIMEOUT_EXPIRED) {
583                                 // NVIDIA likes to busy-wait; yield instead.
584                                 this_thread::sleep_for(milliseconds(1));
585                         } else {
586                                 break;
587                         }
588                 }
589                 check_error();
590                 frame->fence.reset();
591
592                 if (global_flags.ten_bit_output) {
593                         memcpy(frame->uyvy_ptr_local.get(), frame->uyvy_ptr, v210Converter::get_v210_stride(width) * height);
594                 } else {
595                         memcpy(frame->uyvy_ptr_local.get(), frame->uyvy_ptr, width * height * 2);
596                 }
597
598                 // Release any input frames we needed to render this frame.
599                 frame->input_frames.clear();
600
601                 BMDTimeValue pts = frame->pts;
602                 BMDTimeValue duration = frame->duration;
603                 HRESULT res = output->ScheduleVideoFrame(frame.get(), pts, duration, TIMEBASE);
604                 if (res == S_OK) {
605                         frame.release();  // Owned by the driver now.
606                 } else {
607                         fprintf(stderr, "Could not schedule video frame! (error=0x%08x)\n", res);
608
609                         lock_guard<mutex> lock(frame_queue_mutex);
610                         frame_freelist.push(move(frame));
611                         --num_frames_in_flight;
612                         --metric_decklink_output_inflight_frames;
613                 }
614         }
615 }
616
617 HRESULT STDMETHODCALLTYPE DeckLinkOutput::QueryInterface(REFIID, LPVOID *)
618 {
619         return E_NOINTERFACE;
620 }
621
622 ULONG STDMETHODCALLTYPE DeckLinkOutput::AddRef()
623 {
624         return refcount.fetch_add(1) + 1;
625 }
626
627 ULONG STDMETHODCALLTYPE DeckLinkOutput::Release()
628 {
629         int new_ref = refcount.fetch_sub(1) - 1;
630         if (new_ref == 0)
631                 delete this;
632         return new_ref;
633 }
634
635 DeckLinkOutput::Frame::~Frame()
636 {
637         glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo);
638         check_error();
639         glUnmapBuffer(GL_PIXEL_PACK_BUFFER);
640         check_error();
641         glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
642         check_error();
643         glDeleteBuffers(1, &pbo);
644         check_error();
645         resource_pool->release_2d_texture(uyvy_tex);
646         check_error();
647 }
648
649 HRESULT STDMETHODCALLTYPE DeckLinkOutput::Frame::QueryInterface(REFIID, LPVOID *)
650 {
651         return E_NOINTERFACE;
652 }
653
654 ULONG STDMETHODCALLTYPE DeckLinkOutput::Frame::AddRef()
655 {
656         return refcount.fetch_add(1) + 1;
657 }
658
659 ULONG STDMETHODCALLTYPE DeckLinkOutput::Frame::Release()
660 {
661         int new_ref = refcount.fetch_sub(1) - 1;
662         if (new_ref == 0)
663                 delete this;
664         return new_ref;
665 }
666
667 long DeckLinkOutput::Frame::GetWidth()
668 {
669         return global_flags.width;
670 }
671
672 long DeckLinkOutput::Frame::GetHeight()
673 {
674         return global_flags.height;
675 }
676
677 long DeckLinkOutput::Frame::GetRowBytes()
678 {
679         if (global_flags.ten_bit_output) {
680                 return v210Converter::get_v210_stride(global_flags.width);
681         } else {
682                 return global_flags.width * 2;
683         }
684 }
685
686 BMDPixelFormat DeckLinkOutput::Frame::GetPixelFormat()
687 {
688         if (global_flags.ten_bit_output) {
689                 return bmdFormat10BitYUV;
690         } else {
691                 return bmdFormat8BitYUV;
692         }
693 }
694
695 BMDFrameFlags DeckLinkOutput::Frame::GetFlags()
696 {
697         return bmdFrameFlagDefault;
698 }
699
700 HRESULT DeckLinkOutput::Frame::GetBytes(/* out */ void **buffer)
701 {
702         *buffer = uyvy_ptr_local.get();
703         return S_OK;
704 }
705
706 HRESULT DeckLinkOutput::Frame::GetTimecode(/* in */ BMDTimecodeFormat format, /* out */ IDeckLinkTimecode **timecode)
707 {
708         fprintf(stderr, "STUB: GetTimecode()\n");
709         return E_NOTIMPL;
710 }
711
712 HRESULT DeckLinkOutput::Frame::GetAncillaryData(/* out */ IDeckLinkVideoFrameAncillary **ancillary)
713 {
714         fprintf(stderr, "STUB: GetAncillaryData()\n");
715         return E_NOTIMPL;
716 }