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