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