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