forge
Explore
Log in

Don't you dare go Hollow

⚡ engine-hw on ec_hw::HwDecoder/HwEncoder (Vulkan Video first, VA-API fallback): 4K HEVC Main10 hw export 32.9 -> 153 fps, decode bit-exact; per-picture readback or DMA-BUF export; capabilities from ec_hw

Browse files at this commit

ff99ad61bd8ccdc89c71277150f10d4ee298234aAhmet Kaan GümüşParent: 527b49c
Cargo.lockmodified+36 -1
@@ -1665,11 +1665,14 @@ dependencies = [
1665 name = "ec-hw"1665 name = "ec-hw"
1666 version = "0.1.0"1666 version = "0.1.0"
1667 dependencies = [1667 dependencies = [
1668+ "ec-av1",
1668 "ec-av1-syntax",1669 "ec-av1-syntax",
1669 "ec-core",1670 "ec-core",
1671+ "ec-dsp",
1670 "ec-h264-syntax",1672 "ec-h264-syntax",
1671 "ec-h265-syntax",1673 "ec-h265-syntax",
1672 "ec-va",1674 "ec-va",
1675+ "ec-vk",
1673 "ec-vp9-syntax",1676 "ec-vp9-syntax",
1674 ]1677 ]
1675 1678
@@ -1836,6 +1839,13 @@ dependencies = [
1836 "cros-libva",1839 "cros-libva",
1837 ]1840 ]
1838 1841
1842+[[package]]
1843+name = "ec-vk"
1844+version = "0.1.0"
1845+dependencies = [
1846+ "vk-video-ffi",
1847+]
1848+
1839 [[package]]1849 [[package]]
1840 name = "ec-vorbis"1850 name = "ec-vorbis"
1841 version = "0.1.0"1851 version = "0.1.0"
@@ -1989,7 +1999,6 @@ version = "0.1.0"
1989 dependencies = [1999 dependencies = [
1990 "bytemuck",2000 "bytemuck",
1991 "ec-hw",2001 "ec-hw",
1992- "ec-va",
1993 "ec-vp8",2002 "ec-vp8",
1994 "engine",2003 "engine",
1995 ]2004 ]
@@ -6698,6 +6707,13 @@ version = "0.9.5"
6698 source = "registry+https://github.com/rust-lang/crates.io-index"6707 source = "registry+https://github.com/rust-lang/crates.io-index"
6699 checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"6708 checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
6700 6709
6710+[[package]]
6711+name = "vk-video-ffi"
6712+version = "0.1.0"
6713+dependencies = [
6714+ "vulkanalia",
6715+]
6716+
6701 [[package]]6717 [[package]]
6702 name = "vswhom"6718 name = "vswhom"
6703 version = "0.1.0"6719 version = "0.1.0"
@@ -6718,6 +6734,25 @@ dependencies = [
6718 "libc",6734 "libc",
6719 ]6735 ]
6720 6736
6737+[[package]]
6738+name = "vulkanalia"
6739+version = "0.35.0"
6740+source = "registry+https://github.com/rust-lang/crates.io-index"
6741+checksum = "ebd71d6c64383bbdf1c260efa22e81e1a2a7dd832a3831af34495f47d7551d7b"
6742+dependencies = [
6743+ "libloading",
6744+ "vulkanalia-sys",
6745+]
6746+
6747+[[package]]
6748+name = "vulkanalia-sys"
6749+version = "0.35.0"
6750+source = "registry+https://github.com/rust-lang/crates.io-index"
6751+checksum = "08d4da5d5e0c7377cea24358fa238b3b22a1913a7890f65dbd8ff9aa371a493a"
6752+dependencies = [
6753+ "bitflags 1.3.2",
6754+]
6755+
6721 [[package]]6756 [[package]]
6722 name = "waker-fn"6757 name = "waker-fn"
6723 version = "1.2.0"6758 version = "1.2.0"
crates/engine-hw/Cargo.tomlmodified+0 -2
@@ -18,8 +18,6 @@ path = "src/bin/hw-child.rs"
18 [dependencies]18 [dependencies]
19 bytemuck = "1.25"19 bytemuck = "1.25"
20 engine = { path = "../engine" }20 engine = { path = "../engine" }
21-# The decode seat: ec-hw drives the VA-API decoders, ec-va the display under it.
22 ec-hw = { path = "../../../edith_codecs/crates/ec-hw" }21 ec-hw = { path = "../../../edith_codecs/crates/ec-hw" }
23-ec-va = { path = "../../../edith_codecs/crates/ec-va" }
24 # The software VP8 seat, this project's own (`ec-vp8`, RFC 6386).22 # The software VP8 seat, this project's own (`ec-vp8`, RFC 6386).
25 ec-vp8 = { path = "../../../edith_codecs/crates/ec-vp8" }23 ec-vp8 = { path = "../../../edith_codecs/crates/ec-vp8" }
crates/engine-hw/src/child.rsmodified+1 -1
@@ -491,7 +491,7 @@ enum Seat {
491 impl Seat {491 impl Seat {
492 fn dma_geometry(&self) -> Option<(u32, u32)> {492 fn dma_geometry(&self) -> Option<(u32, u32)> {
493 match self {493 match self {
494- Self::Real(encoder) => Some(encoder.coded_size()),494+ Self::Real(encoder) => encoder.coded_size(),
495 // Nothing to import into, so the parent stages pictures instead.495 // Nothing to import into, so the parent stages pictures instead.
496 Self::Fake => None,496 Self::Fake => None,
497 }497 }
crates/engine-hw/src/enc_ec.rsmodified+60 -125
@@ -1,21 +1,20 @@
1-//! The encode seats, on [`ec_hw::Encoder`]: H.264 (Main profile), HEVC and AV1.1+//! The encode seats, on [`ec_hw::HwEncoder`]: H.264 (Main profile), HEVC and AV1.
2 //!2 //!
3-//! A picture reaches the encoder one of two ways. Pixels the caller holds are3+//! Pixels the caller holds are packed I420 and go through [`ec_hw::EncodeInput::I420`]
4-//! packed I420 and go through [`ec_hw::Encoder::encode`], which uploads them4+//! (or `I420_16` for 10-bit). A picture the decoder left on the GPU arrives as a
5-//! into a pooled surface. A picture the decoder left on the GPU arrives as a5+//! DRM-PRIME descriptor ([`DmaFrame`]) and goes through [`ec_hw::EncodeInput::DmaBufYuv`],
6-//! DRM-PRIME descriptor ([`DmaFrame`]); its file descriptors are duplicated into6+//! which the encoder imports and caches itself. The backend, Vulkan or VA-API, is the
7-//! an [`ec_va::PrimeSurface`], imported with [`ec_va::import_prime`]7+//! one [`ec_hw::HwEncoder::open`] picks.
8-//! and read in place by [`ec_hw::Encoder::encode_surface`], so no copy is made.
9 8
10 use std::collections::VecDeque;9 use std::collections::VecDeque;
11-use std::os::fd::{AsFd, OwnedFd};10+use std::os::fd::{AsFd, BorrowedFd};
12-use std::rc::Rc;
13 11
14-use ec_hw::enc::{EncCodec, EncoderConfig, FrameMetadata, RateControlMode};12+use ec_hw::{
15-use ec_hw::{Encoder, H264Profile, I420, I420_16};13+ Backend, DmaBufFormat, DmaBufPlane, DmaBufYuvFrame, EncCodec, EncodeInput, EncoderConfig,
16-use ec_va::{PrimeLayer, PrimeObject, PrimeSurface};14+ FrameMetadata, H264Profile, HwEncoder, I420, I420_16, RateControlMode,
15+};
17 16
18-use engine::hw::{DmaFrame, VhDma};17+use engine::hw::DmaFrame;
19 use engine::hwproc::SeatRate;18 use engine::hwproc::SeatRate;
20 19
21 /// `DRM_FORMAT_NV12`, which is also `VA_FOURCC_NV12`: the four characters.20 /// `DRM_FORMAT_NV12`, which is also `VA_FOURCC_NV12`: the four characters.
@@ -25,30 +24,18 @@ const FOURCC_P010: u32 = u32::from_le_bytes(*b"P010");
25 24
26 /// One hardware encode session on `ec_hw`.25 /// One hardware encode session on `ec_hw`.
27 pub(crate) struct EcEncSession {26 pub(crate) struct EcEncSession {
28- display: Rc<ec_va::Display>,27+ encoder: HwEncoder,
29- encoder: Encoder,
30 /// Display size: what is encoded.28 /// Display size: what is encoded.
31 width: usize,29 width: usize,
32 height: usize,30 height: usize,
33- /// Macroblock- or block-aligned size the driver codes at.
34- coded: (u32, u32),
35 timestamp: i64,31 timestamp: i64,
36 /// Access units the encoder has finished but the caller has not taken yet,32 /// Access units the encoder has finished but the caller has not taken yet,
37 /// in encode order (which is display order: no B-frames).33 /// in encode order (which is display order: no B-frames).
38 ready: VecDeque<Vec<u8>>,34 ready: VecDeque<Vec<u8>>,
39 /// The access unit currently handed out, kept alive until the next call.35 /// The access unit currently handed out, kept alive until the next call.
40 out: Vec<u8>,36 out: Vec<u8>,
41- ten_bit: bool,
42- /// Imported decoder buffers, by the dma-buf inodes and layout they came as:
43- /// the decoder hands the same few surfaces out again and again, and a fresh
44- /// import costs the GPU a new mapping on its first use.
45- imports: VecDeque<(ImportKey, Rc<ec_va::va::Surface<ec_va::surface::PrimeImport>>)>,
46 }37 }
47 38
48-type ImportKey = (Vec<u64>, VhDma);
49-
50-const IMPORTS_MAX: usize = 32;
51-
52 /// The `open` arguments, for any of the three codecs.39 /// The `open` arguments, for any of the three codecs.
53 pub(crate) struct EcOpen {40 pub(crate) struct EcOpen {
54 pub codec: EncCodec,41 pub codec: EncCodec,
@@ -63,7 +50,7 @@ pub(crate) struct EcOpen {
63 pub gop: Option<u32>,50 pub gop: Option<u32>,
64 /// Colour description for the VUI as `(primaries, transfer, matrix, full)`.51 /// Colour description for the VUI as `(primaries, transfer, matrix, full)`.
65 pub colour: Option<(u8, u8, u8, bool)>,52 pub colour: Option<(u8, u8, u8, bool)>,
66- /// HEVC Main10: pictures go through [`EcEncSession::encode16`].53+ /// HEVC Main10: pictures go through [`EcEncSession::encode16_owned`].
67 pub ten_bit: bool,54 pub ten_bit: bool,
68 }55 }
69 56
@@ -122,20 +109,14 @@ impl EcEncSession {
122 if ten_bit {109 if ten_bit {
123 config = config.ten_bit();110 config = config.ten_bit();
124 }111 }
125- let display = ec_va::open().ok()?;112+ let encoder = HwEncoder::open(config, None).ok()?;
126- let encoder = Encoder::new(&display, config).ok()?;
127- let coded = encoder.coded_size();
128 Some(Self {113 Some(Self {
129- display,
130 encoder,114 encoder,
131 width: width as usize,115 width: width as usize,
132 height: height as usize,116 height: height as usize,
133- coded,
134 timestamp: 0,117 timestamp: 0,
135 ready: VecDeque::new(),118 ready: VecDeque::new(),
136- imports: VecDeque::new(),
137 out: Vec::new(),119 out: Vec::new(),
138- ten_bit,
139 })120 })
140 }121 }
141 122
@@ -163,7 +144,11 @@ impl EcEncSession {
163 bit_depth: 10,144 bit_depth: 10,
164 };145 };
165 let meta = self.meta(force_keyframe);146 let meta = self.meta(force_keyframe);
166- if let Some(coded) = self.encoder.submit_16(&picture, meta).map_err(|e| e.to_string())? {147+ if let Some(coded) = self
148+ .encoder
149+ .submit(EncodeInput::I420_16(&picture), meta)
150+ .map_err(|e| e.to_string())?
151+ {
167 self.ready.push_back(coded.data);152 self.ready.push_back(coded.data);
168 }153 }
169 Ok(())154 Ok(())
@@ -176,9 +161,13 @@ impl EcEncSession {
176 Ok(())161 Ok(())
177 }162 }
178 163
179- /// The surface size the driver codes at, as the caller must describe it.164+ /// The size a DMA-BUF picture must be described at, or `None` when the
180- pub(crate) fn coded_size(&self) -> (u32, u32) {165+ /// backend takes no DMA-BUF input (VA-API).
181- self.coded166+ 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+ }
182 }171 }
183 172
184 /// Codes one packed I420 picture (`y`, `u`, `v` at the session's size) and173 /// Codes one packed I420 picture (`y`, `u`, `v` at the session's size) and
@@ -203,7 +192,11 @@ impl EcEncSession {
203 height: h as u32,192 height: h as u32,
204 };193 };
205 let meta = self.meta(force_keyframe);194 let meta = self.meta(force_keyframe);
206- if let Some(coded) = self.encoder.submit(&picture, meta).map_err(|e| e.to_string())? {195+ if let Some(coded) = self
196+ .encoder
197+ .submit(EncodeInput::I420(&picture), meta)
198+ .map_err(|e| e.to_string())?
199+ {
207 self.ready.push_back(coded.data);200 self.ready.push_back(coded.data);
208 }201 }
209 Ok(())202 Ok(())
@@ -211,55 +204,43 @@ impl EcEncSession {
211 204
212 /// Codes one picture the decoder left on the GPU, read in place.205 /// Codes one picture the decoder left on the GPU, read in place.
213 ///206 ///
214- /// The descriptors stay owned by `frame`: they are duplicated into the207+ /// The descriptors stay owned by `frame`; the encoder duplicates them on import.
215- /// imported surface, which owns its copies until it is dropped at the end
216- /// of this call.
217 pub(crate) fn encode_dma(&mut self, frame: &DmaFrame, force_keyframe: bool) -> Result<(), String> {208 pub(crate) fn encode_dma(&mut self, frame: &DmaFrame, force_keyframe: bool) -> Result<(), String> {
218- let inodes = frame209+ let format = match (frame.desc.fourcc, frame.fds.len()) {
219- .fds210+ (FOURCC_NV12, 1 | 2) => DmaBufFormat::Nv12,
220- .iter()211+ (FOURCC_P010, 1 | 2) => DmaBufFormat::P010,
221- .map(|fd| {212+ _ => return Err("DMA-BUF is not an NV12 or P010 picture on the GPU".into()),
222- use std::os::unix::fs::MetadataExt;213+ };
223- Some(std::fs::File::from(fd.try_clone().ok()?).metadata().ok()?.ino())214+ let fds: Vec<BorrowedFd> = frame.fds.iter().map(|fd| fd.as_fd()).collect();
224- })215+ let desc = &frame.desc;
225- .collect::<Option<Vec<u64>>>();216+ let chroma_fd = if fds.len() == 2 { 1 } else { 0 };
226- let key = inodes.map(|inodes| (inodes, frame.desc));217+ let input = DmaBufYuvFrame {
227- let cached = key218+ fds: &fds,
228- .as_ref()219+ planes: [
229- .and_then(|key| self.imports.iter().find(|(k, _)| k == key))220+ DmaBufPlane {
230- .map(|(_, surface)| Rc::clone(surface));221+ fd: 0,
231- let surface = match cached {222+ offset: desc.offset[0],
232- Some(surface) => surface,223+ pitch: desc.stride[0],
233- None => {224+ },
234- let prime = prime_from_vhdma(&frame.desc, &frame.fds)?;225+ DmaBufPlane {
235- let surface = Rc::new(ec_va::import_prime(&self.display, &prime).map_err(|e| e.to_string())?);226+ fd: chroma_fd,
236- if let Some(key) = key {227+ offset: desc.offset[1],
237- self.imports.push_back((key, Rc::clone(&surface)));228+ pitch: desc.stride[1],
238- if self.imports.len() > IMPORTS_MAX {229+ },
239- self.imports.pop_front();230+ ],
240- }231+ width: self.width as u32,
241- }232+ height: self.height as u32,
242- surface233+ modifier: desc.modifier,
243- }234+ format,
244 };235 };
245- let display = (self.width as u32, self.height as u32);
246 let meta = self.meta(force_keyframe);236 let meta = self.meta(force_keyframe);
247- if self.ten_bit {
248 if let Some(coded) = self237 if let Some(coded) = self
249 .encoder238 .encoder
250- .submit_prime(surface, meta)239+ .submit(EncodeInput::DmaBufYuv(&input), meta)
251 .map_err(|e| e.to_string())?240 .map_err(|e| e.to_string())?
252 {241 {
253 self.ready.push_back(coded.data);242 self.ready.push_back(coded.data);
254 }243 }
255- } else {
256- self.flush()?;
257- let coded = self
258- .encoder
259- .encode_surface(&surface, display, meta)
260- .map_err(|e| e.to_string())?;
261- self.ready.push_back(coded.data);
262- }
263 Ok(())244 Ok(())
264 }245 }
265 246
@@ -280,49 +261,3 @@ impl EcEncSession {
280 Some(&self.out)261 Some(&self.out)
281 }262 }
282 }263 }
283-
284-/// Builds the PRIME descriptor for an NV12 or P010 picture the decoder holds.
285-///
286-/// Luma and chroma are either two objects (two descriptors) or one object
287-/// holding both at their own offsets, as the decoder's descriptor says.
288-fn prime_from_vhdma(desc: &VhDma, fds: &[OwnedFd]) -> Result<PrimeSurface, String> {
289- if fds.is_empty() || fds.len() > 2 || !matches!(desc.fourcc, FOURCC_NV12 | FOURCC_P010) {
290- return Err("DMA-BUF is not an NV12 or P010 picture on the GPU".into());
291- }
292- let (w, h) = (desc.coded_width, desc.coded_height);
293- let rows = [h, h / 2];
294- let two_objects = fds.len() == 2;
295- let mut objects = Vec::with_capacity(fds.len());
296- for fd in fds {
297- objects.push(PrimeObject {
298- fd: fd.as_fd().try_clone_to_owned().map_err(|e| e.to_string())?,
299- size: 0,
300- modifier: desc.modifier,
301- });
302- }
303- // The size each object must cover, luma rows then chroma rows.
304- for (plane, &plane_rows) in rows.iter().enumerate() {
305- let index = if two_objects { plane } else { 0 };
306- let end = desc.offset[plane] as u64 + u64::from(desc.stride[plane]) * u64::from(plane_rows);
307- let size = &mut objects[index].size;
308- *size = (*size).max(u32::try_from(end).map_err(|_| "DMA-BUF too large")?);
309- }
310- let layer = PrimeLayer {
311- drm_format: desc.fourcc,
312- planes: vec![
313- (0, desc.offset[0], desc.stride[0]),
314- (
315- if two_objects { 1 } else { 0 },
316- desc.offset[1],
317- desc.stride[1],
318- ),
319- ],
320- };
321- Ok(PrimeSurface {
322- fourcc: desc.fourcc,
323- width: w,
324- height: h,
325- objects,
326- layers: vec![layer],
327- })
328-}
crates/engine-hw/src/lib.rsmodified+78 -149
@@ -1,6 +1,6 @@
1 //! Hardware decode and encode, held in a child process. This library is the1 //! Hardware decode and encode, held in a child process. This library is the
2 //! whole world of the `hw-child` binary ([`child`]), the one process a video2 //! whole world of the `hw-child` binary ([`child`]), the one process a video
3-//! driver is allowed to kill: VA-API decode (H.264, HEVC, VP9 and AV1), VP83+//! driver is allowed to kill: Vulkan Video or VA-API decode (H.264, HEVC, VP9 and AV1), VP8
4 //! decode on `ec-vp8` ([`vpx`], software, linked in), and the encode seats4 //! decode on `ec-vp8` ([`vpx`], software, linked in), and the encode seats
5 //! (H.264, HEVC, and AV1 where the GPU has the entrypoint).5 //! (H.264, HEVC, and AV1 where the GPU has the entrypoint).
6 //!6 //!
@@ -18,11 +18,9 @@ mod vpx;
18 use std::collections::VecDeque;18 use std::collections::VecDeque;
19 use std::os::fd::OwnedFd;19 use std::os::fd::OwnedFd;
20 use std::path::Path;20 use std::path::Path;
21-use std::rc::Rc;
22 21
23-use ec_hw::Frame;
24 use ec_hw::enc::EncCodec as EcCodec;22 use ec_hw::enc::EncCodec as EcCodec;
25-use ec_va::caps::Profile;23+use ec_hw::{CodecProfile, Direction, HwPicture};
26 use enc_ec::{EcEncSession, EcOpen};24 use enc_ec::{EcEncSession, EcOpen};
27 use engine::demux::{Codec, Demuxer, VideoMeta};25 use engine::demux::{Codec, Demuxer, VideoMeta};
28 use engine::hw::{CAP_AV1, CAP_H264, CAP_HEVC, CAP_VP8, CAP_VP9, VhCaps, VhDma, VhMeta};26 use engine::hw::{CAP_AV1, CAP_H264, CAP_HEVC, CAP_VP8, CAP_VP9, VhCaps, VhDma, VhMeta};
@@ -105,10 +103,7 @@ fn forward_skip(_standing: u32, ahead: u32) -> u32 {
105 }103 }
106 104
107 struct Session {105 struct Session {
108- decoder: ec_hw::Decoder,106+ decoder: ec_hw::HwDecoder,
109- /// The VA-API display the decoder's context and surfaces live on: kept
110- /// alive for as long as the session is.
111- _display: Rc<ec_va::Display>,
112 demuxer: Demuxer,107 demuxer: Demuxer,
113 meta: VhMeta,108 meta: VhMeta,
114 timestamp: i64,109 timestamp: i64,
@@ -145,20 +140,14 @@ struct Session {
145 /// holds its surface out of the decoder's pool, so the decoder would write140 /// holds its surface out of the decoder's pool, so the decoder would write
146 /// the next picture into the one an encoder is still reading unless this141 /// the next picture into the one an encoder is still reading unless this
147 /// keeps the last [`DMA_HOLD`] of them alive.142 /// keeps the last [`DMA_HOLD`] of them alive.
148- held: VecDeque<Frame>,143+ held: VecDeque<HwPicture>,
149-}
150-
151-/// The VA-API display the decoders run on: the first render node that opens.
152-fn open_decode_display() -> Option<Rc<ec_va::Display>> {
153- ec_va::open().ok()
154 }144 }
155 145
156 impl Session {146 impl Session {
157- /// Assembles the VA-API half around a container that is already read --147+ /// Assembles the hardware half around a container that is already read --
158 /// [`OpenSession::open_at`] owns the read and routes VP8 away from here148 /// [`OpenSession::open_at`] owns the read and routes VP8 away from here
159 /// before any device is opened.149 /// before any device is opened.
160 fn opened(meta: VideoMeta, demuxer: Demuxer) -> Option<Self> {150 fn opened(meta: VideoMeta, demuxer: Demuxer) -> Option<Self> {
161- let display = open_decode_display()?;
162 let codec = match meta.codec {151 let codec = match meta.codec {
163 Codec::H264 => ec_hw::Codec::H264,152 Codec::H264 => ec_hw::Codec::H264,
164 Codec::Hevc => ec_hw::Codec::H265,153 Codec::Hevc => ec_hw::Codec::H265,
@@ -170,10 +159,9 @@ impl Session {
170 // Never offered to VA-API: `decode::hw_decodes` refuses it first.159 // Never offered to VA-API: `decode::hw_decodes` refuses it first.
171 Codec::Mpeg2 | Codec::ProRes | Codec::Dnxhd | Codec::Mjpeg | Codec::Dv | Codec::Mpeg4 | Codec::MsMpeg4 | Codec::Raw => return None,160 Codec::Mpeg2 | Codec::ProRes | Codec::Dnxhd | Codec::Mjpeg | Codec::Dv | Codec::Mpeg4 | Codec::MsMpeg4 | Codec::Raw => return None,
172 };161 };
173- let decoder = ec_hw::Decoder::new(&display, codec).ok()?;162+ let decoder = ec_hw::HwDecoder::open(codec).ok()?;
174 Some(Self {163 Some(Self {
175 decoder,164 decoder,
176- _display: display,
177 demuxer,165 demuxer,
178 meta: VhMeta {166 meta: VhMeta {
179 width: meta.width,167 width: meta.width,
@@ -246,7 +234,7 @@ impl Session {
246 /// Pumps the decoder until one picture is ready. `Ok(false)` is clean EOF.234 /// Pumps the decoder until one picture is ready. `Ok(false)` is clean EOF.
247 fn pump(&mut self) -> Result<bool, String> {235 fn pump(&mut self) -> Result<bool, String> {
248 loop {236 loop {
249- if let Some(frame) = self.decoder.next_frame() {237+ if let Some(frame) = self.decoder.next_picture().map_err(|e| e.to_string())? {
250 // One picture further along, shown or skipped past alike:238 // One picture further along, shown or skipped past alike:
251 // this is the only place [`Session::position`] walks.239 // this is the only place [`Session::position`] walks.
252 self.position += 1;240 self.position += 1;
@@ -296,7 +284,7 @@ impl Session {
296 /// Hands one decoded picture to the caller: as the buffer it was decoded284 /// Hands one decoded picture to the caller: as the buffer it was decoded
297 /// into where that is what the caller asked for and the encoder on the285 /// into where that is what the caller asked for and the encoder on the
298 /// other side can read it, and as read-back I420 everywhere else.286 /// other side can read it, and as read-back I420 everywhere else.
299- fn deliver(&mut self, frame: Frame) -> Result<(), String> {287+ fn deliver(&mut self, frame: HwPicture) -> Result<(), String> {
300 self.dma = None;288 self.dma = None;
301 if self.want.is_some()289 if self.want.is_some()
302 && let Some(dma) = self.export_dma(&frame)290 && let Some(dma) = self.export_dma(&frame)
@@ -320,68 +308,39 @@ impl Session {
320 /// objects, the fourcc and both sizes it asked for. `None` for every other308 /// objects, the fourcc and both sizes it asked for. `None` for every other
321 /// answer, and the caller then gets the pixels it always got rather than a309 /// answer, and the caller then gets the pixels it always got rather than a
322 /// failure.310 /// failure.
323- fn export_dma(&self, frame: &Frame) -> Option<(VhDma, Vec<OwnedFd>)> {311+ fn export_dma(&self, frame: &HwPicture) -> Option<(VhDma, Vec<OwnedFd>)> {
324 let want = self.want?;312 let want = self.want?;
325- let (w, h) = frame.display_size;313+ if (frame.width, frame.height) != (want.width, want.height) {
326- if (w, h) != (want.width, want.height) {
327- return None;
328- }
329- let prime = frame.export_prime().ok()?;
330- // The driver describes the NV12 buffer as one layer per plane (R8 and
331- // GR88, each one plane into the same object), or as one composed layer
332- // holding both: either is the same two planes, in that order.
333- let planes: Vec<(u32, u32, u32)> = match prime.layers.as_slice() {
334- [layer] => layer.planes.clone(),
335- [luma, chroma] => {
336- let ([y], [uv]) = (luma.planes.as_slice(), chroma.planes.as_slice()) else {
337 return None;314 return None;
338- };
339- vec![*y, *uv]
340 }315 }
341- _ => return None,316+ let pic = frame.export_dmabuf().ok()?;
342- };317+ let [plane0, plane1] = pic.planes;
343- let [(obj0, off0, pitch0), (obj1, off1, pitch1)] = planes.as_slice() else {318+ if pic.fourcc != want.fourcc
344- return None;319+ || pic.width < want.coded_width
345- };320+ || pic.height < want.coded_height
346- let fits = prime.width == want.coded_width && prime.height == want.coded_height;321+ || plane0.fd != 0
347- if prime.fourcc != want.fourcc322+ || plane1.fd > 1
348- || !fits323+ || pic.fds.len() != plane1.fd + 1
349- || *obj0 != 0
350- || *obj1 > 1
351- || prime.objects.len() != *obj1 as usize + 1
352 {324 {
353 return None;325 return None;
354 }326 }
355- let planes = [*obj0, *obj1];
356- let (offset, stride) = ([*off0, *off1], [*pitch0, *pitch1]);
357- // Whatever the driver says the two planes live in, said back to it
358- // unchanged on the import: radeonsi answers with an object per plane,
359- // other drivers with one for both, and neither is ours to reinterpret.
360- let modifier = prime.objects[0].modifier;
361- let mut objects = prime.objects.into_iter();
362- // Owned by the caller from here: they travel to the encoder with the
363- // descriptor, one per plane object.
364- let mut fds = vec![objects.next()?.fd];
365- if planes[1] == 1 {
366- fds.push(objects.next()?.fd);
367- }
368 Some((327 Some((
369 VhDma {328 VhDma {
370- fourcc: prime.fourcc,329+ fourcc: pic.fourcc,
371- modifier,330+ modifier: pic.modifier,
372- coded_width: prime.width,331+ coded_width: pic.width,
373- coded_height: prime.height,332+ coded_height: pic.height,
374- width: w,333+ width: frame.width,
375- height: h,334+ height: frame.height,
376- offset,335+ offset: [plane0.offset, plane1.offset],
377- stride,336+ stride: [plane0.pitch, plane1.pitch],
378 },337 },
379- fds,338+ pic.fds,
380 ))339 ))
381 }340 }
382 341
383 /// Copies a decoded picture into `self.out` as packed I420.342 /// Copies a decoded picture into `self.out` as packed I420.
384- fn emit(&mut self, frame: &Frame) -> Result<(), String> {343+ fn emit(&mut self, frame: &HwPicture) -> Result<(), String> {
385 // The read-back goes through the driver's image copy (`vaGetImage`)344 // The read-back goes through the driver's image copy (`vaGetImage`)
386 // rather than a CPU map of the surface: on a discrete GPU that buffer345 // rather than a CPU map of the surface: on a discrete GPU that buffer
387 // lives in VRAM, and a CPU read of it runs over the PCIe BAR.346 // lives in VRAM, and a CPU read of it runs over the PCIe BAR.
@@ -709,96 +668,66 @@ fn copy_plane(src: &[u8], src_stride: usize, dst: &mut [u8], w: usize, h: usize)
709 }668 }
710 }669 }
711 670
712-/// One row of [`CAP_TABLE`]: the capability bit, its 8-bit and 10-bit decode profiles, and its encode profile.671+/// This machine's decode and encode seats, as the hardware backends report
713-type CapRow = (u32, &'static [Profile], &'static [Profile], Option<Profile>);672+/// them. `None` when there are none at all, the same "software only" a missing
714-673+/// plugin means.
715-/// What each codec needs of the driver before this plugin can claim it: the674+///
716-/// 8-bit decode profiles, the 10-bit ones, and the profile the *encoder* here675+/// VP8 is the one bit asked of nobody: it is this plugin's own native seat
717-/// would open -- `None` for the one this plugin has no encoder for at all, so a676+/// (`vpx`, `ec-vp8` linked in), lit unconditionally.
718-/// GPU with a VP9 encode entrypoint is never reported as one edith can677+fn query_caps() -> Option<VhCaps> {
719-/// reach. The encode profiles are the very ones the seats in [`enc_ec`] and678+ let caps = ec_hw::capabilities();
720-/// [`EncSession::open_seat`] ask for, which is what keeps this a description of the plugin rather than a679+ if caps.is_empty() {
721-/// second opinion about it.680+ return None;
722-const CAP_TABLE: [CapRow; 4] = [681+ }
723- (682+ let decode = |profile: CodecProfile| {
724- CAP_H264,683+ caps.iter()
725- &[684+ .any(|c| c.direction == Direction::Decode && c.profile == profile)
726- Profile::H264ConstrainedBaseline,685+ };
727- Profile::H264Main,686+ let encode = |profile: CodecProfile| {
728- Profile::H264High,687+ caps.iter()
729- ],688+ .any(|c| c.direction == Direction::Encode && c.profile == profile)
730- &[],689+ };
731- Some(Profile::H264Main),690+ let h264_decode = caps
732- ),691+ .iter()
692+ .any(|c| c.direction == Direction::Decode && c.codec == ec_hw::Codec::H264);
693+ let h264_encode = caps
694+ .iter()
695+ .any(|c| c.direction == Direction::Encode && c.codec == ec_hw::Codec::H264);
696+ let table = [
697+ (CAP_H264, h264_decode, false, h264_encode),
733 (698 (
734 CAP_HEVC,699 CAP_HEVC,
735- &[Profile::HEVCMain],700+ decode(CodecProfile::H265Main),
736- &[Profile::HEVCMain10],701+ decode(CodecProfile::H265Main10),
737- // 8-bit Main only: the encoder here opens Main whatever the source was,702+ encode(CodecProfile::H265Main),
738- // so a Main 10 entrypoint is a *decode* claim on this line and nothing
739- // more. Main 10 encode would be a second profile here and a 10-bit input
740- // buffer in `EncSession`, neither of which exists yet.
741- Some(Profile::HEVCMain),
742 ),703 ),
743 (704 (
744 CAP_VP9,705 CAP_VP9,
745- &[Profile::VP9Profile0],706+ decode(CodecProfile::Vp9Profile0),
746- &[Profile::VP9Profile2],707+ decode(CodecProfile::Vp9Profile2),
747- None,708+ false,
748 ),709 ),
749 (710 (
750 CAP_AV1,711 CAP_AV1,
751- &[Profile::AV1Profile0],712+ decode(CodecProfile::Av1Main),
752- // AV1 carries 8- and 10-bit in the same profile 0, so the profile bit713+ decode(CodecProfile::Av1Main10),
753- // is the same one and the P010 read-back is what decides.714+ encode(CodecProfile::Av1Main),
754- &[Profile::AV1Profile0],
755- Some(Profile::AV1Profile0),
756 ),715 ),
757 ];716 ];
758-717+ let mut out = VhCaps::default();
759-/// This machine's decode and encode seats, asked of the driver rather than718+ for (bit, eight, ten, enc) in table {
760-/// assumed: which profiles it has, which entrypoints each of those carries, and719+ if eight {
761-/// whether a P010 image exists to read a 10-bit picture back through. Only720+ out.decode |= bit;
762-/// codecs this plugin actually implements can light up -- `CAP_TABLE` is that721+ }
763-/// half of the intersection.722+ if ten {
764-///723+ out.decode_10bit |= bit;
765-/// VP8 is the one bit asked of nobody: it is this plugin's own native seat724+ }
766-/// (`vpx`, `ec-vp8` linked in), lit unconditionally -- no profile, no725+ if enc {
767-/// entrypoint, no display, no library to load. It rides along only when the726+ out.encode |= bit;
768-/// display *is* answerable, because this symbol's shape says a displayless727+ }
769-/// machine has nothing to report at all; the decode path itself needs no728+ }
770-/// display for it ([`OpenSession::open_at`] routes VP8 before any device729+ out.decode |= CAP_VP8;
771-/// opens).730+ Some(out)
772-///
773-/// `None` when there is no display to ask at all, which is the same "software
774-/// only" a missing plugin means.
775-fn query_caps() -> Option<VhCaps> {
776- use ec_va::caps::Entrypoint;
777- let display = open_decode_display()?;
778- let report = ec_va::CapReport::probe(&display).ok()?;
779- let p010 = report.image_formats.contains(&VA_FOURCC_P010);
780- let decodes = |list: &[Profile]| list.iter().any(|&p| report.supports(p, Entrypoint::VLD));
781- let mut caps = VhCaps::default();
782- for (bit, eight, ten, encode) in CAP_TABLE {
783- if decodes(eight) {
784- caps.decode |= bit;
785- }
786- if p010 && decodes(ten) {
787- caps.decode_10bit |= bit;
788- }
789- // Both entrypoints, exactly as the encoder's own open takes either.
790- if encode.is_some_and(|p| {
791- report.supports(p, Entrypoint::EncSlice) || report.supports(p, Entrypoint::EncSliceLP)
792- }) {
793- caps.encode |= bit;
794- }
795- }
796- // The plugin's own software decoder, on its own account rather than the
797- // driver's -- the plugin's capability, never a GPU feat. Native now, so
798- // the bit has no "when it loads" condition left: it lights on every
799- // machine this plugin runs on.
800- caps.decode |= CAP_VP8;
801- Some(caps)
802 }731 }
803 732
804 /// How many pictures a group of them holds -- the low-delay predictor's733 /// How many pictures a group of them holds -- the low-delay predictor's
crates/engine/src/export.rsmodified+1 -1
@@ -1411,7 +1411,7 @@ fn hevc_irap(au: &[u8]) -> bool {
1411 1411
1412 /// What a hardware encode is called wherever one is named -- the card's line1412 /// What a hardware encode is called wherever one is named -- the card's line
1413 /// before the export and the progress line during it.1413 /// before the export and the progress line during it.
1414-const HW_LABEL: &str = "HW encode (VA-API)";1414+const HW_LABEL: &str = "HW encode (GPU)";
1415 1415
1416 /// ...and what a card says instead where [`EncoderSeat::Hardware`] was picked1416 /// ...and what a card says instead where [`EncoderSeat::Hardware`] was picked
1417 /// and there is no seat: the export's own refusal in the width of a card row,1417 /// and there is no seat: the export's own refusal in the width of a card row,
crates/mcp/src/tools/export.rsmodified+2 -2
@@ -2381,7 +2381,7 @@ mod tests {
2381 2381
2382 #[test]2382 #[test]
2383 fn picture_label_names_the_engine_seat_then_the_plan_and_skips_audio_only() {2383 fn picture_label_names_the_engine_seat_then_the_plan_and_skips_audio_only() {
2384- let measured = Some("HW encode (VA-API) · AAC · SW encode (ec-aac)".to_string());2384+ let measured = Some("HW encode (GPU) · AAC · SW encode (ec-aac)".to_string());
2385 assert_eq!(picture_label(measured, "SW encode (rav1e)", Format::Mp4), " · video: H.264 (hardware)");2385 assert_eq!(picture_label(measured, "SW encode (rav1e)", Format::Mp4), " · video: H.264 (hardware)");
2386 assert_eq!(picture_label(None, "SW encode (ec-h264)", Format::Mp4), " · video: H.264 (software)");2386 assert_eq!(picture_label(None, "SW encode (ec-h264)", Format::Mp4), " · video: H.264 (software)");
2387 assert_eq!(picture_label(Some("copy · AAC".into()), "SW encode (ec-h264)", Format::Mp4), " · video: H.264 (copy)");2387 assert_eq!(picture_label(Some("copy · AAC".into()), "SW encode (ec-h264)", Format::Mp4), " · video: H.264 (copy)");
@@ -2404,7 +2404,7 @@ mod tests {
2404 assert_eq!(av_words(Format::Wav, "", "PCM · SW (hound)"), "audio: PCM, container: WAV");2404 assert_eq!(av_words(Format::Wav, "", "PCM · SW (hound)"), "audio: PCM, container: WAV");
2405 assert_eq!(av_words(Format::Gif, "", ""), "no sound, container: GIF");2405 assert_eq!(av_words(Format::Gif, "", ""), "no sound, container: GIF");
2406 assert_eq!(av_words(Format::PngSequence, "", ""), "no sound, container: PNG folder");2406 assert_eq!(av_words(Format::PngSequence, "", ""), "no sound, container: PNG folder");
2407- assert_eq!(measured_sound(Some("HW encode (VA-API) · AAC · SW encode (ec-aac)")).as_deref(), Some("AAC"));2407+ assert_eq!(measured_sound(Some("HW encode (GPU) · AAC · SW encode (ec-aac)")).as_deref(), Some("AAC"));
2408 assert_eq!(measured_sound(Some("SW encode (ec-h264)")), None);2408 assert_eq!(measured_sound(Some("SW encode (ec-h264)")), None);
2409 assert_eq!(measured_sound(None), None);2409 assert_eq!(measured_sound(None), None);
2410 assert_eq!(plain_audio("no sound to write"), "none");2410 assert_eq!(plain_audio("no sound to write"), "none");