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