]> git.sesse.net Git - nageru/blob - quicksync_encoder_impl.h
Rename ui_foo.ui to foo.ui; seemingly, it is more standard.
[nageru] / quicksync_encoder_impl.h
1 #ifndef _QUICKSYNC_ENCODER_IMPL_H
2 #define _QUICKSYNC_ENCODER_IMPL_H 1
3
4 #include <epoxy/egl.h>
5 #include <movit/image_format.h>
6 #include <va/va.h>
7
8 #include <condition_variable>
9 #include <map>
10 #include <memory>
11 #include <mutex>
12 #include <queue>
13 #include <string>
14 #include <stack>
15 #include <thread>
16 #include <unordered_map>
17
18 #include "audio_encoder.h"
19 #include "defs.h"
20 #include "timebase.h"
21 #include "print_latency.h"
22 #include "ref_counted_gl_sync.h"
23
24 #define SURFACE_NUM 16 /* 16 surfaces for source YUV */
25 #define MAX_NUM_REF1 16 // Seemingly a hardware-fixed value, not related to SURFACE_NUM
26 #define MAX_NUM_REF2 32 // Seemingly a hardware-fixed value, not related to SURFACE_NUM
27
28 struct __bitstream {
29     unsigned int *buffer;
30     int bit_offset;
31     int max_size_in_dword;
32 };
33 typedef struct __bitstream bitstream;
34
35 namespace movit {
36 class ResourcePool;
37 }
38 class DiskSpaceEstimator;
39 class QSurface;
40 class X264Encoder;
41
42 struct VADisplayWithCleanup {
43         ~VADisplayWithCleanup();
44
45         VADisplay va_dpy;
46         Display *x11_display = nullptr;
47         bool can_use_zerocopy = true;
48         int drm_fd = -1;
49 };
50 std::unique_ptr<VADisplayWithCleanup> va_open_display(const std::string &va_display);  // Can return nullptr on failure.
51
52 class QuickSyncEncoderImpl {
53 public:
54         QuickSyncEncoderImpl(const std::string &filename, movit::ResourcePool *resource_pool, QSurface *surface, const std::string &va_display, int width, int height, AVOutputFormat *oformat, X264Encoder *x264_encoder, DiskSpaceEstimator *disk_space_estimator);
55         ~QuickSyncEncoderImpl();
56         void add_audio(int64_t pts, std::vector<float> audio);
57         bool is_zerocopy() const;
58         bool begin_frame(int64_t pts, int64_t duration, movit::YCbCrLumaCoefficients ycbcr_coefficients, const std::vector<RefCountedFrame> &input_frames, GLuint *y_tex, GLuint *cbcr_tex);
59         RefCountedGLsync end_frame();
60         void shutdown();
61         void close_file();
62         void release_gl_resources();
63         void set_stream_mux(Mux *mux)
64         {
65                 stream_mux = mux;
66         }
67
68         // So we never get negative dts.
69         int64_t global_delay() const {
70                 return int64_t(ip_period - 1) * (TIMEBASE / MAX_FPS);
71         }
72
73 private:
74         struct storage_task {
75                 unsigned long long display_order;
76                 int frame_type;
77                 std::vector<float> audio;
78                 int64_t pts, dts, duration;
79                 movit::YCbCrLumaCoefficients ycbcr_coefficients;
80                 ReceivedTimestamps received_ts;
81                 std::vector<size_t> ref_display_frame_numbers;
82         };
83         struct PendingFrame {
84                 RefCountedGLsync fence;
85                 std::vector<RefCountedFrame> input_frames;
86                 int64_t pts, duration;
87                 movit::YCbCrLumaCoefficients ycbcr_coefficients;
88         };
89         struct GLSurface {
90                 // Only if x264_video_to_disk == false.
91                 VASurfaceID src_surface, ref_surface;
92                 VABufferID coded_buf;
93                 VAImage surface_image;
94
95                 // Only if use_zerocopy == true (which implies x264_video_to_disk == false).
96                 GLuint y_tex, cbcr_tex;
97                 EGLImage y_egl_image, cbcr_egl_image;
98
99                 // Only if use_zerocopy == false.
100                 GLuint pbo;
101                 uint8_t *y_ptr, *cbcr_ptr;
102                 size_t y_offset, cbcr_offset;
103
104                 // Surfaces can be busy (have refcount > 0) for a variety of
105                 // reasons: First of all because they belong to a frame that's
106                 // under encoding. But also reference frames take refcounts;
107                 // while a frame is being encoded, all its reference frames
108                 // also have increased refcounts so that they are not dropped.
109                 // Similarly, just being in <reference_frames> increases the
110                 // refcount. Until it is back to zero, the surface cannot be given
111                 // out for encoding another frame. Use release_gl_surface()
112                 // to reduce the refcount, which will free the surface if
113                 // the refcount reaches zero.
114                 //
115                 // Protected by storage_task_queue_mutex.
116                 int refcount = 0;
117         };
118
119         void open_output_file(const std::string &filename);
120         void encode_thread_func();
121         void encode_remaining_frames_as_p(int encoding_frame_num, int gop_start_display_frame_num, int64_t last_dts);
122         void add_packet_for_uncompressed_frame(int64_t pts, int64_t duration, const uint8_t *data);
123         void pass_frame(PendingFrame frame, int display_frame_num, int64_t pts, int64_t duration);
124         void encode_frame(PendingFrame frame, int encoding_frame_num, int display_frame_num, int gop_start_display_frame_num,
125                           int frame_type, int64_t pts, int64_t dts, int64_t duration, movit::YCbCrLumaCoefficients ycbcr_coefficients);
126         void storage_task_thread();
127         void storage_task_enqueue(storage_task task);
128         void save_codeddata(GLSurface *surf, storage_task task);
129         int render_packedsequence(movit::YCbCrLumaCoefficients ycbcr_coefficients);
130         int render_packedpicture();
131         void render_packedslice();
132         int render_sequence();
133         int render_picture(GLSurface *surf, int frame_type, int display_frame_num, int gop_start_display_frame_num);
134         void sps_rbsp(movit::YCbCrLumaCoefficients ycbcr_coefficients, bitstream *bs);
135         void pps_rbsp(bitstream *bs);
136         int build_packed_pic_buffer(unsigned char **header_buffer);
137         int render_slice(int encoding_frame_num, int display_frame_num, int gop_start_display_frame_num, int frame_type);
138         void slice_header(bitstream *bs);
139         int build_packed_seq_buffer(movit::YCbCrLumaCoefficients ycbcr_coefficients, unsigned char **header_buffer);
140         int build_packed_slice_buffer(unsigned char **header_buffer);
141         int init_va(const std::string &va_display);
142         void enable_zerocopy_if_possible();
143         int setup_encode();
144         void release_encode();
145         void update_ReferenceFrames(int current_display_frame, int frame_type);
146         void update_RefPicList_P(VAPictureH264 RefPicList0_P[MAX_NUM_REF2]);
147         void update_RefPicList_B(VAPictureH264 RefPicList0_B[MAX_NUM_REF2], VAPictureH264 RefPicList1_B[MAX_NUM_REF2]);
148         GLSurface *allocate_gl_surface();
149         void release_gl_surface(size_t display_frame_num);
150
151         bool is_shutdown = false;
152         bool has_released_gl_resources = false;
153         std::atomic<bool> use_zerocopy{false};
154
155         std::thread encode_thread, storage_thread;
156
157         std::mutex storage_task_queue_mutex;
158         std::condition_variable storage_task_queue_changed;
159         std::queue<storage_task> storage_task_queue;  // protected by storage_task_queue_mutex
160         bool storage_thread_should_quit = false;  // protected by storage_task_queue_mutex
161
162         std::mutex frame_queue_mutex;
163         std::condition_variable frame_queue_nonempty;
164         bool encode_thread_should_quit = false;  // under frame_queue_mutex
165
166         int current_storage_frame;
167
168         PendingFrame current_video_frame;  // Used only between begin_frame() and end_frame().
169         std::queue<PendingFrame> pending_video_frames;  // under frame_queue_mutex
170         movit::ResourcePool *resource_pool;
171         QSurface *surface;
172
173         // Frames that are done rendering and passed on to x264 (if enabled),
174         // but have not been encoded by Quick Sync yet, and thus also not freed.
175         // The key is the display frame number.
176         std::map<int, PendingFrame> reorder_buffer;
177         int quicksync_encoding_frame_num = 0;
178
179         std::mutex file_audio_encoder_mutex;
180         std::unique_ptr<AudioEncoder> file_audio_encoder;
181
182         X264Encoder *x264_encoder;  // nullptr if not using x264.
183
184         Mux* stream_mux = nullptr;  // To HTTP.
185         std::unique_ptr<Mux> file_mux;  // To local disk.
186
187         // Encoder parameters
188         std::unique_ptr<VADisplayWithCleanup> va_dpy;
189         VAProfile h264_profile = (VAProfile)~0;
190         VAConfigAttrib config_attrib[VAConfigAttribTypeMax];
191         int config_attrib_num = 0, enc_packed_header_idx;
192
193         GLSurface gl_surfaces[SURFACE_NUM];
194
195         // For all frames in encoding (refcount > 0), a pointer into gl_surfaces
196         // for the surface used for that frame. Protected by storage_task_queue_mutex.
197         // The key is display frame number.
198         std::unordered_map<size_t, GLSurface *> surface_for_frame;
199
200         VAConfigID config_id;
201         VAContextID context_id;
202         VAEncSequenceParameterBufferH264 seq_param;
203         VAEncPictureParameterBufferH264 pic_param;
204         VAEncSliceParameterBufferH264 slice_param;
205         VAPictureH264 CurrentCurrPic;
206
207         struct ReferenceFrame {
208                 VAPictureH264 pic;
209                 int display_number;  // To track reference counts.
210         };
211         std::deque<ReferenceFrame> reference_frames;
212
213         // Static quality settings.
214         static constexpr unsigned int frame_bitrate = 15000000 / 60;  // Doesn't really matter; only initial_qp does.
215         static constexpr unsigned int num_ref_frames = 2;
216         static constexpr int initial_qp = 15;
217         static constexpr int minimal_qp = 0;
218         static constexpr int intra_period = 30;
219         static constexpr int intra_idr_period = MAX_FPS;  // About a second; more at lower frame rates. Not ideal.
220
221         // Quality settings that are meant to be static, but might be overridden
222         // by the profile.
223         int constraint_set_flag = 0;
224         int h264_packedheader = 0; /* support pack header? */
225         int h264_maxref = (1<<16|1);
226         int h264_entropy_mode = 1; /* cabac */
227         int ip_period = 3;
228
229         unsigned int current_ref_frame_num = 0;  // Encoding frame order within this GOP, sans B-frames.
230
231         int frame_width;
232         int frame_height;
233         int frame_width_mbaligned;
234         int frame_height_mbaligned;
235
236         DiskSpaceEstimator *disk_space_estimator;
237 };
238
239 #endif  // !defined(_QUICKSYNC_ENCODER_IMPL_H)