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