1 #include "x264_encoder.h"
16 #include "print_latency.h"
18 #include "x264_dynamic.h"
19 #include "x264_speed_control.h"
22 #include <libavcodec/avcodec.h>
23 #include <libavformat/avformat.h>
26 using namespace movit;
28 using namespace std::chrono;
32 void update_vbv_settings(x264_param_t *param)
34 if (global_flags.x264_bitrate == -1) {
37 if (global_flags.x264_vbv_buffer_size < 0) {
38 param->rc.i_vbv_buffer_size = param->rc.i_bitrate; // One-second VBV.
40 param->rc.i_vbv_buffer_size = global_flags.x264_vbv_buffer_size;
42 if (global_flags.x264_vbv_max_bitrate < 0) {
43 param->rc.i_vbv_max_bitrate = param->rc.i_bitrate; // CBR.
45 param->rc.i_vbv_max_bitrate = global_flags.x264_vbv_max_bitrate;
51 X264Encoder::X264Encoder(AVOutputFormat *oformat)
52 : wants_global_headers(oformat->flags & AVFMT_GLOBALHEADER),
53 dyn(load_x264_for_bit_depth(global_flags.x264_bit_depth))
55 size_t bytes_per_pixel = global_flags.x264_bit_depth > 8 ? 2 : 1;
56 frame_pool.reset(new uint8_t[global_flags.width * global_flags.height * 2 * bytes_per_pixel * X264_QUEUE_LENGTH]);
57 for (unsigned i = 0; i < X264_QUEUE_LENGTH; ++i) {
58 free_frames.push(frame_pool.get() + i * (global_flags.width * global_flags.height * 2 * bytes_per_pixel));
60 encoder_thread = thread(&X264Encoder::encoder_thread_func, this);
62 global_metrics.add("x264_queued_frames", &metric_x264_queued_frames, Metrics::TYPE_GAUGE);
63 global_metrics.add("x264_max_queued_frames", &metric_x264_max_queued_frames, Metrics::TYPE_GAUGE);
64 global_metrics.add("x264_dropped_frames", &metric_x264_dropped_frames);
65 global_metrics.add("x264_output_frames", {{ "type", "i" }}, &metric_x264_output_frames_i);
66 global_metrics.add("x264_output_frames", {{ "type", "p" }}, &metric_x264_output_frames_p);
67 global_metrics.add("x264_output_frames", {{ "type", "b" }}, &metric_x264_output_frames_b);
70 X264Encoder::~X264Encoder()
73 queued_frames_nonempty.notify_all();
74 encoder_thread.join();
80 void X264Encoder::add_frame(int64_t pts, int64_t duration, YCbCrLumaCoefficients ycbcr_coefficients, const uint8_t *data, const ReceivedTimestamps &received_ts)
86 qf.duration = duration;
87 qf.ycbcr_coefficients = ycbcr_coefficients;
88 qf.received_ts = received_ts;
91 lock_guard<mutex> lock(mu);
92 if (free_frames.empty()) {
93 fprintf(stderr, "WARNING: x264 queue full, dropping frame with pts %ld\n", pts);
94 ++metric_x264_dropped_frames;
98 qf.data = free_frames.front();
102 size_t bytes_per_pixel = global_flags.x264_bit_depth > 8 ? 2 : 1;
103 memcpy(qf.data, data, global_flags.width * global_flags.height * 2 * bytes_per_pixel);
106 lock_guard<mutex> lock(mu);
107 queued_frames.push(qf);
108 queued_frames_nonempty.notify_all();
109 metric_x264_queued_frames = queued_frames.size();
113 void X264Encoder::init_x264()
116 dyn.x264_param_default_preset(¶m, global_flags.x264_preset.c_str(), global_flags.x264_tune.c_str());
118 param.i_width = global_flags.width;
119 param.i_height = global_flags.height;
120 param.i_csp = X264_CSP_NV12;
121 if (global_flags.x264_bit_depth > 8) {
122 param.i_csp |= X264_CSP_HIGH_DEPTH;
124 param.b_vfr_input = 1;
125 param.i_timebase_num = 1;
126 param.i_timebase_den = TIMEBASE;
127 param.i_keyint_max = 50; // About one second.
128 if (global_flags.x264_speedcontrol) {
129 param.i_frame_reference = 16; // Because speedcontrol is never allowed to change this above what we set at start.
132 // NOTE: These should be in sync with the ones in quicksync_encoder.cpp (sps_rbsp()).
133 param.vui.i_vidformat = 5; // Unspecified.
134 param.vui.b_fullrange = 0;
135 param.vui.i_colorprim = 1; // BT.709.
136 param.vui.i_transfer = 2; // Unspecified (since we use sRGB).
137 if (global_flags.ycbcr_rec709_coefficients) {
138 param.vui.i_colmatrix = 1; // BT.709.
140 param.vui.i_colmatrix = 6; // BT.601/SMPTE 170M.
143 if (!isinf(global_flags.x264_crf)) {
144 param.rc.i_rc_method = X264_RC_CRF;
145 param.rc.f_rf_constant = global_flags.x264_crf;
147 param.rc.i_rc_method = X264_RC_ABR;
148 param.rc.i_bitrate = global_flags.x264_bitrate;
150 update_vbv_settings(¶m);
151 if (param.rc.i_vbv_max_bitrate > 0) {
152 // If the user wants VBV control to cap the max rate, it is
153 // also reasonable to assume that they are fine with the stream
154 // constantly being around that rate even for very low-complexity
155 // content; the obvious and extreme example being a static
158 // One would think it's fine to have low-complexity content use
159 // less bitrate, but it seems to cause problems in practice;
160 // e.g. VLC seems to often drop the stream (similar to a buffer
161 // underrun) in such cases, but only when streaming from Nageru,
162 // not when reading a dump of the same stream from disk.
163 // I'm not 100% sure whether it's in VLC (possibly some buffering
164 // in the HTTP layer), in microhttpd or somewhere in Nageru itself,
165 // but it's a typical case of problems that can arise. Similarly,
166 // TCP's congestion control is not always fond of the rate staying
167 // low for a while and then rising quickly -- a variation on the same
170 // We solve this by simply asking x264 to fill in dummy bits
171 // in these cases, so that the bitrate stays reasonable constant.
172 // It's a waste of bandwidth, but it makes things go much more
173 // smoothly in these cases. (We don't do it if VBV control is off
174 // in general, not the least because it makes no sense and x264
175 // thus ignores the parameter.)
176 param.rc.b_filler = 1;
179 // Occasionally players have problem with extremely low quantizers;
180 // be on the safe side. Shouldn't affect quality in any meaningful way.
181 param.rc.i_qp_min = 5;
183 for (const string &str : global_flags.x264_extra_param) {
184 const size_t pos = str.find(',');
185 if (pos == string::npos) {
186 if (dyn.x264_param_parse(¶m, str.c_str(), nullptr) != 0) {
187 fprintf(stderr, "ERROR: x264 rejected parameter '%s'\n", str.c_str());
190 const string key = str.substr(0, pos);
191 const string value = str.substr(pos + 1);
192 if (dyn.x264_param_parse(¶m, key.c_str(), value.c_str()) != 0) {
193 fprintf(stderr, "ERROR: x264 rejected parameter '%s' set to '%s'\n",
194 key.c_str(), value.c_str());
199 if (global_flags.x264_bit_depth > 8) {
200 dyn.x264_param_apply_profile(¶m, "high10");
202 dyn.x264_param_apply_profile(¶m, "high");
205 param.b_repeat_headers = !wants_global_headers;
207 x264 = dyn.x264_encoder_open(¶m);
208 if (x264 == nullptr) {
209 fprintf(stderr, "ERROR: x264 initialization failed.\n");
213 if (global_flags.x264_speedcontrol) {
214 speed_control.reset(new X264SpeedControl(x264, /*f_speed=*/1.0f, X264_QUEUE_LENGTH, /*f_buffer_init=*/1.0f));
217 if (wants_global_headers) {
221 dyn.x264_encoder_headers(x264, &nal, &num_nal);
223 for (int i = 0; i < num_nal; ++i) {
224 if (nal[i].i_type == NAL_SEI) {
225 // Don't put the SEI in extradata; make it part of the first frame instead.
226 buffered_sei += string((const char *)nal[i].p_payload, nal[i].i_payload);
228 global_headers += string((const char *)nal[i].p_payload, nal[i].i_payload);
234 void X264Encoder::encoder_thread_func()
236 if (nice(5) == -1) { // Note that x264 further nices some of its threads.
238 // No exit; it's not fatal.
240 pthread_setname_np(pthread_self(), "x264_encode");
242 x264_init_done = true;
249 // Wait for a queued frame, then dequeue it.
251 unique_lock<mutex> lock(mu);
252 queued_frames_nonempty.wait(lock, [this]() { return !queued_frames.empty() || should_quit; });
253 if (!queued_frames.empty()) {
254 qf = queued_frames.front();
262 metric_x264_queued_frames = queued_frames.size();
263 frames_left = !queued_frames.empty();
269 lock_guard<mutex> lock(mu);
270 free_frames.push(qf.data);
273 // We should quit only if the should_quit flag is set _and_ we have nothing
275 } while (!should_quit || frames_left || dyn.x264_encoder_delayed_frames(x264) > 0);
277 dyn.x264_encoder_close(x264);
280 void X264Encoder::encode_frame(X264Encoder::QueuedFrame qf)
282 x264_nal_t *nal = nullptr;
285 x264_picture_t *input_pic = nullptr;
288 dyn.x264_picture_init(&pic);
291 if (global_flags.x264_bit_depth > 8) {
292 pic.img.i_csp = X264_CSP_NV12 | X264_CSP_HIGH_DEPTH;
294 pic.img.plane[0] = qf.data;
295 pic.img.i_stride[0] = global_flags.width * sizeof(uint16_t);
296 pic.img.plane[1] = qf.data + global_flags.width * global_flags.height * sizeof(uint16_t);
297 pic.img.i_stride[1] = global_flags.width / 2 * sizeof(uint32_t);
299 pic.img.i_csp = X264_CSP_NV12;
301 pic.img.plane[0] = qf.data;
302 pic.img.i_stride[0] = global_flags.width;
303 pic.img.plane[1] = qf.data + global_flags.width * global_flags.height;
304 pic.img.i_stride[1] = global_flags.width / 2 * sizeof(uint16_t);
306 pic.opaque = reinterpret_cast<void *>(intptr_t(qf.duration));
310 frames_being_encoded[qf.pts] = qf.received_ts;
313 // See if we have a new bitrate to change to.
314 unsigned new_rate = new_bitrate_kbit.exchange(0); // Read and clear.
316 bitrate_override_func = [new_rate](x264_param_t *param) {
317 param->rc.i_bitrate = new_rate;
318 update_vbv_settings(param);
322 auto ycbcr_coefficients_override_func = [qf](x264_param_t *param) {
323 if (qf.ycbcr_coefficients == YCBCR_REC_709) {
324 param->vui.i_colmatrix = 1; // BT.709.
326 assert(qf.ycbcr_coefficients == YCBCR_REC_601);
327 param->vui.i_colmatrix = 6; // BT.601/SMPTE 170M.
332 speed_control->set_config_override_function([this, ycbcr_coefficients_override_func](x264_param_t *param) {
333 if (bitrate_override_func) {
334 bitrate_override_func(param);
336 ycbcr_coefficients_override_func(param);
340 dyn.x264_encoder_parameters(x264, ¶m);
341 if (bitrate_override_func) {
342 bitrate_override_func(¶m);
344 ycbcr_coefficients_override_func(¶m);
345 dyn.x264_encoder_reconfig(x264, ¶m);
349 speed_control->before_frame(float(free_frames.size()) / X264_QUEUE_LENGTH, X264_QUEUE_LENGTH, 1e6 * qf.duration / TIMEBASE);
351 dyn.x264_encoder_encode(x264, &nal, &num_nal, input_pic, &pic);
353 speed_control->after_frame();
356 if (num_nal == 0) return;
358 if (IS_X264_TYPE_I(pic.i_type)) {
359 ++metric_x264_output_frames_i;
360 } else if (IS_X264_TYPE_B(pic.i_type)) {
361 ++metric_x264_output_frames_b;
363 ++metric_x264_output_frames_p;
366 if (frames_being_encoded.count(pic.i_pts)) {
367 ReceivedTimestamps received_ts = frames_being_encoded[pic.i_pts];
368 frames_being_encoded.erase(pic.i_pts);
370 static int frameno = 0;
371 print_latency("Current x264 latency (video inputs → network mux):",
372 received_ts, (pic.i_type == X264_TYPE_B || pic.i_type == X264_TYPE_BREF),
378 // We really need one AVPacket for the entire frame, it seems,
379 // so combine it all.
380 size_t num_bytes = buffered_sei.size();
381 for (int i = 0; i < num_nal; ++i) {
382 num_bytes += nal[i].i_payload;
385 unique_ptr<uint8_t[]> data(new uint8_t[num_bytes]);
386 uint8_t *ptr = data.get();
388 if (!buffered_sei.empty()) {
389 memcpy(ptr, buffered_sei.data(), buffered_sei.size());
390 ptr += buffered_sei.size();
391 buffered_sei.clear();
393 for (int i = 0; i < num_nal; ++i) {
394 memcpy(ptr, nal[i].p_payload, nal[i].i_payload);
395 ptr += nal[i].i_payload;
399 memset(&pkt, 0, sizeof(pkt));
401 pkt.data = data.get();
402 pkt.size = num_bytes;
403 pkt.stream_index = 0;
404 if (pic.b_keyframe) {
405 pkt.flags = AV_PKT_FLAG_KEY;
409 pkt.duration = reinterpret_cast<intptr_t>(pic.opaque);
411 for (Mux *mux : muxes) {
412 mux->add_packet(pkt, pic.i_pts, pic.i_dts);