]> git.sesse.net Git - nageru/blob - jpeg_frame_view.cpp
Allow symlinked frame files. Useful for testing.
[nageru] / jpeg_frame_view.cpp
1 #include "jpeg_frame_view.h"
2
3 #include "defs.h"
4 #include "jpeg_destroyer.h"
5 #include "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 &filename)
86 {
87         shared_ptr<Frame> frame;
88         if (vaapi_jpeg_decoding_usable) {
89                 frame = decode_jpeg_vaapi(filename);
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         FILE *fp = fopen(filename.c_str(), "rb");
105         if (fp == nullptr) {
106                 perror(filename.c_str());
107                 exit(1);
108         }
109         jpeg_stdio_src(&dinfo, fp);
110
111         jpeg_read_header(&dinfo, true);
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                 exit(1);
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         jpeg_start_decompress(&dinfo);
136
137         frame->width = dinfo.output_width;
138         frame->height = dinfo.output_height;
139         frame->chroma_subsampling_x = dinfo.max_h_samp_factor / dinfo.comp_info[1].h_samp_factor;
140         frame->chroma_subsampling_y = dinfo.max_v_samp_factor / dinfo.comp_info[1].v_samp_factor;
141
142         unsigned h_mcu_size = DCTSIZE * dinfo.max_h_samp_factor;
143         unsigned v_mcu_size = DCTSIZE * dinfo.max_v_samp_factor;
144         unsigned mcu_width_blocks = (dinfo.output_width + h_mcu_size - 1) / h_mcu_size;
145         unsigned mcu_height_blocks = (dinfo.output_height + v_mcu_size - 1) / v_mcu_size;
146
147         unsigned luma_width_blocks = mcu_width_blocks * dinfo.comp_info[0].h_samp_factor;
148         unsigned chroma_width_blocks = mcu_width_blocks * dinfo.comp_info[1].h_samp_factor;
149         unsigned luma_height_blocks = mcu_height_blocks * dinfo.comp_info[0].v_samp_factor;
150         unsigned chroma_height_blocks = mcu_height_blocks * dinfo.comp_info[1].v_samp_factor;
151
152         // TODO: Decode into a PBO.
153         frame->y.reset(new uint8_t[luma_width_blocks * luma_height_blocks * DCTSIZE2]);
154         frame->cb.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
155         frame->cr.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
156         frame->pitch_y = luma_width_blocks * DCTSIZE;
157         frame->pitch_chroma = chroma_width_blocks * DCTSIZE;
158
159         JSAMPROW yptr[v_mcu_size], cbptr[v_mcu_size], crptr[v_mcu_size];
160         JSAMPARRAY data[3] = { yptr, cbptr, crptr };
161         for (unsigned y = 0; y < mcu_height_blocks; ++y) {
162                 // NOTE: The last elements of cbptr/crptr will be unused for vertically subsampled chroma.
163                 for (unsigned yy = 0; yy < v_mcu_size; ++yy) {
164                         yptr[yy] = frame->y.get() + (y * DCTSIZE * dinfo.max_v_samp_factor + yy) * frame->pitch_y;
165                         cbptr[yy] = frame->cb.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
166                         crptr[yy] = frame->cr.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
167                 }
168
169                 jpeg_read_raw_data(&dinfo, data, v_mcu_size);
170         }
171
172         (void)jpeg_finish_decompress(&dinfo);
173         fclose(fp);
174
175         return frame;
176 }
177
178 void prune_cache()
179 {
180         // Assumes cache_mu is held.
181         int64_t bytes_still_to_remove = cache_bytes_used - (size_t(CACHE_SIZE_MB) * 1024 * 1024) * 9 / 10;
182         if (bytes_still_to_remove <= 0) return;
183
184         vector<pair<size_t, size_t>> lru_timestamps_and_size;
185         for (const auto &key_and_value : cache) {
186                 lru_timestamps_and_size.emplace_back(
187                         key_and_value.second.last_used,
188                         frame_size(*key_and_value.second.frame));
189         }
190         sort(lru_timestamps_and_size.begin(), lru_timestamps_and_size.end());
191
192         // Remove the oldest ones until we are below 90% of the cache used.
193         size_t lru_cutoff_point = 0;
194         for (const pair<size_t, size_t> &it : lru_timestamps_and_size) {
195                 lru_cutoff_point = it.first;
196                 bytes_still_to_remove -= it.second;
197                 if (bytes_still_to_remove <= 0) break;
198         }
199
200         for (auto it = cache.begin(); it != cache.end(); ) {
201                 if (it->second.last_used <= lru_cutoff_point) {
202                         cache_bytes_used -= frame_size(*it->second.frame);
203                         it = cache.erase(it);
204                 } else {
205                         ++it;
206                 }
207         }
208 }
209
210 shared_ptr<Frame> decode_jpeg_with_cache(FrameOnDisk frame_spec, CacheMissBehavior cache_miss_behavior, FrameReader *frame_reader, bool *did_decode)
211 {
212         *did_decode = false;
213         {
214                 unique_lock<mutex> lock(cache_mu);
215                 auto it = cache.find(frame_spec);
216                 if (it != cache.end()) {
217                         it->second.last_used = event_counter++;
218                         return it->second.frame;
219                 }
220         }
221
222         if (cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE) {
223                 return nullptr;
224         }
225
226         *did_decode = true;
227         shared_ptr<Frame> frame = decode_jpeg(frame_reader->read_frame(frame_spec));
228
229         unique_lock<mutex> lock(cache_mu);
230         cache_bytes_used += frame_size(*frame);
231         cache[frame_spec] = LRUFrame{ frame, event_counter++ };
232
233         if (cache_bytes_used > size_t(CACHE_SIZE_MB) * 1024 * 1024) {
234                 prune_cache();
235         }
236         return frame;
237 }
238
239 void JPEGFrameView::jpeg_decoder_thread_func()
240 {
241         size_t num_decoded = 0, num_dropped = 0;
242
243         pthread_setname_np(pthread_self(), "JPEGDecoder");
244         while (!should_quit.load()) {
245                 PendingDecode decode;
246                 CacheMissBehavior cache_miss_behavior = DECODE_IF_NOT_IN_CACHE;
247                 {
248                         unique_lock<mutex> lock(cache_mu);  // TODO: Perhaps under another lock?
249                         any_pending_decodes.wait(lock, [] {
250                                 return !pending_decodes.empty() || should_quit.load();
251                         });
252                         if (should_quit.load())
253                                 break;
254                         decode = pending_decodes.front();
255                         pending_decodes.pop_front();
256
257                         size_t num_pending = 0;
258                         for (const PendingDecode &other_decode : pending_decodes) {
259                                 if (other_decode.destination == decode.destination) {
260                                         ++num_pending;
261                                 }
262                         }
263                         if (num_pending > 3) {
264                                 cache_miss_behavior = RETURN_NULLPTR_IF_NOT_IN_CACHE;
265                         }
266                 }
267
268                 if (decode.frame != nullptr) {
269                         // Already decoded, so just show it.
270                         decode.destination->setDecodedFrame(decode.frame, nullptr, 1.0f);
271                         continue;
272                 }
273
274                 shared_ptr<Frame> primary_frame, secondary_frame;
275                 bool drop = false;
276                 for (int subframe_idx = 0; subframe_idx < 2; ++subframe_idx) {
277                         const FrameOnDisk &frame_spec = (subframe_idx == 0 ? decode.primary : decode.secondary);
278                         if (frame_spec.pts == -1) {
279                                 // No secondary frame.
280                                 continue;
281                         }
282
283                         bool found_in_cache;
284                         shared_ptr<Frame> frame = decode_jpeg_with_cache(frame_spec, cache_miss_behavior, &decode.destination->frame_reader, &found_in_cache);
285
286                         if (frame == nullptr) {
287                                 assert(cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE);
288                                 drop = true;
289                                 break;
290                         }
291
292                         if (!found_in_cache) {
293                                 ++num_decoded;
294                                 if (num_decoded % 1000 == 0) {
295                                         fprintf(stderr, "Decoded %zu images, dropped %zu (%.2f%% dropped)\n",
296                                                 num_decoded, num_dropped, (100.0 * num_dropped) / (num_decoded + num_dropped));
297                                 }
298                         }
299                         if (subframe_idx == 0) {
300                                 primary_frame = std::move(frame);
301                         } else {
302                                 secondary_frame = std::move(frame);
303                         }
304                 }
305                 if (drop) {
306                         ++num_dropped;
307                         continue;
308                 }
309
310                 // TODO: Could we get jitter between non-interpolated and interpolated frames here?
311                 decode.destination->setDecodedFrame(primary_frame, secondary_frame, decode.fade_alpha);
312         }
313 }
314
315 void JPEGFrameView::shutdown()
316 {
317         any_pending_decodes.notify_all();
318         jpeg_decoder_thread.join();
319 }
320
321 JPEGFrameView::JPEGFrameView(QWidget *parent)
322         : QGLWidget(parent, global_share_widget)
323 {
324 }
325
326 void JPEGFrameView::setFrame(unsigned stream_idx, FrameOnDisk frame, FrameOnDisk secondary_frame, float fade_alpha)
327 {
328         current_stream_idx = stream_idx;  // TODO: Does this interact with fades?
329
330         unique_lock<mutex> lock(cache_mu);
331         PendingDecode decode;
332         decode.primary = frame;
333         decode.secondary = secondary_frame;
334         decode.fade_alpha = fade_alpha;
335         decode.destination = this;
336         pending_decodes.push_back(decode);
337         any_pending_decodes.notify_all();
338 }
339
340 void JPEGFrameView::setFrame(shared_ptr<Frame> frame)
341 {
342         unique_lock<mutex> lock(cache_mu);
343         PendingDecode decode;
344         decode.frame = std::move(frame);
345         decode.destination = this;
346         pending_decodes.push_back(decode);
347         any_pending_decodes.notify_all();
348 }
349
350 ResourcePool *resource_pool = nullptr;
351
352 void JPEGFrameView::initializeGL()
353 {
354         glDisable(GL_BLEND);
355         glDisable(GL_DEPTH_TEST);
356         check_error();
357
358         static once_flag once;
359         call_once(once, [] {
360                 resource_pool = new ResourcePool;
361                 jpeg_decoder_thread = std::thread(jpeg_decoder_thread_func);
362         });
363
364         ycbcr_converter.reset(new YCbCrConverter(YCbCrConverter::OUTPUT_TO_RGBA, resource_pool));
365
366         ImageFormat inout_format;
367         inout_format.color_space = COLORSPACE_sRGB;
368         inout_format.gamma_curve = GAMMA_sRGB;
369
370         overlay_chain.reset(new EffectChain(overlay_base_width, overlay_base_height, resource_pool));
371         overlay_input = (movit::FlatInput *)overlay_chain->add_input(new FlatInput(inout_format, FORMAT_GRAYSCALE, GL_UNSIGNED_BYTE, overlay_base_width, overlay_base_height));
372
373         overlay_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
374         overlay_chain->finalize();
375 }
376
377 void JPEGFrameView::resizeGL(int width, int height)
378 {
379         check_error();
380         glViewport(0, 0, width, height);
381         check_error();
382
383         // Save these, as width() and height() will lie with DPI scaling.
384         gl_width = width;
385         gl_height = height;
386 }
387
388 void JPEGFrameView::paintGL()
389 {
390         glViewport(0, 0, gl_width, gl_height);
391         if (current_frame == nullptr) {
392                 glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
393                 glClear(GL_COLOR_BUFFER_BIT);
394                 return;
395         }
396
397         check_error();
398         current_chain->render_to_screen();
399
400         if (overlay_image != nullptr) {
401                 if (overlay_input_needs_refresh) {
402                         overlay_input->set_width(overlay_width);
403                         overlay_input->set_height(overlay_height);
404                         overlay_input->set_pixel_data(overlay_image->bits());
405                 }
406                 glViewport(gl_width - overlay_width, 0, overlay_width, overlay_height);
407                 overlay_chain->render_to_screen();
408         }
409 }
410
411 namespace {
412
413 }  // namespace
414
415 void JPEGFrameView::setDecodedFrame(shared_ptr<Frame> frame, shared_ptr<Frame> secondary_frame, float fade_alpha)
416 {
417         post_to_main_thread([this, frame, secondary_frame, fade_alpha] {
418                 current_frame = frame;
419                 current_secondary_frame = secondary_frame;
420
421                 if (secondary_frame != nullptr) {
422                         current_chain = ycbcr_converter->prepare_chain_for_fade(frame, secondary_frame, fade_alpha);
423                 } else {
424                         current_chain = ycbcr_converter->prepare_chain_for_conversion(frame);
425                 }
426                 update();
427         });
428 }
429
430 void JPEGFrameView::mousePressEvent(QMouseEvent *event)
431 {
432         if (event->type() == QEvent::MouseButtonPress && event->button() == Qt::LeftButton) {
433                 emit clicked();
434         }
435 }
436
437 void JPEGFrameView::set_overlay(const string &text)
438 {
439         if (text.empty()) {
440                 overlay_image.reset();
441                 return;
442         }
443
444         float dpr = QGuiApplication::primaryScreen()->devicePixelRatio();
445         overlay_width = lrint(overlay_base_width * dpr);
446         overlay_height = lrint(overlay_base_height * dpr);
447
448         overlay_image.reset(new QImage(overlay_width, overlay_height, QImage::Format_Grayscale8));
449         overlay_image->setDevicePixelRatio(dpr);
450         overlay_image->fill(0);
451         QPainter painter(overlay_image.get());
452
453         painter.setPen(Qt::white);
454         QFont font = painter.font();
455         font.setPointSize(12);
456         painter.setFont(font);
457
458         painter.drawText(QRectF(0, 0, overlay_base_width, overlay_base_height), Qt::AlignCenter, QString::fromStdString(text));
459
460         // Don't refresh immediately; we might not have an OpenGL context here.
461         overlay_input_needs_refresh = true;
462 }