forge
Explore
Log in

Don't you dare go Hollow

HwDecoder::next_picture -> HwPicture (to_i420/to_i420_16/to_rgb/export_dmabuf per picture) on a reusable exportable output ring (stable fd inodes); old next_* as wrappers; CodecProfile H264ConstrainedBaseline/H264Main/Vp9Profile2

Browse files at this commit

e12d32fe3eccdd43c66cf72b83a8a47fe5cb36aaAhmet Kaan GümüşParent: dba774a

20 changed files +1121 -739

crates/ec-hw/examples/hw_decode.rsmodified+58 -0
@@ -5,7 +5,10 @@
55 //! cargo run -p ec-hw --example hw_decode -- <scratch dir>
66 //! ```
77
8+use std::collections::HashSet;
89 use std::fs;
10+use std::os::fd::AsRawFd;
11+use std::os::unix::fs::MetadataExt;
912 use std::path::{Path, PathBuf};
1013 use std::process::Command;
1114
@@ -112,9 +115,64 @@ fn main() {
112115 own_av1(&dir);
113116 vp9_cases(&dir);
114117 dmabuf_cases(&dir);
118+ mixed_cases(&dir);
115119 seek_case(&dir);
116120 }
117121
122+const MIXED_PASSES: usize = 2;
123+
124+fn mixed_cases(dir: &Path) {
125+ let h264 = fs::read(dir.join("bf1280.h264")).expect("read bf1280");
126+ let ten = fs::read(dir.join("ten.hevc")).expect("read ten.hevc");
127+ let gpu = ec_vk::Gpu::open().expect("Vulkan device");
128+ mixed_case("bf1280.h264", Codec::H264, &h264_units(&h264), false, &gpu);
129+ mixed_case("ten.hevc", Codec::H265, &nal_units(&ten), true, &gpu);
130+}
131+
132+fn mixed_case(label: &str, codec: Codec, units: &[&[u8]], ten: bool, gpu: &ec_vk::Gpu) {
133+ let mut reference = if ten {
134+ HwDecoder::open_16(codec)
135+ } else {
136+ HwDecoder::open(codec)
137+ }
138+ .expect("open decoder");
139+ let expected = decoded_planes(&mut reference, units, ten);
140+
141+ let mut decoder = HwDecoder::open(codec).expect("open mixed decoder");
142+ assert_eq!(decoder.backend(), Backend::Vk, "{label}: mixed must decode on Vulkan");
143+ let mut exports = 0usize;
144+ let mut inodes = HashSet::new();
145+ for _ in 0..MIXED_PASSES {
146+ decoder.reset();
147+ for (pts, unit) in units.iter().enumerate() {
148+ decoder.decode(unit, pts as i64).expect("decode mixed");
149+ }
150+ decoder.flush().expect("flush mixed");
151+ let mut index = 0usize;
152+ while let Some(picture) = decoder.next_picture().expect("next picture") {
153+ let planes = if ten && index % 2 == 0 {
154+ p010_planes(&picture.to_i420_16().expect("to_i420_16"))
155+ } else {
156+ let dmabuf = picture.export_dmabuf().expect("export DMA-BUF");
157+ for fd in &dmabuf.fds {
158+ let path = format!("/proc/self/fd/{}", fd.as_raw_fd());
159+ inodes.insert(fs::metadata(path).expect("fd inode").ino());
160+ }
161+ exports += 1;
162+ read_back(gpu, dmabuf)
163+ };
164+ assert!(planes == expected[index], "{label}: picture {index} differs");
165+ index += 1;
166+ }
167+ assert_eq!(index, expected.len(), "{label}: picture count");
168+ }
169+ assert!(inodes.len() < exports, "{label}: DMA-BUF slots are not reused");
170+ println!(
171+ "{label} mixed: {exports} DMA-BUF exports, {} distinct fd inodes, all pictures match",
172+ inodes.len(),
173+ );
174+}
175+
118176 fn dmabuf_cases(dir: &Path) {
119177 let h264 = fs::read(dir.join("bf1280.h264")).expect("read bf1280");
120178 dmabuf_case("bf1280.h264", Codec::H264, &h264_units(&h264), false);
crates/ec-hw/src/hevc_dpb.rsmodified+1 -0
@@ -22,6 +22,7 @@ pub(crate) enum Mark {
2222 pub(crate) struct StoredPicture<S> {
2323 pub(crate) surface: S,
2424 pub(crate) poc: i32,
25+ #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
2526 pub(crate) timestamp: i64,
2627 pub(crate) mark: Mark,
2728 /// Still to be handed to the caller.
crates/ec-hw/src/hw.rsmodified+56 -127
@@ -10,11 +10,10 @@ use std::cell::RefCell;
1010 use std::collections::VecDeque;
1111
1212 use crate::error::{Error, Result};
13-use crate::picture::{Decoded, I420, I420_16, RgbPicture};
13+use crate::output::HwPicture;
14+use crate::picture::{I420, I420_16, RgbPicture};
1415 #[cfg(target_os = "linux")]
15-use crate::picture::{DmaBufPicture, i420_to_rgb};
16-#[cfg(target_os = "linux")]
17-use ec_core::color::{ColorDescription, Matrix, Tags};
16+use crate::picture::DmaBufPicture;
1817 use crate::rate::{RateFeedback, hrd_buffer_ms};
1918 use crate::types::{
2019 Codec, CodedFrame, EncCodec, EncoderConfig, FrameMetadata, H264Profile, RateControlMode,
@@ -51,6 +50,10 @@ pub enum Direction {
5150 /// Profile of a [`Capability`], 4:2:0 only.
5251 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
5352 pub enum CodecProfile {
53+ /// H.264 Constrained Baseline, 8-bit.
54+ H264ConstrainedBaseline,
55+ /// H.264 Main, 8-bit.
56+ H264Main,
5457 /// H.264 High, 8-bit.
5558 H264High,
5659 /// H.265 Main, 8-bit.
@@ -63,6 +66,8 @@ pub enum CodecProfile {
6366 Av1Main10,
6467 /// VP9 Profile 0, 8-bit.
6568 Vp9Profile0,
69+ /// VP9 Profile 2, 10-bit.
70+ Vp9Profile2,
6671 }
6772
6873 /// One codec, profile, direction and backend this machine offers.
@@ -212,10 +217,12 @@ fn va_capabilities(out: &mut Vec<Capability>) {
212217 impl CodecProfile {
213218 fn codec(self) -> Codec {
214219 match self {
215- CodecProfile::H264High => Codec::H264,
220+ CodecProfile::H264ConstrainedBaseline
221+ | CodecProfile::H264Main
222+ | CodecProfile::H264High => Codec::H264,
216223 CodecProfile::H265Main | CodecProfile::H265Main10 => Codec::H265,
217224 CodecProfile::Av1Main | CodecProfile::Av1Main10 => Codec::Av1,
218- CodecProfile::Vp9Profile0 => Codec::Vp9,
225+ CodecProfile::Vp9Profile0 | CodecProfile::Vp9Profile2 => Codec::Vp9,
219226 }
220227 }
221228 }
@@ -225,10 +232,13 @@ fn va_profiles(profile: ec_va::Profile, rt_formats: u32) -> Vec<CodecProfile> {
225232 let yuv420 = ec_va::va::VA_RT_FORMAT_YUV420;
226233 let yuv420_10 = ec_va::va::VA_RT_FORMAT_YUV420_10;
227234 match profile {
235+ ec_va::Profile::H264ConstrainedBaseline => vec![CodecProfile::H264ConstrainedBaseline],
236+ ec_va::Profile::H264Main => vec![CodecProfile::H264Main],
228237 ec_va::Profile::H264High => vec![CodecProfile::H264High],
229238 ec_va::Profile::HEVCMain => vec![CodecProfile::H265Main],
230239 ec_va::Profile::HEVCMain10 => vec![CodecProfile::H265Main10],
231240 ec_va::Profile::VP9Profile0 => vec![CodecProfile::Vp9Profile0],
241+ ec_va::Profile::VP9Profile2 if rt_formats & yuv420_10 != 0 => vec![CodecProfile::Vp9Profile2],
232242 ec_va::Profile::AV1Profile0 => [
233243 (yuv420, CodecProfile::Av1Main),
234244 (yuv420_10, CodecProfile::Av1Main10),
@@ -249,6 +259,9 @@ fn vk_profile(profile: ec_vk::CodecProfile) -> CodecProfile {
249259 ec_vk::CodecProfile::Av1Main => CodecProfile::Av1Main,
250260 ec_vk::CodecProfile::Av1Main10 => CodecProfile::Av1Main10,
251261 ec_vk::CodecProfile::Vp9Profile0 => CodecProfile::Vp9Profile0,
262+ ec_vk::CodecProfile::Vp9Profile2 => CodecProfile::Vp9Profile2,
263+ ec_vk::CodecProfile::H264ConstrainedBaseline => CodecProfile::H264ConstrainedBaseline,
264+ ec_vk::CodecProfile::H264Main => CodecProfile::H264Main,
252265 }
253266 }
254267
@@ -948,7 +961,7 @@ impl VkDecoder {
948961 }
949962 }
950963
951- fn next_frame(&mut self) -> Option<(i64, Decoded)> {
964+ fn next_frame(&mut self) -> Option<HwPicture> {
952965 match self {
953966 VkDecoder::H264(d) => d.next_frame(),
954967 VkDecoder::H265(d) => d.next_frame(),
@@ -993,56 +1006,47 @@ pub struct RgbOutput {
9931006 pub max_width: Option<u32>,
9941007 }
9951008
996-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
997-pub(crate) enum Mode {
998- I420,
999- I420_16,
1000- Rgb(RgbOutput),
1001- #[cfg(target_os = "linux")]
1002- DmaBuf,
1003-}
1004-
10051009 /// A hardware decoder on whichever backend opened.
10061010 pub struct HwDecoder {
10071011 inner: DecInner,
10081012 born_epoch: u64,
10091013 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
10101014 codec: Codec,
1011- mode: Mode,
1015+ rgb: Option<RgbOutput>,
10121016 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
10131017 replay: Option<Vec<(Vec<u8>, i64)>>,
10141018 }
10151019
10161020 impl HwDecoder {
1017- /// Open a decoder for `codec` that hands out I420. Every codec tries Vulkan Video first, then VA-API (Linux).
1021+ /// Open a decoder for `codec`. Every codec tries Vulkan Video first, then VA-API (Linux).
10181022 pub fn open(codec: Codec) -> Result<HwDecoder> {
1019- HwDecoder::open_mode(codec, Mode::I420)
1023+ HwDecoder::open_with(codec, None)
10201024 }
10211025
1022- /// Open a decoder for `codec` that hands out packed RGB, converted on the GPU by Vulkan and on the CPU by VA-API.
1026+ /// Open a decoder for `codec` whose [`HwDecoder::next_rgb`] hands out packed RGB, converted on the GPU by Vulkan and on the CPU by VA-API.
10231027 pub fn open_rgb(codec: Codec, output: RgbOutput) -> Result<HwDecoder> {
1024- HwDecoder::open_mode(codec, Mode::Rgb(output))
1028+ HwDecoder::open_with(codec, Some(output))
10251029 }
10261030
1027- /// Open a decoder for `codec` that hands out 10-bit I420 ([`HwDecoder::next_frame_16`]). 8-bit streams are widened to 10 bits.
1031+ /// Same as [`HwDecoder::open`]: every picture can be asked for 10-bit I420 with [`HwPicture::to_i420_16`].
10281032 pub fn open_16(codec: Codec) -> Result<HwDecoder> {
1029- HwDecoder::open_mode(codec, Mode::I420_16)
1033+ HwDecoder::open(codec)
10301034 }
10311035
1032- /// Open a decoder for `codec` that hands out each picture as DMA-BUF file descriptors ([`HwDecoder::next_dmabuf`]). Linux only.
1036+ /// Same as [`HwDecoder::open`]: every picture can be asked for DMA-BUF file descriptors with [`HwPicture::export_dmabuf`]. Linux only.
10331037 #[cfg(target_os = "linux")]
10341038 pub fn open_dmabuf(codec: Codec) -> Result<HwDecoder> {
1035- HwDecoder::open_mode(codec, Mode::DmaBuf)
1039+ HwDecoder::open(codec)
10361040 }
10371041
1038- fn open_mode(codec: Codec, mode: Mode) -> Result<HwDecoder> {
1042+ fn open_with(codec: Codec, rgb: Option<RgbOutput>) -> Result<HwDecoder> {
10391043 let mut reasons = Vec::new();
10401044 let born_epoch = crate::reset::gpu_reset_epoch();
10411045 let vk = vk_grace().and_then(|()| match codec {
1042- Codec::H264 => VkH264Decoder::new(mode).map(VkDecoder::H264),
1043- Codec::H265 => VkH265Decoder::new(mode).map(VkDecoder::H265),
1044- Codec::Av1 => VkAv1Decoder::new(mode).map(VkDecoder::Av1),
1045- Codec::Vp9 => VkVp9Decoder::new(mode).map(VkDecoder::Vp9),
1046+ Codec::H264 => VkH264Decoder::new().map(VkDecoder::H264),
1047+ Codec::H265 => VkH265Decoder::new().map(VkDecoder::H265),
1048+ Codec::Av1 => VkAv1Decoder::new().map(VkDecoder::Av1),
1049+ Codec::Vp9 => VkVp9Decoder::new().map(VkDecoder::Vp9),
10461050 });
10471051 match vk {
10481052 Ok(inner) => {
@@ -1050,7 +1054,7 @@ impl HwDecoder {
10501054 inner: DecInner::Vk(inner),
10511055 born_epoch,
10521056 codec,
1053- mode,
1057+ rgb,
10541058 replay: Some(Vec::new()),
10551059 });
10561060 }
@@ -1064,7 +1068,7 @@ impl HwDecoder {
10641068 inner: DecInner::Va(inner),
10651069 born_epoch,
10661070 codec,
1067- mode,
1071+ rgb,
10681072 replay: None,
10691073 });
10701074 }
@@ -1115,93 +1119,59 @@ impl HwDecoder {
11151119 result
11161120 }
11171121
1118- /// The next picture in display order, as 8-bit I420 with its timestamp. An error on a decoder opened with [`HwDecoder::open_rgb`] or [`HwDecoder::open_16`].
1119- pub fn next_frame(&mut self) -> Result<Option<(i64, I420)>> {
1120- if self.mode != Mode::I420 {
1121- return Err(Error::config(
1122- "next_frame on a decoder not opened as 8-bit I420",
1123- ));
1122+ /// The next picture in display order, held in its decode slot until dropped. Convert it with the `to_*` methods of [`HwPicture`].
1123+ pub fn next_picture(&mut self) -> Result<Option<HwPicture>> {
1124+ self.pull()
11241125 }
1126+
1127+ /// The next picture in display order, as 8-bit I420 with its timestamp.
1128+ pub fn next_frame(&mut self) -> Result<Option<(i64, I420)>> {
11251129 match self.pull()? {
11261130 None => Ok(None),
1127- Some((ts, Decoded::I420(frame))) => Ok(Some((ts, frame))),
1128- Some(_) => Err(Error::config("non-I420 picture from an I420 decoder")),
1131+ Some(picture) => Ok(Some((picture.timestamp, picture.to_i420()?))),
11291132 }
11301133 }
11311134
1132- /// The next picture in display order, as 10-bit I420 with its timestamp. An error on a decoder not opened with [`HwDecoder::open_16`].
1135+ /// The next picture in display order, as 10-bit I420 with its timestamp.
11331136 pub fn next_frame_16(&mut self) -> Result<Option<(i64, I420_16)>> {
1134- if self.mode != Mode::I420_16 {
1135- return Err(Error::config(
1136- "next_frame_16 on a decoder not opened with open_16",
1137- ));
1138- }
11391137 match self.pull()? {
11401138 None => Ok(None),
1141- Some((ts, Decoded::I420_16(frame))) => Ok(Some((ts, frame))),
1142- Some(_) => Err(Error::config("non-16-bit picture from a 16-bit decoder")),
1139+ Some(picture) => Ok(Some((picture.timestamp, picture.to_i420_16()?))),
11431140 }
11441141 }
11451142
1146- /// The next picture in display order, as DMA-BUF file descriptors with its timestamp. An error on a decoder not opened with [`HwDecoder::open_dmabuf`].
1143+ /// The next picture in display order, as DMA-BUF file descriptors with its timestamp. Linux only.
11471144 #[cfg(target_os = "linux")]
11481145 pub fn next_dmabuf(&mut self) -> Result<Option<(i64, DmaBufPicture)>> {
1149- if self.mode != Mode::DmaBuf {
1150- return Err(Error::config(
1151- "next_dmabuf on a decoder not opened with open_dmabuf",
1152- ));
1153- }
11541146 match self.pull()? {
11551147 None => Ok(None),
1156- Some((ts, Decoded::DmaBuf(picture))) => Ok(Some((ts, picture))),
1157- Some(_) => Err(Error::config("non-DMA-BUF picture from a DMA-BUF decoder")),
1148+ Some(picture) => Ok(Some((picture.timestamp, picture.export_dmabuf()?))),
11581149 }
11591150 }
11601151
11611152 /// The next picture in display order, as packed RGB with its timestamp. An error on a decoder not opened with [`HwDecoder::open_rgb`].
11621153 pub fn next_rgb(&mut self) -> Result<Option<(i64, RgbPicture)>> {
1163- if !matches!(self.mode, Mode::Rgb(_)) {
1164- return Err(Error::config(
1165- "next_rgb on a decoder not opened with open_rgb",
1166- ));
1167- }
1154+ let output = self
1155+ .rgb
1156+ .ok_or_else(|| Error::config("next_rgb on a decoder not opened with open_rgb"))?;
11681157 match self.pull()? {
11691158 None => Ok(None),
1170- Some((ts, Decoded::Rgb(picture))) => Ok(Some((ts, picture))),
1171- Some(_) => Err(Error::config("non-RGB picture from an RGB decoder")),
1159+ Some(picture) => Ok(Some((picture.timestamp, picture.to_rgb(&output)?))),
11721160 }
11731161 }
11741162
1175- fn pull(&mut self) -> Result<Option<(i64, Decoded)>> {
1163+ fn pull(&mut self) -> Result<Option<HwPicture>> {
11761164 match &mut self.inner {
11771165 DecInner::Vk(d) => {
11781166 vk_session_alive(self.born_epoch)?;
1179- let frame = d.next_frame();
1180- if frame.is_some() {
1167+ let picture = d.next_frame();
1168+ if picture.is_some() {
11811169 self.replay = None;
11821170 }
1183- Ok(frame)
1171+ Ok(picture)
11841172 }
11851173 #[cfg(target_os = "linux")]
1186- DecInner::Va(d) => match d.next_frame() {
1187- Some(frame) => {
1188- let decoded = match self.mode {
1189- Mode::I420 => Decoded::I420(frame.to_i420()?),
1190- Mode::I420_16 => Decoded::I420_16(frame.to_i420_16()?),
1191- Mode::Rgb(output) => {
1192- let i420 = frame.to_i420()?;
1193- let matrix = frame
1194- .colour
1195- .map(|c| c.description.matrix)
1196- .unwrap_or_else(|| default_matrix(i420.height));
1197- Decoded::Rgb(va_rgb(&i420, output, matrix))
1198- }
1199- Mode::DmaBuf => Decoded::DmaBuf(dmabuf_from_prime(frame.export_prime()?)?),
1200- };
1201- Ok(Some((frame.timestamp, decoded)))
1202- }
1203- None => Ok(None),
1204- },
1174+ DecInner::Va(d) => Ok(d.next_frame().map(HwPicture::va)),
12051175 }
12061176 }
12071177
@@ -1225,47 +1195,6 @@ impl HwDecoder {
12251195 }
12261196 }
12271197
1228-#[cfg(target_os = "linux")]
1229-fn dmabuf_from_prime(surface: ec_va::PrimeSurface) -> Result<DmaBufPicture> {
1230- let planes: Vec<(u32, u32, u32)> = surface
1231- .layers
1232- .iter()
1233- .flat_map(|layer| layer.planes.iter().copied())
1234- .collect();
1235- let [y, uv] = planes.as_slice() else {
1236- return Err(Error::config("exported surface is not a two-plane 4:2:0 picture"));
1237- };
1238- let plane = |&(object, offset, pitch): &(u32, u32, u32)| DmaBufPlane {
1239- fd: object as usize,
1240- offset,
1241- pitch,
1242- };
1243- let modifier = surface.objects.first().map_or(0, |o| o.modifier);
1244- Ok(DmaBufPicture {
1245- fds: surface.objects.into_iter().map(|o| o.fd).collect(),
1246- fourcc: surface.fourcc,
1247- modifier,
1248- width: surface.width,
1249- height: surface.height,
1250- planes: [plane(y), plane(uv)],
1251- })
1252-}
1253-
1254-#[cfg(target_os = "linux")]
1255-fn default_matrix(height: u32) -> Matrix {
1256- ColorDescription::resolve(Tags::default(), Tags::default(), height).matrix
1257-}
1258-
1259-#[cfg(target_os = "linux")]
1260-fn va_rgb(frame: &I420, output: RgbOutput, matrix: Matrix) -> RgbPicture {
1261- i420_to_rgb(
1262- frame,
1263- output.max_width,
1264- output.order == RgbOrder::Bgra,
1265- matrix,
1266- )
1267-}
1268-
12691198 #[cfg(target_os = "linux")]
12701199 fn open_va_decoder(codec: Codec) -> Result<VaDecoder> {
12711200 let display = ec_va::open()?;
crates/ec-hw/src/lib.rsmodified+2 -0
@@ -70,6 +70,7 @@ pub(crate) mod hevc_dpb;
7070 pub mod hw;
7171 #[cfg(target_os = "linux")]
7272 pub mod frame;
73+pub(crate) mod output;
7374 pub mod picture;
7475 #[cfg(target_os = "linux")]
7576 pub mod params;
@@ -96,6 +97,7 @@ pub use hw::{
9697 };
9798 #[cfg(target_os = "linux")]
9899 pub use frame::Frame;
100+pub use output::HwPicture;
99101 pub use picture::{Colour, I420, I420_16, RgbPicture, i420_to_nv12, nv12_to_i420};
100102 #[cfg(target_os = "linux")]
101103 pub use picture::DmaBufPicture;
crates/ec-hw/src/output.rsadded+381 -0
@@ -0,0 +1,381 @@
1+//! What a decoder hands out: a picture held in its GPU ring slot (Vulkan) or
2+//! a VA-API frame, converted on request to I420, 10-bit I420, packed RGB or a
3+//! DMA-BUF.
4+
5+use std::cell::RefCell;
6+use std::rc::Rc;
7+
8+use ec_av1_syntax::{FilmGrainParams, SequenceHeader};
9+use ec_core::color::Matrix;
10+#[cfg(target_os = "linux")]
11+use ec_core::color::{ColorDescription, Tags};
12+use ec_vk::{
13+ Av1DecodeSession, H264DecodeSession, H265DecodeSession, Vp9DecodeSession,
14+};
15+
16+use crate::error::{Error, Result};
17+use crate::hw::{RgbOrder, RgbOutput};
18+use crate::picture::{
19+ Colour, I420, I420_16, RgbPicture, i420_to_rgb, rgb_size, semi_planar_to_i420,
20+ semi_planar_to_i420_16, yuv_to_rgb,
21+};
22+use crate::vkdec_av1::{synthesize, synthesize16};
23+#[cfg(target_os = "linux")]
24+use crate::frame::Frame;
25+#[cfg(target_os = "linux")]
26+use crate::picture::DmaBufPicture;
27+
28+/// One decoded picture, as a handle on its ring slot in the decode session.
29+pub struct HwPicture {
30+ /// Presentation timestamp of the access unit the picture came from.
31+ pub timestamp: i64,
32+ /// Display width in luma samples.
33+ pub width: u32,
34+ /// Display height in luma samples.
35+ pub height: u32,
36+ /// Luma bit depth: 8 or 10.
37+ pub bit_depth: u8,
38+ /// Colour metadata, when the decoder resolved some.
39+ pub colour: Option<Colour>,
40+ source: Source,
41+}
42+
43+enum Source {
44+ Vk(VkPicture),
45+ #[cfg(target_os = "linux")]
46+ Va(Frame),
47+}
48+
49+impl HwPicture {
50+ pub(crate) fn vk(timestamp: i64, picture: VkPicture) -> HwPicture {
51+ HwPicture {
52+ timestamp,
53+ width: picture.width,
54+ height: picture.height,
55+ bit_depth: picture.bit_depth,
56+ colour: None,
57+ source: Source::Vk(picture),
58+ }
59+ }
60+
61+ #[cfg(target_os = "linux")]
62+ pub(crate) fn va(frame: Frame) -> HwPicture {
63+ HwPicture {
64+ timestamp: frame.timestamp,
65+ width: frame.display_size.0,
66+ height: frame.display_size.1,
67+ bit_depth: frame.bit_depth,
68+ colour: frame.colour,
69+ source: Source::Va(frame),
70+ }
71+ }
72+
73+ /// 8-bit I420 at display size. A 10-bit picture is truncated to 8 bits.
74+ pub fn to_i420(&self) -> Result<I420> {
75+ match &self.source {
76+ Source::Vk(picture) => picture.i420(),
77+ #[cfg(target_os = "linux")]
78+ Source::Va(frame) => frame.to_i420(),
79+ }
80+ }
81+
82+ /// 10-bit I420 at display size. An 8-bit picture is widened to 10 bits.
83+ pub fn to_i420_16(&self) -> Result<I420_16> {
84+ match &self.source {
85+ Source::Vk(picture) => picture.i420_16(),
86+ #[cfg(target_os = "linux")]
87+ Source::Va(frame) => frame.to_i420_16(),
88+ }
89+ }
90+
91+ /// Packed RGB, scaled and byte-ordered as `output` asks.
92+ pub fn to_rgb(&self, output: &RgbOutput) -> Result<RgbPicture> {
93+ match &self.source {
94+ Source::Vk(picture) => picture.rgb(output),
95+ #[cfg(target_os = "linux")]
96+ Source::Va(frame) => {
97+ let i420 = frame.to_i420()?;
98+ let matrix = frame
99+ .colour
100+ .map(|c| c.description.matrix)
101+ .unwrap_or_else(|| default_matrix(i420.height));
102+ Ok(i420_to_rgb(
103+ &i420,
104+ output.max_width,
105+ output.order == RgbOrder::Bgra,
106+ matrix,
107+ ))
108+ }
109+ }
110+ }
111+
112+ /// One DMA-BUF of NV12 or P010 planes at display size. Not for a picture with film grain.
113+ #[cfg(target_os = "linux")]
114+ pub fn export_dmabuf(&self) -> Result<DmaBufPicture> {
115+ match &self.source {
116+ Source::Vk(picture) => picture.export(),
117+ Source::Va(frame) => Ok(dmabuf_from_prime(frame.export_prime()?)?),
118+ }
119+ }
120+}
121+
122+/// The GPU ring of one decode session: a token per slot, held by every picture still using the slot.
123+pub(crate) struct Ring {
124+ tokens: Vec<Rc<()>>,
125+}
126+
127+impl Ring {
128+ pub(crate) fn new(len: u32) -> Ring {
129+ Ring {
130+ tokens: (0..len).map(|_| Rc::new(())).collect(),
131+ }
132+ }
133+
134+ /// The first free slot, or a new one from `grow` when every slot is held.
135+ pub(crate) fn take(&mut self, grow: impl FnOnce() -> Result<u32>) -> Result<Slot> {
136+ let index = match self
137+ .tokens
138+ .iter()
139+ .position(|token| Rc::strong_count(token) == 1)
140+ {
141+ Some(index) => index,
142+ None => {
143+ let index = grow()? as usize;
144+ if index != self.tokens.len() {
145+ return Err(Error::config("output ring out of step with the decoder"));
146+ }
147+ self.tokens.push(Rc::new(()));
148+ index
149+ }
150+ };
151+ Ok(Slot {
152+ index: index as u32,
153+ _held: self.tokens[index].clone(),
154+ })
155+ }
156+}
157+
158+/// A ring slot in use. The slot is free again once every copy of this handle is dropped.
159+#[derive(Clone)]
160+pub(crate) struct Slot {
161+ index: u32,
162+ _held: Rc<()>,
163+}
164+
165+impl Slot {
166+ pub(crate) fn index(&self) -> u32 {
167+ self.index
168+ }
169+}
170+
171+/// The decode session's output images, shared with every picture decoded in it.
172+#[derive(Clone)]
173+pub(crate) enum Surfaces {
174+ H264(Rc<RefCell<H264DecodeSession>>),
175+ H265(Rc<RefCell<H265DecodeSession>>),
176+ Av1(Rc<RefCell<Av1DecodeSession>>),
177+ Vp9(Rc<RefCell<Vp9DecodeSession>>),
178+}
179+
180+impl Surfaces {
181+ fn nv12(&self, slot: u32, width: u32, height: u32) -> Result<(Vec<u8>, Vec<u8>)> {
182+ Ok(match self {
183+ Surfaces::H264(s) => s.borrow_mut().read_output(slot, width, height)?,
184+ Surfaces::H265(s) => s.borrow_mut().read_output(slot, width, height)?,
185+ Surfaces::Av1(s) => s.borrow_mut().read_output(slot, width, height)?,
186+ Surfaces::Vp9(s) => s.borrow_mut().read_output(slot, width, height)?,
187+ })
188+ }
189+
190+ fn rgb(
191+ &self,
192+ slot: u32,
193+ crop: (u32, u32, u32, u32),
194+ out: (u32, u32),
195+ bgra: bool,
196+ coeffs: [i32; 5],
197+ ) -> Result<Vec<u8>> {
198+ Ok(match self {
199+ Surfaces::H264(s) => s
200+ .borrow_mut()
201+ .read_output_rgb(slot, crop, out, bgra, coeffs)?,
202+ Surfaces::H265(s) => s
203+ .borrow_mut()
204+ .read_output_rgb(slot, crop, out, bgra, coeffs)?,
205+ Surfaces::Av1(s) => s
206+ .borrow_mut()
207+ .read_output_rgb(slot, crop, out, bgra, coeffs)?,
208+ Surfaces::Vp9(s) => s
209+ .borrow_mut()
210+ .read_output_rgb(slot, crop, out, bgra, coeffs)?,
211+ })
212+ }
213+
214+ #[cfg(target_os = "linux")]
215+ fn export(&self, slot: u32, width: u32, height: u32) -> Result<ec_vk::DmaBufExport> {
216+ Ok(match self {
217+ Surfaces::H264(s) => s.borrow_mut().read_output_dmabuf(slot, width, height)?,
218+ Surfaces::H265(s) => s.borrow_mut().read_output_dmabuf(slot, width, height)?,
219+ Surfaces::Av1(s) => s.borrow_mut().read_output_dmabuf(slot, width, height)?,
220+ Surfaces::Vp9(s) => s.borrow_mut().read_output_dmabuf(slot, width, height)?,
221+ })
222+ }
223+}
224+
225+/// A picture in a ring slot: its display size, bit depth, matrix and, for AV1, the film grain to apply when it is shown.
226+#[derive(Clone)]
227+pub(crate) struct VkPicture {
228+ surfaces: Surfaces,
229+ slot: Slot,
230+ width: u32,
231+ height: u32,
232+ bit_depth: u8,
233+ matrix: Matrix,
234+ grain: Option<Grain>,
235+}
236+
237+#[derive(Clone)]
238+struct Grain {
239+ params: FilmGrainParams,
240+ seq: SequenceHeader,
241+}
242+
243+impl VkPicture {
244+ pub(crate) fn new(
245+ surfaces: Surfaces,
246+ slot: Slot,
247+ (width, height): (u32, u32),
248+ bit_depth: u8,
249+ matrix: Matrix,
250+ ) -> VkPicture {
251+ VkPicture {
252+ surfaces,
253+ slot,
254+ width,
255+ height,
256+ bit_depth,
257+ matrix,
258+ grain: None,
259+ }
260+ }
261+
262+ /// This picture as it is shown with `grain`: unchanged when the frame applies none.
263+ pub(crate) fn with_grain(&self, params: &FilmGrainParams, seq: &SequenceHeader) -> VkPicture {
264+ let mut shown = self.clone();
265+ if params.apply_grain {
266+ shown.grain = Some(Grain {
267+ params: params.clone(),
268+ seq: seq.clone(),
269+ });
270+ }
271+ shown
272+ }
273+
274+ fn read(&self) -> Result<(Vec<u8>, Vec<u8>)> {
275+ self.surfaces.nv12(self.slot.index, self.width, self.height)
276+ }
277+
278+ fn i420(&self) -> Result<I420> {
279+ let (y, uv) = self.read()?;
280+ let frame = semi_planar_to_i420(
281+ self.bit_depth,
282+ &y,
283+ &uv,
284+ self.width as usize,
285+ (0, 0),
286+ (self.width, self.height),
287+ )?;
288+ Ok(match &self.grain {
289+ Some(g) => synthesize(frame, &g.params, &g.seq),
290+ None => frame,
291+ })
292+ }
293+
294+ fn i420_16(&self) -> Result<I420_16> {
295+ let (y, uv) = self.read()?;
296+ let frame = semi_planar_to_i420_16(
297+ self.bit_depth,
298+ &y,
299+ &uv,
300+ self.width as usize,
301+ (0, 0),
302+ (self.width, self.height),
303+ )?;
304+ Ok(match &self.grain {
305+ Some(g) => synthesize16(frame, &g.params, &g.seq),
306+ None => frame,
307+ })
308+ }
309+
310+ fn rgb(&self, output: &RgbOutput) -> Result<RgbPicture> {
311+ let bgra = output.order == RgbOrder::Bgra;
312+ if self.grain.is_some() {
313+ if self.bit_depth != 8 {
314+ return Err(Error::unsupported(
315+ "Vulkan AV1 film grain",
316+ "RGB of 10-bit output",
317+ ));
318+ }
319+ return Ok(i420_to_rgb(
320+ &self.i420()?,
321+ output.max_width,
322+ bgra,
323+ self.matrix,
324+ ));
325+ }
326+ let (w, h) = rgb_size(self.width, self.height, output.max_width);
327+ let data = self.surfaces.rgb(
328+ self.slot.index,
329+ (0, 0, self.width, self.height),
330+ (w, h),
331+ bgra,
332+ yuv_to_rgb(self.matrix).words(),
333+ )?;
334+ Ok(RgbPicture::new(data, w, h))
335+ }
336+
337+ #[cfg(target_os = "linux")]
338+ fn export(&self) -> Result<DmaBufPicture> {
339+ if self.grain.is_some() {
340+ return Err(Error::unsupported(
341+ "Vulkan DMA-BUF export",
342+ "a picture with film grain",
343+ ));
344+ }
345+ Ok(self
346+ .surfaces
347+ .export(self.slot.index, self.width, self.height)?
348+ .into())
349+ }
350+}
351+
352+#[cfg(target_os = "linux")]
353+fn default_matrix(height: u32) -> Matrix {
354+ ColorDescription::resolve(Tags::default(), Tags::default(), height).matrix
355+}
356+
357+#[cfg(target_os = "linux")]
358+fn dmabuf_from_prime(surface: ec_va::PrimeSurface) -> Result<DmaBufPicture> {
359+ let planes: Vec<(u32, u32, u32)> = surface
360+ .layers
361+ .iter()
362+ .flat_map(|layer| layer.planes.iter().copied())
363+ .collect();
364+ let [y, uv] = planes.as_slice() else {
365+ return Err(Error::config("exported surface is not a two-plane 4:2:0 picture"));
366+ };
367+ let plane = |&(object, offset, pitch): &(u32, u32, u32)| ec_vk::DmaBufPlane {
368+ fd: object as usize,
369+ offset,
370+ pitch,
371+ };
372+ let modifier = surface.objects.first().map_or(0, |o| o.modifier);
373+ Ok(DmaBufPicture {
374+ fds: surface.objects.into_iter().map(|o| o.fd).collect(),
375+ fourcc: surface.fourcc,
376+ modifier,
377+ width: surface.width,
378+ height: surface.height,
379+ planes: [plane(y), plane(uv)],
380+ })
381+}
crates/ec-hw/src/picture.rsmodified+0 -24
@@ -114,30 +114,6 @@ impl DmaBufPicture {
114114 }
115115 }
116116
117-/// One decoded picture in the decoder's output form.
118-#[derive(Debug)]
119-pub(crate) enum Decoded {
120- I420(I420),
121- I420_16(I420_16),
122- Rgb(RgbPicture),
123- #[cfg(target_os = "linux")]
124- DmaBuf(DmaBufPicture),
125-}
126-
127-impl Decoded {
128- pub(crate) fn try_clone(&self) -> Result<Decoded> {
129- Ok(match self {
130- Decoded::I420(frame) => Decoded::I420(frame.clone()),
131- Decoded::I420_16(frame) => Decoded::I420_16(frame.clone()),
132- Decoded::Rgb(picture) => Decoded::Rgb(picture.clone()),
133- #[cfg(target_os = "linux")]
134- Decoded::DmaBuf(picture) => Decoded::DmaBuf(picture.try_clone().map_err(|e| {
135- Error::config(format!("duplicating a DMA-BUF picture: {e}"))
136- })?),
137- })
138- }
139-}
140-
141117 /// The YUV to RGB coefficients for a matrix; BT.2020 is taken as BT.709, the nearest integer set here.
142118 pub(crate) fn yuv_to_rgb(matrix: Matrix) -> ec_dsp::rgb::YuvToRgb {
143119 match matrix {
crates/ec-hw/src/vkdec264.rsmodified+33 -76
@@ -1,6 +1,8 @@
11 //! H.264 decoding over Vulkan Video: the shared DPB over DPB slot indices.
22
3+use std::cell::RefCell;
34 use std::collections::{HashMap, VecDeque};
5+use std::rc::Rc;
46
57 use ec_h264_syntax::sps::{ZIGZAG_4X4, ZIGZAG_8X8};
68 use ec_h264_syntax::{
@@ -15,10 +17,7 @@ use ec_vk::{
1517 use crate::dpb264::{self, Mark, PicInfo, Poc};
1618 use crate::error::{Error, Result};
1719 use crate::h264_common::{peek_pps_id, vui_colour_tags};
18-use crate::hw::{Mode, RgbOrder};
19-use crate::picture::{
20- Decoded, I420, RgbPicture, nv12_to_i420, rgb_size, semi_planar_to_i420_16, yuv_to_rgb,
21-};
20+use crate::output::{HwPicture, Ring, Surfaces, VkPicture};
2221 use ec_core::color::{ColorDescription, Tags};
2322
2423 const MAX_SLOTS: u32 = 17;
@@ -27,7 +26,8 @@ type Dpb = dpb264::Dpb<u32>;
2726 type Picture = dpb264::Picture<u32>;
2827
2928 struct Session {
30- h264: H264DecodeSession,
29+ h264: Rc<RefCell<H264DecodeSession>>,
30+ ring: Ring,
3131 max_width: u32,
3232 max_height: u32,
3333 slots: u32,
@@ -48,7 +48,7 @@ struct Current {
4848
4949 struct Side {
5050 fields: [i32; 2],
51- output: Option<(i64, Decoded)>,
51+ output: Option<HwPicture>,
5252 }
5353
5454 /// H.264 Vulkan Video decoder: DPB bookkeeping in Rust, pictures decoded into slots.
@@ -61,13 +61,12 @@ pub(crate) struct VkH264Decoder {
6161 dpb: Dpb,
6262 pics: HashMap<i32, Side>,
6363 current: Option<Current>,
64- ready: VecDeque<(i64, Decoded)>,
64+ ready: VecDeque<HwPicture>,
6565 rbsp: Vec<u8>,
66- mode: Mode,
6766 }
6867
6968 impl VkH264Decoder {
70- pub(crate) fn new(mode: Mode) -> Result<Self> {
69+ pub(crate) fn new() -> Result<Self> {
7170 let gpu = crate::hw::vk_gpu()
7271 .ok_or_else(|| Error::unsupported("Vulkan Video H.264 decode", "no Vulkan device"))?;
7372 Ok(VkH264Decoder {
@@ -81,7 +80,6 @@ impl VkH264Decoder {
8180 current: None,
8281 ready: VecDeque::new(),
8382 rbsp: Vec::new(),
84- mode,
8583 })
8684 }
8785
@@ -124,7 +122,7 @@ impl VkH264Decoder {
124122 self.finish_picture()
125123 }
126124
127- pub(crate) fn next_frame(&mut self) -> Option<(i64, Decoded)> {
125+ pub(crate) fn next_frame(&mut self) -> Option<HwPicture> {
128126 self.ready.pop_front()
129127 }
130128
@@ -253,8 +251,10 @@ impl VkH264Decoder {
253251 profile_idc: sps.profile_idc,
254252 },
255253 )?;
254+ let ring = Ring::new(h264.ring_len());
256255 self.session = Some(Session {
257- h264,
256+ h264: Rc::new(RefCell::new(h264)),
257+ ring,
258258 max_width,
259259 max_height,
260260 slots,
@@ -270,7 +270,7 @@ impl VkH264Decoder {
270270 .session
271271 .as_mut()
272272 .ok_or_else(|| Error::config("H.264 parameters before any SPS"))?;
273- session.h264.set_parameters(&sps, &pps)?;
273+ session.h264.borrow_mut().set_parameters(&sps, &pps)?;
274274 self.params_dirty = false;
275275 Ok(())
276276 }
@@ -323,7 +323,8 @@ impl VkH264Decoder {
323323 .session
324324 .as_mut()
325325 .ok_or_else(|| Error::config("H.264 picture before any SPS"))?;
326- session.h264.decode(&H264DecodePicture {
326+ let slot = session.ring.take(|| Ok(session.h264.borrow_mut().add_ring_slot()?))?;
327+ session.h264.borrow_mut().decode(&H264DecodePicture {
327328 sps_id: current.sps_id,
328329 pps_id: current.pps_id,
329330 idr: current.info.is_idr,
@@ -335,53 +336,23 @@ impl VkH264Decoder {
335336 refs: &refs,
336337 slices: &slices,
337338 })?;
338- let out = match self.mode {
339- Mode::I420 => {
340- let (y, uv) = session
341- .h264
342- .read_output(sps.coded_width, sps.coded_height)?;
343- Decoded::I420(crop(&sps, &y, &uv))
344- }
345- Mode::I420_16 => {
346- let (y, uv) = session
347- .h264
348- .read_output(sps.coded_width, sps.coded_height)?;
349- let (left, _, top, _) = sps.crop;
350- Decoded::I420_16(semi_planar_to_i420_16(
351- 8,
352- &y,
353- &uv,
354- sps.coded_width as usize,
355- (left as usize, top as usize),
356- (sps.width, sps.height),
357- )?)
358- }
359- #[cfg(target_os = "linux")]
360- Mode::DmaBuf => {
361- let (left, _, top, _) = sps.crop;
362- let export = session.h264.read_output_dmabuf((
363- left,
364- top,
365- sps.width,
366- sps.height,
367- ))?;
368- Decoded::DmaBuf(export.into())
369- }
370- Mode::Rgb(rgb) => {
371339 let (left, _, top, _) = sps.crop;
340+ session
341+ .h264
342+ .borrow_mut()
343+ .store_output(slot.index(), (left, top, sps.width, sps.height))?;
372344 let matrix =
373- ColorDescription::resolve(Tags::default(), vui_colour_tags(&sps), sps.height)
374- .matrix;
375- let (w, h) = rgb_size(sps.width, sps.height, rgb.max_width);
376- let data = session.h264.read_output_rgb(
377- (left, top, sps.width, sps.height),
378- (w, h),
379- rgb.order == RgbOrder::Bgra,
380- yuv_to_rgb(matrix).words(),
381- )?;
382- Decoded::Rgb(RgbPicture::new(data, w, h))
383- }
384- };
345+ ColorDescription::resolve(Tags::default(), vui_colour_tags(&sps), sps.height).matrix;
346+ let out = HwPicture::vk(
347+ current.timestamp,
348+ VkPicture::new(
349+ Surfaces::H264(session.h264.clone()),
350+ slot,
351+ (sps.width, sps.height),
352+ 8,
353+ matrix,
354+ ),
355+ );
385356
386357 let picture = Picture {
387358 id: current.id,
@@ -403,7 +374,7 @@ impl VkH264Decoder {
403374 current.id,
404375 Side {
405376 fields,
406- output: Some((current.timestamp, out)),
377+ output: Some(out),
407378 },
408379 );
409380 self.dpb
@@ -415,8 +386,8 @@ impl VkH264Decoder {
415386 fn bump(&mut self, flush: bool) {
416387 while let Some(idx) = self.dpb.next_output(flush) {
417388 let id = self.dpb.frames[idx].id;
418- if let Some((ts, frame)) = self.pics.get_mut(&id).and_then(|s| s.output.take()) {
419- self.ready.push_back((ts, frame));
389+ if let Some(frame) = self.pics.get_mut(&id).and_then(|s| s.output.take()) {
390+ self.ready.push_back(frame);
420391 }
421392 self.dpb.released(idx);
422393 }
@@ -429,20 +400,6 @@ fn field_pocs(poc: i32, delta_bottom: i32) -> [i32; 2] {
429400 [poc - delta_bottom.min(0), poc + delta_bottom.max(0)]
430401 }
431402
432-fn crop(sps: &Sps, y: &[u8], uv: &[u8]) -> I420 {
433- let (left, _, top, _) = sps.crop;
434- let (left, top) = (left as usize, top as usize);
435- let pitch = sps.coded_width as usize;
436- nv12_to_i420(
437- &y[top * pitch + left..],
438- pitch,
439- &uv[(top / 2) * pitch + left..],
440- pitch,
441- sps.width as usize,
442- sps.height as usize,
443- )
444-}
445-
446403 fn lists(l: &ec_h264_syntax::ScalingLists) -> ScalingLists {
447404 let mut out = ScalingLists {
448405 l4x4: [[0; 16]; 6],
crates/ec-hw/src/vkdec265.rsmodified+29 -81
@@ -1,6 +1,8 @@
11 //! H.265 decoding over Vulkan Video: the shared HEVC DPB over DPB slot indices.
22
3+use std::cell::RefCell;
34 use std::collections::{HashMap, VecDeque};
5+use std::rc::Rc;
46
57 use ec_h265_syntax::{
68 AnnexBNal, NalUnitType, Pps, ScalingList, ShortTermRefPicSet, SliceHeader, Sps, Vps,
@@ -18,16 +20,13 @@ use crate::hevc_dpb::{
1820 };
1921 use ec_core::color::{ColorDescription, Tags};
2022
21-use crate::hw::{Mode, RgbOrder};
22-use crate::picture::{
23- Decoded, I420, I420_16, RgbPicture, rgb_size, semi_planar_to_i420, semi_planar_to_i420_16,
24- yuv_to_rgb,
25-};
23+use crate::output::{HwPicture, Ring, Surfaces, VkPicture};
2624
2725 const MAX_SLOTS: u32 = 17;
2826
2927 struct Session {
30- h265: H265DecodeSession,
28+ h265: Rc<RefCell<H265DecodeSession>>,
29+ ring: Ring,
3130 bit_depth: u8,
3231 max_width: u32,
3332 max_height: u32,
@@ -60,15 +59,14 @@ pub(crate) struct VkH265Decoder {
6059 sps_map: Vec<Option<Sps>>,
6160 pps_map: Vec<Option<Pps>>,
6261 dpb: Dpb<u32>,
63- outputs: HashMap<u32, Decoded>,
62+ outputs: HashMap<u32, HwPicture>,
6463 current: Option<Current>,
65- ready: VecDeque<(i64, Decoded)>,
64+ ready: VecDeque<HwPicture>,
6665 no_rasl_output: bool,
67- mode: Mode,
6866 }
6967
7068 impl VkH265Decoder {
71- pub(crate) fn new(mode: Mode) -> Result<Self> {
69+ pub(crate) fn new() -> Result<Self> {
7270 let gpu = crate::hw::vk_gpu()
7371 .ok_or_else(|| Error::unsupported("Vulkan Video H.265 decode", "no Vulkan device"))?;
7472 Ok(VkH265Decoder {
@@ -83,7 +81,6 @@ impl VkH265Decoder {
8381 current: None,
8482 ready: VecDeque::new(),
8583 no_rasl_output: false,
86- mode,
8784 })
8885 }
8986
@@ -120,7 +117,7 @@ impl VkH265Decoder {
120117 self.finish_picture()
121118 }
122119
123- pub(crate) fn next_frame(&mut self) -> Option<(i64, Decoded)> {
120+ pub(crate) fn next_frame(&mut self) -> Option<HwPicture> {
124121 self.ready.pop_front()
125122 }
126123
@@ -264,8 +261,10 @@ impl VkH265Decoder {
264261 bit_depth,
265262 },
266263 )?;
264+ let ring = Ring::new(h265.ring_len());
267265 self.session = Some(Session {
268- h265,
266+ h265: Rc::new(RefCell::new(h265)),
267+ ring,
269268 bit_depth,
270269 max_width,
271270 max_height,
@@ -293,7 +292,7 @@ impl VkH265Decoder {
293292 .session
294293 .as_mut()
295294 .ok_or_else(|| Error::config("H.265 parameters before any SPS"))?;
296- session.h265.set_parameters(&vps, &sps, &pps)?;
295+ session.h265.borrow_mut().set_parameters(&vps, &sps, &pps)?;
297296 self.params_dirty = false;
298297 Ok(())
299298 }
@@ -335,7 +334,7 @@ impl VkH265Decoder {
335334 .session
336335 .as_mut()
337336 .ok_or_else(|| Error::config("H.265 picture before any SPS"))?;
338- session.h265.decode(&H265DecodePicture {
337+ session.h265.borrow_mut().decode(&H265DecodePicture {
339338 vps_id: sps.vps_id,
340339 sps_id: current.sps_id,
341340 pps_id: current.pps_id,
@@ -354,47 +353,24 @@ impl VkH265Decoder {
354353 slices: &slices,
355354 })?;
356355 if current.output {
357- let frame = match self.mode {
358- Mode::I420 => {
359- let (y, uv) = session.h265.read_output(
360- sps.pic_width_in_luma_samples,
361- sps.pic_height_in_luma_samples,
362- )?;
363- Decoded::I420(crop(&sps, &y, &uv)?)
364- }
365- Mode::I420_16 => {
366- let (y, uv) = session.h265.read_output(
367- sps.pic_width_in_luma_samples,
368- sps.pic_height_in_luma_samples,
369- )?;
370- Decoded::I420_16(crop16(&sps, &y, &uv)?)
371- }
372- #[cfg(target_os = "linux")]
373- Mode::DmaBuf => {
374- let (width, height) = sps.display_size();
375- let origin = (2 * sps.conf_win.left as u32, 2 * sps.conf_win.top as u32);
376- let export = session
377- .h265
378- .read_output_dmabuf((origin.0, origin.1, width, height))?;
379- Decoded::DmaBuf(export.into())
380- }
381- Mode::Rgb(rgb) => {
356+ let slot = session.ring.take(|| Ok(session.h265.borrow_mut().add_ring_slot()?))?;
382357 let (width, height) = sps.display_size();
383358 let origin = (2 * sps.conf_win.left as u32, 2 * sps.conf_win.top as u32);
384- let matrix =
385- ColorDescription::resolve(Tags::default(), vui_colour_tags(&sps), height)
386- .matrix;
387- let (w, h) = rgb_size(width, height, rgb.max_width);
388- let data = session.h265.read_output_rgb(
359+ session.h265.borrow_mut().store_output(
360+ slot.index(),
389361 (origin.0, origin.1, width, height),
390- (w, h),
391- rgb.order == RgbOrder::Bgra,
392- yuv_to_rgb(matrix).words(),
393362 )?;
394- Decoded::Rgb(RgbPicture::new(data, w, h))
395- }
396- };
397- self.outputs.insert(current.slot, frame);
363+ let matrix =
364+ ColorDescription::resolve(Tags::default(), vui_colour_tags(&sps), height).matrix;
365+ let picture = VkPicture::new(
366+ Surfaces::H265(session.h265.clone()),
367+ slot,
368+ (width, height),
369+ (8 + sps.bit_depth_luma_minus8) as u8,
370+ matrix,
371+ );
372+ self.outputs
373+ .insert(current.slot, HwPicture::vk(current.timestamp, picture));
398374 }
399375
400376 self.dpb.pictures.push(hevc_dpb::StoredPicture {
@@ -420,7 +396,7 @@ impl VkH265Decoder {
420396 while let Some(idx) = self.dpb.next_output(flush) {
421397 let pic = &self.dpb.pictures[idx];
422398 if let Some(frame) = self.outputs.remove(&pic.surface) {
423- self.ready.push_back((pic.timestamp, frame));
399+ self.ready.push_back(frame);
424400 }
425401 self.dpb.released(idx);
426402 }
@@ -435,34 +411,6 @@ fn store<T: PartialEq>(slot: &mut Option<T>, value: T) -> bool {
435411 true
436412 }
437413
438-fn crop(sps: &Sps, y: &[u8], uv: &[u8]) -> Result<I420> {
439- semi_planar_to_i420(
440- (8 + sps.bit_depth_luma_minus8) as u8,
441- y,
442- uv,
443- sps.pic_width_in_luma_samples as usize,
444- (
445- 2 * sps.conf_win.left as usize,
446- 2 * sps.conf_win.top as usize,
447- ),
448- sps.display_size(),
449- )
450-}
451-
452-fn crop16(sps: &Sps, y: &[u8], uv: &[u8]) -> Result<I420_16> {
453- semi_planar_to_i420_16(
454- (8 + sps.bit_depth_luma_minus8) as u8,
455- y,
456- uv,
457- sps.pic_width_in_luma_samples as usize,
458- (
459- 2 * sps.conf_win.left as usize,
460- 2 * sps.conf_win.top as usize,
461- ),
462- sps.display_size(),
463- )
464-}
465-
466414 fn ptl(p: &ec_h265_syntax::ProfileTierLevel) -> H265ProfileTierLevel {
467415 H265ProfileTierLevel {
468416 tier_flag: p.tier_flag,
crates/ec-hw/src/vkdec_av1.rsmodified+34 -129
@@ -1,5 +1,6 @@
11 //! AV1 decoding over Vulkan Video: the reference slots over DPB slot indices.
22
3+use std::cell::RefCell;
34 use std::collections::VecDeque;
45 use std::rc::Rc;
56
@@ -20,16 +21,14 @@ use crate::ref_slots::RefSlots;
2021 use crate::error::{Error, Result};
2122 use ec_core::color::{ColorDescription, Tags};
2223
23-use crate::hw::{Mode, RgbOrder};
24-use crate::picture::{
25- Decoded, I420, I420_16, RgbPicture, i420_to_rgb, rgb_size, semi_planar_to_i420,
26- semi_planar_to_i420_16, yuv_to_rgb,
27-};
24+use crate::output::{HwPicture, Ring, Surfaces, VkPicture};
25+use crate::picture::{I420, I420_16};
2826
2927 const DPB_SLOTS: u32 = NUM_REF_FRAMES as u32 + 1;
3028
3129 struct Session {
32- av1: Av1DecodeSession,
30+ av1: Rc<RefCell<Av1DecodeSession>>,
31+ ring: Ring,
3332 bit_depth: u8,
3433 width: u32,
3534 height: u32,
@@ -38,7 +37,7 @@ struct Session {
3837
3938 struct Reference {
4039 state: Av1RefSlot,
41- picture: Decoded,
40+ picture: VkPicture,
4241 }
4342
4443 /// AV1 Vulkan Video decoder: reference bookkeeping in Rust, frames decoded into DPB slots.
@@ -47,12 +46,11 @@ pub(crate) struct VkAv1Decoder {
4746 parser: Av1Parser,
4847 session: Option<Session>,
4948 refs: RefSlots<Rc<Reference>>,
50- ready: VecDeque<(i64, Decoded)>,
51- mode: Mode,
49+ ready: VecDeque<HwPicture>,
5250 }
5351
5452 impl VkAv1Decoder {
55- pub(crate) fn new(mode: Mode) -> Result<Self> {
53+ pub(crate) fn new() -> Result<Self> {
5654 let gpu = crate::hw::vk_gpu()
5755 .ok_or_else(|| Error::unsupported("Vulkan Video AV1 decode", "no Vulkan device"))?;
5856 Ok(VkAv1Decoder {
@@ -61,7 +59,6 @@ impl VkAv1Decoder {
6159 session: None,
6260 refs: RefSlots::new(),
6361 ready: VecDeque::new(),
64- mode,
6562 })
6663 }
6764
@@ -90,7 +87,7 @@ impl VkAv1Decoder {
9087 Ok(())
9188 }
9289
93- pub(crate) fn next_frame(&mut self) -> Option<(i64, Decoded)> {
90+ pub(crate) fn next_frame(&mut self) -> Option<HwPicture> {
9491 self.ready.pop_front()
9592 }
9693
@@ -118,16 +115,8 @@ impl VkAv1Decoder {
118115 .parser
119116 .sequence_header()
120117 .ok_or_else(|| Error::config("AV1 frame before any sequence header"))?;
121- if header.film_grain.apply_grain {
122- grain_supported(seq, self.mode)?;
123- }
124- let shown = present(
125- self.mode,
126- reference.picture.try_clone()?,
127- &header.film_grain,
128- seq,
129- )?;
130- self.ready.push_back((timestamp, shown));
118+ let shown = reference.picture.with_grain(&header.film_grain, seq);
119+ self.ready.push_back(HwPicture::vk(timestamp, shown));
131120 if header.frame_type == FrameType::Key {
132121 self.refs.refresh(u8::MAX, Some(reference));
133122 }
@@ -146,7 +135,7 @@ impl VkAv1Decoder {
146135 .sequence_header()
147136 .cloned()
148137 .ok_or_else(|| Error::config("AV1 frame before any sequence header"))?;
149- check_supported(&seq, header, self.mode)?;
138+ check_supported(&seq, header)?;
150139 let (width, height) = (header.upscaled_width, header.frame_height);
151140 self.ensure_session(&seq, width, height)?;
152141
@@ -184,57 +173,22 @@ impl VkAv1Decoder {
184173 .session
185174 .as_mut()
186175 .ok_or_else(|| Error::config("AV1 picture before any session"))?;
187- session.av1.decode(&picture)?;
176+ session.av1.borrow_mut().decode(&picture)?;
188177
189178 if !(header.show_frame || header.refresh_frame_flags != 0) {
190179 return Ok(());
191180 }
192- let mode = self.mode;
193- let readback = match mode {
194- Mode::Rgb(_) if seq.color_config.bit_depth == 8 => Mode::I420,
195- other => other,
196- };
197- let decoded = match readback {
198- Mode::I420 => {
199- let (y, uv) = session.av1.read_output(width, height)?;
200- Decoded::I420(semi_planar_to_i420(
201- session.bit_depth,
202- &y,
203- &uv,
204- width as usize,
205- (0, 0),
206- (width, height),
207- )?)
208- }
209- Mode::I420_16 => {
210- let (y, uv) = session.av1.read_output(width, height)?;
211- Decoded::I420_16(semi_planar_to_i420_16(
212- session.bit_depth,
213- &y,
214- &uv,
215- width as usize,
216- (0, 0),
217- (width, height),
218- )?)
219- }
220- #[cfg(target_os = "linux")]
221- Mode::DmaBuf => {
222- let export = session.av1.read_output_dmabuf((0, 0, width, height))?;
223- Decoded::DmaBuf(export.into())
224- }
225- Mode::Rgb(rgb) => {
181+ let slot = session.ring.take(|| Ok(session.av1.borrow_mut().add_ring_slot()?))?;
182+ session.av1.borrow_mut().store_output(slot.index(), (0, 0, width, height))?;
226183 let codes = Tags::from_codes(u64::from(seq.color_config.matrix_coefficients), 0, 0);
227184 let matrix = ColorDescription::resolve(Tags::default(), codes, height).matrix;
228- let (w, h) = rgb_size(width, height, rgb.max_width);
229- let data = session.av1.read_output_rgb(
230- (0, 0, width, height),
231- (w, h),
232- rgb.order == RgbOrder::Bgra,
233- yuv_to_rgb(matrix).words(),
234- )?;
235- Decoded::Rgb(RgbPicture::new(data, w, h))
236- }
237- };
185+ let decoded = VkPicture::new(
186+ Surfaces::Av1(session.av1.clone()),
187+ slot,
188+ (width, height),
189+ session.bit_depth,
190+ matrix,
191+ );
238192 let state = Av1RefSlot {
239193 slot: setup_slot,
240194 frame_type: av1_frame_type(header.frame_type),
@@ -245,8 +199,8 @@ impl VkAv1Decoder {
245199 segmentation_enabled: header.segmentation.enabled,
246200 };
247201 if header.show_frame {
248- let shown = present(mode, decoded.try_clone()?, &header.film_grain, &seq)?;
249- self.ready.push_back((timestamp, shown));
202+ let shown = decoded.with_grain(&header.film_grain, &seq);
203+ self.ready.push_back(HwPicture::vk(timestamp, shown));
250204 }
251205 if header.refresh_frame_flags != 0 {
252206 let reference = Rc::new(Reference {
@@ -280,8 +234,10 @@ impl VkAv1Decoder {
280234 bit_depth,
281235 },
282236 )?;
237+ let ring = Ring::new(av1.ring_len());
283238 Session {
284- av1,
239+ av1: Rc::new(RefCell::new(av1)),
240+ ring,
285241 bit_depth,
286242 width,
287243 height,
@@ -290,7 +246,10 @@ impl VkAv1Decoder {
290246 }
291247 };
292248 if session.sequence.as_ref() != Some(seq) {
293- session.av1.set_sequence_header(&av1_sequence(seq))?;
249+ session
250+ .av1
251+ .borrow_mut()
252+ .set_sequence_header(&av1_sequence(seq))?;
294253 session.sequence = Some(seq.clone());
295254 }
296255 self.session = Some(session);
@@ -304,7 +263,7 @@ impl VkAv1Decoder {
304263 }
305264 }
306265
307-fn check_supported(seq: &SequenceHeader, header: &FrameHeader, mode: Mode) -> Result<()> {
266+fn check_supported(seq: &SequenceHeader, header: &FrameHeader) -> Result<()> {
308267 let c = &seq.color_config;
309268 if seq.seq_profile != 0
310269 || !matches!(c.bit_depth, 8 | 10)
@@ -320,64 +279,10 @@ fn check_supported(seq: &SequenceHeader, header: &FrameHeader, mode: Mode) -> Re
320279 if header.upscaled_width % 2 != 0 || header.frame_height % 2 != 0 {
321280 return Err(Error::unsupported("Vulkan AV1 decode", "odd frame size"));
322281 }
323- if header.film_grain.apply_grain {
324- grain_supported(seq, mode)?;
325- }
326282 Ok(())
327283 }
328284
329-fn grain_supported(seq: &SequenceHeader, mode: Mode) -> Result<()> {
330- let eight = seq.color_config.bit_depth == 8;
331- let supported = match mode {
332- Mode::I420 | Mode::Rgb(_) => eight,
333- Mode::I420_16 => true,
334- #[cfg(target_os = "linux")]
335- Mode::DmaBuf => false,
336- };
337- if supported {
338- Ok(())
339- } else {
340- Err(Error::unsupported(
341- "Vulkan AV1 film grain",
342- "not for this output format",
343- ))
344- }
345-}
346-
347-fn present(
348- mode: Mode,
349- picture: Decoded,
350- grain: &FilmGrainParams,
351- seq: &SequenceHeader,
352-) -> Result<Decoded> {
353- let picture = grained(picture, grain, seq);
354- Ok(match (mode, picture) {
355- (Mode::Rgb(rgb), Decoded::I420(frame)) => {
356- let codes = Tags::from_codes(u64::from(seq.color_config.matrix_coefficients), 0, 0);
357- let matrix = ColorDescription::resolve(Tags::default(), codes, frame.height).matrix;
358- Decoded::Rgb(i420_to_rgb(
359- &frame,
360- rgb.max_width,
361- rgb.order == RgbOrder::Bgra,
362- matrix,
363- ))
364- }
365- (_, other) => other,
366- })
367-}
368-
369-fn grained(picture: Decoded, grain: &FilmGrainParams, seq: &SequenceHeader) -> Decoded {
370- if !grain.apply_grain {
371- return picture;
372- }
373- match picture {
374- Decoded::I420(frame) => Decoded::I420(synthesize(frame, grain, seq)),
375- Decoded::I420_16(frame) => Decoded::I420_16(synthesize16(frame, grain, seq)),
376- other => other,
377- }
378-}
379-
380-fn synthesize16(frame: I420_16, grain: &FilmGrainParams, seq: &SequenceHeader) -> I420_16 {
285+pub(crate) fn synthesize16(frame: I420_16, grain: &FilmGrainParams, seq: &SequenceHeader) -> I420_16 {
381286 let bit_depth = u32::from(seq.color_config.bit_depth);
382287 let shift = if bit_depth == 8 { 2 } else { 0 };
383288 let narrow = |p: &[u16]| p.iter().map(|&s| s >> shift).collect::<Vec<u16>>();
@@ -405,7 +310,7 @@ fn synthesize16(frame: I420_16, grain: &FilmGrainParams, seq: &SequenceHeader) -
405310 }
406311 }
407312
408-fn synthesize(frame: I420, grain: &FilmGrainParams, seq: &SequenceHeader) -> I420 {
313+pub(crate) fn synthesize(frame: I420, grain: &FilmGrainParams, seq: &SequenceHeader) -> I420 {
409314 let wide = |p: &[u8]| p.iter().map(|&s| u16::from(s)).collect::<Vec<u16>>();
410315 let clean = Picture {
411316 width: frame.width as usize,
crates/ec-hw/src/vkdec_vp9.rsmodified+24 -57
@@ -1,5 +1,6 @@
11 //! VP9 decoding over Vulkan Video: the reference slots over DPB slot indices.
22
3+use std::cell::RefCell;
34 use std::collections::VecDeque;
45 use std::rc::Rc;
56
@@ -14,16 +15,14 @@ use ec_vp9_syntax::{
1415 };
1516
1617 use crate::error::{Error, Result};
17-use crate::hw::{Mode, RgbOrder};
18-use crate::picture::{
19- Decoded, RgbPicture, rgb_size, semi_planar_to_i420, semi_planar_to_i420_16, yuv_to_rgb,
20-};
18+use crate::output::{HwPicture, Ring, Surfaces, VkPicture};
2119 use crate::ref_slots::RefSlots;
2220
2321 const DPB_SLOTS: u32 = NUM_REF_FRAMES as u32 + 1;
2422
2523 struct Session {
26- vp9: Vp9DecodeSession,
24+ vp9: Rc<RefCell<Vp9DecodeSession>>,
25+ ring: Ring,
2726 bit_depth: u8,
2827 width: u32,
2928 height: u32,
@@ -31,7 +30,7 @@ struct Session {
3130
3231 struct Reference {
3332 slot: u32,
34- picture: Decoded,
33+ picture: VkPicture,
3534 }
3635
3736 /// What the next frame needs from the one before it (spec 7.2, UsePrevFrameMvs).
@@ -50,12 +49,11 @@ pub(crate) struct VkVp9Decoder {
5049 session: Option<Session>,
5150 refs: RefSlots<Rc<Reference>>,
5251 previous: Option<PreviousFrame>,
53- ready: VecDeque<(i64, Decoded)>,
54- mode: Mode,
52+ ready: VecDeque<HwPicture>,
5553 }
5654
5755 impl VkVp9Decoder {
58- pub(crate) fn new(mode: Mode) -> Result<Self> {
56+ pub(crate) fn new() -> Result<Self> {
5957 let gpu = crate::hw::vk_gpu()
6058 .ok_or_else(|| Error::unsupported("Vulkan Video VP9 decode", "no Vulkan device"))?;
6159 Ok(VkVp9Decoder {
@@ -65,7 +63,6 @@ impl VkVp9Decoder {
6563 refs: RefSlots::new(),
6664 previous: None,
6765 ready: VecDeque::new(),
68- mode,
6966 })
7067 }
7168
@@ -79,7 +76,7 @@ impl VkVp9Decoder {
7976 Ok(())
8077 }
8178
82- pub(crate) fn next_frame(&mut self) -> Option<(i64, Decoded)> {
79+ pub(crate) fn next_frame(&mut self) -> Option<HwPicture> {
8380 self.ready.pop_front()
8481 }
8582
@@ -106,7 +103,8 @@ impl VkVp9Decoder {
106103 "VP9 show_existing_frame names an empty reference slot",
107104 ))
108105 })?;
109- self.ready.push_back((timestamp, reference.picture.try_clone()?));
106+ self.ready
107+ .push_back(HwPicture::vk(timestamp, reference.picture.clone()));
110108 if let Some(previous) = self.previous.as_mut() {
111109 previous.show_frame = true;
112110 }
@@ -152,7 +150,8 @@ impl VkVp9Decoder {
152150 .session
153151 .as_mut()
154152 .ok_or_else(|| Error::config("VP9 picture before any session"))?;
155- session.vp9.decode(&picture)?;
153+ let slot = session.ring.take(|| Ok(session.vp9.borrow_mut().add_ring_slot()?))?;
154+ session.vp9.borrow_mut().decode(&picture)?;
156155 self.previous = Some(PreviousFrame {
157156 width: header.width,
158157 height: header.height,
@@ -164,53 +163,19 @@ impl VkVp9Decoder {
164163 return Ok(());
165164 }
166165 let (width, height) = (header.width, header.height);
167- let decoded = match self.mode {
168- Mode::I420 => {
169- let (y, uv) = session.vp9.read_output(width, height)?;
170- Decoded::I420(semi_planar_to_i420(
171- session.bit_depth,
172- &y,
173- &uv,
174- width as usize,
175- (0, 0),
166+ let codes = Tags::from_codes(u64::from(header.color_space.h273().map_or(2, |c| c.2)), 0, 0);
167+ let matrix = ColorDescription::resolve(Tags::default(), codes, height).matrix;
168+ session.vp9.borrow_mut().store_output(slot.index(), (0, 0, width, height))?;
169+ let decoded = VkPicture::new(
170+ Surfaces::Vp9(session.vp9.clone()),
171+ slot,
176172 (width, height),
177- )?)
178- }
179- Mode::I420_16 => {
180- let (y, uv) = session.vp9.read_output(width, height)?;
181- Decoded::I420_16(semi_planar_to_i420_16(
182173 session.bit_depth,
183- &y,
184- &uv,
185- width as usize,
186- (0, 0),
187- (width, height),
188- )?)
189- }
190- #[cfg(target_os = "linux")]
191- Mode::DmaBuf => {
192- let export = session.vp9.read_output_dmabuf((0, 0, width, height))?;
193- Decoded::DmaBuf(export.into())
194- }
195- Mode::Rgb(rgb) => {
196- let codes = Tags::from_codes(
197- u64::from(header.color_space.h273().map_or(2, |c| c.2)),
198- 0,
199- 0,
174+ matrix,
200175 );
201- let matrix = ColorDescription::resolve(Tags::default(), codes, height).matrix;
202- let (w, h) = rgb_size(width, height, rgb.max_width);
203- let data = session.vp9.read_output_rgb(
204- (0, 0, width, height),
205- (w, h),
206- rgb.order == RgbOrder::Bgra,
207- yuv_to_rgb(matrix).words(),
208- )?;
209- Decoded::Rgb(RgbPicture::new(data, w, h))
210- }
211- };
212176 if header.show_frame {
213- self.ready.push_back((timestamp, decoded.try_clone()?));
177+ self.ready
178+ .push_back(HwPicture::vk(timestamp, decoded.clone()));
214179 }
215180 if header.refresh_frame_flags != 0 {
216181 let reference = Rc::new(Reference {
@@ -247,8 +212,10 @@ impl VkVp9Decoder {
247212 bit_depth: header.bit_depth,
248213 },
249214 )?;
215+ let ring = Ring::new(vp9.ring_len());
250216 self.session = Some(Session {
251- vp9,
217+ vp9: Rc::new(RefCell::new(vp9)),
218+ ring,
252219 bit_depth: header.bit_depth,
253220 width,
254221 height,
shims/vk-video-ffi/examples/av1_decode_smoke.rsmodified+2 -1
@@ -301,7 +301,8 @@ fn main() {
301301 tile_sizes: &sizes,
302302 };
303303 session.decode(&pic).expect("decode");
304- let (y, uv) = session.read_output(w, h).expect("read output");
304+ session.store_output(0, (0, 0, w, h)).expect("store");
305+ let (y, uv) = session.read_output(0, w, h).expect("read slot");
305306
306307 let reference = fs::read(&reference).expect("read reference");
307308 let luma = (w * h) as usize;
shims/vk-video-ffi/examples/h264_decode_smoke.rsmodified+2 -1
@@ -159,7 +159,8 @@ fn main() {
159159 slices: &slices,
160160 };
161161 session.decode(&pic).expect("decode");
162- let (y, uv) = session.read_output(w, h).expect("read slot");
162+ session.store_output(0, (0, 0, w, h)).expect("store");
163+ let (y, uv) = session.read_output(0, w, h).expect("read slot");
163164
164165 let mut pgm = format!("P5\n{w} {h}\n255\n").into_bytes();
165166 pgm.extend_from_slice(&y);
shims/vk-video-ffi/examples/h265_decode_smoke.rsmodified+2 -1
@@ -258,7 +258,8 @@ fn main() {
258258 slices: &slices,
259259 };
260260 session.decode(&pic).expect("decode");
261- let (y, uv) = session.read_output(w, h).expect("read slot");
261+ session.store_output(0, (0, 0, w, h)).expect("store");
262+ let (y, uv) = session.read_output(0, w, h).expect("read slot");
262263
263264 let ref_data = fs::read(&reference).expect("read reference");
264265 let luma = (w * h) as usize;
shims/vk-video-ffi/src/av1_decode.rsmodified+23 -5
@@ -853,28 +853,46 @@ impl Av1DecodeSession {
853853 }
854854
855855 /// Copies the top-left width x height of the last decoded picture out as NV12 or P010 planes (Y, interleaved UV).
856- pub fn read_output(&mut self, width: u32, height: u32) -> Result<(Vec<u8>, Vec<u8>), Error> {
857- self.dec.read_nv12(width, height)
856+ pub fn ring_len(&self) -> u32 {
857+ self.dec.ring_len()
858+ }
859+
860+ /// Adds one slot to the output ring and returns its index; every slot is then in use or held.
861+ pub fn add_ring_slot(&mut self) -> Result<u32, Error> {
862+ self.dec.add_ring_slot()
863+ }
864+
865+ /// Copies the crop window `(x, y, width, height)` of the last decoded picture into ring slot `slot`, where it stays until that slot is stored into again.
866+ pub fn store_output(&mut self, slot: u32, crop: (u32, u32, u32, u32)) -> Result<(), Error> {
867+ self.dec.store(slot as usize, crop)
868+ }
869+
870+ /// The top-left width x height of ring slot `slot` as NV12 planes (Y, interleaved UV).
871+ pub fn read_output(&mut self, slot: u32, width: u32, height: u32) -> Result<(Vec<u8>, Vec<u8>), Error> {
872+ self.dec.read_nv12(slot as usize, width, height)
858873 }
859874
860875 /// Exports the crop window `(x, y, width, height)` of the last decoded picture as one DMA-BUF of NV12 or P010 planes.
861876 #[cfg(target_os = "linux")]
862877 pub fn read_output_dmabuf(
863878 &mut self,
864- crop: (u32, u32, u32, u32),
879+ slot: u32,
880+ width: u32,
881+ height: u32,
865882 ) -> Result<crate::dmabuf::DmaBufExport, Error> {
866- self.dec.export(crop)
883+ self.dec.export(slot as usize, (width, height))
867884 }
868885
869886 /// Packed 4-byte pixels of the crop window `(x, y, width, height)` of the last decoded picture, box-downscaled to `out`, converted to RGB with integer `coeffs` `[ky, rv, gu, gv, bu]`; `bgra` picks the byte order.
870887 pub fn read_output_rgb(
871888 &mut self,
889+ slot: u32,
872890 crop: (u32, u32, u32, u32),
873891 out: (u32, u32),
874892 bgra: bool,
875893 coeffs: [i32; 5],
876894 ) -> Result<Vec<u8>, Error> {
877- self.dec.read_rgb(crop, out, bgra, coeffs)
895+ self.dec.read_rgb(slot as usize, crop, out, bgra, coeffs)
878896 }
879897 }
880898
shims/vk-video-ffi/src/dmabuf.rsmodified+46 -155
@@ -7,7 +7,7 @@ use vulkanalia::vk::{
77 ExtImageDrmFormatModifierExtensionDeviceCommands, KhrExternalMemoryFdExtensionDeviceCommands,
88 };
99
10-use crate::session::{Lane, NV12, P010, PLANE_0, PLANE_1, color_range, memory_type, vk};
10+use crate::session::{EXTERNAL_FAMILY, Lane, NV12, P010, PLANE_0, PLANE_1, memory_type, transfer, vk};
1111 use std::os::fd::AsFd;
1212 use crate::{Error, Gpu};
1313
@@ -477,46 +477,26 @@ fn export_modifiers(gpu: &Gpu, format: vk::Format) -> Vec<u64> {
477477 list.iter()
478478 .filter(|m| {
479479 m.drm_format_modifier_tiling_features
480- .contains(vk::FormatFeatureFlags::TRANSFER_DST)
480+ .contains(vk::FormatFeatureFlags::TRANSFER_DST | vk::FormatFeatureFlags::TRANSFER_SRC)
481481 })
482482 .map(|m| m.drm_format_modifier)
483483 .collect()
484484 }
485485
486-fn transfer(
487- d: &Device,
488- cb: vk::CommandBuffer,
489- image: vk::Image,
490- from: (vk::ImageLayout, vk::PipelineStageFlags2, vk::AccessFlags2, u32),
491- to: (vk::ImageLayout, vk::PipelineStageFlags2, vk::AccessFlags2, u32),
492-) {
493- let barrier = vk::ImageMemoryBarrier2::builder()
494- .src_stage_mask(from.1)
495- .src_access_mask(from.2)
496- .dst_stage_mask(to.1)
497- .dst_access_mask(to.2)
498- .old_layout(from.0)
499- .new_layout(to.0)
500- .src_queue_family_index(from.3)
501- .dst_queue_family_index(to.3)
502- .image(image)
503- .subresource_range(color_range())
504- .build();
505- let barriers = [barrier];
506- let info = vk::DependencyInfo::builder()
507- .image_memory_barriers(&barriers)
508- .build();
509- unsafe { d.cmd_pipeline_barrier2(cb, &info) };
486+/// A ring slot's DMA-BUF: the one memory object, exported once, and its plane layout.
487+pub(crate) struct Export {
488+ pub(crate) fd: OwnedFd,
489+ pub(crate) modifier: u64,
490+ pub(crate) planes: [DmaBufPlane; 2],
510491 }
511492
512-/// Copies the crop window `(x, y, width, height)` of `src` (decoded NV12 or P010) into a new exportable image on the graphics lane, releases it to the foreign queue and exports it as one DMA-BUF.
513-pub(crate) fn export(
493+/// Creates an exportable NV12 or P010 image of `width` x `height` on the lane's family, leaves it released to the foreign queue in GENERAL, and exports its memory once.
494+pub(crate) fn ring_image(
514495 gpu: &Gpu,
515496 lane: &Lane,
516- src: vk::Image,
517497 format: vk::Format,
518- (x, y, width, height): (u32, u32, u32, u32),
519-) -> Result<DmaBufExport, Error> {
498+ (width, height): (u32, u32),
499+) -> Result<(vk::Image, vk::DeviceMemory, Export), Error> {
520500 check(gpu)?;
521501 let d = gpu.device();
522502 let modifiers = export_modifiers(gpu, format);
@@ -543,7 +523,7 @@ pub(crate) fn export(
543523 } else {
544524 vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT
545525 })
546- .usage(vk::ImageUsageFlags::TRANSFER_DST)
526+ .usage(vk::ImageUsageFlags::TRANSFER_SRC | vk::ImageUsageFlags::TRANSFER_DST)
547527 .sharing_mode(vk::SharingMode::EXCLUSIVE)
548528 .initial_layout(vk::ImageLayout::UNDEFINED)
549529 .push_next(&mut external);
@@ -553,98 +533,16 @@ pub(crate) fn export(
553533 info.push_next(&mut list).build()
554534 };
555535 let image = unsafe { vk(d.create_image(&info, None), "vkCreateImage")? };
556- let exported = export_image(gpu, lane, src, image, (x, y, width, height), linear);
536+ let memory = match bind_exported(gpu, image) {
537+ Ok(memory) => memory,
538+ Err(e) => {
557539 unsafe { d.destroy_image(image, None) };
558- exported.map(|(fd, modifier, planes)| DmaBufExport {
559- fd,
560- modifier,
561- planes,
562- width,
563- height,
564- p010: format == crate::session::P010,
565- })
566-}
567-
568-fn export_image(
569- gpu: &Gpu,
570- lane: &Lane,
571- src: vk::Image,
572- image: vk::Image,
573- (x, y, width, height): (u32, u32, u32, u32),
574- linear: bool,
575-) -> Result<(OwnedFd, u64, [DmaBufPlane; 2]), Error> {
576- let d = gpu.device();
577- let req = unsafe { d.get_image_memory_requirements(image) };
578- let index = memory_type(gpu, req.memory_type_bits, vk::MemoryPropertyFlags::DEVICE_LOCAL)?;
579- let mut export = vk::ExportMemoryAllocateInfo::builder()
580- .handle_types(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT)
581- .build();
582- let mut dedicated = vk::MemoryDedicatedAllocateInfo::builder()
583- .image(image)
584- .build();
585- let alloc = vk::MemoryAllocateInfo::builder()
586- .allocation_size(req.size)
587- .memory_type_index(index)
588- .push_next(&mut dedicated)
589- .push_next(&mut export)
590- .build();
591- let memory = unsafe { vk(d.allocate_memory(&alloc, None), "vkAllocateMemory")? };
592- if let Err(e) = unsafe { vk(d.bind_image_memory(image, memory, 0), "vkBindImageMemory") } {
593- unsafe { d.free_memory(memory, None) };
594540 return Err(e);
595541 }
596- let result = copy_and_export(gpu, lane, src, image, memory, (x, y, width, height), linear);
597- unsafe { d.free_memory(memory, None) };
598- result
599-}
600-
601-fn copy_and_export(
602- gpu: &Gpu,
603- lane: &Lane,
604- src: vk::Image,
605- image: vk::Image,
606- memory: vk::DeviceMemory,
607- (x, y, width, height): (u32, u32, u32, u32),
608- linear: bool,
609-) -> Result<(OwnedFd, u64, [DmaBufPlane; 2]), Error> {
610- let d = gpu.device();
542+ };
611543 let cb = lane.cb;
612- let decode = (
613- vk::ImageLayout::VIDEO_DECODE_DST_KHR,
614- vk::PipelineStageFlags2::ALL_COMMANDS,
615- vk::AccessFlags2::NONE,
616- vk::QUEUE_FAMILY_IGNORED,
617- );
618- let copy_src = (
619- vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
620- vk::PipelineStageFlags2::COPY,
621- vk::AccessFlags2::TRANSFER_READ,
622- vk::QUEUE_FAMILY_IGNORED,
623- );
624- let copy_dst = (
625- vk::ImageLayout::TRANSFER_DST_OPTIMAL,
626- vk::PipelineStageFlags2::COPY,
627- vk::AccessFlags2::TRANSFER_WRITE,
628- vk::QUEUE_FAMILY_IGNORED,
629- );
630- let planes_regions = [
631- plane_copy(PLANE_0, (x, y), (width, height)),
632- plane_copy(PLANE_1, (x / 2, y / 2), (width / 2, height / 2)),
633- ];
634544 lane.begin()?;
635- unsafe {
636- transfer(
637- d,
638- cb,
639- src,
640- decode,
641- (
642- vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
643- vk::PipelineStageFlags2::COPY,
644- vk::AccessFlags2::TRANSFER_READ,
645- vk::QUEUE_FAMILY_IGNORED,
646- ),
647- );
545+ {
648546 transfer(
649547 d,
650548 cb,
@@ -655,15 +553,12 @@ fn copy_and_export(
655553 vk::AccessFlags2::NONE,
656554 vk::QUEUE_FAMILY_IGNORED,
657555 ),
658- copy_dst,
659- );
660- d.cmd_copy_image(
661- cb,
662- src,
663- vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
664- image,
556+ (
665557 vk::ImageLayout::TRANSFER_DST_OPTIMAL,
666- &planes_regions,
558+ vk::PipelineStageFlags2::COPY,
559+ vk::AccessFlags2::TRANSFER_WRITE,
560+ vk::QUEUE_FAMILY_IGNORED,
561+ ),
667562 );
668563 transfer(
669564 d,
@@ -679,10 +574,9 @@ fn copy_and_export(
679574 vk::ImageLayout::GENERAL,
680575 vk::PipelineStageFlags2::NONE,
681576 vk::AccessFlags2::NONE,
682- QUEUE_FAMILY_FOREIGN,
577+ EXTERNAL_FAMILY,
683578 ),
684579 );
685- transfer(d, cb, src, copy_src, decode);
686580 }
687581 lane.end()?;
688582 lane.submit()?;
@@ -703,37 +597,34 @@ fn copy_and_export(
703597 layout(gpu, image, linear, 0)?,
704598 layout(gpu, image, linear, 1)?,
705599 ];
706- Ok((fd, modifier, planes))
600+ Ok((image, memory, Export { fd, modifier, planes }))
707601 }
708602
709-pub(crate) fn plane_copy(
710- aspect: vk::ImageAspectFlags,
711- origin: (u32, u32),
712- (width, height): (u32, u32),
713-) -> vk::ImageCopy {
714- let layers = vk::ImageSubresourceLayers {
715- aspect_mask: aspect,
716- mip_level: 0,
717- base_array_layer: 0,
718- layer_count: 1,
719- };
720- vk::ImageCopy {
721- src_subresource: layers,
722- src_offset: vk::Offset3D {
723- x: origin.0 as i32,
724- y: origin.1 as i32,
725- z: 0,
726- },
727- dst_subresource: layers,
728- dst_offset: vk::Offset3D { x: 0, y: 0, z: 0 },
729- extent: vk::Extent3D {
730- width,
731- height,
732- depth: 1,
733- },
603+fn bind_exported(gpu: &Gpu, image: vk::Image) -> Result<vk::DeviceMemory, Error> {
604+ let d = gpu.device();
605+ let req = unsafe { d.get_image_memory_requirements(image) };
606+ let index = memory_type(gpu, req.memory_type_bits, vk::MemoryPropertyFlags::DEVICE_LOCAL)?;
607+ let mut export = vk::ExportMemoryAllocateInfo::builder()
608+ .handle_types(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT)
609+ .build();
610+ let mut dedicated = vk::MemoryDedicatedAllocateInfo::builder()
611+ .image(image)
612+ .build();
613+ let alloc = vk::MemoryAllocateInfo::builder()
614+ .allocation_size(req.size)
615+ .memory_type_index(index)
616+ .push_next(&mut dedicated)
617+ .push_next(&mut export)
618+ .build();
619+ let memory = unsafe { vk(d.allocate_memory(&alloc, None), "vkAllocateMemory")? };
620+ if let Err(e) = unsafe { vk(d.bind_image_memory(image, memory, 0), "vkBindImageMemory") } {
621+ unsafe { d.free_memory(memory, None) };
622+ return Err(e);
734623 }
624+ Ok(memory)
735625 }
736626
627+
737628 fn export_fd(gpu: &Gpu, memory: vk::DeviceMemory) -> Result<OwnedFd, Error> {
738629 let info = vk::MemoryGetFdInfoKHR::builder()
739630 .memory(memory)
shims/vk-video-ffi/src/h264_decode.rsmodified+23 -5
@@ -457,28 +457,46 @@ impl H264DecodeSession {
457457 }
458458
459459 /// Copies the top-left width x height of the last decoded picture out as NV12 planes (Y, interleaved UV).
460- pub fn read_output(&mut self, width: u32, height: u32) -> Result<(Vec<u8>, Vec<u8>), Error> {
461- self.dec.read_nv12(width, height)
460+ pub fn ring_len(&self) -> u32 {
461+ self.dec.ring_len()
462+ }
463+
464+ /// Adds one slot to the output ring and returns its index; every slot is then in use or held.
465+ pub fn add_ring_slot(&mut self) -> Result<u32, Error> {
466+ self.dec.add_ring_slot()
467+ }
468+
469+ /// Copies the crop window `(x, y, width, height)` of the last decoded picture into ring slot `slot`, where it stays until that slot is stored into again.
470+ pub fn store_output(&mut self, slot: u32, crop: (u32, u32, u32, u32)) -> Result<(), Error> {
471+ self.dec.store(slot as usize, crop)
472+ }
473+
474+ /// The top-left width x height of ring slot `slot` as NV12 planes (Y, interleaved UV).
475+ pub fn read_output(&mut self, slot: u32, width: u32, height: u32) -> Result<(Vec<u8>, Vec<u8>), Error> {
476+ self.dec.read_nv12(slot as usize, width, height)
462477 }
463478
464479 /// Exports the crop window `(x, y, width, height)` of the last decoded picture as one DMA-BUF of NV12 or P010 planes.
465480 #[cfg(target_os = "linux")]
466481 pub fn read_output_dmabuf(
467482 &mut self,
468- crop: (u32, u32, u32, u32),
483+ slot: u32,
484+ width: u32,
485+ height: u32,
469486 ) -> Result<crate::dmabuf::DmaBufExport, Error> {
470- self.dec.export(crop)
487+ self.dec.export(slot as usize, (width, height))
471488 }
472489
473490 /// Packed 4-byte pixels of the crop window `(x, y, width, height)` of the last decoded picture, box-downscaled to `out`, converted to RGB with integer `coeffs` `[ky, rv, gu, gv, bu]`; `bgra` picks the byte order.
474491 pub fn read_output_rgb(
475492 &mut self,
493+ slot: u32,
476494 crop: (u32, u32, u32, u32),
477495 out: (u32, u32),
478496 bgra: bool,
479497 coeffs: [i32; 5],
480498 ) -> Result<Vec<u8>, Error> {
481- self.dec.read_rgb(crop, out, bgra, coeffs)
499+ self.dec.read_rgb(slot as usize, crop, out, bgra, coeffs)
482500 }
483501 }
484502
shims/vk-video-ffi/src/h265_decode.rsmodified+23 -5
@@ -694,28 +694,46 @@ impl H265DecodeSession {
694694 }
695695
696696 /// Copies the top-left width x height of the last decoded picture out as NV12 or P010 planes (Y, interleaved UV).
697- pub fn read_output(&mut self, width: u32, height: u32) -> Result<(Vec<u8>, Vec<u8>), Error> {
698- self.dec.read_nv12(width, height)
697+ pub fn ring_len(&self) -> u32 {
698+ self.dec.ring_len()
699+ }
700+
701+ /// Adds one slot to the output ring and returns its index; every slot is then in use or held.
702+ pub fn add_ring_slot(&mut self) -> Result<u32, Error> {
703+ self.dec.add_ring_slot()
704+ }
705+
706+ /// Copies the crop window `(x, y, width, height)` of the last decoded picture into ring slot `slot`, where it stays until that slot is stored into again.
707+ pub fn store_output(&mut self, slot: u32, crop: (u32, u32, u32, u32)) -> Result<(), Error> {
708+ self.dec.store(slot as usize, crop)
709+ }
710+
711+ /// The top-left width x height of ring slot `slot` as NV12 planes (Y, interleaved UV).
712+ pub fn read_output(&mut self, slot: u32, width: u32, height: u32) -> Result<(Vec<u8>, Vec<u8>), Error> {
713+ self.dec.read_nv12(slot as usize, width, height)
699714 }
700715
701716 /// Exports the crop window `(x, y, width, height)` of the last decoded picture as one DMA-BUF of NV12 or P010 planes.
702717 #[cfg(target_os = "linux")]
703718 pub fn read_output_dmabuf(
704719 &mut self,
705- crop: (u32, u32, u32, u32),
720+ slot: u32,
721+ width: u32,
722+ height: u32,
706723 ) -> Result<crate::dmabuf::DmaBufExport, Error> {
707- self.dec.export(crop)
724+ self.dec.export(slot as usize, (width, height))
708725 }
709726
710727 /// Packed 4-byte pixels of the crop window `(x, y, width, height)` of the last decoded picture, box-downscaled to `out`, converted to RGB with integer `coeffs` `[ky, rv, gu, gv, bu]`; `bgra` picks the byte order.
711728 pub fn read_output_rgb(
712729 &mut self,
730+ slot: u32,
713731 crop: (u32, u32, u32, u32),
714732 out: (u32, u32),
715733 bgra: bool,
716734 coeffs: [i32; 5],
717735 ) -> Result<Vec<u8>, Error> {
718- self.dec.read_rgb(crop, out, bgra, coeffs)
736+ self.dec.read_rgb(slot as usize, crop, out, bgra, coeffs)
719737 }
720738 }
721739
shims/vk-video-ffi/src/lib.rsmodified+23 -6
@@ -138,6 +138,10 @@ pub enum Direction {
138138 /// Profile a capability is queried for, 4:2:0 only.
139139 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
140140 pub enum CodecProfile {
141+ /// H.264 Constrained Baseline, 8-bit.
142+ H264ConstrainedBaseline,
143+ /// H.264 Main, 8-bit.
144+ H264Main,
141145 /// H.264 High, 8-bit.
142146 H264High,
143147 /// H.265 Main, 8-bit.
@@ -150,6 +154,8 @@ pub enum CodecProfile {
150154 Av1Main10,
151155 /// VP9 Profile 0, 8-bit.
152156 Vp9Profile0,
157+ /// VP9 Profile 2, 10-bit.
158+ Vp9Profile2,
153159 }
154160
155161 /// Capabilities of one codec, profile and direction.
@@ -361,7 +367,10 @@ impl Gpu {
361367 /// Capabilities of every codec, profile and direction the device supports.
362368 pub fn caps(&self) -> Vec<CodecCaps> {
363369 [
370+ (Codec::H264, Direction::Encode, CodecProfile::H264Main),
364371 (Codec::H264, Direction::Encode, CodecProfile::H264High),
372+ (Codec::H264, Direction::Decode, CodecProfile::H264ConstrainedBaseline),
373+ (Codec::H264, Direction::Decode, CodecProfile::H264Main),
365374 (Codec::H264, Direction::Decode, CodecProfile::H264High),
366375 (Codec::H265, Direction::Encode, CodecProfile::H265Main),
367376 (Codec::H265, Direction::Encode, CodecProfile::H265Main10),
@@ -372,6 +381,7 @@ impl Gpu {
372381 (Codec::Av1, Direction::Decode, CodecProfile::Av1Main),
373382 (Codec::Av1, Direction::Decode, CodecProfile::Av1Main10),
374383 (Codec::Vp9, Direction::Decode, CodecProfile::Vp9Profile0),
384+ (Codec::Vp9, Direction::Decode, CodecProfile::Vp9Profile2),
375385 ]
376386 .into_iter()
377387 .filter_map(|(codec, direction, profile)| {
@@ -423,7 +433,7 @@ impl Gpu {
423433 return Err(Error::Unsupported(format!("{codec:?} {direction:?}")));
424434 }
425435 let depth = match profile {
426- CodecProfile::H265Main10 | CodecProfile::Av1Main10 => {
436+ CodecProfile::H265Main10 | CodecProfile::Av1Main10 | CodecProfile::Vp9Profile2 => {
427437 vk::VideoComponentBitDepthFlagsKHR::_10
428438 }
429439 _ => vk::VideoComponentBitDepthFlagsKHR::_8,
@@ -435,14 +445,22 @@ impl Gpu {
435445 .luma_bit_depth(depth)
436446 .chroma_bit_depth(depth)
437447 };
448+ let h264_idc = match profile {
449+ CodecProfile::H264ConstrainedBaseline => vk::video::STD_VIDEO_H264_PROFILE_IDC_BASELINE,
450+ CodecProfile::H264Main => vk::video::STD_VIDEO_H264_PROFILE_IDC_MAIN,
451+ _ => vk::video::STD_VIDEO_H264_PROFILE_IDC_HIGH,
452+ };
453+ let vp9_profile = match profile {
454+ CodecProfile::Vp9Profile2 => vk::video::STD_VIDEO_VP9_PROFILE_2,
455+ _ => vk::video::STD_VIDEO_VP9_PROFILE_0,
456+ };
438457 let h265_idc = match profile {
439458 CodecProfile::H265Main10 => vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN_10,
440459 _ => vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN,
441460 };
442461 match (codec, direction) {
443462 (Codec::H264, Direction::Encode) => {
444- let mut h = vk::VideoEncodeH264ProfileInfoKHR::builder()
445- .std_profile_idc(vk::video::STD_VIDEO_H264_PROFILE_IDC_HIGH);
463+ let mut h = vk::VideoEncodeH264ProfileInfoKHR::builder().std_profile_idc(h264_idc);
446464 let p = base(operation).push_next(&mut h);
447465 self.query(
448466 codec,
@@ -454,7 +472,7 @@ impl Gpu {
454472 }
455473 (Codec::H264, Direction::Decode) => {
456474 let mut h = vk::VideoDecodeH264ProfileInfoKHR::builder()
457- .std_profile_idc(vk::video::STD_VIDEO_H264_PROFILE_IDC_HIGH)
475+ .std_profile_idc(h264_idc)
458476 .picture_layout(vk::VideoDecodeH264PictureLayoutFlagsKHR::PROGRESSIVE);
459477 let p = base(operation).push_next(&mut h);
460478 self.query(
@@ -512,8 +530,7 @@ impl Gpu {
512530 )
513531 }
514532 (Codec::Vp9, _) => {
515- let mut h = vk::VideoDecodeVP9ProfileInfoKHR::builder()
516- .std_profile(vk::video::STD_VIDEO_VP9_PROFILE_0);
533+ let mut h = vk::VideoDecodeVP9ProfileInfoKHR::builder().std_profile(vp9_profile);
517534 let p = base(operation).push_next(&mut h);
518535 self.query(
519536 codec,
shims/vk-video-ffi/src/session.rsmodified+336 -61
@@ -7,7 +7,7 @@ use vulkanalia::vk::{
77 };
88
99 #[cfg(target_os = "linux")]
10-use crate::dmabuf::{DmaBuf, DmaBufFormat, ImportCache, acquire, plane_copy, release};
10+use crate::dmabuf::{DmaBuf, DmaBufFormat, ImportCache, acquire, release};
1111 #[cfg(target_os = "linux")]
1212 use crate::rgb_convert::check_size;
1313 use crate::rgb_convert::{Input, RgbConverter};
@@ -163,6 +163,74 @@ pub(crate) fn color_range() -> vk::ImageSubresourceRange {
163163 }
164164 }
165165
166+pub(crate) const EXTERNAL_FAMILY: u32 = if cfg!(target_os = "linux") {
167+ u32::MAX - 1
168+} else {
169+ vk::QUEUE_FAMILY_IGNORED
170+};
171+
172+pub(crate) fn ring_owner(lane: &Lane) -> u32 {
173+ if cfg!(target_os = "linux") {
174+ lane.family
175+ } else {
176+ vk::QUEUE_FAMILY_IGNORED
177+ }
178+}
179+
180+pub(crate) fn transfer(
181+ d: &Device,
182+ cb: vk::CommandBuffer,
183+ image: vk::Image,
184+ from: (vk::ImageLayout, vk::PipelineStageFlags2, vk::AccessFlags2, u32),
185+ to: (vk::ImageLayout, vk::PipelineStageFlags2, vk::AccessFlags2, u32),
186+) {
187+ let barrier = vk::ImageMemoryBarrier2::builder()
188+ .src_stage_mask(from.1)
189+ .src_access_mask(from.2)
190+ .dst_stage_mask(to.1)
191+ .dst_access_mask(to.2)
192+ .old_layout(from.0)
193+ .new_layout(to.0)
194+ .src_queue_family_index(from.3)
195+ .dst_queue_family_index(to.3)
196+ .image(image)
197+ .subresource_range(color_range())
198+ .build();
199+ let barriers = [barrier];
200+ let info = vk::DependencyInfo::builder()
201+ .image_memory_barriers(&barriers)
202+ .build();
203+ unsafe { d.cmd_pipeline_barrier2(cb, &info) };
204+}
205+
206+pub(crate) fn plane_copy(
207+ aspect: vk::ImageAspectFlags,
208+ origin: (u32, u32),
209+ (width, height): (u32, u32),
210+) -> vk::ImageCopy {
211+ let layers = vk::ImageSubresourceLayers {
212+ aspect_mask: aspect,
213+ mip_level: 0,
214+ base_array_layer: 0,
215+ layer_count: 1,
216+ };
217+ vk::ImageCopy {
218+ src_subresource: layers,
219+ src_offset: vk::Offset3D {
220+ x: origin.0 as i32,
221+ y: origin.1 as i32,
222+ z: 0,
223+ },
224+ dst_subresource: layers,
225+ dst_offset: vk::Offset3D { x: 0, y: 0, z: 0 },
226+ extent: vk::Extent3D {
227+ width,
228+ height,
229+ depth: 1,
230+ },
231+ }
232+}
233+
166234 pub(crate) fn copy_region(
167235 offset: u64,
168236 aspect: vk::ImageAspectFlags,
@@ -1304,6 +1372,16 @@ pub(crate) struct Decoder {
13041372 rgb_out: Buffer,
13051373 rgb: Option<RgbPass>,
13061374 pub(crate) coded: bool,
1375+ ring: Vec<RingSlot>,
1376+}
1377+
1378+const RING_EXTRA: u32 = 8;
1379+
1380+struct RingSlot {
1381+ image: vk::Image,
1382+ memory: vk::DeviceMemory,
1383+ #[cfg(target_os = "linux")]
1384+ export: crate::dmabuf::Export,
13071385 }
13081386
13091387 impl Decoder {
@@ -1336,6 +1414,7 @@ impl Decoder {
13361414 rgb_out: Default::default(),
13371415 rgb: None,
13381416 coded: false,
1417+ ring: Vec::new(),
13391418 };
13401419 let mut list = vk::VideoProfileListInfoKHR::builder()
13411420 .profiles(std::slice::from_ref(profile))
@@ -1395,6 +1474,11 @@ impl Decoder {
13951474 (dec.rgb_out.buffer, rgb_size),
13961475 )?);
13971476
1477+ for _ in 0..max_dpb_slots + RING_EXTRA {
1478+ let slot = dec.ring_slot()?;
1479+ dec.ring.push(slot);
1480+ }
1481+
13981482 let d = gpu.device();
13991483 let cb = dec.decode.cb;
14001484 dec.decode.begin()?;
@@ -1446,24 +1530,164 @@ impl Decoder {
14461530 Ok(())
14471531 }
14481532
1449- /// Copies the top-left width x height of the last decoded picture out as NV12 or P010 planes (Y, interleaved UV).
1533+ fn ring_slot(&self) -> Result<RingSlot, Error> {
1534+ let gpu = self.vs.gpu.clone();
1535+ #[cfg(target_os = "linux")]
1536+ {
1537+ let (image, memory, export) = crate::dmabuf::ring_image(
1538+ &gpu,
1539+ &self.graphics,
1540+ self.vs.format,
1541+ (self.max_extent.width, self.max_extent.height),
1542+ )?;
1543+ Ok(RingSlot {
1544+ image,
1545+ memory,
1546+ export,
1547+ })
1548+ }
1549+ #[cfg(not(target_os = "linux"))]
1550+ {
1551+ let d = gpu.device();
1552+ let info = vk::ImageCreateInfo::builder()
1553+ .image_type(vk::ImageType::_2D)
1554+ .format(self.vs.format)
1555+ .extent(vk::Extent3D {
1556+ width: self.max_extent.width,
1557+ height: self.max_extent.height,
1558+ depth: 1,
1559+ })
1560+ .mip_levels(1)
1561+ .array_layers(1)
1562+ .samples(vk::SampleCountFlags::_1)
1563+ .tiling(vk::ImageTiling::OPTIMAL)
1564+ .usage(vk::ImageUsageFlags::TRANSFER_SRC | vk::ImageUsageFlags::TRANSFER_DST)
1565+ .sharing_mode(vk::SharingMode::EXCLUSIVE)
1566+ .initial_layout(vk::ImageLayout::UNDEFINED)
1567+ .build();
1568+ let image = unsafe { vk(d.create_image(&info, None), "vkCreateImage")? };
1569+ let req = unsafe { d.get_image_memory_requirements(image) };
1570+ let index = memory_type(&gpu, req.memory_type_bits, vk::MemoryPropertyFlags::DEVICE_LOCAL)?;
1571+ let alloc = vk::MemoryAllocateInfo::builder()
1572+ .allocation_size(req.size)
1573+ .memory_type_index(index)
1574+ .build();
1575+ let memory = unsafe { vk(d.allocate_memory(&alloc, None), "vkAllocateMemory")? };
1576+ unsafe { vk(d.bind_image_memory(image, memory, 0), "vkBindImageMemory")? };
1577+ self.graphics.begin()?;
1578+ init_barrier(d, self.graphics.cb, image, vk::ImageLayout::GENERAL);
1579+ self.graphics.end()?;
1580+ self.graphics.submit()?;
1581+ Ok(RingSlot { image, memory })
1582+ }
1583+ }
1584+
1585+ /// Copies the crop window `(x, y, width, height)` of the last decoded picture into ring slot `slot`, where it stays until that slot is stored into again.
1586+ pub(crate) fn store(&mut self, slot: usize, crop: (u32, u32, u32, u32)) -> Result<(), Error> {
1587+ self.check_window(crop)?;
1588+ let (x, y, width, height) = crop;
1589+ let target = self.slot_image(slot)?;
1590+ let gpu = self.vs.gpu.clone();
1591+ let d = gpu.device();
1592+ let cb = self.graphics.cb;
1593+ let owner = ring_owner(&self.graphics);
1594+ let source = self.output.image;
1595+ let regions = [
1596+ plane_copy(PLANE_0, (x, y), (width, height)),
1597+ plane_copy(PLANE_1, (x / 2, y / 2), (width / 2, height / 2)),
1598+ ];
1599+ self.graphics.begin()?;
1600+ unsafe {
1601+ transfer(
1602+ d,
1603+ cb,
1604+ source,
1605+ (
1606+ vk::ImageLayout::VIDEO_DECODE_DST_KHR,
1607+ vk::PipelineStageFlags2::ALL_COMMANDS,
1608+ vk::AccessFlags2::NONE,
1609+ vk::QUEUE_FAMILY_IGNORED,
1610+ ),
1611+ (
1612+ vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
1613+ vk::PipelineStageFlags2::COPY,
1614+ vk::AccessFlags2::TRANSFER_READ,
1615+ vk::QUEUE_FAMILY_IGNORED,
1616+ ),
1617+ );
1618+ transfer(
1619+ d,
1620+ cb,
1621+ target,
1622+ (
1623+ vk::ImageLayout::GENERAL,
1624+ vk::PipelineStageFlags2::NONE,
1625+ vk::AccessFlags2::NONE,
1626+ EXTERNAL_FAMILY,
1627+ ),
1628+ (
1629+ vk::ImageLayout::TRANSFER_DST_OPTIMAL,
1630+ vk::PipelineStageFlags2::COPY,
1631+ vk::AccessFlags2::TRANSFER_WRITE,
1632+ owner,
1633+ ),
1634+ );
1635+ d.cmd_copy_image(
1636+ cb,
1637+ source,
1638+ vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
1639+ target,
1640+ vk::ImageLayout::TRANSFER_DST_OPTIMAL,
1641+ &regions,
1642+ );
1643+ transfer(
1644+ d,
1645+ cb,
1646+ target,
1647+ (
1648+ vk::ImageLayout::TRANSFER_DST_OPTIMAL,
1649+ vk::PipelineStageFlags2::COPY,
1650+ vk::AccessFlags2::TRANSFER_WRITE,
1651+ owner,
1652+ ),
1653+ (
1654+ vk::ImageLayout::GENERAL,
1655+ vk::PipelineStageFlags2::NONE,
1656+ vk::AccessFlags2::NONE,
1657+ EXTERNAL_FAMILY,
1658+ ),
1659+ );
1660+ transfer(
1661+ d,
1662+ cb,
1663+ source,
1664+ (
1665+ vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
1666+ vk::PipelineStageFlags2::COPY,
1667+ vk::AccessFlags2::TRANSFER_READ,
1668+ vk::QUEUE_FAMILY_IGNORED,
1669+ ),
1670+ (
1671+ vk::ImageLayout::VIDEO_DECODE_DST_KHR,
1672+ vk::PipelineStageFlags2::ALL_COMMANDS,
1673+ vk::AccessFlags2::NONE,
1674+ vk::QUEUE_FAMILY_IGNORED,
1675+ ),
1676+ );
1677+ }
1678+ self.graphics.end()?;
1679+ self.graphics.submit()
1680+ }
1681+
1682+ /// Copies the top-left width x height of ring slot `slot` out as NV12 or P010 planes (Y, interleaved UV).
14501683 pub(crate) fn read_nv12(
14511684 &mut self,
1685+ slot: usize,
14521686 width: u32,
14531687 height: u32,
14541688 ) -> Result<(Vec<u8>, Vec<u8>), Error> {
1455- if !self.coded {
1456- return Err(Error::Invalid("nothing decoded".into()));
1457- }
1458- if width == 0
1459- || height == 0
1460- || width % 2 != 0
1461- || height % 2 != 0
1462- || width > self.max_extent.width
1463- || height > self.max_extent.height
1464- {
1465- return Err(Error::Invalid("readback size".into()));
1466- }
1689+ self.check_size((width, height))?;
1690+ let target = self.slot_image(slot)?;
14671691 let gpu = self.vs.gpu.clone();
14681692 let d = gpu.device();
14691693 let bytes = bytes_per_sample(self.vs.format);
@@ -1473,40 +1697,28 @@ impl Decoder {
14731697 copy_region(luma as u64, PLANE_1, width / 2, height / 2),
14741698 ];
14751699 self.graphics.begin()?;
1476- self.copy_to_buffer(d, self.graphics.cb, self.readback.buffer, &copies);
1700+ self.slot_to_buffer(d, self.graphics.cb, target, self.readback.buffer, &copies);
14771701 self.graphics.end()?;
14781702 self.graphics.submit()?;
14791703 let bytes = self.readback.bytes(d, luma * 3 / 2)?;
14801704 Ok((bytes[..luma].to_vec(), bytes[luma..].to_vec()))
14811705 }
14821706
1483- /// Copies the crop window `(x, y, width, height)` of the last decoded picture as packed 4-byte pixels, box-downscaled to `out` and converted to RGB on the GPU with the integer `coeffs` `[ky, rv, gu, gv, bu]`. `bgra` picks the byte order; alpha is 255.
1707+ /// Copies the crop window `(x, y, width, height)` of ring slot `slot` as packed 4-byte pixels, box-downscaled to `out` and converted to RGB on the GPU with the integer `coeffs` `[ky, rv, gu, gv, bu]`. `bgra` picks the byte order; alpha is 255.
14841708 pub(crate) fn read_rgb(
14851709 &mut self,
1710+ slot: usize,
14861711 crop: (u32, u32, u32, u32),
14871712 out: (u32, u32),
14881713 bgra: bool,
14891714 coeffs: [i32; 5],
14901715 ) -> Result<Vec<u8>, Error> {
1716+ self.check_window(crop)?;
14911717 let (x, y, width, height) = crop;
1492- if !self.coded {
1493- return Err(Error::Invalid("nothing decoded".into()));
1494- }
1495- if width == 0
1496- || height == 0
1497- || width % 2 != 0
1498- || height % 2 != 0
1499- || x % 2 != 0
1500- || y % 2 != 0
1501- || x + width > self.max_extent.width
1502- || y + height > self.max_extent.height
1503- || out.0 == 0
1504- || out.1 == 0
1505- || out.0 > width
1506- || out.1 > height
1507- {
1718+ if out.0 == 0 || out.1 == 0 || out.0 > width || out.1 > height {
15081719 return Err(Error::Invalid("RGB readback size".into()));
15091720 }
1721+ let target = self.slot_image(slot)?;
15101722 let pass = self
15111723 .rgb
15121724 .as_ref()
@@ -1521,7 +1733,7 @@ impl Decoder {
15211733 copy_rect(luma as u64, PLANE_1, (x / 2, y / 2), (width / 2, height / 2)),
15221734 ];
15231735 self.graphics.begin()?;
1524- self.copy_to_buffer(d, cb, self.planes.buffer, &copies);
1736+ self.slot_to_buffer(d, cb, target, self.planes.buffer, &copies);
15251737 let barrier = vk::BufferMemoryBarrier2::builder()
15261738 .src_stage_mask(vk::PipelineStageFlags2::COPY)
15271739 .src_access_mask(vk::AccessFlags2::TRANSFER_WRITE)
@@ -1556,13 +1768,45 @@ impl Decoder {
15561768 Ok(self.rgb_out.bytes(d, len)?.to_vec())
15571769 }
15581770
1559- /// Exports the crop window `(x, y, width, height)` of the last decoded picture as one DMA-BUF of NV12 or P010 planes.
1771+ /// The DMA-BUF of ring slot `slot`, `width` x `height` from its top-left: a second handle on the slot's memory, which the same slot returns every time.
15601772 #[cfg(target_os = "linux")]
15611773 pub(crate) fn export(
1562- &mut self,
1563- crop: (u32, u32, u32, u32),
1774+ &self,
1775+ slot: usize,
1776+ (width, height): (u32, u32),
15641777 ) -> Result<crate::dmabuf::DmaBufExport, Error> {
1565- let (x, y, width, height) = crop;
1778+ self.check_size((width, height))?;
1779+ let ring = self
1780+ .ring
1781+ .get(slot)
1782+ .ok_or_else(|| Error::Invalid("ring slot out of range".into()))?;
1783+ let fd = ring
1784+ .export
1785+ .fd
1786+ .try_clone()
1787+ .map_err(|e| Error::Invalid(format!("duplicating DMA-BUF: {e}")))?;
1788+ Ok(crate::dmabuf::DmaBufExport {
1789+ fd,
1790+ modifier: ring.export.modifier,
1791+ planes: ring.export.planes,
1792+ width,
1793+ height,
1794+ p010: self.vs.format == P010,
1795+ })
1796+ }
1797+
1798+ pub(crate) fn ring_len(&self) -> u32 {
1799+ self.ring.len() as u32
1800+ }
1801+
1802+ /// Adds one slot to the ring when every slot is held, and returns its index.
1803+ pub(crate) fn add_ring_slot(&mut self) -> Result<u32, Error> {
1804+ let slot = self.ring_slot()?;
1805+ self.ring.push(slot);
1806+ Ok(self.ring.len() as u32 - 1)
1807+ }
1808+
1809+ fn check_size(&self, (width, height): (u32, u32)) -> Result<(), Error> {
15661810 if !self.coded {
15671811 return Err(Error::Invalid("nothing decoded".into()));
15681812 }
@@ -1570,49 +1814,74 @@ impl Decoder {
15701814 || height == 0
15711815 || width % 2 != 0
15721816 || height % 2 != 0
1573- || x % 2 != 0
1574- || y % 2 != 0
1575- || x + width > self.max_extent.width
1576- || y + height > self.max_extent.height
1817+ || width > self.max_extent.width
1818+ || height > self.max_extent.height
15771819 {
1578- return Err(Error::Invalid("DMA-BUF export size".into()));
1820+ return Err(Error::Invalid("picture size".into()));
15791821 }
1580- let gpu = self.vs.gpu.clone();
1581- crate::dmabuf::export(&gpu, &self.graphics, self.output.image, self.vs.format, crop)
1822+ Ok(())
1823+ }
1824+
1825+ fn check_window(&self, (x, y, width, height): (u32, u32, u32, u32)) -> Result<(), Error> {
1826+ self.check_size((width, height))?;
1827+ if x % 2 != 0 || y % 2 != 0 || x + width > self.max_extent.width || y + height > self.max_extent.height {
1828+ return Err(Error::Invalid("picture window".into()));
1829+ }
1830+ Ok(())
15821831 }
15831832
1584- fn copy_to_buffer(
1833+ fn slot_image(&self, slot: usize) -> Result<vk::Image, Error> {
1834+ self.ring
1835+ .get(slot)
1836+ .map(|s| s.image)
1837+ .ok_or_else(|| Error::Invalid("ring slot out of range".into()))
1838+ }
1839+
1840+ fn slot_to_buffer(
15851841 &self,
15861842 d: &Device,
15871843 cb: vk::CommandBuffer,
1844+ image: vk::Image,
15881845 target: vk::Buffer,
15891846 copies: &[vk::BufferImageCopy],
15901847 ) {
1591- let image = self.output.image;
1848+ let owner = ring_owner(&self.graphics);
15921849 unsafe {
1593- barrier(
1850+ slot_acquire(d, cb, image, owner);
1851+ d.cmd_copy_image_to_buffer(
1852+ cb,
1853+ image,
1854+ vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
1855+ target,
1856+ copies,
1857+ );
1858+ slot_release(d, cb, image, owner);
1859+ }
1860+ }
1861+}
1862+
1863+fn slot_acquire(d: &Device, cb: vk::CommandBuffer, image: vk::Image, owner: u32) {
1864+ transfer(
15941865 d,
15951866 cb,
15961867 image,
15971868 (
1598- vk::ImageLayout::VIDEO_DECODE_DST_KHR,
1599- vk::PipelineStageFlags2::ALL_COMMANDS,
1869+ vk::ImageLayout::GENERAL,
1870+ vk::PipelineStageFlags2::NONE,
16001871 vk::AccessFlags2::NONE,
1872+ EXTERNAL_FAMILY,
16011873 ),
16021874 (
16031875 vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
16041876 vk::PipelineStageFlags2::COPY,
16051877 vk::AccessFlags2::TRANSFER_READ,
1878+ owner,
16061879 ),
16071880 );
1608- d.cmd_copy_image_to_buffer(
1609- cb,
1610- image,
1611- vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
1612- target,
1613- copies,
1614- );
1615- barrier(
1881+}
1882+
1883+fn slot_release(d: &Device, cb: vk::CommandBuffer, image: vk::Image, owner: u32) {
1884+ transfer(
16161885 d,
16171886 cb,
16181887 image,
@@ -1620,16 +1889,16 @@ impl Decoder {
16201889 vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
16211890 vk::PipelineStageFlags2::COPY,
16221891 vk::AccessFlags2::TRANSFER_READ,
1892+ owner,
16231893 ),
16241894 (
1625- vk::ImageLayout::VIDEO_DECODE_DST_KHR,
1626- vk::PipelineStageFlags2::ALL_COMMANDS,
1895+ vk::ImageLayout::GENERAL,
1896+ vk::PipelineStageFlags2::NONE,
16271897 vk::AccessFlags2::NONE,
1898+ EXTERNAL_FAMILY,
16281899 ),
16291900 );
16301901 }
1631- }
1632-}
16331902
16341903 impl Drop for Decoder {
16351904 fn drop(&mut self) {
@@ -1641,6 +1910,12 @@ impl Drop for Decoder {
16411910 for img in self.dpb.iter().chain(std::iter::once(&self.output)) {
16421911 img.destroy(d);
16431912 }
1913+ for slot in &self.ring {
1914+ unsafe {
1915+ d.destroy_image(slot.image, None);
1916+ d.free_memory(slot.memory, None);
1917+ }
1918+ }
16441919 self.bitstream.destroy(d);
16451920 self.readback.destroy(d);
16461921 self.planes.destroy(d);
shims/vk-video-ffi/src/vp9_decode.rsmodified+23 -5
@@ -413,28 +413,46 @@ impl Vp9DecodeSession {
413413 }
414414
415415 /// Copies the top-left width x height of the last decoded picture out as NV12 or P010 planes (Y, interleaved UV).
416- pub fn read_output(&mut self, width: u32, height: u32) -> Result<(Vec<u8>, Vec<u8>), Error> {
417- self.dec.read_nv12(width, height)
416+ pub fn ring_len(&self) -> u32 {
417+ self.dec.ring_len()
418+ }
419+
420+ /// Adds one slot to the output ring and returns its index; every slot is then in use or held.
421+ pub fn add_ring_slot(&mut self) -> Result<u32, Error> {
422+ self.dec.add_ring_slot()
423+ }
424+
425+ /// Copies the crop window `(x, y, width, height)` of the last decoded picture into ring slot `slot`, where it stays until that slot is stored into again.
426+ pub fn store_output(&mut self, slot: u32, crop: (u32, u32, u32, u32)) -> Result<(), Error> {
427+ self.dec.store(slot as usize, crop)
428+ }
429+
430+ /// The top-left width x height of ring slot `slot` as NV12 planes (Y, interleaved UV).
431+ pub fn read_output(&mut self, slot: u32, width: u32, height: u32) -> Result<(Vec<u8>, Vec<u8>), Error> {
432+ self.dec.read_nv12(slot as usize, width, height)
418433 }
419434
420435 /// Exports the crop window `(x, y, width, height)` of the last decoded picture as one DMA-BUF of NV12 or P010 planes.
421436 #[cfg(target_os = "linux")]
422437 pub fn read_output_dmabuf(
423438 &mut self,
424- crop: (u32, u32, u32, u32),
439+ slot: u32,
440+ width: u32,
441+ height: u32,
425442 ) -> Result<crate::dmabuf::DmaBufExport, Error> {
426- self.dec.export(crop)
443+ self.dec.export(slot as usize, (width, height))
427444 }
428445
429446 /// Packed 4-byte pixels of the crop window `(x, y, width, height)` of the last decoded picture, box-downscaled to `out`, converted to RGB with integer `coeffs` `[ky, rv, gu, gv, bu]`; `bgra` picks the byte order.
430447 pub fn read_output_rgb(
431448 &mut self,
449+ slot: u32,
432450 crop: (u32, u32, u32, u32),
433451 out: (u32, u32),
434452 bgra: bool,
435453 coeffs: [i32; 5],
436454 ) -> Result<Vec<u8>, Error> {
437- self.dec.read_rgb(crop, out, bgra, coeffs)
455+ self.dec.read_rgb(slot as usize, crop, out, bgra, coeffs)
438456 }
439457 }
440458