]> git.sesse.net Git - nageru/blob - nageru/video_encoder.cpp
Remove the --http-uncompressed-video flag.
[nageru] / nageru / video_encoder.cpp
1 #include "video_encoder.h"
2
3 #include <assert.h>
4 #include <stdio.h>
5 #include <time.h>
6 #include <unistd.h>
7 #include <string>
8 #include <thread>
9
10 extern "C" {
11 #include <libavutil/mem.h>
12 }
13
14 #include "audio_encoder.h"
15 #ifdef HAVE_AV1
16 #include "av1_encoder.h"
17 #endif
18 #include "defs.h"
19 #include "shared/ffmpeg_raii.h"
20 #include "flags.h"
21 #include "shared/httpd.h"
22 #include "shared/mux.h"
23 #include "quicksync_encoder.h"
24 #include "shared/timebase.h"
25 #include "x264_encoder.h"
26
27 class RefCountedFrame;
28
29 using namespace std;
30 using namespace movit;
31
32 namespace {
33
34 string generate_local_dump_filename(int frame)
35 {
36         time_t now = time(NULL);
37         tm now_tm;
38         localtime_r(&now, &now_tm);
39
40         char timestamp[64];
41         strftime(timestamp, sizeof(timestamp), "%F-%H%M%S%z", &now_tm);
42
43         // Use the frame number to disambiguate between two cuts starting
44         // on the same second.
45         char filename[256];
46         snprintf(filename, sizeof(filename), "%s/%s%s-f%02d%s",
47                 global_flags.recording_dir.c_str(),
48                 LOCAL_DUMP_PREFIX, timestamp, frame % 100, LOCAL_DUMP_SUFFIX);
49         return filename;
50 }
51
52 }  // namespace
53
54 VideoEncoder::VideoEncoder(ResourcePool *resource_pool, QSurface *surface, const std::string &va_display, int width, int height, HTTPD *httpd, DiskSpaceEstimator *disk_space_estimator)
55         : resource_pool(resource_pool), surface(surface), va_display(va_display), width(width), height(height), httpd(httpd), disk_space_estimator(disk_space_estimator)
56 {
57         oformat = av_guess_format(global_flags.stream_mux_name.c_str(), nullptr, nullptr);
58         assert(oformat != nullptr);
59         if (global_flags.stream_audio_codec_name.empty()) {
60                 stream_audio_encoder.reset(new AudioEncoder(AUDIO_OUTPUT_CODEC_NAME, DEFAULT_AUDIO_OUTPUT_BIT_RATE, oformat));
61         } else {
62                 stream_audio_encoder.reset(new AudioEncoder(global_flags.stream_audio_codec_name, global_flags.stream_audio_codec_bitrate, oformat));
63         }
64         if (global_flags.x264_video_to_http || global_flags.x264_video_to_disk) {
65                 x264_encoder.reset(new X264Encoder(oformat, /*use_separate_disk_params=*/false));
66         }
67         VideoCodecInterface *http_encoder = x264_encoder.get();
68         VideoCodecInterface *disk_encoder = x264_encoder.get();
69 #ifdef HAVE_AV1
70         if (global_flags.av1_video_to_http) {
71                 av1_encoder.reset(new AV1Encoder(oformat));
72                 http_encoder = av1_encoder.get();
73         }
74 #endif
75         if (global_flags.x264_separate_disk_encode) {
76                 x264_disk_encoder.reset(new X264Encoder(oformat, /*use_separate_disk_params=*/true));
77                 disk_encoder = x264_disk_encoder.get();
78         }
79
80         string filename = generate_local_dump_filename(/*frame=*/0);
81         quicksync_encoder.reset(new QuickSyncEncoder(filename, resource_pool, surface, va_display, width, height, oformat, http_encoder, disk_encoder, disk_space_estimator));
82
83         open_output_stream();
84         stream_audio_encoder->add_mux(stream_mux.get());
85         quicksync_encoder->set_stream_mux(stream_mux.get());
86         if (global_flags.x264_video_to_http) {
87                 x264_encoder->add_mux(stream_mux.get());
88         }
89 #ifdef HAVE_AV1
90         if (global_flags.av1_video_to_http) {
91                 av1_encoder->add_mux(stream_mux.get());
92         }
93 #endif
94 }
95
96 VideoEncoder::~VideoEncoder()
97 {
98         quicksync_encoder->shutdown();
99         x264_encoder.reset(nullptr);
100         x264_disk_encoder.reset(nullptr);
101         quicksync_encoder->close_file();
102         quicksync_encoder.reset(nullptr);
103         while (quicksync_encoders_in_shutdown.load() > 0) {
104                 usleep(10000);
105         }
106 }
107
108 void VideoEncoder::do_cut(int frame)
109 {
110         string filename = generate_local_dump_filename(frame);
111         printf("Starting new recording: %s\n", filename.c_str());
112
113         // Do the shutdown of the old encoder in a separate thread, since it can
114         // take some time (it needs to wait for all the frames in the queue to be
115         // done encoding, for one) and we are running on the main mixer thread.
116         // However, since this means both encoders could be sending packets at
117         // the same time, it means pts could come out of order to the stream mux,
118         // and we need to plug it until the shutdown is complete.
119         stream_mux->plug();
120         lock(qs_mu, qs_audio_mu);
121         lock_guard<mutex> lock1(qs_mu, adopt_lock), lock2(qs_audio_mu, adopt_lock);
122         QuickSyncEncoder *old_encoder = quicksync_encoder.release();  // When we go C++14, we can use move capture instead.
123         X264Encoder *old_x264_encoder = nullptr;
124         X264Encoder *old_x264_disk_encoder = nullptr;
125         if (global_flags.x264_video_to_disk) {
126                 old_x264_encoder = x264_encoder.release();
127         }
128         if (global_flags.x264_separate_disk_encode) {
129                 old_x264_disk_encoder = x264_disk_encoder.release();
130         }
131         thread([old_encoder, old_x264_encoder, old_x264_disk_encoder, this]{
132                 old_encoder->shutdown();
133                 delete old_x264_encoder;
134                 delete old_x264_disk_encoder;
135                 old_encoder->close_file();
136                 stream_mux->unplug();
137
138                 // We cannot delete the encoder here, as this thread has no OpenGL context.
139                 // We'll deal with it in begin_frame().
140                 lock_guard<mutex> lock(qs_mu);
141                 qs_needing_cleanup.emplace_back(old_encoder);
142         }).detach();
143
144         if (global_flags.x264_video_to_disk) {
145                 x264_encoder.reset(new X264Encoder(oformat, /*use_separate_disk_params=*/false));
146                 assert(global_flags.x264_video_to_http);
147                 if (global_flags.x264_video_to_http) {
148                         x264_encoder->add_mux(stream_mux.get());
149                 }
150                 if (overriding_bitrate != 0) {
151                         x264_encoder->change_bitrate(overriding_bitrate);
152                 }
153         }
154         X264Encoder *http_encoder = x264_encoder.get();
155         X264Encoder *disk_encoder = x264_encoder.get();
156         if (global_flags.x264_separate_disk_encode) {
157                 x264_disk_encoder.reset(new X264Encoder(oformat, /*use_separate_disk_params=*/true));
158                 disk_encoder = x264_disk_encoder.get();
159         }
160
161         quicksync_encoder.reset(new QuickSyncEncoder(filename, resource_pool, surface, va_display, width, height, oformat, http_encoder, disk_encoder, disk_space_estimator));
162         quicksync_encoder->set_stream_mux(stream_mux.get());
163 }
164
165 void VideoEncoder::change_x264_bitrate(unsigned rate_kbit)
166 {
167         overriding_bitrate = rate_kbit;
168         x264_encoder->change_bitrate(rate_kbit);
169 }
170
171 void VideoEncoder::add_audio(int64_t pts, std::vector<float> audio)
172 {
173         // Take only qs_audio_mu, since add_audio() is thread safe
174         // (we can only conflict with do_cut(), which takes qs_audio_mu)
175         // and we don't want to contend with begin_frame().
176         {
177                 lock_guard<mutex> lock(qs_audio_mu);
178                 quicksync_encoder->add_audio(pts, audio);
179         }
180         stream_audio_encoder->encode_audio(audio, pts + quicksync_encoder->global_delay());
181 }
182
183 bool VideoEncoder::is_zerocopy() const
184 {
185         // Explicitly do _not_ take qs_mu; this is called from the mixer,
186         // and qs_mu might be contended. is_zerocopy() is thread safe
187         // and never called in parallel with do_cut() (both happen only
188         // from the mixer thread).
189         return quicksync_encoder->is_zerocopy();
190 }
191
192 bool VideoEncoder::begin_frame(int64_t pts, int64_t duration, movit::YCbCrLumaCoefficients ycbcr_coefficients, const std::vector<RefCountedFrame> &input_frames, GLuint *y_tex, GLuint *cbcr_tex)
193 {
194         lock_guard<mutex> lock(qs_mu);
195         qs_needing_cleanup.clear();  // Since we have an OpenGL context here, and are called regularly.
196         return quicksync_encoder->begin_frame(pts, duration, ycbcr_coefficients, input_frames, y_tex, cbcr_tex);
197 }
198
199 RefCountedGLsync VideoEncoder::end_frame()
200 {
201         lock_guard<mutex> lock(qs_mu);
202         return quicksync_encoder->end_frame();
203 }
204
205 void VideoEncoder::open_output_stream()
206 {
207         AVFormatContext *avctx = avformat_alloc_context();
208         avctx->oformat = const_cast<decltype(avctx->oformat)>(oformat);  // const_cast is a hack to work in FFmpeg both before and after 5.0.
209
210         uint8_t *buf = (uint8_t *)av_malloc(MUX_BUFFER_SIZE);
211         avctx->pb = avio_alloc_context(buf, MUX_BUFFER_SIZE, 1, this, nullptr, nullptr, nullptr);
212         avctx->pb->write_data_type = &VideoEncoder::write_packet2_thunk;
213         avctx->pb->ignore_boundary_point = 1;
214
215         Mux::Codec video_codec;
216         if (global_flags.av1_video_to_http) {
217                 video_codec = Mux::CODEC_AV1;
218         } else {
219                 video_codec = Mux::CODEC_H264;
220         }
221
222         avctx->flags = AVFMT_FLAG_CUSTOM_IO;
223
224         string video_extradata;
225         if (global_flags.x264_video_to_http) {
226                 video_extradata = x264_encoder->get_global_headers();
227 #ifdef HAVE_AV1
228         } else if (global_flags.av1_video_to_http) {
229                 video_extradata = av1_encoder->get_global_headers();
230 #endif
231         }
232
233         stream_mux.reset(new Mux(avctx, width, height, video_codec, video_extradata, stream_audio_encoder->get_codec_parameters().get(),
234                 get_color_space(global_flags.ycbcr_rec709_coefficients), COARSE_TIMEBASE,
235                 /*write_callback=*/nullptr, Mux::WRITE_FOREGROUND, { &stream_mux_metrics }));
236         stream_mux_metrics.init({{ "destination", "http" }});
237 }
238
239 int VideoEncoder::write_packet2_thunk(void *opaque, uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
240 {
241         VideoEncoder *video_encoder = (VideoEncoder *)opaque;
242         return video_encoder->write_packet2(buf, buf_size, type, time);
243 }
244
245 int VideoEncoder::write_packet2(uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
246 {
247         if (type == AVIO_DATA_MARKER_SYNC_POINT || type == AVIO_DATA_MARKER_BOUNDARY_POINT) {
248                 seen_sync_markers = true;
249         } else if (type == AVIO_DATA_MARKER_UNKNOWN && !seen_sync_markers) {
250                 // We don't know if this is a keyframe or not (the muxer could
251                 // avoid marking it), so we just have to make the best of it.
252                 type = AVIO_DATA_MARKER_SYNC_POINT;
253         }
254
255         if (type == AVIO_DATA_MARKER_HEADER) {
256                 stream_mux_header.append((char *)buf, buf_size);
257                 httpd->set_header(HTTPD::StreamID{ HTTPD::MAIN_STREAM, 0 }, stream_mux_header);
258         } else {
259                 httpd->add_data(HTTPD::StreamID{ HTTPD::MAIN_STREAM, 0 }, (char *)buf, buf_size, type == AVIO_DATA_MARKER_SYNC_POINT, time, AVRational{ AV_TIME_BASE, 1 });
260         }
261         return buf_size;
262 }
263