Take the device's Y'CbCr conversion for 4:2:2 twins and for YCbCr planes read in place

4:2:2 twins hold the device's own conversion where it has Metal's reconstruction; planes read
in place are sampled through the device's Y'CbCr sampler where the driver lays them out as the
surface does; RADV's 10-bit conversion recorded as reading codes as words. With development's
golden re-bless after the native landings. SEMANTICS 1911, ARTIFACT 477, RUNTIME 1683.

One work packet, landed as 6 commit(s) (a1088b2c2e..67dc5650e1 on archive/development-linear-2026-10-28-evening), in order:

* Hold a 4:2:2 texture's twin as the device's own conversion where it converts the format

A GBGR422 or BGRG422 texture reads a decoded twin of 8-bit codes on every device: Vulkan views
G8B8G8R8_422_UNORM and B8G8R8G8_422_UNORM only through a sampler Y'CbCr conversion, which no
pipeline's layout bakes. Until now the twin always held Metal's decode, (3c + n + 2) >> 2, computed
by the runtime's own kernel or on the CPU, even where the device converts the format itself.

Now, where the device converts the pairs' format with Metal's reconstruction (its optimal tiling
reports SAMPLED_IMAGE, TRANSFER_DST, MIDPOINT_CHROMA_SAMPLES and a linear chroma filter, and the
width is even), the twin holds the device's conversion:
- each decode pass copies the written rows' pairs out of the carrier into the scratch, then into
  a per-texture image of the 4:2:2 format, and samples it through the device's conversion (the
  identity model at full range) into the band's texels, which go into the twin;
- the kernel is the new bind::chroma_sample_module (ChromaSampleModule), a sample at each luma
  texel's centre at level 0, each channel stored as roundEven(clamp(c, 0, 1) * 255);
- such a carrier takes no host or staging copies, so every write's decode is a GPU pass and no
  texel of the twin is the CPU's decode;
