1 #include "jpeg_frame_view.h"
4 #include "jpeg_destroyer.h"
5 #include "jpeglib_error_wrapper.h"
6 #include "shared/post_to_main_thread.h"
7 #include "video_stream.h"
8 #include "ycbcr_converter.h"
10 #include <QMouseEvent>
13 #include <condition_variable>
16 #include <movit/init.h>
17 #include <movit/resource_pool.h>
18 #include <movit/util.h>
25 // Must come after the Qt stuff.
26 #include "vaapi_jpeg_decoder.h"
28 using namespace movit;
33 // Just an arbitrary order for std::map.
34 struct FrameOnDiskLexicalOrder
36 bool operator() (const FrameOnDisk &a, const FrameOnDisk &b) const
40 if (a.offset != b.offset)
41 return a.offset < b.offset;
42 if (a.filename_idx != b.filename_idx)
43 return a.filename_idx < b.filename_idx;
44 assert(a.size == b.size);
49 inline size_t frame_size(const Frame &frame)
51 size_t y_size = frame.width * frame.height;
52 size_t cbcr_size = y_size / frame.chroma_subsampling_x / frame.chroma_subsampling_y;
53 return y_size + cbcr_size * 2;
57 shared_ptr<Frame> frame;
61 struct PendingDecode {
62 JPEGFrameView *destination;
64 // For actual decodes (only if frame below is nullptr).
65 FrameOnDisk primary, secondary;
66 float fade_alpha; // Irrelevant if secondary.stream_idx == -1.
68 // Already-decoded frames are also sent through PendingDecode,
69 // so that they get drawn in the right order. If frame is nullptr,
70 // it's a real decode.
71 shared_ptr<Frame> frame;
76 thread JPEGFrameView::jpeg_decoder_thread;
78 map<FrameOnDisk, LRUFrame, FrameOnDiskLexicalOrder> cache; // Under cache_mu.
79 size_t cache_bytes_used = 0; // Under cache_mu.
80 condition_variable any_pending_decodes;
81 deque<PendingDecode> pending_decodes; // 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 shared_ptr<Frame> frame;
89 if (vaapi_jpeg_decoding_usable) {
90 frame = decode_jpeg_vaapi(jpeg);
91 if (frame != nullptr) {
94 fprintf(stderr, "VA-API hardware decoding failed; falling back to software.\n");
97 frame.reset(new Frame);
99 jpeg_decompress_struct dinfo;
100 JPEGWrapErrorManager error_mgr(&dinfo);
101 if (!error_mgr.run([&dinfo]{ jpeg_create_decompress(&dinfo); })) {
102 return get_black_frame();
104 JPEGDestroyer destroy_dinfo(&dinfo);
106 if (!error_mgr.run([&dinfo, &jpeg]{
107 jpeg_mem_src(&dinfo, reinterpret_cast<const unsigned char *>(jpeg.data()), jpeg.size());
108 jpeg_read_header(&dinfo, true);
110 return get_black_frame();
113 if (dinfo.num_components != 3) {
114 fprintf(stderr, "Not a color JPEG. (%d components, Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
115 dinfo.num_components,
116 dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
117 dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
118 dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
119 return get_black_frame();
121 if (dinfo.comp_info[0].h_samp_factor != dinfo.max_h_samp_factor ||
122 dinfo.comp_info[0].v_samp_factor != dinfo.max_v_samp_factor || // Y' must not be subsampled.
123 dinfo.comp_info[1].h_samp_factor != dinfo.comp_info[2].h_samp_factor ||
124 dinfo.comp_info[1].v_samp_factor != dinfo.comp_info[2].v_samp_factor || // Cb and Cr must be identically subsampled.
125 (dinfo.max_h_samp_factor % dinfo.comp_info[1].h_samp_factor) != 0 ||
126 (dinfo.max_v_samp_factor % dinfo.comp_info[1].v_samp_factor) != 0) { // No 2:3 subsampling or other weirdness.
127 fprintf(stderr, "Unsupported subsampling scheme. (Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
128 dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
129 dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
130 dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
133 dinfo.raw_data_out = true;
135 if (!error_mgr.run([&dinfo]{
136 jpeg_start_decompress(&dinfo);
138 return get_black_frame();
141 frame->width = dinfo.output_width;
142 frame->height = dinfo.output_height;
143 frame->chroma_subsampling_x = dinfo.max_h_samp_factor / dinfo.comp_info[1].h_samp_factor;
144 frame->chroma_subsampling_y = dinfo.max_v_samp_factor / dinfo.comp_info[1].v_samp_factor;
146 unsigned h_mcu_size = DCTSIZE * dinfo.max_h_samp_factor;
147 unsigned v_mcu_size = DCTSIZE * dinfo.max_v_samp_factor;
148 unsigned mcu_width_blocks = (dinfo.output_width + h_mcu_size - 1) / h_mcu_size;
149 unsigned mcu_height_blocks = (dinfo.output_height + v_mcu_size - 1) / v_mcu_size;
151 unsigned luma_width_blocks = mcu_width_blocks * dinfo.comp_info[0].h_samp_factor;
152 unsigned chroma_width_blocks = mcu_width_blocks * dinfo.comp_info[1].h_samp_factor;
153 unsigned luma_height_blocks = mcu_height_blocks * dinfo.comp_info[0].v_samp_factor;
154 unsigned chroma_height_blocks = mcu_height_blocks * dinfo.comp_info[1].v_samp_factor;
156 // TODO: Decode into a PBO.
157 frame->y.reset(new uint8_t[luma_width_blocks * luma_height_blocks * DCTSIZE2]);
158 frame->cb.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
159 frame->cr.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
160 frame->pitch_y = luma_width_blocks * DCTSIZE;
161 frame->pitch_chroma = chroma_width_blocks * DCTSIZE;
163 if (!error_mgr.run([&dinfo, &frame, v_mcu_size, mcu_height_blocks] {
164 JSAMPROW yptr[v_mcu_size], cbptr[v_mcu_size], crptr[v_mcu_size];
165 JSAMPARRAY data[3] = { yptr, cbptr, crptr };
166 for (unsigned y = 0; y < mcu_height_blocks; ++y) {
167 // NOTE: The last elements of cbptr/crptr will be unused for vertically subsampled chroma.
168 for (unsigned yy = 0; yy < v_mcu_size; ++yy) {
169 yptr[yy] = frame->y.get() + (y * DCTSIZE * dinfo.max_v_samp_factor + yy) * frame->pitch_y;
170 cbptr[yy] = frame->cb.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
171 crptr[yy] = frame->cr.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
174 jpeg_read_raw_data(&dinfo, data, v_mcu_size);
177 (void)jpeg_finish_decompress(&dinfo);
179 return get_black_frame();
187 // Assumes cache_mu is held.
188 int64_t bytes_still_to_remove = cache_bytes_used - (size_t(CACHE_SIZE_MB) * 1024 * 1024) * 9 / 10;
189 if (bytes_still_to_remove <= 0) return;
191 vector<pair<size_t, size_t>> lru_timestamps_and_size;
192 for (const auto &key_and_value : cache) {
193 lru_timestamps_and_size.emplace_back(
194 key_and_value.second.last_used,
195 frame_size(*key_and_value.second.frame));
197 sort(lru_timestamps_and_size.begin(), lru_timestamps_and_size.end());
199 // Remove the oldest ones until we are below 90% of the cache used.
200 size_t lru_cutoff_point = 0;
201 for (const pair<size_t, size_t> &it : lru_timestamps_and_size) {
202 lru_cutoff_point = it.first;
203 bytes_still_to_remove -= it.second;
204 if (bytes_still_to_remove <= 0) break;
207 for (auto it = cache.begin(); it != cache.end(); ) {
208 if (it->second.last_used <= lru_cutoff_point) {
209 cache_bytes_used -= frame_size(*it->second.frame);
210 it = cache.erase(it);
217 shared_ptr<Frame> decode_jpeg_with_cache(FrameOnDisk frame_spec, CacheMissBehavior cache_miss_behavior, FrameReader *frame_reader, bool *did_decode)
221 unique_lock<mutex> lock(cache_mu);
222 auto it = cache.find(frame_spec);
223 if (it != cache.end()) {
224 it->second.last_used = event_counter++;
225 return it->second.frame;
229 if (cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE) {
234 shared_ptr<Frame> frame = decode_jpeg(frame_reader->read_frame(frame_spec));
236 unique_lock<mutex> lock(cache_mu);
237 cache_bytes_used += frame_size(*frame);
238 cache[frame_spec] = LRUFrame{ frame, event_counter++ };
240 if (cache_bytes_used > size_t(CACHE_SIZE_MB) * 1024 * 1024) {
246 void JPEGFrameView::jpeg_decoder_thread_func()
248 size_t num_decoded = 0, num_dropped = 0;
250 pthread_setname_np(pthread_self(), "JPEGDecoder");
251 while (!should_quit.load()) {
252 PendingDecode decode;
253 CacheMissBehavior cache_miss_behavior = DECODE_IF_NOT_IN_CACHE;
255 unique_lock<mutex> lock(cache_mu); // TODO: Perhaps under another lock?
256 any_pending_decodes.wait(lock, [] {
257 return !pending_decodes.empty() || should_quit.load();
259 if (should_quit.load())
261 decode = pending_decodes.front();
262 pending_decodes.pop_front();
264 size_t num_pending = 0;
265 for (const PendingDecode &other_decode : pending_decodes) {
266 if (other_decode.destination == decode.destination) {
270 if (num_pending > 3) {
271 cache_miss_behavior = RETURN_NULLPTR_IF_NOT_IN_CACHE;
275 if (decode.frame != nullptr) {
276 // Already decoded, so just show it.
277 decode.destination->setDecodedFrame(decode.frame, nullptr, 1.0f);
281 shared_ptr<Frame> primary_frame, secondary_frame;
283 for (int subframe_idx = 0; subframe_idx < 2; ++subframe_idx) {
284 const FrameOnDisk &frame_spec = (subframe_idx == 0 ? decode.primary : decode.secondary);
285 if (frame_spec.pts == -1) {
286 // No secondary frame.
291 shared_ptr<Frame> frame = decode_jpeg_with_cache(frame_spec, cache_miss_behavior, &decode.destination->frame_reader, &found_in_cache);
293 if (frame == nullptr) {
294 assert(cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE);
299 if (!found_in_cache) {
301 if (num_decoded % 1000 == 0) {
302 fprintf(stderr, "Decoded %zu images, dropped %zu (%.2f%% dropped)\n",
303 num_decoded, num_dropped, (100.0 * num_dropped) / (num_decoded + num_dropped));
306 if (subframe_idx == 0) {
307 primary_frame = std::move(frame);
309 secondary_frame = std::move(frame);
317 // TODO: Could we get jitter between non-interpolated and interpolated frames here?
318 decode.destination->setDecodedFrame(primary_frame, secondary_frame, decode.fade_alpha);
322 void JPEGFrameView::shutdown()
324 any_pending_decodes.notify_all();
325 jpeg_decoder_thread.join();
328 JPEGFrameView::JPEGFrameView(QWidget *parent)
329 : QGLWidget(parent, global_share_widget)
333 void JPEGFrameView::setFrame(unsigned stream_idx, FrameOnDisk frame, FrameOnDisk secondary_frame, float fade_alpha)
335 current_stream_idx = stream_idx; // TODO: Does this interact with fades?
337 unique_lock<mutex> lock(cache_mu);
338 PendingDecode decode;
339 decode.primary = frame;
340 decode.secondary = secondary_frame;
341 decode.fade_alpha = fade_alpha;
342 decode.destination = this;
343 pending_decodes.push_back(decode);
344 any_pending_decodes.notify_all();
347 void JPEGFrameView::setFrame(shared_ptr<Frame> frame)
349 unique_lock<mutex> lock(cache_mu);
350 PendingDecode decode;
351 decode.frame = std::move(frame);
352 decode.destination = this;
353 pending_decodes.push_back(decode);
354 any_pending_decodes.notify_all();
357 ResourcePool *resource_pool = nullptr;
359 void JPEGFrameView::initializeGL()
362 glDisable(GL_DEPTH_TEST);
365 static once_flag once;
367 resource_pool = new ResourcePool;
368 jpeg_decoder_thread = std::thread(jpeg_decoder_thread_func);
371 ycbcr_converter.reset(new YCbCrConverter(YCbCrConverter::OUTPUT_TO_RGBA, resource_pool));
373 ImageFormat inout_format;
374 inout_format.color_space = COLORSPACE_sRGB;
375 inout_format.gamma_curve = GAMMA_sRGB;
377 overlay_chain.reset(new EffectChain(overlay_base_width, overlay_base_height, resource_pool));
378 overlay_input = (movit::FlatInput *)overlay_chain->add_input(new FlatInput(inout_format, FORMAT_GRAYSCALE, GL_UNSIGNED_BYTE, overlay_base_width, overlay_base_height));
380 overlay_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
381 overlay_chain->finalize();
384 void JPEGFrameView::resizeGL(int width, int height)
387 glViewport(0, 0, width, height);
390 // Save these, as width() and height() will lie with DPI scaling.
395 void JPEGFrameView::paintGL()
397 glViewport(0, 0, gl_width, gl_height);
398 if (current_frame == nullptr) {
399 glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
400 glClear(GL_COLOR_BUFFER_BIT);
405 current_chain->render_to_screen();
407 if (overlay_image != nullptr) {
408 if (overlay_input_needs_refresh) {
409 overlay_input->set_width(overlay_width);
410 overlay_input->set_height(overlay_height);
411 overlay_input->set_pixel_data(overlay_image->bits());
413 glViewport(gl_width - overlay_width, 0, overlay_width, overlay_height);
414 overlay_chain->render_to_screen();
422 void JPEGFrameView::setDecodedFrame(shared_ptr<Frame> frame, shared_ptr<Frame> secondary_frame, float fade_alpha)
424 post_to_main_thread([this, frame, secondary_frame, fade_alpha] {
425 current_frame = frame;
426 current_secondary_frame = secondary_frame;
428 if (secondary_frame != nullptr) {
429 current_chain = ycbcr_converter->prepare_chain_for_fade(frame, secondary_frame, fade_alpha);
431 current_chain = ycbcr_converter->prepare_chain_for_conversion(frame);
437 void JPEGFrameView::mousePressEvent(QMouseEvent *event)
439 if (event->type() == QEvent::MouseButtonPress && event->button() == Qt::LeftButton) {
444 void JPEGFrameView::set_overlay(const string &text)
447 overlay_image.reset();
451 float dpr = QGuiApplication::primaryScreen()->devicePixelRatio();
452 overlay_width = lrint(overlay_base_width * dpr);
453 overlay_height = lrint(overlay_base_height * dpr);
455 overlay_image.reset(new QImage(overlay_width, overlay_height, QImage::Format_Grayscale8));
456 overlay_image->setDevicePixelRatio(dpr);
457 overlay_image->fill(0);
458 QPainter painter(overlay_image.get());
460 painter.setPen(Qt::white);
461 QFont font = painter.font();
462 font.setPointSize(12);
463 painter.setFont(font);
465 painter.drawText(QRectF(0, 0, overlay_base_width, overlay_base_height), Qt::AlignCenter, QString::fromStdString(text));
467 // Don't refresh immediately; we might not have an OpenGL context here.
468 overlay_input_needs_refresh = true;
471 shared_ptr<Frame> get_black_frame()
473 static shared_ptr<Frame> black_frame;
474 static once_flag flag;
476 black_frame.reset(new Frame);
477 black_frame->y.reset(new uint8_t[1280 * 720]);
478 black_frame->cb.reset(new uint8_t[(1280 / 2) * (720 / 2)]);
479 black_frame->cr.reset(new uint8_t[(1280 / 2) * (720 / 2)]);
480 black_frame->width = 1280;
481 black_frame->height = 720;
482 black_frame->chroma_subsampling_x = 2;
483 black_frame->chroma_subsampling_y = 2;
484 black_frame->pitch_y = 1280;
485 black_frame->pitch_chroma = 1280 / 2;