1 #include "jpeg_frame_view.h"
8 #include <condition_variable>
14 #include <QMouseEvent>
17 #include <movit/resource_pool.h>
18 #include <movit/init.h>
19 #include <movit/util.h>
22 #include "post_to_main_thread.h"
23 #include "vaapi_jpeg_decoder.h"
24 #include "video_stream.h"
26 using namespace movit;
29 // Just an arbitrary order for std::map.
30 struct JPEGIDLexicalOrder
32 bool operator() (const JPEGID &a, const JPEGID &b) const
34 if (a.stream_idx != b.stream_idx)
35 return a.stream_idx < b.stream_idx;
38 return a.interpolated < b.interpolated;
43 shared_ptr<Frame> frame;
47 thread JPEGFrameView::jpeg_decoder_thread;
49 map<JPEGID, LRUFrame, JPEGIDLexicalOrder> cache; // Under cache_mu.
50 condition_variable any_pending_decodes, cache_updated;
51 deque<pair<JPEGID, JPEGFrameView *>> pending_decodes; // Under cache_mu.
52 atomic<size_t> event_counter{0};
53 extern QGLWidget *global_share_widget;
54 extern atomic<bool> should_quit;
56 shared_ptr<Frame> decode_jpeg(const string &filename)
58 shared_ptr<Frame> frame;
59 if (vaapi_jpeg_decoding_usable) {
60 frame = decode_jpeg_vaapi(filename);
61 if (frame != nullptr) {
64 fprintf(stderr, "VA-API hardware decoding failed; falling back to software.\n");
67 frame.reset(new Frame);
69 jpeg_decompress_struct dinfo;
71 dinfo.err = jpeg_std_error(&jerr);
72 jpeg_create_decompress(&dinfo);
74 FILE *fp = fopen(filename.c_str(), "rb");
76 perror(filename.c_str());
79 jpeg_stdio_src(&dinfo, fp);
81 jpeg_read_header(&dinfo, true);
83 if (dinfo.num_components != 3) {
84 fprintf(stderr, "Not a color JPEG. (%d components, Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
86 dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
87 dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
88 dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
91 if (dinfo.comp_info[0].h_samp_factor != dinfo.max_h_samp_factor ||
92 dinfo.comp_info[0].v_samp_factor != dinfo.max_v_samp_factor || // Y' must not be subsampled.
93 dinfo.comp_info[1].h_samp_factor != dinfo.comp_info[2].h_samp_factor ||
94 dinfo.comp_info[1].v_samp_factor != dinfo.comp_info[2].v_samp_factor || // Cb and Cr must be identically subsampled.
95 (dinfo.max_h_samp_factor % dinfo.comp_info[1].h_samp_factor) != 0 ||
96 (dinfo.max_v_samp_factor % dinfo.comp_info[1].v_samp_factor) != 0) { // No 2:3 subsampling or other weirdness.
97 fprintf(stderr, "Unsupported subsampling scheme. (Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
98 dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
99 dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
100 dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
103 dinfo.raw_data_out = true;
105 jpeg_start_decompress(&dinfo);
107 frame->width = dinfo.output_width;
108 frame->height = dinfo.output_height;
109 frame->chroma_subsampling_x = dinfo.max_h_samp_factor / dinfo.comp_info[1].h_samp_factor;
110 frame->chroma_subsampling_y = dinfo.max_v_samp_factor / dinfo.comp_info[1].v_samp_factor;
112 unsigned h_mcu_size = DCTSIZE * dinfo.max_h_samp_factor;
113 unsigned v_mcu_size = DCTSIZE * dinfo.max_v_samp_factor;
114 unsigned mcu_width_blocks = (dinfo.output_width + h_mcu_size - 1) / h_mcu_size;
115 unsigned mcu_height_blocks = (dinfo.output_height + v_mcu_size - 1) / v_mcu_size;
117 unsigned luma_width_blocks = mcu_width_blocks * dinfo.comp_info[0].h_samp_factor;
118 unsigned chroma_width_blocks = mcu_width_blocks * dinfo.comp_info[1].h_samp_factor;
119 unsigned luma_height_blocks = mcu_height_blocks * dinfo.comp_info[0].v_samp_factor;
120 unsigned chroma_height_blocks = mcu_height_blocks * dinfo.comp_info[1].v_samp_factor;
122 // TODO: Decode into a PBO.
123 frame->y.reset(new uint8_t[luma_width_blocks * luma_height_blocks * DCTSIZE2]);
124 frame->cb.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
125 frame->cr.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
126 frame->pitch_y = luma_width_blocks * DCTSIZE;
127 frame->pitch_chroma = chroma_width_blocks * DCTSIZE;
129 JSAMPROW yptr[v_mcu_size], cbptr[v_mcu_size], crptr[v_mcu_size];
130 JSAMPARRAY data[3] = { yptr, cbptr, crptr };
131 for (unsigned y = 0; y < mcu_height_blocks; ++y) {
132 // NOTE: The last elements of cbptr/crptr will be unused for vertically subsampled chroma.
133 for (unsigned yy = 0; yy < v_mcu_size; ++yy) {
134 yptr[yy] = frame->y.get() + (y * DCTSIZE * dinfo.max_v_samp_factor + yy) * frame->pitch_y;
135 cbptr[yy] = frame->cb.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
136 crptr[yy] = frame->cr.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
139 jpeg_read_raw_data(&dinfo, data, v_mcu_size);
142 (void) jpeg_finish_decompress(&dinfo);
143 jpeg_destroy_decompress(&dinfo);
151 // Assumes cache_mu is held.
152 vector<size_t> lru_timestamps;
153 for (const auto &key_and_value : cache) {
154 lru_timestamps.push_back(key_and_value.second.last_used);
157 size_t cutoff_point = CACHE_SIZE / 10; // Prune away the 10% oldest ones.
158 nth_element(lru_timestamps.begin(), lru_timestamps.begin() + cutoff_point, lru_timestamps.end());
159 size_t must_be_used_after = lru_timestamps[cutoff_point];
160 for (auto it = cache.begin(); it != cache.end(); ) {
161 if (it->second.last_used < must_be_used_after) {
162 it = cache.erase(it);
169 shared_ptr<Frame> decode_jpeg_with_cache(JPEGID id, CacheMissBehavior cache_miss_behavior, bool *did_decode)
173 unique_lock<mutex> lock(cache_mu);
174 auto it = cache.find(id);
175 if (it != cache.end()) {
176 it->second.last_used = event_counter++;
177 return it->second.frame;
181 if (cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE) {
185 assert(!id.interpolated);
187 shared_ptr<Frame> frame = decode_jpeg(filename_for_frame(id.stream_idx, id.pts));
189 unique_lock<mutex> lock(cache_mu);
190 cache[id] = LRUFrame{ frame, event_counter++ };
192 if (cache.size() > CACHE_SIZE) {
198 void jpeg_decoder_thread_func()
200 size_t num_decoded = 0, num_dropped = 0;
202 pthread_setname_np(pthread_self(), "JPEGDecoder");
203 while (!should_quit.load()) {
206 CacheMissBehavior cache_miss_behavior = DECODE_IF_NOT_IN_CACHE;
208 unique_lock<mutex> lock(cache_mu); // TODO: Perhaps under another lock?
209 any_pending_decodes.wait(lock, [] {
210 return !pending_decodes.empty() || should_quit.load();
212 if (should_quit.load()) break;
213 id = pending_decodes.front().first;
214 dest = pending_decodes.front().second;
215 pending_decodes.pop_front();
217 size_t num_pending = 0;
218 for (const pair<JPEGID, JPEGFrameView *> &decode : pending_decodes) {
219 if (decode.second == dest) {
223 if (num_pending > 3) {
224 cache_miss_behavior = RETURN_NULLPTR_IF_NOT_IN_CACHE;
229 shared_ptr<Frame> frame;
230 if (id.interpolated) {
231 // Interpolated frames are never decoded by us,
232 // put directly into the cache from VideoStream.
233 unique_lock<mutex> lock(cache_mu);
234 cache_updated.wait(lock, [id] {
235 return cache.count(id) != 0 || should_quit.load();
237 if (should_quit.load()) break;
238 found_in_cache = true; // Don't count it as a decode.
240 auto it = cache.find(id);
241 assert(it != cache.end());
243 it->second.last_used = event_counter++;
244 frame = it->second.frame;
245 if (frame == nullptr) {
246 // We inserted a nullptr as signal that the frame was never
247 // interpolated and that we should stop waiting.
248 // But don't let it linger in the cache anymore.
252 frame = decode_jpeg_with_cache(id, cache_miss_behavior, &found_in_cache);
255 if (frame == nullptr) {
256 assert(id.interpolated || cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE);
261 if (!found_in_cache) {
263 if (num_decoded % 1000 == 0) {
264 fprintf(stderr, "Decoded %zu images, dropped %zu (%.2f%% dropped)\n",
265 num_decoded, num_dropped, (100.0 * num_dropped) / (num_decoded + num_dropped));
269 // TODO: Could we get jitter between non-interpolated and interpolated frames here?
270 dest->setDecodedFrame(frame);
274 void JPEGFrameView::shutdown()
276 any_pending_decodes.notify_all();
277 jpeg_decoder_thread.join();
280 JPEGFrameView::JPEGFrameView(QWidget *parent)
281 : QGLWidget(parent, global_share_widget) {
284 void JPEGFrameView::setFrame(unsigned stream_idx, int64_t pts, bool interpolated)
286 current_stream_idx = stream_idx;
288 unique_lock<mutex> lock(cache_mu);
289 pending_decodes.emplace_back(JPEGID{ stream_idx, pts, interpolated }, this);
290 any_pending_decodes.notify_all();
293 void JPEGFrameView::insert_interpolated_frame(unsigned stream_idx, int64_t pts, shared_ptr<Frame> frame)
295 JPEGID id{ stream_idx, pts, true };
297 // We rely on the frame not being evicted from the cache before
298 // jpeg_decoder_thread() sees it and can display it (otherwise,
299 // that thread would hang). With a default cache of 1000 elements,
300 // that would sound like a reasonable assumption.
301 unique_lock<mutex> lock(cache_mu);
302 cache[id] = LRUFrame{ std::move(frame), event_counter++ };
303 cache_updated.notify_all();
306 ResourcePool *resource_pool = nullptr;
308 void JPEGFrameView::initializeGL()
311 glDisable(GL_DEPTH_TEST);
314 static once_flag once;
316 resource_pool = new ResourcePool;
317 jpeg_decoder_thread = std::thread(jpeg_decoder_thread_func);
320 ImageFormat inout_format;
321 inout_format.color_space = COLORSPACE_sRGB;
322 inout_format.gamma_curve = GAMMA_sRGB;
324 ycbcr_format.luma_coefficients = YCBCR_REC_709;
325 ycbcr_format.full_range = false;
326 ycbcr_format.num_levels = 256;
327 ycbcr_format.chroma_subsampling_x = 2;
328 ycbcr_format.chroma_subsampling_y = 1;
329 ycbcr_format.cb_x_position = 0.0f; // H.264 -- _not_ JPEG, even though our input is MJPEG-encoded
330 ycbcr_format.cb_y_position = 0.5f; // Irrelevant.
331 ycbcr_format.cr_x_position = 0.0f;
332 ycbcr_format.cr_y_position = 0.5f;
334 // Planar Y'CbCr decoding chain.
335 planar_chain.reset(new EffectChain(1280, 720, resource_pool));
336 ycbcr_planar_input = (movit::YCbCrInput *)planar_chain->add_input(new YCbCrInput(inout_format, ycbcr_format, 1280, 720, YCBCR_INPUT_PLANAR));
337 planar_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
338 planar_chain->set_dither_bits(8);
339 planar_chain->finalize();
341 // Semiplanar Y'CbCr decoding chain (for images coming from VA-API).
342 semiplanar_chain.reset(new EffectChain(1280, 720, resource_pool));
343 ycbcr_semiplanar_input = (movit::YCbCrInput *)semiplanar_chain->add_input(new YCbCrInput(inout_format, ycbcr_format, 1280, 720, YCBCR_INPUT_SPLIT_Y_AND_CBCR));
344 semiplanar_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
345 semiplanar_chain->set_dither_bits(8);
346 semiplanar_chain->finalize();
348 overlay_chain.reset(new EffectChain(overlay_base_width, overlay_base_height, resource_pool));
349 overlay_input = (movit::FlatInput *)overlay_chain->add_input(new FlatInput(inout_format, FORMAT_GRAYSCALE, GL_UNSIGNED_BYTE, overlay_base_width, overlay_base_height));
351 overlay_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
352 overlay_chain->finalize();
355 void JPEGFrameView::resizeGL(int width, int height)
358 glViewport(0, 0, width, height);
361 // Save these, as width() and height() will lie with DPI scaling.
366 void JPEGFrameView::paintGL()
368 glViewport(0, 0, gl_width, gl_height);
369 if (current_frame == nullptr) {
370 glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
371 glClear(GL_COLOR_BUFFER_BIT);
376 if (current_frame->is_semiplanar) {
377 semiplanar_chain->render_to_screen();
379 planar_chain->render_to_screen();
382 if (overlay_image != nullptr) {
383 if (overlay_input_needs_refresh) {
384 overlay_input->set_width(overlay_width);
385 overlay_input->set_height(overlay_height);
386 overlay_input->set_pixel_data(overlay_image->bits());
388 glViewport(gl_width - overlay_width, 0, overlay_width, overlay_height);
389 overlay_chain->render_to_screen();
393 void JPEGFrameView::setDecodedFrame(std::shared_ptr<Frame> frame)
395 post_to_main_thread([this, frame] {
396 current_frame = frame;
397 ycbcr_format.chroma_subsampling_x = frame->chroma_subsampling_x;
398 ycbcr_format.chroma_subsampling_y = frame->chroma_subsampling_y;
400 if (frame->is_semiplanar) {
401 ycbcr_semiplanar_input->change_ycbcr_format(ycbcr_format);
402 ycbcr_semiplanar_input->set_width(frame->width);
403 ycbcr_semiplanar_input->set_height(frame->height);
404 ycbcr_semiplanar_input->set_pixel_data(0, frame->y.get());
405 ycbcr_semiplanar_input->set_pixel_data(1, frame->cbcr.get());
406 ycbcr_semiplanar_input->set_pitch(0, frame->pitch_y);
407 ycbcr_semiplanar_input->set_pitch(1, frame->pitch_chroma);
409 ycbcr_planar_input->change_ycbcr_format(ycbcr_format);
410 ycbcr_planar_input->set_width(frame->width);
411 ycbcr_planar_input->set_height(frame->height);
412 ycbcr_planar_input->set_pixel_data(0, frame->y.get());
413 ycbcr_planar_input->set_pixel_data(1, frame->cb.get());
414 ycbcr_planar_input->set_pixel_data(2, frame->cr.get());
415 ycbcr_planar_input->set_pitch(0, frame->pitch_y);
416 ycbcr_planar_input->set_pitch(1, frame->pitch_chroma);
417 ycbcr_planar_input->set_pitch(2, frame->pitch_chroma);
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;