1 #include "jpeg_frame_view.h"
4 #include "jpeg_destroyer.h"
5 #include "shared/post_to_main_thread.h"
6 #include "video_stream.h"
7 #include "ycbcr_converter.h"
12 #include <condition_variable>
15 #include <movit/init.h>
16 #include <movit/resource_pool.h>
17 #include <movit/util.h>
24 // Must come after the Qt stuff.
25 #include "vaapi_jpeg_decoder.h"
27 using namespace movit;
32 // Just an arbitrary order for std::map.
33 struct FrameOnDiskLexicalOrder
35 bool operator() (const FrameOnDisk &a, const FrameOnDisk &b) const
39 if (a.offset != b.offset)
40 return a.offset < b.offset;
41 if (a.filename_idx != b.filename_idx)
42 return a.filename_idx < b.filename_idx;
43 assert(a.size == b.size);
48 inline size_t frame_size(const Frame &frame)
50 size_t y_size = frame.width * frame.height;
51 size_t cbcr_size = y_size / frame.chroma_subsampling_x / frame.chroma_subsampling_y;
52 return y_size + cbcr_size * 2;
56 shared_ptr<Frame> frame;
60 struct PendingDecode {
61 JPEGFrameView *destination;
63 // For actual decodes (only if frame below is nullptr).
64 FrameOnDisk primary, secondary;
65 float fade_alpha; // Irrelevant if secondary.stream_idx == -1.
67 // Already-decoded frames are also sent through PendingDecode,
68 // so that they get drawn in the right order. If frame is nullptr,
69 // it's a real decode.
70 shared_ptr<Frame> frame;
75 thread JPEGFrameView::jpeg_decoder_thread;
77 map<FrameOnDisk, LRUFrame, FrameOnDiskLexicalOrder> cache; // Under cache_mu.
78 size_t cache_bytes_used = 0; // Under cache_mu.
79 condition_variable any_pending_decodes;
80 deque<PendingDecode> pending_decodes; // Under cache_mu.
81 atomic<size_t> event_counter{0};
82 extern QGLWidget *global_share_widget;
83 extern atomic<bool> should_quit;
85 shared_ptr<Frame> decode_jpeg(const string &filename)
87 shared_ptr<Frame> frame;
88 if (vaapi_jpeg_decoding_usable) {
89 frame = decode_jpeg_vaapi(filename);
90 if (frame != nullptr) {
93 fprintf(stderr, "VA-API hardware decoding failed; falling back to software.\n");
96 frame.reset(new Frame);
98 jpeg_decompress_struct dinfo;
100 dinfo.err = jpeg_std_error(&jerr);
101 jpeg_create_decompress(&dinfo);
102 JPEGDestroyer destroy_dinfo(&dinfo);
104 FILE *fp = fopen(filename.c_str(), "rb");
106 perror(filename.c_str());
109 jpeg_stdio_src(&dinfo, fp);
111 jpeg_read_header(&dinfo, true);
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);
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 jpeg_start_decompress(&dinfo);
137 frame->width = dinfo.output_width;
138 frame->height = dinfo.output_height;
139 frame->chroma_subsampling_x = dinfo.max_h_samp_factor / dinfo.comp_info[1].h_samp_factor;
140 frame->chroma_subsampling_y = dinfo.max_v_samp_factor / dinfo.comp_info[1].v_samp_factor;
142 unsigned h_mcu_size = DCTSIZE * dinfo.max_h_samp_factor;
143 unsigned v_mcu_size = DCTSIZE * dinfo.max_v_samp_factor;
144 unsigned mcu_width_blocks = (dinfo.output_width + h_mcu_size - 1) / h_mcu_size;
145 unsigned mcu_height_blocks = (dinfo.output_height + v_mcu_size - 1) / v_mcu_size;
147 unsigned luma_width_blocks = mcu_width_blocks * dinfo.comp_info[0].h_samp_factor;
148 unsigned chroma_width_blocks = mcu_width_blocks * dinfo.comp_info[1].h_samp_factor;
149 unsigned luma_height_blocks = mcu_height_blocks * dinfo.comp_info[0].v_samp_factor;
150 unsigned chroma_height_blocks = mcu_height_blocks * dinfo.comp_info[1].v_samp_factor;
152 // TODO: Decode into a PBO.
153 frame->y.reset(new uint8_t[luma_width_blocks * luma_height_blocks * DCTSIZE2]);
154 frame->cb.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
155 frame->cr.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
156 frame->pitch_y = luma_width_blocks * DCTSIZE;
157 frame->pitch_chroma = chroma_width_blocks * DCTSIZE;
159 JSAMPROW yptr[v_mcu_size], cbptr[v_mcu_size], crptr[v_mcu_size];
160 JSAMPARRAY data[3] = { yptr, cbptr, crptr };
161 for (unsigned y = 0; y < mcu_height_blocks; ++y) {
162 // NOTE: The last elements of cbptr/crptr will be unused for vertically subsampled chroma.
163 for (unsigned yy = 0; yy < v_mcu_size; ++yy) {
164 yptr[yy] = frame->y.get() + (y * DCTSIZE * dinfo.max_v_samp_factor + yy) * frame->pitch_y;
165 cbptr[yy] = frame->cb.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
166 crptr[yy] = frame->cr.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
169 jpeg_read_raw_data(&dinfo, data, v_mcu_size);
172 (void)jpeg_finish_decompress(&dinfo);
180 // Assumes cache_mu is held.
181 int64_t bytes_still_to_remove = cache_bytes_used - (size_t(CACHE_SIZE_MB) * 1024 * 1024) * 9 / 10;
182 if (bytes_still_to_remove <= 0) return;
184 vector<pair<size_t, size_t>> lru_timestamps_and_size;
185 for (const auto &key_and_value : cache) {
186 lru_timestamps_and_size.emplace_back(
187 key_and_value.second.last_used,
188 frame_size(*key_and_value.second.frame));
190 sort(lru_timestamps_and_size.begin(), lru_timestamps_and_size.end());
192 // Remove the oldest ones until we are below 90% of the cache used.
193 size_t lru_cutoff_point = 0;
194 for (const pair<size_t, size_t> &it : lru_timestamps_and_size) {
195 lru_cutoff_point = it.first;
196 bytes_still_to_remove -= it.second;
197 if (bytes_still_to_remove <= 0) break;
200 for (auto it = cache.begin(); it != cache.end(); ) {
201 if (it->second.last_used <= lru_cutoff_point) {
202 cache_bytes_used -= frame_size(*it->second.frame);
203 it = cache.erase(it);
210 shared_ptr<Frame> decode_jpeg_with_cache(FrameOnDisk frame_spec, CacheMissBehavior cache_miss_behavior, FrameReader *frame_reader, bool *did_decode)
214 unique_lock<mutex> lock(cache_mu);
215 auto it = cache.find(frame_spec);
216 if (it != cache.end()) {
217 it->second.last_used = event_counter++;
218 return it->second.frame;
222 if (cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE) {
227 shared_ptr<Frame> frame = decode_jpeg(frame_reader->read_frame(frame_spec));
229 unique_lock<mutex> lock(cache_mu);
230 cache_bytes_used += frame_size(*frame);
231 cache[frame_spec] = LRUFrame{ frame, event_counter++ };
233 if (cache_bytes_used > size_t(CACHE_SIZE_MB) * 1024 * 1024) {
239 void JPEGFrameView::jpeg_decoder_thread_func()
241 size_t num_decoded = 0, num_dropped = 0;
243 pthread_setname_np(pthread_self(), "JPEGDecoder");
244 while (!should_quit.load()) {
245 PendingDecode decode;
246 CacheMissBehavior cache_miss_behavior = DECODE_IF_NOT_IN_CACHE;
248 unique_lock<mutex> lock(cache_mu); // TODO: Perhaps under another lock?
249 any_pending_decodes.wait(lock, [] {
250 return !pending_decodes.empty() || should_quit.load();
252 if (should_quit.load())
254 decode = pending_decodes.front();
255 pending_decodes.pop_front();
257 size_t num_pending = 0;
258 for (const PendingDecode &other_decode : pending_decodes) {
259 if (other_decode.destination == decode.destination) {
263 if (num_pending > 3) {
264 cache_miss_behavior = RETURN_NULLPTR_IF_NOT_IN_CACHE;
268 if (decode.frame != nullptr) {
269 // Already decoded, so just show it.
270 decode.destination->setDecodedFrame(decode.frame, nullptr, 1.0f);
274 shared_ptr<Frame> primary_frame, secondary_frame;
276 for (int subframe_idx = 0; subframe_idx < 2; ++subframe_idx) {
277 const FrameOnDisk &frame_spec = (subframe_idx == 0 ? decode.primary : decode.secondary);
278 if (frame_spec.pts == -1) {
279 // No secondary frame.
284 shared_ptr<Frame> frame = decode_jpeg_with_cache(frame_spec, cache_miss_behavior, &decode.destination->frame_reader, &found_in_cache);
286 if (frame == nullptr) {
287 assert(cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE);
292 if (!found_in_cache) {
294 if (num_decoded % 1000 == 0) {
295 fprintf(stderr, "Decoded %zu images, dropped %zu (%.2f%% dropped)\n",
296 num_decoded, num_dropped, (100.0 * num_dropped) / (num_decoded + num_dropped));
299 if (subframe_idx == 0) {
300 primary_frame = std::move(frame);
302 secondary_frame = std::move(frame);
310 // TODO: Could we get jitter between non-interpolated and interpolated frames here?
311 decode.destination->setDecodedFrame(primary_frame, secondary_frame, decode.fade_alpha);
315 void JPEGFrameView::shutdown()
317 any_pending_decodes.notify_all();
318 jpeg_decoder_thread.join();
321 JPEGFrameView::JPEGFrameView(QWidget *parent)
322 : QGLWidget(parent, global_share_widget)
326 void JPEGFrameView::setFrame(unsigned stream_idx, FrameOnDisk frame, FrameOnDisk secondary_frame, float fade_alpha)
328 current_stream_idx = stream_idx; // TODO: Does this interact with fades?
330 unique_lock<mutex> lock(cache_mu);
331 PendingDecode decode;
332 decode.primary = frame;
333 decode.secondary = secondary_frame;
334 decode.fade_alpha = fade_alpha;
335 decode.destination = this;
336 pending_decodes.push_back(decode);
337 any_pending_decodes.notify_all();
340 void JPEGFrameView::setFrame(shared_ptr<Frame> frame)
342 unique_lock<mutex> lock(cache_mu);
343 PendingDecode decode;
344 decode.frame = std::move(frame);
345 decode.destination = this;
346 pending_decodes.push_back(decode);
347 any_pending_decodes.notify_all();
350 ResourcePool *resource_pool = nullptr;
352 void JPEGFrameView::initializeGL()
355 glDisable(GL_DEPTH_TEST);
358 static once_flag once;
360 resource_pool = new ResourcePool;
361 jpeg_decoder_thread = std::thread(jpeg_decoder_thread_func);
364 ycbcr_converter.reset(new YCbCrConverter(YCbCrConverter::OUTPUT_TO_RGBA, resource_pool));
366 ImageFormat inout_format;
367 inout_format.color_space = COLORSPACE_sRGB;
368 inout_format.gamma_curve = GAMMA_sRGB;
370 overlay_chain.reset(new EffectChain(overlay_base_width, overlay_base_height, resource_pool));
371 overlay_input = (movit::FlatInput *)overlay_chain->add_input(new FlatInput(inout_format, FORMAT_GRAYSCALE, GL_UNSIGNED_BYTE, overlay_base_width, overlay_base_height));
373 overlay_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
374 overlay_chain->finalize();
377 void JPEGFrameView::resizeGL(int width, int height)
380 glViewport(0, 0, width, height);
383 // Save these, as width() and height() will lie with DPI scaling.
388 void JPEGFrameView::paintGL()
390 glViewport(0, 0, gl_width, gl_height);
391 if (current_frame == nullptr) {
392 glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
393 glClear(GL_COLOR_BUFFER_BIT);
398 current_chain->render_to_screen();
400 if (overlay_image != nullptr) {
401 if (overlay_input_needs_refresh) {
402 overlay_input->set_width(overlay_width);
403 overlay_input->set_height(overlay_height);
404 overlay_input->set_pixel_data(overlay_image->bits());
406 glViewport(gl_width - overlay_width, 0, overlay_width, overlay_height);
407 overlay_chain->render_to_screen();
415 void JPEGFrameView::setDecodedFrame(shared_ptr<Frame> frame, shared_ptr<Frame> secondary_frame, float fade_alpha)
417 post_to_main_thread([this, frame, secondary_frame, fade_alpha] {
418 current_frame = frame;
419 current_secondary_frame = secondary_frame;
421 if (secondary_frame != nullptr) {
422 current_chain = ycbcr_converter->prepare_chain_for_fade(frame, secondary_frame, fade_alpha);
424 current_chain = ycbcr_converter->prepare_chain_for_conversion(frame);
430 void JPEGFrameView::mousePressEvent(QMouseEvent *event)
432 if (event->type() == QEvent::MouseButtonPress && event->button() == Qt::LeftButton) {
437 void JPEGFrameView::set_overlay(const string &text)
440 overlay_image.reset();
444 float dpr = QGuiApplication::primaryScreen()->devicePixelRatio();
445 overlay_width = lrint(overlay_base_width * dpr);
446 overlay_height = lrint(overlay_base_height * dpr);
448 overlay_image.reset(new QImage(overlay_width, overlay_height, QImage::Format_Grayscale8));
449 overlay_image->setDevicePixelRatio(dpr);
450 overlay_image->fill(0);
451 QPainter painter(overlay_image.get());
453 painter.setPen(Qt::white);
454 QFont font = painter.font();
455 font.setPointSize(12);
456 painter.setFont(font);
458 painter.drawText(QRectF(0, 0, overlay_base_width, overlay_base_height), Qt::AlignCenter, QString::fromStdString(text));
460 // Don't refresh immediately; we might not have an OpenGL context here.
461 overlay_input_needs_refresh = true;