1 #include "jpeg_frame_view.h"
8 #include <condition_variable>
14 #include <QMouseEvent>
16 #include <movit/resource_pool.h>
17 #include <movit/init.h>
18 #include <movit/util.h>
21 #include "post_to_main_thread.h"
22 #include "video_stream.h"
24 using namespace movit;
27 // Just an arbitrary order for std::map.
28 struct JPEGIDLexicalOrder
30 bool operator() (const JPEGID &a, const JPEGID &b) const
32 if (a.stream_idx != b.stream_idx)
33 return a.stream_idx < b.stream_idx;
36 return a.interpolated < b.interpolated;
41 shared_ptr<Frame> frame;
46 map<JPEGID, LRUFrame, JPEGIDLexicalOrder> cache; // Under cache_mu.
47 condition_variable any_pending_decodes, cache_updated;
48 deque<pair<JPEGID, JPEGFrameView *>> pending_decodes; // Under cache_mu.
49 atomic<size_t> event_counter{0};
50 extern QGLWidget *global_share_widget;
52 // TODO: Decode using VA-API if available.
53 shared_ptr<Frame> decode_jpeg(const string &filename)
55 shared_ptr<Frame> frame(new Frame);
57 jpeg_decompress_struct dinfo;
59 dinfo.err = jpeg_std_error(&jerr);
60 jpeg_create_decompress(&dinfo);
62 FILE *fp = fopen(filename.c_str(), "rb");
64 perror(filename.c_str());
67 jpeg_stdio_src(&dinfo, fp);
69 jpeg_read_header(&dinfo, true);
71 if (dinfo.num_components != 3) {
72 fprintf(stderr, "Not a color JPEG. (%d components, Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
74 dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
75 dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
76 dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
79 if (dinfo.comp_info[0].h_samp_factor != dinfo.max_h_samp_factor ||
80 dinfo.comp_info[0].v_samp_factor != dinfo.max_v_samp_factor || // Y' must not be subsampled.
81 dinfo.comp_info[1].h_samp_factor != dinfo.comp_info[2].h_samp_factor ||
82 dinfo.comp_info[1].v_samp_factor != dinfo.comp_info[2].v_samp_factor || // Cb and Cr must be identically subsampled.
83 (dinfo.max_h_samp_factor % dinfo.comp_info[1].h_samp_factor) != 0 ||
84 (dinfo.max_v_samp_factor % dinfo.comp_info[1].v_samp_factor) != 0) { // No 2:3 subsampling or other weirdness.
85 fprintf(stderr, "Unsupported subsampling scheme. (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 dinfo.raw_data_out = true;
93 jpeg_start_decompress(&dinfo);
95 frame->width = dinfo.output_width;
96 frame->height = dinfo.output_height;
97 frame->chroma_subsampling_x = dinfo.max_h_samp_factor / dinfo.comp_info[1].h_samp_factor;
98 frame->chroma_subsampling_y = dinfo.max_v_samp_factor / dinfo.comp_info[1].v_samp_factor;
100 unsigned h_mcu_size = DCTSIZE * dinfo.max_h_samp_factor;
101 unsigned v_mcu_size = DCTSIZE * dinfo.max_v_samp_factor;
102 unsigned mcu_width_blocks = (dinfo.output_width + h_mcu_size - 1) / h_mcu_size;
103 unsigned mcu_height_blocks = (dinfo.output_height + v_mcu_size - 1) / v_mcu_size;
105 unsigned luma_width_blocks = mcu_width_blocks * dinfo.comp_info[0].h_samp_factor;
106 unsigned chroma_width_blocks = mcu_width_blocks * dinfo.comp_info[1].h_samp_factor;
107 unsigned luma_height_blocks = mcu_height_blocks * dinfo.comp_info[0].v_samp_factor;
108 unsigned chroma_height_blocks = mcu_height_blocks * dinfo.comp_info[1].v_samp_factor;
110 // TODO: Decode into a PBO.
111 frame->y.reset(new uint8_t[luma_width_blocks * luma_height_blocks * DCTSIZE2]);
112 frame->cb.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
113 frame->cr.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
114 frame->pitch_y = luma_width_blocks * DCTSIZE;
115 frame->pitch_chroma = chroma_width_blocks * DCTSIZE;
117 JSAMPROW yptr[v_mcu_size], cbptr[v_mcu_size], crptr[v_mcu_size];
118 JSAMPARRAY data[3] = { yptr, cbptr, crptr };
119 for (unsigned y = 0; y < mcu_height_blocks; ++y) {
120 // NOTE: The last elements of cbptr/crptr will be unused for vertically subsampled chroma.
121 for (unsigned yy = 0; yy < v_mcu_size; ++yy) {
122 yptr[yy] = frame->y.get() + (y * DCTSIZE * dinfo.max_v_samp_factor + yy) * frame->pitch_y;
123 cbptr[yy] = frame->cb.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
124 crptr[yy] = frame->cr.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
127 jpeg_read_raw_data(&dinfo, data, v_mcu_size);
130 (void) jpeg_finish_decompress(&dinfo);
131 jpeg_destroy_decompress(&dinfo);
139 // Assumes cache_mu is held.
140 vector<size_t> lru_timestamps;
141 for (const auto &key_and_value : cache) {
142 lru_timestamps.push_back(key_and_value.second.last_used);
145 size_t cutoff_point = CACHE_SIZE / 10; // Prune away the 10% oldest ones.
146 nth_element(lru_timestamps.begin(), lru_timestamps.begin() + cutoff_point, lru_timestamps.end());
147 size_t must_be_used_after = lru_timestamps[cutoff_point];
148 for (auto it = cache.begin(); it != cache.end(); ) {
149 if (it->second.last_used < must_be_used_after) {
150 it = cache.erase(it);
157 shared_ptr<Frame> decode_jpeg_with_cache(JPEGID id, CacheMissBehavior cache_miss_behavior, bool *did_decode)
161 unique_lock<mutex> lock(cache_mu);
162 auto it = cache.find(id);
163 if (it != cache.end()) {
164 it->second.last_used = event_counter++;
165 return it->second.frame;
169 if (cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE) {
173 assert(!id.interpolated);
175 shared_ptr<Frame> frame = decode_jpeg(filename_for_frame(id.stream_idx, id.pts));
177 unique_lock<mutex> lock(cache_mu);
178 cache[id] = LRUFrame{ frame, event_counter++ };
180 if (cache.size() > CACHE_SIZE) {
186 void jpeg_decoder_thread()
188 size_t num_decoded = 0, num_dropped = 0;
190 pthread_setname_np(pthread_self(), "JPEGDecoder");
194 CacheMissBehavior cache_miss_behavior = DECODE_IF_NOT_IN_CACHE;
196 unique_lock<mutex> lock(cache_mu); // TODO: Perhaps under another lock?
197 any_pending_decodes.wait(lock, [] {
198 return !pending_decodes.empty();
200 id = pending_decodes.front().first;
201 dest = pending_decodes.front().second;
202 pending_decodes.pop_front();
204 size_t num_pending = 0;
205 for (const pair<JPEGID, JPEGFrameView *> &decode : pending_decodes) {
206 if (decode.second == dest) {
210 if (num_pending > 3) {
211 cache_miss_behavior = RETURN_NULLPTR_IF_NOT_IN_CACHE;
216 shared_ptr<Frame> frame;
217 if (id.interpolated) {
218 // Interpolated frames are never decoded by us,
219 // put directly into the cache from VideoStream.
220 unique_lock<mutex> lock(cache_mu);
221 cache_updated.wait(lock, [id] {
222 return cache.count(id) != 0;
224 found_in_cache = true; // Don't count it as a decode.
226 auto it = cache.find(id);
227 assert(it != cache.end());
229 it->second.last_used = event_counter++;
230 frame = it->second.frame;
231 if (frame == nullptr) {
232 // We inserted a nullptr as signal that the frame was never
233 // interpolated and that we should stop waiting.
234 // But don't let it linger in the cache anymore.
238 frame = decode_jpeg_with_cache(id, cache_miss_behavior, &found_in_cache);
241 if (frame == nullptr) {
242 assert(id.interpolated || cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE);
247 if (!found_in_cache) {
249 if (num_decoded % 1000 == 0) {
250 fprintf(stderr, "Decoded %zu images, dropped %zu (%.2f%% dropped)\n",
251 num_decoded, num_dropped, (100.0 * num_dropped) / (num_decoded + num_dropped));
255 // TODO: Could we get jitter between non-interpolated and interpolated frames here?
256 dest->setDecodedFrame(frame);
260 JPEGFrameView::JPEGFrameView(QWidget *parent)
261 : QGLWidget(parent, global_share_widget) {
264 void JPEGFrameView::setFrame(unsigned stream_idx, int64_t pts, bool interpolated)
266 current_stream_idx = stream_idx;
268 unique_lock<mutex> lock(cache_mu);
269 pending_decodes.emplace_back(JPEGID{ stream_idx, pts, interpolated }, this);
270 any_pending_decodes.notify_all();
273 void JPEGFrameView::insert_interpolated_frame(unsigned stream_idx, int64_t pts, shared_ptr<Frame> frame)
275 JPEGID id{ stream_idx, pts, true };
277 // We rely on the frame not being evicted from the cache before
278 // jpeg_decoder_thread() sees it and can display it (otherwise,
279 // that thread would hang). With a default cache of 1000 elements,
280 // that would sound like a reasonable assumption.
281 unique_lock<mutex> lock(cache_mu);
282 cache[id] = LRUFrame{ std::move(frame), event_counter++ };
283 cache_updated.notify_all();
286 ResourcePool *resource_pool = nullptr;
288 void JPEGFrameView::initializeGL()
291 glDisable(GL_DEPTH_TEST);
294 static once_flag once;
296 resource_pool = new ResourcePool;
297 std::thread(&jpeg_decoder_thread).detach();
300 chain.reset(new EffectChain(1280, 720, resource_pool));
301 ImageFormat image_format;
302 image_format.color_space = COLORSPACE_sRGB;
303 image_format.gamma_curve = GAMMA_sRGB;
304 ycbcr_format.luma_coefficients = YCBCR_REC_709;
305 ycbcr_format.full_range = false;
306 ycbcr_format.num_levels = 256;
307 ycbcr_format.chroma_subsampling_x = 2;
308 ycbcr_format.chroma_subsampling_y = 1;
309 ycbcr_format.cb_x_position = 0.0f; // H.264 -- _not_ JPEG, even though our input is MJPEG-encoded
310 ycbcr_format.cb_y_position = 0.5f; // Irrelevant.
311 ycbcr_format.cr_x_position = 0.0f;
312 ycbcr_format.cr_y_position = 0.5f;
313 ycbcr_input = (movit::YCbCrInput *)chain->add_input(new YCbCrInput(image_format, ycbcr_format, 1280, 720));
315 ImageFormat inout_format;
316 inout_format.color_space = COLORSPACE_sRGB;
317 inout_format.gamma_curve = GAMMA_sRGB;
320 chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
322 chain->set_dither_bits(8);
327 overlay_chain.reset(new EffectChain(overlay_width, overlay_height, resource_pool));
328 overlay_input = (movit::FlatInput *)overlay_chain->add_input(new FlatInput(image_format, FORMAT_GRAYSCALE, GL_UNSIGNED_BYTE, overlay_width, overlay_height));
330 overlay_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
331 overlay_chain->finalize();
334 void JPEGFrameView::resizeGL(int width, int height)
337 glViewport(0, 0, width, height);
341 void JPEGFrameView::paintGL()
343 glViewport(0, 0, width(), height());
344 if (current_frame == nullptr) {
345 glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
346 glClear(GL_COLOR_BUFFER_BIT);
351 chain->render_to_screen();
353 if (overlay_image != nullptr) {
354 if (overlay_input_needs_refresh) {
355 overlay_input->set_pixel_data(overlay_image->bits());
357 glViewport(width() - overlay_width, 0, overlay_width, overlay_height);
358 overlay_chain->render_to_screen();
362 void JPEGFrameView::setDecodedFrame(std::shared_ptr<Frame> frame)
364 post_to_main_thread([this, frame] {
365 current_frame = frame;
366 ycbcr_format.chroma_subsampling_x = frame->chroma_subsampling_x;
367 ycbcr_format.chroma_subsampling_y = frame->chroma_subsampling_y;
368 ycbcr_input->change_ycbcr_format(ycbcr_format);
369 ycbcr_input->set_width(frame->width);
370 ycbcr_input->set_height(frame->height);
371 ycbcr_input->set_pixel_data(0, frame->y.get());
372 ycbcr_input->set_pixel_data(1, frame->cb.get());
373 ycbcr_input->set_pixel_data(2, frame->cr.get());
374 ycbcr_input->set_pitch(0, frame->pitch_y);
375 ycbcr_input->set_pitch(1, frame->pitch_chroma);
376 ycbcr_input->set_pitch(2, frame->pitch_chroma);
381 void JPEGFrameView::mousePressEvent(QMouseEvent *event)
383 if (event->type() == QEvent::MouseButtonPress && event->button() == Qt::LeftButton) {
388 void JPEGFrameView::set_overlay(const string &text)
391 overlay_image.reset();
395 overlay_image.reset(new QImage(overlay_width, overlay_height, QImage::Format_Grayscale8));
396 overlay_image->fill(0);
397 QPainter painter(overlay_image.get());
399 painter.setPen(Qt::white);
400 QFont font = painter.font();
401 font.setPointSize(12);
402 painter.setFont(font);
404 painter.drawText(QRectF(0, 0, overlay_width, overlay_height), Qt::AlignCenter, QString::fromStdString(text));
406 // Don't refresh immediately; we might not have an OpenGL context here.
407 overlay_input_needs_refresh = true;