]> git.sesse.net Git - nageru/blob - futatabi/video_stream.cpp
Support exporting interpolated singletrack video. Probably tickles leaks in Player...
[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 "shared/context.h"
10 #include "flags.h"
11 #include "flow.h"
12 #include "shared/httpd.h"
13 #include "jpeg_frame_view.h"
14 #include "movit/util.h"
15 #include "shared/mux.h"
16 #include "player.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         std::vector<uint8_t> 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 = 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 vector<uint8_t> 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                 // Allocate something just for simplicity; we won't be using it.
213                 op = operating_point1;
214         } else if (global_flags.interpolation_quality == 1) {
215                 op = operating_point1;
216         } else if (global_flags.interpolation_quality == 2) {
217                 op = operating_point2;
218         } else if (global_flags.interpolation_quality == 3) {
219                 op = operating_point3;
220         } else if (global_flags.interpolation_quality == 4) {
221                 op = operating_point4;
222         } else {
223                 assert(false);
224         }
225
226         compute_flow.reset(new DISComputeFlow(width, height, op));
227         interpolate.reset(new Interpolate(op, /*split_ycbcr_output=*/true));
228         interpolate_no_split.reset(new Interpolate(op, /*split_ycbcr_output=*/false));
229         chroma_subsampler.reset(new ChromaSubsampler);
230         check_error();
231
232         // The “last frame” is initially black.
233         unique_ptr<uint8_t[]> y(new uint8_t[global_flags.width * global_flags.height]);
234         unique_ptr<uint8_t[]> cb_or_cr(new uint8_t[(global_flags.width / 2) * global_flags.height]);
235         memset(y.get(), 16, global_flags.width * global_flags.height);
236         memset(cb_or_cr.get(), 128, (global_flags.width / 2) * global_flags.height);
237         last_frame = encode_jpeg(y.get(), cb_or_cr.get(), cb_or_cr.get(), global_flags.width, global_flags.height);
238 }
239
240 VideoStream::~VideoStream() {}
241
242 void VideoStream::start()
243 {
244         if (avctx == nullptr) {
245                 avctx = avformat_alloc_context();
246
247                 // We use Matroska, because it's pretty much the only mux where FFmpeg
248                 // allows writing chroma location to override JFIF's default center placement.
249                 // (Note that at the time of writing, however, FFmpeg does not correctly
250                 // _read_ this information!)
251                 avctx->oformat = av_guess_format("matroska", nullptr, nullptr);
252
253                 uint8_t *buf = (uint8_t *)av_malloc(MUX_BUFFER_SIZE);
254                 avctx->pb = avio_alloc_context(buf, MUX_BUFFER_SIZE, 1, this, nullptr, nullptr, nullptr);
255                 avctx->pb->write_data_type = &VideoStream::write_packet2_thunk;
256                 avctx->pb->ignore_boundary_point = 1;
257
258                 avctx->flags = AVFMT_FLAG_CUSTOM_IO;
259         }
260
261         size_t width = global_flags.width, height = global_flags.height;  // Doesn't matter for MJPEG.
262         mux.reset(new Mux(avctx, width, height, Mux::CODEC_MJPEG, /*video_extradata=*/"", /*audio_codec_parameters=*/nullptr,
263                 AVCOL_SPC_BT709, Mux::WITHOUT_AUDIO,
264                 COARSE_TIMEBASE, /*write_callback=*/nullptr, Mux::WRITE_FOREGROUND, {}));
265
266         encode_thread = thread(&VideoStream::encode_thread_func, this);
267 }
268
269 void VideoStream::stop()
270 {
271         should_quit = true;
272         clear_queue();
273         encode_thread.join();
274 }
275
276 void VideoStream::clear_queue()
277 {
278         deque<QueuedFrame> q;
279
280         {
281                 unique_lock<mutex> lock(queue_lock);
282                 q = move(frame_queue);
283         }
284
285         // These are not RAII-ed, unfortunately, so we'll need to clean them ourselves.
286         // Note that release_texture() is thread-safe.
287         for (const QueuedFrame &qf : q) {
288                 if (qf.type == QueuedFrame::INTERPOLATED ||
289                     qf.type == QueuedFrame::FADED_INTERPOLATED) {
290                         compute_flow->release_texture(qf.flow_tex);
291                 }
292                 if (qf.type == QueuedFrame::INTERPOLATED) {
293                         interpolate->release_texture(qf.output_tex);
294                         interpolate->release_texture(qf.cbcr_tex);
295                 }
296         }
297
298         // Destroy q outside the mutex, as that would be a double-lock.
299 }
300
301 void VideoStream::schedule_original_frame(steady_clock::time_point local_pts,
302                                           int64_t output_pts, function<void()> &&display_func,
303                                           QueueSpotHolder &&queue_spot_holder,
304                                           FrameOnDisk frame)
305 {
306         fprintf(stderr, "output_pts=%ld  original      input_pts=%ld\n", output_pts, frame.pts);
307
308         // Preload the file from disk, so that the encoder thread does not get stalled.
309         // TODO: Consider sending it through the queue instead.
310         (void)frame_reader.read_frame(frame);
311
312         QueuedFrame qf;
313         qf.local_pts = local_pts;
314         qf.type = QueuedFrame::ORIGINAL;
315         qf.output_pts = output_pts;
316         qf.frame1 = frame;
317         qf.display_func = move(display_func);
318         qf.queue_spot_holder = move(queue_spot_holder);
319
320         unique_lock<mutex> lock(queue_lock);
321         frame_queue.push_back(move(qf));
322         queue_changed.notify_all();
323 }
324
325 void VideoStream::schedule_faded_frame(steady_clock::time_point local_pts, int64_t output_pts,
326                                        function<void()> &&display_func,
327                                        QueueSpotHolder &&queue_spot_holder,
328                                        FrameOnDisk frame1_spec, FrameOnDisk frame2_spec,
329                                        float fade_alpha)
330 {
331         fprintf(stderr, "output_pts=%ld  faded         input_pts=%ld,%ld  fade_alpha=%.2f\n", output_pts, frame1_spec.pts, frame2_spec.pts, fade_alpha);
332
333         // Get the temporary OpenGL resources we need for doing the fade.
334         // (We share these with interpolated frames, which is slightly
335         // overkill, but there's no need to waste resources on keeping
336         // separate pools around.)
337         BorrowedInterpolatedFrameResources resources;
338         {
339                 unique_lock<mutex> lock(queue_lock);
340                 if (interpolate_resources.empty()) {
341                         fprintf(stderr, "WARNING: Too many interpolated frames already in transit; dropping one.\n");
342                         return;
343                 }
344                 resources = BorrowedInterpolatedFrameResources(interpolate_resources.front().release());
345                 interpolate_resources.pop_front();
346         }
347
348         bool did_decode;
349
350         shared_ptr<Frame> frame1 = decode_jpeg_with_cache(frame1_spec, DECODE_IF_NOT_IN_CACHE, &frame_reader, &did_decode);
351         shared_ptr<Frame> frame2 = decode_jpeg_with_cache(frame2_spec, DECODE_IF_NOT_IN_CACHE, &frame_reader, &did_decode);
352
353         ycbcr_semiplanar_converter->prepare_chain_for_fade(frame1, frame2, fade_alpha)->render_to_fbo(resources->fade_fbo, global_flags.width, global_flags.height);
354
355         QueuedFrame qf;
356         qf.local_pts = local_pts;
357         qf.type = QueuedFrame::FADED;
358         qf.output_pts = output_pts;
359         qf.frame1 = frame1_spec;
360         qf.display_func = move(display_func);
361         qf.queue_spot_holder = move(queue_spot_holder);
362
363         qf.secondary_frame = frame2_spec;
364
365         // Subsample and split Cb/Cr.
366         chroma_subsampler->subsample_chroma(resources->fade_cbcr_output_tex, global_flags.width, global_flags.height, resources->cb_tex, resources->cr_tex);
367
368         // Read it down (asynchronously) to the CPU.
369         glPixelStorei(GL_PACK_ROW_LENGTH, 0);
370         glBindBuffer(GL_PIXEL_PACK_BUFFER, resources->pbo);
371         check_error();
372         glGetTextureImage(resources->fade_y_output_tex, 0, GL_RED, GL_UNSIGNED_BYTE, global_flags.width * global_flags.height * 4, BUFFER_OFFSET(0));
373         check_error();
374         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));
375         check_error();
376         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));
377         check_error();
378         glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
379
380         // Set a fence we can wait for to make sure the CPU sees the read.
381         glMemoryBarrier(GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT);
382         check_error();
383         qf.fence = RefCountedGLsync(GL_SYNC_GPU_COMMANDS_COMPLETE, /*flags=*/0);
384         check_error();
385         qf.resources = move(resources);
386         qf.local_pts = local_pts;
387
388         unique_lock<mutex> lock(queue_lock);
389         frame_queue.push_back(move(qf));
390         queue_changed.notify_all();
391 }
392
393 void VideoStream::schedule_interpolated_frame(steady_clock::time_point local_pts,
394                                               int64_t output_pts, function<void(shared_ptr<Frame>)> &&display_func,
395                                               QueueSpotHolder &&queue_spot_holder,
396                                               FrameOnDisk frame1, FrameOnDisk frame2,
397                                               float alpha, FrameOnDisk secondary_frame, float fade_alpha)
398 {
399         if (secondary_frame.pts != -1) {
400                 fprintf(stderr, "output_pts=%ld  interpolated  input_pts1=%ld input_pts2=%ld alpha=%.3f  secondary_pts=%ld  fade_alpha=%.2f\n", output_pts, frame1.pts, frame2.pts, alpha, secondary_frame.pts, fade_alpha);
401         } else {
402                 fprintf(stderr, "output_pts=%ld  interpolated  input_pts1=%ld input_pts2=%ld alpha=%.3f\n", output_pts, frame1.pts, frame2.pts, alpha);
403         }
404
405         // Get the temporary OpenGL resources we need for doing the interpolation.
406         BorrowedInterpolatedFrameResources resources;
407         {
408                 unique_lock<mutex> lock(queue_lock);
409                 if (interpolate_resources.empty()) {
410                         fprintf(stderr, "WARNING: Too many interpolated frames already in transit; dropping one.\n");
411                         return;
412                 }
413                 resources = BorrowedInterpolatedFrameResources(interpolate_resources.front().release());
414                 interpolate_resources.pop_front();
415         }
416
417         QueuedFrame qf;
418         qf.type = (secondary_frame.pts == -1) ? QueuedFrame::INTERPOLATED : QueuedFrame::FADED_INTERPOLATED;
419         qf.output_pts = output_pts;
420         qf.display_decoded_func = move(display_func);
421         qf.queue_spot_holder = move(queue_spot_holder);
422         qf.local_pts = local_pts;
423
424         check_error();
425
426         // Convert frame0 and frame1 to OpenGL textures.
427         for (size_t frame_no = 0; frame_no < 2; ++frame_no) {
428                 FrameOnDisk frame_spec = frame_no == 1 ? frame2 : frame1;
429                 bool did_decode;
430                 shared_ptr<Frame> frame = decode_jpeg_with_cache(frame_spec, DECODE_IF_NOT_IN_CACHE, &frame_reader, &did_decode);
431                 ycbcr_converter->prepare_chain_for_conversion(frame)->render_to_fbo(resources->input_fbos[frame_no], global_flags.width, global_flags.height);
432         }
433
434         glGenerateTextureMipmap(resources->input_tex);
435         check_error();
436         glGenerateTextureMipmap(resources->gray_tex);
437         check_error();
438
439         // Compute the interpolated frame.
440         qf.flow_tex = compute_flow->exec(resources->gray_tex, DISComputeFlow::FORWARD_AND_BACKWARD, DISComputeFlow::DO_NOT_RESIZE_FLOW);
441         check_error();
442
443         if (secondary_frame.pts != -1) {
444                 // Fade. First kick off the interpolation.
445                 tie(qf.output_tex, ignore) = interpolate_no_split->exec(resources->input_tex, resources->gray_tex, qf.flow_tex, global_flags.width, global_flags.height, alpha);
446                 check_error();
447
448                 // Now decode the image we are fading against.
449                 bool did_decode;
450                 shared_ptr<Frame> frame2 = decode_jpeg_with_cache(secondary_frame, DECODE_IF_NOT_IN_CACHE, &frame_reader, &did_decode);
451
452                 // Then fade against it, putting it into the fade Y' and CbCr textures.
453                 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);
454
455                 // Subsample and split Cb/Cr.
456                 chroma_subsampler->subsample_chroma(resources->fade_cbcr_output_tex, global_flags.width, global_flags.height, resources->cb_tex, resources->cr_tex);
457
458                 interpolate_no_split->release_texture(qf.output_tex);
459         } else {
460                 tie(qf.output_tex, qf.cbcr_tex) = interpolate->exec(resources->input_tex, resources->gray_tex, qf.flow_tex, global_flags.width, global_flags.height, alpha);
461                 check_error();
462
463                 // Subsample and split Cb/Cr.
464                 chroma_subsampler->subsample_chroma(qf.cbcr_tex, global_flags.width, global_flags.height, resources->cb_tex, resources->cr_tex);
465         }
466
467         // We could have released qf.flow_tex here, but to make sure we don't cause a stall
468         // when trying to reuse it for the next frame, we can just as well hold on to it
469         // and release it only when the readback is done.
470
471         // Read it down (asynchronously) to the CPU.
472         glPixelStorei(GL_PACK_ROW_LENGTH, 0);
473         glBindBuffer(GL_PIXEL_PACK_BUFFER, resources->pbo);
474         check_error();
475         if (secondary_frame.pts != -1) {
476                 glGetTextureImage(resources->fade_y_output_tex, 0, GL_RED, GL_UNSIGNED_BYTE, global_flags.width * global_flags.height * 4, BUFFER_OFFSET(0));
477         } else {
478                 glGetTextureImage(qf.output_tex, 0, GL_RED, GL_UNSIGNED_BYTE, global_flags.width * global_flags.height * 4, BUFFER_OFFSET(0));
479         }
480         check_error();
481         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));
482         check_error();
483         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));
484         check_error();
485         glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
486
487         // Set a fence we can wait for to make sure the CPU sees the read.
488         glMemoryBarrier(GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT);
489         check_error();
490         qf.fence = RefCountedGLsync(GL_SYNC_GPU_COMMANDS_COMPLETE, /*flags=*/0);
491         check_error();
492         qf.resources = move(resources);
493
494         unique_lock<mutex> lock(queue_lock);
495         frame_queue.push_back(move(qf));
496         queue_changed.notify_all();
497 }
498
499 void VideoStream::schedule_refresh_frame(steady_clock::time_point local_pts,
500                                          int64_t output_pts, function<void()> &&display_func,
501                                          QueueSpotHolder &&queue_spot_holder)
502 {
503         QueuedFrame qf;
504         qf.type = QueuedFrame::REFRESH;
505         qf.output_pts = output_pts;
506         qf.display_func = move(display_func);
507         qf.queue_spot_holder = move(queue_spot_holder);
508
509         unique_lock<mutex> lock(queue_lock);
510         frame_queue.push_back(move(qf));
511         queue_changed.notify_all();
512 }
513
514 namespace {
515
516 shared_ptr<Frame> frame_from_pbo(void *contents, size_t width, size_t height)
517 {
518         size_t chroma_width = width / 2;
519
520         const uint8_t *y = (const uint8_t *)contents;
521         const uint8_t *cb = (const uint8_t *)contents + width * height;
522         const uint8_t *cr = (const uint8_t *)contents + width * height + chroma_width * height;
523
524         shared_ptr<Frame> frame(new Frame);
525         frame->y.reset(new uint8_t[width * height]);
526         frame->cb.reset(new uint8_t[chroma_width * height]);
527         frame->cr.reset(new uint8_t[chroma_width * height]);
528         for (unsigned yy = 0; yy < height; ++yy) {
529                 memcpy(frame->y.get() + width * yy, y + width * yy, width);
530                 memcpy(frame->cb.get() + chroma_width * yy, cb + chroma_width * yy, chroma_width);
531                 memcpy(frame->cr.get() + chroma_width * yy, cr + chroma_width * yy, chroma_width);
532         }
533         frame->is_semiplanar = false;
534         frame->width = width;
535         frame->height = height;
536         frame->chroma_subsampling_x = 2;
537         frame->chroma_subsampling_y = 1;
538         frame->pitch_y = width;
539         frame->pitch_chroma = chroma_width;
540         return frame;
541 }
542
543 }  // namespace
544
545 void VideoStream::encode_thread_func()
546 {
547         pthread_setname_np(pthread_self(), "VideoStream");
548         QSurface *surface = create_surface();
549         QOpenGLContext *context = create_context(surface);
550         bool ok = make_current(context, surface);
551         if (!ok) {
552                 fprintf(stderr, "Video stream couldn't get an OpenGL context\n");
553                 exit(1);
554         }
555
556         while (!should_quit) {
557                 QueuedFrame qf;
558                 {
559                         unique_lock<mutex> lock(queue_lock);
560
561                         // Wait until we have a frame to play.
562                         queue_changed.wait(lock, [this]{
563                                 return !frame_queue.empty();
564                         });
565                         steady_clock::time_point frame_start = frame_queue.front().local_pts;
566
567                         // Now sleep until the frame is supposed to start (the usual case),
568                         // _or_ clear_queue() happened.
569                         bool aborted;
570                         if (output_fast_forward) {
571                                 aborted = frame_queue.empty() || frame_queue.front().local_pts != frame_start;
572                         } else {
573                                 aborted = queue_changed.wait_until(lock, frame_start, [this, frame_start]{
574                                         return frame_queue.empty() || frame_queue.front().local_pts != frame_start;
575                                 });
576                         }
577                         if (aborted) {
578                                 // clear_queue() happened, so don't play this frame after all.
579                                 continue;
580                         }
581                         qf = move(frame_queue.front());
582                         frame_queue.pop_front();
583                 }
584
585                 if (qf.type == QueuedFrame::ORIGINAL) {
586                         // Send the JPEG frame on, unchanged.
587                         string jpeg = frame_reader.read_frame(qf.frame1);
588                         AVPacket pkt;
589                         av_init_packet(&pkt);
590                         pkt.stream_index = 0;
591                         pkt.data = (uint8_t *)jpeg.data();
592                         pkt.size = jpeg.size();
593                         mux->add_packet(pkt, qf.output_pts, qf.output_pts);
594
595                         last_frame.assign(&jpeg[0], &jpeg[0] + jpeg.size());
596                 } else if (qf.type == QueuedFrame::FADED) {
597                         glClientWaitSync(qf.fence.get(), /*flags=*/0, GL_TIMEOUT_IGNORED);
598
599                         shared_ptr<Frame> frame = frame_from_pbo(qf.resources->pbo_contents, global_flags.width, global_flags.height);
600
601                         // Now JPEG encode it, and send it on to the stream.
602                         vector<uint8_t> jpeg = encode_jpeg(frame->y.get(), frame->cb.get(), frame->cr.get(), global_flags.width, global_flags.height);
603
604                         AVPacket pkt;
605                         av_init_packet(&pkt);
606                         pkt.stream_index = 0;
607                         pkt.data = (uint8_t *)jpeg.data();
608                         pkt.size = jpeg.size();
609                         mux->add_packet(pkt, qf.output_pts, qf.output_pts);
610                         last_frame = move(jpeg);
611                 } else if (qf.type == QueuedFrame::INTERPOLATED || qf.type == QueuedFrame::FADED_INTERPOLATED) {
612                         glClientWaitSync(qf.fence.get(), /*flags=*/0, GL_TIMEOUT_IGNORED);
613
614                         // Send it on to display.
615                         shared_ptr<Frame> frame = frame_from_pbo(qf.resources->pbo_contents, global_flags.width, global_flags.height);
616                         if (qf.display_decoded_func != nullptr) {
617                                 qf.display_decoded_func(frame);
618                         }
619
620                         // Now JPEG encode it, and send it on to the stream.
621                         vector<uint8_t> jpeg = encode_jpeg(frame->y.get(), frame->cb.get(), frame->cr.get(), global_flags.width, global_flags.height);
622                         compute_flow->release_texture(qf.flow_tex);
623                         if (qf.type != QueuedFrame::FADED_INTERPOLATED) {
624                                 interpolate->release_texture(qf.output_tex);
625                                 interpolate->release_texture(qf.cbcr_tex);
626                         }
627
628                         AVPacket pkt;
629                         av_init_packet(&pkt);
630                         pkt.stream_index = 0;
631                         pkt.data = (uint8_t *)jpeg.data();
632                         pkt.size = jpeg.size();
633                         mux->add_packet(pkt, qf.output_pts, qf.output_pts);
634                         last_frame = move(jpeg);
635                 } else if (qf.type == QueuedFrame::REFRESH) {
636                         AVPacket pkt;
637                         av_init_packet(&pkt);
638                         pkt.stream_index = 0;
639                         pkt.data = (uint8_t *)last_frame.data();
640                         pkt.size = last_frame.size();
641                         mux->add_packet(pkt, qf.output_pts, qf.output_pts);
642                 } else {
643                         assert(false);
644                 }
645                 if (qf.display_func != nullptr) {
646                         qf.display_func();
647                 }
648         }
649 }
650
651 int VideoStream::write_packet2_thunk(void *opaque, uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
652 {
653         VideoStream *video_stream = (VideoStream *)opaque;
654         return video_stream->write_packet2(buf, buf_size, type, time);
655 }
656
657 int VideoStream::write_packet2(uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
658 {
659         if (type == AVIO_DATA_MARKER_SYNC_POINT || type == AVIO_DATA_MARKER_BOUNDARY_POINT) {
660                 seen_sync_markers = true;
661         } else if (type == AVIO_DATA_MARKER_UNKNOWN && !seen_sync_markers) {
662                 // We don't know if this is a keyframe or not (the muxer could
663                 // avoid marking it), so we just have to make the best of it.
664                 type = AVIO_DATA_MARKER_SYNC_POINT;
665         }
666
667         if (type == AVIO_DATA_MARKER_HEADER) {
668                 stream_mux_header.append((char *)buf, buf_size);
669                 global_httpd->set_header(HTTPD::MAIN_STREAM, stream_mux_header);
670         } else {
671                 global_httpd->add_data(HTTPD::MAIN_STREAM, (char *)buf, buf_size, type == AVIO_DATA_MARKER_SYNC_POINT, time, AVRational{ AV_TIME_BASE, 1 });
672         }
673         return buf_size;
674 }