Convert a two-plane YCbCr texture through the device's own Y′CbCr sampler where it has Metal's reconstruction

One work packet, landed as 3 commits (d38741a041..46bd06ec2f on archive/development-linear-2026-10-28), in order:

* Convert a two-plane YCbCr texture through the device's own Y′CbCr sampler where it has Metal's reconstruction

The owner's 10-28 decision: a YCbCr texture's texels are the GPU's own sampler Y′CbCr
conversion where the GPU converts the format and the planes form one image; elsewhere
Metal's fixed-point conversion stays as capability.

Route. The texture's conversion pass (ycbcr.rs's refresh) copies the planes from its staging
copy into an optimal image of the multi-planar format and samples it once per texel through
a combined image sampler whose layout bakes an immutable sampler of the
VkSamplerYcbcrConversion, writing the texture's image in the layout Metal's kernel writes
(bind::ycbcr_sample_module). User pipelines are unchanged: no pipeline variant per
conversion, no immutable sampler in a user layout, no combinedImageSamplerDescriptorCount in
a user pool. The staging-to-image copy runs at every refresh (two regions); the sample
dispatch takes the refresh's indirect arguments, so unchanged planes sample no workgroup.

Which textures. Unpacked 8- or 10-bit codes of a 4:2:0, 4:2:2 or 4:4:4 layout over plane 0
whose planes form one image: no chroma codes 0, no rows past the buffer, each plane at a
multiple of its texel's bytes with rows of whole texels that do not overlap
(VUID-VkBufferImageCopy-bufferRowLength-09101, VUID-vkCmdCopyBufferToImage-dstImage-07976);
on a device that enables samplerYcbcrConversion (enabled wherever present), whose optimal
tiling has SAMPLED_IMAGE and TRANSFER_DST; a 4:4:4 format also needs Vulkan 1.3 or
VK_EXT_ycbcr_2plane_444_formats (VUID-VkImageCreateInfo-None-12279), which the device now
enables below 1.3 where listed.

Metal's reconstruction required. Vulkan's implicit reconstruction of a subsampled format at
MIDPOINT through a LINEAR chroma filter weighs the chroma 3 and 1 along a halved axis, as
Metal does. Cosited it lies half a luma texel off (up to 1340/2048 of random planes on
lavapipe), and nearest it takes one pair: that is what the codes mean, not a precision step,
so a device without MIDPOINT_CHROMA_SAMPLES and a linear chroma filter for the format keeps
Metal's arithmetic for it (a capability the device lacks). The brief allowed cosited; the
measured distance is why I held it back, raised with the orchestrator.

Left on ours, on purpose:
- A 4:4:4 format read as codes (RGB8_444_2P, RGB10_444_2P): the identity model ignores the
  range and there is no chroma to reconstruct, so the device's answer is the codes ours reads,
  and the planes' image would only cost a copy.
