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