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