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