forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

lib.rs332 lines, 11.1 KiBHistoryRawDownload
1//! H.264 encoder over Vulkan Video: IDR and P pictures, one reference, I420 in.
2#![forbid(unsafe_code)]
3#![deny(missing_docs)]
4
5use std::collections::VecDeque;
6
7use history::History;
8use vk_video_ffi::{H264EncodeConfig, H264EncodeSession, H264Picture, H264Ref, LOG2_MAX_FRAME_NUM};
9
10mod av1;
11mod h265;
12mod history;
13
14pub use av1::{Av1Encoder, Av1EncoderConfig};
15pub use h265::{H265Encoder, H265EncoderConfig};
16#[cfg(windows)]
17pub use vk_video_ffi::{D3d11Pool, D3d11Texture, d3d11_importable, windows};
18#[cfg(target_os = "linux")]
19pub use vk_video_ffi::{DmaBuf, DmaBufExport, DmaBufFormat, DmaBufPlane, dup_raw_fd, read_dmabuf, rgb_import_modifiers};
20pub use vk_video_ffi::{
21 Av1Cdef, Av1ColorConfig, Av1DecodeConfig, Av1DecodePicture, Av1DecodeSession, Av1DeltaParams,
22 Av1FrameHeader, Av1FrameType, Av1GlobalMotion, Av1InterpolationFilter, Av1LoopFilter,
23 Av1LoopRestoration, Av1Quantization, Av1RefSlot, Av1Restoration, Av1Segmentation,
24 Av1SequenceHeader, Av1TileInfo, Av1TimingInfo, Av1TxMode, Av1WarpModel, Codec, CodecProfile, Colour,
25 Direction, Error, Gpu, H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps,
26 H264Profile, H264RefSlot, H264Sps, H265DecPicBufMgr, H265DecodeConfig, H265DecodePicture,
27 H265DecodeSession, H265LongTermRefPicSps, H265Pcm, H265Pps, H265ProfileTierLevel, H265RefSlot,
28 H265ScalingLists, H265ShortTermRefPicSet, H265Sps, H265Vps, RateControl, ScalingLists,
29 Vp9ColorConfig, Vp9DecodeConfig, Vp9DecodePicture, Vp9DecodeSession, Vp9FrameHeader,
30 Vp9InterpolationFilter, Vp9LoopFilter, Vp9Segmentation,
31};
32
33/// Encoder settings.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub struct H264EncoderConfig {
36 /// Width in luma samples, even.
37 pub width: u32,
38 /// Height in luma samples, even.
39 pub height: u32,
40 /// Frame rate as numerator and denominator.
41 pub fps: (u32, u32),
42 /// Frames from one IDR to the next, at least 1.
43 pub gop_size: u32,
44 /// Rate control.
45 pub rate: RateControl,
46 /// H.264 profile.
47 pub profile: H264Profile,
48 /// `level_idc`, clamped to the driver maximum.
49 pub level: u8,
50 /// Colour description for the VUI, or none.
51 pub colour: Option<Colour>,
52 /// Speed/quality trade-off as in ec-hw's `EncoderConfig::quality`: 0 for the default level, 1 for the driver's best, each step up one level faster.
53 pub quality: u32,
54}
55
56/// One coded frame, Annex-B. Keyframes carry SPS and PPS before the slice.
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct CodedFrame {
59 /// Annex-B bytes.
60 pub data: Vec<u8>,
61 /// True when the frame is an IDR picture.
62 pub keyframe: bool,
63 /// True when the frame references an acknowledged older picture instead of the previous one.
64 pub recovery: bool,
65 /// Submission index of the frame, the handle [`Av1Encoder::ack`] takes.
66 pub id: u64,
67}
68
69#[derive(Debug, Clone, Copy, Default)]
70pub(crate) struct Meta {
71 pub(crate) keyframe: bool,
72 pub(crate) recovery: bool,
73 pub(crate) id: u64,
74}
75
76#[derive(Default)]
77pub(crate) struct Flight(VecDeque<Meta>);
78
79impl Flight {
80 pub(crate) fn push(&mut self, meta: Meta) {
81 self.0.push_back(meta);
82 }
83
84 pub(crate) fn pop(&mut self) -> Meta {
85 self.0.pop_front().unwrap_or_default()
86 }
87}
88
89pub(crate) fn last_frame(
90 first: Option<CodedFrame>,
91 rest: Vec<CodedFrame>,
92) -> Result<CodedFrame, Error> {
93 rest.into_iter()
94 .last()
95 .or(first)
96 .ok_or_else(|| Error::Invalid("no coded frame".into()))
97}
98
99/// H.264 encoder: GOP, frame_num, POC and DPB slot bookkeeping over [`H264EncodeSession`].
100pub struct H264Encoder {
101 session: H264EncodeSession,
102 parameter_sets: Vec<u8>,
103 width: usize,
104 height: usize,
105 gop_size: u32,
106 position: u32,
107 frame_num: u32,
108 poc: i32,
109 idr_pic_id: u16,
110 history: History<(u32, i32)>,
111 uv: Vec<u8>,
112 flight: Flight,
113}
114
115impl H264Encoder {
116 /// Opens an encoder session on `gpu`.
117 pub fn new(gpu: &Gpu, cfg: H264EncoderConfig) -> Result<Self, Error> {
118 if cfg.gop_size == 0 {
119 return Err(Error::Invalid("gop_size is zero".into()));
120 }
121 let session = H264EncodeSession::new(
122 gpu,
123 &H264EncodeConfig {
124 width: cfg.width,
125 height: cfg.height,
126 fps: cfg.fps,
127 rate: cfg.rate,
128 profile: cfg.profile,
129 level: cfg.level,
130 colour: cfg.colour,
131 quality: cfg.quality,
132 },
133 )?;
134 let parameter_sets = session.parameter_sets()?;
135 Ok(H264Encoder {
136 session,
137 parameter_sets,
138 width: cfg.width as usize,
139 height: cfg.height as usize,
140 gop_size: cfg.gop_size,
141 position: 0,
142 frame_num: 0,
143 poc: 0,
144 idr_pic_id: 0,
145 history: History::new(),
146 uv: vec![0; cfg.width as usize * cfg.height as usize / 2],
147 flight: Flight::default(),
148 })
149 }
150
151 /// Submits one I420 frame without waiting; returns the oldest frame once a second one is queued.
152 pub fn submit(
153 &mut self,
154 y: &[u8],
155 u: &[u8],
156 v: &[u8],
157 force_keyframe: bool,
158 ) -> Result<Option<CodedFrame>, Error> {
159 let chroma = self.width * self.height / 4;
160 if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma {
161 return Err(Error::Invalid("I420 plane size".into()));
162 }
163 for (i, pair) in self.uv.chunks_exact_mut(2).enumerate() {
164 pair[0] = u[i];
165 pair[1] = v[i];
166 }
167 let pic = self.next_picture(force_keyframe);
168 let out = self.session.submit(y, &self.uv, &pic)?;
169 Ok(out.map(|bytes| self.coded(bytes)))
170 }
171
172 /// Encodes one I420 frame; `force_keyframe` makes it an IDR and restarts the GOP.
173 pub fn encode(
174 &mut self,
175 y: &[u8],
176 u: &[u8],
177 v: &[u8],
178 force_keyframe: bool,
179 ) -> Result<CodedFrame, Error> {
180 let first = self.submit(y, u, v, force_keyframe)?;
181 let rest = self.flush()?;
182 last_frame(first, rest)
183 }
184
185 /// Waits for every submitted frame and returns them in order.
186 pub fn flush(&mut self) -> Result<Vec<CodedFrame>, Error> {
187 let bytes = self.session.flush()?;
188 Ok(bytes.into_iter().map(|b| self.coded(b)).collect())
189 }
190
191 /// Changes bitrate or frame rate; takes effect on the next frame.
192 pub fn set_rate(&mut self, rate: RateControl, fps: (u32, u32)) -> Result<(), Error> {
193 Ok(self.session.set_rate(rate, fps)?)
194 }
195
196 /// Submits one packed RGB frame (src_width x src_height, BGRx if `bgr`, else RGBx; row stride in bytes) without waiting.
197 pub fn submit_rgb(
198 &mut self,
199 rgb: &[u8],
200 src_width: u32,
201 src_height: u32,
202 stride_bytes: u32,
203 bgr: bool,
204 force_keyframe: bool,
205 ) -> Result<Option<CodedFrame>, Error> {
206 let pic = self.next_picture(force_keyframe);
207 let out = self
208 .session
209 .submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, &pic)?;
210 Ok(out.map(|bytes| self.coded(bytes)))
211 }
212
213 /// Encodes one packed RGB frame (src_width x src_height, BGRx if `bgr`, else RGBx; row stride in bytes), box-downscaled to the encoder size on the GPU.
214 pub fn encode_rgb(
215 &mut self,
216 rgb: &[u8],
217 src_width: u32,
218 src_height: u32,
219 stride_bytes: u32,
220 bgr: bool,
221 force_keyframe: bool,
222 ) -> Result<CodedFrame, Error> {
223 let first = self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, force_keyframe)?;
224 let rest = self.flush()?;
225 last_frame(first, rest)
226 }
227
228 /// Submits one shared D3D11 texture of the source size without waiting.
229 #[cfg(windows)]
230 pub fn submit_d3d11(
231 &mut self,
232 src: &D3d11Texture<'_>,
233 force_keyframe: bool,
234 ) -> Result<Option<CodedFrame>, Error> {
235 let pic = self.next_picture(force_keyframe);
236 let out = self.session.submit_d3d11(src, &pic)?;
237 Ok(out.map(|bytes| self.coded(bytes)))
238 }
239
240 /// Encodes one shared D3D11 texture of the source size (BGRA if `bgr`, else RGBA), downscaled to the encoder size on the GPU.
241 #[cfg(windows)]
242 pub fn encode_d3d11(
243 &mut self,
244 src: &D3d11Texture<'_>,
245 force_keyframe: bool,
246 ) -> Result<CodedFrame, Error> {
247 let first = self.submit_d3d11(src, force_keyframe)?;
248 let rest = self.flush()?;
249 last_frame(first, rest)
250 }
251
252 /// Submits one DMA-BUF frame of the source size without waiting.
253 #[cfg(target_os = "linux")]
254 pub fn submit_dmabuf(
255 &mut self,
256 src: &DmaBuf<'_>,
257 force_keyframe: bool,
258 ) -> Result<Option<CodedFrame>, Error> {
259 let pic = self.next_picture(force_keyframe);
260 let out = self.session.submit_dmabuf(src, &pic)?;
261 Ok(out.map(|bytes| self.coded(bytes)))
262 }
263
264 /// Encodes one DMA-BUF frame of the source size (BGRx if `bgr`, else RGBx), box-downscaled to the encoder size on the GPU.
265 #[cfg(target_os = "linux")]
266 pub fn encode_dmabuf(
267 &mut self,
268 src: &DmaBuf<'_>,
269 force_keyframe: bool,
270 ) -> Result<CodedFrame, Error> {
271 let first = self.submit_dmabuf(src, force_keyframe)?;
272 let rest = self.flush()?;
273 last_frame(first, rest)
274 }
275
276 fn next_picture(&mut self, force_keyframe: bool) -> H264Picture {
277 let step = self
278 .history
279 .next(force_keyframe || self.position >= self.gop_size);
280 if step.key {
281 self.frame_num = 0;
282 self.poc = 0;
283 } else {
284 self.frame_num = (self.frame_num + 1) % (1 << LOG2_MAX_FRAME_NUM);
285 self.poc += 2;
286 }
287 let pic = H264Picture {
288 idr: step.key,
289 idr_pic_id: self.idr_pic_id,
290 frame_num: self.frame_num,
291 poc: self.poc,
292 slot: step.slot,
293 reference: step.reference.map(|(slot, (frame_num, poc))| H264Ref { slot, frame_num, poc }),
294 };
295 self.history.store(&step, (self.frame_num, self.poc));
296 self.position = if step.key { 1 } else { self.position + 1 };
297 if step.key {
298 self.idr_pic_id = self.idr_pic_id.wrapping_add(1);
299 }
300 self.flight.push(Meta {
301 keyframe: step.key,
302 recovery: step.recovery,
303 id: step.id,
304 });
305 pic
306 }
307
308 /// The receiver decoded every frame up to `id` ([`CodedFrame::id`]); a recovery frame may reference one while it stays in the DPB.
309 pub fn ack(&mut self, id: u64) {
310 self.history.ack(id);
311 }
312
313 /// Make the next frame reference the newest acknowledged frame still held, or an IDR when none is.
314 pub fn recover(&mut self) {
315 self.history.arm();
316 }
317
318 fn coded(&mut self, bytes: Vec<u8>) -> CodedFrame {
319 let meta = self.flight.pop();
320 let data = if meta.keyframe {
321 [self.parameter_sets.as_slice(), bytes.as_slice()].concat()
322 } else {
323 bytes
324 };
325 CodedFrame {
326 data,
327 keyframe: meta.keyframe,
328 recovery: meta.recovery,
329 id: meta.id,
330 }
331 }
332}