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