]> git.sesse.net Git - nageru/blob - video_stream.cpp
Move Y'CbCr conversion into a common utility class.
[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
154         GLuint input_tex[num_interpolate_slots], gray_tex[num_interpolate_slots];
155         GLuint cb_tex[num_interpolate_slots], cr_tex[num_interpolate_slots];
156
157         glCreateTextures(GL_TEXTURE_2D_ARRAY, 10, input_tex);
158         glCreateTextures(GL_TEXTURE_2D_ARRAY, 10, gray_tex);
159         glCreateTextures(GL_TEXTURE_2D, 10, cb_tex);
160         glCreateTextures(GL_TEXTURE_2D, 10, cr_tex);
161         check_error();
162         constexpr size_t width = 1280, height = 720;  // FIXME: adjustable width, height
163         int levels = find_num_levels(width, height);
164         for (size_t i = 0; i < num_interpolate_slots; ++i) {
165                 glTextureStorage3D(input_tex[i], levels, GL_RGBA8, width, height, 2);
166                 check_error();
167                 glTextureStorage3D(gray_tex[i], levels, GL_R8, width, height, 2);
168                 check_error();
169                 glTextureStorage2D(cb_tex[i], 1, GL_R8, width / 2, height);
170                 check_error();
171                 glTextureStorage2D(cr_tex[i], 1, GL_R8, width / 2, height);
172                 check_error();
173
174                 InterpolatedFrameResources resource;
175                 resource.input_tex = input_tex[i];
176                 resource.gray_tex = gray_tex[i];
177                 resource.cb_tex = cb_tex[i];
178                 resource.cr_tex = cr_tex[i];
179                 glCreateFramebuffers(2, resource.input_fbos);
180                 check_error();
181
182                 glNamedFramebufferTextureLayer(resource.input_fbos[0], GL_COLOR_ATTACHMENT0, input_tex[i], 0, 0);
183                 check_error();
184                 glNamedFramebufferTextureLayer(resource.input_fbos[0], GL_COLOR_ATTACHMENT1, gray_tex[i], 0, 0);
185                 check_error();
186                 glNamedFramebufferTextureLayer(resource.input_fbos[1], GL_COLOR_ATTACHMENT0, input_tex[i], 0, 1);
187                 check_error();
188                 glNamedFramebufferTextureLayer(resource.input_fbos[1], GL_COLOR_ATTACHMENT1, gray_tex[i], 0, 1);
189                 check_error();
190
191                 GLuint bufs[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
192                 glNamedFramebufferDrawBuffers(resource.input_fbos[0], 2, bufs);
193                 check_error();
194                 glNamedFramebufferDrawBuffers(resource.input_fbos[1], 2, bufs);
195                 check_error();
196
197                 glCreateBuffers(1, &resource.pbo);
198                 check_error();
199                 glNamedBufferStorage(resource.pbo, width * height * 4, nullptr, GL_MAP_READ_BIT | GL_MAP_PERSISTENT_BIT);
200                 check_error();
201                 resource.pbo_contents = glMapNamedBufferRange(resource.pbo, 0, width * height * 4, GL_MAP_READ_BIT | GL_MAP_PERSISTENT_BIT); 
202                 interpolate_resources.push_back(resource);
203         }
204
205         check_error();
206
207         compute_flow.reset(new DISComputeFlow(width, height, operating_point2));
208         interpolate.reset(new Interpolate(operating_point2, /*split_ycbcr_output=*/true));
209         chroma_subsampler.reset(new ChromaSubsampler);
210         check_error();
211 }
212
213 VideoStream::~VideoStream() {}
214
215 void VideoStream::start()
216 {
217         AVFormatContext *avctx = avformat_alloc_context();
218         avctx->oformat = av_guess_format("nut", nullptr, nullptr);
219
220         uint8_t *buf = (uint8_t *)av_malloc(MUX_BUFFER_SIZE);
221         avctx->pb = avio_alloc_context(buf, MUX_BUFFER_SIZE, 1, this, nullptr, nullptr, nullptr);
222         avctx->pb->write_data_type = &VideoStream::write_packet2_thunk;
223         avctx->pb->ignore_boundary_point = 1;
224
225         Mux::Codec video_codec = Mux::CODEC_MJPEG;
226
227         avctx->flags = AVFMT_FLAG_CUSTOM_IO;
228
229         string video_extradata;
230
231         constexpr int width = 1280, height = 720;  // Doesn't matter for MJPEG.
232         stream_mux.reset(new Mux(avctx, width, height, video_codec, video_extradata, /*audio_codec_parameters=*/nullptr, COARSE_TIMEBASE,
233                 /*write_callback=*/nullptr, Mux::WRITE_FOREGROUND, {}));
234
235
236         encode_thread = thread(&VideoStream::encode_thread_func, this);
237 }
238
239 void VideoStream::stop()
240 {
241         encode_thread.join();
242 }
243
244 void VideoStream::schedule_original_frame(int64_t output_pts, unsigned stream_idx, int64_t input_pts)
245 {
246         fprintf(stderr, "output_pts=%ld  original      input_pts=%ld\n", output_pts, input_pts);
247
248         QueuedFrame qf;
249         qf.type = QueuedFrame::ORIGINAL;
250         qf.output_pts = output_pts;
251         qf.stream_idx = stream_idx;
252         qf.input_first_pts = input_pts; 
253
254         unique_lock<mutex> lock(queue_lock);
255         frame_queue.push_back(qf);
256         queue_nonempty.notify_all();
257 }
258
259 void VideoStream::schedule_interpolated_frame(int64_t output_pts, unsigned stream_idx, int64_t input_first_pts, int64_t input_second_pts, float alpha)
260 {
261         fprintf(stderr, "output_pts=%ld  interpolated  input_pts1=%ld input_pts2=%ld alpha=%.3f\n", output_pts, input_first_pts, input_second_pts, alpha);
262
263         // Get the temporary OpenGL resources we need for doing the interpolation.
264         InterpolatedFrameResources resources;
265         {
266                 unique_lock<mutex> lock(queue_lock);
267                 if (interpolate_resources.empty()) {
268                         fprintf(stderr, "WARNING: Too many interpolated frames already in transit; dropping one.\n");
269                         JPEGFrameView::insert_interpolated_frame(stream_idx, output_pts, nullptr);
270                         return;
271                 }
272                 resources = interpolate_resources.front();
273                 interpolate_resources.pop_front();
274         }
275
276         QueuedFrame qf;
277         qf.type = QueuedFrame::INTERPOLATED;
278         qf.output_pts = output_pts;
279         qf.stream_idx = stream_idx;
280         qf.resources = resources;
281
282         check_error();
283
284         // Convert frame0 and frame1 to OpenGL textures.
285         for (size_t frame_no = 0; frame_no < 2; ++frame_no) {
286                 JPEGID jpeg_id;
287                 jpeg_id.stream_idx = stream_idx;
288                 jpeg_id.pts = frame_no == 1 ? input_second_pts : input_first_pts;
289                 jpeg_id.interpolated = false;
290                 bool did_decode;
291                 shared_ptr<Frame> frame = decode_jpeg_with_cache(jpeg_id, DECODE_IF_NOT_IN_CACHE, &did_decode);
292                 ycbcr_converter->prepare_chain_for_conversion(frame)->render_to_fbo(resources.input_fbos[frame_no], 1280, 720);
293         }
294
295         glGenerateTextureMipmap(resources.input_tex);
296         check_error();
297         glGenerateTextureMipmap(resources.gray_tex);
298         check_error();
299
300         // Compute the interpolated frame.
301         qf.flow_tex = compute_flow->exec(resources.gray_tex, DISComputeFlow::FORWARD_AND_BACKWARD, DISComputeFlow::DO_NOT_RESIZE_FLOW);
302         check_error();
303         tie(qf.output_tex, qf.cbcr_tex) = interpolate->exec(resources.input_tex, resources.gray_tex, qf.flow_tex, 1280, 720, alpha);
304         check_error();
305
306         // Subsample and split Cb/Cr.
307         chroma_subsampler->subsample_chroma(qf.cbcr_tex, 1280, 720, resources.cb_tex, resources.cr_tex);
308
309         // We could have released qf.flow_tex here, but to make sure we don't cause a stall
310         // when trying to reuse it for the next frame, we can just as well hold on to it
311         // and release it only when the readback is done.
312
313         // Read it down (asynchronously) to the CPU.
314         glPixelStorei(GL_PACK_ROW_LENGTH, 0);
315         glBindBuffer(GL_PIXEL_PACK_BUFFER, resources.pbo);
316         check_error();
317         glGetTextureImage(qf.output_tex, 0, GL_RED, GL_UNSIGNED_BYTE, 1280 * 720 * 4, BUFFER_OFFSET(0));
318         check_error();
319         glGetTextureImage(resources.cb_tex, 0, GL_RED, GL_UNSIGNED_BYTE, 1280 * 720 * 3, BUFFER_OFFSET(1280 * 720));
320         check_error();
321         glGetTextureImage(resources.cr_tex, 0, GL_RED, GL_UNSIGNED_BYTE, 1280 * 720 * 3 - 640 * 720, BUFFER_OFFSET(1280 * 720 + 640 * 720));
322         check_error();
323         glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
324
325         // Set a fence we can wait for to make sure the CPU sees the read.
326         glMemoryBarrier(GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT);
327         check_error();
328         qf.fence = RefCountedGLsync(GL_SYNC_GPU_COMMANDS_COMPLETE, /*flags=*/0);
329         check_error();
330
331         unique_lock<mutex> lock(queue_lock);
332         frame_queue.push_back(qf);
333         queue_nonempty.notify_all();
334 }
335
336 namespace {
337
338 shared_ptr<Frame> frame_from_pbo(void *contents, size_t width, size_t height)
339 {
340         size_t chroma_width = width / 2;
341
342         const uint8_t *y = (const uint8_t *)contents;
343         const uint8_t *cb = (const uint8_t *)contents + width * height;
344         const uint8_t *cr = (const uint8_t *)contents + width * height + chroma_width * height;
345
346         shared_ptr<Frame> frame(new Frame);
347         frame->y.reset(new uint8_t[width * height]);
348         frame->cb.reset(new uint8_t[chroma_width * height]);
349         frame->cr.reset(new uint8_t[chroma_width * height]);
350         for (unsigned yy = 0; yy < height; ++yy) {
351                 memcpy(frame->y.get() + width * yy, y + width * yy, width);
352                 memcpy(frame->cb.get() + chroma_width * yy, cb + chroma_width * yy, chroma_width);
353                 memcpy(frame->cr.get() + chroma_width * yy, cr + chroma_width * yy, chroma_width);
354         }
355         frame->is_semiplanar = false;
356         frame->width = width;
357         frame->height = height;
358         frame->chroma_subsampling_x = 2;
359         frame->chroma_subsampling_y = 1;
360         frame->pitch_y = width;
361         frame->pitch_chroma = chroma_width;
362         return frame;
363 }
364
365 }  // namespace
366
367 void VideoStream::encode_thread_func()
368 {
369         pthread_setname_np(pthread_self(), "VideoStream");
370         QSurface *surface = create_surface();
371         QOpenGLContext *context = create_context(surface);
372         bool ok = make_current(context, surface);
373         if (!ok) {
374                 fprintf(stderr, "Video stream couldn't get an OpenGL context\n");
375                 exit(1);
376         }
377
378         for ( ;; ) {
379                 QueuedFrame qf;
380                 {
381                         unique_lock<mutex> lock(queue_lock);
382                         queue_nonempty.wait(lock, [this]{
383                                 return !frame_queue.empty();
384                         });
385                         qf = frame_queue.front();
386                         frame_queue.pop_front();
387                 }
388
389                 if (qf.type == QueuedFrame::ORIGINAL) {
390                         // Send the JPEG frame on, unchanged.
391                         string jpeg = read_file(filename_for_frame(qf.stream_idx, qf.input_first_pts));
392                         AVPacket pkt;
393                         av_init_packet(&pkt);
394                         pkt.stream_index = 0;
395                         pkt.data = (uint8_t *)jpeg.data();
396                         pkt.size = jpeg.size();
397                         stream_mux->add_packet(pkt, qf.output_pts, qf.output_pts);
398                 } else if (qf.type == QueuedFrame::INTERPOLATED) {
399                         glClientWaitSync(qf.fence.get(), /*flags=*/0, GL_TIMEOUT_IGNORED);
400
401
402                         // Send a copy of the frame on to display.
403                         shared_ptr<Frame> frame = frame_from_pbo(qf.resources.pbo_contents, 1280, 720);
404                         JPEGFrameView::insert_interpolated_frame(qf.stream_idx, qf.output_pts, frame);
405
406                         // Now JPEG encode it, and send it on to the stream.
407                         vector<uint8_t> jpeg = encode_jpeg(frame->y.get(), frame->cb.get(), frame->cr.get(), 1280, 720);
408                         compute_flow->release_texture(qf.flow_tex);
409                         interpolate->release_texture(qf.output_tex);
410                         interpolate->release_texture(qf.cbcr_tex);
411
412                         AVPacket pkt;
413                         av_init_packet(&pkt);
414                         pkt.stream_index = 0;
415                         pkt.data = (uint8_t *)jpeg.data();
416                         pkt.size = jpeg.size();
417                         stream_mux->add_packet(pkt, qf.output_pts, qf.output_pts);
418
419                         // Put the frame resources back.
420                         unique_lock<mutex> lock(queue_lock);
421                         interpolate_resources.push_back(qf.resources);
422                 }
423         }
424 }
425
426 int VideoStream::write_packet2_thunk(void *opaque, uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
427 {
428         VideoStream *video_stream = (VideoStream *)opaque;
429         return video_stream->write_packet2(buf, buf_size, type, time);
430 }
431
432 int VideoStream::write_packet2(uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
433 {
434         if (type == AVIO_DATA_MARKER_SYNC_POINT || type == AVIO_DATA_MARKER_BOUNDARY_POINT) {
435                 seen_sync_markers = true;
436         } else if (type == AVIO_DATA_MARKER_UNKNOWN && !seen_sync_markers) {
437                 // We don't know if this is a keyframe or not (the muxer could
438                 // avoid marking it), so we just have to make the best of it.
439                 type = AVIO_DATA_MARKER_SYNC_POINT;
440         }
441
442         if (type == AVIO_DATA_MARKER_HEADER) {
443                 stream_mux_header.append((char *)buf, buf_size);
444                 global_httpd->set_header(stream_mux_header);
445         } else {
446                 global_httpd->add_data((char *)buf, buf_size, type == AVIO_DATA_MARKER_SYNC_POINT, time, AVRational{ AV_TIME_BASE, 1 });
447         }
448         return buf_size;
449 }
450