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