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