forge
Explore
Log in

Don't you dare go Hollow

ec-hw: 4:0:0 H.264 on Vulkan, VA surface growth, refuse VA 12-bit VP9 and AMD CTB16 HEVC, accept unknown H.265 levels

Browse files at this commit

db3af7c27c1254f9db06497ad66c7a8d53baeaecAhmet Kaan GümüşParent: 42021c7
crates/ec-hw/src/dec/av1.rsmodified+2 -7
@@ -182,18 +182,13 @@ impl Av1Decoder {
182182 .session
183183 .as_ref()
184184 .ok_or_else(|| Error::config("AV1 frame before any session"))?;
185- let surface = session
186- .pool
187- .acquire()
188- .ok_or_else(|| Error::config("AV1 decode: every surface is still in use"))?;
185+ let surface = session.acquire()?;
189186
190187 // Film grain (spec 7.18.3) is applied by the driver onto a separate
191188 // display surface, so the reconstruction the references point at stays
192189 // grain-free and the grained copy is what gets shown.
193190 let grained = if wants_grain(&sequence, header) {
194- Some(session.pool.acquire().ok_or_else(|| {
195- Error::config("AV1 decode: every surface is still in use (grain output)")
196- })?)
191+ Some(session.acquire()?)
197192 } else {
198193 None
199194 };
crates/ec-hw/src/dec/h264.rsmodified+7 -4
@@ -250,6 +250,12 @@ impl H264Decoder {
250250
251251 /// Create the GPU session if this stream has not had one yet.
252252 fn ensure_session(&mut self, sps: &Sps) -> Result<()> {
253+ if sps.chroma_format_idc != 1 {
254+ return Err(Error::unsupported(
255+ format!("H.264 chroma_format_idc {}", sps.chroma_format_idc),
256+ "VA-API H.264 decode is 4:2:0 only",
257+ ));
258+ }
253259 let profile = profile_for(sps)?;
254260 let coded = (sps.coded_width, sps.coded_height);
255261 let bit_depth = sps.bit_depth_luma;
@@ -306,10 +312,7 @@ impl H264Decoder {
306312 .session
307313 .as_ref()
308314 .ok_or_else(|| Error::config("H.264 picture before any SPS"))?;
309- let surface = session
310- .pool
311- .acquire()
312- .ok_or_else(|| Error::config("H.264 decode: every surface is still in use"))?;
315+ let surface = session.acquire()?;
313316 let id = self.dpb.next_id();
314317 self.current = Some(Current {
315318 surface,
crates/ec-hw/src/dec/hevc.rsmodified+13 -6
@@ -21,8 +21,8 @@ use super::{ReadyFrames, Session, StreamInfo};
2121 use crate::error::{Error, Result};
2222 use crate::frame::{Colour, Frame};
2323 use crate::hevc_dpb::{
24- Dpb, Mark, Rps, StoredPicture, is_bla_picture, is_rasl_picture, is_reference_picture,
25- is_leading_picture, peek_pps_id, vui_colour_tags,
24+ Dpb, Mark, Rps, StoredPicture, hevc_ctb16_broken, is_bla_picture, is_rasl_picture,
25+ is_reference_picture, is_leading_picture, peek_pps_id, vui_colour_tags,
2626 };
2727 use crate::params::hevc::{
2828 IQMatrixBufferHEVC, LongSliceFlags, PICTURE_INVALID, PICTURE_LONG_TERM_REFERENCE,
@@ -237,6 +237,16 @@ impl HevcDecoder {
237237 }
238238
239239 fn ensure_session(&mut self, sps: &Sps) -> Result<()> {
240+ let amd = || {
241+ ec_va::display::vendor(&self.display)
242+ .is_ok_and(|v| v.contains("AMD") || v.contains("radeonsi"))
243+ };
244+ if hevc_ctb16_broken(sps, amd) {
245+ return Err(Error::unsupported(
246+ "VA-API H.265 decode",
247+ "16x16 CTBs on AMD decode with wrong chroma",
248+ ));
249+ }
240250 let bit_depth = (sps.bit_depth_luma_minus8 + 8) as u8;
241251 let profile = match (sps.chroma_format_idc, bit_depth) {
242252 (1, 8) => Profile::HEVCMain,
@@ -320,10 +330,7 @@ impl HevcDecoder {
320330 .session
321331 .as_ref()
322332 .ok_or_else(|| Error::config("HEVC picture before any SPS"))?;
323- let surface = session
324- .pool
325- .acquire()
326- .ok_or_else(|| Error::config("HEVC decode: every surface is still in use"))?;
333+ let surface = session.acquire()?;
327334
328335 // The driver indexes RefPicList into `reference_frames`, so the mapping
329336 // from DPB slot to that array is fixed once, here.
crates/ec-hw/src/dec/mod.rsmodified+17 -1
@@ -28,7 +28,7 @@ use ec_va::{CapReport, Config, ConfigAttrib, Context, Display, Surface, SurfaceS
2828
2929 use crate::error::{Error, Result};
3030 use crate::frame::Frame;
31-use crate::pool::SurfacePool;
31+use crate::pool::{PooledSurface, SurfacePool};
3232
3333 pub use crate::types::Codec;
3434
@@ -271,6 +271,7 @@ pub(crate) struct Session {
271271 /// `catch_unwind` can stop.
272272 pub(crate) poisoned: std::sync::atomic::AtomicBool,
273273 pub(crate) context: Rc<Context>,
274+ display: Rc<Display>,
274275 /// The readback image every frame of this stream reuses.
275276 pub(crate) pool: SurfacePool,
276277 pub(crate) coded_size: (u32, u32),
@@ -364,6 +365,7 @@ impl Session {
364365 pending: std::sync::Mutex::new(None),
365366 poisoned: std::sync::atomic::AtomicBool::new(false),
366367 context,
368+ display: Rc::clone(display),
367369 pool,
368370 coded_size,
369371 display_size,
@@ -372,6 +374,20 @@ impl Session {
372374 })
373375 }
374376
377+ /// A free surface for the next picture. Frames the caller has not taken yet hold
378+ /// their surfaces, so when the pool runs dry it grows by one surface instead of
379+ /// failing the decode.
380+ pub(crate) fn acquire(&self) -> Result<Rc<PooledSurface>> {
381+ if let Some(surface) = self.pool.acquire() {
382+ return Ok(surface);
383+ }
384+ let spec = *self.pool.spec();
385+ self.pool.grow(ec_va::create_pool(&self.display, &spec, 1)?);
386+ self.pool
387+ .acquire()
388+ .ok_or_else(|| Error::config("surface pool empty after growing"))
389+ }
390+
375391 /// Submit one picture: begin, render every buffer, end, then wait for the
376392 /// *previous* picture (depth-1 pipelining).
377393 ///
crates/ec-hw/src/dec/vp9.rsmodified+7 -10
@@ -125,10 +125,7 @@ impl Vp9Decoder {
125125 .session
126126 .as_ref()
127127 .ok_or_else(|| Error::config("VP9 frame before any session"))?;
128- let surface = session
129- .pool
130- .acquire()
131- .ok_or_else(|| Error::config("VP9 decode: every surface is still in use"))?;
128+ let surface = session.acquire()?;
132129
133130 let pic_param = picture_parameters(&header, &slot_ids(&self.refs));
134131 let slice_param = slice_parameters(&header, data.len());
@@ -159,13 +156,13 @@ impl Vp9Decoder {
159156 }
160157
161158 fn ensure_session(&mut self, header: &FrameHeader) -> Result<()> {
162- let profile = match header.profile {
163- 0 => Profile::VP9Profile0,
164- 2 => Profile::VP9Profile2,
165- other => {
159+ let profile = match (header.profile, header.bit_depth) {
160+ (0, 8) => Profile::VP9Profile0,
161+ (2, 10) => Profile::VP9Profile2,
162+ (other, depth) => {
166163 return Err(Error::unsupported(
167- format!("VP9 profile {other}"),
168- "only the 4:2:0 profiles 0 and 2 are decoded in hardware",
164+ format!("VP9 profile {other} at {depth}-bit"),
165+ "VA-API decodes 8-bit profile 0 and 10-bit profile 2 only",
169166 ));
170167 }
171168 };
crates/ec-hw/src/hevc_dpb.rsmodified+10 -0
@@ -10,6 +10,16 @@ use ec_h265_syntax::{NalUnitType, SliceHeader, Sps};
1010
1111 use crate::error::{Error, Result};
1212
13+/// PCI vendor ID of AMD.
14+pub(crate) const AMD_VENDOR_ID: u32 = 0x1002;
15+
16+/// AMD's VCN returns wrong chroma for HEVC with 16x16 coding tree blocks, in the
17+/// firmware, so ffmpeg's VA-API and Vulkan decoders get the same wrong picture. Such
18+/// streams go to software. `amd` is only asked when the CTB size is 16.
19+pub(crate) fn hevc_ctb16_broken(sps: &Sps, amd: impl FnOnce() -> bool) -> bool {
20+ sps.ctb_size() == 16 && amd()
21+}
22+
1323 /// Reference marking of a stored picture (8.3.2).
1424 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1525 pub(crate) enum Mark {
crates/ec-hw/src/pool.rsmodified+15 -4
@@ -17,7 +17,7 @@ use std::sync::Mutex;
1717
1818 struct PoolInner {
1919 /// Every surface, in allocation order.
20- all: Vec<Rc<Surface>>,
20+ all: Mutex<Vec<Rc<Surface>>>,
2121 free: Mutex<Vec<Rc<Surface>>>,
2222 }
2323
@@ -37,7 +37,7 @@ impl SurfacePool {
3737 SurfacePool {
3838 inner: Rc::new(PoolInner {
3939 free: Mutex::new(all.clone()),
40- all,
40+ all: Mutex::new(all),
4141 }),
4242 spec: *spec,
4343 }
@@ -50,12 +50,23 @@ impl SurfacePool {
5050
5151 /// Total surfaces in the pool.
5252 pub fn len(&self) -> usize {
53- self.inner.all.len()
53+ self.inner.all.lock().map(|all| all.len()).unwrap_or(0)
5454 }
5555
5656 /// True when the pool holds no surfaces at all.
5757 pub fn is_empty(&self) -> bool {
58- self.inner.all.is_empty()
58+ self.len() == 0
59+ }
60+
61+ /// Add surfaces allocated with the pool's spec, free for [`SurfacePool::acquire`].
62+ pub fn grow(&self, surfaces: Vec<Surface>) {
63+ let surfaces: Vec<Rc<Surface>> = surfaces.into_iter().map(Rc::new).collect();
64+ if let Ok(mut all) = self.inner.all.lock() {
65+ all.extend(surfaces.iter().cloned());
66+ }
67+ if let Ok(mut free) = self.inner.free.lock() {
68+ free.extend(surfaces);
69+ }
5970 }
6071
6172 /// Surfaces currently available.
crates/ec-hw/src/vkdec264.rsmodified+21 -5
@@ -31,6 +31,7 @@ struct Session {
3131 max_width: u32,
3232 max_height: u32,
3333 slots: u32,
34+ chroma_format_idc: u8,
3435 }
3536
3637 struct Current {
@@ -225,18 +226,31 @@ impl VkH264Decoder {
225226 }
226227
227228 fn ensure_session(&mut self, sps: &Sps) -> Result<()> {
228- if sps.chroma_format_idc != 1 || sps.bit_depth_luma != 8 || sps.bit_depth_chroma != 8 {
229+ if !matches!(sps.chroma_format_idc, 0 | 1)
230+ || sps.bit_depth_luma != 8
231+ || sps.bit_depth_chroma != 8
232+ {
229233 return Err(Error::unsupported(
230234 "Vulkan H.264 decode",
231- "only 8-bit 4:2:0",
235+ "only 8-bit 4:0:0 and 4:2:0",
232236 ));
233237 }
238+ let chroma = sps.chroma_format_idc;
234239 let slots = (self.dpb.capacity() as u32 + 1).min(MAX_SLOTS);
235240 let (w, h) = (sps.coded_width, sps.coded_height);
236241 let (max_width, max_height, slots) = match &self.session {
237- Some(s) if w <= s.max_width && h <= s.max_height && slots <= s.slots => return Ok(()),
238- Some(s) => (w.max(s.max_width), h.max(s.max_height), slots.max(s.slots)),
239- None => (w, h, slots),
242+ Some(s)
243+ if s.chroma_format_idc == chroma
244+ && w <= s.max_width
245+ && h <= s.max_height
246+ && slots <= s.slots =>
247+ {
248+ return Ok(());
249+ }
250+ Some(s) if s.chroma_format_idc == chroma => {
251+ (w.max(s.max_width), h.max(s.max_height), slots.max(s.slots))
252+ }
253+ _ => (w, h, slots),
240254 };
241255 self.current = None;
242256 self.dpb.clear();
@@ -249,6 +263,7 @@ impl VkH264Decoder {
249263 max_height,
250264 max_dpb_slots: slots,
251265 profile_idc: sps.profile_idc,
266+ chroma_format_idc: chroma,
252267 },
253268 )?;
254269 let ring = Ring::new(h264.ring_len());
@@ -258,6 +273,7 @@ impl VkH264Decoder {
258273 max_width,
259274 max_height,
260275 slots,
276+ chroma_format_idc: chroma,
261277 });
262278 self.params_dirty = true;
263279 Ok(())
crates/ec-hw/src/vkdec265.rsmodified+8 -2
@@ -15,8 +15,8 @@ use ec_vk::{
1515
1616 use crate::error::{Error, Result};
1717 use crate::hevc_dpb::{
18- self, Dpb, Mark, is_bla_picture, is_leading_picture, is_rasl_picture, is_reference_picture,
19- peek_pps_id, vui_colour_tags,
18+ self, AMD_VENDOR_ID, Dpb, Mark, hevc_ctb16_broken, is_bla_picture, is_leading_picture,
19+ is_rasl_picture, is_reference_picture, peek_pps_id, vui_colour_tags,
2020 };
2121 use ec_core::color::{ColorDescription, Tags};
2222
@@ -219,6 +219,12 @@ impl VkH265Decoder {
219219 }
220220
221221 fn ensure_session(&mut self, sps: &Sps) -> Result<()> {
222+ if hevc_ctb16_broken(sps, || self.gpu.vendor_id() == AMD_VENDOR_ID) {
223+ return Err(Error::unsupported(
224+ "Vulkan H.265 decode",
225+ "16x16 CTBs on AMD decode with wrong chroma",
226+ ));
227+ }
222228 if sps.chroma_format_idc != 1
223229 || sps.bit_depth_luma_minus8 != sps.bit_depth_chroma_minus8
224230 || !matches!(sps.bit_depth_luma_minus8, 0 | 2)
shims/vk-video-ffi/examples/h264_decode_smoke.rsmodified+1 -0
@@ -136,6 +136,7 @@ fn main() {
136136 max_height: sps.coded_height,
137137 max_dpb_slots: 2,
138138 profile_idc: sps.profile_idc,
139+ chroma_format_idc: sps.chroma_format_idc,
139140 };
140141 let mut session = H264DecodeSession::new(&gpu, &cfg).expect("decode session");
141142 session
shims/vk-video-ffi/src/h264_decode.rsmodified+16 -3
@@ -19,6 +19,8 @@ pub struct H264DecodeConfig {
1919 pub max_dpb_slots: u32,
2020 /// profile_idc: 66, 77 or 100.
2121 pub profile_idc: u8,
22+ /// chroma_format_idc: 0 for monochrome, 1 for 4:2:0.
23+ pub chroma_format_idc: u8,
2224 }
2325
2426 /// Scaling lists in bitstream (zigzag) order, fall-back rules already applied.
@@ -173,11 +175,16 @@ struct Profile {
173175 }
174176
175177 impl Profile {
176- fn new(idc: u8) -> Box<Self> {
178+ fn new(idc: u8, chroma_format_idc: u8) -> Box<Self> {
179+ let chroma = if chroma_format_idc == 0 {
180+ vk::VideoChromaSubsamplingFlagsKHR::MONOCHROME
181+ } else {
182+ vk::VideoChromaSubsamplingFlagsKHR::_420
183+ };
177184 let mut p = Box::new(Profile {
178185 info: vk::VideoProfileInfoKHR::builder()
179186 .video_codec_operation(vk::VideoCodecOperationFlagsKHR::DECODE_H264)
180- .chroma_subsampling(vk::VideoChromaSubsamplingFlagsKHR::_420)
187+ .chroma_subsampling(chroma)
181188 .luma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8)
182189 .chroma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8)
183190 .build(),
@@ -200,6 +207,12 @@ pub struct H264DecodeSession {
200207 impl H264DecodeSession {
201208 /// Creates a session with its DPB, bitstream and readback buffers.
202209 pub fn new(gpu: &Gpu, cfg: &H264DecodeConfig) -> Result<Self, Error> {
210+ if !matches!(cfg.chroma_format_idc, 0 | 1) {
211+ return Err(Error::Invalid(format!(
212+ "H.264 chroma_format_idc {}",
213+ cfg.chroma_format_idc
214+ )));
215+ }
203216 if !matches!(cfg.profile_idc, 66 | 77 | 100) {
204217 return Err(Error::Invalid(format!(
205218 "H.264 profile_idc {}",
@@ -226,7 +239,7 @@ impl H264DecodeSession {
226239 }
227240 let width = align(cfg.max_width, 16);
228241 let height = align(cfg.max_height, 16);
229- let profile = Profile::new(cfg.profile_idc);
242+ let profile = Profile::new(cfg.profile_idc, cfg.chroma_format_idc);
230243 let caps = query_caps(gpu, &profile.info)?;
231244 if width > caps.max_extent.width
232245 || height > caps.max_extent.height
shims/vk-video-ffi/src/h265_decode.rsmodified+11 -12
@@ -442,10 +442,10 @@ impl H265DecodeSession {
442442 let gpu = self.dec.vs.gpu.clone();
443443 let d = gpu.device();
444444
445- let vps_ptl = vps
445+ let vps_ptl: Vec<_> = vps
446446 .iter()
447- .map(|v| std_ptl(&v.profile_tier_level).map(Box::new))
448- .collect::<Result<Vec<_>, Error>>()?;
447+ .map(|v| Box::new(std_ptl(&v.profile_tier_level)))
448+ .collect();
449449 let vps_dpbm: Vec<_> = vps
450450 .iter()
451451 .map(|v| Box::new(std_dpbm(&v.dec_pic_buf_mgr)))
@@ -457,10 +457,10 @@ impl H265DecodeSession {
457457 .map(|((v, ptl), dpbm)| std_vps(v, ptl, dpbm))
458458 .collect();
459459
460- let sps_ptl = sps
460+ let sps_ptl: Vec<_> = sps
461461 .iter()
462- .map(|s| std_ptl(&s.profile_tier_level).map(Box::new))
463- .collect::<Result<Vec<_>, Error>>()?;
462+ .map(|s| Box::new(std_ptl(&s.profile_tier_level)))
463+ .collect();
464464 let sps_dpbm: Vec<_> = sps
465465 .iter()
466466 .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
775775 info
776776 }
777777
778-fn level(idc: u8) -> Result<vk::video::StdVideoH265LevelIdc, Error> {
778+fn level(idc: u8) -> vk::video::StdVideoH265LevelIdc {
779779 use vk::video::*;
780780 let table = [
781781 (30, STD_VIDEO_H265_LEVEL_IDC_1_0),
@@ -795,11 +795,10 @@ fn level(idc: u8) -> Result<vk::video::StdVideoH265LevelIdc, Error> {
795795 table
796796 .into_iter()
797797 .find(|&(v, _)| v == idc)
798- .map(|(_, level)| level)
799- .ok_or_else(|| Error::Invalid(format!("H.265 level_idc {idc}")))
798+ .map_or(STD_VIDEO_H265_LEVEL_IDC_6_2, |(_, level)| level)
800799 }
801800
802-fn std_ptl(p: &H265ProfileTierLevel) -> Result<vk::video::StdVideoH265ProfileTierLevel, Error> {
801+fn std_ptl(p: &H265ProfileTierLevel) -> vk::video::StdVideoH265ProfileTierLevel {
803802 let mut out = zeroed::<vk::video::StdVideoH265ProfileTierLevel>();
804803 out.flags.set_general_tier_flag(p.tier_flag as u32);
805804 out.flags
@@ -811,8 +810,8 @@ fn std_ptl(p: &H265ProfileTierLevel) -> Result<vk::video::StdVideoH265ProfileTie
811810 out.flags
812811 .set_general_frame_only_constraint_flag(p.frame_only_constraint as u32);
813812 out.general_profile_idc = vk::video::StdVideoH265ProfileIdc(p.profile_idc as i32);
814- out.general_level_idc = level(p.level_idc)?;
815- Ok(out)
813+ out.general_level_idc = level(p.level_idc);
814+ out
816815 }
817816
818817 fn std_dpbm(d: &H265DecPicBufMgr) -> vk::video::StdVideoH265DecPicBufMgr {
shims/vk-video-ffi/src/lib.rsmodified+12 -7
@@ -188,6 +188,7 @@ struct Inner {
188188 instance: Instance,
189189 physical: vk::PhysicalDevice,
190190 name: String,
191+ vendor_id: u32,
191192 encode: Option<u32>,
192193 decode: Option<u32>,
193194 graphics: Option<u32>,
@@ -218,7 +219,7 @@ fn queue_families(instance: &Instance, physical: vk::PhysicalDevice) -> Families
218219 }
219220 }
220221
221-fn setup(instance: &Instance) -> Result<(vk::PhysicalDevice, Device, String, Families), Error> {
222+fn setup(instance: &Instance) -> Result<(vk::PhysicalDevice, Device, String, u32, Families), Error> {
222223 let devices = unsafe { instance.enumerate_physical_devices() }
223224 .map_err(|c| crate::session::vk_error(c, "vkEnumeratePhysicalDevices"))?;
224225 let (physical, families) = devices
@@ -283,11 +284,9 @@ fn setup(instance: &Instance) -> Result<(vk::PhysicalDevice, Device, String, Fam
283284 let device = unsafe { instance.create_device(physical, &info, None) }
284285 .map_err(|c| crate::session::vk_error(c, "vkCreateDevice"))?;
285286
286- let name = unsafe { instance.get_physical_device_properties(physical) }
287- .device_name
288- .to_string_lossy()
289- .into_owned();
290- Ok((physical, device, name, families))
287+ let properties = unsafe { instance.get_physical_device_properties(physical) };
288+ let name = properties.device_name.to_string_lossy().into_owned();
289+ Ok((physical, device, name, properties.vendor_id, families))
291290 }
292291
293292 impl Gpu {
@@ -306,12 +305,13 @@ impl Gpu {
306305 let instance = unsafe { entry.create_instance(&info, None) }
307306 .map_err(|c| crate::session::vk_error(c, "vkCreateInstance"))?;
308307 match setup(&instance) {
309- Ok((physical, device, name, families)) => Ok(Gpu {
308+ Ok((physical, device, name, vendor_id, families)) => Ok(Gpu {
310309 inner: Arc::new(Inner {
311310 device,
312311 instance,
313312 physical,
314313 name,
314+ vendor_id,
315315 encode: families.encode,
316316 decode: families.decode,
317317 graphics: families.graphics,
@@ -330,6 +330,11 @@ impl Gpu {
330330 self.inner.name.clone()
331331 }
332332
333+ /// PCI vendor ID of the device, 0x1002 for AMD.
334+ pub fn vendor_id(&self) -> u32 {
335+ self.inner.vendor_id
336+ }
337+
333338 /// Vulkan instance, physical device and device, for examples that build their own images.
334339 #[doc(hidden)]
335340 pub fn vulkan(&self) -> (&Instance, vk::PhysicalDevice, &Device) {