1 #include "x264_encoder.h"
14 #include "print_latency.h"
16 #include "x264_speed_control.h"
19 #include <libavcodec/avcodec.h>
20 #include <libavformat/avformat.h>
23 using namespace movit;
25 using namespace std::chrono;
29 void update_vbv_settings(x264_param_t *param)
31 if (global_flags.x264_vbv_buffer_size < 0) {
32 param->rc.i_vbv_buffer_size = param->rc.i_bitrate; // One-second VBV.
34 param->rc.i_vbv_buffer_size = global_flags.x264_vbv_buffer_size;
36 if (global_flags.x264_vbv_max_bitrate < 0) {
37 param->rc.i_vbv_max_bitrate = param->rc.i_bitrate; // CBR.
39 param->rc.i_vbv_max_bitrate = global_flags.x264_vbv_max_bitrate;
45 X264Encoder::X264Encoder(AVOutputFormat *oformat)
46 : wants_global_headers(oformat->flags & AVFMT_GLOBALHEADER)
48 frame_pool.reset(new uint8_t[global_flags.width * global_flags.height * 2 * X264_QUEUE_LENGTH]);
49 for (unsigned i = 0; i < X264_QUEUE_LENGTH; ++i) {
50 free_frames.push(frame_pool.get() + i * (global_flags.width * global_flags.height * 2));
52 encoder_thread = thread(&X264Encoder::encoder_thread_func, this);
55 X264Encoder::~X264Encoder()
58 queued_frames_nonempty.notify_all();
59 encoder_thread.join();
62 void X264Encoder::add_frame(int64_t pts, int64_t duration, YCbCrLumaCoefficients ycbcr_coefficients, const uint8_t *data, const ReceivedTimestamps &received_ts)
66 qf.duration = duration;
67 qf.ycbcr_coefficients = ycbcr_coefficients;
68 qf.received_ts = received_ts;
71 lock_guard<mutex> lock(mu);
72 if (free_frames.empty()) {
73 fprintf(stderr, "WARNING: x264 queue full, dropping frame with pts %ld\n", pts);
77 qf.data = free_frames.front();
81 memcpy(qf.data, data, global_flags.width * global_flags.height * 2);
84 lock_guard<mutex> lock(mu);
85 queued_frames.push(qf);
86 queued_frames_nonempty.notify_all();
90 void X264Encoder::init_x264()
93 x264_param_default_preset(¶m, global_flags.x264_preset.c_str(), global_flags.x264_tune.c_str());
95 param.i_width = global_flags.width;
96 param.i_height = global_flags.height;
97 param.i_csp = X264_CSP_NV12;
98 param.b_vfr_input = 1;
99 param.i_timebase_num = 1;
100 param.i_timebase_den = TIMEBASE;
101 param.i_keyint_max = 50; // About one second.
102 if (global_flags.x264_speedcontrol) {
103 param.i_frame_reference = 16; // Because speedcontrol is never allowed to change this above what we set at start.
106 // NOTE: These should be in sync with the ones in quicksync_encoder.cpp (sps_rbsp()).
107 param.vui.i_vidformat = 5; // Unspecified.
108 param.vui.b_fullrange = 0;
109 param.vui.i_colorprim = 1; // BT.709.
110 param.vui.i_transfer = 2; // Unspecified (since we use sRGB).
111 if (global_flags.ycbcr_rec709_coefficients) {
112 param.vui.i_colmatrix = 1; // BT.709.
114 param.vui.i_colmatrix = 6; // BT.601/SMPTE 170M.
117 param.rc.i_rc_method = X264_RC_ABR;
118 param.rc.i_bitrate = global_flags.x264_bitrate;
119 update_vbv_settings(¶m);
120 if (param.rc.i_vbv_max_bitrate > 0) {
121 // If the user wants VBV control to cap the max rate, it is
122 // also reasonable to assume that they are fine with the stream
123 // constantly being around that rate even for very low-complexity
124 // content; the obvious and extreme example being a static
127 // One would think it's fine to have low-complexity content use
128 // less bitrate, but it seems to cause problems in practice;
129 // e.g. VLC seems to often drop the stream (similar to a buffer
130 // underrun) in such cases, but only when streaming from Nageru,
131 // not when reading a dump of the same stream from disk.
132 // I'm not 100% sure whether it's in VLC (possibly some buffering
133 // in the HTTP layer), in microhttpd or somewhere in Nageru itself,
134 // but it's a typical case of problems that can arise. Similarly,
135 // TCP's congestion control is not always fond of the rate staying
136 // low for a while and then rising quickly -- a variation on the same
139 // We solve this by simply asking x264 to fill in dummy bits
140 // in these cases, so that the bitrate stays reasonable constant.
141 // It's a waste of bandwidth, but it makes things go much more
142 // smoothly in these cases. (We don't do it if VBV control is off
143 // in general, not the least because it makes no sense and x264
144 // thus ignores the parameter.)
145 param.rc.b_filler = 1;
148 // Occasionally players have problem with extremely low quantizers;
149 // be on the safe side. Shouldn't affect quality in any meaningful way.
150 param.rc.i_qp_min = 5;
152 for (const string &str : global_flags.x264_extra_param) {
153 const size_t pos = str.find(',');
154 if (pos == string::npos) {
155 if (x264_param_parse(¶m, str.c_str(), nullptr) != 0) {
156 fprintf(stderr, "ERROR: x264 rejected parameter '%s'\n", str.c_str());
159 const string key = str.substr(0, pos);
160 const string value = str.substr(pos + 1);
161 if (x264_param_parse(¶m, key.c_str(), value.c_str()) != 0) {
162 fprintf(stderr, "ERROR: x264 rejected parameter '%s' set to '%s'\n",
163 key.c_str(), value.c_str());
168 x264_param_apply_profile(¶m, "high");
170 param.b_repeat_headers = !wants_global_headers;
172 x264 = x264_encoder_open(¶m);
173 if (x264 == nullptr) {
174 fprintf(stderr, "ERROR: x264 initialization failed.\n");
178 if (global_flags.x264_speedcontrol) {
179 speed_control.reset(new X264SpeedControl(x264, /*f_speed=*/1.0f, X264_QUEUE_LENGTH, /*f_buffer_init=*/1.0f));
182 if (wants_global_headers) {
186 x264_encoder_headers(x264, &nal, &num_nal);
188 for (int i = 0; i < num_nal; ++i) {
189 if (nal[i].i_type == NAL_SEI) {
190 // Don't put the SEI in extradata; make it part of the first frame instead.
191 buffered_sei += string((const char *)nal[i].p_payload, nal[i].i_payload);
193 global_headers += string((const char *)nal[i].p_payload, nal[i].i_payload);
199 void X264Encoder::encoder_thread_func()
201 if (nice(5) == -1) { // Note that x264 further nices some of its threads.
203 // No exit; it's not fatal.
206 x264_init_done = true;
213 // Wait for a queued frame, then dequeue it.
215 unique_lock<mutex> lock(mu);
216 queued_frames_nonempty.wait(lock, [this]() { return !queued_frames.empty() || should_quit; });
217 if (!queued_frames.empty()) {
218 qf = queued_frames.front();
226 frames_left = !queued_frames.empty();
232 lock_guard<mutex> lock(mu);
233 free_frames.push(qf.data);
236 // We should quit only if the should_quit flag is set _and_ we have nothing
238 } while (!should_quit || frames_left || x264_encoder_delayed_frames(x264) > 0);
240 x264_encoder_close(x264);
243 void X264Encoder::encode_frame(X264Encoder::QueuedFrame qf)
245 x264_nal_t *nal = nullptr;
248 x264_picture_t *input_pic = nullptr;
251 x264_picture_init(&pic);
254 pic.img.i_csp = X264_CSP_NV12;
256 pic.img.plane[0] = qf.data;
257 pic.img.i_stride[0] = global_flags.width;
258 pic.img.plane[1] = qf.data + global_flags.width * global_flags.height;
259 pic.img.i_stride[1] = global_flags.width / 2 * sizeof(uint16_t);
260 pic.opaque = reinterpret_cast<void *>(intptr_t(qf.duration));
264 frames_being_encoded[qf.pts] = qf.received_ts;
267 // See if we have a new bitrate to change to.
268 unsigned new_rate = new_bitrate_kbit.exchange(0); // Read and clear.
270 bitrate_override_func = [new_rate](x264_param_t *param) {
271 param->rc.i_bitrate = new_rate;
272 update_vbv_settings(param);
276 auto ycbcr_coefficients_override_func = [qf](x264_param_t *param) {
277 if (qf.ycbcr_coefficients == YCBCR_REC_709) {
278 param->vui.i_colmatrix = 1; // BT.709.
280 assert(qf.ycbcr_coefficients == YCBCR_REC_601);
281 param->vui.i_colmatrix = 6; // BT.601/SMPTE 170M.
286 speed_control->set_config_override_function([this, ycbcr_coefficients_override_func](x264_param_t *param) {
287 if (bitrate_override_func) {
288 bitrate_override_func(param);
290 ycbcr_coefficients_override_func(param);
294 x264_encoder_parameters(x264, ¶m);
295 if (bitrate_override_func) {
296 bitrate_override_func(¶m);
298 ycbcr_coefficients_override_func(¶m);
299 x264_encoder_reconfig(x264, ¶m);
303 speed_control->before_frame(float(free_frames.size()) / X264_QUEUE_LENGTH, X264_QUEUE_LENGTH, 1e6 * qf.duration / TIMEBASE);
305 x264_encoder_encode(x264, &nal, &num_nal, input_pic, &pic);
307 speed_control->after_frame();
310 if (num_nal == 0) return;
312 if (frames_being_encoded.count(pic.i_pts)) {
313 ReceivedTimestamps received_ts = frames_being_encoded[pic.i_pts];
314 frames_being_encoded.erase(pic.i_pts);
316 static int frameno = 0;
317 print_latency("Current x264 latency (video inputs → network mux):",
318 received_ts, (pic.i_type == X264_TYPE_B || pic.i_type == X264_TYPE_BREF),
324 // We really need one AVPacket for the entire frame, it seems,
325 // so combine it all.
326 size_t num_bytes = buffered_sei.size();
327 for (int i = 0; i < num_nal; ++i) {
328 num_bytes += nal[i].i_payload;
331 unique_ptr<uint8_t[]> data(new uint8_t[num_bytes]);
332 uint8_t *ptr = data.get();
334 if (!buffered_sei.empty()) {
335 memcpy(ptr, buffered_sei.data(), buffered_sei.size());
336 ptr += buffered_sei.size();
337 buffered_sei.clear();
339 for (int i = 0; i < num_nal; ++i) {
340 memcpy(ptr, nal[i].p_payload, nal[i].i_payload);
341 ptr += nal[i].i_payload;
345 memset(&pkt, 0, sizeof(pkt));
347 pkt.data = data.get();
348 pkt.size = num_bytes;
349 pkt.stream_index = 0;
350 if (pic.b_keyframe) {
351 pkt.flags = AV_PKT_FLAG_KEY;
355 pkt.duration = reinterpret_cast<intptr_t>(pic.opaque);
357 mux->add_packet(pkt, pic.i_pts, pic.i_dts);