]> git.sesse.net Git - nageru/blob - futatabi/jpeg_frame_view.cpp
Set CEF autoplay policy to be more lenient.
[nageru] / futatabi / jpeg_frame_view.cpp
1 #include "jpeg_frame_view.h"
2
3 #include "defs.h"
4 #include "flags.h"
5 #include "jpeg_destroyer.h"
6 #include "jpeglib_error_wrapper.h"
7 #include "pbo_pool.h"
8 #include "shared/context.h"
9 #include "shared/metrics.h"
10 #include "shared/post_to_main_thread.h"
11 #include "video_stream.h"
12 #include "ycbcr_converter.h"
13
14 #include <QMouseEvent>
15 #include <QScreen>
16 #include <atomic>
17 #include <chrono>
18 #include <condition_variable>
19 #include <deque>
20 #include <jpeglib.h>
21 #include <movit/init.h>
22 #include <movit/resource_pool.h>
23 #include <movit/util.h>
24 #include <mutex>
25 #include <stdint.h>
26 #include <thread>
27 #include <unistd.h>
28 #include <utility>
29
30 // Must come after the Qt stuff.
31 #include "vaapi_jpeg_decoder.h"
32
33 using namespace movit;
34 using namespace std;
35 using namespace std::chrono;
36
37 namespace {
38
39 // Just an arbitrary order for std::map.
40 struct FrameOnDiskLexicalOrder {
41         bool operator()(const FrameOnDisk &a, const FrameOnDisk &b) const
42         {
43                 if (a.pts != b.pts)
44                         return a.pts < b.pts;
45                 if (a.offset != b.offset)
46                         return a.offset < b.offset;
47                 if (a.filename_idx != b.filename_idx)
48                         return a.filename_idx < b.filename_idx;
49                 assert(a.size == b.size);
50                 return false;
51         }
52 };
53
54 inline size_t frame_size(const Frame &frame)
55 {
56         size_t y_size = frame.width * frame.height;
57         size_t cbcr_size = y_size / frame.chroma_subsampling_x / frame.chroma_subsampling_y;
58         return y_size + cbcr_size * 2;
59 }
60
61 struct LRUFrame {
62         shared_ptr<Frame> frame;
63         size_t last_used;
64 };
65
66 // There can be multiple JPEGFrameView instances, so make all the metrics static.
67 once_flag jpeg_metrics_inited;
68 atomic<int64_t> metric_jpeg_cache_used_bytes{ 0 };  // Same value as cache_bytes_used.
69 atomic<int64_t> metric_jpeg_cache_limit_bytes{ size_t(CACHE_SIZE_MB) * 1024 * 1024 };
70 atomic<int64_t> metric_jpeg_cache_given_up_frames{ 0 };
71 atomic<int64_t> metric_jpeg_cache_hit_frames{ 0 };
72 atomic<int64_t> metric_jpeg_cache_miss_frames{ 0 };
73 atomic<int64_t> metric_jpeg_software_decode_frames{ 0 };
74 atomic<int64_t> metric_jpeg_software_fail_frames{ 0 };
75 atomic<int64_t> metric_jpeg_vaapi_decode_frames{ 0 };
76 atomic<int64_t> metric_jpeg_vaapi_fail_frames{ 0 };
77 atomic<int64_t> metric_jpeg_prepared_frames{ 0 };
78 atomic<int64_t> metric_jpeg_displayed_frames{ 0 };
79 Summary metric_jpeg_decode_time_seconds;
80
81 }  // namespace
82
83 mutex cache_mu;
84 map<FrameOnDisk, LRUFrame, FrameOnDiskLexicalOrder> cache;  // Under cache_mu.
85 size_t cache_bytes_used = 0;  // Under cache_mu.
86 atomic<size_t> event_counter{ 0 };
87 extern QGLWidget *global_share_widget;
88 extern atomic<bool> should_quit;
89
90 shared_ptr<Frame> decode_jpeg(const string &jpeg)
91 {
92         steady_clock::time_point start = steady_clock::now();
93         shared_ptr<Frame> frame;
94         if (vaapi_jpeg_decoding_usable) {
95                 frame = decode_jpeg_vaapi(jpeg);
96                 if (frame != nullptr) {
97                         ++metric_jpeg_vaapi_decode_frames;
98                         steady_clock::time_point stop = steady_clock::now();
99                         metric_jpeg_decode_time_seconds.count_event(duration<double>(stop - start).count());
100                         return frame;
101                 }
102                 fprintf(stderr, "VA-API hardware decoding failed; falling back to software.\n");
103                 ++metric_jpeg_vaapi_fail_frames;
104         }
105
106         frame.reset(new Frame);
107
108         jpeg_decompress_struct dinfo;
109         JPEGWrapErrorManager error_mgr(&dinfo);
110         if (!error_mgr.run([&dinfo] { jpeg_create_decompress(&dinfo); })) {
111                 return get_black_frame();
112         }
113         JPEGDestroyer destroy_dinfo(&dinfo);
114
115         jpeg_save_markers(&dinfo, JPEG_APP0 + 1, 0xFFFF);
116
117         if (!error_mgr.run([&dinfo, &jpeg] {
118                     jpeg_mem_src(&dinfo, reinterpret_cast<const unsigned char *>(jpeg.data()), jpeg.size());
119                     jpeg_read_header(&dinfo, true);
120             })) {
121                 return get_black_frame();
122         }
123
124         if (dinfo.num_components != 3) {
125                 fprintf(stderr, "Not a color JPEG. (%d components, Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
126                         dinfo.num_components,
127                         dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
128                         dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
129                         dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
130                 return get_black_frame();
131         }
132         if (dinfo.comp_info[0].h_samp_factor != dinfo.max_h_samp_factor ||
133             dinfo.comp_info[0].v_samp_factor != dinfo.max_v_samp_factor ||  // Y' must not be subsampled.
134             dinfo.comp_info[1].h_samp_factor != dinfo.comp_info[2].h_samp_factor ||
135             dinfo.comp_info[1].v_samp_factor != dinfo.comp_info[2].v_samp_factor ||  // Cb and Cr must be identically subsampled.
136             (dinfo.max_h_samp_factor % dinfo.comp_info[1].h_samp_factor) != 0 ||
137             (dinfo.max_v_samp_factor % dinfo.comp_info[1].v_samp_factor) != 0) {  // No 2:3 subsampling or other weirdness.
138                 fprintf(stderr, "Unsupported subsampling scheme. (Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
139                         dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
140                         dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
141                         dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
142                 abort();
143         }
144         dinfo.raw_data_out = true;
145
146         if (!error_mgr.run([&dinfo] {
147                     jpeg_start_decompress(&dinfo);
148             })) {
149                 return get_black_frame();
150         }
151
152         frame->width = dinfo.output_width;
153         frame->height = dinfo.output_height;
154         frame->chroma_subsampling_x = dinfo.max_h_samp_factor / dinfo.comp_info[1].h_samp_factor;
155         frame->chroma_subsampling_y = dinfo.max_v_samp_factor / dinfo.comp_info[1].v_samp_factor;
156
157         unsigned h_mcu_size = DCTSIZE * dinfo.max_h_samp_factor;
158         unsigned v_mcu_size = DCTSIZE * dinfo.max_v_samp_factor;
159         unsigned mcu_width_blocks = (dinfo.output_width + h_mcu_size - 1) / h_mcu_size;
160         unsigned mcu_height_blocks = (dinfo.output_height + v_mcu_size - 1) / v_mcu_size;
161
162         unsigned luma_width_blocks = mcu_width_blocks * dinfo.comp_info[0].h_samp_factor;
163         unsigned chroma_width_blocks = mcu_width_blocks * dinfo.comp_info[1].h_samp_factor;
164
165         PBO pbo = global_pbo_pool->alloc_pbo();
166         const size_t chroma_width = dinfo.image_width / frame->chroma_subsampling_x;
167         const size_t chroma_height = dinfo.image_height / frame->chroma_subsampling_y;
168         size_t cb_offset = dinfo.image_width * dinfo.image_height;
169         size_t cr_offset = cb_offset + chroma_width * chroma_height;
170         uint8_t *y_pix = pbo.ptr;
171         uint8_t *cb_pix = pbo.ptr + cb_offset;
172         uint8_t *cr_pix = pbo.ptr + cr_offset;
173         unsigned pitch_y = luma_width_blocks * DCTSIZE;
174         unsigned pitch_chroma = chroma_width_blocks * DCTSIZE;
175
176         if (dinfo.marker_list != nullptr &&
177             dinfo.marker_list->marker == JPEG_APP0 + 1 &&
178             dinfo.marker_list->data_length >= 4 &&
179             memcmp(dinfo.marker_list->data, "Exif", 4) == 0) {
180                 frame->exif_data.assign(reinterpret_cast<char *>(dinfo.marker_list->data),
181                         dinfo.marker_list->data_length);
182         }
183
184         if (!error_mgr.run([&dinfo, &y_pix, &cb_pix, &cr_pix, pitch_y, pitch_chroma, v_mcu_size, mcu_height_blocks] {
185                     JSAMPROW yptr[v_mcu_size], cbptr[v_mcu_size], crptr[v_mcu_size];
186                     JSAMPARRAY data[3] = { yptr, cbptr, crptr };
187                     for (unsigned y = 0; y < mcu_height_blocks; ++y) {
188                             // NOTE: The last elements of cbptr/crptr will be unused for vertically subsampled chroma.
189                             for (unsigned yy = 0; yy < v_mcu_size; ++yy) {
190                                     yptr[yy] = y_pix + (y * DCTSIZE * dinfo.max_v_samp_factor + yy) * pitch_y;
191                                     cbptr[yy] = cb_pix + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * pitch_chroma;
192                                     crptr[yy] = cr_pix + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * pitch_chroma;
193                             }
194
195                             jpeg_read_raw_data(&dinfo, data, v_mcu_size);
196                     }
197
198                     (void)jpeg_finish_decompress(&dinfo);
199             })) {
200                 return get_black_frame();
201         }
202
203         // FIXME: what about resolutions that are not divisible by the block factor?
204         glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo.pbo);
205         frame->y = create_texture_2d(frame->width, frame->height, GL_R8, GL_RED, GL_UNSIGNED_BYTE, BUFFER_OFFSET(0));
206         frame->cb = create_texture_2d(chroma_width, chroma_height, GL_R8, GL_RED, GL_UNSIGNED_BYTE, BUFFER_OFFSET(cb_offset));
207         frame->cr = create_texture_2d(chroma_width, chroma_height, GL_R8, GL_RED, GL_UNSIGNED_BYTE, BUFFER_OFFSET(cr_offset));
208         glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
209
210         glFlushMappedNamedBufferRange(pbo.pbo, 0, dinfo.image_width * dinfo.image_height + chroma_width * chroma_height * 2);
211         glMemoryBarrier(GL_PIXEL_BUFFER_BARRIER_BIT);
212         pbo.upload_done = RefCountedGLsync(GL_SYNC_GPU_COMMANDS_COMPLETE, /*flags=*/0);
213         glFlush();
214         frame->uploaded_ui_thread = pbo.upload_done;
215         frame->uploaded_interpolation = pbo.upload_done;
216         global_pbo_pool->release_pbo(move(pbo));
217
218         ++metric_jpeg_software_decode_frames;
219         steady_clock::time_point stop = steady_clock::now();
220         metric_jpeg_decode_time_seconds.count_event(duration<double>(stop - start).count());
221         return frame;
222 }
223
224 void prune_cache()
225 {
226         // Assumes cache_mu is held.
227         int64_t bytes_still_to_remove = cache_bytes_used - (size_t(CACHE_SIZE_MB) * 1024 * 1024) * 9 / 10;
228         if (bytes_still_to_remove <= 0)
229                 return;
230
231         vector<pair<size_t, size_t>> lru_timestamps_and_size;
232         for (const auto &key_and_value : cache) {
233                 lru_timestamps_and_size.emplace_back(
234                         key_and_value.second.last_used,
235                         frame_size(*key_and_value.second.frame));
236         }
237         sort(lru_timestamps_and_size.begin(), lru_timestamps_and_size.end());
238
239         // Remove the oldest ones until we are below 90% of the cache used.
240         size_t lru_cutoff_point = 0;
241         for (const pair<size_t, size_t> &it : lru_timestamps_and_size) {
242                 lru_cutoff_point = it.first;
243                 bytes_still_to_remove -= it.second;
244                 if (bytes_still_to_remove <= 0)
245                         break;
246         }
247
248         for (auto it = cache.begin(); it != cache.end();) {
249                 if (it->second.last_used <= lru_cutoff_point) {
250                         cache_bytes_used -= frame_size(*it->second.frame);
251                         metric_jpeg_cache_used_bytes = cache_bytes_used;
252                         it = cache.erase(it);
253                 } else {
254                         ++it;
255                 }
256         }
257 }
258
259 shared_ptr<Frame> decode_jpeg_with_cache(FrameOnDisk frame_spec, CacheMissBehavior cache_miss_behavior, FrameReader *frame_reader, bool *did_decode)
260 {
261         *did_decode = false;
262         {
263                 lock_guard<mutex> lock(cache_mu);
264                 auto it = cache.find(frame_spec);
265                 if (it != cache.end()) {
266                         ++metric_jpeg_cache_hit_frames;
267                         it->second.last_used = event_counter++;
268                         return it->second.frame;
269                 }
270         }
271
272         if (cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE) {
273                 ++metric_jpeg_cache_given_up_frames;
274                 return nullptr;
275         }
276
277         ++metric_jpeg_cache_miss_frames;
278
279         *did_decode = true;
280         shared_ptr<Frame> frame = decode_jpeg(frame_reader->read_frame(frame_spec, /*read_video=*/true, /*read_audio=*/false).video);
281
282         lock_guard<mutex> lock(cache_mu);
283         cache_bytes_used += frame_size(*frame);
284         metric_jpeg_cache_used_bytes = cache_bytes_used;
285         cache[frame_spec] = LRUFrame{ frame, event_counter++ };
286
287         if (cache_bytes_used > size_t(CACHE_SIZE_MB) * 1024 * 1024) {
288                 prune_cache();
289         }
290         return frame;
291 }
292
293 void JPEGFrameView::jpeg_decoder_thread_func()
294 {
295         size_t num_decoded = 0, num_dropped = 0;
296
297         pthread_setname_np(pthread_self(), "JPEGDecoder");
298         QSurface *surface = create_surface();
299         QOpenGLContext *context = create_context(surface);
300         bool ok = make_current(context, surface);
301         if (!ok) {
302                 fprintf(stderr, "Video stream couldn't get an OpenGL context\n");
303                 abort();
304         }
305         while (!should_quit.load()) {
306                 PendingDecode decode;
307                 CacheMissBehavior cache_miss_behavior = DECODE_IF_NOT_IN_CACHE;
308                 {
309                         unique_lock<mutex> lock(cache_mu);  // TODO: Perhaps under another lock?
310                         any_pending_decodes.wait(lock, [this] {
311                                 return !pending_decodes.empty() || should_quit.load();
312                         });
313                         if (should_quit.load())
314                                 break;
315                         decode = pending_decodes.front();
316                         pending_decodes.pop_front();
317
318                         if (pending_decodes.size() > 3) {
319                                 cache_miss_behavior = RETURN_NULLPTR_IF_NOT_IN_CACHE;
320                         }
321                 }
322
323                 if (decode.frame != nullptr) {
324                         // Already decoded, so just show it.
325                         setDecodedFrame(decode.frame, nullptr, 1.0f);
326                         continue;
327                 }
328
329                 shared_ptr<Frame> primary_frame, secondary_frame;
330                 bool drop = false;
331                 for (int subframe_idx = 0; subframe_idx < 2; ++subframe_idx) {
332                         const FrameOnDisk &frame_spec = (subframe_idx == 0 ? decode.primary : decode.secondary);
333                         if (frame_spec.pts == -1) {
334                                 // No secondary frame.
335                                 continue;
336                         }
337
338                         bool found_in_cache;
339                         shared_ptr<Frame> frame = decode_jpeg_with_cache(frame_spec, cache_miss_behavior, &frame_reader, &found_in_cache);
340
341                         if (frame == nullptr) {
342                                 assert(cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE);
343                                 drop = true;
344                                 break;
345                         }
346
347                         if (!found_in_cache) {
348                                 ++num_decoded;
349                                 if (num_decoded % 1000 == 0) {
350                                         fprintf(stderr, "Decoded %zu images, dropped %zu (%.2f%% dropped)\n",
351                                                 num_decoded, num_dropped, (100.0 * num_dropped) / (num_decoded + num_dropped));
352                                 }
353                         }
354                         if (subframe_idx == 0) {
355                                 primary_frame = std::move(frame);
356                         } else {
357                                 secondary_frame = std::move(frame);
358                         }
359                 }
360                 if (drop) {
361                         ++num_dropped;
362                         continue;
363                 }
364
365                 // TODO: Could we get jitter between non-interpolated and interpolated frames here?
366                 setDecodedFrame(primary_frame, secondary_frame, decode.fade_alpha);
367         }
368 }
369
370 JPEGFrameView::~JPEGFrameView()
371 {
372         any_pending_decodes.notify_all();
373         jpeg_decoder_thread.join();
374 }
375
376 JPEGFrameView::JPEGFrameView(QWidget *parent)
377         : QGLWidget(parent, global_share_widget)
378 {
379         call_once(jpeg_metrics_inited, [] {
380                 global_metrics.add("jpeg_cache_used_bytes", &metric_jpeg_cache_used_bytes, Metrics::TYPE_GAUGE);
381                 global_metrics.add("jpeg_cache_limit_bytes", &metric_jpeg_cache_limit_bytes, Metrics::TYPE_GAUGE);
382                 global_metrics.add("jpeg_cache_frames", { { "action", "given_up" } }, &metric_jpeg_cache_given_up_frames);
383                 global_metrics.add("jpeg_cache_frames", { { "action", "hit" } }, &metric_jpeg_cache_hit_frames);
384                 global_metrics.add("jpeg_cache_frames", { { "action", "miss" } }, &metric_jpeg_cache_miss_frames);
385                 global_metrics.add("jpeg_decode_frames", { { "decoder", "software" }, { "result", "decode" } }, &metric_jpeg_software_decode_frames);
386                 global_metrics.add("jpeg_decode_frames", { { "decoder", "software" }, { "result", "fail" } }, &metric_jpeg_software_fail_frames);
387                 global_metrics.add("jpeg_decode_frames", { { "decoder", "vaapi" }, { "result", "decode" } }, &metric_jpeg_vaapi_decode_frames);
388                 global_metrics.add("jpeg_decode_frames", { { "decoder", "vaapi" }, { "result", "fail" } }, &metric_jpeg_vaapi_fail_frames);
389                 global_metrics.add("jpeg_frames", { { "action", "prepared" } }, &metric_jpeg_prepared_frames);
390                 global_metrics.add("jpeg_frames", { { "action", "displayed" } }, &metric_jpeg_displayed_frames);
391                 vector<double> quantiles{ 0.01, 0.1, 0.25, 0.5, 0.75, 0.9, 0.99 };
392                 metric_jpeg_decode_time_seconds.init(quantiles, 60.0);
393                 global_metrics.add("jpeg_decode_time_seconds", &metric_jpeg_decode_time_seconds);
394         });
395 }
396
397 void JPEGFrameView::setFrame(unsigned stream_idx, FrameOnDisk frame, FrameOnDisk secondary_frame, float fade_alpha)
398 {
399         current_stream_idx = stream_idx;  // TODO: Does this interact with fades?
400
401         lock_guard<mutex> lock(cache_mu);
402         PendingDecode decode;
403         decode.primary = frame;
404         decode.secondary = secondary_frame;
405         decode.fade_alpha = fade_alpha;
406         pending_decodes.push_back(decode);
407         any_pending_decodes.notify_all();
408 }
409
410 void JPEGFrameView::setFrame(shared_ptr<Frame> frame)
411 {
412         lock_guard<mutex> lock(cache_mu);
413         PendingDecode decode;
414         decode.frame = std::move(frame);
415         decode.fade_alpha = 0.0f;
416         pending_decodes.push_back(decode);
417         any_pending_decodes.notify_all();
418 }
419
420 void JPEGFrameView::initializeGL()
421 {
422         init_pbo_pool();
423
424         glDisable(GL_BLEND);
425         glDisable(GL_DEPTH_TEST);
426         check_error();
427
428         resource_pool = new ResourcePool;
429         jpeg_decoder_thread = std::thread(&JPEGFrameView::jpeg_decoder_thread_func, this);
430
431         ycbcr_converter.reset(new YCbCrConverter(YCbCrConverter::OUTPUT_TO_RGBA, resource_pool));
432
433         ImageFormat inout_format;
434         inout_format.color_space = COLORSPACE_sRGB;
435         inout_format.gamma_curve = GAMMA_sRGB;
436
437         overlay_chain.reset(new EffectChain(overlay_base_width, overlay_base_height, resource_pool));
438         overlay_input = (movit::FlatInput *)overlay_chain->add_input(new FlatInput(inout_format, FORMAT_GRAYSCALE, GL_UNSIGNED_BYTE, overlay_base_width, overlay_base_height));
439
440         overlay_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
441         overlay_chain->finalize();
442 }
443
444 void JPEGFrameView::resizeGL(int width, int height)
445 {
446         check_error();
447         glViewport(0, 0, width, height);
448         check_error();
449
450         // Save these, as width() and height() will lie with DPI scaling.
451         gl_width = width;
452         gl_height = height;
453 }
454
455 void JPEGFrameView::paintGL()
456 {
457         glViewport(0, 0, gl_width, gl_height);
458         if (current_frame == nullptr) {
459                 glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
460                 glClear(GL_COLOR_BUFFER_BIT);
461                 return;
462         }
463
464         if (!displayed_this_frame) {
465                 ++metric_jpeg_displayed_frames;
466                 displayed_this_frame = true;
467         }
468         if (current_frame->uploaded_ui_thread != nullptr) {
469                 glWaitSync(current_frame->uploaded_ui_thread.get(), /*flags=*/0, GL_TIMEOUT_IGNORED);
470                 current_frame->uploaded_ui_thread.reset();
471         }
472         if (current_secondary_frame != nullptr && current_secondary_frame->uploaded_ui_thread != nullptr) {
473                 glWaitSync(current_secondary_frame->uploaded_ui_thread.get(), /*flags=*/0, GL_TIMEOUT_IGNORED);
474                 current_secondary_frame->uploaded_ui_thread.reset();
475         }
476
477         check_error();
478         current_chain->render_to_screen();
479
480         if (overlay_image != nullptr) {
481                 if (overlay_input_needs_refresh) {
482                         overlay_input->set_width(overlay_width);
483                         overlay_input->set_height(overlay_height);
484                         overlay_input->set_pixel_data(overlay_image->bits());
485                         overlay_input_needs_refresh = false;
486                 }
487                 glViewport(gl_width - overlay_width, 0, overlay_width, overlay_height);
488                 overlay_chain->render_to_screen();
489         }
490 }
491
492 namespace {
493
494 }  // namespace
495
496 void JPEGFrameView::setDecodedFrame(shared_ptr<Frame> frame, shared_ptr<Frame> secondary_frame, float fade_alpha)
497 {
498         post_to_main_thread([this, frame, secondary_frame, fade_alpha] {
499                 current_frame = frame;
500                 current_secondary_frame = secondary_frame;
501
502                 if (secondary_frame != nullptr) {
503                         current_chain = ycbcr_converter->prepare_chain_for_fade(frame, secondary_frame, fade_alpha);
504                 } else {
505                         current_chain = ycbcr_converter->prepare_chain_for_conversion(frame);
506                 }
507                 ++metric_jpeg_prepared_frames;
508                 displayed_this_frame = false;
509                 update();
510         });
511 }
512
513 void JPEGFrameView::mousePressEvent(QMouseEvent *event)
514 {
515         if (event->type() == QEvent::MouseButtonPress && event->button() == Qt::LeftButton) {
516                 emit clicked();
517         }
518 }
519
520 void JPEGFrameView::set_overlay(const string &text)
521 {
522         if (text.empty()) {
523                 overlay_image.reset();
524                 return;
525         }
526
527         // Figure out how large the texture needs to be.
528         {
529                 QImage img(overlay_width, overlay_height, QImage::Format_Grayscale8);
530                 QPainter painter(&img);
531                 QFont font = painter.font();
532                 font.setPointSize(12);
533                 QFontMetrics metrics(font);
534                 overlay_base_width = lrint(metrics.boundingRect(QString::fromStdString(text)).width() + 8.0);
535                 overlay_base_height = lrint(metrics.height());
536         }
537
538         float dpr = QGuiApplication::primaryScreen()->devicePixelRatio();
539         overlay_width = lrint(overlay_base_width * dpr);
540         overlay_height = lrint(overlay_base_height * dpr);
541
542         // Work around OpenGL alignment issues.
543         while (overlay_width % 4 != 0) ++overlay_width;
544
545         // Now do the actual drawing.
546         overlay_image.reset(new QImage(overlay_width, overlay_height, QImage::Format_Grayscale8));
547         overlay_image->setDevicePixelRatio(dpr);
548         overlay_image->fill(0);
549         QPainter painter(overlay_image.get());
550
551         painter.setPen(Qt::white);
552         QFont font = painter.font();
553         font.setPointSize(12);
554         painter.setFont(font);
555
556         painter.drawText(QRectF(0, 0, overlay_base_width, overlay_base_height), Qt::AlignCenter, QString::fromStdString(text));
557
558         // Don't refresh immediately; we might not have an OpenGL context here.
559         overlay_input_needs_refresh = true;
560 }
561
562 shared_ptr<Frame> get_black_frame()
563 {
564         static shared_ptr<Frame> black_frame;
565         static once_flag flag;
566         call_once(flag, [] {
567                 // Not really black, but whatever. :-)
568                 uint8_t black[] = { 0, 0, 0, 255 };
569                 RefCountedTexture black_tex = create_texture_2d(1, 1, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, black);
570
571                 black_frame->y = black_tex;
572                 black_frame->cb = black_tex;
573                 black_frame->cr = move(black_tex);
574                 black_frame->width = 1;
575                 black_frame->height = 1;
576                 black_frame->chroma_subsampling_x = 1;
577                 black_frame->chroma_subsampling_y = 1;
578         });
579         ++metric_jpeg_software_fail_frames;
580         return black_frame;
581 }