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