1 #include "jpeg_frame_view.h"
5 #include "jpeg_destroyer.h"
6 #include "jpeglib_error_wrapper.h"
7 #include "shared/metrics.h"
8 #include "shared/post_to_main_thread.h"
9 #include "video_stream.h"
10 #include "ycbcr_converter.h"
12 #include <QMouseEvent>
15 #include <condition_variable>
18 #include <movit/init.h>
19 #include <movit/resource_pool.h>
20 #include <movit/util.h>
27 // Must come after the Qt stuff.
28 #include "vaapi_jpeg_decoder.h"
30 using namespace movit;
35 // Just an arbitrary order for std::map.
36 struct FrameOnDiskLexicalOrder
38 bool operator() (const FrameOnDisk &a, const FrameOnDisk &b) const
42 if (a.offset != b.offset)
43 return a.offset < b.offset;
44 if (a.filename_idx != b.filename_idx)
45 return a.filename_idx < b.filename_idx;
46 assert(a.size == b.size);
51 inline size_t frame_size(const Frame &frame)
53 size_t y_size = frame.width * frame.height;
54 size_t cbcr_size = y_size / frame.chroma_subsampling_x / frame.chroma_subsampling_y;
55 return y_size + cbcr_size * 2;
59 shared_ptr<Frame> frame;
63 struct PendingDecode {
64 JPEGFrameView *destination;
66 // For actual decodes (only if frame below is nullptr).
67 FrameOnDisk primary, secondary;
68 float fade_alpha; // Irrelevant if secondary.stream_idx == -1.
70 // Already-decoded frames are also sent through PendingDecode,
71 // so that they get drawn in the right order. If frame is nullptr,
72 // it's a real decode.
73 shared_ptr<Frame> frame;
76 // There can be multiple JPEGFrameView instances, so make all the metrics static.
77 once_flag jpeg_metrics_inited;
78 atomic<int64_t> metric_jpeg_cache_used_bytes{0}; // Same value as cache_bytes_used.
79 atomic<int64_t> metric_jpeg_cache_limit_bytes{size_t(CACHE_SIZE_MB) * 1024 * 1024};
80 atomic<int64_t> metric_jpeg_cache_given_up_frames{0};
81 atomic<int64_t> metric_jpeg_cache_hit_frames{0};
82 atomic<int64_t> metric_jpeg_cache_miss_frames{0};
83 atomic<int64_t> metric_jpeg_software_decode_frames{0};
84 atomic<int64_t> metric_jpeg_software_fail_frames{0};
85 atomic<int64_t> metric_jpeg_vaapi_decode_frames{0};
86 atomic<int64_t> metric_jpeg_vaapi_fail_frames{0};
90 thread JPEGFrameView::jpeg_decoder_thread;
92 map<FrameOnDisk, LRUFrame, FrameOnDiskLexicalOrder> cache; // Under cache_mu.
93 size_t cache_bytes_used = 0; // Under cache_mu.
94 condition_variable any_pending_decodes;
95 deque<PendingDecode> pending_decodes; // Under cache_mu.
96 atomic<size_t> event_counter{0};
97 extern QGLWidget *global_share_widget;
98 extern atomic<bool> should_quit;
100 shared_ptr<Frame> decode_jpeg(const string &jpeg)
102 shared_ptr<Frame> frame;
103 if (vaapi_jpeg_decoding_usable) {
104 frame = decode_jpeg_vaapi(jpeg);
105 if (frame != nullptr) {
106 ++metric_jpeg_vaapi_decode_frames;
109 fprintf(stderr, "VA-API hardware decoding failed; falling back to software.\n");
110 ++metric_jpeg_vaapi_fail_frames;
113 frame.reset(new Frame);
115 jpeg_decompress_struct dinfo;
116 JPEGWrapErrorManager error_mgr(&dinfo);
117 if (!error_mgr.run([&dinfo]{ jpeg_create_decompress(&dinfo); })) {
118 return get_black_frame();
120 JPEGDestroyer destroy_dinfo(&dinfo);
122 if (!error_mgr.run([&dinfo, &jpeg]{
123 jpeg_mem_src(&dinfo, reinterpret_cast<const unsigned char *>(jpeg.data()), jpeg.size());
124 jpeg_read_header(&dinfo, true);
126 return get_black_frame();
129 if (dinfo.num_components != 3) {
130 fprintf(stderr, "Not a color JPEG. (%d components, Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
131 dinfo.num_components,
132 dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
133 dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
134 dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
135 return get_black_frame();
137 if (dinfo.comp_info[0].h_samp_factor != dinfo.max_h_samp_factor ||
138 dinfo.comp_info[0].v_samp_factor != dinfo.max_v_samp_factor || // Y' must not be subsampled.
139 dinfo.comp_info[1].h_samp_factor != dinfo.comp_info[2].h_samp_factor ||
140 dinfo.comp_info[1].v_samp_factor != dinfo.comp_info[2].v_samp_factor || // Cb and Cr must be identically subsampled.
141 (dinfo.max_h_samp_factor % dinfo.comp_info[1].h_samp_factor) != 0 ||
142 (dinfo.max_v_samp_factor % dinfo.comp_info[1].v_samp_factor) != 0) { // No 2:3 subsampling or other weirdness.
143 fprintf(stderr, "Unsupported subsampling scheme. (Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
144 dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
145 dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
146 dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
149 dinfo.raw_data_out = true;
151 if (!error_mgr.run([&dinfo]{
152 jpeg_start_decompress(&dinfo);
154 return get_black_frame();
157 frame->width = dinfo.output_width;
158 frame->height = dinfo.output_height;
159 frame->chroma_subsampling_x = dinfo.max_h_samp_factor / dinfo.comp_info[1].h_samp_factor;
160 frame->chroma_subsampling_y = dinfo.max_v_samp_factor / dinfo.comp_info[1].v_samp_factor;
162 unsigned h_mcu_size = DCTSIZE * dinfo.max_h_samp_factor;
163 unsigned v_mcu_size = DCTSIZE * dinfo.max_v_samp_factor;
164 unsigned mcu_width_blocks = (dinfo.output_width + h_mcu_size - 1) / h_mcu_size;
165 unsigned mcu_height_blocks = (dinfo.output_height + v_mcu_size - 1) / v_mcu_size;
167 unsigned luma_width_blocks = mcu_width_blocks * dinfo.comp_info[0].h_samp_factor;
168 unsigned chroma_width_blocks = mcu_width_blocks * dinfo.comp_info[1].h_samp_factor;
169 unsigned luma_height_blocks = mcu_height_blocks * dinfo.comp_info[0].v_samp_factor;
170 unsigned chroma_height_blocks = mcu_height_blocks * dinfo.comp_info[1].v_samp_factor;
172 // TODO: Decode into a PBO.
173 frame->y.reset(new uint8_t[luma_width_blocks * luma_height_blocks * DCTSIZE2]);
174 frame->cb.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
175 frame->cr.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
176 frame->pitch_y = luma_width_blocks * DCTSIZE;
177 frame->pitch_chroma = chroma_width_blocks * DCTSIZE;
179 if (!error_mgr.run([&dinfo, &frame, v_mcu_size, mcu_height_blocks] {
180 JSAMPROW yptr[v_mcu_size], cbptr[v_mcu_size], crptr[v_mcu_size];
181 JSAMPARRAY data[3] = { yptr, cbptr, crptr };
182 for (unsigned y = 0; y < mcu_height_blocks; ++y) {
183 // NOTE: The last elements of cbptr/crptr will be unused for vertically subsampled chroma.
184 for (unsigned yy = 0; yy < v_mcu_size; ++yy) {
185 yptr[yy] = frame->y.get() + (y * DCTSIZE * dinfo.max_v_samp_factor + yy) * frame->pitch_y;
186 cbptr[yy] = frame->cb.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
187 crptr[yy] = frame->cr.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
190 jpeg_read_raw_data(&dinfo, data, v_mcu_size);
193 (void)jpeg_finish_decompress(&dinfo);
195 return get_black_frame();
198 ++metric_jpeg_software_decode_frames;
204 // Assumes cache_mu is held.
205 int64_t bytes_still_to_remove = cache_bytes_used - (size_t(CACHE_SIZE_MB) * 1024 * 1024) * 9 / 10;
206 if (bytes_still_to_remove <= 0) return;
208 vector<pair<size_t, size_t>> lru_timestamps_and_size;
209 for (const auto &key_and_value : cache) {
210 lru_timestamps_and_size.emplace_back(
211 key_and_value.second.last_used,
212 frame_size(*key_and_value.second.frame));
214 sort(lru_timestamps_and_size.begin(), lru_timestamps_and_size.end());
216 // Remove the oldest ones until we are below 90% of the cache used.
217 size_t lru_cutoff_point = 0;
218 for (const pair<size_t, size_t> &it : lru_timestamps_and_size) {
219 lru_cutoff_point = it.first;
220 bytes_still_to_remove -= it.second;
221 if (bytes_still_to_remove <= 0) break;
224 for (auto it = cache.begin(); it != cache.end(); ) {
225 if (it->second.last_used <= lru_cutoff_point) {
226 cache_bytes_used -= frame_size(*it->second.frame);
227 metric_jpeg_cache_used_bytes = cache_bytes_used;
228 it = cache.erase(it);
235 shared_ptr<Frame> decode_jpeg_with_cache(FrameOnDisk frame_spec, CacheMissBehavior cache_miss_behavior, FrameReader *frame_reader, bool *did_decode)
239 unique_lock<mutex> lock(cache_mu);
240 auto it = cache.find(frame_spec);
241 if (it != cache.end()) {
242 ++metric_jpeg_cache_hit_frames;
243 it->second.last_used = event_counter++;
244 return it->second.frame;
248 if (cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE) {
249 ++metric_jpeg_cache_given_up_frames;
253 ++metric_jpeg_cache_miss_frames;
256 shared_ptr<Frame> frame = decode_jpeg(frame_reader->read_frame(frame_spec));
258 unique_lock<mutex> lock(cache_mu);
259 cache_bytes_used += frame_size(*frame);
260 metric_jpeg_cache_used_bytes = cache_bytes_used;
261 cache[frame_spec] = LRUFrame{ frame, event_counter++ };
263 if (cache_bytes_used > size_t(CACHE_SIZE_MB) * 1024 * 1024) {
269 void JPEGFrameView::jpeg_decoder_thread_func()
271 size_t num_decoded = 0, num_dropped = 0;
273 pthread_setname_np(pthread_self(), "JPEGDecoder");
274 while (!should_quit.load()) {
275 PendingDecode decode;
276 CacheMissBehavior cache_miss_behavior = DECODE_IF_NOT_IN_CACHE;
278 unique_lock<mutex> lock(cache_mu); // TODO: Perhaps under another lock?
279 any_pending_decodes.wait(lock, [] {
280 return !pending_decodes.empty() || should_quit.load();
282 if (should_quit.load())
284 decode = pending_decodes.front();
285 pending_decodes.pop_front();
287 size_t num_pending = 0;
288 for (const PendingDecode &other_decode : pending_decodes) {
289 if (other_decode.destination == decode.destination) {
293 if (num_pending > 3) {
294 cache_miss_behavior = RETURN_NULLPTR_IF_NOT_IN_CACHE;
298 if (decode.frame != nullptr) {
299 // Already decoded, so just show it.
300 decode.destination->setDecodedFrame(decode.frame, nullptr, 1.0f);
304 shared_ptr<Frame> primary_frame, secondary_frame;
306 for (int subframe_idx = 0; subframe_idx < 2; ++subframe_idx) {
307 const FrameOnDisk &frame_spec = (subframe_idx == 0 ? decode.primary : decode.secondary);
308 if (frame_spec.pts == -1) {
309 // No secondary frame.
314 shared_ptr<Frame> frame = decode_jpeg_with_cache(frame_spec, cache_miss_behavior, &decode.destination->frame_reader, &found_in_cache);
316 if (frame == nullptr) {
317 assert(cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE);
322 if (!found_in_cache) {
324 if (num_decoded % 1000 == 0) {
325 fprintf(stderr, "Decoded %zu images, dropped %zu (%.2f%% dropped)\n",
326 num_decoded, num_dropped, (100.0 * num_dropped) / (num_decoded + num_dropped));
329 if (subframe_idx == 0) {
330 primary_frame = std::move(frame);
332 secondary_frame = std::move(frame);
340 // TODO: Could we get jitter between non-interpolated and interpolated frames here?
341 decode.destination->setDecodedFrame(primary_frame, secondary_frame, decode.fade_alpha);
345 void JPEGFrameView::shutdown()
347 any_pending_decodes.notify_all();
348 jpeg_decoder_thread.join();
351 JPEGFrameView::JPEGFrameView(QWidget *parent)
352 : QGLWidget(parent, global_share_widget)
354 call_once(jpeg_metrics_inited, []{
355 global_metrics.add("jpeg_cache_used_bytes", &metric_jpeg_cache_used_bytes, Metrics::TYPE_GAUGE);
356 global_metrics.add("jpeg_cache_limit_bytes", &metric_jpeg_cache_limit_bytes, Metrics::TYPE_GAUGE);
357 global_metrics.add("jpeg_cache_frames", {{ "action", "given_up" }}, &metric_jpeg_cache_given_up_frames);
358 global_metrics.add("jpeg_cache_frames", {{ "action", "hit" }}, &metric_jpeg_cache_hit_frames);
359 global_metrics.add("jpeg_cache_frames", {{ "action", "miss" }}, &metric_jpeg_cache_miss_frames);
360 global_metrics.add("jpeg_decode_frames", {{ "decoder", "software" }, { "result", "decode" }}, &metric_jpeg_software_decode_frames);
361 global_metrics.add("jpeg_decode_frames", {{ "decoder", "software" }, { "result", "fail" }}, &metric_jpeg_software_fail_frames);
362 global_metrics.add("jpeg_decode_frames", {{ "decoder", "vaapi" }, { "result", "decode" }}, &metric_jpeg_vaapi_decode_frames);
363 global_metrics.add("jpeg_decode_frames", {{ "decoder", "vaapi" }, { "result", "fail" }}, &metric_jpeg_vaapi_fail_frames);
367 void JPEGFrameView::setFrame(unsigned stream_idx, FrameOnDisk frame, FrameOnDisk secondary_frame, float fade_alpha)
369 current_stream_idx = stream_idx; // TODO: Does this interact with fades?
371 unique_lock<mutex> lock(cache_mu);
372 PendingDecode decode;
373 decode.primary = frame;
374 decode.secondary = secondary_frame;
375 decode.fade_alpha = fade_alpha;
376 decode.destination = this;
377 pending_decodes.push_back(decode);
378 any_pending_decodes.notify_all();
381 void JPEGFrameView::setFrame(shared_ptr<Frame> frame)
383 unique_lock<mutex> lock(cache_mu);
384 PendingDecode decode;
385 decode.frame = std::move(frame);
386 decode.destination = this;
387 pending_decodes.push_back(decode);
388 any_pending_decodes.notify_all();
391 ResourcePool *resource_pool = nullptr;
393 void JPEGFrameView::initializeGL()
396 glDisable(GL_DEPTH_TEST);
399 static once_flag once;
401 resource_pool = new ResourcePool;
402 jpeg_decoder_thread = std::thread(jpeg_decoder_thread_func);
405 ycbcr_converter.reset(new YCbCrConverter(YCbCrConverter::OUTPUT_TO_RGBA, resource_pool));
407 ImageFormat inout_format;
408 inout_format.color_space = COLORSPACE_sRGB;
409 inout_format.gamma_curve = GAMMA_sRGB;
411 overlay_chain.reset(new EffectChain(overlay_base_width, overlay_base_height, resource_pool));
412 overlay_input = (movit::FlatInput *)overlay_chain->add_input(new FlatInput(inout_format, FORMAT_GRAYSCALE, GL_UNSIGNED_BYTE, overlay_base_width, overlay_base_height));
414 overlay_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
415 overlay_chain->finalize();
418 void JPEGFrameView::resizeGL(int width, int height)
421 glViewport(0, 0, width, height);
424 // Save these, as width() and height() will lie with DPI scaling.
429 void JPEGFrameView::paintGL()
431 glViewport(0, 0, gl_width, gl_height);
432 if (current_frame == nullptr) {
433 glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
434 glClear(GL_COLOR_BUFFER_BIT);
439 current_chain->render_to_screen();
441 if (overlay_image != nullptr) {
442 if (overlay_input_needs_refresh) {
443 overlay_input->set_width(overlay_width);
444 overlay_input->set_height(overlay_height);
445 overlay_input->set_pixel_data(overlay_image->bits());
447 glViewport(gl_width - overlay_width, 0, overlay_width, overlay_height);
448 overlay_chain->render_to_screen();
456 void JPEGFrameView::setDecodedFrame(shared_ptr<Frame> frame, shared_ptr<Frame> secondary_frame, float fade_alpha)
458 post_to_main_thread([this, frame, secondary_frame, fade_alpha] {
459 current_frame = frame;
460 current_secondary_frame = secondary_frame;
462 if (secondary_frame != nullptr) {
463 current_chain = ycbcr_converter->prepare_chain_for_fade(frame, secondary_frame, fade_alpha);
465 current_chain = ycbcr_converter->prepare_chain_for_conversion(frame);
471 void JPEGFrameView::mousePressEvent(QMouseEvent *event)
473 if (event->type() == QEvent::MouseButtonPress && event->button() == Qt::LeftButton) {
478 void JPEGFrameView::set_overlay(const string &text)
481 overlay_image.reset();
485 float dpr = QGuiApplication::primaryScreen()->devicePixelRatio();
486 overlay_width = lrint(overlay_base_width * dpr);
487 overlay_height = lrint(overlay_base_height * dpr);
489 overlay_image.reset(new QImage(overlay_width, overlay_height, QImage::Format_Grayscale8));
490 overlay_image->setDevicePixelRatio(dpr);
491 overlay_image->fill(0);
492 QPainter painter(overlay_image.get());
494 painter.setPen(Qt::white);
495 QFont font = painter.font();
496 font.setPointSize(12);
497 painter.setFont(font);
499 painter.drawText(QRectF(0, 0, overlay_base_width, overlay_base_height), Qt::AlignCenter, QString::fromStdString(text));
501 // Don't refresh immediately; we might not have an OpenGL context here.
502 overlay_input_needs_refresh = true;
505 shared_ptr<Frame> get_black_frame()
507 static shared_ptr<Frame> black_frame;
508 static once_flag flag;
510 black_frame.reset(new Frame);
511 black_frame->y.reset(new uint8_t[global_flags.width * global_flags.height]);
512 black_frame->cb.reset(new uint8_t[(global_flags.width / 2) * (global_flags.height / 2)]);
513 black_frame->cr.reset(new uint8_t[(global_flags.width / 2) * (global_flags.height / 2)]);
514 black_frame->width = global_flags.width;
515 black_frame->height = global_flags.height;
516 black_frame->chroma_subsampling_x = 2;
517 black_frame->chroma_subsampling_y = 2;
518 black_frame->pitch_y = global_flags.width;
519 black_frame->pitch_chroma = global_flags.width / 2;
521 ++metric_jpeg_software_fail_frames;