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>
16 #include <condition_variable>
19 #include <movit/init.h>
20 #include <movit/resource_pool.h>
21 #include <movit/util.h>
28 // Must come after the Qt stuff.
29 #include "vaapi_jpeg_decoder.h"
31 using namespace movit;
33 using namespace std::chrono;
37 // Just an arbitrary order for std::map.
38 struct FrameOnDiskLexicalOrder {
39 bool operator()(const FrameOnDisk &a, const FrameOnDisk &b) const
43 if (a.offset != b.offset)
44 return a.offset < b.offset;
45 if (a.filename_idx != b.filename_idx)
46 return a.filename_idx < b.filename_idx;
47 assert(a.size == b.size);
52 inline size_t frame_size(const Frame &frame)
54 size_t y_size = frame.width * frame.height;
55 size_t cbcr_size = y_size / frame.chroma_subsampling_x / frame.chroma_subsampling_y;
56 return y_size + cbcr_size * 2;
60 shared_ptr<Frame> frame;
64 // There can be multiple JPEGFrameView instances, so make all the metrics static.
65 once_flag jpeg_metrics_inited;
66 atomic<int64_t> metric_jpeg_cache_used_bytes{ 0 }; // Same value as cache_bytes_used.
67 atomic<int64_t> metric_jpeg_cache_limit_bytes{ size_t(CACHE_SIZE_MB) * 1024 * 1024 };
68 atomic<int64_t> metric_jpeg_cache_given_up_frames{ 0 };
69 atomic<int64_t> metric_jpeg_cache_hit_frames{ 0 };
70 atomic<int64_t> metric_jpeg_cache_miss_frames{ 0 };
71 atomic<int64_t> metric_jpeg_software_decode_frames{ 0 };
72 atomic<int64_t> metric_jpeg_software_fail_frames{ 0 };
73 atomic<int64_t> metric_jpeg_vaapi_decode_frames{ 0 };
74 atomic<int64_t> metric_jpeg_vaapi_fail_frames{ 0 };
75 Summary metric_jpeg_decode_time_seconds;
80 map<FrameOnDisk, LRUFrame, FrameOnDiskLexicalOrder> cache; // Under cache_mu.
81 size_t cache_bytes_used = 0; // Under cache_mu.
82 atomic<size_t> event_counter{ 0 };
83 extern QGLWidget *global_share_widget;
84 extern atomic<bool> should_quit;
86 shared_ptr<Frame> decode_jpeg(const string &jpeg)
88 steady_clock::time_point start = steady_clock::now();
89 shared_ptr<Frame> frame;
90 if (vaapi_jpeg_decoding_usable) {
91 frame = decode_jpeg_vaapi(jpeg);
92 if (frame != nullptr) {
93 ++metric_jpeg_vaapi_decode_frames;
94 steady_clock::time_point stop = steady_clock::now();
95 metric_jpeg_decode_time_seconds.count_event(duration<double>(stop - start).count());
98 fprintf(stderr, "VA-API hardware decoding failed; falling back to software.\n");
99 ++metric_jpeg_vaapi_fail_frames;
102 frame.reset(new Frame);
104 jpeg_decompress_struct dinfo;
105 JPEGWrapErrorManager error_mgr(&dinfo);
106 if (!error_mgr.run([&dinfo] { jpeg_create_decompress(&dinfo); })) {
107 return get_black_frame();
109 JPEGDestroyer destroy_dinfo(&dinfo);
111 if (!error_mgr.run([&dinfo, &jpeg] {
112 jpeg_mem_src(&dinfo, reinterpret_cast<const unsigned char *>(jpeg.data()), jpeg.size());
113 jpeg_read_header(&dinfo, true);
115 return get_black_frame();
118 jpeg_save_markers(&dinfo, JPEG_APP0 + 1, 0xFFFF);
120 if (dinfo.num_components != 3) {
121 fprintf(stderr, "Not a color JPEG. (%d components, Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
122 dinfo.num_components,
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 return get_black_frame();
128 if (dinfo.comp_info[0].h_samp_factor != dinfo.max_h_samp_factor ||
129 dinfo.comp_info[0].v_samp_factor != dinfo.max_v_samp_factor || // Y' must not be subsampled.
130 dinfo.comp_info[1].h_samp_factor != dinfo.comp_info[2].h_samp_factor ||
131 dinfo.comp_info[1].v_samp_factor != dinfo.comp_info[2].v_samp_factor || // Cb and Cr must be identically subsampled.
132 (dinfo.max_h_samp_factor % dinfo.comp_info[1].h_samp_factor) != 0 ||
133 (dinfo.max_v_samp_factor % dinfo.comp_info[1].v_samp_factor) != 0) { // No 2:3 subsampling or other weirdness.
134 fprintf(stderr, "Unsupported subsampling scheme. (Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
135 dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
136 dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
137 dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
140 dinfo.raw_data_out = true;
142 if (!error_mgr.run([&dinfo] {
143 jpeg_start_decompress(&dinfo);
145 return get_black_frame();
148 frame->width = dinfo.output_width;
149 frame->height = dinfo.output_height;
150 frame->chroma_subsampling_x = dinfo.max_h_samp_factor / dinfo.comp_info[1].h_samp_factor;
151 frame->chroma_subsampling_y = dinfo.max_v_samp_factor / dinfo.comp_info[1].v_samp_factor;
153 unsigned h_mcu_size = DCTSIZE * dinfo.max_h_samp_factor;
154 unsigned v_mcu_size = DCTSIZE * dinfo.max_v_samp_factor;
155 unsigned mcu_width_blocks = (dinfo.output_width + h_mcu_size - 1) / h_mcu_size;
156 unsigned mcu_height_blocks = (dinfo.output_height + v_mcu_size - 1) / v_mcu_size;
158 unsigned luma_width_blocks = mcu_width_blocks * dinfo.comp_info[0].h_samp_factor;
159 unsigned chroma_width_blocks = mcu_width_blocks * dinfo.comp_info[1].h_samp_factor;
160 unsigned luma_height_blocks = mcu_height_blocks * dinfo.comp_info[0].v_samp_factor;
161 unsigned chroma_height_blocks = mcu_height_blocks * dinfo.comp_info[1].v_samp_factor;
163 // TODO: Decode into a PBO.
164 frame->y.reset(new uint8_t[luma_width_blocks * luma_height_blocks * DCTSIZE2]);
165 frame->cb.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
166 frame->cr.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
167 frame->pitch_y = luma_width_blocks * DCTSIZE;
168 frame->pitch_chroma = chroma_width_blocks * DCTSIZE;
170 if (dinfo.marker_list != nullptr &&
171 dinfo.marker_list->marker == JPEG_APP0 + 1 &&
172 dinfo.marker_list->data_length >= 4 &&
173 memcmp(dinfo.marker_list->data, "Exif", 4) == 0) {
174 frame->exif_data.assign(reinterpret_cast<char *>(dinfo.marker_list->data),
175 dinfo.marker_list->data_length);
178 if (!error_mgr.run([&dinfo, &frame, v_mcu_size, mcu_height_blocks] {
179 JSAMPROW yptr[v_mcu_size], cbptr[v_mcu_size], crptr[v_mcu_size];
180 JSAMPARRAY data[3] = { yptr, cbptr, crptr };
181 for (unsigned y = 0; y < mcu_height_blocks; ++y) {
182 // NOTE: The last elements of cbptr/crptr will be unused for vertically subsampled chroma.
183 for (unsigned yy = 0; yy < v_mcu_size; ++yy) {
184 yptr[yy] = frame->y.get() + (y * DCTSIZE * dinfo.max_v_samp_factor + yy) * frame->pitch_y;
185 cbptr[yy] = frame->cb.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
186 crptr[yy] = frame->cr.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
189 jpeg_read_raw_data(&dinfo, data, v_mcu_size);
192 (void)jpeg_finish_decompress(&dinfo);
194 return get_black_frame();
197 ++metric_jpeg_software_decode_frames;
198 steady_clock::time_point stop = steady_clock::now();
199 metric_jpeg_decode_time_seconds.count_event(duration<double>(stop - start).count());
205 // Assumes cache_mu is held.
206 int64_t bytes_still_to_remove = cache_bytes_used - (size_t(CACHE_SIZE_MB) * 1024 * 1024) * 9 / 10;
207 if (bytes_still_to_remove <= 0)
210 vector<pair<size_t, size_t>> lru_timestamps_and_size;
211 for (const auto &key_and_value : cache) {
212 lru_timestamps_and_size.emplace_back(
213 key_and_value.second.last_used,
214 frame_size(*key_and_value.second.frame));
216 sort(lru_timestamps_and_size.begin(), lru_timestamps_and_size.end());
218 // Remove the oldest ones until we are below 90% of the cache used.
219 size_t lru_cutoff_point = 0;
220 for (const pair<size_t, size_t> &it : lru_timestamps_and_size) {
221 lru_cutoff_point = it.first;
222 bytes_still_to_remove -= it.second;
223 if (bytes_still_to_remove <= 0)
227 for (auto it = cache.begin(); it != cache.end();) {
228 if (it->second.last_used <= lru_cutoff_point) {
229 cache_bytes_used -= frame_size(*it->second.frame);
230 metric_jpeg_cache_used_bytes = cache_bytes_used;
231 it = cache.erase(it);
238 shared_ptr<Frame> decode_jpeg_with_cache(FrameOnDisk frame_spec, CacheMissBehavior cache_miss_behavior, FrameReader *frame_reader, bool *did_decode)
242 lock_guard<mutex> lock(cache_mu);
243 auto it = cache.find(frame_spec);
244 if (it != cache.end()) {
245 ++metric_jpeg_cache_hit_frames;
246 it->second.last_used = event_counter++;
247 return it->second.frame;
251 if (cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE) {
252 ++metric_jpeg_cache_given_up_frames;
256 ++metric_jpeg_cache_miss_frames;
259 shared_ptr<Frame> frame = decode_jpeg(frame_reader->read_frame(frame_spec, /*read_video=*/true, /*read_audio=*/false).video);
261 lock_guard<mutex> lock(cache_mu);
262 cache_bytes_used += frame_size(*frame);
263 metric_jpeg_cache_used_bytes = cache_bytes_used;
264 cache[frame_spec] = LRUFrame{ frame, event_counter++ };
266 if (cache_bytes_used > size_t(CACHE_SIZE_MB) * 1024 * 1024) {
272 void JPEGFrameView::jpeg_decoder_thread_func()
274 size_t num_decoded = 0, num_dropped = 0;
276 pthread_setname_np(pthread_self(), "JPEGDecoder");
277 while (!should_quit.load()) {
278 PendingDecode decode;
279 CacheMissBehavior cache_miss_behavior = DECODE_IF_NOT_IN_CACHE;
281 unique_lock<mutex> lock(cache_mu); // TODO: Perhaps under another lock?
282 any_pending_decodes.wait(lock, [this] {
283 return !pending_decodes.empty() || should_quit.load();
285 if (should_quit.load())
287 decode = pending_decodes.front();
288 pending_decodes.pop_front();
290 if (pending_decodes.size() > 3) {
291 cache_miss_behavior = RETURN_NULLPTR_IF_NOT_IN_CACHE;
295 if (decode.frame != nullptr) {
296 // Already decoded, so just show it.
297 setDecodedFrame(decode.frame, nullptr, 1.0f);
301 shared_ptr<Frame> primary_frame, secondary_frame;
303 for (int subframe_idx = 0; subframe_idx < 2; ++subframe_idx) {
304 const FrameOnDisk &frame_spec = (subframe_idx == 0 ? decode.primary : decode.secondary);
305 if (frame_spec.pts == -1) {
306 // No secondary frame.
311 shared_ptr<Frame> frame = decode_jpeg_with_cache(frame_spec, cache_miss_behavior, &frame_reader, &found_in_cache);
313 if (frame == nullptr) {
314 assert(cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE);
319 if (!found_in_cache) {
321 if (num_decoded % 1000 == 0) {
322 fprintf(stderr, "Decoded %zu images, dropped %zu (%.2f%% dropped)\n",
323 num_decoded, num_dropped, (100.0 * num_dropped) / (num_decoded + num_dropped));
326 if (subframe_idx == 0) {
327 primary_frame = std::move(frame);
329 secondary_frame = std::move(frame);
337 // TODO: Could we get jitter between non-interpolated and interpolated frames here?
338 setDecodedFrame(primary_frame, secondary_frame, decode.fade_alpha);
342 JPEGFrameView::~JPEGFrameView()
344 any_pending_decodes.notify_all();
345 jpeg_decoder_thread.join();
348 JPEGFrameView::JPEGFrameView(QWidget *parent)
349 : QGLWidget(parent, global_share_widget)
351 call_once(jpeg_metrics_inited, [] {
352 global_metrics.add("jpeg_cache_used_bytes", &metric_jpeg_cache_used_bytes, Metrics::TYPE_GAUGE);
353 global_metrics.add("jpeg_cache_limit_bytes", &metric_jpeg_cache_limit_bytes, Metrics::TYPE_GAUGE);
354 global_metrics.add("jpeg_cache_frames", { { "action", "given_up" } }, &metric_jpeg_cache_given_up_frames);
355 global_metrics.add("jpeg_cache_frames", { { "action", "hit" } }, &metric_jpeg_cache_hit_frames);
356 global_metrics.add("jpeg_cache_frames", { { "action", "miss" } }, &metric_jpeg_cache_miss_frames);
357 global_metrics.add("jpeg_decode_frames", { { "decoder", "software" }, { "result", "decode" } }, &metric_jpeg_software_decode_frames);
358 global_metrics.add("jpeg_decode_frames", { { "decoder", "software" }, { "result", "fail" } }, &metric_jpeg_software_fail_frames);
359 global_metrics.add("jpeg_decode_frames", { { "decoder", "vaapi" }, { "result", "decode" } }, &metric_jpeg_vaapi_decode_frames);
360 global_metrics.add("jpeg_decode_frames", { { "decoder", "vaapi" }, { "result", "fail" } }, &metric_jpeg_vaapi_fail_frames);
361 vector<double> quantiles{ 0.01, 0.1, 0.25, 0.5, 0.75, 0.9, 0.99 };
362 metric_jpeg_decode_time_seconds.init(quantiles, 60.0);
363 global_metrics.add("jpeg_decode_time_seconds", &metric_jpeg_decode_time_seconds);
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 lock_guard<mutex> lock(cache_mu);
372 PendingDecode decode;
373 decode.primary = frame;
374 decode.secondary = secondary_frame;
375 decode.fade_alpha = fade_alpha;
376 pending_decodes.push_back(decode);
377 any_pending_decodes.notify_all();
380 void JPEGFrameView::setFrame(shared_ptr<Frame> frame)
382 lock_guard<mutex> lock(cache_mu);
383 PendingDecode decode;
384 decode.frame = std::move(frame);
385 pending_decodes.push_back(decode);
386 any_pending_decodes.notify_all();
389 void JPEGFrameView::initializeGL()
392 glDisable(GL_DEPTH_TEST);
395 resource_pool = new ResourcePool;
396 jpeg_decoder_thread = std::thread(&JPEGFrameView::jpeg_decoder_thread_func, this);
398 ycbcr_converter.reset(new YCbCrConverter(YCbCrConverter::OUTPUT_TO_RGBA, resource_pool));
400 ImageFormat inout_format;
401 inout_format.color_space = COLORSPACE_sRGB;
402 inout_format.gamma_curve = GAMMA_sRGB;
404 overlay_chain.reset(new EffectChain(overlay_base_width, overlay_base_height, resource_pool));
405 overlay_input = (movit::FlatInput *)overlay_chain->add_input(new FlatInput(inout_format, FORMAT_GRAYSCALE, GL_UNSIGNED_BYTE, overlay_base_width, overlay_base_height));
407 overlay_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
408 overlay_chain->finalize();
411 void JPEGFrameView::resizeGL(int width, int height)
414 glViewport(0, 0, width, height);
417 // Save these, as width() and height() will lie with DPI scaling.
422 void JPEGFrameView::paintGL()
424 glViewport(0, 0, gl_width, gl_height);
425 if (current_frame == nullptr) {
426 glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
427 glClear(GL_COLOR_BUFFER_BIT);
432 current_chain->render_to_screen();
434 if (overlay_image != nullptr) {
435 if (overlay_input_needs_refresh) {
436 overlay_input->set_width(overlay_width);
437 overlay_input->set_height(overlay_height);
438 overlay_input->set_pixel_data(overlay_image->bits());
439 overlay_input_needs_refresh = false;
441 glViewport(gl_width - overlay_width, 0, overlay_width, overlay_height);
442 overlay_chain->render_to_screen();
450 void JPEGFrameView::setDecodedFrame(shared_ptr<Frame> frame, shared_ptr<Frame> secondary_frame, float fade_alpha)
452 post_to_main_thread([this, frame, secondary_frame, fade_alpha] {
453 current_frame = frame;
454 current_secondary_frame = secondary_frame;
456 if (secondary_frame != nullptr) {
457 current_chain = ycbcr_converter->prepare_chain_for_fade(frame, secondary_frame, fade_alpha);
459 current_chain = ycbcr_converter->prepare_chain_for_conversion(frame);
465 void JPEGFrameView::mousePressEvent(QMouseEvent *event)
467 if (event->type() == QEvent::MouseButtonPress && event->button() == Qt::LeftButton) {
472 void JPEGFrameView::set_overlay(const string &text)
475 overlay_image.reset();
479 // Figure out how large the texture needs to be.
481 QImage img(overlay_width, overlay_height, QImage::Format_Grayscale8);
482 QPainter painter(&img);
483 QFont font = painter.font();
484 font.setPointSize(12);
485 QFontMetrics metrics(font);
486 overlay_base_width = lrint(metrics.boundingRect(QString::fromStdString(text)).width() + 8.0);
487 overlay_base_height = lrint(metrics.height());
490 float dpr = QGuiApplication::primaryScreen()->devicePixelRatio();
491 overlay_width = lrint(overlay_base_width * dpr);
492 overlay_height = lrint(overlay_base_height * dpr);
494 // Work around OpenGL alignment issues.
495 while (overlay_width % 4 != 0) ++overlay_width;
497 // Now do the actual drawing.
498 overlay_image.reset(new QImage(overlay_width, overlay_height, QImage::Format_Grayscale8));
499 overlay_image->setDevicePixelRatio(dpr);
500 overlay_image->fill(0);
501 QPainter painter(overlay_image.get());
503 painter.setPen(Qt::white);
504 QFont font = painter.font();
505 font.setPointSize(12);
506 painter.setFont(font);
508 painter.drawText(QRectF(0, 0, overlay_base_width, overlay_base_height), Qt::AlignCenter, QString::fromStdString(text));
510 // Don't refresh immediately; we might not have an OpenGL context here.
511 overlay_input_needs_refresh = true;
514 shared_ptr<Frame> get_black_frame()
516 static shared_ptr<Frame> black_frame;
517 static once_flag flag;
519 black_frame.reset(new Frame);
520 black_frame->y.reset(new uint8_t[global_flags.width * global_flags.height]);
521 black_frame->cb.reset(new uint8_t[(global_flags.width / 2) * (global_flags.height / 2)]);
522 black_frame->cr.reset(new uint8_t[(global_flags.width / 2) * (global_flags.height / 2)]);
523 black_frame->width = global_flags.width;
524 black_frame->height = global_flags.height;
525 black_frame->chroma_subsampling_x = 2;
526 black_frame->chroma_subsampling_y = 2;
527 black_frame->pitch_y = global_flags.width;
528 black_frame->pitch_chroma = global_flags.width / 2;
530 ++metric_jpeg_software_fail_frames;