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