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