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