Files
metal2vulkan/crates/metal2vulkan-runtime/src/release.rs
T
Anees Iqbal a1f1677174 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.
2026-10-28 17:24:22 +02:00

183 lines
6.7 KiB
Rust

//! Releasing Vulkan objects: the runtime's one door to the `vkDestroy*` and `vkFree*` entry points.
//! [`object`] runs each inside a section of the exit guard ([`exit_guard`]) and marks its entry
//! point ([`Call`]), so the hook is registered again after the first one of its kind; once the
//! process is exiting, the object is left to the process's end. A release can run on any thread (a
//! runtime thread drops the last reference to what a command buffer held), so every one goes
//! through here.
//!
//! A new kind of Vulkan object implements [`Released`] below, with a [`Call`] of its own (the
//! instance, its messenger, and the objects of `VK_EXT_device_generated_commands` have functions
//! of their own). No other file of the runtime calls such an entry point: a source test fails
//! when one does (`tests/exit_guard.rs`).
use crate::churn_counts::{self, VkRelease};
use crate::exit_guard::{self, Call};
use crate::generated_commands::{Commands, Handle};
use ash::vk;
use std::panic::Location;
/// A Vulkan object a device releases.
pub(crate) trait Released {
/// Its entry point.
const CALL: Call;
/// Release it: only [`object`] can, holding the [`Door`].
///
/// # Safety
///
/// As the entry point's: the object is `device`'s, and nothing pending uses it.
unsafe fn destroy(self, device: &ash::Device, door: Door);
}
/// The proof that [`object`] calls [`Released::destroy`]: nothing else can make one.
pub(crate) struct Door(());
/// The device itself, released with its own functions (`vkDestroyDevice`).
pub(crate) struct WholeDevice;
/// Release `object` with `device`'s functions, inside a section of the exit guard, marking its
/// entry point; once the process is exiting, leave it to the process's end. Whether it was
/// released. Inside a section already (a whole drop's), it is always released. An image, a
/// buffer or a memory released is counted at its caller's place (`churn_counts.rs`).
///
/// # Safety
///
/// As the entry point's: the object is `device`'s, and nothing pending uses it.
#[track_caller]
pub(crate) unsafe fn object<T: Released>(device: &ash::Device, object: T) -> bool {
let Some(_busy) = exit_guard::enter() else {
return false;
};
// SAFETY: the caller's.
unsafe { object.destroy(device, Door(())) };
exit_guard::called(T::CALL);
let counted = match T::CALL {
Call::DestroyImage => Some(VkRelease::Image),
Call::DestroyBuffer => Some(VkRelease::Buffer),
Call::DestroyBufferView => Some(VkRelease::BufferView),
Call::FreeMemory => Some(VkRelease::Memory),
_ => None,
};
if let Some(what) = counted {
churn_counts::vk_released(what, Location::caller());
}
true
}
/// [`object`] for the instance itself (`vkDestroyInstance`).
///
/// # Safety
///
/// Every device and messenger made from the instance is released.
pub(crate) unsafe fn instance(instance: &ash::Instance) -> bool {
let Some(_busy) = exit_guard::enter() else {
return false;
};
// SAFETY: the caller's.
unsafe { instance.destroy_instance(None) };
exit_guard::called(Call::DestroyInstance);
true
}
/// [`object`] for a debug-utils messenger of `loader`'s instance.
///
/// # Safety
///
/// The messenger is the instance's, released once.
pub(crate) unsafe fn messenger(
loader: &ash::ext::debug_utils::Instance,
messenger: vk::DebugUtilsMessengerEXT,
) -> bool {
let Some(_busy) = exit_guard::enter() else {
return false;
};
// SAFETY: the caller's.
unsafe { loader.destroy_debug_utils_messenger(messenger, None) };
exit_guard::called(Call::DestroyDebugUtilsMessenger);
true
}
/// An object of `VK_EXT_device_generated_commands` (`generated_commands.rs`), whose commands
/// `ash`'s device functions do not hold.
pub(crate) enum Generated {
/// A `VkIndirectExecutionSetEXT`.
ExecutionSet(Handle),
/// A `VkIndirectCommandsLayoutEXT`.
CommandsLayout(Handle),
}
/// [`object`] for an object of `VK_EXT_device_generated_commands`, released with the extension's
/// `commands`.
///
/// # Safety
///
/// As the entry point's: the object is the commands' device's, and nothing pending uses it.
pub(crate) unsafe fn generated(commands: &Commands, object: Generated) -> bool {
let Some(_busy) = exit_guard::enter() else {
return false;
};
let (destroy, handle, call) = match object {
Generated::ExecutionSet(set) => (
commands.destroy_execution_set,
set,
Call::DestroyIndirectExecutionSet,
),
Generated::CommandsLayout(layout) => (
commands.destroy_commands_layout,
layout,
Call::DestroyIndirectCommandsLayout,
),
};
// SAFETY: the caller's.
unsafe { destroy(commands.device, handle, std::ptr::null()) };
exit_guard::called(call);
true
}
/// `Released` for handles a device's `vkDestroy*` or `vkFree*` releases.
macro_rules! released {
($($handle:ty => $method:ident, $call:ident;)*) => {
$(
impl Released for $handle {
const CALL: Call = Call::$call;
unsafe fn destroy(self, device: &ash::Device, _: Door) {
// SAFETY: the caller's.
unsafe { device.$method(self, None) }
}
}
)*
};
}
released! {
vk::Buffer => destroy_buffer, DestroyBuffer;
vk::BufferView => destroy_buffer_view, DestroyBufferView;
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;
vk::CommandPool => destroy_command_pool, DestroyCommandPool;
vk::Pipeline => destroy_pipeline, DestroyPipeline;
vk::PipelineLayout => destroy_pipeline_layout, DestroyPipelineLayout;
vk::DescriptorSetLayout => destroy_descriptor_set_layout, DestroyDescriptorSetLayout;
vk::DescriptorPool => destroy_descriptor_pool, DestroyDescriptorPool;
vk::ShaderModule => destroy_shader_module, DestroyShaderModule;
vk::RenderPass => destroy_render_pass, DestroyRenderPass;
vk::Framebuffer => destroy_framebuffer, DestroyFramebuffer;
vk::PipelineCache => destroy_pipeline_cache, DestroyPipelineCache;
vk::QueryPool => destroy_query_pool, DestroyQueryPool;
}
impl Released for WholeDevice {
const CALL: Call = Call::DestroyDevice;
unsafe fn destroy(self, device: &ash::Device, _: Door) {
// SAFETY: the caller's: every object made from the device is released.
unsafe { device.destroy_device(None) }
}
}