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 &jpeg)
87 shared_ptr<Frame> frame;
88 if (vaapi_jpeg_decoding_usable) {
89 frame = decode_jpeg_vaapi(jpeg);
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 jpeg_mem_src(&dinfo, reinterpret_cast<const unsigned char *>(jpeg.data()), jpeg.size());
105 jpeg_read_header(&dinfo, true);
107 if (dinfo.num_components != 3) {
108 fprintf(stderr, "Not a color JPEG. (%d components, Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
109 dinfo.num_components,
110 dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
111 dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
112 dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
115 if (dinfo.comp_info[0].h_samp_factor != dinfo.max_h_samp_factor ||
116 dinfo.comp_info[0].v_samp_factor != dinfo.max_v_samp_factor || // Y' must not be subsampled.
117 dinfo.comp_info[1].h_samp_factor != dinfo.comp_info[2].h_samp_factor ||
118 dinfo.comp_info[1].v_samp_factor != dinfo.comp_info[2].v_samp_factor || // Cb and Cr must be identically subsampled.
119 (dinfo.max_h_samp_factor % dinfo.comp_info[1].h_samp_factor) != 0 ||
120 (dinfo.max_v_samp_factor % dinfo.comp_info[1].v_samp_factor) != 0) { // No 2:3 subsampling or other weirdness.
121 fprintf(stderr, "Unsupported subsampling scheme. (Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
122 dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
123 dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
124 dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
127 dinfo.raw_data_out = true;
129 jpeg_start_decompress(&dinfo);
131 frame->width = dinfo.output_width;
132 frame->height = dinfo.output_height;
133 frame->chroma_subsampling_x = dinfo.max_h_samp_factor / dinfo.comp_info[1].h_samp_factor;
134 frame->chroma_subsampling_y = dinfo.max_v_samp_factor / dinfo.comp_info[1].v_samp_factor;
136 unsigned h_mcu_size = DCTSIZE * dinfo.max_h_samp_factor;
137 unsigned v_mcu_size = DCTSIZE * dinfo.max_v_samp_factor;
138 unsigned mcu_width_blocks = (dinfo.output_width + h_mcu_size - 1) / h_mcu_size;
139 unsigned mcu_height_blocks = (dinfo.output_height + v_mcu_size - 1) / v_mcu_size;
141 unsigned luma_width_blocks = mcu_width_blocks * dinfo.comp_info[0].h_samp_factor;
142 unsigned chroma_width_blocks = mcu_width_blocks * dinfo.comp_info[1].h_samp_factor;
143 unsigned luma_height_blocks = mcu_height_blocks * dinfo.comp_info[0].v_samp_factor;
144 unsigned chroma_height_blocks = mcu_height_blocks * dinfo.comp_info[1].v_samp_factor;
146 // TODO: Decode into a PBO.
147 frame->y.reset(new uint8_t[luma_width_blocks * luma_height_blocks * DCTSIZE2]);
148 frame->cb.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
149 frame->cr.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
150 frame->pitch_y = luma_width_blocks * DCTSIZE;
151 frame->pitch_chroma = chroma_width_blocks * DCTSIZE;
153 JSAMPROW yptr[v_mcu_size], cbptr[v_mcu_size], crptr[v_mcu_size];
154 JSAMPARRAY data[3] = { yptr, cbptr, crptr };
155 for (unsigned y = 0; y < mcu_height_blocks; ++y) {
156 // NOTE: The last elements of cbptr/crptr will be unused for vertically subsampled chroma.
157 for (unsigned yy = 0; yy < v_mcu_size; ++yy) {
158 yptr[yy] = frame->y.get() + (y * DCTSIZE * dinfo.max_v_samp_factor + yy) * frame->pitch_y;
159 cbptr[yy] = frame->cb.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
160 crptr[yy] = frame->cr.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
163 jpeg_read_raw_data(&dinfo, data, v_mcu_size);
166 (void)jpeg_finish_decompress(&dinfo);
173 // Assumes cache_mu is held.
174 int64_t bytes_still_to_remove = cache_bytes_used - (size_t(CACHE_SIZE_MB) * 1024 * 1024) * 9 / 10;
175 if (bytes_still_to_remove <= 0) return;
177 vector<pair<size_t, size_t>> lru_timestamps_and_size;
178 for (const auto &key_and_value : cache) {
179 lru_timestamps_and_size.emplace_back(
180 key_and_value.second.last_used,
181 frame_size(*key_and_value.second.frame));
183 sort(lru_timestamps_and_size.begin(), lru_timestamps_and_size.end());
185 // Remove the oldest ones until we are below 90% of the cache used.
186 size_t lru_cutoff_point = 0;
187 for (const pair<size_t, size_t> &it : lru_timestamps_and_size) {
188 lru_cutoff_point = it.first;
189 bytes_still_to_remove -= it.second;
190 if (bytes_still_to_remove <= 0) break;
193 for (auto it = cache.begin(); it != cache.end(); ) {
194 if (it->second.last_used <= lru_cutoff_point) {
195 cache_bytes_used -= frame_size(*it->second.frame);
196 it = cache.erase(it);
203 shared_ptr<Frame> decode_jpeg_with_cache(FrameOnDisk frame_spec, CacheMissBehavior cache_miss_behavior, FrameReader *frame_reader, bool *did_decode)
207 unique_lock<mutex> lock(cache_mu);
208 auto it = cache.find(frame_spec);
209 if (it != cache.end()) {
210 it->second.last_used = event_counter++;
211 return it->second.frame;
215 if (cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE) {
220 shared_ptr<Frame> frame = decode_jpeg(frame_reader->read_frame(frame_spec));
222 unique_lock<mutex> lock(cache_mu);
223 cache_bytes_used += frame_size(*frame);
224 cache[frame_spec] = LRUFrame{ frame, event_counter++ };
226 if (cache_bytes_used > size_t(CACHE_SIZE_MB) * 1024 * 1024) {
232 void JPEGFrameView::jpeg_decoder_thread_func()
234 size_t num_decoded = 0, num_dropped = 0;
236 pthread_setname_np(pthread_self(), "JPEGDecoder");
237 while (!should_quit.load()) {
238 PendingDecode decode;
239 CacheMissBehavior cache_miss_behavior = DECODE_IF_NOT_IN_CACHE;
241 unique_lock<mutex> lock(cache_mu); // TODO: Perhaps under another lock?
242 any_pending_decodes.wait(lock, [] {
243 return !pending_decodes.empty() || should_quit.load();
245 if (should_quit.load())
247 decode = pending_decodes.front();
248 pending_decodes.pop_front();
250 size_t num_pending = 0;
251 for (const PendingDecode &other_decode : pending_decodes) {
252 if (other_decode.destination == decode.destination) {
256 if (num_pending > 3) {
257 cache_miss_behavior = RETURN_NULLPTR_IF_NOT_IN_CACHE;
261 if (decode.frame != nullptr) {
262 // Already decoded, so just show it.
263 decode.destination->setDecodedFrame(decode.frame, nullptr, 1.0f);
267 shared_ptr<Frame> primary_frame, secondary_frame;
269 for (int subframe_idx = 0; subframe_idx < 2; ++subframe_idx) {
270 const FrameOnDisk &frame_spec = (subframe_idx == 0 ? decode.primary : decode.secondary);
271 if (frame_spec.pts == -1) {
272 // No secondary frame.
277 shared_ptr<Frame> frame = decode_jpeg_with_cache(frame_spec, cache_miss_behavior, &decode.destination->frame_reader, &found_in_cache);
279 if (frame == nullptr) {
280 assert(cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE);
285 if (!found_in_cache) {
287 if (num_decoded % 1000 == 0) {
288 fprintf(stderr, "Decoded %zu images, dropped %zu (%.2f%% dropped)\n",
289 num_decoded, num_dropped, (100.0 * num_dropped) / (num_decoded + num_dropped));
292 if (subframe_idx == 0) {
293 primary_frame = std::move(frame);
295 secondary_frame = std::move(frame);
303 // TODO: Could we get jitter between non-interpolated and interpolated frames here?
304 decode.destination->setDecodedFrame(primary_frame, secondary_frame, decode.fade_alpha);
308 void JPEGFrameView::shutdown()
310 any_pending_decodes.notify_all();
311 jpeg_decoder_thread.join();
314 JPEGFrameView::JPEGFrameView(QWidget *parent)
315 : QGLWidget(parent, global_share_widget)
319 void JPEGFrameView::setFrame(unsigned stream_idx, FrameOnDisk frame, FrameOnDisk secondary_frame, float fade_alpha)
321 current_stream_idx = stream_idx; // TODO: Does this interact with fades?
323 unique_lock<mutex> lock(cache_mu);
324 PendingDecode decode;
325 decode.primary = frame;
326 decode.secondary = secondary_frame;
327 decode.fade_alpha = fade_alpha;
328 decode.destination = this;
329 pending_decodes.push_back(decode);
330 any_pending_decodes.notify_all();
333 void JPEGFrameView::setFrame(shared_ptr<Frame> frame)
335 unique_lock<mutex> lock(cache_mu);
336 PendingDecode decode;
337 decode.frame = std::move(frame);
338 decode.destination = this;
339 pending_decodes.push_back(decode);
340 any_pending_decodes.notify_all();
343 ResourcePool *resource_pool = nullptr;
345 void JPEGFrameView::initializeGL()
348 glDisable(GL_DEPTH_TEST);
351 static once_flag once;
353 resource_pool = new ResourcePool;
354 jpeg_decoder_thread = std::thread(jpeg_decoder_thread_func);
357 ycbcr_converter.reset(new YCbCrConverter(YCbCrConverter::OUTPUT_TO_RGBA, resource_pool));
359 ImageFormat inout_format;
360 inout_format.color_space = COLORSPACE_sRGB;
361 inout_format.gamma_curve = GAMMA_sRGB;
363 overlay_chain.reset(new EffectChain(overlay_base_width, overlay_base_height, resource_pool));
364 overlay_input = (movit::FlatInput *)overlay_chain->add_input(new FlatInput(inout_format, FORMAT_GRAYSCALE, GL_UNSIGNED_BYTE, overlay_base_width, overlay_base_height));
366 overlay_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
367 overlay_chain->finalize();
370 void JPEGFrameView::resizeGL(int width, int height)
373 glViewport(0, 0, width, height);
376 // Save these, as width() and height() will lie with DPI scaling.
381 void JPEGFrameView::paintGL()
383 glViewport(0, 0, gl_width, gl_height);
384 if (current_frame == nullptr) {
385 glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
386 glClear(GL_COLOR_BUFFER_BIT);
391 current_chain->render_to_screen();
393 if (overlay_image != nullptr) {
394 if (overlay_input_needs_refresh) {
395 overlay_input->set_width(overlay_width);
396 overlay_input->set_height(overlay_height);
397 overlay_input->set_pixel_data(overlay_image->bits());
399 glViewport(gl_width - overlay_width, 0, overlay_width, overlay_height);
400 overlay_chain->render_to_screen();
408 void JPEGFrameView::setDecodedFrame(shared_ptr<Frame> frame, shared_ptr<Frame> secondary_frame, float fade_alpha)
410 post_to_main_thread([this, frame, secondary_frame, fade_alpha] {
411 current_frame = frame;
412 current_secondary_frame = secondary_frame;
414 if (secondary_frame != nullptr) {
415 current_chain = ycbcr_converter->prepare_chain_for_fade(frame, secondary_frame, fade_alpha);
417 current_chain = ycbcr_converter->prepare_chain_for_conversion(frame);
423 void JPEGFrameView::mousePressEvent(QMouseEvent *event)
425 if (event->type() == QEvent::MouseButtonPress && event->button() == Qt::LeftButton) {
430 void JPEGFrameView::set_overlay(const string &text)
433 overlay_image.reset();
437 float dpr = QGuiApplication::primaryScreen()->devicePixelRatio();
438 overlay_width = lrint(overlay_base_width * dpr);
439 overlay_height = lrint(overlay_base_height * dpr);
441 overlay_image.reset(new QImage(overlay_width, overlay_height, QImage::Format_Grayscale8));
442 overlay_image->setDevicePixelRatio(dpr);
443 overlay_image->fill(0);
444 QPainter painter(overlay_image.get());
446 painter.setPen(Qt::white);
447 QFont font = painter.font();
448 font.setPointSize(12);
449 painter.setFont(font);
451 painter.drawText(QRectF(0, 0, overlay_base_width, overlay_base_height), Qt::AlignCenter, QString::fromStdString(text));
453 // Don't refresh immediately; we might not have an OpenGL context here.
454 overlay_input_needs_refresh = true;