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