]> git.sesse.net Git - nageru/blob - futatabi/jpeg_frame_view.cpp
Make width/height configurable in Futatabi.
[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/post_to_main_thread.h"
8 #include "video_stream.h"
9 #include "ycbcr_converter.h"
10
11 #include <QMouseEvent>
12 #include <QScreen>
13 #include <atomic>
14 #include <condition_variable>
15 #include <deque>
16 #include <jpeglib.h>
17 #include <movit/init.h>
18 #include <movit/resource_pool.h>
19 #include <movit/util.h>
20 #include <mutex>
21 #include <stdint.h>
22 #include <thread>
23 #include <unistd.h>
24 #include <utility>
25
26 // Must come after the Qt stuff.
27 #include "vaapi_jpeg_decoder.h"
28
29 using namespace movit;
30 using namespace std;
31
32 namespace {
33
34 // Just an arbitrary order for std::map.
35 struct FrameOnDiskLexicalOrder
36 {
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 }  // namespace
76
77 thread JPEGFrameView::jpeg_decoder_thread;
78 mutex cache_mu;
79 map<FrameOnDisk, LRUFrame, FrameOnDiskLexicalOrder> cache;  // Under cache_mu.
80 size_t cache_bytes_used = 0;  // Under cache_mu.
81 condition_variable any_pending_decodes;
82 deque<PendingDecode> pending_decodes;  // Under cache_mu.
83 atomic<size_t> event_counter{0};
84 extern QGLWidget *global_share_widget;
85 extern atomic<bool> should_quit;
86
87 shared_ptr<Frame> decode_jpeg(const string &jpeg)
88 {
89         shared_ptr<Frame> frame;
90         if (vaapi_jpeg_decoding_usable) {
91                 frame = decode_jpeg_vaapi(jpeg);
92                 if (frame != nullptr) {
93                         return frame;
94                 }
95                 fprintf(stderr, "VA-API hardware decoding failed; falling back to software.\n");
96         }
97
98         frame.reset(new Frame);
99
100         jpeg_decompress_struct dinfo;
101         JPEGWrapErrorManager error_mgr(&dinfo);
102         if (!error_mgr.run([&dinfo]{ jpeg_create_decompress(&dinfo); })) {
103                 return get_black_frame();
104         }
105         JPEGDestroyer destroy_dinfo(&dinfo);
106
107         if (!error_mgr.run([&dinfo, &jpeg]{
108                 jpeg_mem_src(&dinfo, reinterpret_cast<const unsigned char *>(jpeg.data()), jpeg.size());
109                 jpeg_read_header(&dinfo, true);
110         })) {
111                 return get_black_frame();
112         }
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                 exit(1);
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 (!error_mgr.run([&dinfo, &frame, v_mcu_size, mcu_height_blocks] {
165                 JSAMPROW yptr[v_mcu_size], cbptr[v_mcu_size], crptr[v_mcu_size];
166                 JSAMPARRAY data[3] = { yptr, cbptr, crptr };
167                 for (unsigned y = 0; y < mcu_height_blocks; ++y) {
168                         // NOTE: The last elements of cbptr/crptr will be unused for vertically subsampled chroma.
169                         for (unsigned yy = 0; yy < v_mcu_size; ++yy) {
170                                 yptr[yy] = frame->y.get() + (y * DCTSIZE * dinfo.max_v_samp_factor + yy) * frame->pitch_y;
171                                 cbptr[yy] = frame->cb.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
172                                 crptr[yy] = frame->cr.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
173                         }
174
175                         jpeg_read_raw_data(&dinfo, data, v_mcu_size);
176                 }
177
178                 (void)jpeg_finish_decompress(&dinfo);
179         })) {
180                 return get_black_frame();
181         }
182
183         return frame;
184 }
185
186 void prune_cache()
187 {
188         // Assumes cache_mu is held.
189         int64_t bytes_still_to_remove = cache_bytes_used - (size_t(CACHE_SIZE_MB) * 1024 * 1024) * 9 / 10;
190         if (bytes_still_to_remove <= 0) return;
191
192         vector<pair<size_t, size_t>> lru_timestamps_and_size;
193         for (const auto &key_and_value : cache) {
194                 lru_timestamps_and_size.emplace_back(
195                         key_and_value.second.last_used,
196                         frame_size(*key_and_value.second.frame));
197         }
198         sort(lru_timestamps_and_size.begin(), lru_timestamps_and_size.end());
199
200         // Remove the oldest ones until we are below 90% of the cache used.
201         size_t lru_cutoff_point = 0;
202         for (const pair<size_t, size_t> &it : lru_timestamps_and_size) {
203                 lru_cutoff_point = it.first;
204                 bytes_still_to_remove -= it.second;
205                 if (bytes_still_to_remove <= 0) break;
206         }
207
208         for (auto it = cache.begin(); it != cache.end(); ) {
209                 if (it->second.last_used <= lru_cutoff_point) {
210                         cache_bytes_used -= frame_size(*it->second.frame);
211                         it = cache.erase(it);
212                 } else {
213                         ++it;
214                 }
215         }
216 }
217
218 shared_ptr<Frame> decode_jpeg_with_cache(FrameOnDisk frame_spec, CacheMissBehavior cache_miss_behavior, FrameReader *frame_reader, bool *did_decode)
219 {
220         *did_decode = false;
221         {
222                 unique_lock<mutex> lock(cache_mu);
223                 auto it = cache.find(frame_spec);
224                 if (it != cache.end()) {
225                         it->second.last_used = event_counter++;
226                         return it->second.frame;
227                 }
228         }
229
230         if (cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE) {
231                 return nullptr;
232         }
233
234         *did_decode = true;
235         shared_ptr<Frame> frame = decode_jpeg(frame_reader->read_frame(frame_spec));
236
237         unique_lock<mutex> lock(cache_mu);
238         cache_bytes_used += frame_size(*frame);
239         cache[frame_spec] = LRUFrame{ frame, event_counter++ };
240
241         if (cache_bytes_used > size_t(CACHE_SIZE_MB) * 1024 * 1024) {
242                 prune_cache();
243         }
244         return frame;
245 }
246
247 void JPEGFrameView::jpeg_decoder_thread_func()
248 {
249         size_t num_decoded = 0, num_dropped = 0;
250
251         pthread_setname_np(pthread_self(), "JPEGDecoder");
252         while (!should_quit.load()) {
253                 PendingDecode decode;
254                 CacheMissBehavior cache_miss_behavior = DECODE_IF_NOT_IN_CACHE;
255                 {
256                         unique_lock<mutex> lock(cache_mu);  // TODO: Perhaps under another lock?
257                         any_pending_decodes.wait(lock, [] {
258                                 return !pending_decodes.empty() || should_quit.load();
259                         });
260                         if (should_quit.load())
261                                 break;
262                         decode = pending_decodes.front();
263                         pending_decodes.pop_front();
264
265                         size_t num_pending = 0;
266                         for (const PendingDecode &other_decode : pending_decodes) {
267                                 if (other_decode.destination == decode.destination) {
268                                         ++num_pending;
269                                 }
270                         }
271                         if (num_pending > 3) {
272                                 cache_miss_behavior = RETURN_NULLPTR_IF_NOT_IN_CACHE;
273                         }
274                 }
275
276                 if (decode.frame != nullptr) {
277                         // Already decoded, so just show it.
278                         decode.destination->setDecodedFrame(decode.frame, nullptr, 1.0f);
279                         continue;
280                 }
281
282                 shared_ptr<Frame> primary_frame, secondary_frame;
283                 bool drop = false;
284                 for (int subframe_idx = 0; subframe_idx < 2; ++subframe_idx) {
285                         const FrameOnDisk &frame_spec = (subframe_idx == 0 ? decode.primary : decode.secondary);
286                         if (frame_spec.pts == -1) {
287                                 // No secondary frame.
288                                 continue;
289                         }
290
291                         bool found_in_cache;
292                         shared_ptr<Frame> frame = decode_jpeg_with_cache(frame_spec, cache_miss_behavior, &decode.destination->frame_reader, &found_in_cache);
293
294                         if (frame == nullptr) {
295                                 assert(cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE);
296                                 drop = true;
297                                 break;
298                         }
299
300                         if (!found_in_cache) {
301                                 ++num_decoded;
302                                 if (num_decoded % 1000 == 0) {
303                                         fprintf(stderr, "Decoded %zu images, dropped %zu (%.2f%% dropped)\n",
304                                                 num_decoded, num_dropped, (100.0 * num_dropped) / (num_decoded + num_dropped));
305                                 }
306                         }
307                         if (subframe_idx == 0) {
308                                 primary_frame = std::move(frame);
309                         } else {
310                                 secondary_frame = std::move(frame);
311                         }
312                 }
313                 if (drop) {
314                         ++num_dropped;
315                         continue;
316                 }
317
318                 // TODO: Could we get jitter between non-interpolated and interpolated frames here?
319                 decode.destination->setDecodedFrame(primary_frame, secondary_frame, decode.fade_alpha);
320         }
321 }
322
323 void JPEGFrameView::shutdown()
324 {
325         any_pending_decodes.notify_all();
326         jpeg_decoder_thread.join();
327 }
328
329 JPEGFrameView::JPEGFrameView(QWidget *parent)
330         : QGLWidget(parent, global_share_widget)
331 {
332 }
333
334 void JPEGFrameView::setFrame(unsigned stream_idx, FrameOnDisk frame, FrameOnDisk secondary_frame, float fade_alpha)
335 {
336         current_stream_idx = stream_idx;  // TODO: Does this interact with fades?
337
338         unique_lock<mutex> lock(cache_mu);
339         PendingDecode decode;
340         decode.primary = frame;
341         decode.secondary = secondary_frame;
342         decode.fade_alpha = fade_alpha;
343         decode.destination = this;
344         pending_decodes.push_back(decode);
345         any_pending_decodes.notify_all();
346 }
347
348 void JPEGFrameView::setFrame(shared_ptr<Frame> frame)
349 {
350         unique_lock<mutex> lock(cache_mu);
351         PendingDecode decode;
352         decode.frame = std::move(frame);
353         decode.destination = this;
354         pending_decodes.push_back(decode);
355         any_pending_decodes.notify_all();
356 }
357
358 ResourcePool *resource_pool = nullptr;
359
360 void JPEGFrameView::initializeGL()
361 {
362         glDisable(GL_BLEND);
363         glDisable(GL_DEPTH_TEST);
364         check_error();
365
366         static once_flag once;
367         call_once(once, [] {
368                 resource_pool = new ResourcePool;
369                 jpeg_decoder_thread = std::thread(jpeg_decoder_thread_func);
370         });
371
372         ycbcr_converter.reset(new YCbCrConverter(YCbCrConverter::OUTPUT_TO_RGBA, resource_pool));
373
374         ImageFormat inout_format;
375         inout_format.color_space = COLORSPACE_sRGB;
376         inout_format.gamma_curve = GAMMA_sRGB;
377
378         overlay_chain.reset(new EffectChain(overlay_base_width, overlay_base_height, resource_pool));
379         overlay_input = (movit::FlatInput *)overlay_chain->add_input(new FlatInput(inout_format, FORMAT_GRAYSCALE, GL_UNSIGNED_BYTE, overlay_base_width, overlay_base_height));
380
381         overlay_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
382         overlay_chain->finalize();
383 }
384
385 void JPEGFrameView::resizeGL(int width, int height)
386 {
387         check_error();
388         glViewport(0, 0, width, height);
389         check_error();
390
391         // Save these, as width() and height() will lie with DPI scaling.
392         gl_width = width;
393         gl_height = height;
394 }
395
396 void JPEGFrameView::paintGL()
397 {
398         glViewport(0, 0, gl_width, gl_height);
399         if (current_frame == nullptr) {
400                 glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
401                 glClear(GL_COLOR_BUFFER_BIT);
402                 return;
403         }
404
405         check_error();
406         current_chain->render_to_screen();
407
408         if (overlay_image != nullptr) {
409                 if (overlay_input_needs_refresh) {
410                         overlay_input->set_width(overlay_width);
411                         overlay_input->set_height(overlay_height);
412                         overlay_input->set_pixel_data(overlay_image->bits());
413                 }
414                 glViewport(gl_width - overlay_width, 0, overlay_width, overlay_height);
415                 overlay_chain->render_to_screen();
416         }
417 }
418
419 namespace {
420
421 }  // namespace
422
423 void JPEGFrameView::setDecodedFrame(shared_ptr<Frame> frame, shared_ptr<Frame> secondary_frame, float fade_alpha)
424 {
425         post_to_main_thread([this, frame, secondary_frame, fade_alpha] {
426                 current_frame = frame;
427                 current_secondary_frame = secondary_frame;
428
429                 if (secondary_frame != nullptr) {
430                         current_chain = ycbcr_converter->prepare_chain_for_fade(frame, secondary_frame, fade_alpha);
431                 } else {
432                         current_chain = ycbcr_converter->prepare_chain_for_conversion(frame);
433                 }
434                 update();
435         });
436 }
437
438 void JPEGFrameView::mousePressEvent(QMouseEvent *event)
439 {
440         if (event->type() == QEvent::MouseButtonPress && event->button() == Qt::LeftButton) {
441                 emit clicked();
442         }
443 }
444
445 void JPEGFrameView::set_overlay(const string &text)
446 {
447         if (text.empty()) {
448                 overlay_image.reset();
449                 return;
450         }
451
452         float dpr = QGuiApplication::primaryScreen()->devicePixelRatio();
453         overlay_width = lrint(overlay_base_width * dpr);
454         overlay_height = lrint(overlay_base_height * dpr);
455
456         overlay_image.reset(new QImage(overlay_width, overlay_height, QImage::Format_Grayscale8));
457         overlay_image->setDevicePixelRatio(dpr);
458         overlay_image->fill(0);
459         QPainter painter(overlay_image.get());
460
461         painter.setPen(Qt::white);
462         QFont font = painter.font();
463         font.setPointSize(12);
464         painter.setFont(font);
465
466         painter.drawText(QRectF(0, 0, overlay_base_width, overlay_base_height), Qt::AlignCenter, QString::fromStdString(text));
467
468         // Don't refresh immediately; we might not have an OpenGL context here.
469         overlay_input_needs_refresh = true;
470 }
471
472 shared_ptr<Frame> get_black_frame()
473 {
474         static shared_ptr<Frame> black_frame;
475         static once_flag flag;
476         call_once(flag, [] {
477                 black_frame.reset(new Frame);
478                 black_frame->y.reset(new uint8_t[global_flags.width * global_flags.height]);
479                 black_frame->cb.reset(new uint8_t[(global_flags.width / 2) * (global_flags.height / 2)]);
480                 black_frame->cr.reset(new uint8_t[(global_flags.width / 2) * (global_flags.height / 2)]);
481                 black_frame->width = global_flags.width;
482                 black_frame->height = global_flags.height;
483                 black_frame->chroma_subsampling_x = 2;
484                 black_frame->chroma_subsampling_y = 2;
485                 black_frame->pitch_y = global_flags.width;
486                 black_frame->pitch_chroma = global_flags.width / 2;
487         });
488         return black_frame;
489 }