1 #include "jpeg_frame_view.h"
5 #include "jpeg_destroyer.h"
6 #include "jpeglib_error_wrapper.h"
7 #include "shared/post_to_main_thread.h"
8 #include "video_stream.h"
9 #include "ycbcr_converter.h"
11 #include <QMouseEvent>
14 #include <condition_variable>
17 #include <movit/init.h>
18 #include <movit/resource_pool.h>
19 #include <movit/util.h>
26 // Must come after the Qt stuff.
27 #include "vaapi_jpeg_decoder.h"
29 using namespace movit;
34 // Just an arbitrary order for std::map.
35 struct FrameOnDiskLexicalOrder
37 bool operator() (const FrameOnDisk &a, const FrameOnDisk &b) const
41 if (a.offset != b.offset)
42 return a.offset < b.offset;
43 if (a.filename_idx != b.filename_idx)
44 return a.filename_idx < b.filename_idx;
45 assert(a.size == b.size);
50 inline size_t frame_size(const Frame &frame)
52 size_t y_size = frame.width * frame.height;
53 size_t cbcr_size = y_size / frame.chroma_subsampling_x / frame.chroma_subsampling_y;
54 return y_size + cbcr_size * 2;
58 shared_ptr<Frame> frame;
62 struct PendingDecode {
63 JPEGFrameView *destination;
65 // For actual decodes (only if frame below is nullptr).
66 FrameOnDisk primary, secondary;
67 float fade_alpha; // Irrelevant if secondary.stream_idx == -1.
69 // Already-decoded frames are also sent through PendingDecode,
70 // so that they get drawn in the right order. If frame is nullptr,
71 // it's a real decode.
72 shared_ptr<Frame> frame;
77 thread JPEGFrameView::jpeg_decoder_thread;
79 map<FrameOnDisk, LRUFrame, FrameOnDiskLexicalOrder> cache; // Under cache_mu.
80 size_t cache_bytes_used = 0; // Under cache_mu.
81 condition_variable any_pending_decodes;
82 deque<PendingDecode> pending_decodes; // Under cache_mu.
83 atomic<size_t> event_counter{0};
84 extern QGLWidget *global_share_widget;
85 extern atomic<bool> should_quit;
87 shared_ptr<Frame> decode_jpeg(const string &jpeg)
89 shared_ptr<Frame> frame;
90 if (vaapi_jpeg_decoding_usable) {
91 frame = decode_jpeg_vaapi(jpeg);
92 if (frame != nullptr) {
95 fprintf(stderr, "VA-API hardware decoding failed; falling back to software.\n");
98 frame.reset(new Frame);
100 jpeg_decompress_struct dinfo;
101 JPEGWrapErrorManager error_mgr(&dinfo);
102 if (!error_mgr.run([&dinfo]{ jpeg_create_decompress(&dinfo); })) {
103 return get_black_frame();
105 JPEGDestroyer destroy_dinfo(&dinfo);
107 if (!error_mgr.run([&dinfo, &jpeg]{
108 jpeg_mem_src(&dinfo, reinterpret_cast<const unsigned char *>(jpeg.data()), jpeg.size());
109 jpeg_read_header(&dinfo, true);
111 return get_black_frame();
114 if (dinfo.num_components != 3) {
115 fprintf(stderr, "Not a color JPEG. (%d components, Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
116 dinfo.num_components,
117 dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
118 dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
119 dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
120 return get_black_frame();
122 if (dinfo.comp_info[0].h_samp_factor != dinfo.max_h_samp_factor ||
123 dinfo.comp_info[0].v_samp_factor != dinfo.max_v_samp_factor || // Y' must not be subsampled.
124 dinfo.comp_info[1].h_samp_factor != dinfo.comp_info[2].h_samp_factor ||
125 dinfo.comp_info[1].v_samp_factor != dinfo.comp_info[2].v_samp_factor || // Cb and Cr must be identically subsampled.
126 (dinfo.max_h_samp_factor % dinfo.comp_info[1].h_samp_factor) != 0 ||
127 (dinfo.max_v_samp_factor % dinfo.comp_info[1].v_samp_factor) != 0) { // No 2:3 subsampling or other weirdness.
128 fprintf(stderr, "Unsupported subsampling scheme. (Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
129 dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
130 dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
131 dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
134 dinfo.raw_data_out = true;
136 if (!error_mgr.run([&dinfo]{
137 jpeg_start_decompress(&dinfo);
139 return get_black_frame();
142 frame->width = dinfo.output_width;
143 frame->height = dinfo.output_height;
144 frame->chroma_subsampling_x = dinfo.max_h_samp_factor / dinfo.comp_info[1].h_samp_factor;
145 frame->chroma_subsampling_y = dinfo.max_v_samp_factor / dinfo.comp_info[1].v_samp_factor;
147 unsigned h_mcu_size = DCTSIZE * dinfo.max_h_samp_factor;
148 unsigned v_mcu_size = DCTSIZE * dinfo.max_v_samp_factor;
149 unsigned mcu_width_blocks = (dinfo.output_width + h_mcu_size - 1) / h_mcu_size;
150 unsigned mcu_height_blocks = (dinfo.output_height + v_mcu_size - 1) / v_mcu_size;
152 unsigned luma_width_blocks = mcu_width_blocks * dinfo.comp_info[0].h_samp_factor;
153 unsigned chroma_width_blocks = mcu_width_blocks * dinfo.comp_info[1].h_samp_factor;
154 unsigned luma_height_blocks = mcu_height_blocks * dinfo.comp_info[0].v_samp_factor;
155 unsigned chroma_height_blocks = mcu_height_blocks * dinfo.comp_info[1].v_samp_factor;
157 // TODO: Decode into a PBO.
158 frame->y.reset(new uint8_t[luma_width_blocks * luma_height_blocks * DCTSIZE2]);
159 frame->cb.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
160 frame->cr.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
161 frame->pitch_y = luma_width_blocks * DCTSIZE;
162 frame->pitch_chroma = chroma_width_blocks * DCTSIZE;
164 if (!error_mgr.run([&dinfo, &frame, v_mcu_size, mcu_height_blocks] {
165 JSAMPROW yptr[v_mcu_size], cbptr[v_mcu_size], crptr[v_mcu_size];
166 JSAMPARRAY data[3] = { yptr, cbptr, crptr };
167 for (unsigned y = 0; y < mcu_height_blocks; ++y) {
168 // NOTE: The last elements of cbptr/crptr will be unused for vertically subsampled chroma.
169 for (unsigned yy = 0; yy < v_mcu_size; ++yy) {
170 yptr[yy] = frame->y.get() + (y * DCTSIZE * dinfo.max_v_samp_factor + yy) * frame->pitch_y;
171 cbptr[yy] = frame->cb.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
172 crptr[yy] = frame->cr.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
175 jpeg_read_raw_data(&dinfo, data, v_mcu_size);
178 (void)jpeg_finish_decompress(&dinfo);
180 return get_black_frame();
188 // Assumes cache_mu is held.
189 int64_t bytes_still_to_remove = cache_bytes_used - (size_t(CACHE_SIZE_MB) * 1024 * 1024) * 9 / 10;
190 if (bytes_still_to_remove <= 0) return;
192 vector<pair<size_t, size_t>> lru_timestamps_and_size;
193 for (const auto &key_and_value : cache) {
194 lru_timestamps_and_size.emplace_back(
195 key_and_value.second.last_used,
196 frame_size(*key_and_value.second.frame));
198 sort(lru_timestamps_and_size.begin(), lru_timestamps_and_size.end());
200 // Remove the oldest ones until we are below 90% of the cache used.
201 size_t lru_cutoff_point = 0;
202 for (const pair<size_t, size_t> &it : lru_timestamps_and_size) {
203 lru_cutoff_point = it.first;
204 bytes_still_to_remove -= it.second;
205 if (bytes_still_to_remove <= 0) break;
208 for (auto it = cache.begin(); it != cache.end(); ) {
209 if (it->second.last_used <= lru_cutoff_point) {
210 cache_bytes_used -= frame_size(*it->second.frame);
211 it = cache.erase(it);
218 shared_ptr<Frame> decode_jpeg_with_cache(FrameOnDisk frame_spec, CacheMissBehavior cache_miss_behavior, FrameReader *frame_reader, bool *did_decode)
222 unique_lock<mutex> lock(cache_mu);
223 auto it = cache.find(frame_spec);
224 if (it != cache.end()) {
225 it->second.last_used = event_counter++;
226 return it->second.frame;
230 if (cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE) {
235 shared_ptr<Frame> frame = decode_jpeg(frame_reader->read_frame(frame_spec));
237 unique_lock<mutex> lock(cache_mu);
238 cache_bytes_used += frame_size(*frame);
239 cache[frame_spec] = LRUFrame{ frame, event_counter++ };
241 if (cache_bytes_used > size_t(CACHE_SIZE_MB) * 1024 * 1024) {
247 void JPEGFrameView::jpeg_decoder_thread_func()
249 size_t num_decoded = 0, num_dropped = 0;
251 pthread_setname_np(pthread_self(), "JPEGDecoder");
252 while (!should_quit.load()) {
253 PendingDecode decode;
254 CacheMissBehavior cache_miss_behavior = DECODE_IF_NOT_IN_CACHE;
256 unique_lock<mutex> lock(cache_mu); // TODO: Perhaps under another lock?
257 any_pending_decodes.wait(lock, [] {
258 return !pending_decodes.empty() || should_quit.load();
260 if (should_quit.load())
262 decode = pending_decodes.front();
263 pending_decodes.pop_front();
265 size_t num_pending = 0;
266 for (const PendingDecode &other_decode : pending_decodes) {
267 if (other_decode.destination == decode.destination) {
271 if (num_pending > 3) {
272 cache_miss_behavior = RETURN_NULLPTR_IF_NOT_IN_CACHE;
276 if (decode.frame != nullptr) {
277 // Already decoded, so just show it.
278 decode.destination->setDecodedFrame(decode.frame, nullptr, 1.0f);
282 shared_ptr<Frame> primary_frame, secondary_frame;
284 for (int subframe_idx = 0; subframe_idx < 2; ++subframe_idx) {
285 const FrameOnDisk &frame_spec = (subframe_idx == 0 ? decode.primary : decode.secondary);
286 if (frame_spec.pts == -1) {
287 // No secondary frame.
292 shared_ptr<Frame> frame = decode_jpeg_with_cache(frame_spec, cache_miss_behavior, &decode.destination->frame_reader, &found_in_cache);
294 if (frame == nullptr) {
295 assert(cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE);
300 if (!found_in_cache) {
302 if (num_decoded % 1000 == 0) {
303 fprintf(stderr, "Decoded %zu images, dropped %zu (%.2f%% dropped)\n",
304 num_decoded, num_dropped, (100.0 * num_dropped) / (num_decoded + num_dropped));
307 if (subframe_idx == 0) {
308 primary_frame = std::move(frame);
310 secondary_frame = std::move(frame);
318 // TODO: Could we get jitter between non-interpolated and interpolated frames here?
319 decode.destination->setDecodedFrame(primary_frame, secondary_frame, decode.fade_alpha);
323 void JPEGFrameView::shutdown()
325 any_pending_decodes.notify_all();
326 jpeg_decoder_thread.join();
329 JPEGFrameView::JPEGFrameView(QWidget *parent)
330 : QGLWidget(parent, global_share_widget)
334 void JPEGFrameView::setFrame(unsigned stream_idx, FrameOnDisk frame, FrameOnDisk secondary_frame, float fade_alpha)
336 current_stream_idx = stream_idx; // TODO: Does this interact with fades?
338 unique_lock<mutex> lock(cache_mu);
339 PendingDecode decode;
340 decode.primary = frame;
341 decode.secondary = secondary_frame;
342 decode.fade_alpha = fade_alpha;
343 decode.destination = this;
344 pending_decodes.push_back(decode);
345 any_pending_decodes.notify_all();
348 void JPEGFrameView::setFrame(shared_ptr<Frame> frame)
350 unique_lock<mutex> lock(cache_mu);
351 PendingDecode decode;
352 decode.frame = std::move(frame);
353 decode.destination = this;
354 pending_decodes.push_back(decode);
355 any_pending_decodes.notify_all();
358 ResourcePool *resource_pool = nullptr;
360 void JPEGFrameView::initializeGL()
363 glDisable(GL_DEPTH_TEST);
366 static once_flag once;
368 resource_pool = new ResourcePool;
369 jpeg_decoder_thread = std::thread(jpeg_decoder_thread_func);
372 ycbcr_converter.reset(new YCbCrConverter(YCbCrConverter::OUTPUT_TO_RGBA, resource_pool));
374 ImageFormat inout_format;
375 inout_format.color_space = COLORSPACE_sRGB;
376 inout_format.gamma_curve = GAMMA_sRGB;
378 overlay_chain.reset(new EffectChain(overlay_base_width, overlay_base_height, resource_pool));
379 overlay_input = (movit::FlatInput *)overlay_chain->add_input(new FlatInput(inout_format, FORMAT_GRAYSCALE, GL_UNSIGNED_BYTE, overlay_base_width, overlay_base_height));
381 overlay_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
382 overlay_chain->finalize();
385 void JPEGFrameView::resizeGL(int width, int height)
388 glViewport(0, 0, width, height);
391 // Save these, as width() and height() will lie with DPI scaling.
396 void JPEGFrameView::paintGL()
398 glViewport(0, 0, gl_width, gl_height);
399 if (current_frame == nullptr) {
400 glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
401 glClear(GL_COLOR_BUFFER_BIT);
406 current_chain->render_to_screen();
408 if (overlay_image != nullptr) {
409 if (overlay_input_needs_refresh) {
410 overlay_input->set_width(overlay_width);
411 overlay_input->set_height(overlay_height);
412 overlay_input->set_pixel_data(overlay_image->bits());
414 glViewport(gl_width - overlay_width, 0, overlay_width, overlay_height);
415 overlay_chain->render_to_screen();
423 void JPEGFrameView::setDecodedFrame(shared_ptr<Frame> frame, shared_ptr<Frame> secondary_frame, float fade_alpha)
425 post_to_main_thread([this, frame, secondary_frame, fade_alpha] {
426 current_frame = frame;
427 current_secondary_frame = secondary_frame;
429 if (secondary_frame != nullptr) {
430 current_chain = ycbcr_converter->prepare_chain_for_fade(frame, secondary_frame, fade_alpha);
432 current_chain = ycbcr_converter->prepare_chain_for_conversion(frame);
438 void JPEGFrameView::mousePressEvent(QMouseEvent *event)
440 if (event->type() == QEvent::MouseButtonPress && event->button() == Qt::LeftButton) {
445 void JPEGFrameView::set_overlay(const string &text)
448 overlay_image.reset();
452 float dpr = QGuiApplication::primaryScreen()->devicePixelRatio();
453 overlay_width = lrint(overlay_base_width * dpr);
454 overlay_height = lrint(overlay_base_height * dpr);
456 overlay_image.reset(new QImage(overlay_width, overlay_height, QImage::Format_Grayscale8));
457 overlay_image->setDevicePixelRatio(dpr);
458 overlay_image->fill(0);
459 QPainter painter(overlay_image.get());
461 painter.setPen(Qt::white);
462 QFont font = painter.font();
463 font.setPointSize(12);
464 painter.setFont(font);
466 painter.drawText(QRectF(0, 0, overlay_base_width, overlay_base_height), Qt::AlignCenter, QString::fromStdString(text));
468 // Don't refresh immediately; we might not have an OpenGL context here.
469 overlay_input_needs_refresh = true;
472 shared_ptr<Frame> get_black_frame()
474 static shared_ptr<Frame> black_frame;
475 static once_flag flag;
477 black_frame.reset(new Frame);
478 black_frame->y.reset(new uint8_t[global_flags.width * global_flags.height]);
479 black_frame->cb.reset(new uint8_t[(global_flags.width / 2) * (global_flags.height / 2)]);
480 black_frame->cr.reset(new uint8_t[(global_flags.width / 2) * (global_flags.height / 2)]);
481 black_frame->width = global_flags.width;
482 black_frame->height = global_flags.height;
483 black_frame->chroma_subsampling_x = 2;
484 black_frame->chroma_subsampling_y = 2;
485 black_frame->pitch_y = global_flags.width;
486 black_frame->pitch_chroma = global_flags.width / 2;