8 #include "x264_encoder.h"
9 #include "x264_speed_control.h"
12 #include <libavformat/avformat.h>
17 X264Encoder::X264Encoder(AVOutputFormat *oformat)
18 : wants_global_headers(oformat->flags & AVFMT_GLOBALHEADER)
20 frame_pool.reset(new uint8_t[WIDTH * HEIGHT * 2 * X264_QUEUE_LENGTH]);
21 for (unsigned i = 0; i < X264_QUEUE_LENGTH; ++i) {
22 free_frames.push(frame_pool.get() + i * (WIDTH * HEIGHT * 2));
24 encoder_thread = thread(&X264Encoder::encoder_thread_func, this);
27 X264Encoder::~X264Encoder()
30 queued_frames_nonempty.notify_all();
31 encoder_thread.join();
34 void X264Encoder::add_frame(int64_t pts, int64_t duration, const uint8_t *data)
38 qf.duration = duration;
41 lock_guard<mutex> lock(mu);
42 if (free_frames.empty()) {
43 fprintf(stderr, "WARNING: x264 queue full, dropping frame with pts %ld\n", pts);
47 qf.data = free_frames.front();
51 memcpy(qf.data, data, WIDTH * HEIGHT * 2);
54 lock_guard<mutex> lock(mu);
55 queued_frames.push(qf);
56 queued_frames_nonempty.notify_all();
60 void X264Encoder::init_x264()
63 x264_param_default_preset(¶m, global_flags.x264_preset.c_str(), global_flags.x264_tune.c_str());
65 param.i_width = WIDTH;
66 param.i_height = HEIGHT;
67 param.i_csp = X264_CSP_NV12;
68 param.b_vfr_input = 1;
69 param.i_timebase_num = 1;
70 param.i_timebase_den = TIMEBASE;
71 param.i_keyint_max = 50; // About one second.
72 if (global_flags.x264_speedcontrol) {
73 param.i_frame_reference = 16; // Because speedcontrol is never allowed to change this above what we set at start.
76 // NOTE: These should be in sync with the ones in h264encode.cpp (sbs_rbsp()).
77 param.vui.i_vidformat = 5; // Unspecified.
78 param.vui.b_fullrange = 0;
79 param.vui.i_colorprim = 1; // BT.709.
80 param.vui.i_transfer = 2; // Unspecified (since we use sRGB).
81 param.vui.i_colmatrix = 6; // BT.601/SMPTE 170M.
84 param.rc.i_rc_method = X264_RC_ABR;
85 param.rc.i_bitrate = global_flags.x264_bitrate;
86 if (global_flags.x264_vbv_buffer_size < 0) {
87 param.rc.i_vbv_buffer_size = param.rc.i_bitrate; // One-second VBV.
89 param.rc.i_vbv_buffer_size = global_flags.x264_vbv_buffer_size;
91 if (global_flags.x264_vbv_max_bitrate < 0) {
92 param.rc.i_vbv_max_bitrate = param.rc.i_bitrate; // CBR.
94 param.rc.i_vbv_max_bitrate = global_flags.x264_vbv_max_bitrate;
96 if (param.rc.i_vbv_max_bitrate > 0) {
97 // If the user wants VBV control to cap the max rate, it is
98 // also reasonable to assume that they are fine with the stream
99 // constantly being around that rate even for very low-complexity
100 // content; the obvious and extreme example being a static
103 // One would think it's fine to have low-complexity codec use
104 // less bitrate, but it seems to cause problems in practice;
105 // e.g. VLC seems to often drop the stream (similar to a buffer
106 // underrun) in such cases, but only when streaming from Nageru,
107 // not when reading a dump of the same stream from disk.
108 // I'm not 100% sure whether it's in VLC (possibly some buffering
109 // in the HTTP layer), in microhttpd or somewhere in Nageru itself,
110 // but it's a typical case of problems that can arise. Similarly,
111 // TCP's congestion control is not always fond of the rate staying
112 // low for a while and then rising quickly -- a variation on the same
115 // We solve this by simply asking x264 to fill in dummy bits
116 // in these cases, so that the bitrate stays reasonable constant.
117 // It's a waste of bandwidth, but it makes things go much more
118 // smoothly in these cases. (We don't do it if VBV control is off
119 // in general, not the least because it makes no sense and x264
120 // thus ignores the parameter.)
121 param.rc.b_filler = 1;
124 // Occasionally players have problem with extremely low quantizers;
125 // be on the safe side. Shouldn't affect quality in any meaningful way.
126 param.rc.i_qp_min = 5;
128 // TODO: more flags here, via x264_param_parse().
130 x264_param_apply_profile(¶m, "high");
132 param.b_repeat_headers = !wants_global_headers;
134 x264 = x264_encoder_open(¶m);
135 if (x264 == nullptr) {
136 fprintf(stderr, "ERROR: x264 initialization failed.\n");
140 if (global_flags.x264_speedcontrol) {
141 speed_control.reset(new X264SpeedControl(x264, /*f_speed=*/1.0f, X264_QUEUE_LENGTH, /*f_buffer_init=*/1.0f));
144 if (wants_global_headers) {
148 x264_encoder_headers(x264, &nal, &num_nal);
150 for (int i = 0; i < num_nal; ++i) {
151 if (nal[i].i_type == NAL_SEI) {
152 // Don't put the SEI in extradata; make it part of the first frame instead.
153 buffered_sei += string((const char *)nal[i].p_payload, nal[i].i_payload);
155 global_headers += string((const char *)nal[i].p_payload, nal[i].i_payload);
161 void X264Encoder::encoder_thread_func()
163 nice(5); // Note that x264 further nices some of its threads.
171 // Wait for a queued frame, then dequeue it.
173 unique_lock<mutex> lock(mu);
174 queued_frames_nonempty.wait(lock, [this]() { return !queued_frames.empty() || should_quit; });
175 if (!queued_frames.empty()) {
176 qf = queued_frames.front();
184 frames_left = !queued_frames.empty();
190 lock_guard<mutex> lock(mu);
191 free_frames.push(qf.data);
194 // We should quit only if the should_quit flag is set _and_ we have nothing
196 } while (!should_quit || frames_left || x264_encoder_delayed_frames(x264) > 0);
198 x264_encoder_close(x264);
201 void X264Encoder::encode_frame(X264Encoder::QueuedFrame qf)
203 x264_nal_t *nal = nullptr;
206 x264_picture_t *input_pic = nullptr;
209 x264_picture_init(&pic);
212 pic.img.i_csp = X264_CSP_NV12;
214 pic.img.plane[0] = qf.data;
215 pic.img.i_stride[0] = WIDTH;
216 pic.img.plane[1] = qf.data + WIDTH * HEIGHT;
217 pic.img.i_stride[1] = WIDTH / 2 * sizeof(uint16_t);
218 pic.opaque = reinterpret_cast<void *>(intptr_t(qf.duration));
224 speed_control->before_frame(float(free_frames.size()) / X264_QUEUE_LENGTH, X264_QUEUE_LENGTH, 1e6 * qf.duration / TIMEBASE);
226 x264_encoder_encode(x264, &nal, &num_nal, input_pic, &pic);
228 speed_control->after_frame();
231 // We really need one AVPacket for the entire frame, it seems,
232 // so combine it all.
233 size_t num_bytes = buffered_sei.size();
234 for (int i = 0; i < num_nal; ++i) {
235 num_bytes += nal[i].i_payload;
238 unique_ptr<uint8_t[]> data(new uint8_t[num_bytes]);
239 uint8_t *ptr = data.get();
241 if (!buffered_sei.empty()) {
242 memcpy(ptr, buffered_sei.data(), buffered_sei.size());
243 ptr += buffered_sei.size();
244 buffered_sei.clear();
246 for (int i = 0; i < num_nal; ++i) {
247 memcpy(ptr, nal[i].p_payload, nal[i].i_payload);
248 ptr += nal[i].i_payload;
252 memset(&pkt, 0, sizeof(pkt));
254 pkt.data = data.get();
255 pkt.size = num_bytes;
256 pkt.stream_index = 0;
257 if (pic.b_keyframe) {
258 pkt.flags = AV_PKT_FLAG_KEY;
262 pkt.duration = reinterpret_cast<intptr_t>(pic.opaque);
264 mux->add_packet(pkt, pic.i_pts, pic.i_dts);