]> git.sesse.net Git - nageru/blob - video_stream.cpp
Move to RAII queue counting, to fix some underflows.
[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                                           QueueSpotHolder &&queue_spot_holder,
294                                           unsigned stream_idx, int64_t input_pts)
295 {
296         fprintf(stderr, "output_pts=%ld  original      input_pts=%ld\n", output_pts, input_pts);
297
298         // Preload the file from disk, so that the encoder thread does not get stalled.
299         // TODO: Consider sending it through the queue instead.
300         (void)read_file(filename_for_frame(stream_idx, input_pts));
301
302         QueuedFrame qf;
303         qf.local_pts = local_pts;
304         qf.type = QueuedFrame::ORIGINAL;
305         qf.output_pts = output_pts;
306         qf.stream_idx = stream_idx;
307         qf.input_first_pts = input_pts;
308         qf.display_func = move(display_func);
309         qf.queue_spot_holder = move(queue_spot_holder);
310
311         unique_lock<mutex> lock(queue_lock);
312         frame_queue.push_back(move(qf));
313         queue_changed.notify_all();
314 }
315
316 void VideoStream::schedule_faded_frame(steady_clock::time_point local_pts, int64_t output_pts,
317                                        function<void()> &&display_func,
318                                        QueueSpotHolder &&queue_spot_holder,
319                                        unsigned stream_idx, int64_t input_pts, int secondary_stream_idx,
320                                        int64_t secondary_input_pts, float fade_alpha)
321 {
322         fprintf(stderr, "output_pts=%ld  faded         input_pts=%ld,%ld  fade_alpha=%.2f\n", output_pts, input_pts, secondary_input_pts, fade_alpha);
323
324         // Get the temporary OpenGL resources we need for doing the fade.
325         // (We share these with interpolated frames, which is slightly
326         // overkill, but there's no need to waste resources on keeping
327         // separate pools around.)
328         InterpolatedFrameResources resources;
329         {
330                 unique_lock<mutex> lock(queue_lock);
331                 if (interpolate_resources.empty()) {
332                         fprintf(stderr, "WARNING: Too many interpolated frames already in transit; dropping one.\n");
333                         return;
334                 }
335                 resources = interpolate_resources.front();
336                 interpolate_resources.pop_front();
337         }
338
339         bool did_decode;
340
341         JPEGID jpeg_id1;
342         jpeg_id1.stream_idx = stream_idx;
343         jpeg_id1.pts = input_pts;
344         jpeg_id1.interpolated = false;
345         shared_ptr<Frame> frame1 = decode_jpeg_with_cache(jpeg_id1, DECODE_IF_NOT_IN_CACHE, &did_decode);
346
347         JPEGID jpeg_id2;
348         jpeg_id2.stream_idx = secondary_stream_idx;
349         jpeg_id2.pts = secondary_input_pts;
350         jpeg_id2.interpolated = false;
351         shared_ptr<Frame> frame2 = decode_jpeg_with_cache(jpeg_id2, DECODE_IF_NOT_IN_CACHE, &did_decode);
352
353         ycbcr_semiplanar_converter->prepare_chain_for_fade(frame1, frame2, fade_alpha)->render_to_fbo(resources.fade_fbo, 1280, 720);
354
355         QueuedFrame qf;
356         qf.local_pts = local_pts;
357         qf.type = QueuedFrame::FADED;
358         qf.output_pts = output_pts;
359         qf.stream_idx = stream_idx;
360         qf.resources = resources;
361         qf.input_first_pts = input_pts;
362         qf.display_func = move(display_func);
363         qf.queue_spot_holder = move(queue_spot_holder);
364
365         qf.secondary_stream_idx = secondary_stream_idx;
366         qf.secondary_input_pts = secondary_input_pts;
367
368         // Subsample and split Cb/Cr.
369         chroma_subsampler->subsample_chroma(resources.fade_cbcr_output_tex, 1280, 720, resources.cb_tex, resources.cr_tex);
370
371         // Read it down (asynchronously) to the CPU.
372         glPixelStorei(GL_PACK_ROW_LENGTH, 0);
373         glBindBuffer(GL_PIXEL_PACK_BUFFER, resources.pbo);
374         check_error();
375         glGetTextureImage(resources.fade_y_output_tex, 0, GL_RED, GL_UNSIGNED_BYTE, 1280 * 720 * 4, BUFFER_OFFSET(0));
376         check_error();
377         glGetTextureImage(resources.cb_tex, 0, GL_RED, GL_UNSIGNED_BYTE, 1280 * 720 * 3, BUFFER_OFFSET(1280 * 720));
378         check_error();
379         glGetTextureImage(resources.cr_tex, 0, GL_RED, GL_UNSIGNED_BYTE, 1280 * 720 * 3 - 640 * 720, BUFFER_OFFSET(1280 * 720 + 640 * 720));
380         check_error();
381         glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
382
383         // Set a fence we can wait for to make sure the CPU sees the read.
384         glMemoryBarrier(GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT);
385         check_error();
386         qf.fence = RefCountedGLsync(GL_SYNC_GPU_COMMANDS_COMPLETE, /*flags=*/0);
387         check_error();
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()> &&display_func,
396                                               QueueSpotHolder &&queue_spot_holder,
397                                               unsigned stream_idx, int64_t input_first_pts,
398                                               int64_t input_second_pts, float alpha,
399                                               int secondary_stream_idx, int64_t secondary_input_pts,
400                                               float fade_alpha)
401 {
402         if (secondary_stream_idx != -1) {
403                 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);
404         } else {
405                 fprintf(stderr, "output_pts=%ld  interpolated  input_pts1=%ld input_pts2=%ld alpha=%.3f\n", output_pts, input_first_pts, input_second_pts, alpha);
406         }
407
408         JPEGID id;
409         if (secondary_stream_idx == -1) {
410                 id = JPEGID{ stream_idx, output_pts, /*interpolated=*/true };
411         } else {
412                 id = create_jpegid_for_interpolated_fade(stream_idx, output_pts, secondary_stream_idx, secondary_input_pts);
413         }
414
415         // Get the temporary OpenGL resources we need for doing the interpolation.
416         InterpolatedFrameResources resources;
417         {
418                 unique_lock<mutex> lock(queue_lock);
419                 if (interpolate_resources.empty()) {
420                         fprintf(stderr, "WARNING: Too many interpolated frames already in transit; dropping one.\n");
421                         return;
422                 }
423                 resources = interpolate_resources.front();
424                 interpolate_resources.pop_front();
425         }
426
427         QueuedFrame qf;
428         qf.type = (secondary_stream_idx == -1) ? QueuedFrame::INTERPOLATED : QueuedFrame::FADED_INTERPOLATED;
429         qf.output_pts = output_pts;
430         qf.stream_idx = stream_idx;
431         qf.resources = resources;
432         qf.id = id;
433         qf.display_func = move(display_func);
434         qf.queue_spot_holder = move(queue_spot_holder);
435
436         check_error();
437
438         // Convert frame0 and frame1 to OpenGL textures.
439         for (size_t frame_no = 0; frame_no < 2; ++frame_no) {
440                 JPEGID jpeg_id;
441                 jpeg_id.stream_idx = stream_idx;
442                 jpeg_id.pts = frame_no == 1 ? input_second_pts : input_first_pts;
443                 jpeg_id.interpolated = false;
444                 bool did_decode;
445                 shared_ptr<Frame> frame = decode_jpeg_with_cache(jpeg_id, DECODE_IF_NOT_IN_CACHE, &did_decode);
446                 ycbcr_converter->prepare_chain_for_conversion(frame)->render_to_fbo(resources.input_fbos[frame_no], 1280, 720);
447         }
448
449         glGenerateTextureMipmap(resources.input_tex);
450         check_error();
451         glGenerateTextureMipmap(resources.gray_tex);
452         check_error();
453
454         // Compute the interpolated frame.
455         qf.flow_tex = compute_flow->exec(resources.gray_tex, DISComputeFlow::FORWARD_AND_BACKWARD, DISComputeFlow::DO_NOT_RESIZE_FLOW);
456         check_error();
457
458         if (secondary_stream_idx != -1) {
459                 // Fade. First kick off the interpolation.
460                 tie(qf.output_tex, ignore) = interpolate_no_split->exec(resources.input_tex, resources.gray_tex, qf.flow_tex, 1280, 720, alpha);
461                 check_error();
462
463                 // Now decode the image we are fading against.
464                 JPEGID jpeg_id;
465                 jpeg_id.stream_idx = secondary_stream_idx;
466                 jpeg_id.pts = secondary_input_pts;
467                 jpeg_id.interpolated = false;
468                 bool did_decode;
469                 shared_ptr<Frame> frame2 = decode_jpeg_with_cache(jpeg_id, DECODE_IF_NOT_IN_CACHE, &did_decode);
470
471                 // Then fade against it, putting it into the fade Y' and CbCr textures.
472                 ycbcr_semiplanar_converter->prepare_chain_for_fade_from_texture(qf.output_tex, frame2, fade_alpha)->render_to_fbo(resources.fade_fbo, 1280, 720);
473
474                 // Subsample and split Cb/Cr.
475                 chroma_subsampler->subsample_chroma(resources.fade_cbcr_output_tex, 1280, 720, resources.cb_tex, resources.cr_tex);
476
477                 interpolate_no_split->release_texture(qf.output_tex);
478         } else {
479                 tie(qf.output_tex, qf.cbcr_tex) = interpolate->exec(resources.input_tex, resources.gray_tex, qf.flow_tex, 1280, 720, alpha);
480                 check_error();
481
482                 // Subsample and split Cb/Cr.
483                 chroma_subsampler->subsample_chroma(qf.cbcr_tex, 1280, 720, resources.cb_tex, resources.cr_tex);
484         }
485
486         // We could have released qf.flow_tex here, but to make sure we don't cause a stall
487         // when trying to reuse it for the next frame, we can just as well hold on to it
488         // and release it only when the readback is done.
489
490         // Read it down (asynchronously) to the CPU.
491         glPixelStorei(GL_PACK_ROW_LENGTH, 0);
492         glBindBuffer(GL_PIXEL_PACK_BUFFER, resources.pbo);
493         check_error();
494         if (secondary_stream_idx != -1) {
495                 glGetTextureImage(resources.fade_y_output_tex, 0, GL_RED, GL_UNSIGNED_BYTE, 1280 * 720 * 4, BUFFER_OFFSET(0));
496         } else {
497                 glGetTextureImage(qf.output_tex, 0, GL_RED, GL_UNSIGNED_BYTE, 1280 * 720 * 4, BUFFER_OFFSET(0));
498         }
499         check_error();
500         glGetTextureImage(resources.cb_tex, 0, GL_RED, GL_UNSIGNED_BYTE, 1280 * 720 * 3, BUFFER_OFFSET(1280 * 720));
501         check_error();
502         glGetTextureImage(resources.cr_tex, 0, GL_RED, GL_UNSIGNED_BYTE, 1280 * 720 * 3 - 640 * 720, BUFFER_OFFSET(1280 * 720 + 640 * 720));
503         check_error();
504         glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
505
506         // Set a fence we can wait for to make sure the CPU sees the read.
507         glMemoryBarrier(GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT);
508         check_error();
509         qf.fence = RefCountedGLsync(GL_SYNC_GPU_COMMANDS_COMPLETE, /*flags=*/0);
510         check_error();
511
512         unique_lock<mutex> lock(queue_lock);
513         frame_queue.push_back(move(qf));
514         queue_changed.notify_all();
515 }
516
517 void VideoStream::schedule_refresh_frame(steady_clock::time_point local_pts,
518                                          int64_t output_pts, function<void()> &&display_func,
519                                          QueueSpotHolder &&queue_spot_holder)
520 {
521         QueuedFrame qf;
522         qf.type = QueuedFrame::REFRESH;
523         qf.output_pts = output_pts;
524         qf.display_func = move(display_func);
525         qf.queue_spot_holder = move(queue_spot_holder);
526
527         unique_lock<mutex> lock(queue_lock);
528         frame_queue.push_back(move(qf));
529         queue_changed.notify_all();
530 }
531
532 namespace {
533
534 shared_ptr<Frame> frame_from_pbo(void *contents, size_t width, size_t height)
535 {
536         size_t chroma_width = width / 2;
537
538         const uint8_t *y = (const uint8_t *)contents;
539         const uint8_t *cb = (const uint8_t *)contents + width * height;
540         const uint8_t *cr = (const uint8_t *)contents + width * height + chroma_width * height;
541
542         shared_ptr<Frame> frame(new Frame);
543         frame->y.reset(new uint8_t[width * height]);
544         frame->cb.reset(new uint8_t[chroma_width * height]);
545         frame->cr.reset(new uint8_t[chroma_width * height]);
546         for (unsigned yy = 0; yy < height; ++yy) {
547                 memcpy(frame->y.get() + width * yy, y + width * yy, width);
548                 memcpy(frame->cb.get() + chroma_width * yy, cb + chroma_width * yy, chroma_width);
549                 memcpy(frame->cr.get() + chroma_width * yy, cr + chroma_width * yy, chroma_width);
550         }
551         frame->is_semiplanar = false;
552         frame->width = width;
553         frame->height = height;
554         frame->chroma_subsampling_x = 2;
555         frame->chroma_subsampling_y = 1;
556         frame->pitch_y = width;
557         frame->pitch_chroma = chroma_width;
558         return frame;
559 }
560
561 }  // namespace
562
563 void VideoStream::encode_thread_func()
564 {
565         pthread_setname_np(pthread_self(), "VideoStream");
566         QSurface *surface = create_surface();
567         QOpenGLContext *context = create_context(surface);
568         bool ok = make_current(context, surface);
569         if (!ok) {
570                 fprintf(stderr, "Video stream couldn't get an OpenGL context\n");
571                 exit(1);
572         }
573
574         for ( ;; ) {
575                 QueuedFrame qf;
576                 {
577                         unique_lock<mutex> lock(queue_lock);
578
579                         // Wait until we have a frame to play.
580                         queue_changed.wait(lock, [this]{
581                                 return !frame_queue.empty();
582                         });
583                         steady_clock::time_point frame_start = frame_queue.front().local_pts;
584
585                         // Now sleep until the frame is supposed to start (the usual case),
586                         // _or_ clear_queue() happened.
587                         bool aborted = queue_changed.wait_until(lock, frame_start, [this, frame_start]{
588                                 return frame_queue.empty() || frame_queue.front().local_pts != frame_start;
589                         });
590                         if (aborted) {
591                                 // clear_queue() happened, so don't play this frame after all.
592                                 continue;
593                         }
594                         qf = move(frame_queue.front());
595                         frame_queue.pop_front();
596                 }
597
598                 if (qf.type == QueuedFrame::ORIGINAL) {
599                         // Send the JPEG frame on, unchanged.
600                         string jpeg = read_file(filename_for_frame(qf.stream_idx, qf.input_first_pts));
601                         AVPacket pkt;
602                         av_init_packet(&pkt);
603                         pkt.stream_index = 0;
604                         pkt.data = (uint8_t *)jpeg.data();
605                         pkt.size = jpeg.size();
606                         stream_mux->add_packet(pkt, qf.output_pts, qf.output_pts);
607
608                         last_frame.assign(&jpeg[0], &jpeg[0] + jpeg.size());
609                 } else if (qf.type == QueuedFrame::FADED) {
610                         glClientWaitSync(qf.fence.get(), /*flags=*/0, GL_TIMEOUT_IGNORED);
611
612                         shared_ptr<Frame> frame = frame_from_pbo(qf.resources.pbo_contents, 1280, 720);
613
614                         // Now JPEG encode it, and send it on to the stream.
615                         vector<uint8_t> jpeg = encode_jpeg(frame->y.get(), frame->cb.get(), frame->cr.get(), 1280, 720);
616
617                         AVPacket pkt;
618                         av_init_packet(&pkt);
619                         pkt.stream_index = 0;
620                         pkt.data = (uint8_t *)jpeg.data();
621                         pkt.size = jpeg.size();
622                         stream_mux->add_packet(pkt, qf.output_pts, qf.output_pts);
623                         last_frame = move(jpeg);
624
625                         // Put the frame resources back.
626                         unique_lock<mutex> lock(queue_lock);
627                         interpolate_resources.push_back(qf.resources);
628                 } else if (qf.type == QueuedFrame::INTERPOLATED || qf.type == QueuedFrame::FADED_INTERPOLATED) {
629                         glClientWaitSync(qf.fence.get(), /*flags=*/0, GL_TIMEOUT_IGNORED);
630
631                         // Send a copy of the frame on to display.
632                         shared_ptr<Frame> frame = frame_from_pbo(qf.resources.pbo_contents, 1280, 720);
633                         JPEGFrameView::insert_interpolated_frame(qf.id, frame);
634
635                         // Now JPEG encode it, and send it on to the stream.
636                         vector<uint8_t> jpeg = encode_jpeg(frame->y.get(), frame->cb.get(), frame->cr.get(), 1280, 720);
637                         compute_flow->release_texture(qf.flow_tex);
638                         if (qf.type != QueuedFrame::FADED_INTERPOLATED) {
639                                 interpolate->release_texture(qf.output_tex);
640                                 interpolate->release_texture(qf.cbcr_tex);
641                         }
642
643                         AVPacket pkt;
644                         av_init_packet(&pkt);
645                         pkt.stream_index = 0;
646                         pkt.data = (uint8_t *)jpeg.data();
647                         pkt.size = jpeg.size();
648                         stream_mux->add_packet(pkt, qf.output_pts, qf.output_pts);
649                         last_frame = move(jpeg);
650
651                         // Put the frame resources back.
652                         unique_lock<mutex> lock(queue_lock);
653                         interpolate_resources.push_back(qf.resources);
654                 } else if (qf.type == QueuedFrame::REFRESH) {
655                         AVPacket pkt;
656                         av_init_packet(&pkt);
657                         pkt.stream_index = 0;
658                         pkt.data = (uint8_t *)last_frame.data();
659                         pkt.size = last_frame.size();
660                         stream_mux->add_packet(pkt, qf.output_pts, qf.output_pts);
661                 } else {
662                         assert(false);
663                 }
664                 if (qf.display_func != nullptr) {
665                         qf.display_func();
666                 }
667         }
668 }
669
670 int VideoStream::write_packet2_thunk(void *opaque, uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
671 {
672         VideoStream *video_stream = (VideoStream *)opaque;
673         return video_stream->write_packet2(buf, buf_size, type, time);
674 }
675
676 int VideoStream::write_packet2(uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
677 {
678         if (type == AVIO_DATA_MARKER_SYNC_POINT || type == AVIO_DATA_MARKER_BOUNDARY_POINT) {
679                 seen_sync_markers = true;
680         } else if (type == AVIO_DATA_MARKER_UNKNOWN && !seen_sync_markers) {
681                 // We don't know if this is a keyframe or not (the muxer could
682                 // avoid marking it), so we just have to make the best of it.
683                 type = AVIO_DATA_MARKER_SYNC_POINT;
684         }
685
686         if (type == AVIO_DATA_MARKER_HEADER) {
687                 stream_mux_header.append((char *)buf, buf_size);
688                 global_httpd->set_header(stream_mux_header);
689         } else {
690                 global_httpd->add_data((char *)buf, buf_size, type == AVIO_DATA_MARKER_SYNC_POINT, time, AVRational{ AV_TIME_BASE, 1 });
691         }
692         return buf_size;
693 }