1 #include "jpeg_frame_view.h"
7 #include <condition_variable>
13 #include <QMouseEvent>
15 #include <movit/resource_pool.h>
16 #include <movit/init.h>
17 #include <movit/util.h>
20 #include "post_to_main_thread.h"
21 #include "video_stream.h"
23 using namespace movit;
26 bool operator< (const JPEGID &a, const JPEGID &b) {
27 return make_pair(a.stream_idx, a.pts) < make_pair(b.stream_idx, b.pts);
31 shared_ptr<Frame> frame;
36 map<JPEGID, LRUFrame> cache; // Under cache_mu.
37 condition_variable any_pending_decodes;
38 deque<pair<JPEGID, JPEGFrameView *>> pending_decodes; // Under cache_mu.
39 atomic<size_t> event_counter{0};
40 extern QGLWidget *global_share_widget;
42 // TODO: Decode using VA-API if available.
43 shared_ptr<Frame> decode_jpeg(const string &filename)
45 shared_ptr<Frame> frame(new Frame);
47 jpeg_decompress_struct dinfo;
49 dinfo.err = jpeg_std_error(&jerr);
50 jpeg_create_decompress(&dinfo);
52 FILE *fp = fopen(filename.c_str(), "rb");
54 perror(filename.c_str());
57 jpeg_stdio_src(&dinfo, fp);
59 jpeg_read_header(&dinfo, true);
61 if (dinfo.num_components != 3) {
62 fprintf(stderr, "Not a color JPEG. (%d components, Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
64 dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
65 dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
66 dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
69 if (dinfo.comp_info[0].h_samp_factor != dinfo.max_h_samp_factor ||
70 dinfo.comp_info[0].v_samp_factor != dinfo.max_v_samp_factor || // Y' must not be subsampled.
71 dinfo.comp_info[1].h_samp_factor != dinfo.comp_info[2].h_samp_factor ||
72 dinfo.comp_info[1].v_samp_factor != dinfo.comp_info[2].v_samp_factor || // Cb and Cr must be identically subsampled.
73 (dinfo.max_h_samp_factor % dinfo.comp_info[1].h_samp_factor) != 0 ||
74 (dinfo.max_v_samp_factor % dinfo.comp_info[1].v_samp_factor) != 0) { // No 2:3 subsampling or other weirdness.
75 fprintf(stderr, "Unsupported subsampling scheme. (Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
76 dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
77 dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
78 dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
81 dinfo.raw_data_out = true;
83 jpeg_start_decompress(&dinfo);
85 frame->width = dinfo.output_width;
86 frame->height = dinfo.output_height;
87 frame->chroma_subsampling_x = dinfo.max_h_samp_factor / dinfo.comp_info[1].h_samp_factor;
88 frame->chroma_subsampling_y = dinfo.max_v_samp_factor / dinfo.comp_info[1].v_samp_factor;
90 unsigned h_mcu_size = DCTSIZE * dinfo.max_h_samp_factor;
91 unsigned v_mcu_size = DCTSIZE * dinfo.max_v_samp_factor;
92 unsigned mcu_width_blocks = (dinfo.output_width + h_mcu_size - 1) / h_mcu_size;
93 unsigned mcu_height_blocks = (dinfo.output_height + v_mcu_size - 1) / v_mcu_size;
95 unsigned luma_width_blocks = mcu_width_blocks * dinfo.comp_info[0].h_samp_factor;
96 unsigned chroma_width_blocks = mcu_width_blocks * dinfo.comp_info[1].h_samp_factor;
97 unsigned luma_height_blocks = mcu_height_blocks * dinfo.comp_info[0].v_samp_factor;
98 unsigned chroma_height_blocks = mcu_height_blocks * dinfo.comp_info[1].v_samp_factor;
100 // TODO: Decode into a PBO.
101 frame->y.reset(new uint8_t[luma_width_blocks * luma_height_blocks * DCTSIZE2]);
102 frame->cb.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
103 frame->cr.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
104 frame->pitch_y = luma_width_blocks * DCTSIZE;
105 frame->pitch_chroma = chroma_width_blocks * DCTSIZE;
107 JSAMPROW yptr[v_mcu_size], cbptr[v_mcu_size], crptr[v_mcu_size];
108 JSAMPARRAY data[3] = { yptr, cbptr, crptr };
109 for (unsigned y = 0; y < mcu_height_blocks; ++y) {
110 // NOTE: The last elements of cbptr/crptr will be unused for vertically subsampled chroma.
111 for (unsigned yy = 0; yy < v_mcu_size; ++yy) {
112 yptr[yy] = frame->y.get() + (y * DCTSIZE * dinfo.max_v_samp_factor + yy) * frame->pitch_y;
113 cbptr[yy] = frame->cb.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
114 crptr[yy] = frame->cr.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
117 jpeg_read_raw_data(&dinfo, data, v_mcu_size);
120 (void) jpeg_finish_decompress(&dinfo);
121 jpeg_destroy_decompress(&dinfo);
129 // Assumes cache_mu is held.
130 vector<size_t> lru_timestamps;
131 for (const auto &key_and_value : cache) {
132 lru_timestamps.push_back(key_and_value.second.last_used);
135 size_t cutoff_point = CACHE_SIZE / 10; // Prune away the 10% oldest ones.
136 nth_element(lru_timestamps.begin(), lru_timestamps.begin() + cutoff_point, lru_timestamps.end());
137 size_t must_be_used_after = lru_timestamps[cutoff_point];
138 for (auto it = cache.begin(); it != cache.end(); ) {
139 if (it->second.last_used < must_be_used_after) {
140 it = cache.erase(it);
147 shared_ptr<Frame> decode_jpeg_with_cache(JPEGID id, CacheMissBehavior cache_miss_behavior, bool *did_decode)
151 unique_lock<mutex> lock(cache_mu);
152 auto it = cache.find(id);
153 if (it != cache.end()) {
154 it->second.last_used = event_counter++;
155 return it->second.frame;
159 if (cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE) {
164 shared_ptr<Frame> frame = decode_jpeg(filename_for_frame(id.stream_idx, id.pts));
166 unique_lock<mutex> lock(cache_mu);
167 cache[id] = LRUFrame{ frame, event_counter++ };
169 if (cache.size() > CACHE_SIZE) {
175 void jpeg_decoder_thread()
177 size_t num_decoded = 0, num_dropped = 0;
179 pthread_setname_np(pthread_self(), "JPEGDecoder");
183 CacheMissBehavior cache_miss_behavior = DECODE_IF_NOT_IN_CACHE;
185 unique_lock<mutex> lock(cache_mu); // TODO: Perhaps under another lock?
186 any_pending_decodes.wait(lock, [] {
187 return !pending_decodes.empty();
189 id = pending_decodes.front().first;
190 dest = pending_decodes.front().second;
191 pending_decodes.pop_front();
193 size_t num_pending = 0;
194 for (const pair<JPEGID, JPEGFrameView *> &decode : pending_decodes) {
195 if (decode.second == dest) {
199 if (num_pending > 3) {
200 cache_miss_behavior = RETURN_NULLPTR_IF_NOT_IN_CACHE;
205 shared_ptr<Frame> frame = decode_jpeg_with_cache(id, cache_miss_behavior, &found_in_cache);
207 if (frame == nullptr) {
208 assert(cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE);
213 if (!found_in_cache) {
215 if (num_decoded % 1000 == 0) {
216 fprintf(stderr, "Decoded %zu images, dropped %zu (%.2f%% dropped)\n",
217 num_decoded, num_dropped, (100.0 * num_dropped) / (num_decoded + num_dropped));
221 dest->setDecodedFrame(frame);
225 JPEGFrameView::JPEGFrameView(QWidget *parent)
226 : QGLWidget(parent, global_share_widget) {
229 void JPEGFrameView::update_frame()
231 unique_lock<mutex> lock(cache_mu);
232 pending_decodes.emplace_back(JPEGID{ stream_idx, pts }, this);
233 any_pending_decodes.notify_all();
236 ResourcePool *resource_pool = nullptr;
238 void JPEGFrameView::initializeGL()
241 glDisable(GL_DEPTH_TEST);
244 static once_flag once;
246 resource_pool = new ResourcePool;
247 std::thread(&jpeg_decoder_thread).detach();
250 chain.reset(new EffectChain(1280, 720, resource_pool));
251 ImageFormat image_format;
252 image_format.color_space = COLORSPACE_sRGB;
253 image_format.gamma_curve = GAMMA_sRGB;
254 ycbcr_format.luma_coefficients = YCBCR_REC_709;
255 ycbcr_format.full_range = false;
256 ycbcr_format.num_levels = 256;
257 ycbcr_format.chroma_subsampling_x = 2;
258 ycbcr_format.chroma_subsampling_y = 1;
259 ycbcr_format.cb_x_position = 0.0f; // H.264 -- _not_ JPEG, even though our input is MJPEG-encoded
260 ycbcr_format.cb_y_position = 0.5f; // Irrelevant.
261 ycbcr_format.cr_x_position = 0.0f;
262 ycbcr_format.cr_y_position = 0.5f;
263 ycbcr_input = (movit::YCbCrInput *)chain->add_input(new YCbCrInput(image_format, ycbcr_format, 1280, 720));
265 ImageFormat inout_format;
266 inout_format.color_space = COLORSPACE_sRGB;
267 inout_format.gamma_curve = GAMMA_sRGB;
270 chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
272 chain->set_dither_bits(8);
278 void JPEGFrameView::resizeGL(int width, int height)
281 glViewport(0, 0, width, height);
285 void JPEGFrameView::paintGL()
287 if (current_frame == nullptr) {
288 glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
289 glClear(GL_COLOR_BUFFER_BIT);
294 chain->render_to_screen();
297 void JPEGFrameView::setDecodedFrame(std::shared_ptr<Frame> frame)
299 post_to_main_thread([this, frame] {
300 current_frame = frame;
301 ycbcr_format.chroma_subsampling_x = frame->chroma_subsampling_x;
302 ycbcr_format.chroma_subsampling_y = frame->chroma_subsampling_y;
303 ycbcr_input->change_ycbcr_format(ycbcr_format);
304 ycbcr_input->set_width(frame->width);
305 ycbcr_input->set_height(frame->height);
306 ycbcr_input->set_pixel_data(0, frame->y.get());
307 ycbcr_input->set_pixel_data(1, frame->cb.get());
308 ycbcr_input->set_pixel_data(2, frame->cr.get());
309 ycbcr_input->set_pitch(0, frame->pitch_y);
310 ycbcr_input->set_pitch(1, frame->pitch_chroma);
311 ycbcr_input->set_pitch(2, frame->pitch_chroma);
316 void JPEGFrameView::mousePressEvent(QMouseEvent *event)
318 if (event->type() == QEvent::MouseButtonPress && event->button() == Qt::LeftButton) {