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