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