1 #include "video_stream.h"
4 #include <libavformat/avformat.h>
5 #include <libavformat/avio.h>
11 #include "chroma_subsampler.h"
15 #include "jpeg_frame_view.h"
16 #include "movit/util.h"
21 #include <epoxy/glx.h>
25 extern HTTPD *global_httpd;
29 string read_file(const string &filename)
31 FILE *fp = fopen(filename.c_str(), "rb");
33 perror(filename.c_str());
37 fseek(fp, 0, SEEK_END);
43 fread(&ret[0], len, 1, fp);
50 struct VectorDestinationManager {
51 jpeg_destination_mgr pub;
52 std::vector<uint8_t> dest;
54 VectorDestinationManager()
56 pub.init_destination = init_destination_thunk;
57 pub.empty_output_buffer = empty_output_buffer_thunk;
58 pub.term_destination = term_destination_thunk;
61 static void init_destination_thunk(j_compress_ptr ptr)
63 ((VectorDestinationManager *)(ptr->dest))->init_destination();
66 inline void init_destination()
71 static boolean empty_output_buffer_thunk(j_compress_ptr ptr)
73 return ((VectorDestinationManager *)(ptr->dest))->empty_output_buffer();
76 inline bool empty_output_buffer()
78 make_room(dest.size()); // Should ignore pub.free_in_buffer!
82 inline void make_room(size_t bytes_used)
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;
90 static void term_destination_thunk(j_compress_ptr ptr)
92 ((VectorDestinationManager *)(ptr->dest))->term_destination();
95 inline void term_destination()
97 dest.resize(dest.size() - pub.free_in_buffer);
100 static_assert(std::is_standard_layout<VectorDestinationManager>::value, "");
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)
104 VectorDestinationManager dest;
106 jpeg_compress_struct cinfo;
108 cinfo.err = jpeg_std_error(&jerr);
109 jpeg_create_compress(&cinfo);
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);
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);
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]);
140 jpeg_write_raw_data(&cinfo, data, /*num_lines=*/8);
143 jpeg_finish_compress(&cinfo);
144 jpeg_destroy_compress(&cinfo);
146 return move(dest.dest);
149 VideoStream::VideoStream()
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));
168 YCbCrFormat ycbcr_output_format = ycbcr_format;
169 ycbcr_output_format.chroma_subsampling_x = 1;
171 ImageFormat inout_format;
172 inout_format.color_space = COLORSPACE_sRGB;
173 inout_format.gamma_curve = GAMMA_sRGB;
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);
182 ycbcr_convert_chain->add_ycbcr_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED, ycbcr_output_format);
184 ycbcr_convert_chain->set_dither_bits(8);
186 ycbcr_convert_chain->finalize();
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);
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);
200 glTextureStorage3D(gray_tex[i], levels, GL_R8, width, height, 2);
202 glTextureStorage2D(cb_tex[i], 1, GL_R8, width / 2, height);
204 glTextureStorage2D(cr_tex[i], 1, GL_R8, width / 2, height);
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);
215 glNamedFramebufferTextureLayer(resource.input_fbos[0], GL_COLOR_ATTACHMENT0, input_tex[i], 0, 0);
217 glNamedFramebufferTextureLayer(resource.input_fbos[0], GL_COLOR_ATTACHMENT1, gray_tex[i], 0, 0);
219 glNamedFramebufferTextureLayer(resource.input_fbos[1], GL_COLOR_ATTACHMENT0, input_tex[i], 0, 1);
221 glNamedFramebufferTextureLayer(resource.input_fbos[1], GL_COLOR_ATTACHMENT1, gray_tex[i], 0, 1);
224 GLuint bufs[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
225 glNamedFramebufferDrawBuffers(resource.input_fbos[0], 2, bufs);
227 glNamedFramebufferDrawBuffers(resource.input_fbos[1], 2, bufs);
230 glCreateBuffers(1, &resource.pbo);
232 glNamedBufferStorage(resource.pbo, width * height * 4, nullptr, GL_MAP_READ_BIT | GL_MAP_PERSISTENT_BIT);
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);
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);
246 VideoStream::~VideoStream() {}
248 void VideoStream::start()
250 AVFormatContext *avctx = avformat_alloc_context();
251 avctx->oformat = av_guess_format("nut", nullptr, nullptr);
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;
258 Mux::Codec video_codec = Mux::CODEC_MJPEG;
260 avctx->flags = AVFMT_FLAG_CUSTOM_IO;
262 string video_extradata;
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, {}));
269 encode_thread = thread(&VideoStream::encode_thread_func, this);
272 void VideoStream::stop()
274 encode_thread.join();
277 void VideoStream::schedule_original_frame(int64_t output_pts, unsigned stream_idx, int64_t input_pts)
279 fprintf(stderr, "output_pts=%ld original input_pts=%ld\n", output_pts, input_pts);
282 qf.type = QueuedFrame::ORIGINAL;
283 qf.output_pts = output_pts;
284 qf.stream_idx = stream_idx;
285 qf.input_first_pts = input_pts;
287 unique_lock<mutex> lock(queue_lock);
288 frame_queue.push_back(qf);
289 queue_nonempty.notify_all();
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)
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);
296 // Get the temporary OpenGL resources we need for doing the interpolation.
297 InterpolatedFrameResources resources;
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");
304 resources = interpolate_resources.front();
305 interpolate_resources.pop_front();
309 qf.type = QueuedFrame::INTERPOLATED;
310 qf.output_pts = output_pts;
311 qf.stream_idx = stream_idx;
312 qf.resources = resources;
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) {
320 jpeg_id.stream_idx = stream_idx;
321 jpeg_id.pts = frame_no == 1 ? input_second_pts : input_first_pts;
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);
338 glGenerateTextureMipmap(resources.input_tex);
340 glGenerateTextureMipmap(resources.gray_tex);
343 // Compute the interpolated frame.
344 qf.flow_tex = compute_flow->exec(resources.gray_tex, DISComputeFlow::FORWARD_AND_BACKWARD, DISComputeFlow::DO_NOT_RESIZE_FLOW);
346 tie(qf.output_tex, qf.cbcr_tex) = interpolate->exec(resources.input_tex, resources.gray_tex, qf.flow_tex, 1280, 720, alpha);
349 // Subsample and split Cb/Cr.
350 chroma_subsampler->subsample_chroma(qf.cbcr_tex, 1280, 720, resources.cb_tex, resources.cr_tex);
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.
356 // Read it down (asynchronously) to the CPU.
357 glPixelStorei(GL_PACK_ROW_LENGTH, 0);
358 glBindBuffer(GL_PIXEL_PACK_BUFFER, resources.pbo);
360 glGetTextureImage(qf.output_tex, 0, GL_RED, GL_UNSIGNED_BYTE, 1280 * 720 * 4, BUFFER_OFFSET(0));
362 glGetTextureImage(resources.cb_tex, 0, GL_RED, GL_UNSIGNED_BYTE, 1280 * 720 * 3, BUFFER_OFFSET(1280 * 720));
364 glGetTextureImage(resources.cr_tex, 0, GL_RED, GL_UNSIGNED_BYTE, 1280 * 720 * 3 - 640 * 720, BUFFER_OFFSET(1280 * 720 + 640 * 720));
366 glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
368 // Set a fence we can wait for to make sure the CPU sees the read.
369 glMemoryBarrier(GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT);
371 qf.fence = RefCountedGLsync(GL_SYNC_GPU_COMMANDS_COMPLETE, /*flags=*/0);
374 unique_lock<mutex> lock(queue_lock);
375 frame_queue.push_back(qf);
376 queue_nonempty.notify_all();
379 void VideoStream::encode_thread_func()
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);
386 fprintf(stderr, "Video stream couldn't get an OpenGL context\n");
393 unique_lock<mutex> lock(queue_lock);
394 queue_nonempty.wait(lock, [this]{
395 return !frame_queue.empty();
397 qf = frame_queue.front();
398 frame_queue.pop_front();
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));
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);
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,
418 compute_flow->release_texture(qf.flow_tex);
419 interpolate->release_texture(qf.output_tex);
420 interpolate->release_texture(qf.cbcr_tex);
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);
429 // Put the frame resources back.
430 unique_lock<mutex> lock(queue_lock);
431 interpolate_resources.push_back(qf.resources);
436 int VideoStream::write_packet2_thunk(void *opaque, uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
438 VideoStream *video_stream = (VideoStream *)opaque;
439 return video_stream->write_packet2(buf, buf_size, type, time);
442 int VideoStream::write_packet2(uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
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;
452 if (type == AVIO_DATA_MARKER_HEADER) {
453 stream_mux_header.append((char *)buf, buf_size);
454 global_httpd->set_header(stream_mux_header);
456 global_httpd->add_data((char *)buf, buf_size, type == AVIO_DATA_MARKER_SYNC_POINT, time, AVRational{ AV_TIME_BASE, 1 });