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