]> git.sesse.net Git - nageru/blob - x264encode.cpp
Fix a shutdown issue in X264Encoder.
[nageru] / x264encode.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 "x264encode.h"
9
10 extern "C" {
11 #include <libavformat/avformat.h>
12 }
13
14 using namespace std;
15
16 X264Encoder::X264Encoder(Mux *mux)
17         : mux(mux)
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, const uint8_t *data)
34 {
35         QueuedFrame qf;
36         qf.pts = pts;
37
38         {
39                 lock_guard<mutex> lock(mu);
40                 if (free_frames.empty()) {
41                         fprintf(stderr, "WARNING: x264 queue full, dropping frame with pts %ld\n", pts);
42                         return;
43                 }
44
45                 qf.data = free_frames.front();
46                 free_frames.pop();
47         }
48
49         memcpy(qf.data, data, WIDTH * HEIGHT * 2);
50
51         {
52                 lock_guard<mutex> lock(mu);
53                 queued_frames.push(qf);
54                 queued_frames_nonempty.notify_all();
55         }
56 }
57         
58 void X264Encoder::init_x264()
59 {
60         x264_param_t param;
61         x264_param_default_preset(&param, global_flags.x264_preset.c_str(), global_flags.x264_tune.c_str());
62
63         param.i_width = WIDTH;
64         param.i_height = HEIGHT;
65         param.i_csp = X264_CSP_NV12;
66         param.b_vfr_input = 1;
67         param.i_timebase_num = 1;
68         param.i_timebase_den = TIMEBASE;
69         param.i_keyint_max = 50; // About one second.
70
71         // NOTE: These should be in sync with the ones in h264encode.cpp (sbs_rbsp()).
72         param.vui.i_vidformat = 5;  // Unspecified.
73         param.vui.b_fullrange = 0;
74         param.vui.i_colorprim = 1;  // BT.709.
75         param.vui.i_transfer = 2;  // Unspecified (since we use sRGB).
76         param.vui.i_colmatrix = 6;  // BT.601/SMPTE 170M.
77
78         // 4.5 Mbit/sec, CBR.
79         param.rc.i_rc_method = X264_RC_ABR;
80         param.rc.i_bitrate = 4500;
81
82         // One-second VBV.
83         param.rc.i_vbv_max_bitrate = 4500;
84         param.rc.i_vbv_buffer_size = 4500;
85
86         // TODO: more flags here, via x264_param_parse().
87
88         x264_param_apply_profile(&param, "high");
89
90         x264 = x264_encoder_open(&param);
91         if (x264 == nullptr) {
92                 fprintf(stderr, "ERROR: x264 initialization failed.\n");
93                 exit(1);
94         }
95 }
96
97 void X264Encoder::encoder_thread_func()
98 {
99         nice(5);  // Note that x264 further nices some of its threads.
100         init_x264();
101
102         bool frames_left;
103
104         do {
105                 QueuedFrame qf;
106
107                 // Wait for a queued frame, then dequeue it.
108                 {
109                         unique_lock<mutex> lock(mu);
110                         queued_frames_nonempty.wait(lock, [this]() { return !queued_frames.empty() || should_quit; });
111                         if (!queued_frames.empty()) {
112                                 qf = queued_frames.front();
113                                 queued_frames.pop();
114                         } else {
115                                 qf.pts = -1;
116                                 qf.data = nullptr;
117                         }
118
119                         frames_left = !queued_frames.empty();
120                 }
121
122                 encode_frame(qf);
123                 
124                 {
125                         lock_guard<mutex> lock(mu);
126                         free_frames.push(qf.data);
127                 }
128
129                 // We should quit only if the should_quit flag is set _and_ we have nothing
130                 // in either queue.
131         } while (!should_quit || frames_left || x264_encoder_delayed_frames(x264) > 0);
132
133         x264_encoder_close(x264);
134 }
135
136 void X264Encoder::encode_frame(X264Encoder::QueuedFrame qf)
137 {
138         x264_nal_t *nal = nullptr;
139         int num_nal = 0;
140         x264_picture_t pic;
141
142         if (qf.data) {
143                 x264_picture_init(&pic);
144
145                 pic.i_pts = qf.pts;
146                 pic.img.i_csp = X264_CSP_NV12;
147                 pic.img.i_plane = 2;
148                 pic.img.plane[0] = qf.data;
149                 pic.img.i_stride[0] = WIDTH;
150                 pic.img.plane[1] = qf.data + WIDTH * HEIGHT;
151                 pic.img.i_stride[1] = WIDTH / 2 * sizeof(uint16_t);
152
153                 x264_encoder_encode(x264, &nal, &num_nal, &pic, &pic);
154         } else {
155                 x264_encoder_encode(x264, &nal, &num_nal, nullptr, &pic);
156         }
157
158         // We really need one AVPacket for the entire frame, it seems,
159         // so combine it all.
160         size_t num_bytes = 0;
161         for (int i = 0; i < num_nal; ++i) {
162                 num_bytes += nal[i].i_payload;
163         }
164
165         unique_ptr<uint8_t[]> data(new uint8_t[num_bytes]);
166         uint8_t *ptr = data.get();
167
168         for (int i = 0; i < num_nal; ++i) {
169                 memcpy(ptr, nal[i].p_payload, nal[i].i_payload);
170                 ptr += nal[i].i_payload;
171         }
172
173         AVPacket pkt;
174         memset(&pkt, 0, sizeof(pkt));
175         pkt.buf = nullptr;
176         pkt.data = data.get();
177         pkt.size = num_bytes;
178         pkt.stream_index = 0;
179         if (pic.b_keyframe) {
180                 pkt.flags = AV_PKT_FLAG_KEY;
181         } else {
182                 pkt.flags = 0;
183         }
184
185         mux->add_packet(pkt, pic.i_pts, pic.i_dts);
186 }