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