]> git.sesse.net Git - nageru/blob - jpeg_frame_view.cpp
Fix JPEGFrameView behavior with Qt DPI scaling.
[nageru] / jpeg_frame_view.cpp
1 #include "jpeg_frame_view.h"
2
3 #include <jpeglib.h>
4 #include <stdint.h>
5 #include <unistd.h>
6
7 #include <atomic>
8 #include <condition_variable>
9 #include <deque>
10 #include <mutex>
11 #include <thread>
12 #include <utility>
13
14 #include <QMouseEvent>
15 #include <QScreen>
16
17 #include <movit/resource_pool.h>
18 #include <movit/init.h>
19 #include <movit/util.h>
20
21 #include "defs.h"
22 #include "post_to_main_thread.h"
23 #include "video_stream.h"
24
25 using namespace movit;
26 using namespace std;
27
28 // Just an arbitrary order for std::map.
29 struct JPEGIDLexicalOrder
30 {
31         bool operator() (const JPEGID &a, const JPEGID &b) const
32         {
33                 if (a.stream_idx != b.stream_idx)
34                         return a.stream_idx < b.stream_idx;
35                 if (a.pts != b.pts)
36                         return a.pts < b.pts;
37                 return a.interpolated < b.interpolated;
38         }
39 };
40
41 struct LRUFrame {
42         shared_ptr<Frame> frame;
43         size_t last_used;
44 };
45
46 mutex cache_mu;
47 map<JPEGID, LRUFrame, JPEGIDLexicalOrder> cache;  // Under cache_mu.
48 condition_variable any_pending_decodes, cache_updated;
49 deque<pair<JPEGID, JPEGFrameView *>> pending_decodes;  // Under cache_mu.
50 atomic<size_t> event_counter{0};
51 extern QGLWidget *global_share_widget;
52
53 // TODO: Decode using VA-API if available.
54 shared_ptr<Frame> decode_jpeg(const string &filename)
55 {
56         shared_ptr<Frame> frame(new Frame);
57
58         jpeg_decompress_struct dinfo;
59         jpeg_error_mgr jerr;
60         dinfo.err = jpeg_std_error(&jerr);
61         jpeg_create_decompress(&dinfo);
62
63         FILE *fp = fopen(filename.c_str(), "rb");
64         if (fp == nullptr) {
65                 perror(filename.c_str());
66                 exit(1);
67         }
68         jpeg_stdio_src(&dinfo, fp);
69
70         jpeg_read_header(&dinfo, true);
71
72         if (dinfo.num_components != 3) {
73                 fprintf(stderr, "Not a color JPEG. (%d components, Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
74                         dinfo.num_components,
75                         dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
76                         dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
77                         dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
78                 exit(1);
79         }
80         if (dinfo.comp_info[0].h_samp_factor != dinfo.max_h_samp_factor ||
81             dinfo.comp_info[0].v_samp_factor != dinfo.max_v_samp_factor ||  // Y' must not be subsampled.
82             dinfo.comp_info[1].h_samp_factor != dinfo.comp_info[2].h_samp_factor ||
83             dinfo.comp_info[1].v_samp_factor != dinfo.comp_info[2].v_samp_factor ||  // Cb and Cr must be identically subsampled.
84             (dinfo.max_h_samp_factor % dinfo.comp_info[1].h_samp_factor) != 0 ||
85             (dinfo.max_v_samp_factor % dinfo.comp_info[1].v_samp_factor) != 0) {  // No 2:3 subsampling or other weirdness.
86                 fprintf(stderr, "Unsupported subsampling scheme. (Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
87                         dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
88                         dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
89                         dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
90                 exit(1);
91         }
92         dinfo.raw_data_out = true;
93
94         jpeg_start_decompress(&dinfo);
95
96         frame->width = dinfo.output_width;
97         frame->height = dinfo.output_height;
98         frame->chroma_subsampling_x = dinfo.max_h_samp_factor / dinfo.comp_info[1].h_samp_factor;
99         frame->chroma_subsampling_y = dinfo.max_v_samp_factor / dinfo.comp_info[1].v_samp_factor;
100
101         unsigned h_mcu_size = DCTSIZE * dinfo.max_h_samp_factor;
102         unsigned v_mcu_size = DCTSIZE * dinfo.max_v_samp_factor;
103         unsigned mcu_width_blocks = (dinfo.output_width + h_mcu_size - 1) / h_mcu_size;
104         unsigned mcu_height_blocks = (dinfo.output_height + v_mcu_size - 1) / v_mcu_size;
105
106         unsigned luma_width_blocks = mcu_width_blocks * dinfo.comp_info[0].h_samp_factor;
107         unsigned chroma_width_blocks = mcu_width_blocks * dinfo.comp_info[1].h_samp_factor;
108         unsigned luma_height_blocks = mcu_height_blocks * dinfo.comp_info[0].v_samp_factor;
109         unsigned chroma_height_blocks = mcu_height_blocks * dinfo.comp_info[1].v_samp_factor;
110
111         // TODO: Decode into a PBO.
112         frame->y.reset(new uint8_t[luma_width_blocks * luma_height_blocks * DCTSIZE2]);
113         frame->cb.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
114         frame->cr.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
115         frame->pitch_y = luma_width_blocks * DCTSIZE;
116         frame->pitch_chroma = chroma_width_blocks * DCTSIZE;
117
118         JSAMPROW yptr[v_mcu_size], cbptr[v_mcu_size], crptr[v_mcu_size];
119         JSAMPARRAY data[3] = { yptr, cbptr, crptr };
120         for (unsigned y = 0; y < mcu_height_blocks; ++y) {
121                 // NOTE: The last elements of cbptr/crptr will be unused for vertically subsampled chroma.
122                 for (unsigned yy = 0; yy < v_mcu_size; ++yy) {
123                         yptr[yy] = frame->y.get() + (y * DCTSIZE * dinfo.max_v_samp_factor + yy) * frame->pitch_y;
124                         cbptr[yy] = frame->cb.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
125                         crptr[yy] = frame->cr.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
126                 }
127
128                 jpeg_read_raw_data(&dinfo, data, v_mcu_size);
129         }
130
131         (void) jpeg_finish_decompress(&dinfo);
132         jpeg_destroy_decompress(&dinfo);
133         fclose(fp);
134
135         return frame;
136 }
137
138 void prune_cache()
139 {
140         // Assumes cache_mu is held.
141         vector<size_t> lru_timestamps;
142         for (const auto &key_and_value : cache) {
143                 lru_timestamps.push_back(key_and_value.second.last_used);
144         }
145
146         size_t cutoff_point = CACHE_SIZE / 10;  // Prune away the 10% oldest ones.
147         nth_element(lru_timestamps.begin(), lru_timestamps.begin() + cutoff_point, lru_timestamps.end());
148         size_t must_be_used_after = lru_timestamps[cutoff_point];
149         for (auto it = cache.begin(); it != cache.end(); ) {
150                 if (it->second.last_used < must_be_used_after) {
151                         it = cache.erase(it);
152                 } else {
153                         ++it;
154                 }
155         }
156 }
157
158 shared_ptr<Frame> decode_jpeg_with_cache(JPEGID id, CacheMissBehavior cache_miss_behavior, bool *did_decode)
159 {
160         *did_decode = false;
161         {
162                 unique_lock<mutex> lock(cache_mu);
163                 auto it = cache.find(id);
164                 if (it != cache.end()) {
165                         it->second.last_used = event_counter++;
166                         return it->second.frame;
167                 }
168         }
169
170         if (cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE) {
171                 return nullptr;
172         }
173
174         assert(!id.interpolated);
175         *did_decode = true;
176         shared_ptr<Frame> frame = decode_jpeg(filename_for_frame(id.stream_idx, id.pts));
177
178         unique_lock<mutex> lock(cache_mu);
179         cache[id] = LRUFrame{ frame, event_counter++ };
180
181         if (cache.size() > CACHE_SIZE) {
182                 prune_cache();
183         }
184         return frame;
185 }
186
187 void jpeg_decoder_thread()
188 {
189         size_t num_decoded = 0, num_dropped = 0;
190
191         pthread_setname_np(pthread_self(), "JPEGDecoder");
192         for ( ;; ) {
193                 JPEGID id;
194                 JPEGFrameView *dest;
195                 CacheMissBehavior cache_miss_behavior = DECODE_IF_NOT_IN_CACHE;
196                 {
197                         unique_lock<mutex> lock(cache_mu);  // TODO: Perhaps under another lock?
198                         any_pending_decodes.wait(lock, [] {
199                                 return !pending_decodes.empty();
200                         });
201                         id = pending_decodes.front().first;
202                         dest = pending_decodes.front().second;
203                         pending_decodes.pop_front();
204
205                         size_t num_pending = 0;
206                         for (const pair<JPEGID, JPEGFrameView *> &decode : pending_decodes) {
207                                 if (decode.second == dest) {
208                                         ++num_pending;
209                                 }
210                         }
211                         if (num_pending > 3) {
212                                 cache_miss_behavior = RETURN_NULLPTR_IF_NOT_IN_CACHE;
213                         }
214                 }
215
216                 bool found_in_cache;
217                 shared_ptr<Frame> frame;
218                 if (id.interpolated) {
219                         // Interpolated frames are never decoded by us,
220                         // put directly into the cache from VideoStream.
221                         unique_lock<mutex> lock(cache_mu);
222                         cache_updated.wait(lock, [id] {
223                                 return cache.count(id) != 0;
224                         });
225                         found_in_cache = true;  // Don't count it as a decode.
226
227                         auto it = cache.find(id);
228                         assert(it != cache.end());
229
230                         it->second.last_used = event_counter++;
231                         frame = it->second.frame;
232                         if (frame == nullptr) {
233                                 // We inserted a nullptr as signal that the frame was never
234                                 // interpolated and that we should stop waiting.
235                                 // But don't let it linger in the cache anymore.
236                                 cache.erase(it);
237                         }
238                 } else {
239                         frame = decode_jpeg_with_cache(id, cache_miss_behavior, &found_in_cache);
240                 }
241
242                 if (frame == nullptr) {
243                         assert(id.interpolated || cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE);
244                         ++num_dropped;
245                         continue;
246                 }
247
248                 if (!found_in_cache) {
249                         ++num_decoded;
250                         if (num_decoded % 1000 == 0) {
251                                 fprintf(stderr, "Decoded %zu images, dropped %zu (%.2f%% dropped)\n",
252                                         num_decoded, num_dropped, (100.0 * num_dropped) / (num_decoded + num_dropped));
253                         }
254                 }
255
256                 // TODO: Could we get jitter between non-interpolated and interpolated frames here?
257                 dest->setDecodedFrame(frame);
258         }
259 }
260
261 JPEGFrameView::JPEGFrameView(QWidget *parent)
262         : QGLWidget(parent, global_share_widget) {
263 }
264
265 void JPEGFrameView::setFrame(unsigned stream_idx, int64_t pts, bool interpolated)
266 {
267         current_stream_idx = stream_idx;
268
269         unique_lock<mutex> lock(cache_mu);
270         pending_decodes.emplace_back(JPEGID{ stream_idx, pts, interpolated }, this);
271         any_pending_decodes.notify_all();
272 }
273
274 void JPEGFrameView::insert_interpolated_frame(unsigned stream_idx, int64_t pts, shared_ptr<Frame> frame)
275 {
276         JPEGID id{ stream_idx, pts, true };
277
278         // We rely on the frame not being evicted from the cache before
279         // jpeg_decoder_thread() sees it and can display it (otherwise,
280         // that thread would hang). With a default cache of 1000 elements,
281         // that would sound like a reasonable assumption.
282         unique_lock<mutex> lock(cache_mu);
283         cache[id] = LRUFrame{ std::move(frame), event_counter++ };
284         cache_updated.notify_all();
285 }
286
287 ResourcePool *resource_pool = nullptr;
288
289 void JPEGFrameView::initializeGL()
290 {
291         glDisable(GL_BLEND);
292         glDisable(GL_DEPTH_TEST);
293         check_error();
294
295         static once_flag once;
296         call_once(once, [] {
297                 resource_pool = new ResourcePool;
298                 std::thread(&jpeg_decoder_thread).detach();
299         });
300
301         chain.reset(new EffectChain(1280, 720, resource_pool));
302         ImageFormat image_format;
303         image_format.color_space = COLORSPACE_sRGB;
304         image_format.gamma_curve = GAMMA_sRGB;
305         ycbcr_format.luma_coefficients = YCBCR_REC_709;
306         ycbcr_format.full_range = false;
307         ycbcr_format.num_levels = 256;
308         ycbcr_format.chroma_subsampling_x = 2;
309         ycbcr_format.chroma_subsampling_y = 1;
310         ycbcr_format.cb_x_position = 0.0f;  // H.264 -- _not_ JPEG, even though our input is MJPEG-encoded
311         ycbcr_format.cb_y_position = 0.5f;  // Irrelevant.
312         ycbcr_format.cr_x_position = 0.0f;
313         ycbcr_format.cr_y_position = 0.5f;
314         ycbcr_input = (movit::YCbCrInput *)chain->add_input(new YCbCrInput(image_format, ycbcr_format, 1280, 720));
315
316         ImageFormat inout_format;
317         inout_format.color_space = COLORSPACE_sRGB;
318         inout_format.gamma_curve = GAMMA_sRGB;
319
320         check_error();
321         chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
322         check_error();
323         chain->set_dither_bits(8);
324         check_error();
325         chain->finalize();
326         check_error();
327
328         overlay_chain.reset(new EffectChain(overlay_base_width, overlay_base_height, resource_pool));
329         overlay_input = (movit::FlatInput *)overlay_chain->add_input(new FlatInput(image_format, FORMAT_GRAYSCALE, GL_UNSIGNED_BYTE, overlay_base_width, overlay_base_height));
330
331         overlay_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
332         overlay_chain->finalize();
333 }
334
335 void JPEGFrameView::resizeGL(int width, int height)
336 {
337         check_error();
338         glViewport(0, 0, width, height);
339         check_error();
340
341         // Save these, as width() and height() will lie with DPI scaling.
342         gl_width = width;
343         gl_height = height;
344 }
345
346 void JPEGFrameView::paintGL()
347 {
348         glViewport(0, 0, gl_width, gl_height);
349         if (current_frame == nullptr) {
350                 glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
351                 glClear(GL_COLOR_BUFFER_BIT);
352                 return;
353         }
354
355         check_error();
356         chain->render_to_screen();
357
358         if (overlay_image != nullptr) {
359                 if (overlay_input_needs_refresh) {
360                         overlay_input->set_width(overlay_width);
361                         overlay_input->set_height(overlay_height);
362                         overlay_input->set_pixel_data(overlay_image->bits());
363                 }
364                 glViewport(gl_width - overlay_width, 0, overlay_width, overlay_height);
365                 overlay_chain->render_to_screen();
366         }
367 }
368
369 void JPEGFrameView::setDecodedFrame(std::shared_ptr<Frame> frame)
370 {
371         post_to_main_thread([this, frame] {
372                 current_frame = frame;
373                 ycbcr_format.chroma_subsampling_x = frame->chroma_subsampling_x;
374                 ycbcr_format.chroma_subsampling_y = frame->chroma_subsampling_y;
375                 ycbcr_input->change_ycbcr_format(ycbcr_format);
376                 ycbcr_input->set_width(frame->width);
377                 ycbcr_input->set_height(frame->height);
378                 ycbcr_input->set_pixel_data(0, frame->y.get());
379                 ycbcr_input->set_pixel_data(1, frame->cb.get());
380                 ycbcr_input->set_pixel_data(2, frame->cr.get());
381                 ycbcr_input->set_pitch(0, frame->pitch_y);
382                 ycbcr_input->set_pitch(1, frame->pitch_chroma);
383                 ycbcr_input->set_pitch(2, frame->pitch_chroma);
384                 update();
385         });
386 }
387
388 void JPEGFrameView::mousePressEvent(QMouseEvent *event)
389 {
390         if (event->type() == QEvent::MouseButtonPress && event->button() == Qt::LeftButton) {
391                 emit clicked();
392         }
393 }
394
395 void JPEGFrameView::set_overlay(const string &text)
396 {
397         if (text.empty()) {
398                 overlay_image.reset();
399                 return;
400         }
401
402         float dpr = QGuiApplication::primaryScreen()->devicePixelRatio();
403         overlay_width = lrint(overlay_base_width * dpr);
404         overlay_height = lrint(overlay_base_height * dpr);
405
406         overlay_image.reset(new QImage(overlay_width, overlay_height, QImage::Format_Grayscale8));
407         overlay_image->setDevicePixelRatio(dpr);
408         overlay_image->fill(0);
409         QPainter painter(overlay_image.get());
410
411         painter.setPen(Qt::white);
412         QFont font = painter.font();
413         font.setPointSize(12);
414         painter.setFont(font);
415
416         painter.drawText(QRectF(0, 0, overlay_base_width, overlay_base_height), Qt::AlignCenter, QString::fromStdString(text));
417
418         // Don't refresh immediately; we might not have an OpenGL context here.
419         overlay_input_needs_refresh = true;
420 }