1 #include "jpeg_frame_view.h"
7 #include <condition_variable>
13 #include <movit/resource_pool.h>
14 #include <movit/init.h>
15 #include <movit/util.h>
18 #include "post_to_main_thread.h"
19 #include "video_stream.h"
21 using namespace movit;
24 bool operator< (const JPEGID &a, const JPEGID &b) {
25 return make_pair(a.stream_idx, a.pts) < make_pair(b.stream_idx, b.pts);
29 shared_ptr<Frame> frame;
34 map<JPEGID, LRUFrame> cache; // Under cache_mu.
35 condition_variable any_pending_decodes;
36 deque<pair<JPEGID, JPEGFrameView *>> pending_decodes; // Under cache_mu.
37 atomic<size_t> event_counter{0};
38 extern QGLWidget *global_share_widget;
40 // TODO: Decode using VA-API if available.
41 shared_ptr<Frame> decode_jpeg(const string &filename)
43 shared_ptr<Frame> frame(new Frame);
45 jpeg_decompress_struct dinfo;
47 dinfo.err = jpeg_std_error(&jerr);
48 jpeg_create_decompress(&dinfo);
50 FILE *fp = fopen(filename.c_str(), "rb");
52 perror(filename.c_str());
55 jpeg_stdio_src(&dinfo, fp);
57 jpeg_read_header(&dinfo, true);
59 if (dinfo.num_components != 3) {
60 fprintf(stderr, "Not a color JPEG. (%d components, Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
62 dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
63 dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
64 dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
67 if (dinfo.comp_info[0].h_samp_factor != dinfo.max_h_samp_factor ||
68 dinfo.comp_info[0].v_samp_factor != dinfo.max_v_samp_factor || // Y' must not be subsampled.
69 dinfo.comp_info[1].h_samp_factor != dinfo.comp_info[2].h_samp_factor ||
70 dinfo.comp_info[1].v_samp_factor != dinfo.comp_info[2].v_samp_factor || // Cb and Cr must be identically subsampled.
71 (dinfo.max_h_samp_factor % dinfo.comp_info[1].h_samp_factor) != 0 ||
72 (dinfo.max_v_samp_factor % dinfo.comp_info[1].v_samp_factor) != 0) { // No 2:3 subsampling or other weirdness.
73 fprintf(stderr, "Unsupported subsampling scheme. (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 dinfo.raw_data_out = true;
81 jpeg_start_decompress(&dinfo);
83 frame->width = dinfo.output_width;
84 frame->height = dinfo.output_height;
85 frame->chroma_subsampling_x = dinfo.max_h_samp_factor / dinfo.comp_info[1].h_samp_factor;
86 frame->chroma_subsampling_y = dinfo.max_v_samp_factor / dinfo.comp_info[1].v_samp_factor;
88 unsigned h_mcu_size = DCTSIZE * dinfo.max_h_samp_factor;
89 unsigned v_mcu_size = DCTSIZE * dinfo.max_v_samp_factor;
90 unsigned mcu_width_blocks = (dinfo.output_width + h_mcu_size - 1) / h_mcu_size;
91 unsigned mcu_height_blocks = (dinfo.output_height + v_mcu_size - 1) / v_mcu_size;
93 unsigned luma_width_blocks = mcu_width_blocks * dinfo.comp_info[0].h_samp_factor;
94 unsigned chroma_width_blocks = mcu_width_blocks * dinfo.comp_info[1].h_samp_factor;
95 unsigned luma_height_blocks = mcu_height_blocks * dinfo.comp_info[0].v_samp_factor;
96 unsigned chroma_height_blocks = mcu_height_blocks * dinfo.comp_info[1].v_samp_factor;
98 // TODO: Decode into a PBO.
99 frame->y.reset(new uint8_t[luma_width_blocks * luma_height_blocks * DCTSIZE2]);
100 frame->cb.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
101 frame->cr.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
102 frame->pitch_y = luma_width_blocks * DCTSIZE;
103 frame->pitch_chroma = chroma_width_blocks * DCTSIZE;
105 JSAMPROW yptr[v_mcu_size], cbptr[v_mcu_size], crptr[v_mcu_size];
106 JSAMPARRAY data[3] = { yptr, cbptr, crptr };
107 for (unsigned y = 0; y < mcu_height_blocks; ++y) {
108 // NOTE: The last elements of cbptr/crptr will be unused for vertically subsampled chroma.
109 for (unsigned yy = 0; yy < v_mcu_size; ++yy) {
110 yptr[yy] = frame->y.get() + (y * DCTSIZE * dinfo.max_v_samp_factor + yy) * frame->pitch_y;
111 cbptr[yy] = frame->cb.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
112 crptr[yy] = frame->cr.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
115 jpeg_read_raw_data(&dinfo, data, v_mcu_size);
118 (void) jpeg_finish_decompress(&dinfo);
119 jpeg_destroy_decompress(&dinfo);
127 // Assumes cache_mu is held.
128 vector<size_t> lru_timestamps;
129 for (const auto &key_and_value : cache) {
130 lru_timestamps.push_back(key_and_value.second.last_used);
133 size_t cutoff_point = CACHE_SIZE / 10; // Prune away the 10% oldest ones.
134 nth_element(lru_timestamps.begin(), lru_timestamps.begin() + cutoff_point, lru_timestamps.end());
135 size_t must_be_used_after = lru_timestamps[cutoff_point];
136 for (auto it = cache.begin(); it != cache.end(); ) {
137 if (it->second.last_used < must_be_used_after) {
138 it = cache.erase(it);
145 shared_ptr<Frame> decode_jpeg_with_cache(JPEGID id, CacheMissBehavior cache_miss_behavior, bool *did_decode)
149 unique_lock<mutex> lock(cache_mu);
150 auto it = cache.find(id);
151 if (it != cache.end()) {
152 it->second.last_used = event_counter++;
153 return it->second.frame;
157 if (cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE) {
162 shared_ptr<Frame> frame = decode_jpeg(filename_for_frame(id.stream_idx, id.pts));
164 unique_lock<mutex> lock(cache_mu);
165 cache[id] = LRUFrame{ frame, event_counter++ };
167 if (cache.size() > CACHE_SIZE) {
173 void jpeg_decoder_thread()
175 size_t num_decoded = 0, num_dropped = 0;
177 pthread_setname_np(pthread_self(), "JPEGDecoder");
181 CacheMissBehavior cache_miss_behavior = DECODE_IF_NOT_IN_CACHE;
183 unique_lock<mutex> lock(cache_mu); // TODO: Perhaps under another lock?
184 any_pending_decodes.wait(lock, [] {
185 return !pending_decodes.empty();
187 id = pending_decodes.front().first;
188 dest = pending_decodes.front().second;
189 pending_decodes.pop_front();
191 size_t num_pending = 0;
192 for (const pair<JPEGID, JPEGFrameView *> &decode : pending_decodes) {
193 if (decode.second == dest) {
197 if (num_pending > 3) {
198 cache_miss_behavior = RETURN_NULLPTR_IF_NOT_IN_CACHE;
203 shared_ptr<Frame> frame = decode_jpeg_with_cache(id, cache_miss_behavior, &found_in_cache);
205 if (frame == nullptr) {
206 assert(cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE);
211 if (!found_in_cache) {
213 if (num_decoded % 1000 == 0) {
214 fprintf(stderr, "Decoded %zu images, dropped %zu (%.2f%% dropped)\n",
215 num_decoded, num_dropped, (100.0 * num_dropped) / (num_decoded + num_dropped));
219 dest->setDecodedFrame(frame);
223 JPEGFrameView::JPEGFrameView(QWidget *parent)
224 : QGLWidget(parent, global_share_widget) {
227 void JPEGFrameView::update_frame()
229 unique_lock<mutex> lock(cache_mu);
230 pending_decodes.emplace_back(JPEGID{ stream_idx, pts }, this);
231 any_pending_decodes.notify_all();
234 ResourcePool *resource_pool = nullptr;
236 void JPEGFrameView::initializeGL()
239 glDisable(GL_DEPTH_TEST);
242 static once_flag once;
244 resource_pool = new ResourcePool;
245 std::thread(&jpeg_decoder_thread).detach();
248 chain.reset(new EffectChain(1280, 720, resource_pool));
249 ImageFormat image_format;
250 image_format.color_space = COLORSPACE_sRGB;
251 image_format.gamma_curve = GAMMA_sRGB;
252 ycbcr_format.luma_coefficients = YCBCR_REC_709;
253 ycbcr_format.full_range = false;
254 ycbcr_format.num_levels = 256;
255 ycbcr_format.chroma_subsampling_x = 2;
256 ycbcr_format.chroma_subsampling_y = 1;
257 ycbcr_format.cb_x_position = 0.0f; // H.264 -- _not_ JPEG, even though our input is MJPEG-encoded
258 ycbcr_format.cb_y_position = 0.5f; // Irrelevant.
259 ycbcr_format.cr_x_position = 0.0f;
260 ycbcr_format.cr_y_position = 0.5f;
261 ycbcr_input = (movit::YCbCrInput *)chain->add_input(new YCbCrInput(image_format, ycbcr_format, 1280, 720));
263 ImageFormat inout_format;
264 inout_format.color_space = COLORSPACE_sRGB;
265 inout_format.gamma_curve = GAMMA_sRGB;
268 chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
270 chain->set_dither_bits(8);
276 void JPEGFrameView::resizeGL(int width, int height)
279 glViewport(0, 0, width, height);
283 void JPEGFrameView::paintGL()
285 if (current_frame == nullptr) {
286 glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
287 glClear(GL_COLOR_BUFFER_BIT);
292 chain->render_to_screen();
295 void JPEGFrameView::setDecodedFrame(std::shared_ptr<Frame> frame)
297 post_to_main_thread([this, frame] {
298 current_frame = frame;
299 ycbcr_format.chroma_subsampling_x = frame->chroma_subsampling_x;
300 ycbcr_format.chroma_subsampling_y = frame->chroma_subsampling_y;
301 ycbcr_input->change_ycbcr_format(ycbcr_format);
302 ycbcr_input->set_width(frame->width);
303 ycbcr_input->set_height(frame->height);
304 ycbcr_input->set_pixel_data(0, frame->y.get());
305 ycbcr_input->set_pixel_data(1, frame->cb.get());
306 ycbcr_input->set_pixel_data(2, frame->cr.get());
307 ycbcr_input->set_pitch(0, frame->pitch_y);
308 ycbcr_input->set_pitch(1, frame->pitch_chroma);
309 ycbcr_input->set_pitch(2, frame->pitch_chroma);