forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'worktree-agent-af775a1ed6a046ae4'

Browse files at this commit

8352fa1d201b85fa8ede43cc6268ec5163ed00b3Ahmet Kaan GümüşParent: fd663bdcad917b
crates/ec-hw/examples/hw_decode.rsmodified+67 -17
@@ -1,4 +1,5 @@
11 //! Decodes ffmpeg libx264, libx265, SVT-AV1 and libaom AV1 streams, plus our own Vulkan AV1 encoder's, through HwDecoder and compares luma with ffmpeg's decode, frame by frame.
2+//! The 10-bit H.265 and AV1 streams run on Vulkan and are compared with the VA-API decode of the same stream.
23 //!
34 //! ```text
45 //! cargo run -p ec-hw --example hw_decode -- <scratch dir>
@@ -103,34 +104,83 @@ fn main() {
103104 for case in CASES {
104105 run(&dir, case);
105106 }
106- ten_bit_falls_back(&dir);
107+ ten_bit(&dir);
107108 own_av1(&dir);
108109 }
109110
110-fn ten_bit_falls_back(dir: &std::path::Path) {
111- let path = dir.join("ten.hevc");
112- let p = path.to_str().expect("utf-8 path");
113- ffmpeg(&["-f", "lavfi", "-i", "testsrc2=size=640x360:rate=30", "-frames:v", "20", "-pix_fmt", "yuv420p10le", "-c:v", "libx265", "-x265-params", "log-level=error", p]);
114- let data = std::fs::read(&path).expect("read 10-bit stream");
115- let mut dec = ec_hw::HwDecoder::open(ec_hw::Codec::H265).expect("open");
116- let opened = dec.backend();
111+fn ten_bit(dir: &Path) {
112+ let hevc = dir.join("ten.hevc");
113+ let ivf = dir.join("ten_av1.ivf");
114+ ffmpeg(&["-f", "lavfi", "-i", "testsrc2=size=640x360:rate=30", "-frames:v", "20", "-pix_fmt", "yuv420p10le", "-c:v", "libx265", "-x265-params", "log-level=error", hevc.to_str().expect("utf-8 path")]);
115+ ffmpeg(&["-f", "lavfi", "-i", "testsrc2=size=640x360:rate=30", "-frames:v", "30", "-pix_fmt", "yuv420p10le", "-c:v", "libsvtav1", "-f", "ivf", ivf.to_str().expect("utf-8 path")]);
116+ let hevc_data = fs::read(&hevc).expect("read 10-bit H.265");
117+ ten_bit_case("ten.hevc", Codec::H265, &nal_units(&hevc_data));
118+ let av1_data = fs::read(&ivf).expect("read 10-bit AV1");
119+ ten_bit_case("ten_av1.ivf", Codec::Av1, &ivf_units(&av1_data));
120+}
121+
122+fn nal_units(data: &[u8]) -> Vec<&[u8]> {
117123 let starts: Vec<usize> = (0..data.len().saturating_sub(3))
118124 .filter(|&i| data[i..i + 3] == [0, 0, 1])
119125 .map(|i| if i > 0 && data[i - 1] == 0 { i - 1 } else { i })
120126 .chain([data.len()])
121127 .collect();
122- let mut n = 0;
123- for w in starts.windows(2) {
124- dec.decode(&data[w[0]..w[1]], 0).expect("decode 10-bit");
125- while dec.next_frame().expect("frame").is_some() {
126- n += 1;
128+ starts.windows(2).map(|w| &data[w[0]..w[1]]).collect()
129+}
130+
131+fn ten_bit_case(label: &str, codec: Codec, units: &[&[u8]]) {
132+ let mut decoder = HwDecoder::open(codec).expect("open decoder");
133+ let backend = decoder.backend();
134+ assert_eq!(backend, Backend::Vk, "{label}: 10-bit must decode on Vulkan");
135+ let mut ours: Vec<I420> = Vec::new();
136+ for (pts, unit) in units.iter().enumerate() {
137+ decoder.decode(unit, pts as i64).expect("decode 10-bit");
138+ drain(&mut decoder, &mut ours);
139+ }
140+ decoder.flush().expect("flush");
141+ drain(&mut decoder, &mut ours);
142+ let theirs = va_frames(codec, units);
143+ compare_i420(label, codec, backend, &ours, &theirs);
144+}
145+
146+fn va_frames(codec: Codec, units: &[&[u8]]) -> Vec<I420> {
147+ let display = ec_va::open().expect("VA display");
148+ let mut decoder = ec_hw::Decoder::new(&display, codec).expect("VA decoder");
149+ let mut out = Vec::new();
150+ for (pts, unit) in units.iter().enumerate() {
151+ decoder.decode(unit, pts as i64).expect("VA decode");
152+ while let Some(frame) = decoder.next_frame() {
153+ out.push(frame.to_i420().expect("VA readback"));
127154 }
128155 }
129- dec.flush().expect("flush");
130- while dec.next_frame().expect("frame").is_some() {
131- n += 1;
156+ decoder.flush().expect("VA flush");
157+ while let Some(frame) = decoder.next_frame() {
158+ out.push(frame.to_i420().expect("VA readback"));
132159 }
133- println!("ten.hevc: opened {opened:?}, decoded on {:?}, {n} frames", dec.backend());
160+ out
161+}
162+
163+fn compare_i420(label: &str, codec: Codec, backend: Backend, ours: &[I420], theirs: &[I420]) {
164+ let worst = ours
165+ .iter()
166+ .zip(theirs)
167+ .map(|(a, b)| {
168+ assert_eq!((a.width, a.height), (b.width, b.height), "{label}: frame size");
169+ let sum: f64 = a
170+ .y
171+ .iter()
172+ .zip(&b.y)
173+ .map(|(&x, &y)| (x as f64 - y as f64).abs())
174+ .sum();
175+ sum / a.y.len() as f64
176+ })
177+ .fold(0.0f64, f64::max);
178+ println!(
179+ "{label} {codec:?} {backend:?}: decoded {} frames, VA {} frames, max mean |diff| Y {worst:.6}",
180+ ours.len(),
181+ theirs.len(),
182+ );
183+ assert_eq!(ours.len(), theirs.len(), "{label}: frame count");
134184 }
135185
136186 fn ffmpeg(args: &[&str]) {
crates/ec-hw/src/frame.rsmodified+1 -74
@@ -7,6 +7,7 @@ use ec_va::va::{VA_FOURCC_NV12, VA_FOURCC_P010};
77 use ec_va::{Display, Image, PrimeSurface, Surface, SurfaceExt};
88
99 use crate::error::{Error, Result};
10+use crate::picture::{check_plane, fill_i420};
1011 use crate::pool::PooledSurface;
1112
1213 pub use crate::picture::{Colour, I420, I420_16, i420_to_nv12, nv12_to_i420};
@@ -191,62 +192,6 @@ impl std::fmt::Debug for Frame {
191192 }
192193 }
193194
194-/// Copy NV12/P010 planes into `out`, after validating every plane against it.
195-fn fill_i420(
196- out: &mut I420,
197- bit_depth: u8,
198- y_plane: &[u8],
199- y_pitch: usize,
200- uv_plane: &[u8],
201- uv_pitch: usize,
202-) -> Result<()> {
203- let (w, h) = (out.width as usize, out.height as usize);
204- let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
205- let bytes = if bit_depth == 8 { 1 } else { 2 };
206- check_plane("luma", y_plane.len(), y_pitch, h, w * bytes)?;
207- check_plane("chroma", uv_plane.len(), uv_pitch, ch, cw * 2 * bytes)?;
208- let mut row_buf = vec![0u8; uv_pitch.max(y_pitch).max(w * 2)];
209- match bit_depth {
210- 8 => {
211- for row in 0..h {
212- let src = row * y_pitch;
213- out.y[row * w..(row + 1) * w].copy_from_slice(&y_plane[src..src + w]);
214- }
215- for row in 0..ch {
216- let src = row * uv_pitch;
217- let line = &mut row_buf[..cw * 2];
218- line.copy_from_slice(&uv_plane[src..src + cw * 2]);
219- for col in 0..cw {
220- out.u[row * cw + col] = line[col * 2];
221- out.v[row * cw + col] = line[col * 2 + 1];
222- }
223- }
224- }
225- _ => {
226- // P010 keeps the sample in the *high* bits of each u16, so the
227- // 8-bit value is the high byte — a shift by 8, not by 2.
228- for row in 0..h {
229- let src = row * y_pitch;
230- let line = &mut row_buf[..w * 2];
231- line.copy_from_slice(&y_plane[src..src + w * 2]);
232- for col in 0..w {
233- out.y[row * w + col] = line[col * 2 + 1];
234- }
235- }
236- for row in 0..ch {
237- let src = row * uv_pitch;
238- let line = &mut row_buf[..cw * 4];
239- line.copy_from_slice(&uv_plane[src..src + cw * 4]);
240- for col in 0..cw {
241- out.u[row * cw + col] = line[col * 4 + 1];
242- out.v[row * cw + col] = line[col * 4 + 3];
243- }
244- }
245- }
246- }
247- Ok(())
248-}
249-
250195 /// Copy NV12/P010 planes into `out`, after validating every plane against it.
251196 fn fill_i420_16(
252197 out: &mut I420_16,
@@ -328,24 +273,6 @@ fn planes_of<'a>(image: &'a Image<'_>) -> Result<(&'a [u8], usize, &'a [u8], usi
328273 Ok((y_plane, y_pitch, uv_plane, uv_pitch))
329274 }
330275
331-/// Check that `rows` rows of `row_bytes` bytes at `pitch` fit in a plane of
332-/// `len` bytes. A lost or half-initialised GPU context can hand back a short
333-/// or odd mapping; this turns what would be a slice panic into an error.
334-fn check_plane(name: &str, len: usize, pitch: usize, rows: usize, row_bytes: usize) -> Result<()> {
335- if rows == 0 || row_bytes == 0 {
336- return Ok(());
337- }
338- let need = (rows - 1)
339- .checked_mul(pitch)
340- .and_then(|n| n.checked_add(row_bytes));
341- match need {
342- Some(need) if pitch >= row_bytes && need <= len => Ok(()),
343- _ => Err(Error::config(format!(
344- "VA image {name} plane does not cover the frame: {rows} rows x {row_bytes} bytes at pitch {pitch}, mapped {len} bytes"
345- ))),
346- }
347-}
348-
349276 #[cfg(test)]
350277 mod tests {
351278 use super::*;
crates/ec-hw/src/hw.rsmodified+1 -1
@@ -561,7 +561,7 @@ impl HwDecoder {
561561 }
562562 }
563563
564- /// Feed one access unit. A stream Vulkan refuses (e.g. 10-bit) before its first
564+ /// Feed one access unit. A stream Vulkan refuses (an unsupported profile) before its first
565565 /// picture comes out moves to VA-API on Linux, replaying what was fed so far.
566566 pub fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> {
567567 let result = match &mut self.inner {
crates/ec-hw/src/picture.rsmodified+108 -0
@@ -3,6 +3,8 @@
33
44 use ec_core::color::{ColorDescription, ContentLight};
55
6+use crate::error::{Error, Result};
7+
68 /// A stream's colour metadata, resolved from its own headers: VUI tags for the
79 /// primaries/transfer/matrix triplet, and — for HEVC — the two HDR prefix SEI
810 /// messages for the peak the mastering grade and the content itself declared.
@@ -90,6 +92,112 @@ pub fn nv12_to_i420(
9092 out
9193 }
9294
95+pub(crate) fn semi_planar_to_i420(
96+ bit_depth: u8,
97+ y: &[u8],
98+ uv: &[u8],
99+ pitch: usize,
100+ origin: (usize, usize),
101+ size: (u32, u32),
102+) -> Result<I420> {
103+ let bytes = if bit_depth == 8 { 1 } else { 2 };
104+ let pitch = pitch * bytes;
105+ let (x, top) = (origin.0 * bytes, origin.1);
106+ let y = y.get(top * pitch + x..).unwrap_or(&[]);
107+ let uv = uv.get((top / 2) * pitch + x..).unwrap_or(&[]);
108+ let (width, height) = size;
109+ let (cw, ch) = ((width as usize).div_ceil(2), (height as usize).div_ceil(2));
110+ let mut out = I420 {
111+ y: vec![0; width as usize * height as usize],
112+ u: vec![0; cw * ch],
113+ v: vec![0; cw * ch],
114+ width,
115+ height,
116+ };
117+ fill_i420(&mut out, bit_depth, y, pitch, uv, pitch)?;
118+ Ok(out)
119+}
120+
121+/// Copy NV12/P010 planes into `out`, after validating every plane against it.
122+pub(crate) fn fill_i420(
123+ out: &mut I420,
124+ bit_depth: u8,
125+ y_plane: &[u8],
126+ y_pitch: usize,
127+ uv_plane: &[u8],
128+ uv_pitch: usize,
129+) -> Result<()> {
130+ let (w, h) = (out.width as usize, out.height as usize);
131+ let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
132+ let bytes = if bit_depth == 8 { 1 } else { 2 };
133+ check_plane("luma", y_plane.len(), y_pitch, h, w * bytes)?;
134+ check_plane("chroma", uv_plane.len(), uv_pitch, ch, cw * 2 * bytes)?;
135+ let mut row_buf = vec![0u8; uv_pitch.max(y_pitch).max(w * 2)];
136+ match bit_depth {
137+ 8 => {
138+ for row in 0..h {
139+ let src = row * y_pitch;
140+ out.y[row * w..(row + 1) * w].copy_from_slice(&y_plane[src..src + w]);
141+ }
142+ for row in 0..ch {
143+ let src = row * uv_pitch;
144+ let line = &mut row_buf[..cw * 2];
145+ line.copy_from_slice(&uv_plane[src..src + cw * 2]);
146+ for col in 0..cw {
147+ out.u[row * cw + col] = line[col * 2];
148+ out.v[row * cw + col] = line[col * 2 + 1];
149+ }
150+ }
151+ }
152+ _ => {
153+ // P010 keeps the sample in the *high* bits of each u16, so the
154+ // 8-bit value is the high byte — a shift by 8, not by 2.
155+ for row in 0..h {
156+ let src = row * y_pitch;
157+ let line = &mut row_buf[..w * 2];
158+ line.copy_from_slice(&y_plane[src..src + w * 2]);
159+ for col in 0..w {
160+ out.y[row * w + col] = line[col * 2 + 1];
161+ }
162+ }
163+ for row in 0..ch {
164+ let src = row * uv_pitch;
165+ let line = &mut row_buf[..cw * 4];
166+ line.copy_from_slice(&uv_plane[src..src + cw * 4]);
167+ for col in 0..cw {
168+ out.u[row * cw + col] = line[col * 4 + 1];
169+ out.v[row * cw + col] = line[col * 4 + 3];
170+ }
171+ }
172+ }
173+ }
174+ Ok(())
175+}
176+
177+/// Check that `rows` rows of `row_bytes` bytes at `pitch` fit in a plane of
178+/// `len` bytes. A lost or half-initialised GPU context can hand back a short
179+/// or odd mapping; this turns what would be a slice panic into an error.
180+pub(crate) fn check_plane(
181+ name: &str,
182+ len: usize,
183+ pitch: usize,
184+ rows: usize,
185+ row_bytes: usize,
186+) -> Result<()> {
187+ if rows == 0 || row_bytes == 0 {
188+ return Ok(());
189+ }
190+ let need = (rows - 1)
191+ .checked_mul(pitch)
192+ .and_then(|n| n.checked_add(row_bytes));
193+ match need {
194+ Some(need) if pitch >= row_bytes && need <= len => Ok(()),
195+ _ => Err(Error::config(format!(
196+ "VA image {name} plane does not cover the frame: {rows} rows x {row_bytes} bytes at pitch {pitch}, mapped {len} bytes"
197+ ))),
198+ }
199+}
200+
93201 /// Interleave I420 chroma into an NV12 buffer, for the encoder input path.
94202 pub fn i420_to_nv12(
95203 src: &I420,
crates/ec-hw/src/vkdec265.rsmodified+33 -20
@@ -16,12 +16,13 @@ use crate::hevc_dpb::{
1616 self, Dpb, Mark, is_bla_picture, is_leading_picture, is_rasl_picture, is_reference_picture,
1717 peek_pps_id,
1818 };
19-use crate::picture::{I420, nv12_to_i420};
19+use crate::picture::{I420, semi_planar_to_i420};
2020
2121 const MAX_SLOTS: u32 = 17;
2222
2323 struct Session {
2424 h265: H265DecodeSession,
25+ bit_depth: u8,
2526 max_width: u32,
2627 max_height: u32,
2728 slots: u32,
@@ -205,23 +206,33 @@ impl VkH265Decoder {
205206
206207 fn ensure_session(&mut self, sps: &Sps) -> Result<()> {
207208 if sps.chroma_format_idc != 1
208- || sps.bit_depth_luma_minus8 != 0
209- || sps.bit_depth_chroma_minus8 != 0
209+ || sps.bit_depth_luma_minus8 != sps.bit_depth_chroma_minus8
210+ || !matches!(sps.bit_depth_luma_minus8, 0 | 2)
210211 {
211212 return Err(Error::unsupported(
212213 "Vulkan H.265 decode",
213- "only 8-bit 4:2:0",
214+ "only 8- and 10-bit 4:2:0",
214215 ));
215216 }
217+ let bit_depth = (8 + sps.bit_depth_luma_minus8) as u8;
216218 let slots = (sps.max_dec_pic_buffering_minus1 + 2).min(MAX_SLOTS);
217219 let (w, h) = (
218220 sps.pic_width_in_luma_samples,
219221 sps.pic_height_in_luma_samples,
220222 );
221223 let (max_width, max_height, slots) = match &self.session {
222- Some(s) if w <= s.max_width && h <= s.max_height && slots <= s.slots => return Ok(()),
223- Some(s) => (w.max(s.max_width), h.max(s.max_height), slots.max(s.slots)),
224- None => (w, h, slots),
224+ Some(s)
225+ if s.bit_depth == bit_depth
226+ && w <= s.max_width
227+ && h <= s.max_height
228+ && slots <= s.slots =>
229+ {
230+ return Ok(());
231+ }
232+ Some(s) if s.bit_depth == bit_depth => {
233+ (w.max(s.max_width), h.max(s.max_height), slots.max(s.slots))
234+ }
235+ _ => (w, h, slots),
225236 };
226237 self.current = None;
227238 self.dpb.pictures.clear();
@@ -233,10 +244,12 @@ impl VkH265Decoder {
233244 max_width,
234245 max_height,
235246 max_dpb_slots: slots,
247+ bit_depth,
236248 },
237249 )?;
238250 self.session = Some(Session {
239251 h265,
252+ bit_depth,
240253 max_width,
241254 max_height,
242255 slots,
@@ -328,7 +341,8 @@ impl VkH265Decoder {
328341 sps.pic_height_in_luma_samples,
329342 )?;
330343 if current.output {
331- self.outputs.insert(current.slot, crop(&sps, &y, &uv));
344+ let frame = crop(&sps, &y, &uv)?;
345+ self.outputs.insert(current.slot, frame);
332346 }
333347
334348 self.dpb.pictures.push(hevc_dpb::StoredPicture {
@@ -369,18 +383,17 @@ fn store<T: PartialEq>(slot: &mut Option<T>, value: T) -> bool {
369383 true
370384 }
371385
372-fn crop(sps: &Sps, y: &[u8], uv: &[u8]) -> I420 {
373- let (width, height) = sps.display_size();
374- let pitch = sps.pic_width_in_luma_samples as usize;
375- let left = 2 * sps.conf_win.left as usize;
376- let top = 2 * sps.conf_win.top as usize;
377- nv12_to_i420(
378- &y[top * pitch + left..],
379- pitch,
380- &uv[(top / 2) * pitch + left..],
381- pitch,
382- width as usize,
383- height as usize,
386+fn crop(sps: &Sps, y: &[u8], uv: &[u8]) -> Result<I420> {
387+ semi_planar_to_i420(
388+ (8 + sps.bit_depth_luma_minus8) as u8,
389+ y,
390+ uv,
391+ sps.pic_width_in_luma_samples as usize,
392+ (
393+ 2 * sps.conf_win.left as usize,
394+ 2 * sps.conf_win.top as usize,
395+ ),
396+ sps.display_size(),
384397 )
385398 }
386399
crates/ec-hw/src/vkdec_av1.rsmodified+22 -9
@@ -17,12 +17,13 @@ use ec_vk::{
1717
1818 use crate::av1_refs::RefSlots;
1919 use crate::error::{Error, Result};
20-use crate::picture::{I420, nv12_to_i420};
20+use crate::picture::{I420, semi_planar_to_i420};
2121
2222 const DPB_SLOTS: u32 = NUM_REF_FRAMES as u32 + 1;
2323
2424 struct Session {
2525 av1: Av1DecodeSession,
26+ bit_depth: u8,
2627 width: u32,
2728 height: u32,
2829 sequence: Option<SequenceHeader>,
@@ -161,8 +162,14 @@ impl VkAv1Decoder {
161162 return Ok(());
162163 }
163164 let (y, uv) = session.av1.read_output(width, height)?;
164- let w = width as usize;
165- let decoded = nv12_to_i420(&y, w, &uv, w, w, height as usize);
165+ let decoded = semi_planar_to_i420(
166+ session.bit_depth,
167+ &y,
168+ &uv,
169+ width as usize,
170+ (0, 0),
171+ (width, height),
172+ )?;
166173 let state = Av1RefSlot {
167174 slot: setup_slot,
168175 frame_type: av1_frame_type(header.frame_type),
@@ -187,12 +194,16 @@ impl VkAv1Decoder {
187194 }
188195
189196 fn ensure_session(&mut self, seq: &SequenceHeader, width: u32, height: u32) -> Result<()> {
197+ let bit_depth = seq.color_config.bit_depth;
190198 let mut session = match self.session.take() {
191- Some(s) if width <= s.width && height <= s.height => s,
199+ Some(s) if s.bit_depth == bit_depth && width <= s.width && height <= s.height => s,
192200 old => {
193- let (width, height) = old.map_or((width, height), |s| {
194- (width.max(s.width), height.max(s.height))
195- });
201+ let (width, height) = match &old {
202+ Some(s) if s.bit_depth == bit_depth => {
203+ (width.max(s.width), height.max(s.height))
204+ }
205+ _ => (width, height),
206+ };
196207 self.refs = RefSlots::new();
197208 let av1 = Av1DecodeSession::new(
198209 &self.gpu,
@@ -200,10 +211,12 @@ impl VkAv1Decoder {
200211 max_width: width,
201212 max_height: height,
202213 max_dpb_slots: DPB_SLOTS,
214+ bit_depth,
203215 },
204216 )?;
205217 Session {
206218 av1,
219+ bit_depth,
207220 width,
208221 height,
209222 sequence: None,
@@ -228,14 +241,14 @@ impl VkAv1Decoder {
228241 fn check_supported(seq: &SequenceHeader, header: &FrameHeader) -> Result<()> {
229242 let c = &seq.color_config;
230243 if seq.seq_profile != 0
231- || c.bit_depth != 8
244+ || !matches!(c.bit_depth, 8 | 10)
232245 || c.mono_chrome
233246 || c.subsampling_x != 1
234247 || c.subsampling_y != 1
235248 {
236249 return Err(Error::unsupported(
237250 "Vulkan AV1 decode",
238- "only Main 8-bit 4:2:0",
251+ "only Main 8- and 10-bit 4:2:0",
239252 ));
240253 }
241254 if header.film_grain.apply_grain {
shims/vk-video-ffi/examples/av1_decode_smoke.rsmodified+1 -0
@@ -285,6 +285,7 @@ fn main() {
285285 max_width: w,
286286 max_height: h,
287287 max_dpb_slots: 9,
288+ bit_depth: 8,
288289 };
289290 let mut session = Av1DecodeSession::new(&gpu, &cfg).expect("decode session");
290291 session
shims/vk-video-ffi/examples/h265_decode_smoke.rsmodified+1 -0
@@ -228,6 +228,7 @@ fn main() {
228228 max_width: w,
229229 max_height: h,
230230 max_dpb_slots: 2,
231+ bit_depth: 8,
231232 };
232233 let mut session = H265DecodeSession::new(&gpu, &cfg).expect("decode session");
233234 session
shims/vk-video-ffi/src/av1_decode.rsmodified+23 -12
@@ -4,7 +4,8 @@ use vulkanalia::prelude::v1_3::*;
44 use vulkanalia::vk::KhrVideoQueueExtensionDeviceCommands;
55
66 use crate::session::{
7- Decoder, VideoSession, align, align_u64, picture_resource, video_caps, vk, zeroed,
7+ Decoder, VideoSession, align, align_u64, component_bit_depth, picture_resource, video_caps, vk,
8+ zeroed,
89 };
910 use crate::{Error, Gpu};
1011
@@ -17,6 +18,8 @@ pub struct Av1DecodeConfig {
1718 pub max_height: u32,
1819 /// DPB slots, including the slot the picture is decoded into.
1920 pub max_dpb_slots: u32,
21+ /// Luma and chroma bit depth: 8 or 10.
22+ pub bit_depth: u8,
2023 }
2124
2225 /// Frame type, values as in the spec and `StdVideoAV1FrameType`.
@@ -471,13 +474,14 @@ struct Profile {
471474 }
472475
473476 impl Profile {
474- fn new() -> Box<Self> {
477+ fn new(bit_depth: u8) -> Box<Self> {
478+ let component = component_bit_depth(bit_depth);
475479 let mut p = Box::new(Profile {
476480 info: vk::VideoProfileInfoKHR::builder()
477481 .video_codec_operation(vk::VideoCodecOperationFlagsKHR::DECODE_AV1)
478482 .chroma_subsampling(vk::VideoChromaSubsamplingFlagsKHR::_420)
479- .luma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8)
480- .chroma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8)
483+ .luma_bit_depth(component)
484+ .chroma_bit_depth(component)
481485 .build(),
482486 av1: vk::VideoDecodeAV1ProfileInfoKHR::builder()
483487 .std_profile(vk::video::STD_VIDEO_AV1_PROFILE_MAIN)
@@ -489,10 +493,11 @@ impl Profile {
489493 }
490494 }
491495
492-/// An AV1 Main 8-bit 4:2:0 Vulkan Video decode session: NV12 DPB images per slot and a separate NV12 output image.
496+/// An AV1 Main 8- or 10-bit 4:2:0 Vulkan Video decode session: DPB images per slot and a separate output image.
493497 pub struct Av1DecodeSession {
494498 dec: Decoder,
495499 sequence: Option<Av1SequenceHeader>,
500+ bit_depth: u8,
496501 }
497502
498503 impl Av1DecodeSession {
@@ -503,6 +508,9 @@ impl Av1DecodeSession {
503508 "decode size or DPB slot count is zero".into(),
504509 ));
505510 }
511+ if !matches!(cfg.bit_depth, 8 | 10) {
512+ return Err(Error::Invalid("bit depth is not 8 or 10".into()));
513+ }
506514 let family = gpu
507515 .decode_family()
508516 .ok_or_else(|| Error::Unsupported("AV1 decode queue family".into()))?;
@@ -518,7 +526,7 @@ impl Av1DecodeSession {
518526 }
519527 let width = align(cfg.max_width, 16);
520528 let height = align(cfg.max_height, 16);
521- let profile = Profile::new();
529+ let profile = Profile::new(cfg.bit_depth);
522530 let caps = query_caps(gpu, &profile.info)?;
523531 if width > caps.max_extent.width
524532 || height > caps.max_extent.height
@@ -555,6 +563,7 @@ impl Av1DecodeSession {
555563 Ok(Av1DecodeSession {
556564 dec,
557565 sequence: None,
566+ bit_depth: cfg.bit_depth,
558567 })
559568 }
560569
@@ -562,14 +571,15 @@ impl Av1DecodeSession {
562571 pub fn set_sequence_header(&mut self, seq: &Av1SequenceHeader) -> Result<(), Error> {
563572 let c = &seq.color_config;
564573 if seq.seq_profile != 0
565- || c.bit_depth != 8
574+ || c.bit_depth != self.bit_depth
566575 || c.mono_chrome
567576 || c.subsampling_x != 1
568577 || c.subsampling_y != 1
569578 {
570- return Err(Error::Unsupported(
571- "AV1 sequence other than Main 8-bit 4:2:0".into(),
572- ));
579+ return Err(Error::Unsupported(format!(
580+ "AV1 sequence other than Main {}-bit 4:2:0",
581+ self.bit_depth
582+ )));
573583 }
574584 let gpu = self.dec.vs.gpu.clone();
575585 let d = gpu.device();
@@ -842,7 +852,7 @@ impl Av1DecodeSession {
842852 self.dec.run(&begin, &decode)
843853 }
844854
845- /// Copies the top-left width x height of the last decoded picture out as NV12 planes (Y, interleaved UV).
855+ /// Copies the top-left width x height of the last decoded picture out as NV12 or P010 planes (Y, interleaved UV).
846856 pub fn read_output(&mut self, width: u32, height: u32) -> Result<(Vec<u8>, Vec<u8>), Error> {
847857 self.dec.read_nv12(width, height)
848858 }
@@ -854,7 +864,8 @@ fn query_caps(gpu: &Gpu, profile: &vk::VideoProfileInfoKHR) -> Result<Caps, Erro
854864 let mut caps = vk::VideoCapabilitiesKHR::builder()
855865 .push_next(&mut av1)
856866 .push_next(&mut decode);
857- video_caps(gpu, profile, &mut caps)?;
867+ video_caps(gpu, profile, &mut caps)
868+ .map_err(|_| Error::Unsupported("AV1 decode profile".into()))?;
858869 let caps = caps.build();
859870 let decode = decode.build();
860871 Ok(Caps {
shims/vk-video-ffi/src/h265_decode.rsmodified+30 -11
@@ -4,7 +4,8 @@ use vulkanalia::prelude::v1_3::*;
44 use vulkanalia::vk::KhrVideoQueueExtensionDeviceCommands;
55
66 use crate::session::{
7- Decoder, VideoSession, align, align_u64, picture_resource, video_caps, vk, zeroed,
7+ Decoder, VideoSession, align, align_u64, component_bit_depth, picture_resource, video_caps, vk,
8+ zeroed,
89 };
910 use crate::{Error, Gpu};
1011
@@ -17,6 +18,8 @@ pub struct H265DecodeConfig {
1718 pub max_height: u32,
1819 /// DPB slots, including the slot the picture is decoded into.
1920 pub max_dpb_slots: u32,
21+ /// Luma and chroma bit depth: 8 or 10.
22+ pub bit_depth: u8,
2023 }
2124
2225 /// Profile, tier and level of a parameter set.
@@ -321,16 +324,22 @@ struct Profile {
321324 }
322325
323326 impl Profile {
324- fn new() -> Box<Self> {
327+ fn new(bit_depth: u8) -> Box<Self> {
328+ let component = component_bit_depth(bit_depth);
329+ let profile_idc = if bit_depth == 10 {
330+ vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN_10
331+ } else {
332+ vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN
333+ };
325334 let mut p = Box::new(Profile {
326335 info: vk::VideoProfileInfoKHR::builder()
327336 .video_codec_operation(vk::VideoCodecOperationFlagsKHR::DECODE_H265)
328337 .chroma_subsampling(vk::VideoChromaSubsamplingFlagsKHR::_420)
329- .luma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8)
330- .chroma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8)
338+ .luma_bit_depth(component)
339+ .chroma_bit_depth(component)
331340 .build(),
332341 h265: vk::VideoDecodeH265ProfileInfoKHR::builder()
333- .std_profile_idc(vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN)
342+ .std_profile_idc(profile_idc)
334343 .build(),
335344 });
336345 p.info.next = &p.h265 as *const _ as *const c_void;
@@ -342,6 +351,7 @@ impl Profile {
342351 pub struct H265DecodeSession {
343352 dec: Decoder,
344353 sps: Vec<H265Sps>,
354+ bit_depth: u8,
345355 }
346356
347357 impl H265DecodeSession {
@@ -352,6 +362,9 @@ impl H265DecodeSession {
352362 "decode size or DPB slot count is zero".into(),
353363 ));
354364 }
365+ if !matches!(cfg.bit_depth, 8 | 10) {
366+ return Err(Error::Invalid("bit depth is not 8 or 10".into()));
367+ }
355368 let family = gpu
356369 .decode_family()
357370 .ok_or_else(|| Error::Unsupported("H.265 decode queue family".into()))?;
@@ -367,7 +380,7 @@ impl H265DecodeSession {
367380 }
368381 let width = align(cfg.max_width, 16);
369382 let height = align(cfg.max_height, 16);
370- let profile = Profile::new();
383+ let profile = Profile::new(cfg.bit_depth);
371384 let caps = query_caps(gpu, &profile.info)?;
372385 if width > caps.max_extent.width
373386 || height > caps.max_extent.height
@@ -404,6 +417,7 @@ impl H265DecodeSession {
404417 Ok(H265DecodeSession {
405418 dec,
406419 sps: Vec::new(),
420+ bit_depth: cfg.bit_depth,
407421 })
408422 }
409423
@@ -414,12 +428,16 @@ impl H265DecodeSession {
414428 sps: &[H265Sps],
415429 pps: &[H265Pps],
416430 ) -> Result<(), Error> {
431+ let minus8 = self.bit_depth - 8;
417432 if sps.iter().any(|s| {
418433 s.chroma_format_idc != 1
419- || s.bit_depth_luma_minus8 != 0
420- || s.bit_depth_chroma_minus8 != 0
434+ || s.bit_depth_luma_minus8 != minus8
435+ || s.bit_depth_chroma_minus8 != minus8
421436 }) {
422- return Err(Error::Unsupported("H.265 decode beyond 8-bit 4:2:0".into()));
437+ return Err(Error::Unsupported(format!(
438+ "H.265 decode other than {}-bit 4:2:0",
439+ self.bit_depth
440+ )));
423441 }
424442 let gpu = self.dec.vs.gpu.clone();
425443 let d = gpu.device();
@@ -675,7 +693,7 @@ impl H265DecodeSession {
675693 self.dec.run(&begin, &decode)
676694 }
677695
678- /// Copies the top-left width x height of the last decoded picture out as NV12 planes (Y, interleaved UV).
696+ /// Copies the top-left width x height of the last decoded picture out as NV12 or P010 planes (Y, interleaved UV).
679697 pub fn read_output(&mut self, width: u32, height: u32) -> Result<(Vec<u8>, Vec<u8>), Error> {
680698 self.dec.read_nv12(width, height)
681699 }
@@ -687,7 +705,8 @@ fn query_caps(gpu: &Gpu, profile: &vk::VideoProfileInfoKHR) -> Result<Caps, Erro
687705 let mut caps = vk::VideoCapabilitiesKHR::builder()
688706 .push_next(&mut h265)
689707 .push_next(&mut decode);
690- video_caps(gpu, profile, &mut caps)?;
708+ video_caps(gpu, profile, &mut caps)
709+ .map_err(|_| Error::Unsupported("H.265 decode profile".into()))?;
691710 let caps = caps.build();
692711 let decode = decode.build();
693712 Ok(Caps {
shims/vk-video-ffi/src/session.rsmodified+30 -8
@@ -8,6 +8,7 @@ use crate::rgb_convert::{Input, RgbConverter};
88 use crate::{Error, Gpu, RateControl};
99
1010 pub(crate) const NV12: vk::Format = vk::Format::G8_B8R8_2PLANE_420_UNORM;
11+pub(crate) const P010: vk::Format = vk::Format::G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16;
1112 pub(crate) const DPB_SLOTS: usize = 2;
1213 pub(crate) const PLANE_0: vk::ImageAspectFlags = vk::ImageAspectFlags::PLANE_0;
1314 pub(crate) const PLANE_1: vk::ImageAspectFlags = vk::ImageAspectFlags::PLANE_1;
@@ -24,6 +25,18 @@ pub(crate) fn zeroed<T>() -> T {
2425 unsafe { std::mem::zeroed() }
2526 }
2627
28+pub(crate) fn bytes_per_sample(format: vk::Format) -> usize {
29+ if format == P010 { 2 } else { 1 }
30+}
31+
32+pub(crate) fn component_bit_depth(bit_depth: u8) -> vk::VideoComponentBitDepthFlagsKHR {
33+ if bit_depth == 10 {
34+ vk::VideoComponentBitDepthFlagsKHR::_10
35+ } else {
36+ vk::VideoComponentBitDepthFlagsKHR::_8
37+ }
38+}
39+
2740 pub(crate) fn align(value: u32, to: u32) -> u32 {
2841 value.div_ceil(to) * to
2942 }
@@ -226,6 +239,7 @@ impl Buffer {
226239 pub(crate) struct VideoSession {
227240 pub(crate) gpu: Gpu,
228241 pub(crate) family: u32,
242+ pub(crate) format: vk::Format,
229243 pub(crate) session: vk::VideoSessionKHR,
230244 pub(crate) params: vk::VideoSessionParametersKHR,
231245 memories: Vec<vk::DeviceMemory>,
@@ -241,9 +255,15 @@ impl VideoSession {
241255 max_dpb_slots: u32,
242256 max_active_refs: u32,
243257 ) -> Result<Self, Error> {
258+ let format = if profile.luma_bit_depth == vk::VideoComponentBitDepthFlagsKHR::_10 {
259+ P010
260+ } else {
261+ NV12
262+ };
244263 let mut s = VideoSession {
245264 gpu: gpu.clone(),
246265 family,
266+ format,
247267 session: Default::default(),
248268 params: Default::default(),
249269 memories: Vec::new(),
@@ -252,9 +272,9 @@ impl VideoSession {
252272 let info = vk::VideoSessionCreateInfoKHR::builder()
253273 .queue_family_index(family)
254274 .video_profile(profile)
255- .picture_format(NV12)
275+ .picture_format(format)
256276 .max_coded_extent(extent)
257- .reference_picture_format(NV12)
277+ .reference_picture_format(format)
258278 .max_dpb_slots(max_dpb_slots)
259279 .max_active_reference_pictures(max_active_refs)
260280 .std_header_version(std_header_version)
@@ -354,7 +374,7 @@ impl VideoSession {
354374 ) -> Result<Image, Error> {
355375 let info = vk::ImageCreateInfo::builder()
356376 .image_type(vk::ImageType::_2D)
357- .format(NV12)
377+ .format(self.format)
358378 .extent(vk::Extent3D {
359379 width: extent.width,
360380 height: extent.height,
@@ -385,7 +405,7 @@ impl VideoSession {
385405 let view_info = vk::ImageViewCreateInfo::builder()
386406 .image(image)
387407 .view_type(vk::ImageViewType::_2D)
388- .format(NV12)
408+ .format(self.format)
389409 .subresource_range(color_range())
390410 .push_next(&mut usage_info)
391411 .build();
@@ -938,8 +958,9 @@ impl Decoder {
938958 &families,
939959 &mut list,
940960 )?;
961+ let bytes = bytes_per_sample(dec.vs.format) as u64;
941962 let bitstream_size = align_u64(
942- max_extent.width as u64 * max_extent.height as u64 * 3 + 65536,
963+ max_extent.width as u64 * max_extent.height as u64 * 3 * bytes / 2 + 65536,
943964 size_align,
944965 );
945966 dec.bitstream = dec.vs.buffer(
@@ -949,7 +970,7 @@ impl Decoder {
949970 Some(&mut list),
950971 )?;
951972 dec.readback = dec.vs.buffer(
952- max_extent.width as u64 * max_extent.height as u64 * 3 / 2,
973+ max_extent.width as u64 * max_extent.height as u64 * 3 / 2 * bytes,
953974 vk::BufferUsageFlags::TRANSFER_DST,
954975 vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT,
955976 None,
@@ -1006,7 +1027,7 @@ impl Decoder {
10061027 Ok(())
10071028 }
10081029
1009- /// Copies the top-left width x height of the last decoded picture out as NV12 planes (Y, interleaved UV).
1030+ /// Copies the top-left width x height of the last decoded picture out as NV12 or P010 planes (Y, interleaved UV).
10101031 pub(crate) fn read_nv12(
10111032 &mut self,
10121033 width: u32,
@@ -1028,7 +1049,8 @@ impl Decoder {
10281049 let d = gpu.device();
10291050 let cb = self.graphics.cb;
10301051 let image = self.output.image;
1031- let luma = width as usize * height as usize;
1052+ let bytes = bytes_per_sample(self.vs.format);
1053+ let luma = width as usize * height as usize * bytes;
10321054 let copies = [
10331055 copy_region(0, PLANE_0, width, height),
10341056 copy_region(luma as u64, PLANE_1, width / 2, height / 2),