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