]> git.sesse.net Git - nageru/blob - futatabi/video_stream.cpp
9a120b51344a70b6b4744519ee07f328c50f7b3b
[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 "flags.h"
10 #include "flow.h"
11 #include "jpeg_frame_view.h"
12 #include "movit/util.h"
13 #include "player.h"
14 #include "shared/context.h"
15 #include "shared/httpd.h"
16 #include "shared/shared_defs.h"
17 #include "shared/mux.h"
18 #include "util.h"
19 #include "ycbcr_converter.h"
20
21 #include <epoxy/glx.h>
22 #include <jpeglib.h>
23 #include <unistd.h>
24
25 using namespace std;
26 using namespace std::chrono;
27
28 extern HTTPD *global_httpd;
29
30 struct VectorDestinationManager {
31         jpeg_destination_mgr pub;
32         string dest;
33
34         VectorDestinationManager()
35         {
36                 pub.init_destination = init_destination_thunk;
37                 pub.empty_output_buffer = empty_output_buffer_thunk;
38                 pub.term_destination = term_destination_thunk;
39         }
40
41         static void init_destination_thunk(j_compress_ptr ptr)
42         {
43                 ((VectorDestinationManager *)(ptr->dest))->init_destination();
44         }
45
46         inline void init_destination()
47         {
48                 make_room(0);
49         }
50
51         static boolean empty_output_buffer_thunk(j_compress_ptr ptr)
52         {
53                 return ((VectorDestinationManager *)(ptr->dest))->empty_output_buffer();
54         }
55
56         inline bool empty_output_buffer()
57         {
58                 make_room(dest.size());  // Should ignore pub.free_in_buffer!
59                 return true;
60         }
61
62         inline void make_room(size_t bytes_used)
63         {
64                 dest.resize(bytes_used + 4096);
65                 dest.resize(dest.capacity());
66                 pub.next_output_byte = (uint8_t *)dest.data() + bytes_used;
67                 pub.free_in_buffer = dest.size() - bytes_used;
68         }
69
70         static void term_destination_thunk(j_compress_ptr ptr)
71         {
72                 ((VectorDestinationManager *)(ptr->dest))->term_destination();
73         }
74
75         inline void term_destination()
76         {
77                 dest.resize(dest.size() - pub.free_in_buffer);
78         }
79 };
80 static_assert(std::is_standard_layout<VectorDestinationManager>::value, "");
81
82 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)
83 {
84         VectorDestinationManager dest;
85
86         jpeg_compress_struct cinfo;
87         jpeg_error_mgr jerr;
88         cinfo.err = jpeg_std_error(&jerr);
89         jpeg_create_compress(&cinfo);
90
91         cinfo.dest = (jpeg_destination_mgr *)&dest;
92         cinfo.input_components = 3;
93         cinfo.in_color_space = JCS_RGB;
94         jpeg_set_defaults(&cinfo);
95         constexpr int quality = 90;
96         jpeg_set_quality(&cinfo, quality, /*force_baseline=*/false);
97
98         cinfo.image_width = width;
99         cinfo.image_height = height;
100         cinfo.raw_data_in = true;
101         jpeg_set_colorspace(&cinfo, JCS_YCbCr);
102         cinfo.comp_info[0].h_samp_factor = 2;
103         cinfo.comp_info[0].v_samp_factor = 1;
104         cinfo.comp_info[1].h_samp_factor = 1;
105         cinfo.comp_info[1].v_samp_factor = 1;
106         cinfo.comp_info[2].h_samp_factor = 1;
107         cinfo.comp_info[2].v_samp_factor = 1;
108         cinfo.CCIR601_sampling = true;  // Seems to be mostly ignored by libjpeg, though.
109         jpeg_start_compress(&cinfo, true);
110
111         // This comment marker is private to FFmpeg. It signals limited Y'CbCr range
112         // (and nothing else).
113         jpeg_write_marker(&cinfo, JPEG_COM, (const JOCTET *)"CS=ITU601", strlen("CS=ITU601"));
114
115         if (!exif_data.empty()) {
116                 jpeg_write_marker(&cinfo, JPEG_APP0 + 1, (const JOCTET *)exif_data.data(), exif_data.size());
117         }
118
119         JSAMPROW yptr[8], cbptr[8], crptr[8];
120         JSAMPARRAY data[3] = { yptr, cbptr, crptr };
121         for (unsigned y = 0; y < height; y += 8) {
122                 for (unsigned yy = 0; yy < 8; ++yy) {
123                         yptr[yy] = const_cast<JSAMPROW>(&y_data[(y + yy) * width]);
124                         cbptr[yy] = const_cast<JSAMPROW>(&cb_data[(y + yy) * width / 2]);
125                         crptr[yy] = const_cast<JSAMPROW>(&cr_data[(y + yy) * width / 2]);
126                 }
127
128                 jpeg_write_raw_data(&cinfo, data, /*num_lines=*/8);
129         }
130
131         jpeg_finish_compress(&cinfo);
132         jpeg_destroy_compress(&cinfo);
133
134         return move(dest.dest);
135 }
136
137 VideoStream::VideoStream(AVFormatContext *file_avctx)
138         : avctx(file_avctx), output_fast_forward(file_avctx != nullptr)
139 {
140         ycbcr_converter.reset(new YCbCrConverter(YCbCrConverter::OUTPUT_TO_DUAL_YCBCR, /*resource_pool=*/nullptr));
141         ycbcr_semiplanar_converter.reset(new YCbCrConverter(YCbCrConverter::OUTPUT_TO_SEMIPLANAR, /*resource_pool=*/nullptr));
142
143         GLuint input_tex[num_interpolate_slots], gray_tex[num_interpolate_slots];
144         GLuint fade_y_output_tex[num_interpolate_slots], fade_cbcr_output_tex[num_interpolate_slots];
145         GLuint cb_tex[num_interpolate_slots], cr_tex[num_interpolate_slots];
146
147         glCreateTextures(GL_TEXTURE_2D_ARRAY, num_interpolate_slots, input_tex);
148         glCreateTextures(GL_TEXTURE_2D_ARRAY, num_interpolate_slots, gray_tex);
149         glCreateTextures(GL_TEXTURE_2D, num_interpolate_slots, fade_y_output_tex);
150         glCreateTextures(GL_TEXTURE_2D, num_interpolate_slots, fade_cbcr_output_tex);
151         glCreateTextures(GL_TEXTURE_2D, num_interpolate_slots, cb_tex);
152         glCreateTextures(GL_TEXTURE_2D, num_interpolate_slots, cr_tex);
153         check_error();
154
155         size_t width = global_flags.width, height = global_flags.height;
156         int levels = find_num_levels(width, height);
157         for (size_t i = 0; i < num_interpolate_slots; ++i) {
158                 glTextureStorage3D(input_tex[i], levels, GL_RGBA8, width, height, 2);
159                 check_error();
160                 glTextureStorage3D(gray_tex[i], levels, GL_R8, width, height, 2);
161                 check_error();
162                 glTextureStorage2D(fade_y_output_tex[i], 1, GL_R8, width, height);
163                 check_error();
164                 glTextureStorage2D(fade_cbcr_output_tex[i], 1, GL_RG8, width, height);
165                 check_error();
166                 glTextureStorage2D(cb_tex[i], 1, GL_R8, width / 2, height);
167                 check_error();
168                 glTextureStorage2D(cr_tex[i], 1, GL_R8, width / 2, height);
169                 check_error();
170
171                 unique_ptr<InterpolatedFrameResources> resource(new InterpolatedFrameResources);
172                 resource->owner = this;
173                 resource->input_tex = input_tex[i];
174                 resource->gray_tex = gray_tex[i];
175                 resource->fade_y_output_tex = fade_y_output_tex[i];
176                 resource->fade_cbcr_output_tex = fade_cbcr_output_tex[i];
177                 resource->cb_tex = cb_tex[i];
178                 resource->cr_tex = cr_tex[i];
179                 glCreateFramebuffers(2, resource->input_fbos);
180                 check_error();
181                 glCreateFramebuffers(1, &resource->fade_fbo);
182                 check_error();
183
184                 glNamedFramebufferTextureLayer(resource->input_fbos[0], GL_COLOR_ATTACHMENT0, input_tex[i], 0, 0);
185                 check_error();
186                 glNamedFramebufferTextureLayer(resource->input_fbos[0], GL_COLOR_ATTACHMENT1, gray_tex[i], 0, 0);
187                 check_error();
188                 glNamedFramebufferTextureLayer(resource->input_fbos[1], GL_COLOR_ATTACHMENT0, input_tex[i], 0, 1);
189                 check_error();
190                 glNamedFramebufferTextureLayer(resource->input_fbos[1], GL_COLOR_ATTACHMENT1, gray_tex[i], 0, 1);
191                 check_error();
192                 glNamedFramebufferTexture(resource->fade_fbo, GL_COLOR_ATTACHMENT0, fade_y_output_tex[i], 0);
193                 check_error();
194                 glNamedFramebufferTexture(resource->fade_fbo, GL_COLOR_ATTACHMENT1, fade_cbcr_output_tex[i], 0);
195                 check_error();
196
197                 GLuint bufs[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
198                 glNamedFramebufferDrawBuffers(resource->input_fbos[0], 2, bufs);
199                 check_error();
200                 glNamedFramebufferDrawBuffers(resource->input_fbos[1], 2, bufs);
201                 check_error();
202                 glNamedFramebufferDrawBuffers(resource->fade_fbo, 2, bufs);
203                 check_error();
204
205                 glCreateBuffers(1, &resource->pbo);
206                 check_error();
207                 glNamedBufferStorage(resource->pbo, width * height * 4, nullptr, GL_MAP_READ_BIT | GL_MAP_PERSISTENT_BIT);
208                 check_error();
209                 resource->pbo_contents = glMapNamedBufferRange(resource->pbo, 0, width * height * 4, GL_MAP_READ_BIT | GL_MAP_PERSISTENT_BIT);
210                 interpolate_resources.push_back(move(resource));
211         }
212
213         check_error();
214
215         OperatingPoint op;
216         if (global_flags.interpolation_quality == 0 ||
217             global_flags.interpolation_quality == 1) {
218                 op = operating_point1;
219         } else if (global_flags.interpolation_quality == 2) {
220                 op = operating_point2;
221         } else if (global_flags.interpolation_quality == 3) {
222                 op = operating_point3;
223         } else if (global_flags.interpolation_quality == 4) {
224                 op = operating_point4;
225         } else {
226                 // Quality 0 will be changed to 1 in flags.cpp.
227                 assert(false);
228         }
229
230         compute_flow.reset(new DISComputeFlow(width, height, op));
231         interpolate.reset(new Interpolate(op, /*split_ycbcr_output=*/true));
232         interpolate_no_split.reset(new Interpolate(op, /*split_ycbcr_output=*/false));
233         chroma_subsampler.reset(new ChromaSubsampler);
234         check_error();
235
236         // The “last frame” is initially black.
237         unique_ptr<uint8_t[]> y(new uint8_t[global_flags.width * global_flags.height]);
238         unique_ptr<uint8_t[]> cb_or_cr(new uint8_t[(global_flags.width / 2) * global_flags.height]);
239         memset(y.get(), 16, global_flags.width * global_flags.height);
240         memset(cb_or_cr.get(), 128, (global_flags.width / 2) * global_flags.height);
241         last_frame = encode_jpeg(y.get(), cb_or_cr.get(), cb_or_cr.get(), global_flags.width, global_flags.height, /*exif_data=*/"");
242
243         if (file_avctx != nullptr) {
244                 with_subtitles = Mux::WITHOUT_SUBTITLES;
245         } else {
246                 with_subtitles = Mux::WITH_SUBTITLES;
247         }
248 }
249
250 VideoStream::~VideoStream()
251 {
252         if (last_flow_tex != 0) {
253                 compute_flow->release_texture(last_flow_tex);
254         }
255
256         for (const unique_ptr<InterpolatedFrameResources> &resource : interpolate_resources) {
257                 glUnmapNamedBuffer(resource->pbo);
258                 check_error();
259                 glDeleteBuffers(1, &resource->pbo);
260                 check_error();
261                 glDeleteFramebuffers(2, resource->input_fbos);
262                 check_error();
263                 glDeleteFramebuffers(1, &resource->fade_fbo);
264                 check_error();
265                 glDeleteTextures(1, &resource->input_tex);
266                 check_error();
267                 glDeleteTextures(1, &resource->gray_tex);
268                 check_error();
269                 glDeleteTextures(1, &resource->fade_y_output_tex);
270                 check_error();
271                 glDeleteTextures(1, &resource->fade_cbcr_output_tex);
272                 check_error();
273                 glDeleteTextures(1, &resource->cb_tex);
274                 check_error();
275                 glDeleteTextures(1, &resource->cr_tex);
276                 check_error();
277         }
278         assert(interpolate_resources.size() == num_interpolate_slots);
279 }
280
281 void VideoStream::start()
282 {
283         if (avctx == nullptr) {
284                 avctx = avformat_alloc_context();
285
286                 // We use Matroska, because it's pretty much the only mux where FFmpeg
287                 // allows writing chroma location to override JFIF's default center placement.
288                 // (Note that at the time of writing, however, FFmpeg does not correctly
289                 // _read_ this information!)
290                 avctx->oformat = av_guess_format("matroska", nullptr, nullptr);
291
292                 uint8_t *buf = (uint8_t *)av_malloc(MUX_BUFFER_SIZE);
293                 avctx->pb = avio_alloc_context(buf, MUX_BUFFER_SIZE, 1, this, nullptr, nullptr, nullptr);
294                 avctx->pb->write_data_type = &VideoStream::write_packet2_thunk;
295                 avctx->pb->ignore_boundary_point = 1;
296
297                 avctx->flags = AVFMT_FLAG_CUSTOM_IO;
298         }
299
300         AVCodecParameters *audio_codecpar = avcodec_parameters_alloc();
301
302         audio_codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
303         audio_codecpar->codec_id = AV_CODEC_ID_PCM_S32LE;
304         audio_codecpar->channel_layout = AV_CH_LAYOUT_STEREO;
305         audio_codecpar->channels = 2;
306         audio_codecpar->sample_rate = OUTPUT_FREQUENCY;
307
308         size_t width = global_flags.width, height = global_flags.height;  // Doesn't matter for MJPEG.
309         mux.reset(new Mux(avctx, width, height, Mux::CODEC_MJPEG, /*video_extradata=*/"", audio_codecpar,
310                           AVCOL_SPC_BT709, COARSE_TIMEBASE, /*write_callback=*/nullptr, Mux::WRITE_FOREGROUND, {}, with_subtitles));
311
312         avcodec_parameters_free(&audio_codecpar);
313         encode_thread = thread(&VideoStream::encode_thread_func, this);
314 }
315
316 void VideoStream::stop()
317 {
318         should_quit = true;
319         queue_changed.notify_all();
320         clear_queue();
321         encode_thread.join();
322 }
323
324 void VideoStream::clear_queue()
325 {
326         deque<QueuedFrame> q;
327
328         {
329                 lock_guard<mutex> lock(queue_lock);
330                 q = move(frame_queue);
331         }
332
333         // These are not RAII-ed, unfortunately, so we'll need to clean them ourselves.
334         // Note that release_texture() is thread-safe.
335         for (const QueuedFrame &qf : q) {
336                 if (qf.type == QueuedFrame::INTERPOLATED ||
337                     qf.type == QueuedFrame::FADED_INTERPOLATED) {
338                         if (qf.flow_tex != 0) {
339                                 compute_flow->release_texture(qf.flow_tex);
340                         }
341                 }
342                 if (qf.type == QueuedFrame::INTERPOLATED) {
343                         interpolate->release_texture(qf.output_tex);
344                         interpolate->release_texture(qf.cbcr_tex);
345                 }
346         }
347
348         // Destroy q outside the mutex, as that would be a double-lock.
349 }
350
351 void VideoStream::schedule_original_frame(steady_clock::time_point local_pts,
352                                           int64_t output_pts, function<void()> &&display_func,
353                                           QueueSpotHolder &&queue_spot_holder,
354                                           FrameOnDisk frame, const string &subtitle, bool include_audio)
355 {
356         fprintf(stderr, "output_pts=%" PRId64 "  original      input_pts=%" PRId64 "\n", output_pts, frame.pts);
357
358         QueuedFrame qf;
359         qf.local_pts = local_pts;
360         qf.type = QueuedFrame::ORIGINAL;
361         qf.output_pts = output_pts;
362         qf.display_func = move(display_func);
363         qf.queue_spot_holder = move(queue_spot_holder);
364         qf.subtitle = subtitle;
365         FrameReader::Frame read_frame = frame_reader.read_frame(frame, /*read_video=*/true, include_audio);
366         qf.encoded_jpeg.reset(new string(move(read_frame.video)));
367         qf.audio = move(read_frame.audio);
368
369         lock_guard<mutex> lock(queue_lock);
370         frame_queue.push_back(move(qf));
371         queue_changed.notify_all();
372 }
373
374 void VideoStream::schedule_faded_frame(steady_clock::time_point local_pts, int64_t output_pts,
375                                        function<void()> &&display_func,
376                                        QueueSpotHolder &&queue_spot_holder,
377                                        FrameOnDisk frame1_spec, FrameOnDisk frame2_spec,
378                                        float fade_alpha, const string &subtitle)
379 {
380         fprintf(stderr, "output_pts=%" PRId64 "  faded         input_pts=%" PRId64 ",%" PRId64 "  fade_alpha=%.2f\n", output_pts, frame1_spec.pts, frame2_spec.pts, fade_alpha);
381
382         // Get the temporary OpenGL resources we need for doing the fade.
383         // (We share these with interpolated frames, which is slightly
384         // overkill, but there's no need to waste resources on keeping
385         // separate pools around.)
386         BorrowedInterpolatedFrameResources resources;
387         {
388                 lock_guard<mutex> lock(queue_lock);
389                 if (interpolate_resources.empty()) {
390                         fprintf(stderr, "WARNING: Too many interpolated frames already in transit; dropping one.\n");
391                         return;
392                 }
393                 resources = BorrowedInterpolatedFrameResources(interpolate_resources.front().release());
394                 interpolate_resources.pop_front();
395         }
396
397         bool did_decode;
398
399         shared_ptr<Frame> frame1 = decode_jpeg_with_cache(frame1_spec, DECODE_IF_NOT_IN_CACHE, &frame_reader, &did_decode);
400         shared_ptr<Frame> frame2 = decode_jpeg_with_cache(frame2_spec, DECODE_IF_NOT_IN_CACHE, &frame_reader, &did_decode);
401
402         ycbcr_semiplanar_converter->prepare_chain_for_fade(frame1, frame2, fade_alpha)->render_to_fbo(resources->fade_fbo, global_flags.width, global_flags.height);
403
404         QueuedFrame qf;
405         qf.local_pts = local_pts;
406         qf.type = QueuedFrame::FADED;
407         qf.output_pts = output_pts;
408         qf.frame1 = frame1_spec;
409         qf.display_func = move(display_func);
410         qf.queue_spot_holder = move(queue_spot_holder);
411         qf.subtitle = subtitle;
412
413         qf.secondary_frame = frame2_spec;
414
415         // Subsample and split Cb/Cr.
416         chroma_subsampler->subsample_chroma(resources->fade_cbcr_output_tex, global_flags.width, global_flags.height, resources->cb_tex, resources->cr_tex);
417
418         // Read it down (asynchronously) to the CPU.
419         glPixelStorei(GL_PACK_ROW_LENGTH, 0);
420         glBindBuffer(GL_PIXEL_PACK_BUFFER, resources->pbo);
421         check_error();
422         glGetTextureImage(resources->fade_y_output_tex, 0, GL_RED, GL_UNSIGNED_BYTE, global_flags.width * global_flags.height * 4, BUFFER_OFFSET(0));
423         check_error();
424         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));
425         check_error();
426         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));
427         check_error();
428         glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
429
430         // Set a fence we can wait for to make sure the CPU sees the read.
431         glMemoryBarrier(GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT);
432         check_error();
433         qf.fence = RefCountedGLsync(GL_SYNC_GPU_COMMANDS_COMPLETE, /*flags=*/0);
434         check_error();
435         qf.resources = move(resources);
436         qf.local_pts = local_pts;
437
438         lock_guard<mutex> lock(queue_lock);
439         frame_queue.push_back(move(qf));
440         queue_changed.notify_all();
441 }
442
443 void VideoStream::schedule_interpolated_frame(steady_clock::time_point local_pts,
444                                               int64_t output_pts, function<void(shared_ptr<Frame>)> &&display_func,
445                                               QueueSpotHolder &&queue_spot_holder,
446                                               FrameOnDisk frame1, FrameOnDisk frame2,
447                                               float alpha, FrameOnDisk secondary_frame, float fade_alpha, const string &subtitle,
448                                               bool play_audio)
449 {
450         if (secondary_frame.pts != -1) {
451                 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);
452         } else {
453                 fprintf(stderr, "output_pts=%" PRId64 "  interpolated  input_pts1=%" PRId64 " input_pts2=%" PRId64 " alpha=%.3f\n", output_pts, frame1.pts, frame2.pts, alpha);
454         }
455
456         // Get the temporary OpenGL resources we need for doing the interpolation.
457         BorrowedInterpolatedFrameResources resources;
458         {
459                 lock_guard<mutex> lock(queue_lock);
460                 if (interpolate_resources.empty()) {
461                         fprintf(stderr, "WARNING: Too many interpolated frames already in transit; dropping one.\n");
462                         return;
463                 }
464                 resources = BorrowedInterpolatedFrameResources(interpolate_resources.front().release());
465                 interpolate_resources.pop_front();
466         }
467
468         QueuedFrame qf;
469         qf.type = (secondary_frame.pts == -1) ? QueuedFrame::INTERPOLATED : QueuedFrame::FADED_INTERPOLATED;
470         qf.output_pts = output_pts;
471         qf.display_decoded_func = move(display_func);
472         qf.queue_spot_holder = move(queue_spot_holder);
473         qf.local_pts = local_pts;
474         qf.subtitle = subtitle;
475
476         if (play_audio) {
477                 qf.audio = frame_reader.read_frame(frame1, /*read_video=*/false, /*read_audio=*/true).audio;
478         }
479
480         check_error();
481
482         // Convert frame0 and frame1 to OpenGL textures.
483         for (size_t frame_no = 0; frame_no < 2; ++frame_no) {
484                 FrameOnDisk frame_spec = frame_no == 1 ? frame2 : frame1;
485                 bool did_decode;
486                 shared_ptr<Frame> frame = decode_jpeg_with_cache(frame_spec, DECODE_IF_NOT_IN_CACHE, &frame_reader, &did_decode);
487                 ycbcr_converter->prepare_chain_for_conversion(frame)->render_to_fbo(resources->input_fbos[frame_no], global_flags.width, global_flags.height);
488                 if (frame_no == 1) {
489                         qf.exif_data = frame->exif_data;  // Use the white point from the last frame.
490                 }
491         }
492
493         glGenerateTextureMipmap(resources->input_tex);
494         check_error();
495         glGenerateTextureMipmap(resources->gray_tex);
496         check_error();
497
498         GLuint flow_tex;
499         if (last_flow_tex != 0 && frame1 == last_frame1 && frame2 == last_frame2) {
500                 // Reuse the flow from previous computation. This frequently happens
501                 // if we slow down by more than 2x, so that there are multiple interpolated
502                 // frames between each original.
503                 flow_tex = last_flow_tex;
504                 qf.flow_tex = 0;
505         } else {
506                 // Cache miss, so release last_flow_tex.
507                 qf.flow_tex = last_flow_tex;
508
509                 // Compute the flow.
510                 flow_tex = compute_flow->exec(resources->gray_tex, DISComputeFlow::FORWARD_AND_BACKWARD, DISComputeFlow::DO_NOT_RESIZE_FLOW);
511                 check_error();
512
513                 // Store the flow texture for possible reuse next frame.
514                 last_flow_tex = flow_tex;
515                 last_frame1 = frame1;
516                 last_frame2 = frame2;
517         }
518
519         if (secondary_frame.pts != -1) {
520                 // Fade. First kick off the interpolation.
521                 tie(qf.output_tex, ignore) = interpolate_no_split->exec(resources->input_tex, resources->gray_tex, flow_tex, global_flags.width, global_flags.height, alpha);
522                 check_error();
523
524                 // Now decode the image we are fading against.
525                 bool did_decode;
526                 shared_ptr<Frame> frame2 = decode_jpeg_with_cache(secondary_frame, DECODE_IF_NOT_IN_CACHE, &frame_reader, &did_decode);
527
528                 // Then fade against it, putting it into the fade Y' and CbCr textures.
529                 ycbcr_semiplanar_converter->prepare_chain_for_fade_from_texture(qf.output_tex, global_flags.width, global_flags.height, frame2, fade_alpha)->render_to_fbo(resources->fade_fbo, global_flags.width, global_flags.height);
530
531                 // Subsample and split Cb/Cr.
532                 chroma_subsampler->subsample_chroma(resources->fade_cbcr_output_tex, global_flags.width, global_flags.height, resources->cb_tex, resources->cr_tex);
533
534                 interpolate_no_split->release_texture(qf.output_tex);
535         } else {
536                 tie(qf.output_tex, qf.cbcr_tex) = interpolate->exec(resources->input_tex, resources->gray_tex, flow_tex, global_flags.width, global_flags.height, alpha);
537                 check_error();
538
539                 // Subsample and split Cb/Cr.
540                 chroma_subsampler->subsample_chroma(qf.cbcr_tex, global_flags.width, global_flags.height, resources->cb_tex, resources->cr_tex);
541         }
542
543         // We could have released qf.flow_tex here, but to make sure we don't cause a stall
544         // when trying to reuse it for the next frame, we can just as well hold on to it
545         // and release it only when the readback is done.
546         //
547         // TODO: This is maybe less relevant now that qf.flow_tex contains the texture we used
548         // _last_ frame, not this one.
549
550         // Read it down (asynchronously) to the CPU.
551         glPixelStorei(GL_PACK_ROW_LENGTH, 0);
552         glBindBuffer(GL_PIXEL_PACK_BUFFER, resources->pbo);
553         check_error();
554         if (secondary_frame.pts != -1) {
555                 glGetTextureImage(resources->fade_y_output_tex, 0, GL_RED, GL_UNSIGNED_BYTE, global_flags.width * global_flags.height * 4, BUFFER_OFFSET(0));
556         } else {
557                 glGetTextureImage(qf.output_tex, 0, GL_RED, GL_UNSIGNED_BYTE, global_flags.width * global_flags.height * 4, BUFFER_OFFSET(0));
558         }
559         check_error();
560         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));
561         check_error();
562         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));
563         check_error();
564         glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
565
566         // Set a fence we can wait for to make sure the CPU sees the read.
567         glMemoryBarrier(GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT);
568         check_error();
569         qf.fence = RefCountedGLsync(GL_SYNC_GPU_COMMANDS_COMPLETE, /*flags=*/0);
570         check_error();
571         qf.resources = move(resources);
572
573         lock_guard<mutex> lock(queue_lock);
574         frame_queue.push_back(move(qf));
575         queue_changed.notify_all();
576 }
577
578 void VideoStream::schedule_refresh_frame(steady_clock::time_point local_pts,
579                                          int64_t output_pts, function<void()> &&display_func,
580                                          QueueSpotHolder &&queue_spot_holder, const string &subtitle)
581 {
582         QueuedFrame qf;
583         qf.type = QueuedFrame::REFRESH;
584         qf.output_pts = output_pts;
585         qf.display_func = move(display_func);
586         qf.queue_spot_holder = move(queue_spot_holder);
587         qf.subtitle = subtitle;
588
589         lock_guard<mutex> lock(queue_lock);
590         frame_queue.push_back(move(qf));
591         queue_changed.notify_all();
592 }
593
594 void VideoStream::schedule_silence(steady_clock::time_point local_pts, int64_t output_pts,
595                                    int64_t length_pts, QueueSpotHolder &&queue_spot_holder)
596 {
597         QueuedFrame qf;
598         qf.type = QueuedFrame::SILENCE;
599         qf.output_pts = output_pts;
600         qf.queue_spot_holder = move(queue_spot_holder);
601         qf.silence_length_pts = length_pts;
602
603         lock_guard<mutex> lock(queue_lock);
604         frame_queue.push_back(move(qf));
605         queue_changed.notify_all();
606 }
607
608 namespace {
609
610 shared_ptr<Frame> frame_from_pbo(void *contents, size_t width, size_t height)
611 {
612         size_t chroma_width = width / 2;
613
614         const uint8_t *y = (const uint8_t *)contents;
615         const uint8_t *cb = (const uint8_t *)contents + width * height;
616         const uint8_t *cr = (const uint8_t *)contents + width * height + chroma_width * height;
617
618         shared_ptr<Frame> frame(new Frame);
619         frame->y.reset(new uint8_t[width * height]);
620         frame->cb.reset(new uint8_t[chroma_width * height]);
621         frame->cr.reset(new uint8_t[chroma_width * height]);
622         for (unsigned yy = 0; yy < height; ++yy) {
623                 memcpy(frame->y.get() + width * yy, y + width * yy, width);
624                 memcpy(frame->cb.get() + chroma_width * yy, cb + chroma_width * yy, chroma_width);
625                 memcpy(frame->cr.get() + chroma_width * yy, cr + chroma_width * yy, chroma_width);
626         }
627         frame->is_semiplanar = false;
628         frame->width = width;
629         frame->height = height;
630         frame->chroma_subsampling_x = 2;
631         frame->chroma_subsampling_y = 1;
632         frame->pitch_y = width;
633         frame->pitch_chroma = chroma_width;
634         return frame;
635 }
636
637 }  // namespace
638
639 void VideoStream::encode_thread_func()
640 {
641         pthread_setname_np(pthread_self(), "VideoStream");
642         QSurface *surface = create_surface();
643         QOpenGLContext *context = create_context(surface);
644         bool ok = make_current(context, surface);
645         if (!ok) {
646                 fprintf(stderr, "Video stream couldn't get an OpenGL context\n");
647                 abort();
648         }
649
650         while (!should_quit) {
651                 QueuedFrame qf;
652                 {
653                         unique_lock<mutex> lock(queue_lock);
654
655                         // Wait until we have a frame to play.
656                         queue_changed.wait(lock, [this] {
657                                 return !frame_queue.empty() || should_quit;
658                         });
659                         if (should_quit) {
660                                 break;
661                         }
662                         steady_clock::time_point frame_start = frame_queue.front().local_pts;
663
664                         // Now sleep until the frame is supposed to start (the usual case),
665                         // _or_ clear_queue() happened.
666                         bool aborted;
667                         if (output_fast_forward) {
668                                 aborted = frame_queue.empty() || frame_queue.front().local_pts != frame_start;
669                         } else {
670                                 aborted = queue_changed.wait_until(lock, frame_start, [this, frame_start] {
671                                         return frame_queue.empty() || frame_queue.front().local_pts != frame_start;
672                                 });
673                         }
674                         if (aborted) {
675                                 // clear_queue() happened, so don't play this frame after all.
676                                 continue;
677                         }
678                         qf = move(frame_queue.front());
679                         frame_queue.pop_front();
680                 }
681
682                 // Hack: We mux the subtitle packet one time unit before the actual frame,
683                 // so that Nageru is sure to get it first.
684                 if (!qf.subtitle.empty() && with_subtitles == Mux::WITH_SUBTITLES) {
685                         AVPacket pkt;
686                         av_init_packet(&pkt);
687                         pkt.stream_index = mux->get_subtitle_stream_idx();
688                         assert(pkt.stream_index != -1);
689                         pkt.data = (uint8_t *)qf.subtitle.data();
690                         pkt.size = qf.subtitle.size();
691                         pkt.flags = 0;
692                         pkt.duration = lrint(TIMEBASE / global_flags.output_framerate);  // Doesn't really matter for Nageru.
693                         mux->add_packet(pkt, qf.output_pts - 1, qf.output_pts - 1);
694                 }
695
696                 if (qf.type == QueuedFrame::ORIGINAL) {
697                         // Send the JPEG frame on, unchanged.
698                         string jpeg = move(*qf.encoded_jpeg);
699                         AVPacket pkt;
700                         av_init_packet(&pkt);
701                         pkt.stream_index = 0;
702                         pkt.data = (uint8_t *)jpeg.data();
703                         pkt.size = jpeg.size();
704                         pkt.flags = AV_PKT_FLAG_KEY;
705                         mux->add_packet(pkt, qf.output_pts, qf.output_pts);
706                         last_frame = move(jpeg);
707
708                         add_audio_or_silence(qf);
709                 } else if (qf.type == QueuedFrame::FADED) {
710                         glClientWaitSync(qf.fence.get(), /*flags=*/0, GL_TIMEOUT_IGNORED);
711
712                         shared_ptr<Frame> frame = frame_from_pbo(qf.resources->pbo_contents, global_flags.width, global_flags.height);
713
714                         // Now JPEG encode it, and send it on to the stream.
715                         string jpeg = encode_jpeg(frame->y.get(), frame->cb.get(), frame->cr.get(), global_flags.width, global_flags.height, move(frame->exif_data));
716
717                         AVPacket pkt;
718                         av_init_packet(&pkt);
719                         pkt.stream_index = 0;
720                         pkt.data = (uint8_t *)jpeg.data();
721                         pkt.size = jpeg.size();
722                         pkt.flags = AV_PKT_FLAG_KEY;
723                         mux->add_packet(pkt, qf.output_pts, qf.output_pts);
724                         last_frame = move(jpeg);
725
726                         add_audio_or_silence(qf);
727                 } else if (qf.type == QueuedFrame::INTERPOLATED || qf.type == QueuedFrame::FADED_INTERPOLATED) {
728                         glClientWaitSync(qf.fence.get(), /*flags=*/0, GL_TIMEOUT_IGNORED);
729
730                         // Send it on to display.
731                         shared_ptr<Frame> frame = frame_from_pbo(qf.resources->pbo_contents, global_flags.width, global_flags.height);
732                         if (qf.display_decoded_func != nullptr) {
733                                 qf.display_decoded_func(frame);
734                         }
735
736                         // Now JPEG encode it, and send it on to the stream.
737                         string jpeg = encode_jpeg(frame->y.get(), frame->cb.get(), frame->cr.get(), global_flags.width, global_flags.height, move(qf.exif_data));
738                         if (qf.flow_tex != 0) {
739                                 compute_flow->release_texture(qf.flow_tex);
740                         }
741                         if (qf.type != QueuedFrame::FADED_INTERPOLATED) {
742                                 interpolate->release_texture(qf.output_tex);
743                                 interpolate->release_texture(qf.cbcr_tex);
744                         }
745
746                         AVPacket pkt;
747                         av_init_packet(&pkt);
748                         pkt.stream_index = 0;
749                         pkt.data = (uint8_t *)jpeg.data();
750                         pkt.size = jpeg.size();
751                         pkt.flags = AV_PKT_FLAG_KEY;
752                         mux->add_packet(pkt, qf.output_pts, qf.output_pts);
753                         last_frame = move(jpeg);
754
755                         add_audio_or_silence(qf);
756                 } else if (qf.type == QueuedFrame::REFRESH) {
757                         AVPacket pkt;
758                         av_init_packet(&pkt);
759                         pkt.stream_index = 0;
760                         pkt.data = (uint8_t *)last_frame.data();
761                         pkt.size = last_frame.size();
762                         pkt.flags = AV_PKT_FLAG_KEY;
763                         mux->add_packet(pkt, qf.output_pts, qf.output_pts);
764
765                         add_audio_or_silence(qf);  // Definitely silence.
766                 } else if (qf.type == QueuedFrame::SILENCE) {
767                         add_silence(qf.output_pts, qf.silence_length_pts);
768                 } else {
769                         assert(false);
770                 }
771                 if (qf.display_func != nullptr) {
772                         qf.display_func();
773                 }
774         }
775 }
776
777 int VideoStream::write_packet2_thunk(void *opaque, uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
778 {
779         VideoStream *video_stream = (VideoStream *)opaque;
780         return video_stream->write_packet2(buf, buf_size, type, time);
781 }
782
783 int VideoStream::write_packet2(uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
784 {
785         if (type == AVIO_DATA_MARKER_SYNC_POINT || type == AVIO_DATA_MARKER_BOUNDARY_POINT) {
786                 seen_sync_markers = true;
787         } else if (type == AVIO_DATA_MARKER_UNKNOWN && !seen_sync_markers) {
788                 // We don't know if this is a keyframe or not (the muxer could
789                 // avoid marking it), so we just have to make the best of it.
790                 type = AVIO_DATA_MARKER_SYNC_POINT;
791         }
792
793         if (type == AVIO_DATA_MARKER_HEADER) {
794                 stream_mux_header.append((char *)buf, buf_size);
795                 global_httpd->set_header(HTTPD::MAIN_STREAM, stream_mux_header);
796         } else {
797                 global_httpd->add_data(HTTPD::MAIN_STREAM, (char *)buf, buf_size, type == AVIO_DATA_MARKER_SYNC_POINT, time, AVRational{ AV_TIME_BASE, 1 });
798         }
799         return buf_size;
800 }
801
802 void VideoStream::add_silence(int64_t pts, int64_t length_pts)
803 {
804         // At 59.94, this will never quite add up (even discounting refresh frames,
805         // which have unpredictable length), but hopefully, the player in the other
806         // end should be able to stretch silence easily enough.
807         long num_samples = lrint(length_pts * double(OUTPUT_FREQUENCY) / double(TIMEBASE)) * 2;
808         uint8_t *zero = (uint8_t *)calloc(num_samples, sizeof(int32_t));
809
810         AVPacket pkt;
811         av_init_packet(&pkt);
812         pkt.stream_index = 1;
813         pkt.data = zero;
814         pkt.size = num_samples * sizeof(int32_t);
815         pkt.flags = AV_PKT_FLAG_KEY;
816         mux->add_packet(pkt, pts, pts);
817
818         free(zero);
819 }
820
821 void VideoStream::add_audio_or_silence(const QueuedFrame &qf)
822 {
823         if (qf.audio.empty()) {
824                 int64_t frame_length = lrint(double(TIMEBASE) / global_flags.output_framerate);
825                 add_silence(qf.output_pts, frame_length);
826         } else {
827                 AVPacket pkt;
828                 av_init_packet(&pkt);
829                 pkt.stream_index = 1;
830                 pkt.data = (uint8_t *)qf.audio.data();
831                 pkt.size = qf.audio.size();
832                 pkt.flags = AV_PKT_FLAG_KEY;
833                 mux->add_packet(pkt, qf.output_pts, qf.output_pts);
834         }
835 }