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