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