]> git.sesse.net Git - nageru/blob - x264_encoder.cpp
Add a switch to print video latency.
[nageru] / x264_encoder.cpp
1 #include "x264_encoder.h"
2
3 #include <assert.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <unistd.h>
8 #include <x264.h>
9 #include <cstdint>
10
11 #include "defs.h"
12 #include "flags.h"
13 #include "mux.h"
14 #include "print_latency.h"
15 #include "timebase.h"
16 #include "x264_speed_control.h"
17
18 extern "C" {
19 #include <libavcodec/avcodec.h>
20 #include <libavformat/avformat.h>
21 }
22
23 using namespace std;
24 using namespace std::chrono;
25
26 namespace {
27
28 void update_vbv_settings(x264_param_t *param)
29 {
30         if (global_flags.x264_vbv_buffer_size < 0) {
31                 param->rc.i_vbv_buffer_size = param->rc.i_bitrate;  // One-second VBV.
32         } else {
33                 param->rc.i_vbv_buffer_size = global_flags.x264_vbv_buffer_size;
34         }
35         if (global_flags.x264_vbv_max_bitrate < 0) {
36                 param->rc.i_vbv_max_bitrate = param->rc.i_bitrate;  // CBR.
37         } else {
38                 param->rc.i_vbv_max_bitrate = global_flags.x264_vbv_max_bitrate;
39         }
40 }
41
42 }  // namespace
43
44 X264Encoder::X264Encoder(AVOutputFormat *oformat)
45         : wants_global_headers(oformat->flags & AVFMT_GLOBALHEADER)
46 {
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));
50         }
51         encoder_thread = thread(&X264Encoder::encoder_thread_func, this);
52 }
53
54 X264Encoder::~X264Encoder()
55 {
56         should_quit = true;
57         queued_frames_nonempty.notify_all();
58         encoder_thread.join();
59 }
60
61 void X264Encoder::add_frame(int64_t pts, int64_t duration, const uint8_t *data, const ReceivedTimestamps &received_ts)
62 {
63         QueuedFrame qf;
64         qf.pts = pts;
65         qf.duration = duration;
66         qf.received_ts = received_ts;
67
68         {
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);
72                         return;
73                 }
74
75                 qf.data = free_frames.front();
76                 free_frames.pop();
77         }
78
79         memcpy(qf.data, data, global_flags.width * global_flags.height * 2);
80
81         {
82                 lock_guard<mutex> lock(mu);
83                 queued_frames.push(qf);
84                 queued_frames_nonempty.notify_all();
85         }
86 }
87         
88 void X264Encoder::init_x264()
89 {
90         x264_param_t param;
91         x264_param_default_preset(&param, global_flags.x264_preset.c_str(), global_flags.x264_tune.c_str());
92
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.
102         }
103
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.
110
111
112         param.rc.i_rc_method = X264_RC_ABR;
113         param.rc.i_bitrate = global_flags.x264_bitrate;
114         update_vbv_settings(&param);
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
120                 // black picture.
121                 //
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
132                 // problem.
133                 //
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;
141         }
142
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;
146
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(&param, str.c_str(), nullptr) != 0) {
151                                 fprintf(stderr, "ERROR: x264 rejected parameter '%s'\n", str.c_str());
152                         }
153                 } else {
154                         const string key = str.substr(0, pos);
155                         const string value = str.substr(pos + 1);
156                         if (x264_param_parse(&param, 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());
159                         }
160                 }
161         }
162
163         x264_param_apply_profile(&param, "high");
164
165         param.b_repeat_headers = !wants_global_headers;
166
167         x264 = x264_encoder_open(&param);
168         if (x264 == nullptr) {
169                 fprintf(stderr, "ERROR: x264 initialization failed.\n");
170                 exit(1);
171         }
172
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));
175         }
176
177         if (wants_global_headers) {
178                 x264_nal_t *nal;
179                 int num_nal;
180
181                 x264_encoder_headers(x264, &nal, &num_nal);
182
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);
187                         } else {
188                                 global_headers += string((const char *)nal[i].p_payload, nal[i].i_payload);
189                         }
190                 }
191         }
192 }
193
194 void X264Encoder::encoder_thread_func()
195 {
196         if (nice(5) == -1) {  // Note that x264 further nices some of its threads.
197                 perror("nice()");
198                 // No exit; it's not fatal.
199         }
200         init_x264();
201         x264_init_done = true;
202
203         bool frames_left;
204
205         do {
206                 QueuedFrame qf;
207
208                 // Wait for a queued frame, then dequeue it.
209                 {
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();
214                                 queued_frames.pop();
215                         } else {
216                                 qf.pts = -1;
217                                 qf.duration = -1;
218                                 qf.data = nullptr;
219                         }
220
221                         frames_left = !queued_frames.empty();
222                 }
223
224                 encode_frame(qf);
225                 
226                 {
227                         lock_guard<mutex> lock(mu);
228                         free_frames.push(qf.data);
229                 }
230
231                 // We should quit only if the should_quit flag is set _and_ we have nothing
232                 // in either queue.
233         } while (!should_quit || frames_left || x264_encoder_delayed_frames(x264) > 0);
234
235         x264_encoder_close(x264);
236 }
237
238 void X264Encoder::encode_frame(X264Encoder::QueuedFrame qf)
239 {
240         x264_nal_t *nal = nullptr;
241         int num_nal = 0;
242         x264_picture_t pic;
243         x264_picture_t *input_pic = nullptr;
244
245         if (qf.data) {
246                 x264_picture_init(&pic);
247
248                 pic.i_pts = qf.pts;
249                 pic.img.i_csp = X264_CSP_NV12;
250                 pic.img.i_plane = 2;
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));
256
257                 input_pic = &pic;
258
259                 frames_being_encoded[qf.pts] = qf.received_ts;
260         }
261
262         // See if we have a new bitrate to change to.
263         unsigned new_rate = new_bitrate_kbit.exchange(0);  // Read and clear.
264         if (new_rate != 0) {
265                 if (speed_control) {
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);
269                         });
270                 } else {
271                         x264_param_t param;
272                         x264_encoder_parameters(x264, &param);
273                         param.rc.i_bitrate = new_rate;
274                         update_vbv_settings(&param);
275                         x264_encoder_reconfig(x264, &param);
276                 }
277         }
278
279         if (speed_control) {
280                 speed_control->before_frame(float(free_frames.size()) / X264_QUEUE_LENGTH, X264_QUEUE_LENGTH, 1e6 * qf.duration / TIMEBASE);
281         }
282         x264_encoder_encode(x264, &nal, &num_nal, input_pic, &pic);
283         if (speed_control) {
284                 speed_control->after_frame();
285         }
286
287         if (num_nal == 0) return;
288
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);
292
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),
296                         &frameno);
297         } else {
298                 assert(false);
299         }
300
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;
306         }
307
308         unique_ptr<uint8_t[]> data(new uint8_t[num_bytes]);
309         uint8_t *ptr = data.get();
310
311         if (!buffered_sei.empty()) {
312                 memcpy(ptr, buffered_sei.data(), buffered_sei.size());
313                 ptr += buffered_sei.size();
314                 buffered_sei.clear();
315         }
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;
319         }
320
321         AVPacket pkt;
322         memset(&pkt, 0, sizeof(pkt));
323         pkt.buf = nullptr;
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;
329         } else {
330                 pkt.flags = 0;
331         }
332         pkt.duration = reinterpret_cast<intptr_t>(pic.opaque);
333
334         mux->add_packet(pkt, pic.i_pts, pic.i_dts);
335 }