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