diff --git a/crates/reims-vgpu-video/examples/hevc-framemd5.rs b/crates/reims-vgpu-video/examples/hevc-framemd5.rs index a5ecdb9b1..50908cf2d 100644 --- a/crates/reims-vgpu-video/examples/hevc-framemd5.rs +++ b/crates/reims-vgpu-video/examples/hevc-framemd5.rs @@ -1,11 +1,15 @@ //! Decodes an HEVC stream with [`reims_vgpu_video::vaapi::HevcDecoder`] and //! prints each frame's MD5 over its planes, packed, in the order the -//! decoder emits them: NV12 for Main, P010 (little-endian 16-bit samples) -//! for Main 10, and for 4:4:4 at 8 bits, which the decoder lands -//! ([`HevcDecoder::lands_4_4_4`]), luma then interleaved Cb and Cr each as -//! large, ffmpeg's NV24. With display order this is what `ffmpeg -f framemd5 -//! -pix_fmt nv12` (or `p010le`, or `nv24`) prints for the same stream, so a -//! software decode is the reference (tools/hevc-check.sh). +//! decoder emits them: luma, then interleaved Cb and Cr, in the two planes a +//! VideoToolbox decoder's picture lands in: NV12 for Main, P010 (little-endian +//! 16-bit samples) for Main 10, and for the range extensions, which the +//! decoder lands ([`HevcDecoder::lands_range_extensions`]), P012 for 4:2:0 at +//! 12 bits, NV16, P210 and P212 for 4:2:2 at 8, 10 and 12 bits (chroma as tall +//! as luma), and NV24, P410 and P412 for 4:4:4 (chroma as wide and tall). With +//! display order this is what `ffmpeg -f framemd5 -pix_fmt nv12` (or `p010le`, +//! `p012le`, `nv16`, `p210le`, `p212le`, `nv24`, `p410le` or `p412le`) prints +//! for the same stream, so a software decode is the reference +//! (tools/hevc-check.sh). //! //! ```sh //! hevc-framemd5 /dev/dri/renderD128 stream.mp4 [options] @@ -66,6 +70,7 @@ mod decode { use reims_vgpu_video::codec::h264::nal::LengthPrefixed; use reims_vgpu_video::codec::hevc::{self, OutputOrder, hvcc::DecoderConfiguration, nal}; + use reims_vgpu_video::core::backend::Chroma; use reims_vgpu_video::vaapi::{Display, Error, Frame, HevcDecoder, PlaneRows}; use super::md5::{Md5, self_test}; @@ -156,42 +161,38 @@ mod decode { let sample = if frame.bit_depth() > 8 { 2 } else { 1 }; self.bit_depth = frame.bit_depth(); let (w, h) = (frame.width() as usize * sample, frame.height() as usize); - // 4:4:4's chroma rows hold a Cb and a Cr a pixel, each as many rows as luma's. - let (uv_w, uv_h) = if frame.is_4_4_4() { - (2 * w, h) - } else { - (w, h / 2) + // 4:4:4's chroma rows hold a Cb and a Cr a pixel, each as many rows as luma's; 4:2:2's + // a pair for each two pixels, as many rows; 4:2:0's a pair for each two, half as many. + let pairs = (frame.width() as usize).div_ceil(2) * 2 * sample; + let (uv_w, uv_h) = match frame.chroma() { + Chroma::Yuv444 => (2 * w, h), + Chroma::Yuv422 => (pairs, h), + Chroma::Yuv420 => (w, h / 2), }; let (stride, uv_stride) = (w + self.pad, uv_w + self.pad); self.y.resize(stride * h, 0); self.uv.resize(uv_stride * uv_h, 0); let start = StdRuntime.now(); - if frame.is_4_4_4() { - let back = frame.read_back().map_err(|e| e.to_string())?; - back.copy_4_4_4_into( - PlaneRows { - bytes: &mut self.y, - bytes_per_row: stride, - rows: h, - row_bytes: w, - }, - PlaneRows { - bytes: &mut self.uv, - bytes_per_row: uv_stride, - rows: uv_h, - row_bytes: uv_w, - }, - ) - .map_err(|e| e.to_string())?; + let back = frame.read_back().map_err(|e| e.to_string())?; + let y = PlaneRows { + bytes: &mut self.y, + bytes_per_row: stride, + rows: h, + row_bytes: w, + }; + let uv = PlaneRows { + bytes: &mut self.uv, + bytes_per_row: uv_stride, + rows: uv_h, + row_bytes: uv_w, + }; + if frame.is_packed() { + back.copy_packed_into(y, uv) } else { - let copy = if sample == 2 { - Frame::copy_p010_to - } else { - Frame::copy_nv12_to - }; - copy(frame, &mut self.y, stride, &mut self.uv, uv_stride) - .map_err(|e| e.to_string())?; + back.copy_into(y, uv) } + .map_err(|e| e.to_string())?; + drop(back); self.readback += StdRuntime.elapsed_since(start); self.stages = frame.readback_times(); let mut md5 = Md5::new(); @@ -255,7 +256,7 @@ mod decode { units.into_iter().map(<[u8]>::to_vec).collect(), ) }; - decoder.lands_4_4_4(); + decoder.lands_range_extensions(); decoder.set_output_order(options.order); let mut reader = Reader { y: Vec::new(), diff --git a/crates/reims-vgpu-video/src/codec/hevc.rs b/crates/reims-vgpu-video/src/codec/hevc.rs index 63ad519e3..a64cd4176 100644 --- a/crates/reims-vgpu-video/src/codec/hevc.rs +++ b/crates/reims-vgpu-video/src/codec/hevc.rs @@ -28,7 +28,7 @@ pub(crate) mod tests; pub use crate::codec::h264::{NalFormat, OutputOrder}; pub use decoder::{ Accelerator, Decoder, MIN_TILE_COLUMN_WIDTH, Output, PictureParams, ReferencePicture, - RpsMembership, SliceParams, check_supported, + RpsMembership, SliceParams, check_supported, is_range_extensions, }; /// Why a stream could not be read or decoded. diff --git a/crates/reims-vgpu-video/src/codec/hevc/decoder.rs b/crates/reims-vgpu-video/src/codec/hevc/decoder.rs index b98b16b47..b434dfd76 100644 --- a/crates/reims-vgpu-video/src/codec/hevc/decoder.rs +++ b/crates/reims-vgpu-video/src/codec/hevc/decoder.rs @@ -134,9 +134,9 @@ pub trait Accelerator { /// decoded: 4:2:0 at 8 or 10 bits, with tiles, wavefront parallel /// processing, dependent slice segments, scaling lists, weighted /// prediction and long-term references; and the range extensions' streams -/// at 4:4:4 and 8 bits, with their tools but extended precision. Other -/// chroma formats and bit depths, and the screen content extensions, are -/// refused with [`Error::Unsupported`] ([`check_supported`]). +/// at 4:2:0, 4:2:2 and 4:4:4 and 8, 10 and 12 bits, with their tools but +/// extended precision. Monochrome, other bit depths, and the screen content +/// extensions, are refused with [`Error::Unsupported`] ([`check_supported`]). /// /// Errors follow Apple's HEVC decoder: after a sample that does not /// decode, each picture is refused with [`Error::Unrecovered`] until an @@ -786,9 +786,11 @@ fn same_but_vui(a: &Sps, b: &Sps) -> bool { /// (Main, Main 10, Main Still Picture, or a stream compatible with one), /// 4:2:0 at 8 or 10 bits alike for luma and chroma, without the range or /// screen content extensions; or a stream of the range extensions' profiles -/// (A.3.5) at 4:4:4 and 8 bits, with their tools but extended precision. -/// Whether the host's decoder takes it is the accelerator's to say, from its -/// driver's answers: this is what the codec builds for. +/// (A.3.5) at 4:2:0, 4:2:2 or 4:4:4 and 8, 10 or 12 bits alike for luma and +/// chroma, with their tools but extended precision, and high precision +/// weighted prediction offsets at 8 bits alone. Whether the host's decoder +/// takes it is the accelerator's to say, from its driver's answers: this is +/// what the codec builds for. pub fn check_supported(sps: &Sps) -> Result<(), Error> { let ptl = &sps.profile_tier_level; let main = matches!(ptl.general_profile_idc, 1..=3) || (1..=3).any(|p| ptl.compatible_with(p)); @@ -811,14 +813,9 @@ pub fn check_supported(sps: &Sps) -> Result<(), Error> { if sps.sps_scc_extension_flag { return Err(Error::Unsupported("screen content coding")); } - if range_extensions && sps.chroma_format_idc == 3 { + if is_range_extensions(sps) { return check_range_extensions(sps); } - if !main { - return Err(Error::Unsupported( - "range extensions streams other than 4:4:4 at 8 bits", - )); - } if sps.chroma_format_idc != 1 { return Err(Error::Unsupported("chroma formats other than 4:2:0")); } @@ -831,14 +828,31 @@ pub fn check_supported(sps: &Sps) -> Result<(), Error> { Ok(()) } -/// [`check_supported`] for a 4:4:4 stream of the range extensions' profiles: -/// 8 bits, its three planes coded together, its SPS read to its range -/// extensions, and every tool of theirs but extended precision processing, -/// which A.3.5 allows only in its 16-bit profiles. +/// Whether `sps`'s stream is decoded as the range extensions' ([`check_supported`]): one of +/// their profiles, but a stream also of the Main family that is 4:2:0 and turns on none of their +/// tools, which decodes as Main's. A decoder of a range extensions stream takes the range +/// extensions' parameters (VA-API's range extensions profiles and their structures). +pub fn is_range_extensions(sps: &Sps) -> bool { + let ptl = &sps.profile_tier_level; + let main = matches!(ptl.general_profile_idc, 1..=3) || (1..=3).any(|p| ptl.compatible_with(p)); + let range_extensions = ptl.general_profile_idc == 4 || ptl.compatible_with(4); + range_extensions && !(main && sps.chroma_format_idc == 1 && !sps.sps_range_extension_flag) +} + +/// [`check_supported`] for a stream of the range extensions' profiles: 4:2:0, +/// 4:2:2 or 4:4:4 at 8, 10 or 12 bits, its planes coded together, its SPS +/// read to its range extensions, and every tool of theirs but extended +/// precision processing, which A.3.5 allows only in its 16-bit profiles, and +/// high precision weighted prediction offsets past 8 bits, whose offsets +/// the slice header's parse holds to 8 bits' range (`slice`'s +/// `pred_weight_table`). fn check_range_extensions(sps: &Sps) -> Result<(), Error> { - if sps.bit_depth_luma_minus8 != 0 { + if sps.chroma_format_idc == 0 { + return Err(Error::Unsupported("monochrome")); + } + if !matches!(sps.bit_depth_luma_minus8, 0 | 2 | 4) { return Err(Error::Unsupported( - "range extensions streams other than 4:4:4 at 8 bits", + "range extensions streams of depths other than 8, 10 and 12 bits", )); } if sps.separate_colour_plane_flag { @@ -847,9 +861,15 @@ fn check_range_extensions(sps: &Sps) -> Result<(), Error> { if sps.extensions_unread { return Err(Error::Unsupported("range extensions an SPS's VUI hides")); } - if sps.range_extension.extended_precision_processing_flag { + let tools = &sps.range_extension; + if tools.extended_precision_processing_flag { return Err(Error::Unsupported("extended precision processing")); } + if tools.high_precision_offsets_enabled_flag && sps.bit_depth_luma_minus8 > 0 { + return Err(Error::Unsupported( + "high precision weighted prediction offsets past 8 bits", + )); + } Ok(()) } @@ -859,8 +879,8 @@ fn check_range_extensions(sps: &Sps) -> Result<(), Error> { /// the SPS within them. fn check_pps_supported(pps: &Pps, sps: &Sps) -> Result<(), Error> { if pps.pps_range_extension_flag { - // 4:2:0: a Main family SPS, the one of 4:2:0 `check_supported` takes. - if sps.chroma_format_idc == 1 { + // A Main family SPS, which `check_supported` takes without the range extensions. + if !is_range_extensions(sps) { return Err(Error::Unsupported("the range extensions")); } check_pps_range_extension(&pps.range_extension, sps)?; diff --git a/crates/reims-vgpu-video/src/codec/hevc/tests.rs b/crates/reims-vgpu-video/src/codec/hevc/tests.rs index bdee5b32d..07e8a8dec 100644 --- a/crates/reims-vgpu-video/src/codec/hevc/tests.rs +++ b/crates/reims-vgpu-video/src/codec/hevc/tests.rs @@ -143,6 +143,9 @@ fn write_set(w: &mut BitWriter, index: usize, count: usize, set: &Set) { #[derive(Clone)] struct SpsSpec { profile_idc: u8, + /// A profile whose `general_profile_compatibility_flag` is set beside + /// `profile_idc`'s. + also_compatible: Option, chroma_format_idc: u32, bit_depth_minus8: u32, /// `log2_max_pic_order_cnt_lsb_minus4`. @@ -185,6 +188,7 @@ impl Default for SpsSpec { fn default() -> Self { Self { profile_idc: 1, + also_compatible: None, chroma_format_idc: 1, bit_depth_minus8: 0, lsb_minus4: 4, @@ -212,7 +216,8 @@ fn sps(spec: &SpsSpec) -> Vec { w.u(4, 0).u(3, 0).bit(true); // profile_tier_level(1, 0) w.u(2, 0).bit(false).u(5, u32::from(spec.profile_idc)); - w.u(32, 1 << (31 - u32::from(spec.profile_idc))); + let also = spec.also_compatible.map_or(0, |p| 1 << (31 - u32::from(p))); + w.u(32, 1 << (31 - u32::from(spec.profile_idc)) | also); w.bit(true) .bit(false) .bit(false) @@ -1811,23 +1816,25 @@ fn what_the_codec_does_not_build_for_is_refused() { "unsupported: profiles outside Main, Main 10, Main Still Picture and the range \ extensions", ), + (range_extensions(0, 0, 0), "unsupported: monochrome"), ( - range_extensions(2, 0, 0), - "unsupported: range extensions streams other than 4:4:4 at 8 bits", + range_extensions(3, 6, 0), + "unsupported: range extensions streams of depths other than 8, 10 and 12 bits", ), ( - range_extensions(3, 2, 0), - "unsupported: range extensions streams other than 4:4:4 at 8 bits", - ), - ( - range_extensions(0, 0, 0), - "unsupported: range extensions streams other than 4:4:4 at 8 bits", + range_extensions(2, 8, 0), + "unsupported: range extensions streams of depths other than 8, 10 and 12 bits", ), ( // extended_precision_processing_flag, the fifth. range_extensions(3, 0, 1 << 4), "unsupported: extended precision processing", ), + ( + // high_precision_offsets_enabled_flag, the seventh, past 8 bits. + range_extensions(2, 2, 1 << 2), + "unsupported: high precision weighted prediction offsets past 8 bits", + ), ( SpsSpec { chroma_format_idc: 2, @@ -1934,6 +1941,147 @@ fn a_range_extensions_444_stream_at_8_bits_decodes() -> Result<(), Error> { Ok(()) } +#[test] +fn range_extensions_streams_of_each_chroma_format_and_depth_decode() -> Result<(), Error> { + // Every tool of the SPS's range extensions but extended precision (the + // fifth of nine flags) and, past 8 bits, high precision offsets (the + // seventh). + for chroma_format_idc in 1..=3 { + for bit_depth_minus8 in [0, 2, 4] { + let range_tools = if bit_depth_minus8 == 0 { + 0b1_1110_1111 + } else { + 0b1_1110_1011 + }; + let spec = SpsSpec { + profile_idc: 4, + chroma_format_idc, + bit_depth_minus8, + range_extension: true, + range_tools, + ..SpsSpec::default() + }; + let pps_spec = PpsSpec { + transform_skip: true, + range_extension: Some(pps::PpsRangeExtension { + log2_max_transform_skip_block_size_minus2: 1, + cross_component_prediction_enabled_flag: chroma_format_idc == 3, + ..pps::PpsRangeExtension::default() + }), + ..PpsSpec::default() + }; + let parsed = sps::Sps::parse(&sps(&spec))?; + assert!(is_range_extensions(&parsed)); + let idr = slice( + &spec, + &pps_spec, + &SliceSpec { + unit_type: nal_type::IDR_W_RADL, + ..SliceSpec::default() + }, + ); + let mut d = decoder(); + let out = d.decode(&sample(&[sps(&spec), pps(&pps_spec), idr]), 3)?; + let depth = 8 + bit_depth_minus8 as u8; + assert_eq!(d.accelerator().configured, [(64, 48, depth, 5)]); + // The conformance window's one unit at the bottom: two rows of 4:2:0, + // one of 4:2:2 and 4:4:4 (SubHeightC). + let rows = if chroma_format_idc == 1 { 46 } else { 47 }; + assert_eq!( + (out.len(), out[0].bit_depth, out[0].crop), + (1, depth, (0, 0, 64, rows)), + "chroma_format_idc {chroma_format_idc}, {depth} bits" + ); + } + } + Ok(()) +} + +#[test] +fn a_range_extensions_sps_cut_short_or_with_a_bit_flipped_is_refused_or_decoded_whole() { + // Every prefix of a range extensions SPS of each chroma format and depth, and the SPS with + // each bit past its NAL header flipped, before a PPS and an IDR slice: the decoder answers + // each, an error or pictures of the size and depth the SPS it read gives, and panics on none. + let pps_spec = PpsSpec::default(); + for chroma_format_idc in 1..=3 { + for bit_depth_minus8 in [0, 2, 4] { + let spec = SpsSpec { + profile_idc: 4, + chroma_format_idc, + bit_depth_minus8, + range_extension: true, + range_tools: 0b1_1110_1011, + ..SpsSpec::default() + }; + let whole = sps(&spec); + let idr = slice( + &spec, + &pps_spec, + &SliceSpec { + unit_type: nal_type::IDR_W_RADL, + ..SliceSpec::default() + }, + ); + let mut units: Vec> = (2..whole.len()).map(|n| whole[..n].to_vec()).collect(); + for bit in 16..whole.len() * 8 { + let mut flipped = whole.clone(); + flipped[bit / 8] ^= 0x80 >> (bit % 8); + units.push(flipped); + } + for unit in units { + let read = sps::Sps::parse(&unit).ok(); + let mut d = decoder(); + let result = d.decode(&sample(&[unit, pps(&pps_spec), idr.clone()]), 0); + if let Ok(out) = result { + for picture in out { + let read = read + .as_ref() + .expect("a picture decoded from an SPS that reads"); + assert_eq!(picture.bit_depth, read.bit_depth_luma_minus8 + 8); + assert!(picture.crop.2 <= read.pic_width_in_luma_samples); + assert!(picture.crop.3 <= read.pic_height_in_luma_samples); + } + } + } + } + } +} + +#[test] +fn a_main_family_stream_decodes_as_main_unless_it_turns_the_range_extensions_on() +-> Result<(), Error> { + // A stream of profile 4 that says it is also Main 10's, 4:2:0, with no range extensions: + // Main 10's, as a decoder of Main 10 takes it. + let compatible = SpsSpec { + profile_idc: 4, + also_compatible: Some(2), + bit_depth_minus8: 2, + ..SpsSpec::default() + }; + assert!(!is_range_extensions(&sps::Sps::parse(&sps(&compatible))?)); + // With its range extensions' SPS syntax, or of 4:2:2, the range extensions'. + for spec in [ + SpsSpec { + range_extension: true, + ..compatible.clone() + }, + SpsSpec { + chroma_format_idc: 2, + ..compatible.clone() + }, + ] { + assert!(is_range_extensions(&sps::Sps::parse(&sps(&spec))?)); + } + // A Main 10 stream is no range extensions stream. + let main_10 = SpsSpec { + profile_idc: 2, + bit_depth_minus8: 2, + ..SpsSpec::default() + }; + assert!(!is_range_extensions(&sps::Sps::parse(&sps(&main_10))?)); + Ok(()) +} + #[test] fn a_pps_of_the_range_extensions_is_held_to_its_sps() { let spec = SpsSpec { diff --git a/crates/reims-vgpu-video/src/core/backend.rs b/crates/reims-vgpu-video/src/core/backend.rs index 99e486aae..b118d1231 100644 --- a/crates/reims-vgpu-video/src/core/backend.rs +++ b/crates/reims-vgpu-video/src/core/backend.rs @@ -6,7 +6,12 @@ use crate::core::fourcc::FourCc; /// A pixel format the host decodes into: the CoreVideo formats a guest -/// pixel buffer can have. +/// pixel buffer can have, each of two planes, luma then interleaved Cb and +/// Cr, deeper samples in the top bits of 16. Past HEVC Main 10's they are +/// the formats an arm64 guest's own software decoder lands each chroma +/// format and depth in (CoreVideo's descriptions name `tv20`, `tv22` and +/// `tv44` 12 bits a component, video range, black at 0x1000; **measured** +/// on an M3 Max, macOS 27.0.1, potluck jobs m3-max-77228, 77231 and 77237). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum PixelFormat { /// 8-bit 4:2:0, Y then interleaved CbCr, video range: `420v`. @@ -21,9 +26,106 @@ pub enum PixelFormat { Yuv444VideoRange, /// The same, full range: `444f`. Yuv444FullRange, + /// 8-bit 4:2:2, Y then interleaved CbCr half as wide and as tall, video range: `422v`. + Nv16VideoRange, + /// The same, full range: `422f`. + Nv16FullRange, + /// 10-bit 4:2:2 in 16-bit samples, video range: `x422`. + P210VideoRange, + /// The same, full range: `xf22`. + P210FullRange, + /// 10-bit 4:4:4 in 16-bit samples, video range: `x444`. + P410VideoRange, + /// The same, full range: `xf44`. + P410FullRange, + /// 12-bit 4:2:0 in 16-bit samples, video range: `tv20`. + P012VideoRange, + /// The same, full range: `tf20`. + P012FullRange, + /// 12-bit 4:2:2 in 16-bit samples, video range: `tv22`. + P212VideoRange, + /// The same, full range: `tf22`. + P212FullRange, + /// 12-bit 4:4:4 in 16-bit samples, video range: `tv44`. + P412VideoRange, + /// The same, full range: `tf44`. + P412FullRange, +} + +/// How a [`PixelFormat`]'s chroma plane is sampled against its luma. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Chroma { + /// A Cb and Cr pair for every two columns and two rows. + Yuv420, + /// A pair for every two columns of each row. + Yuv422, + /// A pair for every pixel. + Yuv444, +} + +impl Chroma { + /// The `chroma_format_idc` of its pictures. + pub const fn chroma_format_idc(self) -> u8 { + match self { + Self::Yuv420 => 1, + Self::Yuv422 => 2, + Self::Yuv444 => 3, + } + } + + /// The chroma format of `chroma_format_idc`, of 4:2:0, 4:2:2 and 4:4:4. + pub const fn of_idc(chroma_format_idc: u8) -> Option { + match chroma_format_idc { + 1 => Some(Self::Yuv420), + 2 => Some(Self::Yuv422), + 3 => Some(Self::Yuv444), + _ => None, + } + } + + /// The pairs a chroma row holds and the chroma rows of a picture `width` by `height`: an + /// odd last column or row takes the pair it shares, as CoreVideo's planes have it. + pub fn plane_size(self, width: usize, height: u32) -> (usize, u32) { + match self { + Self::Yuv420 => (width.div_ceil(2), height.div_ceil(2)), + Self::Yuv422 => (width.div_ceil(2), height), + Self::Yuv444 => (width, height), + } + } + + /// Its name, as a refusal spells it. + pub const fn name(self) -> &'static str { + match self { + Self::Yuv420 => "4:2:0", + Self::Yuv422 => "4:2:2", + Self::Yuv444 => "4:4:4", + } + } } impl PixelFormat { + /// Every format. + const ALL: [Self; 18] = [ + Self::Nv12VideoRange, + Self::Nv12FullRange, + Self::P010VideoRange, + Self::P010FullRange, + Self::Yuv444VideoRange, + Self::Yuv444FullRange, + Self::Nv16VideoRange, + Self::Nv16FullRange, + Self::P210VideoRange, + Self::P210FullRange, + Self::P410VideoRange, + Self::P410FullRange, + Self::P012VideoRange, + Self::P012FullRange, + Self::P212VideoRange, + Self::P212FullRange, + Self::P412VideoRange, + Self::P412FullRange, + ]; + /// The CoreVideo pixel format type. pub const fn fourcc(self) -> FourCc { FourCc::new(match self { @@ -33,38 +135,101 @@ impl PixelFormat { Self::P010FullRange => *b"xf20", Self::Yuv444VideoRange => *b"444v", Self::Yuv444FullRange => *b"444f", + Self::Nv16VideoRange => *b"422v", + Self::Nv16FullRange => *b"422f", + Self::P210VideoRange => *b"x422", + Self::P210FullRange => *b"xf22", + Self::P410VideoRange => *b"x444", + Self::P410FullRange => *b"xf44", + Self::P012VideoRange => *b"tv20", + Self::P012FullRange => *b"tf20", + Self::P212VideoRange => *b"tv22", + Self::P212FullRange => *b"tf22", + Self::P412VideoRange => *b"tv44", + Self::P412FullRange => *b"tf44", }) } /// The format a CoreVideo pixel format type names, if it is one of /// these. pub fn from_fourcc(format: FourCc) -> Option { - [ - Self::Nv12VideoRange, - Self::Nv12FullRange, - Self::P010VideoRange, - Self::P010FullRange, - Self::Yuv444VideoRange, - Self::Yuv444FullRange, - ] - .into_iter() - .find(|known| known.fourcc() == format) + Self::ALL.into_iter().find(|known| known.fourcc() == format) } - /// The bytes one sample takes: 1 for 8-bit formats, 2 for 10-bit ones. - pub const fn bytes_per_sample(self) -> usize { + /// The format pictures of `chroma` at `bits` bits land in, by their range: `None` for a + /// depth other than 8, 10 and 12. + pub fn of(chroma: Chroma, bits: u8, full_range: bool) -> Option { + let (video, full) = match (chroma, bits) { + (Chroma::Yuv420, 8) => (Self::Nv12VideoRange, Self::Nv12FullRange), + (Chroma::Yuv420, 10) => (Self::P010VideoRange, Self::P010FullRange), + (Chroma::Yuv420, 12) => (Self::P012VideoRange, Self::P012FullRange), + (Chroma::Yuv422, 8) => (Self::Nv16VideoRange, Self::Nv16FullRange), + (Chroma::Yuv422, 10) => (Self::P210VideoRange, Self::P210FullRange), + (Chroma::Yuv422, 12) => (Self::P212VideoRange, Self::P212FullRange), + (Chroma::Yuv444, 8) => (Self::Yuv444VideoRange, Self::Yuv444FullRange), + (Chroma::Yuv444, 10) => (Self::P410VideoRange, Self::P410FullRange), + (Chroma::Yuv444, 12) => (Self::P412VideoRange, Self::P412FullRange), + _ => return None, + }; + Some(if full_range { full } else { video }) + } + + /// The bits a sample holds: 8, 10 or 12. + pub const fn bit_depth(self) -> u8 { match self { Self::Nv12VideoRange | Self::Nv12FullRange | Self::Yuv444VideoRange - | Self::Yuv444FullRange => 1, - Self::P010VideoRange | Self::P010FullRange => 2, + | Self::Yuv444FullRange + | Self::Nv16VideoRange + | Self::Nv16FullRange => 8, + Self::P010VideoRange + | Self::P010FullRange + | Self::P210VideoRange + | Self::P210FullRange + | Self::P410VideoRange + | Self::P410FullRange => 10, + Self::P012VideoRange + | Self::P012FullRange + | Self::P212VideoRange + | Self::P212FullRange + | Self::P412VideoRange + | Self::P412FullRange => 12, } } - /// Whether its chroma is as wide and tall as its luma (4:4:4), not half each way (4:2:0). + /// The bytes one sample takes: 1 for 8-bit formats, 2 for deeper ones. + pub const fn bytes_per_sample(self) -> usize { + if self.bit_depth() > 8 { 2 } else { 1 } + } + + /// How its chroma is sampled. + pub const fn chroma(self) -> Chroma { + match self { + Self::Nv12VideoRange + | Self::Nv12FullRange + | Self::P010VideoRange + | Self::P010FullRange + | Self::P012VideoRange + | Self::P012FullRange => Chroma::Yuv420, + Self::Nv16VideoRange + | Self::Nv16FullRange + | Self::P210VideoRange + | Self::P210FullRange + | Self::P212VideoRange + | Self::P212FullRange => Chroma::Yuv422, + Self::Yuv444VideoRange + | Self::Yuv444FullRange + | Self::P410VideoRange + | Self::P410FullRange + | Self::P412VideoRange + | Self::P412FullRange => Chroma::Yuv444, + } + } + + /// Whether its chroma is as wide and tall as its luma (4:4:4). pub const fn is_4_4_4(self) -> bool { - matches!(self, Self::Yuv444VideoRange | Self::Yuv444FullRange) + matches!(self.chroma(), Chroma::Yuv444) } } @@ -115,5 +280,39 @@ mod tests { Some(PixelFormat::Yuv444FullRange) ); assert_eq!(PixelFormat::from_fourcc(FourCc::new(*b"BGRA")), None); + for format in PixelFormat::ALL { + assert_eq!(PixelFormat::from_fourcc(format.fourcc()), Some(format)); + } + } + + /// Each chroma format and depth lands in the format an arm64 guest's own software decoder + /// lands it in, by its range (m3-max-77228, 77237): `tv20` for 4:2:0 at 12 bits, `x422` for + /// 4:2:2 at 10, and so on; a depth past 12, or 4:2:0 at 9, in none. + #[test] + fn each_chroma_format_and_depth_lands_in_the_guest_decoders_own_format() { + let fourcc = |chroma, bits, full| PixelFormat::of(chroma, bits, full).map(|f| f.fourcc()); + let cases = [ + (Chroma::Yuv420, 8, *b"420v", *b"420f"), + (Chroma::Yuv420, 10, *b"x420", *b"xf20"), + (Chroma::Yuv420, 12, *b"tv20", *b"tf20"), + (Chroma::Yuv422, 8, *b"422v", *b"422f"), + (Chroma::Yuv422, 10, *b"x422", *b"xf22"), + (Chroma::Yuv422, 12, *b"tv22", *b"tf22"), + (Chroma::Yuv444, 8, *b"444v", *b"444f"), + (Chroma::Yuv444, 10, *b"x444", *b"xf44"), + (Chroma::Yuv444, 12, *b"tv44", *b"tf44"), + ]; + for (chroma, bits, video, full) in cases { + assert_eq!(fourcc(chroma, bits, false), Some(FourCc::new(video))); + assert_eq!(fourcc(chroma, bits, true), Some(FourCc::new(full))); + let format = PixelFormat::of(chroma, bits, false).expect("a format"); + assert_eq!((format.chroma(), format.bit_depth()), (chroma, bits)); + assert_eq!(format.bytes_per_sample(), if bits > 8 { 2 } else { 1 }); + } + assert_eq!(PixelFormat::of(Chroma::Yuv420, 9, false), None); + assert_eq!(PixelFormat::of(Chroma::Yuv444, 16, false), None); + assert_eq!(Chroma::Yuv422.plane_size(1919, 1081), (960, 1081)); + assert_eq!(Chroma::Yuv420.plane_size(1919, 1081), (960, 541)); + assert_eq!(Chroma::Yuv444.plane_size(1919, 1081), (1919, 1081)); } } diff --git a/crates/reims-vgpu-video/src/core/device_memory.rs b/crates/reims-vgpu-video/src/core/device_memory.rs index 026b83252..9ad88d3ef 100644 --- a/crates/reims-vgpu-video/src/core/device_memory.rs +++ b/crates/reims-vgpu-video/src/core/device_memory.rs @@ -269,7 +269,7 @@ pub struct TargetPlane { pub rows: u32, /// The bytes of each row a frame as wide as the surface fills: its /// samples, an interleaved Cb and Cr pair for every two luma samples - /// (4:2:0) or for every one (4:4:4). + /// (4:2:0 and 4:2:2) or for every one (4:4:4). pub row_bytes: usize, } @@ -277,8 +277,8 @@ pub struct TargetPlane { /// layout checked against that memory (module docs). /// /// What [`GuestTarget::new`] checks, so that a device that writes a plane's -/// rows writes inside the surface's allocation and nowhere else: a 4:2:0 -/// or 4:4:4 format in two planes, luma then interleaved chroma, in ascending order +/// rows writes inside the surface's allocation and nowhere else: a 4:2:0, +/// 4:2:2 or 4:4:4 format in two planes, luma then interleaved chroma, in ascending order /// without overlapping, each row at least as long as the plane's samples, /// and the last row of each ending inside the memory. A backend checks besides what /// its driver takes (pitches, alignments, sizes) and how far its device @@ -321,12 +321,9 @@ impl<'a> GuestTarget<'a> { }; let sample = format.bytes_per_sample(); let width = usize::try_from(layout.width).map_err(|_| "too wide".to_owned())?; - // A Cb and Cr pair for every two columns and two rows of 4:2:0, every one of 4:4:4. - let (pairs, chroma_rows) = if format.is_4_4_4() { - (width, layout.height) - } else { - (width.div_ceil(2), layout.height.div_ceil(2)) - }; + // A Cb and Cr pair for every two columns and two rows of 4:2:0, every two columns of + // 4:2:2, every one of 4:4:4. + let (pairs, chroma_rows) = format.chroma().plane_size(width, layout.height); let row_bytes = [width.checked_mul(sample), pairs.checked_mul(2 * sample)]; let rows = [layout.height, chroma_rows]; let length = memory.length(); diff --git a/crates/reims-vgpu-video/src/nvidia/annex_b.rs b/crates/reims-vgpu-video/src/nvidia/annex_b.rs index 23114f714..3f60ddb79 100644 --- a/crates/reims-vgpu-video/src/nvidia/annex_b.rs +++ b/crates/reims-vgpu-video/src/nvidia/annex_b.rs @@ -26,10 +26,10 @@ //! caller asks ([`AnnexBDecoder::copy_failed_pictures`]), it is written or //! read back as NVDEC left it, telling its status, and the pictures after //! it decode, as a Mac's hardware decoders hand them on. -//! - **A 4:4:4 picture** (HEVC's range extensions, where the caller lands -//! them, [`AnnexBDecoder::lands_4_4_4`]) decodes into three planes, luma, -//! Cb and Cr, each as large, which it reads back; its writes, of two -//! planes, refuse it. +//! - **The range extensions' pictures** (HEVC's, where the caller lands +//! them, [`AnnexBDecoder::lands_range_extensions`]): 4:2:0 ones as Main 10's, +//! and 4:4:4 ones into three planes, luma, Cb and Cr, each as large, which +//! it reads back; its writes, of two planes, refuse those. //! - **A picture holds its decode surface** until it drops: the decoder has //! [`AnnexBDecoder::SPARE_PICTURES`] surfaces beyond its references and //! the picture being decoded, and a decode with none free is @@ -61,8 +61,9 @@ use crate::nvidia::wait::Deadline; pub enum AnnexBCodec { /// H.264, of the profiles the codec crate decodes. H264, - /// HEVC, Main and Main 10, and the range extensions' 4:4:4 at 8 bits - /// where the caller lands them ([`AnnexBDecoder::lands_4_4_4`]). + /// HEVC, Main and Main 10, and the range extensions' 4:2:0 and 4:4:4 at + /// 8, 10 and 12 bits where the caller lands them + /// ([`AnnexBDecoder::lands_range_extensions`]). Hevc, } @@ -148,13 +149,14 @@ impl AnnexBDecoder { self.failed = OnFailed::Copy; } - /// Has an HEVC stream's 4:4:4 pictures decoded, each in three planes, - /// which the caller writes or reads back ([`AnnexBPicture::four_four_four`]); - /// without it, a 4:4:4 stream's decoder is refused when its SPS is - /// taken. An H.264 decoder is left as it is. - pub fn lands_4_4_4(&mut self) { + /// Has an HEVC stream of the range extensions decoded: a 4:2:0 one's + /// pictures as Main 10's, a 4:4:4 one's each in three planes, which the + /// caller writes or reads back ([`AnnexBPicture::four_four_four`]); + /// without it, a range extensions stream's decoder is refused when its SPS + /// is taken. An H.264 decoder is left as it is. + pub fn lands_range_extensions(&mut self) { if let Codec::Hevc(decoder) = &mut self.codec { - decoder.accelerator_mut().four_four_four = true; + decoder.accelerator_mut().range_extensions = true; } } @@ -393,7 +395,7 @@ impl AnnexBPicture { } /// Whether it is a 4:4:4 picture, in three planes, luma, Cb and Cr, each - /// as large ([`AnnexBDecoder::lands_4_4_4`]): its read back has the + /// as large ([`AnnexBDecoder::lands_range_extensions`]): its read back has the /// three, its writes of two planes refuse it, and /// [`Self::write_4_4_4_into_device`] takes the three. pub fn four_four_four(&self) -> bool { diff --git a/crates/reims-vgpu-video/src/nvidia/nvdec/hevc.rs b/crates/reims-vgpu-video/src/nvidia/nvdec/hevc.rs index 380a34e55..17a387065 100644 --- a/crates/reims-vgpu-video/src/nvidia/nvdec/hevc.rs +++ b/crates/reims-vgpu-video/src/nvidia/nvdec/hevc.rs @@ -12,10 +12,12 @@ //! dynlink_cuviddec.h names ("scaling lists (diag order)") and the codec //! crate keeps them in. //! -//! The range extensions' streams the codec crate decodes, 4:4:4 at 8 bits, -//! decode into NVDEC's three planes ([`NvdecHevc::four_four_four`]), their -//! tools and chroma QP offset lists in the picture parameters' range -//! extension fields. +//! The range extensions' streams the codec crate decodes, where the caller +//! lands them ([`NvdecHevc::range_extensions`]): 4:2:0 at 8, 10 and 12 bits +//! into NV12 and P016, and 4:4:4 at 8, 10 and 12 bits into NVDEC's three +//! planes, their tools and chroma QP offset lists in the picture parameters' +//! range extension fields. Their 4:2:2 streams decode into no format built +//! here, and are refused. use std::ffi::{c_int, c_ushort}; use std::sync::Arc; @@ -24,7 +26,7 @@ use crate::codec::PictureRole; use crate::codec::hevc::nal::{is_idr, is_irap}; use crate::codec::hevc::pps::Pps; use crate::codec::hevc::sps::Sps; -use crate::codec::hevc::{Accelerator, PictureParams, SliceParams}; +use crate::codec::hevc::{self, Accelerator, PictureParams, SliceParams}; use super::decoder::{ Decoder, DecoderSpec, InPlace, Picture, SPARE_SURFACES, active, surface_count, @@ -40,9 +42,10 @@ pub(crate) struct NvdecHevc { decoder: Option, /// The sample being decoded, for its slices to go to NVDEC in place. pub(crate) in_place: InPlace, - /// Whether its caller lands 4:4:4 pictures, three planes each: a 4:4:4 - /// stream's configure is refused without it. - pub(crate) four_four_four: bool, + /// Whether its caller lands the range extensions' pictures, 4:4:4 ones + /// in three planes each: a range extensions stream's configure is + /// refused without it. + pub(crate) range_extensions: bool, } impl NvdecHevc { @@ -51,7 +54,7 @@ impl NvdecHevc { gpu, decoder: None, in_place: InPlace::default(), - four_four_four: false, + range_extensions: false, } } @@ -61,8 +64,8 @@ impl NvdecHevc { } /// The decoder `sps`'s pictures need, with a DPB of `dpb_size` pictures: 4:4:4 -/// where the SPS's `chroma_format_idc` is 3, else 4:2:0, the one other the codec -/// crate decodes. +/// where the SPS's `chroma_format_idc` is 3, else 4:2:0, the one other the +/// configure takes (it refuses 4:2:2). pub(crate) fn spec(sps: &Sps, dpb_size: usize) -> DecoderSpec { DecoderSpec { codec: NvdecCodec::Hevc, @@ -85,9 +88,15 @@ impl Accelerator for NvdecHevc { fn configure(&mut self, sps: &Sps, dpb_size: usize) -> Result<(), Error> { self.decoder = None; let spec = spec(sps, dpb_size); - if spec.chroma == ChromaFormat::Yuv444 && !self.four_four_four { + if hevc::is_range_extensions(sps) && !self.range_extensions { return Err(Error::Unsupported( - "HEVC 4:4:4: its caller lands 4:2:0 pictures alone".to_owned(), + "HEVC range extensions: its caller lands Main and Main 10 pictures alone" + .to_owned(), + )); + } + if sps.chroma_format_idc == 2 { + return Err(Error::Unsupported( + "HEVC 4:2:2: no NVDEC output of it is built here".to_owned(), )); } self.decoder = Some(Decoder::new(Arc::clone(&self.gpu), &spec)?); diff --git a/crates/reims-vgpu-video/src/paravirt/decoder.rs b/crates/reims-vgpu-video/src/paravirt/decoder.rs index 4e4ee537b..ba1dbb2fa 100644 --- a/crates/reims-vgpu-video/src/paravirt/decoder.rs +++ b/crates/reims-vgpu-video/src/paravirt/decoder.rs @@ -13,16 +13,19 @@ //! a stream whose pictures the host decodes none of, are refused with //! `kVTVideoDecoderUnsupportedDataFormatErr`, an H.264 SPS that lets pictures be fields with //! `kVTVideoDecoderMalfunctionErr`, and the backend refuses what it does not decode, each with -//! no `Dpba`. The host decodes 4:2:0 pictures at 8 bits, HEVC's at 10 too, and HEVC's 4:4:4 -//! pictures at 8 where the arm does, in the profiles and tools the codec's `check_supported` -//! takes, which every arm's decode of a picture checks: a stream of 4:2:2 or monochrome -//! pictures (a HEIC image's alpha), of deeper samples, or of 4:4:4 ones the arm declines -//! ([`Backend::declines`]; a HEIC image's 4:4:4 thumbnail where the arm decodes no 4:4:4) is -//! refused at its start, not at each frame, with a warning that names why, and the stream's +//! no `Dpba`. The host decodes 4:2:0 pictures at 8 bits, HEVC's at 10 too, and HEVC's range +//! extensions pictures (4:2:0, 4:2:2 and 4:4:4 at 8, 10 and 12 bits) where the arm does, in +//! the profiles and tools the codec's `check_supported` takes, which every arm's decode of a +//! picture checks: a stream of monochrome pictures (a HEIC image's alpha), of deeper samples, +//! or of a chroma format and depth the arm declines ([`Backend::declines`], from its own +//! query of the host's decoder; a HEIC image's 4:4:4 thumbnail where the arm decodes no 4:4:4) +//! is refused at its start, not at each frame, with a warning that names why, and the stream's //! profile, chroma format, bit depths and size ([`Undecoded`]). A started session sends `Dpba`, -//! the attributes the guest's output buffers are to have (the two-plane format of its chroma, -//! depth and range: `420v`, `420f`, `x420`, `xf20`, `444v` or `444f`), before its reply. A second -//! `dsta` is answered `kVTVideoDecoderBadDataErr`, and the session goes on as the first left it. +//! the attributes the guest's output buffers are to have: the two-plane CoreVideo format of its +//! chroma, depth and range that the guest's own software decoder lands the stream in +//! ([`PixelFormat::of`]: `420v`, `x420`, `tv20`, `422v`, `x422`, `tv22`, `444v`, `x444`, `tv44` +//! and their full-range twins), before its reply. A second `dsta` is answered +//! `kVTVideoDecoderBadDataErr`, and the session goes on as the first left it. //! - **`dfrm`** decodes one sample: the host asks the guest for an output buffer (`Dbuf`, waiting //! [`BUFFER_REPLY_WAIT`]), which lends the buffer's surface; the backend decodes the sample's //! access unit into it and returns once the picture is there; the host emits the frame @@ -67,6 +70,7 @@ use crate::codec::h264::{self, avcc}; use crate::codec::hevc::nal::nal_type; use crate::codec::hevc::sps::Sps as HevcSps; use crate::codec::hevc::{self, hvcc}; +use crate::core::backend::{Chroma, PixelFormat}; use crate::core::fourcc::FourCc; use crate::core::runtime::Runtime; use crate::paravirt::WireError; @@ -186,9 +190,15 @@ pub trait Backend: Send + Sync { /// Why the arm decodes none of the pictures of a stream of `stream`, one the codec takes, so /// that its session is refused at its start as one the codec refuses is, not at each picture - /// or tile; `None` where it decodes them. The default takes 4:2:0 streams alone. + /// or tile; `None` where it decodes them. The default takes 4:2:0 streams of Main and Main 10 + /// alone. fn declines(&self, stream: &Stream) -> Option { - (stream.chroma_format_idc != 1).then(|| "the arm decodes 4:2:0 pictures alone".to_owned()) + if stream.chroma_format_idc != 1 { + Some("the arm decodes 4:2:0 pictures alone".to_owned()) + } else { + (stream.range_extensions) + .then(|| "the arm decodes no range extensions pictures".to_owned()) + } } } @@ -209,6 +219,9 @@ pub struct Stream { pub width: u32, /// The coded picture's height, in luma samples. pub height: u32, + /// Whether HEVC's stream decodes as the range extensions' (`codec::hevc::is_range_extensions`), + /// on their profiles; false for H.264's. + pub range_extensions: bool, } /// One open decoder, called on its session's thread, one call at a time. @@ -418,8 +431,11 @@ impl Worker { ); return Err(status::VIDEO_DECODER_UNSUPPORTED_DATA_FORMAT); } + let format = record + .format + .ok_or(status::VIDEO_DECODER_UNSUPPORTED_DATA_FORMAT)?; let decoder = self.backend.open(config)?; - self.send_buffer_attributes(config, &record); + self.send_buffer_attributes(config, format); self.decoder = Some(decoder); self.config = Some(config.clone()); self.length_size = record.length_size; @@ -430,12 +446,11 @@ impl Worker { /// `Dpba`: the attributes the guest's output buffers are to have: the format the picture /// lands in, the description's size, IOSurface backing, which the host needs to reach them, /// and the row and plane alignments and cache mode a hardware decoder's buffers have. - fn send_buffer_attributes(&self, config: &DecoderConfig, record: &Record) { - let format = pixel_format(record); + fn send_buffer_attributes(&self, config: &DecoderConfig, format: PixelFormat) { let attributes = Value::dictionary([ ( "PixelFormatType", - Value::Array(vec![Value::Integer(i64::from(u32::from_be_bytes(format)))]), + Value::Array(vec![Value::Integer(i64::from(format.fourcc().0))]), ), ("Width", Value::Integer(i64::from(config.width))), ("Height", Value::Integer(i64::from(config.height))), @@ -554,9 +569,10 @@ impl Worker { ); return Err(status::UNIMPLEMENTED); } + let format = record.format.ok_or(status::UNIMPLEMENTED)?; let decoder = self.backend.open(config)?; let limits = decoder.tile_limits().ok_or(status::UNIMPLEMENTED)?; - self.send_tile_requirements(&record, limits); + self.send_tile_requirements(format, limits); self.tiles = Some(TileSession { decoder, length_size: record.length_size, @@ -569,13 +585,11 @@ impl Worker { /// in, IOSurface backing, and a hardware decoder's row and plane alignments), and the tiles /// the session decodes: the backend's largest and smallest picture, [`TILE_PIXEL_ALIGNMENT`], /// [`TILE_BYTE_ALIGNMENT`], and rows of an output buffer up to the widest tile's. - fn send_tile_requirements(&self, record: &Record, limits: TileLimits) { + fn send_tile_requirements(&self, format: PixelFormat, limits: TileLimits) { let attributes = Value::dictionary([ ( "PixelFormatType", - Value::Array(vec![Value::Integer(i64::from(u32::from_be_bytes( - pixel_format(record), - )))]), + Value::Array(vec![Value::Integer(i64::from(format.fourcc().0))]), ), ("IOSurfaceProperties", Value::Dictionary(Vec::new())), ("BytesPerRowAlignment", Value::Integer(64)), @@ -1014,18 +1028,14 @@ fn config_from_format(format: &SerializedFormatDescription) -> Option [u8; 4] { - let four_four_four = record.stream.chroma_format_idc == 3; - match (four_four_four, record.ten_bit, record.full_range) { - (true, _, false) => *b"444v", - (true, _, true) => *b"444f", - (false, false, false) => *b"420v", - (false, false, true) => *b"420f", - (false, true, false) => *b"x420", - (false, true, true) => *b"xf20", - } +/// The CoreVideo format a stream's pictures land in: the two-plane format of its chroma format, +/// depth and range ([`PixelFormat::of`]); `None` for one of none (monochrome, or past 12 bits). +fn pixel_format(stream: &Stream, full_range: bool) -> Option { + PixelFormat::of( + Chroma::of_idc(stream.chroma_format_idc)?, + stream.luma_bits, + full_range, + ) } /// A `dtil`'s region from its `,tco`, `,tcd` and `,obp`: `None` for a negative or empty one, one @@ -1051,10 +1061,8 @@ struct Record { length_size: u8, /// Its parameter sets, Annex B. parameter_sets: Vec, - /// Whether the luma samples have more than 8 bits: 10, in a stream the host decodes. - ten_bit: bool, - /// Whether the samples use the full range. - full_range: bool, + /// The CoreVideo format its pictures land in ([`pixel_format`]), where it has one. + format: Option, /// The stream its SPS describes. stream: Stream, /// Why the codec takes none of the stream's pictures, where it takes none. @@ -1063,9 +1071,9 @@ struct Record { /// A stream whose pictures the host's decoders take none of: what the codec's `check_supported` /// refuses of its SPS (a profile, chroma format, bit depths or tools outside 4:2:0 at 8 bits, -/// HEVC's at 8 or 10, and HEVC's 4:4:4 at 8), which every arm's decode of each picture checks, or -/// what the arm declines of it ([`Backend::declines`]), and what the SPS says the stream is, -/// which the refusal's line names. +/// HEVC's at 8 or 10, and HEVC's range extensions at 8, 10 and 12), which every arm's decode of +/// each picture checks, or what the arm declines of it ([`Backend::declines`]), and what the SPS +/// says the stream is, which the refusal's line names. #[derive(Clone, Debug, PartialEq, Eq)] struct Undecoded { /// What `check_supported` refuses, or the arm declines. @@ -1084,6 +1092,7 @@ impl Stream { chroma_bits: sps.bit_depth_chroma_minus8.saturating_add(8), width: sps.pic_width_in_luma_samples, height: sps.pic_height_in_luma_samples, + range_extensions: hevc::is_range_extensions(sps), } } @@ -1097,6 +1106,7 @@ impl Stream { chroma_bits: sps.bit_depth_chroma_minus8.saturating_add(8), width: sps.coded_width(), height: sps.coded_height(), + range_extensions: false, } } } @@ -1174,7 +1184,7 @@ fn undecoded(backend: &dyn Backend, record: &Record) -> Option { /// ([`Record::undecoded`]). fn read_record(config: &DecoderConfig) -> Result { let unsupported = status::VIDEO_DECODER_UNSUPPORTED_DATA_FORMAT; - let (length_size, units, ten_bit, full_range, stream, undecoded) = match config.codec { + let (length_size, units, full_range, stream, undecoded) = match config.codec { Codec::H264 => { let record = avcc::DecoderConfiguration::parse(&config.record).map_err(|_| unsupported)?; @@ -1197,16 +1207,8 @@ fn read_record(config: &DecoderConfig) -> Result { why: error.to_string(), stream, }); - let ten_bit = sps.bit_depth_luma_minus8 > 0; let full_range = sps.is_full_range(); - ( - record.length_size, - units, - ten_bit, - full_range, - stream, - undecoded, - ) + (record.length_size, units, full_range, stream, undecoded) } Codec::Hevc => { let record = @@ -1232,7 +1234,6 @@ fn read_record(config: &DecoderConfig) -> Result { ( record.length_size, record.nal_units, - sps.bit_depth_luma_minus8 > 0, full, stream, undecoded, @@ -1250,8 +1251,7 @@ fn read_record(config: &DecoderConfig) -> Result { Ok(Record { length_size, parameter_sets, - ten_bit, - full_range, + format: pixel_format(&stream, full_range), stream, undecoded, }) diff --git a/crates/reims-vgpu-video/src/paravirt/decoder/tests.rs b/crates/reims-vgpu-video/src/paravirt/decoder/tests.rs index 5a7d21c9c..f14b5bb70 100644 --- a/crates/reims-vgpu-video/src/paravirt/decoder/tests.rs +++ b/crates/reims-vgpu-video/src/paravirt/decoder/tests.rs @@ -99,17 +99,18 @@ impl Backend for FakeBackend { } } -/// A fake backend whose arm decodes 4:4:4 streams as well as 4:2:0 ones. -struct FourFourFour(FakeBackend); +/// A fake backend whose arm decodes the range extensions' streams (4:2:0, 4:2:2 and 4:4:4 at 8, +/// 10 and 12 bits) as well as Main's and Main 10's. +struct RangeExtensions(FakeBackend); -impl Backend for FourFourFour { +impl Backend for RangeExtensions { fn open(&self, config: &DecoderConfig) -> Result, OsStatus> { self.0.open(config) } fn declines(&self, stream: &Stream) -> Option { - (!matches!(stream.chroma_format_idc, 1 | 3)) - .then(|| "the arm decodes 4:2:0 and 4:4:4 pictures alone".to_owned()) + (!matches!(stream.chroma_format_idc, 1..=3)) + .then(|| "the arm decodes 4:2:0, 4:2:2 and 4:4:4 pictures alone".to_owned()) } } @@ -172,12 +173,13 @@ impl Guest { Self::on(codec, result, tiles, false) } - /// [`Guest::of`], on an arm that decodes 4:4:4 streams too where `four_four_four`. + /// [`Guest::of`], on an arm that decodes the range extensions' streams too where + /// `range_extensions`. fn on( codec: Codec, result: Result, tiles: Option, - four_four_four: bool, + range_extensions: bool, ) -> Self { let calls = Calls::default(); let regions = Regions::default(); @@ -187,8 +189,8 @@ impl Guest { result, tiles, }; - let backend: Arc = if four_four_four { - Arc::new(FourFourFour(fake)) + let backend: Arc = if range_extensions { + Arc::new(RangeExtensions(fake)) } else { Arc::new(fake) }; @@ -937,13 +939,13 @@ fn hvcc_of(sps: &[u8]) -> Vec { fn starts_in( codec: Codec, record: &[u8], - four_four_four: bool, + range_extensions: bool, format: Option<&[u8; 4]>, what: &str, ) { let named = format.map(|f| Value::Array(vec![Value::Integer(i64::from(u32::from_be_bytes(*f)))])); - let guest = Guest::on(codec, Ok(Decoded::Landed), Some(TILES), four_four_four); + let guest = Guest::on(codec, Ok(Decoded::Landed), Some(TILES), range_extensions); guest.start(record); if let Some(named) = &named { let (_, dpba) = guest.next_of(b"Dpba"); @@ -964,7 +966,7 @@ fn starts_in( } assert!(guest.quiet(), "{what}"); - let guest = Guest::on(codec, Ok(Decoded::Landed), Some(TILES), four_four_four); + let guest = Guest::on(codec, Ok(Decoded::Landed), Some(TILES), range_extensions); guest.start_tiles(record); if let Some(named) = &named { let (_, tdrs) = guest.next_of(b"TDrs"); @@ -996,13 +998,13 @@ fn starts_in( #[test] fn each_hevc_stream_lands_in_its_format_or_is_refused_at_its_start() { // general_profile_idc, chroma_format_idc, the depths past 8, the range extensions, the - // VUI's range, and the format the pictures land in, on an arm of 4:2:0 alone and on one of - // 4:4:4 too. Apple's HEIC images hold 4:2:0 items of Main Still Picture and Main, and 4:4:4 - // thumbnails and monochrome alpha items of the range extensions' profile (read with ffprobe - // on an M3 Max's own, macOS 27.0.1): the thumbnails land where the arm decodes 4:4:4, and - // the rest of the range extensions' streams nowhere, each refused at its start, not at each - // tile. - for (profile, chroma, deeper, range_extension, full_range, format, with_444) in [ + // VUI's range, and the format the pictures land in, on an arm of Main and Main 10 alone and + // on one of the range extensions too: the format the guest's own software decoder lands each + // in (`PixelFormat::of`). Apple's HEIC images hold 4:2:0 items of Main Still Picture and + // Main, and 4:4:4 thumbnails and monochrome alpha items of the range extensions' profile + // (read with ffprobe on an M3 Max's own, macOS 27.0.1): the thumbnails land where the arm + // decodes 4:4:4, and the alpha items nowhere, each refused at its start, not at each tile. + for (profile, chroma, deeper, range_extension, full_range, format, with_rext) in [ (1, 1, 0, false, None, Some(b"420v"), Some(b"420v")), (1, 1, 0, false, Some(true), Some(b"420f"), Some(b"420f")), (3, 1, 0, false, Some(true), Some(b"420f"), Some(b"420f")), @@ -1010,22 +1012,33 @@ fn each_hevc_stream_lands_in_its_format_or_is_refused_at_its_start() { (2, 1, 2, false, Some(true), Some(b"xf20"), Some(b"xf20")), (4, 3, 0, true, Some(true), None, Some(b"444f")), (4, 3, 0, true, None, None, Some(b"444v")), - (4, 3, 2, true, None, None, None), - (4, 2, 0, true, Some(true), None, None), - (4, 2, 2, true, None, None, None), + (4, 3, 2, true, None, None, Some(b"x444")), + (4, 3, 2, true, Some(true), None, Some(b"xf44")), + (4, 3, 4, true, None, None, Some(b"tv44")), + (4, 3, 4, true, Some(true), None, Some(b"tf44")), + (4, 2, 0, true, Some(true), None, Some(b"422f")), + (4, 2, 0, true, None, None, Some(b"422v")), + (4, 2, 2, true, None, None, Some(b"x422")), + (4, 2, 2, true, Some(true), None, Some(b"xf22")), + (4, 2, 4, true, None, None, Some(b"tv22")), + (4, 2, 4, true, Some(true), None, Some(b"tf22")), + (4, 1, 4, true, None, None, Some(b"tv20")), + (4, 1, 4, true, Some(true), None, Some(b"tf20")), + (4, 1, 2, true, None, None, Some(b"x420")), + (4, 1, 0, true, None, None, Some(b"420v")), + (4, 3, 6, true, None, None, None), (4, 0, 0, true, Some(true), None, None), (1, 3, 0, false, Some(true), None, None), (2, 2, 2, false, None, None, None), (1, 0, 0, false, None, None, None), (2, 1, 4, false, None, None, None), - (4, 1, 0, true, None, None, None), ] { let sps = crate::codec::hevc::tests::sps_of(profile, chroma, deeper, range_extension, full_range); let what = format!("profile {profile}, chroma {chroma}, 8+{deeper} bits, {full_range:?}"); starts_in(Codec::Hevc, &hvcc_of(&sps), false, format, &what); - let what = format!("{what}, on an arm of 4:4:4"); - starts_in(Codec::Hevc, &hvcc_of(&sps), true, with_444, &what); + let what = format!("{what}, on an arm of the range extensions"); + starts_in(Codec::Hevc, &hvcc_of(&sps), true, with_rext, &what); } } @@ -1060,20 +1073,32 @@ fn a_refused_stream_is_named_by_its_profile_chroma_format_depths_and_size() { refused.kind(), "HEVC profile four chroma format three, luma eight bits, chroma eight bits" ); - let four_four_four = FourFourFour(FakeBackend::landing()); + let range_extensions = RangeExtensions(FakeBackend::landing()); assert_eq!( - undecoded_on(&four_four_four, Codec::Hevc, hvcc_of(&thumbnail)), + undecoded_on(&range_extensions, Codec::Hevc, hvcc_of(&thumbnail)), None ); let alpha = crate::codec::hevc::tests::sps_of(4, 0, 2, true, None); - let refused = undecoded_on(&four_four_four, Codec::Hevc, hvcc_of(&alpha)).expect("refused"); + let refused = undecoded_on(&range_extensions, Codec::Hevc, hvcc_of(&alpha)).expect("refused"); assert_eq!( refused.to_string(), - "unsupported: range extensions streams other than 4:4:4 at 8 bits (HEVC \ - general_profile_idc 4, chroma_format_idc 0, luma 10 bits, chroma 10 bits, 64x48)" + "unsupported: monochrome (HEVC general_profile_idc 4, chroma_format_idc 0, luma 10 \ + bits, chroma 10 bits, 64x48)" ); - let high = - undecoded_on(&four_four_four, Codec::H264, avcc(&high_sps(244, 3, 2), 4)).expect("refused"); + // A 4:2:0 stream of the range extensions' tools, on an arm of Main and Main 10 alone. + let twelve = crate::codec::hevc::tests::sps_of(4, 1, 4, true, None); + let refused = undecoded_on(&arm, Codec::Hevc, hvcc_of(&twelve)).expect("refused"); + assert_eq!( + refused.to_string(), + "the arm decodes no range extensions pictures (HEVC general_profile_idc 4, \ + chroma_format_idc 1, luma 12 bits, chroma 12 bits, 64x48)" + ); + let high = undecoded_on( + &range_extensions, + Codec::H264, + avcc(&high_sps(244, 3, 2), 4), + ) + .expect("refused"); assert!( high.to_string().ends_with( "(H.264 profile_idc 244, chroma_format_idc 3, luma 10 bits, chroma 10 bits, 64x48)" @@ -1144,7 +1169,7 @@ fn each_h264_stream_lands_in_its_4_2_0_format_or_is_refused_at_its_start() { (244, 3, 2, None), ] { let what = format!("profile {profile}, chroma {chroma}, 8+{deeper} bits"); - // On an arm of 4:4:4 too: the codec refuses H.264's. + // On an arm of the range extensions too: the codec refuses H.264's. starts_in( Codec::H264, &avcc(&high_sps(profile, chroma, deeper), 4), diff --git a/crates/reims-vgpu-video/src/vaapi.rs b/crates/reims-vgpu-video/src/vaapi.rs index ea5b8fec3..ef9141c25 100644 --- a/crates/reims-vgpu-video/src/vaapi.rs +++ b/crates/reims-vgpu-video/src/vaapi.rs @@ -12,8 +12,8 @@ pub use va::{ Capabilities, ConfigCapabilities, Display, Entrypoint, Error, ExportedPlane, Fourcc, Frame, FrameHold, GuestWrites, H264_MAX_MACROBLOCKS, H264Decoder, HevcDecoder, ImportWrite, ImportWrites, LoadError, PackedTarget, PlaneRows, Profile, ReadBack, ReadbackTimes, - ReadbackWay, SurfaceCapabilities, SurfaceExport, proc_filter_name, read_back_by, - rt_format_names, + ReadbackWay, SurfaceCapabilities, SurfaceExport, proc_filter_name, range_extensions_decoder, + read_back_by, rt_format_names, }; /// A pool's surface on Windows, a shared Direct3D 12 texture, which a frame names diff --git a/crates/reims-vgpu-video/src/vaapi/va.rs b/crates/reims-vgpu-video/src/vaapi/va.rs index 9874507c4..2ea0a0091 100644 --- a/crates/reims-vgpu-video/src/vaapi/va.rs +++ b/crates/reims-vgpu-video/src/vaapi/va.rs @@ -72,7 +72,7 @@ pub use encoder::{ pub use export::{ExportedPlane, SurfaceExport}; pub use frame::{Frame, FrameHold, GuestWrites, PlaneRows, ReadBack}; pub use h264::{H264_MAX_MACROBLOCKS, H264Decoder}; -pub use hevc::HevcDecoder; +pub use hevc::{HevcDecoder, range_extensions_decoder}; pub use import_check::{ImportWrite, ImportWrites}; pub use libva::LoadError; pub use readback::{ReadbackTimes, ReadbackWay, read_back_by}; diff --git a/crates/reims-vgpu-video/src/vaapi/va/caps.rs b/crates/reims-vgpu-video/src/vaapi/va/caps.rs index a673a56de..3d5b2b528 100644 --- a/crates/reims-vgpu-video/src/vaapi/va/caps.rs +++ b/crates/reims-vgpu-video/src/vaapi/va/caps.rs @@ -38,8 +38,18 @@ impl Profile { pub const HEVC_MAIN: Self = Self(ffi::VAProfileHEVCMain); /// `VAProfileHEVCMain10`. pub const HEVC_MAIN10: Self = Self(ffi::VAProfileHEVCMain10); + /// `VAProfileHEVCMain12`: the range extensions' 4:2:0 to 12 bits. + pub const HEVC_MAIN12: Self = Self(ffi::VAProfileHEVCMain12); + /// `VAProfileHEVCMain422_10`: the range extensions' 4:2:2 at 8 and 10 bits. + pub const HEVC_MAIN422_10: Self = Self(ffi::VAProfileHEVCMain422_10); + /// `VAProfileHEVCMain422_12`: the range extensions' 4:2:2 at 12 bits. + pub const HEVC_MAIN422_12: Self = Self(ffi::VAProfileHEVCMain422_12); /// `VAProfileHEVCMain444`: the range extensions' 4:4:4 at 8 bits. pub const HEVC_MAIN444: Self = Self(ffi::VAProfileHEVCMain444); + /// `VAProfileHEVCMain444_10`: the range extensions' 4:4:4 at 10 bits. + pub const HEVC_MAIN444_10: Self = Self(ffi::VAProfileHEVCMain444_10); + /// `VAProfileHEVCMain444_12`: the range extensions' 4:4:4 at 12 bits. + pub const HEVC_MAIN444_12: Self = Self(ffi::VAProfileHEVCMain444_12); /// va.h's name for the profile, without its `VAProfile` prefix. pub fn name(self) -> Option<&'static str> { @@ -139,6 +149,18 @@ impl Fourcc { pub const NV12: Self = Self(ffi::VA_FOURCC_NV12); /// `VA_FOURCC_XYUV`. pub const XYUV: Self = Self(ffi::VA_FOURCC_XYUV); + /// `VA_FOURCC_P012`. + pub const P012: Self = Self(ffi::VA_FOURCC_P012); + /// `VA_FOURCC_YUY2`. + pub const YUY2: Self = Self(ffi::VA_FOURCC_YUY2); + /// `VA_FOURCC_Y210`. + pub const Y210: Self = Self(ffi::VA_FOURCC_Y210); + /// `VA_FOURCC_Y212`. + pub const Y212: Self = Self(ffi::VA_FOURCC_Y212); + /// `VA_FOURCC_Y410`. + pub const Y410: Self = Self(ffi::VA_FOURCC_Y410); + /// `VA_FOURCC_Y412`. + pub const Y412: Self = Self(ffi::VA_FOURCC_Y412); } impl std::fmt::Display for Fourcc { diff --git a/crates/reims-vgpu-video/src/vaapi/va/d3d12.rs b/crates/reims-vgpu-video/src/vaapi/va/d3d12.rs index cac36bc60..32452cdc2 100644 --- a/crates/reims-vgpu-video/src/vaapi/va/d3d12.rs +++ b/crates/reims-vgpu-video/src/vaapi/va/d3d12.rs @@ -525,7 +525,7 @@ impl Device { let dxgi_format = match format { SurfaceFormat::Nv12 => DXGI_FORMAT_NV12, SurfaceFormat::P010 => DXGI_FORMAT_P010, - SurfaceFormat::Xyuv => return Err("no shared texture of XYUV".to_owned()), + format => return Err(format!("no shared texture of {}", format.name())), }; let heap = HeapProperties { type_: D3D12_HEAP_TYPE_DEFAULT, @@ -805,7 +805,7 @@ impl Device { let format = match to.format { SurfaceFormat::Nv12 => DXGI_FORMAT_NV12, SurfaceFormat::P010 => DXGI_FORMAT_P010, - SurfaceFormat::Xyuv => return Err("no shared texture of XYUV".to_owned()), + format => return Err(format!("no shared texture of {}", format.name())), }; let desc = ResourceDesc { dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, diff --git a/crates/reims-vgpu-video/src/vaapi/va/ffi.rs b/crates/reims-vgpu-video/src/vaapi/va/ffi.rs index 9d70c4ff1..1e48b142c 100644 --- a/crates/reims-vgpu-video/src/vaapi/va/ffi.rs +++ b/crates/reims-vgpu-video/src/vaapi/va/ffi.rs @@ -51,10 +51,22 @@ pub(crate) const VA_PROGRESSIVE: c_int = 0x1; pub(crate) const VA_RT_FORMAT_YUV420: c_uint = 0x0000_0001; pub(crate) const VA_RT_FORMAT_YUV420_10: c_uint = 0x0000_0100; pub(crate) const VA_RT_FORMAT_YUV444: c_uint = 0x0000_0004; +pub(crate) const VA_RT_FORMAT_YUV422: c_uint = 0x0000_0002; +pub(crate) const VA_RT_FORMAT_YUV422_10: c_uint = 0x0000_0200; +pub(crate) const VA_RT_FORMAT_YUV444_10: c_uint = 0x0000_0400; +pub(crate) const VA_RT_FORMAT_YUV420_12: c_uint = 0x0000_1000; +pub(crate) const VA_RT_FORMAT_YUV422_12: c_uint = 0x0000_2000; +pub(crate) const VA_RT_FORMAT_YUV444_12: c_uint = 0x0000_4000; pub(crate) const VA_FOURCC_NV12: u32 = 0x3231_564e; pub(crate) const VA_FOURCC_P010: u32 = 0x3031_3050; pub(crate) const VA_FOURCC_XYUV: u32 = 0x5655_5958; +pub(crate) const VA_FOURCC_P012: u32 = 0x3231_3050; +pub(crate) const VA_FOURCC_YUY2: u32 = 0x3259_5559; +pub(crate) const VA_FOURCC_Y210: u32 = 0x3031_3259; +pub(crate) const VA_FOURCC_Y212: u32 = 0x3231_3259; +pub(crate) const VA_FOURCC_Y410: u32 = 0x3031_3459; +pub(crate) const VA_FOURCC_Y412: u32 = 0x3231_3459; pub(crate) const VA_SLICE_DATA_FLAG_ALL: u32 = 0x00; @@ -75,7 +87,12 @@ pub(crate) const VAProfileH264High: VAProfile = 7; pub(crate) const VAProfileH264ConstrainedBaseline: VAProfile = 13; pub(crate) const VAProfileHEVCMain: VAProfile = 17; pub(crate) const VAProfileHEVCMain10: VAProfile = 18; +pub(crate) const VAProfileHEVCMain12: VAProfile = 23; +pub(crate) const VAProfileHEVCMain422_10: VAProfile = 24; +pub(crate) const VAProfileHEVCMain422_12: VAProfile = 25; pub(crate) const VAProfileHEVCMain444: VAProfile = 26; +pub(crate) const VAProfileHEVCMain444_10: VAProfile = 27; +pub(crate) const VAProfileHEVCMain444_12: VAProfile = 28; // VAEntrypoint. pub(crate) const VAEntrypointVLD: VAEntrypoint = 1; @@ -1202,9 +1219,21 @@ mod tests { VA_RT_FORMAT_YUV420, VA_RT_FORMAT_YUV420_10, VA_RT_FORMAT_YUV444, + VA_RT_FORMAT_YUV422, + VA_RT_FORMAT_YUV422_10, + VA_RT_FORMAT_YUV444_10, + VA_RT_FORMAT_YUV420_12, + VA_RT_FORMAT_YUV422_12, + VA_RT_FORMAT_YUV444_12, VA_FOURCC_NV12, VA_FOURCC_P010, VA_FOURCC_XYUV, + VA_FOURCC_P012, + VA_FOURCC_YUY2, + VA_FOURCC_Y210, + VA_FOURCC_Y212, + VA_FOURCC_Y410, + VA_FOURCC_Y412, VA_SLICE_DATA_FLAG_ALL, VA_PICTURE_H264_INVALID, VA_PICTURE_H264_SHORT_TERM_REFERENCE, @@ -1220,7 +1249,12 @@ mod tests { VAProfileH264ConstrainedBaseline, VAProfileHEVCMain, VAProfileHEVCMain10, + VAProfileHEVCMain12, + VAProfileHEVCMain422_10, + VAProfileHEVCMain422_12, VAProfileHEVCMain444, + VAProfileHEVCMain444_10, + VAProfileHEVCMain444_12, VAEntrypointVLD, VAEntrypointVideoProc, VAConfigAttribRTFormat, diff --git a/crates/reims-vgpu-video/src/vaapi/va/ffi_layout.c b/crates/reims-vgpu-video/src/vaapi/va/ffi_layout.c index c75b1b102..ea98c3ca1 100644 --- a/crates/reims-vgpu-video/src/vaapi/va/ffi_layout.c +++ b/crates/reims-vgpu-video/src/vaapi/va/ffi_layout.c @@ -380,9 +380,21 @@ int main(void) C(VA_RT_FORMAT_YUV420); C(VA_RT_FORMAT_YUV420_10); C(VA_RT_FORMAT_YUV444); + C(VA_RT_FORMAT_YUV422); + C(VA_RT_FORMAT_YUV422_10); + C(VA_RT_FORMAT_YUV444_10); + C(VA_RT_FORMAT_YUV420_12); + C(VA_RT_FORMAT_YUV422_12); + C(VA_RT_FORMAT_YUV444_12); C(VA_FOURCC_NV12); C(VA_FOURCC_P010); C(VA_FOURCC_XYUV); + C(VA_FOURCC_P012); + C(VA_FOURCC_YUY2); + C(VA_FOURCC_Y210); + C(VA_FOURCC_Y212); + C(VA_FOURCC_Y410); + C(VA_FOURCC_Y412); C(VA_SLICE_DATA_FLAG_ALL); C(VA_PICTURE_H264_INVALID); C(VA_PICTURE_H264_SHORT_TERM_REFERENCE); @@ -398,7 +410,12 @@ int main(void) C(VAProfileH264ConstrainedBaseline); C(VAProfileHEVCMain); C(VAProfileHEVCMain10); + C(VAProfileHEVCMain12); + C(VAProfileHEVCMain422_10); + C(VAProfileHEVCMain422_12); C(VAProfileHEVCMain444); + C(VAProfileHEVCMain444_10); + C(VAProfileHEVCMain444_12); C(VAEntrypointVLD); C(VAEntrypointVideoProc); C(VAConfigAttribRTFormat); diff --git a/crates/reims-vgpu-video/src/vaapi/va/frame.rs b/crates/reims-vgpu-video/src/vaapi/va/frame.rs index 03409088d..6ba257ed7 100644 --- a/crates/reims-vgpu-video/src/vaapi/va/frame.rs +++ b/crates/reims-vgpu-video/src/vaapi/va/frame.rs @@ -1,10 +1,11 @@ //! A decoded frame, for every codec: its surface, held until the frame is //! dropped, what the decoder knows of it, and its readback into caller -//! planes, NV12 for 8-bit frames and P010 for 10-bit ones. +//! planes, NV12 for 8-bit frames and P010 for 10-bit ones, and two planes of +//! the range extensions' packed frames. use std::sync::Arc; -use crate::core::backend::DeviceWrite; +use crate::core::backend::{Chroma, DeviceWrite}; use crate::core::device_memory::GuestTarget; use crate::core::surfaces::crop_within; @@ -132,20 +133,39 @@ impl Frame { self.full_range } - /// The bits a sample holds: 8 for an NV12 or a 4:4:4 frame, 10 for a P010 one. + /// The bits a sample holds: 8 for an NV12, YUY2 or XYUV frame, 10 for a P010, Y210 or Y410 + /// one, 12 for a P012, Y212 or Y412 one. pub fn bit_depth(&self) -> u32 { - match self.surface.format() { - SurfaceFormat::Nv12 | SurfaceFormat::Xyuv => 8, - SurfaceFormat::P010 => 10, - } + u32::from(self.surface.format().bit_depth()) } - /// Whether the frame is 4:4:4 (HEVC Main 4:4:4's, [`super::HevcDecoder::lands_4_4_4`]), - /// which [`ReadBack::copy_4_4_4_into`] reads back, and else 4:2:0. + /// How the frame's chroma is sampled: 4:2:0, or the range extensions' 4:2:2 or 4:4:4 + /// ([`super::HevcDecoder::lands_range_extensions`]). + pub fn chroma(&self) -> Chroma { + self.surface.format().chroma() + } + + /// Whether the frame is 4:4:4 ([`Self::chroma`]). pub fn is_4_4_4(&self) -> bool { + self.chroma() == Chroma::Yuv444 + } + + /// Whether the frame's pixels are packed in one plane, which [`ReadBack::copy_packed_into`] + /// reads back, rather than in two, which [`ReadBack::copy_into`] reads back. + pub fn is_packed(&self) -> bool { + self.surface.format().planes() == 1 + } + + /// Whether the frame is 8-bit 4:4:4 in XYUV, which [`Frame::write_4_4_4_to`] writes. + pub fn is_xyuv(&self) -> bool { self.surface.format() == SurfaceFormat::Xyuv } + /// The name of its surface's VA format (`NV12`, `P010`, `Y410` and the like). + pub fn surface_format_name(&self) -> &'static str { + self.surface.format().name() + } + /// What the frames of this frame's surface pool came back through so /// far, and how long each part took. pub fn readback_times(&self) -> ReadbackTimes { @@ -314,21 +334,33 @@ impl ReadBack<'_> { ) } - /// Copies an 8-bit 4:4:4 frame ([`Frame::is_4_4_4`]), cropped, into two planes as CoreVideo's - /// `444v` and `444f` and ffmpeg's `nv24` lay them out: `y`, and `cbcr`, each pixel's Cb - /// then Cr, as many rows as `y`, whose rows hold `row_bytes` of the picture each. Planes of + /// Copies a packed frame ([`Frame::is_packed`]: the range extensions' 4:2:2 and 4:4:4), + /// cropped, into two planes as CoreVideo's two-plane formats of its chroma format and depth + /// (`422v`, `x422`, `tv22`, `444v`, `x444`, `tv44` and their full-range twins) and ffmpeg's + /// `nv16`, `p210`, `p212`, `nv24`, `p410` and `p412` lay them out: `y`, and `cbcr`, each pair's + /// Cb then Cr, as many rows as `y`, whose rows hold `row_bytes` of the picture each; a + /// sample a byte at 8 bits, else a little-endian 16-bit word, its bits at the top. Planes of /// fewer rows or columns than the frame take its top left, as [`ReadBack::copy_into`]'s do. - pub fn copy_4_4_4_into(&self, y: PlaneRows<'_>, cbcr: PlaneRows<'_>) -> Result<(), Error> { + pub fn copy_packed_into(&self, y: PlaneRows<'_>, cbcr: PlaneRows<'_>) -> Result<(), Error> { let frame = self.frame; - let fit = |rows: usize| u32::try_from(rows).unwrap_or(u32::MAX); + let format = frame.surface.format(); + let sample = format.bytes_per_sample(); + let fit = |n: usize| u32::try_from(n).unwrap_or(u32::MAX); + let chroma_bytes = cbcr.row_bytes.min(cbcr.bytes_per_row) / (2 * sample); + // A 4:2:2 row holds a pair for every two columns, the last one too where the width is + // odd, so an even width fits where its pairs do. + let chroma_columns = match format.chroma() { + Chroma::Yuv422 => fit(chroma_bytes).saturating_mul(2), + Chroma::Yuv420 | Chroma::Yuv444 => fit(chroma_bytes), + }; let rect = Rect { width: (frame.rect.width) - .min(fit(y.row_bytes.min(y.bytes_per_row))) - .min(fit(cbcr.row_bytes.min(cbcr.bytes_per_row) / 2)), + .min(fit(y.row_bytes.min(y.bytes_per_row) / sample)) + .min(chroma_columns), height: (frame.rect.height).min(fit(y.rows)).min(fit(cbcr.rows)), ..frame.rect }; - self.surface.copy_4_4_4_to( + self.surface.copy_packed_to( rect, (y.bytes, y.bytes_per_row), (cbcr.bytes, cbcr.bytes_per_row), @@ -418,7 +450,7 @@ impl Frame { }) } - /// Writes the frame, a 4:4:4 one ([`Frame::is_4_4_4`]), into `target` as its XYUV surface + /// Writes the frame, an XYUV one ([`Frame::is_xyuv`]), into `target` as its XYUV surface /// holds it, by video-processing runs from its surface as [`Frame::write_to_guest`] writes a /// 4:2:0 frame (`super::zero_copy`), once its decode is done: `target`'s whole width and /// height from the crop's first sample, which the decoded (coded) picture holds. diff --git a/crates/reims-vgpu-video/src/vaapi/va/hevc.rs b/crates/reims-vgpu-video/src/vaapi/va/hevc.rs index bc503e2b4..2a454ca3b 100644 --- a/crates/reims-vgpu-video/src/vaapi/va/hevc.rs +++ b/crates/reims-vgpu-video/src/vaapi/va/hevc.rs @@ -1,14 +1,18 @@ //! HEVC decoding on VA-API: [`crate::codec::hevc::Decoder`] over an accelerator //! that fills libva's HEVC buffers (va_dec_hevc.h) and decodes into a pool //! of NV12 surfaces for Main, P010 ones for Main 10, and, for a caller that -//! lands 4:4:4 pictures ([`HevcDecoder::lands_4_4_4`]), XYUV ones for the -//! range extensions' 4:4:4 at 8 bits, on the driver's `HEVCMain444`. Those -//! pictures' parameters go as va_dec_hevc.h's `…Extension` structures, the -//! base one with the range extensions' after it, in the picture's and each -//! slice's parameter buffer, as ffmpeg sends them for that profile. +//! lands the range extensions' pictures +//! ([`HevcDecoder::lands_range_extensions`]), the surfaces of the driver's +//! range extensions profile of the stream's chroma format and depth +//! ([`range_extensions_decoder`]): `HEVCMain12`'s P012 (NV12 and P010 at 8 +//! and 10 bits), `HEVCMain422_10`'s YUY2 and Y210, `HEVCMain422_12`'s Y212, +//! `HEVCMain444`'s XYUV, `HEVCMain444_10`'s Y410 and `HEVCMain444_12`'s Y412. +//! Those pictures' parameters go as va_dec_hevc.h's `…Extension` structures, +//! the base one with the range extensions' after it, in the picture's and +//! each slice's parameter buffer, as ffmpeg sends them for those profiles. use super::buffer::{Buffer, render_decode}; -use super::caps::{Context, Entrypoint, Profile}; +use super::caps::{Context, Entrypoint, Fourcc, Profile}; use super::display::{Display, Error}; use super::ffi; use super::frame::Frame; @@ -42,8 +46,9 @@ const MAX_CURRENT_REFERENCES: usize = 8; /// record's length size, as VideoToolbox's samples are, or Annex B for /// [`HevcDecoder::new_annex_b`]. Frames come out in decode order unless /// [`HevcDecoder::set_output_order`] asks for display order. Main streams -/// decode into NV12 frames, Main 10 ones into P010, and 4:4:4 ones at 8 bits -/// into XYUV where the caller lands them ([`HevcDecoder::lands_4_4_4`]). +/// decode into NV12 frames, Main 10 ones into P010, and the range extensions' +/// into their profile's surfaces where the caller lands them +/// ([`HevcDecoder::lands_range_extensions`]). pub struct HevcDecoder { inner: Decoder, } @@ -58,9 +63,10 @@ impl HevcDecoder { /// A decoder for samples described by an `hvcC` record (ISO/IEC /// 14496-15, 8.3.3.1), whose parameter sets it takes. The record's /// first SPS is checked against what the decoder and the driver take, - /// so that a stream they cannot decode is refused here. A 4:4:4 stream - /// the driver decodes is taken here, and refused at its first picture - /// unless [`Self::lands_4_4_4`] was called before it. + /// so that a stream they cannot decode is refused here. A range + /// extensions stream the driver decodes is taken here, and refused at its + /// first picture unless [`Self::lands_range_extensions`] was called before + /// it. pub fn new(display: &Display, hvcc: &[u8]) -> Result { let inner = Decoder::from_hvcc(VaHevc::new(display), hvcc)?; let config = DecoderConfiguration::parse(hvcc)?; @@ -83,12 +89,13 @@ impl HevcDecoder { } } - /// Has a 4:4:4 stream at 8 bits decoded, into XYUV surfaces, whose - /// frames the caller reads back with [`super::ReadBack::copy_4_4_4_into`] - /// ([`Frame::is_4_4_4`]); without it, a 4:4:4 stream is refused when its - /// SPS is taken. - pub fn lands_4_4_4(&mut self) { - self.inner.accelerator_mut().four_four_four = true; + /// Has a range extensions stream decoded ([`range_extensions_decoder`]), + /// whose packed frames the caller reads back with + /// [`super::ReadBack::copy_packed_into`] ([`Frame::is_packed`]), and the + /// rest with [`super::ReadBack::copy_into`]; without it, a range + /// extensions stream is refused when its SPS is taken. + pub fn lands_range_extensions(&mut self) { + self.inner.accelerator_mut().range_extensions = true; } /// Chooses decode order (the default) or display order. @@ -196,8 +203,9 @@ struct VaHevc { session: Option, /// What gives the decode in hand its picture's target, taken as the picture is made. target_for: Option, - /// Whether the caller lands 4:4:4 pictures ([`HevcDecoder::lands_4_4_4`]). - four_four_four: bool, + /// Whether the caller lands the range extensions' pictures + /// ([`HevcDecoder::lands_range_extensions`]). + range_extensions: bool, } /// What one SPS's pictures are decoded with. @@ -223,7 +231,7 @@ impl VaHevc { display: display.clone_ref(), session: None, target_for: None, - four_four_four: false, + range_extensions: false, } } @@ -235,26 +243,83 @@ impl VaHevc { } /// The VA profile and surface format for `sps`'s stream: Main at 8 bits, -/// Main 10 at 10, of 4:2:0, and Main 4:4:4 of the range extensions' 4:4:4 -/// at 8 bits where the caller lands its pictures (`four_four_four`). -/// `check_supported` has refused other depths and formats. -fn profile_for(sps: &Sps, four_four_four: bool) -> Result<(Profile, SurfaceFormat), Error> { - match (sps.chroma_format_idc, sps.bit_depth_luma_minus8) { - (1, 0) => Ok((Profile::HEVC_MAIN, SurfaceFormat::Nv12)), - (1, _) => Ok((Profile::HEVC_MAIN10, SurfaceFormat::P010)), - (3, 0) if four_four_four => Ok((Profile::HEVC_MAIN444, SurfaceFormat::Xyuv)), - (3, 0) => Err(Error::Unsupported( - "HEVC 4:4:4: its caller lands 4:2:0 pictures alone".into(), - )), - _ => Err(Error::Unsupported( - "HEVC: VA-API decodes 4:2:0 here, and 4:4:4 at 8 bits".into(), - )), +/// Main 10 at 10, of 4:2:0, and a range extensions stream's +/// ([`range_extensions_format`]) where the caller lands its pictures +/// (`range_extensions`). `check_supported` has refused other depths and +/// formats. +fn profile_for(sps: &Sps, range_extensions: bool) -> Result<(Profile, SurfaceFormat), Error> { + if !hevc::is_range_extensions(sps) { + return match (sps.chroma_format_idc, sps.bit_depth_luma_minus8) { + (1, 0) => Ok((Profile::HEVC_MAIN, SurfaceFormat::Nv12)), + (1, 2) => Ok((Profile::HEVC_MAIN10, SurfaceFormat::P010)), + _ => Err(Error::Unsupported( + "HEVC Main: VA-API decodes 4:2:0 at 8 and 10 bits".into(), + )), + }; } + if !range_extensions { + return Err(Error::Unsupported( + "HEVC range extensions: its caller lands Main and Main 10 pictures alone".into(), + )); + } + let bits = sps.bit_depth_luma_minus8.saturating_add(8); + range_extensions_format(sps.chroma_format_idc, bits).ok_or_else(|| { + Error::Unsupported(format!( + "HEVC range extensions of chroma_format_idc {} at {bits} bits", + sps.chroma_format_idc + )) + }) +} + +/// The driver's range extensions profile that decodes a stream of +/// `chroma_format_idc` at `bits`, and the surfaces it decodes into: Main 12 +/// for 4:2:0, into P012 at 12 bits, and NV12 and P010 below, which a driver +/// whose Main 12 decoder makes none of those render targets declines; Main +/// 4:2:2 10 for 4:2:2 at 8 and 10 bits, into YUY2 and Y210, and Main 4:2:2 +/// 12 at 12, into Y212; Main 4:4:4, Main 4:4:4 10 and Main 4:4:4 12 for +/// 4:4:4, into XYUV, Y410 and Y412 (va.h's profiles; the surfaces as ffmpeg's +/// VA-API decoder maps those formats). +fn range_extensions_format(chroma_format_idc: u8, bits: u8) -> Option<(Profile, SurfaceFormat)> { + Some(match (chroma_format_idc, bits) { + (1, 8) => (Profile::HEVC_MAIN12, SurfaceFormat::Nv12), + (1, 10) => (Profile::HEVC_MAIN12, SurfaceFormat::P010), + (1, 12) => (Profile::HEVC_MAIN12, SurfaceFormat::P012), + (2, 8) => (Profile::HEVC_MAIN422_10, SurfaceFormat::Yuy2), + (2, 10) => (Profile::HEVC_MAIN422_10, SurfaceFormat::Y210), + (2, 12) => (Profile::HEVC_MAIN422_12, SurfaceFormat::Y212), + (3, 8) => (Profile::HEVC_MAIN444, SurfaceFormat::Xyuv), + (3, 10) => (Profile::HEVC_MAIN444_10, SurfaceFormat::Y410), + (3, 12) => (Profile::HEVC_MAIN444_12, SurfaceFormat::Y412), + _ => return None, + }) +} + +/// What a range extensions stream of `chroma_format_idc` at `bits` decodes on, for a caller that +/// checks the driver's answers for it: the profile, the render-target format (a `VA_RT_FORMAT_*` +/// bit) its config is made with, and the surfaces' FOURCC; `None` for a chroma format or depth +/// the decoder takes none of. +pub fn range_extensions_decoder(chroma_format_idc: u8, bits: u8) -> Option<(Profile, u32, Fourcc)> { + let (profile, format) = range_extensions_format(chroma_format_idc, bits)?; + Some((profile, format.rt_format(), Fourcc(format.fourcc()))) +} + +/// Whether `profile` is one of the range extensions', whose pictures' parameters go as +/// va_dec_hevc.h's `…Extension` structures. +fn takes_extensions(profile: Profile) -> bool { + [ + Profile::HEVC_MAIN12, + Profile::HEVC_MAIN422_10, + Profile::HEVC_MAIN422_12, + Profile::HEVC_MAIN444, + Profile::HEVC_MAIN444_10, + Profile::HEVC_MAIN444_12, + ] + .contains(&profile) } /// The VA profile, when the driver decodes `sps`'s stream at its size. -fn select_profile(display: &Display, sps: &Sps, four_four_four: bool) -> Result { - let (profile, format) = profile_for(sps, four_four_four)?; +fn select_profile(display: &Display, sps: &Sps, range_extensions: bool) -> Result { + let (profile, format) = profile_for(sps, range_extensions)?; let name = profile.name().unwrap_or("HEVC"); if !display.supports(profile, Entrypoint::VLD) { return Err(Error::Unsupported(format!( @@ -296,8 +361,8 @@ impl Accelerator for VaHevc { fn configure(&mut self, sps: &Sps, _dpb_size: usize) -> Result<(), Error> { self.session = None; - let profile = select_profile(&self.display, sps, self.four_four_four)?; - let (_, format) = profile_for(sps, self.four_four_four)?; + let profile = select_profile(&self.display, sps, self.range_extensions)?; + let (_, format) = profile_for(sps, self.range_extensions)?; let (width, height) = ( sps.pic_width_in_luma_samples, sps.pic_height_in_luma_samples, @@ -352,9 +417,9 @@ impl Accelerator for VaHevc { .ok_or_else(|| Error::Unsupported("decoding without a context".into()))?; let context = decoding.id; let display = &self.display; - // The range extensions' profile takes the extension structures + // The range extensions' profiles take the extension structures // whole (va_dec_hevc.h), as ffmpeg sends them. - let extensions = session.profile == Profile::HEVC_MAIN444; + let extensions = takes_extensions(session.profile); let base = picture_parameters(picture, params)?; let picture_buffer = if extensions { let parameters = ffi::VAPictureParameterBufferHEVCExtension { @@ -824,29 +889,50 @@ mod tests { } #[test] - fn a_4_4_4_stream_takes_main_4_4_4_into_xyuv_where_its_caller_lands_it() -> Result<(), Error> { - use crate::codec::hevc::tests::{sps_4_4_4_with, sps_of}; - let four = Sps::parse(&sps_4_4_4_with(0))?; - assert_eq!( - profile_for(&four, true)?, - (Profile::HEVC_MAIN444, SurfaceFormat::Xyuv) - ); - assert!(matches!( - profile_for(&four, false), - Err(Error::Unsupported(why)) if why == "HEVC 4:4:4: its caller lands 4:2:0 pictures alone" - )); + fn a_range_extensions_stream_takes_its_profile_where_its_caller_lands_it() -> Result<(), Error> + { + use crate::codec::hevc::tests::sps_of; + use SurfaceFormat::{Nv12, P010, P012, Xyuv, Y210, Y212, Y410, Y412, Yuy2}; + for (chroma, bits, profile, format) in [ + (1, 12, Profile::HEVC_MAIN12, P012), + (1, 10, Profile::HEVC_MAIN12, P010), + (1, 8, Profile::HEVC_MAIN12, Nv12), + (2, 8, Profile::HEVC_MAIN422_10, Yuy2), + (2, 10, Profile::HEVC_MAIN422_10, Y210), + (2, 12, Profile::HEVC_MAIN422_12, Y212), + (3, 8, Profile::HEVC_MAIN444, Xyuv), + (3, 10, Profile::HEVC_MAIN444_10, Y410), + (3, 12, Profile::HEVC_MAIN444_12, Y412), + ] { + // Of the range extensions' profile, with their SPS syntax. + let sps = Sps::parse(&sps_of(4, chroma, u32::from(bits) - 8, true, None))?; + assert_eq!(profile_for(&sps, true)?, (profile, format)); + assert!(takes_extensions(profile)); + assert_eq!( + range_extensions_decoder(chroma as u8, bits), + Some((profile, format.rt_format(), Fourcc(format.fourcc()))) + ); + assert!(matches!( + profile_for(&sps, false), + Err(Error::Unsupported(why)) + if why == "HEVC range extensions: its caller lands Main and Main 10 pictures alone" + )); + } + assert_eq!(range_extensions_decoder(0, 8), None); + assert_eq!(range_extensions_decoder(3, 14), None); let main = Sps::parse(&sps_of(1, 1, 0, false, None))?; let ten = Sps::parse(&sps_of(2, 1, 2, false, None))?; - for four_four_four in [false, true] { + for range_extensions in [false, true] { assert_eq!( - profile_for(&main, four_four_four)?, + profile_for(&main, range_extensions)?, (Profile::HEVC_MAIN, SurfaceFormat::Nv12) ); assert_eq!( - profile_for(&ten, four_four_four)?, + profile_for(&ten, range_extensions)?, (Profile::HEVC_MAIN10, SurfaceFormat::P010) ); } + assert!(!takes_extensions(Profile::HEVC_MAIN10)); Ok(()) } diff --git a/crates/reims-vgpu-video/src/vaapi/va/import_check.rs b/crates/reims-vgpu-video/src/vaapi/va/import_check.rs index fd14969d5..1e2ae4f0a 100644 --- a/crates/reims-vgpu-video/src/vaapi/va/import_check.rs +++ b/crates/reims-vgpu-video/src/vaapi/va/import_check.rs @@ -161,6 +161,12 @@ impl ImportWrites { SurfaceFormat::Nv12 => self.nv12.clone(), SurfaceFormat::P010 => self.p010.clone(), SurfaceFormat::Xyuv => self.xyuv.clone(), + SurfaceFormat::P012 + | SurfaceFormat::Yuy2 + | SurfaceFormat::Y210 + | SurfaceFormat::Y212 + | SurfaceFormat::Y410 + | SurfaceFormat::Y412 => Err(format!("no import of {} is checked", format.name())), } } @@ -427,14 +433,14 @@ fn fill(picture: Picture, bytes: &mut [u8], planes: [(usize, usize); 2]) -> Resu /// The trial picture's sample at `column` (in samples: a chroma row's Cb and Cr alternate, and an /// XYUV pixel's Cr, Cb, Y and fourth byte) of `row` of `plane`, as its bytes hold it: 8-bit -/// values for NV12 and XYUV, 10-bit ones in a sample's high bits for P010. Across the opening's -/// trial picture every value of the format turns up. +/// values for NV12 and XYUV, deeper ones in a sample's high bits for P010 and the rest. Across +/// the opening's trial picture every value of the format turns up. fn sample(format: SurfaceFormat, plane: usize, column: usize, row: usize) -> u16 { let (a, b, c) = if plane == 0 { (3, 5, 7) } else { (7, 11, 101) }; let value = column * a + row * b + c; - match format { - SurfaceFormat::Nv12 | SurfaceFormat::Xyuv => (value % 256) as u16, - SurfaceFormat::P010 => ((value * 13 % 1024) as u16) << 6, + match format.bit_depth() { + 8 => (value % 256) as u16, + bits => ((value * 13 % (1 << bits)) as u16) << (16 - bits), } } @@ -585,6 +591,14 @@ fn trial_in( let held = memory.memory.lock(); return Ok(wrong(picture, held.bytes(), planes)); } + SurfaceFormat::P012 + | SurfaceFormat::Yuy2 + | SurfaceFormat::Y210 + | SurfaceFormat::Y212 + | SurfaceFormat::Y410 + | SurfaceFormat::Y412 => { + return Err(format!("no trial of {} is built", picture.format.name())); + } }; let plane = |n: usize| PlaneLayout { offset: planes[n].0, @@ -1178,7 +1192,7 @@ mod tests { pixel_format: match format { SurfaceFormat::Nv12 => FourCc::new(*b"420v"), SurfaceFormat::P010 => FourCc::new(*b"x420"), - SurfaceFormat::Xyuv => unreachable!("FORMATS has no XYUV"), + _ => unreachable!("FORMATS has NV12 and P010 alone"), }, width: picture.width, height: picture.height, diff --git a/crates/reims-vgpu-video/src/vaapi/va/readback.rs b/crates/reims-vgpu-video/src/vaapi/va/readback.rs index e7ec00f34..43f0310f3 100644 --- a/crates/reims-vgpu-video/src/vaapi/va/readback.rs +++ b/crates/reims-vgpu-video/src/vaapi/va/readback.rs @@ -22,6 +22,7 @@ use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd}; use std::sync::atomic::{AtomicU8, Ordering}; use std::time::Duration; +use crate::core::backend::Chroma; use crate::core::runtime::MonoTime; use super::caps::{Config, Context, Entrypoint, Profile}; @@ -110,27 +111,53 @@ pub(crate) fn asked() -> Option { /// The bytes a row and the rows of `rect`'s two planes: luma, then the /// interleaved chroma, whose last pair and row an odd width or height -/// shares with its last luma column or row; for XYUV, its one plane's -/// pixels, four bytes each, and no second plane. +/// shares with its last luma column or row; for a packed format, its one +/// plane's pixels, whole pairs of them for 4:2:2 (`packed_row_bytes`), and no +/// second plane. pub(crate) fn plane_extents(format: SurfaceFormat, rect: Rect) -> [(usize, usize); 2] { let sample = format.bytes_per_sample(); let (width, height) = (to_usize(rect.width), to_usize(rect.height)); - match format { - SurfaceFormat::Xyuv => [(width * 4, height), (0, 0)], - SurfaceFormat::Nv12 | SurfaceFormat::P010 => [ - (width * sample, height), - (width.div_ceil(2) * 2 * sample, height.div_ceil(2)), - ], + if format.planes() == 1 { + return [(packed_row_bytes(format, width), height), (0, 0)]; + } + [ + (width * sample, height), + (width.div_ceil(2) * 2 * sample, height.div_ceil(2)), + ] +} + +/// The bytes `width` pixels of a packed format take in a row: a 4:2:2 format's +/// pixels in whole pairs, the last one's too where the width is odd. +fn packed_row_bytes(format: SurfaceFormat, width: usize) -> usize { + let pixel = format.first_plane_bytes_per_pixel(); + match format.chroma() { + Chroma::Yuv422 => width.div_ceil(2) * 2 * pixel, + Chroma::Yuv420 | Chroma::Yuv444 => width * pixel, } } -/// Splits `rect` of an XYUV plane in `bytes`, at `plane`'s offset with its -/// pitch, into two destinations, each with its stride: the luma, a byte a -/// pixel, and the chroma, each pixel's Cb then Cr. Each source row is first -/// read whole into a row of the caller's with `copy` (streaming loads where -/// the bytes are a mapping of video memory), then split. -pub(crate) fn split_xyuv( +/// The Cb and Cr pairs one row of `width` pixels of a packed format gives: +/// one for each two pixels of 4:2:2, the last one's too where the width is +/// odd, and one a pixel of 4:4:4. +pub(crate) fn packed_pairs(format: SurfaceFormat, width: usize) -> usize { + match format.chroma() { + Chroma::Yuv422 => width.div_ceil(2), + Chroma::Yuv420 | Chroma::Yuv444 => width, + } +} + +/// Splits `rect` of a packed plane of `format` in `bytes`, at `plane`'s +/// offset with its pitch, into two destinations, each with its stride: the +/// luma, and the chroma, each pair's Cb then Cr, as CoreVideo's two-plane +/// formats of the chroma format and depth lay them out: a byte a sample at 8 +/// bits; deeper, a little-endian 16-bit word, its bits at the top, as the +/// sources' 16-bit words already hold them and Y410's 10-bit fields are moved +/// to. Each source row is first read whole into a row of the caller's with +/// `copy` (streaming loads where the bytes are a mapping of video memory), +/// then split. A 4:2:2 `rect.x` is even, so its rows start on a pair. +pub(crate) fn split_packed( bytes: &[u8], + format: SurfaceFormat, (offset, pitch): (usize, usize), rect: Rect, destinations: [(&mut [u8], usize); 2], @@ -142,10 +169,23 @@ pub(crate) fn split_xyuv( } let short = || Error::Unsupported("an image smaller than its pitches".into()); let too_small = || Error::PlaneTooSmall("destination"); + if format.planes() != 1 || (format.chroma() == Chroma::Yuv422 && rect.x % 2 != 0) { + return Err(Error::Unsupported(format!( + "splitting {} pixels from column {}", + format.name(), + rect.x + ))); + } let [(y, y_stride), (cbcr, cbcr_stride)] = destinations; let width = to_usize(rect.width); - let x = to_usize(rect.x).checked_mul(4).ok_or_else(short)?; - let mut row_bytes = vec![0u8; width.checked_mul(4).ok_or_else(short)?]; + let sample = format.bytes_per_sample(); + let luma_bytes = width.checked_mul(sample).ok_or_else(short)?; + let pairs = packed_pairs(format, width); + let chroma_bytes = pairs.checked_mul(2 * sample).ok_or_else(short)?; + let x = (to_usize(rect.x)) + .checked_mul(format.first_plane_bytes_per_pixel()) + .ok_or_else(short)?; + let mut row_bytes = vec![0u8; packed_row_bytes(format, width)]; for row in 0..to_usize(rect.height) { let src = to_usize(rect.y) .checked_add(row) @@ -154,19 +194,78 @@ pub(crate) fn split_xyuv( .and_then(|start| bytes.get(start..start.checked_add(row_bytes.len())?)) .ok_or_else(short)?; copy(&mut row_bytes, src); - let (pixels, _) = row_bytes.as_chunks::<4>(); - let luma = destination(y, row, y_stride, width).ok_or_else(too_small)?; - for (sample, pixel) in luma.iter_mut().zip(pixels) { - *sample = pixel[2]; - } - let chroma = destination(cbcr, row, cbcr_stride, width * 2).ok_or_else(too_small)?; - for (pair, pixel) in chroma.as_chunks_mut::<2>().0.iter_mut().zip(pixels) { - *pair = [pixel[1], pixel[0]]; - } + let luma = destination(y, row, y_stride, luma_bytes).ok_or_else(too_small)?; + let chroma = destination(cbcr, row, cbcr_stride, chroma_bytes).ok_or_else(too_small)?; + split_row(format, &row_bytes, luma, chroma); } Ok(()) } +/// One row of [`split_packed`]: `packed`'s pixels into `luma`'s samples and +/// `chroma`'s pairs, as many as each holds. +fn split_row(format: SurfaceFormat, packed: &[u8], luma: &mut [u8], chroma: &mut [u8]) { + match format { + SurfaceFormat::Xyuv => { + let (pixels, _) = packed.as_chunks::<4>(); + for (sample, pixel) in luma.iter_mut().zip(pixels) { + *sample = pixel[2]; + } + for (pair, pixel) in chroma.as_chunks_mut::<2>().0.iter_mut().zip(pixels) { + *pair = [pixel[1], pixel[0]]; + } + } + // Y0, Cb, Y1, Cr. + SurfaceFormat::Yuy2 => { + let (groups, _) = packed.as_chunks::<4>(); + for (samples, group) in luma.chunks_mut(2).zip(groups) { + for (sample, y) in samples.iter_mut().zip([group[0], group[2]]) { + *sample = y; + } + } + for (pair, group) in chroma.as_chunks_mut::<2>().0.iter_mut().zip(groups) { + *pair = [group[1], group[3]]; + } + } + // As YUY2, in 16-bit words. + SurfaceFormat::Y210 | SurfaceFormat::Y212 => { + let (groups, _) = packed.as_chunks::<8>(); + for (samples, group) in luma.chunks_mut(4).zip(groups) { + let (y0, y1) = ([group[0], group[1]], [group[4], group[5]]); + for (sample, y) in samples.chunks_mut(2).zip([y0, y1]) { + sample.copy_from_slice(&y[..sample.len()]); + } + } + for (pair, group) in chroma.as_chunks_mut::<4>().0.iter_mut().zip(groups) { + *pair = [group[2], group[3], group[6], group[7]]; + } + } + // Cb, Y and Cr in 10-bit fields of a 32-bit word, moved to the top of 16 bits. + SurfaceFormat::Y410 => { + let (pixels, _) = packed.as_chunks::<4>(); + let field = |w: u32, at: u32| ((((w >> at) & 0x3ff) as u16) << 6).to_le_bytes(); + for (sample, pixel) in luma.as_chunks_mut::<2>().0.iter_mut().zip(pixels) { + *sample = field(u32::from_le_bytes(*pixel), 10); + } + for (pair, pixel) in chroma.as_chunks_mut::<4>().0.iter_mut().zip(pixels) { + let w = u32::from_le_bytes(*pixel); + let (cb, cr) = (field(w, 0), field(w, 20)); + *pair = [cb[0], cb[1], cr[0], cr[1]]; + } + } + // Cb, Y, Cr and alpha, in 16-bit words. + SurfaceFormat::Y412 => { + let (pixels, _) = packed.as_chunks::<8>(); + for (sample, pixel) in luma.as_chunks_mut::<2>().0.iter_mut().zip(pixels) { + *sample = [pixel[2], pixel[3]]; + } + for (pair, pixel) in chroma.as_chunks_mut::<4>().0.iter_mut().zip(pixels) { + *pair = [pixel[0], pixel[1], pixel[4], pixel[5]]; + } + } + SurfaceFormat::Nv12 | SurfaceFormat::P010 | SurfaceFormat::P012 => {} + } +} + /// Copies `rect` out of `bytes`, whose planes are at `offsets` with /// `pitches`, row by row, into the luma and chroma destinations, each with /// its stride, with `copy` for each row. @@ -264,12 +363,12 @@ pub(crate) enum HostFormat { } impl HostFormat { - /// The decoders' format's; `None` for XYUV, which no host surface is of. + /// The decoders' format's; `None` for the others, which no host surface is of. pub(crate) fn of(format: SurfaceFormat) -> Option { match format { SurfaceFormat::Nv12 => Some(Self::Nv12), SurfaceFormat::P010 => Some(Self::P010), - SurfaceFormat::Xyuv => None, + _ => None, } } @@ -854,7 +953,7 @@ pub(crate) struct MappedRead<'a> { #[cfg(test)] mod tests { - use super::{HostFormat, Rect, SurfaceFormat, copy_rect, copy_row, split_xyuv}; + use super::{HostFormat, Rect, SurfaceFormat, copy_rect, copy_row, split_packed}; use crate::vaapi::va::display::Error; /// An NV12 frame of 4x4 in 8 bytes a row: luma 0 to 31, then chroma @@ -900,8 +999,9 @@ mod tests { bytes[at..at + 4].copy_from_slice(&[40 + n, 20 + n, n, 0xff]); } let (mut y, mut cbcr) = (vec![0; 2 * 3], vec![0; 2 * 5]); - let split = split_xyuv( + let split = split_packed( &bytes, + SurfaceFormat::Xyuv, (4, 16), rect(1, 0, 2, 2), [(&mut y, 3), (&mut cbcr, 5)], @@ -913,8 +1013,9 @@ mod tests { assert_eq!(cbcr, [21, 41, 22, 42, 0, 24, 44, 25, 45, 0]); // A crop past the plane, and destinations too small, are refused. let (mut y, mut cbcr) = (vec![0; 6], vec![0; 12]); - let past = split_xyuv( + let past = split_packed( &bytes, + SurfaceFormat::Xyuv, (4, 16), rect(0, 1, 3, 2), [(&mut y, 3), (&mut cbcr, 6)], @@ -922,8 +1023,9 @@ mod tests { ); assert!(matches!(past, Err(Error::Unsupported(_)))); let (mut y, mut cbcr) = (vec![0; 6], vec![0; 7]); - let small = split_xyuv( + let small = split_packed( &bytes, + SurfaceFormat::Xyuv, (4, 16), rect(0, 0, 3, 2), [(&mut y, 3), (&mut cbcr, 6)], @@ -932,6 +1034,116 @@ mod tests { assert!(matches!(small, Err(Error::PlaneTooSmall(_)))); } + /// Splits a packed plane of `format`, `pixels` of its row's bytes from byte 2 at `pitch`, + /// two rows, from column `x`, `width` wide, into planes of exactly their rows' bytes. + fn split( + format: SurfaceFormat, + row: &[u8], + pitch: usize, + (x, width): (u32, u32), + ) -> Result<(Vec, Vec), Error> { + let mut bytes = vec![0xee; 2 + 2 * pitch]; + for r in 0..2 { + bytes[2 + r * pitch..2 + r * pitch + row.len()].copy_from_slice(row); + } + let sample = format.bytes_per_sample(); + let pairs = super::packed_pairs(format, width as usize); + let (y_row, cbcr_row) = (width as usize * sample, pairs * 2 * sample); + let (mut y, mut cbcr) = (vec![0; 2 * y_row], vec![0; 2 * cbcr_row]); + split_packed( + &bytes, + format, + (2, pitch), + rect(x, 0, width, 2), + [(&mut y, y_row), (&mut cbcr, cbcr_row)], + copy_row, + )?; + assert_eq!( + (y[..y_row].to_vec(), cbcr[..cbcr_row].to_vec()), + (y[y_row..].to_vec(), cbcr[cbcr_row..].to_vec()) + ); + y.truncate(y_row); + cbcr.truncate(cbcr_row); + Ok((y, cbcr)) + } + + /// YUY2's Y0, Cb, Y1, Cr bytes, and Y210's and Y212's 16-bit words in that order, split into + /// luma and a Cb/Cr pair for each two pixels; an odd width takes its last pair's first + /// luma sample alone. + #[test] + fn a_4_2_2_rectangle_splits_into_luma_and_a_pair_for_two_pixels() -> Result<(), Error> { + let row = [10, 20, 11, 30, 12, 21, 13, 31]; + let (y, cbcr) = split(SurfaceFormat::Yuy2, &row, 12, (0, 4))?; + assert_eq!((y, cbcr), (vec![10, 11, 12, 13], vec![20, 30, 21, 31])); + let (y, cbcr) = split(SurfaceFormat::Yuy2, &row, 12, (2, 1))?; + assert_eq!((y, cbcr), (vec![12], vec![21, 31])); + let words: Vec = [ + 0x1000u16, 0x2040, 0x1100, 0x3080, 0x1200, 0x20c0, 0x1300, 0x3100, + ] + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + for format in [SurfaceFormat::Y210, SurfaceFormat::Y212] { + let (y, cbcr) = split(format, &words, 20, (0, 3))?; + assert_eq!(y, [0x00, 0x10, 0x00, 0x11, 0x00, 0x12]); + assert_eq!(cbcr, [0x40, 0x20, 0x80, 0x30, 0xc0, 0x20, 0x00, 0x31]); + } + // A first column inside a pair is refused. + assert!(matches!( + split(SurfaceFormat::Yuy2, &row, 12, (1, 2)), + Err(Error::Unsupported(_)) + )); + Ok(()) + } + + /// Y410's 10-bit fields, Cb in bits 0 to 9, Y in 10 to 19 and Cr in 20 to 29, land at the + /// top of 16-bit words, as P010's and CoreVideo's `x444`'s samples lie; Y412's 16-bit Cb, Y, + /// Cr and alpha words land as they are. + #[test] + fn a_4_4_4_rectangle_of_deep_samples_splits_into_16_bit_words() -> Result<(), Error> { + let pixel = |cb: u32, y: u32, cr: u32| (3 << 30 | cr << 20 | y << 10 | cb).to_le_bytes(); + let row: Vec = [pixel(0x3ff, 64, 512), pixel(1, 940, 0)].concat(); + let (y, cbcr) = split(SurfaceFormat::Y410, &row, 12, (0, 2))?; + let words = |w: &[u16]| -> Vec { w.iter().flat_map(|w| w.to_le_bytes()).collect() }; + assert_eq!(y, words(&[64 << 6, 940 << 6])); + assert_eq!(cbcr, words(&[0x3ff << 6, 512 << 6, 1 << 6, 0])); + let row = words(&[ + 0x1230, 0x4560, 0x7890, 0xfff0, 0xabc0, 0xdef0, 0x0120, 0xfff0, + ]); + let (y, cbcr) = split(SurfaceFormat::Y412, &row, 20, (0, 2))?; + assert_eq!(y, words(&[0x4560, 0xdef0])); + assert_eq!(cbcr, words(&[0x1230, 0x7890, 0xabc0, 0x0120])); + Ok(()) + } + + /// A two-plane format, given as packed, is refused, as is a pitch whose rows wrap: none + /// indexes out of its slices. + #[test] + fn a_packed_split_of_a_planar_format_or_a_wrapping_pitch_is_refused() { + let bytes = vec![0; 64]; + let (mut y, mut cbcr) = (vec![0; 8], vec![0; 8]); + let planar = split_packed( + &bytes, + SurfaceFormat::P012, + (0, 16), + rect(0, 0, 2, 2), + [(&mut y, 4), (&mut cbcr, 4)], + copy_row, + ); + assert!(matches!(planar, Err(Error::Unsupported(_)))); + for (offset, pitch) in [(0, usize::MAX), (usize::MAX, 16)] { + let wraps = split_packed( + &bytes, + SurfaceFormat::Y410, + (offset, pitch), + rect(0, 0, 1, 2), + [(&mut y, 4), (&mut cbcr, 4)], + copy_row, + ); + assert!(matches!(wraps, Err(Error::Unsupported(_)))); + } + } + #[test] fn strides_and_offsets_past_the_address_space_are_refused() { let bytes = frame(); diff --git a/crates/reims-vgpu-video/src/vaapi/va/surface.rs b/crates/reims-vgpu-video/src/vaapi/va/surface.rs index 12b4ff5e1..953ae698e 100644 --- a/crates/reims-vgpu-video/src/vaapi/va/surface.rs +++ b/crates/reims-vgpu-video/src/vaapi/va/surface.rs @@ -1,8 +1,10 @@ //! Decode surfaces: a pool of surfaces of one format and size, lent out //! one at a time, and their readback into caller-provided planes. 8-bit -//! 4:2:0 is NV12, 10-bit 4:2:0 is P010, and 8-bit 4:4:4 is XYUV, whose -//! frames are split into two planes as they are read back -//! ([`SurfaceReadBack::copy_4_4_4_to`]). +//! 4:2:0 is NV12, 10-bit 4:2:0 is P010 and 12-bit P012, each of two planes +//! read back as they are; the range extensions' 4:2:2 and 4:4:4 are packed +//! in one plane (YUY2, Y210, Y212; XYUV, Y410, Y412), whose frames are split +//! into two planes as they are read back +//! ([`SurfaceReadBack::copy_packed_to`]). //! //! A pool makes a surface only when one is asked of it and none is free //! ([`SurfacePool::get`]), so it holds no more surfaces than were lent at @@ -27,6 +29,7 @@ use std::sync::{Arc, OnceLock}; use std::time::Duration; +use crate::core::backend::Chroma; use crate::core::runtime::MonoTime; use crate::core::sync::{Mutex, MutexGuard}; @@ -55,7 +58,7 @@ mod shared; const MAX_SURFACES: usize = 48; /// What a pool's surfaces hold: 4:2:0 in two planes, luma then -/// interleaved Cb/Cr, or 4:4:4 packed in one. +/// interleaved Cb/Cr, or 4:2:2 or 4:4:4 packed in one (va_fourcc.h's layouts). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub(crate) enum SurfaceFormat { /// 8-bit samples (`VA_FOURCC_NV12`). @@ -63,10 +66,30 @@ pub(crate) enum SurfaceFormat { /// 10-bit samples in the top bits of little-endian 16-bit words /// (`VA_FOURCC_P010`). P010, + /// 12-bit samples in the top bits of little-endian 16-bit words, as P010 + /// (`VA_FOURCC_P012`). HEVC Main 12's. + P012, + /// 8-bit 4:2:2 in one plane, four bytes for two pixels: Y0, Cb, Y1, Cr, + /// in that order in memory (`VA_FOURCC_YUY2`). HEVC Main 4:2:2 10's at 8 + /// bits. + Yuy2, + /// 10-bit 4:2:2 as YUY2, each sample in the top bits of a little-endian + /// 16-bit word (`VA_FOURCC_Y210`). HEVC Main 4:2:2 10's. + Y210, + /// 12-bit 4:2:2 as Y210 (`VA_FOURCC_Y212`). HEVC Main 4:2:2 12's. + Y212, /// 8-bit 4:4:4 in one plane, four bytes a pixel: Cr, Cb, Y and one /// unused, in that order in memory (`VA_FOURCC_XYUV`, ffmpeg's `VUYX`). /// HEVC Main 4:4:4's. Xyuv, + /// 10-bit 4:4:4 in one plane, a little-endian 32-bit word a pixel: Cb in + /// its bits 0 to 9, Y in 10 to 19, Cr in 20 to 29, and 2 of alpha + /// (`VA_FOURCC_Y410`). HEVC Main 4:4:4 10's. + Y410, + /// 12-bit 4:4:4 in one plane, four little-endian 16-bit words a pixel, + /// each sample in their top bits: Cb, Y, Cr and alpha, in that order in + /// memory (`VA_FOURCC_Y412`). HEVC Main 4:4:4 12's. + Y412, } impl SurfaceFormat { @@ -75,7 +98,13 @@ impl SurfaceFormat { match self { Self::Nv12 => ffi::VA_RT_FORMAT_YUV420, Self::P010 => ffi::VA_RT_FORMAT_YUV420_10, + Self::P012 => ffi::VA_RT_FORMAT_YUV420_12, + Self::Yuy2 => ffi::VA_RT_FORMAT_YUV422, + Self::Y210 => ffi::VA_RT_FORMAT_YUV422_10, + Self::Y212 => ffi::VA_RT_FORMAT_YUV422_12, Self::Xyuv => ffi::VA_RT_FORMAT_YUV444, + Self::Y410 => ffi::VA_RT_FORMAT_YUV444_10, + Self::Y412 => ffi::VA_RT_FORMAT_YUV444_12, } } @@ -83,7 +112,13 @@ impl SurfaceFormat { match self { Self::Nv12 => ffi::VA_FOURCC_NV12, Self::P010 => ffi::VA_FOURCC_P010, + Self::P012 => ffi::VA_FOURCC_P012, + Self::Yuy2 => ffi::VA_FOURCC_YUY2, + Self::Y210 => ffi::VA_FOURCC_Y210, + Self::Y212 => ffi::VA_FOURCC_Y212, Self::Xyuv => ffi::VA_FOURCC_XYUV, + Self::Y410 => ffi::VA_FOURCC_Y410, + Self::Y412 => ffi::VA_FOURCC_Y412, } } @@ -91,33 +126,52 @@ impl SurfaceFormat { pub(crate) fn bits_per_pixel(self) -> u32 { match self { Self::Nv12 => 12, - Self::P010 => 24, - Self::Xyuv => 32, + Self::P010 | Self::P012 => 24, + Self::Yuy2 => 16, + Self::Y210 | Self::Y212 | Self::Xyuv | Self::Y410 => 32, + Self::Y412 => 64, } } - /// The bytes one sample takes. + /// The bytes one sample takes as it is read back into two planes: one at 8 bits, two + /// deeper. pub(crate) fn bytes_per_sample(self) -> usize { - match self { - Self::Nv12 | Self::Xyuv => 1, - Self::P010 => 2, - } + if self.bit_depth() == 8 { 1 } else { 2 } } - /// The bytes a pixel takes in its first plane: a luma sample, or a packed pixel's four. + /// The bytes a pixel takes in its first plane: a luma sample, or a packed pixel's. pub(crate) fn first_plane_bytes_per_pixel(self) -> usize { match self { Self::Nv12 => 1, - Self::P010 => 2, - Self::Xyuv => 4, + Self::P010 | Self::P012 | Self::Yuy2 => 2, + Self::Y210 | Self::Y212 | Self::Xyuv | Self::Y410 => 4, + Self::Y412 => 8, } } /// Its planes: luma and chroma, or one of packed pixels. pub(crate) fn planes(self) -> u32 { match self { - Self::Nv12 | Self::P010 => 2, - Self::Xyuv => 1, + Self::Nv12 | Self::P010 | Self::P012 => 2, + Self::Yuy2 | Self::Y210 | Self::Y212 | Self::Xyuv | Self::Y410 | Self::Y412 => 1, + } + } + + /// How its chroma is sampled. + pub(crate) fn chroma(self) -> Chroma { + match self { + Self::Nv12 | Self::P010 | Self::P012 => Chroma::Yuv420, + Self::Yuy2 | Self::Y210 | Self::Y212 => Chroma::Yuv422, + Self::Xyuv | Self::Y410 | Self::Y412 => Chroma::Yuv444, + } + } + + /// The bits a sample holds. + pub(crate) fn bit_depth(self) -> u8 { + match self { + Self::Nv12 | Self::Yuy2 | Self::Xyuv => 8, + Self::P010 | Self::Y210 | Self::Y410 => 10, + Self::P012 | Self::Y212 | Self::Y412 => 12, } } @@ -126,7 +180,13 @@ impl SurfaceFormat { match self { Self::Nv12 => "NV12", Self::P010 => "P010", + Self::P012 => "P012", + Self::Yuy2 => "YUY2", + Self::Y210 => "Y210", + Self::Y212 => "Y212", Self::Xyuv => "XYUV", + Self::Y410 => "Y410", + Self::Y412 => "Y412", } } } @@ -706,33 +766,41 @@ impl SurfaceReadBack<'_> { Ok(()) } - /// Copies `rect` of an XYUV surface into two planes of 8-bit 4:4:4, as - /// CoreVideo's `444v` and ffmpeg's `nv24` lay them out: `y` with - /// `y_stride` bytes a row, and `cbcr`, each pixel's Cb then Cr, with - /// `cbcr_stride`; `rect.height` rows each. The CPU's copy alone: each - /// row is read whole with the way back's row copy, then split. - pub(crate) fn copy_4_4_4_to( + /// Copies `rect` of a packed surface into two planes, as CoreVideo's two-plane formats of + /// its chroma format and depth lay them out (`readback::split_packed`): `y` with `y_stride` + /// bytes a row, and `cbcr`, each pair's Cb then Cr, with `cbcr_stride`; `rect.height` rows + /// each. The CPU's copy alone: each row is read whole with the way back's row copy, then + /// split. + pub(crate) fn copy_packed_to( &self, rect: Rect, (y, y_stride): (&mut [u8], usize), (cbcr, cbcr_stride): (&mut [u8], usize), ) -> Result<(), Error> { let pool = &self.surface.pool; - if pool.format != SurfaceFormat::Xyuv { + if pool.format.planes() != 1 { return Err(Error::Unsupported(format!( - "reading a {} frame back as 4:4:4", + "reading a {} frame back as packed pixels", pool.format.name() ))); } let (width, rows) = (to_usize(rect.width), to_usize(rect.height)); + let sample = pool.format.bytes_per_sample(); + let pairs = readback::packed_pairs(pool.format, width); self.check_planes( rect, - (y.len(), y_stride, rows, width), - (cbcr.len(), cbcr_stride, rows, width.saturating_mul(2)), + (y.len(), y_stride, rows, width.saturating_mul(sample)), + ( + cbcr.len(), + cbcr_stride, + rows, + pairs.saturating_mul(2 * sample), + ), )?; let started = pool.display.runtime().now(); - readback::split_xyuv( + readback::split_packed( self.bytes(), + pool.format, self.read.planes[0], rect, [(y, y_stride), (cbcr, cbcr_stride)], diff --git a/crates/reims-vgpu-video/src/vaapi/va/target.rs b/crates/reims-vgpu-video/src/vaapi/va/target.rs index c2a63d9fb..6b9f3d6a3 100644 --- a/crates/reims-vgpu-video/src/vaapi/va/target.rs +++ b/crates/reims-vgpu-video/src/vaapi/va/target.rs @@ -73,12 +73,12 @@ impl TargetFormat { } } - /// A decode's of `format`; `None` for XYUV, which no target is of. + /// A decode's of `format`; `None` for the range extensions' formats, which no target is of. pub(crate) fn of(format: SurfaceFormat) -> Option { match format { SurfaceFormat::Nv12 => Some(TargetFormat::Nv12), SurfaceFormat::P010 => Some(TargetFormat::P010), - SurfaceFormat::Xyuv => None, + _ => None, } } diff --git a/crates/reims-vgpu-video/src/vaapi/va/target_probe.rs b/crates/reims-vgpu-video/src/vaapi/va/target_probe.rs index 853d843b6..848e74b48 100644 --- a/crates/reims-vgpu-video/src/vaapi/va/target_probe.rs +++ b/crates/reims-vgpu-video/src/vaapi/va/target_probe.rs @@ -61,8 +61,11 @@ fn import( let drm_format = match format { SurfaceFormat::Nv12 => ffi::DRM_FORMAT_NV12, SurfaceFormat::P010 => ffi::DRM_FORMAT_P010, - SurfaceFormat::Xyuv => { - return Err(Error::Unsupported("a probe surface of XYUV".into())); + other => { + return Err(Error::Unsupported(format!( + "a probe surface of {}", + other.name() + ))); } }; let (w, h) = (width as usize, height as usize); diff --git a/crates/reims-vgpu-video/src/vaapi/va/zero_copy.rs b/crates/reims-vgpu-video/src/vaapi/va/zero_copy.rs index 1f992d16d..f7721620c 100644 --- a/crates/reims-vgpu-video/src/vaapi/va/zero_copy.rs +++ b/crates/reims-vgpu-video/src/vaapi/va/zero_copy.rs @@ -83,7 +83,7 @@ use std::os::fd::{AsFd, AsRawFd, OwnedFd}; use std::sync::{Arc, Weak}; -use crate::core::backend::DeviceWrite; +use crate::core::backend::{Chroma, DeviceWrite}; use crate::core::device_memory::{DeviceImports, DeviceMemory, GuestTarget, TargetPlane}; #[cfg(unix)] use crate::core::device_memory::{DmaBufError, SurfaceDmaBuf}; @@ -395,10 +395,11 @@ pub(crate) fn write( ) -> Result { let format = frame.surface.format(); // The driver's 4:2:0 frames, NV12 and P010, into two planes; a 4:4:4 one, XYUV, is - // written whole into a packed buffer alone (`write_packed`). - if format == SurfaceFormat::Xyuv + // written whole into a packed buffer alone (`write_packed`), and the range extensions' + // others are read back. + if !matches!(format, SurfaceFormat::Nv12 | SurfaceFormat::P010) || target.pixel_format().bytes_per_sample() != format.bytes_per_sample() - || target.pixel_format().is_4_4_4() + || target.pixel_format().chroma() != Chroma::Yuv420 { return Ok(declined(format!( "a {} buffer for {} frames", diff --git a/crates/reims-vgpu-video/tools/hevc-check.sh b/crates/reims-vgpu-video/tools/hevc-check.sh index 73074e63d..74871372f 100755 --- a/crates/reims-vgpu-video/tools/hevc-check.sh +++ b/crates/reims-vgpu-video/tools/hevc-check.sh @@ -15,12 +15,14 @@ # record and length-prefixed samples, as VideoToolbox hands them over) and # from its Annex B form, in display order; every frame's MD5, over NV12 # for Main and P010 for Main 10, must equal ffmpeg's. Decode order must -# give the same frames. Streams the decoder must refuse (4:2:2 and 12-bit, -# which the codec crate refuses) must fail with their refusal. The range -# extensions' 4:4:4 at 8 bits decodes, its MD5s over NV24, where the -# driver lists a Main 4:4:4 decoder of 4:4:4 render targets and XYUV -# surfaces (examples/vaapi-probe), and is refused, naming the driver's -# Main 4:4:4, where it does not. +# give the same frames. The range extensions' streams, 4:2:0 at 12 bits and +# 4:2:2 and 4:4:4 at 8, 10 and 12, each decode, their MD5s over the two +# planes a VideoToolbox decoder's picture lands in (P012; NV16, P210, P212; +# NV24, P410, P412), where the driver lists the decoder of their chroma +# format and depth (Main 12, Main 4:2:2 10, Main 4:2:2 12, Main 4:4:4, +# Main 4:4:4 10 and Main 4:4:4 12) with their render targets and the +# surfaces the VA crate decodes them into (examples/vaapi-probe), and are +# refused, naming the driver's profile, where it does not. # # x265's own reconstruction (--recon) is a second reference. ffmpeg n9.0.2's # software decode differs from it on some CTB-16 streams with SAO and @@ -53,13 +55,29 @@ info=$CARGO_TARGET_DIR/release/examples/hevc-info cut=$CARGO_TARGET_DIR/release/examples/hevc-cut craft=$CARGO_TARGET_DIR/release/examples/hevc-craft -# Whether the driver lists HEVC Main 4:4:4's decoder of 4:4:4 render -# targets and XYUV surfaces, the 4:4:4 streams' decode. -four_four_four=0 +# The range extensions' decoder of a chroma format and depth: the VA +# profile, its render-target format, the surfaces the VA crate decodes into +# (its range_extensions_decoder) and the two planes ffmpeg's reference is +# in, for CHROMA (420, 422, 444) and BITS. +rext_decoder() { + case $1/$2 in + 420/12) echo "HEVCMain12 YUV420_12 P012 p012le" ;; + 422/8) echo "HEVCMain422_10 YUV422 YUY2 nv16" ;; + 422/10) echo "HEVCMain422_10 YUV422_10 Y210 p210le" ;; + 422/12) echo "HEVCMain422_12 YUV422_12 Y212 p212le" ;; + 444/8) echo "HEVCMain444 YUV444 XYUV nv24" ;; + 444/10) echo "HEVCMain444_10 YUV444_10 Y410 p410le" ;; + 444/12) echo "HEVCMain444_12 YUV444_12 Y412 p412le" ;; + esac +} probe=$("$CARGO_TARGET_DIR/release/examples/vaapi-probe" "$node" 2>&1 || true) -if grep -Eq '^HEVCMain444 +VLD +rt=([^ ]*,)?YUV444[, ].* surfaces=([^ ]*,)?XYUV[, ]' <<<"$probe"; then - four_four_four=1 -fi +# Whether the driver lists the decoder of CHROMA at BITS, of its render +# targets and surfaces. +rext_listed() { + local profile rt fourcc _ + read -r profile rt fourcc _ <<<"$(rext_decoder "$1" "$2")" + grep -Eq "^$profile +VLD +rt=([^ ]*,)?$rt[, ].* surfaces=([^ ]*,)?$fourcc[, ]" <<<"$probe" +} # Asymmetric scaling lists in HM's format, so that a list in the wrong # scan order, transposed, in the wrong slot or with the wrong DC changes @@ -127,14 +145,23 @@ streams=( "main-720p-ref1|1280x720|60|8|testsrc2|--preset fast --bframes 0 --ref 1 --no-temporal-mvp --keyint 300" ) -# The range extensions' 4:4:4 at 8 bits, x265's: name|size|frames|source -# filter|x265 options. Each frame's MD5 is over NV24, luma then each -# pixel's Cb and Cr, the two planes the decoder lands it in; the fade's +# The range extensions' streams, x265's: name|size|frames|bits|chroma|source +# filter|x265 options. Each frame's MD5 is over the two planes the decoder +# lands it in, luma then the Cb and Cr pairs (rext_decoder); the fades' # weighted prediction sends the slices' range extension parameters. rext_streams=( - "main444-360p|640x360|10|testsrc2|--preset fast --profile main444-8" - "main444-720p-fade|1280x720|60|fade|--preset fast --profile main444-8 --weightp --weightb --bframes 3 --ref 3" - "main444-1366x766-ctu16|1366x766|30|testsrc2|--preset fast --profile main444-8 --ctu 16 --bframes 2 --tskip" + "main444-360p|640x360|10|8|444|testsrc2|--preset fast --profile main444-8" + "main444-720p-fade|1280x720|60|8|444|fade|--preset fast --profile main444-8 --weightp --weightb --bframes 3 --ref 3" + "main444-1366x766-ctu16|1366x766|30|8|444|testsrc2|--preset fast --profile main444-8 --ctu 16 --bframes 2 --tskip" + "main12-360p|640x360|10|12|420|testsrc2|--preset fast --profile main12" + "main12-720p-fade|1280x720|30|12|420|fade|--preset fast --profile main12 --weightp --weightb --bframes 3 --ref 3" + "main422-8-360p|640x360|10|8|422|testsrc2|--preset fast --profile main422-10 --bframes 3" + "main422-10-720p|1280x720|30|10|422|testsrc2|--preset fast --profile main422-10 --bframes 3 --ref 3" + "main422-10-1366x766-ctu16|1366x766|20|10|422|testsrc2|--preset fast --profile main422-10 --ctu 16 --bframes 2 --tskip" + "main422-12-720p-fade|1280x720|30|12|422|fade|--preset fast --profile main422-12 --weightp --weightb --bframes 3" + "main444-10-720p|1280x720|30|10|444|testsrc2|--preset fast --profile main444-10 --bframes 3 --ref 3" + "main444-12-720p-fade|1280x720|30|12|444|fade|--preset fast --profile main444-12 --weightp --weightb --bframes 3" + "main444-12-1366x766-ctu16|1366x766|20|12|444|testsrc2|--preset fast --profile main444-12 --ctu 16 --tskip" ) # kvazaar 2.3.2's streams, 8 bits only as CachyOS builds it, for what x265 @@ -220,10 +247,10 @@ encode() { return 1 fi local pix_out=nv12 - if (( bits > 8 )); then + if [[ $csp != 420 || $bits == 12 ]]; then + read -r _ _ _ pix_out <<<"$(rext_decoder "$csp" "$bits")" + elif (( bits > 8 )); then pix_out=p010le - elif [[ $csp == 444 ]]; then - pix_out=nv24 fi hashes "$out/$name.recon" -i "$out/$name.recon.y4m" -pix_fmt "$pix_out" || return 1 rm -f "$out/$name.recon.y4m" @@ -333,17 +360,12 @@ bits_of() { } # What the decoder refuses, cleanly, before any slice reaches the GPU: -# x265's name|size|frames|bits|chroma|options|what the refusal says, and kvazaar's -# name|size|frames|source filter|options|what the refusal says. kvazaar -# takes tile columns of 64 samples, one CTB, which radeonsi decodes wrongly -# with no error, and the codec crate refuses columns under 128. -rext='^hevc-framemd5: unsupported: range extensions streams other than 4:4:4 at 8 bits' -refusals=( - "main422-10|640x360|10|10|422|--preset fast --profile main422-10|$rext" - "main12|640x360|10|12|420|--preset fast --profile main12|$rext" -) -# The 4:4:4 streams' refusal where the driver decodes none of them. -rext_refused='^hevc-framemd5: (sample [0-9]+: )?the driver cannot: HEVCMain444: ' +# kvazaar's name|size|frames|source filter|options|what the refusal says. +# kvazaar takes tile columns of 64 samples, one CTB, which radeonsi decodes +# wrongly with no error, and the codec crate refuses columns under 128. +# Every stream x265 writes the codec crate now takes; a range extensions +# stream is refused, naming its profile, where the driver lists no decoder +# of it (rext_listed). kvazaar_refusals=( "kvz-720p-tiles-col64|1280x720|10|testsrc2|--preset fast --gop 8 --level 5.1 --tiles-width-split 64,128,1216|ColumnWidthInLumaSamples is out of range" ) @@ -357,11 +379,14 @@ kvazaar_partial=( ) echo "hevc-check on $node, $(date -Is), $(hostname), $(x265 --version 2>&1 | grep -m1 -o 'version [^ ]*'), $(kvazaar --version 2>&1 | head -n1)" -if (( four_four_four )); then - echo " 4:4:4 at 8 bits: the driver lists HEVC Main 4:4:4's decoder into XYUV: decoded" -else - echo " 4:4:4 at 8 bits: the driver lists no HEVC Main 4:4:4 decoder into XYUV: refused" -fi +for csp_bits in 420/12 422/8 422/10 422/12 444/8 444/10 444/12; do + read -r profile rt fourcc _ <<<"$(rext_decoder "${csp_bits%/*}" "${csp_bits#*/}")" + if rext_listed "${csp_bits%/*}" "${csp_bits#*/}"; then + echo " ${csp_bits%/*} at ${csp_bits#*/} bits: the driver lists $profile's decoder of $rt into $fourcc: decoded" + else + echo " ${csp_bits%/*} at ${csp_bits#*/} bits: the driver lists no $profile decoder of $rt into $fourcc: refused" + fi +done # Every stream and its reference first, then the GPU. Each checked stream # goes into `made` as name|bits. @@ -383,13 +408,14 @@ for entry in "${streams[@]}"; do made+=("$name|$bits") done for entry in "${rext_streams[@]}"; do - IFS='|' read -r name size frames kind opts <<<"$entry" - if ! encode "$name" "$size" "$frames" 8 "$kind" "$opts" 444; then + IFS='|' read -r name size frames bits csp kind opts <<<"$entry" + if ! encode "$name" "$size" "$frames" "$bits" "$kind" "$opts" "$csp"; then failed=1 continue fi - (( four_four_four )) || continue - reference "$name" 8 nv24 + rext_listed "$csp" "$bits" || continue + read -r _ _ _ pix <<<"$(rext_decoder "$csp" "$bits")" + reference "$name" "$bits" "$pix" cp "$out/$name.ref" "$out/$name.expect" if ! cmp -s "$out/$name.ref" "$out/$name.recon"; then echo "NOTE $name: ffmpeg's decode differs from x265's reconstruction from frame" \ @@ -476,10 +502,6 @@ for entry in "${crafted[@]}"; do cp "$out/$source.expect" "$out/$name.expect" made+=("$name|$bits") done -for entry in "${refusals[@]}"; do - IFS='|' read -r name size frames bits csp opts _ <<<"$entry" - encode "$name" "$size" "$frames" "$bits" testsrc2 "$opts" "$csp" || failed=1 -done for entry in "${kvazaar_refusals[@]}" "${kvazaar_partial[@]}"; do IFS='|' read -r name size frames kind opts _ _ <<<"$entry" if encode_kvazaar "$name" "$size" "$frames" "$kind" "$opts"; then @@ -562,21 +584,18 @@ if run "$out/$name.265" "$name.annexb"; then check "$name (Annex B, display order)" "$out/$name.expect" "$out/$name.annexb.md5" fi -# A stream to refuse that was not made has failed already. -for entry in "${refusals[@]}"; do - IFS='|' read -r name _ _ _ _ _ why <<<"$entry" +# A stream to refuse that was not made has failed already. A range +# extensions stream the driver lists no decoder of is refused naming its +# profile. +for entry in "${rext_streams[@]}"; do + IFS='|' read -r name _ _ bits csp _ <<<"$entry" + rext_listed "$csp" "$bits" && continue [[ -s $out/$name.mp4 ]] || continue - refused "$name" "$out/$name.mp4" "$why" -done -if (( ! four_four_four )); then - for entry in "${rext_streams[@]}"; do - IFS='|' read -r name _ <<<"$entry" - [[ -s $out/$name.mp4 ]] || continue - for input in "$out/$name.mp4" "$out/$name.265"; do - refused "$name (${input##*.})" "$input" "$rext_refused" - done + read -r profile _ <<<"$(rext_decoder "$csp" "$bits")" + for input in "$out/$name.mp4" "$out/$name.265"; do + refused "$name (${input##*.})" "$input" "^hevc-framemd5: (sample [0-9]+: )?the driver cannot: $profile: " done -fi +done for entry in "${kvazaar_refusals[@]}"; do IFS='|' read -r name _ _ _ _ why <<<"$entry" [[ -s $out/$name.mp4 ]] || continue diff --git a/crates/reims-vgpu-vulkan/src/answer.rs b/crates/reims-vgpu-vulkan/src/answer.rs index 9feaa0ca6..d2a2c75e9 100644 --- a/crates/reims-vgpu-vulkan/src/answer.rs +++ b/crates/reims-vgpu-vulkan/src/answer.rs @@ -178,7 +178,9 @@ pub fn out_of_host_memory_count() -> u64 { /// output's device caches from a scratch the driver's video processing wrote /// (`video-pictures-gpu-copied`, and their crops' KiB, `video-gpu-copied-kib`), and as its /// NVDEC video on Linux writes a VideoToolbox decoder's 4:4:4 picture into its surface's two -/// planes on the GPU (`video-pictures-gpu-gathered`), and as its video session's picture does not land after its command buffer +/// planes on the GPU (`video-pictures-gpu-gathered`), and as its video on Linux writes such a +/// decoder's picture into its surface's two planes on the CPU from a host surface of another +/// layout (`video-pictures-cpu-converted`), and as its video session's picture does not land after its command buffer /// completed at its decode, the session's next decode failing in its stead /// (`video-landing-failure-carried`); the rt platform's surfaces over Direct3D 11 textures on /// Windows, made (`rt-d3d11-surfaces`) and refused (`rt-refused-d3d11-surface`); and the objects diff --git a/crates/reims-vgpu/src/graphics/decode/video.rs b/crates/reims-vgpu/src/graphics/decode/video.rs index e519a554d..e9be932f0 100644 --- a/crates/reims-vgpu/src/graphics/decode/video.rs +++ b/crates/reims-vgpu/src/graphics/decode/video.rs @@ -125,10 +125,15 @@ pub trait GraphicsVideo: Send + Sync { /// Why a decoder of `codec` from [`Self::guest_decoder`] decodes none of `stream`'s pictures, /// a stream the codec crate's decoder takes, for VideoToolbox's session of it to be refused /// at its start (`reims_vgpu_video::paravirt::Backend::declines`); `None` where it decodes - /// them. The default takes 4:2:0 streams alone, which every arm's caps answer for. + /// them. The default takes 4:2:0 streams of Main and Main 10 alone, which every arm's caps + /// answer for. fn guest_declines(&self, _codec: u32, stream: &Stream) -> Option { - (stream.chroma_format_idc != 1) - .then(|| "the host's video decodes 4:2:0 pictures alone".to_owned()) + if stream.chroma_format_idc != 1 { + Some("the host's video decodes 4:2:0 pictures alone".to_owned()) + } else { + (stream.range_extensions) + .then(|| "the host's video decodes no range extensions pictures".to_owned()) + } } /// The encoders VideoToolbox's paravirtual encoder list names, whose source frames come in /// surfaces the guest lends ([`GuestEncoder`]): one for each codec the arm encodes so; none diff --git a/crates/reims-vgpu/src/graphics/nvidia.rs b/crates/reims-vgpu/src/graphics/nvidia.rs index f53a19c67..4ef959bca 100644 --- a/crates/reims-vgpu/src/graphics/nvidia.rs +++ b/crates/reims-vgpu/src/graphics/nvidia.rs @@ -56,20 +56,25 @@ //! output's pages above, else read back and copied by the CPU, each reason logged once a //! decoder. So every decode codec of the caps has one, and the device offers `VT_MESSAGES` //! where NVDEC decodes H.264 or HEVC. -//! - **HEVC's 4:4:4 at 8 bits**, the range extensions' streams the codec crate decodes, has a -//! paravirtual session where NVDEC decodes HEVC at 4:4:4 and that depth into its three -//! planes, at the stream's size; elsewhere the session is refused at its start, the reason -//! named (`GraphicsVideo::guest_declines`), and the guest decodes in software. The picture -//! lands in the surface's 4:4:4 formats ('444v', '444f'), its luma as it lies and its Cb and -//! Cr interleaved into the surface's second plane, by the GPU where CUDA imports the device's +//! - **HEVC's range extensions**, the codec crate's 4:2:0 and 4:4:4 at 8, 10 and 12 bits, have a +//! paravirtual session where NVDEC's caps say it decodes HEVC at the stream's chroma format +//! and depth into the output the decoder makes (NV12 or P016; 4:4:4's three planes, 8-bit or +//! 16-bit), at the stream's size; elsewhere, and for every 4:2:2 stream (no decode into +//! NVDEC's 4:2:2 outputs is built), the session is refused at its start, the reason named +//! (`GraphicsVideo::guest_declines`), and the guest decodes in software. A 4:2:0 picture +//! lands as Main 10's does, P016 copied into `tv20`/`tf20` at 12 bits, the two laid out +//! alike. A 4:4:4 picture lands in the surface's 4:4:4 format of its depth (`444v`, `x444`, +//! `tv44` and their full-range twins), its luma as it lies and its Cb and Cr interleaved into +//! the surface's second plane; at 8 bits by the GPU where CUDA imports the device's //! exportable buffers: one `cuMemcpy2D` a plane within the GPU into the decoder's scratch, //! an exportable buffer of the device's that CUDA imported, made at the decoder's first //! 4:4:4 picture (and again for a larger one) as zeros, its three planes one after another //! at one pitch, the width rounded up to 256 bytes; then the scratch said written //! (`Buffer::external_write_done`), and the platform library's `videoGather444` kernel writes //! the surface's two planes from it, through a Shared buffer over the surface's pages -//! (`super::gather`, counted as `video-pictures-gpu-gathered`). Where that is refused, the -//! picture is read back and interleaved by the CPU, the reason logged once a decoder: a +//! (`super::gather`, counted as `video-pictures-gpu-gathered`). Where that is refused, and +//! past 8 bits, which the kernel does not take, the picture is read back and interleaved by +//! the CPU (counted as `video-pictures-cpu-converted`), the reason logged once a decoder: a //! scratch the device or CUDA does not make, which the decoder does not ask again, no buffer //! over the surface, a plane off a 32-bit word, the kernel's pipeline refused. //! - **VideoToolbox's paravirtual encoders** (`encode`'s `guest`): an arm64 guest's encode, of @@ -88,7 +93,7 @@ use reims_vgpu_graphics::wire::{ RgfxVideoEncodeCaps, }; use reims_vgpu_video::codec::PictureStart; -use reims_vgpu_video::core::backend::BackendError as VideoError; +use reims_vgpu_video::core::backend::{BackendError as VideoError, Chroma}; use reims_vgpu_video::core::device_memory::{ DeviceImports, GuestTarget, MemoryIdentity, TargetPlane, }; @@ -112,8 +117,8 @@ use super::decode::{ }; use super::gather::{GatherPipeline, Gatherer, Planar, gathers}; use super::video_host::{ - BackendError, DecodeOutput, Extent, Failed, HostDecoder, HostEncodeSession, HostPicture, - HostVideoSession, Landing, OutputPlane, SourcePlane, picture_error, + BackendError, CONVERTED_CODE, DecodeOutput, Extent, Failed, HostDecoder, HostEncodeSession, + HostPicture, HostVideoSession, Landing, OutputPlane, SourcePlane, picture_error, }; mod encode; @@ -434,36 +439,53 @@ fn supported(gpu: &Gpu, codec: NvdecCodec, bit_depth: u32) -> Option Option { +/// Why NVDEC's decoders take none of `stream`'s pictures, an HEVC stream of the range +/// extensions: NVDEC's caps of HEVC at the stream's chroma format and depth, which are to say it +/// decodes it, into the output the decoder makes of them (4:2:0 into `SurfaceFormat::Nv12` at 8 +/// bits and `P016` past; 4:4:4 into its three planes, `Yuv444` at 8 bits and `Yuv444_16Bit` +/// past), at the stream's size; `None` where they do. A 4:2:2 stream is declined whatever they +/// say: no decode of it into NVDEC's 4:2:2 outputs is built here. +fn declines_range_extensions(gpu: &Gpu, stream: &Stream) -> Option { let bits = u32::from(stream.luma_bits); - let caps = match decode_capabilities(gpu, NvdecCodec::Hevc, ChromaFormat::Yuv444, bits) { - Ok(caps) => caps, - Err(error) => { + let (chroma, name) = match stream.chroma_format_idc { + 1 => (ChromaFormat::Yuv420, "4:2:0"), + 3 => (ChromaFormat::Yuv444, "4:4:4"), + 2 => { return Some(format!( - "{NAME}'s caps of HEVC 4:4:4 at {bits} bits: {error}" + "{NAME}'s decoders here land no HEVC 4:2:2 pictures" + )); + } + other => { + return Some(format!( + "{NAME} decodes HEVC of chroma_format_idc 1 to 3, not {other}" )); } }; - let output = if bits > 8 { - SurfaceFormat::Yuv444_16Bit - } else { - SurfaceFormat::Yuv444 + let caps = match decode_capabilities(gpu, NvdecCodec::Hevc, chroma, bits) { + Ok(caps) => caps, + Err(error) => { + return Some(format!( + "{NAME}'s caps of HEVC {name} at {bits} bits: {error}" + )); + } + }; + let output = match (chroma, bits > 8) { + (ChromaFormat::Yuv444, false) => SurfaceFormat::Yuv444, + (ChromaFormat::Yuv444, true) => SurfaceFormat::Yuv444_16Bit, + (_, true) => SurfaceFormat::P016, + (_, false) => SurfaceFormat::Nv12, }; let (width, height) = (stream.width, stream.height); if !caps.supported { - Some(format!("{NAME} does not decode HEVC 4:4:4 at {bits} bits")) + Some(format!("{NAME} does not decode HEVC {name} at {bits} bits")) } else if !caps.output_formats.contains(&output) { Some(format!( - "{NAME} writes HEVC 4:4:4 at {bits} bits as {:?}, not {output:?}", + "{NAME} writes HEVC {name} at {bits} bits as {:?}, not {output:?}", caps.output_formats )) } else if width < caps.min_width || height < caps.min_height { Some(format!( - "{NAME} decodes HEVC 4:4:4 from {}x{}, not {width}x{height}", + "{NAME} decodes HEVC {name} from {}x{}, not {width}x{height}", caps.min_width, caps.min_height )) } else if width > caps.max_width @@ -472,7 +494,7 @@ fn declines_4_4_4(gpu: &Gpu, stream: &Stream) -> Option { > u64::from(caps.max_macroblocks) { Some(format!( - "{NAME} decodes HEVC 4:4:4 up to {}x{} ({} macroblocks), not {width}x{height}", + "{NAME} decodes HEVC {name} up to {}x{} ({} macroblocks), not {width}x{height}", caps.max_width, caps.max_height, caps.max_macroblocks )) } else { @@ -580,7 +602,7 @@ impl GraphicsVideo

