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;
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+172 -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,174 @@ 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.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
111 }282 }
112 283
113 fn vp9_cases(dir: &Path) {284 fn vp9_cases(dir: &Path) {
crates/ec-hw/src/hw.rsmodified+156 -38
@@ -11,7 +11,7 @@ use std::cell::RefCell;
11 use crate::error::{Error, Result};11 use crate::error::{Error, Result};
12 use crate::picture::{Decoded, I420, I420_16, RgbPicture};12 use crate::picture::{Decoded, I420, I420_16, RgbPicture};
13 #[cfg(target_os = "linux")]13 #[cfg(target_os = "linux")]
14-use crate::picture::{rgb_size, yuv_to_rgb};14+use crate::picture::{DmaBufPicture, DmaBufPlane, i420_to_rgb};
15 #[cfg(target_os = "linux")]15 #[cfg(target_os = "linux")]
16 use ec_core::color::{ColorDescription, Matrix, Tags};16 use ec_core::color::{ColorDescription, Matrix, Tags};
17 use crate::types::{17 use crate::types::{
@@ -45,11 +45,30 @@ pub enum Direction {
45 Decode,45 Decode,
46 }46 }
47 47
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.
49 #[derive(Debug, Clone, Copy, PartialEq, Eq)]66 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
50 pub struct Capability {67 pub struct Capability {
51 /// Codec.68 /// Codec.
52 pub codec: Codec,69 pub codec: Codec,
70+ /// Profile.
71+ pub profile: CodecProfile,
53 /// Direction.72 /// Direction.
54 pub direction: Direction,73 pub direction: Direction,
55 /// Largest width in luma samples.74 /// Largest width in luma samples.
@@ -124,6 +143,7 @@ pub fn capabilities() -> Vec<Capability> {
124 &mut out,143 &mut out,
125 Capability {144 Capability {
126 codec,145 codec,
146+ profile: vk_profile(caps.profile),
127 direction,147 direction,
128 max_width: caps.max_width,148 max_width: caps.max_width,
129 max_height: caps.max_height,149 max_height: caps.max_height,
@@ -140,7 +160,12 @@ pub fn capabilities() -> Vec<Capability> {
140 fn push(out: &mut Vec<Capability>, cap: Capability) {160 fn push(out: &mut Vec<Capability>, cap: Capability) {
141 let known = out161 let known = out
142 .iter()162 .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+ });
144 if !known {169 if !known {
145 out.push(cap);170 out.push(cap);
146 }171 }
@@ -155,9 +180,6 @@ fn va_capabilities(out: &mut Vec<Capability>) {
155 return;180 return;
156 };181 };
157 for entry in &report.entries {182 for entry in &report.entries {
158- let Some(codec) = va_codec(entry.profile) else {
159- continue;
160- };
161 let direction = match entry.entrypoint {183 let direction = match entry.entrypoint {
162 ec_va::Entrypoint::VLD => Direction::Decode,184 ec_va::Entrypoint::VLD => Direction::Decode,
163 ec_va::Entrypoint::EncSlice | ec_va::Entrypoint::EncSliceLP => Direction::Encode,185 ec_va::Entrypoint::EncSlice | ec_va::Entrypoint::EncSliceLP => Direction::Encode,
@@ -167,32 +189,64 @@ fn va_capabilities(out: &mut Vec<Capability>) {
167 Some(s) => (s.max_width.unwrap_or(4096), s.max_height.unwrap_or(4096)),189 Some(s) => (s.max_width.unwrap_or(4096), s.max_height.unwrap_or(4096)),
168 None => (4096, 4096),190 None => (4096, 4096),
169 };191 };
170- push(192+ for profile in va_profiles(entry.profile, entry.rt_formats) {
171- out,193+ push(
172- Capability {194+ out,
173- codec,195+ Capability {
174- direction,196+ codec: profile.codec(),
175- max_width,197+ profile,
176- max_height,198+ direction,
177- backend: Backend::Va,199+ max_width,
178- },200+ max_height,
179- );201+ backend: Backend::Va,
202+ },
203+ );
204+ }
180 }205 }
181 }206 }
182 207
183 #[cfg(target_os = "linux")]208 #[cfg(target_os = "linux")]
184-fn va_codec(profile: ec_va::Profile) -> Option<Codec> {209+impl CodecProfile {
185- Some(match profile {210+ fn codec(self) -> Codec {
186- ec_va::Profile::H264Baseline211+ match self {
187- | ec_va::Profile::H264ConstrainedBaseline212+ CodecProfile::H264High => Codec::H264,
188- | ec_va::Profile::H264Main213+ CodecProfile::H265Main | CodecProfile::H265Main10 => Codec::H265,
189- | ec_va::Profile::H264High214+ CodecProfile::Av1Main | CodecProfile::Av1Main10 => Codec::Av1,
190- | ec_va::Profile::H264High10 => Codec::H264,215+ CodecProfile::Vp9Profile0 => Codec::Vp9,
191- ec_va::Profile::HEVCMain | ec_va::Profile::HEVCMain10 => Codec::H265,216+ }
192- ec_va::Profile::VP9Profile0 => Codec::Vp9,217+ }
193- ec_va::Profile::AV1Profile0 => Codec::Av1,218+}
194- _ => return None,219+
195- })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+ }
196 }250 }
197 251
198 /// Byte order of a packed 32-bit RGB pixel; the X or A byte is ignored.252 /// Byte order of a packed 32-bit RGB pixel; the X or A byte is ignored.
@@ -648,6 +702,15 @@ impl VkDecoder {
648 VkDecoder::Vp9(d) => d.flush(),702 VkDecoder::Vp9(d) => d.flush(),
649 }703 }
650 }704 }
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+ }
651 }714 }
652 715
653 enum DecInner {716 enum DecInner {
@@ -672,6 +735,8 @@ pub(crate) enum Mode {
672 I420,735 I420,
673 I420_16,736 I420_16,
674 Rgb(RgbOutput),737 Rgb(RgbOutput),
738+ #[cfg(target_os = "linux")]
739+ DmaBuf,
675 }740 }
676 741
677 /// A hardware decoder on whichever backend opened.742 /// A hardware decoder on whichever backend opened.
@@ -701,6 +766,12 @@ impl HwDecoder {
701 HwDecoder::open_mode(codec, Mode::I420_16)766 HwDecoder::open_mode(codec, Mode::I420_16)
702 }767 }
703 768
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+
704 fn open_mode(codec: Codec, mode: Mode) -> Result<HwDecoder> {775 fn open_mode(codec: Codec, mode: Mode) -> Result<HwDecoder> {
705 let mut reasons = Vec::new();776 let mut reasons = Vec::new();
706 let born_epoch = crate::reset::gpu_reset_epoch();777 let born_epoch = crate::reset::gpu_reset_epoch();
@@ -809,6 +880,21 @@ impl HwDecoder {
809 }880 }
810 }881 }
811 882
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+
812 /// The next picture in display order, as packed RGB with its timestamp. An error on a decoder not opened with [`HwDecoder::open_rgb`].898 /// The next picture in display order, as packed RGB with its timestamp. An error on a decoder not opened with [`HwDecoder::open_rgb`].
813 pub fn next_rgb(&mut self) -> Result<Option<(i64, RgbPicture)>> {899 pub fn next_rgb(&mut self) -> Result<Option<(i64, RgbPicture)>> {
814 if !matches!(self.mode, Mode::Rgb(_)) {900 if !matches!(self.mode, Mode::Rgb(_)) {
@@ -847,6 +933,7 @@ impl HwDecoder {
847 .unwrap_or_else(|| default_matrix(i420.height));933 .unwrap_or_else(|| default_matrix(i420.height));
848 Decoded::Rgb(va_rgb(&i420, output, matrix))934 Decoded::Rgb(va_rgb(&i420, output, matrix))
849 }935 }
936+ Mode::DmaBuf => Decoded::DmaBuf(dmabuf_from_prime(frame.export_prime()?)?),
850 };937 };
851 Ok(Some((frame.timestamp, decoded)))938 Ok(Some((frame.timestamp, decoded)))
852 }939 }
@@ -855,6 +942,16 @@ impl HwDecoder {
855 }942 }
856 }943 }
857 944
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+
858 /// Emit every picture still held for reordering.955 /// Emit every picture still held for reordering.
859 pub fn flush(&mut self) -> Result<()> {956 pub fn flush(&mut self) -> Result<()> {
860 match &mut self.inner {957 match &mut self.inner {
@@ -865,6 +962,32 @@ impl HwDecoder {
865 }962 }
866 }963 }
867 964
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+
868 #[cfg(target_os = "linux")]991 #[cfg(target_os = "linux")]
869 fn default_matrix(height: u32) -> Matrix {992 fn default_matrix(height: u32) -> Matrix {
870 ColorDescription::resolve(Tags::default(), Tags::default(), height).matrix993 ColorDescription::resolve(Tags::default(), Tags::default(), height).matrix
@@ -872,17 +995,12 @@ fn default_matrix(height: u32) -> Matrix {
872 995
873 #[cfg(target_os = "linux")]996 #[cfg(target_os = "linux")]
874 fn va_rgb(frame: &I420, output: RgbOutput, matrix: Matrix) -> RgbPicture {997 fn va_rgb(frame: &I420, output: RgbOutput, matrix: Matrix) -> RgbPicture {
875- let (w, h) = rgb_size(frame.width, frame.height, output.max_width);998+ i420_to_rgb(
876- let data = ec_dsp::rgb::i420_to_packed(999+ frame,
877- &frame.y,1000+ output.max_width,
878- &frame.u,
879- &frame.v,
880- (frame.width as usize, frame.height as usize),
881- (w as usize, h as usize),
882 output.order == RgbOrder::Bgra,1001 output.order == RgbOrder::Bgra,
883- &yuv_to_rgb(matrix),1002+ matrix,
884- );1003+ )
885- RgbPicture::new(data, w, h)
886 }1004 }
887 1005
888 #[cfg(target_os = "linux")]1006 #[cfg(target_os = "linux")]
crates/ec-hw/src/lib.rsmodified+4 -2
@@ -88,13 +88,15 @@ pub use error::{Error, Result};
88 #[cfg(target_os = "linux")]88 #[cfg(target_os = "linux")]
89 pub use hw::DmaBufFrame;89 pub use hw::DmaBufFrame;
90 pub use hw::{90 pub use hw::{
91- Backend, Capability, Direction, HwDecoder, HwEncoder, RgbFrame, RgbOrder, RgbOutput,91+ Backend, Capability, CodecProfile, Direction, HwDecoder, HwEncoder, RgbFrame, RgbOrder,
92- capabilities,92+ RgbOutput, capabilities,
93 };93 };
94 #[cfg(target_os = "linux")]94 #[cfg(target_os = "linux")]
95 pub use frame::Frame;95 pub use frame::Frame;
96 pub use picture::{Colour, I420, I420_16, RgbPicture, i420_to_nv12, nv12_to_i420};96 pub use picture::{Colour, I420, I420_16, RgbPicture, i420_to_nv12, nv12_to_i420};
97 #[cfg(target_os = "linux")]97 #[cfg(target_os = "linux")]
98+pub use picture::{DmaBufPicture, DmaBufPlane};
99+#[cfg(target_os = "linux")]
98 pub use pool::{PooledSurface, SurfacePool};100 pub use pool::{PooledSurface, SurfacePool};
99 pub use reset::{gpu_recently_reset, gpu_reset_epoch, report_gpu_reset};101 pub use reset::{gpu_recently_reset, gpu_reset_epoch, report_gpu_reset};
100 pub use types::{102 pub use types::{
crates/ec-hw/src/picture.rsmodified+109 -1
@@ -58,12 +58,100 @@ impl RgbPicture {
58 }58 }
59 }59 }
60 60
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+
61 /// One decoded picture in the decoder's output form.133 /// One decoded picture in the decoder's output form.
62-#[derive(Debug, Clone, PartialEq, Eq)]134+#[derive(Debug)]
63 pub(crate) enum Decoded {135 pub(crate) enum Decoded {
64 I420(I420),136 I420(I420),
65 I420_16(I420_16),137 I420_16(I420_16),
66 Rgb(RgbPicture),138 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+ }
67 }155 }
68 156
69 /// The YUV to RGB coefficients for a matrix; BT.2020 is taken as BT.709, the nearest integer set here.157 /// 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 {
74 }162 }
75 }163 }
76 164
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+
77 /// Output size of an RGB picture of `width` x `height`: scaled to `max_width` keeping the aspect, height rounded to the nearest even.185 /// 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) {186 pub(crate) fn rgb_size(width: u32, height: u32, max_width: Option<u32>) -> (u32, u32) {
79 match max_width {187 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
@@ -10,12 +10,12 @@ mod h265;
10 pub use av1::{Av1Encoder, Av1EncoderConfig};10 pub use av1::{Av1Encoder, Av1EncoderConfig};
11 pub use h265::{H265Encoder, H265EncoderConfig};11 pub use h265::{H265Encoder, H265EncoderConfig};
12 #[cfg(target_os = "linux")]12 #[cfg(target_os = "linux")]
13-pub use vk_video_ffi::DmaBuf;13+pub use vk_video_ffi::{DmaBuf, DmaBufExport, DmaBufPlane, read_dmabuf};
14 pub use vk_video_ffi::{14 pub use vk_video_ffi::{
15 Av1Cdef, Av1ColorConfig, Av1DecodeConfig, Av1DecodePicture, Av1DecodeSession, Av1DeltaParams,15 Av1Cdef, Av1ColorConfig, Av1DecodeConfig, Av1DecodePicture, Av1DecodeSession, Av1DeltaParams,
16 Av1FrameHeader, Av1FrameType, Av1GlobalMotion, Av1InterpolationFilter, Av1LoopFilter,16 Av1FrameHeader, Av1FrameType, Av1GlobalMotion, Av1InterpolationFilter, Av1LoopFilter,
17 Av1LoopRestoration, Av1Quantization, Av1RefSlot, Av1Restoration, Av1Segmentation,17 Av1LoopRestoration, Av1Quantization, Av1RefSlot, Av1Restoration, Av1Segmentation,
18- Av1SequenceHeader, Av1TileInfo, Av1TimingInfo, Av1TxMode, Av1WarpModel, Codec, Direction,18+ Av1SequenceHeader, Av1TileInfo, Av1TimingInfo, Av1TxMode, Av1WarpModel, Codec, CodecProfile, Direction,
19 Error, Gpu, H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, H264RefSlot,19 Error, Gpu, H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, H264RefSlot,
20 H264Sps, H265DecPicBufMgr, H265DecodeConfig, H265DecodePicture, H265DecodeSession,20 H264Sps, H265DecPicBufMgr, H265DecodeConfig, H265DecodePicture, H265DecodeSession,
21 H265LongTermRefPicSps, H265Pcm, H265Pps, H265ProfileTierLevel, H265RefSlot, H265ScalingLists,21 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+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};
2 3
3 use vulkanalia::prelude::v1_3::*;4 use vulkanalia::prelude::v1_3::*;
4-use vulkanalia::vk::KhrExternalMemoryFdExtensionDeviceCommands;5+use vulkanalia::vk::{
6+ ExtImageDrmFormatModifierExtensionDeviceCommands, KhrExternalMemoryFdExtensionDeviceCommands,
7+};
5 8
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;
7 use crate::{Error, Gpu};11 use crate::{Error, Gpu};
8 12
9 /// Single-plane 4-bytes-per-pixel DMA-BUF, linear or DRM format modifier tiled.13 /// Single-plane 4-bytes-per-pixel DMA-BUF, linear or DRM format modifier tiled.
@@ -24,6 +28,35 @@ pub struct DmaBuf<'a> {
24 pub bgr: bool,28 pub bgr: bool,
25 }29 }
26 30
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+
27 pub(crate) fn check(gpu: &Gpu) -> Result<(), Error> {60 pub(crate) fn check(gpu: &Gpu) -> Result<(), Error> {
28 let ext = gpu.device().extensions();61 let ext = gpu.device().extensions();
29 let needed = [62 let needed = [
@@ -146,3 +179,442 @@ fn bind(gpu: &Gpu, image: vk::Image, fd: BorrowedFd) -> Result<vk::DeviceMemory,
146 }179 }
147 bound.map(|_| memory)180 bound.map(|_| memory)
148 }181 }
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 {
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;30+pub use dmabuf::{DmaBuf, DmaBufExport, 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+25 -0
@@ -1334,6 +1334,31 @@ impl Decoder {
1334 Ok(self.rgb_out.bytes(d, len)?.to_vec())1334 Ok(self.rgb_out.bytes(d, len)?.to_vec())
1335 }1335 }
1336 1336
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+
1337 fn copy_to_buffer(1362 fn copy_to_buffer(
1338 &self,1363 &self,
1339 d: &Device,1364 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,