From cad917bb1e7261c5f1c5887a006bea3555ea2b38 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 25 Nov 2026 14:38:30 +0300 Subject: [PATCH] vk decode: 10-bit H.265 Main10 and AV1 on Vulkan (P010 session, bit depth from SPS/sequence header); P010 -> I420 via the shared picture conversion, bit-identical to VA --- crates/ec-hw/examples/hw_decode.rs | 84 +++++++++++--- crates/ec-hw/src/frame.rs | 75 +----------- crates/ec-hw/src/hw.rs | 2 +- crates/ec-hw/src/picture.rs | 108 ++++++++++++++++++ crates/ec-hw/src/vkdec265.rs | 53 +++++---- crates/ec-hw/src/vkdec_av1.rs | 31 +++-- .../vk-video-ffi/examples/av1_decode_smoke.rs | 1 + .../examples/h265_decode_smoke.rs | 1 + shims/vk-video-ffi/src/av1_decode.rs | 35 ++++-- shims/vk-video-ffi/src/h265_decode.rs | 41 +++++-- shims/vk-video-ffi/src/session.rs | 38 ++++-- 11 files changed, 317 insertions(+), 152 deletions(-) diff --git a/crates/ec-hw/examples/hw_decode.rs b/crates/ec-hw/examples/hw_decode.rs index 3de56862..89a930d1 100644 --- a/crates/ec-hw/examples/hw_decode.rs +++ b/crates/ec-hw/examples/hw_decode.rs @@ -1,4 +1,5 @@ //! 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. +//! The 10-bit H.265 and AV1 streams run on Vulkan and are compared with the VA-API decode of the same stream. //! //! ```text //! cargo run -p ec-hw --example hw_decode -- @@ -103,34 +104,83 @@ fn main() { for case in CASES { run(&dir, case); } - ten_bit_falls_back(&dir); + ten_bit(&dir); own_av1(&dir); } -fn ten_bit_falls_back(dir: &std::path::Path) { - let path = dir.join("ten.hevc"); - let p = path.to_str().expect("utf-8 path"); - ffmpeg(&["-f", "lavfi", "-i", "testsrc2=size=640x360:rate=30", "-frames:v", "20", "-pix_fmt", "yuv420p10le", "-c:v", "libx265", "-x265-params", "log-level=error", p]); - let data = std::fs::read(&path).expect("read 10-bit stream"); - let mut dec = ec_hw::HwDecoder::open(ec_hw::Codec::H265).expect("open"); - let opened = dec.backend(); +fn ten_bit(dir: &Path) { + let hevc = dir.join("ten.hevc"); + let ivf = dir.join("ten_av1.ivf"); + 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")]); + 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")]); + let hevc_data = fs::read(&hevc).expect("read 10-bit H.265"); + ten_bit_case("ten.hevc", Codec::H265, &nal_units(&hevc_data)); + let av1_data = fs::read(&ivf).expect("read 10-bit AV1"); + ten_bit_case("ten_av1.ivf", Codec::Av1, &ivf_units(&av1_data)); +} + +fn nal_units(data: &[u8]) -> Vec<&[u8]> { let starts: Vec = (0..data.len().saturating_sub(3)) .filter(|&i| data[i..i + 3] == [0, 0, 1]) .map(|i| if i > 0 && data[i - 1] == 0 { i - 1 } else { i }) .chain([data.len()]) .collect(); - let mut n = 0; - for w in starts.windows(2) { - dec.decode(&data[w[0]..w[1]], 0).expect("decode 10-bit"); - while dec.next_frame().expect("frame").is_some() { - n += 1; + starts.windows(2).map(|w| &data[w[0]..w[1]]).collect() +} + +fn ten_bit_case(label: &str, codec: Codec, units: &[&[u8]]) { + let mut decoder = HwDecoder::open(codec).expect("open decoder"); + let backend = decoder.backend(); + assert_eq!(backend, Backend::Vk, "{label}: 10-bit must decode on Vulkan"); + let mut ours: Vec = Vec::new(); + for (pts, unit) in units.iter().enumerate() { + decoder.decode(unit, pts as i64).expect("decode 10-bit"); + drain(&mut decoder, &mut ours); + } + decoder.flush().expect("flush"); + drain(&mut decoder, &mut ours); + let theirs = va_frames(codec, units); + compare_i420(label, codec, backend, &ours, &theirs); +} + +fn va_frames(codec: Codec, units: &[&[u8]]) -> Vec { + let display = ec_va::open().expect("VA display"); + let mut decoder = ec_hw::Decoder::new(&display, codec).expect("VA decoder"); + let mut out = Vec::new(); + for (pts, unit) in units.iter().enumerate() { + decoder.decode(unit, pts as i64).expect("VA decode"); + while let Some(frame) = decoder.next_frame() { + out.push(frame.to_i420().expect("VA readback")); } } - dec.flush().expect("flush"); - while dec.next_frame().expect("frame").is_some() { - n += 1; + decoder.flush().expect("VA flush"); + while let Some(frame) = decoder.next_frame() { + out.push(frame.to_i420().expect("VA readback")); } - println!("ten.hevc: opened {opened:?}, decoded on {:?}, {n} frames", dec.backend()); + out +} + +fn compare_i420(label: &str, codec: Codec, backend: Backend, ours: &[I420], theirs: &[I420]) { + let worst = ours + .iter() + .zip(theirs) + .map(|(a, b)| { + assert_eq!((a.width, a.height), (b.width, b.height), "{label}: frame size"); + let sum: f64 = a + .y + .iter() + .zip(&b.y) + .map(|(&x, &y)| (x as f64 - y as f64).abs()) + .sum(); + sum / a.y.len() as f64 + }) + .fold(0.0f64, f64::max); + println!( + "{label} {codec:?} {backend:?}: decoded {} frames, VA {} frames, max mean |diff| Y {worst:.6}", + ours.len(), + theirs.len(), + ); + assert_eq!(ours.len(), theirs.len(), "{label}: frame count"); } fn ffmpeg(args: &[&str]) { diff --git a/crates/ec-hw/src/frame.rs b/crates/ec-hw/src/frame.rs index e136b8d7..951e2bb2 100644 --- a/crates/ec-hw/src/frame.rs +++ b/crates/ec-hw/src/frame.rs @@ -7,6 +7,7 @@ use ec_va::va::{VA_FOURCC_NV12, VA_FOURCC_P010}; use ec_va::{Display, Image, PrimeSurface, Surface, SurfaceExt}; use crate::error::{Error, Result}; +use crate::picture::{check_plane, fill_i420}; use crate::pool::PooledSurface; pub use crate::picture::{Colour, I420, I420_16, i420_to_nv12, nv12_to_i420}; @@ -191,62 +192,6 @@ impl std::fmt::Debug for Frame { } } -/// Copy NV12/P010 planes into `out`, after validating every plane against it. -fn fill_i420( - out: &mut I420, - bit_depth: u8, - y_plane: &[u8], - y_pitch: usize, - uv_plane: &[u8], - uv_pitch: usize, -) -> Result<()> { - let (w, h) = (out.width as usize, out.height as usize); - let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); - let bytes = if bit_depth == 8 { 1 } else { 2 }; - check_plane("luma", y_plane.len(), y_pitch, h, w * bytes)?; - check_plane("chroma", uv_plane.len(), uv_pitch, ch, cw * 2 * bytes)?; - let mut row_buf = vec![0u8; uv_pitch.max(y_pitch).max(w * 2)]; - match bit_depth { - 8 => { - for row in 0..h { - let src = row * y_pitch; - out.y[row * w..(row + 1) * w].copy_from_slice(&y_plane[src..src + w]); - } - for row in 0..ch { - let src = row * uv_pitch; - let line = &mut row_buf[..cw * 2]; - line.copy_from_slice(&uv_plane[src..src + cw * 2]); - for col in 0..cw { - out.u[row * cw + col] = line[col * 2]; - out.v[row * cw + col] = line[col * 2 + 1]; - } - } - } - _ => { - // P010 keeps the sample in the *high* bits of each u16, so the - // 8-bit value is the high byte — a shift by 8, not by 2. - for row in 0..h { - let src = row * y_pitch; - let line = &mut row_buf[..w * 2]; - line.copy_from_slice(&y_plane[src..src + w * 2]); - for col in 0..w { - out.y[row * w + col] = line[col * 2 + 1]; - } - } - for row in 0..ch { - let src = row * uv_pitch; - let line = &mut row_buf[..cw * 4]; - line.copy_from_slice(&uv_plane[src..src + cw * 4]); - for col in 0..cw { - out.u[row * cw + col] = line[col * 4 + 1]; - out.v[row * cw + col] = line[col * 4 + 3]; - } - } - } - } - Ok(()) -} - /// Copy NV12/P010 planes into `out`, after validating every plane against it. fn fill_i420_16( out: &mut I420_16, @@ -328,24 +273,6 @@ fn planes_of<'a>(image: &'a Image<'_>) -> Result<(&'a [u8], usize, &'a [u8], usi Ok((y_plane, y_pitch, uv_plane, uv_pitch)) } -/// Check that `rows` rows of `row_bytes` bytes at `pitch` fit in a plane of -/// `len` bytes. A lost or half-initialised GPU context can hand back a short -/// or odd mapping; this turns what would be a slice panic into an error. -fn check_plane(name: &str, len: usize, pitch: usize, rows: usize, row_bytes: usize) -> Result<()> { - if rows == 0 || row_bytes == 0 { - return Ok(()); - } - let need = (rows - 1) - .checked_mul(pitch) - .and_then(|n| n.checked_add(row_bytes)); - match need { - Some(need) if pitch >= row_bytes && need <= len => Ok(()), - _ => Err(Error::config(format!( - "VA image {name} plane does not cover the frame: {rows} rows x {row_bytes} bytes at pitch {pitch}, mapped {len} bytes" - ))), - } -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/ec-hw/src/hw.rs b/crates/ec-hw/src/hw.rs index 66552c9e..c8fb62e9 100644 --- a/crates/ec-hw/src/hw.rs +++ b/crates/ec-hw/src/hw.rs @@ -561,7 +561,7 @@ impl HwDecoder { } } - /// Feed one access unit. A stream Vulkan refuses (e.g. 10-bit) before its first + /// Feed one access unit. A stream Vulkan refuses (an unsupported profile) before its first /// picture comes out moves to VA-API on Linux, replaying what was fed so far. pub fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { let result = match &mut self.inner { diff --git a/crates/ec-hw/src/picture.rs b/crates/ec-hw/src/picture.rs index 167fc98a..cebadec2 100644 --- a/crates/ec-hw/src/picture.rs +++ b/crates/ec-hw/src/picture.rs @@ -3,6 +3,8 @@ use ec_core::color::{ColorDescription, ContentLight}; +use crate::error::{Error, Result}; + /// A stream's colour metadata, resolved from its own headers: VUI tags for the /// primaries/transfer/matrix triplet, and — for HEVC — the two HDR prefix SEI /// messages for the peak the mastering grade and the content itself declared. @@ -90,6 +92,112 @@ pub fn nv12_to_i420( out } +pub(crate) fn semi_planar_to_i420( + bit_depth: u8, + y: &[u8], + uv: &[u8], + pitch: usize, + origin: (usize, usize), + size: (u32, u32), +) -> Result { + let bytes = if bit_depth == 8 { 1 } else { 2 }; + let pitch = pitch * bytes; + let (x, top) = (origin.0 * bytes, origin.1); + let y = y.get(top * pitch + x..).unwrap_or(&[]); + let uv = uv.get((top / 2) * pitch + x..).unwrap_or(&[]); + let (width, height) = size; + let (cw, ch) = ((width as usize).div_ceil(2), (height as usize).div_ceil(2)); + let mut out = I420 { + y: vec![0; width as usize * height as usize], + u: vec![0; cw * ch], + v: vec![0; cw * ch], + width, + height, + }; + fill_i420(&mut out, bit_depth, y, pitch, uv, pitch)?; + Ok(out) +} + +/// Copy NV12/P010 planes into `out`, after validating every plane against it. +pub(crate) fn fill_i420( + out: &mut I420, + bit_depth: u8, + y_plane: &[u8], + y_pitch: usize, + uv_plane: &[u8], + uv_pitch: usize, +) -> Result<()> { + let (w, h) = (out.width as usize, out.height as usize); + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); + let bytes = if bit_depth == 8 { 1 } else { 2 }; + check_plane("luma", y_plane.len(), y_pitch, h, w * bytes)?; + check_plane("chroma", uv_plane.len(), uv_pitch, ch, cw * 2 * bytes)?; + let mut row_buf = vec![0u8; uv_pitch.max(y_pitch).max(w * 2)]; + match bit_depth { + 8 => { + for row in 0..h { + let src = row * y_pitch; + out.y[row * w..(row + 1) * w].copy_from_slice(&y_plane[src..src + w]); + } + for row in 0..ch { + let src = row * uv_pitch; + let line = &mut row_buf[..cw * 2]; + line.copy_from_slice(&uv_plane[src..src + cw * 2]); + for col in 0..cw { + out.u[row * cw + col] = line[col * 2]; + out.v[row * cw + col] = line[col * 2 + 1]; + } + } + } + _ => { + // P010 keeps the sample in the *high* bits of each u16, so the + // 8-bit value is the high byte — a shift by 8, not by 2. + for row in 0..h { + let src = row * y_pitch; + let line = &mut row_buf[..w * 2]; + line.copy_from_slice(&y_plane[src..src + w * 2]); + for col in 0..w { + out.y[row * w + col] = line[col * 2 + 1]; + } + } + for row in 0..ch { + let src = row * uv_pitch; + let line = &mut row_buf[..cw * 4]; + line.copy_from_slice(&uv_plane[src..src + cw * 4]); + for col in 0..cw { + out.u[row * cw + col] = line[col * 4 + 1]; + out.v[row * cw + col] = line[col * 4 + 3]; + } + } + } + } + Ok(()) +} + +/// Check that `rows` rows of `row_bytes` bytes at `pitch` fit in a plane of +/// `len` bytes. A lost or half-initialised GPU context can hand back a short +/// or odd mapping; this turns what would be a slice panic into an error. +pub(crate) fn check_plane( + name: &str, + len: usize, + pitch: usize, + rows: usize, + row_bytes: usize, +) -> Result<()> { + if rows == 0 || row_bytes == 0 { + return Ok(()); + } + let need = (rows - 1) + .checked_mul(pitch) + .and_then(|n| n.checked_add(row_bytes)); + match need { + Some(need) if pitch >= row_bytes && need <= len => Ok(()), + _ => Err(Error::config(format!( + "VA image {name} plane does not cover the frame: {rows} rows x {row_bytes} bytes at pitch {pitch}, mapped {len} bytes" + ))), + } +} + /// Interleave I420 chroma into an NV12 buffer, for the encoder input path. pub fn i420_to_nv12( src: &I420, diff --git a/crates/ec-hw/src/vkdec265.rs b/crates/ec-hw/src/vkdec265.rs index 38304b35..53fbbb53 100644 --- a/crates/ec-hw/src/vkdec265.rs +++ b/crates/ec-hw/src/vkdec265.rs @@ -16,12 +16,13 @@ use crate::hevc_dpb::{ self, Dpb, Mark, is_bla_picture, is_leading_picture, is_rasl_picture, is_reference_picture, peek_pps_id, }; -use crate::picture::{I420, nv12_to_i420}; +use crate::picture::{I420, semi_planar_to_i420}; const MAX_SLOTS: u32 = 17; struct Session { h265: H265DecodeSession, + bit_depth: u8, max_width: u32, max_height: u32, slots: u32, @@ -205,23 +206,33 @@ impl VkH265Decoder { fn ensure_session(&mut self, sps: &Sps) -> Result<()> { if sps.chroma_format_idc != 1 - || sps.bit_depth_luma_minus8 != 0 - || sps.bit_depth_chroma_minus8 != 0 + || sps.bit_depth_luma_minus8 != sps.bit_depth_chroma_minus8 + || !matches!(sps.bit_depth_luma_minus8, 0 | 2) { return Err(Error::unsupported( "Vulkan H.265 decode", - "only 8-bit 4:2:0", + "only 8- and 10-bit 4:2:0", )); } + let bit_depth = (8 + sps.bit_depth_luma_minus8) as u8; let slots = (sps.max_dec_pic_buffering_minus1 + 2).min(MAX_SLOTS); let (w, h) = ( sps.pic_width_in_luma_samples, sps.pic_height_in_luma_samples, ); let (max_width, max_height, slots) = match &self.session { - Some(s) if w <= s.max_width && h <= s.max_height && slots <= s.slots => return Ok(()), - Some(s) => (w.max(s.max_width), h.max(s.max_height), slots.max(s.slots)), - None => (w, h, slots), + Some(s) + if s.bit_depth == bit_depth + && w <= s.max_width + && h <= s.max_height + && slots <= s.slots => + { + return Ok(()); + } + Some(s) if s.bit_depth == bit_depth => { + (w.max(s.max_width), h.max(s.max_height), slots.max(s.slots)) + } + _ => (w, h, slots), }; self.current = None; self.dpb.pictures.clear(); @@ -233,10 +244,12 @@ impl VkH265Decoder { max_width, max_height, max_dpb_slots: slots, + bit_depth, }, )?; self.session = Some(Session { h265, + bit_depth, max_width, max_height, slots, @@ -328,7 +341,8 @@ impl VkH265Decoder { sps.pic_height_in_luma_samples, )?; if current.output { - self.outputs.insert(current.slot, crop(&sps, &y, &uv)); + let frame = crop(&sps, &y, &uv)?; + self.outputs.insert(current.slot, frame); } self.dpb.pictures.push(hevc_dpb::StoredPicture { @@ -369,18 +383,17 @@ fn store(slot: &mut Option, value: T) -> bool { true } -fn crop(sps: &Sps, y: &[u8], uv: &[u8]) -> I420 { - let (width, height) = sps.display_size(); - let pitch = sps.pic_width_in_luma_samples as usize; - let left = 2 * sps.conf_win.left as usize; - let top = 2 * sps.conf_win.top as usize; - nv12_to_i420( - &y[top * pitch + left..], - pitch, - &uv[(top / 2) * pitch + left..], - pitch, - width as usize, - height as usize, +fn crop(sps: &Sps, y: &[u8], uv: &[u8]) -> Result { + semi_planar_to_i420( + (8 + sps.bit_depth_luma_minus8) as u8, + y, + uv, + sps.pic_width_in_luma_samples as usize, + ( + 2 * sps.conf_win.left as usize, + 2 * sps.conf_win.top as usize, + ), + sps.display_size(), ) } diff --git a/crates/ec-hw/src/vkdec_av1.rs b/crates/ec-hw/src/vkdec_av1.rs index 8409ba72..e2f926ff 100644 --- a/crates/ec-hw/src/vkdec_av1.rs +++ b/crates/ec-hw/src/vkdec_av1.rs @@ -17,12 +17,13 @@ use ec_vk::{ use crate::av1_refs::RefSlots; use crate::error::{Error, Result}; -use crate::picture::{I420, nv12_to_i420}; +use crate::picture::{I420, semi_planar_to_i420}; const DPB_SLOTS: u32 = NUM_REF_FRAMES as u32 + 1; struct Session { av1: Av1DecodeSession, + bit_depth: u8, width: u32, height: u32, sequence: Option, @@ -161,8 +162,14 @@ impl VkAv1Decoder { return Ok(()); } let (y, uv) = session.av1.read_output(width, height)?; - let w = width as usize; - let decoded = nv12_to_i420(&y, w, &uv, w, w, height as usize); + let decoded = semi_planar_to_i420( + session.bit_depth, + &y, + &uv, + width as usize, + (0, 0), + (width, height), + )?; let state = Av1RefSlot { slot: setup_slot, frame_type: av1_frame_type(header.frame_type), @@ -187,12 +194,16 @@ impl VkAv1Decoder { } fn ensure_session(&mut self, seq: &SequenceHeader, width: u32, height: u32) -> Result<()> { + let bit_depth = seq.color_config.bit_depth; let mut session = match self.session.take() { - Some(s) if width <= s.width && height <= s.height => s, + Some(s) if s.bit_depth == bit_depth && width <= s.width && height <= s.height => s, old => { - let (width, height) = old.map_or((width, height), |s| { - (width.max(s.width), height.max(s.height)) - }); + let (width, height) = match &old { + Some(s) if s.bit_depth == bit_depth => { + (width.max(s.width), height.max(s.height)) + } + _ => (width, height), + }; self.refs = RefSlots::new(); let av1 = Av1DecodeSession::new( &self.gpu, @@ -200,10 +211,12 @@ impl VkAv1Decoder { max_width: width, max_height: height, max_dpb_slots: DPB_SLOTS, + bit_depth, }, )?; Session { av1, + bit_depth, width, height, sequence: None, @@ -228,14 +241,14 @@ impl VkAv1Decoder { fn check_supported(seq: &SequenceHeader, header: &FrameHeader) -> Result<()> { let c = &seq.color_config; if seq.seq_profile != 0 - || c.bit_depth != 8 + || !matches!(c.bit_depth, 8 | 10) || c.mono_chrome || c.subsampling_x != 1 || c.subsampling_y != 1 { return Err(Error::unsupported( "Vulkan AV1 decode", - "only Main 8-bit 4:2:0", + "only Main 8- and 10-bit 4:2:0", )); } if header.film_grain.apply_grain { diff --git a/shims/vk-video-ffi/examples/av1_decode_smoke.rs b/shims/vk-video-ffi/examples/av1_decode_smoke.rs index 4f70a952..308ff78a 100644 --- a/shims/vk-video-ffi/examples/av1_decode_smoke.rs +++ b/shims/vk-video-ffi/examples/av1_decode_smoke.rs @@ -285,6 +285,7 @@ fn main() { max_width: w, max_height: h, max_dpb_slots: 9, + bit_depth: 8, }; let mut session = Av1DecodeSession::new(&gpu, &cfg).expect("decode session"); session diff --git a/shims/vk-video-ffi/examples/h265_decode_smoke.rs b/shims/vk-video-ffi/examples/h265_decode_smoke.rs index 32769b0a..c438c7fd 100644 --- a/shims/vk-video-ffi/examples/h265_decode_smoke.rs +++ b/shims/vk-video-ffi/examples/h265_decode_smoke.rs @@ -228,6 +228,7 @@ fn main() { max_width: w, max_height: h, max_dpb_slots: 2, + bit_depth: 8, }; let mut session = H265DecodeSession::new(&gpu, &cfg).expect("decode session"); session diff --git a/shims/vk-video-ffi/src/av1_decode.rs b/shims/vk-video-ffi/src/av1_decode.rs index 154c4f74..86c64a6c 100644 --- a/shims/vk-video-ffi/src/av1_decode.rs +++ b/shims/vk-video-ffi/src/av1_decode.rs @@ -4,7 +4,8 @@ use vulkanalia::prelude::v1_3::*; use vulkanalia::vk::KhrVideoQueueExtensionDeviceCommands; use crate::session::{ - Decoder, VideoSession, align, align_u64, picture_resource, video_caps, vk, zeroed, + Decoder, VideoSession, align, align_u64, component_bit_depth, picture_resource, video_caps, vk, + zeroed, }; use crate::{Error, Gpu}; @@ -17,6 +18,8 @@ pub struct Av1DecodeConfig { pub max_height: u32, /// DPB slots, including the slot the picture is decoded into. pub max_dpb_slots: u32, + /// Luma and chroma bit depth: 8 or 10. + pub bit_depth: u8, } /// Frame type, values as in the spec and `StdVideoAV1FrameType`. @@ -471,13 +474,14 @@ struct Profile { } impl Profile { - fn new() -> Box { + fn new(bit_depth: u8) -> Box { + let component = component_bit_depth(bit_depth); let mut p = Box::new(Profile { info: vk::VideoProfileInfoKHR::builder() .video_codec_operation(vk::VideoCodecOperationFlagsKHR::DECODE_AV1) .chroma_subsampling(vk::VideoChromaSubsamplingFlagsKHR::_420) - .luma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8) - .chroma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8) + .luma_bit_depth(component) + .chroma_bit_depth(component) .build(), av1: vk::VideoDecodeAV1ProfileInfoKHR::builder() .std_profile(vk::video::STD_VIDEO_AV1_PROFILE_MAIN) @@ -489,10 +493,11 @@ impl Profile { } } -/// An AV1 Main 8-bit 4:2:0 Vulkan Video decode session: NV12 DPB images per slot and a separate NV12 output image. +/// An AV1 Main 8- or 10-bit 4:2:0 Vulkan Video decode session: DPB images per slot and a separate output image. pub struct Av1DecodeSession { dec: Decoder, sequence: Option, + bit_depth: u8, } impl Av1DecodeSession { @@ -503,6 +508,9 @@ impl Av1DecodeSession { "decode size or DPB slot count is zero".into(), )); } + if !matches!(cfg.bit_depth, 8 | 10) { + return Err(Error::Invalid("bit depth is not 8 or 10".into())); + } let family = gpu .decode_family() .ok_or_else(|| Error::Unsupported("AV1 decode queue family".into()))?; @@ -518,7 +526,7 @@ impl Av1DecodeSession { } let width = align(cfg.max_width, 16); let height = align(cfg.max_height, 16); - let profile = Profile::new(); + let profile = Profile::new(cfg.bit_depth); let caps = query_caps(gpu, &profile.info)?; if width > caps.max_extent.width || height > caps.max_extent.height @@ -555,6 +563,7 @@ impl Av1DecodeSession { Ok(Av1DecodeSession { dec, sequence: None, + bit_depth: cfg.bit_depth, }) } @@ -562,14 +571,15 @@ impl Av1DecodeSession { pub fn set_sequence_header(&mut self, seq: &Av1SequenceHeader) -> Result<(), Error> { let c = &seq.color_config; if seq.seq_profile != 0 - || c.bit_depth != 8 + || c.bit_depth != self.bit_depth || c.mono_chrome || c.subsampling_x != 1 || c.subsampling_y != 1 { - return Err(Error::Unsupported( - "AV1 sequence other than Main 8-bit 4:2:0".into(), - )); + return Err(Error::Unsupported(format!( + "AV1 sequence other than Main {}-bit 4:2:0", + self.bit_depth + ))); } let gpu = self.dec.vs.gpu.clone(); let d = gpu.device(); @@ -842,7 +852,7 @@ impl Av1DecodeSession { self.dec.run(&begin, &decode) } - /// Copies the top-left width x height of the last decoded picture out as NV12 planes (Y, interleaved UV). + /// Copies the top-left width x height of the last decoded picture out as NV12 or P010 planes (Y, interleaved UV). pub fn read_output(&mut self, width: u32, height: u32) -> Result<(Vec, Vec), Error> { self.dec.read_nv12(width, height) } @@ -854,7 +864,8 @@ fn query_caps(gpu: &Gpu, profile: &vk::VideoProfileInfoKHR) -> Result Box { + fn new(bit_depth: u8) -> Box { + let component = component_bit_depth(bit_depth); + let profile_idc = if bit_depth == 10 { + vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN_10 + } else { + vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN + }; let mut p = Box::new(Profile { info: vk::VideoProfileInfoKHR::builder() .video_codec_operation(vk::VideoCodecOperationFlagsKHR::DECODE_H265) .chroma_subsampling(vk::VideoChromaSubsamplingFlagsKHR::_420) - .luma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8) - .chroma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8) + .luma_bit_depth(component) + .chroma_bit_depth(component) .build(), h265: vk::VideoDecodeH265ProfileInfoKHR::builder() - .std_profile_idc(vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN) + .std_profile_idc(profile_idc) .build(), }); p.info.next = &p.h265 as *const _ as *const c_void; @@ -342,6 +351,7 @@ impl Profile { pub struct H265DecodeSession { dec: Decoder, sps: Vec, + bit_depth: u8, } impl H265DecodeSession { @@ -352,6 +362,9 @@ impl H265DecodeSession { "decode size or DPB slot count is zero".into(), )); } + if !matches!(cfg.bit_depth, 8 | 10) { + return Err(Error::Invalid("bit depth is not 8 or 10".into())); + } let family = gpu .decode_family() .ok_or_else(|| Error::Unsupported("H.265 decode queue family".into()))?; @@ -367,7 +380,7 @@ impl H265DecodeSession { } let width = align(cfg.max_width, 16); let height = align(cfg.max_height, 16); - let profile = Profile::new(); + let profile = Profile::new(cfg.bit_depth); let caps = query_caps(gpu, &profile.info)?; if width > caps.max_extent.width || height > caps.max_extent.height @@ -404,6 +417,7 @@ impl H265DecodeSession { Ok(H265DecodeSession { dec, sps: Vec::new(), + bit_depth: cfg.bit_depth, }) } @@ -414,12 +428,16 @@ impl H265DecodeSession { sps: &[H265Sps], pps: &[H265Pps], ) -> Result<(), Error> { + let minus8 = self.bit_depth - 8; if sps.iter().any(|s| { s.chroma_format_idc != 1 - || s.bit_depth_luma_minus8 != 0 - || s.bit_depth_chroma_minus8 != 0 + || s.bit_depth_luma_minus8 != minus8 + || s.bit_depth_chroma_minus8 != minus8 }) { - return Err(Error::Unsupported("H.265 decode beyond 8-bit 4:2:0".into())); + return Err(Error::Unsupported(format!( + "H.265 decode other than {}-bit 4:2:0", + self.bit_depth + ))); } let gpu = self.dec.vs.gpu.clone(); let d = gpu.device(); @@ -675,7 +693,7 @@ impl H265DecodeSession { self.dec.run(&begin, &decode) } - /// Copies the top-left width x height of the last decoded picture out as NV12 planes (Y, interleaved UV). + /// Copies the top-left width x height of the last decoded picture out as NV12 or P010 planes (Y, interleaved UV). pub fn read_output(&mut self, width: u32, height: u32) -> Result<(Vec, Vec), Error> { self.dec.read_nv12(width, height) } @@ -687,7 +705,8 @@ fn query_caps(gpu: &Gpu, profile: &vk::VideoProfileInfoKHR) -> Result() -> T { unsafe { std::mem::zeroed() } } +pub(crate) fn bytes_per_sample(format: vk::Format) -> usize { + if format == P010 { 2 } else { 1 } +} + +pub(crate) fn component_bit_depth(bit_depth: u8) -> vk::VideoComponentBitDepthFlagsKHR { + if bit_depth == 10 { + vk::VideoComponentBitDepthFlagsKHR::_10 + } else { + vk::VideoComponentBitDepthFlagsKHR::_8 + } +} + pub(crate) fn align(value: u32, to: u32) -> u32 { value.div_ceil(to) * to } @@ -224,6 +237,7 @@ impl Buffer { pub(crate) struct VideoSession { pub(crate) gpu: Gpu, pub(crate) family: u32, + pub(crate) format: vk::Format, pub(crate) session: vk::VideoSessionKHR, pub(crate) params: vk::VideoSessionParametersKHR, memories: Vec, @@ -239,9 +253,15 @@ impl VideoSession { max_dpb_slots: u32, max_active_refs: u32, ) -> Result { + let format = if profile.luma_bit_depth == vk::VideoComponentBitDepthFlagsKHR::_10 { + P010 + } else { + NV12 + }; let mut s = VideoSession { gpu: gpu.clone(), family, + format, session: Default::default(), params: Default::default(), memories: Vec::new(), @@ -250,9 +270,9 @@ impl VideoSession { let info = vk::VideoSessionCreateInfoKHR::builder() .queue_family_index(family) .video_profile(profile) - .picture_format(NV12) + .picture_format(format) .max_coded_extent(extent) - .reference_picture_format(NV12) + .reference_picture_format(format) .max_dpb_slots(max_dpb_slots) .max_active_reference_pictures(max_active_refs) .std_header_version(std_header_version) @@ -331,7 +351,7 @@ impl VideoSession { ) -> Result { let info = vk::ImageCreateInfo::builder() .image_type(vk::ImageType::_2D) - .format(NV12) + .format(self.format) .extent(vk::Extent3D { width: extent.width, height: extent.height, @@ -362,7 +382,7 @@ impl VideoSession { let view_info = vk::ImageViewCreateInfo::builder() .image(image) .view_type(vk::ImageViewType::_2D) - .format(NV12) + .format(self.format) .subresource_range(color_range()) .push_next(&mut usage_info) .build(); @@ -912,8 +932,9 @@ impl Decoder { &families, &mut list, )?; + let bytes = bytes_per_sample(dec.vs.format) as u64; let bitstream_size = align_u64( - max_extent.width as u64 * max_extent.height as u64 * 3 + 65536, + max_extent.width as u64 * max_extent.height as u64 * 3 * bytes / 2 + 65536, size_align, ); dec.bitstream = dec.vs.buffer( @@ -923,7 +944,7 @@ impl Decoder { Some(&mut list), )?; dec.readback = dec.vs.buffer( - max_extent.width as u64 * max_extent.height as u64 * 3 / 2, + max_extent.width as u64 * max_extent.height as u64 * 3 / 2 * bytes, vk::BufferUsageFlags::TRANSFER_DST, vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT, None, @@ -980,7 +1001,7 @@ impl Decoder { Ok(()) } - /// Copies the top-left width x height of the last decoded picture out as NV12 planes (Y, interleaved UV). + /// Copies the top-left width x height of the last decoded picture out as NV12 or P010 planes (Y, interleaved UV). pub(crate) fn read_nv12( &mut self, width: u32, @@ -1002,7 +1023,8 @@ impl Decoder { let d = gpu.device(); let cb = self.graphics.cb; let image = self.output.image; - let luma = width as usize * height as usize; + let bytes = bytes_per_sample(self.vs.format); + let luma = width as usize * height as usize * bytes; let copies = [ copy_region(0, PLANE_0, width, height), copy_region(luma as u64, PLANE_1, width / 2, height / 2),