diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index 1f72c95bf..3ed6449f8 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -1456,7 +1456,10 @@ degradations! { /// runtime sampler slot, only where the sampler bound there filters: a linear /// minification, magnification or mip filter, anisotropy, or a cubic filter; one that /// reads one texel of one level takes the texel the view holds, Metal's read), naming the - /// slot and the format. + /// slot and the format; and at a draw or dispatch whose function filters a texture an + /// argument buffer holds where a texture the command makes resident or binds that its + /// handles can name is two-plane YCbCr, through an argument buffer's sampler only where a + /// live sampler state filters (which state the buffer's memory names is not read). YCbCrFilterNotExact = "ycbcr-filter-not-exact", Precision, "where the device converts the planes' format, the texels are its own Y′CbCr \ conversion's, at its precision and unclamped where it does not clamp, not Metal's \ @@ -3693,7 +3696,9 @@ impl Device { /// reads as data or a bound sampler's word (`SpecClause::tests_bound_values`: a bound /// texture's format class, `SpecKey::BoundSamplerWord`) and holds where the draw's plan gives /// the values `bound` gives (`BindingPlan::specialized_value`; - /// `StageModule::note_clauses_bound`), the class of the format `formats` binds at each + /// `StageModule::note_clauses_bound`; and what the command's handles can name, + /// `SpecKey::HeapYCbCrTextures` and `SpecKey::FilteringArgumentSampler`, which the plan gives + /// too: a filter note's heap texture), the class of the format `formats` binds at each /// texture slot such a clause also tests (`SpecKey::BoundTexelFormat`: a filter note's /// two-plane YCbCr format under a runtime sampler's filtering word). A clause testing a slot /// bound to nothing does not hold, as [`degrade_bound_formats`](Self::degrade_bound_formats) @@ -3765,8 +3770,9 @@ impl Device { /// Announce `note` of `stage`, `at` ([`Occurrence`]), where `clauses`, the clauses of its /// specialized note that hold, are not empty: a filter note's slot bound to a two-plane YCbCr /// texture (or, where the command's formats are not known, `formats` `None`, to the format its - /// clause tests, a two-plane YCbCr one) as its own kind, and the note's kind where a clause - /// that holds tests another slot, or none, the reason naming each such slot (with its bound + /// clause tests, a two-plane YCbCr one), and its clause of a heap's texture + /// (`SpecKey::HeapYCbCrTextures`), as its own kind, and the note's kind where a clause that + /// holds tests another slot, or none, the reason naming each such slot (with its bound /// format, where `formats` knows it) after `under`. fn degrade_clauses( &self, @@ -3812,9 +3818,26 @@ impl Device { ) }); } + // A filter note's clause of a heap's texture: a two-plane YCbCr texture the stage's + // handles can name (`SpecKey::HeapYCbCrTextures`), its own kind too. + let heap = |c: &&metal2vulkan::pipeline::SpecClause| { + filter_note(note) + && (c.all.iter()).any(|t| matches!(t.key, SpecKey::HeapYCbCrTextures(_))) + }; + if clauses.iter().any(heap) { + self.degrade_at(at, Degradation::YCbCrFilterNotExact, || { + ( + stage_object(stage.stage).to_owned(), + format!( + "a filtered sample of a texture its argument buffers name takes the device's filter, not Metal's exact filter of the format, and a texture the command makes resident or binds that they can name is two-plane YCbCr: {}", + self.note_reason(note) + ), + ) + }); + } let covered = |c: &&metal2vulkan::pipeline::SpecClause| { let tested = tested_slots([*c]); - !tested.is_empty() && tested.iter().all(held) + heap(c) || (!tested.is_empty() && tested.iter().all(held)) }; if clauses.iter().all(covered) { return; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/ycbcr_textures.rs b/crates/metal2vulkan-validation/src/runtime_lane/ycbcr_textures.rs index b6cc92d92..8b6424a84 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/ycbcr_textures.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/ycbcr_textures.rs @@ -2126,6 +2126,183 @@ fn a_runtime_sampler_announces_the_ycbcr_filter_only_where_it_filters() { } } +/// A sample of a two-plane YCbCr texture an argument buffer holds announces +/// `ycbcr-filter-not-exact` only where its sampler can filter, on a device that samples through +/// Metal's own sampler (`VkProperty::MetalSampler`): a 4:4:4 texture (`YCBCR8_444_2P` over `444v`, +/// `YCBCR10_444_2P_sRGB` over `x444`, whose address-mode map is the identity, so a function that +/// samples handles reaches it), made resident by the encoder, its `float` and `half` samples +/// through a linear constexpr sampler, a runtime sampler slot, or the sampler state the argument +/// buffer holds. Through a runtime slot the bound sampler's word decides; through the argument +/// buffer's sampler, whether a live sampler state filters, as the runtime cannot read which state +/// the buffer's memory names (`SpecKey::FilteringArgumentSampler`): a program whose live states +/// are all nearest announces nothing, and one with a linear state alive announces, whichever +/// state the buffer holds. An `RGBA16Float` texture in the same place announces no YCbCr notice. +/// A device that samples natively announces it only where it converted the texture itself. +#[test] +fn a_ycbcr_texture_through_an_argument_buffer_announces_its_filter_only_where_it_can_filter() { + #[derive(Clone, Copy, Debug)] + enum Held { + None, + Nearest, + Linear, + } + // Each case: its name, how the kernel samples, the state the buffer holds or the slot binds, + // whether a linear state lives beside it, and whether the sample can filter. + let cases = [ + ( + "constexpr linear", + Through::Constexpr(LINEAR_EDGE), + Held::None, + false, + true, + ), + ( + "runtime nearest", + Through::Runtime, + Held::Nearest, + false, + false, + ), + ( + "runtime linear", + Through::Runtime, + Held::Linear, + false, + true, + ), + ( + "argument nearest", + Through::Argument, + Held::Nearest, + false, + false, + ), + ( + "argument linear", + Through::Argument, + Held::Linear, + false, + true, + ), + ( + "argument nearest, a linear state alive", + Through::Argument, + Held::Nearest, + true, + true, + ), + ]; + let formats = [ + (PixelFormat::YCBCR84442P, "444v", true), + (PixelFormat::YCBCR104442PSRGB, "x444", true), + (PixelFormat::RGBA16Float, "", false), + ]; + for (seed, (pf, ostype, ycbcr)) in (960..).zip(formats) { + for (name, through, held, alive, filters) in cases { + on_device(|device, messages| { + let case = format!("{pf:?} {name}"); + let sampler_of = |held| match held { + Held::None => None, + Held::Nearest => Some(sampler(device, SamplerMinMagFilter::Nearest)), + Held::Linear => Some(sampler(device, SamplerMinMagFilter::Linear)), + }; + let state = sampler_of(held); + let _beside = alive.then(|| sampler(device, SamplerMinMagFilter::Linear)); + let pipelines: Vec = [false, true] + .map(|half| { + let source = argument_linear_samples::kernel(true, through, false, half); + pipeline_of(device, &llvm_assemble_text(&source).unwrap(), "k") + }) + .into(); + // From here: a texture the device converts itself is announced as it is made. + messages.take_notices(); + let (texture, by_device) = match ycbcr { + true => { + let codes = ycbcr_format(pf).and_then(YCbCrCodes::of).unwrap(); + let surface = buffer_with(device, &family_bytes(seed, codes)).unwrap(); + let made = made_by_device(device, || { + family_texture(&surface, pf, ostype, None).unwrap() + }); + assert!(made.0.address_mode_map().is_identity(), "{case}"); + made + } + false => { + let mut d = TextureDescriptor::texture_2d(pf, W, H, false); + d.usage = TextureUsage::SHADER_READ; + (device.new_texture(&d).unwrap(), false) + } + }; + let coords: Vec = (0..8u32) + .flat_map(|i| { + let x = (i as f32 * 4.3 + 0.37) / W as f32; + [x, 0.41, 0.0, 0.0].into_iter().flat_map(f32::to_le_bytes) + }) + .collect(); + let input = buffer_with(device, &coords).unwrap(); + let out = device + .new_buffer(16 * 8, ResourceOptions::shared()) + .unwrap(); + let held_id = match (through, &state) { + (Through::Argument, Some(state)) => state.gpu_resource_id().0, + _ => 0, + }; + let ids = [texture.gpu_resource_id().0, held_id]; + let words: Vec = ids.iter().flat_map(|id| id.to_le_bytes()).collect(); + let argument = buffer_with(device, &words).unwrap(); + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + for pipeline in &pipelines { + encoder.set_compute_pipeline_state(pipeline).unwrap(); + encoder + .use_resource(texture.as_resource(), ResourceUsage::READ) + .unwrap(); + encoder.set_buffer(Some(&input), 0, 0).unwrap(); + encoder.set_buffer(Some(&out), 0, 1).unwrap(); + encoder.set_buffer(Some(&argument), 0, 2).unwrap(); + if let (Through::Runtime, Some(state)) = (through, &state) { + encoder.set_sampler_state(Some(state), 0).unwrap(); + } + encoder + .dispatch_threads(Size::new(8, 1, 1), Size::new(8, 1, 1)) + .unwrap_or_else(|e| panic!("{case}: {e:?}")); + } + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + let metal = metal_sampler(device); + let notices = messages.take_notices(); + let counts = counts(¬ices); + println!( + "YCBCR-ARGUMENT-FILTER {} {case}: metal sampler {metal}, device conversion \ + {by_device}, notices {counts:?}", + device.name() + ); + for kind in [ + Degradation::FloatSampleFilter, + Degradation::HalfSampleFilter, + ] { + assert_eq!(counts.get(&kind), None, "{case}: {counts:?}"); + } + let announced = counts.get(&YCBCR_FILTERS[0]); + let want = (ycbcr && metal && filters) || by_device; + assert_eq!(announced, want.then_some(&1), "{case}: {counts:?}"); + if ycbcr && metal && filters && !by_device { + let notice = notices + .iter() + .filter_map(|m| m.degradation.as_ref()) + .find(|n| n.degradation == YCBCR_FILTERS[0]) + .unwrap(); + assert!( + notice.reason.contains("argument buffers name"), + "{case}: {notice:?}" + ); + } + }); + } + } +} + /// A function that samples textures through handles (an argument buffer's) reads its sampler /// from memory, where no slot's specialization can give it Metal's exact filter of a YCbCr /// texture it reaches, nor the texture's address-mode map: a command whose function samples diff --git a/crates/metal2vulkan/src/bind/graphics.rs b/crates/metal2vulkan/src/bind/graphics.rs index 26328ab4c..415c2ce16 100644 --- a/crates/metal2vulkan/src/bind/graphics.rs +++ b/crates/metal2vulkan/src/bind/graphics.rs @@ -2325,7 +2325,7 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result Result( stages: impl IntoIterator, shape: &BindShape, resources: &mut ResourcePlanner<'_>, + reach: &dyn Fn(metal::RenderStages) -> Vec, ) -> Result<(), BindError> { let tested: Vec = stages .into_iter() @@ -283,7 +286,14 @@ pub(crate) fn record_noted<'a>( .flat_map(|note| ¬e.when) .flat_map(|clause| &clause.all) .map(|test| test.key) - .filter(|key| matches!(key, SpecKey::BoundSamplerWord(_))) + .filter(|key| { + matches!( + key, + SpecKey::BoundSamplerWord(_) + | SpecKey::HeapYCbCrTextures(_) + | SpecKey::FilteringArgumentSampler + ) + }) .collect(); for key in tested { if resources @@ -294,8 +304,17 @@ pub(crate) fn record_noted<'a>( { continue; } - let value = bound_value(key, shape, resources)? - .ok_or_else(|| internal(format!("a noted {key:?}, which no bound resource decides")))?; + let value = match key { + SpecKey::HeapYCbCrTextures(stage) => u64::from(heap_ycbcr(shape, stage, reach)), + // A sampler state of any listed shape may be the one an argument buffer names. + SpecKey::FilteringArgumentSampler => u64::from( + (shape.argument_samplers.shapes.iter()) + .any(|s| s.linear || s.anisotropic || s.cubic), + ), + key => bound_value(key, shape, resources)?.ok_or_else(|| { + internal(format!("a noted {key:?}, which no bound resource decides")) + })?, + }; let value = u32::try_from(value) .map_err(|_| internal(format!("a noted {key:?} of {value}, past a word")))?; resources.template.specialized.push((key, value)); @@ -303,6 +322,24 @@ pub(crate) fn record_noted<'a>( Ok(()) } +/// Whether a heap member of `shape` that reaches `stage` (`bind::heap`'s members: a texture the +/// command makes resident, its render stages through `reach`, or binds at a texture slot of the +/// stage) is of a two-plane YCbCr class (`TexelFormat::two_plane_ycbcr`). +fn heap_ycbcr( + shape: &BindShape, + stage: Stage, + reach: &dyn Fn(metal::RenderStages) -> Vec, +) -> bool { + crate::bind::heap::members(shape, &[stage], reach) + .iter() + .any(|m| match m.shape { + TextureShape::Texture { pixel_format, .. } => { + crate::metal::texel_format::texel_format(pixel_format).two_plane_ycbcr() + } + _ => false, + }) +} + /// Whether `shape` binds anything at `slot`. fn present(shape: &BindShape, slot: SlotRef) -> bool { shape diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index 0dcc69859..3726b9395 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -864,7 +864,8 @@ codec_enum! { ObjectLocalSize(f0), ObjectFlatLocalSize, ObjectMultiRegion, SamplerMinLevel(f0), ConstantLanes(f0), UnmeasuredTexels(f0), BoundTexelFormat(f0), OffsetBaseAxes(f0), SamplerAnisotropy(f0), RangeAtBindOffset(f0), PlainHalfTexels(f0), - NearestPixelSampler(f0), BoundSamplerWord(f0), + NearestPixelSampler(f0), BoundSamplerWord(f0), HeapYCbCrTextures(f0), + FilteringArgumentSampler, } PushField { RootTableAddress, ExecutionStatusAddress, DispatchRegion, BaseVertexInstance, diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 0dcf34370..652b4add3 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -70,7 +70,7 @@ pub const SEMANTICS_VERSION: u32 = 1974; /// re-typed in an encoded type, its `codec` body or its `envelope`. A variant removed while its tag /// stays unused needs no bump: an entry holding it fails to decode, which is a miss. The commit that /// bumps it says what changed; this comment keeps no history. -pub const ARTIFACT_FORMAT_VERSION: u32 = 489; +pub const ARTIFACT_FORMAT_VERSION: u32 = 490; /// The version of what this crate's runtime does with a compiled pipeline: instantiating a binding /// plan (`BindingPlan::instantiate_*`: descriptor ranges, push bytes, root, argument, and handle diff --git a/crates/metal2vulkan/src/lower/sampler/linear.rs b/crates/metal2vulkan/src/lower/sampler/linear.rs index 98beb706f..8bafd3291 100644 --- a/crates/metal2vulkan/src/lower/sampler/linear.rs +++ b/crates/metal2vulkan/src/lower/sampler/linear.rs @@ -18,8 +18,11 @@ //! `RGBA32Float` texture's, within one step of the grid, so a filtered sample of such a slot there //! records `PrecisionNote::HalfSampleFilter` or `PrecisionNote::FloatSampleFilter` where the bound //! format is two-plane YCbCr ([`metal_filtered_ycbcr`]), through a runtime sampler slot only where -//! the bound sampler filters ([`filtering_word`]). A device whose memory is the host's reads the -//! planes in place, Metal's filter exactly (`in_place`). +//! the bound sampler filters ([`filtering_word`]). A heap's texture (an argument buffer's) is held +//! by the same view and sampled by the same sampler, so its filtered sample records the note where +//! a texture its handles can name is two-plane YCbCr, and through an argument buffer's sampler +//! where a sampler state an argument buffer can name filters. A device whose memory is the host's +//! reads a slot's planes in place, Metal's filter exactly (`in_place`). use crate::air::abi::{Filter, MipFilter, SamplerState}; use crate::error::Error; @@ -62,8 +65,10 @@ pub(super) const PLANE_WORDS: u32 = 576; /// Through a runtime sampler slot each clause also tests the word of the sampler bound there /// ([`filtering_word`]), which the runtime reads at each draw or dispatch: a bound sampler that /// reads one texel of one level takes the texel the view holds, Metal's read, and holds none. -/// An argument buffer's sampler states its word in a table no slot's test reads, so its clauses -/// test the bound format alone. +/// An argument buffer's sampler is the state whose ID its memory holds, which no plan reads: its +/// clauses test that a sampler state an argument buffer can name filters +/// (`NoteOn::ArgumentSamplers`, every live state), so a program whose live states all read one +/// texel of one level holds none. pub(super) fn filter_note( cx: &SelectCx<'_>, op: &SampleOp, @@ -83,8 +88,8 @@ pub(super) fn filter_note( true => return Ok(None), false => None, }, - Some(SamplerRef::Slot(n)) => Some(filtering_word(n)), - None => None, + Some(SamplerRef::Slot(n)) => Some(filtering_word(n).to_vec()), + None => Some(vec![NoteTest::equal(NoteOn::ArgumentSamplers, 1, 1)]), }; let Some(formats) = metal_filtered_ycbcr(cx, image) else { return Ok(None); @@ -130,27 +135,30 @@ fn filtering_word(n: u32) -> [NoteTest; 2] { /// [`PackedTexels::YCbCrExtended8192`]), whose view holds Metal's reads exactly but which Metal's /// sampler then filters as an `RGBA16Float` or `RGBA32Float` texture's texels, not on the format's /// own grid. The runtime reads the bound format (`SpecKey::BoundTexelFormat`) and announces it as -/// `ycbcr-filter-not-exact` ([`filter_note`] adds a runtime sampler slot's word). `None` on any -/// other device, and for a heap's texture. +/// `ycbcr-filter-not-exact` ([`filter_note`] adds a runtime sampler slot's word). A heap's +/// texture, which a handle names at run time, holds one clause: a texture the stage's handles can +/// name is two-plane YCbCr (`SpecKey::HeapYCbCrTextures`, which the plan gives from the command's +/// heap members). `None` on any other device. pub(super) fn metal_filtered_ycbcr(cx: &SelectCx<'_>, image: ImageRef) -> Option> { - let ImageRef::Slot(index) = image else { - return None; - }; let metal = cx .profile .fields() .enabled .properties .contains(&crate::device::requirements::VkProperty::MetalSampler); - metal.then(|| { - any_of( + if !metal { + return None; + } + Some(match image { + ImageRef::Slot(index) => any_of( [ PackedTexels::YCbCr2048, PackedTexels::YCbCr8192, PackedTexels::YCbCrExtended8192, ] .map(|p| NoteTest::equal(NoteOn::Bound(index), TexelFormat::PACKED_MASK, p.class().0)), - ) + ), + ImageRef::Heap { .. } => any_of([NoteTest::equal(NoteOn::HeapTextures(cx.stage), 1, 1)]), }) } diff --git a/crates/metal2vulkan/src/lower/sampler/select.rs b/crates/metal2vulkan/src/lower/sampler/select.rs index 282672fd8..689825cfd 100644 --- a/crates/metal2vulkan/src/lower/sampler/select.rs +++ b/crates/metal2vulkan/src/lower/sampler/select.rs @@ -2186,10 +2186,20 @@ fn select_one( // A filtered sample's note, where Metal's own sampler filters the slot and a two-plane YCbCr // format bound there takes another filter than Metal's: the clauses test the bound format, // which the runtime reads at each draw, and through a runtime sampler slot the bound word's - // filter (`SpecKey::BoundSamplerWord`, which the plan gives: no key carries either). + // filter (`SpecKey::BoundSamplerWord`, which the plan gives: no key carries either); a heap + // texture's test what its handles and an argument buffer's sampler can name. A handle names a + // two-plane YCbCr texture (2D, one layer) only through a 2D color class. let by = stat.map(|(r, _)| r); - if let Some((note, when)) = super::linear::filter_note(cx, &op, form, (by, image))? { - cx.note_when(note, when, m)?; + let two_plane_reach = match image { + ImageRef::Slot(_) => true, + ImageRef::Heap { .. } => { + shape.dim == ImageDim::D2 && !shape.array && !shape.depth && !shape.ms + } + }; + if two_plane_reach { + if let Some((note, when)) = super::linear::filter_note(cx, &op, form, (by, image))? { + cx.note_when(note, when, m)?; + } } // A pixel sampler's coordinate reaches the device's sampler over the level-0 size, whose // texels at a texel edge or a filter step's edge are the device's arithmetic's on that diff --git a/crates/metal2vulkan/src/lower/select.rs b/crates/metal2vulkan/src/lower/select.rs index a152bf1d7..16ee747ec 100644 --- a/crates/metal2vulkan/src/lower/select.rs +++ b/crates/metal2vulkan/src/lower/select.rs @@ -1755,7 +1755,10 @@ fn finish( /// `NearestPixelSampler` boolean, by the function's slot index, or a texture slot's /// `UnmeasuredTexels` boolean, or the class of the format bound at a texture slot, which no /// constant carries (`SpecKey::BoundTexelFormat`), or the whole word of the sampler bound at a -/// sampler slot, which none carries either (`SpecKey::BoundSamplerWord`). +/// sampler slot, which none carries either (`SpecKey::BoundSamplerWord`), or whether a texture a +/// stage's handles can name is two-plane YCbCr (`SpecKey::HeapYCbCrTextures`), or whether a sampler +/// state an argument buffer can name filters (`SpecKey::FilteringArgumentSampler`), which the plan +/// gives. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] pub(crate) enum NoteOn { Sampler(u32), @@ -1763,6 +1766,8 @@ pub(crate) enum NoteOn { Unmeasured(u32), Bound(u32), BoundSampler(u32), + HeapTextures(Stage), + ArgumentSamplers, } /// A test of one slot's specialization constant `v`: it holds where `(v & mask == bits) == equal`, @@ -1833,6 +1838,9 @@ fn declared(families: &FamilyPlans, t: NoteTest) -> Option { NoteOn::BoundSampler(index) => { SpecKey::BoundSamplerWord(families.sampler.slots.get(&index)?.slot) } + // Given by the plan from what the command's handles can name, never a constant. + NoteOn::HeapTextures(stage) => SpecKey::HeapYCbCrTextures(stage), + NoteOn::ArgumentSamplers => SpecKey::FilteringArgumentSampler, NoteOn::Sampler(index) => { let r = families.sampler.slots.get(&index)?; let fields = r.fields(); diff --git a/crates/metal2vulkan/src/metal/texel_format.rs b/crates/metal2vulkan/src/metal/texel_format.rs index 0d4890ee3..602a771e3 100644 --- a/crates/metal2vulkan/src/metal/texel_format.rs +++ b/crates/metal2vulkan/src/metal/texel_format.rs @@ -232,6 +232,15 @@ impl TexelFormat { pub const NAN_FREE: u32 = BicubicTexels::UNORM | BicubicTexels::SNORM | BicubicTexels::SRGB | BicubicTexels::EXTENDED; + /// Whether the class's [`PACKED`](Self::PACKED) field is a two-plane YCbCr format's + /// ([`PackedTexels::ycbcr`]): a texture Metal's own sampler filters as a float texture's + /// texels, not on the field's grid (`lower::sampler::linear`). + pub(crate) fn two_plane_ycbcr(self) -> bool { + PackedTexels::ALL + .iter() + .any(|p| p.ycbcr() && self.0 & TexelFormat::PACKED_MASK == p.class().0) + } + /// Whether the class states channels ([`BicubicTexels::PRESENT`]): a measured family's does, /// a [`CubeCorner`] alone does not, so the binder states no border texel for it. pub fn has_channels(self) -> bool { diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index 41d6c01d3..4c20bb8d7 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -443,13 +443,21 @@ impl SpecClause { /// Whether a test reads a value no pipeline's key carries that a plan gives /// (`BindingPlan::specialized_value`): one the function reads as data - /// (`SpecKey::read_as_data`), or the word of the sampler bound at a slot - /// (`SpecKey::BoundSamplerWord`). A runtime reads such a clause at each draw or dispatch, from - /// the values its plan gives ([`StageModule::note_clauses_bound`]). + /// (`SpecKey::read_as_data`), the word of the sampler bound at a slot + /// (`SpecKey::BoundSamplerWord`), or what the stage's handles can name + /// (`SpecKey::HeapYCbCrTextures`, `SpecKey::FilteringArgumentSampler`). A runtime reads such + /// a clause at each draw or dispatch, from the values its plan gives + /// ([`StageModule::note_clauses_bound`]). pub fn tests_bound_values(&self) -> bool { - self.all - .iter() - .any(|t| t.key.read_as_data() || matches!(t.key, SpecKey::BoundSamplerWord(_))) + self.all.iter().any(|t| { + t.key.read_as_data() + || matches!( + t.key, + SpecKey::BoundSamplerWord(_) + | SpecKey::HeapYCbCrTextures(_) + | SpecKey::FilteringArgumentSampler + ) + }) } /// Whether every test of the bound formats holds where `bound` gives the class of the format @@ -1033,12 +1041,14 @@ pub enum PrecisionNote { /// bound format, which the runtime reads at each draw or dispatch and announces as /// `ycbcr-filter-not-exact`, and through a runtime sampler slot under the bound sampler's word /// (`SpecKey::BoundSamplerWord`, which the plan gives) where it filters: a linear minification - /// or magnification filter, a linear mip filter, anisotropy, or a cubic filter. A sample - /// through a sampler that reads one texel of one level (nearest minification and - /// magnification, no mip filter or a nearest one, no anisotropy: a constexpr one, or a runtime - /// slot's bound one) and a gather are not filtered and do not carry it; an argument buffer's - /// sampler, whose word no slot's test reads, carries it whatever it states. A device that - /// samples natively records + /// or magnification filter, a linear mip filter, anisotropy, or a cubic filter. A sample of a + /// texture an argument buffer holds (a heap's) is recorded where a texture its handles can name + /// is two-plane YCbCr (`SpecKey::HeapYCbCrTextures`), and through an argument buffer's sampler + /// where a sampler state an argument buffer can name filters + /// (`SpecKey::FilteringArgumentSampler`): the plan gives both. A sample through a sampler that + /// reads one texel of one level (nearest minification and magnification, no mip filter or a + /// nearest one, no anisotropy: a constexpr one, or a runtime slot's bound one) and a gather + /// are not filtered and do not carry it. A device that samples natively records /// [`PrecisionNote::DeviceSampling`] instead. The `float` result's counterpart is /// [`PrecisionNote::FloatSampleFilter`]. Validation derives no tolerance from it: the class is /// unbounded. @@ -1085,11 +1095,12 @@ pub enum PrecisionNote { /// format bound there: a two-plane YCbCr texture's, as for [`PrecisionNote::HalfSampleFilter`] /// (a depth texture's sample and a comparison's included). A sample is filtered unless its /// sampler has nearest minification and magnification, no mip filter or a nearest one, and no - /// anisotropy: linear minification or magnification, a linear mip filter, anisotropy, and an - /// argument buffer's sampler (whose word no slot's test reads) all filter. Recorded under the - /// slot's bound format, and through a runtime sampler slot under the bound sampler's word - /// (`SpecKey::BoundSamplerWord`), whose filter is not known when the function compiles: the - /// runtime reads both at each draw or dispatch and announces it as `ycbcr-filter-not-exact`. A + /// anisotropy: linear minification or magnification, a linear mip filter, anisotropy, and a + /// cubic filter filter. Recorded under the slot's bound format, and through a runtime sampler + /// slot under the bound sampler's word (`SpecKey::BoundSamplerWord`), whose filter is not + /// known when the function compiles, and for a heap's texture under what its handles and an + /// argument buffer's sampler can name, as [`PrecisionNote::HalfSampleFilter`] is: the runtime + /// reads them at each draw or dispatch and announces it as `ycbcr-filter-not-exact`. A /// device that samples natively records [`PrecisionNote::DeviceSampling`] instead. Validation /// derives no tolerance from it: the class is unbounded. FloatSampleFilter, diff --git a/crates/metal2vulkan/src/pipeline/sym.rs b/crates/metal2vulkan/src/pipeline/sym.rs index 1b665a5f6..5a9edbab5 100644 --- a/crates/metal2vulkan/src/pipeline/sym.rs +++ b/crates/metal2vulkan/src/pipeline/sym.rs @@ -833,6 +833,23 @@ pub enum SpecKey { /// known (a reading of the module alone, `StageModule::precision_notes_under`), such a test /// holds. A slot bound to no sampler takes 0. BoundSamplerWord(SlotRef), + /// Boolean: a texture the stage's handles can name is of a two-plane YCbCr class (its + /// `metal::texel_format::TexelFormat::PACKED` field `YCbCr2048`, `YCbCr8192` or + /// `YCbCrExtended8192`): a heap member of the command reaching the stage, one it makes + /// resident (`BindShape::used`) or binds at a texture slot of the stage + /// (`bind::heap`'s members). Read by a specialized note's test alone + /// ([`SpecTest`](crate::pipeline::SpecTest)), as [`BoundSamplerWord`](Self::BoundSamplerWord) + /// is: a plan gives it (`BindingPlan::specialized_value`), and where it is not known such a + /// test holds. A texture the command neither names nor makes resident, which a handle loaded + /// from memory may still reach and whose read Metal leaves undefined, is not counted. + HeapYCbCrTextures(Stage), + /// Boolean: a sampler state an argument buffer's sampler handle can name filters: one of the + /// bind state's argument samplers (`BindState::argument_samplers`, every live state, its + /// shape in `BindShape`) has a linear minification, magnification or mip filter, anisotropy, + /// or a cubic filter. Which state an argument buffer holds is in its memory, which no plan + /// reads. Read by a specialized note's test alone, given by a plan, as + /// [`HeapYCbCrTextures`](Self::HeapYCbCrTextures) is. + FilteringArgumentSampler, } impl SpecKey { diff --git a/crates/metal2vulkan/src/tests/engine_handles.rs b/crates/metal2vulkan/src/tests/engine_handles.rs index cf6b4ce7b..9ab8d663a 100644 --- a/crates/metal2vulkan/src/tests/engine_handles.rs +++ b/crates/metal2vulkan/src/tests/engine_handles.rs @@ -2796,9 +2796,12 @@ define void @k(ptr addrspace(2) %m, ptr addrspace(1) %out{param}, i32 %gid) {{ } /// A heap texture's linear sample, through a constexpr sampler of linear filters (2D and 3D), a -/// runtime sampler slot, or the sampler its argument buffer holds, is the device's sample, with no -/// filter note; the census names the sample by its source, and the module states no `TexelFormat` -/// specialization. A 2D sample through a constexpr or runtime sampler also emulates a raw-held +/// runtime sampler slot, or the sampler its argument buffer holds, is the device's sample; the +/// census names the sample by its source, and the module states no `TexelFormat` +/// specialization. On a profile that samples through Metal's own sampler a 2D sample records the +/// filter note only under what the command's handles can name (a two-plane YCbCr texture, +/// `SpecKey::HeapYCbCrTextures`), never outright; a 3D one, whose class holds no two-plane +/// texture, records none. A 2D sample through a constexpr or runtime sampler also emulates a raw-held /// texture's, in a branch on the class the handle carries (the search's flagged form, whose masks /// and table the census counts under `HEAP_CLASS_CENSUS`). Each validates; a profile without the /// sampled heap refuses each. (The interpreter models no sample; the runtime lane @@ -2856,10 +2859,21 @@ fn heap_linear_samples_are_the_device_s() { raw, "{what}" ); - assert!( - !a.precision.contains(&PrecisionNote::FloatSampleFilter), + let filter = PrecisionNote::FloatSampleFilter; + assert_eq!( + a.precision.contains(&filter), + !three && metal_sampler(&p), "{what}" ); + let clauses: Vec<_> = (a.specialized.iter()) + .filter(|s| s.note == filter) + .flat_map(|s| &s.when) + .collect(); + assert_eq!(clauses.is_empty(), three || !metal_sampler(&p), "{what}"); + for c in clauses { + let heap = SpecKey::HeapYCbCrTextures(crate::pipeline::sym::Stage::Kernel); + assert!(c.all.iter().any(|t| t.key == heap), "{what}: {c:?}"); + } assert!( !a.interface .read_keys() diff --git a/crates/metal2vulkan/src/tests/engine_heap_binder.rs b/crates/metal2vulkan/src/tests/engine_heap_binder.rs index e03b91ab8..65dca2cfe 100644 --- a/crates/metal2vulkan/src/tests/engine_heap_binder.rs +++ b/crates/metal2vulkan/src/tests/engine_heap_binder.rs @@ -2606,3 +2606,172 @@ fn late_argument_samplers_fit_twice_the_class_and_the_plan_s_checks() { assert!(relisted(&plan, &with(linear)).is_some()); assert_eq!(relisted(&plan, &with(cubic)), None, "beside no test"); } + +/// A filtered `float` sample of a texture an argument buffer holds records its filter note on a +/// device that samples through Metal's own sampler (`moltenvk-m3`), under what the command's +/// handles and an argument buffer's sampler can name (`lower::sampler::linear::filter_note`): the +/// plan gives `SpecKey::HeapYCbCrTextures` 1 exactly where a texture the command makes resident is +/// two-plane YCbCr, and `SpecKey::FilteringArgumentSampler` 1 exactly where a listed argument +/// sampler filters (a linear minification, magnification or mip filter, or anisotropy), and the +/// note holds (`StageModule::precision_notes_bound`) exactly where both do. Through a runtime +/// sampler slot the bound sampler's word decides in the second's place. A comparison of a depth +/// texture, whose class holds no two-plane texture, and an integer texture's sample record no +/// such note; lavapipe, which samples natively, records none. +#[test] +fn a_heap_texture_s_ycbcr_filter_note_holds_where_its_sampler_can_filter() { + use crate::metal::SamplerMipFilter; + use crate::pipeline::artifact::PrecisionNote; + use crate::pipeline::sym::SpecKey; + let note = PrecisionNote::FloatSampleFilter; + let dev = m3(); + let (Some(argument), Some(compare), Some(integer)) = ( + argument_sampler_pipeline(&dev, "argument_sampler_sample"), + argument_sampler_pipeline(&dev, "argument_sampler_compare"), + argument_sampler_pipeline(&dev, "argument_sampler_integer"), + ) else { + return; + }; + let Some(bc) = assembled("handles", llvm_assemble(&engine_dir().join("handles.ll"))) else { + return; + }; + let runtime = compute(&dev, &bc, "argument_buffer_runtime_sampler"); + let keys = |p: &ComputePipeline| -> Vec> { + (p.stage.specialized_notes.iter()) + .filter(|s| s.note == note) + .flat_map(|s| &s.when) + .map(|c| c.all.iter().map(|t| t.key).collect()) + .collect() + }; + let heap = SpecKey::HeapYCbCrTextures(Stage::Kernel); + assert_eq!( + keys(&argument), + vec![vec![heap, SpecKey::FilteringArgumentSampler]] + ); + let sampler = SlotRef { + stage: Stage::Kernel, + class: SlotClass::Sampler, + index: 0, + }; + let runtime_keys = keys(&runtime); + assert!(!runtime_keys.is_empty()); + for k in &runtime_keys { + assert!( + k.contains(&heap) && k.contains(&SpecKey::BoundSamplerWord(sampler)), + "{k:?}" + ); + } + for p in [&compare, &integer] { + assert!(keys(p).is_empty(), "{:?}", p.stage.specialized_notes); + assert!(!p.stage.precision_notes.contains(¬e)); + } + let lavapipe = { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../metal2vulkan-validation/profiles/lavapipe.json"); + let text = std::fs::read_to_string(path).expect("profile"); + let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); + Device::new(desc, DevicePolicy::default()).expect("device") + }; + for entry in ["argument_sampler_sample", "argument_sampler_compare"] { + let native = argument_sampler_pipeline(&lavapipe, entry).expect("lavapipe"); + assert!(keys(&native).is_empty(), "{entry} on lavapipe"); + assert!(!native.stage.precision_notes.contains(¬e), "{entry}"); + } + let desc = |linear: bool, mip: SamplerMipFilter, anisotropy: u32| { + let mut d = SamplerDescriptor::new(); + if linear { + d.min_filter = SamplerMinMagFilter::Linear; + d.mag_filter = SamplerMinMagFilter::Linear; + } + d.mip_filter = mip; + d.max_anisotropy = anisotropy; + d + }; + let nearest = desc(false, SamplerMipFilter::NotMipmapped, 1); + // Each list of live argument samplers, and whether one of them filters. + let lists = [ + ("none", vec![], false), + ("nearest", vec![nearest], false), + ( + "nearest mip filter", + vec![desc(false, SamplerMipFilter::Nearest, 1)], + false, + ), + ( + "nearest and linear", + vec![nearest, desc(true, SamplerMipFilter::NotMipmapped, 1)], + true, + ), + ( + "linear mip filter", + vec![desc(false, SamplerMipFilter::Linear, 1)], + true, + ), + ( + "anisotropic", + vec![desc(false, SamplerMipFilter::NotMipmapped, 16)], + true, + ), + ]; + let formats = [ + (PixelFormat::YCBCR84442P, true), + (PixelFormat::YCBCR104442PSRGB, true), + (PixelFormat::RGBA16Float, false), + (PixelFormat::RGBA8Unorm, false), + ]; + for (pf, ycbcr) in formats { + for (name, list, filters) in &lists { + let what = format!("{pf:?} beside {name}"); + let state = BindState { + used_resources: vec![used(1, TextureType::Type2D, pf, read(), Some(A))], + argument_samplers: (list.iter().zip(1u64..)) + .map(|(d, id)| argument_sampler(*d, id)) + .collect(), + ..Default::default() + }; + let plan = argument + .plan(&dev, &state.shape()) + .unwrap_or_else(|e| panic!("{what}: {e}")); + assert_eq!( + plan.specialized_value(heap), + Some(u64::from(ycbcr)), + "{what}" + ); + let filtering = plan.specialized_value(SpecKey::FilteringArgumentSampler); + assert_eq!(filtering, Some(u64::from(*filters)), "{what}"); + let held = (argument.stage) + .precision_notes_bound(&plan.specialization, &|k| plan.specialized_value(k)) + .contains(¬e); + assert_eq!(held, ycbcr && *filters, "{what}"); + } + // Through a runtime sampler slot: the bound sampler's word. + for (name, d, filters) in [ + ("nearest", nearest, false), + ( + "linear", + desc(true, SamplerMipFilter::NotMipmapped, 1), + true, + ), + ] { + let what = format!("{pf:?} through a runtime {name} sampler"); + let mut state = BindState { + used_resources: vec![used(1, TextureType::Type2D, pf, read(), Some(A))], + ..Default::default() + }; + let mut t = StageTable::default(); + t.samplers.insert(0, BoundSampler::new(d)); + state.stages.insert(Stage::Kernel, t); + let plan = runtime + .plan(&dev, &state.shape()) + .unwrap_or_else(|e| panic!("{what}: {e}")); + assert_eq!( + plan.specialized_value(heap), + Some(u64::from(ycbcr)), + "{what}" + ); + let held = (runtime.stage) + .precision_notes_bound(&plan.specialization, &|k| plan.specialized_value(k)) + .contains(¬e); + assert_eq!(held, ycbcr && filters, "{what}"); + } + } +} diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index fbbed0c7a..58544fa83 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -14120,7 +14120,9 @@ variant metal2vulkan::pipeline::SpecKey::BicubicTexels BicubicTexels(SlotRef) variant metal2vulkan::pipeline::SpecKey::BoundSamplerWord BoundSamplerWord(SlotRef) variant metal2vulkan::pipeline::SpecKey::BoundTexelFormat BoundTexelFormat(SlotRef) variant metal2vulkan::pipeline::SpecKey::ConstantLanes ConstantLanes(SlotRef) +variant metal2vulkan::pipeline::SpecKey::FilteringArgumentSampler FilteringArgumentSampler variant metal2vulkan::pipeline::SpecKey::FlatLocalSize FlatLocalSize +variant metal2vulkan::pipeline::SpecKey::HeapYCbCrTextures HeapYCbCrTextures(Stage) variant metal2vulkan::pipeline::SpecKey::ImageblockHeight ImageblockHeight variant metal2vulkan::pipeline::SpecKey::ImageblockWidth ImageblockWidth variant metal2vulkan::pipeline::SpecKey::LocalSize LocalSize(Axis) diff --git a/docs/API.md b/docs/API.md index ab96edd53..489905620 100644 --- a/docs/API.md +++ b/docs/API.md @@ -2395,7 +2395,14 @@ bound. format of their codes, which Metal's sampler filters as that format's: neither is announced), and through a runtime sampler slot only where the sampler bound there filters (a linear minification, magnification or mip filter, anisotropy, or a cubic filter), read at each draw or - dispatch; an argument buffer's sampler announces it whatever it states. + dispatch. A filtered sample of a texture an argument buffer holds (a 4:4:4 one: a 4:2:0 or 4:2:2 + texture a function that samples through handles can reach is refused) is announced at a draw or + dispatch where a texture the command makes resident or binds that its handles can name is + two-plane YCbCr, through a runtime sampler slot only where the bound sampler filters, and + through an argument buffer's sampler only where a live sampler state filters: the runtime does + not read which state the buffer's memory names, so one linear state alive announces it for a + buffer that holds a nearest one. A texture the command neither names nor makes resident, which + its function may still reach through its ID (Metal's read of it is undefined), is not counted. Cost: where the device converts the planes' format, the texels are its own Y′CbCr conversion's, at its precision and unclamped where it does not clamp, not Metal's fixed-point read; elsewhere the texels hold Metal's reads exactly, but the @@ -3312,7 +3319,8 @@ bound. module samples a texture with a `half` result through a filter (linear minification or magnification, a linear mip filter, anisotropy, or a runtime sampler slot whose bound sampler filters so) that Metal's own sampler (MoltenVK) answers otherwise than Metal filters the format - bound there: a two-plane YCbCr texture's. + bound there: a two-plane YCbCr texture's, at a slot or held by an argument buffer (announced as + `ycbcr-filter-not-exact`). - `metal2vulkan-degrade-srgb-texel-decode` (precision). `PrecisionNote::SrgbTexelDecode`: The module reads, samples, or gathers a texture with a `half` or `float` result through the device's sRGB decode, or decodes the device's filter of its codes, where the texture may be bound in an 8-bit @@ -3327,7 +3335,7 @@ bound. - `metal2vulkan-degrade-float-sample-filter` (precision). `PrecisionNote::FloatSampleFilter`: The module samples a texture with a `float` result through a filter that Metal's own sampler (MoltenVK) answers otherwise than Metal filters the format bound there: a two-plane YCbCr - texture's. + texture's, at a slot or held by an argument buffer (announced as `ycbcr-filter-not-exact`). - `metal2vulkan-degrade-function-storage-assumed` (precision). `PrecisionNote::FunctionStorageAssumed`: A vertex or fragment function keeps more private memory (its `alloca`s, a call stack among them, or constants held as `Private` variables) than the floor,