]> git.sesse.net Git - nageru/blob - video_stream.cpp
Show interpolated frames in the live window.
[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                         JPEGFrameView::insert_interpolated_frame(stream_idx, output_pts, nullptr);
303                         return;
304                 }
305                 resources = interpolate_resources.front();
306                 interpolate_resources.pop_front();
307         }
308
309         QueuedFrame qf;
310         qf.type = QueuedFrame::INTERPOLATED;
311         qf.output_pts = output_pts;
312         qf.stream_idx = stream_idx;
313         qf.resources = resources;
314
315         check_error();
316
317         // Convert frame0 and frame1 to OpenGL textures.
318         // TODO: Deduplicate against JPEGFrameView::setDecodedFrame?
319         for (size_t frame_no = 0; frame_no < 2; ++frame_no) {
320                 JPEGID jpeg_id;
321                 jpeg_id.stream_idx = stream_idx;
322                 jpeg_id.pts = frame_no == 1 ? input_second_pts : input_first_pts;
323                 jpeg_id.interpolated = false;
324                 bool did_decode;
325                 shared_ptr<Frame> frame = decode_jpeg_with_cache(jpeg_id, DECODE_IF_NOT_IN_CACHE, &did_decode);
326                 ycbcr_format.chroma_subsampling_x = frame->chroma_subsampling_x;
327                 ycbcr_format.chroma_subsampling_y = frame->chroma_subsampling_y;
328                 ycbcr_input->change_ycbcr_format(ycbcr_format);
329                 ycbcr_input->set_width(frame->width);
330                 ycbcr_input->set_height(frame->height);
331                 ycbcr_input->set_pixel_data(0, frame->y.get());
332                 ycbcr_input->set_pixel_data(1, frame->cb.get());
333                 ycbcr_input->set_pixel_data(2, frame->cr.get());
334                 ycbcr_input->set_pitch(0, frame->pitch_y);
335                 ycbcr_input->set_pitch(1, frame->pitch_chroma);
336                 ycbcr_input->set_pitch(2, frame->pitch_chroma);
337                 ycbcr_convert_chain->render_to_fbo(resources.input_fbos[frame_no], 1280, 720);
338         }
339
340         glGenerateTextureMipmap(resources.input_tex);
341         check_error();
342         glGenerateTextureMipmap(resources.gray_tex);
343         check_error();
344
345         // Compute the interpolated frame.
346         qf.flow_tex = compute_flow->exec(resources.gray_tex, DISComputeFlow::FORWARD_AND_BACKWARD, DISComputeFlow::DO_NOT_RESIZE_FLOW);
347         check_error();
348         tie(qf.output_tex, qf.cbcr_tex) = interpolate->exec(resources.input_tex, resources.gray_tex, qf.flow_tex, 1280, 720, alpha);
349         check_error();
350
351         // Subsample and split Cb/Cr.
352         chroma_subsampler->subsample_chroma(qf.cbcr_tex, 1280, 720, resources.cb_tex, resources.cr_tex);
353
354         // We could have released qf.flow_tex here, but to make sure we don't cause a stall
355         // when trying to reuse it for the next frame, we can just as well hold on to it
356         // and release it only when the readback is done.
357
358         // Read it down (asynchronously) to the CPU.
359         glPixelStorei(GL_PACK_ROW_LENGTH, 0);
360         glBindBuffer(GL_PIXEL_PACK_BUFFER, resources.pbo);
361         check_error();
362         glGetTextureImage(qf.output_tex, 0, GL_RED, GL_UNSIGNED_BYTE, 1280 * 720 * 4, BUFFER_OFFSET(0));
363         check_error();
364         glGetTextureImage(resources.cb_tex, 0, GL_RED, GL_UNSIGNED_BYTE, 1280 * 720 * 3, BUFFER_OFFSET(1280 * 720));
365         check_error();
366         glGetTextureImage(resources.cr_tex, 0, GL_RED, GL_UNSIGNED_BYTE, 1280 * 720 * 3 - 640 * 720, BUFFER_OFFSET(1280 * 720 + 640 * 720));
367         check_error();
368         glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
369
370         // Set a fence we can wait for to make sure the CPU sees the read.
371         glMemoryBarrier(GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT);
372         check_error();
373         qf.fence = RefCountedGLsync(GL_SYNC_GPU_COMMANDS_COMPLETE, /*flags=*/0);
374         check_error();
375
376         unique_lock<mutex> lock(queue_lock);
377         frame_queue.push_back(qf);
378         queue_nonempty.notify_all();
379 }
380
381 void VideoStream::encode_thread_func()
382 {
383         pthread_setname_np(pthread_self(), "VideoStream");
384         QSurface *surface = create_surface();
385         QOpenGLContext *context = create_context(surface);
386         bool ok = make_current(context, surface);
387         if (!ok) {
388                 fprintf(stderr, "Video stream couldn't get an OpenGL context\n");
389                 exit(1);
390         }
391
392         for ( ;; ) {
393                 QueuedFrame qf;
394                 {
395                         unique_lock<mutex> lock(queue_lock);
396                         queue_nonempty.wait(lock, [this]{
397                                 return !frame_queue.empty();
398                         });
399                         qf = frame_queue.front();
400                         frame_queue.pop_front();
401                 }
402
403                 if (qf.type == QueuedFrame::ORIGINAL) {
404                         // Send the JPEG frame on, unchanged.
405                         string jpeg = read_file(filename_for_frame(qf.stream_idx, qf.input_first_pts));
406                         AVPacket pkt;
407                         av_init_packet(&pkt);
408                         pkt.stream_index = 0;
409                         pkt.data = (uint8_t *)jpeg.data();
410                         pkt.size = jpeg.size();
411                         stream_mux->add_packet(pkt, qf.output_pts, qf.output_pts);
412                 } else if (qf.type == QueuedFrame::INTERPOLATED) {
413                         glClientWaitSync(qf.fence.get(), /*flags=*/0, GL_TIMEOUT_IGNORED);
414
415                         const uint8_t *y = (const uint8_t *)qf.resources.pbo_contents;
416                         const uint8_t *cb = (const uint8_t *)qf.resources.pbo_contents + 1280 * 720;
417                         const uint8_t *cr = (const uint8_t *)qf.resources.pbo_contents + 1280 * 720 + 640 * 720;
418
419                         // Send a copy of the frame on to display.
420                         shared_ptr<Frame> frame(new Frame);
421                         frame->y.reset(new uint8_t[1280 * 720]);
422                         frame->cb.reset(new uint8_t[640 * 720]);
423                         frame->cr.reset(new uint8_t[640 * 720]);
424                         for (unsigned yy = 0; yy < 720; ++yy) {
425                                 memcpy(frame->y.get() + 1280 * yy, y + 1280 * (719 - yy), 1280);
426                                 memcpy(frame->cb.get() + 640 * yy, cb + 640 * (719 - yy), 640);
427                                 memcpy(frame->cr.get() + 640 * yy, cr + 640 * (719 - yy), 640);
428                         }
429                         frame->width = 1280;
430                         frame->height = 720;
431                         frame->chroma_subsampling_x = 2;
432                         frame->chroma_subsampling_y = 1;
433                         frame->pitch_y = 1280;
434                         frame->pitch_chroma = 640;
435                         JPEGFrameView::insert_interpolated_frame(qf.stream_idx, qf.output_pts, std::move(frame));
436
437                         // Now JPEG encode it, and send it on to the stream.
438                         vector<uint8_t> jpeg = encode_jpeg(y, cb, cr, 1280, 720);
439                         compute_flow->release_texture(qf.flow_tex);
440                         interpolate->release_texture(qf.output_tex);
441                         interpolate->release_texture(qf.cbcr_tex);
442
443                         AVPacket pkt;
444                         av_init_packet(&pkt);
445                         pkt.stream_index = 0;
446                         pkt.data = (uint8_t *)jpeg.data();
447                         pkt.size = jpeg.size();
448                         stream_mux->add_packet(pkt, qf.output_pts, qf.output_pts);
449
450                         // Put the frame resources back.
451                         unique_lock<mutex> lock(queue_lock);
452                         interpolate_resources.push_back(qf.resources);
453                 }
454         }
455 }
456
457 int VideoStream::write_packet2_thunk(void *opaque, uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
458 {
459         VideoStream *video_stream = (VideoStream *)opaque;
460         return video_stream->write_packet2(buf, buf_size, type, time);
461 }
462
463 int VideoStream::write_packet2(uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
464 {
465         if (type == AVIO_DATA_MARKER_SYNC_POINT || type == AVIO_DATA_MARKER_BOUNDARY_POINT) {
466                 seen_sync_markers = true;
467         } else if (type == AVIO_DATA_MARKER_UNKNOWN && !seen_sync_markers) {
468                 // We don't know if this is a keyframe or not (the muxer could
469                 // avoid marking it), so we just have to make the best of it.
470                 type = AVIO_DATA_MARKER_SYNC_POINT;
471         }
472
473         if (type == AVIO_DATA_MARKER_HEADER) {
474                 stream_mux_header.append((char *)buf, buf_size);
475                 global_httpd->set_header(stream_mux_header);
476         } else {
477                 global_httpd->add_data((char *)buf, buf_size, type == AVIO_DATA_MARKER_SYNC_POINT, time, AVRational{ AV_TIME_BASE, 1 });
478         }
479         return buf_size;
480 }
481