1 #include "video_stream.h"
4 #include <libavformat/avformat.h>
5 #include <libavformat/avio.h>
8 #include "chroma_subsampler.h"
9 #include "exif_parser.h"
12 #include "jpeg_frame_view.h"
13 #include "movit/util.h"
16 #include "shared/context.h"
17 #include "shared/httpd.h"
18 #include "shared/metrics.h"
19 #include "shared/shared_defs.h"
20 #include "shared/mux.h"
22 #include "ycbcr_converter.h"
24 #include <epoxy/glx.h>
28 using namespace movit;
30 using namespace std::chrono;
34 once_flag video_metrics_inited;
35 Summary metric_jpeg_encode_time_seconds;
36 Summary metric_fade_latency_seconds;
37 Summary metric_interpolation_latency_seconds;
38 Summary metric_fade_fence_wait_time_seconds;
39 Summary metric_interpolation_fence_wait_time_seconds;
41 void wait_for_upload(shared_ptr<Frame> &frame)
43 if (frame->uploaded_interpolation != nullptr) {
44 glWaitSync(frame->uploaded_interpolation.get(), /*flags=*/0, GL_TIMEOUT_IGNORED);
45 frame->uploaded_interpolation.reset();
51 extern HTTPD *global_httpd;
53 struct VectorDestinationManager {
54 jpeg_destination_mgr pub;
57 VectorDestinationManager()
59 pub.init_destination = init_destination_thunk;
60 pub.empty_output_buffer = empty_output_buffer_thunk;
61 pub.term_destination = term_destination_thunk;
64 static void init_destination_thunk(j_compress_ptr ptr)
66 ((VectorDestinationManager *)(ptr->dest))->init_destination();
69 inline void init_destination()
74 static boolean empty_output_buffer_thunk(j_compress_ptr ptr)
76 return ((VectorDestinationManager *)(ptr->dest))->empty_output_buffer();
79 inline bool empty_output_buffer()
81 make_room(dest.size()); // Should ignore pub.free_in_buffer!
85 inline void make_room(size_t bytes_used)
87 dest.resize(bytes_used + 4096);
88 dest.resize(dest.capacity());
89 pub.next_output_byte = (uint8_t *)dest.data() + bytes_used;
90 pub.free_in_buffer = dest.size() - bytes_used;
93 static void term_destination_thunk(j_compress_ptr ptr)
95 ((VectorDestinationManager *)(ptr->dest))->term_destination();
98 inline void term_destination()
100 dest.resize(dest.size() - pub.free_in_buffer);
103 static_assert(std::is_standard_layout<VectorDestinationManager>::value, "");
105 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)
107 steady_clock::time_point start = steady_clock::now();
108 VectorDestinationManager dest;
110 jpeg_compress_struct cinfo;
112 cinfo.err = jpeg_std_error(&jerr);
113 jpeg_create_compress(&cinfo);
115 cinfo.dest = (jpeg_destination_mgr *)&dest;
116 cinfo.input_components = 3;
117 cinfo.in_color_space = JCS_RGB;
118 jpeg_set_defaults(&cinfo);
119 constexpr int quality = 90;
120 jpeg_set_quality(&cinfo, quality, /*force_baseline=*/false);
122 cinfo.image_width = width;
123 cinfo.image_height = height;
124 cinfo.raw_data_in = true;
125 jpeg_set_colorspace(&cinfo, JCS_YCbCr);
126 cinfo.comp_info[0].h_samp_factor = 2;
127 cinfo.comp_info[0].v_samp_factor = 1;
128 cinfo.comp_info[1].h_samp_factor = 1;
129 cinfo.comp_info[1].v_samp_factor = 1;
130 cinfo.comp_info[2].h_samp_factor = 1;
131 cinfo.comp_info[2].v_samp_factor = 1;
132 cinfo.CCIR601_sampling = true; // Seems to be mostly ignored by libjpeg, though.
133 jpeg_start_compress(&cinfo, true);
135 // This comment marker is private to FFmpeg. It signals limited Y'CbCr range
136 // (and nothing else).
137 jpeg_write_marker(&cinfo, JPEG_COM, (const JOCTET *)"CS=ITU601", strlen("CS=ITU601"));
139 if (!exif_data.empty()) {
140 jpeg_write_marker(&cinfo, JPEG_APP0 + 1, (const JOCTET *)exif_data.data(), exif_data.size());
143 JSAMPROW yptr[8], cbptr[8], crptr[8];
144 JSAMPARRAY data[3] = { yptr, cbptr, crptr };
145 for (unsigned y = 0; y < height; y += 8) {
146 for (unsigned yy = 0; yy < 8; ++yy) {
147 yptr[yy] = const_cast<JSAMPROW>(&y_data[(y + yy) * width]);
148 cbptr[yy] = const_cast<JSAMPROW>(&cb_data[(y + yy) * width / 2]);
149 crptr[yy] = const_cast<JSAMPROW>(&cr_data[(y + yy) * width / 2]);
152 jpeg_write_raw_data(&cinfo, data, /*num_lines=*/8);
155 jpeg_finish_compress(&cinfo);
156 jpeg_destroy_compress(&cinfo);
158 steady_clock::time_point stop = steady_clock::now();
159 metric_jpeg_encode_time_seconds.count_event(duration<double>(stop - start).count());
161 return move(dest.dest);
164 string encode_jpeg_from_pbo(void *contents, unsigned width, unsigned height, const string exif_data)
166 unsigned chroma_width = width / 2;
168 const uint8_t *y = (const uint8_t *)contents;
169 const uint8_t *cb = (const uint8_t *)contents + width * height;
170 const uint8_t *cr = (const uint8_t *)contents + width * height + chroma_width * height;
171 return encode_jpeg(y, cb, cr, width, height, move(exif_data));
174 VideoStream::VideoStream(AVFormatContext *file_avctx)
175 : avctx(file_avctx), output_fast_forward(file_avctx != nullptr)
177 call_once(video_metrics_inited, [] {
178 vector<double> quantiles{ 0.01, 0.1, 0.25, 0.5, 0.75, 0.9, 0.99 };
179 metric_jpeg_encode_time_seconds.init(quantiles, 60.0);
180 global_metrics.add("jpeg_encode_time_seconds", &metric_jpeg_encode_time_seconds);
181 metric_fade_fence_wait_time_seconds.init(quantiles, 60.0);
182 global_metrics.add("fade_fence_wait_time_seconds", &metric_fade_fence_wait_time_seconds);
183 metric_interpolation_fence_wait_time_seconds.init(quantiles, 60.0);
184 global_metrics.add("interpolation_fence_wait_time_seconds", &metric_interpolation_fence_wait_time_seconds);
185 metric_fade_latency_seconds.init(quantiles, 60.0);
186 global_metrics.add("fade_latency_seconds", &metric_fade_latency_seconds);
187 metric_interpolation_latency_seconds.init(quantiles, 60.0);
188 global_metrics.add("interpolation_latency_seconds", &metric_interpolation_latency_seconds);
191 ycbcr_converter.reset(new YCbCrConverter(YCbCrConverter::OUTPUT_TO_DUAL_YCBCR, /*resource_pool=*/nullptr));
192 ycbcr_semiplanar_converter.reset(new YCbCrConverter(YCbCrConverter::OUTPUT_TO_SEMIPLANAR, /*resource_pool=*/nullptr));
194 GLuint input_tex[num_interpolate_slots], gray_tex[num_interpolate_slots];
195 GLuint fade_y_output_tex[num_interpolate_slots], fade_cbcr_output_tex[num_interpolate_slots];
196 GLuint cb_tex[num_interpolate_slots], cr_tex[num_interpolate_slots];
198 glCreateTextures(GL_TEXTURE_2D_ARRAY, num_interpolate_slots, input_tex);
199 glCreateTextures(GL_TEXTURE_2D_ARRAY, num_interpolate_slots, gray_tex);
200 glCreateTextures(GL_TEXTURE_2D, num_interpolate_slots, fade_y_output_tex);
201 glCreateTextures(GL_TEXTURE_2D, num_interpolate_slots, fade_cbcr_output_tex);
202 glCreateTextures(GL_TEXTURE_2D, num_interpolate_slots, cb_tex);
203 glCreateTextures(GL_TEXTURE_2D, num_interpolate_slots, cr_tex);
206 size_t width = global_flags.width, height = global_flags.height;
207 int levels = find_num_levels(width, height);
208 for (size_t i = 0; i < num_interpolate_slots; ++i) {
209 glTextureStorage3D(input_tex[i], levels, GL_RGBA8, width, height, 2);
211 glTextureStorage3D(gray_tex[i], levels, GL_R8, width, height, 2);
213 glTextureStorage2D(fade_y_output_tex[i], 1, GL_R8, width, height);
215 glTextureStorage2D(fade_cbcr_output_tex[i], 1, GL_RG8, width, height);
217 glTextureStorage2D(cb_tex[i], 1, GL_R8, width / 2, height);
219 glTextureStorage2D(cr_tex[i], 1, GL_R8, width / 2, height);
222 unique_ptr<InterpolatedFrameResources> resource(new InterpolatedFrameResources);
223 resource->owner = this;
224 resource->input_tex = input_tex[i];
225 resource->gray_tex = gray_tex[i];
226 resource->fade_y_output_tex = fade_y_output_tex[i];
227 resource->fade_cbcr_output_tex = fade_cbcr_output_tex[i];
228 resource->cb_tex = cb_tex[i];
229 resource->cr_tex = cr_tex[i];
230 glCreateFramebuffers(2, resource->input_fbos);
232 glCreateFramebuffers(1, &resource->fade_fbo);
235 glNamedFramebufferTextureLayer(resource->input_fbos[0], GL_COLOR_ATTACHMENT0, input_tex[i], 0, 0);
237 glNamedFramebufferTextureLayer(resource->input_fbos[0], GL_COLOR_ATTACHMENT1, gray_tex[i], 0, 0);
239 glNamedFramebufferTextureLayer(resource->input_fbos[1], GL_COLOR_ATTACHMENT0, input_tex[i], 0, 1);
241 glNamedFramebufferTextureLayer(resource->input_fbos[1], GL_COLOR_ATTACHMENT1, gray_tex[i], 0, 1);
243 glNamedFramebufferTexture(resource->fade_fbo, GL_COLOR_ATTACHMENT0, fade_y_output_tex[i], 0);
245 glNamedFramebufferTexture(resource->fade_fbo, GL_COLOR_ATTACHMENT1, fade_cbcr_output_tex[i], 0);
248 GLuint bufs[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
249 glNamedFramebufferDrawBuffers(resource->input_fbos[0], 2, bufs);
251 glNamedFramebufferDrawBuffers(resource->input_fbos[1], 2, bufs);
253 glNamedFramebufferDrawBuffers(resource->fade_fbo, 2, bufs);
256 glCreateBuffers(1, &resource->pbo);
258 glNamedBufferStorage(resource->pbo, width * height * 4, nullptr, GL_MAP_READ_BIT | GL_MAP_PERSISTENT_BIT);
260 resource->pbo_contents = glMapNamedBufferRange(resource->pbo, 0, width * height * 4, GL_MAP_READ_BIT | GL_MAP_PERSISTENT_BIT);
261 interpolate_resources.push_back(move(resource));
267 if (global_flags.interpolation_quality == 0 ||
268 global_flags.interpolation_quality == 1) {
269 op = operating_point1;
270 } else if (global_flags.interpolation_quality == 2) {
271 op = operating_point2;
272 } else if (global_flags.interpolation_quality == 3) {
273 op = operating_point3;
274 } else if (global_flags.interpolation_quality == 4) {
275 op = operating_point4;
277 // Quality 0 will be changed to 1 in flags.cpp.
281 compute_flow.reset(new DISComputeFlow(width, height, op));
282 interpolate.reset(new Interpolate(op, /*split_ycbcr_output=*/true));
283 interpolate_no_split.reset(new Interpolate(op, /*split_ycbcr_output=*/false));
284 chroma_subsampler.reset(new ChromaSubsampler);
287 // The “last frame” is initially black.
288 unique_ptr<uint8_t[]> y(new uint8_t[global_flags.width * global_flags.height]);
289 unique_ptr<uint8_t[]> cb_or_cr(new uint8_t[(global_flags.width / 2) * global_flags.height]);
290 memset(y.get(), 16, global_flags.width * global_flags.height);
291 memset(cb_or_cr.get(), 128, (global_flags.width / 2) * global_flags.height);
292 last_frame = encode_jpeg(y.get(), cb_or_cr.get(), cb_or_cr.get(), global_flags.width, global_flags.height, /*exif_data=*/"");
294 if (file_avctx != nullptr) {
295 with_subtitles = Mux::WITHOUT_SUBTITLES;
297 with_subtitles = Mux::WITH_SUBTITLES;
301 VideoStream::~VideoStream()
303 if (last_flow_tex != 0) {
304 compute_flow->release_texture(last_flow_tex);
307 for (const unique_ptr<InterpolatedFrameResources> &resource : interpolate_resources) {
308 glUnmapNamedBuffer(resource->pbo);
310 glDeleteBuffers(1, &resource->pbo);
312 glDeleteFramebuffers(2, resource->input_fbos);
314 glDeleteFramebuffers(1, &resource->fade_fbo);
316 glDeleteTextures(1, &resource->input_tex);
318 glDeleteTextures(1, &resource->gray_tex);
320 glDeleteTextures(1, &resource->fade_y_output_tex);
322 glDeleteTextures(1, &resource->fade_cbcr_output_tex);
324 glDeleteTextures(1, &resource->cb_tex);
326 glDeleteTextures(1, &resource->cr_tex);
329 assert(interpolate_resources.size() == num_interpolate_slots);
332 void VideoStream::start()
334 if (avctx == nullptr) {
335 avctx = avformat_alloc_context();
337 // We use Matroska, because it's pretty much the only mux where FFmpeg
338 // allows writing chroma location to override JFIF's default center placement.
339 // (Note that at the time of writing, however, FFmpeg does not correctly
340 // _read_ this information!)
341 avctx->oformat = av_guess_format("matroska", nullptr, nullptr);
343 uint8_t *buf = (uint8_t *)av_malloc(MUX_BUFFER_SIZE);
344 avctx->pb = avio_alloc_context(buf, MUX_BUFFER_SIZE, 1, this, nullptr, nullptr, nullptr);
345 avctx->pb->write_data_type = &VideoStream::write_packet2_thunk;
346 avctx->pb->ignore_boundary_point = 1;
348 avctx->flags = AVFMT_FLAG_CUSTOM_IO;
351 AVCodecParameters *audio_codecpar = avcodec_parameters_alloc();
353 audio_codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
354 audio_codecpar->codec_id = AV_CODEC_ID_PCM_S32LE;
355 audio_codecpar->channel_layout = AV_CH_LAYOUT_STEREO;
356 audio_codecpar->channels = 2;
357 audio_codecpar->sample_rate = OUTPUT_FREQUENCY;
359 size_t width = global_flags.width, height = global_flags.height; // Doesn't matter for MJPEG.
360 mux.reset(new Mux(avctx, width, height, Mux::CODEC_MJPEG, /*video_extradata=*/"", audio_codecpar,
361 AVCOL_SPC_BT709, COARSE_TIMEBASE, /*write_callback=*/nullptr, Mux::WRITE_FOREGROUND, {}, with_subtitles));
363 avcodec_parameters_free(&audio_codecpar);
364 encode_thread = thread(&VideoStream::encode_thread_func, this);
367 void VideoStream::stop()
370 queue_changed.notify_all();
372 encode_thread.join();
375 void VideoStream::clear_queue()
377 deque<QueuedFrame> q;
380 lock_guard<mutex> lock(queue_lock);
381 q = move(frame_queue);
384 // These are not RAII-ed, unfortunately, so we'll need to clean them ourselves.
385 // Note that release_texture() is thread-safe.
386 for (const QueuedFrame &qf : q) {
387 if (qf.type == QueuedFrame::INTERPOLATED ||
388 qf.type == QueuedFrame::FADED_INTERPOLATED) {
389 if (qf.flow_tex != 0) {
390 compute_flow->release_texture(qf.flow_tex);
393 if (qf.type == QueuedFrame::INTERPOLATED) {
394 interpolate->release_texture(qf.output_tex);
395 interpolate->release_texture(qf.cbcr_tex);
399 // Destroy q outside the mutex, as that would be a double-lock.
402 void VideoStream::schedule_original_frame(steady_clock::time_point local_pts,
403 int64_t output_pts, function<void()> &&display_func,
404 QueueSpotHolder &&queue_spot_holder,
405 FrameOnDisk frame, const string &subtitle, bool include_audio)
407 fprintf(stderr, "output_pts=%" PRId64 " original input_pts=%" PRId64 "\n", output_pts, frame.pts);
410 qf.local_pts = local_pts;
411 qf.type = QueuedFrame::ORIGINAL;
412 qf.output_pts = output_pts;
413 qf.display_func = move(display_func);
414 qf.queue_spot_holder = move(queue_spot_holder);
415 qf.subtitle = subtitle;
416 FrameReader::Frame read_frame = frame_reader.read_frame(frame, /*read_video=*/true, include_audio);
417 qf.encoded_jpeg.reset(new string(move(read_frame.video)));
418 qf.audio = move(read_frame.audio);
420 lock_guard<mutex> lock(queue_lock);
421 frame_queue.push_back(move(qf));
422 queue_changed.notify_all();
425 void VideoStream::schedule_faded_frame(steady_clock::time_point local_pts, int64_t output_pts,
426 function<void()> &&display_func,
427 QueueSpotHolder &&queue_spot_holder,
428 FrameOnDisk frame1_spec, FrameOnDisk frame2_spec,
429 float fade_alpha, const string &subtitle)
431 fprintf(stderr, "output_pts=%" PRId64 " faded input_pts=%" PRId64 ",%" PRId64 " fade_alpha=%.2f\n", output_pts, frame1_spec.pts, frame2_spec.pts, fade_alpha);
433 // Get the temporary OpenGL resources we need for doing the fade.
434 // (We share these with interpolated frames, which is slightly
435 // overkill, but there's no need to waste resources on keeping
436 // separate pools around.)
437 BorrowedInterpolatedFrameResources resources;
439 lock_guard<mutex> lock(queue_lock);
440 if (interpolate_resources.empty()) {
441 fprintf(stderr, "WARNING: Too many interpolated frames already in transit; dropping one.\n");
444 resources = BorrowedInterpolatedFrameResources(interpolate_resources.front().release());
445 interpolate_resources.pop_front();
450 shared_ptr<Frame> frame1 = decode_jpeg_with_cache(frame1_spec, DECODE_IF_NOT_IN_CACHE, &frame_reader, &did_decode);
451 shared_ptr<Frame> frame2 = decode_jpeg_with_cache(frame2_spec, DECODE_IF_NOT_IN_CACHE, &frame_reader, &did_decode);
452 wait_for_upload(frame1);
453 wait_for_upload(frame2);
455 ycbcr_semiplanar_converter->prepare_chain_for_fade(frame1, frame2, fade_alpha)->render_to_fbo(resources->fade_fbo, global_flags.width, global_flags.height);
458 qf.local_pts = local_pts;
459 qf.type = QueuedFrame::FADED;
460 qf.output_pts = output_pts;
461 qf.frame1 = frame1_spec;
462 qf.display_func = move(display_func);
463 qf.queue_spot_holder = move(queue_spot_holder);
464 qf.subtitle = subtitle;
466 qf.secondary_frame = frame2_spec;
468 // Subsample and split Cb/Cr.
469 chroma_subsampler->subsample_chroma(resources->fade_cbcr_output_tex, global_flags.width, global_flags.height, resources->cb_tex, resources->cr_tex);
471 // Read it down (asynchronously) to the CPU.
472 glPixelStorei(GL_PACK_ROW_LENGTH, 0);
473 glBindBuffer(GL_PIXEL_PACK_BUFFER, resources->pbo);
475 glGetTextureImage(resources->fade_y_output_tex, 0, GL_RED, GL_UNSIGNED_BYTE, global_flags.width * global_flags.height * 4, BUFFER_OFFSET(0));
477 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));
479 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));
481 glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
483 // Set a fence we can wait for to make sure the CPU sees the read.
484 glMemoryBarrier(GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT);
486 qf.fence_created = steady_clock::now();
487 qf.fence = RefCountedGLsync(GL_SYNC_GPU_COMMANDS_COMPLETE, /*flags=*/0);
489 qf.resources = move(resources);
490 qf.local_pts = local_pts;
492 lock_guard<mutex> lock(queue_lock);
493 frame_queue.push_back(move(qf));
494 queue_changed.notify_all();
497 void VideoStream::schedule_interpolated_frame(steady_clock::time_point local_pts,
498 int64_t output_pts, function<void(shared_ptr<Frame>)> &&display_func,
499 QueueSpotHolder &&queue_spot_holder,
500 FrameOnDisk frame1, FrameOnDisk frame2,
501 float alpha, FrameOnDisk secondary_frame, float fade_alpha, const string &subtitle,
504 if (secondary_frame.pts != -1) {
505 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);
507 fprintf(stderr, "output_pts=%" PRId64 " interpolated input_pts1=%" PRId64 " input_pts2=%" PRId64 " alpha=%.3f\n", output_pts, frame1.pts, frame2.pts, alpha);
510 // Get the temporary OpenGL resources we need for doing the interpolation.
511 BorrowedInterpolatedFrameResources resources;
513 lock_guard<mutex> lock(queue_lock);
514 if (interpolate_resources.empty()) {
515 fprintf(stderr, "WARNING: Too many interpolated frames already in transit; dropping one.\n");
518 resources = BorrowedInterpolatedFrameResources(interpolate_resources.front().release());
519 interpolate_resources.pop_front();
523 qf.type = (secondary_frame.pts == -1) ? QueuedFrame::INTERPOLATED : QueuedFrame::FADED_INTERPOLATED;
524 qf.output_pts = output_pts;
525 qf.display_decoded_func = move(display_func);
526 qf.queue_spot_holder = move(queue_spot_holder);
527 qf.local_pts = local_pts;
528 qf.subtitle = subtitle;
531 qf.audio = frame_reader.read_frame(frame1, /*read_video=*/false, /*read_audio=*/true).audio;
536 // Convert frame0 and frame1 to OpenGL textures.
537 for (size_t frame_no = 0; frame_no < 2; ++frame_no) {
538 FrameOnDisk frame_spec = frame_no == 1 ? frame2 : frame1;
540 shared_ptr<Frame> frame = decode_jpeg_with_cache(frame_spec, DECODE_IF_NOT_IN_CACHE, &frame_reader, &did_decode);
541 wait_for_upload(frame);
542 ycbcr_converter->prepare_chain_for_conversion(frame)->render_to_fbo(resources->input_fbos[frame_no], global_flags.width, global_flags.height);
544 qf.exif_data = frame->exif_data; // Use the white point from the last frame.
548 glGenerateTextureMipmap(resources->input_tex);
550 glGenerateTextureMipmap(resources->gray_tex);
554 if (last_flow_tex != 0 && frame1 == last_frame1 && frame2 == last_frame2) {
555 // Reuse the flow from previous computation. This frequently happens
556 // if we slow down by more than 2x, so that there are multiple interpolated
557 // frames between each original.
558 flow_tex = last_flow_tex;
561 // Cache miss, so release last_flow_tex.
562 qf.flow_tex = last_flow_tex;
565 flow_tex = compute_flow->exec(resources->gray_tex, DISComputeFlow::FORWARD_AND_BACKWARD, DISComputeFlow::DO_NOT_RESIZE_FLOW);
568 // Store the flow texture for possible reuse next frame.
569 last_flow_tex = flow_tex;
570 last_frame1 = frame1;
571 last_frame2 = frame2;
574 if (secondary_frame.pts != -1) {
575 // Fade. First kick off the interpolation.
576 tie(qf.output_tex, ignore) = interpolate_no_split->exec(resources->input_tex, resources->gray_tex, flow_tex, global_flags.width, global_flags.height, alpha);
579 // Now decode the image we are fading against.
581 shared_ptr<Frame> frame2 = decode_jpeg_with_cache(secondary_frame, DECODE_IF_NOT_IN_CACHE, &frame_reader, &did_decode);
582 wait_for_upload(frame2);
584 // Then fade against it, putting it into the fade Y' and CbCr textures.
585 RGBTriplet neutral_color = get_neutral_color(qf.exif_data);
586 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);
588 // Subsample and split Cb/Cr.
589 chroma_subsampler->subsample_chroma(resources->fade_cbcr_output_tex, global_flags.width, global_flags.height, resources->cb_tex, resources->cr_tex);
591 interpolate_no_split->release_texture(qf.output_tex);
593 // We already applied the white balance, so don't have the client redo it.
594 qf.exif_data.clear();
596 tie(qf.output_tex, qf.cbcr_tex) = interpolate->exec(resources->input_tex, resources->gray_tex, flow_tex, global_flags.width, global_flags.height, alpha);
599 // Subsample and split Cb/Cr.
600 chroma_subsampler->subsample_chroma(qf.cbcr_tex, global_flags.width, global_flags.height, resources->cb_tex, resources->cr_tex);
603 // We could have released qf.flow_tex here, but to make sure we don't cause a stall
604 // when trying to reuse it for the next frame, we can just as well hold on to it
605 // and release it only when the readback is done.
607 // TODO: This is maybe less relevant now that qf.flow_tex contains the texture we used
608 // _last_ frame, not this one.
610 // Read it down (asynchronously) to the CPU.
611 glPixelStorei(GL_PACK_ROW_LENGTH, 0);
612 glBindBuffer(GL_PIXEL_PACK_BUFFER, resources->pbo);
614 if (secondary_frame.pts != -1) {
615 glGetTextureImage(resources->fade_y_output_tex, 0, GL_RED, GL_UNSIGNED_BYTE, global_flags.width * global_flags.height * 4, BUFFER_OFFSET(0));
617 glGetTextureImage(qf.output_tex, 0, GL_RED, GL_UNSIGNED_BYTE, global_flags.width * global_flags.height * 4, BUFFER_OFFSET(0));
620 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));
622 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));
624 glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
626 // Set a fence we can wait for to make sure the CPU sees the read.
627 glMemoryBarrier(GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT);
629 qf.fence_created = steady_clock::now();
630 qf.fence = RefCountedGLsync(GL_SYNC_GPU_COMMANDS_COMPLETE, /*flags=*/0);
632 qf.resources = move(resources);
634 lock_guard<mutex> lock(queue_lock);
635 frame_queue.push_back(move(qf));
636 queue_changed.notify_all();
639 void VideoStream::schedule_refresh_frame(steady_clock::time_point local_pts,
640 int64_t output_pts, function<void()> &&display_func,
641 QueueSpotHolder &&queue_spot_holder, const string &subtitle)
644 qf.type = QueuedFrame::REFRESH;
645 qf.output_pts = output_pts;
646 qf.display_func = move(display_func);
647 qf.queue_spot_holder = move(queue_spot_holder);
648 qf.subtitle = subtitle;
650 lock_guard<mutex> lock(queue_lock);
651 frame_queue.push_back(move(qf));
652 queue_changed.notify_all();
655 void VideoStream::schedule_silence(steady_clock::time_point local_pts, int64_t output_pts,
656 int64_t length_pts, QueueSpotHolder &&queue_spot_holder)
659 qf.type = QueuedFrame::SILENCE;
660 qf.output_pts = output_pts;
661 qf.queue_spot_holder = move(queue_spot_holder);
662 qf.silence_length_pts = length_pts;
664 lock_guard<mutex> lock(queue_lock);
665 frame_queue.push_back(move(qf));
666 queue_changed.notify_all();
671 RefCountedTexture clone_r8_texture(GLuint src_tex, unsigned width, unsigned height)
674 glCreateTextures(GL_TEXTURE_2D, 1, &tex);
676 glTextureStorage2D(tex, 1, GL_R8, width, height);
678 glCopyImageSubData(src_tex, GL_TEXTURE_2D, 0, 0, 0, 0,
679 tex, GL_TEXTURE_2D, 0, 0, 0, 0,
682 glTextureParameteri(tex, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
684 glTextureParameteri(tex, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
686 glTextureParameteri(tex, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
688 glTextureParameteri(tex, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
691 return RefCountedTexture(new GLuint(tex), TextureDeleter());
696 void VideoStream::encode_thread_func()
698 pthread_setname_np(pthread_self(), "VideoStream");
699 QSurface *surface = create_surface();
700 QOpenGLContext *context = create_context(surface);
701 bool ok = make_current(context, surface);
703 fprintf(stderr, "Video stream couldn't get an OpenGL context\n");
709 while (!should_quit) {
712 unique_lock<mutex> lock(queue_lock);
714 // Wait until we have a frame to play.
715 queue_changed.wait(lock, [this] {
716 return !frame_queue.empty() || should_quit;
721 steady_clock::time_point frame_start = frame_queue.front().local_pts;
723 // Now sleep until the frame is supposed to start (the usual case),
724 // _or_ clear_queue() happened.
726 if (output_fast_forward) {
727 aborted = frame_queue.empty() || frame_queue.front().local_pts != frame_start;
729 aborted = queue_changed.wait_until(lock, frame_start, [this, frame_start] {
730 return frame_queue.empty() || frame_queue.front().local_pts != frame_start;
734 // clear_queue() happened, so don't play this frame after all.
737 qf = move(frame_queue.front());
738 frame_queue.pop_front();
741 // Hack: We mux the subtitle packet one time unit before the actual frame,
742 // so that Nageru is sure to get it first.
743 if (!qf.subtitle.empty() && with_subtitles == Mux::WITH_SUBTITLES) {
745 av_init_packet(&pkt);
746 pkt.stream_index = mux->get_subtitle_stream_idx();
747 assert(pkt.stream_index != -1);
748 pkt.data = (uint8_t *)qf.subtitle.data();
749 pkt.size = qf.subtitle.size();
751 pkt.duration = lrint(TIMEBASE / global_flags.output_framerate); // Doesn't really matter for Nageru.
752 mux->add_packet(pkt, qf.output_pts - 1, qf.output_pts - 1);
755 if (qf.type == QueuedFrame::ORIGINAL) {
756 // Send the JPEG frame on, unchanged.
757 string jpeg = move(*qf.encoded_jpeg);
759 av_init_packet(&pkt);
760 pkt.stream_index = 0;
761 pkt.data = (uint8_t *)jpeg.data();
762 pkt.size = jpeg.size();
763 pkt.flags = AV_PKT_FLAG_KEY;
764 mux->add_packet(pkt, qf.output_pts, qf.output_pts);
765 last_frame = move(jpeg);
767 add_audio_or_silence(qf);
768 } else if (qf.type == QueuedFrame::FADED) {
769 steady_clock::time_point start = steady_clock::now();
770 glClientWaitSync(qf.fence.get(), /*flags=*/0, GL_TIMEOUT_IGNORED);
771 steady_clock::time_point stop = steady_clock::now();
772 metric_fade_fence_wait_time_seconds.count_event(duration<double>(stop - start).count());
773 metric_fade_latency_seconds.count_event(duration<double>(stop - qf.fence_created).count());
775 // Now JPEG encode it, and send it on to the stream.
776 string jpeg = encode_jpeg_from_pbo(qf.resources->pbo_contents, global_flags.width, global_flags.height, /*exif_data=*/"");
779 av_init_packet(&pkt);
780 pkt.stream_index = 0;
781 pkt.data = (uint8_t *)jpeg.data();
782 pkt.size = jpeg.size();
783 pkt.flags = AV_PKT_FLAG_KEY;
784 mux->add_packet(pkt, qf.output_pts, qf.output_pts);
785 last_frame = move(jpeg);
787 add_audio_or_silence(qf);
788 } else if (qf.type == QueuedFrame::INTERPOLATED || qf.type == QueuedFrame::FADED_INTERPOLATED) {
789 steady_clock::time_point start = steady_clock::now();
790 glClientWaitSync(qf.fence.get(), /*flags=*/0, GL_TIMEOUT_IGNORED);
791 steady_clock::time_point stop = steady_clock::now();
792 metric_interpolation_fence_wait_time_seconds.count_event(duration<double>(stop - start).count());
793 metric_interpolation_latency_seconds.count_event(duration<double>(stop - qf.fence_created).count());
795 // Send it on to display.
796 if (qf.display_decoded_func != nullptr) {
797 shared_ptr<Frame> frame(new Frame);
798 if (qf.type == QueuedFrame::FADED_INTERPOLATED) {
799 frame->y = clone_r8_texture(qf.resources->fade_y_output_tex, global_flags.width, global_flags.height);
801 frame->y = clone_r8_texture(qf.output_tex, global_flags.width, global_flags.height);
803 frame->cb = clone_r8_texture(qf.resources->cb_tex, global_flags.width / 2, global_flags.height);
804 frame->cr = clone_r8_texture(qf.resources->cr_tex, global_flags.width / 2, global_flags.height);
805 frame->width = global_flags.width;
806 frame->height = global_flags.height;
807 frame->chroma_subsampling_x = 2;
808 frame->chroma_subsampling_y = 1;
809 frame->uploaded_ui_thread = RefCountedGLsync(GL_SYNC_GPU_COMMANDS_COMPLETE, /*flags=*/0);
810 qf.display_decoded_func(move(frame));
813 // Now JPEG encode it, and send it on to the stream.
814 string jpeg = encode_jpeg_from_pbo(qf.resources->pbo_contents, global_flags.width, global_flags.height, move(qf.exif_data));
815 if (qf.flow_tex != 0) {
816 compute_flow->release_texture(qf.flow_tex);
818 if (qf.type != QueuedFrame::FADED_INTERPOLATED) {
819 interpolate->release_texture(qf.output_tex);
820 interpolate->release_texture(qf.cbcr_tex);
824 av_init_packet(&pkt);
825 pkt.stream_index = 0;
826 pkt.data = (uint8_t *)jpeg.data();
827 pkt.size = jpeg.size();
828 pkt.flags = AV_PKT_FLAG_KEY;
829 mux->add_packet(pkt, qf.output_pts, qf.output_pts);
830 last_frame = move(jpeg);
832 add_audio_or_silence(qf);
833 } else if (qf.type == QueuedFrame::REFRESH) {
835 av_init_packet(&pkt);
836 pkt.stream_index = 0;
837 pkt.data = (uint8_t *)last_frame.data();
838 pkt.size = last_frame.size();
839 pkt.flags = AV_PKT_FLAG_KEY;
840 mux->add_packet(pkt, qf.output_pts, qf.output_pts);
842 add_audio_or_silence(qf); // Definitely silence.
843 } else if (qf.type == QueuedFrame::SILENCE) {
844 add_silence(qf.output_pts, qf.silence_length_pts);
848 if (qf.display_func != nullptr) {
854 int VideoStream::write_packet2_thunk(void *opaque, uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
856 VideoStream *video_stream = (VideoStream *)opaque;
857 return video_stream->write_packet2(buf, buf_size, type, time);
860 int VideoStream::write_packet2(uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
862 if (type == AVIO_DATA_MARKER_SYNC_POINT || type == AVIO_DATA_MARKER_BOUNDARY_POINT) {
863 seen_sync_markers = true;
864 } else if (type == AVIO_DATA_MARKER_UNKNOWN && !seen_sync_markers) {
865 // We don't know if this is a keyframe or not (the muxer could
866 // avoid marking it), so we just have to make the best of it.
867 type = AVIO_DATA_MARKER_SYNC_POINT;
870 HTTPD::StreamID stream_id{ HTTPD::MAIN_STREAM, 0 };
871 if (type == AVIO_DATA_MARKER_HEADER) {
872 stream_mux_header.append((char *)buf, buf_size);
873 global_httpd->set_header(stream_id, stream_mux_header);
875 global_httpd->add_data(stream_id, (char *)buf, buf_size, type == AVIO_DATA_MARKER_SYNC_POINT, time, AVRational{ AV_TIME_BASE, 1 });
880 void VideoStream::add_silence(int64_t pts, int64_t length_pts)
882 // At 59.94, this will never quite add up (even discounting refresh frames,
883 // which have unpredictable length), but hopefully, the player in the other
884 // end should be able to stretch silence easily enough.
885 long num_samples = lrint(length_pts * double(OUTPUT_FREQUENCY) / double(TIMEBASE)) * 2;
886 uint8_t *zero = (uint8_t *)calloc(num_samples, sizeof(int32_t));
889 av_init_packet(&pkt);
890 pkt.stream_index = 1;
892 pkt.size = num_samples * sizeof(int32_t);
893 pkt.flags = AV_PKT_FLAG_KEY;
894 mux->add_packet(pkt, pts, pts);
899 void VideoStream::add_audio_or_silence(const QueuedFrame &qf)
901 if (qf.audio.empty()) {
902 int64_t frame_length = lrint(double(TIMEBASE) / global_flags.output_framerate);
903 add_silence(qf.output_pts, frame_length);
906 av_init_packet(&pkt);
907 pkt.stream_index = 1;
908 pkt.data = (uint8_t *)qf.audio.data();
909 pkt.size = qf.audio.size();
910 pkt.flags = AV_PKT_FLAG_KEY;
911 mux->add_packet(pkt, qf.output_pts, qf.output_pts);