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