- counted in WorkCounts::chroma_device_twins and chroma_device_decodes, and announced
  decoded-texel-precision (the catalogue's cost text says so).
Elsewhere the twin keeps Metal's decode, as capability. The FAST-PATHS device-gaps table has the
row.

Venues (from the formats' features): MoltenVK 1.4.2 converts both formats (its single-plane 4:2:2
reconstruction is Vulkan's); lavapipe filters their chroma nearest only; RADV (Mesa 26.2.4, 780M)
reports neither format.

Verified:
- clippy -D warnings, plain and --cfg m2v_gpu, for metal2vulkan and metal2vulkan-runtime;
- chroma_decode unit tests (the sample module is valid on every committed profile), fast_paths,
  the degradation catalogue tests, api_surface and api_signatures (table blessed: the new module,
  ChromaDecode::format and the two WorkCounts fields);
- M3 Max (MoltenVK 1.4.2): tests::ycbcr_device::a_four_two_two_twin_holds_the_devices_conversion...
  took the device route for both formats (twins 1, passes >= 2, no CPU decode, announced once);
  chroma within 0.5000 codes of Vulkan's (3c + n) / 4 on 40 x 24 random pairs (the test also
  prints how many chroma codes differ from Metal's; that line is compiled and clippy-clean, not
  yet run);
  runtime_lane::chroma_pairs (5 tests) pass, the read lane checking green exactly and red and
  blue within 1/255 of Metal's on the device route;
- lavapipe (arm64 linux-gate, m2v_cpu_icd): the same runtime test and the five chroma_pairs lane
  tests pass; no 4:2:2 texture took the device route (twins hold Metal's decode, exactly);
- RADV 780M: not run (host away).

docs/REFUSALS.md regenerated: unchanged. runtime-sources.sha256 updated; the RUNTIME_VERSION
bump is in the versions commit.

* Record that RADV's 10-bit Y'CbCr conversion reads codes as words

RADV has the same defect lavapipe has (RuntimeDriverDefect::TenBitCodesReadAsWords): a sampler
Y'CbCr conversion of G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16 reads each code's 16-bit word as a
16-bit UNORM value, its six unused low bits included, where Vulkan converts the 10-bit code as
c / 1023.

Evidence: a bare Vulkan probe on the Radeon 780M (RADV, Mesa 26.2.4) read luma code 1023 (low bits
0) through the identity model of a LINEAR image of the format as 0.999039, which is 65472 / 65535
and not 1.0. The optimal tiling's conversion of the format was not measured; the row is per
driver, as the defect table's rows are.

What changes: the AFFECTED table gains a MESA_RADV row, with no clean GPU. Nothing is refused.
- A 10-bit two-plane texture on RADV now converts through Metal's arithmetic. Before, RADV's
  optimal-tiling device conversion (ycbcr_device.rs) took it, and that path was never measured on
  RADV.
- The planes image of the next commit is not taken for 10-bit codes there.
The driver_defects test expectations (every committed RADV profile, Hawk Point's 780M) and the
docs that name the defect's drivers (ycbcr.rs, ycbcr_device.rs, docs/API.md) say RADV too.

Verified: clippy -D warnings (plain and --cfg m2v_gpu) for metal2vulkan, metal2vulkan-runtime and
metal2vulkan-validation; tests::driver_defects on the host. The RADV device itself was not run: the
host is away.

* Sample YCbCr planes read in place through the device's own Y'CbCr sampler where it has Metal's reconstruction

On an integrated GPU or a CPU device, a function that only samples a YCBCR8_420_2P or
YCBCR10_420_2P texture reads the planes in place through a uniform texel buffer. It converts and
filters them with Metal's fixed-point arithmetic in the shader. Where the device converts the
planes' 4:2:0 format as a linear image with Metal's reconstruction (midpoint chroma through a
linear chroma filter), rule 1 makes the device's own conversion the only form. So such a slot now
samples the planes through the device's sampler Y'CbCr conversion. Elsewhere the texel buffer
read stays, as capability.

Translator (metal2vulkan):
- bind::YCbCrPlanesSampler (new, non-exhaustive) holds the conversion: the codes' bits and the
  surface's range and matrix. It also gives the image's format: G8_B8R8_2PLANE_420_UNORM, or
  G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16.
- YCbCrInPlace::with_planes_image, ::sampler and ::planes_sampler. TextureShape::Texture gains
  ycbcr_planes_sampler.
- RuntimeFact::YCbCrInPlace gains `device`: the device's sampler takes every sample of the slot.
  It does not where a constexpr sampler has a border address mode, or a texel offset is placed by a
  parent's size.
- VariantKey and LoweringInputs gain ycbcr_planes_sampled. The binder fills it from slots with
  `device`, bound to a texture that holds the image, whose runtime sampler words have no border
  mode on s or t.
- Such a slot is declared as a combined image sampler: ResourceKind::YCbCrPlanes and
  BindingSource::YCbCrPlanes, written from WriteSource::YCbCrPlanesImage. Its immutable sampler is
  the new vk::SamplerDesc::ycbcr: linear, clamp to edge, lod 0, and a new `ycbcr` field.
- Each sample (lower/sampler/in_place.rs device_sample) is OpImageSampleExplicitLod at level 0:
  - a linear sample takes Metal's coordinate, with its texel offset moved in texels;
  - a nearest one takes the centre of the luma texel Metal reads, clamped to the edge;
  - pixel coordinates and the filter are known when the module is made (constexpr) or read from
    the runtime word;
  - a half result is rounded to a half, as every sampled texel's is.
- The texel buffer stays the slot's resource otherwise. The planes read use is tracked as before.

Runtime (metal2vulkan-runtime):
- YCbCrFormats queries the two 4:2:0 formats' LINEAR tiling: SAMPLED_IMAGE,
  MIDPOINT_CHROMA_SAMPLES, a linear chroma filter, and the limits and
  combinedImageSamplerDescriptorCount.
- YCbCrSampler::planes gives the conversion. It is None under TwoPlaneChromaMisplaced, and for
  10-bit codes under TenBitCodesReadAsWords. holds_planes checks for an even size within the
  limits.
- texture/ycbcr_planes.rs (new) makes a PREINITIALIZED linear image of the format over the planes'
  bytes, and only in memory the runtime allocated. It is made only where:
  - the luma plane comes first;
  - the driver's PLANE_0 and PLANE_1 subresource layouts are the surface's offsets and pitches;
  - the alignment, the type and the room within the buffer fit.
  Its view and every immutable sampler of it share one VkSamplerYcbcrConversion
  (Device::made_ycbcr_conversion, kept in the owned kernels' map), so the two are identically
  defined (VUID-VkWriteDescriptorSet-descriptorType-02738). Its first move rides the next
  submission (Fresh, never rebindable), and it is announced ycbcr-filter-not-exact.
- Fresh pages, no-copy pages and the caller's VkBuffer keep the texel buffer. An image bound to
  imported memory starts UNDEFINED, and the in-place check covers that first move for single-plane
  images only.
- The texture's facts state the image (with_planes_image). binding.rs writes the view in GENERAL
  under the layout's immutable sampler.
- sampler_set chains the conversion into each SamplerDesc::ycbcr sampler. A non-pushed set 0
  reserves combinedImageSamplerDescriptorCount descriptors per such binding.
- WorkCounts gains ycbcr_planes_images, ycbcr_planes_images_kept_{conversion,memory,layout} and
  ycbcr_planes_images_bound.

Venues (from the formats' linear features):
- Radeon 780M (RADV, Mesa 26.2.4): reports the 8-bit route for rows 256 bytes apart. Its 10-bit
  codes carry TenBitCodesReadAsWords (previous commit).
- MoltenVK 1.4.2: TwoPlaneChromaMisplaced.
- lavapipe: its 4:2:0 conversion is cosited only.

Measured before building, through a bare Vulkan probe on the 780M with 8-bit codes:
- luma centres within 0.0003 codes of Vulkan's model, and points between texels within 0.66
  codes;
- Metal's conversion-then-filter differs by up to 54/255 between texels of random planes;
- GPU time, 3840x2160 composited into 1680x1050: 248 us against the texel buffer's 340 (1 pass),
  741 against 1027 (3 passes).
The runtime's path itself is not measured on a device that takes it: the 780M host is away.

Docs: a FAST-PATHS device-gaps row (the device's route, where the texel buffer stays, and why);
the in-place paragraph; docs/API.md (the pipeline interface paragraph, and the notice's catalogue
entry); module docs (ycbcr.rs, ycbcr_device.rs, ycbcr_image.rs); the api_surface table
(YCbCrPlanesSampler N); api_signatures blessed.

Tests:
- bind::ycbcr_in_place::the_planes_sampler_is_the_conversion_word.
- bind::plan::slots::the_planes_image_variant_takes_a_slot_the_device_s_sampler_reads.
- tests::engine_ycbcr_in_place::a_planes_image_slot_samples_through_the_device_s_conversion: the
  lavapipe and M3 profiles; linear, nearest, pixel, offset and runtime samplers, each half and
  float. Each case links and validates, with one OpImageSampleExplicitLod. Border and repeat-offset
  slots state device false.
- Lane runtime_lane::ycbcr_in_place::a_ycbcr_texture_s_planes_image_samples_through_the_device_s_conversion
  covers surfaces whose rows are 256 bytes apart. Each in-place texture is counted exactly once,
  as an image or by why not. Through the image, nearest samples are Vulkan's conversion within the
  device's bound, announced; without it, Metal's texels through the texel buffer, unannounced.

Verified:
- clippy -D warnings, plain and --cfg m2v_gpu, for metal2vulkan, metal2vulkan-runtime and
  metal2vulkan-validation.
- Host, plain target, the touched selection (ycbcr, fast_paths, api_surface, api_signatures,
  codec, slots, api_tests, the inputs encoding, sampler, ash_interop, driver_defects, degradation,
  vk tests): 408 run, 407 passed. The engine test's half cases failed, because a half result was
  an f16 where a sample holds it widened. They now take narrow::round_texel, and the in-place
  engine tests pass, 4 of 4.
- M3 Max (MoltenVK 1.4.2), runtime and validation, ycbcr|chroma|driver_defects|runtime_sources:
  66 run, 64 passed. The planes image test counted [0, 1, 0, 0] for both surfaces (kept for the
  conversion: TwoPlaneChromaMisplaced), bound the texel buffer and read Metal's texels. The two
  failures:
  - the runtime-sources pin, re-pinned in the versions commit;
  - runtime_lane::ycbcr_textures::a_ycbcr_sample_through_an_unmeasured_filter_is_announced
    (anisotropic through a constexpr sampler), which fails the same way at the base, as
    a1f1677174 recorded.
  The 4:2:2 test's new line: GBGR422 and BGRG422 chroma within 0.5000 codes of Vulkan's, and
  0 of 1920 chroma channels a code off Metal's.
- lavapipe (linux-gate arm64, --cfg m2v_cpu_icd), the same selection without the pin: 66 of 66.
  The planes image test counted [0, 1, 0, 0] for both surfaces (cosited only).
- Radeon 780M, the only venue whose features take the route: not run, the host is away. The
  device route's lane test, its notice and its GPU time against the texel buffer are unverified
  through the runtime.

* Bump the cache versions for the 4:2:2 device twins and the YCbCr planes images

- SEMANTICS_VERSION 1908 -> 1909: the translator emits something new under keys that existed
  before. A two-plane YCbCr in-place slot's RuntimeFact::YCbCrInPlace now states `device`, and
  ycbcr_planes_sampled lowers such a slot as a combined image sampler sampled through the device's
  Y'CbCr conversion.
- ARTIFACT_FORMAT_VERSION 475 -> 476: the encoding changed. RuntimeFact::YCbCrInPlace gains
  `device`, SamplerDesc gains `ycbcr`, ResourceKind and BindingSource gain YCbCrPlanes, and the
  YCbCrPlanesSampler struct is new.
- RUNTIME_VERSION 1681 -> 1682: a run of an unchanged artifact may now do something else.
  - A 4:2:2 texture's twin holds the device's conversion where the device converts the format.
  - RADV's 10-bit two-plane textures convert through Metal's arithmetic (TenBitCodesReadAsWords).
  - The runtime makes planes images where the device converts the 4:2:0 format as a linear image
    with Metal's reconstruction.
  - Pools reserve combinedImageSamplerDescriptorCount for planes samplers.

runtime-sources.sha256 is re-pinned over this branch's runtime inputs:
d520b4179f55291b57dc7ffd5182ea5f37790889c768b9d49914f174f428ce7c. This is the fingerprint the
validation build script computed at the tip's tree.

These are lane numbers. The orchestrator renumbers them at landing.

* Re-pin the runtime sources at the landing tip

The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.

* Re-bless the golden hashes on development after the native landings

Two rows of golden_hashes.tsv move: the RADV profile's cells, whose
16-bit-depth bias and tile-store answers the boundary-case commits made the
device's own (SEMANTICS_VERSION 1910, then 1911 with the YCbCr commits). The
engine inventory and the engine golden printouts blessed with no change.

The YCbCr versions commit (569d988e99) names SEMANTICS 1909, ARTIFACT 476
and RUNTIME 1682, the values it was written with on 8b7a8aa2d8. On
development they collided with the 16-bit half output's 1909/476 and the
boundary cases' 1682, so the landing set them to SEMANTICS 1911,
ARTIFACT_FORMAT_VERSION 477 and RUNTIME_VERSION 1683; the commit's text was
not rewritten.

Verified on macOS at 465e0eb538: bless_engine_inventory,
bless_golden_hashes and bless_engine_goldens pass; the conformance crate's
suite 1007/1007.
This commit is contained in:
Anees Iqbal committed 2026-10-28 21:19:28 +02:00
1 parent 57efe92a1a
commit 2f033d3002
63 files changed
+2600 -153

No files matched your search

@@ -1769,6 +1769,17 @@ fn image_descriptor(
// An element past the listed states: no handle names it.
None => vk::DescriptorImageInfo::default().sampler(device.neutral_sampler(*compare)?),
},
// The planes of a two-plane YCbCr texture as the image the device's conversion samples
// (`texture/ycbcr_planes.rs`), its sampler the layout's immutable one of that conversion.
WriteSource::YCbCrPlanesImage { slot }
if ty == vk::DescriptorType::COMBINED_IMAGE_SAMPLER =>
{
let texture = slot_texture(tables, *slot)
.ok_or_else(|| internal("the plan binds an unbound texture slot's planes image"))?;
let view = texture.planes_image_view()?;
device.shared().counts.ycbcr_planes_image_bound();
image(view)
}
_ => return Err(unexpected(&write.source)),
})
}
@@ -24,7 +24,11 @@
//! linear and bicubic) and gathered both formats bit for bit as such an `RGBA8Unorm` texture),
//! exact, decoded after
//! each write as an ETC2 texture's twin is, on the GPU (`bind::chroma_decode_module`) or a host
//! write's on the CPU. A texel reads the pair beside it, so a write's decode is of whole rows
//! write's on the CPU. Where the device converts the format itself with Metal's reconstruction
//! (`ycbcr_device.rs`: a sampler Y′CbCr conversion of `G8B8G8R8_422_UNORM` or
//! `B8G8R8G8_422_UNORM` at the midpoint through a linear chroma filter, MoltenVK), the twin holds
//! the device's conversion of the pairs instead, every write's decode a GPU pass that samples
//! the pairs through it (`bind::chroma_sample_module`), announced `decoded-texel-precision`. A texel reads the pair beside it, so a write's decode is of whole rows
//! (a host write of part of a row decodes its rows as the texture then holds them). Refused: a
//! sparse heap's texture (`RuntimeGap::DecodedHeapTexture`). Without a twin (a heap's texture
//! over the caller's host pages or laid out apart from the heap's bytes) a command that binds
+21 -6
View File
@@ -1373,7 +1373,9 @@ degradations! {
/// random planes, every texel: within 0.04/2048 of Vulkan's conversion past the `half`
/// its image stores, and of Metal's within 6/2048 where the result lies in `[0, 1]`;
/// outside it by what Metal's clamp takes off). Announced where the texture is made,
/// naming its layout.
/// naming its layout. So do the samples of a texture whose planes are read in place
/// through the device's conversion of a linear image of them (`texture/ycbcr_planes.rs`),
/// the device's filter of the codes too: announced where the image is made.
///
/// And a pipeline stage's filtered sample of a texture slot bound to a two-plane YCbCr
/// texture, on a device that samples through Metal's own sampler (MoltenVK,
@@ -1702,9 +1704,12 @@ degradations! {
/// EAC one's 8-bit codes, exact, decoded after each write into it (a PVRTC
/// texture's whole levels). An ASTC texture's first view in its other colour space gives
/// it a second twin of that form's decode. Also a texture of a 4:2:2 format (`GBGR422`,
/// `BGRG422`) on every device, whose Vulkan formats reconstruct chroma by the
/// implementation's rules: its texels' bytes lie in an `R8G8_UNORM` carrier, and its twin
/// holds Metal's texels as 8-bit codes, exact, decoded in whole rows.
/// `BGRG422`) on every device, whose Vulkan formats are viewed only through a sampler
/// Y′CbCr conversion: its texels' bytes lie in an `R8G8_UNORM` carrier, and its twin holds
/// its texels as 8-bit codes, decoded in whole rows: the device's own conversion of its
/// pairs where it converts the format with Metal's reconstruction
/// (`decoded-texel-precision`; every decode then a GPU pass, its CPU copies through
/// submissions), else Metal's texels, exact.
CarriedDecodedTwin = "carried-decoded-twin", Performance,
"a carrier image of its blocks, at most about 1 byte a texel (a 4:2:2 texture's 2), \
and a decoded twin of 4 bytes a texel (R8G8B8A8; an EAC 11-bit texture's \
@@ -1720,11 +1725,21 @@ degradations! {
/// It reads an EAC 11-bit channel as `c / 2047` (signed `c / 1023`), which the twin holds
/// as the nearest 16-bit normalized code (at most half a 16-bit step off). (An ASTC sRGB
/// texture's twin holds Metal's own 8-bit codes, which its slots read through the twin's
/// sRGB view, the device's decode: `srgb-texel-decode`.)
/// sRGB view, the device's decode: `srgb-texel-decode`.) And a 4:2:2 texture's twin where
/// the device converts its format with Metal's reconstruction (`ycbcr_device.rs`): it
/// holds the device's own sampler Y′CbCr conversion of the pairs (the identity model, the
/// chroma at the midpoint through a linear filter: 3 parts the texel's pair and 1 the pair
/// beside it, Metal's weights, at the device's precision), each channel as the nearest
/// 8-bit code with ties to even, where Metal's `(3 c + n + 2) >> 2` rounds its ties up:
/// within a code of Metal's where the device's sum is within half a code of the exact one
/// (MoltenVK 1.4.2 samples through Metal's own `GBGR422` and `BGRG422` texture unit).
/// Announced where such a texture is made.
DecodedTexelPrecision = "decoded-texel-precision", Precision,
"a read, sample or gather of its texels answers the nearest 8-bit code to Metal's \
12-bit value, at most 1/510 off it; an EAC 11-bit texture's, the nearest 16-bit \
normalized code to Metal's 11-bit value, at most half a 16-bit step off it";
normalized code to Metal's 11-bit value, at most half a 16-bit step off it; a 4:2:2 \
texture's, where the device converts its format, the nearest 8-bit code to the \
device's own Y′CbCr conversion of its pairs, not Metal's decode";
/// A command queue made for presenting
/// ([`Device::new_command_queue_for_presenting`](crate::Device::new_command_queue_for_presenting))
/// on a device that reserved no `VkQueue` for presenting: its queue family has no queue
@@ -437,6 +437,13 @@ pub(super) struct Affected {
/// wherever the word's low bits put it below the code's value. Measured on 26.0.8 (LLVM
/// 21.1.8): known broken through 26.0.8. Nothing is refused: a 10-bit two-plane texture converts
/// through Metal's arithmetic there (`ycbcr_device.rs`).
/// - Mesa's RADV (`MESA_RADV`): the same read. A bare Vulkan probe of a linear
/// `G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16` image on a Radeon 780M read luma code 1023 (low
/// bits 0) as 0.999039 through the identity model. Measured on 26.2.4 (linear tiling; the
/// optimal tiling's conversion of the format was not measured): known broken through 26.2.4.
/// Nothing is refused: a 10-bit two-plane texture converts through Metal's arithmetic there, and
/// its planes read in place through the texel buffer (`ycbcr_device.rs`,
/// `texture/ycbcr_planes.rs`).
pub(super) const AFFECTED: &[Affected] = &[
Affected {
defect: RuntimeDriverDefect::HostTransferImagesCopiedAtBind,
@@ -565,6 +572,11 @@ pub(super) const AFFECTED: &[Affected] = &[
driver: DriverId::MESA_LLVMPIPE,
clean: &[],
},
Affected {
defect: RuntimeDriverDefect::TenBitCodesReadAsWords,
driver: DriverId::MESA_RADV,
clean: &[],
},
];
/// The defects of the driver and device `description` names, its GPU read by the `deviceID` it
@@ -149,6 +149,11 @@ pub(super) enum OwnedModule {
/// conversion's sampler, made with the first kernel of it and released with the device
/// (`ycbcr_device.rs`). One per sampler and output a texture of the device reads through.
YCbCrSample(YCbCrSampler, YCbCrCodes),
/// `bind::chroma_sample_module`: a 4:2:2 texture's pairs' image sampled through the device's
/// own Y′CbCr conversion into a band of its decoded twin's texels
/// (`texture/decoded_twin.rs`); its layout bakes the conversion's sampler, as
/// [`YCbCrSample`](Self::YCbCrSample)'s does. One per sampler (a format, two at most).
ChromaSample(YCbCrSampler),
/// `bind::ycbcr_refresh_module`: a YCbCr texture's planes compared with the copy its last
/// conversion read, the changed words stored over it, and the conversion's indirect group
/// count written where any changed (`ycbcr.rs`).
@@ -192,8 +197,8 @@ impl OwnedModule {
OwnedModule::MipmapFilter(kernel) => u32::from(kernel.fetches()),
OwnedModule::ShadowCopyBack(_) | OwnedModule::ShadowMergeImage(_) => 1,
OwnedModule::ShadowMergeKeptImage(_) => 2,
// The combined image sampler of the planes' image.
OwnedModule::YCbCrSample(..) => 1,
// The combined image sampler of the planes' (or pairs') image.
OwnedModule::YCbCrSample(..) | OwnedModule::ChromaSample(_) => 1,
_ => 0,
}
}
@@ -409,6 +414,11 @@ impl OwnedModule {
let push_bytes = metal2vulkan::bind::YCbCrSampleModule::PUSH_BYTES;
Ok((module.spirv.to_vec(), 0, push_bytes))
}
OwnedModule::ChromaSample(_) => {
let module = metal2vulkan::bind::chroma_sample_module(device.compile_device())
.map_err(Error::Compile)?;
Ok((module.spirv.to_vec(), 2, 0))
}
OwnedModule::RotateTexels => {
let module = metal2vulkan::bind::rotate_texels_module(device.compile_device())
.map_err(Error::Compile)?;
@@ -544,8 +554,10 @@ pub(super) struct OwnedKernels {
ycbcr_refresh: Option<OwnedKernel>,
ycbcr_converts: HashMap<(YCbCrConversion, bool), OwnedKernel>,
ycbcr_samples: HashMap<(YCbCrSampler, YCbCrCodes), OwnedKernel>,
/// The conversions and samplers the YCbCr sample kernels' layouts bake, made with the first
/// kernel of each and released with the device.
chroma_samples: HashMap<YCbCrSampler, OwnedKernel>,
/// The conversions and samplers the YCbCr and 4:2:2 sample kernels' layouts bake, made with
/// the first kernel of each (or the first planes image or layout of a planes sampler,
/// [`Device::made_ycbcr_conversion`]) and released with the device.
ycbcr_samplers: HashMap<YCbCrSampler, (vk::SamplerYcbcrConversion, vk::Sampler)>,
two_plane_texels: Option<OwnedKernel>,
plane_bytes_copy: Option<OwnedKernel>,
@@ -602,6 +614,7 @@ impl OwnedKernels {
.chain(self.index_rewrite_runs.values().copied())
.chain(self.ycbcr_converts.values().copied())
.chain(self.ycbcr_samples.values().copied())
.chain(self.chroma_samples.values().copied())
.chain(self.extended_shadow_loads.values().copied())
.chain(self.twin_decodes.values().copied())
.chain(self.tessellation_scans.values().copied())
@@ -652,6 +665,7 @@ impl OwnedKernels {
OwnedModule::YCbCrSample(sampler, codes) => {
self.ycbcr_samples.get(&(sampler, codes)).copied()
}
OwnedModule::ChromaSample(sampler) => self.chroma_samples.get(&sampler).copied(),
OwnedModule::ExtendedShadowLoad(form) => self.extended_shadow_loads.get(&form).copied(),
OwnedModule::TwinDecode(decode) => self.twin_decodes.get(&decode).copied(),
OwnedModule::TessellationScan(kernel) => self.tessellation_scans.get(&kernel).copied(),
@@ -689,6 +703,9 @@ impl OwnedKernels {
OwnedModule::YCbCrSample(sampler, codes) => {
self.ycbcr_samples.insert((sampler, codes), kernel);
}
OwnedModule::ChromaSample(sampler) => {
self.chroma_samples.insert(sampler, kernel);
}
OwnedModule::ExtendedShadowLoad(form) => {
self.extended_shadow_loads.insert(form, kernel);
}
@@ -739,6 +756,7 @@ impl OwnedKernels {
| OwnedModule::IndexRewriteRun(_)
| OwnedModule::YCbCrConvert(..)
| OwnedModule::YCbCrSample(..)
| OwnedModule::ChromaSample(_)
| OwnedModule::ExtendedShadowLoad(_)
| OwnedModule::TwinDecode(_)
| OwnedModule::TessellationScan(_) => return None,
@@ -781,6 +799,20 @@ impl Device {
made.map(|&(conversion, _)| conversion)
}
/// The device's Y′CbCr conversion of `sampler` ([`OwnedKernels::ycbcr_sampler`]), made on
/// first use: a planes image's view (`texture/ycbcr_planes.rs`) and every immutable sampler
/// of it a pipeline's layout bakes (`pipeline/objects.rs`'s `sampler_set`) are made with this
/// one conversion, so each sampler's `VkSamplerYcbcrConversionInfo` is identically defined to
/// the view's (`VUID-VkWriteDescriptorSet-descriptorType-02738`).
pub(super) fn made_ycbcr_conversion(
&self,
sampler: YCbCrSampler,
) -> Result<vk::SamplerYcbcrConversion, Error> {
let mut kernels = lock(&self.shared().owned_kernels);
let (conversion, _) = kernels.ycbcr_sampler(self, sampler)?;
Ok(conversion)
}
/// The kernel of `which`, made on first use.
pub(super) fn owned_kernel(&self, which: OwnedModule) -> Result<OwnedKernel, Error> {
// A making's turn before the lock (`budget::helper_turn`): none where it is made.
@@ -794,7 +826,7 @@ impl Device {
let (spirv, buffers, push_bytes) = which.build(self)?;
let bindings = (which.images(), which.storage_images(), buffers);
let baked = match which {
OwnedModule::YCbCrSample(sampler, ..) => {
OwnedModule::YCbCrSample(sampler, ..) | OwnedModule::ChromaSample(sampler) => {
let (_, made) = kernels.ycbcr_sampler(self, sampler)?;
Some((made, sampler.descriptors))
}
@@ -30,6 +30,7 @@ use crate::generated_commands::INDIRECT_BINDABLE;
use crate::heap_sets::{self, HeapSet};
use crate::release;
use crate::shader_cache::driver::Making;
use crate::ycbcr_device::YCbCrSampler;
use crate::Device;
use ash::vk;
use metal2vulkan::bind::{DispatchRegion, DynamicViewsModule};
@@ -125,6 +126,22 @@ pub(crate) fn sampler_set(
return Ok((Arc::new(empty), false));
}
let shared = device.shared();
// The device's Y′CbCr conversion of each sampler of a planes image (`texture/ycbcr_planes.rs`),
// the one its view is made with, so the two are identically defined: made before the sets'
// lock, as it takes the owned kernels' own.
let conversions = descs
.iter()
.map(|desc| {
desc.ycbcr
.map(|sampler| {
let ycbcr = YCbCrSampler::planes(device, sampler).ok_or_else(|| {
internal("a layout bakes a planes sampler the device does not convert")
})?;
device.made_ycbcr_conversion(ycbcr)
})
.transpose()
})
.collect::<Result<Vec<_>, Error>>()?;
let program = program_call();
// The lock is held across the creation, so two of the program's calls never make two sets of
// the same samplers.
@@ -133,11 +150,16 @@ pub(crate) fn sampler_set(
let mut set = SamplerSet {
samplers: Vec::with_capacity(descs.len()),
};
for desc in &descs {
for (desc, conversion) in descs.iter().zip(&conversions) {
let mut chained = vk::SamplerYcbcrConversionInfo::default();
let mut reduction = vk::SamplerReductionModeCreateInfo::default();
let mut border = vk::SamplerBorderColorComponentMappingCreateInfoEXT::default();
let info =
let mut info =
metal2vulkan::ash_interop::sampler_create_info(desc, &mut reduction, &mut border);
if let Some(conversion) = *conversion {
chained = chained.conversion(conversion);
info = info.push_next(&mut chained);
}
// SAFETY: `info` and its chain are live for the call. Counted against the device's
// limit (`DeviceShared::create_sampler`).
match unsafe { shared.create_sampler(&info) } {
@@ -570,7 +592,7 @@ impl VariantObjects {
) -> Result<VariantObjects, Error> {
let push_set_zero = pushes_set_zero(device, layout, stages, pipeline);
let dynamic = dynamic_bindings(device, layout, push_set_zero);
let set_needs = needs_of(layout, push_set_zero, &dynamic)?;
let set_needs = needs_of(device, layout, push_set_zero, &dynamic)?;
// One sampler per binding that bakes one, in the layout's order: the live set of the same
// samplers where it holds one, else one made now (`sampler_set`).
let descs: Vec<metal2vulkan::vk::SamplerDesc> = layout
@@ -658,7 +680,7 @@ impl VariantObjects {
) -> Result<(VariantObjects, Vec<(Place, RawPipeline)>), Error> {
let push_set_zero = pushes_set_zero(device, layout, stages, pipeline);
let dynamic = dynamic_bindings(device, layout, push_set_zero);
let set_needs = needs_of(layout, push_set_zero, &dynamic)?;
let set_needs = needs_of(device, layout, push_set_zero, &dynamic)?;
let shared = device.shared();
let back = lock(&shared.kept).take(shared, compiled);
// The kept variants' queue applied (an evicted instance's modules let go): the device's
@@ -1261,6 +1283,7 @@ fn set_zero_shape(layout: &PipelineLayout, push_set_zero: bool, dynamic: &[u32])
/// where it is pushed (`push_set_zero`), and set 0's bindings numbered in `dynamic` of their
/// dynamic types.
fn needs_of(
device: &Device,
layout: &PipelineLayout,
push_set_zero: bool,
dynamic: &[u32],
@@ -1274,7 +1297,9 @@ fn needs_of(
counts: Vec::new(),
flags: vk::DescriptorPoolCreateFlags::empty(),
}),
(false, 0) => needs_typed(set, dynamic),
(false, 0) => needs_typed(set, dynamic, |sampler| {
device.shared().ycbcr_formats.planes_descriptors(sampler)
}),
_ => set_needs(set),
})
.collect()
@@ -1575,11 +1600,18 @@ fn immutable_pushes(
/// descriptor type, since a set takes every binding's whole count; and `UPDATE_AFTER_BIND` when
/// the set layout is `UPDATE_AFTER_BIND_POOL`.
pub(crate) fn set_needs(set: &DescriptorSetLayout) -> Result<SetNeeds, Error> {
needs_typed(set, &[])
needs_typed(set, &[], |_| 1)
}
/// [`set_needs`] of `set` with its bindings numbered in `dynamic` of their dynamic types.
fn needs_typed(set: &DescriptorSetLayout, dynamic: &[u32]) -> Result<SetNeeds, Error> {
/// [`set_needs`] of `set` with its bindings numbered in `dynamic` of their dynamic types, a
/// combined image sampler binding whose immutable sampler is a planes image's Y′CbCr conversion
/// (`SamplerDesc::ycbcr`) taking `planes` of its sampler descriptors for each of its count
/// (`combinedImageSamplerDescriptorCount`, `ycbcr_device.rs`).
fn needs_typed(
set: &DescriptorSetLayout,
dynamic: &[u32],
planes: impl Fn(metal2vulkan::bind::YCbCrPlanesSampler) -> u32,
) -> Result<SetNeeds, Error> {
let mut counts: std::collections::BTreeMap<i32, u32> = std::collections::BTreeMap::new();
let mut flags = vk::DescriptorPoolCreateFlags::empty();
let set_flags: vk::DescriptorSetLayoutCreateFlags = set.flags.into();
@@ -1592,9 +1624,15 @@ fn needs_typed(set: &DescriptorSetLayout, dynamic: &[u32]) -> Result<SetNeeds, E
true => crate::binding::dynamic_type(ty),
false => ty,
};
let each = match binding.immutable_sampler.and_then(|desc| desc.ycbcr) {
Some(sampler) => planes(sampler),
None => 1,
};
let count = counts.entry(ty.as_raw()).or_default();
*count = count
.checked_add(binding.count)
*count = binding
.count
.checked_mul(each)
.and_then(|taken| count.checked_add(taken))
.ok_or_else(|| internal("the layout's descriptor count overflows"))?;
}
Ok(SetNeeds {
@@ -45,7 +45,8 @@ const TEN_BIT_WORDS: RuntimeDriverDefect = RuntimeDriverDefect::TenBitCodesReadA
/// colour copies, the depth/stencil resolve of the first layer and level, the explicit plane's
/// rows past its height, the baked samplers lost after a copy and the 10-bit codes its Y′CbCr
/// conversion reads as words;
/// RADV the multisampled copies that convert float NaNs, and the implicit
/// RADV the multisampled copies that convert float NaNs, the 10-bit codes its Y′CbCr conversion
/// reads as words, and the implicit
/// preprocessing after an execution set on every GPU but the 780M (Phoenix's and Hawk Point's),
/// measured clean; ANV
/// the compressed image's short size, the occlusion count per color output and the pushed
@@ -88,9 +89,9 @@ fn the_committed_profiles_drivers_have_their_defects() {
}
// The 780M, under Phoenix's `deviceID` and Hawk Point's.
Some(DriverId::MESA_RADV) if matches!(desc.device_id, 0x15bf | 0x1900) => {
vec![NAN_COPIES]
vec![NAN_COPIES, TEN_BIT_WORDS]
}
Some(DriverId::MESA_RADV) => vec![NAN_COPIES, PREPROCESS],
Some(DriverId::MESA_RADV) => vec![NAN_COPIES, PREPROCESS, TEN_BIT_WORDS],
Some(DriverId::INTEL_OPEN_SOURCE_MESA) => vec![COMPRESSION, COUNTS, STALE_PUSHES],
Some(DriverId::NVIDIA_PROPRIETARY) if desc.device_id == 0x2c19 => Vec::new(),
Some(DriverId::NVIDIA_PROPRIETARY) => vec![STENCIL_COPIES],
@@ -183,12 +184,12 @@ fn hawk_points_780m_is_phoenixs_gpu() {
assert_eq!(properties.driver_defects, measured.driver_defects);
assert_eq!(
of(&hawk_point).into_iter().collect::<Vec<_>>(),
[NAN_COPIES]
[NAN_COPIES, TEN_BIT_WORDS]
);
hawk_point.driver_version += 1;
assert_eq!(
of(&hawk_point).into_iter().collect::<Vec<_>>(),
[NAN_COPIES]
[NAN_COPIES, TEN_BIT_WORDS]
);
let mut neighbour = phoenix;
neighbour.device_id = 0x1901;
@@ -12,16 +12,25 @@
//! (`ycbcr-filter-not-exact`). Its distance from Metal's reads (`metal2vulkan::bind::ycbcr_read`
//! after Metal's chroma filter) is printed, the note's measured bound. Everywhere else every
//! texel is Metal's read exactly, and nothing is counted or announced.
//!
//! A 4:2:2 texture (`GBGR422`, `BGRG422`) likewise: where the device converts its pairs' format
//! (`YCbCrSampler::pairs`), its decoded twin holds the device's conversion of the pairs, each
//! channel the nearest code to Vulkan's midpoint reconstruction through a linear chroma filter
//! (`3 c + n` over 4 of the texel's pair `c` and the pair beside it `n`), counted
//! (`WorkCounts::chroma_device_twins`, `chroma_device_decodes`) and announced
//! (`decoded-texel-precision`); elsewhere it holds Metal's decode exactly.
use super::blit_holds::{Scratch, WAIT};
use crate::shadow::ShadowSource;
use crate::ycbcr_device::YCbCrSampler;
use crate::{
Buffer, ComputePipelineState, Degradation, DegradeNotice, Device, DeviceKind, DeviceOptions,
IoSurfacePlane, IoSurfaceYCbCr, MessageSink, PipelineOptions, ResourceOptions,
IoSurfacePlane, IoSurfaceYCbCr, MessageSink, PipelineOptions, Region, ResourceOptions,
ShaderCacheOptions, Size, SurfaceYCbCrMatrix, Texture, TextureDescriptor,
};
use metal2vulkan::bind::{ycbcr_read, YCbCrCodes, YCbCrMatrix, YCbCrOutput, YCbCrRange};
use metal2vulkan::bind::{
ycbcr_read, ChromaDecode, YCbCrCodes, YCbCrMatrix, YCbCrOutput, YCbCrRange,
};
use metal2vulkan::error::RuntimeDriverDefect;
use metal2vulkan::metal::format::{ycbcr_format, ChromaSubsampling};
use metal2vulkan::metal::{PixelFormat, TextureUsage};
@@ -96,7 +105,12 @@ fn device(cache: &Path, heard: &Heard) -> Device {
heard.lock().unwrap().push(notice.clone());
}
})),
announce_each: [Degradation::YCbCrFilterNotExact].into_iter().collect(),
announce_each: [
Degradation::YCbCrFilterNotExact,
Degradation::DecodedTexelPrecision,
]
.into_iter()
.collect(),
..DeviceOptions::default()
};
Device::system_default_with(&options).unwrap()
@@ -560,3 +574,150 @@ fn a_ycbcr_texture_reads_the_devices_conversion_where_it_converts_the_format() {
}
println!("{taken} textures took the device's conversion");
}
/// The largest distance of a 4:2:2 twin's chroma channel, in codes, from Vulkan's
/// reconstruction `(3 c + n) / 4` the device's conversion may take: half a code (the twin holds
/// the nearest code) and a quarter for the device's precision.
const PAIRS_BOUND: f64 = 0.75;
/// Every texel `state` reads of a 4:2:2 `texture` of `w x h`, `[r, g, b]` in rows.
fn read_pairs(
device: &Device,
state: &ComputePipelineState,
texture: &Texture,
(w, h): (u64, u64),
) -> Vec<[f32; 3]> {
let case = Case {
pf: PixelFormat::YCBCR84222P,
ostype: b"422v",
size: [w, h],
matrix: None,
};
read(device, state, &case, texture)
}
/// Each 4:2:2 texture whose format the device converts holds the device's conversion of its pairs
/// in its twin at every texel: its green its own code, its red and blue within [`PAIRS_BOUND`] of
/// Vulkan's midpoint reconstruction, counted and announced; every other reads Metal's decode
/// exactly, unannounced. The texture is written on the CPU, whole and in part of two rows.
#[test]
fn a_four_two_two_twin_holds_the_devices_conversion_where_it_converts_the_format() {
let scratch = Scratch::new("ycbcr-device-pairs");
let heard: Heard = Arc::default();
let device = device(&scratch.0, &heard);
let state = read_state(&device);
let (w, h) = (40u64, 24u64);
let mut taken = 0;
for (k, pf) in [PixelFormat::GBGR422, PixelFormat::BGRG422]
.into_iter()
.enumerate()
{
let decode = ChromaDecode::of(pf).unwrap();
let form = YCbCrSampler::pairs(&device, decode, [w as u32, h as u32]);
heard.lock().unwrap().clear();
let before = device.work_counts();
let mut descriptor = TextureDescriptor::texture_2d(pf, w, h, false);
descriptor.usage = TextureUsage::SHADER_READ;
descriptor.resource_options = ResourceOptions::shared();
let texture = device.new_texture(&descriptor).unwrap();
let mut random = 0x422_u64 + k as u64;
let mut bytes: Vec<u8> = (0..2 * w * h)
.map(|_| {
random = random
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
(random >> 56) as u8
})
.collect();
texture
.replace_region(Region::new_2d(0, 0, w, h), 0, 0, &bytes, 2 * w, 0)
.unwrap();
// 6 texels from x 3 on rows 5 and 6: their pairs' red and blue change beside them.
let patch: Vec<u8> = (0..24u32).map(|i| (i * 37 + 11) as u8).collect();
texture
.replace_region(Region::new_2d(3, 5, 6, 2), 0, 0, &patch, 12, 0)
.unwrap();
for row in 0..2u64 {
let at = ((5 + row) * 2 * w + 2 * 3) as usize;
bytes[at..at + 12].copy_from_slice(&patch[12 * row as usize..][..12]);
}
let texels = read_pairs(&device, &state, &texture, (w, h));
let after = device.work_counts();
let metal = decode.decode(&bytes, [w as u32, h as u32, 1]);
let pair =
|x: u64, y: u64, byte: u64| f64::from(bytes[(y * 2 * w + (x / 2) * 4 + byte) as usize]);
let (red, blue) = match decode {
ChromaDecode::Gbgr => (3, 1),
_ => (2, 0),
};
let (mut far, mut off_metal) = (0.0f64, 0);
for y in 0..h {
for x in 0..w {
let got = texels[(y * w + x) as usize].map(|v| f64::from(v) * 255.0);
let want = &metal[((y * w + x) * 4) as usize..][..4];
match form {
Some(_) => {
assert!(
(got[1] - f64::from(want[1])).abs() < 1e-3,
"{pf:?} texel ({x}, {y}): green {} against its code {}",
got[1],
want[1]
);
// The pair beside: before an even texel, after an odd one, its own at
// the row's ends.
let beside = match x % 2 {
0 => x.saturating_sub(2),
_ => (x + 2).min(w - 1),
};
for (c, byte) in [(0, red), (2, blue)] {
let spec = (3.0 * pair(x, y, byte) + pair(beside, y, byte)) / 4.0;
far = far.max((got[c] - spec).abs());
off_metal += usize::from((got[c] - f64::from(want[c])).abs() > 1e-3);
}
}
None => {
for c in 0..3 {
assert!(
(got[c] - f64::from(want[c])).abs() < 1e-3,
"{pf:?} texel ({x}, {y}) channel {c}: {} against Metal's {}",
got[c],
want[c]
);
}
}
}
}
}
let twins = after.chroma_device_twins - before.chroma_device_twins;
let decodes = after.chroma_device_decodes - before.chroma_device_decodes;
let announced = heard
.lock()
.unwrap()
.iter()
.filter(|notice| notice.degradation == Degradation::DecodedTexelPrecision)
.count();
match form {
Some(_) => {
taken += 1;
println!(
"{pf:?} {w}x{h}: chroma within {far:.4} codes of Vulkan's; {off_metal} of {} \
chroma channels a code off Metal's",
2 * w * h
);
assert!(far <= PAIRS_BOUND, "{pf:?}: {far} codes from Vulkan's");
assert_eq!(twins, 1, "{pf:?}: counted");
assert!(decodes >= 2, "{pf:?}: each write a pass, {decodes}");
assert_eq!(
after.cpu_block_decodes, before.cpu_block_decodes,
"{pf:?}: no CPU decode"
);
assert_eq!(announced, 1, "{pf:?}: announced");
}
None => {
assert_eq!((twins, decodes), (0, 0), "{pf:?}: Metal's decode");
assert_eq!(announced, 0, "{pf:?}: exact, unannounced");
}
}
}
println!("{taken} 4:2:2 textures took the device's conversion");
}
+6 -1
View File
@@ -180,7 +180,9 @@ mod usage_shadow;
mod view_shadow;
pub(super) mod wrapped;
mod ycbcr_image;
mod ycbcr_planes;
pub(crate) use ycbcr_image::{KeptImage, PlanesInPlace};
pub(crate) use ycbcr_planes::KeptTexels;
pub(crate) use attached_reads::feedback_candidate;
pub use shared::SharedTextureHandle;
@@ -4578,7 +4580,10 @@ impl Texture {
let mut facts = texture_facts(&record);
facts.sparse = self.is_sparse();
// A two-plane YCbCr texture whose planes a function may read in place.
facts.ycbcr_in_place = self.0.planes_in_place.map(|p| p.words);
facts.ycbcr_in_place = self.0.planes_in_place.as_ref().map(|p| match p.image {
Some(_) => p.words.with_planes_image(),
None => p.words,
});
facts
}
@@ -89,6 +89,16 @@
//! write of part of a row decodes its rows as the carrier then holds them, read back first). A new
//! one's zero pairs read opaque black: the twin starts cleared to it.
//!
//! **4:2:2 through the device's own conversion.** Where the device converts the pairs' format
//! itself with Metal's reconstruction (`ycbcr_device.rs`, [`YCbCrSampler::pairs`]), the twin holds
//! the device's conversion of the pairs instead (announced `decoded-texel-precision`; counted
//! `WorkCounts::chroma_device_twins`): each decode pass's band, its pairs copied out of the
//! carrier into the scratch, is copied into the texture's pairs' image ([`PairsSampling`]) and
//! sampled through the conversion into the band's texels (`bind::chroma_sample_module`), which are
//! copied into the twin. Every write's decode is such a pass: the carrier's CPU copies go through
//! submissions there (no host or staging copies), each followed by its pass, so no texel of the
//! twin is the CPU's (Metal's) decode.
//!
//! **Cost**, announced once per device (`carried-decoded-twin`, performance): the carrier and the
//! twin's memory, and a decode pass after each write. A `VkImage` handed out (`Texture::vk_image`)
//! is the carrier: what the caller writes into it outside the runtime's calls leaves the twin as
@@ -108,7 +118,7 @@ use super::super::error::{internal, Error};
use super::super::etc;
use super::super::exit_guard::{self, Call};
use super::super::image_plan::ImagePlan;
use super::super::owned_kernel::{OwnedModule, OwnedSets};
use super::super::owned_kernel::{OwnedModule, OwnedSet, OwnedSets};
use super::super::pvrtc;
use super::super::resource::Identity;
use super::super::resource::ResourceKey;
@@ -116,6 +126,7 @@ use super::super::texture_descriptor::{TextureDescriptor, TextureLayout};
use super::super::tracker::{Access, Barrier, Use, UseRange};
use super::super::trails::Trail;
use super::super::values::{HazardTrackingMode, ResourceOptions};
use super::super::ycbcr_device::{PairsSampling, YCbCrSampler};
use super::super::{Buffer, Device};
use super::first_move::{FirstMove, Pattern, Patterned, TexelCopy};
use super::twin_decode::{self, Job};
@@ -313,6 +324,9 @@ pub(super) struct Decoded {
/// The layout and descriptor of the texture it was made for, by which an ASTC carrier's
/// second twin is made ([`Image::make_second_twin`]).
made_for: (TextureLayout, TextureDescriptor),
/// A 4:2:2 twin's pairs' image, where it holds the device's own conversion of its pairs (the
/// module docs); `None` where it holds Metal's decode.
pairs: Option<PairsSampling>,
}
impl Decoded {
@@ -507,6 +521,22 @@ impl Device {
self.degrade_block_decode(layout);
return Ok(image);
};
// A 4:2:2 twin holds the device's own conversion of the pairs where it converts their
// format with Metal's reconstruction (the module docs). Every decode is then a GPU pass:
// the carrier's CPU copies go through submissions, each followed by its pass.
let pairs = match decode {
TwinDecode::Chroma(chroma) => {
let [width, height, _] = layout.extent;
YCbCrSampler::pairs(self, chroma, [width, height])
.map(|sampler| PairsSampling::new(self, sampler, [width, height]))
.transpose()?
}
_ => None,
};
if pairs.is_some() {
image.host_copies = false;
image.staging_copies = false;
}
// A twin starts, and takes the CPU's decodes, as the carrier's CPU copies go: on the
// host or the staging queue where they do (then made as a `Shared` or `Managed`
// texture's image is), else through submissions.
@@ -570,6 +600,7 @@ impl Device {
decode,
started_on_the_cpu: routed && fresh,
made_for: (*layout, *descriptor),
pairs,
};
self.degrade_carried_twin(layout, &decoded, placed(&image));
image.decoded = Some(Box::new(decoded));
@@ -594,8 +625,15 @@ impl Device {
let placed =
|bytes: Option<u64>| bytes.map_or_else(String::new, |n| format!(", {n} placed"));
let held = match decoded.decode {
TwinDecode::Chroma(_) => "Vulkan's 4:2:2 formats reconstruct chroma by the \
implementation's rules"
TwinDecode::Chroma(_) if decoded.pairs.is_some() => {
"Vulkan views a 4:2:2 format only through a sampler Y′CbCr conversion, which \
no pipeline's layout bakes, so its twin holds the device's conversion of its \
pairs"
.to_owned()
}
TwinDecode::Chroma(_) => "the device does not convert its 4:2:2 format with \
Metal's reconstruction (its chroma at the midpoint \
through a linear filter)"
.to_owned(),
_ => format!("the device has no {:?} format", layout.pixel_format),
};
@@ -610,6 +648,12 @@ impl Device {
(object(), why)
});
let why = match decoded.decode {
TwinDecode::Chroma(_) if decoded.pairs.is_some() => {
"its decoded twin holds the device's own Y′CbCr conversion of its pairs (Vulkan's \
midpoint reconstruction through a linear chroma filter, at the device's \
precision), each channel as the nearest 8-bit code with ties to even, where \
Metal's 3:1 sum of the codes rounds its ties up"
}
TwinDecode::Astc(decode, AstcTexels::Unorm8) if !decode.srgb => {
"its decoded twin holds each channel as the 8-bit code nearest Metal's 12-bit \
value, at most 1/510 off it"
@@ -1184,10 +1228,17 @@ impl Image {
let [w, h, _] = r.size.map(u64::from);
(w * h * u64::from(r.size[2]) * u64::from(r.layers) * texel).next_multiple_of(4)
};
let plans: Vec<BandPlan> = steps
let mut plans: Vec<BandPlan> = steps
.iter()
.map(|step| self.band_plan(decode, step))
.collect();
// A 4:2:2 twin of the device's conversion: each band's rows sampled out of the pairs'
// image (the module docs), its own shape and workgroups.
if let Some(pairs) = &decoded.pairs {
for (plan, step) in plans.iter_mut().zip(&steps) {
(plan.shape, plan.groups) = pairs.step(step.origin[1], step.size[1]);
}
}
// Each step's blocks at the scratch's start and its texels at the alignment after them:
// at most `most` bytes together (`bands`), so within `most` and the alignment.
let layouts: Vec<(u64, u64, u64)> = (steps.iter().zip(&plans))
@@ -1235,18 +1286,42 @@ impl Image {
std::ptr::copy_nonoverlapping(plan.shape.as_ptr(), to, plan.shape.len());
}
}
let kernel = device.owned_kernel(OwnedModule::TwinDecode(decode))?;
let ranges: Vec<Vec<(vk::Buffer, u64, u64)>> = (layouts.iter())
.zip(0u64..)
.map(|(&(blocks, texels_at, texels), at)| {
vec![
(raw_shapes, shapes_base + at * slot, shape_bytes),
(raw_scratch, base, blocks),
(raw_scratch, base + texels_at, texels),
]
})
.collect();
let sets = OwnedSets::write(device, &kernel, &ranges)?;
let (kernel, sets) = match &decoded.pairs {
None => {
let kernel = device.owned_kernel(OwnedModule::TwinDecode(decode))?;
let ranges: Vec<Vec<(vk::Buffer, u64, u64)>> = (layouts.iter())
.zip(0u64..)
.map(|(&(blocks, texels_at, texels), at)| {
vec![
(raw_shapes, shapes_base + at * slot, shape_bytes),
(raw_scratch, base, blocks),
(raw_scratch, base + texels_at, texels),
]
})
.collect();
(kernel, OwnedSets::write(device, &kernel, &ranges)?)
}
// The pairs' image, then the shape and the texels (`bind::ChromaSampleModule`).
Some(pairs) => {
let owned: Vec<OwnedSet> = (layouts.iter())
.zip(0u64..)
.map(|(&(_, texels_at, texels), at)| OwnedSet {
images: vec![pairs.view],
storage_images: Vec::new(),
buffers: vec![
(raw_shapes, shapes_base + at * slot, shape_bytes),
(raw_scratch, base + texels_at, texels),
],
})
.collect();
let kernels = vec![pairs.kernel; owned.len()];
device.shared().counts.chroma_device_decode();
(
pairs.kernel,
OwnedSets::write_each(device, &kernels, &owned)?,
)
}
};
let steps = steps
.iter()
.zip(&plans)
@@ -1257,6 +1332,12 @@ impl Image {
buffer_offset: base,
..buffer_image_copy(&plan.blocks)
},
// The band's pairs, tight rows of the texture's width out of the scratch, into
// the same rows of the pairs' image.
pairs: decoded.pairs.as_ref().map(|_| vk::BufferImageCopy {
buffer_offset: base,
..buffer_image_copy(&plan.blocks)
}),
texels: vk::BufferImageCopy {
buffer_offset: base + texels_at,
..buffer_image_copy(region)
@@ -1269,6 +1350,10 @@ impl Image {
Ok(Some(DecodePass {
image: self.raw.get(),
twin: decoded.image.raw.get(),
pairs: decoded
.pairs
.as_ref()
.map_or(vk::Image::null(), |pairs| pairs.image),
scratch: raw_scratch,
pipeline: kernel.pipeline,
layout: kernel.layout,
@@ -1335,6 +1420,7 @@ impl Image {
decode,
started_on_the_cpu: false,
made_for: (layout, own),
pairs: None,
};
let mut viewed = layout;
viewed.pixel_format = pf;
@@ -1495,10 +1581,12 @@ struct BandPlan {
groups: [u32; 3],
}
/// One band of a decode pass: its blocks copied out of the image, its set, its workgroups and its
/// texels copied into the twin.
/// One band of a decode pass: its blocks copied out of the image, a 4:2:2 twin's of the device's
/// conversion copied on into the pairs' image, its set, its workgroups and its texels copied into
/// the twin.
struct Step {
blocks: vk::BufferImageCopy,
pairs: Option<vk::BufferImageCopy>,
texels: vk::BufferImageCopy,
set: vk::DescriptorSet,
groups: [u32; 3],
@@ -1628,6 +1716,8 @@ pub(crate) enum PassScratch {
pub(crate) struct DecodePass {
image: vk::Image,
twin: vk::Image,
/// A 4:2:2 twin's pairs' image, where it holds the device's conversion; null elsewhere.
pairs: vk::Image,
scratch: vk::Buffer,
pipeline: vk::Pipeline,
layout: vk::PipelineLayout,
@@ -1659,6 +1749,38 @@ impl DecodePass {
let blocks = std::slice::from_ref(&step.blocks);
device.cmd_copy_image_to_buffer(raw, self.image, general, self.scratch, blocks);
Barrier::everything().record(device, raw);
if let Some(pairs) = &step.pairs {
// The pairs' image's earlier texels dropped (a step samples only the rows
// it copies), the band's pairs copied in, then sampled.
let whole = vk::ImageSubresourceRange {
aspect_mask: vk::ImageAspectFlags::COLOR,
base_mip_level: 0,
level_count: 1,
base_array_layer: 0,
layer_count: 1,
};
let into = vk::ImageMemoryBarrier::default()
.src_access_mask(vk::AccessFlags::SHADER_READ)
.dst_access_mask(vk::AccessFlags::TRANSFER_WRITE)
.old_layout(vk::ImageLayout::UNDEFINED)
.new_layout(general)
.src_queue_family_index(vk::QUEUE_FAMILY_IGNORED)
.dst_queue_family_index(vk::QUEUE_FAMILY_IGNORED)
.image(self.pairs)
.subresource_range(whole);
device.cmd_pipeline_barrier(
raw,
vk::PipelineStageFlags::ALL_COMMANDS,
vk::PipelineStageFlags::TRANSFER,
vk::DependencyFlags::empty(),
&[],
&[],
&[into],
);
let pairs = std::slice::from_ref(pairs);
device.cmd_copy_buffer_to_image(raw, self.scratch, self.pairs, general, pairs);
Barrier::everything().record(device, raw);
}
let set = std::slice::from_ref(&step.set);
device.cmd_bind_descriptor_sets(raw, compute, self.layout, 0, set, &[]);
let [x, y, z] = step.groups;
@@ -671,7 +671,7 @@ fn placed(
/// The memory requirements of `raw`, a live image of the device of `raw_device`, and whether it
/// requires a dedicated allocation.
fn requirements_of(
pub(super) fn requirements_of(
raw_device: &crate::device::functions::Vk,
raw: vk::Image,
) -> (vk::MemoryRequirements, bool) {
@@ -16,8 +16,13 @@
//! cannot be viewed so, the texture keeps its image alone, counted by the reason
//! (`WorkCounts::ycbcr_images_kept_*`): the device, the layout, a swizzle, the planes' first byte
//! off `minTexelBufferOffsetAlignment`, more elements than `maxTexelBufferElements`, planes past
//! their buffer, or a format the device views no uniform texel buffer of.
//! their buffer, or a format the device views no uniform texel buffer of. Where the device
//! converts the planes' 4:2:0 format as a linear image with Metal's reconstruction, the planes
//! are also an image of it over their bytes (`ycbcr_planes.rs`), which a slot whose every sample
//! the device's sampler takes samples through the device's conversion instead of the texel
//! buffer.
use super::ycbcr_planes::PlanesImage;
use super::{image_error, IdUse, Image, Storage, Texture};
use crate::address_map::AddressModeMap;
use crate::binding_view::VkView;
@@ -138,11 +143,12 @@ fn over_read(read: [TextureSwizzle; 3], swizzle: TextureSwizzleChannels) -> Text
}
/// A two-plane YCbCr texture's planes as a function reads them in place (the module docs): their
/// words, and their first byte in the texels' buffer.
#[derive(Clone, Copy, Debug)]
/// words, their first byte in the texels' buffer, and their image the device's conversion samples
/// where it has one (`ycbcr_planes.rs`).
pub(crate) struct PlanesInPlace {
pub(super) words: YCbCrInPlace,
start: u64,
pub(super) image: Option<Arc<PlanesImage>>,
}
/// Why a two-plane YCbCr texture keeps its image alone, its planes read in place by no function
@@ -221,6 +227,7 @@ impl Device {
Ok(PlanesInPlace {
words,
start: span.start,
image: None,
})
}
@@ -247,12 +254,19 @@ impl Device {
let texels = Arc::new(texels);
let mut record = ViewRecord::of_descriptor(layout, &descriptor);
if !codes_alone(layout.pixel_format, planes) {
let in_place = self.planes_in_place(&texels, &descriptor, (planes, &span));
let mut in_place = self.planes_in_place(&texels, &descriptor, (planes, &span));
let counts = &self.shared().counts;
match &in_place {
Ok(_) => counts.ycbcr_texture_in_place(),
Err(kept) => counts.ycbcr_image_kept(*kept),
}
// Its planes as an image the device's conversion samples, where it has one.
if let Ok(p) = &mut in_place {
match self.planes_image(&texels, (planes, &p.words), p.start)? {
Ok(image) => p.image = Some(image),
Err(kept) => counts.ycbcr_planes_image_kept(kept),
}
}
let storage =
self.converted_storage(call, texels, &descriptor, layout, (planes, span))?;
let made = (storage, in_place.ok());
@@ -389,7 +403,7 @@ impl Texture {
/// The uniform texel buffer view of the texture's planes read in place (the module docs), made
/// at its first bind and kept with the texels. Internal for a texture whose planes are not.
pub(crate) fn planes_view(&self) -> Result<vk::BufferView, Error> {
let (Some(p), Some(texels)) = (self.0.planes_in_place, self.buffer_texels()) else {
let (Some(p), Some(texels)) = (&self.0.planes_in_place, self.buffer_texels()) else {
return Err(internal(
"a planes view of a texture without planes in place",
));
@@ -398,10 +412,28 @@ impl Texture {
texels.view_of(p.words.format(), false, (at, p.words.view_bytes()))
}
/// The view of the texture's planes as an image the device's conversion samples
/// (`ycbcr_planes.rs`), which a slot that samples them through it binds. Internal for a
/// texture whose planes take no such image.
pub(crate) fn planes_image_view(&self) -> Result<vk::ImageView, Error> {
match self
.0
.planes_in_place
.as_ref()
.and_then(|p| p.image.as_ref())
{
Some(image) => Ok(image.view),
None => Err(internal(
"a planes image view of a texture whose planes take no image",
)),
}
}
/// A read by `read` of the bytes of the texture's planes read in place, which a binding of
/// them makes (the module docs). Internal for a texture whose planes are not.
/// them makes, through their texel buffer or their image (the module docs). Internal for a
/// texture whose planes are not.
pub(crate) fn planes_use(&self, read: Access) -> Result<Use<ResourceKey>, Error> {
let (Some(p), Some(texels)) = (self.0.planes_in_place, self.buffer_texels()) else {
let (Some(p), Some(texels)) = (&self.0.planes_in_place, self.buffer_texels()) else {
return Err(internal(
"a planes use of a texture without planes in place",
));
@@ -0,0 +1,271 @@
//! A two-plane YCbCr texture's planes read in place through the device's own sampler Y′CbCr
//! conversion (`ycbcr_image.rs`'s planes in place, `metal2vulkan::bind::YCbCrPlanesSampler`): a
//! linear image of the multi-planar 4:2:0 format bound over the planes' own bytes, which a slot of
//! a function whose every sample the device's sampler takes samples through an immutable sampler
//! of the device's conversion, where the device converts the format with Metal's reconstruction.
//!
//! - **Which.** A texture whose planes a function reads in place (`PlanesInPlace`), on a device
//! whose linear tiling of `G8_B8R8_2PLANE_420_UNORM` (8-bit codes) or
//! `G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16` (10-bit) reports `SAMPLED_IMAGE`,
//! `MIDPOINT_CHROMA_SAMPLES` and a linear chroma filter, with no defect in the format
//! (`RuntimeDriverDefect::TwoPlaneChromaMisplaced`, `TenBitCodesReadAsWords`;
//! `ycbcr_device.rs`), of an even width and height within the format's linear limits, whose
//! luma plane comes first.
//! - **Its memory.** The planes' bytes in memory of the runtime's own that it allocated (a
//! buffer's pooled memory or a heap's): the image starts `PREINITIALIZED`, whose move to
//! `GENERAL` keeps its bytes (the first move, `first_move.rs`). Over fresh pages
//! (`fresh_pages.rs`), a no-copy buffer's pages (imported by their pointer or as dma-bufs) or the
//! caller's `VkBuffer`, none: an image bound to imported memory starts `UNDEFINED`
//! (`VUID-VkImageCreateInfo-pNext-01443`), whose move the device's check covers for
//! single-plane images alone (`in_place_check.rs`), so the texel buffer reads the planes there.
//! - **Its layout** is the driver's: the image is taken where its planes lie at the surface's
//! offsets and row pitches from the luma plane's first byte, at an offset of the memory that
//! meets its alignment, within the buffer, in a memory type it takes; elsewhere the texel buffer
//! reads the planes.
//! - **What a sample answers** is the device's: its conversion of the codes (the surface's matrix
//! and range, Metal's reconstruction) and its filter, announced `ycbcr-filter-not-exact` where
//! the image is made.
//!
//! Each texture whose planes are read in place and take no such image is counted by the reason
//! (`WorkCounts::ycbcr_planes_images_kept_*`).
use super::first_move::{FirstMove, Fresh};
use crate::buffer_texture::Texels;
use crate::creation;
use crate::degradation::Degradation;
use crate::device::lock;
use crate::error::{vulkan, Error};
use crate::exit_guard::{self, Call};
use crate::release;
use crate::resource::ResourceKey;
use crate::ycbcr_device::YCbCrSampler;
use crate::Device;
use ash::vk;
use metal2vulkan::bind::{YCbCrInPlace, YCbCrPlanes, YCbCrPlanesSampler};
use std::sync::{Arc, Mutex};
/// Why a texture whose planes a function reads in place samples them through no image of the
/// device's conversion (the module docs), in `WorkCounts::ycbcr_planes_images_kept_*`'s order.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum KeptTexels {
/// The device does not convert the format with Metal's reconstruction as a linear image of
/// the texture's size.
Conversion,
/// The planes lie in memory no such image is made over: fresh pages, a no-copy buffer's
/// pages, the caller's `VkBuffer`.
Memory,
/// The driver's image lays the planes out otherwise, or does not fit the buffer there.
Layout,
}
impl KeptTexels {
/// The reasons, in their counters' order.
pub(crate) const ALL: [KeptTexels; 3] = [
KeptTexels::Conversion,
KeptTexels::Memory,
KeptTexels::Layout,
];
}
/// The image of a texture's planes the device's conversion samples in place (the module docs):
/// its view, made with the conversion every immutable sampler of its sampler bakes, and its first
/// move until a submission takes it. It holds the texels, and so the memory it is bound to.
pub(crate) struct PlanesImage {
device: Device,
image: vk::Image,
pub(crate) view: vk::ImageView,
_texels: Arc<Texels>,
first: Mutex<Option<FirstMove>>,
}
impl Fresh for PlanesImage {
fn take(&self) -> Vec<FirstMove> {
lock(&self.first).take().into_iter().collect()
}
fn give_back(&self, moves: Vec<FirstMove>) {
let mut first = lock(&self.first);
if first.is_none() {
*first = moves.into_iter().next();
}
}
/// Bound for good: memory of the runtime's own never moves.
fn rebindable(&self) -> Option<ResourceKey> {
None
}
}
impl Drop for PlanesImage {
fn drop(&mut self) {
// Once the process is exiting, the objects are left to its end (`exit_guard`).
let Some(_busy) = exit_guard::enter() else {
return;
};
let raw = self.device.shared().vk();
// SAFETY: no pending command uses them: the commands that bind the view hold the texture,
// and a submission that takes the move holds this image, until they complete.
unsafe {
release::object(raw, self.view);
release::object(raw, self.image);
}
}
}
impl Device {
/// The image of `planes` (read in place as `words`, from byte `start` of `texels`' buffer)
/// that the device's conversion samples (the module docs), or why there is none.
pub(super) fn planes_image(
&self,
texels: &Arc<Texels>,
(planes, words): (&YCbCrPlanes, &YCbCrInPlace),
start: u64,
) -> Result<Result<Arc<PlanesImage>, KeptTexels>, Error> {
let sampler = words.sampler();
let [width, height] = planes.size;
let Some(ycbcr) = YCbCrSampler::planes(self, sampler)
.filter(|ycbcr| ycbcr.holds_planes(self, [width, height]))
else {
return Ok(Err(KeptTexels::Conversion));
};
if texels.buffer.caller_memory().is_some() || texels.buffer.in_fresh_pages() {
return Ok(Err(KeptTexels::Memory));
}
let [luma_at, luma_row] = planes.luma.map(u64::from);
let [chroma_at, chroma_row] = planes.chroma.map(u64::from);
if chroma_at <= luma_at {
return Ok(Err(KeptTexels::Layout));
}
let shared = self.shared();
let raw_device = shared.vk();
let format: vk::Format = sampler.format().into();
let info = shared.sharing().image(
vk::ImageCreateInfo::default()
.image_type(vk::ImageType::TYPE_2D)
.format(format)
.extent(vk::Extent3D {
width,
height,
depth: 1,
})
.mip_levels(1)
.array_layers(1)
.samples(vk::SampleCountFlags::TYPE_1)
.tiling(vk::ImageTiling::LINEAR)
.usage(vk::ImageUsageFlags::SAMPLED)
.initial_layout(vk::ImageLayout::PREINITIALIZED),
);
let limits = self.image_limits(&info, &[])?;
if width > limits.max_extent.width || height > limits.max_extent.height {
return Ok(Err(KeptTexels::Conversion));
}
// SAFETY: the device is live and `info` valid and within its limits.
let image = unsafe { creation::image(raw_device, &info) }?;
let unwind = |image| {
// SAFETY: the image is live, and no command uses it.
unsafe { release::object(raw_device, image) };
};
let (requirements, dedicated) = super::in_place_image::requirements_of(raw_device, image);
let plane = |aspect| vk::ImageSubresource {
aspect_mask: aspect,
mip_level: 0,
array_layer: 0,
};
// SAFETY: `image` is a live linear image of a two-plane format, whose planes are its
// subresources' aspects (`VUID-vkGetImageSubresourceLayout-format-08886`).
let [luma, chroma] = [vk::ImageAspectFlags::PLANE_0, vk::ImageAspectFlags::PLANE_1]
.map(|aspect| unsafe { raw_device.get_image_subresource_layout(image, plane(aspect)) });
exit_guard::called(Call::GetImageSubresourceLayout);
let (memory, buffer_offset, type_index) = texels.buffer.memory();
let at = buffer_offset + start + luma_at;
let room = texels
.buffer
.padded_length()
.saturating_sub(start + luma_at);
let lies = luma.offset == 0
&& luma.row_pitch == luma_row
&& chroma.offset == chroma_at - luma_at
&& chroma.row_pitch == chroma_row;
if dedicated
|| !lies
|| !at.is_multiple_of(requirements.alignment.max(1))
|| requirements.size > room
|| requirements.memory_type_bits & (1 << type_index) == 0
{
unwind(image);
return Ok(Err(KeptTexels::Layout));
}
// SAFETY: the image is live and unbound; the memory is the buffer's, which the image
// holds through the texels, in a type the image takes, at an offset that meets its
// alignment, its size within the buffer.
if let Err(error) = unsafe { creation::bind_image(raw_device, image, memory, at) } {
unwind(image);
return Err(vulkan(error));
}
let conversion = match self.made_ycbcr_conversion(ycbcr) {
Ok(conversion) => conversion,
Err(error) => {
unwind(image);
return Err(error);
}
};
let mut chained = vk::SamplerYcbcrConversionInfo::default().conversion(conversion);
let view_info = vk::ImageViewCreateInfo::default()
.image(image)
.view_type(vk::ImageViewType::TYPE_2D)
.format(format)
.subresource_range(vk::ImageSubresourceRange {
aspect_mask: vk::ImageAspectFlags::COLOR,
base_mip_level: 0,
level_count: 1,
base_array_layer: 0,
layer_count: 1,
})
.push_next(&mut chained);
// SAFETY: the image is live and bound; the conversion is of its format.
let view = match unsafe { creation::image_view(raw_device, &view_info) } {
Ok(view) => view,
Err(error) => {
unwind(image);
return Err(vulkan(error));
}
};
// Leaving `PREINITIALIZED` keeps the bytes the image holds: the planes'. Its colour
// aspect is every plane of the image, which is not disjoint.
let first = FirstMove::new(
image,
sampler.format(),
vk::ImageLayout::PREINITIALIZED,
None,
);
let made = Arc::new(PlanesImage {
device: self.clone(),
image,
view,
_texels: Arc::clone(texels),
first: Mutex::new(Some(first)),
});
let fresh: Arc<dyn Fresh> = made.clone();
shared.textures.first_moves.register(Arc::downgrade(&fresh));
shared.counts.ycbcr_planes_image();
announce(self, sampler);
Ok(Ok(made))
}
}
/// The notice of a planes image of `sampler` (the module docs).
fn announce(device: &Device, sampler: YCbCrPlanesSampler) {
device.degrade(Degradation::YCbCrFilterNotExact, || {
(
"texture".to_owned(),
format!(
"a two-plane YCbCr texture of {}-bit 4:2:0 codes ({:?}, {:?}) whose planes a \
function samples in place reads the device's own sampler Y′CbCr conversion and \
filter of them, not Metal's fixed-point conversion and exact filter",
sampler.bits(),
sampler.range(),
sampler.matrix()
),
)
});
}
@@ -126,6 +126,9 @@ pub(crate) struct Counters {
ycbcr_textures_in_place: AtomicU64,
ycbcr_images_kept: [AtomicU64; 7],
ycbcr_planes_bound: AtomicU64,
ycbcr_planes_images: AtomicU64,
ycbcr_planes_images_kept: [AtomicU64; 3],
ycbcr_planes_images_bound: AtomicU64,
ycbcr_device_conversions: AtomicU64,
ycbcr_device_samples: AtomicU64,
attachment_clears_recorded: AtomicU64,
@@ -208,6 +211,8 @@ pub(crate) struct Counters {
uncached_host_images: AtomicU64,
cpu_block_decodes: AtomicU64,
block_decode_passes: AtomicU64,
chroma_device_twins: AtomicU64,
chroma_device_decodes: AtomicU64,
second_twins: AtomicU64,
second_twin_checks: AtomicU64,
second_twin_decodes: AtomicU64,
@@ -667,6 +672,30 @@ impl Counters {
self.ycbcr_planes_bound.fetch_add(1, Ordering::Relaxed);
}
/// A two-plane YCbCr texture's planes read in place were made an image the device's
/// conversion samples (`texture/ycbcr_planes.rs`).
pub(crate) fn ycbcr_planes_image(&self) {
self.ycbcr_planes_images.fetch_add(1, Ordering::Relaxed);
}
/// A two-plane YCbCr texture's planes read in place were made no image the device's
/// conversion samples, for `kept` (`texture/ycbcr_planes.rs`).
pub(crate) fn ycbcr_planes_image_kept(&self, kept: crate::texture::KeptTexels) {
let at = crate::texture::KeptTexels::ALL
.iter()
.position(|k| *k == kept)
.unwrap_or(0);
if let Some(counter) = self.ycbcr_planes_images_kept.get(at) {
counter.fetch_add(1, Ordering::Relaxed);
}
}
/// A binding of a two-plane YCbCr texture's planes image was written (`binding.rs`).
pub(crate) fn ycbcr_planes_image_bound(&self) {
self.ycbcr_planes_images_bound
.fetch_add(1, Ordering::Relaxed);
}
/// A YCbCr texture's conversion, or a render shadow's load, was made to sample its planes'
/// image through the device's own Y′CbCr conversion (`ycbcr_device.rs`).
pub(crate) fn ycbcr_device_conversion(&self) {
@@ -1481,6 +1510,18 @@ impl Counters {
self.block_decode_passes.fetch_add(1, Ordering::Relaxed);
}
/// A 4:2:2 texture's decoded twin was made to hold the device's own Y′CbCr conversion of its
/// pairs (`ycbcr_device::PairsSampling`).
pub(crate) fn chroma_device_twin(&self) {
self.chroma_device_twins.fetch_add(1, Ordering::Relaxed);
}
/// A GPU decode pass into a 4:2:2 texture's decoded twin through the device's own Y′CbCr
/// conversion was made (`Image::decode_pass`).
pub(crate) fn chroma_device_decode(&self) {
self.chroma_device_decodes.fetch_add(1, Ordering::Relaxed);
}
/// An ASTC carrier's second decoded twin was made (`Image::make_second_twin`).
pub(crate) fn second_twin(&self) {
self.second_twins.fetch_add(1, Ordering::Relaxed);
@@ -3215,6 +3256,24 @@ pub struct WorkCounts {
pub ycbcr_images_kept_view: u64,
/// Bindings of two-plane YCbCr textures' planes read in place written into descriptor sets.
pub ycbcr_planes_bound: u64,
/// Two-plane YCbCr textures whose planes read in place are also an image the device's own
/// sampler Y′CbCr conversion samples, a linear image of the multi-planar 4:2:0 format over
/// their bytes (`texture/ycbcr_planes.rs`): a slot whose every sample the device's sampler
/// takes samples it through the device's conversion.
pub ycbcr_planes_images: u64,
/// Two-plane YCbCr textures whose planes read in place take no such image because the device
/// does not convert the format with Metal's reconstruction as a linear image of their size (no
/// such format features, a driver defect in it, an odd size or one past its limits).
pub ycbcr_planes_images_kept_conversion: u64,
/// Two-plane YCbCr textures whose planes read in place take no such image because the planes
/// lie in memory no such image is made over: fresh pages, a no-copy buffer's pages, the
/// caller's `VkBuffer`.
pub ycbcr_planes_images_kept_memory: u64,
/// Two-plane YCbCr textures whose planes read in place take no such image because the driver's
/// image lays the planes out otherwise than the surface, or does not fit their buffer there.
pub ycbcr_planes_images_kept_layout: u64,
/// Bindings of two-plane YCbCr textures' planes images written into descriptor sets.
pub ycbcr_planes_images_bound: u64,
/// Two-plane YCbCr textures' conversions, and render shadows' loads, made to sample the
/// planes' image through the device's own Y′CbCr conversion where it converts their format
/// (`ycbcr_device.rs`), in place of Metal's arithmetic.
@@ -3767,6 +3826,13 @@ pub struct WorkCounts {
/// a blit's or a copy's into a carried texture, a heap texture's start, a write through
/// submissions. None for a twin that takes CPU copies, whose texels only the CPU decodes.
pub block_decode_passes: u64,
/// 4:2:2 textures' decoded twins made to hold the device's own Y′CbCr conversion of their
/// pairs, where it converts their format with Metal's reconstruction (`ycbcr_device.rs`), in
/// place of Metal's decode: their writes all decode through GPU passes.
pub chroma_device_twins: u64,
/// GPU decode passes into such twins made (among `block_decode_passes`), each band's pairs
/// sampled through the device's conversion.
pub chroma_device_decodes: u64,
/// ASTC textures' second decoded twins made (`texture/decoded_twin.rs`): one at a texture's
/// first view in its other colour space (an `_sRGB` texture's as its LDR form, or the other
/// way), which reads Metal's decode of the blocks in that form.
@@ -4845,6 +4911,14 @@ impl Device {
ycbcr_images_kept_reach: counters.ycbcr_images_kept[5].load(Ordering::Relaxed),
ycbcr_images_kept_view: counters.ycbcr_images_kept[6].load(Ordering::Relaxed),
ycbcr_planes_bound: counters.ycbcr_planes_bound.load(Ordering::Relaxed),
ycbcr_planes_images: counters.ycbcr_planes_images.load(Ordering::Relaxed),
ycbcr_planes_images_kept_conversion: counters.ycbcr_planes_images_kept[0]
.load(Ordering::Relaxed),
ycbcr_planes_images_kept_memory: counters.ycbcr_planes_images_kept[1]
.load(Ordering::Relaxed),
ycbcr_planes_images_kept_layout: counters.ycbcr_planes_images_kept[2]
.load(Ordering::Relaxed),
ycbcr_planes_images_bound: counters.ycbcr_planes_images_bound.load(Ordering::Relaxed),
ycbcr_device_conversions: counters.ycbcr_device_conversions.load(Ordering::Relaxed),
ycbcr_device_samples: counters.ycbcr_device_samples.load(Ordering::Relaxed),
attachment_clears_recorded: counters.attachment_clears_recorded.load(Ordering::Relaxed),
@@ -5011,6 +5085,8 @@ impl Device {
uncached_host_images: counters.uncached_host_images.load(Ordering::Relaxed),
cpu_block_decodes: counters.cpu_block_decodes.load(Ordering::Relaxed),
block_decode_passes: counters.block_decode_passes.load(Ordering::Relaxed),
chroma_device_twins: counters.chroma_device_twins.load(Ordering::Relaxed),
chroma_device_decodes: counters.chroma_device_decodes.load(Ordering::Relaxed),
second_twins: counters.second_twins.load(Ordering::Relaxed),
second_twin_checks: counters.second_twin_checks.load(Ordering::Relaxed),
second_twin_decodes: counters.second_twin_decodes.load(Ordering::Relaxed),
+8 -5
View File
@@ -48,8 +48,8 @@
//! `ycbcr_device_samples`). A render shadow's load stays Metal's arithmetic, which the store
//! inverts (**Passes** below). Metal's fixed-point conversion converts every other texture, and
//! every texture of a device without the conversion or with a defect in it (MoltenVK's 4:2:0
//! and 4:2:2 formats, `RuntimeDriverDefect::TwoPlaneChromaMisplaced`; lavapipe's 10-bit ones,
//! `RuntimeDriverDefect::TenBitCodesReadAsWords`).
//! and 4:2:2 formats, `RuntimeDriverDefect::TwoPlaneChromaMisplaced`; lavapipe's and RADV's
//! 10-bit ones, `RuntimeDriverDefect::TenBitCodesReadAsWords`).
//! - **When it converts.** Before an encoder's first command that uses the texture, and again
//! after a command of the encoder that writes the planes' bytes (through the buffer, a texture
//! over the planes such as a decoder's `R8Unorm` and `RG8Unorm` ones, or a blit): a use of the
@@ -78,9 +78,12 @@
//! `R8G8_UINT` of 8-bit codes and `R16G16_UINT` of 10-bit ones, and the function fetches the codes
//! and converts and filters them as Metal does, exactly; the draw or dispatch reads those bytes
//! alone, and converts no image (`WorkCounts::ycbcr_textures_in_place`, `ycbcr_planes_bound`).
//! The planes in place form no image of a multi-planar format (their rows are the surface's),
//! so the function converts them as Metal does on a device that converts the format itself
//! too, where the texture's image holds the device's conversion.
//! Where the device converts the 4:2:0 format as a linear image with Metal's reconstruction and
//! the planes lie as that image's would, in memory the runtime allocated, they are also such an
//! image (`texture/ycbcr_planes.rs`), and a slot whose every sample the device's sampler takes
//! samples it through the device's conversion instead (`WorkCounts::ycbcr_planes_images`,
//! `ycbcr_planes_images_bound`); elsewhere the function converts them as Metal does, on a device
//! that converts the format itself too, where the texture's image holds the device's conversion.
//! A read, a gather or any other use binds the image, converted as above. A discrete, virtual or
//! other GPU keeps the image alone (`ycbcr_images_kept_device`): it reads the host's planes
//! across its bus at every pass, where the image lies in its own memory. Both forms are Metal's
+339 -6
View File
@@ -15,8 +15,8 @@
//! `MIDPOINT_CHROMA_SAMPLES`, for a 4:2:0 or 4:2:2 format; either for a 4:4:4 one, which
//! reconstructs nothing), a 4:4:4 format also Vulkan 1.3 or `VK_EXT_ycbcr_2plane_444_formats`,
//! and its driver has no defect in it (`RuntimeDriverDefect::TwoPlaneChromaMisplaced`, MoltenVK,
//! for the subsampled formats; `RuntimeDriverDefect::TenBitCodesReadAsWords`, lavapipe, for the
//! 10-bit ones). A 4:4:4 format read as codes (`RGB8_444_2P`, `RGB10_444_2P`) converts
//! for the subsampled formats; `RuntimeDriverDefect::TenBitCodesReadAsWords`, lavapipe and RADV,
//! for the 10-bit ones). A 4:4:4 format read as codes (`RGB8_444_2P`, `RGB10_444_2P`) converts
//! nothing there (the identity model, which ignores the range, and no chroma to reconstruct),
//! so it reads its codes through ours, without a planes' image. Every other texture, and every
//! texture of another device, converts through Metal's arithmetic as before
@@ -62,6 +62,24 @@
//! takes off. MoltenVK 1.4.2 converts no two-plane format here: its 4:2:0 and 4:2:2
//! reconstruction is misplaced (`TwoPlaneChromaMisplaced`), and it reports no 4:4:4 two-plane
//! format.
//! - **4:2:2 pairs** (`GBGR422`, `BGRG422`, `chroma_pairs.rs`). The device converts a 4:2:2
//! texture's pairs itself where its optimal tiling of `G8B8G8R8_422_UNORM` or
//! `B8G8R8G8_422_UNORM` reports `SAMPLED_IMAGE`, `TRANSFER_DST` and Metal's reconstruction
//! (`MIDPOINT_CHROMA_SAMPLES` through a linear chroma filter, as above): the texture's decoded
//! twin then holds the device's conversion of its pairs (the identity model, full range),
//! sampled once per texel by each decode pass ([`PairsSampling`], `bind::chroma_sample_module`),
//! where elsewhere it holds Metal's (`bind::chroma_decode_module`). MoltenVK 1.4.2 converts both
//! (its single-plane 4:2:2 reconstruction is Vulkan's, `TwoPlaneChromaMisplaced`); lavapipe
//! filters their chroma nearest alone (no `SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER`) and
//! RADV has neither format, so their twins hold Metal's decode.
//! - **Planes images** (`texture/ycbcr_planes.rs`). A texture whose planes a function reads in
//! place is also a linear image of its 4:2:0 format over their bytes where the device's linear
//! tiling of `G8_B8R8_2PLANE_420_UNORM` or `G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16` reports
//! `SAMPLED_IMAGE` and Metal's reconstruction (as above) and its driver has no defect in the
//! format ([`YCbCrSampler::planes`]): the conversion is the surface's matrix and range, and the
//! view and every immutable sampler of it in a pipeline's layout share one conversion object
//! ([`Device::made_ycbcr_conversion`]). A pool sets aside `combinedImageSamplerDescriptorCount`
//! descriptors for each such binding ([`YCbCrFormats::planes_descriptors`]).
use super::device::lock;
use super::error::{vulkan, Error};
@@ -71,7 +89,10 @@ use super::Device;
use crate::device::functions::Vk;
use crate::{creation, release};
use ash::vk;
use metal2vulkan::bind::{YCbCrMatrix, YCbCrOutput, YCbCrPlanes, YCbCrRange, YCbCrSampleModule};
use metal2vulkan::bind::{
ChromaDecode, ChromaSampleModule, YCbCrMatrix, YCbCrOutput, YCbCrPlanes, YCbCrPlanesSampler,
YCbCrRange, YCbCrSampleModule,
};
use metal2vulkan::error::RuntimeDriverDefect;
use metal2vulkan::metal::format::ChromaSubsampling;
@@ -109,6 +130,12 @@ const FORMATS: [(vk::Format, u32, ChromaSubsampling); 6] = [
),
];
/// The 4:2:2 formats of a single plane the device is asked to convert (the module docs).
const PAIR_FORMATS: [vk::Format; 2] = [
vk::Format::G8B8G8R8_422_UNORM,
vk::Format::B8G8R8G8_422_UNORM,
];
/// One format the device converts: its optimal tiling's features, the largest image of it the
/// device makes, and the descriptors a combined image sampler of it takes.
#[derive(Clone, Copy)]
@@ -124,8 +151,18 @@ struct Converts {
#[derive(Clone, Default)]
pub(super) struct YCbCrFormats {
converts: Vec<Converts>,
/// The 4:2:0 formats it converts as a linear image that is sampled, with Metal's
/// reconstruction: the planes images a function samples in place
/// (`texture/ycbcr_planes.rs`).
linear: Vec<Converts>,
}
/// The 4:2:0 formats a planes image is of (`texture/ycbcr_planes.rs`).
const PLANES_FORMATS: [vk::Format; 2] = [
vk::Format::G8_B8R8_2PLANE_420_UNORM,
vk::Format::G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16,
];
impl YCbCrFormats {
/// The formats `physical` converts, as an image that is sampled and copied into; the
/// two-plane 4:4:4 ones only where its device takes them (`four_four_four`: Vulkan 1.3, or
@@ -141,12 +178,17 @@ impl YCbCrFormats {
four_four_four: bool,
) -> YCbCrFormats {
let usage = vk::ImageUsageFlags::SAMPLED | vk::ImageUsageFlags::TRANSFER_DST;
let pairs = PAIR_FORMATS
.iter()
.map(|&format| (format, 8, ChromaSubsampling::Chroma422));
let converts = FORMATS
.iter()
.filter(|&&(_, _, subsampling)| {
.copied()
.filter(|&(_, _, subsampling)| {
four_four_four || subsampling != ChromaSubsampling::Chroma444
})
.filter_map(|&(format, _, subsampling)| {
.chain(pairs)
.filter_map(|(format, _, subsampling)| {
// SAFETY: the caller's.
let properties =
unsafe { instance.get_physical_device_format_properties(physical, format) };
@@ -189,7 +231,42 @@ impl YCbCrFormats {
})
})
.collect();
YCbCrFormats { converts }
// As a linear image that is sampled: its linear tiling's features and limits.
let linear = PLANES_FORMATS
.iter()
.filter_map(|&format| {
// SAFETY: the caller's.
let properties =
unsafe { instance.get_physical_device_format_properties(physical, format) };
let features = properties.linear_tiling_features;
if !features.contains(vk::FormatFeatureFlags::SAMPLED_IMAGE)
|| !features.contains(vk::FormatFeatureFlags::MIDPOINT_CHROMA_SAMPLES)
|| !linear_chroma(features)
{
return None;
}
let info = vk::PhysicalDeviceImageFormatInfo2::default()
.format(format)
.ty(vk::ImageType::TYPE_2D)
.tiling(vk::ImageTiling::LINEAR)
.usage(vk::ImageUsageFlags::SAMPLED);
let mut ycbcr = vk::SamplerYcbcrConversionImageFormatProperties::default();
let mut out = vk::ImageFormatProperties2::default().push_next(&mut ycbcr);
// SAFETY: the caller's; the chain lives for the call.
unsafe {
instance.get_physical_device_image_format_properties2(physical, &info, &mut out)
}
.ok()?;
let extent = out.image_format_properties.max_extent;
Some(Converts {
format,
features,
extent: [extent.width, extent.height],
descriptors: ycbcr.combined_image_sampler_descriptor_count.max(1),
})
})
.collect();
YCbCrFormats { converts, linear }
}
/// A conversion of the first format the device converts, which its priming makes and
@@ -211,6 +288,22 @@ impl YCbCrFormats {
fn of_format(&self, format: vk::Format) -> Option<Converts> {
self.converts.iter().copied().find(|c| c.format == format)
}
/// `format` as a linear image the device samples, where it converts it so.
fn linear_of(&self, format: vk::Format) -> Option<Converts> {
self.linear.iter().copied().find(|c| c.format == format)
}
/// The descriptors a combined image sampler of a planes image of `sampler` takes from a pool
/// (`combinedImageSamplerDescriptorCount`): Vulkan's "each combined image sampler descriptor
/// binding with a layout that includes at least one immutable Y′CBCR conversion sampler will
/// internally use a number of descriptors equal to the maximum
/// combinedImageSamplerDescriptorCount of the formats", 1 where the device converts no such
/// image.
pub(super) fn planes_descriptors(&self, sampler: YCbCrPlanesSampler) -> u32 {
self.linear_of(sampler.format().into())
.map_or(1, |c| c.descriptors)
}
}
/// Whether a format of `features` filters its chroma linearly: the conversion's linear filter,
@@ -366,6 +459,98 @@ impl YCbCrSampler {
})
}
/// The device's conversion of a planes image of `sampler` (`texture/ycbcr_planes.rs`): its
/// 4:2:0 format as a linear image the device samples with Metal's reconstruction (the module
/// docs), the surface's matrix and range, and a linear filter, which every immutable sampler of
/// it in a pipeline's layout bakes; `None` where the device does not convert the format so (a
/// defect in it among the reasons).
pub(super) fn planes(device: &Device, sampler: YCbCrPlanesSampler) -> Option<YCbCrSampler> {
let format: vk::Format = sampler.format().into();
let converts = device.shared().ycbcr_formats.linear_of(format)?;
let defects = &device.properties().driver_defects;
if defects.contains(&RuntimeDriverDefect::TwoPlaneChromaMisplaced)
|| (sampler.bits() == 10
&& defects.contains(&RuntimeDriverDefect::TenBitCodesReadAsWords))
{
return None;
}
let model = match sampler.matrix() {
YCbCrMatrix::Bt601 => vk::SamplerYcbcrModelConversion::YCBCR_601,
YCbCrMatrix::Bt709 => vk::SamplerYcbcrModelConversion::YCBCR_709,
YCbCrMatrix::Bt2020 => vk::SamplerYcbcrModelConversion::YCBCR_2020,
_ => return None,
};
let range = match sampler.range() {
YCbCrRange::Video => vk::SamplerYcbcrRange::ITU_NARROW,
YCbCrRange::Full => vk::SamplerYcbcrRange::ITU_FULL,
_ => return None,
};
Some(YCbCrSampler {
format,
model,
range,
location: vk::ChromaLocation::MIDPOINT,
chroma_filter: vk::Filter::LINEAR,
// The chroma's filter, as Vulkan requires without a separate reconstruction filter
// (`VUID-VkSamplerCreateInfo-minFilter-01645`), and the filter a linear sample takes.
filter: vk::Filter::LINEAR,
descriptors: converts.descriptors,
})
}
/// Whether a planes image of [`planes`](Self::planes)'s format may be `[width, height]`: a
/// 4:2:0 image's width and height are even ("If format has a _420 suffix, extent.width must
/// be a multiple of 2", `VUID-VkImageCreateInfo-format-04712`, and its height,
/// `-04713`), within the format's linear limits.
pub(super) fn holds_planes(&self, device: &Device, [width, height]: [u32; 2]) -> bool {
let Some(converts) = device.shared().ycbcr_formats.linear_of(self.format) else {
return false;
};
width > 0
&& height > 0
&& width.is_multiple_of(2)
&& height.is_multiple_of(2)
&& width <= converts.extent[0]
&& height <= converts.extent[1]
}
/// The device's conversion of a 4:2:2 texture's pairs of `decode` over an image of `extent`,
/// where it converts them with Metal's reconstruction (the module docs): its midpoint through
/// a linear chroma filter, the identity model at full range (its channels are the codes);
/// `None` where Metal's decode holds them.
pub(super) fn pairs(
device: &Device,
decode: ChromaDecode,
extent: [u32; 2],
) -> Option<YCbCrSampler> {
let format: vk::Format = decode.format().into();
let converts = device.shared().ycbcr_formats.of_format(format)?;
// A 4:2:2 image's width is even (`VUID-VkImageCreateInfo-format-04712`).
if !extent[0].is_multiple_of(2)
|| extent[0] > converts.extent[0]
|| extent[1] > converts.extent[1]
{
return None;
}
// Its midpoint and linear chroma filter: `YCbCrFormats::of` holds no subsampled format
// without them.
let separate = converts.features.contains(
vk::FormatFeatureFlags::SAMPLED_IMAGE_YCBCR_CONVERSION_SEPARATE_RECONSTRUCTION_FILTER,
);
Some(YCbCrSampler {
format,
model: vk::SamplerYcbcrModelConversion::RGB_IDENTITY,
range: vk::SamplerYcbcrRange::ITU_FULL,
location: vk::ChromaLocation::MIDPOINT,
chroma_filter: vk::Filter::LINEAR,
filter: match separate {
true => vk::Filter::NEAREST,
false => vk::Filter::LINEAR,
},
descriptors: converts.descriptors,
})
}
/// Whether its chroma lies at Metal's midpoint (else cosited), and whether its chroma filter
/// is linear (else nearest).
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
@@ -719,3 +904,151 @@ impl Drop for YCbCrDeviceSampling {
lock(&shared.memory).free(raw, &self.placement);
}
}
/// The pairs' image of a 4:2:2 texture whose decoded twin holds the device's own conversion of
/// its pairs (the module docs, `texture/decoded_twin.rs`): an optimal image of the pairs' format
/// of the texture's extent, which each decode pass's step copies the band's pairs into and
/// samples through the device's conversion into the band's texels (`bind::chroma_sample_module`).
/// Its objects are released with it; no pending command uses them then (the texture's command
/// buffers hold the texture, and its twin with it, until they complete).
pub(crate) struct PairsSampling {
device: Device,
pub(crate) image: vk::Image,
placement: Placement,
pub(crate) view: vk::ImageView,
pub(crate) kernel: OwnedKernel,
pub(crate) extent: [u32; 2],
}
impl PairsSampling {
/// The pairs' image of a texture of `extent` (an even width) through `sampler`
/// ([`YCbCrSampler::pairs`]), on `device`. Refused as the image, its memory, the kernel and
/// the view are refused.
pub(crate) fn new(
device: &Device,
sampler: YCbCrSampler,
extent: [u32; 2],
) -> Result<PairsSampling, Error> {
let shared = device.shared();
let raw = shared.vk();
let [width, height] = extent;
let info = shared.sharing().image(
vk::ImageCreateInfo::default()
.image_type(vk::ImageType::TYPE_2D)
.format(sampler.format)
.extent(vk::Extent3D {
width,
height,
depth: 1,
})
.mip_levels(1)
.array_layers(1)
.samples(vk::SampleCountFlags::TYPE_1)
.tiling(vk::ImageTiling::OPTIMAL)
.usage(vk::ImageUsageFlags::SAMPLED | vk::ImageUsageFlags::TRANSFER_DST)
.initial_layout(vk::ImageLayout::UNDEFINED),
);
// SAFETY: the device converts the format as an optimal image that is sampled and
// copied into, of this extent (`YCbCrSampler::pairs`).
let image = unsafe { creation::image(raw, &info) }?;
// SAFETY: `image` is a live image of this device.
let requirements = unsafe { raw.get_image_memory_requirements(image) };
let requirements = shared.textures.placement().place(requirements);
let placement = match crate::memory::allocate_image(
&shared.memory,
raw,
&requirements,
MemoryClass::Private,
) {
Ok(placement) => placement,
Err(error) => {
// SAFETY: the image is unused.
unsafe { release::object(raw, image) };
return Err(error);
}
};
let unwind = || {
lock(&shared.memory).free(raw, &placement);
// SAFETY: the image is unused.
unsafe { release::object(raw, image) };
};
// SAFETY: the placement meets the image's requirements and is not bound elsewhere.
if let Err(error) =
unsafe { creation::bind_image(raw, image, placement.memory, placement.offset) }
{
unwind();
return Err(vulkan(error));
}
let kernel = match device.owned_kernel(OwnedModule::ChromaSample(sampler)) {
Ok(kernel) => kernel,
Err(error) => {
unwind();
return Err(error);
}
};
let Some(conversion) = device.ycbcr_conversion(sampler) else {
unwind();
return Err(super::error::internal(
"a 4:2:2 sample kernel without its conversion",
));
};
let mut chained = vk::SamplerYcbcrConversionInfo::default().conversion(conversion);
let info = vk::ImageViewCreateInfo::default()
.image(image)
.view_type(vk::ImageViewType::TYPE_2D)
.format(sampler.format)
.subresource_range(vk::ImageSubresourceRange {
aspect_mask: vk::ImageAspectFlags::COLOR,
base_mip_level: 0,
level_count: 1,
base_array_layer: 0,
layer_count: 1,
})
.push_next(&mut chained);
// SAFETY: the image is live and bound; the conversion is of its format.
let view = match unsafe { creation::image_view(raw, &info) } {
Ok(view) => view,
Err(error) => {
unwind();
return Err(vulkan(error));
}
};
shared.counts.chroma_device_twin();
Ok(PairsSampling {
device: device.clone(),
image,
placement,
view,
kernel,
extent,
})
}
/// The shape of a step that samples `rows` rows from row `first` of the image
/// (`ChromaSampleModule::shape`), and its workgroups.
pub(crate) fn step(
&self,
first: u32,
rows: u32,
) -> ([u8; ChromaSampleModule::SHAPE_WORDS as usize * 4], [u32; 3]) {
let [width, _] = self.extent;
let local = ChromaSampleModule::LOCAL_SIZE;
(
ChromaSampleModule::shape([width, rows], first, self.extent),
[width.div_ceil(local), rows.div_ceil(local), 1],
)
}
}
impl Drop for PairsSampling {
fn drop(&mut self) {
let shared = self.device.shared();
let raw = shared.vk();
// SAFETY: no pending command uses them (the type's docs).
unsafe {
release::object(raw, self.view);
release::object(raw, self.image);
}
lock(&shared.memory).free(raw, &self.placement);
}
}
@@ -1 +1 @@
6698e1ba9f7c528ef84b271ac227938f310e48bc5c7665e2fb183bd6414f0e1f
da175e3e4747419320728a17ce8431bc0ef52b9775255a81b2014ff11ef5a318
@@ -17,11 +17,15 @@
//! against an Apple M3 Max's reads by its own tests; where the device does not sample through
//! Metal's own texture unit, within its conversion of the codes, announced
//! `device-texel-conversion`: `converted_holds`) through the texture's decoded twin,
//! announced `carried-decoded-twin` once and `decoded-texel-precision` never: a new texture's
//! opaque black, then after a CPU copy of the whole texture and of part of two rows, a blit
//! from a buffer of the whole texture and of part of a row, and a copy from another texture,
//! each decoded into the twin in whole rows (a blit's by a GPU decode pass, a CPU copy's by one
//! or on the CPU, counted in `WorkCounts`; [`four_two_two_texels_read_as_metal_s`]).
//! announced `carried-decoded-twin` once: a new texture's opaque black, then after a CPU copy
//! of the whole texture and of part of two rows, a blit from a buffer of the whole texture and
//! of part of a row, and a copy from another texture, each decoded into the twin in whole rows
//! (a blit's by a GPU decode pass, a CPU copy's by one or on the CPU, counted in `WorkCounts`;
//! [`four_two_two_texels_read_as_metal_s`]). Where the device converts the format itself with
//! Metal's reconstruction (`WorkCounts::chroma_device_twins`: MoltenVK), the twin holds the
//! device's own conversion of the pairs, its red and blue within a code of Metal's and its
//! green Metal's, every decode a GPU pass, announced `decoded-texel-precision` once; elsewhere
//! never.
//! - A render pipeline state of the format, which Metal's own validation aborts plain too, and a
//! render pass into the texture, whose clear plain Metal stores in the format's encoding (not
//! built), are refused typed (`Unsupported`, `Feature::Format`).
@@ -528,14 +532,24 @@ fn four_two_two_texels_read_as_metal_s() {
(counts.block_decode_passes, counts.cpu_block_decodes)
};
let mut wrong = Vec::new();
// The device's own conversion of the pairs (the module docs): red and blue within a
// code of Metal's, each the device's nearest code.
let converts = |device: &Device| device.work_counts().chroma_device_twins > 0;
let check =
|wrong: &mut Vec<String>, what: &str, pf: PixelFormat, t: &Texture, bytes: &[u8]| {
assert_eq!(bytes_of(device, t), bytes, "{pf:?} {what}: its bytes");
let got = read_whole(device, &state, t);
let want = metal_texels(pf, bytes);
let device_conversion = converts(device);
for (at, (got, want)) in got.iter().zip(&want).enumerate() {
for c in 0..4 {
if !converted_holds(got[c], want[c], exact) && wrong.len() < 24 {
let holds = match c {
0 | 2 if device_conversion => {
(got[c] - want[c]).abs() <= 1.0 / 255.0 + 1e-6
}
_ => converted_holds(got[c], want[c], exact),
};
if !holds && wrong.len() < 24 {
wrong.push(format!(
"{pf:?} {what}, texel {at} channel {c}: {} against Metal's {}",
got[c], want[c]
@@ -622,9 +636,16 @@ fn four_two_two_texels_read_as_metal_s() {
announced(Degradation::CarriedDecodedTwin),
announced(Degradation::DecodedTexelPrecision)
),
(1, 0),
(1, usize::from(converts(device))),
"on {name}"
);
if converts(device) {
assert_eq!(
device.work_counts().cpu_block_decodes,
0,
"every decode a GPU pass where the device converts the format, on {name}"
);
}
assert_eq!(
announced(Degradation::DeviceTexelConversion),
usize::from(!exact),
@@ -16,9 +16,12 @@
//! little-endian word whose low 6 bits are noise, which Metal does not read.
use super::degrade_notices::{counts, on_device, on_device_with};
use super::ycbcr_device_reads::{assert_device_reads, vulkan_read};
use super::{buffer_with, read_buffer, ycbcr_textures};
use crate::air_library::AirLibrary;
use metal2vulkan::bind::{ycbcr_read, SamplerDescriptor, YCbCrCodes, YCbCrMatrix, YCbCrRange};
use metal2vulkan::bind::{
ycbcr_read, SamplerDescriptor, YCbCrCodes, YCbCrMatrix, YCbCrOutput, YCbCrRange,
};
use metal2vulkan::device::DevicePolicy;
use metal2vulkan::metal::format::ycbcr_format;
use metal2vulkan::metal::{PixelFormat, SamplerMinMagFilter, TextureUsage};
@@ -87,6 +90,30 @@ const SURFACES: [Surface; 4] = [
},
];
/// Surfaces whose rows lie 256 bytes apart, the pitch a driver's linear image of their width
/// takes (`texture/ycbcr_planes.rs` takes the image only where its planes lie as the surface's):
/// 8-bit `420v` and 10-bit `x420`, 40 x 24.
const PLANES_SURFACES: [Surface; 2] = [
Surface {
format: PixelFormat::YCBCR84202P,
ostype: *b"420v",
matrix: None,
conversion: (YCbCrRange::Video, YCbCrMatrix::Bt601),
size: [40, 24],
row: 256,
chroma_at: 256 * 24,
},
Surface {
format: PixelFormat::YCBCR104202P,
ostype: *b"x420",
matrix: Some(SurfaceYCbCrMatrix::Itu2020),
conversion: (YCbCrRange::Video, YCbCrMatrix::Bt2020),
size: [40, 24],
row: 256,
chroma_at: 256 * 24,
},
];
impl Surface {
/// The format's codes.
fn codes(&self) -> YCbCrCodes {
@@ -156,6 +183,32 @@ impl Surface {
/// luma code at its place, the four nearest chroma pairs weighted 9/3/3/1 and rounded to a
/// code, converted (`metal2vulkan::bind::ycbcr_read`).
pub(super) fn model(&self, bytes: &[u8]) -> Vec<[u16; 3]> {
self.sums(bytes)
.into_iter()
.map(|(luma, sums)| {
let [cb, cr] = sums.map(|s| ((s + 8) >> 4) as u16);
ycbcr_read(self.codes(), self.conversion, [luma, cb, cr])
})
.collect()
}
/// Each texel's red, green and blue through the device's conversion of `bytes`, row by row:
/// Vulkan's of the luma code and the chroma sums over 16, unrounded
/// (`ycbcr_device_reads::vulkan_read`), which is Vulkan's midpoint reconstruction through a
/// linear chroma filter at a luma texel's centre.
fn device_model(&self, bytes: &[u8]) -> Vec<[f64; 3]> {
self.sums(bytes)
.into_iter()
.map(|(luma, sums)| {
let [cb, cr] = sums.map(|s| f64::from(s) / 16.0);
vulkan_read(self.codes(), self.conversion, [f64::from(luma), cb, cr])
})
.collect()
}
/// Each texel's luma code and its four nearest chroma pairs' Cb and Cr codes weighted
/// 9/3/3/1, in sixteenths, row by row.
fn sums(&self, bytes: &[u8]) -> Vec<(u16, [u32; 2])> {
let taps = |q: u64, n: u64| -> [(u64, u32); 2] {
let c = q / 2;
if q % 2 == 1 {
@@ -177,9 +230,8 @@ impl Surface {
sums[1] += wx * wy * u32::from(self.code(bytes, at + self.unit()));
}
}
let [cb, cr] = sums.map(|s| ((s + 8) >> 4) as u16);
let luma = self.code(bytes, y * self.row + x * self.unit());
out.push(ycbcr_read(self.codes(), self.conversion, [luma, cb, cr]));
out.push((luma, sums));
}
}
out
@@ -274,6 +326,38 @@ pub(super) fn texels(
(texture, size): (&Texture, [u64; 2]),
sampler: Option<&SamplerState>,
) -> Vec<[u16; 3]> {
on_grid(&raw_texels(device, state, (texture, size), sampler))
}
/// The `v` of `v / 2048` of each channel of the `float4`s `raw`, checked to be on the grid, alpha
/// 1.
fn on_grid(raw: &[u8]) -> Vec<[u16; 3]> {
raw.as_chunks::<16>()
.0
.iter()
.map(|t| {
let c = |i: usize| f32::from_le_bytes(t[4 * i..4 * i + 4].try_into().unwrap());
assert_eq!(c(3), 1.0, "alpha 1");
std::array::from_fn(|i| {
let v = c(i) * 2048.0;
assert!(
v == v.round() && (0.0..=2048.0).contains(&v),
"{v} off the grid"
);
v as u16
})
})
.collect()
}
/// The `float4`s `state` writes of `texture` of `size` through `sampler`, one thread a texel, in a
/// command buffer of its own, as their bytes.
fn raw_texels(
device: &Device,
state: &ComputePipelineState,
(texture, size): (&Texture, [u64; 2]),
sampler: Option<&SamplerState>,
) -> Vec<u8> {
let [w, h] = size;
let out = device
.new_buffer(16 * w * h, ResourceOptions::shared())
@@ -294,24 +378,7 @@ pub(super) fn texels(
command_buffer.commit().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(command_buffer.status(), CommandBufferStatus::Completed);
let bytes = read_buffer(&out, 0, 16 * w * h).unwrap();
bytes
.as_chunks::<16>()
.0
.iter()
.map(|t| {
let c = |i: usize| f32::from_le_bytes(t[4 * i..4 * i + 4].try_into().unwrap());
assert_eq!(c(3), 1.0, "alpha 1");
std::array::from_fn(|i| {
let v = c(i) * 2048.0;
assert!(
v == v.round() && (0.0..=2048.0).contains(&v),
"{v} off the grid"
);
v as u16
})
})
.collect()
read_buffer(&out, 0, 16 * w * h).unwrap()
}
/// The counts of the YCbCr paths between two readings: textures made reading their planes in
@@ -526,3 +593,87 @@ fn a_ycbcr_texture_the_form_does_not_read_keeps_its_image() {
);
});
}
/// The planes images made between two readings, then the textures kept from one by each reason:
/// the device's conversion, the memory, the layout (`WorkCounts::ycbcr_planes_images*`).
fn planes_images(before: &WorkCounts, after: &WorkCounts) -> [u64; 4] {
[
after.ycbcr_planes_images - before.ycbcr_planes_images,
after.ycbcr_planes_images_kept_conversion - before.ycbcr_planes_images_kept_conversion,
after.ycbcr_planes_images_kept_memory - before.ycbcr_planes_images_kept_memory,
after.ycbcr_planes_images_kept_layout - before.ycbcr_planes_images_kept_layout,
]
}
/// A texture whose planes are read in place is also an image the device's own sampler Y′CbCr
/// conversion samples where the device converts the 4:2:0 format as a linear image with Metal's
/// reconstruction (`WorkCounts::ycbcr_planes_images`, the runtime's `texture/ycbcr_planes.rs`),
/// and is counted by why where it is not: each such texture once. Through the image a nearest
/// sample of each texel is the device's conversion, Vulkan's of the luma code and Metal's
/// chroma sums unrounded within the device's bound, announced (`ycbcr-filter-not-exact`);
/// without it, Metal's texel through the texel buffer, unannounced.
#[test]
fn a_ycbcr_texture_s_planes_image_samples_through_the_device_s_conversion() {
on_device(|device, messages| {
if !reads_in_place(device) {
eprintln!("{}: reads no planes in place", device.name());
return;
}
let kernels = Kernels::new(device);
let nearest = sampler(device, SamplerMinMagFilter::Nearest);
let mut images = 0;
for (seed, surface) in (11..).zip(PLANES_SURFACES) {
let what = format!("{:?} {:?}", surface.format, surface.conversion);
let bytes = surface.bytes(seed);
let buffer = buffer_with(device, &bytes).unwrap();
let before = device.work_counts();
let texture = surface.texture(&buffer, 0).unwrap();
let after = device.work_counts();
let made = planes_images(&before, &after);
eprintln!(
"YCBCR-PLANES-IMAGE {} {what}: image, or kept for the conversion, the memory, \
the layout: {made:?}",
device.name()
);
assert_eq!(
after.ycbcr_textures_in_place - before.ycbcr_textures_in_place,
1,
"{what}: in place"
);
assert_eq!(made.iter().sum::<u64>(), 1, "{what}: one answer, {made:?}");
images += made[0];
let before = device.work_counts();
let raw = raw_texels(
device,
&kernels.sample,
(&texture, surface.size),
Some(&nearest),
);
let after = device.work_counts();
let bound = (
after.ycbcr_planes_images_bound - before.ycbcr_planes_images_bound,
after.ycbcr_planes_bound - before.ycbcr_planes_bound,
);
match made[0] {
1 => {
assert_eq!(bound, (1, 0), "{what}: the planes image bound");
let want = surface.device_model(&bytes);
assert_device_reads(&raw, &want, (YCbCrOutput::Converted, false), &what);
}
_ => {
assert_eq!(bound, (0, 1), "{what}: the texel buffer bound");
assert!(
on_grid(&raw) == surface.model(&bytes),
"{what}: Metal's texels"
);
}
}
}
let notices = counts(&messages.take_notices());
assert_eq!(
notices.contains_key(&Degradation::YCbCrFilterNotExact),
images > 0,
"{notices:?}"
);
});
}
@@ -125,7 +125,9 @@ impl From<vk::SpecializationMapEntry> for ash::vk::SpecializationMapEntry {
/// The `VkSamplerCreateInfo` of a sampler description, with the reduction mode chained through
/// `reduction` when it is not the default weighted average (a `SamplerDesc` is never
/// unnormalized), and the border's component mapping through `border` when the description has one
/// (`SamplerDesc::border_components`).
/// (`SamplerDesc::border_components`). A description of a Y′CbCr conversion
/// (`SamplerDesc::ycbcr`) also needs the caller's `VkSamplerYcbcrConversionInfo` of its conversion
/// chained, which this does not make.
///
/// `reduction` and `border` are caller storage: they must outlive the returned structure.
pub fn sampler_create_info<'a>(
@@ -1223,6 +1223,7 @@ fn sampler_create_info_chains_reduction_only_when_needed() {
border_color: vk::BorderColor::FLOAT_OPAQUE_WHITE,
reduction: vk::SamplerReductionMode::WEIGHTED_AVERAGE,
border_components: None,
ycbcr: None,
};
let mut reduction = avk::SamplerReductionModeCreateInfo::default();
let mut border = avk::SamplerBorderColorComponentMappingCreateInfoEXT::default();
@@ -1268,6 +1269,7 @@ fn sampler_create_info_chains_reduction_only_when_needed() {
let mapped = vk::SamplerDesc {
border_color: vk::BorderColor::FLOAT_OPAQUE_BLACK,
border_components: Some(argb),
ycbcr: None,
..desc
};
let mut reduction = avk::SamplerReductionModeCreateInfo::default();
+239 -2
View File
@@ -15,16 +15,57 @@
//! it does any 8-bit format's texture, which is how Metal samples them.
//!
//! A texel's codes read its row's pairs alone, so a decode is of whole rows.
//!
//! **The device's own conversion.** Where the device converts the format itself (a sampler
//! Y′CbCr conversion of `G8B8G8R8_422_UNORM` or `B8G8R8G8_422_UNORM`, [`ChromaDecode::format`],
//! whose chroma lies at Metal's midpoint through a linear chroma filter), the consumer copies the
//! pairs into an image of that format and one dispatch of [`chroma_sample_module`] samples it
//! through a sampler of that conversion (the identity model, full range) at each texel's centre,
//! writing the twin's codes as [`chroma_decode_module`] writes Metal's: Vulkan's implicit
//! reconstruction weighs the pair's chroma 3 and the pair beside it 1 at a texel's centre, clamped
//! to the edge at the row's ends, as Metal does, at the device's precision; each channel is
//! stored as `roundEven(clamp(c, 0, 1) · 255)`, where Metal's sum rounds its ties up.
//!
//! **The sample module** (one per device; the sampler, its conversion and the pairs' format are
//! the consumer's layout's). One `GLCompute` entry `main` with local size
//! ([`ChromaSampleModule::LOCAL_SIZE`], [`ChromaSampleModule::LOCAL_SIZE`], 1), no push
//! constants, and in set 0:
//!
//! | Binding | Resource |
//! |---|---|
//! | [`ChromaSampleModule::PAIRS_BINDING`] | the pairs' image, a 2D combined image sampler through a sampler of the device's Y′CbCr conversion (immutable, as Vulkan requires), sampled at level 0 |
//! | [`ChromaSampleModule::SHAPE_BINDING`] | a storage buffer of [`ChromaSampleModule::SHAPE_WORDS`] words ([`ChromaSampleModule::shape`]) |
//! | [`ChromaSampleModule::TEXELS_BINDING`] | the band's texels, a storage buffer of words, written tight as a copy into the twin reads them |
//!
//! The shape's words, in order: the band's width and rows, its first row in the pairs' image,
//! and the image's width and height. Invocation `(x, y)` inside the band samples `((x + 0.5) /
//! W, (first + y + 0.5) / H)` and writes word `y · width + x`: red (Cr) lowest, then green (Y),
//! blue (Cb) and alpha 255. One outside it writes nothing. The consumer dispatches `⌈width / 8⌉ x
//! ⌈rows / 8⌉` workgroups.
//!
//! **Synchronization** (consumer): the pairs' copy into the image and the shape's write
//! (`TRANSFER_WRITE`) → `SHADER_SAMPLED_READ` and `SHADER_STORAGE_READ` in `COMPUTE_SHADER` before
//! the dispatch; its texel writes (`SHADER_STORAGE_WRITE`) → `TRANSFER_READ` before the texels are
//! copied into the twin.
use super::block_decode::{decode_module, BlockDecodeModule, BLOCKS, SHAPE, TEXELS};
use super::ycbcr_convert::{scalar, words_buffer};
use crate::budget::{Budget, Meter};
use crate::device::requirements::Requirements;
use crate::device::Device;
use crate::error::Error;
use crate::error::{Error, InternalError, InternalKind};
use crate::metal::PixelFormat;
use crate::pipeline::sym::{
CombinedSampler, ResourceKind, ResourceSlot, SamplerRef, Stage, Symbol,
};
use crate::spirv::builder::constructs::{ArmEnd, ArmFn};
use crate::spirv::error::BResult;
use crate::spirv::ir::{BinOp, ExecMode, ExecModel, IoDir, MemAccess, Type, TypedModule};
use crate::spirv::ir::{
BinOp, ConvOp, Dim, ExecMode, ExecModel, GlslOp, ImageOperands, ImageType, ImageUsage, IoDir,
MemAccess, StorageClass, Type, TypedModule,
};
use crate::vk::Format;
use std::sync::Arc;
/// The 4:2:2 decode module of `device` for `decode`'s pairs: one invocation per texel on the block
/// decode's bindings and shape ([`BlockDecodeModule`]), built with the typed builder, checked by
@@ -82,6 +123,15 @@ impl ChromaDecode {
PixelFormat::RGBA8Unorm
}
/// Vulkan's format of the pairs, which a sampler Y′CbCr conversion reads (the module docs):
/// `G8B8G8R8_422_UNORM` (`G0 B G1 R`) or `B8G8R8G8_422_UNORM` (`B G0 R G1`).
pub fn format(self) -> Format {
match self {
ChromaDecode::Gbgr => Format::G8B8G8R8_422_UNORM,
ChromaDecode::Bgrg => Format::B8G8R8G8_422_UNORM,
}
}
/// The byte of a pair (its 4 bytes as a little-endian word, byte `k` at bits `8k`) holding
/// red, blue, and the green of the pair's texel `t` (0 or 1).
fn bytes(self) -> (u32, u32, [u32; 2]) {
@@ -253,5 +303,192 @@ fn typed_module(decode: ChromaDecode) -> BResult<TypedModule> {
b.finalize()
}
/// The crate-owned 4:2:2 sample module of one device (the module docs), validated like any
/// output.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ChromaSampleModule {
/// SPIR-V 1.5 words, entry point `main`, bindings numbered as below in set 0.
pub spirv: Arc<[u32]>,
/// What the module needs from the device (within every Vulkan 1.2 device).
pub requirements: Requirements,
}
impl ChromaSampleModule {
/// Descriptor set of every binding.
pub const SET: u32 = 0;
/// The pairs' image through the device's Y′CbCr conversion: a combined image sampler.
pub const PAIRS_BINDING: u32 = 0;
/// The band's shape: a storage buffer of [`SHAPE_WORDS`](Self::SHAPE_WORDS) words.
pub const SHAPE_BINDING: u32 = 1;
/// The band's texels: a storage buffer, written.
pub const TEXELS_BINDING: u32 = 2;
/// The words of a shape.
pub const SHAPE_WORDS: u32 = 5;
/// Invocations of one workgroup along x, and along y: one texel each.
pub const LOCAL_SIZE: u32 = 8;
/// The shape's bytes of a band of `size` texels (its width and rows) from row `first` of a
/// pairs' image of `extent` (the module docs).
pub fn shape(
size: [u32; 2],
first: u32,
extent: [u32; 2],
) -> [u8; Self::SHAPE_WORDS as usize * 4] {
let words = [size[0], size[1], first, extent[0], extent[1]];
let mut bytes = [0; Self::SHAPE_WORDS as usize * 4];
for (chunk, word) in bytes.as_chunks_mut::<4>().0.iter_mut().zip(words) {
chunk.copy_from_slice(&word.to_le_bytes());
}
bytes
}
}
/// The binding symbol of the pairs' combined image sampler in the sample module.
const PAIRS: ResourceSlot = ResourceSlot {
stage: Stage::Kernel,
kind: ResourceKind::CombinedTextureSampler(CombinedSampler {
sampler: SamplerRef::Slot(0),
compare: false,
integer: false,
}),
index: 0,
};
/// The fixed binding numbers of the sample module's symbols.
fn sample_binding_of(sym: &Symbol) -> Option<u32> {
match sym {
Symbol::DescriptorSet(_) => Some(ChromaSampleModule::SET),
Symbol::Binding(s) if *s == PAIRS => Some(ChromaSampleModule::PAIRS_BINDING),
Symbol::Binding(s) if *s == SHAPE => Some(ChromaSampleModule::SHAPE_BINDING),
Symbol::Binding(s) if *s == TEXELS => Some(ChromaSampleModule::TEXELS_BINDING),
_ => None,
}
}
/// The 4:2:2 sample module of `device` (the module docs): built with the typed builder, checked
/// by the owned verifier against the device's profile (requirements included), serialized, and
/// numbered with the fixed bindings of [`ChromaSampleModule`]. The sampler and the pairs' image
/// are the consumer's, so one module samples both formats.
pub fn chroma_sample_module(device: &Device) -> Result<ChromaSampleModule, Error> {
let profile = device.profile();
let m = sample_typed_module()?;
let mut meter = Meter::new(&Budget::default());
crate::spirv::verify::verify(&m, profile, &mut meter)?;
let r = crate::spirv::serialize::serialize(m)?;
profile.check(&r.requirements).map_err(|c| {
Error::Internal(InternalError::new(
InternalKind::RequirementsExceedProfile,
format!("the 4:2:2 sample module needs {c:?}"),
))
})?;
let words = crate::spirv::serialize::relocate(&r, &sample_binding_of)?;
Ok(ChromaSampleModule {
spirv: words.into(),
requirements: r.requirements,
})
}
/// The sample module as a typed module, before serialization (the module docs).
fn sample_typed_module() -> BResult<TypedModule> {
let mut b = crate::spirv::builder::ModuleBuilder::new();
let u32_ = b.ty(Type::Int {
width: 32,
signed: false,
})?;
let f32_ = b.ty(Type::Float { width: 32 })?;
let uvec3 = b.ty(Type::Vector { elem: u32_, len: 3 })?;
let vec2 = b.ty(Type::Vector { elem: f32_, len: 2 })?;
let pairs_ty = b.ty(Type::Image(ImageType {
sampled_type: f32_,
dim: Dim::D2,
depth: false,
arrayed: false,
multisampled: false,
usage: ImageUsage::Sampled,
format: crate::spv::ImageFormat::Unknown,
}))?;
let combined_ty = b.ty(Type::SampledImage { image: pairs_ty })?;
let pairs = b.resource(PAIRS, StorageClass::UniformConstant, combined_ty)?;
let shape = words_buffer(&mut b, SHAPE, u32_)?;
let texels = words_buffer(&mut b, TEXELS, u32_)?;
let invocation = b.builtin(crate::spv::BuiltIn::GlobalInvocationId, IoDir::Input, uvec3)?;
let void = b.ty(Type::Void)?;
let mut f = b.function(void)?;
let zero = scalar(&mut f, u32_, 0)?;
let invocation = f.module().global_value(invocation)?;
let invocation = f.load(invocation, MemAccess::default())?;
let x = f.composite_extract(invocation, &[0])?;
let y = f.composite_extract(invocation, &[1])?;
let shape = f.module().global_value(shape)?;
let mut field = |index: u32| -> BResult<_> {
let index = scalar(&mut f, u32_, u64::from(index))?;
let p = f.access_chain(shape, &[zero, index])?;
f.load(p, MemAccess::default())
};
let (width, rows, first) = (field(0)?, field(1)?, field(2)?);
let (across, down) = (field(3)?, field(4)?);
let in_x = f.binary(BinOp::ULessThan, x, width)?;
let in_y = f.binary(BinOp::ULessThan, y, rows)?;
let inside = f.binary(BinOp::LogicalAnd, in_x, in_y)?;
let pairs = f.module().global_value(pairs)?;
let texels = f.module().global_value(texels)?;
let sampled: ArmFn<'_, ()> = Box::new(move |f, _| {
let float = |f: &mut crate::spirv::builder::FunctionBuilder<'_>, v: f32| {
scalar(f, f32_, u64::from(v.to_bits()))
};
// The centre of texel `(x, first + y)` of the pairs' image, normalized.
let half = float(f, 0.5)?;
let row = f.binary(BinOp::IAdd, first, y)?;
let mut coord = Vec::with_capacity(2);
for (at, extent) in [(x, across), (row, down)] {
let at = f.convert(ConvOp::ConvertUToF, at, f32_)?;
let at = f.binary(BinOp::FAdd, at, half)?;
let extent = f.convert(ConvOp::ConvertUToF, extent, f32_)?;
coord.push(f.binary(BinOp::FDiv, at, extent)?);
}
let coord = f.composite_construct(vec2, &coord)?;
let combined = f.load(pairs, MemAccess::default())?;
let lod = float(f, 0.0)?;
let ops = ImageOperands {
lod: Some(lod),
..ImageOperands::default()
};
let sample = f.sample(combined, coord, None, false, &ops)?;
// Red (Cr), green (Y) and blue (Cb), each rounded to a code, red lowest, alpha 255.
let (low, one) = (float(f, 0.0)?, float(f, 1.0)?);
let largest = float(f, 255.0)?;
let mut word = scalar(f, u32_, 0xff << 24)?;
for c in 0..3 {
let v = f.composite_extract(sample, &[c])?;
let v = f.glsl(GlslOp::FClamp, &[v, low, one])?;
let v = f.binary(BinOp::FMul, v, largest)?;
let v = f.glsl(GlslOp::RoundEven, &[v])?;
let v = f.convert(ConvOp::ConvertFToU, v, u32_)?;
let shift = scalar(f, u32_, u64::from(8 * c))?;
let v = f.binary(BinOp::ShiftLeftLogical, v, shift)?;
word = f.binary(BinOp::BitwiseOr, word, v)?;
}
let t = f.binary(BinOp::IMul, y, width)?;
let t = f.binary(BinOp::IAdd, t, x)?;
let ptr = f.access_chain(texels, &[zero, t])?;
f.store(ptr, word, MemAccess::default())?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
f.if_(&mut (), inside, sampled, None)?;
f.ret(None)?;
let id = f.finish()?;
b.entry(
ExecModel::GLCompute,
id,
vec![ExecMode::LocalSize {
x: ChromaSampleModule::LOCAL_SIZE,
y: ChromaSampleModule::LOCAL_SIZE,
z: 1,
}],
)?;
b.finalize()
}
#[cfg(test)]
mod tests;
@@ -1,4 +1,4 @@
use super::{typed_module, ChromaDecode};
use super::{sample_typed_module, typed_module, ChromaDecode, ChromaSampleModule};
use crate::bind::block_decode::{BlockDecodeModule, BLOCKS, SHAPE, TEXELS};
use crate::spirv::interp::{run, Buffer, Config, Order, Resources};
use crate::spirv::testing::{assert_valid, committed_profiles};
@@ -94,6 +94,24 @@ fn the_chroma_decode_kernels_are_valid_on_every_committed_profile() {
assert_valid(typed_module(decode).expect("module"), p);
}
}
// The device's own conversion's sample kernel, one for both formats.
for (_, p) in &profiles {
assert_valid(sample_typed_module().expect("sample module"), p);
}
}
/// The sample module's shape: the band's width and rows, its first row, and the image's extent,
/// each a little-endian word; Vulkan's formats of the pairs, in either order.
#[test]
fn the_chroma_sample_shape_and_formats() {
let shape = ChromaSampleModule::shape([16, 3], 5, [16, 12]);
let words: Vec<u32> = (shape.as_chunks::<4>().0.iter())
.map(|w| u32::from_le_bytes(*w))
.collect();
assert_eq!(words, [16, 3, 5, 16, 12]);
use crate::vk::Format;
assert_eq!(ChromaDecode::Gbgr.format(), Format::G8B8G8R8_422_UNORM);
assert_eq!(ChromaDecode::Bgrg.format(), Format::B8G8R8G8_422_UNORM);
}
/// The kernel's texels of a region `size` of `decode`'s `pairs`; the texel buffer's bytes past the
+5 -1
View File
@@ -309,7 +309,7 @@ use crate::bind::plan::slots::{
address_map_variant, anisotropic_variant, bindings, bound_value, buffer_use, check_slots,
check_sparse_textures, cross_variant, cubic_variant, large_view_candidates, mark_disjoint,
plan_buffer, psb_variant, range_variant, record_specialized, snapshot_forms, srgb_variant,
storage_view_variant, used_uses, ycbcr_in_place_variant,
storage_view_variant, used_uses, ycbcr_in_place_variant, ycbcr_planes_sampled_variant,
};
use crate::bind::plan::{
AccessClass, BindingPlan, BoundKind, ByteRange, DescriptorWrite, FactorSite, FactorTemplate,
@@ -2113,6 +2113,8 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
}
// A texture's snapshot, which the draw reads the texture through.
BindingSource::SnapshotTexels(slot) => WriteSource::SnapshotTexels { slot },
// A two-plane YCbCr texture's planes image, through the device's conversion.
BindingSource::YCbCrPlanes(slot) => resources.planes_image_write(slot)?,
};
descriptors.push(DescriptorWrite {
set: set.set,
@@ -2445,6 +2447,8 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
variant.cross_class = cross_variant(&p.dependencies, &p.interface.slots, shape);
variant.srgb_textures = srgb_variant(profile, &p.dependencies, shape, &variant.cross_class);
variant.ycbcr_in_place = ycbcr_in_place_variant(&p.dependencies, shape);
variant.ycbcr_planes_sampled =
ycbcr_planes_sampled_variant(&p.dependencies, shape, &variant.ycbcr_in_place);
variant.address_maps = address_map_variant(&p.dependencies, shape);
variant.cubic_samplers = cubic_variant(&p.dependencies, shape)?;
variant.anisotropic_samplers = anisotropic_variant(&p.dependencies, shape);
@@ -34,6 +34,7 @@ fn shape(ty: TextureType, pf: PixelFormat, samples: u32, usage: TextureUsage) ->
address_modes: crate::metal::sampler::AddressModeMap::IDENTITY,
offset_base_axes: 0,
ycbcr_in_place: false,
ycbcr_planes_sampler: None,
texture_type: ty,
pixel_format: pf,
sample_count: samples,
+7 -3
View File
@@ -103,7 +103,9 @@
//! ([`PvrtcDecode`]), which [`pvrtc_decode_module`] writes; an ETC2 or EAC texture on a device
//! without the formats through a twin of its codes or an 11-bit format's values ([`EtcDecode`], in
//! the texels [`EtcTexels`] names), which [`etc_decode_module`] writes; a 4:2:2 texture through a
//! twin of its texels' codes ([`ChromaDecode`]), which [`chroma_decode_module`] writes.
//! twin of its texels' codes ([`ChromaDecode`]), which [`chroma_decode_module`] writes, or, where
//! the device converts the format itself, [`chroma_sample_module`] samples through the device's
//! own Y′CbCr conversion ([`ChromaSampleModule`]).
//! [`sampler_desc`] gives the Vulkan sampler a plan's sampler write needs, [`heap_classes`] the
//! classes of the handle heap's arrays on a profile, [`FunctionTableWords`] the words of a
//! visible-function table's buffer, and [`FunctionTableSnapshot`] the one buffer of a command's
@@ -186,7 +188,9 @@ pub use argument_buffer::{
};
pub use astc_decode::{astc_decode_module, AstcDecode, AstcTexels};
pub use block_decode::BlockDecodeModule;
pub use chroma_decode::{chroma_decode_module, ChromaDecode};
pub use chroma_decode::{
chroma_decode_module, chroma_sample_module, ChromaDecode, ChromaSampleModule,
};
pub use color_resolve::{
color_resolve_modules, ColorResolveFormat, ColorResolveModules, ResolveChannel, ResolveRule,
ResolveSource, SRGB_RESOLVE_LINEAR, SRGB_RESOLVE_THRESHOLDS,
@@ -327,7 +331,7 @@ pub use ycbcr_convert::{
ycbcr_convert_floats_module, ycbcr_convert_module, ycbcr_read, ycbcr_texel, YCbCrCodes,
YCbCrConversion, YCbCrConvertModule, YCbCrMatrix, YCbCrOutput, YCbCrPlanes, YCbCrRange,
};
pub use ycbcr_in_place::YCbCrInPlace;
pub use ycbcr_in_place::{YCbCrInPlace, YCbCrPlanesSampler};
pub use ycbcr_refresh::{ycbcr_refresh_module, YCbCrRefreshModule};
pub use ycbcr_sample::{ycbcr_sample_module, YCbCrSampleModule};
pub use ycbcr_write::{ycbcr_store, ycbcr_write, ycbcr_write_module, YCbCrWriteModule};
+9 -1
View File
@@ -616,6 +616,13 @@ pub enum WriteSource {
/// `YCbCrInPlace::view_bytes`. Only a slot under its in-place variant binds it
/// (`VariantKey::ycbcr_in_place`).
YCbCrInPlace { slot: SlotRef },
/// The planes of the two-plane YCbCr texture bound at `slot`, held as an image the device's
/// own sampler Y′CbCr conversion samples (`TextureShape::Texture::ycbcr_planes_sampler`): a
/// combined image sampler whose image is that image viewed with the conversion
/// (`bind::YCbCrPlanesSampler`) and whose sampler is the binding's immutable one, in
/// `GENERAL`. Only a slot under its planes-image variant binds it
/// (`VariantKey::ycbcr_planes_sampled`, `BindingSource::YCbCrPlanes`).
YCbCrPlanesImage { slot: SlotRef },
/// The texture buffer bound at `slot`, as a texel buffer view.
TexelBuffer {
slot: SlotRef,
@@ -1052,7 +1059,8 @@ pub enum AccessClass {
Indirect,
Attachment,
/// A two-plane YCbCr texture's planes, read in place through the slot's uniform texel buffer
/// (`WriteSource::YCbCrInPlace`): a read of the planes' bytes, not of the texture's image.
/// (`WriteSource::YCbCrInPlace`) or the image of them the device's conversion samples
/// (`WriteSource::YCbCrPlanesImage`): a read of the planes' bytes, not of the texture's image.
YCbCrPlanes,
}
@@ -63,6 +63,7 @@ use super::slots::{
address_map_variant, anisotropic_variant, bindings, bound_value, buffer_use, check_slots,
check_sparse_textures, cross_variant, cubic_variant, mark_disjoint, plan_buffer, psb_variant,
record_specialized, srgb_variant, storage_view_variant, used_uses, ycbcr_in_place_variant,
ycbcr_planes_sampled_variant,
};
use super::{
BindingPlan, BoundKind, ComputeTemplate, DescriptorWrite, FieldLocation, LocalRules,
@@ -636,6 +637,8 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result<Bindi
}
// A sparse texture's tile map.
BindingSource::TileMap(slot) => resources.tile_map(slot),
// A two-plane YCbCr texture's planes image, through the device's conversion.
BindingSource::YCbCrPlanes(slot) => resources.planes_image_write(slot)?,
// A tile function's attachment.
BindingSource::TileAttachment(color_index) => WriteSource::TileAttachment {
color_index,
@@ -813,6 +816,8 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result<Bindi
&variant.cross_class,
);
variant.ycbcr_in_place = ycbcr_in_place_variant(&p.dependencies, shape);
variant.ycbcr_planes_sampled =
ycbcr_planes_sampled_variant(&p.dependencies, shape, &variant.ycbcr_in_place);
variant.address_maps = address_map_variant(&p.dependencies, shape);
variant.cubic_samplers = cubic_variant(&p.dependencies, shape)?;
variant.anisotropic_samplers = anisotropic_variant(&p.dependencies, shape);
@@ -677,6 +677,34 @@ impl ResourcePlanner<'_> {
}
}
/// The write of `slot`'s binding under its planes-image variant (`BindingSource::YCbCrPlanes`,
/// `VariantKey::ycbcr_planes_sampled`): the image of the planes of the two-plane YCbCr texture
/// the shape binds there, viewed with the device's conversion of `TextureShape::Texture::
/// ycbcr_planes_sampler`, a read of the planes' bytes. The plan takes the variant only where
/// the shape binds such a texture there (`slots::ycbcr_planes_sampled_variant`), so any other
/// is the binder's defect.
pub(crate) fn planes_image_write(&mut self, slot: SlotRef) -> Result<WriteSource, BindError> {
match self.texture_shape(slot) {
Some(TextureShape::Texture {
ycbcr_planes_sampler: Some(_),
..
}) => {
self.uses.push(ResourceUse {
resource: UseTarget::Slot(slot),
access: AccessSet::READ,
class: AccessClass::YCbCrPlanes,
stages: (self.stage_flags)(slot.stage),
range: None,
});
Ok(WriteSource::YCbCrPlanesImage { slot })
}
_ => Err(internal(format!(
"a planes image's binding of {slot:?}, which binds no texture whose planes are \
held as an image"
))),
}
}
fn texture_use(&mut self, slot: SlotRef, t: &TextureSlot, storage: bool) {
self.uses.push(ResourceUse {
resource: UseTarget::Slot(slot),
@@ -92,6 +92,7 @@ fn compatibility_is_type_samples_numeric_type_and_depth() {
address_modes: crate::metal::sampler::AddressModeMap::IDENTITY,
offset_base_axes: 0,
ycbcr_in_place: false,
ycbcr_planes_sampler: None,
texture_type,
pixel_format,
sample_count,
@@ -162,6 +163,7 @@ fn a_ulong_slot_binds_only_rg32uint_textures() {
address_modes: crate::metal::sampler::AddressModeMap::IDENTITY,
offset_base_axes: 0,
ycbcr_in_place: false,
ycbcr_planes_sampler: None,
texture_type: TextureType::Type2D,
pixel_format,
sample_count: 1,
@@ -255,6 +257,7 @@ fn a_numeric_slot_binds_either_integer_type() {
address_modes: crate::metal::sampler::AddressModeMap::IDENTITY,
offset_base_axes: 0,
ycbcr_in_place: false,
ycbcr_planes_sampler: None,
texture_type: TextureType::Type2D,
pixel_format,
sample_count: 1,
@@ -621,6 +624,7 @@ fn an_immutable_linear_sampler_needs_a_filterable_view() {
address_modes: crate::metal::sampler::AddressModeMap::IDENTITY,
offset_base_axes: 0,
ycbcr_in_place: false,
ycbcr_planes_sampler: None,
texture_type: TextureType::Type2D,
pixel_format: pf,
sample_count: 1,
@@ -721,6 +725,7 @@ fn a_linear_compare_sampler_needs_no_filterable_view() {
address_modes: crate::metal::sampler::AddressModeMap::IDENTITY,
offset_base_axes: 0,
ycbcr_in_place: false,
ycbcr_planes_sampler: None,
texture_type: TextureType::Type2D,
pixel_format: pf,
sample_count: 1,
@@ -815,6 +820,7 @@ fn bicubic_texels_follow_the_bound_format() {
address_modes: crate::metal::sampler::AddressModeMap::IDENTITY,
offset_base_axes: 0,
ycbcr_in_place: false,
ycbcr_planes_sampler: None,
texture_type: TextureType::Type2D,
pixel_format: pf,
sample_count: 1,
@@ -975,6 +981,7 @@ fn texel_format_follows_the_bound_format() {
address_modes: crate::metal::sampler::AddressModeMap::IDENTITY,
offset_base_axes: 0,
ycbcr_in_place: false,
ycbcr_planes_sampler: None,
texture_type: TextureType::Type2D,
pixel_format,
sample_count: 1,
@@ -1158,6 +1165,7 @@ fn a_separate_pair_takes_the_combined_pairs_checks() {
address_modes: crate::metal::sampler::AddressModeMap::IDENTITY,
offset_base_axes: 0,
ycbcr_in_place: false,
ycbcr_planes_sampler: None,
texture_type: TextureType::Type2D,
pixel_format: pf,
sample_count: 1,
+57 -1
View File
@@ -395,7 +395,7 @@ pub(crate) fn ycbcr_in_place_variant(
dependencies
.iter()
.filter_map(|d| match d.fact {
RuntimeFact::YCbCrInPlace { slot, samplers } => Some((slot, samplers)),
RuntimeFact::YCbCrInPlace { slot, samplers, .. } => Some((slot, samplers)),
_ => None,
})
.filter(|&(slot, samplers)| {
@@ -418,6 +418,62 @@ pub(crate) fn ycbcr_in_place_variant(
.collect()
}
/// The slots of `in_place` (the plan's `VariantKey::ycbcr_in_place`) whose function's every sample
/// the device's own sampler Y′CbCr conversion takes (`RuntimeFact::YCbCrInPlace`'s `device`), at
/// which `shape` binds a texture whose planes are also held as an image it samples
/// (`TextureShape::Texture::ycbcr_planes_sampler`), and each runtime sampler the function samples
/// the slot through addresses no border on either plane axis ([`planes_word`]), each with that
/// conversion: the plan's `VariantKey::ycbcr_planes_sampled`. The variant's compile states the
/// same facts, so its plan for the same shape states the same key.
pub(crate) fn ycbcr_planes_sampled_variant(
dependencies: &[RuntimeDependency],
shape: &BindShape,
in_place: &std::collections::BTreeSet<SlotRef>,
) -> BTreeMap<SlotRef, crate::bind::YCbCrPlanesSampler> {
dependencies
.iter()
.filter_map(|d| match d.fact {
RuntimeFact::YCbCrInPlace {
slot,
samplers,
device: true,
} if in_place.contains(&slot) => Some((slot, samplers)),
_ => None,
})
.filter_map(|(slot, samplers)| {
let sampler = match bound_texture(shape, slot) {
Some(&TextureShape::Texture {
ycbcr_planes_sampler: Some(sampler),
..
}) => sampler,
_ => return None,
};
let stage = shape.stages.get(&slot.stage);
let mut words = (0..32).filter(|n| samplers >> n & 1 != 0).map(|n| {
stage
.and_then(|s| s.samplers.get(&n))
.map_or(0, |s| s.word.0)
});
words.all(planes_word).then_some((slot, sampler))
})
.collect()
}
/// Whether a runtime sampler of word `word` samples a two-plane YCbCr texture in a way the device's
/// own sampler Y′CbCr conversion of its planes' image takes: no clamp-to-zero or border color on
/// the `s` or `t` axis, which a 4:2:0 texture reads as the border where that sampler clamps to the
/// edge (every other mode a 4:2:0 texture samples as clamp-to-edge). Its filter and coordinate
/// space are the function's to apply.
pub(crate) fn planes_word(word: u32) -> bool {
use crate::metal::sampler::SamplerWord;
use crate::metal::SamplerAddressMode as M;
let border = [M::ClampToZero.as_raw(), M::ClampToBorderColor.as_raw()];
(0..2).all(|axis| {
let mode = (word & SamplerWord::ADDRESS[axis]) >> SamplerWord::ADDRESS_SHIFT[axis];
!border.contains(&mode)
})
}
/// Whether a runtime sampler of word `word` samples a two-plane YCbCr texture in a way its
/// in-place form reads: one filter for minification and magnification (nearest or linear), no
/// anisotropy, no cubic filter, no comparison and the weighted-average reduction. Its mip filter
@@ -779,7 +779,11 @@ fn the_in_place_variant_takes_a_slot_its_texture_and_samplers_read() {
s
};
let fact = |slot, samplers| RuntimeDependency {
fact: RuntimeFact::YCbCrInPlace { slot, samplers },
fact: RuntimeFact::YCbCrInPlace {
slot,
samplers,
device: true,
},
mechanism: Mechanism::Variant,
};
// Slot 0 samples through constexpr samplers alone, slot 1 also through `[[sampler(3)]]`.
@@ -834,4 +838,104 @@ fn the_in_place_variant_takes_a_slot_its_texture_and_samplers_read() {
}
// A stage that states no form takes none, whatever its textures.
assert!(ycbcr_in_place_variant(&[], &s).is_empty());
// No texture's planes are held as an image the device samples: no slot samples one.
assert!(ycbcr_planes_sampled_variant(&deps, &s, &in_place).is_empty());
}
/// An in-place slot enters `VariantKey::ycbcr_planes_sampled` only where the bound texture's
/// planes are held as an image the device's conversion samples, the function's every sample is one
/// that sampler takes (the fact's `device`), and each runtime sampler it samples through addresses
/// no border on the plane axes.
#[test]
fn the_planes_image_variant_takes_a_slot_the_device_s_sampler_reads() {
use crate::bind::state::{BoundSampler, SamplerDescriptor, TextureFacts};
use crate::bind::ycbcr_convert::{YCbCrCodes, YCbCrMatrix, YCbCrPlanes, YCbCrRange};
use crate::bind::YCbCrInPlace;
use metal::SamplerAddressMode as M;
let texture = |index| SlotRef {
stage: Stage::Kernel,
class: SlotClass::Texture,
index,
};
let pf = metal::PixelFormat::YCBCR84202P;
let codes = metal::format::ycbcr_format(pf)
.and_then(YCbCrCodes::of)
.expect("codes");
let planes = YCbCrPlanes::new(
[8, 4],
[0, 16],
[64, 16],
(YCbCrRange::Full, YCbCrMatrix::Bt601),
codes,
);
let words = YCbCrInPlace::of(&planes).expect("in place");
// Slots 0 to 2 bind textures whose planes are held as an image, slot 3 one whose are not.
let shape = |sampler: SamplerDescriptor| {
let mut stage = StageShape::default();
for index in 0..4 {
let mut facts = TextureFacts::new(metal::TextureType::Type2D, pf);
facts.ycbcr_in_place = Some(match index {
3 => words,
_ => words.with_planes_image(),
});
stage.textures.insert(index, facts.shape());
}
stage.samplers.insert(3, BoundSampler::new(sampler).shape());
let mut s = BindShape::default();
s.stages.insert(Stage::Kernel, stage);
s
};
let fact = |slot, samplers, device| RuntimeDependency {
fact: RuntimeFact::YCbCrInPlace {
slot,
samplers,
device,
},
mechanism: Mechanism::Variant,
};
// Slot 0 samples through constexpr samplers the device takes, slot 1 also through
// `[[sampler(3)]]`, slot 2 through a constexpr sampler it does not take.
let deps = [
fact(texture(0), 0, true),
fact(texture(1), 1 << 3, true),
fact(texture(2), 0, false),
fact(texture(3), 0, true),
];
let edge = SamplerDescriptor::new();
let s = shape(edge);
let in_place = ycbcr_in_place_variant(&deps, &s);
assert_eq!(in_place.len(), 4);
let sampler = words.sampler();
assert_eq!(
ycbcr_planes_sampled_variant(&deps, &s, &in_place),
BTreeMap::from([(texture(0), sampler), (texture(1), sampler)])
);
// A runtime sampler that addresses a border on a plane axis keeps slot 1 from it; one on `r`
// does not.
for (mode, axis, taken) in [
(M::ClampToZero, 0, false),
(M::ClampToBorderColor, 1, false),
(M::Repeat, 0, true),
(M::MirrorClampToEdge, 1, true),
(M::ClampToBorderColor, 2, true),
] {
let mut sampler_state = edge;
match axis {
0 => sampler_state.s_address_mode = mode,
1 => sampler_state.t_address_mode = mode,
_ => sampler_state.r_address_mode = mode,
}
let s = shape(sampler_state);
let in_place = ycbcr_in_place_variant(&deps, &s);
let got = ycbcr_planes_sampled_variant(&deps, &s, &in_place);
assert_eq!(
got.contains_key(&texture(1)),
taken,
"{mode:?} on axis {axis}"
);
assert!(got.contains_key(&texture(0)), "{mode:?} on axis {axis}");
}
// A slot outside the in-place variant takes no image.
let none = std::collections::BTreeSet::new();
assert!(ycbcr_planes_sampled_variant(&deps, &s, &none).is_empty());
}
+8 -1
View File
@@ -1112,7 +1112,7 @@ impl TextureFacts {
/// storage slot's level views and pushed level count, its swizzle, its address-mode map, its
/// [`offset_base_axes`](Self::offset_base_axes), and whether its planes are read in place
/// ([`ycbcr_in_place`](Self::ycbcr_in_place), whose words the slot's push field carries, not
/// the shape). Its array length only changes the view's subresource range, which is every
/// the shape) and through which device conversion where they are held as an image. Its array length only changes the view's subresource range, which is every
/// layer.
///
/// The level count is stated whatever the usage: plain Metal writes a texture made without
@@ -1132,6 +1132,7 @@ impl TextureFacts {
address_modes: self.address_modes,
offset_base_axes: self.offset_base_axes(),
ycbcr_in_place: self.ycbcr_in_place.is_some(),
ycbcr_planes_sampler: self.ycbcr_in_place.and_then(|p| p.planes_sampler()),
}
}
}
@@ -1956,6 +1957,12 @@ pub enum TextureShape {
/// (`VariantKey::ycbcr_in_place`).
#[cfg_attr(feature = "serde", serde(default))]
ycbcr_in_place: bool,
/// The device's conversion of the texture's planes, where the consumer holds them as an
/// image it samples ([`YCbCrInPlace::planes_sampler`](crate::bind::YCbCrInPlace)): a slot
/// whose every sample the device's sampler takes samples that image
/// (`VariantKey::ycbcr_planes_sampled`).
#[cfg_attr(feature = "serde", serde(default))]
ycbcr_planes_sampler: Option<crate::bind::YCbCrPlanesSampler>,
},
Buffer {
pixel_format: metal::PixelFormat,
+136 -1
View File
@@ -23,6 +23,17 @@
//! the conversion of the surface's range and matrix, each channel a step of `1 / 2048`, alpha 1.
//! A sample is Metal's filter of those texels on that grid (`lower::sampler::in_place`), exact,
//! as the image's emulated filter is.
//!
//! **Through the device's sampler.** Where the consumer also holds the planes as an image of the
//! multi-planar 4:2:0 format over their own bytes, which the device's sampler Y′CbCr conversion
//! reads with Metal's reconstruction (the chroma at the midpoint through a linear chroma filter),
//! the texture states it ([`YCbCrInPlace::with_planes_image`]), and a slot whose every sample the
//! device's sampler takes (`RuntimeFact::YCbCrInPlace`'s `device`: no border address mode, no
//! texel offset placed by a parent's size) samples that image instead
//! (`VariantKey::ycbcr_planes_sampled`): its binding a combined image sampler whose immutable
//! sampler bakes the conversion ([`YCbCrPlanesSampler`], `ResourceKind::YCbCrPlanes`), each sample
//! the device's at level 0, a nearest one at the centre of the luma texel Metal reads. Its answer
//! is the device's conversion and filter of the codes, not Metal's.
use super::ycbcr_convert::{YCbCrMatrix, YCbCrOutput, YCbCrPlanes, YCbCrRange};
use crate::metal::format::ChromaSubsampling;
@@ -47,6 +58,10 @@ pub struct YCbCrInPlace {
/// The bytes the texel buffer views, from the planes' first byte: the end of the last row of
/// codes either plane holds, rounded up to a whole element.
bytes: u64,
/// The consumer holds the planes as an image the device's conversion samples
/// ([`with_planes_image`](Self::with_planes_image)).
#[cfg_attr(feature = "serde", serde(default))]
planes_image: bool,
}
impl YCbCrInPlace {
@@ -116,7 +131,36 @@ impl YCbCrInPlace {
words[Self::CHROMA_AT] = chroma_at / element;
words[Self::CHROMA_ROW] = chroma_row / element;
words[Self::CONVERSION] = conversion_word(codes.bits, planes.range, planes.matrix);
Some(YCbCrInPlace { words, bytes })
Some(YCbCrInPlace {
words,
bytes,
planes_image: false,
})
}
/// The form of the same planes where the consumer also holds them as an image of
/// [`sampler`](Self::sampler)'s format over their bytes, which the device's sampler Y′CbCr
/// conversion of it reads (the module docs): a slot whose every sample the device's sampler
/// takes samples that image (`VariantKey::ycbcr_planes_sampled`).
pub fn with_planes_image(self) -> YCbCrInPlace {
YCbCrInPlace {
planes_image: true,
..self
}
}
/// The device's conversion of the planes as an image ([`YCbCrPlanesSampler`]): their codes'
/// bits, range and matrix.
pub fn sampler(&self) -> YCbCrPlanesSampler {
YCbCrPlanesSampler {
conversion: self.words[Self::CONVERSION],
}
}
/// [`sampler`](Self::sampler), where the consumer holds the planes as an image it samples
/// ([`with_planes_image`](Self::with_planes_image)); `None` where it does not.
pub fn planes_sampler(&self) -> Option<YCbCrPlanesSampler> {
self.planes_image.then(|| self.sampler())
}
/// The words of the slot's push field.
@@ -157,6 +201,55 @@ impl YCbCrInPlace {
}
}
/// The device's own sampler Y′CbCr conversion of a two-plane YCbCr texture's planes held as an
/// image of the multi-planar 4:2:0 format over their bytes (the module docs, **Through the
/// device's sampler**): the codes' bits, the surface's range and matrix, Metal's reconstruction
/// (the chroma at the midpoint through a linear chroma filter) and a linear filter. A slot that
/// samples such a texture through it is a combined image sampler whose immutable sampler is the
/// device's conversion of this (`ResourceKind::YCbCrPlanes`, `vk::SamplerDesc::ycbcr`); the
/// consumer makes the image's view with the same conversion.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct YCbCrPlanesSampler {
/// The conversion word ([`YCbCrInPlace::CONVERSION`]).
pub(crate) conversion: u32,
}
impl YCbCrPlanesSampler {
/// The codes' bits: 8 or 10.
pub fn bits(self) -> u32 {
self.conversion & 0xff
}
/// The surface's range.
pub fn range(self) -> YCbCrRange {
match self.conversion >> 8 & 1 {
1 => YCbCrRange::Full,
_ => YCbCrRange::Video,
}
}
/// The surface's matrix.
pub fn matrix(self) -> YCbCrMatrix {
match self.conversion >> 9 & 3 {
1 => YCbCrMatrix::Bt709,
2 => YCbCrMatrix::Bt2020,
_ => YCbCrMatrix::Bt601,
}
}
/// The multi-planar format of the planes' image: `G8_B8R8_2PLANE_420_UNORM` of 8-bit codes,
/// `G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16` of 10-bit ones (the high 10 bits of each
/// little-endian 16-bit word, as the planes hold them).
pub fn format(self) -> vk::Format {
match self.bits() {
8 => vk::Format::G8_B8R8_2PLANE_420_UNORM,
_ => vk::Format::G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16,
}
}
}
/// The conversion word ([`YCbCrInPlace::CONVERSION`]) of `bits`-bit codes of `range` and
/// `matrix`.
fn conversion_word(bits: u32, range: YCbCrRange, matrix: YCbCrMatrix) -> u32 {
@@ -240,4 +333,46 @@ mod tests {
let zero = planes(PixelFormat::YCBCR84202P, [0, 16], [96, 0]);
assert_eq!(YCbCrInPlace::of(&zero), None);
}
/// The planes' image's conversion is the codes' bits, range and matrix, of the format of
/// their bits; a texture states it only once the consumer holds the image.
#[test]
fn the_planes_sampler_is_the_conversion_word() {
let p8 =
YCbCrInPlace::of(&planes(PixelFormat::YCBCR84202P, [0, 16], [96, 16])).expect("8-bit");
assert_eq!(p8.planes_sampler(), None);
let held = p8.with_planes_image();
assert_eq!(held.words(), p8.words());
let s = held.planes_sampler().expect("held");
assert_eq!(s, p8.sampler());
assert_eq!(
(s.bits(), s.range(), s.matrix(), s.format()),
(
8,
YCbCrRange::Full,
YCbCrMatrix::Bt709,
vk::Format::G8_B8R8_2PLANE_420_UNORM
)
);
let codes = ycbcr_format(PixelFormat::YCBCR104202P)
.and_then(YCbCrCodes::of)
.expect("codes");
let p10 = YCbCrPlanes::new(
[8, 4],
[0, 16],
[64, 16],
(YCbCrRange::Video, YCbCrMatrix::Bt2020),
codes,
);
let s = YCbCrInPlace::of(&p10).expect("10-bit").sampler();
assert_eq!(
(s.bits(), s.range(), s.matrix(), s.format()),
(
10,
YCbCrRange::Video,
YCbCrMatrix::Bt2020,
vk::Format::G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16
)
);
}
}
+6 -2
View File
@@ -21,6 +21,7 @@
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use crate::bind::YCbCrPlanesSampler;
use crate::device::profile::Independence;
use crate::device::requirements::{
ApiVersion, FloatControl, FloatWidth, FormatUsage, Requirements, ResolveMode, SpirvCapability,
@@ -794,9 +795,10 @@ codec_struct! {
SamplerDesc {
mag_filter, min_filter, mipmap_mode, address_mode_u, address_mode_v, address_mode_w,
mip_lod_bias, max_anisotropy, compare, min_lod, max_lod, border_color, reduction,
border_components,
border_components, ycbcr,
}
ComponentMapping { r, g, b, a }
YCbCrPlanesSampler { conversion }
}
// ---- Link symbols (`pipeline::sym`) ----
@@ -848,6 +850,7 @@ codec_enum! {
TileMap, SeparateTexture(f0), SeparateSampler(f0),
ExtendedShadow(f0),
SnapshotTexels(f0),
YCbCrPlanes(f0),
}
AccelerationStructureLevel { Primitive, Instance }
SamplerRef { Slot(f0), Constexpr(f0) }
@@ -1261,7 +1264,7 @@ codec_enum! {
MergedDraws,
QuadPrimitiveIds,
PrivateList,
YCbCrInPlace { slot, samplers },
YCbCrInPlace { slot, samplers, device },
}
UniformViewChoice { Viewed, Spare, Kept }
Mechanism {
@@ -1450,6 +1453,7 @@ codec_enum! {
SeparateTexture { texture, sampler }, SeparateSampler { stage, sampler },
ExtendedShadow(f0),
SnapshotTexels(f0),
YCbCrPlanes(f0),
}
VertexStride { Static(f0), PerBind }
}
+22 -3
View File
@@ -60,7 +60,7 @@ mod tests;
/// unchanged version, and its bless records the version. Independent of the crate's version and of
/// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no
/// history.
pub const SEMANTICS_VERSION: u32 = 1910;
pub const SEMANTICS_VERSION: u32 = 1911;
/// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the
/// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another
@@ -70,7 +70,7 @@ pub const SEMANTICS_VERSION: u32 = 1910;
/// 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 = 476;
pub const ARTIFACT_FORMAT_VERSION: u32 = 477;
/// 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
@@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 476;
/// changes no behaviour, and then updates that hash alone with the commit saying why, or changes
/// behaviour and also bumps this version. The commit that bumps it says what changed; this comment
/// keeps no history.
pub const RUNTIME_VERSION: u32 = 1682;
pub const RUNTIME_VERSION: u32 = 1683;
/// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex,
/// of the manifest, the build script, and exactly the files the crate roots' module tree compiles
@@ -211,6 +211,18 @@ pub struct VariantKey {
/// (`bind::YCbCrInPlace`). The plan of a pipeline compiled under it states it.
#[cfg_attr(feature = "serde", serde(default))]
pub ycbcr_in_place: BTreeSet<SlotRef>,
/// Slots of [`ycbcr_in_place`](Self::ycbcr_in_place) whose function's every sample the
/// device's own sampler Y′CbCr conversion takes, at which the shape binds a texture whose
/// planes are also held as an image it samples, each with that conversion
/// (`TextureShape::Texture::ycbcr_planes_sampler`, `RuntimeFact::YCbCrInPlace`'s `device`):
/// each such slot binds that image through an immutable sampler of the conversion, and its
/// samples are the device's (`bind::YCbCrPlanesSampler`). The plan of a pipeline compiled
/// under it states it.
#[cfg_attr(
feature = "serde",
serde(default, with = "crate::pipeline::serde_pairs")
)]
pub ycbcr_planes_sampled: BTreeMap<SlotRef, crate::bind::YCbCrPlanesSampler>,
/// Texture slots a constexpr sampler samples, each with the address-mode map of the texture
/// the shape binds there where it is not the identity: every slot of a
/// `RuntimeFact::ConstexprSampled` the shape binds such a texture at. The function's constexpr
@@ -517,6 +529,7 @@ impl VariantKey {
&& self.srgb_textures.is_empty()
&& self.snapshot_textures.is_empty()
&& self.ycbcr_in_place.is_empty()
&& self.ycbcr_planes_sampled.is_empty()
&& self.address_maps.is_empty()
&& !self.flat_grid
&& !self.replay_bindings
@@ -628,6 +641,12 @@ impl VariantKey {
.filter(|s| s.stage == stage)
.copied()
.collect();
out.ycbcr_planes_sampled = self
.ycbcr_planes_sampled
.iter()
.filter(|(s, _)| s.stage == stage)
.map(|(s, sampler)| (*s, *sampler))
.collect();
out.address_maps = self
.address_maps
.iter()
@@ -156,7 +156,11 @@ fn every_fact() -> Vec<RuntimeFact> {
RuntimeFact::QuadPrimitiveIds,
RuntimeFact::RotatedWeights,
RuntimeFact::PrivateList,
RuntimeFact::YCbCrInPlace { slot, samplers: 1 },
RuntimeFact::YCbCrInPlace {
slot,
samplers: 1,
device: true,
},
RuntimeFact::MeshLastFirst,
RuntimeFact::AbsentArgumentRead {
stage: Stage::Fragment,
@@ -1051,6 +1051,7 @@ fn image_decl(s: &TileSlot) -> ImageDecl {
extended: None,
x_channel: false,
in_place: false,
planes_sampler: None,
}
}
@@ -22,6 +22,18 @@
//! sampler's modes arrive mapped (`LoweringInputs::address_maps`), and a runtime sampler's word is
//! mapped here ([`mapped_word`]). A border tap reads the border color through the format's
//! channels, alpha 1.
//!
//! **The device's sampler** (`LoweringInputs::ycbcr_planes_sampled`): where the consumer holds
//! the planes as an image of the multi-planar 4:2:0 format over their bytes and every sample of the
//! slot is one the device's own sampler Y′CbCr conversion takes (no border address mode, no texel
//! offset placed by a parent's size), the slot is a combined image sampler whose immutable sampler
//! is that conversion (`ResourceKind::YCbCrPlanes`), and a sample is the device's sample of the
//! image at level 0: a linear one at Metal's coordinate (normalized from pixels by the push field's
//! size, its texel offset moved in texels), a nearest one at the centre of the luma texel Metal
//! reads, clamped to the edge (where the device's linear filter of its conversion reads that
//! texel's luma and Metal's 9/3/3/1 chroma weights). The answer is the device's conversion and
//! filter, not Metal's integer arithmetic. No `ConstOffset` or `Offset` reaches the sample
//! (`VUID-RuntimeSpirv-ConstOffset-10718`), and the size queries read the push field as above.
use crate::air::ir::ValueId;
use crate::lower::emit::EmitCx;
@@ -435,6 +447,122 @@ fn mapped_word(fb: &mut FunctionBuilder<'_>, t: &T, word: SValue) -> BResult<SVa
Ok(w)
}
/// The texel of in-place sample `s` through the device's own sampler Y′CbCr conversion
/// (`LoweringInputs::ycbcr_planes_sampled`, the module docs' **The device's sampler**), in the open
/// block: the slot's combined image `sampled` sampled at level 0, a linear sample at Metal's
/// coordinate (its texel offset moved in texels), a nearest one at the centre of the luma texel
/// Metal reads (clamped to the edge, as a 4:2:0 texture addresses every mode but a border one).
fn device_sample(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
s: &Sample,
slot: SlotRef,
(coord, sampled): (SValue, SValue),
) -> BResult<SValue> {
let t = T::new(fb)?;
let w = words(cx, fb, slot)?;
let vec2 = fb.module().ty(SType::Vector {
elem: t.f32_,
len: 2,
})?;
let size = fb.composite_construct(t.uvec2, &w.size)?;
let size = fb.convert(ConvOp::ConvertUToF, size, vec2)?;
// Whether the sampler reads pixel coordinates and filters linearly: a constexpr sampler's
// state, or a runtime sampler's word.
let (pixel, linear) = match &s.state {
State::Constant { linear, pixel, .. } => (Known::Fixed(*pixel), Known::Fixed(*linear)),
State::Slot { sampler } => {
let word = super::emit::sampler_word(cx, fb, Pixel::Spec(*sampler))?;
let bit = t.u(fb, crate::metal::sampler::SamplerWord::PIXEL_COORDINATES)?;
let set = fb.binary(BinOp::BitwiseAnd, word, bit)?;
let pixel = fb.binary(BinOp::IEqual, set, bit)?;
let tys = Tys::new(fb)?;
let linear = super::extended::word_linear(fb, &tys, word)?;
(Known::Run(pixel), Known::Run(linear))
}
};
// The coordinate in texels, and normalized.
let texels = fb.binary(BinOp::FMul, coord, size)?;
let (mut texels, mut normal) = match pixel {
Known::Fixed(true) => (coord, fb.binary(BinOp::FDiv, coord, size)?),
Known::Fixed(false) => (texels, coord),
Known::Run(pixel) => {
let normal = fb.binary(BinOp::FDiv, coord, size)?;
let b2 = bvec2(fb)?;
let pixel2 = fb.composite_construct(b2, &[pixel, pixel])?;
(
fb.select(pixel2, coord, texels)?,
fb.select(pixel2, normal, coord)?,
)
}
};
if let Some(offset) = s.offset.as_deref() {
let lanes: Vec<SValue> = offset
.iter()
.map(|&k| t.f(fb, k as f32))
.collect::<BResult<_>>()?;
let k = fb.composite_construct(vec2, &lanes)?;
texels = fb.binary(BinOp::FAdd, texels, k)?;
let moved = fb.binary(BinOp::FDiv, k, size)?;
normal = fb.binary(BinOp::FAdd, normal, moved)?;
}
// A nearest sample's luma texel, clamped to the edge, at its centre.
let nearest = |fb: &mut FunctionBuilder<'_>| -> BResult<SValue> {
let floor = fb.glsl(GlslOp::Floor, &[texels])?;
let zero = t.f(fb, 0.0)?;
let zero = fb.composite_construct(vec2, &[zero, zero])?;
let one = t.f(fb, 1.0)?;
let one = fb.composite_construct(vec2, &[one, one])?;
let last = fb.binary(BinOp::FSub, size, one)?;
let texel = fb.glsl(GlslOp::FClamp, &[floor, zero, last])?;
let half = t.f(fb, 0.5)?;
let half = fb.composite_construct(vec2, &[half, half])?;
let centre = fb.binary(BinOp::FAdd, texel, half)?;
fb.binary(BinOp::FDiv, centre, size)
};
let at = match linear {
Known::Fixed(true) => normal,
Known::Fixed(false) => nearest(fb)?,
Known::Run(linear) => {
let centre = nearest(fb)?;
let b2 = bvec2(fb)?;
let linear2 = fb.composite_construct(b2, &[linear, linear])?;
fb.select(linear2, normal, centre)?
}
};
let lod = t.f(fb, 0.0)?;
let ops = ImageOperands {
lod: Some(lod),
..ImageOperands::default()
};
let x = fb.sample(sampled, at, None, false, &ops)?;
// A `half` result is held widened, rounded to a `half` as every sampled texel's is
// (`texture::held_texel`).
match s.half {
false => Ok(x),
true => {
let half = crate::lower::arith::Form {
held: crate::lower::arith::Held::Float(crate::lower::arith::FloatFmt::Half),
lanes: 4,
};
crate::lower::arith::narrow::round_texel(fb, half, x)
}
}
}
/// A value fixed as the module is made, or known only as it runs.
#[derive(Clone, Copy)]
enum Known {
Fixed(bool),
Run(SValue),
}
/// The `bvec2` type.
fn bvec2(fb: &mut FunctionBuilder<'_>) -> BResult<TypeId> {
let b = fb.module().ty(SType::Bool)?;
fb.module().ty(SType::Vector { elem: b, len: 2 })
}
/// The texel of in-place sample `s` in the open block, with its status word 0 (module docs).
pub(crate) fn emit(
cx: &mut EmitCx<'_>,
@@ -453,6 +581,10 @@ pub(crate) fn emit(
else {
return Err(cx.fail(format!("texture slot {} is not planned", s.texture)));
};
if decl.planes_sampler.is_some() {
let x = device_sample(cx, fb, s, slot, (coord, img))?;
return crate::lower::texture::with_word(cx, fb, &s.result, x, None);
}
let (planes, size) = prepare(cx, fb, slot)?;
let t = Tys::new(fb)?;
let tt = T::new(fb)?;
@@ -1190,6 +1190,7 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> {
extended: None,
x_channel: false,
in_place: false,
planes_sampler: None,
};
let symbol = ResourceSlot {
stage: cx.stage,
@@ -1071,6 +1071,7 @@ fn select_in_place(
return Err(cx.invariant("an unplanned texture slot"));
};
s.in_place.samplers |= samplers;
s.in_place.device_blocked |= !device_takes(&sample);
if !variant {
return Ok(None);
}
@@ -1098,6 +1099,23 @@ fn select_in_place(
Ok(Some(sample))
}
/// Whether the device's own sampler Y′CbCr conversion of a planes image takes in-place sample `s`
/// (`LoweringInputs::ycbcr_planes_sampled`, `super::in_place`'s **The device's sampler**): a
/// constexpr sampler that addresses no border on either plane axis (a 4:2:0 texture samples every
/// other mode as clamp-to-edge, as that sampler does), or a runtime sampler, whose bound word the
/// binder holds to the same (`bind::plan::slots::planes_word`); and no texel offset Metal places
/// by a parent's size.
fn device_takes(s: &super::in_place::Sample) -> bool {
use super::bicubic::TapAddress;
let border = match &s.state {
super::extended::State::Constant { address, .. } => {
address.iter().any(|m| matches!(m, TapAddress::Border))
}
super::extended::State::Slot { .. } => false,
};
!border && !s.offset_base
}
/// Sampling call `call` of texture slot `index` through `sampler` as the in-place form reads it
/// (`in_place`), with the runtime sampler slots it reads (bit `n` `[[sampler(n)]]`); `None` where
/// the form does not: anything but a 2D texture's sample or gradient sample without comparison,
+14 -5
View File
@@ -1120,11 +1120,20 @@ pub fn declare(
}
None => image,
};
let g = mb.resource(
crate::pipeline::sym::ResourceSlot::metal(s.slot),
crate::spirv::ir::StorageClass::UniformConstant,
ty,
)?;
// A planes image's slot is the combined image sampler of the device's conversion
// (`ResourceKind::YCbCrPlanes`).
let (ty, symbol) = match decl.planes_sampler {
Some(sampler) => (
mb.ty(SType::SampledImage { image: ty })?,
crate::pipeline::sym::ResourceSlot {
stage: s.slot.stage,
kind: crate::pipeline::sym::ResourceKind::YCbCrPlanes(sampler),
index: s.slot.index,
},
),
None => (ty, crate::pipeline::sym::ResourceSlot::metal(s.slot)),
};
let g = mb.resource(symbol, crate::spirv::ir::StorageClass::UniformConstant, ty)?;
if s.volatile && volatile_decorated(plan) {
mb.volatile(g)?;
}
@@ -102,6 +102,10 @@ pub struct InPlaceReads {
pub blocked: bool,
/// The runtime sampler slots the slot's samples read, bit `n` `[[sampler(n)]]`.
pub samplers: u32,
/// A sample the device's own sampler Y′CbCr conversion does not take
/// (`LoweringInputs::ycbcr_planes_sampled`): one through a constexpr sampler that addresses a
/// border, or one that places a texel offset by a parent's size.
pub device_blocked: bool,
}
/// The `OpTypeImage` a slot is declared as, and the conversion a storage image's class needs.
@@ -133,6 +137,11 @@ pub struct ImageDecl {
/// (`LoweringInputs::ycbcr_in_place`): the image is the planes' uniform texel buffer of
/// unsigned codes (`sampler::in_place`), the texture's size its push field's.
pub in_place: bool,
/// The slot's variant samples those planes as an image through the device's own sampler
/// Y′CbCr conversion (`LoweringInputs::ycbcr_planes_sampled`): the slot is a combined image
/// sampler of a sampled 2D `float` image (`ResourceKind::YCbCrPlanes`), whose immutable
/// sampler bakes the conversion; `in_place` holds, so its size is still the push field's.
pub planes_sampler: Option<crate::bind::YCbCrPlanesSampler>,
}
impl ImageDecl {
@@ -555,6 +564,7 @@ fn declare_heap(
extended: None,
x_channel: false,
in_place: false,
planes_sampler: None,
};
Ok((class, decl))
}
@@ -1001,6 +1011,33 @@ fn declare_slot(
) -> Result<ImageDecl, Error> {
let images = &cx.profile.fields().images;
let storage = s.storage();
// A slot that samples its texture's planes as an image through the device's own sampler
// Y′CbCr conversion is a combined image sampler of a 2D `float` image, with the field of the
// planes' words for its size (`sampler::in_place`).
if let Some(&sampler) = cx.inputs.ycbcr_planes_sampled.get(&s.slot) {
if !cx.inputs.ycbcr_in_place.contains(&s.slot) {
return Err(cx.invariant("a planes image's slot outside its in-place variant"));
}
push.push(PushField::YCbCrInPlace(s.slot));
counts.sampled_images = counts.sampled_images.saturating_add(1);
counts.samplers = counts.samplers.saturating_add(1);
return Ok(ImageDecl {
dim: Dim::D2,
arrayed: false,
multisampled: false,
depth: false,
usage: ImageUsage::Sampled,
format: crate::spv::ImageFormat::Unknown,
texel: TexelClass::Float,
cube_as_array: false,
class: StorageImageClass::Identity,
level_views: None,
extended: None,
x_channel: false,
in_place: true,
planes_sampler: Some(sampler),
});
}
// A slot under its in-place variant is the uniform texel buffer of its texture's planes, of
// unsigned codes, with the field of their words (`sampler::in_place`).
if cx.inputs.ycbcr_in_place.contains(&s.slot) {
@@ -1020,6 +1057,7 @@ fn declare_slot(
extended: None,
x_channel: false,
in_place: true,
planes_sampler: None,
});
}
// A slot bound in an extended-range format holds its raw texels in an unsigned integer
@@ -1149,6 +1187,7 @@ fn declare_slot(
extended,
x_channel,
in_place: false,
planes_sampler: None,
})
}
@@ -1250,10 +1289,16 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> {
cx.invariant("an in-place texture slot whose accesses the form does not read")
);
}
if s.in_place.device_blocked && cx.inputs.ycbcr_planes_sampled.contains_key(&s.slot) {
return Err(cx.invariant(
"a planes image's texture slot with a sample the device's sampler does not take",
));
}
if reads {
facts.push(RuntimeFact::YCbCrInPlace {
slot: s.slot,
samplers: s.in_place.samplers,
device: !s.in_place.device_blocked,
});
}
}
+1
View File
@@ -390,6 +390,7 @@ pub fn vk_sampler(
border_color,
reduction: vk::SamplerReductionMode::WEIGHTED_AVERAGE,
border_components: None,
ycbcr: None,
})
}
@@ -166,6 +166,22 @@ mod serde_round_trips {
assert_eq!(&back, value, "{json}");
}
/// A planes image's conversion: an 8-bit 4:2:0 surface's, full range, BT.709.
fn planes_sampler() -> crate::bind::YCbCrPlanesSampler {
use crate::bind::{YCbCrCodes, YCbCrInPlace, YCbCrMatrix, YCbCrPlanes, YCbCrRange};
let codes = metal::format::ycbcr_format(metal::PixelFormat::YCBCR84202P)
.and_then(YCbCrCodes::of)
.expect("codes");
let planes = YCbCrPlanes::new(
[8, 4],
[0, 16],
[64, 16],
(YCbCrRange::Full, YCbCrMatrix::Bt709),
codes,
);
YCbCrInPlace::of(&planes).expect("in place").sampler()
}
fn buffer(index: u32) -> SlotRef {
slot(Stage::Fragment, SlotClass::Buffer, index)
}
@@ -197,6 +213,10 @@ mod serde_round_trips {
storage_view_slots: BTreeSet::from([buffer(3)]),
srgb_textures: BTreeSet::from([slot(Stage::Kernel, SlotClass::Texture, 4)]),
ycbcr_in_place: BTreeSet::from([slot(Stage::Kernel, SlotClass::Texture, 7)]),
ycbcr_planes_sampled: BTreeMap::from([(
slot(Stage::Kernel, SlotClass::Texture, 7),
planes_sampler(),
)]),
flat_grid: true,
replay_bindings: true,
merged_draws: true,
@@ -327,6 +347,10 @@ mod serde_round_trips {
crate::pipeline::SnapshotForm::Half,
)]),
ycbcr_in_place: BTreeSet::from([slot(Stage::Fragment, SlotClass::Texture, 9)]),
ycbcr_planes_sampled: BTreeMap::from([(
slot(Stage::Fragment, SlotClass::Texture, 9),
planes_sampler(),
)]),
viewport_index_varying: true,
// An emulated post-tessellation vertex function's state.
tessellation: Some(crate::pipeline::TessellationDescriptor {
@@ -214,6 +214,11 @@ pub fn function_key(
.bytes(format!("{:?}", inputs.ycbcr_in_place).as_bytes());
}
// Appended only when set, as `storage_view_slots`.
if !inputs.ycbcr_planes_sampled.is_empty() {
h.bytes(b"ycbcr-planes-sampled")
.bytes(format!("{:?}", inputs.ycbcr_planes_sampled).as_bytes());
}
// Appended only when set, as `storage_view_slots`.
if !inputs.extended_range.is_empty() {
h.bytes(b"extended-range")
.bytes(format!("{:?}", inputs.extended_range).as_bytes());
@@ -675,6 +675,7 @@ fn the_inputs_encoding_is_the_earlier_derived_debug() {
.replace(", srgb_textures: {}", "")
.replace(", snapshot_textures: {}", "")
.replace(", ycbcr_in_place: {}", "")
.replace(", ycbcr_planes_sampled: {}", "")
.replace(", viewport_index_varying: false", "")
.replace(", max_call_stack_depth: None", "")
.replace(", flat_grid: false", "")
+11 -2
View File
@@ -727,8 +727,17 @@ pub enum RuntimeFact {
/// which the slot's one binding is the planes' texel buffer (`WriteSource::YCbCrInPlace`) and
/// every access of it reads the codes and converts them as Metal does, its words in the slot's
/// push field (`PushField::YCbCrInPlace`). Elsewhere the slot binds the texture's image as
/// before.
YCbCrInPlace { slot: SlotRef, samplers: u32 },
/// before. `device`: every sample of the slot is one the device's own sampler Y′CbCr
/// conversion takes (none addresses a border through a constexpr sampler or places a texel
/// offset by a parent's size): where the bound texture's planes are also held as an image it
/// samples (`TextureShape::Texture::ycbcr_planes_sampler`) and each runtime sampler addresses
/// no border on either axis, the slot samples that image instead
/// (`VariantKey::ycbcr_planes_sampled`, `bind::YCbCrPlanesSampler`).
YCbCrInPlace {
slot: SlotRef,
samplers: u32,
device: bool,
},
}
/// What one compile made of a slot of a `RuntimeFact::UniformViewRange`.
@@ -82,6 +82,12 @@ pub enum BindingSource {
texture: SlotRef,
sampler: CombinedSampler,
},
/// The planes of the two-plane YCbCr texture bound at a Metal `[[texture(n)]]` slot, held as
/// an image the device's own sampler Y′CbCr conversion samples
/// (`ResourceKind::YCbCrPlanes`): one combined descriptor, its image the planes' image viewed
/// with the conversion, its sampler the binding's `immutable_sampler`
/// (`vk::SamplerDesc::ycbcr`).
YCbCrPlanes(SlotRef),
/// A binding the translator adds for one stage (argument table, root or handle table,
/// constant blob).
Synthetic {
+10 -3
View File
@@ -688,16 +688,19 @@ fn binding_source(slot: ResourceSlot) -> BindingSource {
},
ResourceKind::ExtendedShadow(color) => BindingSource::ExtendedShadow(color),
ResourceKind::SnapshotTexels(texture) => BindingSource::SnapshotTexels(texture),
ResourceKind::YCbCrPlanes(_) => BindingSource::YCbCrPlanes(metal(SlotClass::Texture)),
}
}
/// The immutable sampler of binding `slot`: a combined image sampler's, heap sampler's, or
/// separate sampler's constexpr sampler, made for its use.
/// separate sampler's constexpr sampler, made for its use; a planes image's device conversion
/// (`ResourceKind::YCbCrPlanes`).
fn immutable_sampler(
slot: ResourceSlot,
p: &DeviceProfile,
) -> Result<Option<vk::SamplerDesc>, Error> {
let c = match slot.kind {
ResourceKind::YCbCrPlanes(sampler) => return Ok(Some(vk::SamplerDesc::ycbcr(sampler))),
ResourceKind::CombinedTextureSampler(c) => c,
ResourceKind::HeapSampler(sampler) | ResourceKind::SeparateSampler(sampler) => {
CombinedSampler::from_heap_index(sampler, slot.index)
@@ -818,8 +821,12 @@ fn layout(
)));
}
// A combined image sampler is exactly a `CombinedTextureSampler` symbol, which names
// its texture slot and its sampler.
let combined = matches!(d.slot.kind, ResourceKind::CombinedTextureSampler(_));
// its texture slot and its sampler, or a planes image's (`YCbCrPlanes`), which names
// its texture slot and the conversion its immutable sampler bakes.
let combined = matches!(
d.slot.kind,
ResourceKind::CombinedTextureSampler(_) | ResourceKind::YCbCrPlanes(_)
);
if combined != (d.ty == vk::DescriptorType::COMBINED_IMAGE_SAMPLER) {
return Err(Error::Internal(InternalError::new(
InternalKind::Invariant,
@@ -175,6 +175,17 @@ pub struct LoweringInputs {
/// planes in place (`ProfileFields::ycbcr_in_place`).
#[cfg_attr(feature = "serde", serde(default))]
pub ycbcr_in_place: BTreeSet<SlotRef>,
/// Slots of [`ycbcr_in_place`](Self::ycbcr_in_place) bound to a texture whose planes are also
/// held as an image the device's own sampler Y′CbCr conversion samples, each with that
/// conversion (`VariantKey::ycbcr_planes_sampled`): each is declared as a combined image
/// sampler whose immutable sampler is the conversion (`ResourceKind::YCbCrPlanes`), and its
/// samples are the device's at level 0 (`bind::YCbCrPlanesSampler`); its size queries read the
/// push field as the in-place form's do.
#[cfg_attr(
feature = "serde",
serde(default, with = "crate::pipeline::serde_pairs")
)]
pub ycbcr_planes_sampled: BTreeMap<SlotRef, crate::bind::YCbCrPlanesSampler>,
/// The fragment function's render pipeline has a vertex function that writes
/// `[[viewport_array_index]]`. That function stores `ViewportIndex` as 0 for an index at or
/// past the draw's viewport count, where Metal draws through viewport 0 and its fragment
+6
View File
@@ -420,6 +420,12 @@ pub enum ResourceKind {
/// `R32G32B32A32_UINT` 2D storage image covering the draw's render area, each texel the bits
/// of the four values a fetch of the texture's level 0 there returned.
SnapshotTexels(u32),
/// The planes of the two-plane YCbCr texture bound at the stage's texture slot
/// `ResourceSlot::index`, held as an image of the multi-planar format that the device's own
/// sampler Y′CbCr conversion samples (`LoweringInputs::ycbcr_planes_sampled`): a combined
/// image sampler whose immutable sampler is the device's conversion of this
/// (`vk::SamplerDesc::ycbcr`), whose image the consumer views with the same conversion.
YCbCrPlanes(crate::bind::YCbCrPlanesSampler),
}
/// What a bound acceleration structure holds: the binder binds a top-level structure, so a
@@ -552,9 +552,15 @@ impl ModuleBuilder {
})
);
let ok = ok && subpass == matches!(sym.kind, ResourceKind::InputAttachment(_));
// A combined image sampler is exactly one `OpTypeSampledImage`.
// A combined image sampler is exactly one `OpTypeSampledImage`: a texture and sampler's,
// or a planes image's through the device's conversion.
let combined = matches!(self.types.get(ty)?, Type::SampledImage { .. });
let ok = ok && combined == matches!(sym.kind, ResourceKind::CombinedTextureSampler(_));
let ok = ok
&& combined
== matches!(
sym.kind,
ResourceKind::CombinedTextureSampler(_) | ResourceKind::YCbCrPlanes(_)
);
// An acceleration structure binding is exactly one acceleration structure.
let accel = matches!(self.types.get(ty)?, Type::AccelerationStructure);
let ok = ok && accel == matches!(sym.kind, ResourceKind::AccelerationStructure(_));
@@ -118,9 +118,9 @@ pub fn own_pixel_textures(m: &TypedModule, meter: &mut Meter) -> Result<Vec<u32>
}
GlobalKind::Resource(slot) => {
let texture = match slot.kind {
ResourceKind::Texture | ResourceKind::CombinedTextureSampler(_) => {
Some(slot.index)
}
ResourceKind::Texture
| ResourceKind::CombinedTextureSampler(_)
| ResourceKind::YCbCrPlanes(_) => Some(slot.index),
ResourceKind::SeparateTexture(_) => slot.separate_texture_of().map(|(t, _)| t),
_ => None,
};
@@ -116,7 +116,9 @@ fn reach(m: &TypedModule, own: &[u32], n: usize) -> Result<Vec<u32>, Error> {
for g in m.globals() {
if let GlobalKind::Resource(slot) = &g.kind {
let texture = match slot.kind {
ResourceKind::Texture | ResourceKind::CombinedTextureSampler(_) => Some(slot.index),
ResourceKind::Texture
| ResourceKind::CombinedTextureSampler(_)
| ResourceKind::YCbCrPlanes(_) => Some(slot.index),
ResourceKind::SeparateTexture(_) => slot.separate_texture_of().map(|(t, _)| t),
_ => None,
};
@@ -336,7 +338,9 @@ fn copies_alone(m: &TypedModule, slots: &[u32], n: usize) -> Result<bool, Error>
for g in m.globals() {
if let GlobalKind::Resource(slot) = &g.kind {
let texture = match slot.kind {
ResourceKind::Texture | ResourceKind::CombinedTextureSampler(_) => Some(slot.index),
ResourceKind::Texture
| ResourceKind::CombinedTextureSampler(_)
| ResourceKind::YCbCrPlanes(_) => Some(slot.index),
ResourceKind::SeparateTexture(_) => slot.separate_texture_of().map(|(t, _)| t),
_ => None,
};
@@ -730,6 +730,7 @@ fn a_slot_states_the_in_place_form_where_it_reads_only_it() {
let fact = |samplers| RuntimeFact::YCbCrInPlace {
slot: TEXTURE,
samplers,
device: true,
};
let reads = [
(
@@ -772,7 +773,9 @@ fn a_slot_states_the_in_place_form_where_it_reads_only_it() {
let (plan, _) = typed_module_with(&bc, "k", &p, &inputs(false))
.unwrap_or_else(|e| panic!("{what}: {e}"));
let stated = plan.facts.iter().find_map(|f| match f {
RuntimeFact::YCbCrInPlace { slot, samplers } if *slot == TEXTURE => Some(*samplers),
RuntimeFact::YCbCrInPlace { slot, samplers, .. } if *slot == TEXTURE => {
Some(*samplers)
}
_ => None,
});
assert_eq!(stated, samplers.filter(|_| takes), "{what}");
@@ -784,3 +787,120 @@ fn a_slot_states_the_in_place_form_where_it_reads_only_it() {
}
}
}
/// Under the planes-image variant (`LoweringInputs::ycbcr_planes_sampled`) the slot is one
/// combined image sampler of the device's conversion (`ResourceKind::YCbCrPlanes`), every sample
/// is the device's `OpImageSampleExplicitLod` at level 0 with no offset operand
/// (`VUID-RuntimeSpirv-ConstOffset-10718`), and the module is valid, through a constexpr sampler
/// (nearest and linear, normalized and pixel coordinates, with a texel offset on edge axes) and a
/// runtime one. A sample through a border mode, or with an offset on an axis that repeats, states
/// the in-place fact without `device`, so no plan takes the variant for it.
#[test]
fn a_planes_image_slot_samples_through_the_device_s_conversion() {
use crate::pipeline::interface::StageDescriptor;
use crate::vk;
let codes = ycbcr_format(PixelFormat::YCBCR84202P)
.and_then(YCbCrCodes::of)
.expect("codes");
let planes = YCbCrPlanes::new(
[8, 4],
[0, 16],
[64, 16],
(YCbCrRange::Video, YCbCrMatrix::Bt709),
codes,
);
let sampler = YCbCrInPlace::of(&planes).expect("in place").sampler();
let device_inputs = || {
let mut i = inputs(true);
i.ycbcr_planes_sampled.insert(TEXTURE, sampler);
i
};
let nearest = sampler_words(0, 0, 1, false, 0);
let device_state = |plan: &Plan| {
plan.facts.iter().find_map(|f| match f {
RuntimeFact::YCbCrInPlace { slot, device, .. } if *slot == TEXTURE => Some(*device),
_ => None,
})
};
let taken = [
("device linear", Some(linear(1, false, 0)), (0, 0)),
("device nearest", Some(nearest), (0, 0)),
("device pixel", Some(linear(1, true, 0)), (0, 0)),
("device offset", Some(linear(1, false, 0)), (1, -2)),
("device runtime", None, (0, 0)),
];
for (name, sampler_words, offset) in taken {
for half in [false, true] {
let form = Form::Plain { offset };
let Some(bc) = assemble(name, &kernel_of(sampler_words, form, !half)) else {
return;
};
for (stem, p) in [("lavapipe", lavapipe()), ("moltenvk-m3", m3())] {
let what = format!("{name} half={half} on {stem}");
let (plan, _) = typed_module_with(&bc, "k", &p, &inputs(true))
.unwrap_or_else(|e| panic!("{what}: {e}"));
assert_eq!(device_state(&plan), Some(true), "{what}");
let a = compile_with(&bc, "k", &p, &device_inputs())
.unwrap_or_else(|e| panic!("{what}, planes image: {e}"));
let want = StageDescriptor::new(
ResourceSlot {
stage: Stage::Kernel,
kind: ResourceKind::YCbCrPlanes(sampler),
index: 0,
},
vk::DescriptorType::COMBINED_IMAGE_SAMPLER,
1,
);
assert!(
a.interface.descriptors.contains(&want),
"{what}: {:?}",
a.interface.descriptors
);
assert!(
a.facts.iter().any(|f| matches!(
f,
RuntimeFact::YCbCrInPlace { slot, device: true, .. } if *slot == TEXTURE
)),
"{what}: the variant states the same fact"
);
let (_, words) =
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: {e}"));
// Every sample: `OpImageSampleExplicitLod` (88) whose operands are `Lod` (0x2)
// alone.
let mut samples = 0;
let mut at = 5;
while let Some(&first) = words.get(at) {
let (count, op) = ((first >> 16) as usize, first & 0xffff);
assert!(count > 0, "{what}: a zero-length instruction");
if op == 88 {
samples += 1;
assert_eq!(words.get(at + 5), Some(&0x2), "{what}: operands");
assert_eq!(count, 7, "{what}: the Lod operand alone");
}
assert!(
!(87..=94).contains(&op) || op == 88,
"{what}: another sample opcode {op}"
);
at += count;
}
assert_eq!(samples, 1, "{what}");
}
}
}
// Through a border mode, or with an offset on an axis that repeats: no device sample.
let kept = [
("device border", Some(linear(0, false, 0)), (0, 0)),
("device repeat offset", Some(linear(2, false, 0)), (1, 0)),
];
for (name, sampler_words, offset) in kept {
let Some(bc) = assemble(
name,
&kernel_of(sampler_words, Form::Plain { offset }, false),
) else {
return;
};
let (plan, _) = typed_module_with(&bc, "k", &lavapipe(), &inputs(true))
.unwrap_or_else(|e| panic!("{name}: {e}"));
assert_eq!(device_state(&plan), Some(false), "{name}");
}
}
+36
View File
@@ -233,6 +233,40 @@ pub struct SamplerDesc {
/// mapping. Never set for a layout's immutable sampler.
#[cfg_attr(feature = "serde", serde(default))]
pub border_components: Option<ComponentMapping>,
/// The device's sampler Y′CbCr conversion the sampler enables
/// (`VkSamplerYcbcrConversionInfo`), a planes image's ([`SamplerDesc::ycbcr`],
/// `ResourceKind::YCbCrPlanes`): the consumer makes the conversion of this (its format, the
/// matrix's model, the range, midpoint chroma offsets and a linear chroma filter) and chains it,
/// and views the image with the same conversion. Only a layout's immutable sampler sets it.
#[cfg_attr(feature = "serde", serde(default))]
pub ycbcr: Option<crate::bind::YCbCrPlanesSampler>,
}
impl SamplerDesc {
/// The immutable sampler of a planes image's binding (`ResourceKind::YCbCrPlanes`): the
/// device's conversion `ycbcr`, through a linear filter (a conversion's linear chroma filter
/// asks it, `VUID-VkSamplerCreateInfo-minFilter-01645`), clamped to the edge on every axis, no
/// anisotropy or comparison and the weighted average (`VUID-VkSamplerCreateInfo-addressModeU-
/// 01646`, `VUID-VkSamplerCreateInfo-None-01647`), level 0 alone.
pub fn ycbcr(ycbcr: crate::bind::YCbCrPlanesSampler) -> SamplerDesc {
SamplerDesc {
mag_filter: Filter::LINEAR,
min_filter: Filter::LINEAR,
mipmap_mode: SamplerMipmapMode::NEAREST,
address_mode_u: SamplerAddressMode::CLAMP_TO_EDGE,
address_mode_v: SamplerAddressMode::CLAMP_TO_EDGE,
address_mode_w: SamplerAddressMode::CLAMP_TO_EDGE,
mip_lod_bias: 0.0,
max_anisotropy: None,
compare: None,
min_lod: 0.0,
max_lod: 0.0,
border_color: BorderColor::FLOAT_TRANSPARENT_BLACK,
reduction: SamplerReductionMode::WEIGHTED_AVERAGE,
border_components: None,
ycbcr: Some(ycbcr),
}
}
}
/// A [`SamplerDesc`] with floats as bit patterns, so equality is total.
@@ -248,6 +282,7 @@ struct SamplerKey {
border_color: BorderColor,
reduction: SamplerReductionMode,
border_components: Option<ComponentMapping>,
ycbcr: Option<crate::bind::YCbCrPlanesSampler>,
}
impl SamplerDesc {
@@ -267,6 +302,7 @@ impl SamplerDesc {
border_color: self.border_color,
reduction: self.reduction,
border_components: self.border_components,
ycbcr: self.ycbcr,
}
}
}
+2
View File
@@ -210,6 +210,7 @@ fn sampler_desc_equality_is_total() {
border_color: BorderColor::FLOAT_TRANSPARENT_BLACK,
reduction: SamplerReductionMode::WEIGHTED_AVERAGE,
border_components: None,
ycbcr: None,
};
assert_eq!(desc, desc);
let set: HashSet<SamplerDesc> = [desc, desc].into_iter().collect();
@@ -222,6 +223,7 @@ fn sampler_desc_equality_is_total() {
// A sampler made for one view mapping is another sampler.
let mapped = SamplerDesc {
border_components: Some(ComponentMapping::IDENTITY),
ycbcr: None,
..desc
};
assert_ne!(desc, mapped);
+42 -2
View File
@@ -70,6 +70,12 @@ assoc-const metal2vulkan::bind::BlockDecodeModule::TEXELS_BINDING pub const TEXE
assoc-const metal2vulkan::bind::ChromaDecode::ALL pub const ALL: [ChromaDecode; 2]
assoc-const metal2vulkan::bind::ChromaDecode::BLOCK_BYTES pub const BLOCK_BYTES: u32
assoc-const metal2vulkan::bind::ChromaDecode::TEXEL_BYTES pub const TEXEL_BYTES: u32
assoc-const metal2vulkan::bind::ChromaSampleModule::LOCAL_SIZE pub const LOCAL_SIZE: u32
assoc-const metal2vulkan::bind::ChromaSampleModule::PAIRS_BINDING pub const PAIRS_BINDING: u32
assoc-const metal2vulkan::bind::ChromaSampleModule::SET pub const SET: u32
assoc-const metal2vulkan::bind::ChromaSampleModule::SHAPE_BINDING pub const SHAPE_BINDING: u32
assoc-const metal2vulkan::bind::ChromaSampleModule::SHAPE_WORDS pub const SHAPE_WORDS: u32
assoc-const metal2vulkan::bind::ChromaSampleModule::TEXELS_BINDING pub const TEXELS_BINDING: u32
assoc-const metal2vulkan::bind::ColorResolveModules::SET pub const SET: u32
assoc-const metal2vulkan::bind::ColorResolveModules::SOURCE_BINDING pub const SOURCE_BINDING: u32
assoc-const metal2vulkan::bind::DepthSplitModule::DESTINATION_BINDING pub const DESTINATION_BINDING: u32
@@ -529,6 +535,12 @@ assoc-const-value metal2vulkan::bind::BlockDecodeModule::TEXELS_BINDING 2
assoc-const-value metal2vulkan::bind::ChromaDecode::ALL [ChromaDecode::Gbgr, ChromaDecode::Bgrg]
assoc-const-value metal2vulkan::bind::ChromaDecode::BLOCK_BYTES 4
assoc-const-value metal2vulkan::bind::ChromaDecode::TEXEL_BYTES 4
assoc-const-value metal2vulkan::bind::ChromaSampleModule::LOCAL_SIZE 8
assoc-const-value metal2vulkan::bind::ChromaSampleModule::PAIRS_BINDING 0
assoc-const-value metal2vulkan::bind::ChromaSampleModule::SET 0
assoc-const-value metal2vulkan::bind::ChromaSampleModule::SHAPE_BINDING 1
assoc-const-value metal2vulkan::bind::ChromaSampleModule::SHAPE_WORDS 5
assoc-const-value metal2vulkan::bind::ChromaSampleModule::TEXELS_BINDING 2
assoc-const-value metal2vulkan::bind::ColorResolveModules::SET 0
assoc-const-value metal2vulkan::bind::ColorResolveModules::SOURCE_BINDING 0
assoc-const-value metal2vulkan::bind::DepthSplitModule::DESTINATION_BINDING 1
@@ -2423,6 +2435,8 @@ field metal2vulkan-runtime::WorkCounts.calibration_deviation_most pub calibratio
field metal2vulkan-runtime::WorkCounts.calibration_disagreements pub calibration_disagreements: u64
field metal2vulkan-runtime::WorkCounts.calibration_readings pub calibration_readings: u64
field metal2vulkan-runtime::WorkCounts.calibrations pub calibrations: u64
field metal2vulkan-runtime::WorkCounts.chroma_device_decodes pub chroma_device_decodes: u64
field metal2vulkan-runtime::WorkCounts.chroma_device_twins pub chroma_device_twins: u64
field metal2vulkan-runtime::WorkCounts.color_group_draws_skipped pub color_group_draws_skipped: u64
field metal2vulkan-runtime::WorkCounts.color_group_passes pub color_group_passes: u64
field metal2vulkan-runtime::WorkCounts.color_group_twins pub color_group_twins: u64
@@ -2860,6 +2874,11 @@ field metal2vulkan-runtime::WorkCounts.ycbcr_images_kept_reach pub ycbcr_images_
field metal2vulkan-runtime::WorkCounts.ycbcr_images_kept_swizzle pub ycbcr_images_kept_swizzle: u64
field metal2vulkan-runtime::WorkCounts.ycbcr_images_kept_view pub ycbcr_images_kept_view: u64
field metal2vulkan-runtime::WorkCounts.ycbcr_planes_bound pub ycbcr_planes_bound: u64
field metal2vulkan-runtime::WorkCounts.ycbcr_planes_images pub ycbcr_planes_images: u64
field metal2vulkan-runtime::WorkCounts.ycbcr_planes_images_bound pub ycbcr_planes_images_bound: u64
field metal2vulkan-runtime::WorkCounts.ycbcr_planes_images_kept_conversion pub ycbcr_planes_images_kept_conversion: u64
field metal2vulkan-runtime::WorkCounts.ycbcr_planes_images_kept_layout pub ycbcr_planes_images_kept_layout: u64
field metal2vulkan-runtime::WorkCounts.ycbcr_planes_images_kept_memory pub ycbcr_planes_images_kept_memory: u64
field metal2vulkan-runtime::WorkCounts.ycbcr_refreshes pub ycbcr_refreshes: u64
field metal2vulkan-runtime::WorkCounts.ycbcr_textures_in_place pub ycbcr_textures_in_place: u64
field metal2vulkan-runtime::WorkCounts.ycbcr_whole_conversions pub ycbcr_whole_conversions: u64
@@ -2986,6 +3005,8 @@ field metal2vulkan::bind::BufferRange.offset pub offset: u64
field metal2vulkan::bind::BufferRange.range pub range: u64
field metal2vulkan::bind::ByteRange.len pub len: u64
field metal2vulkan::bind::ByteRange.offset pub offset: u64
field metal2vulkan::bind::ChromaSampleModule.requirements pub requirements: Requirements
field metal2vulkan::bind::ChromaSampleModule.spirv pub spirv: Arc<[u32]>
field metal2vulkan::bind::ColorResolveModules.fragment pub fragment: Arc<[u32]>
field metal2vulkan::bind::ColorResolveModules.requirements pub requirements: Requirements
field metal2vulkan::bind::ColorResolveModules.vertex pub vertex: Arc<[u32]>
@@ -3550,6 +3571,7 @@ field metal2vulkan::cache::VariantKey.swizzled_storage pub swizzled_storage: BTr
field metal2vulkan::cache::VariantKey.viewport_compensation pub viewport_compensation: Option<crate::pipeline::ViewportCompensation>
field metal2vulkan::cache::VariantKey.window_depth_varying pub window_depth_varying: bool
field metal2vulkan::cache::VariantKey.ycbcr_in_place pub ycbcr_in_place: BTreeSet<SlotRef>
field metal2vulkan::cache::VariantKey.ycbcr_planes_sampled pub ycbcr_planes_sampled: BTreeMap<SlotRef, crate::bind::YCbCrPlanesSampler>
field metal2vulkan::cache::VariantKey.zeroed_colors pub zeroed_colors: BTreeMap<u32, crate::metal::PixelFormat>
field metal2vulkan::device::AllocationLimits.max_buffer_size pub max_buffer_size: u64
field metal2vulkan::device::AllocationLimits.max_memory_allocation_size pub max_memory_allocation_size: u64
@@ -4124,6 +4146,7 @@ field metal2vulkan::pipeline::LoweringInputs.viewport_index_varying pub viewport
field metal2vulkan::pipeline::LoweringInputs.window_depth_varying pub window_depth_varying: bool
field metal2vulkan::pipeline::LoweringInputs.word_colors pub word_colors: BTreeMap<u32, metal::format::WordAttachment>
field metal2vulkan::pipeline::LoweringInputs.ycbcr_in_place pub ycbcr_in_place: BTreeSet<SlotRef>
field metal2vulkan::pipeline::LoweringInputs.ycbcr_planes_sampled pub ycbcr_planes_sampled: BTreeMap<SlotRef, crate::bind::YCbCrPlanesSampler>
field metal2vulkan::pipeline::LoweringInputs.zeroed_colors pub zeroed_colors: BTreeMap<u32, metal::PixelFormat>
field metal2vulkan::pipeline::MeshPipelineDescriptor.alpha_to_coverage pub alpha_to_coverage: bool
field metal2vulkan::pipeline::MeshPipelineDescriptor.alpha_to_one pub alpha_to_one: bool
@@ -4412,6 +4435,7 @@ field metal2vulkan::vk::SamplerDesc.min_lod pub min_lod: f32
field metal2vulkan::vk::SamplerDesc.mip_lod_bias pub mip_lod_bias: f32
field metal2vulkan::vk::SamplerDesc.mipmap_mode pub mipmap_mode: SamplerMipmapMode
field metal2vulkan::vk::SamplerDesc.reduction pub reduction: SamplerReductionMode
field metal2vulkan::vk::SamplerDesc.ycbcr pub ycbcr: Option<crate::bind::YCbCrPlanesSampler>
field metal2vulkan::vk::SpecializationMapEntry.constant_id pub constant_id: u32
field metal2vulkan::vk::SpecializationMapEntry.offset pub offset: u32
field metal2vulkan::vk::SpecializationMapEntry.size pub size: u32
@@ -4445,6 +4469,7 @@ fn metal2vulkan-runtime::sampler_border_color pub fn sampler_border_color(raw: u
fn metal2vulkan::ash_interop::sampler_create_info pub fn sampler_create_info<'a>(desc: &vk::SamplerDesc, reduction: &'a mut ash::vk::SamplerReductionModeCreateInfo<'static>, border: &'a mut ash::vk::SamplerBorderColorComponentMappingCreateInfoEXT<'static>) -> ash::vk::SamplerCreateInfo<'a>
fn metal2vulkan::bind::astc_decode_module pub fn astc_decode_module(device: &Device, decode: AstcDecode, texels: AstcTexels) -> Result<BlockDecodeModule, Error>
fn metal2vulkan::bind::chroma_decode_module pub fn chroma_decode_module(device: &Device, decode: ChromaDecode) -> Result<BlockDecodeModule, Error>
fn metal2vulkan::bind::chroma_sample_module pub fn chroma_sample_module(device: &Device) -> Result<ChromaSampleModule, Error>
fn metal2vulkan::bind::color_resolve_modules pub fn color_resolve_modules(device: &Device, format: ColorResolveFormat, samples: u32, source: ResolveSource, feature: Feature) -> Result<ColorResolveModules, Error>
fn metal2vulkan::bind::depth_split_module pub fn depth_split_module(device: &Device, form: DepthStandInForm, feature: Feature) -> Result<DepthSplitModule, Error>
fn metal2vulkan::bind::depth_stencil_copy_modules pub fn depth_stencil_copy_modules(device: &Device, copy: DepthStencilCopy, feature: Feature) -> Result<DepthStencilCopyModules, Error>
@@ -8209,9 +8234,11 @@ method metal2vulkan::bind::BoundTexture::shape pub fn shape(&self) -> TextureSha
method metal2vulkan::bind::ChromaDecode::block_extent pub fn block_extent(self) -> [u32; 2]
method metal2vulkan::bind::ChromaDecode::decode pub fn decode(self, pairs: &[u8], size: [u32; 3]) -> Vec<u8>
method metal2vulkan::bind::ChromaDecode::decode_into pub fn decode_into(self, pairs: &[u8], [width, height, depth]: [u32; 3], out: &mut [u8])
method metal2vulkan::bind::ChromaDecode::format pub fn format(self) -> Format
method metal2vulkan::bind::ChromaDecode::of pub fn of(pf: PixelFormat) -> Option<ChromaDecode>
method metal2vulkan::bind::ChromaDecode::texel_format pub fn texel_format(self) -> Format
method metal2vulkan::bind::ChromaDecode::texel_pixel_format pub fn texel_pixel_format(self) -> PixelFormat
method metal2vulkan::bind::ChromaSampleModule::shape pub fn shape(size: [u32; 2], first: u32, extent: [u32; 2]) -> [u8; Self::SHAPE_WORDS as usize * 4]
method metal2vulkan::bind::ColorResolveFormat::channels pub fn channels(self) -> [Option<ResolveChannel>; 4]
method metal2vulkan::bind::ColorResolveFormat::decodes_on_device pub fn decodes_on_device(self) -> bool
method metal2vulkan::bind::ColorResolveFormat::device_srgb pub fn device_srgb(self) -> ColorResolveFormat
@@ -8508,11 +8535,18 @@ method metal2vulkan::bind::YCbCrInPlace::element_bytes pub fn element_bytes(&sel
method metal2vulkan::bind::YCbCrInPlace::elements pub fn elements(&self) -> u64
method metal2vulkan::bind::YCbCrInPlace::format pub fn format(&self) -> vk::Format
method metal2vulkan::bind::YCbCrInPlace::of pub fn of(planes: &YCbCrPlanes) -> Option<YCbCrInPlace>
method metal2vulkan::bind::YCbCrInPlace::planes_sampler pub fn planes_sampler(&self) -> Option<YCbCrPlanesSampler>
method metal2vulkan::bind::YCbCrInPlace::sampler pub fn sampler(&self) -> YCbCrPlanesSampler
method metal2vulkan::bind::YCbCrInPlace::view_bytes pub fn view_bytes(&self) -> u64
method metal2vulkan::bind::YCbCrInPlace::with_planes_image pub fn with_planes_image(self) -> YCbCrInPlace
method metal2vulkan::bind::YCbCrInPlace::words pub fn words(&self) -> [u32; Self::WORDS]
method metal2vulkan::bind::YCbCrPlanes::chroma_size pub fn chroma_size(&self) -> [u32; 2]
method metal2vulkan::bind::YCbCrPlanes::conversion pub fn conversion(&self) -> YCbCrConversion
method metal2vulkan::bind::YCbCrPlanes::new pub fn new(size: [u32; 2], luma: [u32; 2], chroma: [u32; 2], (range, matrix): (YCbCrRange, YCbCrMatrix), codes: YCbCrCodes) -> YCbCrPlanes
method metal2vulkan::bind::YCbCrPlanesSampler::bits pub fn bits(self) -> u32
method metal2vulkan::bind::YCbCrPlanesSampler::format pub fn format(self) -> vk::Format
method metal2vulkan::bind::YCbCrPlanesSampler::matrix pub fn matrix(self) -> YCbCrMatrix
method metal2vulkan::bind::YCbCrPlanesSampler::range pub fn range(self) -> YCbCrRange
method metal2vulkan::bind::YCbCrRefreshModule::groups pub fn groups(words: u32) -> [u32; 2]
method metal2vulkan::bind::YCbCrRefreshModule::shape pub fn shape(firsts: [u32; 2], words: u32, groups: u32) -> [u8; 16]
method metal2vulkan::bind::YCbCrSampleModule::push pub fn push(size: [u32; 2], extent: [u32; 2]) -> [u8; Self::PUSH_BYTES as usize]
@@ -8996,6 +9030,7 @@ method metal2vulkan::vk::DescriptorType::from_raw pub fn from_raw(raw: u64) -> O
method metal2vulkan::vk::FormatBlock::vertex_alignment pub const fn vertex_alignment(self) -> Option<u32>
method metal2vulkan::vk::FormatExposure::exposed pub fn exposed(&self, api: super::ApiVersion, has_extension: impl Fn(&str) -> bool) -> bool
method metal2vulkan::vk::NumericFormat::numeric_type pub const fn numeric_type(self) -> NumericType
method metal2vulkan::vk::SamplerDesc::ycbcr pub fn ycbcr(ycbcr: crate::bind::YCbCrPlanesSampler) -> SamplerDesc
struct metal2vulkan-air::ConstValue #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct ConstValue
struct metal2vulkan-air::Decoded #[derive(Clone, Debug, PartialEq, Eq)] pub struct Decoded
struct metal2vulkan-air::DynamicLinks #[derive(Clone, Debug, Default)] pub struct DynamicLinks
@@ -9281,6 +9316,7 @@ struct metal2vulkan::bind::BoundsRunDraw #[derive(Clone, Copy, Debug, PartialEq,
struct metal2vulkan::bind::BufferExtent #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct BufferExtent
struct metal2vulkan::bind::BufferRange #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct BufferRange
struct metal2vulkan::bind::ByteRange #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ByteRange
struct metal2vulkan::bind::ChromaSampleModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct ChromaSampleModule
struct metal2vulkan::bind::ColorResolveFormat #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct ColorResolveFormat
struct metal2vulkan::bind::ColorResolveModules #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct ColorResolveModules
struct metal2vulkan::bind::CompensatedViewport #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq)] #[non_exhaustive] pub struct CompensatedViewport
@@ -9425,6 +9461,7 @@ struct metal2vulkan::bind::YCbCrConversion #[derive(Clone, Copy, Debug, PartialE
struct metal2vulkan::bind::YCbCrConvertModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct YCbCrConvertModule
struct metal2vulkan::bind::YCbCrInPlace #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] #[non_exhaustive] pub struct YCbCrInPlace
struct metal2vulkan::bind::YCbCrPlanes #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct YCbCrPlanes
struct metal2vulkan::bind::YCbCrPlanesSampler #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] #[non_exhaustive] pub struct YCbCrPlanesSampler
struct metal2vulkan::bind::YCbCrRefreshModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct YCbCrRefreshModule
struct metal2vulkan::bind::YCbCrSampleModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct YCbCrSampleModule
struct metal2vulkan::bind::YCbCrWriteModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct YCbCrWriteModule
@@ -12074,7 +12111,7 @@ variant metal2vulkan::bind::StatusWord::Status Status
variant metal2vulkan::bind::TessellationRecords::Exact Exact { records: u32 }
variant metal2vulkan::bind::TessellationRecords::Pool Pool
variant metal2vulkan::bind::TextureShape::Buffer Buffer { pixel_format: metal::PixelFormat, swizzle: metal::TextureSwizzleChannels }
variant metal2vulkan::bind::TextureShape::Texture Texture { texture_type: metal::TextureType, pixel_format: metal::PixelFormat, sample_count: u32, usage: metal::TextureUsage, mipmap_level_count: u32, sparse: bool, swizzle: metal::TextureSwizzleChannels, address_modes: metal::sampler::AddressModeMap, offset_base_axes: u8, ycbcr_in_place: bool }
variant metal2vulkan::bind::TextureShape::Texture Texture { texture_type: metal::TextureType, pixel_format: metal::PixelFormat, sample_count: u32, usage: metal::TextureUsage, mipmap_level_count: u32, sparse: bool, swizzle: metal::TextureSwizzleChannels, address_modes: metal::sampler::AddressModeMap, offset_base_axes: u8, ycbcr_in_place: bool, ycbcr_planes_sampler: Option<crate::bind::YCbCrPlanesSampler> }
variant metal2vulkan::bind::TileMapError::Region Region { level: u32, slice: u32, origin: [u32; 3], size: [u32; 3] }
variant metal2vulkan::bind::TileMapError::Shape Shape
variant metal2vulkan::bind::TileMapError::TextureType TextureType { texture_type: TextureType }
@@ -12131,6 +12168,7 @@ variant metal2vulkan::bind::WriteSource::TileAttachment TileAttachment { color_i
variant metal2vulkan::bind::WriteSource::TileMap TileMap { slot: SlotRef }
variant metal2vulkan::bind::WriteSource::TileMemory TileMemory { bytes: u64 }
variant metal2vulkan::bind::WriteSource::YCbCrInPlace YCbCrInPlace { slot: SlotRef }
variant metal2vulkan::bind::WriteSource::YCbCrPlanesImage YCbCrPlanesImage { slot: SlotRef }
variant metal2vulkan::bind::YCbCrMatrix::Bt2020 Bt2020
variant metal2vulkan::bind::YCbCrMatrix::Bt601 Bt601
variant metal2vulkan::bind::YCbCrMatrix::Bt709 Bt709
@@ -13256,6 +13294,7 @@ variant metal2vulkan::pipeline::BindingSource::Synthetic Synthetic { stage: Stag
variant metal2vulkan::pipeline::BindingSource::Texture Texture(SlotRef)
variant metal2vulkan::pipeline::BindingSource::TileAttachment TileAttachment(u32)
variant metal2vulkan::pipeline::BindingSource::TileMap TileMap(SlotRef)
variant metal2vulkan::pipeline::BindingSource::YCbCrPlanes YCbCrPlanes(SlotRef)
variant metal2vulkan::pipeline::BufferForm::Descriptor Descriptor(DescriptorView)
variant metal2vulkan::pipeline::BufferForm::Psb Psb
variant metal2vulkan::pipeline::BufferKind::Buffer Buffer
@@ -13458,6 +13497,7 @@ variant metal2vulkan::pipeline::ResourceKind::Synthetic Synthetic(SyntheticBindi
variant metal2vulkan::pipeline::ResourceKind::Texture Texture
variant metal2vulkan::pipeline::ResourceKind::TileAttachment TileAttachment(u32)
variant metal2vulkan::pipeline::ResourceKind::TileMap TileMap
variant metal2vulkan::pipeline::ResourceKind::YCbCrPlanes YCbCrPlanes(crate::bind::YCbCrPlanesSampler)
variant metal2vulkan::pipeline::RotatedBlendForm::Premultiplied Premultiplied
variant metal2vulkan::pipeline::RotatedBlendForm::Unmeasured Unmeasured
variant metal2vulkan::pipeline::RuntimeFact::AbsentArgumentRead AbsentArgumentRead { stage: Stage }
@@ -13547,7 +13587,7 @@ variant metal2vulkan::pipeline::RuntimeFact::VertexFetch VertexFetch { attr: u32
variant metal2vulkan::pipeline::RuntimeFact::ViewportCompensation ViewportCompensation { depth: bool, point_guard: bool, mirrors: bool, vertex_clamp: bool }
variant metal2vulkan::pipeline::RuntimeFact::ViewportCount ViewportCount
variant metal2vulkan::pipeline::RuntimeFact::WordInputMerge WordInputMerge { color: u32, kept: crate::vk::ColorComponentFlags }
variant metal2vulkan::pipeline::RuntimeFact::YCbCrInPlace YCbCrInPlace { slot: SlotRef, samplers: u32 }
variant metal2vulkan::pipeline::RuntimeFact::YCbCrInPlace YCbCrInPlace { slot: SlotRef, samplers: u32, device: bool }
variant metal2vulkan::pipeline::RuntimeFact::ZeroedColor ZeroedColor { color: u32, format: crate::metal::PixelFormat }
variant metal2vulkan::pipeline::SampledType::Float Float
variant metal2vulkan::pipeline::SampledType::Sint Sint
Can't render this file because it is too large.
+3
View File
@@ -658,6 +658,8 @@ surface! {
enum EtcTexels N;
fn chroma_decode_module;
enum ChromaDecode N;
fn chroma_sample_module;
struct ChromaSampleModule N;
fn mesh_scan_module;
fn mesh_object_arguments_module;
struct MeshScanModule N;
@@ -705,6 +707,7 @@ surface! {
struct YCbCrConvertModule N;
struct YCbCrPlanes N;
struct YCbCrInPlace N;
struct YCbCrPlanesSampler N;
struct YCbCrConversion N;
struct YCbCrCodes N;
enum YCbCrOutput N;
+2 -2
View File
@@ -4,8 +4,8 @@
# A cell is the first 64 bits of SHA-256 over the final SPIR-V of its subject, or its
# refusal class. A cell that changes under an unchanged fixture source and profile
# fingerprint needs cache::SEMANTICS_VERSION above its value at the last bless.
profile amd-780m-hawkpoint-radv 35ce6ca3d970c381
profile amd-780m-radv 35ce6ca3d970c381
profile amd-780m-hawkpoint-radv 86f432d257e0ecb6
profile amd-780m-radv 86f432d257e0ecb6
profile amd-rdna2-apu-radv d5fcc109ebb6097a
profile amd-rdna3-radv be1ee9e20062c089
profile gate-lavapipe 5770790cbab1c12d
Can't render this file because it is too large.
+34 -11
View File
@@ -800,7 +800,19 @@ for dependency in &pipeline.dependencies {
over the planes' bytes (`WriteSource::YCbCrInPlace`, in `YCbCrInPlace::format`), its push field
(`PushField::YCbCrInPlace`) holds `YCbCrInPlace::words`, and the function converts and filters
the codes as Metal does, exactly. Any other slot, and any texture without the fact, binds the
texture's image of converted texels.
texture's image of converted texels. Where the consumer also holds the planes as a linear image
of their multi-planar 4:2:0 format over their bytes, which the device's sampler Y′CbCr
conversion reads with Metal's reconstruction, it states so (`YCbCrInPlace::with_planes_image`,
its conversion `YCbCrInPlace::sampler`, a `YCbCrPlanesSampler`). A slot whose every sample the
device's sampler takes (the fact's `device`: no border address mode, no texel offset placed by a
parent's size; a runtime sampler's word without a border mode) then takes the planes variant
(`VariantKey::ycbcr_planes_sampled`): the slot is a combined image sampler of the image
(`ResourceKind::YCbCrPlanes`, `BindingSource::YCbCrPlanes`, written from
`WriteSource::YCbCrPlanesImage`) whose immutable sampler is `SamplerDesc::ycbcr` of the
conversion. The consumer chains its `VkSamplerYcbcrConversionInfo` into that sampler and makes
the image's view with an identically defined conversion, and sizes a pool for the format's
`combinedImageSamplerDescriptorCount` descriptors at the binding. Each sample is the device's,
at level 0, its conversion and filter of the codes rather than Metal's.
- `interface.reaches_command_buffers` and `interface.texture_writing_stages` say, provably, which
pipelines may touch an indirect command buffer and which stages may write a texture.
`interface.command_writes` (`CommandWrites`) says what its functions may write into the
@@ -2129,8 +2141,11 @@ bound.
unpacked 8- or 10-bit codes of a 4:2:0, 4:2:2 or 4:4:4 layout over plane 0, a 4:4:4 one read as
codes aside, on a device that reports the format's conversion features, Metal's midpoint chroma
through a linear chroma filter among them for a 4:2:0 or 4:2:2 one, and has no defect in it:
MoltenVK's 4:2:0 and 4:2:2 formats and lavapipe's 10-bit ones aside) reads the device's conversion
of its planes, announced where the texture is made; and a pipeline stage's filtered sample of a
MoltenVK's 4:2:0 and 4:2:2 formats and lavapipe's and RADV's 10-bit ones aside) reads the device's conversion
of its planes, announced where the texture is made; so do the samples of a texture whose planes
are read in place through the device's conversion of a linear image of them (where the device's
linear tiling of the 4:2:0 format has Metal's reconstruction), the device's filter of the codes
too, announced where the image is made; and a pipeline stage's filtered sample of a
texture slot bound to a two-plane YCbCr texture, through Metal's own sampler (MoltenVK), does not
take Metal's exact filter of the format: the stage records `PrecisionNote::HalfSampleFilter` or
`FloatSampleFilter` under the slot's bound format. Cost: where the device converts the planes'
@@ -2352,10 +2367,12 @@ bound.
colors come from the blocks around it). An ASTC texture's first view in its other colour
space (its sRGB form as LDR, or the other way) gives it a second twin of that form's decode, kept
in step by GPU passes its command buffers' submissions record. Also a texture of a 4:2:2 format
(`GBGR422`, `BGRG422`) on every device, whose Vulkan formats reconstruct chroma by the
implementation's rules: its texels' bytes lie in an `R8G8_UNORM` carrier, and its twin holds
Metal's texels as 8-bit codes, exact (each texel's own green, its red and blue interpolated with
the pair beside it), decoded in whole rows. Cost: a carrier image of its
(`GBGR422`, `BGRG422`) on every device, whose Vulkan formats are viewed only through a sampler
Y′CbCr conversion: its texels' bytes lie in an `R8G8_UNORM` carrier, and its twin holds its
texels as 8-bit codes (each texel's own green, its red and blue interpolated with the pair beside
it), decoded in whole rows: the device's own conversion of its pairs where it converts the format
with Metal's reconstruction (`decoded-texel-precision`; every decode then a GPU pass, its CPU
copies through submissions), else Metal's texels, exact. Cost: a carrier image of its
blocks, at most about 1 byte a texel (a 4:2:2 texture's 2), and a decoded twin of 4 bytes a texel
(R8G8B8A8; an EAC 11-bit texture's 16-bit codes, 2 bytes a channel, or its floats, 4 bytes a
channel, where the device does not take those codes), two for an ASTC texture viewed in both
@@ -2364,12 +2381,18 @@ bound.
device's decode thread, where its CPU copies go on the host or the staging queue.
- `metal2vulkan-degrade-decoded-texel-precision` (precision). `DecodedTexelPrecision`: A texture
with an ASTC LDR decoded twin of 8-bit codes, or an EAC 11-bit one (`R11`, `RG11`) of 16-bit
normalized codes. Cost: a read, sample or gather of its
normalized codes; or a 4:2:2 texture (`GBGR422`, `BGRG422`) whose twin holds the device's own
sampler Y′CbCr conversion of its pairs, where the device converts `G8B8G8R8_422_UNORM` or
`B8G8R8G8_422_UNORM` with Metal's reconstruction (the chroma at the midpoint through a linear
filter: MoltenVK). Cost: a read, sample or gather of its
texels answers the nearest 8-bit code to Metal's 12-bit value, at most 1/510 off it; an EAC 11-bit
texture's, the nearest 16-bit normalized code to Metal's 11-bit value, at most half a 16-bit step
off it (Metal reads an EAC 11-bit channel as `c / 2047`, signed `c / 1023`). An ASTC sRGB
texture's twin holds Metal's own 8-bit codes, which its slots read through the twin's sRGB view,
the device's decode (`srgb-texel-decode`).
off it; a 4:2:2 texture's, where the device converts its format, the nearest 8-bit code to the
device's own Y′CbCr conversion of its pairs, not Metal's decode (Metal reads an EAC 11-bit
channel as `c / 2047`, signed `c / 1023`; a 4:2:2 chroma channel as `(3 c + n + 2) >> 2` of its
pair's code and the code beside, whose ties the device's nearest code takes to even). An ASTC
sRGB texture's twin holds Metal's own 8-bit codes, which its slots read through the twin's sRGB
view, the device's decode (`srgb-texel-decode`).
- `metal2vulkan-degrade-shared-present-queue` (performance). `SharedPresentQueue`: A command queue
made for presenting (`Device::new_command_queue_for_presenting`) on a device that reserved no
`VkQueue` for presenting: its queue family has no queue past the ones the round robin takes
+7 -4
View File
@@ -62,11 +62,13 @@ known. The rest of the differences are docs/API.md section 9's precision notes.
| `f32` denormals in a `float` operation on a device not measured to read them as Metal does (`DriverDeviation::MetalFloatDenormals`: lavapipe, and every unmeasured device), in `floor`, `ceil` and `fneg` on every device, in the maths functions (`fabs`, `sign` and `fract` among them) and the device's order of the rows above, and in a conversion to or from `double`. Metal reads them as zero and flushes a denormal result. | The device's reading is the contract: Vulkan lets each device keep or flush them, and Metal runs no `double`, so its reading of a conversion is not measured. | `DeviceDenormals` (`device-denormals`) |
| Samples, gathers, depth comparisons and level queries are the device's own sampler's on every device whose sampler is not Metal's (every device but MoltenVK): its filter, footprint, level, anisotropy, sRGB decode and comparison, its level clamp (the descriptor's as given, which Metal holds on a `1/64` grid) and its reading of a subnormal coordinate (which Metal reads as the zero of its sign before addressing). A sample's or gather's residency on a device with `shaderResourceResidency` is the device's `OpImageSparse*` word and non-resident value (`SparseResidency`); Metal's footprint rule answers it only where the device has no residency and the slot's tile map does. A two-plane YCbCr texture's linear sample is the device's filter of its texels (the device's own Y′CbCr conversion's where it converts the format, next row; Metal's reads exactly elsewhere); where the device's memory is the host's, a sample that reads the planes in place is Metal's filter exactly. An 8-bit sRGB format the device cannot sample (`R8_SRGB` on lavapipe, `R8G8_SRGB` on lavapipe, ANV and NVIDIA) is held as its UNORM twin, the device lacking its decode: a read, a nearest sample, a fetch, a gather and a bicubic tap decode the twin's codes through Metal's table, exactly, and a filtered sample is the device's filter of the codes, decoded through the table. | The device's sampler is the contract. | Linear filter within one code (1/255) on the measured devices, sRGB within 1.83, a two-plane YCbCr texture's within 1.183; levels, anisotropy, cubes, 3D, gathers and comparisons unmeasured. A twin's filtered sample: exact for one texel and for a blend of two adjacent codes, up to 0.286 off for a blend of codes 0 and 255 (`SrgbTexelDecode`). `DeviceSampling` (`device-sampling`) |
| A pixel-coordinate sampler's sample, gather, comparison and level query is the device's sampler's at the coordinate divided by the texture's level-0 size in the shader, on every device, MoltenVK included: the device reads its texels from that coordinate in its own arithmetic, where Metal reads the coordinate as given (its nearest texel `floor(x)`, its filter's footprint from `x`). A constexpr pixel sampler that filters nearest and clamps to the edge fetches its texel (`sampler.pixel_fetch`), as does an argument buffer's sample without a comparison through a state that does. | The device's sampler is the contract. Vulkan's unnormalized samplers take no gather, offset, comparison, array, 3D image or level of detail, so the shader scales the coordinate; nothing reproduces Metal's position at a texel edge. | The device answers as its normalized sampler at a coordinate within one `f32` ulp of the quotient on MoltenVK (10 of 800 cells of each mirror-clamp configuration move by it; a nearest sample at a texel edge then reads the neighbouring texel) and at the quotient itself on lavapipe (`runtime_lane::pixel_samplers`: 800 coordinates at and around each texel edge of a 5x3 texture, every filter and address mode); a linear downscale by 8 of textures 1000 to 1920 texels wide within 1/255 of Metal's on MoltenVK and 2/255 on lavapipe (`runtime_lane::pixel_downscales`); other devices unmeasured. `PixelSamplerScaling` (`pixel-sampler-scaling`), `ArgumentPixelSamplerScaling` (`argument-pixel-sampler-scaling`) |
| A two-plane YCbCr texture's texels are the device's own sampler Y′CbCr conversion of its planes where the device converts their format (`ycbcr_device.rs`): unpacked 8- or 10-bit codes of a 4:2:0, 4:2:2 or 4:4:4 layout over plane 0 that form one image (no chroma codes 0, no rows past the buffer; a 4:4:4 layout read as codes aside, whose identity conversion converts nothing), on a device that enables `samplerYcbcrConversion` (a 4:4:4 layout also needs Vulkan 1.3 or `VK_EXT_ycbcr_2plane_444_formats`), reports the multi-planar format's conversion and, for a 4:2:0 or 4:2:2 layout, Metal's reconstruction (midpoint chroma through a linear chroma filter), and has no defect in the format; the planes are copied into an image of it and sampled once per texel into the texture's image (`bind::ycbcr_sample_module`), through the refresh's indirect arguments. The conversion takes the surface's matrix and range (the identity model for the code-reading formats), and Metal's reconstruction of a subsampled layout; a device's cosited or nearest reconstruction would move what the codes mean to Metal (cosited, up to 1340/2048 of random planes on lavapipe), a capability it lacks, so such a layout converts through Metal's arithmetic. A render pass's load stays Metal's arithmetic, which our store inverts, so a loaded texel no draw changes keeps its codes, as `MTLLoadActionLoad` keeps the attachment's contents. lavapipe (Mesa 26.0.8) converts the 8-bit 4:4:4 layout (its 4:2:0 and 4:2:2 ones are cosited only, and it reads 10-bit codes as 16-bit words, `RuntimeDriverDefect::TenBitCodesReadAsWords`); MoltenVK 1.4.2 converts none (its 4:2:0 and 4:2:2 reconstruction is misplaced, `RuntimeDriverDefect::TwoPlaneChromaMisplaced`, and it reports no 4:4:4 two-plane format). Elsewhere, and for packed codes, chroma codes 0 and plane 1, Metal's fixed-point conversion stays as capability (`WorkCounts::ycbcr_device_conversions`). | The device's conversion is the contract: Vulkan states the reconstruction's weights and the model's matrices, the precision of each step at least the format's, and the clamp of the result into `[0, 1]` the implementation's. | Each channel within 0.04/2048 of Vulkan's conversion past the `half` its image stores on lavapipe's 8-bit 4:4:4 layout; of Metal's read within 6/2048 where the result lies in `[0, 1]`, and unclamped outside it (random planes, every texel, `tests/ycbcr_device.rs`). `YCbCrFilterNotExact` (`ycbcr-filter-not-exact`) |
| A two-plane YCbCr texture's texels are the device's own sampler Y′CbCr conversion of its planes where the device converts their format (`ycbcr_device.rs`): unpacked 8- or 10-bit codes of a 4:2:0, 4:2:2 or 4:4:4 layout over plane 0 that form one image (no chroma codes 0, no rows past the buffer; a 4:4:4 layout read as codes aside, whose identity conversion converts nothing), on a device that enables `samplerYcbcrConversion` (a 4:4:4 layout also needs Vulkan 1.3 or `VK_EXT_ycbcr_2plane_444_formats`), reports the multi-planar format's conversion and, for a 4:2:0 or 4:2:2 layout, Metal's reconstruction (midpoint chroma through a linear chroma filter), and has no defect in the format; the planes are copied into an image of it and sampled once per texel into the texture's image (`bind::ycbcr_sample_module`), through the refresh's indirect arguments. The conversion takes the surface's matrix and range (the identity model for the code-reading formats), and Metal's reconstruction of a subsampled layout; a device's cosited or nearest reconstruction would move what the codes mean to Metal (cosited, up to 1340/2048 of random planes on lavapipe), a capability it lacks, so such a layout converts through Metal's arithmetic. A render pass's load stays Metal's arithmetic, which our store inverts, so a loaded texel no draw changes keeps its codes, as `MTLLoadActionLoad` keeps the attachment's contents. lavapipe (Mesa 26.0.8) converts the 8-bit 4:4:4 layout (its 4:2:0 and 4:2:2 ones are cosited only, and it reads 10-bit codes as 16-bit words, `RuntimeDriverDefect::TenBitCodesReadAsWords`); MoltenVK 1.4.2 converts none (its 4:2:0 and 4:2:2 reconstruction is misplaced, `RuntimeDriverDefect::TwoPlaneChromaMisplaced`, and it reports no 4:4:4 two-plane format). RADV (Mesa 26.2.4) reads 10-bit codes as 16-bit words too (measured on a linear image of the 4:2:0 format on the Radeon 780M), so its 10-bit layouts convert through Metal's arithmetic. Elsewhere, and for packed codes, chroma codes 0 and plane 1, Metal's fixed-point conversion stays as capability (`WorkCounts::ycbcr_device_conversions`). | The device's conversion is the contract: Vulkan states the reconstruction's weights and the model's matrices, the precision of each step at least the format's, and the clamp of the result into `[0, 1]` the implementation's. | Each channel within 0.04/2048 of Vulkan's conversion past the `half` its image stores on lavapipe's 8-bit 4:4:4 layout; of Metal's read within 6/2048 where the result lies in `[0, 1]`, and unclamped outside it (random planes, every texel, `tests/ycbcr_device.rs`). `YCbCrFilterNotExact` (`ycbcr-filter-not-exact`) |
| A texel's `float` value is the device's conversion of its codes on every device whose texture unit is not Metal's (every device but MoltenVK), and a `half` result the device's `float` texel rounded to nearest even on every device: on MoltenVK the `float` texel is Metal's, whose `half` Metal rounds otherwise for a 32-bit float texel's sample (toward zero, saturating at `±65504`) and the 16-bit normalized grids (three steps round twice through `float`); a two-plane YCbCr field on the grid `8192` keeps Metal's ties away from zero in one texel's read, sample and gather. An sRGB texel (the 8-bit sRGB formats, and the sRGB forms of BC1 to BC3, BC7, PVRTC, ETC2, EAC and ASTC, a decoded twin's through its `R8G8B8A8_SRGB` view) is the device's sRGB decode through the texture's sRGB view, in every read, sample, gather, bicubic tap and input-attachment read, where Metal decodes each code through its twelve-bit table; so is a resolve's into an 8-bit UNORM attachment's sRGB twin, which decodes the samples and encodes their average through the twin's sRGB views where Metal's resolve takes its own tables (`DeviceRoundedResolve`). | The device's conversion is the contract. | One `f32` ulp for 8- and 16-bit codes, 0.18 of a code for 5- and 6-bit packed channels; `half` within one ulp, but a 32-bit float texel's sample past `±65504` the infinity of its sign where Metal saturates (MoltenVK included); NaN bits the device's. An sRGB decode: lavapipe's within 5.25 steps of Metal's table (0.00128) at every code, MoltenVK's Metal's at every code (`runtime_lane::srgb_decode`); Vulkan sets no precision for it, and other devices are not measured. `DeviceTexelConversion` (`device-texel-conversion`), `HalfTexelConversion` (`half-texel-conversion`, also recorded for heap textures and unmeasured formats), `SrgbTexelDecode` (`srgb-texel-decode`, under the bound format) |
| A texture of a BC format (`BC1_RGBA` to `BC7_RGBAUnorm_sRGB`) is the device's decode of its own BC image on every device: where its driver is not measured to decode the format as Metal does (BC1 to BC3 off MoltenVK and RADV on the 780M; BC4 and BC5 off MoltenVK; BC7 on lavapipe), its reads, samples and gathers answer the device's interpolation of the blocks, where Metal's weights are 6-bit (an sRGB form's code then through the device's sRGB decode, the texel-conversion row). No BC texture keeps a decoded twin. | The device has the format: its decode is the contract. | A BC1 to BC3 channel within 3/255 of Metal's on NVIDIA (BC3's alpha 6/255) and lavapipe, 1/255 on ANV; a BC4 or BC5 channel within 7.3/255 (signed 0.064) on NVIDIA, 1.3/255 (signed 0.013) on ANV, 2.4/255 (signed 0.022) on lavapipe, a signed one with an endpoint of -128 within 1.7/255 on RADV; a BC7 channel a `float` ulp on lavapipe; other drivers unmeasured. `CompressedTexelDecode` (`compressed-texel-decode`) |
| A vertex attribute that fixed-function vertex input fetches is the device's conversion of its format: a normalized one (`UCharNormalized` through `Short4Normalized` of either sign, `UChar4Normalized_BGRA`, `Int1010102Normalized`, `UInt1010102Normalized`) through its own Vulkan `UNORM` or `SNORM` vertex format, where Metal divides each code by its maximum correctly rounded (an `Int1010102Normalized` 10-bit field it multiplies by `float(1 / 511)` in `float`) and rounds the quotient once to a `half` attribute; a narrow float's (a `half` format, `FloatRG11B10`) read as `float` by the device's widening, NaNs included. The format is `VertexAttribute` state that no instruction names, so every format the device fetches shares one module, and the render pipeline's link notes the conversion on its vertex stage (`pipeline::link::vertex`). **Exempt:** a normalized attribute on a profile that takes `DriverDeviation::MetalNormalizedVertexFetch`, MoltenVK on Apple's GPUs of the Apple M3 Max's macOS 27 identity, which hands the format to Metal's own fetch and was measured to answer Metal's `float` at every code of all 19 normalized formats, per vertex and per instance (`runtime_lane::normalized_vertex_fetch`): its pipeline records no note and requires `VkProperty::MetalNormalizedVertexFetch`, but for a 16-bit format read as `half`, whose `float` the module rounds to `half` again. | The device's conversion is the contract. | One `f32` ulp at some codes on a driver that multiplies by the reciprocal: llvmpipe, read at every code (Mesa 26.0.8 on LLVM 21.1.8, arm64), is within one ulp per vertex at every normalized format (127/255 as `0x3EFEFF00` where Metal reads `0x3EFEFEFF`; `Int1010102Normalized` Metal's), and per instance reads the most negative code of an 8- or 16-bit signed format unclamped (-128/127, -32768/32767) where Metal reads -1; RADV's unsigned formats are Metal's at the sites measured. A 16-bit format read as `half`: one `half` ulp at codes 65455 and 65519 unsigned, 32759 and -32759 signed, on a device whose `float` is Metal's (the quotient rounded to `half` twice). The signed formats are **unaudited** on RADV, ANV and NVIDIA. A narrow float's NaN is the device's widening's, where Metal answers `0x7fc00000`. `DeviceVertexConversion` (`device-vertex-conversion`), `DeviceNanEncoding` (`device-nan-encoding`) |
| A texture of an ASTC LDR format on a device without that ASTC format reads a decoded twin of 8-bit codes, each channel the code nearest Metal's 12-bit value (`C >> 4` over 4095); an sRGB form's twin holds Metal's own 8-bit codes, which its slots read through the twin's `R8G8B8A8_SRGB` view, the device's sRGB decode (the texel-conversion row). A texture of an EAC 11-bit format (`R11`, `RG11`, unsigned and signed) on a device without ETC2 reads one of 16-bit normalized codes, each nearest Metal's value (`c / 2047`, signed `c / 1023`). | The device lacks the format; the twin's codes are the compact form the device samples. | Within 1/510 of Metal's value; an EAC 11-bit channel within half a 16-bit step (1/131070, signed 1/65534). `decoded-texel-precision`, announced where such a texture is made |
| A texture of a 4:2:2 format (`GBGR422`, `BGRG422`) reads a decoded twin of 8-bit codes on every device (`chroma_pairs.rs`): where the device converts the pairs' format, `G8B8G8R8_422_UNORM` or `B8G8R8G8_422_UNORM`, with Metal's reconstruction (its optimal tiling reports `SAMPLED_IMAGE`, `TRANSFER_DST`, `MIDPOINT_CHROMA_SAMPLES` and a linear chroma filter; an even width), each decode pass copies the written rows' pairs into an image of that format and samples it through the device's own sampler Y′CbCr conversion (the identity model at full range) into the twin (`ycbcr_device.rs`, `bind::chroma_sample_module`), each channel the nearest 8-bit code to the device's value; elsewhere the twin holds Metal's decode, `(3c + n + 2) >> 2` of the texel's pair `c` and the pair beside it `n`, as capability. MoltenVK 1.4.2 converts both formats; lavapipe (Mesa 26.0.8) filters their chroma nearest only and RADV reports neither format, so theirs hold Metal's decode (`WorkCounts::chroma_device_twins`). | Vulkan views a 4:2:2 format only through a sampler Y′CbCr conversion, which no pipeline's layout bakes: the twin is the form every slot samples, and where the device converts the format the conversion is the contract. | Green the texel's own code; red and blue within half a code of Vulkan's `(3c + n) / 4` on MoltenVK 1.4.2 (the nearest code; random pairs, every texel of 40 x 24, `tests/ycbcr_device.rs`), where Metal's `(3c + n + 2) >> 2` rounds that sum's ties up. `DecodedTexelPrecision` (`decoded-texel-precision`), announced where such a texture is made |
| A two-plane YCbCr texture whose planes are read in place (`texture/ycbcr_image.rs`) is sampled through the device's own sampler Y′CbCr conversion where the device converts their 4:2:0 format as a linear image with Metal's reconstruction (its linear tiling of `G8_B8R8_2PLANE_420_UNORM` or `G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16` reports `SAMPLED_IMAGE`, `MIDPOINT_CHROMA_SAMPLES` and a linear chroma filter, and its driver has no defect in the format): the planes are also a linear image of the format bound over their bytes in memory the runtime allocated (`texture/ycbcr_planes.rs`; an even size, the driver's planes at the surface's offsets and row pitches), and a slot whose every sample the device's sampler takes (no border address mode, no texel offset placed by a parent's size) binds it as a combined image sampler whose immutable sampler bakes the conversion (`bind::YCbCrPlanesSampler`), each sample the device's at level 0, a nearest one at the centre of the luma texel Metal reads. Elsewhere the texel buffer read stays, Metal's fixed-point conversion and exact filter in the shader, as capability: on a device whose conversion is not Metal's reconstruction (lavapipe's 4:2:0 conversion is cosited only, MoltenVK 1.4.2's misplaced, `TwoPlaneChromaMisplaced`; RADV reads 10-bit codes as words, `TenBitCodesReadAsWords`), over fresh pages, a no-copy buffer's pages or the caller's `VkBuffer` (an image bound to imported memory starts `UNDEFINED`, and the in-place check covers that first move for single-plane images alone), where the driver lays the planes out otherwise (RADV's linear rows lie 256 bytes apart), and for a slot that samples with a border or a parent-placed offset (`WorkCounts::ycbcr_planes_images`, `ycbcr_planes_images_kept_*`). | Where the device has Metal's reconstruction, its conversion and filter are the contract; a device without it reads Metal's texels through the texel buffer, which is the capability it lacks. | The device's conversion and filter of the codes, not Metal's. A bare Vulkan probe on the Radeon 780M (RADV, Mesa 26.2.4, 8-bit codes) read each luma centre within 0.0003 codes of Vulkan's model and points between texels within 0.66 codes, where Metal's conversion then filter differs by up to 54/255 between texels of random planes (the device reconstructs the chroma at the point); the runtime's path is not measured on a device that takes it. GPU time of that probe, 3840 x 2160 composited into 1680 x 1050: 248 µs against the texel buffer's 340, one pass. `YCbCrFilterNotExact` (`ycbcr-filter-not-exact`), announced where the image is made |
| `generate_mipmaps` of a filtered format is the device's filter of each level at the scaled texel centres: its blit chain (`vkCmdBlitImage` with `VK_FILTER_LINEAR`) where its blits filter the image's format, else the runtime's bilinear (trilinear in 3D) compute filter in `float` (an extended-range format, an 8-bit sRGB texture held as its UNORM twin, a format without blits or linear filtering). An integer format's texels are picked as plain Metal picks them, exactly. | The device's filter is the contract; Apple's datapath is not modelled, and its answers differ between Apple's GPUs. | `DeviceFilteredMipmaps` (`device-filtered-mipmaps`) |
| A draw biasing a `Depth16Unorm` depth by a constant, or by a slope alone, biases by Metal's constant `c` in the device's own unit `r` on every device: Metal biases by `c + 1` units of 1/65535 for `c` of 0 or more and `c - 1` below (one unit for a slope alone), added to the depth rounded toward zero, where Vulkan's `r` of a 16-bit unorm depth is the implementation's, at most `2 × 2^-16`, and the device rounds the sum its own way. MoltenVK hands Metal its constant (`DriverDeviation::MetalDepth16BiasedStores`). | The device's depth bias is the contract. | Another code than Metal's for a biased depth: one unit's difference or more. `UnormDepthBias` (`unorm-depth-bias`) |
| A render pass that loads and stores an extended-range, padded 10-bit or bfloat color attachment (`BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10`, `R10Unorm_X6`, `RG10Unorm_X12` and their sRGB twins, `RGB10A2Unorm_sRGB`, `R16Bfloat`, `RG16Bfloat`, `RGBA16Bfloat`) keeps the bytes its draws do not write, on every device, MoltenVK included (such an attachment is an image of an unsigned integer format there too): Metal's pass writes each 32 x 32 tile a draw reaches back through its tile store, the unused bits of the codes made canonical, `BGRA10_XR`'s alpha code clamped to `[384, 894]`, a padded sRGB twin's codes through Metal's table and a bfloat code through `half` (a NaN to `0x7fc0`). A single-sampled signed normalized or `RGB9E5Float` attachment likewise keeps its minimum codes and unnormalized words, but on MoltenVK, whose pass is a Metal pass (`DriverFact::TileStoreIsMetals`). | The device's load and store are the contract: no pass rewrites the texels its draws do not write. | Bytes no Metal write left (uploads, copies) differ in the tiles a draw reaches; an extended-range texel reads the same value either way, a bfloat code off `half`'s grid reads its own value. `ExtendedRangeBitsKept` (`extended-range-bits-kept`), `SnormMinimumKept` (`snorm-minimum-kept`), `SharedExponentKept` (`shared-exponent-kept`) |
@@ -156,9 +158,10 @@ recorded here.
A discrete GPU reads the host's planes across its bus at every pass, where its image lies in its
own memory; changed planes add the conversion of every texel to the image's form (1055 to 1252
µs on the 780M, 1790 to 3636 on the 7900 XTX, 350 on the M3 Max). The planes in place form no
image of a multi-planar format (their rows are the surface's), so the in-place form converts as
Metal does on a device that converts the format itself too. A texture whose planes' first
µs on the 780M, 1790 to 3636 on the 7900 XTX, 350 on the M3 Max). Where the device converts the
planes' 4:2:0 format as a linear image with Metal's reconstruction and the planes lie as that
image's would, the in-place form samples them through the device's conversion (the device-gaps
row); elsewhere it converts as Metal does. A texture whose planes' first
byte misses `minTexelBufferOffsetAlignment`, whose planes exceed `maxTexelBufferElements` or reach
past their buffer, or which has a swizzle keeps the image on every device
(`WorkCounts::ycbcr_images_kept_*`).