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);
69 metric_x264_crf.init_uniform(50);
70 global_metrics.add("x264_crf", &metric_x264_crf);
72 latency_histogram.init("x264");
75 X264Encoder::~X264Encoder()
78 queued_frames_nonempty.notify_all();
79 encoder_thread.join();
85 void X264Encoder::add_frame(int64_t pts, int64_t duration, YCbCrLumaCoefficients ycbcr_coefficients, const uint8_t *data, const ReceivedTimestamps &received_ts)
91 qf.duration = duration;
92 qf.ycbcr_coefficients = ycbcr_coefficients;
93 qf.received_ts = received_ts;
96 lock_guard<mutex> lock(mu);
97 if (free_frames.empty()) {
98 fprintf(stderr, "WARNING: x264 queue full, dropping frame with pts %ld\n", pts);
99 ++metric_x264_dropped_frames;
103 qf.data = free_frames.front();
107 size_t bytes_per_pixel = global_flags.x264_bit_depth > 8 ? 2 : 1;
108 memcpy(qf.data, data, global_flags.width * global_flags.height * 2 * bytes_per_pixel);
111 lock_guard<mutex> lock(mu);
112 queued_frames.push(qf);
113 queued_frames_nonempty.notify_all();
114 metric_x264_queued_frames = queued_frames.size();
118 void X264Encoder::init_x264()
121 dyn.x264_param_default_preset(¶m, global_flags.x264_preset.c_str(), global_flags.x264_tune.c_str());
123 param.i_width = global_flags.width;
124 param.i_height = global_flags.height;
125 param.i_csp = X264_CSP_NV12;
126 if (global_flags.x264_bit_depth > 8) {
127 param.i_csp |= X264_CSP_HIGH_DEPTH;
129 param.b_vfr_input = 1;
130 param.i_timebase_num = 1;
131 param.i_timebase_den = TIMEBASE;
132 param.i_keyint_max = 50; // About one second.
133 if (global_flags.x264_speedcontrol) {
134 param.i_frame_reference = 16; // Because speedcontrol is never allowed to change this above what we set at start.
137 // NOTE: These should be in sync with the ones in quicksync_encoder.cpp (sps_rbsp()).
138 param.vui.i_vidformat = 5; // Unspecified.
139 param.vui.b_fullrange = 0;
140 param.vui.i_colorprim = 1; // BT.709.
141 param.vui.i_transfer = 2; // Unspecified (since we use sRGB).
142 if (global_flags.ycbcr_rec709_coefficients) {
143 param.vui.i_colmatrix = 1; // BT.709.
145 param.vui.i_colmatrix = 6; // BT.601/SMPTE 170M.
148 if (!isinf(global_flags.x264_crf)) {
149 param.rc.i_rc_method = X264_RC_CRF;
150 param.rc.f_rf_constant = global_flags.x264_crf;
152 param.rc.i_rc_method = X264_RC_ABR;
153 param.rc.i_bitrate = global_flags.x264_bitrate;
155 update_vbv_settings(¶m);
156 if (param.rc.i_vbv_max_bitrate > 0) {
157 // If the user wants VBV control to cap the max rate, it is
158 // also reasonable to assume that they are fine with the stream
159 // constantly being around that rate even for very low-complexity
160 // content; the obvious and extreme example being a static
163 // One would think it's fine to have low-complexity content use
164 // less bitrate, but it seems to cause problems in practice;
165 // e.g. VLC seems to often drop the stream (similar to a buffer
166 // underrun) in such cases, but only when streaming from Nageru,
167 // not when reading a dump of the same stream from disk.
168 // I'm not 100% sure whether it's in VLC (possibly some buffering
169 // in the HTTP layer), in microhttpd or somewhere in Nageru itself,
170 // but it's a typical case of problems that can arise. Similarly,
171 // TCP's congestion control is not always fond of the rate staying
172 // low for a while and then rising quickly -- a variation on the same
175 // We solve this by simply asking x264 to fill in dummy bits
176 // in these cases, so that the bitrate stays reasonable constant.
177 // It's a waste of bandwidth, but it makes things go much more
178 // smoothly in these cases. (We don't do it if VBV control is off
179 // in general, not the least because it makes no sense and x264
180 // thus ignores the parameter.)
181 param.rc.b_filler = 1;
184 // Occasionally players have problem with extremely low quantizers;
185 // be on the safe side. Shouldn't affect quality in any meaningful way.
186 param.rc.i_qp_min = 5;
188 for (const string &str : global_flags.x264_extra_param) {
189 const size_t pos = str.find(',');
190 if (pos == string::npos) {
191 if (dyn.x264_param_parse(¶m, str.c_str(), nullptr) != 0) {
192 fprintf(stderr, "ERROR: x264 rejected parameter '%s'\n", str.c_str());
195 const string key = str.substr(0, pos);
196 const string value = str.substr(pos + 1);
197 if (dyn.x264_param_parse(¶m, key.c_str(), value.c_str()) != 0) {
198 fprintf(stderr, "ERROR: x264 rejected parameter '%s' set to '%s'\n",
199 key.c_str(), value.c_str());
204 if (global_flags.x264_bit_depth > 8) {
205 dyn.x264_param_apply_profile(¶m, "high10");
207 dyn.x264_param_apply_profile(¶m, "high");
210 param.b_repeat_headers = !wants_global_headers;
212 x264 = dyn.x264_encoder_open(¶m);
213 if (x264 == nullptr) {
214 fprintf(stderr, "ERROR: x264 initialization failed.\n");
218 if (global_flags.x264_speedcontrol) {
219 speed_control.reset(new X264SpeedControl(x264, /*f_speed=*/1.0f, X264_QUEUE_LENGTH, /*f_buffer_init=*/1.0f));
222 if (wants_global_headers) {
226 dyn.x264_encoder_headers(x264, &nal, &num_nal);
228 for (int i = 0; i < num_nal; ++i) {
229 if (nal[i].i_type == NAL_SEI) {
230 // Don't put the SEI in extradata; make it part of the first frame instead.
231 buffered_sei += string((const char *)nal[i].p_payload, nal[i].i_payload);
233 global_headers += string((const char *)nal[i].p_payload, nal[i].i_payload);
239 void X264Encoder::encoder_thread_func()
241 if (nice(5) == -1) { // Note that x264 further nices some of its threads.
243 // No exit; it's not fatal.
245 pthread_setname_np(pthread_self(), "x264_encode");
247 x264_init_done = true;
254 // Wait for a queued frame, then dequeue it.
256 unique_lock<mutex> lock(mu);
257 queued_frames_nonempty.wait(lock, [this]() { return !queued_frames.empty() || should_quit; });
258 if (!queued_frames.empty()) {
259 qf = queued_frames.front();
267 metric_x264_queued_frames = queued_frames.size();
268 frames_left = !queued_frames.empty();
274 lock_guard<mutex> lock(mu);
275 free_frames.push(qf.data);
278 // We should quit only if the should_quit flag is set _and_ we have nothing
280 } while (!should_quit || frames_left || dyn.x264_encoder_delayed_frames(x264) > 0);
282 dyn.x264_encoder_close(x264);
285 void X264Encoder::encode_frame(X264Encoder::QueuedFrame qf)
287 x264_nal_t *nal = nullptr;
290 x264_picture_t *input_pic = nullptr;
293 dyn.x264_picture_init(&pic);
296 if (global_flags.x264_bit_depth > 8) {
297 pic.img.i_csp = X264_CSP_NV12 | X264_CSP_HIGH_DEPTH;
299 pic.img.plane[0] = qf.data;
300 pic.img.i_stride[0] = global_flags.width * sizeof(uint16_t);
301 pic.img.plane[1] = qf.data + global_flags.width * global_flags.height * sizeof(uint16_t);
302 pic.img.i_stride[1] = global_flags.width / 2 * sizeof(uint32_t);
304 pic.img.i_csp = X264_CSP_NV12;
306 pic.img.plane[0] = qf.data;
307 pic.img.i_stride[0] = global_flags.width;
308 pic.img.plane[1] = qf.data + global_flags.width * global_flags.height;
309 pic.img.i_stride[1] = global_flags.width / 2 * sizeof(uint16_t);
311 pic.opaque = reinterpret_cast<void *>(intptr_t(qf.duration));
315 frames_being_encoded[qf.pts] = qf.received_ts;
318 // See if we have a new bitrate to change to.
319 unsigned new_rate = new_bitrate_kbit.exchange(0); // Read and clear.
321 bitrate_override_func = [new_rate](x264_param_t *param) {
322 param->rc.i_bitrate = new_rate;
323 update_vbv_settings(param);
327 auto ycbcr_coefficients_override_func = [qf](x264_param_t *param) {
328 if (qf.ycbcr_coefficients == YCBCR_REC_709) {
329 param->vui.i_colmatrix = 1; // BT.709.
331 assert(qf.ycbcr_coefficients == YCBCR_REC_601);
332 param->vui.i_colmatrix = 6; // BT.601/SMPTE 170M.
337 speed_control->set_config_override_function([this, ycbcr_coefficients_override_func](x264_param_t *param) {
338 if (bitrate_override_func) {
339 bitrate_override_func(param);
341 ycbcr_coefficients_override_func(param);
345 dyn.x264_encoder_parameters(x264, ¶m);
346 if (bitrate_override_func) {
347 bitrate_override_func(¶m);
349 ycbcr_coefficients_override_func(¶m);
350 dyn.x264_encoder_reconfig(x264, ¶m);
354 speed_control->before_frame(float(free_frames.size()) / X264_QUEUE_LENGTH, X264_QUEUE_LENGTH, 1e6 * qf.duration / TIMEBASE);
356 dyn.x264_encoder_encode(x264, &nal, &num_nal, input_pic, &pic);
358 speed_control->after_frame();
361 if (num_nal == 0) return;
363 if (IS_X264_TYPE_I(pic.i_type)) {
364 ++metric_x264_output_frames_i;
365 } else if (IS_X264_TYPE_B(pic.i_type)) {
366 ++metric_x264_output_frames_b;
368 ++metric_x264_output_frames_p;
371 metric_x264_crf.count_event(pic.prop.f_crf_avg);
373 if (frames_being_encoded.count(pic.i_pts)) {
374 ReceivedTimestamps received_ts = frames_being_encoded[pic.i_pts];
375 frames_being_encoded.erase(pic.i_pts);
377 static int frameno = 0;
378 print_latency("Current x264 latency (video inputs → network mux):",
379 received_ts, (pic.i_type == X264_TYPE_B || pic.i_type == X264_TYPE_BREF),
380 &frameno, &latency_histogram);
385 // We really need one AVPacket for the entire frame, it seems,
386 // so combine it all.
387 size_t num_bytes = buffered_sei.size();
388 for (int i = 0; i < num_nal; ++i) {
389 num_bytes += nal[i].i_payload;
392 unique_ptr<uint8_t[]> data(new uint8_t[num_bytes]);
393 uint8_t *ptr = data.get();
395 if (!buffered_sei.empty()) {
396 memcpy(ptr, buffered_sei.data(), buffered_sei.size());
397 ptr += buffered_sei.size();
398 buffered_sei.clear();
400 for (int i = 0; i < num_nal; ++i) {
401 memcpy(ptr, nal[i].p_payload, nal[i].i_payload);
402 ptr += nal[i].i_payload;
406 memset(&pkt, 0, sizeof(pkt));
408 pkt.data = data.get();
409 pkt.size = num_bytes;
410 pkt.stream_index = 0;
411 if (pic.b_keyframe) {
412 pkt.flags = AV_PKT_FLAG_KEY;
416 pkt.duration = reinterpret_cast<intptr_t>(pic.opaque);
418 for (Mux *mux : muxes) {
419 mux->add_packet(pkt, pic.i_pts, pic.i_dts);