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