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