1 #include "jpeg_frame_view.h"
4 #include "jpeg_destroyer.h"
5 #include "post_to_main_thread.h"
6 #include "video_stream.h"
7 #include "ycbcr_converter.h"
12 #include <condition_variable>
15 #include <movit/init.h>
16 #include <movit/resource_pool.h>
17 #include <movit/util.h>
24 // Must come after the Qt stuff.
25 #include "vaapi_jpeg_decoder.h"
27 using namespace movit;
30 // Just an arbitrary order for std::map.
31 struct JPEGIDLexicalOrder
33 bool operator() (const JPEGID &a, const JPEGID &b) const
35 if (a.stream_idx != b.stream_idx)
36 return a.stream_idx < b.stream_idx;
39 return a.interpolated < b.interpolated;
44 shared_ptr<Frame> frame;
48 struct PendingDecode {
49 JPEGID primary, secondary;
50 float fade_alpha; // Irrelevant if secondary.stream_idx == -1.
51 JPEGFrameView *destination;
54 thread JPEGFrameView::jpeg_decoder_thread;
56 map<JPEGID, LRUFrame, JPEGIDLexicalOrder> cache; // Under cache_mu.
57 condition_variable any_pending_decodes, cache_updated;
58 deque<PendingDecode> pending_decodes; // Under cache_mu.
59 atomic<size_t> event_counter{0};
60 extern QGLWidget *global_share_widget;
61 extern atomic<bool> should_quit;
63 shared_ptr<Frame> decode_jpeg(const string &filename)
65 shared_ptr<Frame> frame;
66 if (vaapi_jpeg_decoding_usable) {
67 frame = decode_jpeg_vaapi(filename);
68 if (frame != nullptr) {
71 fprintf(stderr, "VA-API hardware decoding failed; falling back to software.\n");
74 frame.reset(new Frame);
76 jpeg_decompress_struct dinfo;
78 dinfo.err = jpeg_std_error(&jerr);
79 jpeg_create_decompress(&dinfo);
80 JPEGDestroyer destroy_dinfo(&dinfo);
82 FILE *fp = fopen(filename.c_str(), "rb");
84 perror(filename.c_str());
87 jpeg_stdio_src(&dinfo, fp);
89 jpeg_read_header(&dinfo, true);
91 if (dinfo.num_components != 3) {
92 fprintf(stderr, "Not a color JPEG. (%d components, Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
94 dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
95 dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
96 dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
99 if (dinfo.comp_info[0].h_samp_factor != dinfo.max_h_samp_factor ||
100 dinfo.comp_info[0].v_samp_factor != dinfo.max_v_samp_factor || // Y' must not be subsampled.
101 dinfo.comp_info[1].h_samp_factor != dinfo.comp_info[2].h_samp_factor ||
102 dinfo.comp_info[1].v_samp_factor != dinfo.comp_info[2].v_samp_factor || // Cb and Cr must be identically subsampled.
103 (dinfo.max_h_samp_factor % dinfo.comp_info[1].h_samp_factor) != 0 ||
104 (dinfo.max_v_samp_factor % dinfo.comp_info[1].v_samp_factor) != 0) { // No 2:3 subsampling or other weirdness.
105 fprintf(stderr, "Unsupported subsampling scheme. (Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
106 dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
107 dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
108 dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
111 dinfo.raw_data_out = true;
113 jpeg_start_decompress(&dinfo);
115 frame->width = dinfo.output_width;
116 frame->height = dinfo.output_height;
117 frame->chroma_subsampling_x = dinfo.max_h_samp_factor / dinfo.comp_info[1].h_samp_factor;
118 frame->chroma_subsampling_y = dinfo.max_v_samp_factor / dinfo.comp_info[1].v_samp_factor;
120 unsigned h_mcu_size = DCTSIZE * dinfo.max_h_samp_factor;
121 unsigned v_mcu_size = DCTSIZE * dinfo.max_v_samp_factor;
122 unsigned mcu_width_blocks = (dinfo.output_width + h_mcu_size - 1) / h_mcu_size;
123 unsigned mcu_height_blocks = (dinfo.output_height + v_mcu_size - 1) / v_mcu_size;
125 unsigned luma_width_blocks = mcu_width_blocks * dinfo.comp_info[0].h_samp_factor;
126 unsigned chroma_width_blocks = mcu_width_blocks * dinfo.comp_info[1].h_samp_factor;
127 unsigned luma_height_blocks = mcu_height_blocks * dinfo.comp_info[0].v_samp_factor;
128 unsigned chroma_height_blocks = mcu_height_blocks * dinfo.comp_info[1].v_samp_factor;
130 // TODO: Decode into a PBO.
131 frame->y.reset(new uint8_t[luma_width_blocks * luma_height_blocks * DCTSIZE2]);
132 frame->cb.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
133 frame->cr.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
134 frame->pitch_y = luma_width_blocks * DCTSIZE;
135 frame->pitch_chroma = chroma_width_blocks * DCTSIZE;
137 JSAMPROW yptr[v_mcu_size], cbptr[v_mcu_size], crptr[v_mcu_size];
138 JSAMPARRAY data[3] = { yptr, cbptr, crptr };
139 for (unsigned y = 0; y < mcu_height_blocks; ++y) {
140 // NOTE: The last elements of cbptr/crptr will be unused for vertically subsampled chroma.
141 for (unsigned yy = 0; yy < v_mcu_size; ++yy) {
142 yptr[yy] = frame->y.get() + (y * DCTSIZE * dinfo.max_v_samp_factor + yy) * frame->pitch_y;
143 cbptr[yy] = frame->cb.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
144 crptr[yy] = frame->cr.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
147 jpeg_read_raw_data(&dinfo, data, v_mcu_size);
150 (void)jpeg_finish_decompress(&dinfo);
158 // Assumes cache_mu is held.
159 vector<size_t> lru_timestamps;
160 for (const auto &key_and_value : cache) {
161 lru_timestamps.push_back(key_and_value.second.last_used);
164 size_t cutoff_point = CACHE_SIZE / 10; // Prune away the 10% oldest ones.
165 nth_element(lru_timestamps.begin(), lru_timestamps.begin() + cutoff_point, lru_timestamps.end());
166 size_t must_be_used_after = lru_timestamps[cutoff_point];
167 for (auto it = cache.begin(); it != cache.end(); ) {
168 if (it->second.last_used < must_be_used_after) {
169 it = cache.erase(it);
176 shared_ptr<Frame> decode_jpeg_with_cache(JPEGID id, CacheMissBehavior cache_miss_behavior, bool *did_decode)
180 unique_lock<mutex> lock(cache_mu);
181 auto it = cache.find(id);
182 if (it != cache.end()) {
183 it->second.last_used = event_counter++;
184 return it->second.frame;
188 if (cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE) {
192 assert(!id.interpolated);
194 shared_ptr<Frame> frame = decode_jpeg(filename_for_frame(id.stream_idx, id.pts));
196 unique_lock<mutex> lock(cache_mu);
197 cache[id] = LRUFrame{ frame, event_counter++ };
199 if (cache.size() > CACHE_SIZE) {
205 void jpeg_decoder_thread_func()
207 size_t num_decoded = 0, num_dropped = 0;
209 pthread_setname_np(pthread_self(), "JPEGDecoder");
210 while (!should_quit.load()) {
211 PendingDecode decode;
212 CacheMissBehavior cache_miss_behavior = DECODE_IF_NOT_IN_CACHE;
214 unique_lock<mutex> lock(cache_mu); // TODO: Perhaps under another lock?
215 any_pending_decodes.wait(lock, [] {
216 return !pending_decodes.empty() || should_quit.load();
218 if (should_quit.load())
220 decode = pending_decodes.front();
221 pending_decodes.pop_front();
223 size_t num_pending = 0;
224 for (const PendingDecode &other_decode : pending_decodes) {
225 if (other_decode.destination == decode.destination) {
229 if (num_pending > 3) {
230 cache_miss_behavior = RETURN_NULLPTR_IF_NOT_IN_CACHE;
234 shared_ptr<Frame> primary_frame, secondary_frame;
236 for (int subframe_idx = 0; subframe_idx < 2; ++subframe_idx) {
237 const JPEGID &id = (subframe_idx == 0 ? decode.primary : decode.secondary);
238 if (id.stream_idx == (unsigned)-1) {
239 // No secondary frame.
244 shared_ptr<Frame> frame;
245 if (id.interpolated) {
246 // Interpolated frames are never decoded by us,
247 // put directly into the cache from VideoStream.
248 unique_lock<mutex> lock(cache_mu);
249 cache_updated.wait(lock, [id] {
250 return cache.count(id) != 0 || should_quit.load();
252 if (should_quit.load())
254 found_in_cache = true; // Don't count it as a decode.
256 auto it = cache.find(id);
257 assert(it != cache.end());
259 it->second.last_used = event_counter++;
260 frame = it->second.frame;
261 if (frame == nullptr) {
262 // We inserted a nullptr as signal that the frame was never
263 // interpolated and that we should stop waiting.
264 // But don't let it linger in the cache anymore.
268 frame = decode_jpeg_with_cache(id, cache_miss_behavior, &found_in_cache);
271 if (frame == nullptr) {
272 assert(id.interpolated || cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE);
277 if (!found_in_cache) {
279 if (num_decoded % 1000 == 0) {
280 fprintf(stderr, "Decoded %zu images, dropped %zu (%.2f%% dropped)\n",
281 num_decoded, num_dropped, (100.0 * num_dropped) / (num_decoded + num_dropped));
284 if (subframe_idx == 0) {
285 primary_frame = move(frame);
287 secondary_frame = move(frame);
295 // TODO: Could we get jitter between non-interpolated and interpolated frames here?
296 decode.destination->setDecodedFrame(primary_frame, secondary_frame, decode.fade_alpha);
300 void JPEGFrameView::shutdown()
302 any_pending_decodes.notify_all();
303 jpeg_decoder_thread.join();
306 JPEGFrameView::JPEGFrameView(QWidget *parent)
307 : QGLWidget(parent, global_share_widget)
311 void JPEGFrameView::setFrame(unsigned stream_idx, int64_t pts, bool interpolated, int secondary_stream_idx, int64_t secondary_pts, float fade_alpha)
313 current_stream_idx = stream_idx; // TODO: Does this interact with fades?
315 unique_lock<mutex> lock(cache_mu);
316 PendingDecode decode;
317 if (interpolated && secondary_stream_idx != -1) {
318 // The frame will already be faded for us, so ask for only one; we shouldn't fade it against anything.
319 decode.primary = create_jpegid_for_interpolated_fade(stream_idx, pts, secondary_stream_idx, secondary_pts);
320 decode.secondary = JPEGID{ (unsigned)-1, -1, /*interpolated=*/false };
322 decode.primary = JPEGID{ stream_idx, pts, interpolated };
323 decode.secondary = JPEGID{ (unsigned)secondary_stream_idx, secondary_pts, /*interpolated=*/false };
325 decode.fade_alpha = fade_alpha;
326 decode.destination = this;
327 pending_decodes.push_back(decode);
328 any_pending_decodes.notify_all();
331 void JPEGFrameView::insert_interpolated_frame(JPEGID id, shared_ptr<Frame> frame)
333 // We rely on the frame not being evicted from the cache before
334 // jpeg_decoder_thread() sees it and can display it (otherwise,
335 // that thread would hang). With a default cache of 1000 elements,
336 // that would sound like a reasonable assumption.
337 unique_lock<mutex> lock(cache_mu);
338 cache[id] = LRUFrame{ std::move(frame), event_counter++ };
339 cache_updated.notify_all();
342 ResourcePool *resource_pool = nullptr;
344 void JPEGFrameView::initializeGL()
347 glDisable(GL_DEPTH_TEST);
350 static once_flag once;
352 resource_pool = new ResourcePool;
353 jpeg_decoder_thread = std::thread(jpeg_decoder_thread_func);
356 ycbcr_converter.reset(new YCbCrConverter(YCbCrConverter::OUTPUT_TO_RGBA, resource_pool));
358 ImageFormat inout_format;
359 inout_format.color_space = COLORSPACE_sRGB;
360 inout_format.gamma_curve = GAMMA_sRGB;
362 overlay_chain.reset(new EffectChain(overlay_base_width, overlay_base_height, resource_pool));
363 overlay_input = (movit::FlatInput *)overlay_chain->add_input(new FlatInput(inout_format, FORMAT_GRAYSCALE, GL_UNSIGNED_BYTE, overlay_base_width, overlay_base_height));
365 overlay_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
366 overlay_chain->finalize();
369 void JPEGFrameView::resizeGL(int width, int height)
372 glViewport(0, 0, width, height);
375 // Save these, as width() and height() will lie with DPI scaling.
380 void JPEGFrameView::paintGL()
382 glViewport(0, 0, gl_width, gl_height);
383 if (current_frame == nullptr) {
384 glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
385 glClear(GL_COLOR_BUFFER_BIT);
390 current_chain->render_to_screen();
392 if (overlay_image != nullptr) {
393 if (overlay_input_needs_refresh) {
394 overlay_input->set_width(overlay_width);
395 overlay_input->set_height(overlay_height);
396 overlay_input->set_pixel_data(overlay_image->bits());
398 glViewport(gl_width - overlay_width, 0, overlay_width, overlay_height);
399 overlay_chain->render_to_screen();
407 void JPEGFrameView::setDecodedFrame(shared_ptr<Frame> frame, shared_ptr<Frame> secondary_frame, float fade_alpha)
409 post_to_main_thread([this, frame, secondary_frame, fade_alpha] {
410 current_frame = frame;
411 current_secondary_frame = secondary_frame;
413 if (secondary_frame != nullptr) {
414 current_chain = ycbcr_converter->prepare_chain_for_fade(frame, secondary_frame, fade_alpha);
416 current_chain = ycbcr_converter->prepare_chain_for_conversion(frame);
422 void JPEGFrameView::mousePressEvent(QMouseEvent *event)
424 if (event->type() == QEvent::MouseButtonPress && event->button() == Qt::LeftButton) {
429 void JPEGFrameView::set_overlay(const string &text)
432 overlay_image.reset();
436 float dpr = QGuiApplication::primaryScreen()->devicePixelRatio();
437 overlay_width = lrint(overlay_base_width * dpr);
438 overlay_height = lrint(overlay_base_height * dpr);
440 overlay_image.reset(new QImage(overlay_width, overlay_height, QImage::Format_Grayscale8));
441 overlay_image->setDevicePixelRatio(dpr);
442 overlay_image->fill(0);
443 QPainter painter(overlay_image.get());
445 painter.setPen(Qt::white);
446 QFont font = painter.font();
447 font.setPointSize(12);
448 painter.setFont(font);
450 painter.drawText(QRectF(0, 0, overlay_base_width, overlay_base_height), Qt::AlignCenter, QString::fromStdString(text));
452 // Don't refresh immediately; we might not have an OpenGL context here.
453 overlay_input_needs_refresh = true;