]> git.sesse.net Git - nageru/blob - x264_encoder.cpp
Small refactoring in X264Encoder.
[nageru] / x264_encoder.cpp
1 #include <string.h>
2 #include <unistd.h>
3
4 #include "defs.h"
5 #include "flags.h"
6 #include "mux.h"
7 #include "timebase.h"
8 #include "x264_encoder.h"
9 #include "x264_speed_control.h"
10
11 extern "C" {
12 #include <libavformat/avformat.h>
13 }
14
15 using namespace std;
16
17 X264Encoder::X264Encoder(AVOutputFormat *oformat)
18         : wants_global_headers(oformat->flags & AVFMT_GLOBALHEADER)
19 {
20         frame_pool.reset(new uint8_t[WIDTH * HEIGHT * 2 * X264_QUEUE_LENGTH]);
21         for (unsigned i = 0; i < X264_QUEUE_LENGTH; ++i) {
22                 free_frames.push(frame_pool.get() + i * (WIDTH * HEIGHT * 2));
23         }
24         encoder_thread = thread(&X264Encoder::encoder_thread_func, this);
25 }
26
27 X264Encoder::~X264Encoder()
28 {
29         should_quit = true;
30         queued_frames_nonempty.notify_all();
31         encoder_thread.join();
32 }
33
34 void X264Encoder::add_frame(int64_t pts, int64_t duration, const uint8_t *data)
35 {
36         QueuedFrame qf;
37         qf.pts = pts;
38         qf.duration = duration;
39
40         {
41                 lock_guard<mutex> lock(mu);
42                 if (free_frames.empty()) {
43                         fprintf(stderr, "WARNING: x264 queue full, dropping frame with pts %ld\n", pts);
44                         return;
45                 }
46
47                 qf.data = free_frames.front();
48                 free_frames.pop();
49         }
50
51         memcpy(qf.data, data, WIDTH * HEIGHT * 2);
52
53         {
54                 lock_guard<mutex> lock(mu);
55                 queued_frames.push(qf);
56                 queued_frames_nonempty.notify_all();
57         }
58 }
59         
60 void X264Encoder::init_x264()
61 {
62         x264_param_t param;
63         x264_param_default_preset(&param, global_flags.x264_preset.c_str(), global_flags.x264_tune.c_str());
64
65         param.i_width = WIDTH;
66         param.i_height = HEIGHT;
67         param.i_csp = X264_CSP_NV12;
68         param.b_vfr_input = 1;
69         param.i_timebase_num = 1;
70         param.i_timebase_den = TIMEBASE;
71         param.i_keyint_max = 50; // About one second.
72         if (global_flags.x264_speedcontrol) {
73                 param.i_frame_reference = 16;  // Because speedcontrol is never allowed to change this above what we set at start.
74         }
75
76         // NOTE: These should be in sync with the ones in h264encode.cpp (sbs_rbsp()).
77         param.vui.i_vidformat = 5;  // Unspecified.
78         param.vui.b_fullrange = 0;
79         param.vui.i_colorprim = 1;  // BT.709.
80         param.vui.i_transfer = 2;  // Unspecified (since we use sRGB).
81         param.vui.i_colmatrix = 6;  // BT.601/SMPTE 170M.
82
83
84         param.rc.i_rc_method = X264_RC_ABR;
85         param.rc.i_bitrate = global_flags.x264_bitrate;
86         if (global_flags.x264_vbv_buffer_size < 0) {
87                 param.rc.i_vbv_buffer_size = param.rc.i_bitrate;  // One-second VBV.
88         } else {
89                 param.rc.i_vbv_buffer_size = global_flags.x264_vbv_buffer_size;
90         }
91         if (global_flags.x264_vbv_max_bitrate < 0) {
92                 param.rc.i_vbv_max_bitrate = param.rc.i_bitrate;  // CBR.
93         } else {
94                 param.rc.i_vbv_max_bitrate = global_flags.x264_vbv_max_bitrate;
95         }
96
97         // Occasionally players have problem with extremely low quantizers;
98         // be on the safe side. Shouldn't affect quality in any meaningful way.
99         param.rc.i_qp_min = 5;
100
101         // TODO: more flags here, via x264_param_parse().
102
103         x264_param_apply_profile(&param, "high");
104
105         param.b_repeat_headers = !wants_global_headers;
106
107         x264 = x264_encoder_open(&param);
108         if (x264 == nullptr) {
109                 fprintf(stderr, "ERROR: x264 initialization failed.\n");
110                 exit(1);
111         }
112
113         if (global_flags.x264_speedcontrol) {
114                 speed_control.reset(new X264SpeedControl(x264, /*f_speed=*/1.0f, X264_QUEUE_LENGTH, /*f_buffer_init=*/1.0f));
115         }
116
117         if (wants_global_headers) {
118                 x264_nal_t *nal;
119                 int num_nal;
120
121                 x264_encoder_headers(x264, &nal, &num_nal);
122
123                 for (int i = 0; i < num_nal; ++i) {
124                         if (nal[i].i_type == NAL_SEI) {
125                                 // Don't put the SEI in extradata; make it part of the first frame instead.
126                                 buffered_sei += string((const char *)nal[i].p_payload, nal[i].i_payload);
127                         } else {
128                                 global_headers += string((const char *)nal[i].p_payload, nal[i].i_payload);
129                         }
130                 }
131         }
132 }
133
134 void X264Encoder::encoder_thread_func()
135 {
136         nice(5);  // Note that x264 further nices some of its threads.
137         init_x264();
138
139         bool frames_left;
140
141         do {
142                 QueuedFrame qf;
143
144                 // Wait for a queued frame, then dequeue it.
145                 {
146                         unique_lock<mutex> lock(mu);
147                         queued_frames_nonempty.wait(lock, [this]() { return !queued_frames.empty() || should_quit; });
148                         if (!queued_frames.empty()) {
149                                 qf = queued_frames.front();
150                                 queued_frames.pop();
151                         } else {
152                                 qf.pts = -1;
153                                 qf.duration = -1;
154                                 qf.data = nullptr;
155                         }
156
157                         frames_left = !queued_frames.empty();
158                 }
159
160                 encode_frame(qf);
161                 
162                 {
163                         lock_guard<mutex> lock(mu);
164                         free_frames.push(qf.data);
165                 }
166
167                 // We should quit only if the should_quit flag is set _and_ we have nothing
168                 // in either queue.
169         } while (!should_quit || frames_left || x264_encoder_delayed_frames(x264) > 0);
170
171         x264_encoder_close(x264);
172 }
173
174 void X264Encoder::encode_frame(X264Encoder::QueuedFrame qf)
175 {
176         x264_nal_t *nal = nullptr;
177         int num_nal = 0;
178         x264_picture_t pic;
179         x264_picture_t *input_pic = nullptr;
180
181         if (qf.data) {
182                 x264_picture_init(&pic);
183
184                 pic.i_pts = qf.pts;
185                 pic.img.i_csp = X264_CSP_NV12;
186                 pic.img.i_plane = 2;
187                 pic.img.plane[0] = qf.data;
188                 pic.img.i_stride[0] = WIDTH;
189                 pic.img.plane[1] = qf.data + WIDTH * HEIGHT;
190                 pic.img.i_stride[1] = WIDTH / 2 * sizeof(uint16_t);
191                 pic.opaque = reinterpret_cast<void *>(intptr_t(qf.duration));
192
193                 input_pic = &pic;
194         }
195
196         if (speed_control) {
197                 speed_control->before_frame(float(free_frames.size()) / X264_QUEUE_LENGTH, X264_QUEUE_LENGTH, 1e6 * qf.duration / TIMEBASE);
198         }
199         x264_encoder_encode(x264, &nal, &num_nal, input_pic, &pic);
200         if (speed_control) {
201                 speed_control->after_frame();
202         }
203
204         // We really need one AVPacket for the entire frame, it seems,
205         // so combine it all.
206         size_t num_bytes = buffered_sei.size();
207         for (int i = 0; i < num_nal; ++i) {
208                 num_bytes += nal[i].i_payload;
209         }
210
211         unique_ptr<uint8_t[]> data(new uint8_t[num_bytes]);
212         uint8_t *ptr = data.get();
213
214         if (!buffered_sei.empty()) {
215                 memcpy(ptr, buffered_sei.data(), buffered_sei.size());
216                 ptr += buffered_sei.size();
217                 buffered_sei.clear();
218         }
219         for (int i = 0; i < num_nal; ++i) {
220                 memcpy(ptr, nal[i].p_payload, nal[i].i_payload);
221                 ptr += nal[i].i_payload;
222         }
223
224         AVPacket pkt;
225         memset(&pkt, 0, sizeof(pkt));
226         pkt.buf = nullptr;
227         pkt.data = data.get();
228         pkt.size = num_bytes;
229         pkt.stream_index = 0;
230         if (pic.b_keyframe) {
231                 pkt.flags = AV_PKT_FLAG_KEY;
232         } else {
233                 pkt.flags = 0;
234         }
235         pkt.duration = reinterpret_cast<intptr_t>(pic.opaque);
236
237         mux->add_packet(pkt, pic.i_pts, pic.i_dts);
238 }