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