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;
48 map<JPEGID, LRUFrame, JPEGIDLexicalOrder> cache; // Under cache_mu.
49 condition_variable any_pending_decodes, cache_updated;
50 deque<pair<JPEGID, JPEGFrameView *>> pending_decodes; // Under cache_mu.
51 atomic<size_t> event_counter{0};
52 extern QGLWidget *global_share_widget;
54 shared_ptr<Frame> decode_jpeg(const string &filename)
56 shared_ptr<Frame> frame;
57 if (vaapi_jpeg_decoding_usable) {
58 frame = decode_jpeg_vaapi(filename);
59 if (frame != nullptr) {
62 fprintf(stderr, "VA-API hardware decoding failed; falling back to software.\n");
65 frame.reset(new Frame);
67 jpeg_decompress_struct dinfo;
69 dinfo.err = jpeg_std_error(&jerr);
70 jpeg_create_decompress(&dinfo);
72 FILE *fp = fopen(filename.c_str(), "rb");
74 perror(filename.c_str());
77 jpeg_stdio_src(&dinfo, fp);
79 jpeg_read_header(&dinfo, true);
81 if (dinfo.num_components != 3) {
82 fprintf(stderr, "Not a color JPEG. (%d components, Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
84 dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
85 dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
86 dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
89 if (dinfo.comp_info[0].h_samp_factor != dinfo.max_h_samp_factor ||
90 dinfo.comp_info[0].v_samp_factor != dinfo.max_v_samp_factor || // Y' must not be subsampled.
91 dinfo.comp_info[1].h_samp_factor != dinfo.comp_info[2].h_samp_factor ||
92 dinfo.comp_info[1].v_samp_factor != dinfo.comp_info[2].v_samp_factor || // Cb and Cr must be identically subsampled.
93 (dinfo.max_h_samp_factor % dinfo.comp_info[1].h_samp_factor) != 0 ||
94 (dinfo.max_v_samp_factor % dinfo.comp_info[1].v_samp_factor) != 0) { // No 2:3 subsampling or other weirdness.
95 fprintf(stderr, "Unsupported subsampling scheme. (Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
96 dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
97 dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
98 dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
101 dinfo.raw_data_out = true;
103 jpeg_start_decompress(&dinfo);
105 frame->width = dinfo.output_width;
106 frame->height = dinfo.output_height;
107 frame->chroma_subsampling_x = dinfo.max_h_samp_factor / dinfo.comp_info[1].h_samp_factor;
108 frame->chroma_subsampling_y = dinfo.max_v_samp_factor / dinfo.comp_info[1].v_samp_factor;
110 unsigned h_mcu_size = DCTSIZE * dinfo.max_h_samp_factor;
111 unsigned v_mcu_size = DCTSIZE * dinfo.max_v_samp_factor;
112 unsigned mcu_width_blocks = (dinfo.output_width + h_mcu_size - 1) / h_mcu_size;
113 unsigned mcu_height_blocks = (dinfo.output_height + v_mcu_size - 1) / v_mcu_size;
115 unsigned luma_width_blocks = mcu_width_blocks * dinfo.comp_info[0].h_samp_factor;
116 unsigned chroma_width_blocks = mcu_width_blocks * dinfo.comp_info[1].h_samp_factor;
117 unsigned luma_height_blocks = mcu_height_blocks * dinfo.comp_info[0].v_samp_factor;
118 unsigned chroma_height_blocks = mcu_height_blocks * dinfo.comp_info[1].v_samp_factor;
120 // TODO: Decode into a PBO.
121 frame->y.reset(new uint8_t[luma_width_blocks * luma_height_blocks * DCTSIZE2]);
122 frame->cb.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
123 frame->cr.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
124 frame->pitch_y = luma_width_blocks * DCTSIZE;
125 frame->pitch_chroma = chroma_width_blocks * DCTSIZE;
127 JSAMPROW yptr[v_mcu_size], cbptr[v_mcu_size], crptr[v_mcu_size];
128 JSAMPARRAY data[3] = { yptr, cbptr, crptr };
129 for (unsigned y = 0; y < mcu_height_blocks; ++y) {
130 // NOTE: The last elements of cbptr/crptr will be unused for vertically subsampled chroma.
131 for (unsigned yy = 0; yy < v_mcu_size; ++yy) {
132 yptr[yy] = frame->y.get() + (y * DCTSIZE * dinfo.max_v_samp_factor + yy) * frame->pitch_y;
133 cbptr[yy] = frame->cb.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
134 crptr[yy] = frame->cr.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
137 jpeg_read_raw_data(&dinfo, data, v_mcu_size);
140 (void) jpeg_finish_decompress(&dinfo);
141 jpeg_destroy_decompress(&dinfo);
149 // Assumes cache_mu is held.
150 vector<size_t> lru_timestamps;
151 for (const auto &key_and_value : cache) {
152 lru_timestamps.push_back(key_and_value.second.last_used);
155 size_t cutoff_point = CACHE_SIZE / 10; // Prune away the 10% oldest ones.
156 nth_element(lru_timestamps.begin(), lru_timestamps.begin() + cutoff_point, lru_timestamps.end());
157 size_t must_be_used_after = lru_timestamps[cutoff_point];
158 for (auto it = cache.begin(); it != cache.end(); ) {
159 if (it->second.last_used < must_be_used_after) {
160 it = cache.erase(it);
167 shared_ptr<Frame> decode_jpeg_with_cache(JPEGID id, CacheMissBehavior cache_miss_behavior, bool *did_decode)
171 unique_lock<mutex> lock(cache_mu);
172 auto it = cache.find(id);
173 if (it != cache.end()) {
174 it->second.last_used = event_counter++;
175 return it->second.frame;
179 if (cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE) {
183 assert(!id.interpolated);
185 shared_ptr<Frame> frame = decode_jpeg(filename_for_frame(id.stream_idx, id.pts));
187 unique_lock<mutex> lock(cache_mu);
188 cache[id] = LRUFrame{ frame, event_counter++ };
190 if (cache.size() > CACHE_SIZE) {
196 void jpeg_decoder_thread()
198 size_t num_decoded = 0, num_dropped = 0;
200 pthread_setname_np(pthread_self(), "JPEGDecoder");
204 CacheMissBehavior cache_miss_behavior = DECODE_IF_NOT_IN_CACHE;
206 unique_lock<mutex> lock(cache_mu); // TODO: Perhaps under another lock?
207 any_pending_decodes.wait(lock, [] {
208 return !pending_decodes.empty();
210 id = pending_decodes.front().first;
211 dest = pending_decodes.front().second;
212 pending_decodes.pop_front();
214 size_t num_pending = 0;
215 for (const pair<JPEGID, JPEGFrameView *> &decode : pending_decodes) {
216 if (decode.second == dest) {
220 if (num_pending > 3) {
221 cache_miss_behavior = RETURN_NULLPTR_IF_NOT_IN_CACHE;
226 shared_ptr<Frame> frame;
227 if (id.interpolated) {
228 // Interpolated frames are never decoded by us,
229 // put directly into the cache from VideoStream.
230 unique_lock<mutex> lock(cache_mu);
231 cache_updated.wait(lock, [id] {
232 return cache.count(id) != 0;
234 found_in_cache = true; // Don't count it as a decode.
236 auto it = cache.find(id);
237 assert(it != cache.end());
239 it->second.last_used = event_counter++;
240 frame = it->second.frame;
241 if (frame == nullptr) {
242 // We inserted a nullptr as signal that the frame was never
243 // interpolated and that we should stop waiting.
244 // But don't let it linger in the cache anymore.
248 frame = decode_jpeg_with_cache(id, cache_miss_behavior, &found_in_cache);
251 if (frame == nullptr) {
252 assert(id.interpolated || cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE);
257 if (!found_in_cache) {
259 if (num_decoded % 1000 == 0) {
260 fprintf(stderr, "Decoded %zu images, dropped %zu (%.2f%% dropped)\n",
261 num_decoded, num_dropped, (100.0 * num_dropped) / (num_decoded + num_dropped));
265 // TODO: Could we get jitter between non-interpolated and interpolated frames here?
266 dest->setDecodedFrame(frame);
270 JPEGFrameView::JPEGFrameView(QWidget *parent)
271 : QGLWidget(parent, global_share_widget) {
274 void JPEGFrameView::setFrame(unsigned stream_idx, int64_t pts, bool interpolated)
276 current_stream_idx = stream_idx;
278 unique_lock<mutex> lock(cache_mu);
279 pending_decodes.emplace_back(JPEGID{ stream_idx, pts, interpolated }, this);
280 any_pending_decodes.notify_all();
283 void JPEGFrameView::insert_interpolated_frame(unsigned stream_idx, int64_t pts, shared_ptr<Frame> frame)
285 JPEGID id{ stream_idx, pts, true };
287 // We rely on the frame not being evicted from the cache before
288 // jpeg_decoder_thread() sees it and can display it (otherwise,
289 // that thread would hang). With a default cache of 1000 elements,
290 // that would sound like a reasonable assumption.
291 unique_lock<mutex> lock(cache_mu);
292 cache[id] = LRUFrame{ std::move(frame), event_counter++ };
293 cache_updated.notify_all();
296 ResourcePool *resource_pool = nullptr;
298 void JPEGFrameView::initializeGL()
301 glDisable(GL_DEPTH_TEST);
304 static once_flag once;
306 resource_pool = new ResourcePool;
307 std::thread(&jpeg_decoder_thread).detach();
310 ImageFormat inout_format;
311 inout_format.color_space = COLORSPACE_sRGB;
312 inout_format.gamma_curve = GAMMA_sRGB;
314 ycbcr_format.luma_coefficients = YCBCR_REC_709;
315 ycbcr_format.full_range = false;
316 ycbcr_format.num_levels = 256;
317 ycbcr_format.chroma_subsampling_x = 2;
318 ycbcr_format.chroma_subsampling_y = 1;
319 ycbcr_format.cb_x_position = 0.0f; // H.264 -- _not_ JPEG, even though our input is MJPEG-encoded
320 ycbcr_format.cb_y_position = 0.5f; // Irrelevant.
321 ycbcr_format.cr_x_position = 0.0f;
322 ycbcr_format.cr_y_position = 0.5f;
324 // Planar Y'CbCr decoding chain.
325 planar_chain.reset(new EffectChain(1280, 720, resource_pool));
326 ycbcr_planar_input = (movit::YCbCrInput *)planar_chain->add_input(new YCbCrInput(inout_format, ycbcr_format, 1280, 720, YCBCR_INPUT_PLANAR));
327 planar_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
328 planar_chain->set_dither_bits(8);
329 planar_chain->finalize();
331 // Semiplanar Y'CbCr decoding chain (for images coming from VA-API).
332 semiplanar_chain.reset(new EffectChain(1280, 720, resource_pool));
333 ycbcr_semiplanar_input = (movit::YCbCrInput *)semiplanar_chain->add_input(new YCbCrInput(inout_format, ycbcr_format, 1280, 720, YCBCR_INPUT_SPLIT_Y_AND_CBCR));
334 semiplanar_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
335 semiplanar_chain->set_dither_bits(8);
336 semiplanar_chain->finalize();
338 overlay_chain.reset(new EffectChain(overlay_base_width, overlay_base_height, resource_pool));
339 overlay_input = (movit::FlatInput *)overlay_chain->add_input(new FlatInput(inout_format, FORMAT_GRAYSCALE, GL_UNSIGNED_BYTE, overlay_base_width, overlay_base_height));
341 overlay_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
342 overlay_chain->finalize();
345 void JPEGFrameView::resizeGL(int width, int height)
348 glViewport(0, 0, width, height);
351 // Save these, as width() and height() will lie with DPI scaling.
356 void JPEGFrameView::paintGL()
358 glViewport(0, 0, gl_width, gl_height);
359 if (current_frame == nullptr) {
360 glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
361 glClear(GL_COLOR_BUFFER_BIT);
366 if (current_frame->is_semiplanar) {
367 semiplanar_chain->render_to_screen();
369 planar_chain->render_to_screen();
372 if (overlay_image != nullptr) {
373 if (overlay_input_needs_refresh) {
374 overlay_input->set_width(overlay_width);
375 overlay_input->set_height(overlay_height);
376 overlay_input->set_pixel_data(overlay_image->bits());
378 glViewport(gl_width - overlay_width, 0, overlay_width, overlay_height);
379 overlay_chain->render_to_screen();
383 void JPEGFrameView::setDecodedFrame(std::shared_ptr<Frame> frame)
385 post_to_main_thread([this, frame] {
386 current_frame = frame;
387 ycbcr_format.chroma_subsampling_x = frame->chroma_subsampling_x;
388 ycbcr_format.chroma_subsampling_y = frame->chroma_subsampling_y;
390 if (frame->is_semiplanar) {
391 ycbcr_semiplanar_input->change_ycbcr_format(ycbcr_format);
392 ycbcr_semiplanar_input->set_width(frame->width);
393 ycbcr_semiplanar_input->set_height(frame->height);
394 ycbcr_semiplanar_input->set_pixel_data(0, frame->y.get());
395 ycbcr_semiplanar_input->set_pixel_data(1, frame->cbcr.get());
396 ycbcr_semiplanar_input->set_pitch(0, frame->pitch_y);
397 ycbcr_semiplanar_input->set_pitch(1, frame->pitch_chroma);
399 ycbcr_planar_input->change_ycbcr_format(ycbcr_format);
400 ycbcr_planar_input->set_width(frame->width);
401 ycbcr_planar_input->set_height(frame->height);
402 ycbcr_planar_input->set_pixel_data(0, frame->y.get());
403 ycbcr_planar_input->set_pixel_data(1, frame->cb.get());
404 ycbcr_planar_input->set_pixel_data(2, frame->cr.get());
405 ycbcr_planar_input->set_pitch(0, frame->pitch_y);
406 ycbcr_planar_input->set_pitch(1, frame->pitch_chroma);
407 ycbcr_planar_input->set_pitch(2, frame->pitch_chroma);
413 void JPEGFrameView::mousePressEvent(QMouseEvent *event)
415 if (event->type() == QEvent::MouseButtonPress && event->button() == Qt::LeftButton) {
420 void JPEGFrameView::set_overlay(const string &text)
423 overlay_image.reset();
427 float dpr = QGuiApplication::primaryScreen()->devicePixelRatio();
428 overlay_width = lrint(overlay_base_width * dpr);
429 overlay_height = lrint(overlay_base_height * dpr);
431 overlay_image.reset(new QImage(overlay_width, overlay_height, QImage::Format_Grayscale8));
432 overlay_image->setDevicePixelRatio(dpr);
433 overlay_image->fill(0);
434 QPainter painter(overlay_image.get());
436 painter.setPen(Qt::white);
437 QFont font = painter.font();
438 font.setPointSize(12);
439 painter.setFont(font);
441 painter.drawText(QRectF(0, 0, overlay_base_width, overlay_base_height), Qt::AlignCenter, QString::fromStdString(text));
443 // Don't refresh immediately; we might not have an OpenGL context here.
444 overlay_input_needs_refresh = true;