forge
Explore
Log in

Don't you dare go Hollow

ec-hw: HwEncoder (Vulkan first, VA fallback on Linux), HwDecoder (VA for now), capabilities() without opening an encoder; compiles on every OS; hw_caps example

Browse files at this commit

274b9cb95d91511f24b2ddf82e02073ee31a0568Ahmet Kaan GümüşParent: 4d688f2
Cargo.lockmodified+1 -0
@@ -531,6 +531,7 @@ dependencies = [
531531 "ec-h264-syntax",
532532 "ec-h265-syntax",
533533 "ec-va",
534+ "ec-vk",
534535 "ec-vp9-syntax",
535536 ]
536537
Cargo.tomlmodified+1 -0
@@ -29,6 +29,7 @@ ec-h264-syntax = { path = "crates/ec-h264-syntax", version = "0.1.0" }
2929 ec-h265 = { path = "crates/ec-h265", version = "0.1.0" }
3030 ec-h265-syntax = { path = "crates/ec-h265-syntax", version = "0.1.0" }
3131 ec-hw = { path = "crates/ec-hw", version = "0.1.0" }
32+ec-vk = { path = "crates/ec-vk", version = "0.1.0" }
3233 ec-image = { path = "crates/ec-image", version = "0.1.0" }
3334 ec-inflate = { path = "crates/ec-inflate", version = "0.1.0" }
3435 ec-mpegts = { path = "crates/ec-mpegts", version = "0.1.0" }
crates/ec-hw/Cargo.tomlmodified+1 -0
@@ -11,6 +11,7 @@ ec-av1-syntax.workspace = true
1111 ec-core.workspace = true
1212 ec-h264-syntax.workspace = true
1313 ec-h265-syntax.workspace = true
14+ec-vk.workspace = true
1415 ec-vp9-syntax.workspace = true
1516
1617 [target.'cfg(target_os = "linux")'.dependencies]
crates/ec-hw/examples/hw_caps.rsadded+102 -0
@@ -0,0 +1,102 @@
1+//! Lists hardware capabilities, then encodes a gradient with each codec and decodes the Vulkan streams back.
2+//!
3+//! ```text
4+//! cargo run -p ec-hw --example hw_caps
5+//! ```
6+
7+use ec_hw::{
8+ Backend, Codec, EncCodec, EncoderConfig, FrameMetadata, HwDecoder, HwEncoder, I420,
9+ RateControlMode, capabilities,
10+};
11+
12+const FRAMES: u32 = 30;
13+const WIDTH: u32 = 1280;
14+const HEIGHT: u32 = 720;
15+
16+fn main() {
17+ for cap in capabilities() {
18+ println!(
19+ "{:?} {:?} {:?} max {}x{}",
20+ cap.backend, cap.direction, cap.codec, cap.max_width, cap.max_height
21+ );
22+ }
23+ for codec in [EncCodec::H264, EncCodec::H265, EncCodec::Av1] {
24+ if let Err(e) = run(codec) {
25+ println!("{codec:?}: error: {e}");
26+ }
27+ }
28+}
29+
30+fn run(codec: EncCodec) -> ec_hw::Result<()> {
31+ let config = EncoderConfig {
32+ bitrate: 2_000_000,
33+ rate_control: RateControlMode::ConstantBitrate,
34+ ..EncoderConfig::new(codec, WIDTH, HEIGHT)
35+ };
36+ let mut encoder = match HwEncoder::open(config, None) {
37+ Ok(encoder) => encoder,
38+ Err(e) => {
39+ println!("{codec:?}: no encoder: {e}");
40+ return Ok(());
41+ }
42+ };
43+ let backend = encoder.backend();
44+ let mut coded = Vec::with_capacity(FRAMES as usize);
45+ for index in 0..FRAMES {
46+ let meta = FrameMetadata {
47+ timestamp: index as i64,
48+ force_keyframe: index == 0,
49+ };
50+ coded.push(encoder.encode(&gray_gradient(index), meta)?);
51+ }
52+ let bytes: usize = coded.iter().map(|c| c.data.len()).sum();
53+ println!("{codec:?} {backend:?} {FRAMES} frames {bytes} bytes");
54+
55+ if backend != Backend::Vk {
56+ return Ok(());
57+ }
58+ let mut decoder = match HwDecoder::open(decode_codec(codec)) {
59+ Ok(decoder) => decoder,
60+ Err(e) => {
61+ println!(" decode unavailable: {e}");
62+ return Ok(());
63+ }
64+ };
65+ let mut frames = 0;
66+ for c in &coded {
67+ decoder.decode(&c.data, c.timestamp)?;
68+ while decoder.next_frame()?.is_some() {
69+ frames += 1;
70+ }
71+ }
72+ decoder.flush()?;
73+ while decoder.next_frame()?.is_some() {
74+ frames += 1;
75+ }
76+ println!(" decoded {frames} frames");
77+ Ok(())
78+}
79+
80+fn decode_codec(codec: EncCodec) -> Codec {
81+ match codec {
82+ EncCodec::H264 => Codec::H264,
83+ EncCodec::H265 => Codec::H265,
84+ EncCodec::Av1 => Codec::Av1,
85+ }
86+}
87+
88+fn gray_gradient(index: u32) -> I420 {
89+ let (w, h) = (WIDTH as usize, HEIGHT as usize);
90+ let shift = 4 * index as usize;
91+ let y = (0..h)
92+ .flat_map(|row| (0..w).map(move |col| ((col + row + shift) & 0xff) as u8))
93+ .collect();
94+ let chroma = w.div_ceil(2) * h.div_ceil(2);
95+ I420 {
96+ y,
97+ u: vec![128; chroma],
98+ v: vec![128; chroma],
99+ width: WIDTH,
100+ height: HEIGHT,
101+ }
102+}
crates/ec-hw/src/error.rsmodified+9 -0
@@ -31,6 +31,8 @@ pub enum Error {
3131 /// The caller asked for something inconsistent, e.g. feeding H.264 to a
3232 /// decoder configured for AV1, or encoding a frame of the wrong size.
3333 Config(String),
34+ /// A Vulkan Video call failed or the Vulkan path refused the request.
35+ Vk(String),
3436 /// The GPU was reset (a hung ring, a lost context) while this session was
3537 /// alive, or a session was asked for during the grace period after one.
3638 /// The session is dead; use software. See [`crate::reset`].
@@ -83,6 +85,12 @@ impl From<ec_va::Error> for Error {
8385 }
8486 }
8587
88+impl From<ec_vk::Error> for Error {
89+ fn from(e: ec_vk::Error) -> Error {
90+ Error::Vk(e.to_string())
91+ }
92+}
93+
8694 impl From<ec_core::Error> for Error {
8795 fn from(e: ec_core::Error) -> Error {
8896 Error::Stream(e)
@@ -97,6 +105,7 @@ impl fmt::Display for Error {
97105 Error::Stream(e) => write!(f, "bitstream: {e}"),
98106 Error::Unsupported { what, why } => write!(f, "{what} is not supported: {why}"),
99107 Error::Config(what) => write!(f, "{what}"),
108+ Error::Vk(what) => write!(f, "Vulkan Video: {what}"),
100109 Error::HwReset(what) => write!(f, "GPU reset: {what}"),
101110 }
102111 }
crates/ec-hw/src/hw.rsadded+373 -0
@@ -0,0 +1,373 @@
1+//! One API over Vulkan Video and VA-API.
2+
3+use crate::error::{Error, Result};
4+use crate::picture::I420;
5+use crate::types::{Codec, CodedFrame, EncCodec, EncoderConfig, FrameMetadata, RateControlMode};
6+
7+#[cfg(target_os = "linux")]
8+use crate::dec::Decoder as VaDecoder;
9+#[cfg(target_os = "linux")]
10+use crate::enc::Encoder as VaEncoder;
11+
12+/// Where a codec runs.
13+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14+pub enum Backend {
15+ /// Vulkan Video, every OS.
16+ Vk,
17+ /// VA-API, Linux only.
18+ Va,
19+}
20+
21+/// Which way a codec runs.
22+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23+pub enum Direction {
24+ /// Encode.
25+ Encode,
26+ /// Decode.
27+ Decode,
28+}
29+
30+/// One codec, direction and backend this machine offers.
31+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32+pub struct Capability {
33+ /// Codec.
34+ pub codec: Codec,
35+ /// Direction.
36+ pub direction: Direction,
37+ /// Largest width in luma samples.
38+ pub max_width: u32,
39+ /// Largest height in luma samples.
40+ pub max_height: u32,
41+ /// Backend offering it.
42+ pub backend: Backend,
43+}
44+
45+thread_local! {
46+ static GPU: Option<ec_vk::Gpu> = ec_vk::Gpu::open().ok();
47+}
48+
49+fn vk_gpu() -> Option<ec_vk::Gpu> {
50+ GPU.with(|gpu| gpu.clone())
51+}
52+
53+/// Every codec, direction and backend this machine can use. Never fails.
54+pub fn capabilities() -> Vec<Capability> {
55+ let mut out = Vec::new();
56+ if let Some(gpu) = vk_gpu() {
57+ for caps in gpu.caps().into_iter().filter(|c| c.direction == ec_vk::Direction::Encode) {
58+ let codec = match caps.codec {
59+ ec_vk::Codec::H264 => Codec::H264,
60+ ec_vk::Codec::H265 => Codec::H265,
61+ ec_vk::Codec::Av1 => Codec::Av1,
62+ ec_vk::Codec::Vp9 => Codec::Vp9,
63+ };
64+ let direction = match caps.direction {
65+ ec_vk::Direction::Encode => Direction::Encode,
66+ ec_vk::Direction::Decode => Direction::Decode,
67+ };
68+ push(
69+ &mut out,
70+ Capability {
71+ codec,
72+ direction,
73+ max_width: caps.max_width,
74+ max_height: caps.max_height,
75+ backend: Backend::Vk,
76+ },
77+ );
78+ }
79+ }
80+ #[cfg(target_os = "linux")]
81+ va_capabilities(&mut out);
82+ out
83+}
84+
85+fn push(out: &mut Vec<Capability>, cap: Capability) {
86+ let known = out.iter().any(|c| {
87+ c.codec == cap.codec && c.direction == cap.direction && c.backend == cap.backend
88+ });
89+ if !known {
90+ out.push(cap);
91+ }
92+}
93+
94+#[cfg(target_os = "linux")]
95+fn va_capabilities(out: &mut Vec<Capability>) {
96+ let Ok(display) = ec_va::open() else {
97+ return;
98+ };
99+ let Ok(report) = ec_va::CapReport::probe(&display) else {
100+ return;
101+ };
102+ for entry in &report.entries {
103+ let Some(codec) = va_codec(entry.profile) else {
104+ continue;
105+ };
106+ let direction = match entry.entrypoint {
107+ ec_va::Entrypoint::VLD => Direction::Decode,
108+ ec_va::Entrypoint::EncSlice | ec_va::Entrypoint::EncSliceLP => Direction::Encode,
109+ _ => continue,
110+ };
111+ let (max_width, max_height) = match &entry.surfaces {
112+ Some(s) => (s.max_width.unwrap_or(4096), s.max_height.unwrap_or(4096)),
113+ None => (4096, 4096),
114+ };
115+ push(
116+ out,
117+ Capability {
118+ codec,
119+ direction,
120+ max_width,
121+ max_height,
122+ backend: Backend::Va,
123+ },
124+ );
125+ }
126+}
127+
128+#[cfg(target_os = "linux")]
129+fn va_codec(profile: ec_va::Profile) -> Option<Codec> {
130+ Some(match profile {
131+ ec_va::Profile::H264Baseline
132+ | ec_va::Profile::H264ConstrainedBaseline
133+ | ec_va::Profile::H264Main
134+ | ec_va::Profile::H264High
135+ | ec_va::Profile::H264High10 => Codec::H264,
136+ ec_va::Profile::HEVCMain | ec_va::Profile::HEVCMain10 => Codec::H265,
137+ ec_va::Profile::VP9Profile0 => Codec::Vp9,
138+ ec_va::Profile::AV1Profile0 => Codec::Av1,
139+ _ => return None,
140+ })
141+}
142+
143+/// The Vulkan encoder for one codec.
144+enum VkEncoder {
145+ H264(ec_vk::H264Encoder),
146+ H265(ec_vk::H265Encoder),
147+ Av1(ec_vk::Av1Encoder),
148+}
149+
150+impl VkEncoder {
151+ fn encode(
152+ &mut self,
153+ frame: &I420,
154+ force_keyframe: bool,
155+ ) -> std::result::Result<ec_vk::CodedFrame, ec_vk::Error> {
156+ let (y, u, v) = (&frame.y, &frame.u, &frame.v);
157+ match self {
158+ VkEncoder::H264(e) => e.encode(y, u, v, force_keyframe),
159+ VkEncoder::H265(e) => e.encode(y, u, v, force_keyframe),
160+ VkEncoder::Av1(e) => e.encode(y, u, v, force_keyframe),
161+ }
162+ }
163+}
164+
165+enum EncInner {
166+ Vk(VkEncoder),
167+ #[cfg(target_os = "linux")]
168+ Va(VaEncoder),
169+}
170+
171+/// A hardware encoder on whichever backend opened.
172+pub struct HwEncoder {
173+ inner: EncInner,
174+}
175+
176+impl HwEncoder {
177+ /// Open an encoder. `prefer` = `None` tries Vulkan, then VA-API.
178+ pub fn open(config: EncoderConfig, prefer: Option<Backend>) -> Result<HwEncoder> {
179+ let order = match prefer {
180+ Some(backend) => vec![backend],
181+ None => vec![Backend::Vk, Backend::Va],
182+ };
183+ let mut reasons = Vec::new();
184+ for backend in order {
185+ match open_backend(backend, config) {
186+ Ok(inner) => return Ok(HwEncoder { inner }),
187+ Err(e) => reasons.push(format!("{backend:?}: {e}")),
188+ }
189+ }
190+ Err(Error::unsupported(
191+ format!("{:?} hardware encode", config.codec),
192+ reasons.join("; "),
193+ ))
194+ }
195+
196+ /// The backend this encoder runs on.
197+ pub fn backend(&self) -> Backend {
198+ match self.inner {
199+ EncInner::Vk(_) => Backend::Vk,
200+ #[cfg(target_os = "linux")]
201+ EncInner::Va(_) => Backend::Va,
202+ }
203+ }
204+
205+ /// Encode one frame; `meta.force_keyframe` starts a new GOP.
206+ pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result<CodedFrame> {
207+ match &mut self.inner {
208+ EncInner::Vk(enc) => {
209+ let coded = enc.encode(frame, meta.force_keyframe)?;
210+ Ok(CodedFrame {
211+ data: coded.data,
212+ timestamp: meta.timestamp,
213+ is_keyframe: coded.keyframe,
214+ })
215+ }
216+ #[cfg(target_os = "linux")]
217+ EncInner::Va(enc) => enc.encode(frame, meta),
218+ }
219+ }
220+}
221+
222+fn open_backend(backend: Backend, config: EncoderConfig) -> Result<EncInner> {
223+ match backend {
224+ Backend::Vk => open_vk(config).map(EncInner::Vk),
225+ Backend::Va => open_va(config),
226+ }
227+}
228+
229+fn open_vk(config: EncoderConfig) -> Result<VkEncoder> {
230+ if config.bit_depth != 8 {
231+ return Err(Error::unsupported(
232+ "10-bit Vulkan Video encode",
233+ "the Vulkan encoders are 8-bit",
234+ ));
235+ }
236+ let gpu = vk_gpu().ok_or_else(|| {
237+ Error::unsupported("Vulkan Video encode", "no Vulkan Video device")
238+ })?;
239+ let rate = vk_rate(&config);
240+ let (width, height, fps, gop_size) =
241+ (config.width, config.height, config.framerate, config.gop_size);
242+ Ok(match config.codec {
243+ EncCodec::H264 => VkEncoder::H264(ec_vk::H264Encoder::new(
244+ &gpu,
245+ ec_vk::H264EncoderConfig {
246+ width,
247+ height,
248+ fps,
249+ gop_size,
250+ rate,
251+ },
252+ )?),
253+ EncCodec::H265 => VkEncoder::H265(ec_vk::H265Encoder::new(
254+ &gpu,
255+ ec_vk::H265EncoderConfig {
256+ width,
257+ height,
258+ fps,
259+ gop_size,
260+ rate,
261+ },
262+ )?),
263+ EncCodec::Av1 => VkEncoder::Av1(ec_vk::Av1Encoder::new(
264+ &gpu,
265+ ec_vk::Av1EncoderConfig {
266+ width,
267+ height,
268+ fps,
269+ gop_size,
270+ rate,
271+ },
272+ )?),
273+ })
274+}
275+
276+fn vk_rate(config: &EncoderConfig) -> ec_vk::RateControl {
277+ match (config.rate_control, config.codec) {
278+ (RateControlMode::ConstantQp { qp }, EncCodec::Av1) => ec_vk::RateControl::ConstantQp {
279+ qp: (qp / 5).min(51) as u8,
280+ },
281+ (RateControlMode::ConstantQp { qp }, _) => ec_vk::RateControl::ConstantQp {
282+ qp: qp.min(51) as u8,
283+ },
284+ _ => ec_vk::RateControl::Cbr {
285+ bitrate: config.bitrate,
286+ },
287+ }
288+}
289+
290+#[cfg(target_os = "linux")]
291+fn open_va(config: EncoderConfig) -> Result<EncInner> {
292+ let display = ec_va::open()?;
293+ Ok(EncInner::Va(VaEncoder::new(&display, config)?))
294+}
295+
296+#[cfg(not(target_os = "linux"))]
297+fn open_va(config: EncoderConfig) -> Result<EncInner> {
298+ Err(Error::unsupported(
299+ format!("{:?} VA-API encode", config.codec),
300+ "VA-API is Linux only",
301+ ))
302+}
303+
304+/// A hardware decoder. Only VA-API decodes for now.
305+pub struct HwDecoder {
306+ #[cfg(target_os = "linux")]
307+ inner: VaDecoder,
308+}
309+
310+impl HwDecoder {
311+ /// Open a decoder for `codec`. Non-Linux: always `Unsupported`.
312+ pub fn open(codec: Codec) -> Result<HwDecoder> {
313+ #[cfg(target_os = "linux")]
314+ {
315+ let display = ec_va::open()?;
316+ Ok(HwDecoder {
317+ inner: VaDecoder::new(&display, codec)?,
318+ })
319+ }
320+ #[cfg(not(target_os = "linux"))]
321+ {
322+ Err(Error::unsupported(
323+ format!("{codec:?} hardware decode"),
324+ "VA-API is Linux only",
325+ ))
326+ }
327+ }
328+
329+ /// The backend this decoder runs on.
330+ pub fn backend(&self) -> Backend {
331+ Backend::Va
332+ }
333+
334+ /// Feed one access unit.
335+ pub fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> {
336+ #[cfg(target_os = "linux")]
337+ {
338+ self.inner.decode(data, timestamp)
339+ }
340+ #[cfg(not(target_os = "linux"))]
341+ {
342+ let _ = (data, timestamp);
343+ Err(Error::unsupported("hardware decode", "VA-API is Linux only"))
344+ }
345+ }
346+
347+ /// The next picture in display order, as 8-bit I420 with its timestamp.
348+ pub fn next_frame(&mut self) -> Result<Option<(i64, I420)>> {
349+ #[cfg(target_os = "linux")]
350+ {
351+ match self.inner.next_frame() {
352+ Some(frame) => Ok(Some((frame.timestamp, frame.to_i420()?))),
353+ None => Ok(None),
354+ }
355+ }
356+ #[cfg(not(target_os = "linux"))]
357+ {
358+ Ok(None)
359+ }
360+ }
361+
362+ /// Emit every picture still held for reordering.
363+ pub fn flush(&mut self) -> Result<()> {
364+ #[cfg(target_os = "linux")]
365+ {
366+ self.inner.flush()
367+ }
368+ #[cfg(not(target_os = "linux"))]
369+ {
370+ Ok(())
371+ }
372+ }
373+}
crates/ec-hw/src/lib.rsmodified+2 -0
@@ -59,6 +59,7 @@ pub mod dec;
5959 #[cfg(target_os = "linux")]
6060 pub mod enc;
6161 pub mod error;
62+pub mod hw;
6263 #[cfg(target_os = "linux")]
6364 pub mod frame;
6465 pub mod picture;
@@ -74,6 +75,7 @@ pub use dec::{Decoder, StreamInfo};
7475 #[cfg(target_os = "linux")]
7576 pub use enc::Encoder;
7677 pub use error::{Error, Result};
78+pub use hw::{Backend, Capability, Direction, HwDecoder, HwEncoder, capabilities};
7779 #[cfg(target_os = "linux")]
7880 pub use frame::Frame;
7981 pub use picture::{Colour, I420, I420_16, i420_to_nv12, nv12_to_i420};
crates/ec-vk/src/lib.rsmodified+1 -1
@@ -9,7 +9,7 @@ mod h265;
99
1010 pub use av1::{Av1Encoder, Av1EncoderConfig};
1111 pub use h265::{H265Encoder, H265EncoderConfig};
12-pub use vk_video_ffi::{Error, Gpu, RateControl};
12+pub use vk_video_ffi::{Codec, Direction, Error, Gpu, RateControl};
1313
1414 /// Encoder settings.
1515 #[derive(Debug, Clone, Copy, PartialEq, Eq)]