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