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