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