]> git.sesse.net Git - nageru/blob - jpeg_frame_view.cpp
Properly release the flow texture; saves 1 ms (!) on FBO creation.
[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 <movit/resource_pool.h>
14 #include <movit/init.h>
15 #include <movit/util.h>
16
17 #include "defs.h"
18 #include "post_to_main_thread.h"
19
20 using namespace movit;
21 using namespace std;
22
23 string filename_for_frame(unsigned stream_idx, int64_t pts);
24
25 struct JPEGID {
26         unsigned stream_idx;
27         int64_t pts;
28 };
29 bool operator< (const JPEGID &a, const JPEGID &b) {
30         return make_pair(a.stream_idx, a.pts) < make_pair(b.stream_idx, b.pts);
31 }
32
33 struct LRUFrame {
34         shared_ptr<Frame> frame;
35         size_t last_used;
36 };
37
38 mutex cache_mu;
39 map<JPEGID, LRUFrame> cache;  // Under cache_mu.
40 condition_variable any_pending_decodes;
41 deque<pair<JPEGID, JPEGFrameView *>> pending_decodes;  // Under cache_mu.
42 atomic<size_t> event_counter{0};
43 extern QGLWidget *global_share_widget;
44
45 // TODO: Decode using VA-API if available.
46 shared_ptr<Frame> decode_jpeg(const string &filename)
47 {
48         shared_ptr<Frame> frame(new Frame);
49
50         jpeg_decompress_struct dinfo;
51         jpeg_error_mgr jerr;
52         dinfo.err = jpeg_std_error(&jerr);
53         jpeg_create_decompress(&dinfo);
54
55         FILE *fp = fopen(filename.c_str(), "rb");
56         if (fp == nullptr) {
57                 perror(filename.c_str());
58                 exit(1);
59         }
60         jpeg_stdio_src(&dinfo, fp);
61
62         jpeg_read_header(&dinfo, true);
63
64         if (dinfo.num_components != 3) {
65                 fprintf(stderr, "Not a color JPEG. (%d components, Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
66                         dinfo.num_components,
67                         dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
68                         dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
69                         dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
70                 exit(1);
71         }
72         if (dinfo.comp_info[0].h_samp_factor != dinfo.max_h_samp_factor ||
73             dinfo.comp_info[0].v_samp_factor != dinfo.max_v_samp_factor ||  // Y' must not be subsampled.
74             dinfo.comp_info[1].h_samp_factor != dinfo.comp_info[2].h_samp_factor ||
75             dinfo.comp_info[1].v_samp_factor != dinfo.comp_info[2].v_samp_factor ||  // Cb and Cr must be identically subsampled.
76             (dinfo.max_h_samp_factor % dinfo.comp_info[1].h_samp_factor) != 0 ||
77             (dinfo.max_v_samp_factor % dinfo.comp_info[1].v_samp_factor) != 0) {  // No 2:3 subsampling or other weirdness.
78                 fprintf(stderr, "Unsupported subsampling scheme. (Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
79                         dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
80                         dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
81                         dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
82                 exit(1);
83         }
84         dinfo.raw_data_out = true;
85
86         jpeg_start_decompress(&dinfo);
87
88         frame->width = dinfo.output_width;
89         frame->height = dinfo.output_height;
90         frame->chroma_subsampling_x = dinfo.max_h_samp_factor / dinfo.comp_info[1].h_samp_factor;
91         frame->chroma_subsampling_y = dinfo.max_v_samp_factor / dinfo.comp_info[1].v_samp_factor;
92
93         unsigned h_mcu_size = DCTSIZE * dinfo.max_h_samp_factor;
94         unsigned v_mcu_size = DCTSIZE * dinfo.max_v_samp_factor;
95         unsigned mcu_width_blocks = (dinfo.output_width + h_mcu_size - 1) / h_mcu_size;
96         unsigned mcu_height_blocks = (dinfo.output_height + v_mcu_size - 1) / v_mcu_size;
97
98         unsigned luma_width_blocks = mcu_width_blocks * dinfo.comp_info[0].h_samp_factor;
99         unsigned chroma_width_blocks = mcu_width_blocks * dinfo.comp_info[1].h_samp_factor;
100         unsigned luma_height_blocks = mcu_height_blocks * dinfo.comp_info[0].v_samp_factor;
101         unsigned chroma_height_blocks = mcu_height_blocks * dinfo.comp_info[1].v_samp_factor;
102
103         // TODO: Decode into a PBO.
104         frame->y.reset(new uint8_t[luma_width_blocks * luma_height_blocks * DCTSIZE2]);
105         frame->cb.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
106         frame->cr.reset(new uint8_t[chroma_width_blocks * chroma_height_blocks * DCTSIZE2]);
107         frame->pitch_y = luma_width_blocks * DCTSIZE;
108         frame->pitch_chroma = chroma_width_blocks * DCTSIZE;
109
110         JSAMPROW yptr[v_mcu_size], cbptr[v_mcu_size], crptr[v_mcu_size];
111         JSAMPARRAY data[3] = { yptr, cbptr, crptr };
112         for (unsigned y = 0; y < mcu_height_blocks; ++y) {
113                 // NOTE: The last elements of cbptr/crptr will be unused for vertically subsampled chroma.
114                 for (unsigned yy = 0; yy < v_mcu_size; ++yy) {
115                         yptr[yy] = frame->y.get() + (y * DCTSIZE * dinfo.max_v_samp_factor + yy) * frame->pitch_y;
116                         cbptr[yy] = frame->cb.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
117                         crptr[yy] = frame->cr.get() + (y * DCTSIZE * dinfo.comp_info[1].v_samp_factor + yy) * frame->pitch_chroma;
118                 }
119
120                 jpeg_read_raw_data(&dinfo, data, v_mcu_size);
121         }
122
123         (void) jpeg_finish_decompress(&dinfo);
124         jpeg_destroy_decompress(&dinfo);
125         fclose(fp);
126
127         return frame;
128 }
129
130 void prune_cache()
131 {
132         // Assumes cache_mu is held.
133         vector<size_t> lru_timestamps;
134         for (const auto &key_and_value : cache) {
135                 lru_timestamps.push_back(key_and_value.second.last_used);
136         }
137
138         size_t cutoff_point = CACHE_SIZE / 10;  // Prune away the 10% oldest ones.
139         nth_element(lru_timestamps.begin(), lru_timestamps.begin() + cutoff_point, lru_timestamps.end());
140         size_t must_be_used_after = lru_timestamps[cutoff_point];
141         for (auto it = cache.begin(); it != cache.end(); ) {
142                 if (it->second.last_used < must_be_used_after) {
143                         it = cache.erase(it);
144                 } else {
145                         ++it;
146                 }
147         }
148 }
149
150 void jpeg_decoder_thread()
151 {
152         size_t num_decoded = 0, num_dropped = 0;
153
154         pthread_setname_np(pthread_self(), "JPEGDecoder");
155         for ( ;; ) {
156                 JPEGID id;
157                 JPEGFrameView *dest;
158                 shared_ptr<Frame> frame;
159                 {
160                         unique_lock<mutex> lock(cache_mu);
161                         any_pending_decodes.wait(lock, [] {
162                                 return !pending_decodes.empty();
163                         });
164                         id = pending_decodes.front().first;
165                         dest = pending_decodes.front().second;
166                         pending_decodes.pop_front();
167
168                         auto it = cache.find(id);
169                         if (it != cache.end()) {
170                                 frame = it->second.frame;
171                                 it->second.last_used = event_counter++;
172                         }
173                 }
174
175                 if (frame == nullptr) {
176                         // Not found in the cache, so we need to do a decode or drop the request.
177                         // Prune the queue if there are too many pending for this destination.
178                         // TODO: Could we get starvation here?
179                         size_t num_pending = 0;
180                         for (const pair<JPEGID, JPEGFrameView *> &decode : pending_decodes) {
181                                 if (decode.second == dest) {
182                                         ++num_pending;
183                                 }
184                         }
185                         if (num_pending > 3) {
186                                 ++num_dropped;
187                                 continue;
188                         }
189
190                         frame = decode_jpeg(filename_for_frame(id.stream_idx, id.pts));
191
192                         unique_lock<mutex> lock(cache_mu);
193                         cache[id] = LRUFrame{ frame, event_counter++ };
194
195                         if (cache.size() > CACHE_SIZE) {
196                                 prune_cache();
197                         }
198                         ++num_decoded;
199                         if (num_decoded % 1000 == 0) {
200                                 fprintf(stderr, "Decoded %zu images, dropped %zu (%.2f%% dropped)\n",
201                                         num_decoded, num_dropped, (100.0 * num_dropped) / (num_decoded + num_dropped));
202                         }
203                 }
204
205                 dest->setDecodedFrame(frame);
206         }
207 }
208
209 JPEGFrameView::JPEGFrameView(QWidget *parent)
210         : QGLWidget(parent, global_share_widget) {
211 }
212
213 void JPEGFrameView::update_frame()
214 {
215         unique_lock<mutex> lock(cache_mu);
216         pending_decodes.emplace_back(JPEGID{ stream_idx, pts }, this);
217         any_pending_decodes.notify_all();
218 }
219
220 ResourcePool *resource_pool = nullptr;
221
222 void JPEGFrameView::initializeGL()
223 {
224         glDisable(GL_BLEND);
225         glDisable(GL_DEPTH_TEST);
226         glDepthMask(GL_FALSE);
227         check_error();
228
229         static once_flag once;
230         call_once(once, [] {
231                 CHECK(init_movit(MOVIT_SHADER_DIR, MOVIT_DEBUG_OFF));
232                 resource_pool = new ResourcePool;
233
234                 std::thread(&jpeg_decoder_thread).detach();
235         });
236
237         chain.reset(new EffectChain(1280, 720, resource_pool));
238         ImageFormat image_format;
239         image_format.color_space = COLORSPACE_sRGB;
240         image_format.gamma_curve = GAMMA_sRGB;
241         ycbcr_format.luma_coefficients = YCBCR_REC_709;
242         ycbcr_format.full_range = false;
243         ycbcr_format.num_levels = 256;
244         ycbcr_format.chroma_subsampling_x = 2;
245         ycbcr_format.chroma_subsampling_y = 1;
246         ycbcr_format.cb_x_position = 0.0f;  // H.264 -- _not_ JPEG, even though our input is MJPEG-encoded
247         ycbcr_format.cb_y_position = 0.5f;  // Irrelevant.
248         ycbcr_format.cr_x_position = 0.0f;
249         ycbcr_format.cr_y_position = 0.5f;
250         ycbcr_input = (movit::YCbCrInput *)chain->add_input(new YCbCrInput(image_format, ycbcr_format, 1280, 720));
251
252         ImageFormat inout_format;
253         inout_format.color_space = COLORSPACE_sRGB;
254         inout_format.gamma_curve = GAMMA_sRGB;
255
256         check_error();
257         chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
258         check_error();
259         chain->set_dither_bits(8);
260         check_error();
261         chain->finalize();
262         check_error();
263 }
264
265 void JPEGFrameView::resizeGL(int width, int height)
266 {
267         check_error();
268         glViewport(0, 0, width, height);
269         check_error();
270 }
271
272 void JPEGFrameView::paintGL()
273 {
274         if (current_frame == nullptr) {
275                 glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
276                 glClear(GL_COLOR_BUFFER_BIT);
277                 return;
278         }
279
280         check_error();
281         chain->render_to_screen();
282 }
283
284 void JPEGFrameView::setDecodedFrame(std::shared_ptr<Frame> frame)
285 {
286         post_to_main_thread([this, frame] {
287                 current_frame = frame;
288                 ycbcr_format.chroma_subsampling_x = frame->chroma_subsampling_x;
289                 ycbcr_format.chroma_subsampling_y = frame->chroma_subsampling_y;
290                 ycbcr_input->change_ycbcr_format(ycbcr_format);
291                 ycbcr_input->set_width(frame->width);
292                 ycbcr_input->set_height(frame->height);
293                 ycbcr_input->set_pixel_data(0, frame->y.get());
294                 ycbcr_input->set_pixel_data(1, frame->cb.get());
295                 ycbcr_input->set_pixel_data(2, frame->cr.get());
296                 ycbcr_input->set_pitch(0, frame->pitch_y);
297                 ycbcr_input->set_pitch(1, frame->pitch_chroma);
298                 ycbcr_input->set_pitch(2, frame->pitch_chroma);
299                 update();
300         });
301 }