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