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