]> git.sesse.net Git - nageru/blob - futatabi/video_stream.cpp
Set CEF autoplay policy to be more lenient.
[nageru] / futatabi / 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 "chroma_subsampler.h"
9 #include "exif_parser.h"
10 #include "flags.h"
11 #include "flow.h"
12 #include "jpeg_frame_view.h"
13 #include "movit/util.h"
14 #include "pbo_pool.h"
15 #include "player.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"
21 #include "util.h"
22 #include "ycbcr_converter.h"
23
24 #include <epoxy/glx.h>
25 #include <jpeglib.h>
26 #include <unistd.h>
27
28 using namespace movit;
29 using namespace std;
30 using namespace std::chrono;
31
32 namespace {
33
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;
40
41 void wait_for_upload(shared_ptr<Frame> &frame)
42 {
43         if (frame->uploaded_interpolation != nullptr) {
44                 glWaitSync(frame->uploaded_interpolation.get(), /*flags=*/0, GL_TIMEOUT_IGNORED);
45                 frame->uploaded_interpolation.reset();
46         }
47 }
48
49 }  // namespace
50
51 extern HTTPD *global_httpd;
52
53 struct VectorDestinationManager {
54         jpeg_destination_mgr pub;
55         string dest;
56
57         VectorDestinationManager()
58         {
59                 pub.init_destination = init_destination_thunk;
60                 pub.empty_output_buffer = empty_output_buffer_thunk;
61                 pub.term_destination = term_destination_thunk;
62         }
63
64         static void init_destination_thunk(j_compress_ptr ptr)
65         {
66                 ((VectorDestinationManager *)(ptr->dest))->init_destination();
67         }
68
69         inline void init_destination()
70         {
71                 make_room(0);
72         }
73
74         static boolean empty_output_buffer_thunk(j_compress_ptr ptr)
75         {
76                 return ((VectorDestinationManager *)(ptr->dest))->empty_output_buffer();
77         }
78
79         inline bool empty_output_buffer()
80         {
81                 make_room(dest.size());  // Should ignore pub.free_in_buffer!
82                 return true;
83         }
84
85         inline void make_room(size_t bytes_used)
86         {
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;
91         }
92
93         static void term_destination_thunk(j_compress_ptr ptr)
94         {
95                 ((VectorDestinationManager *)(ptr->dest))->term_destination();
96         }
97
98         inline void term_destination()
99         {
100                 dest.resize(dest.size() - pub.free_in_buffer);
101         }
102 };
103 static_assert(std::is_standard_layout<VectorDestinationManager>::value, "");
104
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)
106 {
107         steady_clock::time_point start = steady_clock::now();
108         VectorDestinationManager dest;
109
110         jpeg_compress_struct cinfo;
111         jpeg_error_mgr jerr;
112         cinfo.err = jpeg_std_error(&jerr);
113         jpeg_create_compress(&cinfo);
114
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);
121
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);
134
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"));
138
139         if (!exif_data.empty()) {
140                 jpeg_write_marker(&cinfo, JPEG_APP0 + 1, (const JOCTET *)exif_data.data(), exif_data.size());
141         }
142
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]);
150                 }
151
152                 jpeg_write_raw_data(&cinfo, data, /*num_lines=*/8);
153         }
154
155         jpeg_finish_compress(&cinfo);
156         jpeg_destroy_compress(&cinfo);
157
158         steady_clock::time_point stop = steady_clock::now();
159         metric_jpeg_encode_time_seconds.count_event(duration<double>(stop - start).count());
160
161         return move(dest.dest);
162 }
163
164 string encode_jpeg_from_pbo(void *contents, unsigned width, unsigned height, const string exif_data)
165 {
166         unsigned chroma_width = width / 2;
167
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));
172 }
173
174 VideoStream::VideoStream(AVFormatContext *file_avctx)
175         : avctx(file_avctx), output_fast_forward(file_avctx != nullptr)
176 {
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);
189         });
190
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));
193
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];
197
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);
204         check_error();
205
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);
210                 check_error();
211                 glTextureStorage3D(gray_tex[i], levels, GL_R8, width, height, 2);
212                 check_error();
213                 glTextureStorage2D(fade_y_output_tex[i], 1, GL_R8, width, height);
214                 check_error();
215                 glTextureStorage2D(fade_cbcr_output_tex[i], 1, GL_RG8, width, height);
216                 check_error();
217                 glTextureStorage2D(cb_tex[i], 1, GL_R8, width / 2, height);
218                 check_error();
219                 glTextureStorage2D(cr_tex[i], 1, GL_R8, width / 2, height);
220                 check_error();
221
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);
231                 check_error();
232                 glCreateFramebuffers(1, &resource->fade_fbo);
233                 check_error();
234
235                 glNamedFramebufferTextureLayer(resource->input_fbos[0], GL_COLOR_ATTACHMENT0, input_tex[i], 0, 0);
236                 check_error();
237                 glNamedFramebufferTextureLayer(resource->input_fbos[0], GL_COLOR_ATTACHMENT1, gray_tex[i], 0, 0);
238                 check_error();
239                 glNamedFramebufferTextureLayer(resource->input_fbos[1], GL_COLOR_ATTACHMENT0, input_tex[i], 0, 1);
240                 check_error();
241                 glNamedFramebufferTextureLayer(resource->input_fbos[1], GL_COLOR_ATTACHMENT1, gray_tex[i], 0, 1);
242                 check_error();
243                 glNamedFramebufferTexture(resource->fade_fbo, GL_COLOR_ATTACHMENT0, fade_y_output_tex[i], 0);
244                 check_error();
245                 glNamedFramebufferTexture(resource->fade_fbo, GL_COLOR_ATTACHMENT1, fade_cbcr_output_tex[i], 0);
246                 check_error();
247
248                 GLuint bufs[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
249                 glNamedFramebufferDrawBuffers(resource->input_fbos[0], 2, bufs);
250                 check_error();
251                 glNamedFramebufferDrawBuffers(resource->input_fbos[1], 2, bufs);
252                 check_error();
253                 glNamedFramebufferDrawBuffers(resource->fade_fbo, 2, bufs);
254                 check_error();
255
256                 glCreateBuffers(1, &resource->pbo);
257                 check_error();
258                 glNamedBufferStorage(resource->pbo, width * height * 4, nullptr, GL_MAP_READ_BIT | GL_MAP_PERSISTENT_BIT);
259                 check_error();
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));
262         }
263
264         check_error();
265
266         OperatingPoint op;
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;
276         } else {
277                 // Quality 0 will be changed to 1 in flags.cpp.
278                 assert(false);
279         }
280
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);
285         check_error();
286
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=*/"");
293
294         if (file_avctx != nullptr) {
295                 with_subtitles = Mux::WITHOUT_SUBTITLES;
296         } else {
297                 with_subtitles = Mux::WITH_SUBTITLES;
298         }
299 }
300
301 VideoStream::~VideoStream()
302 {
303         if (last_flow_tex != 0) {
304                 compute_flow->release_texture(last_flow_tex);
305         }
306
307         for (const unique_ptr<InterpolatedFrameResources> &resource : interpolate_resources) {
308                 glUnmapNamedBuffer(resource->pbo);
309                 check_error();
310                 glDeleteBuffers(1, &resource->pbo);
311                 check_error();
312                 glDeleteFramebuffers(2, resource->input_fbos);
313                 check_error();
314                 glDeleteFramebuffers(1, &resource->fade_fbo);
315                 check_error();
316                 glDeleteTextures(1, &resource->input_tex);
317                 check_error();
318                 glDeleteTextures(1, &resource->gray_tex);
319                 check_error();
320                 glDeleteTextures(1, &resource->fade_y_output_tex);
321                 check_error();
322                 glDeleteTextures(1, &resource->fade_cbcr_output_tex);
323                 check_error();
324                 glDeleteTextures(1, &resource->cb_tex);
325                 check_error();
326                 glDeleteTextures(1, &resource->cr_tex);
327                 check_error();
328         }
329         assert(interpolate_resources.size() == num_interpolate_slots);
330 }
331
332 void VideoStream::start()
333 {
334         if (avctx == nullptr) {
335                 avctx = avformat_alloc_context();
336
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);
342
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;
347
348                 avctx->flags = AVFMT_FLAG_CUSTOM_IO;
349         }
350
351         AVCodecParameters *audio_codecpar = avcodec_parameters_alloc();
352
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;
358
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));
362
363         avcodec_parameters_free(&audio_codecpar);
364         encode_thread = thread(&VideoStream::encode_thread_func, this);
365 }
366
367 void VideoStream::stop()
368 {
369         should_quit = true;
370         queue_changed.notify_all();
371         clear_queue();
372         encode_thread.join();
373 }
374
375 void VideoStream::clear_queue()
376 {
377         deque<QueuedFrame> q;
378
379         {
380                 lock_guard<mutex> lock(queue_lock);
381                 q = move(frame_queue);
382         }
383
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);
391                         }
392                 }
393                 if (qf.type == QueuedFrame::INTERPOLATED) {
394                         interpolate->release_texture(qf.output_tex);
395                         interpolate->release_texture(qf.cbcr_tex);
396                 }
397         }
398
399         // Destroy q outside the mutex, as that would be a double-lock.
400 }
401
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)
406 {
407         fprintf(stderr, "output_pts=%" PRId64 "  original      input_pts=%" PRId64 "\n", output_pts, frame.pts);
408
409         QueuedFrame qf;
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);
419
420         lock_guard<mutex> lock(queue_lock);
421         frame_queue.push_back(move(qf));
422         queue_changed.notify_all();
423 }
424
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)
430 {
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);
432
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;
438         {
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");
442                         return;
443                 }
444                 resources = BorrowedInterpolatedFrameResources(interpolate_resources.front().release());
445                 interpolate_resources.pop_front();
446         }
447
448         bool did_decode;
449
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);
454
455         ycbcr_semiplanar_converter->prepare_chain_for_fade(frame1, frame2, fade_alpha)->render_to_fbo(resources->fade_fbo, global_flags.width, global_flags.height);
456
457         QueuedFrame qf;
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;
465
466         qf.secondary_frame = frame2_spec;
467
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);
470
471         // Read it down (asynchronously) to the CPU.
472         glPixelStorei(GL_PACK_ROW_LENGTH, 0);
473         glBindBuffer(GL_PIXEL_PACK_BUFFER, resources->pbo);
474         check_error();
475         glGetTextureImage(resources->fade_y_output_tex, 0, GL_RED, GL_UNSIGNED_BYTE, global_flags.width * global_flags.height * 4, BUFFER_OFFSET(0));
476         check_error();
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));
478         check_error();
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));
480         check_error();
481         glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
482
483         // Set a fence we can wait for to make sure the CPU sees the read.
484         glMemoryBarrier(GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT);
485         check_error();
486         qf.fence_created = steady_clock::now();
487         qf.fence = RefCountedGLsync(GL_SYNC_GPU_COMMANDS_COMPLETE, /*flags=*/0);
488         check_error();
489         qf.resources = move(resources);
490         qf.local_pts = local_pts;
491
492         lock_guard<mutex> lock(queue_lock);
493         frame_queue.push_back(move(qf));
494         queue_changed.notify_all();
495 }
496
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,
502                                               bool play_audio)
503 {
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);
506         } else {
507                 fprintf(stderr, "output_pts=%" PRId64 "  interpolated  input_pts1=%" PRId64 " input_pts2=%" PRId64 " alpha=%.3f\n", output_pts, frame1.pts, frame2.pts, alpha);
508         }
509
510         // Get the temporary OpenGL resources we need for doing the interpolation.
511         BorrowedInterpolatedFrameResources resources;
512         {
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");
516                         return;
517                 }
518                 resources = BorrowedInterpolatedFrameResources(interpolate_resources.front().release());
519                 interpolate_resources.pop_front();
520         }
521
522         QueuedFrame qf;
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;
529
530         if (play_audio) {
531                 qf.audio = frame_reader.read_frame(frame1, /*read_video=*/false, /*read_audio=*/true).audio;
532         }
533
534         check_error();
535
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;
539                 bool did_decode;
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);
543                 if (frame_no == 1) {
544                         qf.exif_data = frame->exif_data;  // Use the white point from the last frame.
545                 }
546         }
547
548         glGenerateTextureMipmap(resources->input_tex);
549         check_error();
550         glGenerateTextureMipmap(resources->gray_tex);
551         check_error();
552
553         GLuint flow_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;
559                 qf.flow_tex = 0;
560         } else {
561                 // Cache miss, so release last_flow_tex.
562                 qf.flow_tex = last_flow_tex;
563
564                 // Compute the flow.
565                 flow_tex = compute_flow->exec(resources->gray_tex, DISComputeFlow::FORWARD_AND_BACKWARD, DISComputeFlow::DO_NOT_RESIZE_FLOW);
566                 check_error();
567
568                 // Store the flow texture for possible reuse next frame.
569                 last_flow_tex = flow_tex;
570                 last_frame1 = frame1;
571                 last_frame2 = frame2;
572         }
573
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);
577                 check_error();
578
579                 // Now decode the image we are fading against.
580                 bool did_decode;
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);
583
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);
587
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);
590
591                 interpolate_no_split->release_texture(qf.output_tex);
592
593                 // We already applied the white balance, so don't have the client redo it.
594                 qf.exif_data.clear();
595         } else {
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);
597                 check_error();
598
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);
601         }
602
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.
606         //
607         // TODO: This is maybe less relevant now that qf.flow_tex contains the texture we used
608         // _last_ frame, not this one.
609
610         // Read it down (asynchronously) to the CPU.
611         glPixelStorei(GL_PACK_ROW_LENGTH, 0);
612         glBindBuffer(GL_PIXEL_PACK_BUFFER, resources->pbo);
613         check_error();
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));
616         } else {
617                 glGetTextureImage(qf.output_tex, 0, GL_RED, GL_UNSIGNED_BYTE, global_flags.width * global_flags.height * 4, BUFFER_OFFSET(0));
618         }
619         check_error();
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));
621         check_error();
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));
623         check_error();
624         glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
625
626         // Set a fence we can wait for to make sure the CPU sees the read.
627         glMemoryBarrier(GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT);
628         check_error();
629         qf.fence_created = steady_clock::now();
630         qf.fence = RefCountedGLsync(GL_SYNC_GPU_COMMANDS_COMPLETE, /*flags=*/0);
631         check_error();
632         qf.resources = move(resources);
633
634         lock_guard<mutex> lock(queue_lock);
635         frame_queue.push_back(move(qf));
636         queue_changed.notify_all();
637 }
638
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)
642 {
643         QueuedFrame qf;
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;
649
650         lock_guard<mutex> lock(queue_lock);
651         frame_queue.push_back(move(qf));
652         queue_changed.notify_all();
653 }
654
655 void VideoStream::schedule_silence(steady_clock::time_point local_pts, int64_t output_pts,
656                                    int64_t length_pts, QueueSpotHolder &&queue_spot_holder)
657 {
658         QueuedFrame qf;
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;
663
664         lock_guard<mutex> lock(queue_lock);
665         frame_queue.push_back(move(qf));
666         queue_changed.notify_all();
667 }
668
669 namespace {
670
671 RefCountedTexture clone_r8_texture(GLuint src_tex, unsigned width, unsigned height)
672 {
673         GLuint tex;
674         glCreateTextures(GL_TEXTURE_2D, 1, &tex);
675         check_error();
676         glTextureStorage2D(tex, 1, GL_R8, width, height);
677         check_error();
678         glCopyImageSubData(src_tex, GL_TEXTURE_2D, 0, 0, 0, 0,
679                            tex, GL_TEXTURE_2D, 0, 0, 0, 0,
680                            width, height, 1);
681         check_error();
682         glTextureParameteri(tex, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
683         check_error();
684         glTextureParameteri(tex, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
685         check_error();
686         glTextureParameteri(tex, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
687         check_error();
688         glTextureParameteri(tex, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
689         check_error();
690
691         return RefCountedTexture(new GLuint(tex), TextureDeleter());
692 }
693
694 }  // namespace
695
696 void VideoStream::encode_thread_func()
697 {
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);
702         if (!ok) {
703                 fprintf(stderr, "Video stream couldn't get an OpenGL context\n");
704                 abort();
705         }
706
707         init_pbo_pool();
708
709         while (!should_quit) {
710                 QueuedFrame qf;
711                 {
712                         unique_lock<mutex> lock(queue_lock);
713
714                         // Wait until we have a frame to play.
715                         queue_changed.wait(lock, [this] {
716                                 return !frame_queue.empty() || should_quit;
717                         });
718                         if (should_quit) {
719                                 break;
720                         }
721                         steady_clock::time_point frame_start = frame_queue.front().local_pts;
722
723                         // Now sleep until the frame is supposed to start (the usual case),
724                         // _or_ clear_queue() happened.
725                         bool aborted;
726                         if (output_fast_forward) {
727                                 aborted = frame_queue.empty() || frame_queue.front().local_pts != frame_start;
728                         } else {
729                                 aborted = queue_changed.wait_until(lock, frame_start, [this, frame_start] {
730                                         return frame_queue.empty() || frame_queue.front().local_pts != frame_start;
731                                 });
732                         }
733                         if (aborted) {
734                                 // clear_queue() happened, so don't play this frame after all.
735                                 continue;
736                         }
737                         qf = move(frame_queue.front());
738                         frame_queue.pop_front();
739                 }
740
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) {
744                         AVPacket pkt;
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();
750                         pkt.flags = 0;
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);
753                 }
754
755                 if (qf.type == QueuedFrame::ORIGINAL) {
756                         // Send the JPEG frame on, unchanged.
757                         string jpeg = move(*qf.encoded_jpeg);
758                         AVPacket pkt;
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);
766
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());
774
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=*/"");
777
778                         AVPacket pkt;
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);
786
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());
794
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);
800                                 } else {
801                                         frame->y = clone_r8_texture(qf.output_tex, global_flags.width, global_flags.height);
802                                 }
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));
811                         }
812
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);
817                         }
818                         if (qf.type != QueuedFrame::FADED_INTERPOLATED) {
819                                 interpolate->release_texture(qf.output_tex);
820                                 interpolate->release_texture(qf.cbcr_tex);
821                         }
822
823                         AVPacket pkt;
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);
831
832                         add_audio_or_silence(qf);
833                 } else if (qf.type == QueuedFrame::REFRESH) {
834                         AVPacket pkt;
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);
841
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);
845                 } else {
846                         assert(false);
847                 }
848                 if (qf.display_func != nullptr) {
849                         qf.display_func();
850                 }
851         }
852 }
853
854 int VideoStream::write_packet2_thunk(void *opaque, uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
855 {
856         VideoStream *video_stream = (VideoStream *)opaque;
857         return video_stream->write_packet2(buf, buf_size, type, time);
858 }
859
860 int VideoStream::write_packet2(uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
861 {
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;
868         }
869
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);
874         } else {
875                 global_httpd->add_data(stream_id, (char *)buf, buf_size, type == AVIO_DATA_MARKER_SYNC_POINT, time, AVRational{ AV_TIME_BASE, 1 });
876         }
877         return buf_size;
878 }
879
880 void VideoStream::add_silence(int64_t pts, int64_t length_pts)
881 {
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));
887
888         AVPacket pkt;
889         av_init_packet(&pkt);
890         pkt.stream_index = 1;
891         pkt.data = zero;
892         pkt.size = num_samples * sizeof(int32_t);
893         pkt.flags = AV_PKT_FLAG_KEY;
894         mux->add_packet(pkt, pts, pts);
895
896         free(zero);
897 }
898
899 void VideoStream::add_audio_or_silence(const QueuedFrame &qf)
900 {
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);
904         } else {
905                 AVPacket pkt;
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);
912         }
913 }