]> git.sesse.net Git - nageru/blob - x264_encoder.cpp
Let settings follow buses when editing the mapping.
[nageru] / x264_encoder.cpp
1 #include <string.h>
2 #include <unistd.h>
3
4 #include "defs.h"
5 #include "flags.h"
6 #include "mux.h"
7 #include "timebase.h"
8 #include "x264_encoder.h"
9 #include "x264_speed_control.h"
10
11 extern "C" {
12 #include <libavformat/avformat.h>
13 }
14
15 using namespace std;
16
17 namespace {
18
19 void update_vbv_settings(x264_param_t *param)
20 {
21         if (global_flags.x264_vbv_buffer_size < 0) {
22                 param->rc.i_vbv_buffer_size = param->rc.i_bitrate;  // One-second VBV.
23         } else {
24                 param->rc.i_vbv_buffer_size = global_flags.x264_vbv_buffer_size;
25         }
26         if (global_flags.x264_vbv_max_bitrate < 0) {
27                 param->rc.i_vbv_max_bitrate = param->rc.i_bitrate;  // CBR.
28         } else {
29                 param->rc.i_vbv_max_bitrate = global_flags.x264_vbv_max_bitrate;
30         }
31 }
32
33 }  // namespace
34
35 X264Encoder::X264Encoder(AVOutputFormat *oformat)
36         : wants_global_headers(oformat->flags & AVFMT_GLOBALHEADER)
37 {
38         frame_pool.reset(new uint8_t[WIDTH * HEIGHT * 2 * X264_QUEUE_LENGTH]);
39         for (unsigned i = 0; i < X264_QUEUE_LENGTH; ++i) {
40                 free_frames.push(frame_pool.get() + i * (WIDTH * HEIGHT * 2));
41         }
42         encoder_thread = thread(&X264Encoder::encoder_thread_func, this);
43 }
44
45 X264Encoder::~X264Encoder()
46 {
47         should_quit = true;
48         queued_frames_nonempty.notify_all();
49         encoder_thread.join();
50 }
51
52 void X264Encoder::add_frame(int64_t pts, int64_t duration, const uint8_t *data)
53 {
54         QueuedFrame qf;
55         qf.pts = pts;
56         qf.duration = duration;
57
58         {
59                 lock_guard<mutex> lock(mu);
60                 if (free_frames.empty()) {
61                         fprintf(stderr, "WARNING: x264 queue full, dropping frame with pts %ld\n", pts);
62                         return;
63                 }
64
65                 qf.data = free_frames.front();
66                 free_frames.pop();
67         }
68
69         memcpy(qf.data, data, WIDTH * HEIGHT * 2);
70
71         {
72                 lock_guard<mutex> lock(mu);
73                 queued_frames.push(qf);
74                 queued_frames_nonempty.notify_all();
75         }
76 }
77         
78 void X264Encoder::init_x264()
79 {
80         x264_param_t param;
81         x264_param_default_preset(&param, global_flags.x264_preset.c_str(), global_flags.x264_tune.c_str());
82
83         param.i_width = WIDTH;
84         param.i_height = HEIGHT;
85         param.i_csp = X264_CSP_NV12;
86         param.b_vfr_input = 1;
87         param.i_timebase_num = 1;
88         param.i_timebase_den = TIMEBASE;
89         param.i_keyint_max = 50; // About one second.
90         if (global_flags.x264_speedcontrol) {
91                 param.i_frame_reference = 16;  // Because speedcontrol is never allowed to change this above what we set at start.
92         }
93
94         // NOTE: These should be in sync with the ones in h264encode.cpp (sbs_rbsp()).
95         param.vui.i_vidformat = 5;  // Unspecified.
96         param.vui.b_fullrange = 0;
97         param.vui.i_colorprim = 1;  // BT.709.
98         param.vui.i_transfer = 2;  // Unspecified (since we use sRGB).
99         param.vui.i_colmatrix = 6;  // BT.601/SMPTE 170M.
100
101
102         param.rc.i_rc_method = X264_RC_ABR;
103         param.rc.i_bitrate = global_flags.x264_bitrate;
104         update_vbv_settings(&param);
105         if (param.rc.i_vbv_max_bitrate > 0) {
106                 // If the user wants VBV control to cap the max rate, it is
107                 // also reasonable to assume that they are fine with the stream
108                 // constantly being around that rate even for very low-complexity
109                 // content; the obvious and extreme example being a static
110                 // black picture.
111                 //
112                 // One would think it's fine to have low-complexity content use
113                 // less bitrate, but it seems to cause problems in practice;
114                 // e.g. VLC seems to often drop the stream (similar to a buffer
115                 // underrun) in such cases, but only when streaming from Nageru,
116                 // not when reading a dump of the same stream from disk.
117                 // I'm not 100% sure whether it's in VLC (possibly some buffering
118                 // in the HTTP layer), in microhttpd or somewhere in Nageru itself,
119                 // but it's a typical case of problems that can arise. Similarly,
120                 // TCP's congestion control is not always fond of the rate staying
121                 // low for a while and then rising quickly -- a variation on the same
122                 // problem.
123                 //
124                 // We solve this by simply asking x264 to fill in dummy bits
125                 // in these cases, so that the bitrate stays reasonable constant.
126                 // It's a waste of bandwidth, but it makes things go much more
127                 // smoothly in these cases. (We don't do it if VBV control is off
128                 // in general, not the least because it makes no sense and x264
129                 // thus ignores the parameter.)
130                 param.rc.b_filler = 1;
131         }
132
133         // Occasionally players have problem with extremely low quantizers;
134         // be on the safe side. Shouldn't affect quality in any meaningful way.
135         param.rc.i_qp_min = 5;
136
137         for (const string &str : global_flags.x264_extra_param) {
138                 const size_t pos = str.find(',');
139                 if (pos == string::npos) {
140                         if (x264_param_parse(&param, str.c_str(), nullptr) != 0) {
141                                 fprintf(stderr, "ERROR: x264 rejected parameter '%s'\n", str.c_str());
142                         }
143                 } else {
144                         const string key = str.substr(0, pos);
145                         const string value = str.substr(pos + 1);
146                         if (x264_param_parse(&param, key.c_str(), value.c_str()) != 0) {
147                                 fprintf(stderr, "ERROR: x264 rejected parameter '%s' set to '%s'\n",
148                                         key.c_str(), value.c_str());
149                         }
150                 }
151         }
152
153         x264_param_apply_profile(&param, "high");
154
155         param.b_repeat_headers = !wants_global_headers;
156
157         x264 = x264_encoder_open(&param);
158         if (x264 == nullptr) {
159                 fprintf(stderr, "ERROR: x264 initialization failed.\n");
160                 exit(1);
161         }
162
163         if (global_flags.x264_speedcontrol) {
164                 speed_control.reset(new X264SpeedControl(x264, /*f_speed=*/1.0f, X264_QUEUE_LENGTH, /*f_buffer_init=*/1.0f));
165         }
166
167         if (wants_global_headers) {
168                 x264_nal_t *nal;
169                 int num_nal;
170
171                 x264_encoder_headers(x264, &nal, &num_nal);
172
173                 for (int i = 0; i < num_nal; ++i) {
174                         if (nal[i].i_type == NAL_SEI) {
175                                 // Don't put the SEI in extradata; make it part of the first frame instead.
176                                 buffered_sei += string((const char *)nal[i].p_payload, nal[i].i_payload);
177                         } else {
178                                 global_headers += string((const char *)nal[i].p_payload, nal[i].i_payload);
179                         }
180                 }
181         }
182 }
183
184 void X264Encoder::encoder_thread_func()
185 {
186         if (nice(5) == -1) {  // Note that x264 further nices some of its threads.
187                 perror("nice()");
188                 // No exit; it's not fatal.
189         }
190         init_x264();
191
192         bool frames_left;
193
194         do {
195                 QueuedFrame qf;
196
197                 // Wait for a queued frame, then dequeue it.
198                 {
199                         unique_lock<mutex> lock(mu);
200                         queued_frames_nonempty.wait(lock, [this]() { return !queued_frames.empty() || should_quit; });
201                         if (!queued_frames.empty()) {
202                                 qf = queued_frames.front();
203                                 queued_frames.pop();
204                         } else {
205                                 qf.pts = -1;
206                                 qf.duration = -1;
207                                 qf.data = nullptr;
208                         }
209
210                         frames_left = !queued_frames.empty();
211                 }
212
213                 encode_frame(qf);
214                 
215                 {
216                         lock_guard<mutex> lock(mu);
217                         free_frames.push(qf.data);
218                 }
219
220                 // We should quit only if the should_quit flag is set _and_ we have nothing
221                 // in either queue.
222         } while (!should_quit || frames_left || x264_encoder_delayed_frames(x264) > 0);
223
224         x264_encoder_close(x264);
225 }
226
227 void X264Encoder::encode_frame(X264Encoder::QueuedFrame qf)
228 {
229         x264_nal_t *nal = nullptr;
230         int num_nal = 0;
231         x264_picture_t pic;
232         x264_picture_t *input_pic = nullptr;
233
234         if (qf.data) {
235                 x264_picture_init(&pic);
236
237                 pic.i_pts = qf.pts;
238                 pic.img.i_csp = X264_CSP_NV12;
239                 pic.img.i_plane = 2;
240                 pic.img.plane[0] = qf.data;
241                 pic.img.i_stride[0] = WIDTH;
242                 pic.img.plane[1] = qf.data + WIDTH * HEIGHT;
243                 pic.img.i_stride[1] = WIDTH / 2 * sizeof(uint16_t);
244                 pic.opaque = reinterpret_cast<void *>(intptr_t(qf.duration));
245
246                 input_pic = &pic;
247         }
248
249         // See if we have a new bitrate to change to.
250         unsigned new_rate = new_bitrate_kbit.exchange(0);  // Read and clear.
251         if (new_rate != 0) {
252                 if (speed_control) {
253                         speed_control->set_config_override_function([new_rate](x264_param_t *param) {
254                                 param->rc.i_bitrate = new_rate;
255                                 update_vbv_settings(param);
256                         });
257                 } else {
258                         x264_param_t param;
259                         x264_encoder_parameters(x264, &param);
260                         param.rc.i_bitrate = new_rate;
261                         update_vbv_settings(&param);
262                         x264_encoder_reconfig(x264, &param);
263                 }
264         }
265
266         if (speed_control) {
267                 speed_control->before_frame(float(free_frames.size()) / X264_QUEUE_LENGTH, X264_QUEUE_LENGTH, 1e6 * qf.duration / TIMEBASE);
268         }
269         x264_encoder_encode(x264, &nal, &num_nal, input_pic, &pic);
270         if (speed_control) {
271                 speed_control->after_frame();
272         }
273
274         // We really need one AVPacket for the entire frame, it seems,
275         // so combine it all.
276         size_t num_bytes = buffered_sei.size();
277         for (int i = 0; i < num_nal; ++i) {
278                 num_bytes += nal[i].i_payload;
279         }
280
281         unique_ptr<uint8_t[]> data(new uint8_t[num_bytes]);
282         uint8_t *ptr = data.get();
283
284         if (!buffered_sei.empty()) {
285                 memcpy(ptr, buffered_sei.data(), buffered_sei.size());
286                 ptr += buffered_sei.size();
287                 buffered_sei.clear();
288         }
289         for (int i = 0; i < num_nal; ++i) {
290                 memcpy(ptr, nal[i].p_payload, nal[i].i_payload);
291                 ptr += nal[i].i_payload;
292         }
293
294         AVPacket pkt;
295         memset(&pkt, 0, sizeof(pkt));
296         pkt.buf = nullptr;
297         pkt.data = data.get();
298         pkt.size = num_bytes;
299         pkt.stream_index = 0;
300         if (pic.b_keyframe) {
301                 pkt.flags = AV_PKT_FLAG_KEY;
302         } else {
303                 pkt.flags = 0;
304         }
305         pkt.duration = reinterpret_cast<intptr_t>(pic.opaque);
306
307         mux->add_packet(pkt, pic.i_pts, pic.i_dts);
308 }