]> git.sesse.net Git - nageru/blob - video_stream.cpp
Subsample chroma on the GPU instead of the CPU.
[nageru] / video_stream.cpp
1 #include "video_stream.h"
2
3 extern "C" {
4 #include <libavformat/avformat.h>
5 #include <libavformat/avio.h>
6 }
7
8 #include <jpeglib.h>
9 #include <unistd.h>
10
11 #include "chroma_subsampler.h"
12 #include "context.h"
13 #include "flow.h"
14 #include "httpd.h"
15 #include "jpeg_frame_view.h"
16 #include "movit/util.h"
17 #include "mux.h"
18 #include "player.h"
19 #include "util.h"
20
21 #include <epoxy/glx.h>
22
23 using namespace std;
24
25 extern HTTPD *global_httpd;
26
27 namespace {
28
29 string read_file(const string &filename)
30 {
31         FILE *fp = fopen(filename.c_str(), "rb");
32         if (fp == nullptr) {
33                 perror(filename.c_str());
34                 return "";
35         }
36
37         fseek(fp, 0, SEEK_END);
38         long len = ftell(fp);
39         rewind(fp);
40
41         string ret;
42         ret.resize(len);
43         fread(&ret[0], len, 1, fp);
44         fclose(fp);
45         return ret;
46 }
47
48 }  // namespace
49
50 struct VectorDestinationManager {
51         jpeg_destination_mgr pub;
52         std::vector<uint8_t> dest;
53
54         VectorDestinationManager()
55         {
56                 pub.init_destination = init_destination_thunk;
57                 pub.empty_output_buffer = empty_output_buffer_thunk;
58                 pub.term_destination = term_destination_thunk;
59         }
60
61         static void init_destination_thunk(j_compress_ptr ptr)
62         {
63                 ((VectorDestinationManager *)(ptr->dest))->init_destination();
64         }
65
66         inline void init_destination()
67         {
68                 make_room(0);
69         }
70
71         static boolean empty_output_buffer_thunk(j_compress_ptr ptr)
72         {
73                 return ((VectorDestinationManager *)(ptr->dest))->empty_output_buffer();
74         }
75
76         inline bool empty_output_buffer()
77         {
78                 make_room(dest.size());  // Should ignore pub.free_in_buffer!
79                 return true;
80         }
81
82         inline void make_room(size_t bytes_used)
83         {
84                 dest.resize(bytes_used + 4096);
85                 dest.resize(dest.capacity());
86                 pub.next_output_byte = dest.data() + bytes_used;
87                 pub.free_in_buffer = dest.size() - bytes_used;
88         }
89
90         static void term_destination_thunk(j_compress_ptr ptr)
91         {
92                 ((VectorDestinationManager *)(ptr->dest))->term_destination();
93         }
94
95         inline void term_destination()
96         {
97                 dest.resize(dest.size() - pub.free_in_buffer);
98         }
99 };
100 static_assert(std::is_standard_layout<VectorDestinationManager>::value, "");
101
102 vector<uint8_t> encode_jpeg(const uint8_t *y_data, const uint8_t *cb_data, const uint8_t *cr_data, unsigned width, unsigned height)
103 {
104         VectorDestinationManager dest;
105
106         jpeg_compress_struct cinfo;
107         jpeg_error_mgr jerr;
108         cinfo.err = jpeg_std_error(&jerr);
109         jpeg_create_compress(&cinfo);
110
111         cinfo.dest = (jpeg_destination_mgr *)&dest;
112         cinfo.input_components = 3;
113         cinfo.in_color_space = JCS_RGB;
114         jpeg_set_defaults(&cinfo);
115         constexpr int quality = 90;
116         jpeg_set_quality(&cinfo, quality, /*force_baseline=*/false);
117
118         cinfo.image_width = width;
119         cinfo.image_height = height;
120         cinfo.raw_data_in = true;
121         jpeg_set_colorspace(&cinfo, JCS_YCbCr);
122         cinfo.comp_info[0].h_samp_factor = 2;
123         cinfo.comp_info[0].v_samp_factor = 1;
124         cinfo.comp_info[1].h_samp_factor = 1;
125         cinfo.comp_info[1].v_samp_factor = 1;
126         cinfo.comp_info[2].h_samp_factor = 1;
127         cinfo.comp_info[2].v_samp_factor = 1;
128         cinfo.CCIR601_sampling = true;  // Seems to be mostly ignored by libjpeg, though.
129         jpeg_start_compress(&cinfo, true);
130
131         JSAMPROW yptr[8], cbptr[8], crptr[8];
132         JSAMPARRAY data[3] = { yptr, cbptr, crptr };
133         for (unsigned y = 0; y < height; y += 8) {
134                 for (unsigned yy = 0; yy < 8; ++yy) {
135                         yptr[yy] = const_cast<JSAMPROW>(&y_data[(height - y - yy - 1) * width]);
136                         cbptr[yy] = const_cast<JSAMPROW>(&cb_data[(height - y - yy - 1) * width/2]);
137                         crptr[yy] = const_cast<JSAMPROW>(&cr_data[(height - y - yy - 1) * width/2]);
138                 }
139
140                 jpeg_write_raw_data(&cinfo, data, /*num_lines=*/8);
141         }
142
143         jpeg_finish_compress(&cinfo);
144         jpeg_destroy_compress(&cinfo);
145
146         return move(dest.dest);
147 }
148
149 VideoStream::VideoStream()
150 {
151         using namespace movit;
152         // TODO: deduplicate code against JPEGFrameView?
153         ycbcr_convert_chain.reset(new EffectChain(1280, 720));
154         ImageFormat image_format;
155         image_format.color_space = COLORSPACE_sRGB;
156         image_format.gamma_curve = GAMMA_sRGB;
157         ycbcr_format.luma_coefficients = YCBCR_REC_709;
158         ycbcr_format.full_range = true;  // JPEG.
159         ycbcr_format.num_levels = 256;
160         ycbcr_format.chroma_subsampling_x = 2;
161         ycbcr_format.chroma_subsampling_y = 1;
162         ycbcr_format.cb_x_position = 0.0f;  // H.264 -- _not_ JPEG, even though our input is MJPEG-encoded
163         ycbcr_format.cb_y_position = 0.5f;  // Irrelevant.
164         ycbcr_format.cr_x_position = 0.0f;
165         ycbcr_format.cr_y_position = 0.5f;
166         ycbcr_input = (movit::YCbCrInput *)ycbcr_convert_chain->add_input(new YCbCrInput(image_format, ycbcr_format, 1280, 720));
167
168         YCbCrFormat ycbcr_output_format = ycbcr_format;
169         ycbcr_output_format.chroma_subsampling_x = 1;
170
171         ImageFormat inout_format;
172         inout_format.color_space = COLORSPACE_sRGB;
173         inout_format.gamma_curve = GAMMA_sRGB;
174
175         check_error();
176
177         // One full Y'CbCr texture (for interpolation), one that's just Y (throwing away the
178         // Cb and Cr channels). The second copy is sort of redundant, but it's the easiest way
179         // of getting the gray data into a layered texture.
180         ycbcr_convert_chain->add_ycbcr_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED, ycbcr_output_format);
181         check_error();
182         ycbcr_convert_chain->add_ycbcr_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED, ycbcr_output_format);
183         check_error();
184         ycbcr_convert_chain->set_dither_bits(8);
185         check_error();
186         ycbcr_convert_chain->finalize();
187         check_error();
188
189         GLuint input_tex[num_interpolate_slots], gray_tex[num_interpolate_slots], cb_tex[num_interpolate_slots], cr_tex[num_interpolate_slots];
190         glCreateTextures(GL_TEXTURE_2D_ARRAY, 10, input_tex);
191         glCreateTextures(GL_TEXTURE_2D_ARRAY, 10, gray_tex);
192         glCreateTextures(GL_TEXTURE_2D, 10, cb_tex);
193         glCreateTextures(GL_TEXTURE_2D, 10, cr_tex);
194         check_error();
195         constexpr size_t width = 1280, height = 720;  // FIXME: adjustable width, height
196         int levels = find_num_levels(width, height);
197         for (size_t i = 0; i < num_interpolate_slots; ++i) {
198                 glTextureStorage3D(input_tex[i], levels, GL_RGBA8, width, height, 2);
199                 check_error();
200                 glTextureStorage3D(gray_tex[i], levels, GL_R8, width, height, 2);
201                 check_error();
202                 glTextureStorage2D(cb_tex[i], 1, GL_R8, width / 2, height);
203                 check_error();
204                 glTextureStorage2D(cr_tex[i], 1, GL_R8, width / 2, height);
205                 check_error();
206
207                 InterpolatedFrameResources resource;
208                 resource.input_tex = input_tex[i];
209                 resource.gray_tex = gray_tex[i];
210                 resource.cb_tex = cb_tex[i];
211                 resource.cr_tex = cr_tex[i];
212                 glCreateFramebuffers(2, resource.input_fbos);
213                 check_error();
214
215                 glNamedFramebufferTextureLayer(resource.input_fbos[0], GL_COLOR_ATTACHMENT0, input_tex[i], 0, 0);
216                 check_error();
217                 glNamedFramebufferTextureLayer(resource.input_fbos[0], GL_COLOR_ATTACHMENT1, gray_tex[i], 0, 0);
218                 check_error();
219                 glNamedFramebufferTextureLayer(resource.input_fbos[1], GL_COLOR_ATTACHMENT0, input_tex[i], 0, 1);
220                 check_error();
221                 glNamedFramebufferTextureLayer(resource.input_fbos[1], GL_COLOR_ATTACHMENT1, gray_tex[i], 0, 1);
222                 check_error();
223
224                 GLuint bufs[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
225                 glNamedFramebufferDrawBuffers(resource.input_fbos[0], 2, bufs);
226                 check_error();
227                 glNamedFramebufferDrawBuffers(resource.input_fbos[1], 2, bufs);
228                 check_error();
229
230                 glCreateBuffers(1, &resource.pbo);
231                 check_error();
232                 glNamedBufferStorage(resource.pbo, width * height * 4, nullptr, GL_MAP_READ_BIT | GL_MAP_PERSISTENT_BIT);
233                 check_error();
234                 resource.pbo_contents = glMapNamedBufferRange(resource.pbo, 0, width * height * 4, GL_MAP_READ_BIT | GL_MAP_PERSISTENT_BIT); 
235                 interpolate_resources.push_back(resource);
236         }
237
238         check_error();
239
240         compute_flow.reset(new DISComputeFlow(width, height, operating_point2));
241         interpolate.reset(new Interpolate(width, height, operating_point2, /*split_ycbcr_output=*/true));
242         chroma_subsampler.reset(new ChromaSubsampler);
243         check_error();
244 }
245
246 VideoStream::~VideoStream() {}
247
248 void VideoStream::start()
249 {
250         AVFormatContext *avctx = avformat_alloc_context();
251         avctx->oformat = av_guess_format("nut", nullptr, nullptr);
252
253         uint8_t *buf = (uint8_t *)av_malloc(MUX_BUFFER_SIZE);
254         avctx->pb = avio_alloc_context(buf, MUX_BUFFER_SIZE, 1, this, nullptr, nullptr, nullptr);
255         avctx->pb->write_data_type = &VideoStream::write_packet2_thunk;
256         avctx->pb->ignore_boundary_point = 1;
257
258         Mux::Codec video_codec = Mux::CODEC_MJPEG;
259
260         avctx->flags = AVFMT_FLAG_CUSTOM_IO;
261
262         string video_extradata;
263
264         constexpr int width = 1280, height = 720;  // Doesn't matter for MJPEG.
265         stream_mux.reset(new Mux(avctx, width, height, video_codec, video_extradata, /*audio_codec_parameters=*/nullptr, COARSE_TIMEBASE,
266                 /*write_callback=*/nullptr, Mux::WRITE_FOREGROUND, {}));
267
268
269         encode_thread = thread(&VideoStream::encode_thread_func, this);
270 }
271
272 void VideoStream::stop()
273 {
274         encode_thread.join();
275 }
276
277 void VideoStream::schedule_original_frame(int64_t output_pts, unsigned stream_idx, int64_t input_pts)
278 {
279         fprintf(stderr, "output_pts=%ld  original      input_pts=%ld\n", output_pts, input_pts);
280
281         QueuedFrame qf;
282         qf.type = QueuedFrame::ORIGINAL;
283         qf.output_pts = output_pts;
284         qf.stream_idx = stream_idx;
285         qf.input_first_pts = input_pts; 
286
287         unique_lock<mutex> lock(queue_lock);
288         frame_queue.push_back(qf);
289         queue_nonempty.notify_all();
290 }
291
292 void VideoStream::schedule_interpolated_frame(int64_t output_pts, unsigned stream_idx, int64_t input_first_pts, int64_t input_second_pts, float alpha)
293 {
294         fprintf(stderr, "output_pts=%ld  interpolated  input_pts1=%ld input_pts2=%ld alpha=%.3f\n", output_pts, input_first_pts, input_second_pts, alpha);
295
296         // Get the temporary OpenGL resources we need for doing the interpolation.
297         InterpolatedFrameResources resources;
298         {
299                 unique_lock<mutex> lock(queue_lock);
300                 if (interpolate_resources.empty()) {
301                         fprintf(stderr, "WARNING: Too many interpolated frames already in transit; dropping one.\n");
302                         return;
303                 }
304                 resources = interpolate_resources.front();
305                 interpolate_resources.pop_front();
306         }
307
308         QueuedFrame qf;
309         qf.type = QueuedFrame::INTERPOLATED;
310         qf.output_pts = output_pts;
311         qf.stream_idx = stream_idx;
312         qf.resources = resources;
313
314         check_error();
315
316         // Convert frame0 and frame1 to OpenGL textures.
317         // TODO: Deduplicate against JPEGFrameView::setDecodedFrame?
318         for (size_t frame_no = 0; frame_no < 2; ++frame_no) {
319                 JPEGID jpeg_id;
320                 jpeg_id.stream_idx = stream_idx;
321                 jpeg_id.pts = frame_no == 1 ? input_second_pts : input_first_pts;
322                 bool did_decode;
323                 shared_ptr<Frame> frame = decode_jpeg_with_cache(jpeg_id, DECODE_IF_NOT_IN_CACHE, &did_decode);
324                 ycbcr_format.chroma_subsampling_x = frame->chroma_subsampling_x;
325                 ycbcr_format.chroma_subsampling_y = frame->chroma_subsampling_y;
326                 ycbcr_input->change_ycbcr_format(ycbcr_format);
327                 ycbcr_input->set_width(frame->width);
328                 ycbcr_input->set_height(frame->height);
329                 ycbcr_input->set_pixel_data(0, frame->y.get());
330                 ycbcr_input->set_pixel_data(1, frame->cb.get());
331                 ycbcr_input->set_pixel_data(2, frame->cr.get());
332                 ycbcr_input->set_pitch(0, frame->pitch_y);
333                 ycbcr_input->set_pitch(1, frame->pitch_chroma);
334                 ycbcr_input->set_pitch(2, frame->pitch_chroma);
335                 ycbcr_convert_chain->render_to_fbo(resources.input_fbos[frame_no], 1280, 720);
336         }
337
338         glGenerateTextureMipmap(resources.input_tex);
339         check_error();
340         glGenerateTextureMipmap(resources.gray_tex);
341         check_error();
342
343         // Compute the interpolated frame.
344         qf.flow_tex = compute_flow->exec(resources.gray_tex, DISComputeFlow::FORWARD_AND_BACKWARD, DISComputeFlow::DO_NOT_RESIZE_FLOW);
345         check_error();
346         tie(qf.output_tex, qf.cbcr_tex) = interpolate->exec(resources.input_tex, resources.gray_tex, qf.flow_tex, 1280, 720, alpha);
347         check_error();
348
349         // Subsample and split Cb/Cr.
350         chroma_subsampler->subsample_chroma(qf.cbcr_tex, 1280, 720, resources.cb_tex, resources.cr_tex);
351
352         // We could have released qf.flow_tex here, but to make sure we don't cause a stall
353         // when trying to reuse it for the next frame, we can just as well hold on to it
354         // and release it only when the readback is done.
355
356         // Read it down (asynchronously) to the CPU.
357         glPixelStorei(GL_PACK_ROW_LENGTH, 0);
358         glBindBuffer(GL_PIXEL_PACK_BUFFER, resources.pbo);
359         check_error();
360         glGetTextureImage(qf.output_tex, 0, GL_RED, GL_UNSIGNED_BYTE, 1280 * 720 * 4, BUFFER_OFFSET(0));
361         check_error();
362         glGetTextureImage(resources.cb_tex, 0, GL_RED, GL_UNSIGNED_BYTE, 1280 * 720 * 3, BUFFER_OFFSET(1280 * 720));
363         check_error();
364         glGetTextureImage(resources.cr_tex, 0, GL_RED, GL_UNSIGNED_BYTE, 1280 * 720 * 3 - 640 * 720, BUFFER_OFFSET(1280 * 720 + 640 * 720));
365         check_error();
366         glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
367
368         // Set a fence we can wait for to make sure the CPU sees the read.
369         glMemoryBarrier(GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT);
370         check_error();
371         qf.fence = RefCountedGLsync(GL_SYNC_GPU_COMMANDS_COMPLETE, /*flags=*/0);
372         check_error();
373
374         unique_lock<mutex> lock(queue_lock);
375         frame_queue.push_back(qf);
376         queue_nonempty.notify_all();
377 }
378
379 void VideoStream::encode_thread_func()
380 {
381         pthread_setname_np(pthread_self(), "VideoStream");
382         QSurface *surface = create_surface();
383         QOpenGLContext *context = create_context(surface);
384         bool ok = make_current(context, surface);
385         if (!ok) {
386                 fprintf(stderr, "Video stream couldn't get an OpenGL context\n");
387                 exit(1);
388         }
389
390         for ( ;; ) {
391                 QueuedFrame qf;
392                 {
393                         unique_lock<mutex> lock(queue_lock);
394                         queue_nonempty.wait(lock, [this]{
395                                 return !frame_queue.empty();
396                         });
397                         qf = frame_queue.front();
398                         frame_queue.pop_front();
399                 }
400
401                 if (qf.type == QueuedFrame::ORIGINAL) {
402                         // Send the JPEG frame on, unchanged.
403                         string jpeg = read_file(filename_for_frame(qf.stream_idx, qf.input_first_pts));
404                         AVPacket pkt;
405                         av_init_packet(&pkt);
406                         pkt.stream_index = 0;
407                         pkt.data = (uint8_t *)jpeg.data();
408                         pkt.size = jpeg.size();
409                         stream_mux->add_packet(pkt, qf.output_pts, qf.output_pts);
410                 } else if (qf.type == QueuedFrame::INTERPOLATED) {
411                         glClientWaitSync(qf.fence.get(), /*flags=*/0, GL_TIMEOUT_IGNORED);
412
413                         vector<uint8_t> jpeg = encode_jpeg(
414                                 (const uint8_t *)qf.resources.pbo_contents,
415                                 (const uint8_t *)qf.resources.pbo_contents + 1280 * 720,
416                                 (const uint8_t *)qf.resources.pbo_contents + 1280 * 720 + 640 * 720,
417                                 1280, 720);
418                         compute_flow->release_texture(qf.flow_tex);
419                         interpolate->release_texture(qf.output_tex);
420                         interpolate->release_texture(qf.cbcr_tex);
421
422                         AVPacket pkt;
423                         av_init_packet(&pkt);
424                         pkt.stream_index = 0;
425                         pkt.data = (uint8_t *)jpeg.data();
426                         pkt.size = jpeg.size();
427                         stream_mux->add_packet(pkt, qf.output_pts, qf.output_pts);
428
429                         // Put the frame resources back.
430                         unique_lock<mutex> lock(queue_lock);
431                         interpolate_resources.push_back(qf.resources);
432                 }
433         }
434 }
435
436 int VideoStream::write_packet2_thunk(void *opaque, uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
437 {
438         VideoStream *video_stream = (VideoStream *)opaque;
439         return video_stream->write_packet2(buf, buf_size, type, time);
440 }
441
442 int VideoStream::write_packet2(uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
443 {
444         if (type == AVIO_DATA_MARKER_SYNC_POINT || type == AVIO_DATA_MARKER_BOUNDARY_POINT) {
445                 seen_sync_markers = true;
446         } else if (type == AVIO_DATA_MARKER_UNKNOWN && !seen_sync_markers) {
447                 // We don't know if this is a keyframe or not (the muxer could
448                 // avoid marking it), so we just have to make the best of it.
449                 type = AVIO_DATA_MARKER_SYNC_POINT;
450         }
451
452         if (type == AVIO_DATA_MARKER_HEADER) {
453                 stream_mux_header.append((char *)buf, buf_size);
454                 global_httpd->set_header(stream_mux_header);
455         } else {
456                 global_httpd->add_data((char *)buf, buf_size, type == AVIO_DATA_MARKER_SYNC_POINT, time, AVRational{ AV_TIME_BASE, 1 });
457         }
458         return buf_size;
459 }
460