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;
32 // Just an arbitrary order for std::map.
33 struct JPEGIDLexicalOrder
35 bool operator() (const JPEGID &a, const JPEGID &b) const
37 if (a.stream_idx != b.stream_idx)
38 return a.stream_idx < b.stream_idx;
43 inline size_t frame_size(const Frame &frame)
45 size_t y_size = frame.width * frame.height;
46 size_t cbcr_size = y_size / frame.chroma_subsampling_x / frame.chroma_subsampling_y;
47 return y_size + cbcr_size * 2;
51 shared_ptr<Frame> frame;
55 struct PendingDecode {
56 JPEGFrameView *destination;
58 // For actual decodes (only if frame below is nullptr).
59 JPEGID primary, secondary;
60 float fade_alpha; // Irrelevant if secondary.stream_idx == -1.
62 // Already-decoded frames are also sent through PendingDecode,
63 // so that they get drawn in the right order. If frame is nullptr,
64 // it's a real decode.
65 shared_ptr<Frame> frame;
70 thread JPEGFrameView::jpeg_decoder_thread;
72 map<JPEGID, LRUFrame, JPEGIDLexicalOrder> cache; // Under cache_mu.
73 size_t cache_bytes_used = 0; // Under cache_mu.
74 condition_variable any_pending_decodes;
75 deque<PendingDecode> pending_decodes; // Under cache_mu.
76 atomic<size_t> event_counter{0};
77 extern QGLWidget *global_share_widget;
78 extern atomic<bool> should_quit;
80 shared_ptr<Frame> decode_jpeg(const string &filename)
82 shared_ptr<Frame> frame;
83 if (vaapi_jpeg_decoding_usable) {
84 frame = decode_jpeg_vaapi(filename);
85 if (frame != nullptr) {
88 fprintf(stderr, "VA-API hardware decoding failed; falling back to software.\n");
91 frame.reset(new Frame);
93 jpeg_decompress_struct dinfo;
95 dinfo.err = jpeg_std_error(&jerr);
96 jpeg_create_decompress(&dinfo);
97 JPEGDestroyer destroy_dinfo(&dinfo);
99 FILE *fp = fopen(filename.c_str(), "rb");
101 perror(filename.c_str());
104 jpeg_stdio_src(&dinfo, fp);
106 jpeg_read_header(&dinfo, true);
108 if (dinfo.num_components != 3) {
109 fprintf(stderr, "Not a color JPEG. (%d components, Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
110 dinfo.num_components,
111 dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
112 dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
113 dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
116 if (dinfo.comp_info[0].h_samp_factor != dinfo.max_h_samp_factor ||
117 dinfo.comp_info[0].v_samp_factor != dinfo.max_v_samp_factor || // Y' must not be subsampled.
118 dinfo.comp_info[1].h_samp_factor != dinfo.comp_info[2].h_samp_factor ||
119 dinfo.comp_info[1].v_samp_factor != dinfo.comp_info[2].v_samp_factor || // Cb and Cr must be identically subsampled.
120 (dinfo.max_h_samp_factor % dinfo.comp_info[1].h_samp_factor) != 0 ||
121 (dinfo.max_v_samp_factor % dinfo.comp_info[1].v_samp_factor) != 0) { // No 2:3 subsampling or other weirdness.
122 fprintf(stderr, "Unsupported subsampling scheme. (Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
123 dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
124 dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
125 dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
128 dinfo.raw_data_out = true;
130 jpeg_start_decompress(&dinfo);
132 frame->width = dinfo.output_width;
133 frame->height = dinfo.output_height;
134 frame->chroma_subsampling_x = dinfo.max_h_samp_factor / dinfo.comp_info[1].h_samp_factor;
135 frame->chroma_subsampling_y = dinfo.max_v_samp_factor / dinfo.comp_info[1].v_samp_factor;
137 unsigned h_mcu_size = DCTSIZE * dinfo.max_h_samp_factor;
138 unsigned v_mcu_size = DCTSIZE * dinfo.max_v_samp_factor;
139 unsigned mcu_width_blocks = (dinfo.output_width + h_mcu_size - 1) / h_mcu_size;
140 unsigned mcu_height_blocks = (dinfo.output_height + v_mcu_size - 1) / v_mcu_size;
142 unsigned luma_width_blocks = mcu_width_blocks * dinfo.comp_info[0].h_samp_factor;
143 unsigned chroma_width_blocks = mcu_width_blocks * dinfo.comp_info[1].h_samp_factor;
144 unsigned luma_height_blocks = mcu_height_blocks * dinfo.comp_info[0].v_samp_factor;
145 unsigned chroma_height_blocks = mcu_height_blocks * dinfo.comp_info[1].v_samp_factor;
147 // TODO: Decode into a PBO.
148 frame->y.reset(new uint8_t[luma_width_blocks * luma_height_blocks * DCTSIZE2]);
149 frame->cb.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
150 frame->cr.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
151 frame->pitch_y = luma_width_blocks * DCTSIZE;
152 frame->pitch_chroma = chroma_width_blocks * DCTSIZE;
154 JSAMPROW yptr[v_mcu_size], cbptr[v_mcu_size], crptr[v_mcu_size];
155 JSAMPARRAY data[3] = { yptr, cbptr, crptr };
156 for (unsigned y = 0; y < mcu_height_blocks; ++y) {
157 // NOTE: The last elements of cbptr/crptr will be unused for vertically subsampled chroma.
158 for (unsigned yy = 0; yy < v_mcu_size; ++yy) {
159 yptr[yy] = frame->y.get() + (y * DCTSIZE * dinfo.max_v_samp_factor + yy) * frame->pitch_y;
160 cbptr[yy] = frame->cb.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
161 crptr[yy] = frame->cr.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
164 jpeg_read_raw_data(&dinfo, data, v_mcu_size);
167 (void)jpeg_finish_decompress(&dinfo);
175 // Assumes cache_mu is held.
176 int64_t bytes_still_to_remove = cache_bytes_used - (size_t(CACHE_SIZE_MB) * 1024 * 1024) * 9 / 10;
177 if (bytes_still_to_remove <= 0) return;
179 vector<pair<size_t, size_t>> lru_timestamps_and_size;
180 for (const auto &key_and_value : cache) {
181 lru_timestamps_and_size.emplace_back(
182 key_and_value.second.last_used,
183 frame_size(*key_and_value.second.frame));
185 sort(lru_timestamps_and_size.begin(), lru_timestamps_and_size.end());
187 // Remove the oldest ones until we are below 90% of the cache used.
188 size_t lru_cutoff_point = 0;
189 for (const pair<size_t, size_t> &it : lru_timestamps_and_size) {
190 lru_cutoff_point = it.first;
191 bytes_still_to_remove -= it.second;
192 if (bytes_still_to_remove <= 0) break;
195 for (auto it = cache.begin(); it != cache.end(); ) {
196 if (it->second.last_used <= lru_cutoff_point) {
197 cache_bytes_used -= frame_size(*it->second.frame);
198 it = cache.erase(it);
205 shared_ptr<Frame> decode_jpeg_with_cache(JPEGID id, CacheMissBehavior cache_miss_behavior, bool *did_decode)
209 unique_lock<mutex> lock(cache_mu);
210 auto it = cache.find(id);
211 if (it != cache.end()) {
212 it->second.last_used = event_counter++;
213 return it->second.frame;
217 if (cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE) {
222 shared_ptr<Frame> frame = decode_jpeg(filename_for_frame(id.stream_idx, id.pts));
224 unique_lock<mutex> lock(cache_mu);
225 cache_bytes_used += frame_size(*frame);
226 cache[id] = LRUFrame{ frame, event_counter++ };
228 if (cache_bytes_used > size_t(CACHE_SIZE_MB) * 1024 * 1024) {
234 void jpeg_decoder_thread_func()
236 size_t num_decoded = 0, num_dropped = 0;
238 pthread_setname_np(pthread_self(), "JPEGDecoder");
239 while (!should_quit.load()) {
240 PendingDecode decode;
241 CacheMissBehavior cache_miss_behavior = DECODE_IF_NOT_IN_CACHE;
243 unique_lock<mutex> lock(cache_mu); // TODO: Perhaps under another lock?
244 any_pending_decodes.wait(lock, [] {
245 return !pending_decodes.empty() || should_quit.load();
247 if (should_quit.load())
249 decode = pending_decodes.front();
250 pending_decodes.pop_front();
252 size_t num_pending = 0;
253 for (const PendingDecode &other_decode : pending_decodes) {
254 if (other_decode.destination == decode.destination) {
258 if (num_pending > 3) {
259 cache_miss_behavior = RETURN_NULLPTR_IF_NOT_IN_CACHE;
263 if (decode.frame != nullptr) {
264 // Already decoded, so just show it.
265 decode.destination->setDecodedFrame(decode.frame, nullptr, 1.0f);
269 shared_ptr<Frame> primary_frame, secondary_frame;
271 for (int subframe_idx = 0; subframe_idx < 2; ++subframe_idx) {
272 const JPEGID &id = (subframe_idx == 0 ? decode.primary : decode.secondary);
273 if (id.stream_idx == (unsigned)-1) {
274 // No secondary frame.
279 shared_ptr<Frame> frame = decode_jpeg_with_cache(id, cache_miss_behavior, &found_in_cache);
281 if (frame == nullptr) {
282 assert(cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE);
287 if (!found_in_cache) {
289 if (num_decoded % 1000 == 0) {
290 fprintf(stderr, "Decoded %zu images, dropped %zu (%.2f%% dropped)\n",
291 num_decoded, num_dropped, (100.0 * num_dropped) / (num_decoded + num_dropped));
294 if (subframe_idx == 0) {
295 primary_frame = move(frame);
297 secondary_frame = move(frame);
305 // TODO: Could we get jitter between non-interpolated and interpolated frames here?
306 decode.destination->setDecodedFrame(primary_frame, secondary_frame, decode.fade_alpha);
310 void JPEGFrameView::shutdown()
312 any_pending_decodes.notify_all();
313 jpeg_decoder_thread.join();
316 JPEGFrameView::JPEGFrameView(QWidget *parent)
317 : QGLWidget(parent, global_share_widget)
321 void JPEGFrameView::setFrame(unsigned stream_idx, int64_t pts, int secondary_stream_idx, int64_t secondary_pts, float fade_alpha)
323 if (secondary_stream_idx != -1) assert(secondary_pts != -1);
324 current_stream_idx = stream_idx; // TODO: Does this interact with fades?
326 unique_lock<mutex> lock(cache_mu);
327 PendingDecode decode;
328 decode.primary = JPEGID{ stream_idx, pts };
329 decode.secondary = JPEGID{ (unsigned)secondary_stream_idx, secondary_pts };
330 decode.fade_alpha = fade_alpha;
331 decode.destination = this;
332 pending_decodes.push_back(decode);
333 any_pending_decodes.notify_all();
336 void JPEGFrameView::setFrame(shared_ptr<Frame> frame)
338 unique_lock<mutex> lock(cache_mu);
339 PendingDecode decode;
340 decode.frame = std::move(frame);
341 decode.destination = this;
342 pending_decodes.push_back(decode);
343 any_pending_decodes.notify_all();
346 ResourcePool *resource_pool = nullptr;
348 void JPEGFrameView::initializeGL()
351 glDisable(GL_DEPTH_TEST);
354 static once_flag once;
356 resource_pool = new ResourcePool;
357 jpeg_decoder_thread = std::thread(jpeg_decoder_thread_func);
360 ycbcr_converter.reset(new YCbCrConverter(YCbCrConverter::OUTPUT_TO_RGBA, resource_pool));
362 ImageFormat inout_format;
363 inout_format.color_space = COLORSPACE_sRGB;
364 inout_format.gamma_curve = GAMMA_sRGB;
366 overlay_chain.reset(new EffectChain(overlay_base_width, overlay_base_height, resource_pool));
367 overlay_input = (movit::FlatInput *)overlay_chain->add_input(new FlatInput(inout_format, FORMAT_GRAYSCALE, GL_UNSIGNED_BYTE, overlay_base_width, overlay_base_height));
369 overlay_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
370 overlay_chain->finalize();
373 void JPEGFrameView::resizeGL(int width, int height)
376 glViewport(0, 0, width, height);
379 // Save these, as width() and height() will lie with DPI scaling.
384 void JPEGFrameView::paintGL()
386 glViewport(0, 0, gl_width, gl_height);
387 if (current_frame == nullptr) {
388 glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
389 glClear(GL_COLOR_BUFFER_BIT);
394 current_chain->render_to_screen();
396 if (overlay_image != nullptr) {
397 if (overlay_input_needs_refresh) {
398 overlay_input->set_width(overlay_width);
399 overlay_input->set_height(overlay_height);
400 overlay_input->set_pixel_data(overlay_image->bits());
402 glViewport(gl_width - overlay_width, 0, overlay_width, overlay_height);
403 overlay_chain->render_to_screen();
411 void JPEGFrameView::setDecodedFrame(shared_ptr<Frame> frame, shared_ptr<Frame> secondary_frame, float fade_alpha)
413 post_to_main_thread([this, frame, secondary_frame, fade_alpha] {
414 current_frame = frame;
415 current_secondary_frame = secondary_frame;
417 if (secondary_frame != nullptr) {
418 current_chain = ycbcr_converter->prepare_chain_for_fade(frame, secondary_frame, fade_alpha);
420 current_chain = ycbcr_converter->prepare_chain_for_conversion(frame);
426 void JPEGFrameView::mousePressEvent(QMouseEvent *event)
428 if (event->type() == QEvent::MouseButtonPress && event->button() == Qt::LeftButton) {
433 void JPEGFrameView::set_overlay(const string &text)
436 overlay_image.reset();
440 float dpr = QGuiApplication::primaryScreen()->devicePixelRatio();
441 overlay_width = lrint(overlay_base_width * dpr);
442 overlay_height = lrint(overlay_base_height * dpr);
444 overlay_image.reset(new QImage(overlay_width, overlay_height, QImage::Format_Grayscale8));
445 overlay_image->setDevicePixelRatio(dpr);
446 overlay_image->fill(0);
447 QPainter painter(overlay_image.get());
449 painter.setPen(Qt::white);
450 QFont font = painter.font();
451 font.setPointSize(12);
452 painter.setFont(font);
454 painter.drawText(QRectF(0, 0, overlay_base_width, overlay_base_height), Qt::AlignCenter, QString::fromStdString(text));
456 // Don't refresh immediately; we might not have an OpenGL context here.
457 overlay_input_needs_refresh = true;