forge
Explore
Log in

Don't you dare go Hollow

Merge Vk decode DMA-BUF export, HwDecoder::reset, per-profile capabilities, grain for 16-bit/RGB; one DmaBufPlane type for import and export

Browse files at this commit

0df0354e231003818ba2b4f15231f6fbaa7cf67bAhmet Kaan GümüşParent: 5d4b8b4f49eeb8

17 changed files +1210 -127

crates/ec-hw/examples/hw_caps.rsmodified+2 -2
@@ -16,8 +16,8 @@ const HEIGHT: u32 = 720;
16 fn main() {16 fn main() {
17 for cap in capabilities() {17 for cap in capabilities() {
18 println!(18 println!(
19- "{:?} {:?} {:?} max {}x{}",19+ "{:?} {:?} {:?} {:?} max {}x{}",
20- cap.backend, cap.direction, cap.codec, cap.max_width, cap.max_height20+ cap.backend, cap.direction, cap.codec, cap.profile, cap.max_width, cap.max_height
21 );21 );
22 }22 }
23 for codec in [EncCodec::H264, EncCodec::H265, EncCodec::Av1] {23 for codec in [EncCodec::H264, EncCodec::H265, EncCodec::Av1] {
crates/ec-hw/examples/hw_decode.rsmodified+169 -1
@@ -9,7 +9,10 @@ use std::fs;
9 use std::path::{Path, PathBuf};9 use std::path::{Path, PathBuf};
10 use std::process::Command;10 use std::process::Command;
11 11
12-use ec_hw::{Backend, Codec, EncCodec, EncoderConfig, FrameMetadata, HwDecoder, HwEncoder, I420, RateControlMode};12+use ec_hw::{
13+ Backend, Codec, DmaBufPicture, EncCodec, EncoderConfig, FrameMetadata, HwDecoder, HwEncoder,
14+ I420, I420_16, RateControlMode,
15+};
13 16
14 struct Case {17 struct Case {
15 name: &'static str,18 name: &'static str,
@@ -108,6 +111,171 @@ fn main() {
108 grain(&dir);111 grain(&dir);
109 own_av1(&dir);112 own_av1(&dir);
110 vp9_cases(&dir);113 vp9_cases(&dir);
114+ dmabuf_cases(&dir);
115+ seek_case(&dir);
116+}
117+
118+fn dmabuf_cases(dir: &Path) {
119+ let h264 = fs::read(dir.join("bf1280.h264")).expect("read bf1280");
120+ dmabuf_case("bf1280.h264", Codec::H264, &h264_units(&h264), false);
121+ let hevc = fs::read(dir.join("h265idr720.hevc")).expect("read h265idr720");
122+ dmabuf_case("h265idr720.hevc", Codec::H265, &[&hevc[..]], false);
123+ let av1 = fs::read(dir.join("av1aom720.ivf")).expect("read av1aom720");
124+ dmabuf_case("av1aom720.ivf", Codec::Av1, &ivf_units(&av1), false);
125+ let vp9 = fs::read(dir.join("vp9_720.ivf")).expect("read vp9_720");
126+ dmabuf_case("vp9_720.ivf", Codec::Vp9, &ivf_units(&vp9), false);
127+ let ten = fs::read(dir.join("ten.hevc")).expect("read ten.hevc");
128+ dmabuf_case("ten.hevc P010", Codec::H265, &nal_units(&ten), true);
129+}
130+
131+fn dmabuf_case(label: &str, codec: Codec, units: &[&[u8]], ten: bool) {
132+ let mut reference = if ten {
133+ HwDecoder::open_16(codec)
134+ } else {
135+ HwDecoder::open(codec)
136+ }
137+ .expect("open decoder");
138+ assert_eq!(reference.backend(), Backend::Vk, "{label}: must decode on Vulkan");
139+ let expected = decoded_planes(&mut reference, units, ten);
140+
141+ let gpu = ec_vk::Gpu::open().expect("Vulkan device");
142+ let mut decoder = HwDecoder::open_dmabuf(codec).expect("open DMA-BUF decoder");
143+ assert_eq!(decoder.backend(), Backend::Vk, "{label}: DMA-BUF must decode on Vulkan");
144+ let mut got = Vec::new();
145+ for (pts, unit) in units.iter().enumerate() {
146+ decoder.decode(unit, pts as i64).expect("decode DMA-BUF");
147+ collect_dmabuf(&mut decoder, &gpu, &mut got);
148+ }
149+ decoder.flush().expect("flush DMA-BUF");
150+ collect_dmabuf(&mut decoder, &gpu, &mut got);
151+ compare_planes(label, codec, &expected, &got);
152+}
153+
154+fn decoded_planes(decoder: &mut HwDecoder, units: &[&[u8]], ten: bool) -> Vec<(Vec<u8>, Vec<u8>)> {
155+ let mut out = Vec::new();
156+ for (pts, unit) in units.iter().enumerate() {
157+ decoder.decode(unit, pts as i64).expect("decode");
158+ take_planes(decoder, ten, &mut out);
159+ }
160+ decoder.flush().expect("flush");
161+ take_planes(decoder, ten, &mut out);
162+ out
163+}
164+
165+fn take_planes(decoder: &mut HwDecoder, ten: bool, out: &mut Vec<(Vec<u8>, Vec<u8>)>) {
166+ if ten {
167+ while let Some((_, frame)) = decoder.next_frame_16().expect("next frame") {
168+ out.push(p010_planes(&frame));
169+ }
170+ } else {
171+ while let Some((_, frame)) = decoder.next_frame().expect("next frame") {
172+ out.push(nv12_planes(&frame));
173+ }
174+ }
175+}
176+
177+fn nv12_planes(frame: &I420) -> (Vec<u8>, Vec<u8>) {
178+ let uv = frame.u.iter().zip(&frame.v).flat_map(|(&u, &v)| [u, v]).collect();
179+ (frame.y.clone(), uv)
180+}
181+
182+fn p010_planes(frame: &I420_16) -> (Vec<u8>, Vec<u8>) {
183+ let le = |v: &u16| (v << 6).to_le_bytes();
184+ let y = frame.y.iter().flat_map(le).collect();
185+ let uv = frame
186+ .u
187+ .iter()
188+ .zip(&frame.v)
189+ .flat_map(|(u, v)| [le(u), le(v)].into_iter().flatten())
190+ .collect();
191+ (y, uv)
192+}
193+
194+fn collect_dmabuf(decoder: &mut HwDecoder, gpu: &ec_vk::Gpu, out: &mut Vec<(Vec<u8>, Vec<u8>)>) {
195+ while let Some((_, picture)) = decoder.next_dmabuf().expect("next DMA-BUF") {
196+ out.push(read_back(gpu, picture));
197+ }
198+}
199+
200+fn read_back(gpu: &ec_vk::Gpu, picture: DmaBufPicture) -> (Vec<u8>, Vec<u8>) {
201+ assert!(picture.planes.iter().all(|p| p.fd == 0), "one DMA-BUF object per picture");
202+ let p010 = picture.fourcc == u32::from_le_bytes(*b"P010");
203+ let planes = picture.planes;
204+ let fd = picture.fds.into_iter().next().expect("one DMA-BUF object");
205+ let export = ec_vk::DmaBufExport {
206+ fd,
207+ modifier: picture.modifier,
208+ planes,
209+ width: picture.width,
210+ height: picture.height,
211+ p010,
212+ };
213+ ec_vk::read_dmabuf(gpu, &export).expect("read back DMA-BUF")
214+}
215+
216+fn compare_planes(label: &str, codec: Codec, expected: &[(Vec<u8>, Vec<u8>)], got: &[(Vec<u8>, Vec<u8>)]) {
217+ assert_eq!(got.len(), expected.len(), "{label}: frame count");
218+ let mut luma_sum = 0.0f64;
219+ let mut luma_len = 0usize;
220+ let mut chroma_diff = 0usize;
221+ for ((ey, euv), (gy, guv)) in expected.iter().zip(got) {
222+ assert_eq!((ey.len(), euv.len()), (gy.len(), guv.len()), "{label}: plane size");
223+ luma_sum += ey.iter().zip(gy).map(|(&a, &b)| (a as f64 - b as f64).abs()).sum::<f64>();
224+ luma_len += ey.len();
225+ chroma_diff += euv.iter().zip(guv).filter(|(a, b)| a != b).count();
226+ }
227+ let mean = luma_sum / luma_len.max(1) as f64;
228+ println!(
229+ "{label} {codec:?} DMA-BUF: decoded {} frames, max mean |diff| Y {mean:.6}, UV mismatched bytes {chroma_diff}",
230+ got.len(),
231+ );
232+ assert_eq!(chroma_diff, 0, "{label}: UV differs");
233+ assert_eq!(mean, 0.0, "{label}: Y differs");
234+}
235+
236+fn seek_case(dir: &Path) {
237+ let stream = fs::read(dir.join("bf1280.h264")).expect("read bf1280");
238+ let reference = fs::read(dir.join("bf1280.yuv")).expect("read bf1280 reference");
239+ let units = h264_units(&stream);
240+ let mut decoder = HwDecoder::open(Codec::H264).expect("open decoder");
241+ assert_eq!(decoder.backend(), Backend::Vk, "seek: must decode on Vulkan");
242+ let mut before = Vec::new();
243+ for (pts, unit) in units.iter().take(21).enumerate() {
244+ decoder.decode(unit, pts as i64).expect("decode before seek");
245+ drain(&mut decoder, &mut before);
246+ }
247+ println!("seek: {} frames before reset", before.len());
248+ decoder.reset();
249+ assert!(decoder.decode(units[5], 0).is_err(), "seek: P picture after reset must be an error");
250+ let mut after = Vec::new();
251+ for (pts, unit) in units.iter().enumerate() {
252+ decoder.decode(unit, pts as i64).expect("decode from IDR after seek");
253+ drain(&mut decoder, &mut after);
254+ }
255+ decoder.flush().expect("flush");
256+ drain(&mut decoder, &mut after);
257+ compare("bf1280 seek", Codec::H264, Backend::Vk, dims("1280x720"), &after, &reference);
258+}
259+
260+fn h264_units(data: &[u8]) -> Vec<&[u8]> {
261+ let mut units = Vec::new();
262+ let mut start = 0;
263+ let mut seen_slice = false;
264+ for nal in nal_units(data) {
265+ let at = nal.as_ptr() as usize - data.as_ptr() as usize;
266+ let body = if nal[..3] == [0, 0, 1] { 3 } else { 4 };
267+ let kind = nal[body] & 0x1f;
268+ let slice = matches!(kind, 1 | 5);
269+ let first_slice = slice && nal[body + 1] & 0x80 != 0;
270+ if (first_slice || (matches!(kind, 6..=9) && seen_slice)) && seen_slice {
271+ units.push(&data[start..at]);
272+ start = at;
273+ seen_slice = false;
274+ }
275+ seen_slice |= slice;
276+ }
277+ units.push(&data[start..]);
278+ units
111 }279 }
112 280
113 fn vp9_cases(dir: &Path) {281 fn vp9_cases(dir: &Path) {
crates/ec-hw/src/hw.rsmodified+156 -38
@@ -12,7 +12,7 @@ use std::collections::VecDeque;
12 use crate::error::{Error, Result};12 use crate::error::{Error, Result};
13 use crate::picture::{Decoded, I420, I420_16, RgbPicture};13 use crate::picture::{Decoded, I420, I420_16, RgbPicture};
14 #[cfg(target_os = "linux")]14 #[cfg(target_os = "linux")]
15-use crate::picture::{rgb_size, yuv_to_rgb};15+use crate::picture::{DmaBufPicture, i420_to_rgb};
16 #[cfg(target_os = "linux")]16 #[cfg(target_os = "linux")]
17 use ec_core::color::{ColorDescription, Matrix, Tags};17 use ec_core::color::{ColorDescription, Matrix, Tags};
18 use crate::types::{18 use crate::types::{
@@ -46,11 +46,30 @@ pub enum Direction {
46 Decode,46 Decode,
47 }47 }
48 48
49-/// One codec, direction and backend this machine offers.49+/// Profile of a [`Capability`], 4:2:0 only.
50+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51+pub enum CodecProfile {
52+ /// H.264 High, 8-bit.
53+ H264High,
54+ /// H.265 Main, 8-bit.
55+ H265Main,
56+ /// H.265 Main 10, 10-bit.
57+ H265Main10,
58+ /// AV1 Main, 8-bit.
59+ Av1Main,
60+ /// AV1 Main, 10-bit.
61+ Av1Main10,
62+ /// VP9 Profile 0, 8-bit.
63+ Vp9Profile0,
64+}
65+
66+/// One codec, profile, direction and backend this machine offers.
50 #[derive(Debug, Clone, Copy, PartialEq, Eq)]67 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
51 pub struct Capability {68 pub struct Capability {
52 /// Codec.69 /// Codec.
53 pub codec: Codec,70 pub codec: Codec,
71+ /// Profile.
72+ pub profile: CodecProfile,
54 /// Direction.73 /// Direction.
55 pub direction: Direction,74 pub direction: Direction,
56 /// Largest width in luma samples.75 /// Largest width in luma samples.
@@ -125,6 +144,7 @@ pub fn capabilities() -> Vec<Capability> {
125 &mut out,144 &mut out,
126 Capability {145 Capability {
127 codec,146 codec,
147+ profile: vk_profile(caps.profile),
128 direction,148 direction,
129 max_width: caps.max_width,149 max_width: caps.max_width,
130 max_height: caps.max_height,150 max_height: caps.max_height,
@@ -141,7 +161,12 @@ pub fn capabilities() -> Vec<Capability> {
141 fn push(out: &mut Vec<Capability>, cap: Capability) {161 fn push(out: &mut Vec<Capability>, cap: Capability) {
142 let known = out162 let known = out
143 .iter()163 .iter()
144- .any(|c| c.codec == cap.codec && c.direction == cap.direction && c.backend == cap.backend);164+ .any(|c| {
165+ c.codec == cap.codec
166+ && c.profile == cap.profile
167+ && c.direction == cap.direction
168+ && c.backend == cap.backend
169+ });
145 if !known {170 if !known {
146 out.push(cap);171 out.push(cap);
147 }172 }
@@ -156,9 +181,6 @@ fn va_capabilities(out: &mut Vec<Capability>) {
156 return;181 return;
157 };182 };
158 for entry in &report.entries {183 for entry in &report.entries {
159- let Some(codec) = va_codec(entry.profile) else {
160- continue;
161- };
162 let direction = match entry.entrypoint {184 let direction = match entry.entrypoint {
163 ec_va::Entrypoint::VLD => Direction::Decode,185 ec_va::Entrypoint::VLD => Direction::Decode,
164 ec_va::Entrypoint::EncSlice | ec_va::Entrypoint::EncSliceLP => Direction::Encode,186 ec_va::Entrypoint::EncSlice | ec_va::Entrypoint::EncSliceLP => Direction::Encode,
@@ -168,32 +190,64 @@ fn va_capabilities(out: &mut Vec<Capability>) {
168 Some(s) => (s.max_width.unwrap_or(4096), s.max_height.unwrap_or(4096)),190 Some(s) => (s.max_width.unwrap_or(4096), s.max_height.unwrap_or(4096)),
169 None => (4096, 4096),191 None => (4096, 4096),
170 };192 };
171- push(193+ for profile in va_profiles(entry.profile, entry.rt_formats) {
172- out,194+ push(
173- Capability {195+ out,
174- codec,196+ Capability {
175- direction,197+ codec: profile.codec(),
176- max_width,198+ profile,
177- max_height,199+ direction,
178- backend: Backend::Va,200+ max_width,
179- },201+ max_height,
180- );202+ backend: Backend::Va,
203+ },
204+ );
205+ }
181 }206 }
182 }207 }
183 208
184 #[cfg(target_os = "linux")]209 #[cfg(target_os = "linux")]
185-fn va_codec(profile: ec_va::Profile) -> Option<Codec> {210+impl CodecProfile {
186- Some(match profile {211+ fn codec(self) -> Codec {
187- ec_va::Profile::H264Baseline212+ match self {
188- | ec_va::Profile::H264ConstrainedBaseline213+ CodecProfile::H264High => Codec::H264,
189- | ec_va::Profile::H264Main214+ CodecProfile::H265Main | CodecProfile::H265Main10 => Codec::H265,
190- | ec_va::Profile::H264High215+ CodecProfile::Av1Main | CodecProfile::Av1Main10 => Codec::Av1,
191- | ec_va::Profile::H264High10 => Codec::H264,216+ CodecProfile::Vp9Profile0 => Codec::Vp9,
192- ec_va::Profile::HEVCMain | ec_va::Profile::HEVCMain10 => Codec::H265,217+ }
193- ec_va::Profile::VP9Profile0 => Codec::Vp9,218+ }
194- ec_va::Profile::AV1Profile0 => Codec::Av1,219+}
195- _ => return None,220+
196- })221+#[cfg(target_os = "linux")]
222+fn va_profiles(profile: ec_va::Profile, rt_formats: u32) -> Vec<CodecProfile> {
223+ let yuv420 = ec_va::va::VA_RT_FORMAT_YUV420;
224+ let yuv420_10 = ec_va::va::VA_RT_FORMAT_YUV420_10;
225+ match profile {
226+ ec_va::Profile::H264High => vec![CodecProfile::H264High],
227+ ec_va::Profile::HEVCMain => vec![CodecProfile::H265Main],
228+ ec_va::Profile::HEVCMain10 => vec![CodecProfile::H265Main10],
229+ ec_va::Profile::VP9Profile0 => vec![CodecProfile::Vp9Profile0],
230+ ec_va::Profile::AV1Profile0 => [
231+ (yuv420, CodecProfile::Av1Main),
232+ (yuv420_10, CodecProfile::Av1Main10),
233+ ]
234+ .into_iter()
235+ .filter(|(bit, _)| rt_formats & bit != 0)
236+ .map(|(_, p)| p)
237+ .collect(),
238+ _ => Vec::new(),
239+ }
240+}
241+
242+fn vk_profile(profile: ec_vk::CodecProfile) -> CodecProfile {
243+ match profile {
244+ ec_vk::CodecProfile::H264High => CodecProfile::H264High,
245+ ec_vk::CodecProfile::H265Main => CodecProfile::H265Main,
246+ ec_vk::CodecProfile::H265Main10 => CodecProfile::H265Main10,
247+ ec_vk::CodecProfile::Av1Main => CodecProfile::Av1Main,
248+ ec_vk::CodecProfile::Av1Main10 => CodecProfile::Av1Main10,
249+ ec_vk::CodecProfile::Vp9Profile0 => CodecProfile::Vp9Profile0,
250+ }
197 }251 }
198 252
199 /// Byte order of a packed 32-bit RGB pixel; the X or A byte is ignored.253 /// Byte order of a packed 32-bit RGB pixel; the X or A byte is ignored.
@@ -863,6 +917,15 @@ impl VkDecoder {
863 VkDecoder::Vp9(d) => d.flush(),917 VkDecoder::Vp9(d) => d.flush(),
864 }918 }
865 }919 }
920+
921+ fn reset(&mut self) {
922+ match self {
923+ VkDecoder::H264(d) => d.reset(),
924+ VkDecoder::H265(d) => d.reset(),
925+ VkDecoder::Av1(d) => d.reset(),
926+ VkDecoder::Vp9(d) => d.reset(),
927+ }
928+ }
866 }929 }
867 930
868 enum DecInner {931 enum DecInner {
@@ -887,6 +950,8 @@ pub(crate) enum Mode {
887 I420,950 I420,
888 I420_16,951 I420_16,
889 Rgb(RgbOutput),952 Rgb(RgbOutput),
953+ #[cfg(target_os = "linux")]
954+ DmaBuf,
890 }955 }
891 956
892 /// A hardware decoder on whichever backend opened.957 /// A hardware decoder on whichever backend opened.
@@ -916,6 +981,12 @@ impl HwDecoder {
916 HwDecoder::open_mode(codec, Mode::I420_16)981 HwDecoder::open_mode(codec, Mode::I420_16)
917 }982 }
918 983
984+ /// Open a decoder for `codec` that hands out each picture as DMA-BUF file descriptors ([`HwDecoder::next_dmabuf`]). Linux only.
985+ #[cfg(target_os = "linux")]
986+ pub fn open_dmabuf(codec: Codec) -> Result<HwDecoder> {
987+ HwDecoder::open_mode(codec, Mode::DmaBuf)
988+ }
989+
919 fn open_mode(codec: Codec, mode: Mode) -> Result<HwDecoder> {990 fn open_mode(codec: Codec, mode: Mode) -> Result<HwDecoder> {
920 let mut reasons = Vec::new();991 let mut reasons = Vec::new();
921 let born_epoch = crate::reset::gpu_reset_epoch();992 let born_epoch = crate::reset::gpu_reset_epoch();
@@ -1024,6 +1095,21 @@ impl HwDecoder {
1024 }1095 }
1025 }1096 }
1026 1097
1098+ /// 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`].
1099+ #[cfg(target_os = "linux")]
1100+ pub fn next_dmabuf(&mut self) -> Result<Option<(i64, DmaBufPicture)>> {
1101+ if self.mode != Mode::DmaBuf {
1102+ return Err(Error::config(
1103+ "next_dmabuf on a decoder not opened with open_dmabuf",
1104+ ));
1105+ }
1106+ match self.pull()? {
1107+ None => Ok(None),
1108+ Some((ts, Decoded::DmaBuf(picture))) => Ok(Some((ts, picture))),
1109+ Some(_) => Err(Error::config("non-DMA-BUF picture from a DMA-BUF decoder")),
1110+ }
1111+ }
1112+
1027 /// The next picture in display order, as packed RGB with its timestamp. An error on a decoder not opened with [`HwDecoder::open_rgb`].1113 /// The next picture in display order, as packed RGB with its timestamp. An error on a decoder not opened with [`HwDecoder::open_rgb`].
1028 pub fn next_rgb(&mut self) -> Result<Option<(i64, RgbPicture)>> {1114 pub fn next_rgb(&mut self) -> Result<Option<(i64, RgbPicture)>> {
1029 if !matches!(self.mode, Mode::Rgb(_)) {1115 if !matches!(self.mode, Mode::Rgb(_)) {
@@ -1062,6 +1148,7 @@ impl HwDecoder {
1062 .unwrap_or_else(|| default_matrix(i420.height));1148 .unwrap_or_else(|| default_matrix(i420.height));
1063 Decoded::Rgb(va_rgb(&i420, output, matrix))1149 Decoded::Rgb(va_rgb(&i420, output, matrix))
1064 }1150 }
1151+ Mode::DmaBuf => Decoded::DmaBuf(dmabuf_from_prime(frame.export_prime()?)?),
1065 };1152 };
1066 Ok(Some((frame.timestamp, decoded)))1153 Ok(Some((frame.timestamp, decoded)))
1067 }1154 }
@@ -1070,6 +1157,16 @@ impl HwDecoder {
1070 }1157 }
1071 }1158 }
1072 1159
1160+ /// Drop every held picture and all reference state so decoding restarts at a sync sample after a seek. Parameter sets and the GPU session survive. After a reset an inter picture whose references were not decoded since is an error, never a guess.
1161+ pub fn reset(&mut self) {
1162+ match &mut self.inner {
1163+ DecInner::Vk(d) => d.reset(),
1164+ #[cfg(target_os = "linux")]
1165+ DecInner::Va(d) => d.reset(),
1166+ }
1167+ self.replay = None;
1168+ }
1169+
1073 /// Emit every picture still held for reordering.1170 /// Emit every picture still held for reordering.
1074 pub fn flush(&mut self) -> Result<()> {1171 pub fn flush(&mut self) -> Result<()> {
1075 match &mut self.inner {1172 match &mut self.inner {
@@ -1080,6 +1177,32 @@ impl HwDecoder {
1080 }1177 }
1081 }1178 }
1082 1179
1180+#[cfg(target_os = "linux")]
1181+fn dmabuf_from_prime(surface: ec_va::PrimeSurface) -> Result<DmaBufPicture> {
1182+ let planes: Vec<(u32, u32, u32)> = surface
1183+ .layers
1184+ .iter()
1185+ .flat_map(|layer| layer.planes.iter().copied())
1186+ .collect();
1187+ let [y, uv] = planes.as_slice() else {
1188+ return Err(Error::config("exported surface is not a two-plane 4:2:0 picture"));
1189+ };
1190+ let plane = |&(object, offset, pitch): &(u32, u32, u32)| DmaBufPlane {
1191+ fd: object as usize,
1192+ offset,
1193+ pitch,
1194+ };
1195+ let modifier = surface.objects.first().map_or(0, |o| o.modifier);
1196+ Ok(DmaBufPicture {
1197+ fds: surface.objects.into_iter().map(|o| o.fd).collect(),
1198+ fourcc: surface.fourcc,
1199+ modifier,
1200+ width: surface.width,
1201+ height: surface.height,
1202+ planes: [plane(y), plane(uv)],
1203+ })
1204+}
1205+
1083 #[cfg(target_os = "linux")]1206 #[cfg(target_os = "linux")]
1084 fn default_matrix(height: u32) -> Matrix {1207 fn default_matrix(height: u32) -> Matrix {
1085 ColorDescription::resolve(Tags::default(), Tags::default(), height).matrix1208 ColorDescription::resolve(Tags::default(), Tags::default(), height).matrix
@@ -1087,17 +1210,12 @@ fn default_matrix(height: u32) -> Matrix {
1087 1210
1088 #[cfg(target_os = "linux")]1211 #[cfg(target_os = "linux")]
1089 fn va_rgb(frame: &I420, output: RgbOutput, matrix: Matrix) -> RgbPicture {1212 fn va_rgb(frame: &I420, output: RgbOutput, matrix: Matrix) -> RgbPicture {
1090- let (w, h) = rgb_size(frame.width, frame.height, output.max_width);1213+ i420_to_rgb(
1091- let data = ec_dsp::rgb::i420_to_packed(1214+ frame,
1092- &frame.y,1215+ output.max_width,
1093- &frame.u,
1094- &frame.v,
1095- (frame.width as usize, frame.height as usize),
1096- (w as usize, h as usize),
1097 output.order == RgbOrder::Bgra,1216 output.order == RgbOrder::Bgra,
1098- &yuv_to_rgb(matrix),1217+ matrix,
1099- );1218+ )
1100- RgbPicture::new(data, w, h)
1101 }1219 }
1102 1220
1103 #[cfg(target_os = "linux")]1221 #[cfg(target_os = "linux")]
crates/ec-hw/src/lib.rsmodified+4 -3
@@ -90,14 +90,15 @@ pub use ec_vk::{DmaBufFormat, DmaBufPlane};
90 #[cfg(target_os = "linux")]90 #[cfg(target_os = "linux")]
91 pub use hw::{DmaBufFrame, DmaBufYuvFrame};91 pub use hw::{DmaBufFrame, DmaBufYuvFrame};
92 pub use hw::{92 pub use hw::{
93- Backend, Capability, Direction, EncodeInput, HwDecoder, HwEncoder, RgbFrame, RgbOrder,93+ Backend, Capability, CodecProfile, Direction, EncodeInput, HwDecoder, HwEncoder, RgbFrame,
94- RgbOutput,94+ RgbOrder, RgbOutput, capabilities,
95- capabilities,
96 };95 };
97 #[cfg(target_os = "linux")]96 #[cfg(target_os = "linux")]
98 pub use frame::Frame;97 pub use frame::Frame;
99 pub use picture::{Colour, I420, I420_16, RgbPicture, i420_to_nv12, nv12_to_i420};98 pub use picture::{Colour, I420, I420_16, RgbPicture, i420_to_nv12, nv12_to_i420};
100 #[cfg(target_os = "linux")]99 #[cfg(target_os = "linux")]
100+pub use picture::DmaBufPicture;
101+#[cfg(target_os = "linux")]
101 pub use pool::{PooledSurface, SurfacePool};102 pub use pool::{PooledSurface, SurfacePool};
102 pub use reset::{gpu_recently_reset, gpu_reset_epoch, report_gpu_reset};103 pub use reset::{gpu_recently_reset, gpu_reset_epoch, report_gpu_reset};
103 pub use types::{104 pub use types::{
crates/ec-hw/src/picture.rsmodified+93 -1
@@ -58,12 +58,84 @@ impl RgbPicture {
58 }58 }
59 }59 }
60 60
61+/// A decoded picture as DMA-BUF file descriptors: NV12 or P010, Y then UV, in an exportable layout.
62+#[cfg(target_os = "linux")]
63+#[derive(Debug)]
64+pub struct DmaBufPicture {
65+ /// The DMA-BUF objects. Each is closed when the picture drops.
66+ pub fds: Vec<std::os::fd::OwnedFd>,
67+ /// DRM fourcc: NV12 or P010.
68+ pub fourcc: u32,
69+ /// DRM format modifier, 0 for linear.
70+ pub modifier: u64,
71+ /// Width in luma samples.
72+ pub width: u32,
73+ /// Height in luma samples.
74+ pub height: u32,
75+ /// Y plane then UV plane.
76+ pub planes: [ec_vk::DmaBufPlane; 2],
77+}
78+
79+#[cfg(target_os = "linux")]
80+impl From<ec_vk::DmaBufExport> for DmaBufPicture {
81+ fn from(export: ec_vk::DmaBufExport) -> DmaBufPicture {
82+ let fourcc = if export.p010 {
83+ u32::from_le_bytes(*b"P010")
84+ } else {
85+ u32::from_le_bytes(*b"NV12")
86+ };
87+ DmaBufPicture {
88+ fds: vec![export.fd],
89+ fourcc,
90+ modifier: export.modifier,
91+ width: export.width,
92+ height: export.height,
93+ planes: export.planes,
94+ }
95+ }
96+}
97+
98+#[cfg(target_os = "linux")]
99+impl DmaBufPicture {
100+ /// A second handle on the same memory, for a picture shown again from a reference.
101+ pub fn try_clone(&self) -> std::io::Result<DmaBufPicture> {
102+ Ok(DmaBufPicture {
103+ fds: self
104+ .fds
105+ .iter()
106+ .map(|fd| fd.try_clone())
107+ .collect::<std::io::Result<_>>()?,
108+ fourcc: self.fourcc,
109+ modifier: self.modifier,
110+ width: self.width,
111+ height: self.height,
112+ planes: self.planes,
113+ })
114+ }
115+}
116+
61 /// One decoded picture in the decoder's output form.117 /// One decoded picture in the decoder's output form.
62-#[derive(Debug, Clone, PartialEq, Eq)]118+#[derive(Debug)]
63 pub(crate) enum Decoded {119 pub(crate) enum Decoded {
64 I420(I420),120 I420(I420),
65 I420_16(I420_16),121 I420_16(I420_16),
66 Rgb(RgbPicture),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+ }
67 }139 }
68 140
69 /// The YUV to RGB coefficients for a matrix; BT.2020 is taken as BT.709, the nearest integer set here.141 /// The YUV to RGB coefficients for a matrix; BT.2020 is taken as BT.709, the nearest integer set here.
@@ -74,6 +146,26 @@ pub(crate) fn yuv_to_rgb(matrix: Matrix) -> ec_dsp::rgb::YuvToRgb {
74 }146 }
75 }147 }
76 148
149+/// Packed RGB of an 8-bit I420 picture, scaled to `max_width`, converted on the CPU with the coefficients of `matrix`.
150+pub(crate) fn i420_to_rgb(
151+ frame: &I420,
152+ max_width: Option<u32>,
153+ bgra: bool,
154+ matrix: Matrix,
155+) -> RgbPicture {
156+ let (w, h) = rgb_size(frame.width, frame.height, max_width);
157+ let data = ec_dsp::rgb::i420_to_packed(
158+ &frame.y,
159+ &frame.u,
160+ &frame.v,
161+ (frame.width as usize, frame.height as usize),
162+ (w as usize, h as usize),
163+ bgra,
164+ &yuv_to_rgb(matrix),
165+ );
166+ RgbPicture::new(data, w, h)
167+}
168+
77 /// Output size of an RGB picture of `width` x `height`: scaled to `max_width` keeping the aspect, height rounded to the nearest even.169 /// Output size of an RGB picture of `width` x `height`: scaled to `max_width` keeping the aspect, height rounded to the nearest even.
78 pub(crate) fn rgb_size(width: u32, height: u32, max_width: Option<u32>) -> (u32, u32) {170 pub(crate) fn rgb_size(width: u32, height: u32, max_width: Option<u32>) -> (u32, u32) {
79 match max_width {171 match max_width {
crates/ec-hw/src/vkdec264.rsmodified+26 -1
@@ -4,7 +4,8 @@ use std::collections::{HashMap, VecDeque};
4 4
5 use ec_h264_syntax::sps::{ZIGZAG_4X4, ZIGZAG_8X8};5 use ec_h264_syntax::sps::{ZIGZAG_4X4, ZIGZAG_8X8};
6 use ec_h264_syntax::{6 use ec_h264_syntax::{
7- AnnexBIter, DecRefPicMarking, NalHeader, NalUnitType, Pps, SliceHeader, Sps, unescape_rbsp,7+ AnnexBIter, DecRefPicMarking, NalHeader, NalUnitType, Pps, SliceHeader, SliceType, Sps,
8+ unescape_rbsp,
8 };9 };
9 use ec_vk::{10 use ec_vk::{
10 H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, H264RefSlot, H264Sps,11 H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, H264RefSlot, H264Sps,
@@ -127,6 +128,13 @@ impl VkH264Decoder {
127 self.ready.pop_front()128 self.ready.pop_front()
128 }129 }
129 130
131+ pub(crate) fn reset(&mut self) {
132+ self.current = None;
133+ self.dpb.clear();
134+ self.pics.clear();
135+ self.ready.clear();
136+ }
137+
130 pub(crate) fn flush(&mut self) -> Result<()> {138 pub(crate) fn flush(&mut self) -> Result<()> {
131 self.finish_picture()?;139 self.finish_picture()?;
132 self.bump(true);140 self.bump(true);
@@ -179,6 +187,12 @@ impl VkH264Decoder {
179 header: NalHeader,187 header: NalHeader,
180 timestamp: i64,188 timestamp: i64,
181 ) -> Result<()> {189 ) -> Result<()> {
190+ let inter = !matches!(sh.slice_type, SliceType::I | SliceType::Si);
191+ if inter && !header.is_idr() && self.dpb.frames.iter().all(|p| p.mark == Mark::Unused) {
192+ return Err(Error::Stream(ec_core::Error::corrupt(
193+ "H.264 inter picture with no reference picture since the last IDR or reset",
194+ )));
195+ }
182 self.ensure_session(sps)?;196 self.ensure_session(sps)?;
183 if self.params_dirty {197 if self.params_dirty {
184 self.set_parameters()?;198 self.set_parameters()?;
@@ -342,6 +356,17 @@ impl VkH264Decoder {
342 (sps.width, sps.height),356 (sps.width, sps.height),
343 )?)357 )?)
344 }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+ }
345 Mode::Rgb(rgb) => {370 Mode::Rgb(rgb) => {
346 let (left, _, top, _) = sps.crop;371 let (left, _, top, _) = sps.crop;
347 let matrix =372 let matrix =
crates/ec-hw/src/vkdec265.rsmodified+18 -0
@@ -124,6 +124,15 @@ impl VkH265Decoder {
124 self.ready.pop_front()124 self.ready.pop_front()
125 }125 }
126 126
127+ pub(crate) fn reset(&mut self) {
128+ self.current = None;
129+ self.dpb.pictures.clear();
130+ self.dpb.started = false;
131+ self.dpb.prev_tid0_poc = 0;
132+ self.outputs.clear();
133+ self.ready.clear();
134+ }
135+
127 pub(crate) fn flush(&mut self) -> Result<()> {136 pub(crate) fn flush(&mut self) -> Result<()> {
128 self.finish_picture()?;137 self.finish_picture()?;
129 self.bump(true);138 self.bump(true);
@@ -360,6 +369,15 @@ impl VkH265Decoder {
360 )?;369 )?;
361 Decoded::I420_16(crop16(&sps, &y, &uv)?)370 Decoded::I420_16(crop16(&sps, &y, &uv)?)
362 }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+ }
363 Mode::Rgb(rgb) => {381 Mode::Rgb(rgb) => {
364 let (width, height) = sps.display_size();382 let (width, height) = sps.display_size();
365 let origin = (2 * sps.conf_win.left as u32, 2 * sps.conf_win.top as u32);383 let origin = (2 * sps.conf_win.left as u32, 2 * sps.conf_win.top as u32);
crates/ec-hw/src/vkdec_av1.rsmodified+106 -27
@@ -22,8 +22,8 @@ use ec_core::color::{ColorDescription, Tags};
22 22
23 use crate::hw::{Mode, RgbOrder};23 use crate::hw::{Mode, RgbOrder};
24 use crate::picture::{24 use crate::picture::{
25- Decoded, I420, RgbPicture, rgb_size, semi_planar_to_i420, semi_planar_to_i420_16,25+ Decoded, I420, I420_16, RgbPicture, i420_to_rgb, rgb_size, semi_planar_to_i420,
26- yuv_to_rgb,26+ semi_planar_to_i420_16, yuv_to_rgb,
27 };27 };
28 28
29 const DPB_SLOTS: u32 = NUM_REF_FRAMES as u32 + 1;29 const DPB_SLOTS: u32 = NUM_REF_FRAMES as u32 + 1;
@@ -94,6 +94,12 @@ impl VkAv1Decoder {
94 self.ready.pop_front()94 self.ready.pop_front()
95 }95 }
96 96
97+ pub(crate) fn reset(&mut self) {
98+ self.parser = Av1Parser::new();
99+ self.refs = RefSlots::new();
100+ self.ready.clear();
101+ }
102+
97 pub(crate) fn flush(&mut self) -> Result<()> {103 pub(crate) fn flush(&mut self) -> Result<()> {
98 Ok(())104 Ok(())
99 }105 }
@@ -108,16 +114,19 @@ impl VkAv1Decoder {
108 "AV1 show_existing_frame names an empty reference slot",114 "AV1 show_existing_frame names an empty reference slot",
109 ))115 ))
110 })?;116 })?;
111- let shown = if header.film_grain.apply_grain {117+ let seq = self
112- let seq = self118+ .parser
113- .parser119+ .sequence_header()
114- .sequence_header()120+ .ok_or_else(|| Error::config("AV1 frame before any sequence header"))?;
115- .ok_or_else(|| Error::config("AV1 frame before any sequence header"))?;121+ if header.film_grain.apply_grain {
116- grain_supported(seq, !matches!(self.mode, Mode::I420))?;122+ grain_supported(seq, self.mode)?;
117- grained(reference.picture.clone(), &header.film_grain, seq)123+ }
118- } else {124+ let shown = present(
119- reference.picture.clone()125+ self.mode,
120- };126+ reference.picture.try_clone()?,
127+ &header.film_grain,
128+ seq,
129+ )?;
121 self.ready.push_back((timestamp, shown));130 self.ready.push_back((timestamp, shown));
122 if header.frame_type == FrameType::Key {131 if header.frame_type == FrameType::Key {
123 self.refs.refresh(u8::MAX, Some(reference));132 self.refs.refresh(u8::MAX, Some(reference));
@@ -137,7 +146,7 @@ impl VkAv1Decoder {
137 .sequence_header()146 .sequence_header()
138 .cloned()147 .cloned()
139 .ok_or_else(|| Error::config("AV1 frame before any sequence header"))?;148 .ok_or_else(|| Error::config("AV1 frame before any sequence header"))?;
140- check_supported(&seq, header, !matches!(self.mode, Mode::I420))?;149+ check_supported(&seq, header, self.mode)?;
141 let (width, height) = (header.upscaled_width, header.frame_height);150 let (width, height) = (header.upscaled_width, header.frame_height);
142 self.ensure_session(&seq, width, height)?;151 self.ensure_session(&seq, width, height)?;
143 152
@@ -180,7 +189,12 @@ impl VkAv1Decoder {
180 if !(header.show_frame || header.refresh_frame_flags != 0) {189 if !(header.show_frame || header.refresh_frame_flags != 0) {
181 return Ok(());190 return Ok(());
182 }191 }
183- let decoded = match self.mode {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 {
184 Mode::I420 => {198 Mode::I420 => {
185 let (y, uv) = session.av1.read_output(width, height)?;199 let (y, uv) = session.av1.read_output(width, height)?;
186 Decoded::I420(semi_planar_to_i420(200 Decoded::I420(semi_planar_to_i420(
@@ -203,6 +217,11 @@ impl VkAv1Decoder {
203 (width, height),217 (width, height),
204 )?)218 )?)
205 }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+ }
206 Mode::Rgb(rgb) => {225 Mode::Rgb(rgb) => {
207 let codes = Tags::from_codes(u64::from(seq.color_config.matrix_coefficients), 0, 0);226 let codes = Tags::from_codes(u64::from(seq.color_config.matrix_coefficients), 0, 0);
208 let matrix = ColorDescription::resolve(Tags::default(), codes, height).matrix;227 let matrix = ColorDescription::resolve(Tags::default(), codes, height).matrix;
@@ -226,10 +245,8 @@ impl VkAv1Decoder {
226 segmentation_enabled: header.segmentation.enabled,245 segmentation_enabled: header.segmentation.enabled,
227 };246 };
228 if header.show_frame {247 if header.show_frame {
229- self.ready.push_back((248+ let shown = present(mode, decoded.try_clone()?, &header.film_grain, &seq)?;
230- timestamp,249+ self.ready.push_back((timestamp, shown));
231- grained(decoded.clone(), &header.film_grain, &seq),
232- ));
233 }250 }
234 if header.refresh_frame_flags != 0 {251 if header.refresh_frame_flags != 0 {
235 let reference = Rc::new(Reference {252 let reference = Rc::new(Reference {
@@ -287,7 +304,7 @@ impl VkAv1Decoder {
287 }304 }
288 }305 }
289 306
290-fn check_supported(seq: &SequenceHeader, header: &FrameHeader, rgb: bool) -> Result<()> {307+fn check_supported(seq: &SequenceHeader, header: &FrameHeader, mode: Mode) -> Result<()> {
291 let c = &seq.color_config;308 let c = &seq.color_config;
292 if seq.seq_profile != 0309 if seq.seq_profile != 0
293 || !matches!(c.bit_depth, 8 | 10)310 || !matches!(c.bit_depth, 8 | 10)
@@ -304,28 +321,90 @@ fn check_supported(seq: &SequenceHeader, header: &FrameHeader, rgb: bool) -> Res
304 return Err(Error::unsupported("Vulkan AV1 decode", "odd frame size"));321 return Err(Error::unsupported("Vulkan AV1 decode", "odd frame size"));
305 }322 }
306 if header.film_grain.apply_grain {323 if header.film_grain.apply_grain {
307- grain_supported(seq, rgb)?;324+ grain_supported(seq, mode)?;
308 }325 }
309 Ok(())326 Ok(())
310 }327 }
311 328
312-fn grain_supported(seq: &SequenceHeader, rgb: bool) -> Result<()> {329+fn grain_supported(seq: &SequenceHeader, mode: Mode) -> Result<()> {
313- if rgb || seq.color_config.bit_depth != 8 {330+ let eight = seq.color_config.bit_depth == 8;
314- return Err(Error::unsupported(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(
315 "Vulkan AV1 film grain",341 "Vulkan AV1 film grain",
316- "only 8-bit I420 output",342+ "not for this output format",
317- ));343+ ))
318 }344 }
319- Ok(())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+ })
320 }367 }
321 368
322 fn grained(picture: Decoded, grain: &FilmGrainParams, seq: &SequenceHeader) -> Decoded {369 fn grained(picture: Decoded, grain: &FilmGrainParams, seq: &SequenceHeader) -> Decoded {
370+ if !grain.apply_grain {
371+ return picture;
372+ }
323 match picture {373 match picture {
324- Decoded::I420(frame) if grain.apply_grain => Decoded::I420(synthesize(frame, grain, seq)),374+ Decoded::I420(frame) => Decoded::I420(synthesize(frame, grain, seq)),
375+ Decoded::I420_16(frame) => Decoded::I420_16(synthesize16(frame, grain, seq)),
325 other => other,376 other => other,
326 }377 }
327 }378 }
328 379
380+fn synthesize16(frame: I420_16, grain: &FilmGrainParams, seq: &SequenceHeader) -> I420_16 {
381+ let bit_depth = u32::from(seq.color_config.bit_depth);
382+ let shift = if bit_depth == 8 { 2 } else { 0 };
383+ let narrow = |p: &[u16]| p.iter().map(|&s| s >> shift).collect::<Vec<u16>>();
384+ let clean = Picture {
385+ width: frame.width as usize,
386+ height: frame.height as usize,
387+ y: narrow(&frame.y),
388+ u: narrow(&frame.u),
389+ v: narrow(&frame.v),
390+ };
391+ let out = ec_av1::apply_film_grain(
392+ &clean,
393+ grain,
394+ seq.color_config.matrix_coefficients == 0,
395+ bit_depth,
396+ );
397+ let widen = |p: &[u16]| p.iter().map(|&s| s << shift).collect::<Vec<u16>>();
398+ I420_16 {
399+ y: widen(&out.y),
400+ u: widen(&out.u),
401+ v: widen(&out.v),
402+ width: frame.width,
403+ height: frame.height,
404+ bit_depth: 10,
405+ }
406+}
407+
329 fn synthesize(frame: I420, grain: &FilmGrainParams, seq: &SequenceHeader) -> I420 {408 fn synthesize(frame: I420, grain: &FilmGrainParams, seq: &SequenceHeader) -> I420 {
330 let wide = |p: &[u8]| p.iter().map(|&s| u16::from(s)).collect::<Vec<u16>>();409 let wide = |p: &[u8]| p.iter().map(|&s| u16::from(s)).collect::<Vec<u16>>();
331 let clean = Picture {410 let clean = Picture {
crates/ec-hw/src/vkdec_vp9.rsmodified+14 -2
@@ -83,6 +83,13 @@ impl VkVp9Decoder {
83 self.ready.pop_front()83 self.ready.pop_front()
84 }84 }
85 85
86+ pub(crate) fn reset(&mut self) {
87+ self.parser = Vp9Parser::new();
88+ self.refs = RefSlots::new();
89+ self.previous = None;
90+ self.ready.clear();
91+ }
92+
86 pub(crate) fn flush(&mut self) -> Result<()> {93 pub(crate) fn flush(&mut self) -> Result<()> {
87 Ok(())94 Ok(())
88 }95 }
@@ -99,7 +106,7 @@ impl VkVp9Decoder {
99 "VP9 show_existing_frame names an empty reference slot",106 "VP9 show_existing_frame names an empty reference slot",
100 ))107 ))
101 })?;108 })?;
102- self.ready.push_back((timestamp, reference.picture.clone()));109+ self.ready.push_back((timestamp, reference.picture.try_clone()?));
103 if let Some(previous) = self.previous.as_mut() {110 if let Some(previous) = self.previous.as_mut() {
104 previous.show_frame = true;111 previous.show_frame = true;
105 }112 }
@@ -180,6 +187,11 @@ impl VkVp9Decoder {
180 (width, height),187 (width, height),
181 )?)188 )?)
182 }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+ }
183 Mode::Rgb(rgb) => {195 Mode::Rgb(rgb) => {
184 let codes = Tags::from_codes(196 let codes = Tags::from_codes(
185 u64::from(header.color_space.h273().map_or(2, |c| c.2)),197 u64::from(header.color_space.h273().map_or(2, |c| c.2)),
@@ -198,7 +210,7 @@ impl VkVp9Decoder {
198 }210 }
199 };211 };
200 if header.show_frame {212 if header.show_frame {
201- self.ready.push_back((timestamp, decoded.clone()));213+ self.ready.push_back((timestamp, decoded.try_clone()?));
202 }214 }
203 if header.refresh_frame_flags != 0 {215 if header.refresh_frame_flags != 0 {
204 let reference = Rc::new(Reference {216 let reference = Rc::new(Reference {
crates/ec-vk/src/lib.rsmodified+2 -2
@@ -12,12 +12,12 @@ mod h265;
12 pub use av1::{Av1Encoder, Av1EncoderConfig};12 pub use av1::{Av1Encoder, Av1EncoderConfig};
13 pub use h265::{H265Encoder, H265EncoderConfig};13 pub use h265::{H265Encoder, H265EncoderConfig};
14 #[cfg(target_os = "linux")]14 #[cfg(target_os = "linux")]
15-pub use vk_video_ffi::{DmaBuf, DmaBufFormat, DmaBufPlane};15+pub use vk_video_ffi::{DmaBuf, DmaBufExport, DmaBufFormat, DmaBufPlane, read_dmabuf};
16 pub use vk_video_ffi::{16 pub use vk_video_ffi::{
17 Av1Cdef, Av1ColorConfig, Av1DecodeConfig, Av1DecodePicture, Av1DecodeSession, Av1DeltaParams,17 Av1Cdef, Av1ColorConfig, Av1DecodeConfig, Av1DecodePicture, Av1DecodeSession, Av1DeltaParams,
18 Av1FrameHeader, Av1FrameType, Av1GlobalMotion, Av1InterpolationFilter, Av1LoopFilter,18 Av1FrameHeader, Av1FrameType, Av1GlobalMotion, Av1InterpolationFilter, Av1LoopFilter,
19 Av1LoopRestoration, Av1Quantization, Av1RefSlot, Av1Restoration, Av1Segmentation,19 Av1LoopRestoration, Av1Quantization, Av1RefSlot, Av1Restoration, Av1Segmentation,
20- Av1SequenceHeader, Av1TileInfo, Av1TimingInfo, Av1TxMode, Av1WarpModel, Codec, Direction,20+ Av1SequenceHeader, Av1TileInfo, Av1TimingInfo, Av1TxMode, Av1WarpModel, Codec, CodecProfile, Direction,
21 Error, Gpu, H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, H264RefSlot,21 Error, Gpu, H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, H264RefSlot,
22 H264Sps, H265DecPicBufMgr, H265DecodeConfig, H265DecodePicture, H265DecodeSession,22 H264Sps, H265DecPicBufMgr, H265DecodeConfig, H265DecodePicture, H265DecodeSession,
23 H265LongTermRefPicSps, H265Pcm, H265Pps, H265ProfileTierLevel, H265RefSlot, H265ScalingLists,23 H265LongTermRefPicSps, H265Pcm, H265Pps, H265ProfileTierLevel, H265RefSlot, H265ScalingLists,
shims/vk-video-ffi/src/av1_decode.rsmodified+9 -0
@@ -857,6 +857,15 @@ impl Av1DecodeSession {
857 self.dec.read_nv12(width, height)857 self.dec.read_nv12(width, height)
858 }858 }
859 859
860+ /// Exports the crop window `(x, y, width, height)` of the last decoded picture as one DMA-BUF of NV12 or P010 planes.
861+ #[cfg(target_os = "linux")]
862+ pub fn read_output_dmabuf(
863+ &mut self,
864+ crop: (u32, u32, u32, u32),
865+ ) -> Result<crate::dmabuf::DmaBufExport, Error> {
866+ self.dec.export(crop)
867+ }
868+
860 /// 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.869 /// 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.
861 pub fn read_output_rgb(870 pub fn read_output_rgb(
862 &mut self,871 &mut self,
shims/vk-video-ffi/src/dmabuf.rsmodified+482 -23
@@ -1,10 +1,14 @@
1-use std::os::fd::{AsRawFd, BorrowedFd, IntoRawFd};1+use std::ffi::c_int;
2+use std::os::fd::{AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd};
2 use std::os::unix::fs::MetadataExt;3 use std::os::unix::fs::MetadataExt;
3 4
4 use vulkanalia::prelude::v1_3::*;5 use vulkanalia::prelude::v1_3::*;
5-use vulkanalia::vk::KhrExternalMemoryFdExtensionDeviceCommands;6+use vulkanalia::vk::{
7+ ExtImageDrmFormatModifierExtensionDeviceCommands, KhrExternalMemoryFdExtensionDeviceCommands,
8+};
6 9
7-use crate::session::{NV12, P010, memory_type, vk};10+use crate::session::{Lane, NV12, P010, PLANE_0, PLANE_1, color_range, memory_type, vk};
11+use std::os::fd::AsFd;
8 use crate::{Error, Gpu};12 use crate::{Error, Gpu};
9 13
10 const CACHE_SIZE: usize = 16;14 const CACHE_SIZE: usize = 16;
@@ -59,6 +63,26 @@ pub struct DmaBuf<'a> {
59 pub format: DmaBufFormat,63 pub format: DmaBufFormat,
60 }64 }
61 65
66+/// A decoded picture exported as one DMA-BUF holding NV12 or P010 planes (Y, then interleaved UV).
67+#[derive(Debug)]
68+pub struct DmaBufExport {
69+ /// The DMA-BUF; both planes live in it.
70+ pub fd: OwnedFd,
71+ /// DRM format modifier, 0 for linear.
72+ pub modifier: u64,
73+ /// Y then UV plane.
74+ pub planes: [DmaBufPlane; 2],
75+ /// Width in pixels.
76+ pub width: u32,
77+ /// Height in pixels.
78+ pub height: u32,
79+ /// P010 (10 bits in 16-bit words) when true, NV12 otherwise.
80+ pub p010: bool,
81+}
82+
83+const MEMORY_PLANES: [u32; 4] = [0x80, 0x100, 0x200, 0x400];
84+const QUEUE_FAMILY_FOREIGN: u32 = u32::MAX - 1;
85+
62 pub(crate) fn check(gpu: &Gpu) -> Result<(), Error> {86 pub(crate) fn check(gpu: &Gpu) -> Result<(), Error> {
63 let ext = gpu.device().extensions();87 let ext = gpu.device().extensions();
64 let needed = [88 let needed = [
@@ -103,26 +127,6 @@ fn aspect_range(aspect: vk::ImageAspectFlags) -> vk::ImageSubresourceRange {
103 }127 }
104 }128 }
105 129
106-pub(crate) fn plane_copy(aspect: vk::ImageAspectFlags, width: u32, height: u32) -> vk::ImageCopy {
107- let layers = vk::ImageSubresourceLayers {
108- aspect_mask: aspect,
109- mip_level: 0,
110- base_array_layer: 0,
111- layer_count: 1,
112- };
113- vk::ImageCopy::builder()
114- .src_subresource(layers)
115- .src_offset(vk::Offset3D { x: 0, y: 0, z: 0 })
116- .dst_subresource(layers)
117- .dst_offset(vk::Offset3D { x: 0, y: 0, z: 0 })
118- .extent(vk::Extent3D {
119- width,
120- height,
121- depth: 1,
122- })
123- .build()
124-}
125-
126 pub(crate) fn acquire(130 pub(crate) fn acquire(
127 d: &Device,131 d: &Device,
128 cb: vk::CommandBuffer,132 cb: vk::CommandBuffer,
@@ -456,3 +460,458 @@ fn bind(gpu: &Gpu, image: vk::Image, src: &DmaBuf) -> Result<Vec<vk::DeviceMemor
456 }460 }
457 Ok(memories)461 Ok(memories)
458 }462 }
463+
464+/// Every DRM format modifier that can be a transfer destination for `format`.
465+fn export_modifiers(gpu: &Gpu, format: vk::Format) -> Vec<u64> {
466+ let instance = gpu.instance();
467+ let mut count = vk::DrmFormatModifierPropertiesListEXT::builder().build();
468+ let mut props = vk::FormatProperties2::builder().push_next(&mut count).build();
469+ unsafe { instance.get_physical_device_format_properties2(gpu.physical(), format, &mut props) };
470+ let n = count.drm_format_modifier_count as usize;
471+ let mut list = vec![vk::DrmFormatModifierPropertiesEXT::default(); n];
472+ let mut full = vk::DrmFormatModifierPropertiesListEXT::builder()
473+ .drm_format_modifier_properties(&mut list)
474+ .build();
475+ let mut props = vk::FormatProperties2::builder().push_next(&mut full).build();
476+ unsafe { instance.get_physical_device_format_properties2(gpu.physical(), format, &mut props) };
477+ list.iter()
478+ .filter(|m| {
479+ m.drm_format_modifier_tiling_features
480+ .contains(vk::FormatFeatureFlags::TRANSFER_DST)
481+ })
482+ .map(|m| m.drm_format_modifier)
483+ .collect()
484+}
485+
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) };
510+}
511+
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(
514+ gpu: &Gpu,
515+ lane: &Lane,
516+ src: vk::Image,
517+ format: vk::Format,
518+ (x, y, width, height): (u32, u32, u32, u32),
519+) -> Result<DmaBufExport, Error> {
520+ check(gpu)?;
521+ let d = gpu.device();
522+ let modifiers = export_modifiers(gpu, format);
523+ let linear = modifiers.is_empty();
524+ let mut external = vk::ExternalMemoryImageCreateInfo::builder()
525+ .handle_types(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT)
526+ .build();
527+ let mut list = vk::ImageDrmFormatModifierListCreateInfoEXT::builder()
528+ .drm_format_modifiers(&modifiers)
529+ .build();
530+ let info = vk::ImageCreateInfo::builder()
531+ .image_type(vk::ImageType::_2D)
532+ .format(format)
533+ .extent(vk::Extent3D {
534+ width,
535+ height,
536+ depth: 1,
537+ })
538+ .mip_levels(1)
539+ .array_layers(1)
540+ .samples(vk::SampleCountFlags::_1)
541+ .tiling(if linear {
542+ vk::ImageTiling::LINEAR
543+ } else {
544+ vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT
545+ })
546+ .usage(vk::ImageUsageFlags::TRANSFER_DST)
547+ .sharing_mode(vk::SharingMode::EXCLUSIVE)
548+ .initial_layout(vk::ImageLayout::UNDEFINED)
549+ .push_next(&mut external);
550+ let info = if linear {
551+ info.build()
552+ } else {
553+ info.push_next(&mut list).build()
554+ };
555+ let image = unsafe { vk(d.create_image(&info, None), "vkCreateImage")? };
556+ let exported = export_image(gpu, lane, src, image, (x, y, width, height), linear);
557+ 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) };
594+ return Err(e);
595+ }
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();
611+ 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+ ];
634+ 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+ );
648+ transfer(
649+ d,
650+ cb,
651+ image,
652+ (
653+ vk::ImageLayout::UNDEFINED,
654+ vk::PipelineStageFlags2::NONE,
655+ vk::AccessFlags2::NONE,
656+ vk::QUEUE_FAMILY_IGNORED,
657+ ),
658+ copy_dst,
659+ );
660+ d.cmd_copy_image(
661+ cb,
662+ src,
663+ vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
664+ image,
665+ vk::ImageLayout::TRANSFER_DST_OPTIMAL,
666+ &planes_regions,
667+ );
668+ transfer(
669+ d,
670+ cb,
671+ image,
672+ (
673+ vk::ImageLayout::TRANSFER_DST_OPTIMAL,
674+ vk::PipelineStageFlags2::COPY,
675+ vk::AccessFlags2::TRANSFER_WRITE,
676+ lane.family,
677+ ),
678+ (
679+ vk::ImageLayout::GENERAL,
680+ vk::PipelineStageFlags2::NONE,
681+ vk::AccessFlags2::NONE,
682+ QUEUE_FAMILY_FOREIGN,
683+ ),
684+ );
685+ transfer(d, cb, src, copy_src, decode);
686+ }
687+ lane.end()?;
688+ lane.submit()?;
689+ let fd = export_fd(gpu, memory)?;
690+ let modifier = if linear {
691+ 0
692+ } else {
693+ let mut props = vk::ImageDrmFormatModifierPropertiesEXT::default();
694+ unsafe {
695+ vk(
696+ d.get_image_drm_format_modifier_properties_ext(image, &mut props),
697+ "vkGetImageDrmFormatModifierPropertiesEXT",
698+ )?
699+ };
700+ props.drm_format_modifier
701+ };
702+ let planes = [
703+ layout(gpu, image, linear, 0)?,
704+ layout(gpu, image, linear, 1)?,
705+ ];
706+ Ok((fd, modifier, planes))
707+}
708+
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+ },
734+ }
735+}
736+
737+fn export_fd(gpu: &Gpu, memory: vk::DeviceMemory) -> Result<OwnedFd, Error> {
738+ let info = vk::MemoryGetFdInfoKHR::builder()
739+ .memory(memory)
740+ .handle_type(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT)
741+ .build();
742+ let fd: c_int = unsafe {
743+ vk(
744+ gpu.device().get_memory_fd_khr(&info),
745+ "vkGetMemoryFdKHR",
746+ )?
747+ };
748+ Ok(unsafe { OwnedFd::from_raw_fd(fd) })
749+}
750+
751+fn layout(gpu: &Gpu, image: vk::Image, linear: bool, plane: usize) -> Result<DmaBufPlane, Error> {
752+ let aspect = if linear {
753+ [PLANE_0, PLANE_1][plane]
754+ } else {
755+ vk::ImageAspectFlags::from_bits_truncate(MEMORY_PLANES[plane])
756+ };
757+ let sub = vk::ImageSubresource {
758+ aspect_mask: aspect,
759+ mip_level: 0,
760+ array_layer: 0,
761+ };
762+ let l = unsafe { gpu.device().get_image_subresource_layout(image, &sub) };
763+ Ok(DmaBufPlane {
764+ fd: 0,
765+ offset: l.offset as u32,
766+ pitch: l.row_pitch as u32,
767+ })
768+}
769+
770+/// Imports an exported picture back on the GPU and reads its NV12 or P010 planes (Y, interleaved UV) into host memory.
771+pub fn read_dmabuf(gpu: &Gpu, desc: &DmaBufExport) -> Result<(Vec<u8>, Vec<u8>), Error> {
772+ check(gpu)?;
773+ let d = gpu.device();
774+ let format = if desc.p010 {
775+ crate::session::P010
776+ } else {
777+ crate::session::NV12
778+ };
779+ let bytes = if desc.p010 { 2 } else { 1 };
780+ let (w, h) = (desc.width, desc.height);
781+ let layouts = desc.planes.map(|p| vk::SubresourceLayout {
782+ offset: u64::from(p.offset),
783+ size: 0,
784+ row_pitch: u64::from(p.pitch),
785+ array_pitch: 0,
786+ depth_pitch: 0,
787+ });
788+ let mut explicit = vk::ImageDrmFormatModifierExplicitCreateInfoEXT::builder()
789+ .drm_format_modifier(desc.modifier)
790+ .plane_layouts(&layouts)
791+ .build();
792+ let mut external = vk::ExternalMemoryImageCreateInfo::builder()
793+ .handle_types(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT)
794+ .build();
795+ let info = vk::ImageCreateInfo::builder()
796+ .image_type(vk::ImageType::_2D)
797+ .format(format)
798+ .extent(vk::Extent3D {
799+ width: w,
800+ height: h,
801+ depth: 1,
802+ })
803+ .mip_levels(1)
804+ .array_layers(1)
805+ .samples(vk::SampleCountFlags::_1)
806+ .tiling(vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT)
807+ .usage(vk::ImageUsageFlags::TRANSFER_SRC)
808+ .sharing_mode(vk::SharingMode::EXCLUSIVE)
809+ .initial_layout(vk::ImageLayout::UNDEFINED)
810+ .push_next(&mut external)
811+ .push_next(&mut explicit)
812+ .build();
813+ let image = unsafe { vk(d.create_image(&info, None), "vkCreateImage")? };
814+ let fds = [desc.fd.as_fd()];
815+ let src = DmaBuf {
816+ fds: &fds,
817+ planes: &desc.planes,
818+ width: w,
819+ height: h,
820+ modifier: desc.modifier,
821+ format: if desc.p010 {
822+ DmaBufFormat::P010
823+ } else {
824+ DmaBufFormat::Nv12
825+ },
826+ };
827+ let result = match bind(gpu, image, &src) {
828+ Ok(memories) => {
829+ let out = read_image(gpu, image, (w, h), bytes);
830+ for m in memories {
831+ unsafe { d.free_memory(m, None) };
832+ }
833+ out
834+ }
835+ Err(e) => Err(e),
836+ };
837+ unsafe { d.destroy_image(image, None) };
838+ result
839+}
840+
841+fn read_image(
842+ gpu: &Gpu,
843+ image: vk::Image,
844+ (w, h): (u32, u32),
845+ bytes: u32,
846+) -> Result<(Vec<u8>, Vec<u8>), Error> {
847+ let d = gpu.device();
848+ let luma = w as u64 * h as u64 * u64::from(bytes);
849+ let size = luma * 3 / 2;
850+ let info = vk::BufferCreateInfo::builder()
851+ .size(size)
852+ .usage(vk::BufferUsageFlags::TRANSFER_DST)
853+ .sharing_mode(vk::SharingMode::EXCLUSIVE)
854+ .build();
855+ let buffer = unsafe { vk(d.create_buffer(&info, None), "vkCreateBuffer")? };
856+ let req = unsafe { d.get_buffer_memory_requirements(buffer) };
857+ let flags = vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT;
858+ let index = memory_type(gpu, req.memory_type_bits, flags)?;
859+ let alloc = vk::MemoryAllocateInfo::builder()
860+ .allocation_size(req.size)
861+ .memory_type_index(index)
862+ .build();
863+ let memory = unsafe { vk(d.allocate_memory(&alloc, None), "vkAllocateMemory")? };
864+ let lane = Lane::new(gpu, gpu.graphics_family().ok_or(Error::NoDevice)?)?;
865+ let out = (|| -> Result<(Vec<u8>, Vec<u8>), Error> {
866+ unsafe { vk(d.bind_buffer_memory(buffer, memory, 0), "vkBindBufferMemory")? };
867+ let ptr = unsafe {
868+ vk(
869+ d.map_memory(memory, 0, size, vk::MemoryMapFlags::empty()),
870+ "vkMapMemory",
871+ )?
872+ };
873+ let copies = [
874+ crate::session::copy_region(0, PLANE_0, w, h),
875+ crate::session::copy_region(luma, PLANE_1, w / 2, h / 2),
876+ ];
877+ lane.begin()?;
878+ unsafe {
879+ transfer(
880+ d,
881+ lane.cb,
882+ image,
883+ (
884+ vk::ImageLayout::GENERAL,
885+ vk::PipelineStageFlags2::NONE,
886+ vk::AccessFlags2::NONE,
887+ QUEUE_FAMILY_FOREIGN,
888+ ),
889+ (
890+ vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
891+ vk::PipelineStageFlags2::COPY,
892+ vk::AccessFlags2::TRANSFER_READ,
893+ lane.family,
894+ ),
895+ );
896+ d.cmd_copy_image_to_buffer(
897+ lane.cb,
898+ image,
899+ vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
900+ buffer,
901+ &copies,
902+ );
903+ }
904+ lane.end()?;
905+ lane.submit()?;
906+ let data = unsafe { std::slice::from_raw_parts(ptr as *const u8, size as usize) };
907+ let split = luma as usize;
908+ let planes = (data[..split].to_vec(), data[split..].to_vec());
909+ unsafe { d.unmap_memory(memory) };
910+ Ok(planes)
911+ })();
912+ unsafe {
913+ d.destroy_buffer(buffer, None);
914+ d.free_memory(memory, None);
915+ }
916+ out
917+}
shims/vk-video-ffi/src/h264_decode.rsmodified+9 -0
@@ -461,6 +461,15 @@ impl H264DecodeSession {
461 self.dec.read_nv12(width, height)461 self.dec.read_nv12(width, height)
462 }462 }
463 463
464+ /// Exports the crop window `(x, y, width, height)` of the last decoded picture as one DMA-BUF of NV12 or P010 planes.
465+ #[cfg(target_os = "linux")]
466+ pub fn read_output_dmabuf(
467+ &mut self,
468+ crop: (u32, u32, u32, u32),
469+ ) -> Result<crate::dmabuf::DmaBufExport, Error> {
470+ self.dec.export(crop)
471+ }
472+
464 /// 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.473 /// 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.
465 pub fn read_output_rgb(474 pub fn read_output_rgb(
466 &mut self,475 &mut self,
shims/vk-video-ffi/src/h265_decode.rsmodified+9 -0
@@ -698,6 +698,15 @@ impl H265DecodeSession {
698 self.dec.read_nv12(width, height)698 self.dec.read_nv12(width, height)
699 }699 }
700 700
701+ /// Exports the crop window `(x, y, width, height)` of the last decoded picture as one DMA-BUF of NV12 or P010 planes.
702+ #[cfg(target_os = "linux")]
703+ pub fn read_output_dmabuf(
704+ &mut self,
705+ crop: (u32, u32, u32, u32),
706+ ) -> Result<crate::dmabuf::DmaBufExport, Error> {
707+ self.dec.export(crop)
708+ }
709+
701 /// 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.710 /// 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.
702 pub fn read_output_rgb(711 pub fn read_output_rgb(
703 &mut self,712 &mut self,
shims/vk-video-ffi/src/lib.rsmodified+73 -26
@@ -27,7 +27,7 @@ pub use av1_decode::{
27 };27 };
28 pub use av1_encode::{Av1EncodeConfig, Av1EncodeSession, Av1Picture, Av1Ref};28 pub use av1_encode::{Av1EncodeConfig, Av1EncodeSession, Av1Picture, Av1Ref};
29 #[cfg(target_os = "linux")]29 #[cfg(target_os = "linux")]
30-pub use dmabuf::{DmaBuf, DmaBufFormat, DmaBufPlane};30+pub use dmabuf::{DmaBuf, DmaBufExport, DmaBufFormat, DmaBufPlane, read_dmabuf};
31 pub use vp9_decode::{31 pub use vp9_decode::{
32 Vp9ColorConfig, Vp9DecodeConfig, Vp9DecodePicture, Vp9DecodeSession, Vp9FrameHeader,32 Vp9ColorConfig, Vp9DecodeConfig, Vp9DecodePicture, Vp9DecodeSession, Vp9FrameHeader,
33 Vp9InterpolationFilter, Vp9LoopFilter, Vp9Segmentation,33 Vp9InterpolationFilter, Vp9LoopFilter, Vp9Segmentation,
@@ -120,13 +120,32 @@ pub enum Direction {
120 Decode,120 Decode,
121 }121 }
122 122
123-/// Capabilities of one codec and direction, 4:2:0 8-bit.123+/// Profile a capability is queried for, 4:2:0 only.
124+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125+pub enum CodecProfile {
126+ /// H.264 High, 8-bit.
127+ H264High,
128+ /// H.265 Main, 8-bit.
129+ H265Main,
130+ /// H.265 Main 10, 10-bit.
131+ H265Main10,
132+ /// AV1 Main, 8-bit.
133+ Av1Main,
134+ /// AV1 Main, 10-bit.
135+ Av1Main10,
136+ /// VP9 Profile 0, 8-bit.
137+ Vp9Profile0,
138+}
139+
140+/// Capabilities of one codec, profile and direction.
124 #[derive(Debug, Clone, Copy, PartialEq, Eq)]141 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
125 pub struct CodecCaps {142 pub struct CodecCaps {
126 /// Codec.143 /// Codec.
127 pub codec: Codec,144 pub codec: Codec,
128 /// Direction.145 /// Direction.
129 pub direction: Direction,146 pub direction: Direction,
147+ /// Profile.
148+ pub profile: CodecProfile,
130 /// Maximum coded width.149 /// Maximum coded width.
131 pub max_width: u32,150 pub max_width: u32,
132 /// Maximum coded height.151 /// Maximum coded height.
@@ -324,23 +343,34 @@ impl Gpu {
324 self.inner.graphics343 self.inner.graphics
325 }344 }
326 345
327- /// Capabilities of every codec and direction the device supports.346+ /// Capabilities of every codec, profile and direction the device supports.
328 pub fn caps(&self) -> Vec<CodecCaps> {347 pub fn caps(&self) -> Vec<CodecCaps> {
329 [348 [
330- (Codec::H264, Direction::Encode),349+ (Codec::H264, Direction::Encode, CodecProfile::H264High),
331- (Codec::H264, Direction::Decode),350+ (Codec::H264, Direction::Decode, CodecProfile::H264High),
332- (Codec::H265, Direction::Encode),351+ (Codec::H265, Direction::Encode, CodecProfile::H265Main),
333- (Codec::H265, Direction::Decode),352+ (Codec::H265, Direction::Encode, CodecProfile::H265Main10),
334- (Codec::Av1, Direction::Encode),353+ (Codec::H265, Direction::Decode, CodecProfile::H265Main),
335- (Codec::Av1, Direction::Decode),354+ (Codec::H265, Direction::Decode, CodecProfile::H265Main10),
336- (Codec::Vp9, Direction::Decode),355+ (Codec::Av1, Direction::Encode, CodecProfile::Av1Main),
356+ (Codec::Av1, Direction::Encode, CodecProfile::Av1Main10),
357+ (Codec::Av1, Direction::Decode, CodecProfile::Av1Main),
358+ (Codec::Av1, Direction::Decode, CodecProfile::Av1Main10),
359+ (Codec::Vp9, Direction::Decode, CodecProfile::Vp9Profile0),
337 ]360 ]
338 .into_iter()361 .into_iter()
339- .filter_map(|(codec, direction)| self.codec_caps(codec, direction).ok())362+ .filter_map(|(codec, direction, profile)| {
363+ self.codec_caps(codec, direction, profile).ok()
364+ })
340 .collect()365 .collect()
341 }366 }
342 367
343- fn codec_caps(&self, codec: Codec, direction: Direction) -> Result<CodecCaps, Error> {368+ fn codec_caps(
369+ &self,
370+ codec: Codec,
371+ direction: Direction,
372+ profile: CodecProfile,
373+ ) -> Result<CodecCaps, Error> {
344 let (operation, extension) = match (codec, direction) {374 let (operation, extension) = match (codec, direction) {
345 (Codec::H264, Direction::Encode) => (375 (Codec::H264, Direction::Encode) => (
346 vk::VideoCodecOperationFlagsKHR::ENCODE_H264,376 vk::VideoCodecOperationFlagsKHR::ENCODE_H264,
@@ -377,21 +407,32 @@ impl Gpu {
377 if !self.inner.device.extensions().contains(&extension.name) {407 if !self.inner.device.extensions().contains(&extension.name) {
378 return Err(Error::Unsupported(format!("{codec:?} {direction:?}")));408 return Err(Error::Unsupported(format!("{codec:?} {direction:?}")));
379 }409 }
380- let profile = |operation| {410+ let depth = match profile {
411+ CodecProfile::H265Main10 | CodecProfile::Av1Main10 => {
412+ vk::VideoComponentBitDepthFlagsKHR::_10
413+ }
414+ _ => vk::VideoComponentBitDepthFlagsKHR::_8,
415+ };
416+ let base = |operation| {
381 vk::VideoProfileInfoKHR::builder()417 vk::VideoProfileInfoKHR::builder()
382 .video_codec_operation(operation)418 .video_codec_operation(operation)
383 .chroma_subsampling(vk::VideoChromaSubsamplingFlagsKHR::_420)419 .chroma_subsampling(vk::VideoChromaSubsamplingFlagsKHR::_420)
384- .luma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8)420+ .luma_bit_depth(depth)
385- .chroma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8)421+ .chroma_bit_depth(depth)
422+ };
423+ let h265_idc = match profile {
424+ CodecProfile::H265Main10 => vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN_10,
425+ _ => vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN,
386 };426 };
387 match (codec, direction) {427 match (codec, direction) {
388 (Codec::H264, Direction::Encode) => {428 (Codec::H264, Direction::Encode) => {
389 let mut h = vk::VideoEncodeH264ProfileInfoKHR::builder()429 let mut h = vk::VideoEncodeH264ProfileInfoKHR::builder()
390 .std_profile_idc(vk::video::STD_VIDEO_H264_PROFILE_IDC_HIGH);430 .std_profile_idc(vk::video::STD_VIDEO_H264_PROFILE_IDC_HIGH);
391- let p = profile(operation).push_next(&mut h);431+ let p = base(operation).push_next(&mut h);
392 self.query(432 self.query(
393 codec,433 codec,
394 direction,434 direction,
435+ profile,
395 &p,436 &p,
396 &mut vk::VideoEncodeH264CapabilitiesKHR::builder(),437 &mut vk::VideoEncodeH264CapabilitiesKHR::builder(),
397 )438 )
@@ -400,32 +441,33 @@ impl Gpu {
400 let mut h = vk::VideoDecodeH264ProfileInfoKHR::builder()441 let mut h = vk::VideoDecodeH264ProfileInfoKHR::builder()
401 .std_profile_idc(vk::video::STD_VIDEO_H264_PROFILE_IDC_HIGH)442 .std_profile_idc(vk::video::STD_VIDEO_H264_PROFILE_IDC_HIGH)
402 .picture_layout(vk::VideoDecodeH264PictureLayoutFlagsKHR::PROGRESSIVE);443 .picture_layout(vk::VideoDecodeH264PictureLayoutFlagsKHR::PROGRESSIVE);
403- let p = profile(operation).push_next(&mut h);444+ let p = base(operation).push_next(&mut h);
404 self.query(445 self.query(
405 codec,446 codec,
406 direction,447 direction,
448+ profile,
407 &p,449 &p,
408 &mut vk::VideoDecodeH264CapabilitiesKHR::builder(),450 &mut vk::VideoDecodeH264CapabilitiesKHR::builder(),
409 )451 )
410 }452 }
411 (Codec::H265, Direction::Encode) => {453 (Codec::H265, Direction::Encode) => {
412- let mut h = vk::VideoEncodeH265ProfileInfoKHR::builder()454+ let mut h = vk::VideoEncodeH265ProfileInfoKHR::builder().std_profile_idc(h265_idc);
413- .std_profile_idc(vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN);455+ let p = base(operation).push_next(&mut h);
414- let p = profile(operation).push_next(&mut h);
415 self.query(456 self.query(
416 codec,457 codec,
417 direction,458 direction,
459+ profile,
418 &p,460 &p,
419 &mut vk::VideoEncodeH265CapabilitiesKHR::builder(),461 &mut vk::VideoEncodeH265CapabilitiesKHR::builder(),
420 )462 )
421 }463 }
422 (Codec::H265, Direction::Decode) => {464 (Codec::H265, Direction::Decode) => {
423- let mut h = vk::VideoDecodeH265ProfileInfoKHR::builder()465+ let mut h = vk::VideoDecodeH265ProfileInfoKHR::builder().std_profile_idc(h265_idc);
424- .std_profile_idc(vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN);466+ let p = base(operation).push_next(&mut h);
425- let p = profile(operation).push_next(&mut h);
426 self.query(467 self.query(
427 codec,468 codec,
428 direction,469 direction,
470+ profile,
429 &p,471 &p,
430 &mut vk::VideoDecodeH265CapabilitiesKHR::builder(),472 &mut vk::VideoDecodeH265CapabilitiesKHR::builder(),
431 )473 )
@@ -433,10 +475,11 @@ impl Gpu {
433 (Codec::Av1, Direction::Encode) => {475 (Codec::Av1, Direction::Encode) => {
434 let mut h = vk::VideoEncodeAV1ProfileInfoKHR::builder()476 let mut h = vk::VideoEncodeAV1ProfileInfoKHR::builder()
435 .std_profile(vk::video::STD_VIDEO_AV1_PROFILE_MAIN);477 .std_profile(vk::video::STD_VIDEO_AV1_PROFILE_MAIN);
436- let p = profile(operation).push_next(&mut h);478+ let p = base(operation).push_next(&mut h);
437 self.query(479 self.query(
438 codec,480 codec,
439 direction,481 direction,
482+ profile,
440 &p,483 &p,
441 &mut vk::VideoEncodeAV1CapabilitiesKHR::builder(),484 &mut vk::VideoEncodeAV1CapabilitiesKHR::builder(),
442 )485 )
@@ -444,10 +487,11 @@ impl Gpu {
444 (Codec::Av1, Direction::Decode) => {487 (Codec::Av1, Direction::Decode) => {
445 let mut h = vk::VideoDecodeAV1ProfileInfoKHR::builder()488 let mut h = vk::VideoDecodeAV1ProfileInfoKHR::builder()
446 .std_profile(vk::video::STD_VIDEO_AV1_PROFILE_MAIN);489 .std_profile(vk::video::STD_VIDEO_AV1_PROFILE_MAIN);
447- let p = profile(operation).push_next(&mut h);490+ let p = base(operation).push_next(&mut h);
448 self.query(491 self.query(
449 codec,492 codec,
450 direction,493 direction,
494+ profile,
451 &p,495 &p,
452 &mut vk::VideoDecodeAV1CapabilitiesKHR::builder(),496 &mut vk::VideoDecodeAV1CapabilitiesKHR::builder(),
453 )497 )
@@ -455,10 +499,11 @@ impl Gpu {
455 (Codec::Vp9, _) => {499 (Codec::Vp9, _) => {
456 let mut h = vk::VideoDecodeVP9ProfileInfoKHR::builder()500 let mut h = vk::VideoDecodeVP9ProfileInfoKHR::builder()
457 .std_profile(vk::video::STD_VIDEO_VP9_PROFILE_0);501 .std_profile(vk::video::STD_VIDEO_VP9_PROFILE_0);
458- let p = profile(operation).push_next(&mut h);502+ let p = base(operation).push_next(&mut h);
459 self.query(503 self.query(
460 codec,504 codec,
461 direction,505 direction,
506+ profile,
462 &p,507 &p,
463 &mut vk::VideoDecodeVP9CapabilitiesKHR::builder(),508 &mut vk::VideoDecodeVP9CapabilitiesKHR::builder(),
464 )509 )
@@ -470,6 +515,7 @@ impl Gpu {
470 &self,515 &self,
471 codec: Codec,516 codec: Codec,
472 direction: Direction,517 direction: Direction,
518+ codec_profile: CodecProfile,
473 profile: &vk::VideoProfileInfoKHR,519 profile: &vk::VideoProfileInfoKHR,
474 codec_caps: &mut C,520 codec_caps: &mut C,
475 ) -> Result<CodecCaps, Error>521 ) -> Result<CodecCaps, Error>
@@ -495,6 +541,7 @@ impl Gpu {
495 Ok(CodecCaps {541 Ok(CodecCaps {
496 codec,542 codec,
497 direction,543 direction,
544+ profile: codec_profile,
498 max_width: caps.max_coded_extent.width,545 max_width: caps.max_coded_extent.width,
499 max_height: caps.max_coded_extent.height,546 max_height: caps.max_coded_extent.height,
500 max_dpb_slots: caps.max_dpb_slots,547 max_dpb_slots: caps.max_dpb_slots,
shims/vk-video-ffi/src/session.rsmodified+29 -1
@@ -1069,7 +1069,10 @@ impl Encoder {
1069 let cb = slot.upload.cb;1069 let cb = slot.upload.cb;
1070 let (w, h) = (self.input.0 as u32, self.input.1 as u32);1070 let (w, h) = (self.input.0 as u32, self.input.1 as u32);
1071 let aspects = [PLANE_0, PLANE_1];1071 let aspects = [PLANE_0, PLANE_1];
1072- let regions = [plane_copy(PLANE_0, w, h), plane_copy(PLANE_1, w / 2, h / 2)];1072+ let regions = [
1073+ plane_copy(PLANE_0, (0, 0), (w, h)),
1074+ plane_copy(PLANE_1, (0, 0), (w / 2, h / 2)),
1075+ ];
1073 slot.upload.begin()?;1076 slot.upload.begin()?;
1074 acquire(d, cb, image, &aspects, slot.upload.family);1077 acquire(d, cb, image, &aspects, slot.upload.family);
1075 unsafe {1078 unsafe {
@@ -1554,6 +1557,31 @@ impl Decoder {
1554 Ok(self.rgb_out.bytes(d, len)?.to_vec())1557 Ok(self.rgb_out.bytes(d, len)?.to_vec())
1555 }1558 }
1556 1559
1560+ /// Exports the crop window `(x, y, width, height)` of the last decoded picture as one DMA-BUF of NV12 or P010 planes.
1561+ #[cfg(target_os = "linux")]
1562+ pub(crate) fn export(
1563+ &mut self,
1564+ crop: (u32, u32, u32, u32),
1565+ ) -> Result<crate::dmabuf::DmaBufExport, Error> {
1566+ let (x, y, width, height) = crop;
1567+ if !self.coded {
1568+ return Err(Error::Invalid("nothing decoded".into()));
1569+ }
1570+ if width == 0
1571+ || height == 0
1572+ || width % 2 != 0
1573+ || height % 2 != 0
1574+ || x % 2 != 0
1575+ || y % 2 != 0
1576+ || x + width > self.max_extent.width
1577+ || y + height > self.max_extent.height
1578+ {
1579+ return Err(Error::Invalid("DMA-BUF export size".into()));
1580+ }
1581+ let gpu = self.vs.gpu.clone();
1582+ crate::dmabuf::export(&gpu, &self.graphics, self.output.image, self.vs.format, crop)
1583+ }
1584+
1557 fn copy_to_buffer(1585 fn copy_to_buffer(
1558 &self,1586 &self,
1559 d: &Device,1587 d: &Device,
shims/vk-video-ffi/src/vp9_decode.rsmodified+9 -0
@@ -417,6 +417,15 @@ impl Vp9DecodeSession {
417 self.dec.read_nv12(width, height)417 self.dec.read_nv12(width, height)
418 }418 }
419 419
420+ /// Exports the crop window `(x, y, width, height)` of the last decoded picture as one DMA-BUF of NV12 or P010 planes.
421+ #[cfg(target_os = "linux")]
422+ pub fn read_output_dmabuf(
423+ &mut self,
424+ crop: (u32, u32, u32, u32),
425+ ) -> Result<crate::dmabuf::DmaBufExport, Error> {
426+ self.dec.export(crop)
427+ }
428+
420 /// 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.429 /// 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.
421 pub fn read_output_rgb(430 pub fn read_output_rgb(
422 &mut self,431 &mut self,