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 "video_stream.h"
25 using namespace movit;
28 // Just an arbitrary order for std::map.
29 struct JPEGIDLexicalOrder
31 bool operator() (const JPEGID &a, const JPEGID &b) const
33 if (a.stream_idx != b.stream_idx)
34 return a.stream_idx < b.stream_idx;
37 return a.interpolated < b.interpolated;
42 shared_ptr<Frame> frame;
47 map<JPEGID, LRUFrame, JPEGIDLexicalOrder> cache; // Under cache_mu.
48 condition_variable any_pending_decodes, cache_updated;
49 deque<pair<JPEGID, JPEGFrameView *>> pending_decodes; // Under cache_mu.
50 atomic<size_t> event_counter{0};
51 extern QGLWidget *global_share_widget;
53 // TODO: Decode using VA-API if available.
54 shared_ptr<Frame> decode_jpeg(const string &filename)
56 shared_ptr<Frame> frame(new Frame);
58 jpeg_decompress_struct dinfo;
60 dinfo.err = jpeg_std_error(&jerr);
61 jpeg_create_decompress(&dinfo);
63 FILE *fp = fopen(filename.c_str(), "rb");
65 perror(filename.c_str());
68 jpeg_stdio_src(&dinfo, fp);
70 jpeg_read_header(&dinfo, true);
72 if (dinfo.num_components != 3) {
73 fprintf(stderr, "Not a color JPEG. (%d components, Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
75 dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
76 dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
77 dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
80 if (dinfo.comp_info[0].h_samp_factor != dinfo.max_h_samp_factor ||
81 dinfo.comp_info[0].v_samp_factor != dinfo.max_v_samp_factor || // Y' must not be subsampled.
82 dinfo.comp_info[1].h_samp_factor != dinfo.comp_info[2].h_samp_factor ||
83 dinfo.comp_info[1].v_samp_factor != dinfo.comp_info[2].v_samp_factor || // Cb and Cr must be identically subsampled.
84 (dinfo.max_h_samp_factor % dinfo.comp_info[1].h_samp_factor) != 0 ||
85 (dinfo.max_v_samp_factor % dinfo.comp_info[1].v_samp_factor) != 0) { // No 2:3 subsampling or other weirdness.
86 fprintf(stderr, "Unsupported subsampling scheme. (Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
87 dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
88 dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
89 dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
92 dinfo.raw_data_out = true;
94 jpeg_start_decompress(&dinfo);
96 frame->width = dinfo.output_width;
97 frame->height = dinfo.output_height;
98 frame->chroma_subsampling_x = dinfo.max_h_samp_factor / dinfo.comp_info[1].h_samp_factor;
99 frame->chroma_subsampling_y = dinfo.max_v_samp_factor / dinfo.comp_info[1].v_samp_factor;
101 unsigned h_mcu_size = DCTSIZE * dinfo.max_h_samp_factor;
102 unsigned v_mcu_size = DCTSIZE * dinfo.max_v_samp_factor;
103 unsigned mcu_width_blocks = (dinfo.output_width + h_mcu_size - 1) / h_mcu_size;
104 unsigned mcu_height_blocks = (dinfo.output_height + v_mcu_size - 1) / v_mcu_size;
106 unsigned luma_width_blocks = mcu_width_blocks * dinfo.comp_info[0].h_samp_factor;
107 unsigned chroma_width_blocks = mcu_width_blocks * dinfo.comp_info[1].h_samp_factor;
108 unsigned luma_height_blocks = mcu_height_blocks * dinfo.comp_info[0].v_samp_factor;
109 unsigned chroma_height_blocks = mcu_height_blocks * dinfo.comp_info[1].v_samp_factor;
111 // TODO: Decode into a PBO.
112 frame->y.reset(new uint8_t[luma_width_blocks * luma_height_blocks * DCTSIZE2]);
113 frame->cb.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
114 frame->cr.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
115 frame->pitch_y = luma_width_blocks * DCTSIZE;
116 frame->pitch_chroma = chroma_width_blocks * DCTSIZE;
118 JSAMPROW yptr[v_mcu_size], cbptr[v_mcu_size], crptr[v_mcu_size];
119 JSAMPARRAY data[3] = { yptr, cbptr, crptr };
120 for (unsigned y = 0; y < mcu_height_blocks; ++y) {
121 // NOTE: The last elements of cbptr/crptr will be unused for vertically subsampled chroma.
122 for (unsigned yy = 0; yy < v_mcu_size; ++yy) {
123 yptr[yy] = frame->y.get() + (y * DCTSIZE * dinfo.max_v_samp_factor + yy) * frame->pitch_y;
124 cbptr[yy] = frame->cb.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
125 crptr[yy] = frame->cr.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
128 jpeg_read_raw_data(&dinfo, data, v_mcu_size);
131 (void) jpeg_finish_decompress(&dinfo);
132 jpeg_destroy_decompress(&dinfo);
140 // Assumes cache_mu is held.
141 vector<size_t> lru_timestamps;
142 for (const auto &key_and_value : cache) {
143 lru_timestamps.push_back(key_and_value.second.last_used);
146 size_t cutoff_point = CACHE_SIZE / 10; // Prune away the 10% oldest ones.
147 nth_element(lru_timestamps.begin(), lru_timestamps.begin() + cutoff_point, lru_timestamps.end());
148 size_t must_be_used_after = lru_timestamps[cutoff_point];
149 for (auto it = cache.begin(); it != cache.end(); ) {
150 if (it->second.last_used < must_be_used_after) {
151 it = cache.erase(it);
158 shared_ptr<Frame> decode_jpeg_with_cache(JPEGID id, CacheMissBehavior cache_miss_behavior, bool *did_decode)
162 unique_lock<mutex> lock(cache_mu);
163 auto it = cache.find(id);
164 if (it != cache.end()) {
165 it->second.last_used = event_counter++;
166 return it->second.frame;
170 if (cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE) {
174 assert(!id.interpolated);
176 shared_ptr<Frame> frame = decode_jpeg(filename_for_frame(id.stream_idx, id.pts));
178 unique_lock<mutex> lock(cache_mu);
179 cache[id] = LRUFrame{ frame, event_counter++ };
181 if (cache.size() > CACHE_SIZE) {
187 void jpeg_decoder_thread()
189 size_t num_decoded = 0, num_dropped = 0;
191 pthread_setname_np(pthread_self(), "JPEGDecoder");
195 CacheMissBehavior cache_miss_behavior = DECODE_IF_NOT_IN_CACHE;
197 unique_lock<mutex> lock(cache_mu); // TODO: Perhaps under another lock?
198 any_pending_decodes.wait(lock, [] {
199 return !pending_decodes.empty();
201 id = pending_decodes.front().first;
202 dest = pending_decodes.front().second;
203 pending_decodes.pop_front();
205 size_t num_pending = 0;
206 for (const pair<JPEGID, JPEGFrameView *> &decode : pending_decodes) {
207 if (decode.second == dest) {
211 if (num_pending > 3) {
212 cache_miss_behavior = RETURN_NULLPTR_IF_NOT_IN_CACHE;
217 shared_ptr<Frame> frame;
218 if (id.interpolated) {
219 // Interpolated frames are never decoded by us,
220 // put directly into the cache from VideoStream.
221 unique_lock<mutex> lock(cache_mu);
222 cache_updated.wait(lock, [id] {
223 return cache.count(id) != 0;
225 found_in_cache = true; // Don't count it as a decode.
227 auto it = cache.find(id);
228 assert(it != cache.end());
230 it->second.last_used = event_counter++;
231 frame = it->second.frame;
232 if (frame == nullptr) {
233 // We inserted a nullptr as signal that the frame was never
234 // interpolated and that we should stop waiting.
235 // But don't let it linger in the cache anymore.
239 frame = decode_jpeg_with_cache(id, cache_miss_behavior, &found_in_cache);
242 if (frame == nullptr) {
243 assert(id.interpolated || cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE);
248 if (!found_in_cache) {
250 if (num_decoded % 1000 == 0) {
251 fprintf(stderr, "Decoded %zu images, dropped %zu (%.2f%% dropped)\n",
252 num_decoded, num_dropped, (100.0 * num_dropped) / (num_decoded + num_dropped));
256 // TODO: Could we get jitter between non-interpolated and interpolated frames here?
257 dest->setDecodedFrame(frame);
261 JPEGFrameView::JPEGFrameView(QWidget *parent)
262 : QGLWidget(parent, global_share_widget) {
265 void JPEGFrameView::setFrame(unsigned stream_idx, int64_t pts, bool interpolated)
267 current_stream_idx = stream_idx;
269 unique_lock<mutex> lock(cache_mu);
270 pending_decodes.emplace_back(JPEGID{ stream_idx, pts, interpolated }, this);
271 any_pending_decodes.notify_all();
274 void JPEGFrameView::insert_interpolated_frame(unsigned stream_idx, int64_t pts, shared_ptr<Frame> frame)
276 JPEGID id{ stream_idx, pts, true };
278 // We rely on the frame not being evicted from the cache before
279 // jpeg_decoder_thread() sees it and can display it (otherwise,
280 // that thread would hang). With a default cache of 1000 elements,
281 // that would sound like a reasonable assumption.
282 unique_lock<mutex> lock(cache_mu);
283 cache[id] = LRUFrame{ std::move(frame), event_counter++ };
284 cache_updated.notify_all();
287 ResourcePool *resource_pool = nullptr;
289 void JPEGFrameView::initializeGL()
292 glDisable(GL_DEPTH_TEST);
295 static once_flag once;
297 resource_pool = new ResourcePool;
298 std::thread(&jpeg_decoder_thread).detach();
301 chain.reset(new EffectChain(1280, 720, resource_pool));
302 ImageFormat image_format;
303 image_format.color_space = COLORSPACE_sRGB;
304 image_format.gamma_curve = GAMMA_sRGB;
305 ycbcr_format.luma_coefficients = YCBCR_REC_709;
306 ycbcr_format.full_range = false;
307 ycbcr_format.num_levels = 256;
308 ycbcr_format.chroma_subsampling_x = 2;
309 ycbcr_format.chroma_subsampling_y = 1;
310 ycbcr_format.cb_x_position = 0.0f; // H.264 -- _not_ JPEG, even though our input is MJPEG-encoded
311 ycbcr_format.cb_y_position = 0.5f; // Irrelevant.
312 ycbcr_format.cr_x_position = 0.0f;
313 ycbcr_format.cr_y_position = 0.5f;
314 ycbcr_input = (movit::YCbCrInput *)chain->add_input(new YCbCrInput(image_format, ycbcr_format, 1280, 720));
316 ImageFormat inout_format;
317 inout_format.color_space = COLORSPACE_sRGB;
318 inout_format.gamma_curve = GAMMA_sRGB;
321 chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
323 chain->set_dither_bits(8);
328 overlay_chain.reset(new EffectChain(overlay_base_width, overlay_base_height, resource_pool));
329 overlay_input = (movit::FlatInput *)overlay_chain->add_input(new FlatInput(image_format, FORMAT_GRAYSCALE, GL_UNSIGNED_BYTE, overlay_base_width, overlay_base_height));
331 overlay_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
332 overlay_chain->finalize();
335 void JPEGFrameView::resizeGL(int width, int height)
338 glViewport(0, 0, width, height);
341 // Save these, as width() and height() will lie with DPI scaling.
346 void JPEGFrameView::paintGL()
348 glViewport(0, 0, gl_width, gl_height);
349 if (current_frame == nullptr) {
350 glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
351 glClear(GL_COLOR_BUFFER_BIT);
356 chain->render_to_screen();
358 if (overlay_image != nullptr) {
359 if (overlay_input_needs_refresh) {
360 overlay_input->set_width(overlay_width);
361 overlay_input->set_height(overlay_height);
362 overlay_input->set_pixel_data(overlay_image->bits());
364 glViewport(gl_width - overlay_width, 0, overlay_width, overlay_height);
365 overlay_chain->render_to_screen();
369 void JPEGFrameView::setDecodedFrame(std::shared_ptr<Frame> frame)
371 post_to_main_thread([this, frame] {
372 current_frame = frame;
373 ycbcr_format.chroma_subsampling_x = frame->chroma_subsampling_x;
374 ycbcr_format.chroma_subsampling_y = frame->chroma_subsampling_y;
375 ycbcr_input->change_ycbcr_format(ycbcr_format);
376 ycbcr_input->set_width(frame->width);
377 ycbcr_input->set_height(frame->height);
378 ycbcr_input->set_pixel_data(0, frame->y.get());
379 ycbcr_input->set_pixel_data(1, frame->cb.get());
380 ycbcr_input->set_pixel_data(2, frame->cr.get());
381 ycbcr_input->set_pitch(0, frame->pitch_y);
382 ycbcr_input->set_pitch(1, frame->pitch_chroma);
383 ycbcr_input->set_pitch(2, frame->pitch_chroma);
388 void JPEGFrameView::mousePressEvent(QMouseEvent *event)
390 if (event->type() == QEvent::MouseButtonPress && event->button() == Qt::LeftButton) {
395 void JPEGFrameView::set_overlay(const string &text)
398 overlay_image.reset();
402 float dpr = QGuiApplication::primaryScreen()->devicePixelRatio();
403 overlay_width = lrint(overlay_base_width * dpr);
404 overlay_height = lrint(overlay_base_height * dpr);
406 overlay_image.reset(new QImage(overlay_width, overlay_height, QImage::Format_Grayscale8));
407 overlay_image->setDevicePixelRatio(dpr);
408 overlay_image->fill(0);
409 QPainter painter(overlay_image.get());
411 painter.setPen(Qt::white);
412 QFont font = painter.font();
413 font.setPointSize(12);
414 painter.setFont(font);
416 painter.drawText(QRectF(0, 0, overlay_base_width, overlay_base_height), Qt::AlignCenter, QString::fromStdString(text));
418 // Don't refresh immediately; we might not have an OpenGL context here.
419 overlay_input_needs_refresh = true;