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