forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust381.4 MiBcdccbc2Tahinli9 hours ago4263 commits

lib.rs334 lines, 11.2 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) -> Result<Meta, Error> {
85 self.0
86 .pop_front()
87 .ok_or_else(|| Error::Invalid("frame queue out of step".into()))
88 }
89}
90
91pub(crate) fn last_frame(
92 first: Option<CodedFrame>,
93 rest: Vec<CodedFrame>,
94) -> Result<CodedFrame, Error> {
95 rest.into_iter()
96 .last()
97 .or(first)
98 .ok_or_else(|| Error::Invalid("no coded frame".into()))
99}
100
101/// H.264 encoder: GOP, frame_num, POC and DPB slot bookkeeping over [`H264EncodeSession`].
102pub struct H264Encoder {
103 session: H264EncodeSession,
104 parameter_sets: Vec<u8>,
105 width: usize,
106 height: usize,
107 gop_size: u32,
108 position: u32,
109 frame_num: u32,
110 poc: i32,
111 idr_pic_id: u16,
112 history: History<(u32, i32)>,
113 uv: Vec<u8>,
114 flight: Flight,
115}
116
117impl H264Encoder {
118 /// Opens an encoder session on `gpu`.
119 pub fn new(gpu: &Gpu, cfg: H264EncoderConfig) -> Result<Self, Error> {
120 if cfg.gop_size == 0 {
121 return Err(Error::Invalid("gop_size is zero".into()));
122 }
123 let session = H264EncodeSession::new(
124 gpu,
125 &H264EncodeConfig {
126 width: cfg.width,
127 height: cfg.height,
128 fps: cfg.fps,
129 rate: cfg.rate,
130 profile: cfg.profile,
131 level: cfg.level,
132 colour: cfg.colour,
133 quality: cfg.quality,
134 },
135 )?;
136 let parameter_sets = session.parameter_sets()?;
137 Ok(H264Encoder {
138 session,
139 parameter_sets,
140 width: cfg.width as usize,
141 height: cfg.height as usize,
142 gop_size: cfg.gop_size,
143 position: 0,
144 frame_num: 0,
145 poc: 0,
146 idr_pic_id: 0,
147 history: History::new(),
148 uv: vec![0; cfg.width as usize * cfg.height as usize / 2],
149 flight: Flight::default(),
150 })
151 }
152
153 /// Submits one I420 frame without waiting; returns the oldest frame once a second one is queued.
154 pub fn submit(
155 &mut self,
156 y: &[u8],
157 u: &[u8],
158 v: &[u8],
159 force_keyframe: bool,
160 ) -> Result<Option<CodedFrame>, Error> {
161 let chroma = self.width * self.height / 4;
162 if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma {
163 return Err(Error::Invalid("I420 plane size".into()));
164 }
165 for (i, pair) in self.uv.chunks_exact_mut(2).enumerate() {
166 pair[0] = u[i];
167 pair[1] = v[i];
168 }
169 let pic = self.next_picture(force_keyframe);
170 let out = self.session.submit(y, &self.uv, &pic)?;
171 out.map(|bytes| self.coded(bytes)).transpose()
172 }
173
174 /// Encodes one I420 frame; `force_keyframe` makes it an IDR and restarts the GOP.
175 pub fn encode(
176 &mut self,
177 y: &[u8],
178 u: &[u8],
179 v: &[u8],
180 force_keyframe: bool,
181 ) -> Result<CodedFrame, Error> {
182 let first = self.submit(y, u, v, force_keyframe)?;
183 let rest = self.flush()?;
184 last_frame(first, rest)
185 }
186
187 /// Waits for every submitted frame and returns them in order.
188 pub fn flush(&mut self) -> Result<Vec<CodedFrame>, Error> {
189 let bytes = self.session.flush()?;
190 bytes.into_iter().map(|b| self.coded(b)).collect()
191 }
192
193 /// Changes bitrate or frame rate; takes effect on the next frame.
194 pub fn set_rate(&mut self, rate: RateControl, fps: (u32, u32)) -> Result<(), Error> {
195 Ok(self.session.set_rate(rate, fps)?)
196 }
197
198 /// Submits one packed RGB frame (src_width x src_height, BGRx if `bgr`, else RGBx; row stride in bytes) without waiting.
199 pub fn submit_rgb(
200 &mut self,
201 rgb: &[u8],
202 src_width: u32,
203 src_height: u32,
204 stride_bytes: u32,
205 bgr: bool,
206 force_keyframe: bool,
207 ) -> Result<Option<CodedFrame>, Error> {
208 let pic = self.next_picture(force_keyframe);
209 let out = self
210 .session
211 .submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, &pic)?;
212 out.map(|bytes| self.coded(bytes)).transpose()
213 }
214
215 /// 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.
216 pub fn encode_rgb(
217 &mut self,
218 rgb: &[u8],
219 src_width: u32,
220 src_height: u32,
221 stride_bytes: u32,
222 bgr: bool,
223 force_keyframe: bool,
224 ) -> Result<CodedFrame, Error> {
225 let first = self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, force_keyframe)?;
226 let rest = self.flush()?;
227 last_frame(first, rest)
228 }
229
230 /// Submits one shared D3D11 texture of the source size without waiting.
231 #[cfg(windows)]
232 pub fn submit_d3d11(
233 &mut self,
234 src: &D3d11Texture<'_>,
235 force_keyframe: bool,
236 ) -> Result<Option<CodedFrame>, Error> {
237 let pic = self.next_picture(force_keyframe);
238 let out = self.session.submit_d3d11(src, &pic)?;
239 out.map(|bytes| self.coded(bytes)).transpose()
240 }
241
242 /// Encodes one shared D3D11 texture of the source size (BGRA if `bgr`, else RGBA), downscaled to the encoder size on the GPU.
243 #[cfg(windows)]
244 pub fn encode_d3d11(
245 &mut self,
246 src: &D3d11Texture<'_>,
247 force_keyframe: bool,
248 ) -> Result<CodedFrame, Error> {
249 let first = self.submit_d3d11(src, force_keyframe)?;
250 let rest = self.flush()?;
251 last_frame(first, rest)
252 }
253
254 /// Submits one DMA-BUF frame of the source size without waiting.
255 #[cfg(target_os = "linux")]
256 pub fn submit_dmabuf(
257 &mut self,
258 src: &DmaBuf<'_>,
259 force_keyframe: bool,
260 ) -> Result<Option<CodedFrame>, Error> {
261 let pic = self.next_picture(force_keyframe);
262 let out = self.session.submit_dmabuf(src, &pic)?;
263 out.map(|bytes| self.coded(bytes)).transpose()
264 }
265
266 /// Encodes one DMA-BUF frame of the source size (BGRx if `bgr`, else RGBx), box-downscaled to the encoder size on the GPU.
267 #[cfg(target_os = "linux")]
268 pub fn encode_dmabuf(
269 &mut self,
270 src: &DmaBuf<'_>,
271 force_keyframe: bool,
272 ) -> Result<CodedFrame, Error> {
273 let first = self.submit_dmabuf(src, force_keyframe)?;
274 let rest = self.flush()?;
275 last_frame(first, rest)
276 }
277
278 fn next_picture(&mut self, force_keyframe: bool) -> H264Picture {
279 let step = self
280 .history
281 .next(force_keyframe || self.position >= self.gop_size);
282 if step.key {
283 self.frame_num = 0;
284 self.poc = 0;
285 } else {
286 self.frame_num = (self.frame_num + 1) % (1 << LOG2_MAX_FRAME_NUM);
287 self.poc += 2;
288 }
289 let pic = H264Picture {
290 idr: step.key,
291 idr_pic_id: self.idr_pic_id,
292 frame_num: self.frame_num,
293 poc: self.poc,
294 slot: step.slot,
295 reference: step.reference.map(|(slot, (frame_num, poc))| H264Ref { slot, frame_num, poc }),
296 };
297 self.history.store(&step, (self.frame_num, self.poc));
298 self.position = if step.key { 1 } else { self.position + 1 };
299 if step.key {
300 self.idr_pic_id = self.idr_pic_id.wrapping_add(1);
301 }
302 self.flight.push(Meta {
303 keyframe: step.key,
304 recovery: step.recovery,
305 id: step.id,
306 });
307 pic
308 }
309
310 /// The receiver decoded every frame up to `id` ([`CodedFrame::id`]); a recovery frame may reference one while it stays in the DPB.
311 pub fn ack(&mut self, id: u64) {
312 self.history.ack(id);
313 }
314
315 /// Make the next frame reference the newest acknowledged frame still held, or an IDR when none is.
316 pub fn recover(&mut self) {
317 self.history.arm();
318 }
319
320 fn coded(&mut self, bytes: Vec<u8>) -> Result<CodedFrame, Error> {
321 let meta = self.flight.pop()?;
322 let data = if meta.keyframe {
323 [self.parameter_sets.as_slice(), bytes.as_slice()].concat()
324 } else {
325 bytes
326 };
327 Ok(CodedFrame {
328 data,
329 keyframe: meta.keyframe,
330 recovery: meta.recovery,
331 id: meta.id,
332 })
333 }
334}