]> git.sesse.net Git - nageru/blob - jpeg_frame_view.cpp
Make it possible to switch camera angles by clicking on the preview displays.
[nageru] / jpeg_frame_view.cpp
1 #include "jpeg_frame_view.h"
2
3 #include <jpeglib.h>
4 #include <stdint.h>
5
6 #include <atomic>
7 #include <condition_variable>
8 #include <deque>
9 #include <mutex>
10 #include <thread>
11 #include <utility>
12
13 #include <QMouseEvent>
14
15 #include <movit/resource_pool.h>
16 #include <movit/init.h>
17 #include <movit/util.h>
18
19 #include "defs.h"
20 #include "post_to_main_thread.h"
21 #include "video_stream.h"
22
23 using namespace movit;
24 using namespace std;
25
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);
28 }
29
30 struct LRUFrame {
31         shared_ptr<Frame> frame;
32         size_t last_used;
33 };
34
35 mutex cache_mu;
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;
41
42 // TODO: Decode using VA-API if available.
43 shared_ptr<Frame> decode_jpeg(const string &filename)
44 {
45         shared_ptr<Frame> frame(new Frame);
46
47         jpeg_decompress_struct dinfo;
48         jpeg_error_mgr jerr;
49         dinfo.err = jpeg_std_error(&jerr);
50         jpeg_create_decompress(&dinfo);
51
52         FILE *fp = fopen(filename.c_str(), "rb");
53         if (fp == nullptr) {
54                 perror(filename.c_str());
55                 exit(1);
56         }
57         jpeg_stdio_src(&dinfo, fp);
58
59         jpeg_read_header(&dinfo, true);
60
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",
63                         dinfo.num_components,
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);
67                 exit(1);
68         }
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);
79                 exit(1);
80         }
81         dinfo.raw_data_out = true;
82
83         jpeg_start_decompress(&dinfo);
84
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;
89
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;
94
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;
99
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;
106
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;
115                 }
116
117                 jpeg_read_raw_data(&dinfo, data, v_mcu_size);
118         }
119
120         (void) jpeg_finish_decompress(&dinfo);
121         jpeg_destroy_decompress(&dinfo);
122         fclose(fp);
123
124         return frame;
125 }
126
127 void prune_cache()
128 {
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);
133         }
134
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);
141                 } else {
142                         ++it;
143                 }
144         }
145 }
146
147 shared_ptr<Frame> decode_jpeg_with_cache(JPEGID id, CacheMissBehavior cache_miss_behavior, bool *did_decode)
148 {
149         *did_decode = false;
150         {
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;
156                 }
157         }
158
159         if (cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE) {
160                 return nullptr;
161         }
162
163         *did_decode = true;
164         shared_ptr<Frame> frame = decode_jpeg(filename_for_frame(id.stream_idx, id.pts));
165
166         unique_lock<mutex> lock(cache_mu);
167         cache[id] = LRUFrame{ frame, event_counter++ };
168
169         if (cache.size() > CACHE_SIZE) {
170                 prune_cache();
171         }
172         return frame;
173 }
174
175 void jpeg_decoder_thread()
176 {
177         size_t num_decoded = 0, num_dropped = 0;
178
179         pthread_setname_np(pthread_self(), "JPEGDecoder");
180         for ( ;; ) {
181                 JPEGID id;
182                 JPEGFrameView *dest;
183                 CacheMissBehavior cache_miss_behavior = DECODE_IF_NOT_IN_CACHE;
184                 {
185                         unique_lock<mutex> lock(cache_mu);  // TODO: Perhaps under another lock?
186                         any_pending_decodes.wait(lock, [] {
187                                 return !pending_decodes.empty();
188                         });
189                         id = pending_decodes.front().first;
190                         dest = pending_decodes.front().second;
191                         pending_decodes.pop_front();
192
193                         size_t num_pending = 0;
194                         for (const pair<JPEGID, JPEGFrameView *> &decode : pending_decodes) {
195                                 if (decode.second == dest) {
196                                         ++num_pending;
197                                 }
198                         }
199                         if (num_pending > 3) {
200                                 cache_miss_behavior = RETURN_NULLPTR_IF_NOT_IN_CACHE;
201                         }
202                 }
203
204                 bool found_in_cache;
205                 shared_ptr<Frame> frame = decode_jpeg_with_cache(id, cache_miss_behavior, &found_in_cache);
206
207                 if (frame == nullptr) {
208                         assert(cache_miss_behavior == RETURN_NULLPTR_IF_NOT_IN_CACHE);
209                         ++num_dropped;
210                         continue;
211                 }
212
213                 if (!found_in_cache) {
214                         ++num_decoded;
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));
218                         }
219                 }
220
221                 dest->setDecodedFrame(frame);
222         }
223 }
224
225 JPEGFrameView::JPEGFrameView(QWidget *parent)
226         : QGLWidget(parent, global_share_widget) {
227 }
228
229 void JPEGFrameView::update_frame()
230 {
231         unique_lock<mutex> lock(cache_mu);
232         pending_decodes.emplace_back(JPEGID{ stream_idx, pts }, this);
233         any_pending_decodes.notify_all();
234 }
235
236 ResourcePool *resource_pool = nullptr;
237
238 void JPEGFrameView::initializeGL()
239 {
240         glDisable(GL_BLEND);
241         glDisable(GL_DEPTH_TEST);
242         check_error();
243
244         static once_flag once;
245         call_once(once, [] {
246                 resource_pool = new ResourcePool;
247                 std::thread(&jpeg_decoder_thread).detach();
248         });
249
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));
264
265         ImageFormat inout_format;
266         inout_format.color_space = COLORSPACE_sRGB;
267         inout_format.gamma_curve = GAMMA_sRGB;
268
269         check_error();
270         chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
271         check_error();
272         chain->set_dither_bits(8);
273         check_error();
274         chain->finalize();
275         check_error();
276 }
277
278 void JPEGFrameView::resizeGL(int width, int height)
279 {
280         check_error();
281         glViewport(0, 0, width, height);
282         check_error();
283 }
284
285 void JPEGFrameView::paintGL()
286 {
287         if (current_frame == nullptr) {
288                 glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
289                 glClear(GL_COLOR_BUFFER_BIT);
290                 return;
291         }
292
293         check_error();
294         chain->render_to_screen();
295 }
296
297 void JPEGFrameView::setDecodedFrame(std::shared_ptr<Frame> frame)
298 {
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);
312                 update();
313         });
314 }
315
316 void JPEGFrameView::mousePressEvent(QMouseEvent *event)
317 {
318         if (event->type() == QEvent::MouseButtonPress && event->button() == Qt::LeftButton) {
319                 emit clicked();
320         }
321 }