forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

h265.rs288 lines, 9.6 KiBHistoryRawDownload
1use vk_video_ffi::{H265EncodeConfig, H265EncodeSession, H265Picture, H265Ref};
2
3#[cfg(windows)]
4use crate::D3d11Texture;
5#[cfg(target_os = "linux")]
6use crate::DmaBuf;
7use crate::history::History;
8use crate::{CodedFrame, Colour, Error, Flight, Gpu, Meta, RateControl, last_frame};
9
10/// H.265 encoder settings.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub struct H265EncoderConfig {
13 /// Width in luma samples, even.
14 pub width: u32,
15 /// Height in luma samples, even.
16 pub height: u32,
17 /// Frame rate as numerator and denominator.
18 pub fps: (u32, u32),
19 /// Frames from one IDR to the next, at least 1.
20 pub gop_size: u32,
21 /// Rate control.
22 pub rate: RateControl,
23 /// Luma and chroma bit depth: 8, or 10 for Main 10 (`encode_16`).
24 pub bit_depth: u8,
25 /// `general_level_idc`, clamped to the driver maximum.
26 pub level: u8,
27 /// Colour description for the VUI, or none.
28 pub colour: Option<Colour>,
29 /// 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.
30 pub quality: u32,
31}
32
33/// H.265 encoder: GOP, POC and DPB slot bookkeeping over [`H265EncodeSession`].
34pub struct H265Encoder {
35 session: H265EncodeSession,
36 parameter_sets: Vec<u8>,
37 width: usize,
38 height: usize,
39 gop_size: u32,
40 position: u32,
41 poc: i32,
42 history: History<i32>,
43 uv: Vec<u8>,
44 uv16: Vec<u16>,
45 flight: Flight,
46}
47
48impl H265Encoder {
49 /// Opens an encoder session on `gpu`.
50 pub fn new(gpu: &Gpu, cfg: H265EncoderConfig) -> Result<Self, Error> {
51 if cfg.gop_size == 0 {
52 return Err(Error::Invalid("gop_size is zero".into()));
53 }
54 let session = H265EncodeSession::new(
55 gpu,
56 &H265EncodeConfig {
57 width: cfg.width,
58 height: cfg.height,
59 fps: cfg.fps,
60 rate: cfg.rate,
61 bit_depth: cfg.bit_depth,
62 level: cfg.level,
63 colour: cfg.colour,
64 quality: cfg.quality,
65 },
66 )?;
67 let parameter_sets = session.parameter_sets()?;
68 Ok(H265Encoder {
69 session,
70 parameter_sets,
71 width: cfg.width as usize,
72 height: cfg.height as usize,
73 gop_size: cfg.gop_size,
74 position: 0,
75 poc: 0,
76 history: History::new(),
77 uv: vec![0; cfg.width as usize * cfg.height as usize / 2],
78 uv16: vec![0; cfg.width as usize * cfg.height as usize / 2],
79 flight: Flight::default(),
80 })
81 }
82
83 /// Submits one I420 frame without waiting; returns the oldest frame once a second one is queued.
84 pub fn submit(
85 &mut self,
86 y: &[u8],
87 u: &[u8],
88 v: &[u8],
89 force_keyframe: bool,
90 ) -> Result<Option<CodedFrame>, Error> {
91 let chroma = self.width * self.height / 4;
92 if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma {
93 return Err(Error::Invalid("I420 plane size".into()));
94 }
95 for (i, pair) in self.uv.chunks_exact_mut(2).enumerate() {
96 pair[0] = u[i];
97 pair[1] = v[i];
98 }
99 let pic = self.next_picture(force_keyframe);
100 let out = self.session.submit(y, &self.uv, &pic)?;
101 Ok(out.map(|bytes| self.coded(bytes)))
102 }
103
104 /// Encodes one I420 frame; `force_keyframe` makes it an IDR and restarts the GOP.
105 pub fn encode(
106 &mut self,
107 y: &[u8],
108 u: &[u8],
109 v: &[u8],
110 force_keyframe: bool,
111 ) -> Result<CodedFrame, Error> {
112 let first = self.submit(y, u, v, force_keyframe)?;
113 let rest = self.flush()?;
114 last_frame(first, rest)
115 }
116
117 /// Submits one 10-bit I420 frame of a 10-bit encoder without waiting.
118 pub fn submit_16(
119 &mut self,
120 y: &[u16],
121 u: &[u16],
122 v: &[u16],
123 force_keyframe: bool,
124 ) -> Result<Option<CodedFrame>, Error> {
125 let chroma = self.width * self.height / 4;
126 if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma {
127 return Err(Error::Invalid("I420 plane size".into()));
128 }
129 for (i, pair) in self.uv16.chunks_exact_mut(2).enumerate() {
130 pair[0] = u[i];
131 pair[1] = v[i];
132 }
133 let pic = self.next_picture(force_keyframe);
134 let out = self.session.submit_16(y, &self.uv16, &pic)?;
135 Ok(out.map(|bytes| self.coded(bytes)))
136 }
137
138 /// Encodes one 10-bit I420 frame of a 10-bit encoder; `force_keyframe` makes it IDR and restarts the GOP.
139 pub fn encode_16(
140 &mut self,
141 y: &[u16],
142 u: &[u16],
143 v: &[u16],
144 force_keyframe: bool,
145 ) -> Result<CodedFrame, Error> {
146 let first = self.submit_16(y, u, v, force_keyframe)?;
147 let rest = self.flush()?;
148 last_frame(first, rest)
149 }
150
151 /// Waits for every submitted frame and returns them in order.
152 pub fn flush(&mut self) -> Result<Vec<CodedFrame>, Error> {
153 let bytes = self.session.flush()?;
154 Ok(bytes.into_iter().map(|b| self.coded(b)).collect())
155 }
156
157 /// Changes bitrate or frame rate; takes effect on the next frame.
158 pub fn set_rate(&mut self, rate: RateControl, fps: (u32, u32)) -> Result<(), Error> {
159 Ok(self.session.set_rate(rate, fps)?)
160 }
161
162 /// Submits one packed RGB frame (src_width x src_height, BGRx if `bgr`, else RGBx; row stride in bytes) without waiting.
163 pub fn submit_rgb(
164 &mut self,
165 rgb: &[u8],
166 src_width: u32,
167 src_height: u32,
168 stride_bytes: u32,
169 bgr: bool,
170 force_keyframe: bool,
171 ) -> Result<Option<CodedFrame>, Error> {
172 let pic = self.next_picture(force_keyframe);
173 let out = self
174 .session
175 .submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, &pic)?;
176 Ok(out.map(|bytes| self.coded(bytes)))
177 }
178
179 /// 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.
180 pub fn encode_rgb(
181 &mut self,
182 rgb: &[u8],
183 src_width: u32,
184 src_height: u32,
185 stride_bytes: u32,
186 bgr: bool,
187 force_keyframe: bool,
188 ) -> Result<CodedFrame, Error> {
189 let first = self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, force_keyframe)?;
190 let rest = self.flush()?;
191 last_frame(first, rest)
192 }
193
194 /// Submits one shared D3D11 texture of the source size without waiting.
195 #[cfg(windows)]
196 pub fn submit_d3d11(
197 &mut self,
198 src: &D3d11Texture<'_>,
199 force_keyframe: bool,
200 ) -> Result<Option<CodedFrame>, Error> {
201 let pic = self.next_picture(force_keyframe);
202 let out = self.session.submit_d3d11(src, &pic)?;
203 Ok(out.map(|bytes| self.coded(bytes)))
204 }
205
206 /// Encodes one shared D3D11 texture of the source size (BGRA if `bgr`, else RGBA), downscaled to the encoder size on the GPU.
207 #[cfg(windows)]
208 pub fn encode_d3d11(
209 &mut self,
210 src: &D3d11Texture<'_>,
211 force_keyframe: bool,
212 ) -> Result<CodedFrame, Error> {
213 let first = self.submit_d3d11(src, force_keyframe)?;
214 let rest = self.flush()?;
215 last_frame(first, rest)
216 }
217
218 /// Submits one DMA-BUF frame of the source size without waiting.
219 #[cfg(target_os = "linux")]
220 pub fn submit_dmabuf(
221 &mut self,
222 src: &DmaBuf<'_>,
223 force_keyframe: bool,
224 ) -> Result<Option<CodedFrame>, Error> {
225 let pic = self.next_picture(force_keyframe);
226 let out = self.session.submit_dmabuf(src, &pic)?;
227 Ok(out.map(|bytes| self.coded(bytes)))
228 }
229
230 /// Encodes one DMA-BUF frame of the source size (BGRx if `bgr`, else RGBx), box-downscaled to the encoder size on the GPU.
231 #[cfg(target_os = "linux")]
232 pub fn encode_dmabuf(
233 &mut self,
234 src: &DmaBuf<'_>,
235 force_keyframe: bool,
236 ) -> Result<CodedFrame, Error> {
237 let first = self.submit_dmabuf(src, force_keyframe)?;
238 let rest = self.flush()?;
239 last_frame(first, rest)
240 }
241
242 fn next_picture(&mut self, force_keyframe: bool) -> H265Picture {
243 let step = self
244 .history
245 .next(force_keyframe || self.position >= self.gop_size);
246 self.poc = if step.key { 0 } else { self.poc + 1 };
247 let keep = self.history.kept(&step);
248 self.history.store(&step, self.poc);
249 self.position = if step.key { 1 } else { self.position + 1 };
250 self.flight.push(Meta {
251 keyframe: step.key,
252 recovery: step.recovery,
253 id: step.id,
254 });
255 H265Picture {
256 idr: step.key,
257 poc: self.poc,
258 slot: step.slot,
259 reference: step.reference.map(|(slot, poc)| H265Ref { slot, poc }),
260 keep,
261 }
262 }
263
264 /// The receiver decoded every frame up to `id` ([`CodedFrame::id`]); a recovery frame may reference one while it stays in the DPB.
265 pub fn ack(&mut self, id: u64) {
266 self.history.ack(id);
267 }
268
269 /// Make the next frame reference the newest acknowledged frame still held, or an IDR when none is.
270 pub fn recover(&mut self) {
271 self.history.arm();
272 }
273
274 fn coded(&mut self, bytes: Vec<u8>) -> CodedFrame {
275 let meta = self.flight.pop();
276 let data = if meta.keyframe {
277 [self.parameter_sets.as_slice(), bytes.as_slice()].concat()
278 } else {
279 bytes
280 };
281 CodedFrame {
282 data,
283 keyframe: meta.keyframe,
284 recovery: meta.recovery,
285 id: meta.id,
286 }
287 }
288}