forge
Explore
Log in

Don't you dare go Hollow

Vk decode parity: DMA-BUF export, reset, AV1 film grain for 10-bit, per-profile capabilities

Browse files at this commit

f49eeb8551ac7369e3b1445aecbaa0f053a5efddAhmet Kaan GümüşParent: a9418fa

17 changed files +1218 -105

crates/ec-hw/examples/hw_caps.rsmodified+2 -2
@@ -16,8 +16,8 @@ const HEIGHT: u32 = 720;
1616 fn main() {
1717 for cap in capabilities() {
1818 println!(
19- "{:?} {:?} {:?} max {}x{}",
20- cap.backend, cap.direction, cap.codec, cap.max_width, cap.max_height
19+ "{:?} {:?} {:?} {:?} max {}x{}",
20+ cap.backend, cap.direction, cap.codec, cap.profile, cap.max_width, cap.max_height
2121 );
2222 }
2323 for codec in [EncCodec::H264, EncCodec::H265, EncCodec::Av1] {
crates/ec-hw/examples/hw_decode.rsmodified+172 -1
@@ -9,7 +9,10 @@ use std::fs;
99 use std::path::{Path, PathBuf};
1010 use std::process::Command;
1111
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+};
1316
1417 struct Case {
1518 name: &'static str,
@@ -108,6 +111,174 @@ fn main() {
108111 grain(&dir);
109112 own_av1(&dir);
110113 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.object == 0), "one DMA-BUF object per picture");
202+ let p010 = picture.fourcc == u32::from_le_bytes(*b"P010");
203+ let planes = picture.planes.map(|p| ec_vk::DmaBufPlane {
204+ offset: p.offset,
205+ pitch: p.pitch,
206+ });
207+ let fd = picture.fds.into_iter().next().expect("one DMA-BUF object");
208+ let export = ec_vk::DmaBufExport {
209+ fd,
210+ modifier: picture.modifier,
211+ planes,
212+ width: picture.width,
213+ height: picture.height,
214+ p010,
215+ };
216+ ec_vk::read_dmabuf(gpu, &export).expect("read back DMA-BUF")
217+}
218+
219+fn compare_planes(label: &str, codec: Codec, expected: &[(Vec<u8>, Vec<u8>)], got: &[(Vec<u8>, Vec<u8>)]) {
220+ assert_eq!(got.len(), expected.len(), "{label}: frame count");
221+ let mut luma_sum = 0.0f64;
222+ let mut luma_len = 0usize;
223+ let mut chroma_diff = 0usize;
224+ for ((ey, euv), (gy, guv)) in expected.iter().zip(got) {
225+ assert_eq!((ey.len(), euv.len()), (gy.len(), guv.len()), "{label}: plane size");
226+ luma_sum += ey.iter().zip(gy).map(|(&a, &b)| (a as f64 - b as f64).abs()).sum::<f64>();
227+ luma_len += ey.len();
228+ chroma_diff += euv.iter().zip(guv).filter(|(a, b)| a != b).count();
229+ }
230+ let mean = luma_sum / luma_len.max(1) as f64;
231+ println!(
232+ "{label} {codec:?} DMA-BUF: decoded {} frames, max mean |diff| Y {mean:.6}, UV mismatched bytes {chroma_diff}",
233+ got.len(),
234+ );
235+ assert_eq!(chroma_diff, 0, "{label}: UV differs");
236+ assert_eq!(mean, 0.0, "{label}: Y differs");
237+}
238+
239+fn seek_case(dir: &Path) {
240+ let stream = fs::read(dir.join("bf1280.h264")).expect("read bf1280");
241+ let reference = fs::read(dir.join("bf1280.yuv")).expect("read bf1280 reference");
242+ let units = h264_units(&stream);
243+ let mut decoder = HwDecoder::open(Codec::H264).expect("open decoder");
244+ assert_eq!(decoder.backend(), Backend::Vk, "seek: must decode on Vulkan");
245+ let mut before = Vec::new();
246+ for (pts, unit) in units.iter().take(21).enumerate() {
247+ decoder.decode(unit, pts as i64).expect("decode before seek");
248+ drain(&mut decoder, &mut before);
249+ }
250+ println!("seek: {} frames before reset", before.len());
251+ decoder.reset();
252+ assert!(decoder.decode(units[5], 0).is_err(), "seek: P picture after reset must be an error");
253+ let mut after = Vec::new();
254+ for (pts, unit) in units.iter().enumerate() {
255+ decoder.decode(unit, pts as i64).expect("decode from IDR after seek");
256+ drain(&mut decoder, &mut after);
257+ }
258+ decoder.flush().expect("flush");
259+ drain(&mut decoder, &mut after);
260+ compare("bf1280 seek", Codec::H264, Backend::Vk, dims("1280x720"), &after, &reference);
261+}
262+
263+fn h264_units(data: &[u8]) -> Vec<&[u8]> {
264+ let mut units = Vec::new();
265+ let mut start = 0;
266+ let mut seen_slice = false;
267+ for nal in nal_units(data) {
268+ let at = nal.as_ptr() as usize - data.as_ptr() as usize;
269+ let body = if nal[..3] == [0, 0, 1] { 3 } else { 4 };
270+ let kind = nal[body] & 0x1f;
271+ let slice = matches!(kind, 1 | 5);
272+ let first_slice = slice && nal[body + 1] & 0x80 != 0;
273+ if (first_slice || (matches!(kind, 6..=9) && seen_slice)) && seen_slice {
274+ units.push(&data[start..at]);
275+ start = at;
276+ seen_slice = false;
277+ }
278+ seen_slice |= slice;
279+ }
280+ units.push(&data[start..]);
281+ units
111282 }
112283
113284 fn vp9_cases(dir: &Path) {
crates/ec-hw/src/hw.rsmodified+156 -38
@@ -11,7 +11,7 @@ use std::cell::RefCell;
1111 use crate::error::{Error, Result};
1212 use crate::picture::{Decoded, I420, I420_16, RgbPicture};
1313 #[cfg(target_os = "linux")]
14-use crate::picture::{rgb_size, yuv_to_rgb};
14+use crate::picture::{DmaBufPicture, DmaBufPlane, i420_to_rgb};
1515 #[cfg(target_os = "linux")]
1616 use ec_core::color::{ColorDescription, Matrix, Tags};
1717 use crate::types::{
@@ -45,11 +45,30 @@ pub enum Direction {
4545 Decode,
4646 }
4747
48-/// One codec, direction and backend this machine offers.
48+/// Profile of a [`Capability`], 4:2:0 only.
49+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50+pub enum CodecProfile {
51+ /// H.264 High, 8-bit.
52+ H264High,
53+ /// H.265 Main, 8-bit.
54+ H265Main,
55+ /// H.265 Main 10, 10-bit.
56+ H265Main10,
57+ /// AV1 Main, 8-bit.
58+ Av1Main,
59+ /// AV1 Main, 10-bit.
60+ Av1Main10,
61+ /// VP9 Profile 0, 8-bit.
62+ Vp9Profile0,
63+}
64+
65+/// One codec, profile, direction and backend this machine offers.
4966 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
5067 pub struct Capability {
5168 /// Codec.
5269 pub codec: Codec,
70+ /// Profile.
71+ pub profile: CodecProfile,
5372 /// Direction.
5473 pub direction: Direction,
5574 /// Largest width in luma samples.
@@ -124,6 +143,7 @@ pub fn capabilities() -> Vec<Capability> {
124143 &mut out,
125144 Capability {
126145 codec,
146+ profile: vk_profile(caps.profile),
127147 direction,
128148 max_width: caps.max_width,
129149 max_height: caps.max_height,
@@ -140,7 +160,12 @@ pub fn capabilities() -> Vec<Capability> {
140160 fn push(out: &mut Vec<Capability>, cap: Capability) {
141161 let known = out
142162 .iter()
143- .any(|c| c.codec == cap.codec && c.direction == cap.direction && c.backend == cap.backend);
163+ .any(|c| {
164+ c.codec == cap.codec
165+ && c.profile == cap.profile
166+ && c.direction == cap.direction
167+ && c.backend == cap.backend
168+ });
144169 if !known {
145170 out.push(cap);
146171 }
@@ -155,9 +180,6 @@ fn va_capabilities(out: &mut Vec<Capability>) {
155180 return;
156181 };
157182 for entry in &report.entries {
158- let Some(codec) = va_codec(entry.profile) else {
159- continue;
160- };
161183 let direction = match entry.entrypoint {
162184 ec_va::Entrypoint::VLD => Direction::Decode,
163185 ec_va::Entrypoint::EncSlice | ec_va::Entrypoint::EncSliceLP => Direction::Encode,
@@ -167,32 +189,64 @@ fn va_capabilities(out: &mut Vec<Capability>) {
167189 Some(s) => (s.max_width.unwrap_or(4096), s.max_height.unwrap_or(4096)),
168190 None => (4096, 4096),
169191 };
170- push(
171- out,
172- Capability {
173- codec,
174- direction,
175- max_width,
176- max_height,
177- backend: Backend::Va,
178- },
179- );
192+ for profile in va_profiles(entry.profile, entry.rt_formats) {
193+ push(
194+ out,
195+ Capability {
196+ codec: profile.codec(),
197+ profile,
198+ direction,
199+ max_width,
200+ max_height,
201+ backend: Backend::Va,
202+ },
203+ );
204+ }
180205 }
181206 }
182207
183208 #[cfg(target_os = "linux")]
184-fn va_codec(profile: ec_va::Profile) -> Option<Codec> {
185- Some(match profile {
186- ec_va::Profile::H264Baseline
187- | ec_va::Profile::H264ConstrainedBaseline
188- | ec_va::Profile::H264Main
189- | ec_va::Profile::H264High
190- | ec_va::Profile::H264High10 => Codec::H264,
191- ec_va::Profile::HEVCMain | ec_va::Profile::HEVCMain10 => Codec::H265,
192- ec_va::Profile::VP9Profile0 => Codec::Vp9,
193- ec_va::Profile::AV1Profile0 => Codec::Av1,
194- _ => return None,
195- })
209+impl CodecProfile {
210+ fn codec(self) -> Codec {
211+ match self {
212+ CodecProfile::H264High => Codec::H264,
213+ CodecProfile::H265Main | CodecProfile::H265Main10 => Codec::H265,
214+ CodecProfile::Av1Main | CodecProfile::Av1Main10 => Codec::Av1,
215+ CodecProfile::Vp9Profile0 => Codec::Vp9,
216+ }
217+ }
218+}
219+
220+#[cfg(target_os = "linux")]
221+fn va_profiles(profile: ec_va::Profile, rt_formats: u32) -> Vec<CodecProfile> {
222+ let yuv420 = ec_va::va::VA_RT_FORMAT_YUV420;
223+ let yuv420_10 = ec_va::va::VA_RT_FORMAT_YUV420_10;
224+ match profile {
225+ ec_va::Profile::H264High => vec![CodecProfile::H264High],
226+ ec_va::Profile::HEVCMain => vec![CodecProfile::H265Main],
227+ ec_va::Profile::HEVCMain10 => vec![CodecProfile::H265Main10],
228+ ec_va::Profile::VP9Profile0 => vec![CodecProfile::Vp9Profile0],
229+ ec_va::Profile::AV1Profile0 => [
230+ (yuv420, CodecProfile::Av1Main),
231+ (yuv420_10, CodecProfile::Av1Main10),
232+ ]
233+ .into_iter()
234+ .filter(|(bit, _)| rt_formats & bit != 0)
235+ .map(|(_, p)| p)
236+ .collect(),
237+ _ => Vec::new(),
238+ }
239+}
240+
241+fn vk_profile(profile: ec_vk::CodecProfile) -> CodecProfile {
242+ match profile {
243+ ec_vk::CodecProfile::H264High => CodecProfile::H264High,
244+ ec_vk::CodecProfile::H265Main => CodecProfile::H265Main,
245+ ec_vk::CodecProfile::H265Main10 => CodecProfile::H265Main10,
246+ ec_vk::CodecProfile::Av1Main => CodecProfile::Av1Main,
247+ ec_vk::CodecProfile::Av1Main10 => CodecProfile::Av1Main10,
248+ ec_vk::CodecProfile::Vp9Profile0 => CodecProfile::Vp9Profile0,
249+ }
196250 }
197251
198252 /// Byte order of a packed 32-bit RGB pixel; the X or A byte is ignored.
@@ -648,6 +702,15 @@ impl VkDecoder {
648702 VkDecoder::Vp9(d) => d.flush(),
649703 }
650704 }
705+
706+ fn reset(&mut self) {
707+ match self {
708+ VkDecoder::H264(d) => d.reset(),
709+ VkDecoder::H265(d) => d.reset(),
710+ VkDecoder::Av1(d) => d.reset(),
711+ VkDecoder::Vp9(d) => d.reset(),
712+ }
713+ }
651714 }
652715
653716 enum DecInner {
@@ -672,6 +735,8 @@ pub(crate) enum Mode {
672735 I420,
673736 I420_16,
674737 Rgb(RgbOutput),
738+ #[cfg(target_os = "linux")]
739+ DmaBuf,
675740 }
676741
677742 /// A hardware decoder on whichever backend opened.
@@ -701,6 +766,12 @@ impl HwDecoder {
701766 HwDecoder::open_mode(codec, Mode::I420_16)
702767 }
703768
769+ /// Open a decoder for `codec` that hands out each picture as DMA-BUF file descriptors ([`HwDecoder::next_dmabuf`]). Linux only.
770+ #[cfg(target_os = "linux")]
771+ pub fn open_dmabuf(codec: Codec) -> Result<HwDecoder> {
772+ HwDecoder::open_mode(codec, Mode::DmaBuf)
773+ }
774+
704775 fn open_mode(codec: Codec, mode: Mode) -> Result<HwDecoder> {
705776 let mut reasons = Vec::new();
706777 let born_epoch = crate::reset::gpu_reset_epoch();
@@ -809,6 +880,21 @@ impl HwDecoder {
809880 }
810881 }
811882
883+ /// 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`].
884+ #[cfg(target_os = "linux")]
885+ pub fn next_dmabuf(&mut self) -> Result<Option<(i64, DmaBufPicture)>> {
886+ if self.mode != Mode::DmaBuf {
887+ return Err(Error::config(
888+ "next_dmabuf on a decoder not opened with open_dmabuf",
889+ ));
890+ }
891+ match self.pull()? {
892+ None => Ok(None),
893+ Some((ts, Decoded::DmaBuf(picture))) => Ok(Some((ts, picture))),
894+ Some(_) => Err(Error::config("non-DMA-BUF picture from a DMA-BUF decoder")),
895+ }
896+ }
897+
812898 /// The next picture in display order, as packed RGB with its timestamp. An error on a decoder not opened with [`HwDecoder::open_rgb`].
813899 pub fn next_rgb(&mut self) -> Result<Option<(i64, RgbPicture)>> {
814900 if !matches!(self.mode, Mode::Rgb(_)) {
@@ -847,6 +933,7 @@ impl HwDecoder {
847933 .unwrap_or_else(|| default_matrix(i420.height));
848934 Decoded::Rgb(va_rgb(&i420, output, matrix))
849935 }
936+ Mode::DmaBuf => Decoded::DmaBuf(dmabuf_from_prime(frame.export_prime()?)?),
850937 };
851938 Ok(Some((frame.timestamp, decoded)))
852939 }
@@ -855,6 +942,16 @@ impl HwDecoder {
855942 }
856943 }
857944
945+ /// 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.
946+ pub fn reset(&mut self) {
947+ match &mut self.inner {
948+ DecInner::Vk(d) => d.reset(),
949+ #[cfg(target_os = "linux")]
950+ DecInner::Va(d) => d.reset(),
951+ }
952+ self.replay = None;
953+ }
954+
858955 /// Emit every picture still held for reordering.
859956 pub fn flush(&mut self) -> Result<()> {
860957 match &mut self.inner {
@@ -865,6 +962,32 @@ impl HwDecoder {
865962 }
866963 }
867964
965+#[cfg(target_os = "linux")]
966+fn dmabuf_from_prime(surface: ec_va::PrimeSurface) -> Result<DmaBufPicture> {
967+ let planes: Vec<(u32, u32, u32)> = surface
968+ .layers
969+ .iter()
970+ .flat_map(|layer| layer.planes.iter().copied())
971+ .collect();
972+ let [y, uv] = planes.as_slice() else {
973+ return Err(Error::config("exported surface is not a two-plane 4:2:0 picture"));
974+ };
975+ let plane = |&(object, offset, pitch): &(u32, u32, u32)| DmaBufPlane {
976+ object,
977+ offset: u64::from(offset),
978+ pitch,
979+ };
980+ let modifier = surface.objects.first().map_or(0, |o| o.modifier);
981+ Ok(DmaBufPicture {
982+ fds: surface.objects.into_iter().map(|o| o.fd).collect(),
983+ fourcc: surface.fourcc,
984+ modifier,
985+ width: surface.width,
986+ height: surface.height,
987+ planes: [plane(y), plane(uv)],
988+ })
989+}
990+
868991 #[cfg(target_os = "linux")]
869992 fn default_matrix(height: u32) -> Matrix {
870993 ColorDescription::resolve(Tags::default(), Tags::default(), height).matrix
@@ -872,17 +995,12 @@ fn default_matrix(height: u32) -> Matrix {
872995
873996 #[cfg(target_os = "linux")]
874997 fn va_rgb(frame: &I420, output: RgbOutput, matrix: Matrix) -> RgbPicture {
875- let (w, h) = rgb_size(frame.width, frame.height, output.max_width);
876- let data = ec_dsp::rgb::i420_to_packed(
877- &frame.y,
878- &frame.u,
879- &frame.v,
880- (frame.width as usize, frame.height as usize),
881- (w as usize, h as usize),
998+ i420_to_rgb(
999+ frame,
1000+ output.max_width,
8821001 output.order == RgbOrder::Bgra,
883- &yuv_to_rgb(matrix),
884- );
885- RgbPicture::new(data, w, h)
1002+ matrix,
1003+ )
8861004 }
8871005
8881006 #[cfg(target_os = "linux")]
crates/ec-hw/src/lib.rsmodified+4 -2
@@ -88,13 +88,15 @@ pub use error::{Error, Result};
8888 #[cfg(target_os = "linux")]
8989 pub use hw::DmaBufFrame;
9090 pub use hw::{
91- Backend, Capability, Direction, HwDecoder, HwEncoder, RgbFrame, RgbOrder, RgbOutput,
92- capabilities,
91+ Backend, Capability, CodecProfile, Direction, HwDecoder, HwEncoder, RgbFrame, RgbOrder,
92+ RgbOutput, capabilities,
9393 };
9494 #[cfg(target_os = "linux")]
9595 pub use frame::Frame;
9696 pub use picture::{Colour, I420, I420_16, RgbPicture, i420_to_nv12, nv12_to_i420};
9797 #[cfg(target_os = "linux")]
98+pub use picture::{DmaBufPicture, DmaBufPlane};
99+#[cfg(target_os = "linux")]
98100 pub use pool::{PooledSurface, SurfacePool};
99101 pub use reset::{gpu_recently_reset, gpu_reset_epoch, report_gpu_reset};
100102 pub use types::{
crates/ec-hw/src/picture.rsmodified+109 -1
@@ -58,12 +58,100 @@ impl RgbPicture {
5858 }
5959 }
6060
61+/// One plane of a DMA-BUF picture: the object it lives in, its byte offset and row pitch.
62+#[cfg(target_os = "linux")]
63+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64+pub struct DmaBufPlane {
65+ /// Index into [`DmaBufPicture::fds`].
66+ pub object: u32,
67+ /// Byte offset of the plane inside its object.
68+ pub offset: u64,
69+ /// Row pitch in bytes.
70+ pub pitch: u32,
71+}
72+
73+/// A decoded picture as DMA-BUF file descriptors: NV12 or P010, Y then UV, in an exportable layout.
74+#[cfg(target_os = "linux")]
75+#[derive(Debug)]
76+pub struct DmaBufPicture {
77+ /// The DMA-BUF objects. Each is closed when the picture drops.
78+ pub fds: Vec<std::os::fd::OwnedFd>,
79+ /// DRM fourcc: NV12 or P010.
80+ pub fourcc: u32,
81+ /// DRM format modifier, 0 for linear.
82+ pub modifier: u64,
83+ /// Width in luma samples.
84+ pub width: u32,
85+ /// Height in luma samples.
86+ pub height: u32,
87+ /// Y plane then UV plane.
88+ pub planes: [DmaBufPlane; 2],
89+}
90+
91+#[cfg(target_os = "linux")]
92+impl From<ec_vk::DmaBufExport> for DmaBufPicture {
93+ fn from(export: ec_vk::DmaBufExport) -> DmaBufPicture {
94+ let fourcc = if export.p010 {
95+ u32::from_le_bytes(*b"P010")
96+ } else {
97+ u32::from_le_bytes(*b"NV12")
98+ };
99+ DmaBufPicture {
100+ fds: vec![export.fd],
101+ fourcc,
102+ modifier: export.modifier,
103+ width: export.width,
104+ height: export.height,
105+ planes: export.planes.map(|p| DmaBufPlane {
106+ object: 0,
107+ offset: p.offset,
108+ pitch: p.pitch,
109+ }),
110+ }
111+ }
112+}
113+
114+#[cfg(target_os = "linux")]
115+impl DmaBufPicture {
116+ /// A second handle on the same memory, for a picture shown again from a reference.
117+ pub fn try_clone(&self) -> std::io::Result<DmaBufPicture> {
118+ Ok(DmaBufPicture {
119+ fds: self
120+ .fds
121+ .iter()
122+ .map(|fd| fd.try_clone())
123+ .collect::<std::io::Result<_>>()?,
124+ fourcc: self.fourcc,
125+ modifier: self.modifier,
126+ width: self.width,
127+ height: self.height,
128+ planes: self.planes,
129+ })
130+ }
131+}
132+
61133 /// One decoded picture in the decoder's output form.
62-#[derive(Debug, Clone, PartialEq, Eq)]
134+#[derive(Debug)]
63135 pub(crate) enum Decoded {
64136 I420(I420),
65137 I420_16(I420_16),
66138 Rgb(RgbPicture),
139+ #[cfg(target_os = "linux")]
140+ DmaBuf(DmaBufPicture),
141+}
142+
143+impl Decoded {
144+ pub(crate) fn try_clone(&self) -> Result<Decoded> {
145+ Ok(match self {
146+ Decoded::I420(frame) => Decoded::I420(frame.clone()),
147+ Decoded::I420_16(frame) => Decoded::I420_16(frame.clone()),
148+ Decoded::Rgb(picture) => Decoded::Rgb(picture.clone()),
149+ #[cfg(target_os = "linux")]
150+ Decoded::DmaBuf(picture) => Decoded::DmaBuf(picture.try_clone().map_err(|e| {
151+ Error::config(format!("duplicating a DMA-BUF picture: {e}"))
152+ })?),
153+ })
154+ }
67155 }
68156
69157 /// The YUV to RGB coefficients for a matrix; BT.2020 is taken as BT.709, the nearest integer set here.
@@ -74,6 +162,26 @@ pub(crate) fn yuv_to_rgb(matrix: Matrix) -> ec_dsp::rgb::YuvToRgb {
74162 }
75163 }
76164
165+/// Packed RGB of an 8-bit I420 picture, scaled to `max_width`, converted on the CPU with the coefficients of `matrix`.
166+pub(crate) fn i420_to_rgb(
167+ frame: &I420,
168+ max_width: Option<u32>,
169+ bgra: bool,
170+ matrix: Matrix,
171+) -> RgbPicture {
172+ let (w, h) = rgb_size(frame.width, frame.height, max_width);
173+ let data = ec_dsp::rgb::i420_to_packed(
174+ &frame.y,
175+ &frame.u,
176+ &frame.v,
177+ (frame.width as usize, frame.height as usize),
178+ (w as usize, h as usize),
179+ bgra,
180+ &yuv_to_rgb(matrix),
181+ );
182+ RgbPicture::new(data, w, h)
183+}
184+
77185 /// Output size of an RGB picture of `width` x `height`: scaled to `max_width` keeping the aspect, height rounded to the nearest even.
78186 pub(crate) fn rgb_size(width: u32, height: u32, max_width: Option<u32>) -> (u32, u32) {
79187 match max_width {
crates/ec-hw/src/vkdec264.rsmodified+26 -1
@@ -4,7 +4,8 @@ use std::collections::{HashMap, VecDeque};
44
55 use ec_h264_syntax::sps::{ZIGZAG_4X4, ZIGZAG_8X8};
66 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,
89 };
910 use ec_vk::{
1011 H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, H264RefSlot, H264Sps,
@@ -127,6 +128,13 @@ impl VkH264Decoder {
127128 self.ready.pop_front()
128129 }
129130
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+
130138 pub(crate) fn flush(&mut self) -> Result<()> {
131139 self.finish_picture()?;
132140 self.bump(true);
@@ -179,6 +187,12 @@ impl VkH264Decoder {
179187 header: NalHeader,
180188 timestamp: i64,
181189 ) -> 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+ }
182196 self.ensure_session(sps)?;
183197 if self.params_dirty {
184198 self.set_parameters()?;
@@ -342,6 +356,17 @@ impl VkH264Decoder {
342356 (sps.width, sps.height),
343357 )?)
344358 }
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+ }
345370 Mode::Rgb(rgb) => {
346371 let (left, _, top, _) = sps.crop;
347372 let matrix =
crates/ec-hw/src/vkdec265.rsmodified+18 -0
@@ -124,6 +124,15 @@ impl VkH265Decoder {
124124 self.ready.pop_front()
125125 }
126126
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+
127136 pub(crate) fn flush(&mut self) -> Result<()> {
128137 self.finish_picture()?;
129138 self.bump(true);
@@ -360,6 +369,15 @@ impl VkH265Decoder {
360369 )?;
361370 Decoded::I420_16(crop16(&sps, &y, &uv)?)
362371 }
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+ }
363381 Mode::Rgb(rgb) => {
364382 let (width, height) = sps.display_size();
365383 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};
2222
2323 use crate::hw::{Mode, RgbOrder};
2424 use crate::picture::{
25- Decoded, I420, RgbPicture, rgb_size, semi_planar_to_i420, semi_planar_to_i420_16,
26- yuv_to_rgb,
25+ Decoded, I420, I420_16, RgbPicture, i420_to_rgb, rgb_size, semi_planar_to_i420,
26+ semi_planar_to_i420_16, yuv_to_rgb,
2727 };
2828
2929 const DPB_SLOTS: u32 = NUM_REF_FRAMES as u32 + 1;
@@ -94,6 +94,12 @@ impl VkAv1Decoder {
9494 self.ready.pop_front()
9595 }
9696
97+ pub(crate) fn reset(&mut self) {
98+ self.parser = Av1Parser::new();
99+ self.refs = RefSlots::new();
100+ self.ready.clear();
101+ }
102+
97103 pub(crate) fn flush(&mut self) -> Result<()> {
98104 Ok(())
99105 }
@@ -108,16 +114,19 @@ impl VkAv1Decoder {
108114 "AV1 show_existing_frame names an empty reference slot",
109115 ))
110116 })?;
111- let shown = if header.film_grain.apply_grain {
112- let seq = self
113- .parser
114- .sequence_header()
115- .ok_or_else(|| Error::config("AV1 frame before any sequence header"))?;
116- grain_supported(seq, !matches!(self.mode, Mode::I420))?;
117- grained(reference.picture.clone(), &header.film_grain, seq)
118- } else {
119- reference.picture.clone()
120- };
117+ let seq = self
118+ .parser
119+ .sequence_header()
120+ .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+ )?;
121130 self.ready.push_back((timestamp, shown));
122131 if header.frame_type == FrameType::Key {
123132 self.refs.refresh(u8::MAX, Some(reference));
@@ -137,7 +146,7 @@ impl VkAv1Decoder {
137146 .sequence_header()
138147 .cloned()
139148 .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)?;
141150 let (width, height) = (header.upscaled_width, header.frame_height);
142151 self.ensure_session(&seq, width, height)?;
143152
@@ -180,7 +189,12 @@ impl VkAv1Decoder {
180189 if !(header.show_frame || header.refresh_frame_flags != 0) {
181190 return Ok(());
182191 }
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 {
184198 Mode::I420 => {
185199 let (y, uv) = session.av1.read_output(width, height)?;
186200 Decoded::I420(semi_planar_to_i420(
@@ -203,6 +217,11 @@ impl VkAv1Decoder {
203217 (width, height),
204218 )?)
205219 }
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+ }
206225 Mode::Rgb(rgb) => {
207226 let codes = Tags::from_codes(u64::from(seq.color_config.matrix_coefficients), 0, 0);
208227 let matrix = ColorDescription::resolve(Tags::default(), codes, height).matrix;
@@ -226,10 +245,8 @@ impl VkAv1Decoder {
226245 segmentation_enabled: header.segmentation.enabled,
227246 };
228247 if header.show_frame {
229- self.ready.push_back((
230- timestamp,
231- grained(decoded.clone(), &header.film_grain, &seq),
232- ));
248+ let shown = present(mode, decoded.try_clone()?, &header.film_grain, &seq)?;
249+ self.ready.push_back((timestamp, shown));
233250 }
234251 if header.refresh_frame_flags != 0 {
235252 let reference = Rc::new(Reference {
@@ -287,7 +304,7 @@ impl VkAv1Decoder {
287304 }
288305 }
289306
290-fn check_supported(seq: &SequenceHeader, header: &FrameHeader, rgb: bool) -> Result<()> {
307+fn check_supported(seq: &SequenceHeader, header: &FrameHeader, mode: Mode) -> Result<()> {
291308 let c = &seq.color_config;
292309 if seq.seq_profile != 0
293310 || !matches!(c.bit_depth, 8 | 10)
@@ -304,28 +321,90 @@ fn check_supported(seq: &SequenceHeader, header: &FrameHeader, rgb: bool) -> Res
304321 return Err(Error::unsupported("Vulkan AV1 decode", "odd frame size"));
305322 }
306323 if header.film_grain.apply_grain {
307- grain_supported(seq, rgb)?;
324+ grain_supported(seq, mode)?;
308325 }
309326 Ok(())
310327 }
311328
312-fn grain_supported(seq: &SequenceHeader, rgb: bool) -> Result<()> {
313- if rgb || seq.color_config.bit_depth != 8 {
314- return Err(Error::unsupported(
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(
315341 "Vulkan AV1 film grain",
316- "only 8-bit I420 output",
317- ));
342+ "not for this output format",
343+ ))
318344 }
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+ })
320367 }
321368
322369 fn grained(picture: Decoded, grain: &FilmGrainParams, seq: &SequenceHeader) -> Decoded {
370+ if !grain.apply_grain {
371+ return picture;
372+ }
323373 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)),
325376 other => other,
326377 }
327378 }
328379
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+
329408 fn synthesize(frame: I420, grain: &FilmGrainParams, seq: &SequenceHeader) -> I420 {
330409 let wide = |p: &[u8]| p.iter().map(|&s| u16::from(s)).collect::<Vec<u16>>();
331410 let clean = Picture {
crates/ec-hw/src/vkdec_vp9.rsmodified+14 -2
@@ -83,6 +83,13 @@ impl VkVp9Decoder {
8383 self.ready.pop_front()
8484 }
8585
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+
8693 pub(crate) fn flush(&mut self) -> Result<()> {
8794 Ok(())
8895 }
@@ -99,7 +106,7 @@ impl VkVp9Decoder {
99106 "VP9 show_existing_frame names an empty reference slot",
100107 ))
101108 })?;
102- self.ready.push_back((timestamp, reference.picture.clone()));
109+ self.ready.push_back((timestamp, reference.picture.try_clone()?));
103110 if let Some(previous) = self.previous.as_mut() {
104111 previous.show_frame = true;
105112 }
@@ -180,6 +187,11 @@ impl VkVp9Decoder {
180187 (width, height),
181188 )?)
182189 }
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+ }
183195 Mode::Rgb(rgb) => {
184196 let codes = Tags::from_codes(
185197 u64::from(header.color_space.h273().map_or(2, |c| c.2)),
@@ -198,7 +210,7 @@ impl VkVp9Decoder {
198210 }
199211 };
200212 if header.show_frame {
201- self.ready.push_back((timestamp, decoded.clone()));
213+ self.ready.push_back((timestamp, decoded.try_clone()?));
202214 }
203215 if header.refresh_frame_flags != 0 {
204216 let reference = Rc::new(Reference {
crates/ec-vk/src/lib.rsmodified+2 -2
@@ -10,12 +10,12 @@ mod h265;
1010 pub use av1::{Av1Encoder, Av1EncoderConfig};
1111 pub use h265::{H265Encoder, H265EncoderConfig};
1212 #[cfg(target_os = "linux")]
13-pub use vk_video_ffi::DmaBuf;
13+pub use vk_video_ffi::{DmaBuf, DmaBufExport, DmaBufPlane, read_dmabuf};
1414 pub use vk_video_ffi::{
1515 Av1Cdef, Av1ColorConfig, Av1DecodeConfig, Av1DecodePicture, Av1DecodeSession, Av1DeltaParams,
1616 Av1FrameHeader, Av1FrameType, Av1GlobalMotion, Av1InterpolationFilter, Av1LoopFilter,
1717 Av1LoopRestoration, Av1Quantization, Av1RefSlot, Av1Restoration, Av1Segmentation,
18- Av1SequenceHeader, Av1TileInfo, Av1TimingInfo, Av1TxMode, Av1WarpModel, Codec, Direction,
18+ Av1SequenceHeader, Av1TileInfo, Av1TimingInfo, Av1TxMode, Av1WarpModel, Codec, CodecProfile, Direction,
1919 Error, Gpu, H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, H264RefSlot,
2020 H264Sps, H265DecPicBufMgr, H265DecodeConfig, H265DecodePicture, H265DecodeSession,
2121 H265LongTermRefPicSps, H265Pcm, H265Pps, H265ProfileTierLevel, H265RefSlot, H265ScalingLists,
shims/vk-video-ffi/src/av1_decode.rsmodified+9 -0
@@ -857,6 +857,15 @@ impl Av1DecodeSession {
857857 self.dec.read_nv12(width, height)
858858 }
859859
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+
860869 /// 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.
861870 pub fn read_output_rgb(
862871 &mut self,
shims/vk-video-ffi/src/dmabuf.rsmodified+475 -3
@@ -1,9 +1,13 @@
1-use std::os::fd::{AsRawFd, BorrowedFd, IntoRawFd};
1+use std::ffi::c_int;
2+use std::os::fd::{AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd};
23
34 use vulkanalia::prelude::v1_3::*;
4-use vulkanalia::vk::KhrExternalMemoryFdExtensionDeviceCommands;
5+use vulkanalia::vk::{
6+ ExtImageDrmFormatModifierExtensionDeviceCommands, KhrExternalMemoryFdExtensionDeviceCommands,
7+};
58
6-use crate::session::{memory_type, vk};
9+use crate::session::{Lane, PLANE_0, PLANE_1, color_range, memory_type, vk};
10+use std::os::fd::AsFd;
711 use crate::{Error, Gpu};
812
913 /// Single-plane 4-bytes-per-pixel DMA-BUF, linear or DRM format modifier tiled.
@@ -24,6 +28,35 @@ pub struct DmaBuf<'a> {
2428 pub bgr: bool,
2529 }
2630
31+/// One plane of an exported picture inside its DMA-BUF.
32+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33+pub struct DmaBufPlane {
34+ /// Byte offset of the plane inside the DMA-BUF.
35+ pub offset: u64,
36+ /// Row pitch in bytes.
37+ pub pitch: u32,
38+}
39+
40+/// A decoded picture exported as one DMA-BUF holding NV12 or P010 planes (Y, then interleaved UV).
41+#[derive(Debug)]
42+pub struct DmaBufExport {
43+ /// The DMA-BUF; both planes live in it.
44+ pub fd: OwnedFd,
45+ /// DRM format modifier, 0 for linear.
46+ pub modifier: u64,
47+ /// Y then UV plane.
48+ pub planes: [DmaBufPlane; 2],
49+ /// Width in pixels.
50+ pub width: u32,
51+ /// Height in pixels.
52+ pub height: u32,
53+ /// P010 (10 bits in 16-bit words) when true, NV12 otherwise.
54+ pub p010: bool,
55+}
56+
57+const MEMORY_PLANES: [u32; 4] = [0x80, 0x100, 0x200, 0x400];
58+const QUEUE_FAMILY_FOREIGN: u32 = u32::MAX - 1;
59+
2760 pub(crate) fn check(gpu: &Gpu) -> Result<(), Error> {
2861 let ext = gpu.device().extensions();
2962 let needed = [
@@ -146,3 +179,442 @@ fn bind(gpu: &Gpu, image: vk::Image, fd: BorrowedFd) -> Result<vk::DeviceMemory,
146179 }
147180 bound.map(|_| memory)
148181 }
182+
183+/// Every DRM format modifier that can be a transfer destination for `format`.
184+fn export_modifiers(gpu: &Gpu, format: vk::Format) -> Vec<u64> {
185+ let instance = gpu.instance();
186+ let mut count = vk::DrmFormatModifierPropertiesListEXT::builder().build();
187+ let mut props = vk::FormatProperties2::builder().push_next(&mut count).build();
188+ unsafe { instance.get_physical_device_format_properties2(gpu.physical(), format, &mut props) };
189+ let n = count.drm_format_modifier_count as usize;
190+ let mut list = vec![vk::DrmFormatModifierPropertiesEXT::default(); n];
191+ let mut full = vk::DrmFormatModifierPropertiesListEXT::builder()
192+ .drm_format_modifier_properties(&mut list)
193+ .build();
194+ let mut props = vk::FormatProperties2::builder().push_next(&mut full).build();
195+ unsafe { instance.get_physical_device_format_properties2(gpu.physical(), format, &mut props) };
196+ list.iter()
197+ .filter(|m| {
198+ m.drm_format_modifier_tiling_features
199+ .contains(vk::FormatFeatureFlags::TRANSFER_DST)
200+ })
201+ .map(|m| m.drm_format_modifier)
202+ .collect()
203+}
204+
205+fn transfer(
206+ d: &Device,
207+ cb: vk::CommandBuffer,
208+ image: vk::Image,
209+ from: (vk::ImageLayout, vk::PipelineStageFlags2, vk::AccessFlags2, u32),
210+ to: (vk::ImageLayout, vk::PipelineStageFlags2, vk::AccessFlags2, u32),
211+) {
212+ let barrier = vk::ImageMemoryBarrier2::builder()
213+ .src_stage_mask(from.1)
214+ .src_access_mask(from.2)
215+ .dst_stage_mask(to.1)
216+ .dst_access_mask(to.2)
217+ .old_layout(from.0)
218+ .new_layout(to.0)
219+ .src_queue_family_index(from.3)
220+ .dst_queue_family_index(to.3)
221+ .image(image)
222+ .subresource_range(color_range())
223+ .build();
224+ let barriers = [barrier];
225+ let info = vk::DependencyInfo::builder()
226+ .image_memory_barriers(&barriers)
227+ .build();
228+ unsafe { d.cmd_pipeline_barrier2(cb, &info) };
229+}
230+
231+/// 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.
232+pub(crate) fn export(
233+ gpu: &Gpu,
234+ lane: &Lane,
235+ src: vk::Image,
236+ format: vk::Format,
237+ (x, y, width, height): (u32, u32, u32, u32),
238+) -> Result<DmaBufExport, Error> {
239+ check(gpu)?;
240+ let d = gpu.device();
241+ let modifiers = export_modifiers(gpu, format);
242+ let linear = modifiers.is_empty();
243+ let mut external = vk::ExternalMemoryImageCreateInfo::builder()
244+ .handle_types(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT)
245+ .build();
246+ let mut list = vk::ImageDrmFormatModifierListCreateInfoEXT::builder()
247+ .drm_format_modifiers(&modifiers)
248+ .build();
249+ let info = vk::ImageCreateInfo::builder()
250+ .image_type(vk::ImageType::_2D)
251+ .format(format)
252+ .extent(vk::Extent3D {
253+ width,
254+ height,
255+ depth: 1,
256+ })
257+ .mip_levels(1)
258+ .array_layers(1)
259+ .samples(vk::SampleCountFlags::_1)
260+ .tiling(if linear {
261+ vk::ImageTiling::LINEAR
262+ } else {
263+ vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT
264+ })
265+ .usage(vk::ImageUsageFlags::TRANSFER_DST)
266+ .sharing_mode(vk::SharingMode::EXCLUSIVE)
267+ .initial_layout(vk::ImageLayout::UNDEFINED)
268+ .push_next(&mut external);
269+ let info = if linear {
270+ info.build()
271+ } else {
272+ info.push_next(&mut list).build()
273+ };
274+ let image = unsafe { vk(d.create_image(&info, None), "vkCreateImage")? };
275+ let exported = export_image(gpu, lane, src, image, (x, y, width, height), linear);
276+ unsafe { d.destroy_image(image, None) };
277+ exported.map(|(fd, modifier, planes)| DmaBufExport {
278+ fd,
279+ modifier,
280+ planes,
281+ width,
282+ height,
283+ p010: format == crate::session::P010,
284+ })
285+}
286+
287+fn export_image(
288+ gpu: &Gpu,
289+ lane: &Lane,
290+ src: vk::Image,
291+ image: vk::Image,
292+ (x, y, width, height): (u32, u32, u32, u32),
293+ linear: bool,
294+) -> Result<(OwnedFd, u64, [DmaBufPlane; 2]), Error> {
295+ let d = gpu.device();
296+ let req = unsafe { d.get_image_memory_requirements(image) };
297+ let index = memory_type(gpu, req.memory_type_bits, vk::MemoryPropertyFlags::DEVICE_LOCAL)?;
298+ let mut export = vk::ExportMemoryAllocateInfo::builder()
299+ .handle_types(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT)
300+ .build();
301+ let mut dedicated = vk::MemoryDedicatedAllocateInfo::builder()
302+ .image(image)
303+ .build();
304+ let alloc = vk::MemoryAllocateInfo::builder()
305+ .allocation_size(req.size)
306+ .memory_type_index(index)
307+ .push_next(&mut dedicated)
308+ .push_next(&mut export)
309+ .build();
310+ let memory = unsafe { vk(d.allocate_memory(&alloc, None), "vkAllocateMemory")? };
311+ if let Err(e) = unsafe { vk(d.bind_image_memory(image, memory, 0), "vkBindImageMemory") } {
312+ unsafe { d.free_memory(memory, None) };
313+ return Err(e);
314+ }
315+ let result = copy_and_export(gpu, lane, src, image, memory, (x, y, width, height), linear);
316+ unsafe { d.free_memory(memory, None) };
317+ result
318+}
319+
320+fn copy_and_export(
321+ gpu: &Gpu,
322+ lane: &Lane,
323+ src: vk::Image,
324+ image: vk::Image,
325+ memory: vk::DeviceMemory,
326+ (x, y, width, height): (u32, u32, u32, u32),
327+ linear: bool,
328+) -> Result<(OwnedFd, u64, [DmaBufPlane; 2]), Error> {
329+ let d = gpu.device();
330+ let cb = lane.cb;
331+ let decode = (
332+ vk::ImageLayout::VIDEO_DECODE_DST_KHR,
333+ vk::PipelineStageFlags2::ALL_COMMANDS,
334+ vk::AccessFlags2::NONE,
335+ vk::QUEUE_FAMILY_IGNORED,
336+ );
337+ let copy_src = (
338+ vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
339+ vk::PipelineStageFlags2::COPY,
340+ vk::AccessFlags2::TRANSFER_READ,
341+ vk::QUEUE_FAMILY_IGNORED,
342+ );
343+ let copy_dst = (
344+ vk::ImageLayout::TRANSFER_DST_OPTIMAL,
345+ vk::PipelineStageFlags2::COPY,
346+ vk::AccessFlags2::TRANSFER_WRITE,
347+ vk::QUEUE_FAMILY_IGNORED,
348+ );
349+ let planes_regions = [
350+ plane_copy(PLANE_0, (x, y), (width, height)),
351+ plane_copy(PLANE_1, (x / 2, y / 2), (width / 2, height / 2)),
352+ ];
353+ lane.begin()?;
354+ unsafe {
355+ transfer(
356+ d,
357+ cb,
358+ src,
359+ decode,
360+ (
361+ vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
362+ vk::PipelineStageFlags2::COPY,
363+ vk::AccessFlags2::TRANSFER_READ,
364+ vk::QUEUE_FAMILY_IGNORED,
365+ ),
366+ );
367+ transfer(
368+ d,
369+ cb,
370+ image,
371+ (
372+ vk::ImageLayout::UNDEFINED,
373+ vk::PipelineStageFlags2::NONE,
374+ vk::AccessFlags2::NONE,
375+ vk::QUEUE_FAMILY_IGNORED,
376+ ),
377+ copy_dst,
378+ );
379+ d.cmd_copy_image(
380+ cb,
381+ src,
382+ vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
383+ image,
384+ vk::ImageLayout::TRANSFER_DST_OPTIMAL,
385+ &planes_regions,
386+ );
387+ transfer(
388+ d,
389+ cb,
390+ image,
391+ (
392+ vk::ImageLayout::TRANSFER_DST_OPTIMAL,
393+ vk::PipelineStageFlags2::COPY,
394+ vk::AccessFlags2::TRANSFER_WRITE,
395+ lane.family,
396+ ),
397+ (
398+ vk::ImageLayout::GENERAL,
399+ vk::PipelineStageFlags2::NONE,
400+ vk::AccessFlags2::NONE,
401+ QUEUE_FAMILY_FOREIGN,
402+ ),
403+ );
404+ transfer(d, cb, src, copy_src, decode);
405+ }
406+ lane.end()?;
407+ lane.submit()?;
408+ let fd = export_fd(gpu, memory)?;
409+ let modifier = if linear {
410+ 0
411+ } else {
412+ let mut props = vk::ImageDrmFormatModifierPropertiesEXT::default();
413+ unsafe {
414+ vk(
415+ d.get_image_drm_format_modifier_properties_ext(image, &mut props),
416+ "vkGetImageDrmFormatModifierPropertiesEXT",
417+ )?
418+ };
419+ props.drm_format_modifier
420+ };
421+ let planes = [
422+ layout(gpu, image, linear, 0)?,
423+ layout(gpu, image, linear, 1)?,
424+ ];
425+ Ok((fd, modifier, planes))
426+}
427+
428+fn plane_copy(
429+ aspect: vk::ImageAspectFlags,
430+ origin: (u32, u32),
431+ (width, height): (u32, u32),
432+) -> vk::ImageCopy {
433+ let layers = vk::ImageSubresourceLayers {
434+ aspect_mask: aspect,
435+ mip_level: 0,
436+ base_array_layer: 0,
437+ layer_count: 1,
438+ };
439+ vk::ImageCopy {
440+ src_subresource: layers,
441+ src_offset: vk::Offset3D {
442+ x: origin.0 as i32,
443+ y: origin.1 as i32,
444+ z: 0,
445+ },
446+ dst_subresource: layers,
447+ dst_offset: vk::Offset3D { x: 0, y: 0, z: 0 },
448+ extent: vk::Extent3D {
449+ width,
450+ height,
451+ depth: 1,
452+ },
453+ }
454+}
455+
456+fn export_fd(gpu: &Gpu, memory: vk::DeviceMemory) -> Result<OwnedFd, Error> {
457+ let info = vk::MemoryGetFdInfoKHR::builder()
458+ .memory(memory)
459+ .handle_type(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT)
460+ .build();
461+ let fd: c_int = unsafe {
462+ vk(
463+ gpu.device().get_memory_fd_khr(&info),
464+ "vkGetMemoryFdKHR",
465+ )?
466+ };
467+ Ok(unsafe { OwnedFd::from_raw_fd(fd) })
468+}
469+
470+fn layout(gpu: &Gpu, image: vk::Image, linear: bool, plane: usize) -> Result<DmaBufPlane, Error> {
471+ let aspect = if linear {
472+ [PLANE_0, PLANE_1][plane]
473+ } else {
474+ vk::ImageAspectFlags::from_bits_truncate(MEMORY_PLANES[plane])
475+ };
476+ let sub = vk::ImageSubresource {
477+ aspect_mask: aspect,
478+ mip_level: 0,
479+ array_layer: 0,
480+ };
481+ let l = unsafe { gpu.device().get_image_subresource_layout(image, &sub) };
482+ Ok(DmaBufPlane {
483+ offset: l.offset,
484+ pitch: l.row_pitch as u32,
485+ })
486+}
487+
488+/// Imports an exported picture back on the GPU and reads its NV12 or P010 planes (Y, interleaved UV) into host memory.
489+pub fn read_dmabuf(gpu: &Gpu, desc: &DmaBufExport) -> Result<(Vec<u8>, Vec<u8>), Error> {
490+ check(gpu)?;
491+ let d = gpu.device();
492+ let format = if desc.p010 {
493+ crate::session::P010
494+ } else {
495+ crate::session::NV12
496+ };
497+ let bytes = if desc.p010 { 2 } else { 1 };
498+ let (w, h) = (desc.width, desc.height);
499+ let layouts = desc.planes.map(|p| vk::SubresourceLayout {
500+ offset: p.offset,
501+ size: 0,
502+ row_pitch: u64::from(p.pitch),
503+ array_pitch: 0,
504+ depth_pitch: 0,
505+ });
506+ let mut explicit = vk::ImageDrmFormatModifierExplicitCreateInfoEXT::builder()
507+ .drm_format_modifier(desc.modifier)
508+ .plane_layouts(&layouts)
509+ .build();
510+ let mut external = vk::ExternalMemoryImageCreateInfo::builder()
511+ .handle_types(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT)
512+ .build();
513+ let info = vk::ImageCreateInfo::builder()
514+ .image_type(vk::ImageType::_2D)
515+ .format(format)
516+ .extent(vk::Extent3D {
517+ width: w,
518+ height: h,
519+ depth: 1,
520+ })
521+ .mip_levels(1)
522+ .array_layers(1)
523+ .samples(vk::SampleCountFlags::_1)
524+ .tiling(vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT)
525+ .usage(vk::ImageUsageFlags::TRANSFER_SRC)
526+ .sharing_mode(vk::SharingMode::EXCLUSIVE)
527+ .initial_layout(vk::ImageLayout::UNDEFINED)
528+ .push_next(&mut external)
529+ .push_next(&mut explicit)
530+ .build();
531+ let image = unsafe { vk(d.create_image(&info, None), "vkCreateImage")? };
532+ let result = match bind(gpu, image, desc.fd.as_fd()) {
533+ Ok(memory) => {
534+ let out = read_image(gpu, image, (w, h), bytes);
535+ unsafe { d.free_memory(memory, None) };
536+ out
537+ }
538+ Err(e) => Err(e),
539+ };
540+ unsafe { d.destroy_image(image, None) };
541+ result
542+}
543+
544+fn read_image(
545+ gpu: &Gpu,
546+ image: vk::Image,
547+ (w, h): (u32, u32),
548+ bytes: u32,
549+) -> Result<(Vec<u8>, Vec<u8>), Error> {
550+ let d = gpu.device();
551+ let luma = w as u64 * h as u64 * u64::from(bytes);
552+ let size = luma * 3 / 2;
553+ let info = vk::BufferCreateInfo::builder()
554+ .size(size)
555+ .usage(vk::BufferUsageFlags::TRANSFER_DST)
556+ .sharing_mode(vk::SharingMode::EXCLUSIVE)
557+ .build();
558+ let buffer = unsafe { vk(d.create_buffer(&info, None), "vkCreateBuffer")? };
559+ let req = unsafe { d.get_buffer_memory_requirements(buffer) };
560+ let flags = vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT;
561+ let index = memory_type(gpu, req.memory_type_bits, flags)?;
562+ let alloc = vk::MemoryAllocateInfo::builder()
563+ .allocation_size(req.size)
564+ .memory_type_index(index)
565+ .build();
566+ let memory = unsafe { vk(d.allocate_memory(&alloc, None), "vkAllocateMemory")? };
567+ let lane = Lane::new(gpu, gpu.graphics_family().ok_or(Error::NoDevice)?)?;
568+ let out = (|| -> Result<(Vec<u8>, Vec<u8>), Error> {
569+ unsafe { vk(d.bind_buffer_memory(buffer, memory, 0), "vkBindBufferMemory")? };
570+ let ptr = unsafe {
571+ vk(
572+ d.map_memory(memory, 0, size, vk::MemoryMapFlags::empty()),
573+ "vkMapMemory",
574+ )?
575+ };
576+ let copies = [
577+ crate::session::copy_region(0, PLANE_0, w, h),
578+ crate::session::copy_region(luma, PLANE_1, w / 2, h / 2),
579+ ];
580+ lane.begin()?;
581+ unsafe {
582+ transfer(
583+ d,
584+ lane.cb,
585+ image,
586+ (
587+ vk::ImageLayout::GENERAL,
588+ vk::PipelineStageFlags2::NONE,
589+ vk::AccessFlags2::NONE,
590+ QUEUE_FAMILY_FOREIGN,
591+ ),
592+ (
593+ vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
594+ vk::PipelineStageFlags2::COPY,
595+ vk::AccessFlags2::TRANSFER_READ,
596+ lane.family,
597+ ),
598+ );
599+ d.cmd_copy_image_to_buffer(
600+ lane.cb,
601+ image,
602+ vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
603+ buffer,
604+ &copies,
605+ );
606+ }
607+ lane.end()?;
608+ lane.submit()?;
609+ let data = unsafe { std::slice::from_raw_parts(ptr as *const u8, size as usize) };
610+ let split = luma as usize;
611+ let planes = (data[..split].to_vec(), data[split..].to_vec());
612+ unsafe { d.unmap_memory(memory) };
613+ Ok(planes)
614+ })();
615+ unsafe {
616+ d.destroy_buffer(buffer, None);
617+ d.free_memory(memory, None);
618+ }
619+ out
620+}
shims/vk-video-ffi/src/h264_decode.rsmodified+9 -0
@@ -461,6 +461,15 @@ impl H264DecodeSession {
461461 self.dec.read_nv12(width, height)
462462 }
463463
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+
464473 /// 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.
465474 pub fn read_output_rgb(
466475 &mut self,
shims/vk-video-ffi/src/h265_decode.rsmodified+9 -0
@@ -698,6 +698,15 @@ impl H265DecodeSession {
698698 self.dec.read_nv12(width, height)
699699 }
700700
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+
701710 /// 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.
702711 pub fn read_output_rgb(
703712 &mut self,
shims/vk-video-ffi/src/lib.rsmodified+73 -26
@@ -27,7 +27,7 @@ pub use av1_decode::{
2727 };
2828 pub use av1_encode::{Av1EncodeConfig, Av1EncodeSession, Av1Picture, Av1Ref};
2929 #[cfg(target_os = "linux")]
30-pub use dmabuf::DmaBuf;
30+pub use dmabuf::{DmaBuf, DmaBufExport, DmaBufPlane, read_dmabuf};
3131 pub use vp9_decode::{
3232 Vp9ColorConfig, Vp9DecodeConfig, Vp9DecodePicture, Vp9DecodeSession, Vp9FrameHeader,
3333 Vp9InterpolationFilter, Vp9LoopFilter, Vp9Segmentation,
@@ -120,13 +120,32 @@ pub enum Direction {
120120 Decode,
121121 }
122122
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.
124141 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
125142 pub struct CodecCaps {
126143 /// Codec.
127144 pub codec: Codec,
128145 /// Direction.
129146 pub direction: Direction,
147+ /// Profile.
148+ pub profile: CodecProfile,
130149 /// Maximum coded width.
131150 pub max_width: u32,
132151 /// Maximum coded height.
@@ -324,23 +343,34 @@ impl Gpu {
324343 self.inner.graphics
325344 }
326345
327- /// Capabilities of every codec and direction the device supports.
346+ /// Capabilities of every codec, profile and direction the device supports.
328347 pub fn caps(&self) -> Vec<CodecCaps> {
329348 [
330- (Codec::H264, Direction::Encode),
331- (Codec::H264, Direction::Decode),
332- (Codec::H265, Direction::Encode),
333- (Codec::H265, Direction::Decode),
334- (Codec::Av1, Direction::Encode),
335- (Codec::Av1, Direction::Decode),
336- (Codec::Vp9, Direction::Decode),
349+ (Codec::H264, Direction::Encode, CodecProfile::H264High),
350+ (Codec::H264, Direction::Decode, CodecProfile::H264High),
351+ (Codec::H265, Direction::Encode, CodecProfile::H265Main),
352+ (Codec::H265, Direction::Encode, CodecProfile::H265Main10),
353+ (Codec::H265, Direction::Decode, CodecProfile::H265Main),
354+ (Codec::H265, Direction::Decode, CodecProfile::H265Main10),
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),
337360 ]
338361 .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+ })
340365 .collect()
341366 }
342367
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> {
344374 let (operation, extension) = match (codec, direction) {
345375 (Codec::H264, Direction::Encode) => (
346376 vk::VideoCodecOperationFlagsKHR::ENCODE_H264,
@@ -377,21 +407,32 @@ impl Gpu {
377407 if !self.inner.device.extensions().contains(&extension.name) {
378408 return Err(Error::Unsupported(format!("{codec:?} {direction:?}")));
379409 }
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| {
381417 vk::VideoProfileInfoKHR::builder()
382418 .video_codec_operation(operation)
383419 .chroma_subsampling(vk::VideoChromaSubsamplingFlagsKHR::_420)
384- .luma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8)
385- .chroma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8)
420+ .luma_bit_depth(depth)
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,
386426 };
387427 match (codec, direction) {
388428 (Codec::H264, Direction::Encode) => {
389429 let mut h = vk::VideoEncodeH264ProfileInfoKHR::builder()
390430 .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);
392432 self.query(
393433 codec,
394434 direction,
435+ profile,
395436 &p,
396437 &mut vk::VideoEncodeH264CapabilitiesKHR::builder(),
397438 )
@@ -400,32 +441,33 @@ impl Gpu {
400441 let mut h = vk::VideoDecodeH264ProfileInfoKHR::builder()
401442 .std_profile_idc(vk::video::STD_VIDEO_H264_PROFILE_IDC_HIGH)
402443 .picture_layout(vk::VideoDecodeH264PictureLayoutFlagsKHR::PROGRESSIVE);
403- let p = profile(operation).push_next(&mut h);
444+ let p = base(operation).push_next(&mut h);
404445 self.query(
405446 codec,
406447 direction,
448+ profile,
407449 &p,
408450 &mut vk::VideoDecodeH264CapabilitiesKHR::builder(),
409451 )
410452 }
411453 (Codec::H265, Direction::Encode) => {
412- let mut h = vk::VideoEncodeH265ProfileInfoKHR::builder()
413- .std_profile_idc(vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN);
414- let p = profile(operation).push_next(&mut h);
454+ let mut h = vk::VideoEncodeH265ProfileInfoKHR::builder().std_profile_idc(h265_idc);
455+ let p = base(operation).push_next(&mut h);
415456 self.query(
416457 codec,
417458 direction,
459+ profile,
418460 &p,
419461 &mut vk::VideoEncodeH265CapabilitiesKHR::builder(),
420462 )
421463 }
422464 (Codec::H265, Direction::Decode) => {
423- let mut h = vk::VideoDecodeH265ProfileInfoKHR::builder()
424- .std_profile_idc(vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN);
425- let p = profile(operation).push_next(&mut h);
465+ let mut h = vk::VideoDecodeH265ProfileInfoKHR::builder().std_profile_idc(h265_idc);
466+ let p = base(operation).push_next(&mut h);
426467 self.query(
427468 codec,
428469 direction,
470+ profile,
429471 &p,
430472 &mut vk::VideoDecodeH265CapabilitiesKHR::builder(),
431473 )
@@ -433,10 +475,11 @@ impl Gpu {
433475 (Codec::Av1, Direction::Encode) => {
434476 let mut h = vk::VideoEncodeAV1ProfileInfoKHR::builder()
435477 .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);
437479 self.query(
438480 codec,
439481 direction,
482+ profile,
440483 &p,
441484 &mut vk::VideoEncodeAV1CapabilitiesKHR::builder(),
442485 )
@@ -444,10 +487,11 @@ impl Gpu {
444487 (Codec::Av1, Direction::Decode) => {
445488 let mut h = vk::VideoDecodeAV1ProfileInfoKHR::builder()
446489 .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);
448491 self.query(
449492 codec,
450493 direction,
494+ profile,
451495 &p,
452496 &mut vk::VideoDecodeAV1CapabilitiesKHR::builder(),
453497 )
@@ -455,10 +499,11 @@ impl Gpu {
455499 (Codec::Vp9, _) => {
456500 let mut h = vk::VideoDecodeVP9ProfileInfoKHR::builder()
457501 .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);
459503 self.query(
460504 codec,
461505 direction,
506+ profile,
462507 &p,
463508 &mut vk::VideoDecodeVP9CapabilitiesKHR::builder(),
464509 )
@@ -470,6 +515,7 @@ impl Gpu {
470515 &self,
471516 codec: Codec,
472517 direction: Direction,
518+ codec_profile: CodecProfile,
473519 profile: &vk::VideoProfileInfoKHR,
474520 codec_caps: &mut C,
475521 ) -> Result<CodecCaps, Error>
@@ -495,6 +541,7 @@ impl Gpu {
495541 Ok(CodecCaps {
496542 codec,
497543 direction,
544+ profile: codec_profile,
498545 max_width: caps.max_coded_extent.width,
499546 max_height: caps.max_coded_extent.height,
500547 max_dpb_slots: caps.max_dpb_slots,
shims/vk-video-ffi/src/session.rsmodified+25 -0
@@ -1334,6 +1334,31 @@ impl Decoder {
13341334 Ok(self.rgb_out.bytes(d, len)?.to_vec())
13351335 }
13361336
1337+ /// Exports the crop window `(x, y, width, height)` of the last decoded picture as one DMA-BUF of NV12 or P010 planes.
1338+ #[cfg(target_os = "linux")]
1339+ pub(crate) fn export(
1340+ &mut self,
1341+ crop: (u32, u32, u32, u32),
1342+ ) -> Result<crate::dmabuf::DmaBufExport, Error> {
1343+ let (x, y, width, height) = crop;
1344+ if !self.coded {
1345+ return Err(Error::Invalid("nothing decoded".into()));
1346+ }
1347+ if width == 0
1348+ || height == 0
1349+ || width % 2 != 0
1350+ || height % 2 != 0
1351+ || x % 2 != 0
1352+ || y % 2 != 0
1353+ || x + width > self.max_extent.width
1354+ || y + height > self.max_extent.height
1355+ {
1356+ return Err(Error::Invalid("DMA-BUF export size".into()));
1357+ }
1358+ let gpu = self.vs.gpu.clone();
1359+ crate::dmabuf::export(&gpu, &self.graphics, self.output.image, self.vs.format, crop)
1360+ }
1361+
13371362 fn copy_to_buffer(
13381363 &self,
13391364 d: &Device,
shims/vk-video-ffi/src/vp9_decode.rsmodified+9 -0
@@ -417,6 +417,15 @@ impl Vp9DecodeSession {
417417 self.dec.read_nv12(width, height)
418418 }
419419
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+
420429 /// 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.
421430 pub fn read_output_rgb(
422431 &mut self,