]> git.sesse.net Git - nageru/blob - jpeg_frame_view.cpp
Add some 1-4 overlays on the previews.
[nageru] / jpeg_frame_view.cpp
1 #include "jpeg_frame_view.h"
2
3 #include <jpeglib.h>
4 #include <stdint.h>
5 #include <unistd.h>
6
7 #include <atomic>
8 #include <condition_variable>
9 #include <deque>
10 #include <mutex>
11 #include <thread>
12 #include <utility>
13
14 #include <QMouseEvent>
15
16 #include <movit/resource_pool.h>
17 #include <movit/init.h>
18 #include <movit/util.h>
19
20 #include "defs.h"
21 #include "post_to_main_thread.h"
22 #include "video_stream.h"
23
24 using namespace movit;
25 using namespace std;
26
27 // Just an arbitrary order for std::map.
28 struct JPEGIDLexicalOrder
29 {
30         bool operator() (const JPEGID &a, const JPEGID &b) const
31         {
32                 if (a.stream_idx != b.stream_idx)
33                         return a.stream_idx < b.stream_idx;
34                 if (a.pts != b.pts)
35                         return a.pts < b.pts;
36                 return a.interpolated < b.interpolated;
37         }
38 };
39
40 struct LRUFrame {
41         shared_ptr<Frame> frame;
42         size_t last_used;
43 };
44
45 mutex cache_mu;
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;
51
52 // TODO: Decode using VA-API if available.
53 shared_ptr<Frame> decode_jpeg(const string &filename)
54 {
55         shared_ptr<Frame> frame(new Frame);
56
57         jpeg_decompress_struct dinfo;
58         jpeg_error_mgr jerr;
59         dinfo.err = jpeg_std_error(&jerr);
60         jpeg_create_decompress(&dinfo);
61
62         FILE *fp = fopen(filename.c_str(), "rb");
63         if (fp == nullptr) {
64                 perror(filename.c_str());
65                 exit(1);
66         }
67         jpeg_stdio_src(&dinfo, fp);
68
69         jpeg_read_header(&dinfo, true);
70
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",
73                         dinfo.num_components,
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);
77                 exit(1);
78         }
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);
89                 exit(1);
90         }
91         dinfo.raw_data_out = true;
92
93         jpeg_start_decompress(&dinfo);
94
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;
99
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;
104
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;
109
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;
116
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;
125                 }
126
127                 jpeg_read_raw_data(&dinfo, data, v_mcu_size);
128         }
129
130         (void) jpeg_finish_decompress(&dinfo);
131         jpeg_destroy_decompress(&dinfo);
132         fclose(fp);
133
134         return frame;
135 }
136
137 void prune_cache()
138 {
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);
143         }
144
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);
151                 } else {
152                         ++it;
153                 }
154         }
155 }
156
157 shared_ptr<Frame> decode_jpeg_with_cache(JPEGID id, CacheMissBehavior cache_miss_behavior, bool *did_decode)
158 {
159         *did_decode = false;
160         {
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;
166                 }
167         }
168
169         if (cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE) {
170                 return nullptr;
171         }
172
173         assert(!id.interpolated);
174         *did_decode = true;
175         shared_ptr<Frame> frame = decode_jpeg(filename_for_frame(id.stream_idx, id.pts));
176
177         unique_lock<mutex> lock(cache_mu);
178         cache[id] = LRUFrame{ frame, event_counter++ };
179
180         if (cache.size() > CACHE_SIZE) {
181                 prune_cache();
182         }
183         return frame;
184 }
185
186 void jpeg_decoder_thread()
187 {
188         size_t num_decoded = 0, num_dropped = 0;
189
190         pthread_setname_np(pthread_self(), "JPEGDecoder");
191         for ( ;; ) {
192                 JPEGID id;
193                 JPEGFrameView *dest;
194                 CacheMissBehavior cache_miss_behavior = DECODE_IF_NOT_IN_CACHE;
195                 {
196                         unique_lock<mutex> lock(cache_mu);  // TODO: Perhaps under another lock?
197                         any_pending_decodes.wait(lock, [] {
198                                 return !pending_decodes.empty();
199                         });
200                         id = pending_decodes.front().first;
201                         dest = pending_decodes.front().second;
202                         pending_decodes.pop_front();
203
204                         size_t num_pending = 0;
205                         for (const pair<JPEGID, JPEGFrameView *> &decode : pending_decodes) {
206                                 if (decode.second == dest) {
207                                         ++num_pending;
208                                 }
209                         }
210                         if (num_pending > 3) {
211                                 cache_miss_behavior = RETURN_NULLPTR_IF_NOT_IN_CACHE;
212                         }
213                 }
214
215                 bool found_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;
223                         });
224                         found_in_cache = true;  // Don't count it as a decode.
225
226                         auto it = cache.find(id);
227                         assert(it != cache.end());
228
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.
235                                 cache.erase(it);
236                         }
237                 } else {
238                         frame = decode_jpeg_with_cache(id, cache_miss_behavior, &found_in_cache);
239                 }
240
241                 if (frame == nullptr) {
242                         assert(id.interpolated || cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE);
243                         ++num_dropped;
244                         continue;
245                 }
246
247                 if (!found_in_cache) {
248                         ++num_decoded;
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));
252                         }
253                 }
254
255                 // TODO: Could we get jitter between non-interpolated and interpolated frames here?
256                 dest->setDecodedFrame(frame);
257         }
258 }
259
260 JPEGFrameView::JPEGFrameView(QWidget *parent)
261         : QGLWidget(parent, global_share_widget) {
262 }
263
264 void JPEGFrameView::setFrame(unsigned stream_idx, int64_t pts, bool interpolated)
265 {
266         current_stream_idx = stream_idx;
267
268         unique_lock<mutex> lock(cache_mu);
269         pending_decodes.emplace_back(JPEGID{ stream_idx, pts, interpolated }, this);
270         any_pending_decodes.notify_all();
271 }
272
273 void JPEGFrameView::insert_interpolated_frame(unsigned stream_idx, int64_t pts, shared_ptr<Frame> frame)
274 {
275         JPEGID id{ stream_idx, pts, true };
276
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();
284 }
285
286 ResourcePool *resource_pool = nullptr;
287
288 void JPEGFrameView::initializeGL()
289 {
290         glDisable(GL_BLEND);
291         glDisable(GL_DEPTH_TEST);
292         check_error();
293
294         static once_flag once;
295         call_once(once, [] {
296                 resource_pool = new ResourcePool;
297                 std::thread(&jpeg_decoder_thread).detach();
298         });
299
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));
314
315         ImageFormat inout_format;
316         inout_format.color_space = COLORSPACE_sRGB;
317         inout_format.gamma_curve = GAMMA_sRGB;
318
319         check_error();
320         chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
321         check_error();
322         chain->set_dither_bits(8);
323         check_error();
324         chain->finalize();
325         check_error();
326
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));
329
330         overlay_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
331         overlay_chain->finalize();
332 }
333
334 void JPEGFrameView::resizeGL(int width, int height)
335 {
336         check_error();
337         glViewport(0, 0, width, height);
338         check_error();
339 }
340
341 void JPEGFrameView::paintGL()
342 {
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);
347                 return;
348         }
349
350         check_error();
351         chain->render_to_screen();
352
353         if (overlay_image != nullptr) {
354                 if (overlay_input_needs_refresh) {
355                         overlay_input->set_pixel_data(overlay_image->bits());
356                 }
357                 glViewport(width() - overlay_width, 0, overlay_width, overlay_height);
358                 overlay_chain->render_to_screen();
359         }
360 }
361
362 void JPEGFrameView::setDecodedFrame(std::shared_ptr<Frame> frame)
363 {
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);
377                 update();
378         });
379 }
380
381 void JPEGFrameView::mousePressEvent(QMouseEvent *event)
382 {
383         if (event->type() == QEvent::MouseButtonPress && event->button() == Qt::LeftButton) {
384                 emit clicked();
385         }
386 }
387
388 void JPEGFrameView::set_overlay(const string &text)
389 {
390         if (text.empty()) {
391                 overlay_image.reset();
392                 return;
393         }
394
395         overlay_image.reset(new QImage(overlay_width, overlay_height, QImage::Format_Grayscale8));
396         overlay_image->fill(0);
397         QPainter painter(overlay_image.get());
398
399         painter.setPen(Qt::white);
400         QFont font = painter.font();
401         font.setPointSize(12);
402         painter.setFont(font);
403
404         painter.drawText(QRectF(0, 0, overlay_width, overlay_height), Qt::AlignCenter, QString::fromStdString(text));
405
406         // Don't refresh immediately; we might not have an OpenGL context here.
407         overlay_input_needs_refresh = true;
408 }