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