diff --git a/crates/ec-hw/src/dec/av1.rs b/crates/ec-hw/src/dec/av1.rs index 77973c44..dbbbfdf9 100644 --- a/crates/ec-hw/src/dec/av1.rs +++ b/crates/ec-hw/src/dec/av1.rs @@ -182,18 +182,13 @@ impl Av1Decoder { .session .as_ref() .ok_or_else(|| Error::config("AV1 frame before any session"))?; - let surface = session - .pool - .acquire() - .ok_or_else(|| Error::config("AV1 decode: every surface is still in use"))?; + let surface = session.acquire()?; // Film grain (spec 7.18.3) is applied by the driver onto a separate // display surface, so the reconstruction the references point at stays // grain-free and the grained copy is what gets shown. let grained = if wants_grain(&sequence, header) { - Some(session.pool.acquire().ok_or_else(|| { - Error::config("AV1 decode: every surface is still in use (grain output)") - })?) + Some(session.acquire()?) } else { None }; diff --git a/crates/ec-hw/src/dec/h264.rs b/crates/ec-hw/src/dec/h264.rs index c9870e49..6e81ab21 100644 --- a/crates/ec-hw/src/dec/h264.rs +++ b/crates/ec-hw/src/dec/h264.rs @@ -250,6 +250,12 @@ impl H264Decoder { /// Create the GPU session if this stream has not had one yet. fn ensure_session(&mut self, sps: &Sps) -> Result<()> { + if sps.chroma_format_idc != 1 { + return Err(Error::unsupported( + format!("H.264 chroma_format_idc {}", sps.chroma_format_idc), + "VA-API H.264 decode is 4:2:0 only", + )); + } let profile = profile_for(sps)?; let coded = (sps.coded_width, sps.coded_height); let bit_depth = sps.bit_depth_luma; @@ -306,10 +312,7 @@ impl H264Decoder { .session .as_ref() .ok_or_else(|| Error::config("H.264 picture before any SPS"))?; - let surface = session - .pool - .acquire() - .ok_or_else(|| Error::config("H.264 decode: every surface is still in use"))?; + let surface = session.acquire()?; let id = self.dpb.next_id(); self.current = Some(Current { surface, diff --git a/crates/ec-hw/src/dec/hevc.rs b/crates/ec-hw/src/dec/hevc.rs index 8bcd30a3..83a15723 100644 --- a/crates/ec-hw/src/dec/hevc.rs +++ b/crates/ec-hw/src/dec/hevc.rs @@ -21,8 +21,8 @@ use super::{ReadyFrames, Session, StreamInfo}; use crate::error::{Error, Result}; use crate::frame::{Colour, Frame}; use crate::hevc_dpb::{ - Dpb, Mark, Rps, StoredPicture, is_bla_picture, is_rasl_picture, is_reference_picture, - is_leading_picture, peek_pps_id, vui_colour_tags, + Dpb, Mark, Rps, StoredPicture, hevc_ctb16_broken, is_bla_picture, is_rasl_picture, + is_reference_picture, is_leading_picture, peek_pps_id, vui_colour_tags, }; use crate::params::hevc::{ IQMatrixBufferHEVC, LongSliceFlags, PICTURE_INVALID, PICTURE_LONG_TERM_REFERENCE, @@ -237,6 +237,16 @@ impl HevcDecoder { } fn ensure_session(&mut self, sps: &Sps) -> Result<()> { + let amd = || { + ec_va::display::vendor(&self.display) + .is_ok_and(|v| v.contains("AMD") || v.contains("radeonsi")) + }; + if hevc_ctb16_broken(sps, amd) { + return Err(Error::unsupported( + "VA-API H.265 decode", + "16x16 CTBs on AMD decode with wrong chroma", + )); + } let bit_depth = (sps.bit_depth_luma_minus8 + 8) as u8; let profile = match (sps.chroma_format_idc, bit_depth) { (1, 8) => Profile::HEVCMain, @@ -320,10 +330,7 @@ impl HevcDecoder { .session .as_ref() .ok_or_else(|| Error::config("HEVC picture before any SPS"))?; - let surface = session - .pool - .acquire() - .ok_or_else(|| Error::config("HEVC decode: every surface is still in use"))?; + let surface = session.acquire()?; // The driver indexes RefPicList into `reference_frames`, so the mapping // from DPB slot to that array is fixed once, here. diff --git a/crates/ec-hw/src/dec/mod.rs b/crates/ec-hw/src/dec/mod.rs index ded51045..bf57c837 100644 --- a/crates/ec-hw/src/dec/mod.rs +++ b/crates/ec-hw/src/dec/mod.rs @@ -28,7 +28,7 @@ use ec_va::{CapReport, Config, ConfigAttrib, Context, Display, Surface, SurfaceS use crate::error::{Error, Result}; use crate::frame::Frame; -use crate::pool::SurfacePool; +use crate::pool::{PooledSurface, SurfacePool}; pub use crate::types::Codec; @@ -271,6 +271,7 @@ pub(crate) struct Session { /// `catch_unwind` can stop. pub(crate) poisoned: std::sync::atomic::AtomicBool, pub(crate) context: Rc, + display: Rc, /// The readback image every frame of this stream reuses. pub(crate) pool: SurfacePool, pub(crate) coded_size: (u32, u32), @@ -364,6 +365,7 @@ impl Session { pending: std::sync::Mutex::new(None), poisoned: std::sync::atomic::AtomicBool::new(false), context, + display: Rc::clone(display), pool, coded_size, display_size, @@ -372,6 +374,20 @@ impl Session { }) } + /// A free surface for the next picture. Frames the caller has not taken yet hold + /// their surfaces, so when the pool runs dry it grows by one surface instead of + /// failing the decode. + pub(crate) fn acquire(&self) -> Result> { + if let Some(surface) = self.pool.acquire() { + return Ok(surface); + } + let spec = *self.pool.spec(); + self.pool.grow(ec_va::create_pool(&self.display, &spec, 1)?); + self.pool + .acquire() + .ok_or_else(|| Error::config("surface pool empty after growing")) + } + /// Submit one picture: begin, render every buffer, end, then wait for the /// *previous* picture (depth-1 pipelining). /// diff --git a/crates/ec-hw/src/dec/vp9.rs b/crates/ec-hw/src/dec/vp9.rs index 7bde9dd2..1bafcbd9 100644 --- a/crates/ec-hw/src/dec/vp9.rs +++ b/crates/ec-hw/src/dec/vp9.rs @@ -125,10 +125,7 @@ impl Vp9Decoder { .session .as_ref() .ok_or_else(|| Error::config("VP9 frame before any session"))?; - let surface = session - .pool - .acquire() - .ok_or_else(|| Error::config("VP9 decode: every surface is still in use"))?; + let surface = session.acquire()?; let pic_param = picture_parameters(&header, &slot_ids(&self.refs)); let slice_param = slice_parameters(&header, data.len()); @@ -159,13 +156,13 @@ impl Vp9Decoder { } fn ensure_session(&mut self, header: &FrameHeader) -> Result<()> { - let profile = match header.profile { - 0 => Profile::VP9Profile0, - 2 => Profile::VP9Profile2, - other => { + let profile = match (header.profile, header.bit_depth) { + (0, 8) => Profile::VP9Profile0, + (2, 10) => Profile::VP9Profile2, + (other, depth) => { return Err(Error::unsupported( - format!("VP9 profile {other}"), - "only the 4:2:0 profiles 0 and 2 are decoded in hardware", + format!("VP9 profile {other} at {depth}-bit"), + "VA-API decodes 8-bit profile 0 and 10-bit profile 2 only", )); } }; diff --git a/crates/ec-hw/src/hevc_dpb.rs b/crates/ec-hw/src/hevc_dpb.rs index 28644e90..f987d51d 100644 --- a/crates/ec-hw/src/hevc_dpb.rs +++ b/crates/ec-hw/src/hevc_dpb.rs @@ -10,6 +10,16 @@ use ec_h265_syntax::{NalUnitType, SliceHeader, Sps}; use crate::error::{Error, Result}; +/// PCI vendor ID of AMD. +pub(crate) const AMD_VENDOR_ID: u32 = 0x1002; + +/// AMD's VCN returns wrong chroma for HEVC with 16x16 coding tree blocks, in the +/// firmware, so ffmpeg's VA-API and Vulkan decoders get the same wrong picture. Such +/// streams go to software. `amd` is only asked when the CTB size is 16. +pub(crate) fn hevc_ctb16_broken(sps: &Sps, amd: impl FnOnce() -> bool) -> bool { + sps.ctb_size() == 16 && amd() +} + /// Reference marking of a stored picture (8.3.2). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum Mark { diff --git a/crates/ec-hw/src/pool.rs b/crates/ec-hw/src/pool.rs index aee0d892..b795188b 100644 --- a/crates/ec-hw/src/pool.rs +++ b/crates/ec-hw/src/pool.rs @@ -17,7 +17,7 @@ use std::sync::Mutex; struct PoolInner { /// Every surface, in allocation order. - all: Vec>, + all: Mutex>>, free: Mutex>>, } @@ -37,7 +37,7 @@ impl SurfacePool { SurfacePool { inner: Rc::new(PoolInner { free: Mutex::new(all.clone()), - all, + all: Mutex::new(all), }), spec: *spec, } @@ -50,12 +50,23 @@ impl SurfacePool { /// Total surfaces in the pool. pub fn len(&self) -> usize { - self.inner.all.len() + self.inner.all.lock().map(|all| all.len()).unwrap_or(0) } /// True when the pool holds no surfaces at all. pub fn is_empty(&self) -> bool { - self.inner.all.is_empty() + self.len() == 0 + } + + /// Add surfaces allocated with the pool's spec, free for [`SurfacePool::acquire`]. + pub fn grow(&self, surfaces: Vec) { + let surfaces: Vec> = surfaces.into_iter().map(Rc::new).collect(); + if let Ok(mut all) = self.inner.all.lock() { + all.extend(surfaces.iter().cloned()); + } + if let Ok(mut free) = self.inner.free.lock() { + free.extend(surfaces); + } } /// Surfaces currently available. diff --git a/crates/ec-hw/src/vkdec264.rs b/crates/ec-hw/src/vkdec264.rs index 3fb288f9..e8e3f26d 100644 --- a/crates/ec-hw/src/vkdec264.rs +++ b/crates/ec-hw/src/vkdec264.rs @@ -31,6 +31,7 @@ struct Session { max_width: u32, max_height: u32, slots: u32, + chroma_format_idc: u8, } struct Current { @@ -225,18 +226,31 @@ impl VkH264Decoder { } fn ensure_session(&mut self, sps: &Sps) -> Result<()> { - if sps.chroma_format_idc != 1 || sps.bit_depth_luma != 8 || sps.bit_depth_chroma != 8 { + if !matches!(sps.chroma_format_idc, 0 | 1) + || sps.bit_depth_luma != 8 + || sps.bit_depth_chroma != 8 + { return Err(Error::unsupported( "Vulkan H.264 decode", - "only 8-bit 4:2:0", + "only 8-bit 4:0:0 and 4:2:0", )); } + let chroma = sps.chroma_format_idc; let slots = (self.dpb.capacity() as u32 + 1).min(MAX_SLOTS); let (w, h) = (sps.coded_width, sps.coded_height); 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.chroma_format_idc == chroma + && w <= s.max_width + && h <= s.max_height + && slots <= s.slots => + { + return Ok(()); + } + Some(s) if s.chroma_format_idc == chroma => { + (w.max(s.max_width), h.max(s.max_height), slots.max(s.slots)) + } + _ => (w, h, slots), }; self.current = None; self.dpb.clear(); @@ -249,6 +263,7 @@ impl VkH264Decoder { max_height, max_dpb_slots: slots, profile_idc: sps.profile_idc, + chroma_format_idc: chroma, }, )?; let ring = Ring::new(h264.ring_len()); @@ -258,6 +273,7 @@ impl VkH264Decoder { max_width, max_height, slots, + chroma_format_idc: chroma, }); self.params_dirty = true; Ok(()) diff --git a/crates/ec-hw/src/vkdec265.rs b/crates/ec-hw/src/vkdec265.rs index e5e715d0..dab4b36f 100644 --- a/crates/ec-hw/src/vkdec265.rs +++ b/crates/ec-hw/src/vkdec265.rs @@ -15,8 +15,8 @@ use ec_vk::{ use crate::error::{Error, Result}; use crate::hevc_dpb::{ - self, Dpb, Mark, is_bla_picture, is_leading_picture, is_rasl_picture, is_reference_picture, - peek_pps_id, vui_colour_tags, + self, AMD_VENDOR_ID, Dpb, Mark, hevc_ctb16_broken, is_bla_picture, is_leading_picture, + is_rasl_picture, is_reference_picture, peek_pps_id, vui_colour_tags, }; use ec_core::color::{ColorDescription, Tags}; @@ -219,6 +219,12 @@ impl VkH265Decoder { } fn ensure_session(&mut self, sps: &Sps) -> Result<()> { + if hevc_ctb16_broken(sps, || self.gpu.vendor_id() == AMD_VENDOR_ID) { + return Err(Error::unsupported( + "Vulkan H.265 decode", + "16x16 CTBs on AMD decode with wrong chroma", + )); + } if sps.chroma_format_idc != 1 || sps.bit_depth_luma_minus8 != sps.bit_depth_chroma_minus8 || !matches!(sps.bit_depth_luma_minus8, 0 | 2) diff --git a/shims/vk-video-ffi/examples/h264_decode_smoke.rs b/shims/vk-video-ffi/examples/h264_decode_smoke.rs index e4beebc4..939b1805 100644 --- a/shims/vk-video-ffi/examples/h264_decode_smoke.rs +++ b/shims/vk-video-ffi/examples/h264_decode_smoke.rs @@ -136,6 +136,7 @@ fn main() { max_height: sps.coded_height, max_dpb_slots: 2, profile_idc: sps.profile_idc, + chroma_format_idc: sps.chroma_format_idc, }; let mut session = H264DecodeSession::new(&gpu, &cfg).expect("decode session"); session diff --git a/shims/vk-video-ffi/src/h264_decode.rs b/shims/vk-video-ffi/src/h264_decode.rs index 29c835c6..a7492415 100644 --- a/shims/vk-video-ffi/src/h264_decode.rs +++ b/shims/vk-video-ffi/src/h264_decode.rs @@ -19,6 +19,8 @@ pub struct H264DecodeConfig { pub max_dpb_slots: u32, /// profile_idc: 66, 77 or 100. pub profile_idc: u8, + /// chroma_format_idc: 0 for monochrome, 1 for 4:2:0. + pub chroma_format_idc: u8, } /// Scaling lists in bitstream (zigzag) order, fall-back rules already applied. @@ -173,11 +175,16 @@ struct Profile { } impl Profile { - fn new(idc: u8) -> Box { + fn new(idc: u8, chroma_format_idc: u8) -> Box { + let chroma = if chroma_format_idc == 0 { + vk::VideoChromaSubsamplingFlagsKHR::MONOCHROME + } else { + vk::VideoChromaSubsamplingFlagsKHR::_420 + }; let mut p = Box::new(Profile { info: vk::VideoProfileInfoKHR::builder() .video_codec_operation(vk::VideoCodecOperationFlagsKHR::DECODE_H264) - .chroma_subsampling(vk::VideoChromaSubsamplingFlagsKHR::_420) + .chroma_subsampling(chroma) .luma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8) .chroma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8) .build(), @@ -200,6 +207,12 @@ pub struct H264DecodeSession { impl H264DecodeSession { /// Creates a session with its DPB, bitstream and readback buffers. pub fn new(gpu: &Gpu, cfg: &H264DecodeConfig) -> Result { + if !matches!(cfg.chroma_format_idc, 0 | 1) { + return Err(Error::Invalid(format!( + "H.264 chroma_format_idc {}", + cfg.chroma_format_idc + ))); + } if !matches!(cfg.profile_idc, 66 | 77 | 100) { return Err(Error::Invalid(format!( "H.264 profile_idc {}", @@ -226,7 +239,7 @@ impl H264DecodeSession { } let width = align(cfg.max_width, 16); let height = align(cfg.max_height, 16); - let profile = Profile::new(cfg.profile_idc); + let profile = Profile::new(cfg.profile_idc, cfg.chroma_format_idc); let caps = query_caps(gpu, &profile.info)?; if width > caps.max_extent.width || height > caps.max_extent.height diff --git a/shims/vk-video-ffi/src/h265_decode.rs b/shims/vk-video-ffi/src/h265_decode.rs index 1d7dc6fb..63d9a050 100644 --- a/shims/vk-video-ffi/src/h265_decode.rs +++ b/shims/vk-video-ffi/src/h265_decode.rs @@ -442,10 +442,10 @@ impl H265DecodeSession { let gpu = self.dec.vs.gpu.clone(); let d = gpu.device(); - let vps_ptl = vps + let vps_ptl: Vec<_> = vps .iter() - .map(|v| std_ptl(&v.profile_tier_level).map(Box::new)) - .collect::, Error>>()?; + .map(|v| Box::new(std_ptl(&v.profile_tier_level))) + .collect(); let vps_dpbm: Vec<_> = vps .iter() .map(|v| Box::new(std_dpbm(&v.dec_pic_buf_mgr))) @@ -457,10 +457,10 @@ impl H265DecodeSession { .map(|((v, ptl), dpbm)| std_vps(v, ptl, dpbm)) .collect(); - let sps_ptl = sps + let sps_ptl: Vec<_> = sps .iter() - .map(|s| std_ptl(&s.profile_tier_level).map(Box::new)) - .collect::, Error>>()?; + .map(|s| Box::new(std_ptl(&s.profile_tier_level))) + .collect(); let sps_dpbm: Vec<_> = sps .iter() .map(|s| Box::new(std_dpbm(&s.dec_pic_buf_mgr))) @@ -775,7 +775,7 @@ fn ref_info(poc: i32, long_term: bool) -> vk::video::StdVideoDecodeH265Reference info } -fn level(idc: u8) -> Result { +fn level(idc: u8) -> vk::video::StdVideoH265LevelIdc { use vk::video::*; let table = [ (30, STD_VIDEO_H265_LEVEL_IDC_1_0), @@ -795,11 +795,10 @@ fn level(idc: u8) -> Result { table .into_iter() .find(|&(v, _)| v == idc) - .map(|(_, level)| level) - .ok_or_else(|| Error::Invalid(format!("H.265 level_idc {idc}"))) + .map_or(STD_VIDEO_H265_LEVEL_IDC_6_2, |(_, level)| level) } -fn std_ptl(p: &H265ProfileTierLevel) -> Result { +fn std_ptl(p: &H265ProfileTierLevel) -> vk::video::StdVideoH265ProfileTierLevel { let mut out = zeroed::(); out.flags.set_general_tier_flag(p.tier_flag as u32); out.flags @@ -811,8 +810,8 @@ fn std_ptl(p: &H265ProfileTierLevel) -> Result vk::video::StdVideoH265DecPicBufMgr { diff --git a/shims/vk-video-ffi/src/lib.rs b/shims/vk-video-ffi/src/lib.rs index 32ecd5ed..90d5104a 100644 --- a/shims/vk-video-ffi/src/lib.rs +++ b/shims/vk-video-ffi/src/lib.rs @@ -188,6 +188,7 @@ struct Inner { instance: Instance, physical: vk::PhysicalDevice, name: String, + vendor_id: u32, encode: Option, decode: Option, graphics: Option, @@ -218,7 +219,7 @@ fn queue_families(instance: &Instance, physical: vk::PhysicalDevice) -> Families } } -fn setup(instance: &Instance) -> Result<(vk::PhysicalDevice, Device, String, Families), Error> { +fn setup(instance: &Instance) -> Result<(vk::PhysicalDevice, Device, String, u32, Families), Error> { let devices = unsafe { instance.enumerate_physical_devices() } .map_err(|c| crate::session::vk_error(c, "vkEnumeratePhysicalDevices"))?; let (physical, families) = devices @@ -283,11 +284,9 @@ fn setup(instance: &Instance) -> Result<(vk::PhysicalDevice, Device, String, Fam let device = unsafe { instance.create_device(physical, &info, None) } .map_err(|c| crate::session::vk_error(c, "vkCreateDevice"))?; - let name = unsafe { instance.get_physical_device_properties(physical) } - .device_name - .to_string_lossy() - .into_owned(); - Ok((physical, device, name, families)) + let properties = unsafe { instance.get_physical_device_properties(physical) }; + let name = properties.device_name.to_string_lossy().into_owned(); + Ok((physical, device, name, properties.vendor_id, families)) } impl Gpu { @@ -306,12 +305,13 @@ impl Gpu { let instance = unsafe { entry.create_instance(&info, None) } .map_err(|c| crate::session::vk_error(c, "vkCreateInstance"))?; match setup(&instance) { - Ok((physical, device, name, families)) => Ok(Gpu { + Ok((physical, device, name, vendor_id, families)) => Ok(Gpu { inner: Arc::new(Inner { device, instance, physical, name, + vendor_id, encode: families.encode, decode: families.decode, graphics: families.graphics, @@ -330,6 +330,11 @@ impl Gpu { self.inner.name.clone() } + /// PCI vendor ID of the device, 0x1002 for AMD. + pub fn vendor_id(&self) -> u32 { + self.inner.vendor_id + } + /// Vulkan instance, physical device and device, for examples that build their own images. #[doc(hidden)] pub fn vulkan(&self) -> (&Instance, vk::PhysicalDevice, &Device) {