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