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