for Shared

{ _ => return None, }; let mut decoder = AnnexBDecoder::new(&video.gpu, annex_b, &video.runtime); - decoder.lands_4_4_4(); + decoder.lands_range_extensions(); let gathers = match &video.imports { Some(_) => Ok(Gathers { gpu: Arc::clone(&video.gpu), @@ -597,15 +619,18 @@ impl GraphicsVideo

for Shared

{ })) } - /// 4:2:0 streams, and HEVC's at 4:4:4 where NVDEC decodes them ([`declines_4_4_4`]). + /// 4:2:0 streams of Main and Main 10, and HEVC's range extensions where NVDEC decodes them + /// ([`declines_range_extensions`]). fn guest_declines(&self, codec: u32, stream: &Stream) -> Option { - match stream.chroma_format_idc { - 1 => None, - 3 if codec == RGFX_VIDEO_CODEC_HEVC => declines_4_4_4(&self.0.gpu, stream), - _ => Some(format!( - "{NAME}'s decoders land 4:2:0 pictures, and HEVC's 4:4:4, alone" - )), + if codec == RGFX_VIDEO_CODEC_HEVC && stream.range_extensions { + return declines_range_extensions(&self.0.gpu, stream); } + (stream.chroma_format_idc != 1 || stream.range_extensions).then(|| { + format!( + "{NAME}'s decoders land 4:2:0 pictures, and HEVC's range extensions where NVDEC \ + decodes them, alone" + ) + }) } } @@ -1058,8 +1083,13 @@ impl NvGuestDecoder

