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