forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

enc_ec.rs263 lines, 9.3 KiBHistoryRawDownload
1//! The encode seats, on [`ec_hw::HwEncoder`]: H.264 (Main profile), HEVC and AV1.
2//!
3//! Pixels the caller holds are packed I420 and go through [`ec_hw::EncodeInput::I420`]
4//! (or `I420_16` for 10-bit). A picture the decoder left on the GPU arrives as a
5//! DRM-PRIME descriptor ([`DmaFrame`]) and goes through [`ec_hw::EncodeInput::DmaBufYuv`],
6//! which the encoder imports and caches itself. The backend, Vulkan or VA-API, is the
7//! one [`ec_hw::HwEncoder::open`] picks.
8
9use std::collections::VecDeque;
10use std::os::fd::{AsFd, BorrowedFd};
11
12use ec_hw::{
13 Backend, DmaBufFormat, DmaBufPlane, DmaBufYuvFrame, EncCodec, EncodeInput, EncoderConfig,
14 FrameMetadata, H264Profile, HwEncoder, I420, I420_16, RateControlMode,
15};
16
17use engine::hw::DmaFrame;
18use engine::hwproc::SeatRate;
19
20/// `DRM_FORMAT_NV12`, which is also `VA_FOURCC_NV12`: the four characters.
21const FOURCC_NV12: u32 = u32::from_le_bytes(*b"NV12");
22/// `DRM_FORMAT_P010`, which is also `VA_FOURCC_P010`.
23const FOURCC_P010: u32 = u32::from_le_bytes(*b"P010");
24
25/// One hardware encode session on `ec_hw`.
26pub(crate) struct EcEncSession {
27 encoder: HwEncoder,
28 /// Display size: what is encoded.
29 width: usize,
30 height: usize,
31 timestamp: i64,
32 /// Access units the encoder has finished but the caller has not taken yet,
33 /// in encode order (which is display order: no B-frames).
34 ready: VecDeque<Vec<u8>>,
35 /// The access unit currently handed out, kept alive until the next call.
36 out: Vec<u8>,
37}
38
39/// The `open` arguments, for any of the three codecs.
40pub(crate) struct EcOpen {
41 pub codec: EncCodec,
42 pub width: u32,
43 pub height: u32,
44 pub fps_num: u32,
45 pub fps_den: u32,
46 pub rate: SeatRate,
47 /// Every picture an IDR: what a proxy is coded with (see `gop_limit`).
48 pub intra_only: bool,
49 /// Pictures between key frames; `None` is `gop_limit`'s.
50 pub gop: Option<u32>,
51 /// Colour description for the VUI as `(primaries, transfer, matrix, full)`.
52 pub colour: Option<(u8, u8, u8, bool)>,
53 /// HEVC Main10: pictures go through [`EcEncSession::encode16_owned`].
54 pub ten_bit: bool,
55}
56
57impl EcEncSession {
58 pub(crate) fn open(req: EcOpen) -> Option<Self> {
59 let EcOpen {
60 codec,
61 width,
62 height,
63 fps_num,
64 fps_den,
65 rate,
66 intra_only,
67 gop,
68 colour,
69 ten_bit,
70 } = req;
71 // NV12 chroma is half resolution, so odd dimensions have no packing;
72 // radeonsi refuses encode contexts below 64x64 (measured).
73 if width < 64 || height < 64 || !width.is_multiple_of(2) || !height.is_multiple_of(2) {
74 return None;
75 }
76 // The HEVC entrypoint's own floor: the same driver that takes a
77 // 128x128 H.264 context answers `VaError(19)` to an HEVC one below
78 // 384x384 (measured 2026-08-13 on radeonsi).
79 if codec == EncCodec::H265 && (width < 384 || height < 384) {
80 return None;
81 }
82 if fps_num == 0 || fps_den == 0 || rate == SeatRate::Bitrate(0) {
83 return None;
84 }
85 let framerate = ((fps_num as f64 / fps_den as f64).round() as i64).clamp(1, 240) as u32;
86 let mut config = EncoderConfig::new(codec, width, height);
87 config.framerate = (framerate, 1);
88 if let SeatRate::Bitrate(bitrate) = rate {
89 config.bitrate = u32::try_from(bitrate).unwrap_or(u32::MAX);
90 }
91 config.gop_size = gop.unwrap_or_else(|| match (codec, intra_only) {
92 (EncCodec::H265, false) => framerate,
93 _ => u32::from(crate::gop_limit(framerate, intra_only)),
94 });
95 config.rate_control = match (codec, rate) {
96 (EncCodec::Av1, SeatRate::ConstantQp(qp)) => RateControlMode::ConstantQp { qp: qp.min(51) * 255 / 51 },
97 (_, SeatRate::ConstantQp(qp)) => RateControlMode::ConstantQp { qp },
98 // Constant quality at 128 of 255, the AV1 rate control measured.
99 (EncCodec::Av1, SeatRate::Bitrate(_)) => RateControlMode::ConstantQp { qp: 128 },
100 (_, SeatRate::Bitrate(_)) => RateControlMode::ConstantBitrate,
101 };
102 if codec == EncCodec::H264 {
103 // Main, not the High default: the seat's tests pin the profile.
104 config = config.h264_profile(H264Profile::Main);
105 }
106 if let Some((p, t, m, full)) = colour {
107 config = config.colour(p, t, m, full);
108 }
109 if ten_bit {
110 config = config.ten_bit();
111 }
112 let encoder = HwEncoder::open(config, None).ok()?;
113 Some(Self {
114 encoder,
115 width: width as usize,
116 height: height as usize,
117 timestamp: 0,
118 ready: VecDeque::new(),
119 out: Vec::new(),
120 })
121 }
122
123 pub(crate) fn encode16_owned(
124 &mut self,
125 mut y: Vec<u16>,
126 mut u: Vec<u16>,
127 mut v: Vec<u16>,
128 force_keyframe: bool,
129 ) -> Result<(), String> {
130 let (w, h) = (self.width, self.height);
131 let (cw, ch) = (w / 2, h / 2);
132 if y.len() < w * h || u.len() < cw * ch || v.len() < cw * ch {
133 return Err("encode input is not a packed I420 frame".into());
134 }
135 y.truncate(w * h);
136 u.truncate(cw * ch);
137 v.truncate(cw * ch);
138 let picture = I420_16 {
139 y,
140 u,
141 v,
142 width: w as u32,
143 height: h as u32,
144 bit_depth: 10,
145 };
146 let meta = self.meta(force_keyframe);
147 if let Some(coded) = self
148 .encoder
149 .submit(EncodeInput::I420_16(&picture), meta)
150 .map_err(|e| e.to_string())?
151 {
152 self.ready.push_back(coded.data);
153 }
154 Ok(())
155 }
156
157 pub(crate) fn flush(&mut self) -> Result<(), String> {
158 for coded in self.encoder.flush().map_err(|e| e.to_string())? {
159 self.ready.push_back(coded.data);
160 }
161 Ok(())
162 }
163
164 /// The size a DMA-BUF picture must be described at, or `None` when the
165 /// backend takes no DMA-BUF input (VA-API).
166 pub(crate) fn coded_size(&self) -> Option<(u32, u32)> {
167 match self.encoder.backend() {
168 Backend::Vk => Some((self.width as u32, self.height as u32)),
169 Backend::Va => None,
170 }
171 }
172
173 /// Codes one packed I420 picture (`y`, `u`, `v` at the session's size) and
174 /// queues the access unit it finishes.
175 pub(crate) fn encode(
176 &mut self,
177 y: &[u8],
178 u: &[u8],
179 v: &[u8],
180 force_keyframe: bool,
181 ) -> Result<(), String> {
182 let (w, h) = (self.width, self.height);
183 let (cw, ch) = (w / 2, h / 2);
184 if y.len() < w * h || u.len() < cw * ch || v.len() < cw * ch {
185 return Err("encode input is not a packed I420 frame".into());
186 }
187 let picture = I420 {
188 y: y[..w * h].to_vec(),
189 u: u[..cw * ch].to_vec(),
190 v: v[..cw * ch].to_vec(),
191 width: w as u32,
192 height: h as u32,
193 };
194 let meta = self.meta(force_keyframe);
195 if let Some(coded) = self
196 .encoder
197 .submit(EncodeInput::I420(&picture), meta)
198 .map_err(|e| e.to_string())?
199 {
200 self.ready.push_back(coded.data);
201 }
202 Ok(())
203 }
204
205 /// Codes one picture the decoder left on the GPU, read in place.
206 ///
207 /// The descriptors stay owned by `frame`; the encoder duplicates them on import.
208 pub(crate) fn encode_dma(&mut self, frame: &DmaFrame, force_keyframe: bool) -> Result<(), String> {
209 let format = match (frame.desc.fourcc, frame.fds.len()) {
210 (FOURCC_NV12, 1 | 2) => DmaBufFormat::Nv12,
211 (FOURCC_P010, 1 | 2) => DmaBufFormat::P010,
212 _ => return Err("DMA-BUF is not an NV12 or P010 picture on the GPU".into()),
213 };
214 let fds: Vec<BorrowedFd> = frame.fds.iter().map(|fd| fd.as_fd()).collect();
215 let desc = &frame.desc;
216 let chroma_fd = if fds.len() == 2 { 1 } else { 0 };
217 let input = DmaBufYuvFrame {
218 fds: &fds,
219 planes: [
220 DmaBufPlane {
221 fd: 0,
222 offset: desc.offset[0],
223 pitch: desc.stride[0],
224 },
225 DmaBufPlane {
226 fd: chroma_fd,
227 offset: desc.offset[1],
228 pitch: desc.stride[1],
229 },
230 ],
231 width: self.width as u32,
232 height: self.height as u32,
233 modifier: desc.modifier,
234 format,
235 };
236 let meta = self.meta(force_keyframe);
237 if let Some(coded) = self
238 .encoder
239 .submit(EncodeInput::DmaBufYuv(&input), meta)
240 .map_err(|e| e.to_string())?
241 {
242 self.ready.push_back(coded.data);
243 }
244 Ok(())
245 }
246
247 fn meta(&mut self, force_keyframe: bool) -> FrameMetadata {
248 let meta = FrameMetadata {
249 timestamp: self.timestamp,
250 force_keyframe,
251 };
252 self.timestamp += 1;
253 meta
254 }
255
256 /// The oldest finished access unit, or `None` when the encoder has nothing
257 /// queued. It stays valid until the next call on this session.
258 pub(crate) fn next_au(&mut self) -> Option<&[u8]> {
259 let au = self.ready.pop_front()?;
260 self.out = au;
261 Some(&self.out)
262 }
263}