1 #include "video_encoder.h"
11 #include <libavutil/mem.h>
14 #include "audio_encoder.h"
16 #include "shared/ffmpeg_raii.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"
24 class RefCountedFrame;
27 using namespace movit;
31 string generate_local_dump_filename(int frame)
33 time_t now = time(NULL);
35 localtime_r(&now, &now_tm);
38 strftime(timestamp, sizeof(timestamp), "%F-%H%M%S%z", &now_tm);
40 // Use the frame number to disambiguate between two cuts starting
41 // on the same second.
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);
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)
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));
59 stream_audio_encoder.reset(new AudioEncoder(global_flags.stream_audio_codec_name, global_flags.stream_audio_codec_bitrate, oformat));
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));
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();
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));
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());
82 VideoEncoder::~VideoEncoder()
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) {
94 void VideoEncoder::do_cut(int frame)
96 string filename = generate_local_dump_filename(frame);
97 printf("Starting new recording: %s\n", filename.c_str());
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.
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();
114 if (global_flags.x264_separate_disk_encode) {
115 old_x264_disk_encoder = x264_disk_encoder.release();
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();
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);
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());
136 if (overriding_bitrate != 0) {
137 x264_encoder->change_bitrate(overriding_bitrate);
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();
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());
151 void VideoEncoder::change_x264_bitrate(unsigned rate_kbit)
153 overriding_bitrate = rate_kbit;
154 x264_encoder->change_bitrate(rate_kbit);
157 void VideoEncoder::add_audio(int64_t pts, std::vector<float> audio)
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().
163 lock_guard<mutex> lock(qs_audio_mu);
164 quicksync_encoder->add_audio(pts, audio);
166 stream_audio_encoder->encode_audio(audio, pts + quicksync_encoder->global_delay());
169 bool VideoEncoder::is_zerocopy() const
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();
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)
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);
185 RefCountedGLsync VideoEncoder::end_frame()
187 lock_guard<mutex> lock(qs_mu);
188 return quicksync_encoder->end_frame();
191 void VideoEncoder::open_output_stream()
193 AVFormatContext *avctx = avformat_alloc_context();
194 avctx->oformat = const_cast<decltype(avctx->oformat)>(oformat); // const_cast is a hack to work in FFmpeg both before and after 5.0.
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;
201 Mux::Codec video_codec;
202 if (global_flags.uncompressed_video_to_http) {
203 video_codec = Mux::CODEC_NV12;
205 video_codec = Mux::CODEC_H264;
208 avctx->flags = AVFMT_FLAG_CUSTOM_IO;
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();
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" }});
221 int VideoEncoder::write_packet2_thunk(void *opaque, uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
223 VideoEncoder *video_encoder = (VideoEncoder *)opaque;
224 return video_encoder->write_packet2(buf, buf_size, type, time);
227 int VideoEncoder::write_packet2(uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
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;
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);
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 });