- A render pass's load: MTLLoadActionLoad keeps the attachment's contents and our store
  inverts Metal's read, not the device's; the device's load moved untouched codes by one on
  lavapipe (ycbcr_passes' loaded-pass lane), so the load stays Metal's arithmetic.

Conversion. The surface's matrix (601/709/2020 model) and range (narrow/full); chroma filter
linear where the format has YCBCR_CONVERSION_LINEAR_FILTER and (SEPARATE_RECONSTRUCTION or
FILTER_LINEAR); the sampler's own filter nearest with SEPARATE_RECONSTRUCTION, else the
chroma's (VUID-VkSamplerCreateInfo-minFilter-01645); each sample at a luma centre. No clamp
of our own: "An implementation may clamp the R′G′B′ results of these conversions to the
range [0,1]."

Defects (measured, spec-forbidden; a RuntimeDriverDefect row keeps Metal's conversion):
- TwoPlaneChromaMisplaced (MoltenVK 1.4.2): 4:2:0 and 4:2:2 chroma one luma texel up and
  left of the midpoint's and filtered twice.
- TenBitCodesReadAsWords (lavapipe, Mesa 26.0.8): a 10-bit code's 16-bit word read as a
  16-bit UNORM (1023 as 0.999039) where Vulkan converts c/(2^10-1).

Paths measured: lavapipe converts its 8-bit 4:4:4 layout (its 4:2:0 and 4:2:2 ones are
cosited only, its 10-bit ones carry the defect); MoltenVK converts none.

Note and bound. ycbcr-filter-not-exact now also covers the device's conversion, announced
where such a texture is made. Each channel within 0.04/2048 of Vulkan's conversion past the
half the texture's image stores (0.038 measured at most), of Metal's read within 6/2048
inside [0, 1], unclamped outside it (lavapipe). FAST-PATHS gains its row; API.md matches.

Plumbing: OwnedModule::YCbCrSample with a baked combined sampler; conversions and samplers
held in OwnedKernels and released with it; priming makes and releases a conversion (the exit
guard's 128th call, vkDestroySamplerYcbcrConversion); WorkCounts::ycbcr_device_conversions
and ycbcr_device_samples count the path. RUNTIME_VERSION 1730.

Lanes: the YCbCr lanes hold a texture the device converts (counted as it is made) to
Vulkan's conversion within the bound instead of Metal's steps, and expect its notice
(validation runtime_lane/ycbcr_device_reads.rs).

Consumers: RuntimeDriverDefect gains TwoPlaneChromaMisplaced and TenBitCodesReadAsWords
(an exhaustive match breaks); WorkCounts gains two public fields (a struct literal breaks);
bind gains ycbcr_sample_module and YCbCrSampleModule.

In place on an integrated or CPU device (not changed, not decided): a throwaway probe on the
M3 Max under MoltenVK 1.4.2, 3840x2160 4:2:0 planes in host-visible memory composited into
1680x1050, best of 3x40: the device's Y′CbCr sampler over a LINEAR two-plane image of the
planes in place 72.2 us (8-bit) and 81.2 us (10-bit), against 121.1 and 122.6 us for Metal's
arithmetic over texel buffers (today's in-place form). MoltenVK's 4:2:0 conversion carries
TwoPlaneChromaMisplaced and lavapipe's is cosited only, so neither venue could take it.

Verified: build and clippy (plain and --cfg m2v_gpu); the touched host tests (catalogue,
defect lists, exit guard, api_surface, api_signatures, fast_paths, the sample module on every
committed profile). lavapipe (linux-gate arm64, --cfg m2v_cpu_icd): the runtime and validation
YCbCr, chroma, two-plane, defect, exit-guard and degradation tests, 166 of 166, the device
test counting 3 device-converted textures and the lanes 16; conformance replay --cpu exits 0,
its 723 rows exactly known-gaps.tsv's (no YCbCr conformance case reaches the device path:
they are 4:2:0). MoltenVK (M3 Max): the same selection 123 of 124, 0 textures device-converted;
the one failure (a_ycbcr_sample_through_an_unmeasured_filter_is_announced, anisotropic through
a constexpr sampler) fails identically at the base d736af8d66. Golden hashes: 2757 stale cells
at the base and at this tip alike (key changes), none from this change.

* Drop the YCbCr sample module's raw field, gone from CombinedSampler

The sRGB change (9835965499) removed CombinedSampler::raw with the raw-view
mechanism; the rebased YCbCr sample module still set it. Verified: clippy
--workspace --all-targets --all-features -D warnings clean.

* 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.
This commit is contained in:
Anees Iqbal committed 2026-10-28 17:24:22 +02:00
1 parent 2ec1f9fdc8
commit a1f1677174
30 files changed
+2624 -190

No files matched your search

+19 -5
View File
@@ -1337,8 +1337,19 @@ degradations! {
ID of the state set on it runs its program, as Metal runs a command the CPU encoded, \
where for a record the GPU wrote while another state held the ID Metal runs that \
state (nothing, for a state of the other kind)";
/// 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,
/// 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`): Vulkan's chroma
/// reconstruction at Metal's midpoint through a linear chroma filter, and the range
/// expansion and model conversion at the device's precision, unclamped where the device
/// does not clamp. Each channel lies within the device's precision of Vulkan's conversion
/// and off Metal's fixed-point read (lavapipe, Mesa 26.0.8, its 8-bit 4:4:4 layout,
/// 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.
///
/// 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,
/// `VkProperty::MetalSampler`), does not take Metal's exact filter of the format: the stage
/// records `PrecisionNote::HalfSampleFilter` or `FloatSampleFilter` under any two-plane
/// YCbCr format bound there (`lower::sampler::linear`), whose converted texels Metal's
@@ -1351,9 +1362,12 @@ degradations! {
/// pipeline is made, or at a draw or dispatch that binds such a texture there (through a
/// runtime sampler, whatever its word states), naming the slot and the format.
YCbCrFilterNotExact = "ycbcr-filter-not-exact", Precision,
"the texels hold Metal's reads exactly, but the sample filters them as the device \
does, off the grid Metal sums the format's steps on, so a filtered result can miss \
Metal's by a step of that grid or more";
"where the device converts the planes' format, the texels are its own Y′CbCr \
conversion's, at its precision and unclamped where it does not clamp, not Metal's \
fixed-point read; elsewhere the texels \
hold Metal's reads exactly, but the sample filters them as the device does, off the \
grid Metal sums the format's steps on, so a filtered result can miss Metal's by a \
step of that grid or more";
/// A render pass that draws loads and stores a rotated texture of rotation 4, whose load
/// is the plane transposed and whose store is rotation 1's (`rotated.rs`): every tile of
/// the frame lands mirrored, where Metal loads and stores only the 32x32 tiles a draw's
@@ -285,6 +285,10 @@ impl Device {
host_image_copy,
linear_color_attachment,
graphics_pipeline_library,
// Nor whether `samplerYcbcrConversion` was: its YCbCr textures convert through
// Metal's arithmetic.
ycbcr_conversion: false,
ycbcr_444: false,
sparse_features: raw.sparse_features.features(),
memory_reads,
owned: false,
@@ -1035,6 +1035,36 @@ pub(super) unsafe fn graphics_pipeline_library_supported(
&& linking.graphics_pipeline_library_independent_interpolation_decoration == vk::TRUE
}
/// Whether `physical` has `samplerYcbcrConversion` (Vulkan 1.1's).
///
/// # Safety
///
/// `physical` was enumerated from `instance`, made at Vulkan 1.2 or later.
unsafe fn ycbcr_conversion_supported(
instance: &ash::Instance,
physical: vk::PhysicalDevice,
) -> bool {
let mut v11 = vk::PhysicalDeviceVulkan11Features::default();
let mut features = vk::PhysicalDeviceFeatures2::default().push_next(&mut v11);
// SAFETY: the caller's contract; the chain lives for the call.
unsafe { instance.get_physical_device_features2(physical, &mut features) };
v11.sampler_ycbcr_conversion == vk::TRUE
}
/// Whether `physical` has `VK_EXT_ycbcr_2plane_444_formats`' `ycbcr2plane444Formats`.
///
/// # Safety
///
/// `physical` was enumerated from `instance`, made at Vulkan 1.2 or later, and lists the
/// extension.
unsafe fn ycbcr_444_supported(instance: &ash::Instance, physical: vk::PhysicalDevice) -> bool {
let mut formats = vk::PhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT::default();
let mut features = vk::PhysicalDeviceFeatures2::default().push_next(&mut formats);
// SAFETY: the caller's contract; the chain lives for the call.
unsafe { instance.get_physical_device_features2(physical, &mut features) };
formats.ycbcr2plane444_formats == vk::TRUE
}
/// Whether a device of version `api` (its own, capped by the instance's) that lists `listed`
/// enables `VK_NV_linear_color_attachment` and its `linearColorAttachment`: it lists the
/// extension and has what it requires, `VK_KHR_format_feature_flags2` or Vulkan 1.3, where that
@@ -1344,6 +1374,24 @@ fn create_on(
if graphics_pipeline_library {
enables.enable_graphics_pipeline_library();
}
// The runtime's own need, outside the vocabulary, where the device has it: two-plane YCbCr
// textures convert through the device's own conversion (`ycbcr_device.rs`).
// SAFETY: `physical` was enumerated from the instance, made at Vulkan 1.2.
let ycbcr_conversion = unsafe { ycbcr_conversion_supported(&instance.raw, physical) };
if ycbcr_conversion {
enables.enable_ycbcr_conversion();
}
// And its two-plane 4:4:4 formats: core from Vulkan 1.3, else where the device lists
// `VK_EXT_ycbcr_2plane_444_formats` with its feature.
let ycbcr_444 = ycbcr_conversion
&& (api >= ApiVersion::V1_3
|| listed.contains(ash::ext::ycbcr_2plane_444_formats::NAME)
// SAFETY: `physical` was enumerated from the instance, made at Vulkan 1.2, and
// lists the extension.
&& unsafe { ycbcr_444_supported(&instance.raw, physical) });
if ycbcr_444 && api < ApiVersion::V1_3 {
enables.enable_ycbcr_2plane_444();
}
// The runtime's own need, outside the vocabulary: the device's pipelines are cached in the
// shader cache's records alone, the driver's internal cache off where it allows; else the
// device says once that the driver keeps it.
@@ -1431,6 +1479,8 @@ fn create_on(
host_image_copy,
linear_color_attachment,
graphics_pipeline_library,
ycbcr_conversion,
ycbcr_444,
creation_feedback: creation_feedback || feedback_asked,
dma_buf: dma_buf.is_some(),
dma_buf_images: dma_buf_images.is_some(),
@@ -387,6 +387,8 @@ pub(super) struct DeviceShared {
/// The crate-owned compute kernels the runtime dispatches for itself, made on first use
/// (`owned_kernel.rs`).
pub(super) owned_kernels: Mutex<OwnedKernels>,
/// The two-plane YCbCr formats the device converts itself (`ycbcr_device.rs`).
pub(super) ycbcr_formats: crate::ycbcr_device::YCbCrFormats,
/// The spare scratch block of `generate_mipmaps`' filter chains (`mipmap_scratch.rs`).
pub(super) mipmap_scratch: Mutex<MipmapScratch>,
/// The sample planes' copy kernels and merge pipelines, made on first use
@@ -1108,6 +1110,14 @@ pub(super) struct Parts {
/// `adopt.rs`, where the consumer lists it), outside `enabled`'s vocabulary: its render
/// pipelines are linked from libraries (`pipeline/libraries.rs`).
pub(super) graphics_pipeline_library: bool,
/// It enables `samplerYcbcrConversion` (`create.rs`), outside `enabled`'s vocabulary: a
/// two-plane YCbCr texture's planes convert through the device's own conversion where it
/// converts their format (`ycbcr_device.rs`). An adopted device's consumer does not say, so
/// it is false there.
pub(super) ycbcr_conversion: bool,
/// It takes the two-plane 4:4:4 formats with that conversion: Vulkan 1.3, or
/// `VK_EXT_ycbcr_2plane_444_formats` enabled with its feature (`create.rs`).
pub(super) ycbcr_444: bool,
/// It enables `VK_EXT_pipeline_creation_feedback` (`create.rs`), outside `enabled`'s
/// vocabulary, wherever listed: each making of a program's pipeline reads whether its cache
/// held the pipeline (`shader_cache/mod.rs`).
@@ -1162,6 +1172,8 @@ impl Device {
host_image_copy,
linear_color_attachment,
graphics_pipeline_library,
ycbcr_conversion,
ycbcr_444,
creation_feedback,
dma_buf,
dma_buf_images,
@@ -1412,6 +1424,15 @@ impl Device {
crate::recorder::through(recording.as_ref(), Command::CmdSetColorWriteMask, masks)
})
});
// The YCbCr formats the device converts itself, where it enables the conversion.
let ycbcr_formats = match ycbcr_conversion {
// SAFETY: `physical` belongs to `instance`, created at Vulkan 1.2 or later, and the
// device enables `samplerYcbcrConversion`.
true => unsafe {
crate::ycbcr_device::YCbCrFormats::of(&instance.raw, physical, ycbcr_444)
},
false => crate::ycbcr_device::YCbCrFormats::default(),
};
let drawn = prime::PrimedDraws {
dynamic: extended_dynamic_state,
color_write_masks,
@@ -1453,11 +1474,13 @@ impl Device {
color_write_masks: false,
depth_bias: false,
sized_index_bind: false,
ycbcr_conversion: ycbcr_formats.primer().is_some(),
}),
generated_commands.as_ref(),
push_descriptor,
calibrated,
drawn,
ycbcr_formats.primer(),
)
} {
scheduler.stop();
@@ -1773,6 +1796,7 @@ impl Device {
gpu_work: AtomicU64::new(0),
dynamic_multi_variable: OnceLock::new(),
owned_kernels: Mutex::new(OwnedKernels::default()),
ycbcr_formats,
mipmap_scratch: Mutex::default(),
planes: Mutex::new(PlanesObjects::default()),
interleave: Mutex::default(),
@@ -182,6 +182,10 @@ pub(crate) const DEPTH_BIAS_CALLS: [Call; 1] = [Call::CmdSetDepthBias2];
/// buffer bound with its size (`draw_source.rs`).
pub(crate) const SIZED_INDEX_BIND_CALLS: [Call; 1] = [Call::CmdBindIndexBuffer2];
/// The table's entry points a device that converts no YCbCr format itself never calls, nor
/// primes: the release of a YCbCr sample kernel's conversion (`ycbcr_device.rs`).
pub(crate) const YCBCR_CONVERSION_CALLS: [Call; 1] = [Call::DestroySamplerYcbcrConversion];
/// The debug name of a render host step's pipeline that priming makes, where the instance reports
/// messages ([`NAMING_CALLS`]).
const PRIMING_PIPELINE: &std::ffi::CStr =
@@ -377,6 +381,7 @@ pub(crate) struct Has {
pub(crate) color_write_masks: bool,
pub(crate) depth_bias: bool,
pub(crate) sized_index_bind: bool,
pub(crate) ycbcr_conversion: bool,
}
/// The commands a render encoder records that the device has where it has their feature or
@@ -409,15 +414,16 @@ impl PrimedDraws {
/// Prime `device` of `physical`, made from `instance`, whose queues are `queues`, the first of
/// its primary family `queue_family`, its buffers and images shared as `sharing` says, on this
/// thread; `has` says what the device has, `generated` holds the commands of
/// `VK_EXT_device_generated_commands` where it has them, and `drawn` the render encoder's
/// commands it has.
/// `VK_EXT_device_generated_commands` where it has them, `drawn` the render encoder's commands
/// it has, and `ycbcr` a Y′CbCr conversion of a format it converts, where it converts one.
///
/// # Safety
///
/// The device is live and enables timeline semaphores, and `bufferDeviceAddress` where `has`
/// says it has device addresses; `queues` holds at least one of its queues, which nothing else
/// uses yet; `generated` is the device's, which enables the extension and `maintenance5`;
/// `loader_word` is the device's loader word.
/// `loader_word` is the device's loader word; the device enables `samplerYcbcrConversion` and
/// converts `ycbcr`'s format with its chroma location where `ycbcr` is given.
pub(super) unsafe fn prime(
instance: &ash::Instance,
physical: vk::PhysicalDevice,
@@ -431,6 +437,7 @@ pub(super) unsafe fn prime(
push: Option<vk::PFN_vkCmdPushDescriptorSetKHR>,
calibration: Option<Calibration>,
drawn: PrimedDraws,
ycbcr: Option<vk::SamplerYcbcrConversionCreateInfo<'static>>,
) -> Result<(), Error> {
let mut primer = Primer {
device,
@@ -454,6 +461,7 @@ pub(super) unsafe fn prime(
None => Ok(()),
})
.and_then(|()| primer.sparse(queues, has.sparse_binding))
.and_then(|()| primer.ycbcr(ycbcr))
};
// SAFETY: the submission completed, or was never made, or the device is lost; nothing else
// uses the objects held.
@@ -484,7 +492,8 @@ pub(super) unsafe fn prime(
/// of [`NAMING_CALLS`] where its instance reports no messages, and those of
/// [`EXTENDED_DYNAMIC_STATE_CALLS`], [`PRIMITIVE_RESTART_CALLS`],
/// [`COLOR_WRITE_MASK_CALLS`], [`DEPTH_BIAS_CALLS`] and [`SIZED_INDEX_BIND_CALLS`] where it has
/// not their commands, that `calls` (one bit each) does not hold.
/// not their commands, and those of [`YCBCR_CONVERSION_CALLS`] where it converts no YCbCr format,
/// that `calls` (one bit each) does not hold.
pub(crate) fn missing(calls: u128, has: Has) -> Vec<Call> {
Call::ALL
.iter()
@@ -506,6 +515,7 @@ pub(crate) fn missing(calls: u128, has: Has) -> Vec<Call> {
&& (has.color_write_masks || !COLOR_WRITE_MASK_CALLS.contains(&call))
&& (has.depth_bias || !DEPTH_BIAS_CALLS.contains(&call))
&& (has.sized_index_bind || !SIZED_INDEX_BIND_CALLS.contains(&call))
&& (has.ycbcr_conversion || !YCBCR_CONVERSION_CALLS.contains(&call))
})
.collect()
}
@@ -868,6 +878,27 @@ impl Primer<'_> {
Ok(())
}
/// A Y′CbCr conversion of `info`, a format the device converts, where it converts one
/// ([`YCBCR_CONVERSION_CALLS`]).
///
/// # Safety
///
/// As [`prime`]'s; the device enables `samplerYcbcrConversion` where `info` is given, and
/// converts its format with its chroma location.
unsafe fn ycbcr(
&mut self,
info: Option<vk::SamplerYcbcrConversionCreateInfo<'static>>,
) -> Result<(), Error> {
let Some(info) = info else {
return Ok(());
};
// SAFETY: the caller's.
let conversion =
unsafe { self.device.create_sampler_ycbcr_conversion(&info, None) }.map_err(vulkan)?;
self.hold(conversion);
Ok(())
}
/// An object of every other kind the runtime releases, the read of a pipeline cache's data,
/// and a command buffer of a pool of `queue_family` recorded as a host step records one;
/// `device_addresses` where the device has them.
@@ -405,6 +405,39 @@ pub(super) struct Affected {
/// refused: such an image takes no host-transfer usage there (`Device::host_placed_image`), so it
/// stays in memory of its own class and its CPU copies go through a submission; on every other
/// driver a block-compressed texture's CPU copies stay on the host.
///
/// `TwoPlaneChromaMisplaced`:
/// - MoltenVK (`MOLTENVK`): a sampler Y′CbCr conversion of `G8_B8R8_2PLANE_420_UNORM`,
/// `G8_B8R8_2PLANE_422_UNORM` or their 10-bit formats, whose optimal tiling reports midpoint
/// and cosited chroma, a linear chroma filter, separate reconstruction and forced explicit
/// reconstruction, reconstructs the chroma off where Vulkan places it (20.2.8, "Chroma
/// Reconstruction"). A bare Vulkan probe on an M3 Max under macOS 27.0.1 sampled 40 x 24
/// images at every luma texel's centre and at 2048 random points, the planes random and, for
/// the weights, one chroma pair alone set: under a nearest sampler filter, a linear chroma
/// filter and midpoint chroma, the weights of a chroma sample have the right shape (1/4, 3/4,
/// 3/4, 1/4 across and down) but centred one luma texel up and to the left of the midpoint's
/// (chroma sample `k` at luma `2k` where Vulkan's lies at `2k + 1`); under a linear sampler
/// filter the chroma is filtered twice (3/16, 3/16, 10/16, 10/16, 3/16, 3/16 across) and
/// shifted alike; forced explicit reconstruction changes nothing, and cosited chroma reads
/// weights of no interpolation. A texel's channels lay up to 1000/2048 from Vulkan's
/// conversion (4:2:0, the identity model) and 366/2048 (4:2:2), the luma exact. Its 4:2:2
/// single-plane formats (`G8B8G8R8_422_UNORM`, `B8G8R8G8_422_UNORM`) reconstruct as Vulkan
/// states. Measured on 1.4.2 (driverVersion 10402): known broken through 1.4.2. Nothing is
/// refused: a two-plane 4:2:0 or 4:2:2 texture converts through Metal's arithmetic there
/// (`ycbcr_device.rs`), as on a device without the conversion.
///
/// `TenBitCodesReadAsWords`:
/// - Mesa's lavapipe (`MESA_LLVMPIPE`): a sampler Y′CbCr conversion of
/// `G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16` and its 4:4:4 format reads each code's 16-bit
/// word as a 16-bit unsigned normalized value, `word / 65535`, its six unused low bits included,
/// where Vulkan converts the 10-bit code as `c / (2^10 - 1)` ("Fixed-Point Data Conversions";
/// the format "has a 10-bit G component in the top 10 bits of each 16-bit word ... with the
/// bottom 6 bits of each word unused"). A bare Vulkan probe read luma code 1023 (low bits 0) as
/// 0.999039 through the identity model, and the runtime's conversion of random words through it
/// (`runtime_lane::ycbcr_textures::retyped_views_read_their_luma_codes`) read codes one low
/// 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`).
pub(super) const AFFECTED: &[Affected] = &[
Affected {
defect: RuntimeDriverDefect::HostTransferImagesCopiedAtBind,
@@ -523,6 +556,16 @@ pub(super) const AFFECTED: &[Affected] = &[
driver: DriverId::MOLTENVK,
clean: &[],
},
Affected {
defect: RuntimeDriverDefect::TwoPlaneChromaMisplaced,
driver: DriverId::MOLTENVK,
clean: &[],
},
Affected {
defect: RuntimeDriverDefect::TenBitCodesReadAsWords,
driver: DriverId::MESA_LLVMPIPE,
clean: &[],
},
];
/// The defects of the driver and device `description` names, its GPU read by the `deviceID` it
+27 -3
View File
@@ -408,6 +408,9 @@ pub(super) enum Structure {
/// `VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT`, outside the vocabulary: linked only
/// by [`Enables::enable_graphics_pipeline_library`].
GraphicsPipelineLibrary,
/// `VkPhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT`, outside the vocabulary: linked only by
/// [`Enables::enable_ycbcr_2plane_444`], below Vulkan 1.3.
Ycbcr2Plane444,
}
/// Vulkan 1.4.
@@ -483,7 +486,8 @@ impl Structure {
| Structure::LinearColorAttachment
| Structure::PipelineBinary
| Structure::InternalCacheControl
| Structure::GraphicsPipelineLibrary => None,
| Structure::GraphicsPipelineLibrary
| Structure::Ycbcr2Plane444 => None,
}
}
@@ -540,7 +544,8 @@ impl Structure {
| Structure::LinearColorAttachment
| Structure::PipelineBinary
| Structure::InternalCacheControl
| Structure::GraphicsPipelineLibrary => &[],
| Structure::GraphicsPipelineLibrary
| Structure::Ycbcr2Plane444 => &[],
}
}
}
@@ -603,6 +608,7 @@ struct FeatureChain {
pipeline_binary: PipelineBinaryFeatures,
internal_cache_control: InternalCacheControl,
graphics_pipeline_library: vk::PhysicalDeviceGraphicsPipelineLibraryFeaturesEXT<'static>,
ycbcr_2plane_444: vk::PhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT<'static>,
}
/// One `VkBool32` member of a [`FeatureChain`] structure, named by the vocabulary.
@@ -1123,7 +1129,8 @@ macro_rules! link_extensions {
LinearColorAttachment => linear_color_attachment,
PipelineBinary => pipeline_binary,
InternalCacheControl => internal_cache_control,
GraphicsPipelineLibrary => graphics_pipeline_library
GraphicsPipelineLibrary => graphics_pipeline_library,
Ycbcr2Plane444 => ycbcr_2plane_444
)
};
(@ $info:ident, $chain:ident, $linked:ident; $($variant:ident => $field:ident),*) => {
@@ -1213,6 +1220,23 @@ impl Enables {
Ok(enables)
}
/// Enables `samplerYcbcrConversion`, core in Vulkan 1.1, the runtime's own need outside the
/// vocabulary: a two-plane YCbCr texture's planes convert through the device's own conversion
/// where it converts their format (`ycbcr_device.rs`), on a device that has the feature.
pub(super) fn enable_ycbcr_conversion(&mut self) {
self.chain.v11.sampler_ycbcr_conversion = vk::TRUE;
}
/// Enables `VK_EXT_ycbcr_2plane_444_formats` and its `ycbcr2plane444Formats`, the runtime's
/// own need outside the vocabulary below Vulkan 1.3, where the two-plane 4:4:4 formats are
/// core: a two-plane 4:4:4 YCbCr texture converts through the device's own conversion
/// (`ycbcr_device.rs`), on a device that lists the extension and has the feature.
pub(super) fn enable_ycbcr_2plane_444(&mut self) {
self.chain.ycbcr_2plane_444.ycbcr2plane444_formats = vk::TRUE;
self.linked.insert(Structure::Ycbcr2Plane444);
self.push_name(ash::ext::ycbcr_2plane_444_formats::NAME.to_owned());
}
/// Enables the portability subset's `imageViewFormatReinterpretation`, the runtime's own need
/// outside the vocabulary (Metal's texture views of another component layout,
/// `view_plan.rs`), on a device whose subset has it and whose set enables the subset.
@@ -368,6 +368,8 @@ calls! {
DestroyFence => c"vkDestroyFence",
DestroySemaphore => c"vkDestroySemaphore",
DestroySampler => c"vkDestroySampler",
// A YCbCr sample kernel's conversion (`ycbcr_device.rs`), released with the kernel.
DestroySamplerYcbcrConversion => c"vkDestroySamplerYcbcrConversion",
DestroyBuffer => c"vkDestroyBuffer",
DestroyBufferView => c"vkDestroyBufferView",
DestroyImage => c"vkDestroyImage",
+1
View File
@@ -221,6 +221,7 @@ mod word_fill;
mod work_counts;
mod wrapped_buffer;
mod ycbcr;
mod ycbcr_device;
#[cfg(test)]
mod tests;
+124 -9
View File
@@ -30,13 +30,14 @@ use super::device::lock;
use super::error::{internal, vulkan, Error};
use super::release;
use super::texture::decoded_twin::TwinDecode;
use super::ycbcr_device::YCbCrSampler;
use super::Device;
use crate::device::functions::Vk;
use crate::shader_cache::driver::Making;
use ash::vk;
use metal2vulkan::bind::{
CompressedBlit, MipmapFilterKernel, RewritePhase, RewriteProgram, ShadowMergeRead,
ShadowTexelView, TessellationScanKernel, TexelWords, YCbCrConversion,
ShadowTexelView, TessellationScanKernel, TexelWords, YCbCrCodes, YCbCrConversion,
};
use metal2vulkan::metal::format::ExtendedRange;
use metal2vulkan::metal::PixelFormat;
@@ -144,6 +145,11 @@ pub(super) enum OwnedModule {
/// the device reads through, within the two-plane formats' layouts and the ranges and
/// matrices they convert under.
YCbCrConvert(YCbCrConversion, bool),
/// `bind::ycbcr_sample_module`: a YCbCr texture's planes' image sampled through the device's
/// own Y′CbCr conversion into its image, the output of the codes; its layout bakes the
/// 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::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`).
@@ -203,6 +209,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,
_ => 0,
}
}
@@ -227,6 +235,7 @@ impl OwnedModule {
fn storage_images(self) -> u32 {
match self {
OwnedModule::YCbCrConvert(..)
| OwnedModule::YCbCrSample(..)
| OwnedModule::YCbCrWrite
| OwnedModule::ShadowCopyIn(_) => 1,
OwnedModule::ExtendedShadowLoad(_) => 2,
@@ -410,6 +419,13 @@ impl OwnedModule {
.map_err(Error::Compile)?;
Ok((module.spirv.to_vec(), 2, 0))
}
OwnedModule::YCbCrSample(_, codes) => {
let module =
metal2vulkan::bind::ycbcr_sample_module(device.compile_device(), codes)
.map_err(Error::Compile)?;
let push_bytes = metal2vulkan::bind::YCbCrSampleModule::PUSH_BYTES;
Ok((module.spirv.to_vec(), 0, push_bytes))
}
OwnedModule::RotateTexels => {
let module = metal2vulkan::bind::rotate_texels_module(device.compile_device())
.map_err(Error::Compile)?;
@@ -516,6 +532,10 @@ pub(super) struct OwnedKernel {
/// Whether set 0's layout is a push descriptor set's: its dispatches push their descriptors
/// (`vkCmdPushDescriptorSetKHR`) in place of a set from a pool.
pub(super) pushed: bool,
/// The descriptors its first binding takes from a pool where that binding is the combined
/// image sampler of a sampler of the device's Y′CbCr conversion its layout bakes
/// (`combinedImageSamplerDescriptorCount`, `ycbcr_device.rs`); 0 for every other kernel.
combined: u8,
}
impl OwnedKernel {
@@ -567,6 +587,10 @@ pub(super) struct OwnedKernels {
rows_copy: Option<OwnedKernel>,
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.
ycbcr_samplers: HashMap<YCbCrSampler, (vk::SamplerYcbcrConversion, vk::Sampler)>,
two_plane_texels: Option<OwnedKernel>,
plane_bytes_copy: Option<OwnedKernel>,
ycbcr_write: Option<OwnedKernel>,
@@ -629,6 +653,7 @@ impl OwnedKernels {
.chain(self.index_rewrites.values().copied())
.chain(self.index_rewrite_runs.values().copied())
.chain(self.ycbcr_converts.values().copied())
.chain(self.ycbcr_samples.values().copied())
.chain(self.unused_bits.values().copied())
.chain(self.compressed_blits.values().copied())
.chain(self.extended_shadow_loads.values().copied())
@@ -637,6 +662,28 @@ impl OwnedKernels {
{
kernel.destroy(raw);
}
for &(conversion, sampler) in self.ycbcr_samplers.values() {
// SAFETY: as above; the kernels whose layouts bake them are destroyed.
unsafe {
release::object(raw, sampler);
release::object(raw, conversion);
}
}
}
/// The device's conversion of `sampler` and the sampler of it that the YCbCr sample kernels
/// of `sampler` bake, made on first use; the sampler counted against the device's samplers.
fn ycbcr_sampler(
&mut self,
device: &Device,
sampler: YCbCrSampler,
) -> Result<(vk::SamplerYcbcrConversion, vk::Sampler), Error> {
if let Some(&made) = self.ycbcr_samplers.get(&sampler) {
return Ok(made);
}
let made = sampler.make(device)?;
self.ycbcr_samplers.insert(sampler, made);
Ok(made)
}
/// The kernel of `which`, where the device has made it.
@@ -656,6 +703,9 @@ impl OwnedKernels {
OwnedModule::YCbCrConvert(conversion, floats) => {
self.ycbcr_converts.get(&(conversion, floats)).copied()
}
OwnedModule::YCbCrSample(sampler, codes) => {
self.ycbcr_samples.get(&(sampler, codes)).copied()
}
OwnedModule::UnusedBits(format, words) => {
self.unused_bits.get(&(format, words)).copied()
}
@@ -694,6 +744,9 @@ impl OwnedKernels {
OwnedModule::YCbCrConvert(conversion, floats) => {
self.ycbcr_converts.insert((conversion, floats), kernel);
}
OwnedModule::YCbCrSample(sampler, codes) => {
self.ycbcr_samples.insert((sampler, codes), kernel);
}
OwnedModule::UnusedBits(format, words) => {
self.unused_bits.insert((format, words), kernel);
}
@@ -749,6 +802,7 @@ impl OwnedKernels {
| OwnedModule::IndexRewrite(..)
| OwnedModule::IndexRewriteRun(_)
| OwnedModule::YCbCrConvert(..)
| OwnedModule::YCbCrSample(..)
| OwnedModule::UnusedBits(..)
| OwnedModule::CompressedBlit(_)
| OwnedModule::ExtendedShadowLoad(_)
@@ -784,6 +838,18 @@ impl OwnedKernels {
}
impl Device {
/// The device's Y′CbCr conversion of `sampler` that its YCbCr sample kernels bake, where a
/// kernel of it was made ([`OwnedKernels::ycbcr_sampler`]): an image view such a kernel
/// samples is made with it.
pub(super) fn ycbcr_conversion(
&self,
sampler: YCbCrSampler,
) -> Option<vk::SamplerYcbcrConversion> {
let kernels = lock(&self.shared().owned_kernels);
let made = kernels.ycbcr_samplers.get(&sampler);
made.map(|&(conversion, _)| 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.
@@ -796,7 +862,20 @@ impl Device {
}
let (spirv, buffers, push_bytes) = which.build(self)?;
let bindings = (which.images(), which.storage_images(), buffers);
let kernel = make(self, &spirv, bindings, (push_bytes, which.pushed(self)))?;
let baked = match which {
OwnedModule::YCbCrSample(sampler, ..) => {
let (_, made) = kernels.ycbcr_sampler(self, sampler)?;
Some((made, sampler.descriptors))
}
_ => None,
};
let kernel = make(
self,
&spirv,
bindings,
(push_bytes, which.pushed(self)),
baked,
)?;
// Counted here, so the build attributes to the call that first needed the kernel rather
// than to whichever path the kernel serves (`WorkCounts::owned_kernels_made`).
self.shared().counts.owned_kernel_made(spirv.len());
@@ -807,15 +886,21 @@ impl Device {
/// The objects of a kernel of `spirv` (entry point `main`) with `images` sampled images, then
/// `storage_images` storage images and then `buffers` storage buffers in set 0, a push descriptor
/// set's where `pushed`, and `push_bytes` of `COMPUTE` push constants.
/// set's where `pushed`, and `push_bytes` of `COMPUTE` push constants. With `baked`, a sampler
/// of a Y′CbCr conversion and the descriptors a combined image sampler of it takes, its first
/// binding is that combined image sampler, the sampler immutable.
fn make(
device: &Device,
spirv: &[u32],
(images, storage_images, buffers): (u32, u32, u32),
(push_bytes, pushed): (u32, bool),
baked: Option<(vk::Sampler, u32)>,
) -> Result<OwnedKernel, Error> {
let shared = device.shared();
let raw = shared.vk();
let (sampler, combined) = baked.unwrap_or((vk::Sampler::null(), 0));
let combined =
u8::try_from(combined).map_err(|_| internal("a YCbCr format of too many planes"))?;
let mut kernel = OwnedKernel {
module: vk::ShaderModule::null(),
set_layout: vk::DescriptorSetLayout::null(),
@@ -825,7 +910,9 @@ fn make(
storage_images,
buffers,
pushed,
combined,
};
let immutable = [sampler];
let made = (|| {
let info = vk::ShaderModuleCreateInfo::default().code(spirv);
// SAFETY: the code is live SPIR-V words for the call.
@@ -833,11 +920,15 @@ fn make(
let bindings: Vec<vk::DescriptorSetLayoutBinding<'_>> =
(0..images + storage_images + buffers)
.map(|binding| {
vk::DescriptorSetLayoutBinding::default()
let info = vk::DescriptorSetLayoutBinding::default()
.binding(binding)
.descriptor_type(descriptor_type(binding, images, storage_images))
.descriptor_type(kernel.descriptor_type(binding))
.descriptor_count(1)
.stage_flags(vk::ShaderStageFlags::COMPUTE)
.stage_flags(vk::ShaderStageFlags::COMPUTE);
match kernel.baked(binding) {
true => info.immutable_samplers(&immutable),
false => info,
}
})
.collect();
let mut info = vk::DescriptorSetLayoutCreateInfo::default().bindings(&bindings);
@@ -908,6 +999,23 @@ fn descriptor_type(binding: u32, images: u32, storage_images: u32) -> vk::Descri
}
}
impl OwnedKernel {
/// Whether binding `binding` of its set 0 is the combined image sampler of a baked Y′CbCr
/// conversion's sampler.
fn baked(&self, binding: u32) -> bool {
binding == 0 && self.combined > 0
}
/// The type of binding `binding` of its set 0: [`descriptor_type`]'s, but the combined image
/// sampler of a baked sampler.
fn descriptor_type(&self, binding: u32) -> vk::DescriptorType {
match self.baked(binding) {
true => vk::DescriptorType::COMBINED_IMAGE_SAMPLER,
false => descriptor_type(binding, self.images, self.storage_images),
}
}
}
/// What one set of an [`OwnedKernel`] binds: its sampled images' views, then its storage images'
/// views, each in the `GENERAL` layout, then its storage buffers' `(buffer, offset, range)`.
pub(super) struct OwnedSet {
@@ -935,8 +1043,13 @@ impl OwnedKernel {
/// What one set of its set 0 takes from a pool: its sampled images, storage images and
/// storage buffers (`SetNeeds`, by raw type ascending, each count above 0).
fn set_needs(&self) -> SetNeeds {
let baked = u32::from(self.combined > 0);
let counts = [
(vk::DescriptorType::SAMPLED_IMAGE, self.images),
(
vk::DescriptorType::COMBINED_IMAGE_SAMPLER,
u32::from(self.combined),
),
(vk::DescriptorType::SAMPLED_IMAGE, self.images - baked),
(vk::DescriptorType::STORAGE_IMAGE, self.storage_images),
(vk::DescriptorType::STORAGE_BUFFER, self.buffers),
];
@@ -1031,13 +1144,15 @@ impl OwnedSets {
.collect();
let mut writes = Vec::new();
let infos = image_infos.iter().zip(&storage_infos).zip(&buffer_infos);
for (set, ((images, storage), buffers)) in owned.sets.iter().zip(infos) {
for ((set, ((images, storage), buffers)), kernel) in
owned.sets.iter().zip(infos).zip(kernels)
{
for (binding, info) in images.iter().enumerate() {
writes.push(
vk::WriteDescriptorSet::default()
.dst_set(*set)
.dst_binding(binding as u32)
.descriptor_type(vk::DescriptorType::SAMPLED_IMAGE)
.descriptor_type(kernel.descriptor_type(binding as u32))
.image_info(std::slice::from_ref(info)),
);
}
@@ -156,6 +156,7 @@ released! {
vk::Image => destroy_image, DestroyImage;
vk::ImageView => destroy_image_view, DestroyImageView;
vk::Sampler => destroy_sampler, DestroySampler;
vk::SamplerYcbcrConversion => destroy_sampler_ycbcr_conversion, DestroySamplerYcbcrConversion;
vk::DeviceMemory => free_memory, FreeMemory;
vk::Semaphore => destroy_semaphore, DestroySemaphore;
vk::Fence => destroy_fence, DestroyFence;
@@ -29,6 +29,8 @@ const SET_SUPPORT: RuntimeDriverDefect = RuntimeDriverDefect::SetLayoutSupportUn
const PART_VIEWS: RuntimeDriverDefect = RuntimeDriverDefect::LazilyAllocatedSubresourceViews;
const BIND_COPIES: RuntimeDriverDefect = RuntimeDriverDefect::HostTransferImagesCopiedAtBind;
const LOST_SIGNALS: RuntimeDriverDefect = RuntimeDriverDefect::WaitForAnyObjectLosesASignal;
const CHROMA: RuntimeDriverDefect = RuntimeDriverDefect::TwoPlaneChromaMisplaced;
const TEN_BIT_WORDS: RuntimeDriverDefect = RuntimeDriverDefect::TenBitCodesReadAsWords;
/// Every committed profile's driver has its defects at every release and GPU but those a probe
/// found clean: MoltenVK the multisampled depth/stencil colour copies, the inexact depths past
@@ -38,9 +40,11 @@ const LOST_SIGNALS: RuntimeDriverDefect = RuntimeDriverDefect::WaitForAnyObjectL
/// submission encoding meanwhile, the pushed sets' unset buffer sizes, the set layouts its support
/// query refuses though it runs them, the textureless views of some of a lazily allocated image's
/// levels or layers, the block-compressed image it copies out of host memory at bind time with a
/// one-block row pitch and the signal its wait for any of several objects loses; lavapipe the
/// one-block row pitch, the signal its wait for any of several objects loses and the misplaced
/// chroma of its two-plane Y′CbCr conversions; lavapipe the
/// colour copies, the depth/stencil resolve of the first layer and level, the explicit plane's
/// rows past its height and the baked samplers lost after a copy;
/// 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
/// preprocessing after an execution set on every GPU but the 780M (Phoenix's and Hawk Point's),
/// measured clean; ANV
@@ -76,9 +80,12 @@ fn the_committed_profiles_drivers_have_their_defects() {
PART_VIEWS,
BIND_COPIES,
LOST_SIGNALS,
CHROMA,
]
}
Some(DriverId::MESA_LLVMPIPE) => vec![COPIES, RESOLVES, PAST_HEIGHT, BAKED_SAMPLERS],
Some(DriverId::MESA_LLVMPIPE) => {
vec![COPIES, RESOLVES, PAST_HEIGHT, BAKED_SAMPLERS, TEN_BIT_WORDS]
}
// The 780M, under Phoenix's `deviceID` and Hawk Point's.
Some(DriverId::MESA_RADV) if matches!(desc.device_id, 0x15bf | 0x1900) => {
vec![NAN_COPIES]
@@ -2087,7 +2087,7 @@ fn the_priming_check_names_what_was_not_made() {
missing, Has, CALIBRATION_CALLS, COLOR_WRITE_MASK_CALLS, DEPTH_BIAS_CALLS,
DEVICE_ADDRESS_CALLS, EXTENDED_DYNAMIC_STATE_CALLS, GENERATED_COMMANDS_CALLS,
HOST_QUERY_RESET_CALLS, NAMING_CALLS, PRIMITIVE_RESTART_CALLS, PUSH_DESCRIPTOR_CALLS,
SIZED_INDEX_BIND_CALLS, SPARSE_CALLS, TIMESTAMP_CALLS, UNPRIMED,
SIZED_INDEX_BIND_CALLS, SPARSE_CALLS, TIMESTAMP_CALLS, UNPRIMED, YCBCR_CONVERSION_CALLS,
};
let has = |timestamps, device_addresses| Has {
timestamps,
@@ -2103,6 +2103,7 @@ fn the_priming_check_names_what_was_not_made() {
color_write_masks: true,
depth_bias: true,
sized_index_bind: true,
ycbcr_conversion: true,
};
let all = Call::ALL.iter().fold(0, |bits, call| bits | call.bit());
assert!(missing(all, has(true, true)).is_empty());
@@ -2199,7 +2200,7 @@ fn the_priming_check_names_what_was_not_made() {
assert!(missing(unnamed, without).is_empty());
assert_eq!(missing(unnamed, has(true, true)), NAMING_CALLS);
// Without a render encoder's command of an extension or of Vulkan 1.3, nor is that command.
let groups: [(&[Call], fn(Has) -> Has); 5] = [
let groups: [(&[Call], fn(Has) -> Has); 6] = [
(&EXTENDED_DYNAMIC_STATE_CALLS, |has| Has {
extended_dynamic_state: false,
..has
@@ -2220,6 +2221,11 @@ fn the_priming_check_names_what_was_not_made() {
sized_index_bind: false,
..has
}),
// Without a YCbCr format the device converts, nor is a conversion's release.
(&YCBCR_CONVERSION_CALLS, |has| Has {
ycbcr_conversion: false,
..has
}),
];
for (calls, without) in groups {
let unmade = calls.iter().fold(made, |bits, call| bits & !call.bit());
@@ -299,4 +299,6 @@ mod word_fill;
mod wrapped;
mod written_commands;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod ycbcr_device;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod ycbcr_refresh;
@@ -0,0 +1,562 @@
//! The device's own Y′CbCr conversion of two-plane YCbCr textures (`ycbcr_device.rs`).
//!
//! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`,
//! `m2v_cpu_icd`), on the kind of device the cfg selects. Each surface is a `Shared` buffer of
//! random codes standing for a CoreVideo surface of its OSType: the luma plane at byte 0 and the
//! interleaved chroma plane after it, rows 64-byte aligned. A kernel reads every texel.
//!
//! Where the device converts the texture's format (`YCbCrSampler::of`), every texel is the
//! conversion Vulkan states for the sampler's chroma location and filter, the format's range
//! expansion and its model's matrix ([`spec_rgb`]), within [`SPEC_BOUND`]; the texture is
//! counted (`WorkCounts::ycbcr_device_conversions`, `ycbcr_device_samples`) and announced
//! (`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.
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,
ShaderCacheOptions, Size, SurfaceYCbCrMatrix, Texture, TextureDescriptor,
};
use metal2vulkan::bind::{ycbcr_read, YCbCrCodes, YCbCrMatrix, YCbCrOutput, YCbCrRange};
use metal2vulkan::error::RuntimeDriverDefect;
use metal2vulkan::metal::format::{ycbcr_format, ChromaSubsampling};
use metal2vulkan::metal::{PixelFormat, TextureUsage};
use std::path::Path;
use std::sync::{Arc, Mutex};
/// The largest distance of a texel's channel, in units of `1/2048`, from Vulkan's conversion
/// ([`spec_rgb`]; before the sRGB curve, for the formats read through it) the device's may take,
/// past the `half` a converted format's image stores: at most 0.025 measured on lavapipe (Mesa
/// 26.0.8, LLVM 21.1.8), whose 8-bit 4:4:4 layout is the one it converts (0.038 over the
/// validation lanes' surfaces).
const SPEC_BOUND: f64 = 0.04;
/// A kernel that reads every texel of texture 0 into buffer 0, `float4`s in rows of the grid.
const READ: &str = r#"; Owned synthetic kernel.
source_filename = "ycbcr_device.metal"
define void @read_texels(ptr addrspace(1) %t, ptr addrspace(1) noalias %out, <2 x i32> %gid, <2 x i32> %size) {
entry:
%s = tail call ptr addrspace(2) @air.get_read_sampler()
%r = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) %t, ptr addrspace(2) %s, <2 x i32> %gid, <2 x i32> zeroinitializer, i32 0, i32 1)
%v = extractvalue { <4 x float>, i8 } %r, 0
%x = extractelement <2 x i32> %gid, i64 0
%y = extractelement <2 x i32> %gid, i64 1
%w = extractelement <2 x i32> %size, i64 0
%row = mul i32 %y, %w
%i = add i32 %row, %x
%j = zext i32 %i to i64
%p = getelementptr inbounds <4 x float>, ptr addrspace(1) %out, i64 %j
store <4 x float> %v, ptr addrspace(1) %p, align 16
ret void
}
declare ptr addrspace(2) @air.get_read_sampler()
declare { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1), ptr addrspace(2), <2 x i32>, <2 x i32>, i32, i32)
!air.kernel = !{!0}
!air.version = !{!30}
!air.language_version = !{!31}
!0 = !{ptr @read_texels, !1, !2}
!1 = !{}
!2 = !{!3, !4, !5, !6}
!3 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d<float, read>", !"air.arg_name", !"t"}
!4 = !{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"out"}
!5 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint2", !"air.arg_name", !"gid"}
!6 = !{i32 3, !"air.threads_per_grid", !"air.arg_type_name", !"uint2", !"air.arg_name", !"size"}
!30 = !{i32 2, i32 8, i32 0}
!31 = !{!"Metal", i32 4, i32 0, i32 0}
"#;
/// The notices a device announced.
type Heard = Arc<Mutex<Vec<DegradeNotice>>>;
/// A device of the kind the cfg selects, its notices into `heard`.
fn device(cache: &Path, heard: &Heard) -> Device {
let heard = Arc::clone(heard);
let options = DeviceOptions {
kinds: match cfg!(m2v_cpu_icd) {
true => vec![DeviceKind::Cpu],
false => vec![
DeviceKind::Discrete,
DeviceKind::Integrated,
DeviceKind::Virtual,
],
},
shader_cache: ShaderCacheOptions {
directory: Some(cache.to_owned()),
..ShaderCacheOptions::default()
},
messages: Some(MessageSink::new(move |message| {
if let Some(notice) = &message.degradation {
heard.lock().unwrap().push(notice.clone());
}
})),
announce_each: [Degradation::YCbCrFilterNotExact].into_iter().collect(),
..DeviceOptions::default()
};
Device::system_default_with(&options).unwrap()
}
/// The read kernel's state on `device`.
fn read_state(device: &Device) -> ComputePipelineState {
let air = metal2vulkan_devtools::llvm_assemble_text(READ).unwrap();
let library = metal2vulkan::library::Library::from_air(&air).unwrap();
let function = device
.new_library_with_compile_library(library)
.new_function_with_name("read_texels")
.unwrap();
device
.new_compute_pipeline_state_with_function(&function, &PipelineOptions::default())
.unwrap()
}
/// One texture: its format over a surface of `ostype` and `size`, with `matrix`.
#[derive(Clone, Copy, Debug)]
struct Case {
pf: PixelFormat,
ostype: &'static [u8; 4],
size: [u64; 2],
matrix: Option<SurfaceYCbCrMatrix>,
}
impl Case {
fn codes(&self) -> YCbCrCodes {
ycbcr_format(self.pf).and_then(YCbCrCodes::of).unwrap()
}
fn range(&self) -> YCbCrRange {
match self.ostype[3] == b'f' || self.ostype[1] == b'f' {
true => YCbCrRange::Full,
false => YCbCrRange::Video,
}
}
fn matrix(&self) -> YCbCrMatrix {
match self.matrix {
Some(SurfaceYCbCrMatrix::Itu709) => YCbCrMatrix::Bt709,
Some(SurfaceYCbCrMatrix::Itu2020) => YCbCrMatrix::Bt2020,
_ => YCbCrMatrix::Bt601,
}
}
/// The chroma plane's pairs across and rows.
fn chroma(&self) -> [u64; 2] {
let halved = self.codes().subsampling.halved();
[0, 1].map(|axis| match halved[axis] {
true => self.size[axis].div_ceil(2),
false => self.size[axis],
})
}
/// The luma plane's row bytes and the chroma plane's, each 64-byte aligned, and where the
/// chroma plane starts.
fn layout(&self) -> (u64, u64, u64) {
let unit = u64::from(self.codes().bytes);
let luma = (self.size[0] * unit).next_multiple_of(64);
let chroma = (2 * self.chroma()[0] * unit).next_multiple_of(64);
(luma, chroma, luma * self.size[1])
}
fn length(&self) -> u64 {
let (_, chroma, at) = self.layout();
at + chroma * self.chroma()[1]
}
}
/// The surface's bytes: random codes from `seed`, every unit's every bit random.
fn surface_bytes(case: &Case, seed: u64) -> Vec<u8> {
let mut state = seed;
let mut next = || {
state = state
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
(state >> 56) as u8
};
(0..case.length()).map(|_| next()).collect()
}
/// Code `i` of the row at byte `at` of `bytes`, of `codes`.
fn code(bytes: &[u8], codes: YCbCrCodes, at: u64, i: u64) -> u16 {
match codes.bytes {
1 => u16::from(bytes[(at + i) as usize]),
_ => {
let at = (at + 2 * i) as usize;
u16::from_le_bytes([bytes[at], bytes[at + 1]]) >> (16 - codes.bits)
}
}
}
/// The luma code at `(x, y)`, and the chroma pair `(i, j)`'s Cb and Cr.
fn codes_at(
case: &Case,
bytes: &[u8],
) -> (impl Fn(u64, u64) -> u16, impl Fn(u64, u64) -> [u16; 2]) {
let codes = case.codes();
let (luma_row, chroma_row, chroma_at) = case.layout();
let luma = {
let bytes = bytes.to_vec();
move |x: u64, y: u64| code(&bytes, codes, y * luma_row, x)
};
let chroma = {
let bytes = bytes.to_vec();
move |i: u64, j: u64| {
let at = chroma_at + j * chroma_row;
[
code(&bytes, codes, at, 2 * i),
code(&bytes, codes, at, 2 * i + 1),
]
}
};
(luma, chroma)
}
/// Metal's read of texel `(x, y)` (`bind::ycbcr_read` after Metal's chroma filter: 9/3/3/1 of
/// 4:2:0, 3/1 of 4:2:2, each sum rounded), as values.
fn metal_rgb(case: &Case, bytes: &[u8], (x, y): (u64, u64)) -> [f64; 3] {
let codes = case.codes();
let (luma, chroma) = codes_at(case, bytes);
let [cw, ch] = case.chroma();
let halved = codes.subsampling.halved();
// The taps of one axis: the nearer pair weighted 3, the farther 1, clamped.
let taps = |v: u64, n: u64, halved: bool| -> Vec<(u64, u64)> {
match halved {
false => vec![(v, 4)],
true => {
let near = v / 2;
let far = match v % 2 {
1 => (near + 1).min(n - 1),
_ => near.saturating_sub(1),
};
vec![(near, 3), (far, 1)]
}
}
};
let across = taps(x, cw, halved[0]);
let down = taps(y, ch, halved[1]);
let mut sums = [0u64; 2];
for &(i, wi) in &across {
for &(j, wj) in &down {
let pair = chroma(i, j);
for c in 0..2 {
sums[c] += wi * wj * u64::from(pair[c]);
}
}
}
let [cb, cr] = sums.map(|s| ((s + 8) >> 4) as u16);
let read = ycbcr_read(codes, (case.range(), case.matrix()), [luma(x, y), cb, cr]);
let grid = match codes.output {
YCbCrOutput::Srgb => 8192.0,
YCbCrOutput::Codes => f64::from((1u32 << codes.bits) - 1),
_ => 2048.0,
};
read.map(|v| f64::from(v) / grid)
}
/// The sRGB curve's inverse: the value a channel `l` of a texel read through it was decoded
/// from, which [`spec_rgb`] states.
fn unsrgb(l: f64) -> f64 {
match l <= 0.04045 / 12.92 {
true => l * 12.92,
false => 1.055 * l.powf(1.0 / 2.4) - 0.055,
}
}
/// Vulkan's conversion of texel `(x, y)` sampled at its centre (implicit reconstruction at the
/// midpoint through a linear chroma filter, the only one the runtime takes of a subsampled
/// format; the range expansion; the model's matrix), as the sample module writes it, unclamped,
/// or rounded to codes; before the sRGB curve, for a format read through it.
fn spec_rgb(case: &Case, bytes: &[u8], (x, y): (u64, u64)) -> [f64; 3] {
let codes = case.codes();
let max = f64::from((1u32 << codes.bits) - 1);
let (luma, chroma) = codes_at(case, bytes);
let [cw, ch] = case.chroma();
let halved = codes.subsampling.halved();
// The taps of one axis at luma texel `v`'s centre, in the chroma plane's texel space.
let taps = |v: u64, n: u64, halved: bool| -> Vec<(u64, f64)> {
if !halved {
return vec![(v, 1.0)];
}
let clamp = |i: f64| (i.max(0.0) as u64).min(n - 1);
let q = (v as f64 + 0.5) / 2.0 - 0.5;
let i0 = q.floor();
let f = q - i0;
vec![(clamp(i0), 1.0 - f), (clamp(i0 + 1.0), f)]
};
let across = taps(x, cw, halved[0]);
let down = taps(y, ch, halved[1]);
let mut c = [0.0f64; 2];
for &(i, wi) in &across {
for &(j, wj) in &down {
let pair = chroma(i, j);
for k in 0..2 {
c[k] += wi * wj * f64::from(pair[k]) / max;
}
}
}
let y_code = f64::from(luma(x, y));
if codes.output == YCbCrOutput::Codes {
return [c[1], y_code / max, c[0]]
.map(|v| (v.clamp(0.0, 1.0) * max).round_ties_even() / max);
}
let n = codes.bits as i32;
let scale = f64::from(1u32 << (n - 8));
let (luma, cb, cr) = match case.range() {
YCbCrRange::Video => (
(y_code - 16.0 * scale) / (219.0 * scale),
(c[0] * max - 128.0 * scale) / (224.0 * scale),
(c[1] * max - 128.0 * scale) / (224.0 * scale),
),
_ => {
let mid = f64::from(1u32 << (n - 1)) / max;
(y_code / max, c[0] - mid, c[1] - mid)
}
};
let (kr, kb) = match case.matrix() {
YCbCrMatrix::Bt709 => (0.2126, 0.0722),
YCbCrMatrix::Bt2020 => (0.2627, 0.0593),
_ => (0.299, 0.114),
};
let kg = 1.0 - kr - kb;
[
luma + 2.0 * (1.0 - kr) * cr,
luma - 2.0 * kb * (1.0 - kb) / kg * cb - 2.0 * kr * (1.0 - kr) / kg * cr,
luma + 2.0 * (1.0 - kb) * cb,
]
}
/// A texture of `case` over `surface`'s plane 0.
fn texture(case: &Case, surface: &Buffer) -> Texture {
let [w, h] = case.size;
let mut d = TextureDescriptor::texture_2d(case.pf, w, h, false);
d.usage = TextureUsage::SHADER_READ;
d.resource_options = ResourceOptions::shared();
let (luma_row, chroma_row, chroma_at) = case.layout();
let mut facts = IoSurfaceYCbCr::new(
u32::from_be_bytes(*case.ostype),
0,
case.size,
chroma_at,
chroma_row,
);
if let Some(matrix) = case.matrix {
facts = facts.with_matrix(matrix);
}
surface
.new_texture_with_iosurface_plane(
&d,
IoSurfacePlane::new(0, luma_row, true).with_ycbcr(facts),
)
.unwrap()
}
/// Every texel `state` reads of `texture`, `[r, g, b]` in rows.
fn read(
device: &Device,
state: &ComputePipelineState,
case: &Case,
texture: &Texture,
) -> Vec<[f32; 3]> {
let [w, h] = case.size;
let out = device
.new_buffer(16 * w * h, ResourceOptions::shared())
.unwrap();
let queue = device.new_command_queue().unwrap();
let command_buffer = queue.command_buffer().unwrap();
let mut encoder = command_buffer.compute_command_encoder().unwrap();
encoder.set_compute_pipeline_state(state).unwrap();
encoder.set_texture(Some(texture), 0).unwrap();
encoder.set_buffer(Some(&out), 0, 0).unwrap();
encoder
.dispatch_threads(Size::new(w, h, 1), Size::new(8, 8, 1))
.unwrap();
encoder.end_encoding().unwrap();
command_buffer.commit().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(command_buffer.error(), None);
let contents = out.contents().unwrap();
// SAFETY: the buffer's bytes, which no command uses now.
let bytes = unsafe { std::slice::from_raw_parts(contents.as_ptr(), (16 * w * h) as usize) };
bytes
.as_chunks::<16>()
.0
.iter()
.map(|t| {
[0, 1, 2]
.map(|c| f32::from_le_bytes([t[4 * c], t[4 * c + 1], t[4 * c + 2], t[4 * c + 3]]))
})
.collect()
}
/// Every case: each layout the device may convert, both ranges, three matrices, an even and an
/// odd size, the code-reading and the sRGB-reading formats.
fn cases() -> Vec<Case> {
let even = [40, 24];
let odd = [41, 23];
let mut out = Vec::new();
for (pf, ostype, size) in [
(PixelFormat::YCBCR84202P, b"420v", even),
(PixelFormat::YCBCR84202P, b"420f", odd),
(PixelFormat::YCBCR84222P, b"422v", even),
(PixelFormat::YCBCR84442P, b"444f", even),
(PixelFormat::YCBCR104202P, b"x420", even),
(PixelFormat::YCBCR104202P, b"xf20", odd),
(PixelFormat::YCBCR104222P, b"x422", even),
(PixelFormat::YCBCR104442P, b"x444", even),
(PixelFormat::RGB84202P, b"420v", even),
(PixelFormat::RGB104442P, b"x444", even),
(PixelFormat::YCBCR84202PSRGB, b"420v", even),
(PixelFormat::YCBCR104202PSRGB, b"xf20", even),
] {
for matrix in [
None,
Some(SurfaceYCbCrMatrix::Itu709),
Some(SurfaceYCbCrMatrix::Itu2020),
] {
out.push(Case {
pf,
ostype,
size,
matrix,
});
}
}
out
}
/// Each texture whose format the device converts reads Vulkan's conversion of its planes at
/// every texel, within [`SPEC_BOUND`], counted and announced; every other reads Metal's
/// exactly. A 4:2:0 or 4:2:2 texture takes it only at Metal's midpoint chroma. On MoltenVK, whose
/// two-plane chroma reconstruction is misplaced (`RuntimeDriverDefect::TwoPlaneChromaMisplaced`),
/// no 4:2:0 or 4:2:2 texture takes it; on lavapipe, which reads 10-bit codes as 16-bit words
/// (`RuntimeDriverDefect::TenBitCodesReadAsWords`), no 10-bit one.
#[test]
fn a_ycbcr_texture_reads_the_devices_conversion_where_it_converts_the_format() {
let scratch = Scratch::new("ycbcr-device");
let heard: Heard = Arc::default();
let device = device(&scratch.0, &heard);
let state = read_state(&device);
let defects = &device.properties().driver_defects;
let misplaced = defects.contains(&RuntimeDriverDefect::TwoPlaneChromaMisplaced);
let words = defects.contains(&RuntimeDriverDefect::TenBitCodesReadAsWords);
let mut taken = 0;
for (n, case) in cases().into_iter().enumerate() {
let bytes = surface_bytes(&case, 17 + n as u64);
let surface = device
.new_buffer_with_bytes(&bytes, ResourceOptions::shared())
.unwrap();
heard.lock().unwrap().clear();
let before = device.work_counts();
let texture = texture(&case, &surface);
let texels = read(&device, &state, &case, &texture);
let after = device.work_counts();
let copies = texture.shadow().expect("a converted texture's shadow");
let ShadowSource::Converted { conversion, .. } = &copies.source else {
panic!("a converted texture's source");
};
let planes = conversion.source().0;
let form = YCbCrSampler::of(&device, &planes, false).map(|sampler| sampler.chroma());
let conversions = after.ycbcr_device_conversions - before.ycbcr_device_conversions;
let samples = after.ycbcr_device_samples - before.ycbcr_device_samples;
let announced = heard
.lock()
.unwrap()
.iter()
.filter(|notice| notice.degradation == Degradation::YCbCrFilterNotExact)
.count();
let subsampled = case.codes().subsampling != ChromaSubsampling::Chroma444;
if (misplaced && subsampled) || (words && case.codes().bits == 10) {
assert_eq!(form, None, "{case:?}: the defect keeps Metal's arithmetic");
}
if let Some((midpoint, linear)) = form {
assert!(
(midpoint && linear) || !subsampled,
"{case:?}: Metal's reconstruction, the midpoint through a linear chroma filter"
);
}
let [w, h] = case.size;
let (mut spec_far, mut metal_far, mut metal_far_in, mut outside) =
(0.0f64, 0.0f64, 0.0f64, 0);
for y in 0..h {
for x in 0..w {
let got = texels[(y * w + x) as usize].map(f64::from);
let metal = metal_rgb(&case, &bytes, (x, y));
match form {
Some(_) => {
let spec = spec_rgb(&case, &bytes, (x, y));
let decoded = match case.codes().output {
YCbCrOutput::Srgb => got.map(unsrgb),
_ => got,
};
let inside = spec.iter().all(|v| (0.0..=1.0).contains(v));
outside += usize::from(!inside);
for c in 0..3 {
// A converted format's image holds `half`s: the device's value lies
// within one unit in the last place of the stored one
// (`PrecisionNote::NativeHalfConversion`).
let ulp = match case.codes().output {
YCbCrOutput::Converted => 2f64.powi(
got[c].abs().max(2f64.powi(-14)).log2().floor() as i32 - 10,
),
_ => 0.0,
};
let far = ((decoded[c] - spec[c]).abs() - ulp).max(0.0);
spec_far = spec_far.max(far * 2048.0);
let far = (got[c] - metal[c]).abs() * 2048.0;
metal_far = metal_far.max(far);
if inside {
metal_far_in = metal_far_in.max(far);
}
}
}
None => {
let (got, metal) = (got.map(|v| v as f32), metal.map(|v| v as f32));
// A code's value is the device's conversion of the texture's format's
// normalized code, within one unit in the last place
// (`PrecisionNote::DeviceTexelConversion`); every other output exact.
let ulps = match case.codes().output {
YCbCrOutput::Codes => 1,
_ => 0,
};
assert!(
(0..3).all(|c| got[c].to_bits().abs_diff(metal[c].to_bits()) <= ulps),
"{case:?} texel ({x}, {y}): {got:?}, Metal's read {metal:?}"
);
}
}
}
}
match form {
Some(form) => {
taken += 1;
println!(
"{:?} {} {:?} {w}x{h} midpoint/linear {form:?}: from Vulkan's {spec_far:.4}/2048, \
from Metal's {metal_far:.2}/2048 ({metal_far_in:.4} in [0, 1]), {outside} \
texels outside [0, 1]",
case.pf,
String::from_utf8_lossy(case.ostype),
case.matrix,
);
assert!(
spec_far <= SPEC_BOUND,
"{case:?}: {spec_far} from Vulkan's conversion"
);
assert_eq!((conversions, samples), (1, 1), "{case:?}: counted");
assert_eq!(announced, 1, "{case:?}: announced");
}
None => {
assert_eq!(
(conversions, samples),
(0, 0),
"{case:?}: Metal's arithmetic"
);
assert_eq!(announced, 0, "{case:?}: exact, unannounced");
}
}
}
println!("{taken} textures took the device's conversion");
}
@@ -135,6 +135,8 @@ pub(crate) struct Counters {
ycbcr_textures_in_place: AtomicU64,
ycbcr_images_kept: [AtomicU64; 7],
ycbcr_planes_bound: AtomicU64,
ycbcr_device_conversions: AtomicU64,
ycbcr_device_samples: AtomicU64,
attachment_clears_recorded: AtomicU64,
image_blits_recorded: AtomicU64,
query_result_copies_recorded: AtomicU64,
@@ -673,6 +675,19 @@ impl Counters {
self.ycbcr_planes_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) {
self.ycbcr_device_conversions
.fetch_add(1, Ordering::Relaxed);
}
/// A sampling of a YCbCr texture's planes' image through the device's own Y′CbCr conversion
/// was recorded (`ycbcr_device.rs`).
pub(crate) fn ycbcr_device_sampled(&self) {
self.ycbcr_device_samples.fetch_add(1, Ordering::Relaxed);
}
/// A `VkCommandPool` was made for a command buffer, none of the device's spares taken.
pub(crate) fn command_pool_made(&self) {
self.command_pools_made.fetch_add(1, Ordering::Relaxed);
@@ -3272,6 +3287,14 @@ 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' 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.
pub ycbcr_device_conversions: u64,
/// Samplings of two-plane YCbCr textures' planes' images through the device's own Y′CbCr
/// conversion recorded: one per conversion or load of such a texture, run through the
/// refresh's indirect arguments where it has one.
pub ycbcr_device_samples: u64,
// The commands MoltenVK 1.4.1 compiles a pipeline for per command pool on Apple's GPUs
// (`PoolCompiled`), each counted as the runtime records it: a run's survey of which can
// stall a commit behind a compile storm, as the fill did.
@@ -4875,6 +4898,8 @@ 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_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),
image_blits_recorded: counters.image_blits_recorded.load(Ordering::Relaxed),
query_result_copies_recorded: counters
+183 -67
View File
@@ -38,6 +38,18 @@
//! (`bind::ycbcr_convert_module`, `owned_kernel.rs`) writing every texel. The texture reads
//! alpha 1 (`alpha_reads_one`) and maps those modes to clamp-to-edge (`address_mode_map`), so
//! a nearest sample and a border read are Metal's exactly.
//! - **The device's own conversion.** Where the device converts the planes' format itself (a
//! sampler Y′CbCr conversion of the multi-planar format: unpacked 8- or 10-bit codes over plane
//! 0 that form one image, `ycbcr_device.rs`), the conversion's dispatch copies the staging
//! buffer's planes into an image of that format and samples it through the device's
//! conversion, once per texel (`bind::ycbcr_sample_module`), into the same image of the
//! texture: its texels are the device's answer, not Metal's, announced where the texture is
//! made (`ycbcr-filter-not-exact`; `WorkCounts::ycbcr_device_conversions`,
//! `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`).
//! - **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
@@ -66,10 +78,14 @@
//! `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.
//! 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 exact; the
//! choice is the cheaper one by device kind, measured as GPU time of a 3840 x 2160 texture whose
//! across its bus at every pass, where the image lies in its own memory. Both forms are Metal's
//! (but for the image of a device that converts the format itself); the choice is the cheaper one
//! by device kind, measured as GPU time of a 3840 x 2160 texture whose
//! planes lie in host memory composited into 1680 x 1050 (µs, best of 3 x 40; the image's form
//! the refresh's compare and the samples, over unchanged planes; Mesa 26.2.4, MoltenVK 1.4.2):
//!
@@ -176,9 +192,12 @@
//! storing every texel ([`YCbCrWriteBack`] of a store), and the texture's converted texels
//! convert again at their next use. A pass that clears the attachment, or leaves it to the pass
//! (`DontCare`), clears the shadow at its copy in and stores every texel, exact. A pass that
//! loads it loads each texel as the texture reads it ([`YCbCrLoad`], the conversion kernel
//! writing floats), and Metal stores only the 32x32 tiles its draws reach, every texel of each
//! re-encoded, leaving the others' bytes (a load with no draw stores nothing): the copy back
//! loads it loads each texel as Metal's arithmetic reads it ([`YCbCrLoad`], the conversion
//! kernel writing floats; Metal's even where the texture's texels are the device's
//! conversion's, since the store inverts Metal's read and a loaded texel no draw changes is to
//! keep its codes, as `MTLLoadActionLoad` keeps the attachment's contents), and Metal stores
//! only the 32x32 tiles its draws reach, every texel of each re-encoded, leaving the others'
//! bytes (a load with no draw stores nothing): the copy back
//! stores the tiles of the pass's drawn area (`render/shadows.rs`'s `DrawnArea`, the scissored
//! bounds of its draws), so a tile inside that area that no primitive reaches is re-encoded
//! where Metal keeps its bytes, announced (`ycbcr-load-tiles`). A `DontCare` store, and a store
@@ -210,7 +229,9 @@ use super::shadow::ShadowCopies;
use super::texture_descriptor::TextureLayout;
use super::tracker::{Access, Barrier, Use, UseRange};
use super::values::ResourceOptions;
use super::ycbcr_device::{YCbCrDeviceSampling, YCbCrSampler};
use super::Device;
use crate::degradation::Degradation;
use crate::device::functions::Vk;
use ash::vk;
use metal2vulkan::bind::{
@@ -503,14 +524,138 @@ pub(super) struct YCbCrConversion {
/// Where the zeros a texture over plane 1 reads as its chroma lie in the staging buffer's
/// `VkBuffer`, and their bytes (0 for every other texture).
zeros: (u64, u64),
kernel: OwnedKernel,
sets: OwnedSets,
converts: Converts,
groups: [u32; 2],
/// The refresh that converts only where the planes changed, where the device makes it
/// ([`YCbCrRefresh`]); every conversion is whole without it.
refresh: Option<YCbCrRefresh>,
}
/// How a conversion turns its staging copy of the planes into texels: Metal's arithmetic (the
/// conversion kernel, `bind::ycbcr_convert_module`), or the device's own Y′CbCr conversion where
/// it converts the planes' format (`ycbcr_device.rs`).
enum Converts {
Ours {
kernel: OwnedKernel,
sets: OwnedSets,
},
Device(Box<YCbCrDeviceSampling>),
}
impl Converts {
/// The conversion of `planes` (whose staging copy lies at `bytes` of the staging buffer's
/// `VkBuffer`, `held` bytes from it) into `view`, a storage view of an image of their texels:
/// the device's where it converts them, else [`ours`](Self::ours). `zeros` says whether the
/// planes read zeros past their bytes. The workgroups of its dispatch too.
fn new(
device: &Device,
planes: &YCbCrPlanes,
(raw, bytes, held): (vk::Buffer, u64, u64),
(shape_at, zeros): (u64, bool),
view: vk::ImageView,
) -> Result<(Converts, [u32; 2]), Error> {
// The staging copy's planes at a multiple of 4 bytes, every plane's element size or a
// multiple of it (`ycbcr_device.rs`).
let sampler = YCbCrSampler::of(device, planes, zeros).filter(|_| bytes % 4 == 0);
if let Some(sampler) = sampler {
let sampling = YCbCrDeviceSampling::new(device, (planes, sampler), view)?;
let groups = sampling.groups();
announce_device_conversion(device, planes);
return Ok((Converts::Device(Box::new(sampling)), groups));
}
Converts::ours(device, planes, (raw, bytes, held), shape_at, (view, false))
}
/// Metal's fixed-point conversion of `planes` (as [`new`](Self::new)'s) into `view`: of their
/// texels, or, `floats`, of a render shadow's floats. The workgroups of its dispatch too.
fn ours(
device: &Device,
planes: &YCbCrPlanes,
(raw, bytes, held): (vk::Buffer, u64, u64),
shape_at: u64,
(view, floats): (vk::ImageView, bool),
) -> Result<(Converts, [u32; 2]), Error> {
let kernel = device.owned_kernel(OwnedModule::YCbCrConvert(planes.conversion(), floats))?;
let set = OwnedSet {
images: Vec::new(),
storage_images: vec![view],
buffers: vec![
(
raw,
shape_at,
4 * u64::from(YCbCrConvertModule::SHAPE_WORDS),
),
(raw, bytes, held),
],
};
let sets = OwnedSets::write_each(device, &[kernel], &[set])?;
let groups = planes
.size
.map(|n| n.div_ceil(YCbCrConvertModule::LOCAL_SIZE));
Ok((Converts::Ours { kernel, sets }, groups))
}
/// Record the conversion of the staging copy at `bytes` of `staging` (written before, a
/// barrier recorded): dispatched through the indirect arguments at `indirect` of `staging`
/// where given, else over every texel (`groups`).
///
/// # Safety
///
/// As [`YCbCrConversion::record`]'s.
unsafe fn record(
&self,
device: &Vk,
command_buffer: vk::CommandBuffer,
(staging, bytes): (vk::Buffer, u64),
indirect: Option<u64>,
groups: [u32; 2],
) {
match self {
Converts::Device(sampling) => {
// SAFETY: the caller's.
unsafe { sampling.record(device, command_buffer, (staging, bytes), indirect) }
}
// SAFETY: the caller's; the set binds the shape and the copy.
Converts::Ours { kernel, sets } => unsafe {
let point = vk::PipelineBindPoint::COMPUTE;
device.cmd_bind_pipeline(command_buffer, point, kernel.pipeline);
device.cmd_bind_descriptor_sets(
command_buffer,
point,
kernel.layout,
0,
&sets.sets,
&[],
);
match indirect {
Some(at) => device.cmd_dispatch_indirect(command_buffer, staging, at),
None => device.cmd_dispatch(command_buffer, groups[0], groups[1], 1),
}
},
}
}
}
/// Announce, as a texture of `planes` is made, that its texels are the device's own Y′CbCr
/// conversion's (`ycbcr_device.rs`), naming its layout.
fn announce_device_conversion(device: &Device, planes: &YCbCrPlanes) {
device.degrade(Degradation::YCbCrFilterNotExact, || {
(
"texture".to_owned(),
format!(
"a two-plane YCbCr texture of {}-bit {:?} codes ({:?}, {:?}, {:?}) reads the \
device's own sampler Y′CbCr conversion of its planes, not Metal's fixed-point \
one",
planes.codes.bits,
planes.codes.subsampling,
planes.codes.output,
planes.range,
planes.matrix
),
)
});
}
/// The refresh of a conversion's staging copy (the module docs' **When it converts**): one
/// dispatch of the refresh kernel (`bind::ycbcr_refresh_module`) compares the planes' words with
/// the copy, stores each changed one over it, and writes the conversion's group count into the
@@ -609,19 +754,13 @@ impl YCbCrConversion {
let (raw, start) = staging.at(0);
let (identity, range) = staging.tracked(0..BYTES_AT + held);
let shape = YCbCrConvertModule::shape(planes);
let kernel = device.owned_kernel(OwnedModule::YCbCrConvert(planes.conversion(), false))?;
let set = OwnedSet {
images: Vec::new(),
storage_images: vec![view],
buffers: vec![
(raw, start, shape.len() as u64),
(raw, start + BYTES_AT, held),
],
};
let sets = OwnedSets::write_each(device, &[kernel], &[set])?;
let groups = planes
.size
.map(|n| n.div_ceil(YCbCrConvertModule::LOCAL_SIZE));
let (converts, groups) = Converts::new(
device,
planes,
(raw, start + BYTES_AT, held),
(start, zeros > 0),
view,
)?;
let limits = &device.properties().description.limits;
if groups[0] > limits.max_compute_work_group_count[0]
|| groups[1] > limits.max_compute_work_group_count[1]
@@ -643,8 +782,7 @@ impl YCbCrConversion {
},
zeros: (start + BYTES_AT + bytes, zeros),
staging,
kernel,
sets,
converts,
groups,
refresh,
})
@@ -799,23 +937,13 @@ impl YCbCrConversion {
}
}
Barrier::everything().record(device, command_buffer);
device.cmd_bind_pipeline(
self.converts.record(
device,
command_buffer,
vk::PipelineBindPoint::COMPUTE,
self.kernel.pipeline,
(staging, self.shape_at + BYTES_AT),
refresh.map(|_| state_at),
self.groups,
);
device.cmd_bind_descriptor_sets(
command_buffer,
vk::PipelineBindPoint::COMPUTE,
self.kernel.layout,
0,
&self.sets.sets,
&[],
);
match refresh {
Some(_) => device.cmd_dispatch_indirect(command_buffer, staging, state_at),
None => device.cmd_dispatch(command_buffer, self.groups[0], self.groups[1], 1),
}
Barrier::everything().record(device, command_buffer);
device.cmd_update_buffer(command_buffer, staging, completed_at, &word(1));
}
@@ -854,14 +982,15 @@ pub(super) struct YCbCrWriteBack {
/// The load of a render shadow (the module docs' **Passes**): the copy in of a pass that loads
/// the attachment, which converts the planes' bytes into the shadow as floats through the
/// conversion kernel (`bind::ycbcr_convert_floats_module`), each texel what the texture reads.
/// conversion kernel (`bind::ycbcr_convert_floats_module`), each texel what Metal's arithmetic
/// reads (the module docs' **Passes**).
/// It shares the write-back's staging buffer, its shape past the planes' bytes.
struct YCbCrLoad {
/// Where the shape lies in the staging buffer's `VkBuffer`.
shape_at: u64,
shape: [u8; YCbCrConvertModule::SHAPE_WORDS as usize * 4],
kernel: OwnedKernel,
sets: OwnedSets,
/// The load's conversion: ours, always.
converts: Converts,
groups: [u32; 2],
}
@@ -1121,20 +1250,13 @@ impl YCbCrWriteBack {
device.cmd_update_buffer(command_buffer, staging, load.shape_at, &load.shape);
device.cmd_copy_buffer(command_buffer, source, staging, &[self.into]);
Barrier::everything().record(device, command_buffer);
device.cmd_bind_pipeline(
load.converts.record(
device,
command_buffer,
vk::PipelineBindPoint::COMPUTE,
load.kernel.pipeline,
(staging, self.bytes_at[0]),
None,
load.groups,
);
device.cmd_bind_descriptor_sets(
command_buffer,
vk::PipelineBindPoint::COMPUTE,
load.kernel.layout,
0,
&load.sets.sets,
&[],
);
device.cmd_dispatch(command_buffer, load.groups[0], load.groups[1], 1);
}
}
}
@@ -1151,24 +1273,18 @@ impl YCbCrLoad {
view: vk::ImageView,
) -> Result<YCbCrLoad, Error> {
let shape = YCbCrConvertModule::shape(planes);
let kernel = device.owned_kernel(OwnedModule::YCbCrConvert(planes.conversion(), true))?;
let set = OwnedSet {
images: Vec::new(),
storage_images: vec![view],
buffers: vec![
(raw, start + shape_at, shape.len() as u64),
(raw, start + BYTES_AT, held),
],
};
let sets = OwnedSets::write_each(device, &[kernel], &[set])?;
let groups = planes
.size
.map(|n| n.div_ceil(YCbCrConvertModule::LOCAL_SIZE));
// A texture that takes passes reads no zeros past its planes (`texture/ycbcr_image.rs`).
let (converts, groups) = Converts::ours(
device,
planes,
(raw, start + BYTES_AT, held),
start + shape_at,
(view, true),
)?;
Ok(YCbCrLoad {
shape_at: start + shape_at,
shape,
kernel,
sets,
converts,
groups,
})
}
@@ -0,0 +1,721 @@
//! The device's own sampler Y′CbCr conversion of a two-plane YCbCr texture's planes
//! (`ycbcr.rs`): where the device converts the planes' format itself, the texture's image holds
//! the device's answer, and Metal's fixed-point conversion (`bind::ycbcr_convert_module`) runs
//! only where it does not.
//!
//! - **Which textures.** A texture whose planes form one image of a multi-planar format: 8-bit
//! or 10-bit codes unpacked (a byte, or the high 10 bits of a 16-bit word), the luma plane
//! and a chroma plane of Cb and Cr pairs at their own rows (no chroma codes 0, no rows past the
//! buffer; each plane at a multiple of its texel's bytes, its rows whole texels that do not
//! overlap), 4:2:0, 4:2:2 or 4:4:4: `G8_B8R8_2PLANE_420_UNORM`,
//! `G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16` and their 4:2:2 and 4:4:4 formats. The device
//! converts the format where it enables `samplerYcbcrConversion` (a device the runtime makes
//! enables it wherever it has it, outside the vocabulary: `device/create.rs`) and its optimal
//! tiling reports `SAMPLED_IMAGE`, `TRANSFER_DST` and a chroma location (Metal's midpoint,
//! `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
//! 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
//! (`WorkCounts::ycbcr_device_conversions` counts the device's).
//! - **The conversion** (`VkSamplerYcbcrConversion`): the surface's matrix (BT.601, BT.709 or
//! BT.2020 model) and range (`ITU_NARROW` video, `ITU_FULL` full), or the identity model of a
//! format read as codes; and Metal's reconstruction of a 4:2:0 or 4:2:2 format's chroma, its
//! midpoint (`MIDPOINT_CHROMA_SAMPLES`) through a linear chroma filter
//! (`SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER`, and a linear sampler filter or a separate
//! one). Vulkan's implicit reconstruction weighs a midpoint format's chroma 3 and 1 along a
//! halved axis, as Metal does; cosited, its chroma lies half a luma texel off, and nearest, it
//! takes one pair: what the surface's codes mean to Metal moves (up to 1340/2048 of random
//! planes, lavapipe, cosited), a capability the device lacks rather than a precision, so such
//! a format converts through Metal's arithmetic. A 4:4:4 format reconstructs nothing, so its
//! location and chroma filter are any the device has (linear where it has it). The sampler's
//! own filter is nearest where the format has `SEPARATE_RECONSTRUCTION_FILTER`, else the
//! chroma's, as Vulkan requires: "If sampler Y′CBCR
//! conversion is enabled and the potential format features of the sampler Y′CBCR conversion do
//! not support VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_SEPARATE_RECONSTRUCTION_FILTER_BIT,
//! minFilter and magFilter must be equal to the sampler Y′CBCR conversion’s chromaFilter"
//! (`VUID-VkSamplerCreateInfo-minFilter-01645`); each sample lies at a luma texel's centre, where
//! either filter reads that texel's luma.
//! - **The image and the dispatch.** The texture's conversion copies the planes from its staging
//! copy (`ycbcr.rs`'s refresh) into an optimal image of the format (its size rounded up to the
//! chroma block) and samples it once per texel into the texture's image
//! (`bind::ycbcr_sample_module`), through the refresh's indirect arguments: unchanged planes
//! copy their bytes and sample no workgroup. A render pass's load of the texture stays Metal's
//! arithmetic (`ycbcr.rs`): Metal's `MTLLoadActionLoad` keeps the attachment's contents, and the
//! store, ours (`bind::ycbcr_store`), inverts Metal's read, not the device's, so the device's
//! load would move the codes of texels the pass does not draw (lavapipe: by a code, over an
//! 8-bit 4:4:4 surface).
//! - **What it reads** is the device's answer, announced where the texture is made
//! (`ycbcr-filter-not-exact`): Vulkan states the reconstruction's weights and the model's
//! matrices, and leaves each step's precision at least the format's and the clamp of the result
//! into `[0, 1]` the implementation's ("An implementation may clamp the R′G′B′ results of these
//! conversions to the range [0,1]."). Measured at every texel of random planes
//! (`tests/ycbcr_device.rs`, and the validation crate's YCbCr lanes) on lavapipe (Mesa 26.0.8,
//! LLVM 21.1.8), which converts only the 8-bit 4:4:4 layout here (its 4:2:0 and 4:2:2
//! conversions site the chroma cosited alone, and its 10-bit ones read words,
//! `TenBitCodesReadAsWords`): each channel within 0.04/2048 of Vulkan's conversion past the
//! `half` the texture's image stores (0.038 at most), and of Metal's read within 6/2048 where
//! the result lies in `[0, 1]`; outside it, which lavapipe does not clamp, by what Metal's clamp
//! 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.
use super::device::lock;
use super::error::{vulkan, Error};
use super::memory::{MemoryClass, Placement};
use super::owned_kernel::{OwnedKernel, OwnedModule, OwnedSet, OwnedSets};
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::error::RuntimeDriverDefect;
use metal2vulkan::metal::format::ChromaSubsampling;
/// The formats the device is asked to convert, each of its codes' bits and subsampling.
const FORMATS: [(vk::Format, u32, ChromaSubsampling); 6] = [
(
vk::Format::G8_B8R8_2PLANE_420_UNORM,
8,
ChromaSubsampling::Chroma420,
),
(
vk::Format::G8_B8R8_2PLANE_422_UNORM,
8,
ChromaSubsampling::Chroma422,
),
(
vk::Format::G8_B8R8_2PLANE_444_UNORM,
8,
ChromaSubsampling::Chroma444,
),
(
vk::Format::G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16,
10,
ChromaSubsampling::Chroma420,
),
(
vk::Format::G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16,
10,
ChromaSubsampling::Chroma422,
),
(
vk::Format::G10X6_B10X6R10X6_2PLANE_444_UNORM_3PACK16,
10,
ChromaSubsampling::Chroma444,
),
];
/// 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)]
struct Converts {
format: vk::Format,
features: vk::FormatFeatureFlags,
extent: [u32; 2],
descriptors: u32,
}
/// The formats of [`FORMATS`] a device converts (the module docs): none where it does not enable
/// `samplerYcbcrConversion`.
#[derive(Clone, Default)]
pub(super) struct YCbCrFormats {
converts: Vec<Converts>,
}
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
/// `VK_EXT_ycbcr_2plane_444_formats` enabled).
///
/// # Safety
///
/// `physical` was enumerated from `instance`, made at Vulkan 1.1 or later, and its device
/// enables `samplerYcbcrConversion`.
pub(super) unsafe fn of(
instance: &ash::Instance,
physical: vk::PhysicalDevice,
four_four_four: bool,
) -> YCbCrFormats {
let usage = vk::ImageUsageFlags::SAMPLED | vk::ImageUsageFlags::TRANSFER_DST;
let converts = FORMATS
.iter()
.filter(|&&(_, _, subsampling)| {
four_four_four || subsampling != ChromaSubsampling::Chroma444
})
.filter_map(|&(format, _, subsampling)| {
// SAFETY: the caller's.
let properties =
unsafe { instance.get_physical_device_format_properties(physical, format) };
let features = properties.optimal_tiling_features;
let needed =
vk::FormatFeatureFlags::SAMPLED_IMAGE | vk::FormatFeatureFlags::TRANSFER_DST;
// Metal's reconstruction of a subsampled format: its midpoint, through a linear
// chroma filter (the module docs); a 4:4:4 one reconstructs nothing.
let reconstructs = match subsampling {
ChromaSubsampling::Chroma444 => features.intersects(
vk::FormatFeatureFlags::MIDPOINT_CHROMA_SAMPLES
| vk::FormatFeatureFlags::COSITED_CHROMA_SAMPLES,
),
_ => {
features.contains(vk::FormatFeatureFlags::MIDPOINT_CHROMA_SAMPLES)
&& linear_chroma(features)
}
};
if !features.contains(needed) || !reconstructs {
return None;
}
let info = vk::PhysicalDeviceImageFormatInfo2::default()
.format(format)
.ty(vk::ImageType::TYPE_2D)
.tiling(vk::ImageTiling::OPTIMAL)
.usage(usage);
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 }
}
/// A conversion of the first format the device converts, which its priming makes and
/// releases (`device/prime.rs`); `None` where it converts none.
pub(super) fn primer(&self) -> Option<vk::SamplerYcbcrConversionCreateInfo<'static>> {
let first = self.converts.first()?;
Some(conversion_info(&YCbCrSampler {
format: first.format,
model: vk::SamplerYcbcrModelConversion::RGB_IDENTITY,
range: vk::SamplerYcbcrRange::ITU_FULL,
location: location(first.features),
chroma_filter: vk::Filter::NEAREST,
filter: vk::Filter::NEAREST,
descriptors: first.descriptors,
}))
}
/// The format's entry, where the device converts it.
fn of_format(&self, format: vk::Format) -> Option<Converts> {
self.converts.iter().copied().find(|c| c.format == format)
}
}
/// Whether a format of `features` filters its chroma linearly: the conversion's linear filter,
/// and either a separate reconstruction filter or a linear sampler filter, which then is the
/// chroma's (`VUID-VkSamplerCreateInfo-minFilter-01645`).
fn linear_chroma(features: vk::FormatFeatureFlags) -> bool {
let separate = features.contains(
vk::FormatFeatureFlags::SAMPLED_IMAGE_YCBCR_CONVERSION_SEPARATE_RECONSTRUCTION_FILTER,
);
features.contains(vk::FormatFeatureFlags::SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER)
&& (separate || features.contains(vk::FormatFeatureFlags::SAMPLED_IMAGE_FILTER_LINEAR))
}
/// The chroma location of a format of `features`: Metal's midpoint where it has it (every
/// subsampled format [`YCbCrFormats`] holds has it).
fn location(features: vk::FormatFeatureFlags) -> vk::ChromaLocation {
match features.contains(vk::FormatFeatureFlags::MIDPOINT_CHROMA_SAMPLES) {
true => vk::ChromaLocation::MIDPOINT,
false => vk::ChromaLocation::COSITED_EVEN,
}
}
/// The device's conversion of one texture's planes (the module docs): the sampler a sample
/// kernel's layout bakes (`owned_kernel.rs`), its conversion's, and the planes' image's format.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub(super) struct YCbCrSampler {
pub(super) format: vk::Format,
model: vk::SamplerYcbcrModelConversion,
range: vk::SamplerYcbcrRange,
location: vk::ChromaLocation,
chroma_filter: vk::Filter,
filter: vk::Filter,
/// The descriptors a combined image sampler of the format takes
/// (`combinedImageSamplerDescriptorCount`).
pub(super) descriptors: u32,
}
impl std::fmt::Debug for YCbCrSampler {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// `ash` names no Vulkan value here: the raw numbers.
f.debug_struct("YCbCrSampler")
.field("format", &self.format.as_raw())
.field("model", &self.model.as_raw())
.field("range", &self.range.as_raw())
.field("location", &self.location.as_raw())
.field("chroma_filter", &self.chroma_filter.as_raw())
.field("filter", &self.filter.as_raw())
.field("descriptors", &self.descriptors)
.finish()
}
}
/// The conversion's creation info of `sampler`.
fn conversion_info(sampler: &YCbCrSampler) -> vk::SamplerYcbcrConversionCreateInfo<'static> {
vk::SamplerYcbcrConversionCreateInfo::default()
.format(sampler.format)
.ycbcr_model(sampler.model)
.ycbcr_range(sampler.range)
.components(vk::ComponentMapping::default())
.x_chroma_offset(sampler.location)
.y_chroma_offset(sampler.location)
.chroma_filter(sampler.chroma_filter)
.force_explicit_reconstruction(false)
}
impl YCbCrSampler {
/// The device's conversion of `planes`, where it converts them (the module docs); `None`
/// where Metal's arithmetic does. `zeros` says whether the texture reads zeros past its
/// planes' bytes (chroma codes 0, or rows past its buffer), which no image of the planes
/// holds.
pub(super) fn of(device: &Device, planes: &YCbCrPlanes, zeros: bool) -> Option<YCbCrSampler> {
let codes = planes.codes;
if zeros || codes.packed {
return None;
}
// The planes form one image: each plane's rows whole texels that do not overlap, at a
// multiple of its texel's bytes ("bufferRowLength must be 0, or greater than or equal
// to the width member of imageExtent", `VUID-VkBufferImageCopy-bufferRowLength-09101`;
// a plane's `bufferOffset` a multiple of its element's size,
// `VUID-vkCmdCopyBufferToImage-dstImage-07976`).
let [chroma_width, _] = planes.chroma_size();
let rows = [
(planes.luma, codes.bytes, planes.size[0]),
(planes.chroma, 2 * codes.bytes, chroma_width),
];
if !rows.iter().all(|&([at, row], texel, width)| {
at % texel == 0 && row % texel == 0 && row / texel >= width
}) {
return None;
}
let (format, _, subsampling) =
FORMATS.iter().copied().find(|&(_, bits, subsampling)| {
bits == codes.bits && subsampling == codes.subsampling
})?;
let defects = &device.properties().driver_defects;
let subsampled = subsampling != ChromaSubsampling::Chroma444;
if (subsampled && defects.contains(&RuntimeDriverDefect::TwoPlaneChromaMisplaced))
|| (codes.bits == 10 && defects.contains(&RuntimeDriverDefect::TenBitCodesReadAsWords))
{
return None;
}
// A 4:4:4 format's codes convert through nothing: the identity model, no range
// (`RGB_IDENTITY` ignores it) and no chroma to reconstruct, so the device's answer is the
// codes ours reads, without a planes' image.
if codes.output == YCbCrOutput::Codes && !subsampled {
return None;
}
let converts = device.shared().ycbcr_formats.of_format(format)?;
let extent = extent(planes.size, subsampling);
if extent[0] > converts.extent[0] || extent[1] > converts.extent[1] {
return None;
}
let features = converts.features;
let separate = features.contains(
vk::FormatFeatureFlags::SAMPLED_IMAGE_YCBCR_CONVERSION_SEPARATE_RECONSTRUCTION_FILTER,
);
let chroma_filter = match linear_chroma(features) {
true => vk::Filter::LINEAR,
false => vk::Filter::NEAREST,
};
// An output, matrix or range not named here converts through Metal's arithmetic.
let (model, range) = match codes.output {
YCbCrOutput::Codes => (
vk::SamplerYcbcrModelConversion::RGB_IDENTITY,
vk::SamplerYcbcrRange::ITU_FULL,
),
YCbCrOutput::Converted | YCbCrOutput::Srgb => (
match planes.matrix {
YCbCrMatrix::Bt601 => vk::SamplerYcbcrModelConversion::YCBCR_601,
YCbCrMatrix::Bt709 => vk::SamplerYcbcrModelConversion::YCBCR_709,
YCbCrMatrix::Bt2020 => vk::SamplerYcbcrModelConversion::YCBCR_2020,
_ => return None,
},
match planes.range {
YCbCrRange::Video => vk::SamplerYcbcrRange::ITU_NARROW,
YCbCrRange::Full => vk::SamplerYcbcrRange::ITU_FULL,
_ => return None,
},
),
_ => return None,
};
Some(YCbCrSampler {
format,
model,
range,
location: location(features),
chroma_filter,
filter: match separate {
true => vk::Filter::NEAREST,
false => chroma_filter,
},
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)))]
pub(crate) fn chroma(&self) -> (bool, bool) {
(
self.location == vk::ChromaLocation::MIDPOINT,
self.chroma_filter == vk::Filter::LINEAR,
)
}
/// The conversion and the sampler of it, made by `device`; the sampler counted against the
/// device's samplers (`DeviceShared::create_sampler`).
pub(super) fn make(
&self,
device: &Device,
) -> Result<(vk::SamplerYcbcrConversion, vk::Sampler), Error> {
let shared = device.shared();
let raw = shared.vk();
let info = conversion_info(self);
// SAFETY: the device enables `samplerYcbcrConversion` and converts the format with the
// location and filter chosen from its features (`of`).
let conversion =
unsafe { raw.create_sampler_ycbcr_conversion(&info, None) }.map_err(vulkan)?;
let mut chained = vk::SamplerYcbcrConversionInfo::default().conversion(conversion);
let info = vk::SamplerCreateInfo::default()
.mag_filter(self.filter)
.min_filter(self.filter)
.mipmap_mode(vk::SamplerMipmapMode::NEAREST)
.address_mode_u(vk::SamplerAddressMode::CLAMP_TO_EDGE)
.address_mode_v(vk::SamplerAddressMode::CLAMP_TO_EDGE)
.address_mode_w(vk::SamplerAddressMode::CLAMP_TO_EDGE)
.min_lod(0.0)
.max_lod(0.0)
.push_next(&mut chained);
// SAFETY: `info` and its chain live for the call; the conversion is live.
match unsafe { shared.create_sampler(&info) } {
Ok(sampler) => Ok((conversion, sampler)),
Err(error) => {
// SAFETY: the conversion is unused.
unsafe { release::object(raw, conversion) };
Err(error)
}
}
}
}
/// The planes' image of a texture of `size` luma texels at `subsampling`: its size rounded up
/// to the chroma block, which Vulkan's 4:2:0 and 4:2:2 formats require.
fn extent(size: [u32; 2], subsampling: ChromaSubsampling) -> [u32; 2] {
let halved = subsampling.halved();
[0, 1].map(|axis| match halved[axis] {
true => size[axis].next_multiple_of(2),
false => size[axis],
})
}
/// The planes' image of the device's conversion of one texture, and the dispatch that samples
/// it into the texture's image (the module docs). Its objects
/// are released with it; no pending command uses them then (the texture's command buffers hold
/// the texture until they complete).
pub(super) struct YCbCrDeviceSampling {
device: Device,
image: vk::Image,
placement: Placement,
view: vk::ImageView,
kernel: OwnedKernel,
sets: OwnedSets,
push: [u8; YCbCrSampleModule::PUSH_BYTES as usize],
/// The planes' bytes from the staging buffer's copy into each plane, from the copy's first
/// byte.
regions: [vk::BufferImageCopy; 2],
groups: [u32; 2],
}
impl YCbCrDeviceSampling {
/// The image of `planes` through `sampler`, and the sampling of it into `target`, a storage
/// view of the texture's image, on `device`. Refused as the image, its memory, its view, the
/// kernel's objects and its set are refused.
pub(super) fn new(
device: &Device,
(planes, sampler): (&YCbCrPlanes, YCbCrSampler),
target: vk::ImageView,
) -> Result<YCbCrDeviceSampling, Error> {
let shared = device.shared();
let raw = shared.vk();
let [width, height] = extent(planes.size, planes.codes.subsampling);
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::of`).
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 = |view: Option<vk::ImageView>| {
if let Some(view) = view {
// SAFETY: the view is unused.
unsafe { release::object(raw, view) };
}
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(None);
return Err(vulkan(error));
}
let kernel = match device.owned_kernel(OwnedModule::YCbCrSample(sampler, planes.codes)) {
Ok(kernel) => kernel,
Err(error) => {
unwind(None);
return Err(error);
}
};
let Some(conversion) = device.ycbcr_conversion(sampler) else {
unwind(None);
return Err(super::error::internal(
"a YCbCr 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(None);
return Err(vulkan(error));
}
};
let set = OwnedSet {
images: vec![view],
storage_images: vec![target],
buffers: Vec::new(),
};
let sets = match OwnedSets::write_each(device, &[kernel], &[set]) {
Ok(sets) => sets,
Err(error) => {
unwind(Some(view));
return Err(error);
}
};
let bytes = planes.codes.bytes;
let [chroma_width, chroma_height] = planes.chroma_size();
let region =
|(at, row): (u32, u32), aspect, texel: u32, [w, h]: [u32; 2]| vk::BufferImageCopy {
buffer_offset: u64::from(at),
buffer_row_length: row / texel,
buffer_image_height: 0,
image_subresource: vk::ImageSubresourceLayers {
aspect_mask: aspect,
mip_level: 0,
base_array_layer: 0,
layer_count: 1,
},
image_offset: vk::Offset3D::default(),
image_extent: vk::Extent3D {
width: w,
height: h,
depth: 1,
},
};
let regions = [
region(
(planes.luma[0], planes.luma[1]),
vk::ImageAspectFlags::PLANE_0,
bytes,
planes.size,
),
region(
(planes.chroma[0], planes.chroma[1]),
vk::ImageAspectFlags::PLANE_1,
2 * bytes,
[chroma_width, chroma_height],
),
];
device.shared().counts.ycbcr_device_conversion();
Ok(YCbCrDeviceSampling {
device: device.clone(),
image,
placement,
view,
kernel,
sets,
push: YCbCrSampleModule::push(planes.size, [width, height]),
regions,
groups: planes
.size
.map(|n| n.div_ceil(YCbCrSampleModule::LOCAL_SIZE)),
})
}
/// The workgroups of its dispatch, which the conversion's refresh writes into its indirect
/// arguments where the planes changed (`ycbcr.rs`).
pub(super) fn groups(&self) -> [u32; 2] {
self.groups
}
/// Record the copy of the planes from `bytes_at` of `staging` into the image, and the
/// sampling of it into the target: dispatched through the indirect arguments at `indirect`
/// of `staging` where given, else over every texel.
///
/// # Safety
///
/// `command_buffer` is recording, outside a render pass; `staging` holds the planes' bytes
/// from `bytes_at`, as the regions read them, written before (a barrier recorded), and it,
/// the image and the target are live until the command buffer completes; the target is in
/// the `GENERAL` layout.
pub(super) unsafe fn record(
&self,
device: &Vk,
command_buffer: vk::CommandBuffer,
(staging, bytes_at): (vk::Buffer, u64),
indirect: Option<u64>,
) {
let regions = self.regions.map(|region| vk::BufferImageCopy {
buffer_offset: bytes_at + region.buffer_offset,
..region
});
let whole = vk::ImageSubresourceRange {
aspect_mask: vk::ImageAspectFlags::COLOR,
base_mip_level: 0,
level_count: 1,
base_array_layer: 0,
layer_count: 1,
};
// Every earlier use of the image (an earlier conversion's sample) before its texels are
// dropped and copied in whole.
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(vk::ImageLayout::GENERAL)
.src_queue_family_index(vk::QUEUE_FAMILY_IGNORED)
.dst_queue_family_index(vk::QUEUE_FAMILY_IGNORED)
.image(self.image)
.subresource_range(whole);
let sampled = vk::ImageMemoryBarrier::default()
.src_access_mask(vk::AccessFlags::TRANSFER_WRITE)
.dst_access_mask(vk::AccessFlags::SHADER_READ)
.old_layout(vk::ImageLayout::GENERAL)
.new_layout(vk::ImageLayout::GENERAL)
.src_queue_family_index(vk::QUEUE_FAMILY_IGNORED)
.dst_queue_family_index(vk::QUEUE_FAMILY_IGNORED)
.image(self.image)
.subresource_range(whole);
// SAFETY: the caller's contract; the regions lie in the staging copy's planes, and the
// set binds the image's view and the target.
unsafe {
device.cmd_pipeline_barrier(
command_buffer,
vk::PipelineStageFlags::COMPUTE_SHADER,
vk::PipelineStageFlags::TRANSFER,
vk::DependencyFlags::empty(),
&[],
&[],
&[into],
);
device.cmd_copy_buffer_to_image(
command_buffer,
staging,
self.image,
vk::ImageLayout::GENERAL,
&regions,
);
device.cmd_pipeline_barrier(
command_buffer,
vk::PipelineStageFlags::TRANSFER,
vk::PipelineStageFlags::COMPUTE_SHADER,
vk::DependencyFlags::empty(),
&[],
&[],
&[sampled],
);
let point = vk::PipelineBindPoint::COMPUTE;
device.cmd_bind_pipeline(command_buffer, point, self.kernel.pipeline);
device.cmd_bind_descriptor_sets(
command_buffer,
point,
self.kernel.layout,
0,
&self.sets.sets,
&[],
);
device.cmd_push_constants(
command_buffer,
self.kernel.layout,
vk::ShaderStageFlags::COMPUTE,
0,
&self.push,
);
match indirect {
Some(at) => device.cmd_dispatch_indirect(command_buffer, staging, at),
None => device.cmd_dispatch(command_buffer, self.groups[0], self.groups[1], 1),
}
}
self.device.shared().counts.ycbcr_device_sampled();
}
}
impl Drop for YCbCrDeviceSampling {
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 @@
7ddb9d93ec3e6a1f9312bd47267182b9cd12d899035e4581d800308486c3e121
149bea7e97d81788d5a33b98b177863b1c73e9dc4809efec8f8efea9b03e22b3
@@ -866,6 +866,8 @@ mod word_samples;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod wrapped_buffers;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod ycbcr_device_reads;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod ycbcr_in_place;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod ycbcr_minify;
@@ -0,0 +1,114 @@
//! The device's own Y′CbCr conversion of a two-plane YCbCr texture, as the YCbCr lanes check it
//! (the runtime's `ycbcr_device.rs`). Where the device converts a texture's planes itself
//! ([`device_conversions`] counts it as the texture is made), each texel is Vulkan's conversion
//! of them ([`vulkan_read`]) within [`DEVICE_BOUND`], announced (`ycbcr-filter-not-exact`), and
//! not Metal's fixed-point read: a lane that holds such a texture to Metal's steps holds it to
//! these instead. The runtime takes the device's conversion of a 4:2:0 or 4:2:2 format only at
//! Metal's midpoint through a linear chroma filter, whose weights Vulkan states as Metal's (3 and
//! 1 along a halved axis), so a lane's reconstruction is Metal's sum of weighted codes over 16,
//! unrounded.
use metal2vulkan::bind::{YCbCrCodes, YCbCrMatrix, YCbCrOutput, YCbCrRange};
use metal2vulkan_runtime::Device;
/// The largest distance of a channel, in units of `1/2048`, from Vulkan's conversion
/// ([`vulkan_read`]; before the sRGB curve, for an `_sRGB` twin) the device's may take, past the
/// `half` a converted texture's image stores it in: at most 0.038 measured on lavapipe (Mesa
/// 26.0.8, LLVM 21.1.8), whose 8-bit 4:4:4 layout is the one it converts, every texel of the
/// lanes' surfaces.
pub(super) const DEVICE_BOUND: f64 = 0.04;
/// The textures the device has converted itself so far
/// (`WorkCounts::ycbcr_device_conversions`): a texture made while it grows is the device's.
pub(super) fn device_conversions(device: &Device) -> u64 {
device.work_counts().ycbcr_device_conversions
}
/// Vulkan's conversion of a texel of luma code `y` and chroma `cb` and `cr` (codes, reconstructed
/// unrounded) of `codes` under `conversion`: the range's expansion and the model's matrix,
/// unclamped, red, green and blue (before the sRGB curve, for an `_sRGB` twin).
pub(super) fn vulkan_read(
codes: YCbCrCodes,
(range, matrix): (YCbCrRange, YCbCrMatrix),
[y, cb, cr]: [f64; 3],
) -> [f64; 3] {
let n = codes.bits as i32;
let max = f64::from((1u32 << n) - 1);
let scale = f64::from(1u32 << (n - 8));
let (luma, cb, cr) = match range {
YCbCrRange::Video => (
(y - 16.0 * scale) / (219.0 * scale),
(cb - 128.0 * scale) / (224.0 * scale),
(cr - 128.0 * scale) / (224.0 * scale),
),
_ => {
let mid = f64::from(1u32 << (n - 1));
(y / max, (cb - mid) / max, (cr - mid) / max)
}
};
let (kr, kb) = match matrix {
YCbCrMatrix::Bt709 => (0.2126, 0.0722),
YCbCrMatrix::Bt2020 => (0.2627, 0.0593),
_ => (0.299, 0.114),
};
let kg = 1.0 - kr - kb;
[
luma + 2.0 * (1.0 - kr) * cr,
luma - 2.0 * kb * (1.0 - kb) / kg * cb - 2.0 * kr * (1.0 - kr) / kg * cr,
luma + 2.0 * (1.0 - kb) * cb,
]
}
/// `v` through the sRGB encoding: the inverse of the decoding curve the sample module applies to
/// an `_sRGB` twin's texels.
fn encoded(v: f64) -> f64 {
match v <= 0.04045 / 12.92 {
true => v * 12.92,
false => 1.055 * v.powf(1.0 / 2.4) - 0.055,
}
}
/// Asserts that the `float4`s `texels` of a texture of `output` the device converted hold
/// `want` ([`vulkan_read`] of each texel) within [`DEVICE_BOUND`], an `_sRGB` twin's through the
/// inverse of the curve, alpha 1. A converted format's texels, which its image stores as
/// `half`s, and `half` reads also take the `half`'s rounding of each value, within one unit in
/// the last place (`PrecisionNote::NativeHalfConversion`). The largest
/// distance, in units of `1/2048`, is printed.
pub(super) fn assert_device_reads(
texels: &[u8],
want: &[[f64; 3]],
(output, half): (YCbCrOutput, bool),
case: &str,
) {
assert_ne!(
output,
YCbCrOutput::Codes,
"{case}: codes are read through ours"
);
let mut most = 0.0f64;
for (i, (t, w)) in texels.as_chunks::<16>().0.iter().zip(want).enumerate() {
let c = |i: usize| f64::from(f32::from_le_bytes(t[4 * i..4 * i + 4].try_into().unwrap()));
assert_eq!(c(3), 1.0, "{case}: texel {i}'s alpha");
for (k, &want) in w.iter().enumerate() {
let got = c(k);
// A `half`'s unit in the last place at the value: the value it rounded lies within it.
let ulp = match half || output == YCbCrOutput::Converted {
true => 2f64.powi(got.abs().max(2f64.powi(-14)).log2().floor() as i32 - 10),
false => 0.0,
};
let decode = |v: f64| match output {
YCbCrOutput::Srgb => encoded(v),
_ => v,
};
let (low, high) = (decode(got - ulp), decode(got + ulp));
let far = (low - want).max(want - high).max(0.0);
most = most.max(far * 2048.0);
assert!(
far <= DEVICE_BOUND / 2048.0,
"{case}: texel {i} channel {k}: {got}, Vulkan's conversion {want} ({} / 2048 off)",
far * 2048.0
);
}
}
println!("YCBCR-DEVICE {case}: within {most:.4} / 2048 of Vulkan's conversion");
}
@@ -34,6 +34,7 @@ use super::depth_compares::{pipeline_of, run_held, Held, Through};
use super::driver_deviations::stage_notes;
use super::host_memory::{self, host_page, Mapping};
use super::pixel_samplers::{metal_sampler, own_sampler};
use super::ycbcr_device_reads::{assert_device_reads, device_conversions, vulkan_read};
use super::{buffer_with, converted_holds, half_within, read_buffer};
use crate::air_library::AirLibrary;
use metal2vulkan::bind::{
@@ -1260,9 +1261,12 @@ fn made_in_place(device: &Device) -> u64 {
/// (`VkProperty::MetalSampler`) within one step of the grid, a `half` result within one `half` unit
/// in the last place (`ycbcr-filter-not-exact`); on any other device by its own filter, within
/// [`DEVICE_FILTER_BOUND`] (`device-sampling`). The values off Metal's step are counted, with the
/// largest distance in codes of `1/255`.
/// largest distance in codes of `1/255`. The textures the device converts itself while it runs
/// are counted too (`ycbcr_device_reads`), each announced as `ycbcr-filter-not-exact`.
struct Between {
metal: bool,
/// The device's conversions before the run ([`device_conversions`]).
converted: u64,
/// Samples of textures that keep their image.
kept: usize,
checked: usize,
@@ -1274,6 +1278,7 @@ impl Between {
fn new(device: &Device) -> Between {
Between {
metal: metal_sampler(device),
converted: device_conversions(device),
kept: 0,
checked: 0,
differ: 0,
@@ -1343,17 +1348,23 @@ impl Between {
self.most
);
}
assert_filter_notices(device, announced, self.kept > 0);
let by_device = device_conversions(device) > self.converted;
assert_filter_notices(device, announced, (self.kept > 0, by_device));
}
}
/// The filter notices `announced` of a run on `device` whose samples of converted two-plane
/// YCbCr textures read a texture that keeps its image where `kept`: `ycbcr-filter-not-exact` once
/// where one did on a device that samples through Metal's own sampler (a runtime sampler's slot
/// bound to such a texture records its filter note whatever the sampler's word,
/// `lower::sampler::linear`), none elsewhere; no generic filter notice; `device-sampling` on
/// every device that samples natively, and only there.
fn assert_filter_notices(device: &Device, announced: &BTreeMap<Degradation, usize>, kept: bool) {
/// YCbCr textures read a texture that keeps its image where `kept`, and that made a texture the
/// device converts itself where `by_device`: `ycbcr-filter-not-exact` once where one did on a
/// device that samples through Metal's own sampler (a runtime sampler's slot bound to such a
/// texture records its filter note whatever the sampler's word, `lower::sampler::linear`), or
/// where the device converted one (`ycbcr_device_reads`), none elsewhere; no generic filter
/// notice; `device-sampling` on every device that samples natively, and only there.
fn assert_filter_notices(
device: &Device,
announced: &BTreeMap<Degradation, usize>,
(kept, by_device): (bool, bool),
) {
let metal = metal_sampler(device);
for kind in [
Degradation::FloatSampleFilter,
@@ -1362,7 +1373,11 @@ fn assert_filter_notices(device: &Device, announced: &BTreeMap<Degradation, usiz
assert_eq!(announced.get(&kind), None, "{announced:?}");
}
let ycbcr = announced.get(&Degradation::YCbCrFilterNotExact);
assert_eq!(ycbcr, (metal && kept).then_some(&1), "{announced:?}");
assert_eq!(
ycbcr,
((metal && kept) || by_device).then_some(&1),
"{announced:?}"
);
assert_eq!(
announced.contains_key(&Degradation::DeviceSampling),
!metal,
@@ -2312,9 +2327,11 @@ fn write_then_read(
/// about two texels in three, over both ranges and each matrix: the surface's bytes are those codes
/// and otherwise as they were, the rows' padding and the bytes past the planes among them. A
/// `read()` of the texture in the same encoder after the writes, and one in a later command buffer,
/// read the planes as written. A dispatch writing no texel keeps every byte. Nothing is announced
/// past the lane's pipeline states' own notes and, on a device without unified memory, the first
/// `Shared` buffer's `shared-in-system-memory`.
/// read the planes as written (where the device converts the texture, its conversion of them:
/// `ycbcr_device_reads`). A dispatch writing no texel keeps every byte. Nothing is announced
/// past the lane's pipeline states' own notes, on a device without unified memory the first
/// `Shared` buffer's `shared-in-system-memory`, and where the device converts a texture itself
/// `ycbcr-filter-not-exact`.
#[test]
fn a_four_four_four_texture_s_writes_store_metal_s_codes() {
use PixelFormat as P;
@@ -2331,6 +2348,7 @@ fn a_four_four_four_texture_s_writes_store_metal_s_codes() {
Some(SurfaceYCbCrMatrix::Itu2020),
);
let mut seed = 640;
let mut by_devices = false;
for (pf, ostype, matrix, conversion) in [
(P::YCBCR84442P, "444v", None, (Video, Bt601)),
(P::YCBCR84442P, "444f", b709, (Full, Bt709)),
@@ -2348,7 +2366,10 @@ fn a_four_four_four_texture_s_writes_store_metal_s_codes() {
let mut random = Random(seed);
let bytes = family_bytes(seed, codes);
let surface = buffer_with(device, &bytes).unwrap();
let converted = device_conversions(device);
let texture = written_texture(&surface, pf, ostype, matrix).unwrap();
let by_device = device_conversions(device) > converted;
by_devices |= by_device;
let (mut values, mut mask, mut texels) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..W * H {
let written = !random.next().is_multiple_of(3);
@@ -2380,15 +2401,19 @@ fn a_four_four_four_texture_s_writes_store_metal_s_codes() {
);
// The converted formats' reads, of the planes as written.
if codes.output == YCbCrOutput::Converted {
let read = family_modelled(&want, codes, conversion);
let planes = (&want[..], codes, conversion);
let same = read_buffer(&out, 0, 16 * W * H).unwrap();
assert_eq!(grid(&same), read, "{case}: read() in the same encoder");
let later = texels_of(device, &kernels.read, &texture, None);
assert_eq!(
grid(&later),
read,
"{case}: read() in a later command buffer"
);
for (texels, when) in [(same, "in the same encoder"), (later, "later")] {
let case = format!("{case}: read() {when}");
assert_family_read(
&kernels,
&texels,
planes,
(2048, false, by_device),
&case,
);
}
}
}
}
@@ -2419,11 +2444,16 @@ fn a_four_four_four_texture_s_writes_store_metal_s_codes() {
}
// Nothing but, on a device without unified memory, the first `Shared` buffer the case made
// (`blits::SYSTEM_MEMORY`, announced as that buffer is made), as
// `blits::shared_buffers_follow_the_memory_model` expects it.
let expected: &[Degradation] = match device.properties().has_unified_memory {
true => &[],
false => &SYSTEM_MEMORY,
// `blits::shared_buffers_follow_the_memory_model` expects it, and the device's own
// conversion where it converted a texture (`ycbcr_device_reads`).
let mut expected: Vec<Degradation> = match device.properties().has_unified_memory {
true => Vec::new(),
false => SYSTEM_MEMORY.to_vec(),
};
if by_devices {
expected.push(Degradation::YCbCrFilterNotExact);
}
let expected = &expected[..];
let notices = assert_once(&messages.take_notices(), expected);
assert!(
notices.keys().all(|kind| expected.contains(kind)),
@@ -2816,8 +2846,40 @@ fn read_anywhere(
bytes: &[u8],
codes: YCbCrCodes,
conversion: (YCbCrRange, YCbCrMatrix),
(luma, chroma): ([u64; 2], Option<[u64; 2]>),
planes: ([u64; 2], Option<[u64; 2]>),
) -> Vec<[u16; 3]> {
anywhere_sums(bytes, codes, planes)
.into_iter()
.map(|(y, sums)| {
let [cb, cr] = sums.map(|s| ((s + 8) >> 4) as u16);
ycbcr_read(codes, conversion, [y, cb, cr])
})
.collect()
}
/// What [`read_anywhere`] reads, through the device's conversion
/// (`ycbcr_device_reads::vulkan_read`): the chroma sums over 16, unrounded.
fn anywhere_vulkan(
bytes: &[u8],
codes: YCbCrCodes,
conversion: (YCbCrRange, YCbCrMatrix),
planes: ([u64; 2], Option<[u64; 2]>),
) -> Vec<[f64; 3]> {
anywhere_sums(bytes, codes, planes)
.into_iter()
.map(|(y, sums)| {
let [cb, cr] = sums.map(|s| f64::from(s) / 16.0);
vulkan_read(codes, conversion, [f64::from(y), cb, cr])
})
.collect()
}
/// Each texel's luma code and its chroma sums of 16 weights, as [`read_anywhere`] reads them.
fn anywhere_sums(
bytes: &[u8],
codes: YCbCrCodes,
(luma, chroma): ([u64; 2], Option<[u64; 2]>),
) -> Vec<(u16, [u32; 2])> {
let byte = |at: u64| bytes.get(at as usize).copied().unwrap_or(0);
let unit = u64::from(codes.bytes);
let code = |at: u64| match unit {
@@ -2847,9 +2909,7 @@ fn read_anywhere(
}
}
}
let [cb, cr] = sums.map(|s| ((s + 8) >> 4) as u16);
let y_code = code(luma[0] + y * luma[1] + unit * x);
out.push(ycbcr_read(codes, conversion, [y_code, cb, cr]));
out.push((code(luma[0] + y * luma[1] + unit * x), sums));
}
}
out
@@ -2880,7 +2940,8 @@ fn assert_codes_read(kernels: &Kernels, texels: &[u8], want: &[[u16; 3]], max: u
/// lossless compressed OSType, plane 1 of a surface without planes, an `_sRGB` twin over a P3
/// surface, rows of codes that overlap (a 10-bit format over 8-bit rows narrower than its codes)
/// and luma rows past the buffer, the last two the runtime's gaps. Metal makes no render target of
/// a 4:2:0 format of odd width: its nil.
/// a 4:2:0 format of odd width: its nil. A texture the device converts itself reads its conversion
/// of the same codes, within its bound (`ycbcr_device_reads`).
#[test]
fn textures_over_any_surface_read_what_metal_reads() {
use PixelFormat as P;
@@ -2971,16 +3032,27 @@ fn textures_over_any_surface_read_what_metal_reads() {
"{pf:?} over {:?}",
(String::from_utf8_lossy(at.0), at.1, at.2)
);
let converted = device_conversions(device);
let made = texture(buffer, pf, at, planes, matrix);
let made = made.unwrap_or_else(|e| panic!("{case}: {e:?}"));
let by_device = device_conversions(device) > converted;
let source = match buffer.length() {
2000 => short_bytes,
_ => &bytes[..],
};
let chroma = read_chroma.then_some(planes.1);
let want = read_anywhere(source, codes(pf), (range, Bt601), (planes.0, chroma));
let got = grid(&texels_of(device, &kernels.read, &made, None));
assert_eq!(got, want, "{case}");
let read = texels_of(device, &kernels.read, &made, None);
let (codes, planes) = (codes(pf), (planes.0, chroma));
match by_device {
true => {
let want = anywhere_vulkan(source, codes, (range, Bt601), planes);
assert_device_reads(&read, &want, (codes.output, false), &case);
}
false => {
let want = read_anywhere(source, codes, (range, Bt601), planes);
assert_eq!(grid(&read), want, "{case}");
}
}
}
// P3: a converted format reads its luma, Cb and Cr codes alone, a code format its codes.
for (pf, matrix) in [
@@ -3767,15 +3839,10 @@ fn chroma_size(codes: YCbCrCodes) -> [u64; 2] {
[(W, halved[0]), (H, halved[1])].map(|(n, halved)| if halved { n.div_ceil(2) } else { n })
}
/// Each texel `codes` reads of the surface `bytes` (laid out as [`family_bytes`] lays them)
/// under `conversion` (`metal2vulkan::bind::ycbcr_read`): along a halved axis the two nearest
/// chroma pairs weighted 3 and 1, along a direct one the texel's own pair weighted 4, the sum `S`
/// of the 16 weights rounded `(S + 8) >> 4`.
fn family_modelled(
bytes: &[u8],
codes: YCbCrCodes,
conversion: (YCbCrRange, YCbCrMatrix),
) -> Vec<[u16; 3]> {
/// Each texel's luma code and the sums `S` of its chroma codes Cb and Cr, `codes` of the surface
/// `bytes` (laid out as [`family_bytes`] lays them): along a halved axis the two nearest chroma
/// pairs weighted 3 and 1, along a direct one the texel's own pair weighted 4, 16 in all.
fn family_sums(bytes: &[u8], codes: YCbCrCodes) -> Vec<(u16, [u32; 2])> {
let code = |row: u64, index: u64| code_of(bytes, codes, row, index);
let [cw, ch] = chroma_size(codes);
let halved = codes.subsampling.halved();
@@ -3800,13 +3867,74 @@ fn family_modelled(
sums[1] += wx * wy * u32::from(code(row, 2 * cx + 1));
}
}
let [cb, cr] = sums.map(|s| ((s + 8) >> 4) as u16);
out.push(ycbcr_read(codes, conversion, [code(y * ROWQ, x), cb, cr]));
out.push((code(y * ROWQ, x), sums));
}
}
out
}
/// Each texel `codes` reads of the surface `bytes` (laid out as [`family_bytes`] lays them)
/// under `conversion` (`metal2vulkan::bind::ycbcr_read`): [`family_sums`]' chroma sums rounded
/// `(S + 8) >> 4`.
fn family_modelled(
bytes: &[u8],
codes: YCbCrCodes,
conversion: (YCbCrRange, YCbCrMatrix),
) -> Vec<[u16; 3]> {
family_sums(bytes, codes)
.into_iter()
.map(|(y, sums)| {
let [cb, cr] = sums.map(|s| ((s + 8) >> 4) as u16);
ycbcr_read(codes, conversion, [y, cb, cr])
})
.collect()
}
/// Each texel of the surface `bytes` (laid out as [`family_bytes`] lays them) through the
/// device's conversion of `codes` under `conversion` (`ycbcr_device_reads::vulkan_read`):
/// [`family_sums`]' chroma sums over 16, unrounded.
fn family_vulkan(
bytes: &[u8],
codes: YCbCrCodes,
conversion: (YCbCrRange, YCbCrMatrix),
) -> Vec<[f64; 3]> {
family_sums(bytes, codes)
.into_iter()
.map(|(y, sums)| {
let [cb, cr] = sums.map(|s| f64::from(s) / 16.0);
vulkan_read(codes, conversion, [f64::from(y), cb, cr])
})
.collect()
}
/// Asserts a `read()` (or a sample at the centres, or, `half`, a `half` read) of a texture of
/// `codes` over the surface `bytes` (laid out as [`family_bytes`] lays them) under `conversion`:
/// Metal's steps of `1 / grid` exactly ([`family_modelled`]), or, where the device converted the
/// texture (`by_device`), Vulkan's conversion within the device's bound ([`family_vulkan`],
/// `ycbcr_device_reads`). A `half` read of Metal's steps is [`assert_half_steps`]'s.
fn assert_family_read(
kernels: &Kernels,
texels: &[u8],
(bytes, codes, conversion): (&[u8], YCbCrCodes, (YCbCrRange, YCbCrMatrix)),
(grid, half, by_device): (u32, bool, bool),
case: &str,
) {
match (by_device, half) {
(true, _) => {
let want = family_vulkan(bytes, codes, conversion);
assert_device_reads(texels, &want, (codes.output, half), case);
}
(false, true) => {
let want = family_modelled(bytes, codes, conversion);
assert_half_steps(kernels, texels, &want, grid, case);
}
(false, false) => {
let want = family_modelled(bytes, codes, conversion);
assert_eq!(grid_of(texels, grid), want, "{case}");
}
}
}
/// The texture of `pf` over plane 0 of `surface`, a surface of OSType `ostype` and `matrix` laid
/// out by [`ROWQ`] and [`CHROMAQ_AT`], of shader read usage.
fn family_texture(
@@ -3835,7 +3963,9 @@ fn family_texture(
/// sample at each texel's centre, and a `half` read (the twins' steps rounded with ties away from
/// zero). The filter notices are [`assert_filter_notices`]'s: no function reads these planes in
/// place. A format over a surface whose chroma plane holds its own reads its pairs at the
/// surface's rows, and over one whose plane is smaller the same, past the plane.
/// surface's rows, and over one whose plane is smaller the same, past the plane. A texture the
/// device converts itself reads Vulkan's conversion of the same codes instead, within the device's
/// bound (`ycbcr_device_reads`; lavapipe's 8-bit 4:4:4 ones).
#[test]
fn four_two_two_and_four_four_four_textures_read_what_metal_reads() {
on_device(|device, messages| {
@@ -3844,6 +3974,7 @@ fn four_two_two_and_four_four_four_textures_read_what_metal_reads() {
let linear = sampler(device, SamplerMinMagFilter::Linear);
let mut steps = Between::new(device);
let mut seed = 120;
let mut by_devices = 0;
for (pf, ostypes) in [
(PixelFormat::YCBCR84222P, ["422v", "422f"]),
(PixelFormat::YCBCR84442P, ["444v", "444f"]),
@@ -3873,28 +4004,35 @@ fn four_two_two_and_four_four_four_textures_read_what_metal_reads() {
let bytes = family_bytes(seed, codes);
let surface = buffer_with(device, &bytes).unwrap();
let before = made_in_place(device);
let converted = device_conversions(device);
let texture = family_texture(&surface, pf, ostype, matrix).unwrap();
steps.sampled(made_in_place(device) > before);
let want = family_modelled(&bytes, codes, (range, modelled));
let by_device = device_conversions(device) > converted;
by_devices += usize::from(by_device);
let case = format!("{pf:?} over {ostype}, {matrix:?}");
let of = |texels: &[u8]| grid_of(texels, grid);
let read = of(&texels_of(device, &kernels.read, &texture, None));
assert_eq!(read, want, "{case}: read()");
let surface = (&bytes[..], codes, (range, modelled));
let read = texels_of(device, &kernels.read, &texture, None);
let check = |texels: &[u8], half, what: &str| {
let case = format!("{case}: {what}");
assert_family_read(
&kernels,
texels,
surface,
(grid, half, by_device),
&case,
);
};
check(&read, false, "read()");
for (filter, state) in [("nearest", &nearest), ("linear", &linear)] {
let sampled = texels_of(device, &kernels.sample, &texture, Some(state));
assert_eq!(of(&sampled), want, "{case}: a {filter} sample");
check(&sampled, false, &format!("a {filter} sample"));
}
let half = texels_of(device, &kernels.read_half, &texture, None);
assert_half_steps(
&kernels,
&half,
&want,
grid,
&format!("{case}: a half read()"),
);
check(&half, true, "a half read()");
}
}
}
println!("YCBCR-DEVICE 4:2:2 and 4:4:4: {by_devices} textures the device's conversion");
steps.finish(device, &counts(&messages.take_notices()), "4:2:2 and 4:4:4");
// Over a surface whose chroma plane holds the format's (for 4:2:2 over
// 4:4:4): the format's pairs, at the surface's rows.
@@ -3907,14 +4045,17 @@ fn four_two_two_and_four_four_four_textures_read_what_metal_reads() {
let codes = ycbcr_format(pf).and_then(YCbCrCodes::of).unwrap();
let bytes = family_bytes(seed, codes);
let surface = buffer_with(device, &bytes).unwrap();
let converted = device_conversions(device);
let texture = family_texture(&surface, pf, ostype, None).unwrap();
let by_device = device_conversions(device) > converted;
let grid = match codes.output {
YCbCrOutput::Srgb => 8192,
_ => 2048,
};
let read = grid_of(&texels_of(device, &kernels.read, &texture, None), grid);
let want = family_modelled(&bytes, codes, (range, YCbCrMatrix::Bt601));
assert_eq!(read, want, "{pf:?} over {ostype}");
let read = texels_of(device, &kernels.read, &texture, None);
let surface = (&bytes[..], codes, (range, YCbCrMatrix::Bt601));
let case = format!("{pf:?} over {ostype}");
assert_family_read(&kernels, &read, surface, (grid, false, by_device), &case);
}
// Over a surface whose chroma plane is smaller than the format's: the format's pairs at
// the surface's rows all the same, past the plane where it ends.
@@ -3927,18 +4068,22 @@ fn four_two_two_and_four_four_four_textures_read_what_metal_reads() {
let codes = ycbcr_format(pf).and_then(YCbCrCodes::of).unwrap();
let bytes = family_bytes(1, codes);
let surface = buffer_with(device, &bytes).unwrap();
let converted = device_conversions(device);
let texture = family_texture(&surface, pf, ostype, None)
.unwrap_or_else(|e| panic!("{pf:?} over {ostype}: {e:?}"));
let read = grid_of(&texels_of(device, &kernels.read, &texture, None), 2048);
let want = family_modelled(&bytes, codes, (YCbCrRange::Video, YCbCrMatrix::Bt601));
assert_eq!(read, want, "{pf:?} over {ostype}");
let by_device = device_conversions(device) > converted;
let read = texels_of(device, &kernels.read, &texture, None);
let surface = (&bytes[..], codes, (YCbCrRange::Video, YCbCrMatrix::Bt601));
let case = format!("{pf:?} over {ostype}");
assert_family_read(&kernels, &read, surface, (2048, false, by_device), &case);
}
});
}
/// A 4:2:2 or 4:4:4 texture's view as its `_sRGB` twin reads what a texture of the twin over the
/// same planes reads, as Metal's view does (made with `ShaderRead` alone), and the
/// texture itself its own conversion.
/// texture itself its own conversion: Metal's, or where the device converts it, the device's
/// (`ycbcr_device_reads`).
#[test]
fn four_two_two_and_four_four_four_views_read_their_twins_texels() {
on_device(|device, _| {
@@ -3970,18 +4115,24 @@ fn four_two_two_and_four_four_four_views_read_their_twins_texels() {
let surface = buffer_with(device, &bytes).unwrap();
let bt709 = (YCbCrRange::Full, YCbCrMatrix::Bt709);
let matrix = Some(SurfaceYCbCrMatrix::Itu709);
let base = family_texture(&surface, pf, ostype, matrix).unwrap();
let view = base.new_texture_view(twin).unwrap();
let direct = family_texture(&surface, twin, ostype, matrix).unwrap();
let read = |t: &Texture, d| grid_of(&texels_of(device, &kernels.read, t, None), d);
let want = family_modelled(&bytes, codes(twin), bt709);
assert_eq!(read(&view, 8192), want, "{pf:?}'s view");
assert_eq!(read(&direct, 8192), want, "{twin:?}");
assert_eq!(
read(&base, 2048),
family_modelled(&bytes, codes(pf), bt709),
"{pf:?}"
);
// Each texture, and whether the device converted it as it was made.
let made = |make: &dyn Fn() -> Texture| {
let converted = device_conversions(device);
let texture = make();
(texture, device_conversions(device) > converted)
};
let base = made(&|| family_texture(&surface, pf, ostype, matrix).unwrap());
let view = made(&|| base.0.new_texture_view(twin).unwrap());
let direct = made(&|| family_texture(&surface, twin, ostype, matrix).unwrap());
for ((texture, by_device), of, grid, case) in [
(&view, twin, 8192, format!("{pf:?}'s view")),
(&direct, twin, 8192, format!("{twin:?}")),
(&base, pf, 2048, format!("{pf:?}")),
] {
let read = texels_of(device, &kernels.read, texture, None);
let surface = (&bytes[..], codes(of), bt709);
assert_family_read(&kernels, &read, surface, (grid, false, *by_device), &case);
}
}
});
}
@@ -4076,7 +4227,9 @@ fn is_half_tie(step: u16) -> bool {
/// 4:4:4 twins, and `YCBCR8_420_2P`, at every texel corner under clamp-to-edge, clamp-to-zero and
/// clamp-to-border-color: each lane the `float` gather's step of `1/8192` rounded so, ties among
/// them. Where the stage rounds a `half` by the device's conversion (`Kernels::native_half`) the
/// lanes that differ are counted and printed.
/// lanes that differ are counted and printed. A texture the device converts itself lies off
/// Metal's steps (`ycbcr_device_reads`): each `half` lane is its `float` lane's `half`, within one
/// unit in the last place.
#[test]
fn ycbcr_half_gathers_round_ties_away() {
on_device(|device, _| {
@@ -4093,7 +4246,7 @@ fn ycbcr_half_gathers_round_ties_away() {
d.t_address_mode = mode;
(mode, device.new_sampler_state(&d).unwrap())
});
let mut textures: Vec<(PixelFormat, String, Texture)> = Vec::new();
let mut textures: Vec<(PixelFormat, String, Texture, bool)> = Vec::new();
for (seed, (pf, matrix)) in (200..).zip([
(PixelFormat::YCBCR84202PSRGB, None),
(
@@ -4107,14 +4260,18 @@ fn ycbcr_half_gathers_round_ties_away() {
(PixelFormat::YCBCR84202P, Some(SurfaceYCbCrMatrix::Itu709)),
]) {
let surface = buffer_with(device, &surface_bytes(seed)).unwrap();
let converted = device_conversions(device);
let texture = eight_bit_texture(&surface, pf, Some(facts(VIDEO, matrix)), usage);
textures.push((pf, format!("420v {matrix:?}"), texture.unwrap()));
let by_device = device_conversions(device) > converted;
textures.push((pf, format!("420v {matrix:?}"), texture.unwrap(), by_device));
}
let ten = buffer_with(device, &ten_bit_bytes(210)).unwrap();
let pf = PixelFormat::YCBCR104202PSRGB;
let matrix = Some(SurfaceYCbCrMatrix::Itu709);
let converted = device_conversions(device);
let texture = ten_bit_texture(&ten, pf, (b"x420", 0), matrix).unwrap();
textures.push((pf, "x420".into(), texture));
let by_device = device_conversions(device) > converted;
textures.push((pf, "x420".into(), texture, by_device));
for (seed, (pf, ostype)) in (220..).zip([
(PixelFormat::YCBCR84222PSRGB, "422v"),
(PixelFormat::YCBCR84442PSRGB, "444f"),
@@ -4125,11 +4282,13 @@ fn ycbcr_half_gathers_round_ties_away() {
]) {
let codes = ycbcr_format(pf).and_then(YCbCrCodes::of).unwrap();
let surface = buffer_with(device, &family_bytes(seed, codes)).unwrap();
let converted = device_conversions(device);
let texture = family_texture(&surface, pf, ostype, None).unwrap();
textures.push((pf, ostype.into(), texture));
let by_device = device_conversions(device) > converted;
textures.push((pf, ostype.into(), texture, by_device));
}
let (mut ties, mut rounded) = (0, 0usize);
for (pf, over, texture) in &textures {
for (pf, over, texture, by_device) in &textures {
for (mode, state) in &samplers {
for (channel, [float, half]) in ["red", "blue"].iter().zip(&kernels.gathers) {
let floats = gathered_of(device, float, texture, state);
@@ -4142,6 +4301,18 @@ fn ycbcr_half_gathers_round_ties_away() {
for (i, (f, h)) in lanes.enumerate() {
let [f, h] = [f, h].map(|b| f32::from_le_bytes(*b));
let case = format!("{pf:?} over {over}, {mode:?}, {channel} lane {i}");
if *by_device {
// The device's conversion lies off Metal's steps: the `half` gather
// is the `float` one's `half` (`PrecisionNote::NativeHalfConversion`).
let nearest = f64::from(f);
let exponent = match nearest.abs() {
v if v < 2f64.powi(-14) => -24,
v => v.log2().floor() as i32 - 10,
};
let off = (f64::from(h) - nearest).abs();
assert!(off <= 2f64.powi(exponent), "{case}: {h}, the float {f}");
continue;
}
let step = f * 8192.0;
assert!(
step.fract() == 0.0 && (0.0..=8192.0).contains(&step),
+2
View File
@@ -186,6 +186,7 @@ pub(crate) mod visibility_resolve;
pub(crate) mod ycbcr_convert;
pub(crate) mod ycbcr_in_place;
pub(crate) mod ycbcr_refresh;
pub(crate) mod ycbcr_sample;
pub(crate) mod ycbcr_write;
pub use acceleration::{
@@ -347,4 +348,5 @@ pub use ycbcr_convert::{
};
pub use ycbcr_in_place::YCbCrInPlace;
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};
@@ -0,0 +1,348 @@
//! A two-plane YCbCr texture's texels as the device's own sampler Y′CbCr conversion reads them,
//! written into the texture's image.
//!
//! Where the device converts a texture's planes itself (a `VkSamplerYcbcrConversion` of the
//! planes' multi-planar format, its model, range, chroma offsets and chroma filter), the
//! consumer copies the planes into an image of that format and one dispatch of
//! [`ycbcr_sample_module`] samples it through a sampler of that conversion at the centre of each
//! luma texel, writing each texel into the texture's image in the layout
//! [`ycbcr_convert`](super::ycbcr_convert) writes Metal's: the device's model conversion and its
//! chroma reconstruction take the place of Metal's fixed-point ones, and every pipeline that
//! reads the texture reads its image as before. What a texel holds is the device's answer: Vulkan
//! states the reconstruction's weights (`VkChromaLocation`, `VkFilter`) and the model's matrices,
//! and leaves the precision of each step at least that of the format's codes, a clamp of the
//! result into `[0, 1]` optional.
//!
//! **The module** (one per device and output; the sampler, its conversion and the planes' format
//! are the consumer's layout's, so one module samples any of them). One `GLCompute` entry `main`
//! with local size ([`YCbCrSampleModule::LOCAL_SIZE`], [`YCbCrSampleModule::LOCAL_SIZE`], 1),
//! [`YCbCrSampleModule::PUSH_BYTES`] of `COMPUTE` push constants at offset 0
//! ([`YCbCrSampleModule::push`]), and in set 0:
//!
//! | Binding | Resource |
//! |---|---|
//! | [`YCbCrSampleModule::PLANES_BINDING`] | the planes' image, a 2D combined image sampler, through a sampler of the device's Y′CbCr conversion (immutable, as Vulkan requires), sampled at level 0 |
//! | [`YCbCrSampleModule::IMAGE_BINDING`] | the texture's image, a 2D storage image, written as [`YCbCrConvertModule::IMAGE_BINDING`](super::YCbCrConvertModule::IMAGE_BINDING) states for the output |
//!
//! The push constants' words, in order: the texture's width and height in luma texels, then the
//! planes' image's (each the texture's, rounded up to the format's chroma block). Invocation
//! `(x, y)` inside the texture samples `((x + 0.5) / W, (y + 0.5) / H)` of the image's `W x H` and
//! writes texel `(x, y)` of the sample `(r, g, b)`:
//!
//! - **Converted** ([`YCbCrOutput::Converted`]): `(r, g, b, 1)`, the device's conversion of the
//! surface's matrix and range.
//! - **sRGB** ([`YCbCrOutput::Srgb`]): each channel `c` of that conversion through the sRGB
//! curve, `c / 12.92` up to `0.04045` and `((c + 0.055) / 1.055)^2.4` above (`float`
//! arithmetic), alpha 1.
//! - **Codes** ([`YCbCrOutput::Codes`], a conversion of the identity model): the sample's red
//! (Cr), green (Y) and blue (Cb) as codes of `b` bits, each `roundEven(clamp(c, 0, 1) · (2^b
//! - 1))`, packed as the conversion module packs them.
//!
//! An invocation outside the texture writes nothing. The consumer dispatches
//! `⌈w / 8⌉ x ⌈h / 8⌉` workgroups.
//!
//! **Synchronization** (consumer): the planes' copy into the image (`TRANSFER_WRITE`) →
//! `SHADER_SAMPLED_READ` in `COMPUTE_SHADER` before the dispatch; its image writes
//! (`SHADER_STORAGE_WRITE`) → whatever reads the texture after.
use std::sync::Arc;
use super::ycbcr_convert::{scalar, YCbCrCodes, YCbCrOutput};
use crate::budget::{Budget, Meter};
use crate::device::requirements::Requirements;
use crate::device::Device;
use crate::error::{Error, InternalError, InternalKind};
use crate::pipeline::sym::{
CombinedSampler, PushField, ResourceKind, ResourceSlot, SamplerRef, Stage, Symbol,
};
use crate::spirv::builder::constructs::{ArmEnd, ArmFn};
use crate::spirv::builder::ModuleBuilder;
use crate::spirv::error::BResult;
use crate::spirv::ids::Value;
use crate::spirv::ir::{
BinOp, ConvOp, Dim, ExecMode, ExecModel, GlslOp, ImageOperands, ImageType, ImageUsage, IoDir,
MemAccess, StorageClass, TexelMemory, Type, TypedModule,
};
/// The crate-owned YCbCr sample module of one device, validated like any output.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct YCbCrSampleModule {
/// 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 YCbCrSampleModule {
/// Descriptor set of every binding.
pub const SET: u32 = 0;
/// The planes' image through the device's Y′CbCr conversion: a combined image sampler.
pub const PLANES_BINDING: u32 = 0;
/// The texture's image: a 2D storage image, written.
pub const IMAGE_BINDING: u32 = 1;
/// Bytes of the `COMPUTE` push-constant range at offset 0 ([`push`](Self::push)).
pub const PUSH_BYTES: u32 = 16;
/// Invocations of one workgroup along x, and along y: one texel each.
pub const LOCAL_SIZE: u32 = 8;
/// The push bytes of a texture of `size` luma texels over a planes' image of `extent` (the
/// module docs).
pub fn push(size: [u32; 2], extent: [u32; 2]) -> [u8; Self::PUSH_BYTES as usize] {
let words = [size[0], size[1], extent[0], extent[1]];
let mut bytes = [0; Self::PUSH_BYTES as usize];
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 planes' combined image sampler in the typed module.
const PLANES: ResourceSlot = ResourceSlot {
stage: Stage::Kernel,
kind: ResourceKind::CombinedTextureSampler(CombinedSampler {
sampler: SamplerRef::Slot(0),
compare: false,
integer: false,
cube_gradient: false,
}),
index: 0,
};
/// The binding symbol of the texture's image in the typed module.
const IMAGE: ResourceSlot = ResourceSlot {
stage: Stage::Kernel,
kind: ResourceKind::Texture,
index: 1,
};
/// The push field the sizes are declared under: a crate-owned module's own words, which no
/// selection places.
const SIZES: PushField = PushField::DispatchRegion;
/// The sample module as a typed module, before serialization, writing `codes`' output.
fn typed_module(codes: YCbCrCodes) -> BResult<TypedModule> {
let output = codes.output;
let mut b = ModuleBuilder::new();
let u32_ = b.ty(Type::Int {
width: 32,
signed: false,
})?;
let f32_ = b.ty(Type::Float { width: 32 })?;
let uvec2 = b.ty(Type::Vector { elem: u32_, len: 2 })?;
let uvec3 = b.ty(Type::Vector { elem: u32_, len: 3 })?;
let uvec4 = b.ty(Type::Vector { elem: u32_, len: 4 })?;
let vec2 = b.ty(Type::Vector { elem: f32_, len: 2 })?;
let vec4 = b.ty(Type::Vector { elem: f32_, len: 4 })?;
let (sampled_type, format) = match output {
YCbCrOutput::Converted => (f32_, crate::spv::ImageFormat::Rgba16f),
YCbCrOutput::Srgb => (f32_, crate::spv::ImageFormat::Rgba32f),
YCbCrOutput::Codes => (u32_, crate::spv::ImageFormat::R32ui),
};
let texel_ty = b.ty(Type::Vector {
elem: sampled_type,
len: 4,
})?;
let planes_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: planes_ty })?;
let planes = b.resource(PLANES, StorageClass::UniformConstant, combined_ty)?;
let image_ty = b.ty(Type::Image(ImageType {
sampled_type,
dim: Dim::D2,
depth: false,
arrayed: false,
multisampled: false,
usage: ImageUsage::Storage,
format,
}))?;
let image = b.resource(IMAGE, StorageClass::UniformConstant, image_ty)?;
let m_sizes = b.push_member(SIZES, uvec4, 0)?;
let push = b.push_global()?;
let invocation = b.builtin(crate::spv::BuiltIn::GlobalInvocationId, IoDir::Input, uvec3)?;
let void = b.ty(Type::Void)?;
let mut f = b.function(void)?;
let float = |f: &mut crate::spirv::builder::FunctionBuilder<'_>, v: f32| {
scalar(f, f32_, u64::from(v.to_bits()))
};
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 push = f.module().global_value(push)?;
let member = scalar(&mut f, u32_, u64::from(m_sizes.index))?;
let sizes = f.access_chain(push, &[member])?;
let sizes = f.load(sizes, MemAccess::default())?;
let width = f.composite_extract(sizes, &[0])?;
let height = f.composite_extract(sizes, &[1])?;
let across = f.composite_extract(sizes, &[2])?;
let down = f.composite_extract(sizes, &[3])?;
let in_x = f.binary(BinOp::ULessThan, x, width)?;
let in_y = f.binary(BinOp::ULessThan, y, height)?;
let inside = f.binary(BinOp::LogicalAnd, in_x, in_y)?;
let planes = f.module().global_value(planes)?;
let image = f.module().global_value(image)?;
let sampled: ArmFn<'_, ()> = Box::new(move |f, _| {
// The centre of luma texel `(x, y)` of the planes' image, normalized.
let half = float(f, 0.5)?;
let mut coord = Vec::with_capacity(2);
for (at, extent) in [(x, across), (y, 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(planes, 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)?;
let one = float(f, 1.0)?;
let rgb: Vec<Value> = (0..3)
.map(|c| f.composite_extract(sample, &[c]))
.collect::<BResult<_>>()?;
let texel = match output {
YCbCrOutput::Converted => {
f.composite_construct(vec4, &[rgb[0], rgb[1], rgb[2], one])?
}
YCbCrOutput::Srgb => {
// The sRGB curve, in `float` arithmetic.
let knee = float(f, 0.04045)?;
let slope = float(f, 12.92)?;
let offset = float(f, 0.055)?;
let scale = float(f, 1.055)?;
let power = float(f, 2.4)?;
let mut channels = Vec::with_capacity(4);
for c in rgb {
let low = f.binary(BinOp::FDiv, c, slope)?;
let high = f.binary(BinOp::FAdd, c, offset)?;
let high = f.binary(BinOp::FDiv, high, scale)?;
let high = f.glsl(GlslOp::Pow, &[high, power])?;
let below = f.binary(BinOp::FOrdLessThanEqual, c, knee)?;
channels.push(f.select(below, low, high)?);
}
channels.push(one);
f.composite_construct(vec4, &channels)?
}
YCbCrOutput::Codes => {
// Red Cr, green Y and blue Cb, each rounded to a code.
let zero = float(f, 0.0)?;
let max = (1u32 << codes.bits) - 1;
let largest = float(f, max as f32)?;
let mut code = Vec::with_capacity(3);
for c in rgb {
let c = f.glsl(GlslOp::FClamp, &[c, zero, one])?;
let c = f.binary(BinOp::FMul, c, largest)?;
code.push(f.glsl(GlslOp::RoundEven, &[c])?);
}
// `A2B10G10R10_UNORM_PACK32`'s or `R8G8B8A8_UNORM`'s bits, `b` each: red Cr,
// green Y, blue Cb, and alpha every bit above.
let mut packed = scalar(f, u32_, u64::from(u32::MAX << (3 * codes.bits)))?;
for (i, c) in code.into_iter().enumerate() {
let c = f.convert(ConvOp::ConvertFToU, c, u32_)?;
let shift = scalar(f, u32_, u64::from(i as u32 * codes.bits))?;
let c = f.binary(BinOp::ShiftLeftLogical, c, shift)?;
packed = f.binary(BinOp::BitwiseOr, packed, c)?;
}
let zero = scalar(f, u32_, 0)?;
f.composite_construct(texel_ty, &[packed, zero, zero, zero])?
}
};
let at = f.composite_construct(uvec2, &[x, y])?;
let image = f.load(image, MemAccess::default())?;
f.write(
image,
at,
texel,
&ImageOperands::default(),
TexelMemory::PRIVATE,
)?;
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: YCbCrSampleModule::LOCAL_SIZE,
y: YCbCrSampleModule::LOCAL_SIZE,
z: 1,
}],
)?;
b.finalize()
}
/// The fixed binding numbers of the module's symbols.
fn binding_of(sym: &Symbol) -> Option<u32> {
match sym {
Symbol::DescriptorSet(_) => Some(YCbCrSampleModule::SET),
Symbol::Binding(s) if *s == PLANES => Some(YCbCrSampleModule::PLANES_BINDING),
Symbol::Binding(s) if *s == IMAGE => Some(YCbCrSampleModule::IMAGE_BINDING),
_ => None,
}
}
/// The YCbCr sample module of `device` that writes the texels of `codes`' output (its
/// [`YCbCrCodes::output`], and its [`YCbCrCodes::bits`] where it reads codes): 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 [`YCbCrSampleModule`]. The
/// sampler and the planes' image are the consumer's (the module docs), so one module samples
/// every conversion of an output.
pub fn ycbcr_sample_module(device: &Device, codes: YCbCrCodes) -> Result<YCbCrSampleModule, Error> {
let profile = device.profile();
let m = typed_module(codes)?;
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 YCbCr sample module needs {c:?}"),
))
})?;
let words = crate::spirv::serialize::relocate(&r, &binding_of)?;
Ok(YCbCrSampleModule {
spirv: words.into(),
requirements: r.requirements,
})
}
#[cfg(test)]
mod tests {
use super::typed_module;
use crate::bind::YCbCrCodes;
use crate::metal::format::ycbcr_format;
use crate::metal::PixelFormat;
use crate::spirv::testing::{assert_valid, committed_profiles};
/// Every layout's module on every committed profile.
#[test]
fn the_ycbcr_sample_kernel_is_valid_on_every_committed_profile() {
let mut layouts: Vec<YCbCrCodes> = Vec::new();
for pf in PixelFormat::ALL.iter().copied() {
if let Some(codes) = ycbcr_format(pf).and_then(YCbCrCodes::of) {
if !layouts.contains(&codes) {
layouts.push(codes);
}
}
}
assert!(layouts.len() >= 3, "{layouts:?}");
for (_, p) in committed_profiles().expect("profiles") {
for &codes in &layouts {
assert_valid(typed_module(codes).expect("module"), &p);
}
}
}
}
+1 -1
View File
@@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 469;
/// 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 = 1672;
pub const RUNTIME_VERSION: u32 = 1673;
/// 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
+14
View File
@@ -976,6 +976,20 @@ pub enum RuntimeDriverDefect {
/// thread sleeps on its condition variable, woken by the completion turns, in place of
/// waiting for the signals its held batches wait for to land on the GPU itself.
WaitForAnyObjectLosesASignal,
/// A sampler Y′CbCr conversion of a two-plane 4:2:0 or 4:2:2 format reconstructs the chroma
/// away from where its chroma offsets place it: each chroma sample's weights, of the right
/// shape, lie one luma texel up and to the left of the midpoint's (or, cosited, are no
/// interpolation at all), and a linear filter filters the chroma twice, which Vulkan's
/// reconstruction (`VkChromaLocation`, `VkFilter`) forbids. Nothing is refused: the runtime
/// converts such a texture's planes with its own kernel there, as on a device without the
/// conversion.
TwoPlaneChromaMisplaced,
/// A sampler Y′CbCr conversion of a 10-bit multi-planar format (`..._3PACK16`) reads each
/// code's 16-bit word, its six unused low bits included, as a 16-bit unsigned normalized
/// value, where Vulkan converts the 10-bit code as `c / 1023`: a code reads up to one code
/// low (1023 as 0.999039). Nothing is refused: the runtime converts such a texture's planes
/// with its own kernel there, as on a device without the conversion.
TenBitCodesReadAsWords,
}
/// One device capability a refusal can name.
@@ -422,6 +422,11 @@ assoc-const metal2vulkan::bind::YCbCrRefreshModule::ROW_WORDS pub const ROW_WORD
assoc-const metal2vulkan::bind::YCbCrRefreshModule::SET pub const SET: u32
assoc-const metal2vulkan::bind::YCbCrRefreshModule::STATE_BINDING pub const STATE_BINDING: u32
assoc-const metal2vulkan::bind::YCbCrRefreshModule::STATE_WORDS pub const STATE_WORDS: u32
assoc-const metal2vulkan::bind::YCbCrSampleModule::IMAGE_BINDING pub const IMAGE_BINDING: u32
assoc-const metal2vulkan::bind::YCbCrSampleModule::LOCAL_SIZE pub const LOCAL_SIZE: u32
assoc-const metal2vulkan::bind::YCbCrSampleModule::PLANES_BINDING pub const PLANES_BINDING: u32
assoc-const metal2vulkan::bind::YCbCrSampleModule::PUSH_BYTES pub const PUSH_BYTES: u32
assoc-const metal2vulkan::bind::YCbCrSampleModule::SET pub const SET: u32
assoc-const metal2vulkan::bind::YCbCrWriteModule::BYTES_BINDING pub const BYTES_BINDING: u32
assoc-const metal2vulkan::bind::YCbCrWriteModule::LOCAL_SIZE pub const LOCAL_SIZE: u32
assoc-const metal2vulkan::bind::YCbCrWriteModule::SET pub const SET: u32
@@ -916,6 +921,11 @@ assoc-const-value metal2vulkan::bind::YCbCrRefreshModule::ROW_WORDS Self::LOCAL_
assoc-const-value metal2vulkan::bind::YCbCrRefreshModule::SET 0
assoc-const-value metal2vulkan::bind::YCbCrRefreshModule::STATE_BINDING 2
assoc-const-value metal2vulkan::bind::YCbCrRefreshModule::STATE_WORDS 4
assoc-const-value metal2vulkan::bind::YCbCrSampleModule::IMAGE_BINDING 1
assoc-const-value metal2vulkan::bind::YCbCrSampleModule::LOCAL_SIZE 8
assoc-const-value metal2vulkan::bind::YCbCrSampleModule::PLANES_BINDING 0
assoc-const-value metal2vulkan::bind::YCbCrSampleModule::PUSH_BYTES 16
assoc-const-value metal2vulkan::bind::YCbCrSampleModule::SET 0
assoc-const-value metal2vulkan::bind::YCbCrWriteModule::BYTES_BINDING 2
assoc-const-value metal2vulkan::bind::YCbCrWriteModule::LOCAL_SIZE 8
assoc-const-value metal2vulkan::bind::YCbCrWriteModule::SET 0
@@ -2923,6 +2933,8 @@ field metal2vulkan-runtime::WorkCounts.wakes_handler_threads pub wakes_handler_t
field metal2vulkan-runtime::WorkCounts.wakes_spared pub wakes_spared: u64
field metal2vulkan-runtime::WorkCounts.ycbcr_conversion_scratch_buffers pub ycbcr_conversion_scratch_buffers: u64
field metal2vulkan-runtime::WorkCounts.ycbcr_conversion_scratch_bytes pub ycbcr_conversion_scratch_bytes: u64
field metal2vulkan-runtime::WorkCounts.ycbcr_device_conversions pub ycbcr_device_conversions: u64
field metal2vulkan-runtime::WorkCounts.ycbcr_device_samples pub ycbcr_device_samples: u64
field metal2vulkan-runtime::WorkCounts.ycbcr_images_kept_alignment pub ycbcr_images_kept_alignment: u64
field metal2vulkan-runtime::WorkCounts.ycbcr_images_kept_device pub ycbcr_images_kept_device: u64
field metal2vulkan-runtime::WorkCounts.ycbcr_images_kept_elements pub ycbcr_images_kept_elements: u64
@@ -3568,6 +3580,8 @@ field metal2vulkan::bind::YCbCrPlanes.range pub range: YCbCrRange
field metal2vulkan::bind::YCbCrPlanes.size pub size: [u32; 2]
field metal2vulkan::bind::YCbCrRefreshModule.requirements pub requirements: Requirements
field metal2vulkan::bind::YCbCrRefreshModule.spirv pub spirv: Arc<[u32]>
field metal2vulkan::bind::YCbCrSampleModule.requirements pub requirements: Requirements
field metal2vulkan::bind::YCbCrSampleModule.spirv pub spirv: Arc<[u32]>
field metal2vulkan::bind::YCbCrWriteModule.requirements pub requirements: Requirements
field metal2vulkan::bind::YCbCrWriteModule.spirv pub spirv: Arc<[u32]>
field metal2vulkan::bind::indirect_commands::Bindings.pipeline pub pipeline: Option<NonZeroU64>
@@ -4608,6 +4622,7 @@ fn metal2vulkan::bind::ycbcr_convert_floats_module pub fn ycbcr_convert_floats_m
fn metal2vulkan::bind::ycbcr_convert_module pub fn ycbcr_convert_module(device: &Device, conversion: YCbCrConversion) -> Result<YCbCrConvertModule, Error>
fn metal2vulkan::bind::ycbcr_read pub fn ycbcr_read(codes: YCbCrCodes, (range, matrix): (YCbCrRange, YCbCrMatrix), [y, cb, cr]: [u16; 3]) -> [u16; 3]
fn metal2vulkan::bind::ycbcr_refresh_module pub fn ycbcr_refresh_module(device: &Device) -> Result<YCbCrRefreshModule, Error>
fn metal2vulkan::bind::ycbcr_sample_module pub fn ycbcr_sample_module(device: &Device, codes: YCbCrCodes) -> Result<YCbCrSampleModule, Error>
fn metal2vulkan::bind::ycbcr_store pub fn ycbcr_store(codes: YCbCrCodes, (range, matrix): (YCbCrRange, YCbCrMatrix), texels: &[[f32; 3]], size: [u32; 2]) -> Option<(Vec<u16>, Vec<[u16; 2]>)>
fn metal2vulkan::bind::ycbcr_texel pub fn ycbcr_texel(range: YCbCrRange, matrix: YCbCrMatrix, y: u8, cb: u8, cr: u8) -> [u16; 3]
fn metal2vulkan::bind::ycbcr_write pub fn ycbcr_write(codes: YCbCrCodes, (range, matrix): (YCbCrRange, YCbCrMatrix), [r, g, b]: [f32; 3]) -> Option<[u16; 3]>
@@ -8618,6 +8633,7 @@ method metal2vulkan::bind::YCbCrPlanes::conversion pub fn conversion(&self) -> Y
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::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]
method metal2vulkan::bind::YCbCrWriteModule::groups pub fn groups(planes: &YCbCrPlanes) -> [u32; 2]
method metal2vulkan::bind::YCbCrWriteModule::shape pub fn shape(planes: &YCbCrPlanes, all: bool) -> [u8; Self::SHAPE_WORDS as usize * 4]
method metal2vulkan::bind::indirect_commands::Bindings::buffers pub fn buffers(&self, stage: BufferStage) -> &[Option<BufferBinding>; BINDING_COUNT]
@@ -9536,6 +9552,7 @@ struct metal2vulkan::bind::YCbCrConvertModule #[derive(Clone, Debug, PartialEq,
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::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
struct metal2vulkan::bind::indirect_commands::Bindings #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Bindings
struct metal2vulkan::bind::indirect_commands::BufferBinding #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct BufferBinding
@@ -13235,6 +13252,8 @@ variant metal2vulkan::error::RuntimeDriverDefect::PushedBufferSizesUnset PushedB
variant metal2vulkan::error::RuntimeDriverDefect::PushedDescriptorsStaleAfterPipelineBinds PushedDescriptorsStaleAfterPipelineBinds
variant metal2vulkan::error::RuntimeDriverDefect::ReadsCommandBuffersAfterTheirSignal ReadsCommandBuffersAfterTheirSignal
variant metal2vulkan::error::RuntimeDriverDefect::SetLayoutSupportUnderstated SetLayoutSupportUnderstated
variant metal2vulkan::error::RuntimeDriverDefect::TenBitCodesReadAsWords TenBitCodesReadAsWords
variant metal2vulkan::error::RuntimeDriverDefect::TwoPlaneChromaMisplaced TwoPlaneChromaMisplaced
variant metal2vulkan::error::RuntimeDriverDefect::WaitForAnyObjectLosesASignal WaitForAnyObjectLosesASignal
variant metal2vulkan::error::RuntimeInput::AlphaTest AlphaTest
variant metal2vulkan::error::RuntimeInput::ColorWrites ColorWrites
Can't render this file because it is too large.
+2
View File
@@ -729,6 +729,8 @@ surface! {
struct YCbCrWriteModule N;
fn ycbcr_refresh_module;
struct YCbCrRefreshModule N;
fn ycbcr_sample_module;
struct YCbCrSampleModule N;
fn planes_merge_modules;
fn planes_split_module;
enum PlanesCopy N;
+22 -12
View File
@@ -2084,18 +2084,28 @@ bound.
of the state set on it runs its program, as Metal runs a command the CPU encoded, where for a
record the GPU wrote while another state held the ID Metal runs that state (nothing, for a
state of the other kind).
- `metal2vulkan-degrade-ycbcr-filter-not-exact` (precision). `YCbCrFilterNotExact`: 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:
the texels hold Metal's reads exactly, but the sample filters them as the device does, off
the grid Metal sums the format's steps on, so a filtered result can miss Metal's by a step of that
grid or more. A device that samples natively answers the device's filter,
`metal2vulkan-degrade-device-sampling`; on MoltenVK, Metal's own sampler
filters the converted texels as an `RGBA16Float` or `RGBA32Float` texture's, within one step of
the grid (a `half` result within one `half` ulp, measured in plain Metal on an Apple M3 Max under
macOS 27.0.1 for `YCBCR8_420_2P` and its sRGB twin against such a texture of the same texels),
announced at a draw that binds such a texture.
- `metal2vulkan-degrade-ycbcr-filter-not-exact` (precision). `YCbCrFilterNotExact`: A two-plane
YCbCr texture whose planes' format the device converts itself (its sampler Y′CbCr conversion:
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
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'
format, the texels are its own Y′CbCr conversion's, at its precision and unclamped where it does
not clamp, not Metal's fixed-point read; elsewhere the texels hold Metal's reads exactly, but the
sample filters them as the device does, off the grid Metal sums the format's steps on, so a
filtered result can miss Metal's by a step of that grid or more. Measured on lavapipe (Mesa
26.0.8; random planes, every texel), which converts the 8-bit 4:4:4 layout here: each channel
within 0.04/2048 of Vulkan's conversion past the `half` its image stores, and of Metal's read
within 6/2048 where the result lies in `[0, 1]`; outside it by what Metal's clamp takes off. A
device that samples natively answers the device's filter, `metal2vulkan-degrade-device-sampling`;
on MoltenVK, Metal's own sampler filters the converted texels as an `RGBA16Float` or `RGBA32Float`
texture's, within one step of the grid (a `half` result within one `half` ulp, measured in plain
Metal on an Apple M3 Max under macOS 27.0.1 for `YCBCR8_420_2P` and its sRGB twin against such a
texture of the same texels), announced at a draw that binds such a texture.
- `metal2vulkan-degrade-rotated-load-tiles` (precision). `RotatedLoadTiles`: A render pass that
draws loads and stores a rotated texture of rotation 4, whose load is the plane transposed and
whose store is rotation 1's: every tile of the frame lands mirrored, where Metal loads and stores
+7 -3
View File
@@ -57,7 +57,8 @@ known. The rest of the differences are docs/API.md section 9's precision notes.
| `dot`, `mix` and `fast::sqrt` are the device's `OpDot`, `FMix` and `Sqrt`, not Metal's fused chain, its two fused multiply-adds and `x · rsqrt(x)`, on every device but MoltenVK, which takes Metal's order; a `dot` of other than two to four lanes sums the `OpDot` of each chunk of up to four lanes. | The device's order is the contract. | `float` `dot` of n lanes within (3n − 1)·2^-24·Σ\|aᵢbᵢ\|, `mix` within 2^-21 of its two terms, `fast::sqrt` 4.5 ulp. `NativeDot` (`native-dot`), `NativeMix` (`native-mix`), `NativeTranscendentals` (`native-transcendentals`); a `dot` of other than two to four lanes within Vulkan's precision of its chunks' `OpDot` and sum, `DeviceArithmetic` (`device-arithmetic`) |
| Off MoltenVK a `float` multiply, and a fused multiply-add by `OpFmaKHR`, round before Metal's flush: Metal flushes a result whose exact value lies below `2^-126` before rounding it, so a result whose exact value lies within half a unit below `2^-126` answers `2^-126` of its sign where Metal answers the zero of its sign. | Every device measured off MoltenVK (RADV, ANV, NVIDIA, lavapipe) rounds first; its multiply is the contract. | Announced once per device as it is made: `float-tininess-after-rounding` |
| `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` and `ceil` on every device, in the maths functions 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 and depth comparisons 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. A two-plane YCbCr texture's linear sample is the device's filter of its texels, which hold Metal's reads exactly; 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`) |
| Samples, gathers and depth comparisons 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. 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 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 texel's `float` value is the device's conversion of its codes, and a `half` result the device's `float` texel rounded to nearest even, on every device whose texture unit is not Metal's (every device but MoltenVK). 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. | 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; 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`) |
@@ -131,7 +132,8 @@ recorded here.
buffer over their bytes, and converts and filters them in the shader as Metal does; every other
device, and every other use (a `read()`, a gather), converts the texture's image from the planes
before the command buffer's first use (the refresh compares every word first) and reads the
image, which holds Metal's texels exactly and whose linear sample is the device's filter
image, which holds Metal's texels exactly, or the device's own Y′CbCr conversion of them where
it converts the format (the device-gaps row), and whose linear sample is the device's filter
(`device-sampling`; on MoltenVK `ycbcr-filter-not-exact`). Neither is a switch: the device's kind
picks the cheaper. GPU time of a 3840 x 2160 texture whose planes lie in host memory composited
into 1680 x 1050 (µs, best of 3 x 40, unchanged planes; Mesa 26.2.4, MoltenVK 1.4.2):
@@ -147,7 +149,9 @@ 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). A texture whose planes' first
µ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
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_*`).