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