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