1 #include "video_stream.h"
4 #include <libavformat/avformat.h>
5 #include <libavformat/avio.h>
6 #include <libavutil/channel_layout.h>
9 #include "chroma_subsampler.h"
10 #include "exif_parser.h"
13 #include "jpeg_frame_view.h"
14 #include "movit/util.h"
17 #include "shared/context.h"
18 #include "shared/httpd.h"
19 #include "shared/metrics.h"
20 #include "shared/shared_defs.h"
21 #include "shared/mux.h"
23 #include "ycbcr_converter.h"
25 #include <epoxy/glx.h>
29 using namespace movit;
31 using namespace std::chrono;
35 once_flag video_metrics_inited;
36 Summary metric_jpeg_encode_time_seconds;
37 Summary metric_fade_latency_seconds;
38 Summary metric_interpolation_latency_seconds;
39 Summary metric_fade_fence_wait_time_seconds;
40 Summary metric_interpolation_fence_wait_time_seconds;
42 void wait_for_upload(shared_ptr<Frame> &frame)
44 if (frame->uploaded_interpolation != nullptr) {
45 glWaitSync(frame->uploaded_interpolation.get(), /*flags=*/0, GL_TIMEOUT_IGNORED);
46 frame->uploaded_interpolation.reset();
52 extern HTTPD *global_httpd;
54 struct VectorDestinationManager {
55 jpeg_destination_mgr pub;
58 VectorDestinationManager()
60 pub.init_destination = init_destination_thunk;
61 pub.empty_output_buffer = empty_output_buffer_thunk;
62 pub.term_destination = term_destination_thunk;
65 static void init_destination_thunk(j_compress_ptr ptr)
67 ((VectorDestinationManager *)(ptr->dest))->init_destination();
70 inline void init_destination()
75 static boolean empty_output_buffer_thunk(j_compress_ptr ptr)
77 return ((VectorDestinationManager *)(ptr->dest))->empty_output_buffer();
80 inline bool empty_output_buffer()
82 make_room(dest.size()); // Should ignore pub.free_in_buffer!
86 inline void make_room(size_t bytes_used)
88 dest.resize(bytes_used + 4096);
89 dest.resize(dest.capacity());
90 pub.next_output_byte = (uint8_t *)dest.data() + bytes_used;
91 pub.free_in_buffer = dest.size() - bytes_used;
94 static void term_destination_thunk(j_compress_ptr ptr)
96 ((VectorDestinationManager *)(ptr->dest))->term_destination();
99 inline void term_destination()
101 dest.resize(dest.size() - pub.free_in_buffer);
104 static_assert(std::is_standard_layout<VectorDestinationManager>::value, "");
106 string encode_jpeg(const uint8_t *y_data, const uint8_t *cb_data, const uint8_t *cr_data, unsigned width, unsigned height, const string exif_data)
108 steady_clock::time_point start = steady_clock::now();
109 VectorDestinationManager dest;
111 jpeg_compress_struct cinfo;
113 cinfo.err = jpeg_std_error(&jerr);
114 jpeg_create_compress(&cinfo);
116 cinfo.dest = (jpeg_destination_mgr *)&dest;
117 cinfo.input_components = 3;
118 cinfo.in_color_space = JCS_RGB;
119 jpeg_set_defaults(&cinfo);
120 constexpr int quality = 90;
121 jpeg_set_quality(&cinfo, quality, /*force_baseline=*/false);
123 cinfo.image_width = width;
124 cinfo.image_height = height;
125 cinfo.raw_data_in = true;
126 jpeg_set_colorspace(&cinfo, JCS_YCbCr);
127 cinfo.comp_info[0].h_samp_factor = 2;
128 cinfo.comp_info[0].v_samp_factor = 1;
129 cinfo.comp_info[1].h_samp_factor = 1;
130 cinfo.comp_info[1].v_samp_factor = 1;
131 cinfo.comp_info[2].h_samp_factor = 1;
132 cinfo.comp_info[2].v_samp_factor = 1;
133 cinfo.CCIR601_sampling = true; // Seems to be mostly ignored by libjpeg, though.
134 jpeg_start_compress(&cinfo, true);
136 // This comment marker is private to FFmpeg. It signals limited Y'CbCr range
137 // (and nothing else).
138 jpeg_write_marker(&cinfo, JPEG_COM, (const JOCTET *)"CS=ITU601", strlen("CS=ITU601"));
140 if (!exif_data.empty()) {
141 jpeg_write_marker(&cinfo, JPEG_APP0 + 1, (const JOCTET *)exif_data.data(), exif_data.size());
144 JSAMPROW yptr[8], cbptr[8], crptr[8];
145 JSAMPARRAY data[3] = { yptr, cbptr, crptr };
146 for (unsigned y = 0; y < height; y += 8) {
147 for (unsigned yy = 0; yy < 8; ++yy) {
148 yptr[yy] = const_cast<JSAMPROW>(&y_data[(y + yy) * width]);
149 cbptr[yy] = const_cast<JSAMPROW>(&cb_data[(y + yy) * width / 2]);
150 crptr[yy] = const_cast<JSAMPROW>(&cr_data[(y + yy) * width / 2]);
153 jpeg_write_raw_data(&cinfo, data, /*num_lines=*/8);
156 jpeg_finish_compress(&cinfo);
157 jpeg_destroy_compress(&cinfo);
159 steady_clock::time_point stop = steady_clock::now();
160 metric_jpeg_encode_time_seconds.count_event(duration<double>(stop - start).count());
162 return move(dest.dest);
165 string encode_jpeg_from_pbo(void *contents, unsigned width, unsigned height, const string exif_data)
167 unsigned chroma_width = width / 2;
169 const uint8_t *y = (const uint8_t *)contents;
170 const uint8_t *cb = (const uint8_t *)contents + width * height;
171 const uint8_t *cr = (const uint8_t *)contents + width * height + chroma_width * height;
172 return encode_jpeg(y, cb, cr, width, height, move(exif_data));
175 VideoStream::VideoStream(AVFormatContext *file_avctx)
176 : avctx(file_avctx), output_fast_forward(file_avctx != nullptr)
178 call_once(video_metrics_inited, [] {
179 vector<double> quantiles{ 0.01, 0.1, 0.25, 0.5, 0.75, 0.9, 0.99 };
180 metric_jpeg_encode_time_seconds.init(quantiles, 60.0);
181 global_metrics.add("jpeg_encode_time_seconds", &metric_jpeg_encode_time_seconds);
182 metric_fade_fence_wait_time_seconds.init(quantiles, 60.0);
183 global_metrics.add("fade_fence_wait_time_seconds", &metric_fade_fence_wait_time_seconds);
184 metric_interpolation_fence_wait_time_seconds.init(quantiles, 60.0);
185 global_metrics.add("interpolation_fence_wait_time_seconds", &metric_interpolation_fence_wait_time_seconds);
186 metric_fade_latency_seconds.init(quantiles, 60.0);
187 global_metrics.add("fade_latency_seconds", &metric_fade_latency_seconds);
188 metric_interpolation_latency_seconds.init(quantiles, 60.0);
189 global_metrics.add("interpolation_latency_seconds", &metric_interpolation_latency_seconds);
192 ycbcr_converter.reset(new YCbCrConverter(YCbCrConverter::OUTPUT_TO_DUAL_YCBCR, /*resource_pool=*/nullptr));
193 ycbcr_semiplanar_converter.reset(new YCbCrConverter(YCbCrConverter::OUTPUT_TO_SEMIPLANAR, /*resource_pool=*/nullptr));
195 GLuint input_tex[num_interpolate_slots], gray_tex[num_interpolate_slots];
196 GLuint fade_y_output_tex[num_interpolate_slots], fade_cbcr_output_tex[num_interpolate_slots];
197 GLuint cb_tex[num_interpolate_slots], cr_tex[num_interpolate_slots];
199 glCreateTextures(GL_TEXTURE_2D_ARRAY, num_interpolate_slots, input_tex);
200 glCreateTextures(GL_TEXTURE_2D_ARRAY, num_interpolate_slots, gray_tex);
201 glCreateTextures(GL_TEXTURE_2D, num_interpolate_slots, fade_y_output_tex);
202 glCreateTextures(GL_TEXTURE_2D, num_interpolate_slots, fade_cbcr_output_tex);
203 glCreateTextures(GL_TEXTURE_2D, num_interpolate_slots, cb_tex);
204 glCreateTextures(GL_TEXTURE_2D, num_interpolate_slots, cr_tex);
207 size_t width = global_flags.width, height = global_flags.height;
208 int levels = find_num_levels(width, height);
209 for (size_t i = 0; i < num_interpolate_slots; ++i) {
210 glTextureStorage3D(input_tex[i], levels, GL_RGBA8, width, height, 2);
212 glTextureStorage3D(gray_tex[i], levels, GL_R8, width, height, 2);
214 glTextureStorage2D(fade_y_output_tex[i], 1, GL_R8, width, height);
216 glTextureStorage2D(fade_cbcr_output_tex[i], 1, GL_RG8, width, height);
218 glTextureStorage2D(cb_tex[i], 1, GL_R8, width / 2, height);
220 glTextureStorage2D(cr_tex[i], 1, GL_R8, width / 2, height);
223 unique_ptr<InterpolatedFrameResources> resource(new InterpolatedFrameResources);
224 resource->owner = this;
225 resource->input_tex = input_tex[i];
226 resource->gray_tex = gray_tex[i];
227 resource->fade_y_output_tex = fade_y_output_tex[i];
228 resource->fade_cbcr_output_tex = fade_cbcr_output_tex[i];
229 resource->cb_tex = cb_tex[i];
230 resource->cr_tex = cr_tex[i];
231 glCreateFramebuffers(2, resource->input_fbos);
233 glCreateFramebuffers(1, &resource->fade_fbo);
236 glNamedFramebufferTextureLayer(resource->input_fbos[0], GL_COLOR_ATTACHMENT0, input_tex[i], 0, 0);
238 glNamedFramebufferTextureLayer(resource->input_fbos[0], GL_COLOR_ATTACHMENT1, gray_tex[i], 0, 0);
240 glNamedFramebufferTextureLayer(resource->input_fbos[1], GL_COLOR_ATTACHMENT0, input_tex[i], 0, 1);
242 glNamedFramebufferTextureLayer(resource->input_fbos[1], GL_COLOR_ATTACHMENT1, gray_tex[i], 0, 1);
244 glNamedFramebufferTexture(resource->fade_fbo, GL_COLOR_ATTACHMENT0, fade_y_output_tex[i], 0);
246 glNamedFramebufferTexture(resource->fade_fbo, GL_COLOR_ATTACHMENT1, fade_cbcr_output_tex[i], 0);
249 GLuint bufs[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
250 glNamedFramebufferDrawBuffers(resource->input_fbos[0], 2, bufs);
252 glNamedFramebufferDrawBuffers(resource->input_fbos[1], 2, bufs);
254 glNamedFramebufferDrawBuffers(resource->fade_fbo, 2, bufs);
257 glCreateBuffers(1, &resource->pbo);
259 glNamedBufferStorage(resource->pbo, width * height * 4, nullptr, GL_MAP_READ_BIT | GL_MAP_PERSISTENT_BIT);
261 resource->pbo_contents = glMapNamedBufferRange(resource->pbo, 0, width * height * 4, GL_MAP_READ_BIT | GL_MAP_PERSISTENT_BIT);
262 interpolate_resources.push_back(move(resource));
268 if (global_flags.interpolation_quality == 0 ||
269 global_flags.interpolation_quality == 1) {
270 op = operating_point1;
271 } else if (global_flags.interpolation_quality == 2) {
272 op = operating_point2;
273 } else if (global_flags.interpolation_quality == 3) {
274 op = operating_point3;
275 } else if (global_flags.interpolation_quality == 4) {
276 op = operating_point4;
278 // Quality 0 will be changed to 1 in flags.cpp.
282 compute_flow.reset(new DISComputeFlow(width, height, op));
283 interpolate.reset(new Interpolate(op, /*split_ycbcr_output=*/true));
284 interpolate_no_split.reset(new Interpolate(op, /*split_ycbcr_output=*/false));
285 chroma_subsampler.reset(new ChromaSubsampler);
288 // The “last frame” is initially black.
289 unique_ptr<uint8_t[]> y(new uint8_t[global_flags.width * global_flags.height]);
290 unique_ptr<uint8_t[]> cb_or_cr(new uint8_t[(global_flags.width / 2) * global_flags.height]);
291 memset(y.get(), 16, global_flags.width * global_flags.height);
292 memset(cb_or_cr.get(), 128, (global_flags.width / 2) * global_flags.height);
293 last_frame = encode_jpeg(y.get(), cb_or_cr.get(), cb_or_cr.get(), global_flags.width, global_flags.height, /*exif_data=*/"");
295 if (file_avctx != nullptr) {
296 with_subtitles = Mux::WITHOUT_SUBTITLES;
298 with_subtitles = Mux::WITH_SUBTITLES;
302 VideoStream::~VideoStream()
304 if (last_flow_tex != 0) {
305 compute_flow->release_texture(last_flow_tex);
308 for (const unique_ptr<InterpolatedFrameResources> &resource : interpolate_resources) {
309 glUnmapNamedBuffer(resource->pbo);
311 glDeleteBuffers(1, &resource->pbo);
313 glDeleteFramebuffers(2, resource->input_fbos);
315 glDeleteFramebuffers(1, &resource->fade_fbo);
317 glDeleteTextures(1, &resource->input_tex);
319 glDeleteTextures(1, &resource->gray_tex);
321 glDeleteTextures(1, &resource->fade_y_output_tex);
323 glDeleteTextures(1, &resource->fade_cbcr_output_tex);
325 glDeleteTextures(1, &resource->cb_tex);
327 glDeleteTextures(1, &resource->cr_tex);
330 assert(interpolate_resources.size() == num_interpolate_slots);
333 void VideoStream::start()
335 if (avctx == nullptr) {
336 avctx = avformat_alloc_context();
338 // We use Matroska, because it's pretty much the only mux where FFmpeg
339 // allows writing chroma location to override JFIF's default center placement.
340 // (Note that at the time of writing, however, FFmpeg does not correctly
341 // _read_ this information!)
342 avctx->oformat = av_guess_format("matroska", nullptr, nullptr);
344 uint8_t *buf = (uint8_t *)av_malloc(MUX_BUFFER_SIZE);
345 avctx->pb = avio_alloc_context(buf, MUX_BUFFER_SIZE, 1, this, nullptr, nullptr, nullptr);
346 avctx->pb->write_data_type = &VideoStream::write_packet2_thunk;
347 avctx->pb->ignore_boundary_point = 1;
349 avctx->flags = AVFMT_FLAG_CUSTOM_IO;
352 AVCodecParameters *audio_codecpar = avcodec_parameters_alloc();
354 audio_codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
355 audio_codecpar->codec_id = AV_CODEC_ID_PCM_S32LE;
356 audio_codecpar->channel_layout = AV_CH_LAYOUT_STEREO;
357 audio_codecpar->channels = 2;
358 audio_codecpar->sample_rate = OUTPUT_FREQUENCY;
360 size_t width = global_flags.width, height = global_flags.height; // Doesn't matter for MJPEG.
361 mux.reset(new Mux(avctx, width, height, Mux::CODEC_MJPEG, /*video_extradata=*/"", audio_codecpar,
362 AVCOL_SPC_BT709, COARSE_TIMEBASE, /*write_callback=*/nullptr, Mux::WRITE_FOREGROUND, {}, with_subtitles));
364 avcodec_parameters_free(&audio_codecpar);
365 encode_thread = thread(&VideoStream::encode_thread_func, this);
368 void VideoStream::stop()
371 queue_changed.notify_all();
373 encode_thread.join();
376 void VideoStream::clear_queue()
378 deque<QueuedFrame> q;
381 lock_guard<mutex> lock(queue_lock);
382 q = move(frame_queue);
385 // These are not RAII-ed, unfortunately, so we'll need to clean them ourselves.
386 // Note that release_texture() is thread-safe.
387 for (const QueuedFrame &qf : q) {
388 if (qf.type == QueuedFrame::INTERPOLATED ||
389 qf.type == QueuedFrame::FADED_INTERPOLATED) {
390 if (qf.flow_tex != 0) {
391 compute_flow->release_texture(qf.flow_tex);
394 if (qf.type == QueuedFrame::INTERPOLATED) {
395 interpolate->release_texture(qf.output_tex);
396 interpolate->release_texture(qf.cbcr_tex);
400 // Destroy q outside the mutex, as that would be a double-lock.
403 void VideoStream::schedule_original_frame(steady_clock::time_point local_pts,
404 int64_t output_pts, function<void()> &&display_func,
405 QueueSpotHolder &&queue_spot_holder,
406 FrameOnDisk frame, const string &subtitle, bool include_audio)
408 fprintf(stderr, "output_pts=%" PRId64 " original input_pts=%" PRId64 "\n", output_pts, frame.pts);
411 qf.local_pts = local_pts;
412 qf.type = QueuedFrame::ORIGINAL;
413 qf.output_pts = output_pts;
414 qf.display_func = move(display_func);
415 qf.queue_spot_holder = move(queue_spot_holder);
416 qf.subtitle = subtitle;
417 FrameReader::Frame read_frame = frame_reader.read_frame(frame, /*read_video=*/true, include_audio);
418 qf.encoded_jpeg.reset(new string(move(read_frame.video)));
419 qf.audio = move(read_frame.audio);
421 lock_guard<mutex> lock(queue_lock);
422 frame_queue.push_back(move(qf));
423 queue_changed.notify_all();
426 void VideoStream::schedule_faded_frame(steady_clock::time_point local_pts, int64_t output_pts,
427 function<void()> &&display_func,
428 QueueSpotHolder &&queue_spot_holder,
429 FrameOnDisk frame1_spec, FrameOnDisk frame2_spec,
430 float fade_alpha, const string &subtitle)
432 fprintf(stderr, "output_pts=%" PRId64 " faded input_pts=%" PRId64 ",%" PRId64 " fade_alpha=%.2f\n", output_pts, frame1_spec.pts, frame2_spec.pts, fade_alpha);
434 // Get the temporary OpenGL resources we need for doing the fade.
435 // (We share these with interpolated frames, which is slightly
436 // overkill, but there's no need to waste resources on keeping
437 // separate pools around.)
438 BorrowedInterpolatedFrameResources resources;
440 lock_guard<mutex> lock(queue_lock);
441 if (interpolate_resources.empty()) {
442 fprintf(stderr, "WARNING: Too many interpolated frames already in transit; dropping one.\n");
445 resources = BorrowedInterpolatedFrameResources(interpolate_resources.front().release());
446 interpolate_resources.pop_front();
451 shared_ptr<Frame> frame1 = decode_jpeg_with_cache(frame1_spec, DECODE_IF_NOT_IN_CACHE, &frame_reader, &did_decode);
452 shared_ptr<Frame> frame2 = decode_jpeg_with_cache(frame2_spec, DECODE_IF_NOT_IN_CACHE, &frame_reader, &did_decode);
453 wait_for_upload(frame1);
454 wait_for_upload(frame2);
456 ycbcr_semiplanar_converter->prepare_chain_for_fade(frame1, frame2, fade_alpha)->render_to_fbo(resources->fade_fbo, global_flags.width, global_flags.height);
459 qf.local_pts = local_pts;
460 qf.type = QueuedFrame::FADED;
461 qf.output_pts = output_pts;
462 qf.frame1 = frame1_spec;
463 qf.display_func = move(display_func);
464 qf.queue_spot_holder = move(queue_spot_holder);
465 qf.subtitle = subtitle;
467 qf.secondary_frame = frame2_spec;
469 // Subsample and split Cb/Cr.
470 chroma_subsampler->subsample_chroma(resources->fade_cbcr_output_tex, global_flags.width, global_flags.height, resources->cb_tex, resources->cr_tex);
472 // Read it down (asynchronously) to the CPU.
473 glPixelStorei(GL_PACK_ROW_LENGTH, 0);
474 glBindBuffer(GL_PIXEL_PACK_BUFFER, resources->pbo);
476 glGetTextureImage(resources->fade_y_output_tex, 0, GL_RED, GL_UNSIGNED_BYTE, global_flags.width * global_flags.height * 4, BUFFER_OFFSET(0));
478 glGetTextureImage(resources->cb_tex, 0, GL_RED, GL_UNSIGNED_BYTE, global_flags.width * global_flags.height * 3, BUFFER_OFFSET(global_flags.width * global_flags.height));
480 glGetTextureImage(resources->cr_tex, 0, GL_RED, GL_UNSIGNED_BYTE, global_flags.width * global_flags.height * 3 - (global_flags.width / 2) * global_flags.height, BUFFER_OFFSET(global_flags.width * global_flags.height + (global_flags.width / 2) * global_flags.height));
482 glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
484 // Set a fence we can wait for to make sure the CPU sees the read.
485 glMemoryBarrier(GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT);
487 qf.fence_created = steady_clock::now();
488 qf.fence = RefCountedGLsync(GL_SYNC_GPU_COMMANDS_COMPLETE, /*flags=*/0);
490 qf.resources = move(resources);
491 qf.local_pts = local_pts;
493 lock_guard<mutex> lock(queue_lock);
494 frame_queue.push_back(move(qf));
495 queue_changed.notify_all();
498 void VideoStream::schedule_interpolated_frame(steady_clock::time_point local_pts,
499 int64_t output_pts, function<void(shared_ptr<Frame>)> &&display_func,
500 QueueSpotHolder &&queue_spot_holder,
501 FrameOnDisk frame1, FrameOnDisk frame2,
502 float alpha, FrameOnDisk secondary_frame, float fade_alpha, const string &subtitle,
505 if (secondary_frame.pts != -1) {
506 fprintf(stderr, "output_pts=%" PRId64 " interpolated input_pts1=%" PRId64 " input_pts2=%" PRId64 " alpha=%.3f secondary_pts=%" PRId64 " fade_alpha=%.2f\n", output_pts, frame1.pts, frame2.pts, alpha, secondary_frame.pts, fade_alpha);
508 fprintf(stderr, "output_pts=%" PRId64 " interpolated input_pts1=%" PRId64 " input_pts2=%" PRId64 " alpha=%.3f\n", output_pts, frame1.pts, frame2.pts, alpha);
511 // Get the temporary OpenGL resources we need for doing the interpolation.
512 BorrowedInterpolatedFrameResources resources;
514 lock_guard<mutex> lock(queue_lock);
515 if (interpolate_resources.empty()) {
516 fprintf(stderr, "WARNING: Too many interpolated frames already in transit; dropping one.\n");
519 resources = BorrowedInterpolatedFrameResources(interpolate_resources.front().release());
520 interpolate_resources.pop_front();
524 qf.type = (secondary_frame.pts == -1) ? QueuedFrame::INTERPOLATED : QueuedFrame::FADED_INTERPOLATED;
525 qf.output_pts = output_pts;
526 qf.display_decoded_func = move(display_func);
527 qf.queue_spot_holder = move(queue_spot_holder);
528 qf.local_pts = local_pts;
529 qf.subtitle = subtitle;
532 qf.audio = frame_reader.read_frame(frame1, /*read_video=*/false, /*read_audio=*/true).audio;
537 // Convert frame0 and frame1 to OpenGL textures.
538 for (size_t frame_no = 0; frame_no < 2; ++frame_no) {
539 FrameOnDisk frame_spec = frame_no == 1 ? frame2 : frame1;
541 shared_ptr<Frame> frame = decode_jpeg_with_cache(frame_spec, DECODE_IF_NOT_IN_CACHE, &frame_reader, &did_decode);
542 wait_for_upload(frame);
543 ycbcr_converter->prepare_chain_for_conversion(frame)->render_to_fbo(resources->input_fbos[frame_no], global_flags.width, global_flags.height);
545 qf.exif_data = frame->exif_data; // Use the white point from the last frame.
549 glGenerateTextureMipmap(resources->input_tex);
551 glGenerateTextureMipmap(resources->gray_tex);
555 if (last_flow_tex != 0 && frame1 == last_frame1 && frame2 == last_frame2) {
556 // Reuse the flow from previous computation. This frequently happens
557 // if we slow down by more than 2x, so that there are multiple interpolated
558 // frames between each original.
559 flow_tex = last_flow_tex;
562 // Cache miss, so release last_flow_tex.
563 qf.flow_tex = last_flow_tex;
566 flow_tex = compute_flow->exec(resources->gray_tex, DISComputeFlow::FORWARD_AND_BACKWARD, DISComputeFlow::DO_NOT_RESIZE_FLOW);
569 // Store the flow texture for possible reuse next frame.
570 last_flow_tex = flow_tex;
571 last_frame1 = frame1;
572 last_frame2 = frame2;
575 if (secondary_frame.pts != -1) {
576 // Fade. First kick off the interpolation.
577 tie(qf.output_tex, ignore) = interpolate_no_split->exec(resources->input_tex, resources->gray_tex, flow_tex, global_flags.width, global_flags.height, alpha);
580 // Now decode the image we are fading against.
582 shared_ptr<Frame> frame2 = decode_jpeg_with_cache(secondary_frame, DECODE_IF_NOT_IN_CACHE, &frame_reader, &did_decode);
583 wait_for_upload(frame2);
585 // Then fade against it, putting it into the fade Y' and CbCr textures.
586 RGBTriplet neutral_color = get_neutral_color(qf.exif_data);
587 ycbcr_semiplanar_converter->prepare_chain_for_fade_from_texture(qf.output_tex, neutral_color, global_flags.width, global_flags.height, frame2, fade_alpha)->render_to_fbo(resources->fade_fbo, global_flags.width, global_flags.height);
589 // Subsample and split Cb/Cr.
590 chroma_subsampler->subsample_chroma(resources->fade_cbcr_output_tex, global_flags.width, global_flags.height, resources->cb_tex, resources->cr_tex);
592 interpolate_no_split->release_texture(qf.output_tex);
594 // We already applied the white balance, so don't have the client redo it.
595 qf.exif_data.clear();
597 tie(qf.output_tex, qf.cbcr_tex) = interpolate->exec(resources->input_tex, resources->gray_tex, flow_tex, global_flags.width, global_flags.height, alpha);
600 // Subsample and split Cb/Cr.
601 chroma_subsampler->subsample_chroma(qf.cbcr_tex, global_flags.width, global_flags.height, resources->cb_tex, resources->cr_tex);
604 // We could have released qf.flow_tex here, but to make sure we don't cause a stall
605 // when trying to reuse it for the next frame, we can just as well hold on to it
606 // and release it only when the readback is done.
608 // TODO: This is maybe less relevant now that qf.flow_tex contains the texture we used
609 // _last_ frame, not this one.
611 // Read it down (asynchronously) to the CPU.
612 glPixelStorei(GL_PACK_ROW_LENGTH, 0);
613 glBindBuffer(GL_PIXEL_PACK_BUFFER, resources->pbo);
615 if (secondary_frame.pts != -1) {
616 glGetTextureImage(resources->fade_y_output_tex, 0, GL_RED, GL_UNSIGNED_BYTE, global_flags.width * global_flags.height * 4, BUFFER_OFFSET(0));
618 glGetTextureImage(qf.output_tex, 0, GL_RED, GL_UNSIGNED_BYTE, global_flags.width * global_flags.height * 4, BUFFER_OFFSET(0));
621 glGetTextureImage(resources->cb_tex, 0, GL_RED, GL_UNSIGNED_BYTE, global_flags.width * global_flags.height * 3, BUFFER_OFFSET(global_flags.width * global_flags.height));
623 glGetTextureImage(resources->cr_tex, 0, GL_RED, GL_UNSIGNED_BYTE, global_flags.width * global_flags.height * 3 - (global_flags.width / 2) * global_flags.height, BUFFER_OFFSET(global_flags.width * global_flags.height + (global_flags.width / 2) * global_flags.height));
625 glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
627 // Set a fence we can wait for to make sure the CPU sees the read.
628 glMemoryBarrier(GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT);
630 qf.fence_created = steady_clock::now();
631 qf.fence = RefCountedGLsync(GL_SYNC_GPU_COMMANDS_COMPLETE, /*flags=*/0);
633 qf.resources = move(resources);
635 lock_guard<mutex> lock(queue_lock);
636 frame_queue.push_back(move(qf));
637 queue_changed.notify_all();
640 void VideoStream::schedule_refresh_frame(steady_clock::time_point local_pts,
641 int64_t output_pts, function<void()> &&display_func,
642 QueueSpotHolder &&queue_spot_holder, const string &subtitle)
645 qf.type = QueuedFrame::REFRESH;
646 qf.output_pts = output_pts;
647 qf.display_func = move(display_func);
648 qf.queue_spot_holder = move(queue_spot_holder);
649 qf.subtitle = subtitle;
651 lock_guard<mutex> lock(queue_lock);
652 frame_queue.push_back(move(qf));
653 queue_changed.notify_all();
656 void VideoStream::schedule_silence(steady_clock::time_point local_pts, int64_t output_pts,
657 int64_t length_pts, QueueSpotHolder &&queue_spot_holder)
660 qf.type = QueuedFrame::SILENCE;
661 qf.output_pts = output_pts;
662 qf.queue_spot_holder = move(queue_spot_holder);
663 qf.silence_length_pts = length_pts;
665 lock_guard<mutex> lock(queue_lock);
666 frame_queue.push_back(move(qf));
667 queue_changed.notify_all();
672 RefCountedTexture clone_r8_texture(GLuint src_tex, unsigned width, unsigned height)
675 glCreateTextures(GL_TEXTURE_2D, 1, &tex);
677 glTextureStorage2D(tex, 1, GL_R8, width, height);
679 glCopyImageSubData(src_tex, GL_TEXTURE_2D, 0, 0, 0, 0,
680 tex, GL_TEXTURE_2D, 0, 0, 0, 0,
683 glTextureParameteri(tex, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
685 glTextureParameteri(tex, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
687 glTextureParameteri(tex, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
689 glTextureParameteri(tex, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
692 return RefCountedTexture(new GLuint(tex), TextureDeleter());
697 void VideoStream::encode_thread_func()
699 pthread_setname_np(pthread_self(), "VideoStream");
700 QSurface *surface = create_surface();
701 QOpenGLContext *context = create_context(surface);
702 bool ok = make_current(context, surface);
704 fprintf(stderr, "Video stream couldn't get an OpenGL context\n");
710 while (!should_quit) {
713 unique_lock<mutex> lock(queue_lock);
715 // Wait until we have a frame to play.
716 queue_changed.wait(lock, [this] {
717 return !frame_queue.empty() || should_quit;
722 steady_clock::time_point frame_start = frame_queue.front().local_pts;
724 // Now sleep until the frame is supposed to start (the usual case),
725 // _or_ clear_queue() happened.
727 if (output_fast_forward) {
728 aborted = frame_queue.empty() || frame_queue.front().local_pts != frame_start;
730 aborted = queue_changed.wait_until(lock, frame_start, [this, frame_start] {
731 return frame_queue.empty() || frame_queue.front().local_pts != frame_start;
735 // clear_queue() happened, so don't play this frame after all.
738 qf = move(frame_queue.front());
739 frame_queue.pop_front();
742 // Hack: We mux the subtitle packet one time unit before the actual frame,
743 // so that Nageru is sure to get it first.
744 if (!qf.subtitle.empty() && with_subtitles == Mux::WITH_SUBTITLES) {
746 av_init_packet(&pkt);
747 pkt.stream_index = mux->get_subtitle_stream_idx();
748 assert(pkt.stream_index != -1);
749 pkt.data = (uint8_t *)qf.subtitle.data();
750 pkt.size = qf.subtitle.size();
752 pkt.duration = lrint(TIMEBASE / global_flags.output_framerate); // Doesn't really matter for Nageru.
753 mux->add_packet(pkt, qf.output_pts - 1, qf.output_pts - 1);
756 if (qf.type == QueuedFrame::ORIGINAL) {
757 // Send the JPEG frame on, unchanged.
758 string jpeg = move(*qf.encoded_jpeg);
760 av_init_packet(&pkt);
761 pkt.stream_index = 0;
762 pkt.data = (uint8_t *)jpeg.data();
763 pkt.size = jpeg.size();
764 pkt.flags = AV_PKT_FLAG_KEY;
765 mux->add_packet(pkt, qf.output_pts, qf.output_pts);
766 last_frame = move(jpeg);
768 add_audio_or_silence(qf);
769 } else if (qf.type == QueuedFrame::FADED) {
770 steady_clock::time_point start = steady_clock::now();
771 glClientWaitSync(qf.fence.get(), /*flags=*/0, GL_TIMEOUT_IGNORED);
772 steady_clock::time_point stop = steady_clock::now();
773 metric_fade_fence_wait_time_seconds.count_event(duration<double>(stop - start).count());
774 metric_fade_latency_seconds.count_event(duration<double>(stop - qf.fence_created).count());
776 // Now JPEG encode it, and send it on to the stream.
777 string jpeg = encode_jpeg_from_pbo(qf.resources->pbo_contents, global_flags.width, global_flags.height, /*exif_data=*/"");
780 av_init_packet(&pkt);
781 pkt.stream_index = 0;
782 pkt.data = (uint8_t *)jpeg.data();
783 pkt.size = jpeg.size();
784 pkt.flags = AV_PKT_FLAG_KEY;
785 mux->add_packet(pkt, qf.output_pts, qf.output_pts);
786 last_frame = move(jpeg);
788 add_audio_or_silence(qf);
789 } else if (qf.type == QueuedFrame::INTERPOLATED || qf.type == QueuedFrame::FADED_INTERPOLATED) {
790 steady_clock::time_point start = steady_clock::now();
791 glClientWaitSync(qf.fence.get(), /*flags=*/0, GL_TIMEOUT_IGNORED);
792 steady_clock::time_point stop = steady_clock::now();
793 metric_interpolation_fence_wait_time_seconds.count_event(duration<double>(stop - start).count());
794 metric_interpolation_latency_seconds.count_event(duration<double>(stop - qf.fence_created).count());
796 // Send it on to display.
797 if (qf.display_decoded_func != nullptr) {
798 shared_ptr<Frame> frame(new Frame);
799 if (qf.type == QueuedFrame::FADED_INTERPOLATED) {
800 frame->y = clone_r8_texture(qf.resources->fade_y_output_tex, global_flags.width, global_flags.height);
802 frame->y = clone_r8_texture(qf.output_tex, global_flags.width, global_flags.height);
804 frame->cb = clone_r8_texture(qf.resources->cb_tex, global_flags.width / 2, global_flags.height);
805 frame->cr = clone_r8_texture(qf.resources->cr_tex, global_flags.width / 2, global_flags.height);
806 frame->width = global_flags.width;
807 frame->height = global_flags.height;
808 frame->chroma_subsampling_x = 2;
809 frame->chroma_subsampling_y = 1;
810 frame->uploaded_ui_thread = RefCountedGLsync(GL_SYNC_GPU_COMMANDS_COMPLETE, /*flags=*/0);
811 qf.display_decoded_func(move(frame));
814 // Now JPEG encode it, and send it on to the stream.
815 string jpeg = encode_jpeg_from_pbo(qf.resources->pbo_contents, global_flags.width, global_flags.height, move(qf.exif_data));
816 if (qf.flow_tex != 0) {
817 compute_flow->release_texture(qf.flow_tex);
819 if (qf.type != QueuedFrame::FADED_INTERPOLATED) {
820 interpolate->release_texture(qf.output_tex);
821 interpolate->release_texture(qf.cbcr_tex);
825 av_init_packet(&pkt);
826 pkt.stream_index = 0;
827 pkt.data = (uint8_t *)jpeg.data();
828 pkt.size = jpeg.size();
829 pkt.flags = AV_PKT_FLAG_KEY;
830 mux->add_packet(pkt, qf.output_pts, qf.output_pts);
831 last_frame = move(jpeg);
833 add_audio_or_silence(qf);
834 } else if (qf.type == QueuedFrame::REFRESH) {
836 av_init_packet(&pkt);
837 pkt.stream_index = 0;
838 pkt.data = (uint8_t *)last_frame.data();
839 pkt.size = last_frame.size();
840 pkt.flags = AV_PKT_FLAG_KEY;
841 mux->add_packet(pkt, qf.output_pts, qf.output_pts);
843 add_audio_or_silence(qf); // Definitely silence.
844 } else if (qf.type == QueuedFrame::SILENCE) {
845 add_silence(qf.output_pts, qf.silence_length_pts);
849 if (qf.display_func != nullptr) {
855 int VideoStream::write_packet2_thunk(void *opaque, uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
857 VideoStream *video_stream = (VideoStream *)opaque;
858 return video_stream->write_packet2(buf, buf_size, type, time);
861 int VideoStream::write_packet2(uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
863 if (type == AVIO_DATA_MARKER_SYNC_POINT || type == AVIO_DATA_MARKER_BOUNDARY_POINT) {
864 seen_sync_markers = true;
865 } else if (type == AVIO_DATA_MARKER_UNKNOWN && !seen_sync_markers) {
866 // We don't know if this is a keyframe or not (the muxer could
867 // avoid marking it), so we just have to make the best of it.
868 type = AVIO_DATA_MARKER_SYNC_POINT;
871 HTTPD::StreamID stream_id{ HTTPD::MAIN_STREAM, 0 };
872 if (type == AVIO_DATA_MARKER_HEADER) {
873 stream_mux_header.append((char *)buf, buf_size);
874 global_httpd->set_header(stream_id, stream_mux_header);
876 global_httpd->add_data(stream_id, (char *)buf, buf_size, type == AVIO_DATA_MARKER_SYNC_POINT, time, AVRational{ AV_TIME_BASE, 1 });
881 void VideoStream::add_silence(int64_t pts, int64_t length_pts)
883 // At 59.94, this will never quite add up (even discounting refresh frames,
884 // which have unpredictable length), but hopefully, the player in the other
885 // end should be able to stretch silence easily enough.
886 long num_samples = lrint(length_pts * double(OUTPUT_FREQUENCY) / double(TIMEBASE)) * 2;
887 uint8_t *zero = (uint8_t *)calloc(num_samples, sizeof(int32_t));
890 av_init_packet(&pkt);
891 pkt.stream_index = 1;
893 pkt.size = num_samples * sizeof(int32_t);
894 pkt.flags = AV_PKT_FLAG_KEY;
895 mux->add_packet(pkt, pts, pts);
900 void VideoStream::add_audio_or_silence(const QueuedFrame &qf)
902 if (qf.audio.empty()) {
903 int64_t frame_length = lrint(double(TIMEBASE) / global_flags.output_framerate);
904 add_silence(qf.output_pts, frame_length);
907 av_init_packet(&pkt);
908 pkt.stream_index = 1;
909 pkt.data = (uint8_t *)qf.audio.data();
910 pkt.size = qf.audio.size();
911 pkt.flags = AV_PKT_FLAG_KEY;
912 mux->add_packet(pkt, qf.output_pts, qf.output_pts);