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