{ ))); } let four_four_four = picture.four_four_four(); - if target.pixel_format().is_4_4_4() != four_four_four { - let chroma = if four_four_four { "4:4:4" } else { "4:2:0" }; + let chroma = if four_four_four { + Chroma::Yuv444 + } else { + Chroma::Yuv420 + }; + if target.pixel_format().chroma() != chroma { + let chroma = chroma.name(); return Err(VideoError::Unsupported(format!( "a {chroma} picture for a '{}' surface", output.layout.pixel_format @@ -1104,11 +1134,11 @@ impl NvGuestDecoder

{ unsafe { std::slice::from_raw_parts_mut(view.first.as_ptr().add(view.offset), length) }; let read = read.planes(); if four_four_four { - interleave_planes(&read, &planes, surface, sample) + interleave_planes(&read, &planes, surface, sample).map_err(VideoError::Malfunction)?; + reims_vgpu_vulkan::answer::count_kind(CONVERTED_CODE); } else { - copy_planes(&read, &planes, surface) + copy_planes(&read, &planes, surface).map_err(VideoError::Malfunction)?; } - .map_err(VideoError::Malfunction)?; drop(view); Ok(true) } diff --git a/crates/reims-vgpu/src/graphics/vaapi.rs b/crates/reims-vgpu/src/graphics/vaapi.rs index 87744d70c..1d312fa04 100644 --- a/crates/reims-vgpu/src/graphics/vaapi.rs +++ b/crates/reims-vgpu/src/graphics/vaapi.rs @@ -80,11 +80,18 @@ //! decode lands in the IOSurface its kext lent, written there by the driver's video processing //! (`Frame::write_to_guest`, the first way above) where the import check takes the surface's //! layout and memory, else read back and copied by the CPU into the surface's pages. An HEVC -//! 4:4:4 stream at 8 bits decodes where the driver's Main 4:4:4 decoder takes it -//! (`declines_4_4_4`) into XYUV surfaces, split into the surface's two planes, luma and -//! interleaved Cb and Cr (`444v` and `444f`): on Linux by the runtime device's GPU where the -//! import check passed XYUV (`xyuv`), else read back and split by the CPU; every other stream -//! that is not 4:2:0 is refused at its session's start. +//! stream of the range extensions decodes where the driver's decoder of its chroma format and +//! depth takes it (`declines_range_extensions`, from the driver's own answers: the profile, its +//! render-target format, its surfaces' FOURCC and sizes; the VA crate's +//! `range_extensions_decoder`), into the guest's two-plane format of the stream +//! (`PixelFormat::of`). Per host surface: P012 (4:2:0 at 12 bits) is read back and copied into +//! `tv20`/`tf20` as it is, the two laid out alike; the packed ones are split into the surface's +//! two planes, luma and interleaved Cb and Cr: YUY2 into `422v`/`422f`, Y210 into `x422`/`xf22`, +//! Y212 into `tv22`/`tf22`, Y410 into `x444`/`xf44` (its 10-bit fields moved to the top of 16 +//! bits), Y412 into `tv44`/`tf44`, and XYUV into `444v`/`444f`, on Linux by the runtime device's +//! GPU where the import check passed XYUV (`xyuv`). The rest are read back and split by the +//! CPU, each picture counted (`video-pictures-cpu-converted`). Every other stream that is not +//! 4:2:0 Main or Main 10 is refused at its session's start, naming why. //! - **VideoToolbox's paravirtual encoders** (`encode::VaGuestEncoder`, `super::vt`): an arm64 //! guest's encoder reads each source frame from the IOSurface its kext lent: written by the //! runtime device's GPU from a buffer over its pages into an input of the encoder's, as an x86 @@ -121,12 +128,13 @@ use reims_vgpu_video::core::fourcc::FourCc; use reims_vgpu_video::core::runtime::Runtime; use reims_vgpu_video::core::surfaces::{PlaneLayout, SurfaceLayout}; use reims_vgpu_video::vaapi::{ - Capabilities, ConfigCapabilities, Display, EncoderSupport, Entrypoint, Fourcc, Frame, - GuestWrites, H264_MAX_MACROBLOCKS, H264Decoder, HevcDecoder, ImportWrites, PlaneRows, Profile, - Target, TargetCodec, TargetFor, VideoEncoder, encoder_support, + Capabilities, ConfigCapabilities, Display, EncoderSupport, Entrypoint, Frame, GuestWrites, + H264_MAX_MACROBLOCKS, H264Decoder, HevcDecoder, ImportWrites, PlaneRows, Profile, Target, + TargetCodec, TargetFor, VideoEncoder, encoder_support, }; #[cfg(unix)] use reims_vgpu_video::vaapi::{TARGET_ALIGNMENT, TargetChecks, TargetPlane, TargetShape}; +use reims_vgpu_video::vaapi::{range_extensions_decoder, rt_format_names}; #[cfg(unix)] use reims_vgpu_vulkan::core::num::ToU64 as _; use reims_vgpu_vulkan::core::num::ToUsize as _; @@ -150,8 +158,8 @@ use super::gather::GatherPipeline; #[cfg(unix)] use super::video_host::Failed; use super::video_host::{ - BackendError, DecodeOutput, Extent, HostDecoder, HostEncodeSession, HostPicture, HostPlane, - HostVideoSession, Landing, OutputPlane, picture_error, + BackendError, CONVERTED_CODE, DecodeOutput, Extent, HostDecoder, HostEncodeSession, + HostPicture, HostPlane, HostVideoSession, Landing, OutputPlane, picture_error, }; mod encode; @@ -170,8 +178,6 @@ const NAME: &str = "VA-API"; /// `VA_RT_FORMAT_YUV420` and `VA_RT_FORMAT_YUV420_10` (va.h): 8-bit and 10-bit 4:2:0. const RT_YUV420: u32 = 0x0000_0001; const RT_YUV420_10: u32 = 0x0000_0100; -/// `VA_RT_FORMAT_YUV444`. -const RT_YUV444: u32 = 0x0000_0004; /// The smallest picture a decode answers where its configs' surfaces give no minimum. const MIN_SIZE: u32 = 16; @@ -372,9 +378,9 @@ struct VaapiVideo { /// What writes pictures into device caches through their memory, where the platform makes /// caches of dma-bufs and the driver's checks passed anything (`cache_writes`, on Unix). targets: Option>>, - /// The driver's HEVC Main 4:4:4 decoder, where it lists one: what VideoToolbox's sessions of - /// 4:4:4 streams decode on ([`declines_4_4_4`]). - hevc_4_4_4: Option, + /// The driver's HEVC range extensions decoders it lists: what VideoToolbox's sessions of + /// those streams decode on ([`declines_range_extensions`]). + hevc_range_extensions: Vec, /// The kernel that writes VideoToolbox's 4:4:4 pictures into their surfaces (`xyuv`), made at /// its first use and kept for the device's decoders. #[cfg(unix)] @@ -404,7 +410,17 @@ impl VaapiVideo

{ }; let mut caps = caps_of(&capabilities); caps.extend(encode::encode_caps_of(&encoders, &capabilities)); - let hevc_4_4_4 = (capabilities.find(Profile::HEVC_MAIN444, Entrypoint::VLD)).cloned(); + let hevc_range_extensions = [ + Profile::HEVC_MAIN12, + Profile::HEVC_MAIN422_10, + Profile::HEVC_MAIN422_12, + Profile::HEVC_MAIN444, + Profile::HEVC_MAIN444_10, + Profile::HEVC_MAIN444_12, + ] + .into_iter() + .filter_map(|profile| capabilities.find(profile, Entrypoint::VLD).cloned()) + .collect(); if caps.is_empty() { return Err("the driver decodes and encodes neither H.264 nor HEVC".to_owned()); } @@ -438,7 +454,7 @@ impl VaapiVideo

{ imports, copies, targets, - hevc_4_4_4, + hevc_range_extensions, #[cfg(unix)] gathers: Arc::new(GatherPipeline::new(device)), }) @@ -531,16 +547,18 @@ impl GraphicsVideo

for VaapiVideo

{ true } - /// 4:2:0 streams, and HEVC's 4:4:4 at 8 bits where the driver's Main 4:4:4 decoder decodes - /// them ([`declines_4_4_4`]). + /// 4:2:0 streams of Main and Main 10, and HEVC's range extensions where the driver's + /// decoder of their chroma format and depth decodes them ([`declines_range_extensions`]). fn guest_declines(&self, codec: u32, stream: &Stream) -> Option { - match stream.chroma_format_idc { - 1 => None, - 3 if codec == RGFX_VIDEO_CODEC_HEVC => declines_4_4_4(self.hevc_4_4_4.as_ref(), stream), - _ => Some(format!( - "{NAME}'s decoders land 4:2:0 pictures, and HEVC's 4:4:4 at 8 bits, alone" - )), + if codec == RGFX_VIDEO_CODEC_HEVC && stream.range_extensions { + return declines_range_extensions(&self.hevc_range_extensions, stream); } + (stream.chroma_format_idc != 1 || stream.range_extensions).then(|| { + format!( + "{NAME}'s decoders land 4:2:0 pictures, and HEVC's range extensions where the \ + driver decodes them, alone" + ) + }) } /// One for each codec the driver encodes a profile of (`encode::guest_encoders`). @@ -560,15 +578,15 @@ impl GraphicsVideo

for VaapiVideo

{ Ok(Box::new(encoder)) } - /// An HEVC decoder lands 4:4:4 pictures too, which [`Self::guest_declines`] lets through - /// where the driver decodes them. + /// An HEVC decoder lands the range extensions' pictures too, which [`Self::guest_declines`] + /// lets through where the driver decodes them. fn guest_decoder(&self, codec: u32) -> Option>> { (self.caps.iter()).find(|c| c.codec == codec && c.direction == RGFX_VIDEO_DECODE)?; let codec = match codec { RGFX_VIDEO_CODEC_H264 => Codec::H264(H264Decoder::new_annex_b(&self.display)), RGFX_VIDEO_CODEC_HEVC => { let mut decoder = HevcDecoder::new_annex_b(&self.display); - decoder.lands_4_4_4(); + decoder.lands_range_extensions(); Codec::Hevc(decoder) } _ => return None, @@ -586,41 +604,43 @@ impl GraphicsVideo

for VaapiVideo

{ } } -/// Why the driver decodes none of an HEVC 4:4:4 `stream`'s pictures into the XYUV surfaces the -/// VA crate's decoder lands them from, `None` where it decodes them: on its Main 4:4:4 decoder, -/// `config`, of 4:4:4 render targets and XYUV surfaces, at 8 bits, within its sizes. -fn declines_4_4_4(config: Option<&ConfigCapabilities>, stream: &Stream) -> Option { - let bits = stream.luma_bits; - if bits != 8 { +/// Why the driver decodes none of an HEVC range extensions `stream`'s pictures into the surfaces +/// the VA crate's decoder lands them from, `None` where it decodes them: on the decoder among +/// `configs` of the profile of the stream's chroma format and depth (`range_extensions_decoder`), +/// of its render targets and its surfaces' FOURCC, within its sizes. +fn declines_range_extensions(configs: &[ConfigCapabilities], stream: &Stream) -> Option { + let (chroma, bits) = (stream.chroma_format_idc, stream.luma_bits); + let Some((profile, rt_format, fourcc)) = range_extensions_decoder(chroma, bits) else { return Some(format!( - "{NAME} decodes HEVC 4:4:4 at 8 bits here, not {bits}" + "{NAME} decodes HEVC's range extensions of 4:2:0, 4:2:2 and 4:4:4 at 8, 10 and 12 \ + bits, not chroma_format_idc {chroma} at {bits}" )); - } - let Some(config) = config else { - return Some(format!("{NAME}: the driver has no HEVC Main 4:4:4 decoder")); + }; + let name = profile.name().unwrap_or("HEVC"); + let Some(config) = configs.iter().find(|config| config.profile == profile) else { + return Some(format!("{NAME}: the driver has no {name} decoder")); }; if config .rt_formats - .is_some_and(|formats| formats & RT_YUV444 == 0) + .is_some_and(|formats| formats & rt_format == 0) { return Some(format!( - "{NAME}: the driver's HEVC Main 4:4:4 decoder has no 4:4:4 render targets" + "{NAME}: the driver's {name} decoder has no {} render targets", + rt_format_names(rt_format).join(", ") )); } let surfaces = match &config.surfaces { Ok(surfaces) => surfaces, Err(error) => { - return Some(format!( - "{NAME}: the HEVC Main 4:4:4 decoder's surfaces: {error}" - )); + return Some(format!("{NAME}: the {name} decoder's surfaces: {error}")); } }; - if !surfaces.pixel_formats.contains(&Fourcc::XYUV) { + if !surfaces.pixel_formats.contains(&fourcc) { let formats: Vec = (surfaces.pixel_formats.iter()) .map(ToString::to_string) .collect(); return Some(format!( - "{NAME} writes HEVC 4:4:4 as [{}], not XYUV", + "{NAME}'s {name} decoder writes [{}], not {fourcc}", formats.join(", ") )); } @@ -638,11 +658,11 @@ fn declines_4_4_4(config: Option<&ConfigCapabilities>, stream: &Stream) -> Optio ); if width < min_width || height < min_height { Some(format!( - "{NAME} decodes HEVC 4:4:4 from {min_width}x{min_height}, not {width}x{height}" + "{NAME} decodes {name} from {min_width}x{min_height}, not {width}x{height}" )) } else if width > max_width || height > max_height { Some(format!( - "{NAME} decodes HEVC 4:4:4 up to {max_width}x{max_height}, not {width}x{height}" + "{NAME} decodes {name} up to {max_width}x{max_height}, not {width}x{height}" )) } else { None @@ -1448,21 +1468,30 @@ impl VaGuestDecoder

{ .crop_within(x, y, width, height) .map_err(video_error)?; } - // A 4:4:4 stream's pictures are XYUV, which the GPU or the CPU splits into the surface's - // two planes; a 4:2:0 one's are NV12 or P010, which land as they are. - let four_four_four = frame.is_4_4_4(); + // The range extensions' 4:2:2 and 4:4:4 pictures are packed in one plane, which the CPU + // splits into the surface's two planes, as the GPU does XYUV's where it takes them; a + // 4:2:0 one's are NV12, P010 or P012, which land as they are. The surface is of the + // picture's chroma format and depth (`paravirt`'s `Dpba` named it). let format = output.layout.pixel_format; - if PixelFormat::from_fourcc(format).is_some_and(PixelFormat::is_4_4_4) != four_four_four { - let chroma = if four_four_four { "4:4:4" } else { "4:2:0" }; + let fits = PixelFormat::from_fourcc(format).is_some_and(|guest| { + guest.chroma() == frame.chroma() && u32::from(guest.bit_depth()) == frame.bit_depth() + }); + if !fits { return Err(VideoError::Unsupported(format!( - "a {chroma} picture for a '{format}' surface" + "a {} picture for a '{format}' surface", + frame.surface_format_name() ))); } - let declined = if four_four_four { + let declined = if frame.is_xyuv() { match self.gather(&frame, output)? { Ok(()) => return Ok(true), Err(why) => format!("a 4:4:4 picture's XYUV samples into two planes: {why}"), } + } else if frame.is_packed() { + format!( + "a picture's packed {} samples into two planes", + frame.surface_format_name() + ) } else { match GuestTarget::new(&output.layout, output.memory) { Ok(target) => match frame.write_to_guest(&target, &self.imports) { @@ -1528,12 +1557,12 @@ impl VaGuestDecoder

{ rows: chroma.height.to_usize(), row_bytes: uv_row, }; - if four_four_four { - back.copy_4_4_4_into(y, uv) + if frame.is_packed() { + back.copy_packed_into(y, uv).map_err(video_error)?; + reims_vgpu_vulkan::answer::count_kind(CONVERTED_CODE); } else { - back.copy_into(y, uv) + back.copy_into(y, uv).map_err(video_error)?; } - .map_err(video_error)?; drop(view); Ok(true) } diff --git a/crates/reims-vgpu/src/graphics/vaapi/tests.rs b/crates/reims-vgpu/src/graphics/vaapi/tests.rs index 94401257a..a0c1dc3f5 100644 --- a/crates/reims-vgpu/src/graphics/vaapi/tests.rs +++ b/crates/reims-vgpu/src/graphics/vaapi/tests.rs @@ -1,6 +1,6 @@ use super::*; use crate::graphics::video_choice::tested_gpu::Arm; -use reims_vgpu_video::vaapi::{ImportWrite, SurfaceCapabilities, TargetFormat}; +use reims_vgpu_video::vaapi::{Fourcc, ImportWrite, SurfaceCapabilities, TargetFormat}; /// A VLD config of `profile`, decoding `rt_formats`, up to `max` with surfaces from `min`. fn config( @@ -141,71 +141,106 @@ fn a_profile_whose_config_decodes_none_of_its_formats_is_left_out() { assert!(caps_of(&driver(Vec::new())).is_empty()); } -/// An HEVC 4:4:4 stream decodes where the driver's Main 4:4:4 decoder writes XYUV surfaces of -/// 4:4:4 render targets at its size and the stream is of 8 bits, as iHD's answers on an Iris Xe -/// (AYUV and XYUV up to 16384x16384), and is declined, naming why, everywhere else +/// An HEVC range extensions stream decodes where the driver's decoder of its chroma format and +/// depth writes that decoder's surfaces of the stream's render targets at its size, as iHD's +/// answers on an Iris Xe (Main 4:4:4's AYUV and XYUV, Main 12's P012 and P016, Main 4:2:2 10's +/// YUY2 and Y210 of 4:2:2 and 4:2:2 10-bit render targets, Main 4:4:4 12's Y412, each up to +/// 16384x16384; potluck job m3-max-77223), and is declined, naming why, everywhere else #[test] -fn an_hevc_4_4_4_stream_decodes_on_a_main_4_4_4_decoder_of_xyuv_surfaces_alone() { +fn an_hevc_range_extensions_stream_decodes_on_its_profiles_decoder_of_its_surfaces_alone() { use reims_vgpu_video::paravirt::Codec as StreamCodec; - let stream = |luma_bits: u8, width: u32, height: u32| Stream { + let stream = |chroma_format_idc: u8, luma_bits: u8, width: u32, height: u32| Stream { codec: StreamCodec::Hevc, profile: 4, - chroma_format_idc: 3, + chroma_format_idc, luma_bits, chroma_bits: luma_bits, width, height, + range_extensions: true, }; - let ayuv = Fourcc(u32::from_le_bytes(*b"AYUV")); - let iris = |pixel_formats: Vec, rt_formats: u32| { - let mut config = config( - Profile::HEVC_MAIN444, - rt_formats, - (16384, 16384), - Some((16, 16)), - ); + let named = |name: &[u8; 4]| Fourcc(u32::from_le_bytes(*name)); + let iris = |profile, pixel_formats: Vec, rt_formats: u32| { + let mut config = config(profile, rt_formats, (16384, 16384), Some((16, 16))); if let Ok(surfaces) = config.surfaces.as_mut() { surfaces.pixel_formats = pixel_formats; } config }; - let taken = iris(vec![ayuv, Fourcc::XYUV], 0x0000_000f); - assert_eq!(declines_4_4_4(Some(&taken), &stream(8, 1920, 1080)), None); - assert_eq!(declines_4_4_4(Some(&taken), &stream(8, 16384, 16)), None); + let configs = [ + iris( + Profile::HEVC_MAIN444, + vec![named(b"AYUV"), Fourcc::XYUV], + 0x0000_000f, + ), + iris( + Profile::HEVC_MAIN12, + vec![Fourcc::P012, named(b"P016")], + 0x0000_1000, + ), + iris( + Profile::HEVC_MAIN422_10, + vec![Fourcc::YUY2, Fourcc::Y210], + 0x0000_0202, + ), + iris(Profile::HEVC_MAIN444_12, vec![Fourcc::Y412], 0x0000_4000), + ]; + for taken in [ + stream(3, 8, 1920, 1080), + stream(3, 8, 16384, 16), + stream(1, 12, 1920, 1080), + stream(2, 8, 1920, 1080), + stream(2, 10, 1920, 1080), + stream(3, 12, 1920, 1080), + ] { + assert_eq!( + declines_range_extensions(&configs, &taken), + None, + "{taken:?}" + ); + } let declined = [ ( - None, - stream(8, 1920, 1080), - "VA-API: the driver has no HEVC Main 4:4:4 decoder", + stream(3, 10, 1920, 1080), + "VA-API: the driver has no HEVCMain444_10 decoder", ), ( - Some(&taken), - stream(10, 1920, 1080), - "VA-API decodes HEVC 4:4:4 at 8 bits here, not 10", + stream(1, 10, 1920, 1080), + "VA-API: the driver's HEVCMain12 decoder has no YUV420_10 render targets", ), ( - Some(&taken), - stream(8, 16400, 1080), - "VA-API decodes HEVC 4:4:4 up to 16384x16384, not 16400x1080", + stream(3, 14, 1920, 1080), + "VA-API decodes HEVC's range extensions of 4:2:0, 4:2:2 and 4:4:4 at 8, 10 and 12 \ + bits, not chroma_format_idc 3 at 14", ), ( - Some(&taken), - stream(8, 8, 8), - "VA-API decodes HEVC 4:4:4 from 16x16, not 8x8", + stream(3, 8, 16400, 1080), + "VA-API decodes HEVCMain444 up to 16384x16384, not 16400x1080", + ), + ( + stream(2, 8, 8, 8), + "VA-API decodes HEVCMain422_10 from 16x16, not 8x8", ), ]; - for (config, stream, why) in declined { - assert_eq!(declines_4_4_4(config, &stream).as_deref(), Some(why)); + for (stream, why) in declined { + assert_eq!( + declines_range_extensions(&configs, &stream).as_deref(), + Some(why) + ); } - let packed_alone = iris(vec![ayuv], 0x0000_000f); + let packed_alone = [iris( + Profile::HEVC_MAIN444, + vec![named(b"AYUV")], + 0x0000_000f, + )]; assert_eq!( - declines_4_4_4(Some(&packed_alone), &stream(8, 1920, 1080)).as_deref(), - Some("VA-API writes HEVC 4:4:4 as [AYUV], not XYUV") + declines_range_extensions(&packed_alone, &stream(3, 8, 1920, 1080)).as_deref(), + Some("VA-API's HEVCMain444 decoder writes [AYUV], not XYUV") ); - let no_4_4_4 = iris(vec![Fourcc::XYUV], RT_YUV420); + let no_4_4_4 = [iris(Profile::HEVC_MAIN444, vec![Fourcc::XYUV], RT_YUV420)]; assert_eq!( - declines_4_4_4(Some(&no_4_4_4), &stream(8, 1920, 1080)).as_deref(), - Some("VA-API: the driver's HEVC Main 4:4:4 decoder has no 4:4:4 render targets") + declines_range_extensions(&no_4_4_4, &stream(3, 8, 1920, 1080)).as_deref(), + Some("VA-API: the driver's HEVCMain444 decoder has no YUV444 render targets") ); } @@ -853,8 +888,9 @@ pub(super) fn va_streams() -> Vec { /// Decodes each of `streams` on `display`, in decode order, and hands each frame to `each` with /// its stream and its access unit's id, until `each` answered `true` (written) for `most` of the -/// stream's frames or the stream ends. With `four_four_four`, an HEVC decoder decodes 4:4:4 -/// streams too (`HevcDecoder::lands_4_4_4`). A stream the decoder refuses is left at its refusal, +/// stream's frames or the stream ends. With `four_four_four`, an HEVC decoder decodes the range +/// extensions' streams too (`HevcDecoder::lands_range_extensions`), 4:4:4 among them. A stream the +/// decoder refuses is left at its refusal, /// which is answered. pub(super) fn each_picture( display: &Display, @@ -871,7 +907,7 @@ pub(super) fn each_picture( let (units, mut decoder) = if stream.to_string_lossy().ends_with(".265") { let mut decoder = HevcDecoder::new_annex_b(display); if four_four_four { - decoder.lands_4_4_4(); + decoder.lands_range_extensions(); } (hevc::nal::access_units(&file), Codec::Hevc(decoder)) } else { diff --git a/crates/reims-vgpu/src/graphics/vaapi/xyuv.rs b/crates/reims-vgpu/src/graphics/vaapi/xyuv.rs index 5fd4142ab..7e53e6d7b 100644 --- a/crates/reims-vgpu/src/graphics/vaapi/xyuv.rs +++ b/crates/reims-vgpu/src/graphics/vaapi/xyuv.rs @@ -17,7 +17,7 @@ //! then `videoGather444` writes the crop's samples into the surface's two planes through the //! Shared buffer over its pages that VideoToolbox's decoder hands for a 4:4:4 surface //! (`super::super::vt`), and is waited for: the rows and bytes that the CPU's split of the read -//! back writes (`ReadBack::copy_4_4_4_into`), and nothing else of the surface. +//! back writes (`ReadBack::copy_packed_into`), and nothing else of the surface. //! - **Refusals** come before anything is written into the surface, and the picture is then read //! back and split by the CPU, the reason logged once a decoder: no buffer over the surface, a //! crop the kernel does not write (`gather::gathers`), the driver's decline of the scratch @@ -163,8 +163,8 @@ impl XyuvGathers

{ let Some(surface) = surface else { return declined("no buffer of the device's over the surface"); }; - if !frame.is_4_4_4() { - return declined("a 4:2:0 picture"); + if !frame.is_xyuv() { + return declined("a picture of no XYUV surface"); } let crop = (frame.width(), frame.height()); let even = (crop.0.next_multiple_of(2), crop.1.next_multiple_of(2)); diff --git a/crates/reims-vgpu/src/graphics/vaapi/xyuv/tests.rs b/crates/reims-vgpu/src/graphics/vaapi/xyuv/tests.rs index 5979c8cb5..b157322c5 100644 --- a/crates/reims-vgpu/src/graphics/vaapi/xyuv/tests.rs +++ b/crates/reims-vgpu/src/graphics/vaapi/xyuv/tests.rs @@ -203,7 +203,7 @@ fn a_4_4_4_picture_written_by_the_gpu_is_the_cpus_split() { // Each written picture's CPU and wall times, the GPU's way then the CPU's. let mut times: Vec<[Duration; 4]> = Vec::new(); let mut each = |stream: &std::path::Path, id: u64, frame: &Frame| -> bool { - if !frame.is_4_4_4() { + if !frame.is_xyuv() { return false; } let (width, height) = (u64::from(frame.width()), u64::from(frame.height())); @@ -247,7 +247,7 @@ fn a_4_4_4_picture_written_by_the_gpu_is_the_cpus_split() { let (y, uv) = cpu.split_at_mut(usize_of(chroma_at)); let (cpu_at, wall_at) = (thread_cpu(), std::time::Instant::now()); (frame.read_back().expect("the read back")) - .copy_4_4_4_into( + .copy_packed_into( plane_rows(&mut y[usize_of(luma_at)..], luma_pitch, height, width), plane_rows(uv, chroma_pitch, height, 2 * width), ) diff --git a/crates/reims-vgpu/src/graphics/video_host.rs b/crates/reims-vgpu/src/graphics/video_host.rs index 652443f41..95cacaf6b 100644 --- a/crates/reims-vgpu/src/graphics/video_host.rs +++ b/crates/reims-vgpu/src/graphics/video_host.rs @@ -157,6 +157,15 @@ const FAILURES_LOGGED: u64 = 8; /// logged once per boot, then counted"). pub(crate) const CARRIED_CODE: &str = "video-landing-failure-carried"; +/// The code of a VideoToolbox decoder's picture the CPU wrote into its surface's two planes from +/// a host surface of another layout: the range extensions' packed 4:2:2 and 4:4:4 samples a +/// VA-API driver decodes into (YUY2, Y210, Y212, Y410, Y412, and XYUV where the GPU's gather does +/// not take it) split into luma and Cb/Cr pairs, and NVDEC's three 4:4:4 planes interleaved into +/// two where the GPU's gather does not take them: one CPU pass a picture that a Mac, whose +/// decoder writes the guest's format, does not make (docs/conventions.md, "Each degradation is +/// logged once per boot, then counted"). +pub(crate) const CONVERTED_CODE: &str = "video-pictures-cpu-converted"; + /// A backend's error: what it could not do, which the session logs or faults the command buffer /// with. pub(crate) type BackendError = Box; diff --git a/crates/reims-vgpu/src/graphics/vt.rs b/crates/reims-vgpu/src/graphics/vt.rs index f06ff7df2..164eb4e30 100644 --- a/crates/reims-vgpu/src/graphics/vt.rs +++ b/crates/reims-vgpu/src/graphics/vt.rs @@ -30,7 +30,7 @@ use reims_vgpu_graphics::wire::{ RgfxVtSurface, }; use reims_vgpu_video::codec::encode::{Coded, FailedSample}; -use reims_vgpu_video::core::backend::{BackendError as VideoError, PixelFormat}; +use reims_vgpu_video::core::backend::{BackendError as VideoError, Chroma, PixelFormat}; use reims_vgpu_video::core::fourcc::FourCc; use reims_vgpu_video::core::surfaces::{PlaneLayout, SurfaceLayout}; use reims_vgpu_video::paravirt::status::{self, OsStatus}; @@ -230,9 +230,9 @@ impl VtDecoder

{ Ok(view) => view, Err(why) => return Err(self.failed(status::VIDEO_DECODER_MALFUNCTION, why)), }; - // A buffer over a 4:4:4 surface's pages, for a decoder whose GPU writes them. - let four_four_four = - PixelFormat::from_fourcc(layout.pixel_format).is_some_and(PixelFormat::is_4_4_4); + // A buffer over an 8-bit 4:4:4 surface's pages, for a decoder whose GPU writes them. + let four_four_four = PixelFormat::from_fourcc(layout.pixel_format) + .is_some_and(|format| format.is_4_4_4() && format.bit_depth() == 8); let buffer = match four_four_four && self.decoder.lands_4_4_4_by_gpu() { false => None, true => { @@ -475,25 +475,25 @@ pub(super) fn layout_of(record: &RgfxVtSurface) -> Result } /// The part of a surface laid out as `layout` that a tile's `region` lands in: each plane from the -/// region's first row and column, `region.width` by `region.height` luma samples (half, rounded -/// up, of a 4:2:0 chroma plane's, of pairs; as many of a 4:4:4 one's), with the surface's rows. -/// A region past the surface, or one from an odd column or row, is refused, as is a surface of a -/// format other than the 4:2:0 and 4:4:4 ones a picture lands in: a tile session starts only on -/// a stream of pictures the arm decodes (`reims_vgpu_video::paravirt`'s decoder refuses the rest -/// at the session's `dsts`), and its `TDrs` names their format. +/// region's first row and column, `region.width` by `region.height` luma samples (of pairs, half +/// as many, rounded up, across a 4:2:0 or 4:2:2 chroma plane and down a 4:2:0 one; as many of a +/// 4:4:4 one's), with the surface's rows. A region past the surface, or one from an odd column +/// or row, is refused, as is a surface of a format other than the two-plane ones a picture lands +/// in ([`PixelFormat`]): a tile session starts only on a stream of pictures the arm decodes +/// (`reims_vgpu_video::paravirt`'s decoder refuses the rest at the session's `dsts`), and its +/// `TDrs` names their format. fn region_layout(layout: &SurfaceLayout, region: TileRegion) -> Result { let format = layout.pixel_format; - let one_of = |formats: [&[u8; 4]; 2]| formats.map(|f| FourCc::new(*f)).contains(&format); - // Bytes a sample, and whether chroma has a pair for every two columns and rows. - let (sample, half) = if one_of([b"420v", b"420f"]) { - (1, true) - } else if one_of([b"x420", b"xf20"]) { - (2, true) - } else if one_of([b"444v", b"444f"]) { - (1, false) - } else { + let Some(pixels) = PixelFormat::from_fourcc(format) else { return Err(format!("tiles in '{format}'")); }; + let sample = pixels.bytes_per_sample(); + // The luma columns and rows a chroma pair stands for. + let (across, down) = match pixels.chroma() { + Chroma::Yuv420 => (2, 2), + Chroma::Yuv422 => (2, 1), + Chroma::Yuv444 => (1, 1), + }; let fits = (region.x.checked_add(region.width)).is_some_and(|end| end <= layout.width) && (region.y.checked_add(region.height)).is_some_and(|end| end <= layout.height); if !fits || (region.x | region.y) & 1 != 0 { @@ -505,8 +505,6 @@ fn region_layout(layout: &SurfaceLayout, region: TileRegion) -> Result Result