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>
24 using namespace std::chrono;
28 void update_vbv_settings(x264_param_t *param)
30 if (global_flags.x264_vbv_buffer_size < 0) {
31 param->rc.i_vbv_buffer_size = param->rc.i_bitrate; // One-second VBV.
33 param->rc.i_vbv_buffer_size = global_flags.x264_vbv_buffer_size;
35 if (global_flags.x264_vbv_max_bitrate < 0) {
36 param->rc.i_vbv_max_bitrate = param->rc.i_bitrate; // CBR.
38 param->rc.i_vbv_max_bitrate = global_flags.x264_vbv_max_bitrate;
44 X264Encoder::X264Encoder(AVOutputFormat *oformat)
45 : wants_global_headers(oformat->flags & AVFMT_GLOBALHEADER)
47 frame_pool.reset(new uint8_t[global_flags.width * global_flags.height * 2 * X264_QUEUE_LENGTH]);
48 for (unsigned i = 0; i < X264_QUEUE_LENGTH; ++i) {
49 free_frames.push(frame_pool.get() + i * (global_flags.width * global_flags.height * 2));
51 encoder_thread = thread(&X264Encoder::encoder_thread_func, this);
54 X264Encoder::~X264Encoder()
57 queued_frames_nonempty.notify_all();
58 encoder_thread.join();
61 void X264Encoder::add_frame(int64_t pts, int64_t duration, const uint8_t *data, const ReceivedTimestamps &received_ts)
65 qf.duration = duration;
66 qf.received_ts = received_ts;
69 lock_guard<mutex> lock(mu);
70 if (free_frames.empty()) {
71 fprintf(stderr, "WARNING: x264 queue full, dropping frame with pts %ld\n", pts);
75 qf.data = free_frames.front();
79 memcpy(qf.data, data, global_flags.width * global_flags.height * 2);
82 lock_guard<mutex> lock(mu);
83 queued_frames.push(qf);
84 queued_frames_nonempty.notify_all();
88 void X264Encoder::init_x264()
91 x264_param_default_preset(¶m, global_flags.x264_preset.c_str(), global_flags.x264_tune.c_str());
93 param.i_width = global_flags.width;
94 param.i_height = global_flags.height;
95 param.i_csp = X264_CSP_NV12;
96 param.b_vfr_input = 1;
97 param.i_timebase_num = 1;
98 param.i_timebase_den = TIMEBASE;
99 param.i_keyint_max = 50; // About one second.
100 if (global_flags.x264_speedcontrol) {
101 param.i_frame_reference = 16; // Because speedcontrol is never allowed to change this above what we set at start.
104 // NOTE: These should be in sync with the ones in h264encode.cpp (sbs_rbsp()).
105 param.vui.i_vidformat = 5; // Unspecified.
106 param.vui.b_fullrange = 0;
107 param.vui.i_colorprim = 1; // BT.709.
108 param.vui.i_transfer = 2; // Unspecified (since we use sRGB).
109 param.vui.i_colmatrix = 6; // BT.601/SMPTE 170M.
112 param.rc.i_rc_method = X264_RC_ABR;
113 param.rc.i_bitrate = global_flags.x264_bitrate;
114 update_vbv_settings(¶m);
115 if (param.rc.i_vbv_max_bitrate > 0) {
116 // If the user wants VBV control to cap the max rate, it is
117 // also reasonable to assume that they are fine with the stream
118 // constantly being around that rate even for very low-complexity
119 // content; the obvious and extreme example being a static
122 // One would think it's fine to have low-complexity content use
123 // less bitrate, but it seems to cause problems in practice;
124 // e.g. VLC seems to often drop the stream (similar to a buffer
125 // underrun) in such cases, but only when streaming from Nageru,
126 // not when reading a dump of the same stream from disk.
127 // I'm not 100% sure whether it's in VLC (possibly some buffering
128 // in the HTTP layer), in microhttpd or somewhere in Nageru itself,
129 // but it's a typical case of problems that can arise. Similarly,
130 // TCP's congestion control is not always fond of the rate staying
131 // low for a while and then rising quickly -- a variation on the same
134 // We solve this by simply asking x264 to fill in dummy bits
135 // in these cases, so that the bitrate stays reasonable constant.
136 // It's a waste of bandwidth, but it makes things go much more
137 // smoothly in these cases. (We don't do it if VBV control is off
138 // in general, not the least because it makes no sense and x264
139 // thus ignores the parameter.)
140 param.rc.b_filler = 1;
143 // Occasionally players have problem with extremely low quantizers;
144 // be on the safe side. Shouldn't affect quality in any meaningful way.
145 param.rc.i_qp_min = 5;
147 for (const string &str : global_flags.x264_extra_param) {
148 const size_t pos = str.find(',');
149 if (pos == string::npos) {
150 if (x264_param_parse(¶m, str.c_str(), nullptr) != 0) {
151 fprintf(stderr, "ERROR: x264 rejected parameter '%s'\n", str.c_str());
154 const string key = str.substr(0, pos);
155 const string value = str.substr(pos + 1);
156 if (x264_param_parse(¶m, key.c_str(), value.c_str()) != 0) {
157 fprintf(stderr, "ERROR: x264 rejected parameter '%s' set to '%s'\n",
158 key.c_str(), value.c_str());
163 x264_param_apply_profile(¶m, "high");
165 param.b_repeat_headers = !wants_global_headers;
167 x264 = x264_encoder_open(¶m);
168 if (x264 == nullptr) {
169 fprintf(stderr, "ERROR: x264 initialization failed.\n");
173 if (global_flags.x264_speedcontrol) {
174 speed_control.reset(new X264SpeedControl(x264, /*f_speed=*/1.0f, X264_QUEUE_LENGTH, /*f_buffer_init=*/1.0f));
177 if (wants_global_headers) {
181 x264_encoder_headers(x264, &nal, &num_nal);
183 for (int i = 0; i < num_nal; ++i) {
184 if (nal[i].i_type == NAL_SEI) {
185 // Don't put the SEI in extradata; make it part of the first frame instead.
186 buffered_sei += string((const char *)nal[i].p_payload, nal[i].i_payload);
188 global_headers += string((const char *)nal[i].p_payload, nal[i].i_payload);
194 void X264Encoder::encoder_thread_func()
196 if (nice(5) == -1) { // Note that x264 further nices some of its threads.
198 // No exit; it's not fatal.
201 x264_init_done = true;
208 // Wait for a queued frame, then dequeue it.
210 unique_lock<mutex> lock(mu);
211 queued_frames_nonempty.wait(lock, [this]() { return !queued_frames.empty() || should_quit; });
212 if (!queued_frames.empty()) {
213 qf = queued_frames.front();
221 frames_left = !queued_frames.empty();
227 lock_guard<mutex> lock(mu);
228 free_frames.push(qf.data);
231 // We should quit only if the should_quit flag is set _and_ we have nothing
233 } while (!should_quit || frames_left || x264_encoder_delayed_frames(x264) > 0);
235 x264_encoder_close(x264);
238 void X264Encoder::encode_frame(X264Encoder::QueuedFrame qf)
240 x264_nal_t *nal = nullptr;
243 x264_picture_t *input_pic = nullptr;
246 x264_picture_init(&pic);
249 pic.img.i_csp = X264_CSP_NV12;
251 pic.img.plane[0] = qf.data;
252 pic.img.i_stride[0] = global_flags.width;
253 pic.img.plane[1] = qf.data + global_flags.width * global_flags.height;
254 pic.img.i_stride[1] = global_flags.width / 2 * sizeof(uint16_t);
255 pic.opaque = reinterpret_cast<void *>(intptr_t(qf.duration));
259 frames_being_encoded[qf.pts] = qf.received_ts;
262 // See if we have a new bitrate to change to.
263 unsigned new_rate = new_bitrate_kbit.exchange(0); // Read and clear.
266 speed_control->set_config_override_function([new_rate](x264_param_t *param) {
267 param->rc.i_bitrate = new_rate;
268 update_vbv_settings(param);
272 x264_encoder_parameters(x264, ¶m);
273 param.rc.i_bitrate = new_rate;
274 update_vbv_settings(¶m);
275 x264_encoder_reconfig(x264, ¶m);
280 speed_control->before_frame(float(free_frames.size()) / X264_QUEUE_LENGTH, X264_QUEUE_LENGTH, 1e6 * qf.duration / TIMEBASE);
282 x264_encoder_encode(x264, &nal, &num_nal, input_pic, &pic);
284 speed_control->after_frame();
287 if (num_nal == 0) return;
289 if (frames_being_encoded.count(pic.i_pts)) {
290 ReceivedTimestamps received_ts = frames_being_encoded[pic.i_pts];
291 frames_being_encoded.erase(pic.i_pts);
293 static int frameno = 0;
294 print_latency("Current x264 latency (video inputs → network mux):",
295 received_ts, (pic.i_type == X264_TYPE_B || pic.i_type == X264_TYPE_BREF),
301 // We really need one AVPacket for the entire frame, it seems,
302 // so combine it all.
303 size_t num_bytes = buffered_sei.size();
304 for (int i = 0; i < num_nal; ++i) {
305 num_bytes += nal[i].i_payload;
308 unique_ptr<uint8_t[]> data(new uint8_t[num_bytes]);
309 uint8_t *ptr = data.get();
311 if (!buffered_sei.empty()) {
312 memcpy(ptr, buffered_sei.data(), buffered_sei.size());
313 ptr += buffered_sei.size();
314 buffered_sei.clear();
316 for (int i = 0; i < num_nal; ++i) {
317 memcpy(ptr, nal[i].p_payload, nal[i].i_payload);
318 ptr += nal[i].i_payload;
322 memset(&pkt, 0, sizeof(pkt));
324 pkt.data = data.get();
325 pkt.size = num_bytes;
326 pkt.stream_index = 0;
327 if (pic.b_keyframe) {
328 pkt.flags = AV_PKT_FLAG_KEY;
332 pkt.duration = reinterpret_cast<intptr_t>(pic.opaque);
334 mux->add_packet(pkt, pic.i_pts, pic.i_dts);