Read a YCbCr texture's planes in place on integrated GPUs
One work packet, landed as 2 commits (42abe9a315..391480a6b2 on archive/development-linear-2026-10-28), in order:
* Read a YCbCr texture's planes in place on integrated GPUs
On an integrated GPU or a CPU device, a function that only samples a two-plane YCbCr texture now
reads the texture's planes directly. Such a texture is `YCBCR8_420_2P` or `YCBCR10_420_2P` over
plane 0 of a surface. "Only samples" means nearest or linear, no comparison, no anisotropy and no
`min_lod_clamp`; reading the texture's size is allowed too. The function fetches the codes from a
uniform texel buffer over the planes' bytes, then converts and filters them as Metal does, with
Metal's integer arithmetic. The draw or dispatch reads those bytes alone, so the texture's image is
not converted for it. Every other device, and every other use (a `read()`, a gather), keeps today's
form: the image is converted from the planes through the refresh, then sampled.
Both forms are exact, so there is no precision note and no switch. The device's kind picks the
cheaper one, by Vulkan's deviceType: INTEGRATED_GPU and CPU read in place; DISCRETE_GPU,
VIRTUAL_GPU and OTHER keep the image. This is the same rule as hasUnifiedMemory. Nothing is timed
at startup.
The measured basis is GPU time of a 3840x2160 texture whose planes lie in host memory, composited
into 1680x1050. Figures are microseconds, best of 3 x 40, over unchanged planes; "image" means
today's refresh compare plus the sample. Mesa 26.2.4 and MoltenVK 1.4.2.
device codes in place 1 pass image 1 pass in place 3 passes image 3 passes
Radeon 780M 8-bit 340 1178 1027 3013
Radeon 780M 10-bit 457 1509 1371 3344
RX 7900 XTX 8-bit 1819 1754 5460 1876
RX 7900 XTX 10-bit 3614 3479 10843 3613
M3 Max (MoltenVK) 8-bit 127 259 375 634
M3 Max (MoltenVK) 10-bit 125 364 378 737
A discrete GPU reads the host's planes across its bus at every pass, while its image lies in its
own memory. Where the planes changed, the image's form also converts every texel: 1055 to 1252 us
more on the 780M, 1790 to 3636 on the 7900 XTX, 350 on the M3 Max.
The texel buffer formats are R8G8_UINT for 8-bit codes and R16G16_UINT for 10-bit ones. Vulkan
requires UNIFORM_TEXEL_BUFFER support for both on every device ("Required Format Support": the
1-3 byte-sized components table and the 16-bit components table). Each element holds two luma
codes or one chroma pair.
The translator:
- bind::YCbCrInPlace (new, public) holds the slot's push words and the view's format and bytes:
the size, the planes' places and rows in elements, and the conversion word.
- On a profile that reads in place (ProfileFields::ycbcr_in_place), a 2D float texture slot whose
every access the form reads records RuntimeFact::YCbCrInPlace { slot, samplers }.
- The plan takes VariantKey::ycbcr_in_place for such a slot when the bound texture states
TextureFacts::ycbcr_in_place and every runtime sampler it is sampled through has one filter for
min and mag, no anisotropy, no cubic filter, no comparison and the weighted-average reduction.
The slot then binds WriteSource::YCbCrInPlace and PushField::YCbCrInPlace.
- The variant lowers each sample through lower::sampler::in_place. It builds Metal's texel from
the luma code and the 9/3/3/1 chroma, and feeds extended's exact filter routine
(Decode::InPlace). A runtime sampler's address word is mapped in the shader, as 4:2:0 maps
repeat and mirror to clamp-to-edge.
- Size and level-count queries answer from the push words.
- The YCbCr image variant excludes these slots, so the variant's plan states the same key.
The runtime:
- texture/ycbcr_image.rs states PlanesInPlace for a converted texture where the device reads in
place. Otherwise the texture keeps its image, counted by reason in
WorkCounts::ycbcr_images_kept_{device,layout,swizzle,alignment,elements,reach,view}:
- device: the device's kind;
- layout: another layout, or staged planes;
- swizzle: a swizzle;
- alignment: the planes' first byte misses minTexelBufferOffsetAlignment;
- elements: more than maxTexelBufferElements;
- reach: planes past the buffer, which Metal reads as zeros;
- view: no view usage.
- Binding a slot under the variant makes the texel buffer view, counted in ycbcr_planes_bound.
It records a read of the planes' bytes in the tracker, so writes to the planes through the
buffer, plane textures or blits are ordered before it. The texture's image is not used there.
- The image stays allocated; making it lazily is later work.
SEMANTICS_VERSION 1868, RUNTIME_VERSION 1645.
Also fixed: development's runtime_lane/dma_buf_imports.rs did not compile on Linux under the GPU
cfgs (layer_reported_nothing not imported). It now imports it.
Docs: the runtime's ycbcr.rs and ycbcr_image.rs module docs, docs/FAST-PATHS.md ("Costs of
matching Metal", and the YCbCr filter row), docs/API.md, the runtime README. The api_surface table
and api_signatures.tsv are blessed. REFUSALS, METAL-COVERAGE and CONFORMANCE-COVERAGE did not move.
Verified:
- New interpreter tests (tests::engine_linear_half::in_place) run every texel of a 7x5 texture
against Metal's model, on lavapipe and moltenvk-m3:
- 8-bit and 10-bit codes, with junk in the 10-bit words' low bits, under all six conversions;
- constexpr linear, nearest and offset (2, -1) samples;
- runtime linear, nearest and repeat-as-edge samples;
- half and float results.
They also check that the planner states the fact on lavapipe and moltenvk-m3 and not on
nvidia-rtx5080-laptop, and that a dynamic offset, min_lod_clamp or a 3D texture gets none. A
negative control, a deliberately broken in-place form, failed them.
- bind::plan::slots: the_in_place_variant_takes_a_slot_its_texture_and_samplers_read.
- The device lanes, filter test(/ycbcr/) over the validation and runtime crates, 49 tests:
- M3 Max, MoltenVK 1.4.2, INTEGRATED: 48 passed. The one failure, a constexpr linear mip
filter that is now read in place, is fixed in this commit's test.
- Radeon 780M, RADV, Mesa 26.2.4, INTEGRATED: 49 passed. The samples bind the planes:
ycbcr_planes_bound 3, refreshes 0, whole conversions 0 per three-dispatch round. The 4K
10-bit minify and padded lanes match Metal's hashes in place (planes bound 7, no refresh).
- RX 7900 XTX, RADV, DISCRETE: 49 passed. ycbcr_images_kept_device is counted, the planes are
bound 0 times and the refresh runs.
- lavapipe (linux-gate, LLVM 21.1.8, CPU): 47 passed. The 2 failures are test expectations,
fixed in this commit: the constexpr mip case above, and the baked-sampler test, where the
in-place variant bakes no sampler. The minify lanes read in place and match Metal's hashes.
- Chunked dma-buf buffer, runtime_lane::dma_buf_imports::
a_ycbcr_texture_over_a_buffer_of_chunks_reads_its_planes_in_place. The buffer is
list_limit + 76 single pages, assembled from 2 udmabuf chunks into 1 sparse buffer.
- 780M: read in place across the chunks, every texel Metal's (planes bound 1, no refresh).
- 7900 XTX: kept the image, every texel Metal's.
- Conformance replay on the M3 Max: ycbcr-minify-band-x and -y, ycbcr-texel-reads-420v and
ycbcr-two-plane-format-descriptors all compare exact against Metal's recordings. The bands now
count ycbcr_planes_bound 1 and no refresh, where the recordings hold ycbcr_refreshes 1, so their
cost records want a re-bless on development.
- clippy -D warnings over the workspace (all features), and over the validation, runtime and
translator crates under --cfg m2v_gpu. cargo fmt.
- The core suite is still running at commit time; its result goes in the report.
* 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:
1 parent
54a8b32154
commit
cdf59197cc
56 files changed
+3013
-78
No files matched your search
@@ -231,6 +231,12 @@ the runtime made.
|
||||
`HostPageTexturePolicy::Shadow`, one that renders or writes, one made before the check answered
|
||||
or whose check did not pass), where the device's linear images cannot hold Metal's layout, and
|
||||
where the rows lie with bytes between them.
|
||||
- **Two-plane YCbCr textures** (`YCBCR8_420_2P` and its kin over a surface's planes) hold an
|
||||
image of the texels Metal reads, converted from the planes before a command buffer's first use
|
||||
where they changed. Where `has_unified_memory`, a function that only samples a `YCBCR8_420_2P`
|
||||
or `YCBCR10_420_2P` texture reads the planes' codes in place instead and converts them in the
|
||||
shader, exactly as the image holds them (`WorkCounts::ycbcr_textures_in_place`,
|
||||
`ycbcr_planes_bound`; a texture that keeps the image counts why, `ycbcr_images_kept_*`).
|
||||
|
||||
## Runtime extensions
|
||||
|
||||
|
||||
@@ -1374,6 +1374,13 @@ fn texel_descriptor(
|
||||
WriteSource::Neutral(NeutralResource::TexelBuffer { format }) => {
|
||||
device.neutral_texel_view(*format, storage)
|
||||
}
|
||||
// The planes of a two-plane YCbCr texture read in place (`texture/ycbcr_image.rs`).
|
||||
WriteSource::YCbCrInPlace { slot } => {
|
||||
let texture = slot_texture(tables, *slot)
|
||||
.ok_or_else(|| internal("the plan binds an unbound texture slot's planes"))?;
|
||||
device.shared().counts.ycbcr_planes_bound();
|
||||
texture.planes_view()
|
||||
}
|
||||
other => Err(unexpected(other)),
|
||||
}
|
||||
}
|
||||
@@ -2199,6 +2206,17 @@ pub(super) fn command_uses_into(
|
||||
// An unbound slot takes a neutral image; a texture whose image and usage
|
||||
// lack the binding's usage, its shadow (`texture/usage_shadow.rs`), as does
|
||||
// a draw's sampled one its instance renders (`texture/attached_reads.rs`).
|
||||
// A two-plane YCbCr texture's planes read in place: their bytes, not the
|
||||
// image, which converts for no such read (`texture/ycbcr_image.rs`).
|
||||
if let (Some(texture), AccessClass::YCbCrPlanes) =
|
||||
(slot_texture(tables, slot), resource.class)
|
||||
{
|
||||
let read = vk::AccessFlags2::SHADER_SAMPLED_READ;
|
||||
let used = texture.planes_use(access(read, resource.access.read))?;
|
||||
name(&mut named, &reached, used.key);
|
||||
uses.push(used);
|
||||
continue;
|
||||
}
|
||||
if let Some(texture) = slot_texture(tables, slot) {
|
||||
let (read, write) = image_access(resource.class)?;
|
||||
let storage = resource.class == AccessClass::StorageImage;
|
||||
|
||||
@@ -1508,7 +1508,17 @@ impl Texels {
|
||||
storage: bool,
|
||||
range: BufferRange,
|
||||
) -> Result<vk::BufferView, Error> {
|
||||
let key = (format, storage, range.offset, range.range);
|
||||
self.view_of(format, storage, (range.offset, range.range))
|
||||
}
|
||||
|
||||
/// [`view`](Self::view) of `range` bytes from `offset` in the viewed `VkBuffer`.
|
||||
pub(super) fn view_of(
|
||||
&self,
|
||||
format: Format,
|
||||
storage: bool,
|
||||
(offset, range): (u64, u64),
|
||||
) -> Result<vk::BufferView, Error> {
|
||||
let key = (format, storage, offset, range);
|
||||
let mut views = lock(&self.views.views);
|
||||
if let Some(&view) = views.get(&key) {
|
||||
return Ok(view);
|
||||
@@ -1526,8 +1536,8 @@ impl Texels {
|
||||
let mut info = vk::BufferViewCreateInfo::default()
|
||||
.buffer(buffer)
|
||||
.format(format.into())
|
||||
.offset(range.offset)
|
||||
.range(range.range);
|
||||
.offset(offset)
|
||||
.range(range);
|
||||
if let Some(named) = usage.named() {
|
||||
only = only.usage(named);
|
||||
info = info.push_next(&mut only);
|
||||
|
||||
@@ -191,6 +191,7 @@ mod usage_shadow;
|
||||
mod view_shadow;
|
||||
pub(super) mod wrapped;
|
||||
mod ycbcr_image;
|
||||
pub(crate) use ycbcr_image::{KeptImage, PlanesInPlace};
|
||||
|
||||
pub(crate) use attached_reads::feedback_candidate;
|
||||
pub use shared::SharedTextureHandle;
|
||||
@@ -452,6 +453,10 @@ pub(super) struct TextureShared {
|
||||
///
|
||||
/// [`facts`]: Texture::facts
|
||||
facts: OnceLock<TextureFacts>,
|
||||
/// A two-plane YCbCr texture's planes as a function reads them in place
|
||||
/// (`texture/ycbcr_image.rs`): a slot of a function that reads it only so binds them, not the
|
||||
/// image. `None` for every other texture, a view of one among them.
|
||||
planes_in_place: Option<PlanesInPlace>,
|
||||
}
|
||||
|
||||
impl Drop for TextureShared {
|
||||
@@ -4124,6 +4129,18 @@ impl Texture {
|
||||
record: ViewRecord,
|
||||
parent: Option<Texture>,
|
||||
id_use: IdUse,
|
||||
) -> Texture {
|
||||
Texture::made_with_planes(device, (storage, None), record, parent, id_use)
|
||||
}
|
||||
|
||||
/// [`made`](Self::made), of a two-plane YCbCr texture whose planes a function may read in
|
||||
/// place where `planes_in_place` holds them.
|
||||
fn made_with_planes(
|
||||
device: &Device,
|
||||
(storage, planes_in_place): (Storage, Option<PlanesInPlace>),
|
||||
record: ViewRecord,
|
||||
parent: Option<Texture>,
|
||||
id_use: IdUse,
|
||||
) -> Texture {
|
||||
let ids = &device.shared().resource_ids;
|
||||
let id = match id_use {
|
||||
@@ -4153,6 +4170,7 @@ impl Texture {
|
||||
render_shadow: Mutex::new(None),
|
||||
heap,
|
||||
facts: OnceLock::new(),
|
||||
planes_in_place,
|
||||
}));
|
||||
if let Some(objects) = texture.0.storage.objects() {
|
||||
objects.object_made();
|
||||
@@ -4719,6 +4737,8 @@ impl Texture {
|
||||
// (`MultisampleDepthTwinPolicy::Exact`).
|
||||
facts.depth_twin = self.holds_depth_in_colour();
|
||||
facts.sparse = self.is_sparse();
|
||||
// A two-plane YCbCr texture whose planes a function may read in place.
|
||||
facts.ycbcr_in_place = self.0.planes_in_place.map(|p| p.words);
|
||||
// A wrapped image made without `MUTABLE_FORMAT` takes no view in a storage binding's
|
||||
// other formats (a half-float texture's unsigned integer alias): its storage slots keep
|
||||
// its own format's view. A texture whose storage binding takes the usage shadow binds
|
||||
|
||||
@@ -6,25 +6,37 @@
|
||||
//! image of 10-bit codes or an `R8G8B8A8_UNORM` one of 8-bit codes, which the conversion writes
|
||||
//! packed through an `R32_UINT` view (a store of its bits, where a store of `code / (2^b - 1)`
|
||||
//! through the image's own format would be the device's conversion to the code).
|
||||
//!
|
||||
//! **Planes read in place** (`PlanesInPlace`). On a device that reads host memory with no bus
|
||||
//! between (`ProfileFields::ycbcr_in_place`: an integrated GPU, a CPU device), a texture of
|
||||
//! `YCBCR8_420_2P` or `YCBCR10_420_2P` over plane 0 of a two-plane surface, without a swizzle,
|
||||
//! also states its planes as a function reads them in place (`bind::YCbCrInPlace`): a slot whose
|
||||
//! function reads the texture only so binds a uniform texel buffer over the planes' bytes, and the
|
||||
//! draw or dispatch reads those bytes alone, so the image is not converted for it. Where a plane
|
||||
//! cannot be viewed so, the texture keeps its image alone, counted by the reason
|
||||
//! (`WorkCounts::ycbcr_images_kept_*`): the device, the layout, a swizzle, the planes' first byte
|
||||
//! off `minTexelBufferOffsetAlignment`, more elements than `maxTexelBufferElements`, planes past
|
||||
//! their buffer, or a format the device views no uniform texel buffer of.
|
||||
|
||||
use super::{image_error, IdUse, Image, Storage, Texture};
|
||||
use crate::address_map::AddressModeMap;
|
||||
use crate::binding_view::VkView;
|
||||
use crate::buffer_texture::Texels;
|
||||
use crate::buffer_texture::{view_usage, Texels};
|
||||
use crate::device::lock;
|
||||
use crate::error::{internal, Error};
|
||||
use crate::image_plan::plan_image;
|
||||
use crate::resource::ResourceKey;
|
||||
use crate::shadow::{ShadowBuffer, ShadowCopies, ShadowSource};
|
||||
use crate::shadow_merge::ScratchSpares;
|
||||
use crate::texture_descriptor::{TextureDescriptor, TextureLayout};
|
||||
use crate::tracker::UseRange;
|
||||
use crate::tracker::{Access, Use, UseRange};
|
||||
use crate::values::ResourceOptions;
|
||||
use crate::view_plan::ViewRecord;
|
||||
use crate::ycbcr::{YCbCrConversion, YCbCrWriteBack};
|
||||
use crate::Device;
|
||||
use ash::vk;
|
||||
use metal2vulkan::bind::{YCbCrCodes, YCbCrOutput, YCbCrPlanes};
|
||||
use metal2vulkan::device::FormatUsage;
|
||||
use metal2vulkan::bind::{YCbCrCodes, YCbCrInPlace, YCbCrOutput, YCbCrPlanes};
|
||||
use metal2vulkan::device::{FormatUsage, VkFeature};
|
||||
use metal2vulkan::error::{Feature, Unsupported};
|
||||
use metal2vulkan::metal::format::{
|
||||
vk_format, ycbcr_format, ycbcr_renders, ChromaSubsampling, YCbCrReads,
|
||||
@@ -125,7 +137,93 @@ fn over_read(read: [TextureSwizzle; 3], swizzle: TextureSwizzleChannels) -> Text
|
||||
}
|
||||
}
|
||||
|
||||
/// A two-plane YCbCr texture's planes as a function reads them in place (the module docs): their
|
||||
/// words, and their first byte in the texels' buffer.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct PlanesInPlace {
|
||||
pub(super) words: YCbCrInPlace,
|
||||
start: u64,
|
||||
}
|
||||
|
||||
/// Why a two-plane YCbCr texture keeps its image alone, its planes read in place by no function
|
||||
/// (the module docs), in `WorkCounts::ycbcr_images_kept_*`'s order.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum KeptImage {
|
||||
/// The device's type: a discrete, virtual or other GPU, or none stated.
|
||||
Device,
|
||||
/// A layout the form does not read: another format, plane 1, a P3 surface's codes.
|
||||
Layout,
|
||||
/// The texture's swizzle, which the form does not apply.
|
||||
Swizzle,
|
||||
/// The planes' first byte is off `minTexelBufferOffsetAlignment` in the buffer.
|
||||
Alignment,
|
||||
/// The planes hold more elements than `maxTexelBufferElements`.
|
||||
Elements,
|
||||
/// The planes reach past their buffer, whose bytes past its end Metal reads as zeros.
|
||||
Reach,
|
||||
/// The device views no uniform texel buffer of the planes' format in a buffer of the runtime's
|
||||
/// usage (`buffer_texture::view_usage`).
|
||||
View,
|
||||
}
|
||||
|
||||
impl KeptImage {
|
||||
/// The reasons, in their counters' order.
|
||||
pub(crate) const ALL: [KeptImage; 7] = [
|
||||
KeptImage::Device,
|
||||
KeptImage::Layout,
|
||||
KeptImage::Swizzle,
|
||||
KeptImage::Alignment,
|
||||
KeptImage::Elements,
|
||||
KeptImage::Reach,
|
||||
KeptImage::View,
|
||||
];
|
||||
}
|
||||
|
||||
impl Device {
|
||||
/// The planes in place of a converted texture of `descriptor` over `texels`, whose planes
|
||||
/// `planes` lie in `span` of the texels' buffer (the module docs), or why it keeps its image
|
||||
/// alone.
|
||||
fn planes_in_place(
|
||||
&self,
|
||||
texels: &Texels,
|
||||
descriptor: &TextureDescriptor,
|
||||
(planes, span): (&YCbCrPlanes, &Range<u64>),
|
||||
) -> Result<PlanesInPlace, KeptImage> {
|
||||
let profile = self.compile_device().profile();
|
||||
if !profile.reads_ycbcr_planes_in_place() {
|
||||
return Err(KeptImage::Device);
|
||||
}
|
||||
let words = YCbCrInPlace::of(planes).ok_or(KeptImage::Layout)?;
|
||||
if texels.staged().is_some() {
|
||||
return Err(KeptImage::Layout);
|
||||
}
|
||||
if descriptor.swizzle != TextureSwizzleChannels::DEFAULT {
|
||||
return Err(KeptImage::Swizzle);
|
||||
}
|
||||
if span.start.saturating_add(words.view_bytes()) > span.end {
|
||||
return Err(KeptImage::Reach);
|
||||
}
|
||||
let limits = profile.limits();
|
||||
let (_, at) = texels.buffer.at(span.start);
|
||||
if !at.is_multiple_of(limits.min_texel_buffer_offset_alignment.max(1)) {
|
||||
return Err(KeptImage::Alignment);
|
||||
}
|
||||
if words.elements() > u64::from(limits.max_texel_buffer_elements) {
|
||||
return Err(KeptImage::Elements);
|
||||
}
|
||||
let maintenance5 = self.enabled().features.contains(&VkFeature::Maintenance5);
|
||||
view_usage(
|
||||
|usage| profile.supports_format(words.format(), usage),
|
||||
false,
|
||||
maintenance5,
|
||||
)
|
||||
.map_err(|_| KeptImage::View)?;
|
||||
Ok(PlanesInPlace {
|
||||
words,
|
||||
start: span.start,
|
||||
})
|
||||
}
|
||||
|
||||
/// The two-plane YCbCr texture of `descriptor` (checked as `layout`) over `texels`, the luma
|
||||
/// plane, for Metal's `call`, whose planes `planes` lie in `span` of the texels' buffer: its
|
||||
/// image of the texels Metal reads and the conversion (`ycbcr.rs`). It reads alpha 1 and maps
|
||||
@@ -149,9 +247,16 @@ impl Device {
|
||||
let texels = Arc::new(texels);
|
||||
let mut record = ViewRecord::of_descriptor(layout, &descriptor);
|
||||
if !codes_alone(layout.pixel_format, planes) {
|
||||
let in_place = self.planes_in_place(&texels, &descriptor, (planes, &span));
|
||||
let counts = &self.shared().counts;
|
||||
match &in_place {
|
||||
Ok(_) => counts.ycbcr_texture_in_place(),
|
||||
Err(kept) => counts.ycbcr_image_kept(*kept),
|
||||
}
|
||||
let storage =
|
||||
self.converted_storage(call, texels, &descriptor, layout, (planes, span))?;
|
||||
return Ok(Texture::made(self, storage, record, None, id_use));
|
||||
let made = (storage, in_place.ok());
|
||||
return Ok(Texture::made_with_planes(self, made, record, None, id_use));
|
||||
}
|
||||
// Over a surface of a P3 matrix: an image of the codes of the code-reading format, its
|
||||
// luma, Cb and Cr (green, blue and red there) read as red, green and blue.
|
||||
@@ -281,6 +386,37 @@ impl Device {
|
||||
}
|
||||
|
||||
impl Texture {
|
||||
/// The uniform texel buffer view of the texture's planes read in place (the module docs), made
|
||||
/// at its first bind and kept with the texels. Internal for a texture whose planes are not.
|
||||
pub(crate) fn planes_view(&self) -> Result<vk::BufferView, Error> {
|
||||
let (Some(p), Some(texels)) = (self.0.planes_in_place, self.buffer_texels()) else {
|
||||
return Err(internal(
|
||||
"a planes view of a texture without planes in place",
|
||||
));
|
||||
};
|
||||
let (_, at) = texels.buffer.at(p.start);
|
||||
texels.view_of(p.words.format(), false, (at, p.words.view_bytes()))
|
||||
}
|
||||
|
||||
/// A read by `read` of the bytes of the texture's planes read in place, which a binding of
|
||||
/// them makes (the module docs). Internal for a texture whose planes are not.
|
||||
pub(crate) fn planes_use(&self, read: Access) -> Result<Use<ResourceKey>, Error> {
|
||||
let (Some(p), Some(texels)) = (self.0.planes_in_place, self.buffer_texels()) else {
|
||||
return Err(internal(
|
||||
"a planes use of a texture without planes in place",
|
||||
));
|
||||
};
|
||||
let end = p.start.saturating_add(p.words.view_bytes());
|
||||
let (identity, range) = texels.buffer.tracked(p.start..end);
|
||||
Ok(Use {
|
||||
key: identity.key,
|
||||
tracked: texels.tracked(),
|
||||
range: UseRange::Bytes(range),
|
||||
read,
|
||||
write: Access::NONE,
|
||||
})
|
||||
}
|
||||
|
||||
/// The storage of a view presenting `record` of this texture in its `_sRGB` twin's format
|
||||
/// (`view_plan::check_format` admits `YCBCR8_420_2P` as `YCBCR8_420_2P_sRGB` and
|
||||
/// `YCBCR10_420_2P` as `YCBCR10_420_2P_sRGB`, as Metal makes them, its usage `ShaderRead`
|
||||
|
||||
@@ -131,6 +131,9 @@ pub(crate) struct Counters {
|
||||
fills_by_transfers: AtomicU64,
|
||||
ycbcr_refreshes: AtomicU64,
|
||||
ycbcr_whole_conversions: AtomicU64,
|
||||
ycbcr_textures_in_place: AtomicU64,
|
||||
ycbcr_images_kept: [AtomicU64; 7],
|
||||
ycbcr_planes_bound: AtomicU64,
|
||||
attachment_clears_recorded: AtomicU64,
|
||||
image_blits_recorded: AtomicU64,
|
||||
query_result_copies_recorded: AtomicU64,
|
||||
@@ -651,6 +654,30 @@ impl Counters {
|
||||
self.ycbcr_whole_conversions.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// A two-plane YCbCr texture was made with its planes read in place
|
||||
/// (`texture/ycbcr_image.rs`).
|
||||
pub(crate) fn ycbcr_texture_in_place(&self) {
|
||||
self.ycbcr_textures_in_place.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// A two-plane YCbCr texture was made keeping its image alone for `kept`
|
||||
/// (`texture/ycbcr_image.rs`).
|
||||
pub(crate) fn ycbcr_image_kept(&self, kept: crate::texture::KeptImage) {
|
||||
let at = crate::texture::KeptImage::ALL
|
||||
.iter()
|
||||
.position(|k| *k == kept)
|
||||
.unwrap_or(0);
|
||||
if let Some(counter) = self.ycbcr_images_kept.get(at) {
|
||||
counter.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
/// A binding of a two-plane YCbCr texture's planes read in place was written
|
||||
/// (`binding.rs`).
|
||||
pub(crate) fn ycbcr_planes_bound(&self) {
|
||||
self.ycbcr_planes_bound.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);
|
||||
@@ -3241,6 +3268,33 @@ pub struct WorkCounts {
|
||||
/// over every texel, where the refresh is not made (planes not whole words, or past one
|
||||
/// storage binding) or the planes' `VkBuffer` is not the one it binds.
|
||||
pub ycbcr_whole_conversions: u64,
|
||||
/// Two-plane YCbCr textures made with their planes read in place: a slot whose function reads
|
||||
/// the texture only as the in-place form reads binds a uniform texel buffer over the planes'
|
||||
/// bytes, and its draws and dispatches convert no image (`texture/ycbcr_image.rs`).
|
||||
pub ycbcr_textures_in_place: u64,
|
||||
/// Two-plane YCbCr textures that keep their image alone because the device keeps every one's:
|
||||
/// a discrete, virtual or other GPU, whose image reads the planes across the bus once per
|
||||
/// change where the planes in place would read them at every pass.
|
||||
pub ycbcr_images_kept_device: u64,
|
||||
/// Two-plane YCbCr textures that keep their image alone because the form reads no such
|
||||
/// layout: a format other than `YCBCR8_420_2P` and `YCBCR10_420_2P`, plane 1, a P3 surface.
|
||||
pub ycbcr_images_kept_layout: u64,
|
||||
/// Two-plane YCbCr textures that keep their image alone because of their swizzle.
|
||||
pub ycbcr_images_kept_swizzle: u64,
|
||||
/// Two-plane YCbCr textures that keep their image alone because their planes' first byte is
|
||||
/// off the device's `minTexelBufferOffsetAlignment` in their buffer.
|
||||
pub ycbcr_images_kept_alignment: u64,
|
||||
/// Two-plane YCbCr textures that keep their image alone because their planes hold more
|
||||
/// elements than the device's `maxTexelBufferElements`.
|
||||
pub ycbcr_images_kept_elements: u64,
|
||||
/// Two-plane YCbCr textures that keep their image alone because their planes reach past their
|
||||
/// buffer, whose bytes past its end Metal reads as zeros.
|
||||
pub ycbcr_images_kept_reach: u64,
|
||||
/// Two-plane YCbCr textures that keep their image alone because the device views no uniform
|
||||
/// texel buffer of their planes' format in a buffer of the runtime's usage.
|
||||
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,
|
||||
// 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.
|
||||
@@ -4862,6 +4916,15 @@ impl Device {
|
||||
fills_by_transfers: counters.fills_by_transfers.load(Ordering::Relaxed),
|
||||
ycbcr_refreshes: counters.ycbcr_refreshes.load(Ordering::Relaxed),
|
||||
ycbcr_whole_conversions: counters.ycbcr_whole_conversions.load(Ordering::Relaxed),
|
||||
ycbcr_textures_in_place: counters.ycbcr_textures_in_place.load(Ordering::Relaxed),
|
||||
ycbcr_images_kept_device: counters.ycbcr_images_kept[0].load(Ordering::Relaxed),
|
||||
ycbcr_images_kept_layout: counters.ycbcr_images_kept[1].load(Ordering::Relaxed),
|
||||
ycbcr_images_kept_swizzle: counters.ycbcr_images_kept[2].load(Ordering::Relaxed),
|
||||
ycbcr_images_kept_alignment: counters.ycbcr_images_kept[3].load(Ordering::Relaxed),
|
||||
ycbcr_images_kept_elements: counters.ycbcr_images_kept[4].load(Ordering::Relaxed),
|
||||
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),
|
||||
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
|
||||
|
||||
@@ -57,6 +57,36 @@
|
||||
//! word, past one storage range, or past the device's workgroup counts) or the planes' buffer
|
||||
//! is not the one its set binds, the conversion copies the planes and converts whole
|
||||
//! (`WorkCounts::ycbcr_refreshes`, `ycbcr_whole_conversions`).
|
||||
//! - **Planes read in place, by the device's kind.** On a device whose memory is the host's (Vulkan's
|
||||
//! `deviceType` an integrated GPU or a CPU, `DeviceProperties::has_unified_memory`), a
|
||||
//! `YCBCR8_420_2P` or `YCBCR10_420_2P` texture over plane 0 also states its planes as a function
|
||||
//! reads them in place (`texture/ycbcr_image.rs`, `metal2vulkan::bind::YCbCrInPlace`): a slot
|
||||
//! whose function only samples it (nearest or linear, no comparison, anisotropy or
|
||||
//! `min_lod_clamp`) or reads its size binds a uniform texel buffer over the planes' bytes,
|
||||
//! `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`).
|
||||
//! 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
|
||||
//! 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):
|
||||
//!
|
||||
//! | Device | Codes | In place, 1 pass | Image, 1 pass | In place, 3 passes | Image, 3 passes |
|
||||
//! |---|---|---|---|---|---|
|
||||
//! | Radeon 780M (RADV) | 8-bit | 340 | 1178 | 1027 | 3013 |
|
||||
//! | Radeon 780M (RADV) | 10-bit | 457 | 1509 | 1371 | 3344 |
|
||||
//! | Radeon RX 7900 XTX (RADV) | 8-bit | 1819 | 1754 | 5460 | 1876 |
|
||||
//! | Radeon RX 7900 XTX (RADV) | 10-bit | 3614 | 3479 | 10843 | 3613 |
|
||||
//! | Apple M3 Max (MoltenVK) | 8-bit | 127 | 259 | 375 | 634 |
|
||||
//! | Apple M3 Max (MoltenVK) | 10-bit | 125 | 364 | 378 | 737 |
|
||||
//!
|
||||
//! Where the planes changed, the image's form also converts every texel: 1055 to 1252 µs more on
|
||||
//! the 780M, 1790 to 3636 on the 7900 XTX, 350 on the M3 Max. A texture whose planes' first byte
|
||||
//! misses `minTexelBufferOffsetAlignment`, whose planes hold more elements than
|
||||
//! `maxTexelBufferElements` or reach past their buffer, or which has a swizzle, keeps the image on
|
||||
//! every device, counted by the reason (`ycbcr_images_kept_*`).
|
||||
//! - **The texels Metal's copies move** are the luma plane's bytes, a code's bytes a texel
|
||||
//! (for 4:2:2 and 4:4:4 and, for the code formats): `get_bytes`, `replace_region` and a blit to
|
||||
//! or from a buffer move the luma rows (Metal keeps the chroma plane), the texture's `Texels`
|
||||
|
||||
@@ -1 +1 @@
|
||||
abac60496a48f6b457b02a25a40019a3e3eefe9bf2c37c46793547525e70eaee
|
||||
82ba7ff4cdf11dddef55bbca2ad612f81162b0224b7a2406df81d2d9c1155a00
|
||||
@@ -862,6 +862,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_in_place;
|
||||
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
|
||||
mod ycbcr_minify;
|
||||
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
|
||||
mod ycbcr_passes;
|
||||
|
||||
@@ -33,13 +33,15 @@ use super::keep_alives::eventually;
|
||||
use super::no_copy_heaps::{
|
||||
blit_into, blit_texels, encode_texels_in, encode_texels_out, shared, staged,
|
||||
};
|
||||
use super::ycbcr_in_place::{reads_in_place, sampler, texels, ycbcr_work, Kernels, Surface};
|
||||
use super::{
|
||||
layer_reported_nothing, layer_reported_nothing_at_all, read_buffer, validated_device,
|
||||
validated_device_with, Messages, ScratchCache,
|
||||
};
|
||||
use crate::gpu::TEST_DEVICE;
|
||||
use metal2vulkan::bind::{YCbCrMatrix, YCbCrRange};
|
||||
use metal2vulkan::device::HostPageTexturePolicy;
|
||||
use metal2vulkan::metal::{PixelFormat, TextureUsage};
|
||||
use metal2vulkan::metal::{PixelFormat, SamplerMinMagFilter, TextureUsage};
|
||||
use metal2vulkan::vk::DriverId;
|
||||
use metal2vulkan_runtime::{
|
||||
BlitOption, Buffer, BufferContents, BufferDescriptor, CommandBuffer, CommandQueue,
|
||||
@@ -687,6 +689,90 @@ fn a_view_past_one_udmabuf_s_limits_is_assembled_from_chunks() {
|
||||
});
|
||||
}
|
||||
|
||||
/// A `YCBCR8_420_2P` texture over a no-copy buffer of more discontiguous pages than one udmabuf
|
||||
/// takes (`list_limit + 76` single pages, every other page of the file, each row of both planes a
|
||||
/// page of its own). Where the device refuses the pointer and binds sparse buffers of dma-bufs
|
||||
/// (RADV), the buffer is assembled from chunks, counted, and the planes cross from one chunk into
|
||||
/// the next; where its memory is the host's (an integrated GPU, a CPU device), a kernel's samples
|
||||
/// read the planes in place across them (`WorkCounts::ycbcr_planes_bound`), converting nothing.
|
||||
/// Every nearest sample at a texel's centre is Metal's texel of the codes, on every device.
|
||||
#[test]
|
||||
fn a_ycbcr_texture_over_a_buffer_of_chunks_reads_its_planes_in_place() {
|
||||
const TEST: &str = "dma-buf ycbcr planes";
|
||||
if !udmabuf_openable(TEST) {
|
||||
return;
|
||||
}
|
||||
on_device(|device| {
|
||||
let page = host_page();
|
||||
let runs = Limits::of_host().items + 76;
|
||||
// Two luma rows a chroma row, every row its own page.
|
||||
let rows = 2 * (runs / 3);
|
||||
let surface = Surface {
|
||||
format: PixelFormat::YCBCR84202P,
|
||||
ostype: *b"420v",
|
||||
matrix: None,
|
||||
conversion: (YCbCrRange::Video, YCbCrMatrix::Bt601),
|
||||
size: [512, rows as u64],
|
||||
row: page as u64,
|
||||
chroma_at: (rows * page) as u64,
|
||||
};
|
||||
assert!(surface.length() as usize <= runs * page);
|
||||
let ram = Memfd::new(2 * runs * page);
|
||||
let pieces: Vec<(usize, usize)> = (0..runs).map(|run| (2 * run * page, page)).collect();
|
||||
let view = ram.view(&pieces);
|
||||
let bytes = surface.bytes(11);
|
||||
for (run, piece) in bytes.chunks(page).enumerate() {
|
||||
ram.whole.write(2 * run * page, piece);
|
||||
}
|
||||
let calls = Calls::default();
|
||||
let before = dma_buf_counts(device);
|
||||
let buffer = match no_copy(device, &view, 0, runs * page, ram.source(&view, &calls)) {
|
||||
Ok(buffer) => buffer,
|
||||
Err(error) if imports_dma_buf(device).is_none() => {
|
||||
eprintln!("{TEST}: on {}: {error:?}", device.name());
|
||||
return;
|
||||
}
|
||||
Err(error) => panic!("{TEST}: {error:?}"),
|
||||
};
|
||||
let (imports, sparse) = dma_buf_counts(device);
|
||||
let chunks = calls.lock().unwrap().iter().map(|(_, n)| n).sum::<usize>();
|
||||
eprintln!(
|
||||
"{TEST} on {}: {} imports, {} sparse buffers, {chunks} chunks",
|
||||
device.name(),
|
||||
imports - before.0,
|
||||
sparse - before.1
|
||||
);
|
||||
if imports_dma_buf(device) == Some(true) {
|
||||
assert!(chunks >= 2, "{TEST}: the source's chunks");
|
||||
assert_eq!(sparse - before.1, 1, "{TEST}: a sparse buffer");
|
||||
}
|
||||
let in_place = reads_in_place(device);
|
||||
let texture = surface.texture(&buffer, 0).unwrap();
|
||||
let kernels = Kernels::new(device);
|
||||
let nearest = sampler(device, SamplerMinMagFilter::Nearest);
|
||||
let counted = device.work_counts();
|
||||
let got = texels(
|
||||
device,
|
||||
&kernels.sample,
|
||||
(&texture, surface.size),
|
||||
Some(&nearest),
|
||||
);
|
||||
let work = ycbcr_work(&counted, &device.work_counts());
|
||||
eprintln!(
|
||||
"{TEST} on {}: in place {in_place}, work {work:?}",
|
||||
device.name()
|
||||
);
|
||||
let model = surface.model(&bytes);
|
||||
let wrong = got.iter().zip(&model).filter(|(a, b)| a != b).count();
|
||||
assert_eq!(wrong, 0, "{TEST}: texels not Metal's");
|
||||
if in_place {
|
||||
assert_eq!(work[2..], [1, 0, 0], "{TEST}: the planes read in place");
|
||||
}
|
||||
drop(texture);
|
||||
drop(buffer);
|
||||
});
|
||||
}
|
||||
|
||||
/// [`every_other_page`]'s 64 pages, each its own mapping, as a consumer's view of a surface's
|
||||
/// scattered pages: a no-copy buffer over them all asks the kernel about each of the 64 mappings
|
||||
/// for their write permission before its import (`WorkCounts::host_mappings_queried`), refused or
|
||||
|
||||
@@ -0,0 +1,528 @@
|
||||
//! Device tests of a two-plane YCbCr texture's planes read in place
|
||||
//! (`metal2vulkan::bind::YCbCrInPlace`, the runtime's `texture/ycbcr_image.rs`), on the device the
|
||||
//! cfg selects, under the validation layer.
|
||||
//!
|
||||
//! A device whose memory is the host's (an integrated GPU or a CPU device: `hasUnifiedMemory`)
|
||||
//! reads the planes of a `YCBCR8_420_2P` or `YCBCR10_420_2P` texture in place: the texture counts
|
||||
//! `WorkCounts::ycbcr_textures_in_place` when it is made, and a dispatch whose kernel only samples
|
||||
//! it binds a uniform texel buffer over the planes' bytes (`ycbcr_planes_bound`) and converts
|
||||
//! nothing (`ycbcr_refreshes`, `ycbcr_whole_conversions`). Any other device keeps the texture's
|
||||
//! image alone (`ycbcr_images_kept_device`) and converts it through the refresh. On either, a
|
||||
//! nearest sample and a linear one at a texel's centre read Metal's texel, and a linear one between
|
||||
//! texels Metal's filter of them; a `read()` takes the image on every device.
|
||||
//!
|
||||
//! Each surface is a buffer standing for the IOSurface: the luma plane at byte 0, rows padded past
|
||||
//! their codes, the interleaved chroma plane after it; a 10-bit code in the high 10 bits of a
|
||||
//! little-endian word whose low 6 bits are noise, which Metal does not read.
|
||||
|
||||
use super::degrade_notices::{counts, on_device, on_device_with};
|
||||
use super::{buffer_with, read_buffer, ycbcr_textures};
|
||||
use crate::air_library::AirLibrary;
|
||||
use metal2vulkan::bind::{ycbcr_read, SamplerDescriptor, YCbCrCodes, YCbCrMatrix, YCbCrRange};
|
||||
use metal2vulkan::device::DevicePolicy;
|
||||
use metal2vulkan::metal::format::ycbcr_format;
|
||||
use metal2vulkan::metal::{PixelFormat, SamplerMinMagFilter, TextureUsage};
|
||||
use metal2vulkan::pipeline::{ComputePipelineDescriptor, StageSource};
|
||||
use metal2vulkan_devtools::llvm_assemble_text;
|
||||
use metal2vulkan_runtime::{
|
||||
Buffer, CommandBufferStatus, ComputePipelineState, Degradation, Device, Error, IoSurfacePlane,
|
||||
IoSurfaceYCbCr, PipelineOptions, ResourceOptions, SamplerState, Size, SurfaceYCbCrMatrix,
|
||||
Texture, TextureDescriptor, WorkCounts,
|
||||
};
|
||||
use std::time::Duration;
|
||||
|
||||
const WAIT: Duration = Duration::from_secs(60);
|
||||
|
||||
/// A two-plane 4:2:0 surface of one format: its OSType and matrix attachment, the conversion Metal
|
||||
/// reads them as, its size, the bytes between both planes' rows, and the chroma plane's offset.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(super) struct Surface {
|
||||
pub(super) format: PixelFormat,
|
||||
pub(super) ostype: [u8; 4],
|
||||
pub(super) matrix: Option<SurfaceYCbCrMatrix>,
|
||||
pub(super) conversion: (YCbCrRange, YCbCrMatrix),
|
||||
pub(super) size: [u64; 2],
|
||||
pub(super) row: u64,
|
||||
pub(super) chroma_at: u64,
|
||||
}
|
||||
|
||||
/// The lane's surfaces: 40 x 24, 8-bit `420v` without a matrix (BT.601) and `420f` of BT.709 with
|
||||
/// rows of 64 bytes, 10-bit `x420` of BT.2020 and `xf20` without a matrix with rows of 96.
|
||||
const SURFACES: [Surface; 4] = [
|
||||
Surface {
|
||||
format: PixelFormat::YCBCR84202P,
|
||||
ostype: *b"420v",
|
||||
matrix: None,
|
||||
conversion: (YCbCrRange::Video, YCbCrMatrix::Bt601),
|
||||
size: [40, 24],
|
||||
row: 64,
|
||||
chroma_at: 64 * 24,
|
||||
},
|
||||
Surface {
|
||||
format: PixelFormat::YCBCR84202P,
|
||||
ostype: *b"420f",
|
||||
matrix: Some(SurfaceYCbCrMatrix::Itu709),
|
||||
conversion: (YCbCrRange::Full, YCbCrMatrix::Bt709),
|
||||
size: [40, 24],
|
||||
row: 64,
|
||||
chroma_at: 64 * 24,
|
||||
},
|
||||
Surface {
|
||||
format: PixelFormat::YCBCR104202P,
|
||||
ostype: *b"x420",
|
||||
matrix: Some(SurfaceYCbCrMatrix::Itu2020),
|
||||
conversion: (YCbCrRange::Video, YCbCrMatrix::Bt2020),
|
||||
size: [40, 24],
|
||||
row: 96,
|
||||
chroma_at: 96 * 24,
|
||||
},
|
||||
Surface {
|
||||
format: PixelFormat::YCBCR104202P,
|
||||
ostype: *b"xf20",
|
||||
matrix: None,
|
||||
conversion: (YCbCrRange::Full, YCbCrMatrix::Bt601),
|
||||
size: [40, 24],
|
||||
row: 96,
|
||||
chroma_at: 96 * 24,
|
||||
},
|
||||
];
|
||||
|
||||
impl Surface {
|
||||
/// The format's codes.
|
||||
fn codes(&self) -> YCbCrCodes {
|
||||
ycbcr_format(self.format)
|
||||
.and_then(YCbCrCodes::of)
|
||||
.expect("a converted two-plane format")
|
||||
}
|
||||
|
||||
/// The bytes of a code: 1 or 2.
|
||||
fn unit(&self) -> u64 {
|
||||
u64::from(self.codes().bytes)
|
||||
}
|
||||
|
||||
/// The chroma plane's pairs across and rows.
|
||||
fn chroma_size(&self) -> [u64; 2] {
|
||||
self.size.map(|n| n.div_ceil(2))
|
||||
}
|
||||
|
||||
/// The surface's bytes: through the chroma plane's last row.
|
||||
pub(super) fn length(&self) -> u64 {
|
||||
self.chroma_at + self.row * self.chroma_size()[1]
|
||||
}
|
||||
|
||||
/// The surface's bytes of codes from generator `seed`, every other byte `0xa5`.
|
||||
pub(super) fn bytes(&self, seed: u64) -> Vec<u8> {
|
||||
let mut random = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1;
|
||||
let mut next = move || {
|
||||
random = random
|
||||
.wrapping_mul(6_364_136_223_846_793_005)
|
||||
.wrapping_add(1_442_695_040_888_963_407);
|
||||
(random >> 33) as u16
|
||||
};
|
||||
let mut bytes = vec![0xa5; self.length() as usize];
|
||||
let unit = self.unit() as usize;
|
||||
let mut put = |at: u64, word: u16| {
|
||||
let at = at as usize;
|
||||
match unit {
|
||||
1 => bytes[at] = word as u8,
|
||||
_ => bytes[at..at + 2].copy_from_slice(&word.to_le_bytes()),
|
||||
}
|
||||
};
|
||||
let [w, h] = self.size;
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
put(y * self.row + x * self.unit(), next());
|
||||
}
|
||||
}
|
||||
let [cw, ch] = self.chroma_size();
|
||||
for y in 0..ch {
|
||||
for x in 0..2 * cw {
|
||||
put(self.chroma_at + y * self.row + x * self.unit(), next());
|
||||
}
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
/// The code at byte `at` of `bytes`: a byte, or a word's high 10 bits.
|
||||
fn code(&self, bytes: &[u8], at: u64) -> u16 {
|
||||
let at = at as usize;
|
||||
match self.unit() {
|
||||
1 => u16::from(bytes[at]),
|
||||
_ => u16::from_le_bytes([bytes[at], bytes[at + 1]]) >> 6,
|
||||
}
|
||||
}
|
||||
|
||||
/// Each texel's red, green and blue `v` of `v / 2048` Metal reads of `bytes`, row by row: the
|
||||
/// luma code at its place, the four nearest chroma pairs weighted 9/3/3/1 and rounded to a
|
||||
/// code, converted (`metal2vulkan::bind::ycbcr_read`).
|
||||
pub(super) fn model(&self, bytes: &[u8]) -> Vec<[u16; 3]> {
|
||||
let taps = |q: u64, n: u64| -> [(u64, u32); 2] {
|
||||
let c = q / 2;
|
||||
if q % 2 == 1 {
|
||||
[(c, 3), ((c + 1).min(n - 1), 1)]
|
||||
} else {
|
||||
[(c.saturating_sub(1), 1), (c, 3)]
|
||||
}
|
||||
};
|
||||
let [w, h] = self.size;
|
||||
let [cw, ch] = self.chroma_size();
|
||||
let mut out = Vec::with_capacity((w * h) as usize);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let mut sums = [0u32; 2];
|
||||
for (cy, wy) in taps(y, ch) {
|
||||
for (cx, wx) in taps(x, cw) {
|
||||
let at = self.chroma_at + cy * self.row + 2 * cx * self.unit();
|
||||
sums[0] += wx * wy * u32::from(self.code(bytes, at));
|
||||
sums[1] += wx * wy * u32::from(self.code(bytes, at + self.unit()));
|
||||
}
|
||||
}
|
||||
let [cb, cr] = sums.map(|s| ((s + 8) >> 4) as u16);
|
||||
let luma = self.code(bytes, y * self.row + x * self.unit());
|
||||
out.push(ycbcr_read(self.codes(), self.conversion, [luma, cb, cr]));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The texture of the surface's format over `buffer`'s plane 0, its luma plane at
|
||||
/// `luma_at`, with the surface's facts (its chroma plane at `luma_at + chroma_at`).
|
||||
pub(super) fn texture(&self, buffer: &Buffer, luma_at: u64) -> Result<Texture, Error> {
|
||||
let [w, h] = self.size;
|
||||
let mut d = TextureDescriptor::texture_2d(self.format, w, h, false);
|
||||
d.usage = TextureUsage::SHADER_READ;
|
||||
d.resource_options = ResourceOptions::shared();
|
||||
let ostype = u32::from_be_bytes(self.ostype);
|
||||
let facts = IoSurfaceYCbCr::new(ostype, 0, self.size, luma_at + self.chroma_at, self.row);
|
||||
let facts = match self.matrix {
|
||||
Some(matrix) => facts.with_matrix(matrix),
|
||||
None => facts,
|
||||
};
|
||||
let plane = IoSurfacePlane::new(luma_at, self.row, true).with_ycbcr(facts);
|
||||
buffer.new_texture_with_iosurface_plane(&d, plane)
|
||||
}
|
||||
}
|
||||
|
||||
/// Metal's step of a linear sample at fractions `[a, b]` (in `1/256`) past texel `(x, y)` of
|
||||
/// texels `texels` of `size`, channel `c`: the taps `(x, y)` to `(x + 1, y + 1)` clamped to the
|
||||
/// edge, an axis whose two taps address one texel weighed `(256, 0)`, each term `k · w` truncated by
|
||||
/// `2^7`, then `(T + 2^8) >> 9` (the YCbCr lane's `metal_step`).
|
||||
fn filtered(texels: &[[u16; 3]], [w, h]: [u64; 2], (x, y): (u64, u64), c: usize) -> u16 {
|
||||
let [a, b] = ycbcr_textures::BETWEEN;
|
||||
let (x1, y1) = ((x + 1).min(w - 1), (y + 1).min(h - 1));
|
||||
let a = if x1 == x { 0 } else { a };
|
||||
let b = if y1 == y { 0 } else { b };
|
||||
let k = |x: u64, y: u64| u32::from(texels[(y * w + x) as usize][c]);
|
||||
let taps = [
|
||||
(k(x, y), 256 - a, 256 - b),
|
||||
(k(x1, y), a, 256 - b),
|
||||
(k(x, y1), 256 - a, b),
|
||||
(k(x1, y1), a, b),
|
||||
];
|
||||
let t: u32 = taps.into_iter().map(|(k, wx, wy)| (k * wx * wy) >> 7).sum();
|
||||
((t + 256) >> 9) as u16
|
||||
}
|
||||
|
||||
/// The lane's kernels (`ycbcr_textures::KERNELS`) this module dispatches: `read()` of each texel,
|
||||
/// a sample at its centre with a `float` and a `half` result, and a sample between it and the
|
||||
/// next ([`ycbcr_textures::BETWEEN`]).
|
||||
pub(super) struct Kernels {
|
||||
read: ComputePipelineState,
|
||||
pub(super) sample: ComputePipelineState,
|
||||
sample_half: ComputePipelineState,
|
||||
between: ComputePipelineState,
|
||||
}
|
||||
|
||||
impl Kernels {
|
||||
pub(super) fn new(device: &Device) -> Kernels {
|
||||
let library = device
|
||||
.new_library_with_air(&llvm_assemble_text(ycbcr_textures::KERNELS).unwrap())
|
||||
.unwrap();
|
||||
let state = |name: &str| {
|
||||
let function = library.new_function_with_name(name).unwrap();
|
||||
device
|
||||
.new_compute_pipeline_state(
|
||||
&ComputePipelineDescriptor::new(StageSource::Function(
|
||||
function.function_descriptor(),
|
||||
)),
|
||||
&PipelineOptions::default(),
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
Kernels {
|
||||
read: state("read_texels"),
|
||||
sample: state("sample_texels"),
|
||||
sample_half: state("sample_half"),
|
||||
between: state("sample_between"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A sampler of `filter` for both min and mag.
|
||||
pub(super) fn sampler(device: &Device, filter: SamplerMinMagFilter) -> SamplerState {
|
||||
let mut d = SamplerDescriptor::new();
|
||||
d.min_filter = filter;
|
||||
d.mag_filter = filter;
|
||||
device.new_sampler_state(&d).unwrap()
|
||||
}
|
||||
|
||||
/// The `v` of `v / 2048` of each channel `state` writes of `texture` of `size` through `sampler`,
|
||||
/// one thread a texel, in a command buffer of its own; checked to be on the grid, alpha 1.
|
||||
pub(super) fn texels(
|
||||
device: &Device,
|
||||
state: &ComputePipelineState,
|
||||
(texture, size): (&Texture, [u64; 2]),
|
||||
sampler: Option<&SamplerState>,
|
||||
) -> Vec<[u16; 3]> {
|
||||
let [w, h] = 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();
|
||||
if let Some(sampler) = sampler {
|
||||
encoder.set_sampler_state(Some(sampler), 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.status(), CommandBufferStatus::Completed);
|
||||
let bytes = read_buffer(&out, 0, 16 * w * h).unwrap();
|
||||
bytes
|
||||
.as_chunks::<16>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|t| {
|
||||
let c = |i: usize| f32::from_le_bytes(t[4 * i..4 * i + 4].try_into().unwrap());
|
||||
assert_eq!(c(3), 1.0, "alpha 1");
|
||||
std::array::from_fn(|i| {
|
||||
let v = c(i) * 2048.0;
|
||||
assert!(
|
||||
v == v.round() && (0.0..=2048.0).contains(&v),
|
||||
"{v} off the grid"
|
||||
);
|
||||
v as u16
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The counts of the YCbCr paths between two readings: textures made reading their planes in
|
||||
/// place, kept on their image for the device, planes bound, refreshes and whole conversions.
|
||||
pub(super) fn ycbcr_work(before: &WorkCounts, after: &WorkCounts) -> [u64; 5] {
|
||||
[
|
||||
after.ycbcr_textures_in_place - before.ycbcr_textures_in_place,
|
||||
after.ycbcr_images_kept_device - before.ycbcr_images_kept_device,
|
||||
after.ycbcr_planes_bound - before.ycbcr_planes_bound,
|
||||
after.ycbcr_refreshes - before.ycbcr_refreshes,
|
||||
after.ycbcr_whole_conversions - before.ycbcr_whole_conversions,
|
||||
]
|
||||
}
|
||||
|
||||
/// Whether `device` reads two-plane YCbCr textures' planes in place: its profile's answer, which
|
||||
/// is the device's kind (an integrated GPU or a CPU device, `hasUnifiedMemory`).
|
||||
pub(super) fn reads_in_place(device: &Device) -> bool {
|
||||
let in_place = device
|
||||
.compile_device()
|
||||
.profile()
|
||||
.reads_ycbcr_planes_in_place();
|
||||
assert_eq!(
|
||||
in_place,
|
||||
device.properties().has_unified_memory,
|
||||
"{}: the profile's rule is the device's kind ({:?})",
|
||||
device.name(),
|
||||
device.properties().kind
|
||||
);
|
||||
in_place
|
||||
}
|
||||
|
||||
/// The samples of each surface, then of new codes the CPU wrote into its planes, and a `read()`:
|
||||
/// each texel Metal's, and on a device whose memory is the host's the samples read the planes in
|
||||
/// place, converting nothing, where any other device converts the image. A linear sample at a
|
||||
/// texel's centre and between texels is Metal's texel and Metal's filter of them under `exact` (the
|
||||
/// lane's policy) on every device, and under the defaults on a device that reads in place, where
|
||||
/// they are taken; a device that keeps the image filters it as the device does under the
|
||||
/// defaults, which this module does not sample.
|
||||
fn samples_read_the_planes(device: &Device, exact: bool) {
|
||||
let in_place = reads_in_place(device);
|
||||
eprintln!(
|
||||
"YCBCR-IN-PLACE {} ({:?}): in place {in_place}",
|
||||
device.name(),
|
||||
device.properties().kind
|
||||
);
|
||||
let kernels = Kernels::new(device);
|
||||
let nearest = sampler(device, SamplerMinMagFilter::Nearest);
|
||||
let linear = sampler(device, SamplerMinMagFilter::Linear);
|
||||
for (seed, surface) in (1..).zip(SURFACES) {
|
||||
let what = format!("{:?} {:?}", surface.format, surface.conversion);
|
||||
let mut bytes = surface.bytes(seed);
|
||||
let buffer = buffer_with(device, &bytes).unwrap();
|
||||
let before = device.work_counts();
|
||||
let texture = surface.texture(&buffer, 0).unwrap();
|
||||
let made = ycbcr_work(&before, &device.work_counts());
|
||||
let want = if in_place { [1, 0] } else { [0, 1] };
|
||||
assert_eq!(made[..2], want, "{what}: in place, or kept for the device");
|
||||
let size = surface.size;
|
||||
for round in 0..2 {
|
||||
let model = surface.model(&bytes);
|
||||
let before = device.work_counts();
|
||||
let centres = texels(device, &kernels.sample, (&texture, size), Some(&nearest));
|
||||
assert!(centres == model, "{what} round {round}: nearest samples");
|
||||
// Under the defaults a device that keeps the image filters it as the device does,
|
||||
// off Metal's grid: its linear samples are another row's (docs/FAST-PATHS.md).
|
||||
if exact || in_place {
|
||||
let half = texels(
|
||||
device,
|
||||
&kernels.sample_half,
|
||||
(&texture, size),
|
||||
Some(&linear),
|
||||
);
|
||||
assert!(half == model, "{what} round {round}: half linear samples");
|
||||
let between = texels(device, &kernels.between, (&texture, size), Some(&linear));
|
||||
for (i, got) in (0u64..).zip(&between) {
|
||||
let at = (i % size[0], i / size[0]);
|
||||
let want: [u16; 3] = std::array::from_fn(|c| filtered(&model, size, at, c));
|
||||
assert_eq!(*got, want, "{what} round {round}: texel {at:?}");
|
||||
}
|
||||
}
|
||||
let work = ycbcr_work(&before, &device.work_counts());
|
||||
eprintln!("YCBCR-IN-PLACE {what} round {round}: work {work:?}");
|
||||
match in_place {
|
||||
// Three dispatches, each binding the planes, none converting.
|
||||
true => assert_eq!(work[2..], [3, 0, 0], "{what} round {round}"),
|
||||
false => {
|
||||
assert_eq!(work[2], 0, "{what} round {round}: planes bound");
|
||||
assert!(work[3] >= 1, "{what} round {round}: the image's refresh");
|
||||
}
|
||||
}
|
||||
// The CPU writes new codes into the planes, which no command uses now.
|
||||
bytes = surface.bytes(seed + 100);
|
||||
let contents = buffer.contents().unwrap();
|
||||
// SAFETY: the buffer's bytes, which no command uses (each dispatch was waited for).
|
||||
unsafe {
|
||||
std::ptr::copy_nonoverlapping(bytes.as_ptr(), contents.as_ptr(), bytes.len())
|
||||
};
|
||||
}
|
||||
let before = device.work_counts();
|
||||
let read = texels(device, &kernels.read, (&texture, size), None);
|
||||
let work = ycbcr_work(&before, &device.work_counts());
|
||||
assert!(read == surface.model(&bytes), "{what}: read()");
|
||||
assert_eq!(work[2..], [0, 1, 0], "{what}: a read() converts the image");
|
||||
}
|
||||
}
|
||||
|
||||
/// Under the lane's policy (Metal's answers), a texture's samples are Metal's texels and Metal's
|
||||
/// filter of them on every device, read in place on a device whose memory is the host's
|
||||
/// ([`samples_read_the_planes`]), unannounced.
|
||||
#[test]
|
||||
fn a_ycbcr_texture_s_samples_read_its_planes_in_place_where_the_memory_is_the_host_s() {
|
||||
on_device(|device, messages| {
|
||||
samples_read_the_planes(device, true);
|
||||
let notices = counts(&messages.take_notices());
|
||||
for kind in [
|
||||
Degradation::FloatSampleFilter,
|
||||
Degradation::HalfSampleFilter,
|
||||
Degradation::YCbCrFilterNotExact,
|
||||
] {
|
||||
assert_eq!(notices.get(&kind), None, "{notices:?}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Under the runtime's defaults the device takes the same form: in place on a device whose memory
|
||||
/// is the host's, where the samples are Metal's exactly, unannounced; elsewhere the image, sampled
|
||||
/// through the device's filter under the defaults.
|
||||
#[test]
|
||||
fn a_ycbcr_texture_reads_its_planes_in_place_under_the_defaults() {
|
||||
let defaults = |options: &mut metal2vulkan_runtime::DeviceOptions| {
|
||||
options.policy = DevicePolicy::default();
|
||||
};
|
||||
on_device_with(defaults, |device, messages| {
|
||||
samples_read_the_planes(device, false);
|
||||
let notices = counts(&messages.take_notices());
|
||||
if reads_in_place(device) {
|
||||
for kind in [
|
||||
Degradation::FloatSampleFilter,
|
||||
Degradation::HalfSampleFilter,
|
||||
Degradation::YCbCrFilterNotExact,
|
||||
] {
|
||||
assert_eq!(notices.get(&kind), None, "{notices:?}");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// A texture whose planes reach past their buffer (Metal reads zeros there) and one made with a
|
||||
/// swizzle keep their image on a device whose memory is the host's, counted by the reason
|
||||
/// (`ycbcr_images_kept_reach`, `ycbcr_images_kept_swizzle`), and the first still samples Metal's
|
||||
/// texels of the bytes and zeros past them.
|
||||
#[test]
|
||||
fn a_ycbcr_texture_the_form_does_not_read_keeps_its_image() {
|
||||
on_device(|device, _| {
|
||||
if !reads_in_place(device) {
|
||||
eprintln!("{}: reads no planes in place", device.name());
|
||||
return;
|
||||
}
|
||||
let kernels = Kernels::new(device);
|
||||
let nearest = sampler(device, SamplerMinMagFilter::Nearest);
|
||||
let surface = SURFACES[0];
|
||||
let bytes = surface.bytes(7);
|
||||
// The buffer ends 100 bytes before the chroma plane's last row does.
|
||||
let short = surface.length() as usize - 100;
|
||||
let buffer = buffer_with(device, &bytes[..short]).unwrap();
|
||||
let before = device.work_counts();
|
||||
let texture = surface.texture(&buffer, 0).unwrap();
|
||||
let after = device.work_counts();
|
||||
assert_eq!(
|
||||
(
|
||||
after.ycbcr_images_kept_reach - before.ycbcr_images_kept_reach,
|
||||
after.ycbcr_textures_in_place - before.ycbcr_textures_in_place,
|
||||
),
|
||||
(1, 0),
|
||||
"planes past the buffer"
|
||||
);
|
||||
let mut zeroed = bytes.clone();
|
||||
zeroed[short..].fill(0);
|
||||
let got = texels(
|
||||
device,
|
||||
&kernels.sample,
|
||||
(&texture, surface.size),
|
||||
Some(&nearest),
|
||||
);
|
||||
assert!(got == surface.model(&zeroed), "the bytes, then zeros");
|
||||
let whole = buffer_with(device, &bytes).unwrap();
|
||||
let [w, h] = surface.size;
|
||||
let mut d = TextureDescriptor::texture_2d(surface.format, w, h, false);
|
||||
d.usage = TextureUsage::SHADER_READ;
|
||||
d.resource_options = ResourceOptions::shared();
|
||||
d.swizzle = metal2vulkan::metal::TextureSwizzleChannels {
|
||||
red: metal2vulkan::metal::TextureSwizzle::Blue,
|
||||
green: metal2vulkan::metal::TextureSwizzle::Green,
|
||||
blue: metal2vulkan::metal::TextureSwizzle::Red,
|
||||
alpha: metal2vulkan::metal::TextureSwizzle::Alpha,
|
||||
};
|
||||
let facts = IoSurfaceYCbCr::new(
|
||||
u32::from_be_bytes(surface.ostype),
|
||||
0,
|
||||
surface.size,
|
||||
surface.chroma_at,
|
||||
surface.row,
|
||||
);
|
||||
let plane = IoSurfacePlane::new(0, surface.row, true).with_ycbcr(facts);
|
||||
let before = device.work_counts();
|
||||
whole.new_texture_with_iosurface_plane(&d, plane).unwrap();
|
||||
let after = device.work_counts();
|
||||
assert_eq!(
|
||||
after.ycbcr_images_kept_swizzle - before.ycbcr_images_kept_swizzle,
|
||||
1,
|
||||
"a swizzle"
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -28,13 +28,15 @@
|
||||
//! A second `read` converts through the texture's refresh (`WorkCounts::ycbcr_refreshes`): the
|
||||
//! planes, unchanged, are compared with the staging buffer's copy, none of their bytes copied
|
||||
//! (`copy_regions_split` unchanged over [`PADDED`]'s span of 25,440,128 bytes, no multiple of
|
||||
//! 4 KiB), and it reads the first one's texels.
|
||||
//! 4 KiB), and it reads the first one's texels. On a device whose memory is the host's the bands,
|
||||
//! the grid and the draw read the planes in place (`ycbcr_in_place.rs`): they bind the planes
|
||||
//! (`WorkCounts::ycbcr_planes_bound`) and convert nothing; elsewhere they bind no planes.
|
||||
|
||||
use super::argument_linear_samples::{kernel, LINEAR_EDGE};
|
||||
use super::degrade_notices::{counts, on_device};
|
||||
use super::depth_compares::{pipeline_of, run_held, Held, Through};
|
||||
use super::pixel_downscales::RENDER;
|
||||
use super::{buffer_with, read_buffer, ycbcr_textures, WAIT};
|
||||
use super::{buffer_with, read_buffer, ycbcr_in_place, ycbcr_textures, WAIT};
|
||||
use crate::air_library::AirLibrary;
|
||||
use metal2vulkan::bind::SamplerDescriptor;
|
||||
use metal2vulkan::metal::{
|
||||
@@ -522,6 +524,10 @@ fn samples_as_metal_does(layout: Layout, what: &str) {
|
||||
made(Through::Runtime),
|
||||
made(Through::Constexpr(LINEAR_EDGE)),
|
||||
);
|
||||
// The samples and the draw read the planes in place on a device whose memory is the
|
||||
// host's, converting nothing; elsewhere the image the reads converted.
|
||||
let in_place = ycbcr_in_place::reads_in_place(device);
|
||||
let before = device.work_counts();
|
||||
for (set, jobs) in [("bandx", band(0)), ("bandy", band(1)), ("grid", grid())] {
|
||||
for (name, kernel, sampler) in [
|
||||
("sample_rt", &runtime, Some(&state)),
|
||||
@@ -546,6 +552,12 @@ fn samples_as_metal_does(layout: Layout, what: &str) {
|
||||
}
|
||||
}
|
||||
let target = draw(device, &texture, &state);
|
||||
let work = ycbcr_in_place::ycbcr_work(&before, &device.work_counts());
|
||||
eprintln!("{what}: in place {in_place}, work {work:?}");
|
||||
match in_place {
|
||||
true => assert!(work[2] >= 7 && work[3..] == [0, 0], "{what}: in place"),
|
||||
false => assert_eq!(work[2], 0, "{what}: planes bound"),
|
||||
}
|
||||
let got = hash(&target);
|
||||
let is = verdict("draw", &got);
|
||||
eprintln!("{what} draw: {is:?} hash {got}");
|
||||
|
||||
@@ -851,7 +851,7 @@ fn ycbcr_textures_read_the_texels_metal_converts() {
|
||||
|
||||
/// The fractions, in 1/256 steps, at which `sample_between` samples past each texel's centre:
|
||||
/// `(0.90625, 0.71875)` texels past its corner.
|
||||
const BETWEEN: [u32; 2] = [104, 56];
|
||||
pub(super) const BETWEEN: [u32; 2] = [104, 56];
|
||||
|
||||
/// Metal's step of a linear sample of a `YCBCR8_420_2P` texture at fractions `[a, b]` past texel
|
||||
/// `(x, y)`, from the texels' steps `read`: the taps `(x, y)` to `(x + 1, y + 1)` clamped to the
|
||||
@@ -1259,7 +1259,9 @@ const DEVICE_FILTER_BOUND: f32 = 0.5;
|
||||
/// device's filter of them), within [`DEVICE_FILTER_BOUND`] of Metal's step. On a device that
|
||||
/// samples natively the module's `device-sampling` is announced and no filter notice; on one that
|
||||
/// samples through Metal's own sampler `ycbcr-filter-not-exact`, once, naming the slot and the
|
||||
/// format, and no `device-sampling`.
|
||||
/// format, and no `device-sampling`. A device whose memory is the host's reads the planes in place
|
||||
/// instead (`ycbcr_in_place.rs`): one pipeline more, its samples Metal's step exactly, announced by
|
||||
/// no filter notice, as under the exact switch.
|
||||
#[test]
|
||||
fn a_ycbcr_slot_takes_the_devices_filter_in_the_pipeline_its_creation_made() {
|
||||
ycbcr_draws_under(YCbCrFilterPolicy::Device);
|
||||
@@ -1306,7 +1308,10 @@ fn ycbcr_draws_under(filter: YCbCrFilterPolicy) {
|
||||
.enabled()
|
||||
.properties
|
||||
.contains(&VkProperty::MetalSampler);
|
||||
let exact = filter == YCbCrFilterPolicy::Exact;
|
||||
// A device whose memory is the host's reads the planes in place, Metal's filter exactly,
|
||||
// in the slot's in-place variant under either policy.
|
||||
let in_place = super::ycbcr_in_place::reads_in_place(device);
|
||||
let exact = filter == YCbCrFilterPolicy::Exact || in_place;
|
||||
let linear = sampler(device, SamplerMinMagFilter::Linear);
|
||||
let library = device
|
||||
.new_library_with_air(&llvm_assemble_text(&fragments()).unwrap())
|
||||
@@ -1508,7 +1513,11 @@ fn a_ycbcr_sample_the_exact_filter_does_not_reach_is_announced() {
|
||||
/// naming the slot and the format, and no generic filter notice; through a constexpr sampler an
|
||||
/// anisotropic one, one with a linear mip filter and one whose filters differ announce the
|
||||
/// generic `float-sample-filter` once (the constexpr note holds whatever the slot holds, so it
|
||||
/// names no format). Each case runs on a device of its own.
|
||||
/// names no format). Each case runs on a device of its own. On a device that reads the planes in
|
||||
/// place (`ycbcr_in_place.rs`) the constexpr linear mip filter is read there, Metal's filter of the
|
||||
/// texture's one level whatever the mip filter, as a runtime sampler's is everywhere: Metal's step,
|
||||
/// with no YCbCr filter notice (the function's generic note, of its sample of any other texture,
|
||||
/// stays where the device emulates Metal's sampler).
|
||||
#[test]
|
||||
fn a_ycbcr_sample_through_an_unmeasured_filter_is_announced() {
|
||||
let anisotropic = |d: &mut SamplerDescriptor| d.max_anisotropy = 16;
|
||||
@@ -1559,7 +1568,7 @@ fn a_ycbcr_sample_through_an_unmeasured_filter_is_announced() {
|
||||
.collect();
|
||||
let source = argument_linear_samples::kernel(false, through, false, false);
|
||||
let state = pipeline_of(device, &llvm_assemble_text(&source).unwrap(), "k");
|
||||
run_held(
|
||||
let got = run_held(
|
||||
device,
|
||||
(&texture, Held::Slot, sampler.as_ref()),
|
||||
&state,
|
||||
@@ -1569,6 +1578,22 @@ fn a_ycbcr_sample_through_an_unmeasured_filter_is_announced() {
|
||||
let notices = messages.take_notices();
|
||||
let counts = counts(¬ices);
|
||||
let case = format!("{name} through {through:?}: {counts:?}");
|
||||
let in_place = super::ycbcr_in_place::reads_in_place(device);
|
||||
if in_place && name == "linear mip filter" {
|
||||
// The function's own note, of the sample it makes of any other texture, stays
|
||||
// where the device emulates Metal's sampler; no YCbCr filter is announced.
|
||||
assert_eq!(counts.get(&YCBCR_FILTERS[0]), None, "{case}");
|
||||
let model = modelled(&surface_bytes(9), YCbCrRange::Video, YCbCrMatrix::Bt601);
|
||||
for (i, texel) in (0..W * H).zip(got.as_chunks::<4>().0.iter()) {
|
||||
let at = (i % W, i / W);
|
||||
let want: [f32; 4] = std::array::from_fn(|c| match c {
|
||||
3 => 1.0,
|
||||
c => metal_step(&model, at, BETWEEN, c) as f32 / 2048.0,
|
||||
});
|
||||
assert_eq!(*texel, want, "{case}: texel {at:?}");
|
||||
}
|
||||
return;
|
||||
}
|
||||
match through {
|
||||
Through::Runtime => {
|
||||
assert_eq!(counts.get(&YCBCR_FILTERS[0]), Some(&1), "{case}");
|
||||
@@ -3339,7 +3364,9 @@ declare {{ <4 x float>, i8 }} @air.sample_texture_2d.v4f32(ptr addrspace(1), ptr
|
||||
/// texels clamped to the edge. A dispatch again of a made variant, after the texture's shadow
|
||||
/// copy, records in a `VkCommandBuffer` of its own exactly where the driver loses baked samplers
|
||||
/// after a copy (`RuntimeDriverDefect::ImmutableSamplersLostAfterCopies`: lavapipe 26.0.8 sampled
|
||||
/// it as Repeat in place).
|
||||
/// it as Repeat in place). On a device that reads the planes in place (`ycbcr_in_place.rs`) the
|
||||
/// 4:2:0 textures' variant is the in-place one, which bakes no sampler and copies no image, so it
|
||||
/// records with the rest.
|
||||
#[test]
|
||||
fn a_constexpr_sampler_takes_a_ycbcr_map_through_one_variant() {
|
||||
on_device(|device, _| {
|
||||
@@ -3451,8 +3478,11 @@ fn a_constexpr_sampler_takes_a_ycbcr_map_through_one_variant() {
|
||||
let (got, modules, pipelines, recorded_apart) = dispatched(&ten_420);
|
||||
assert_eq!(got, want[1], "YCBCR10_420_2P, again");
|
||||
assert_eq!((modules, pipelines), (0, 0), "YCBCR10_420_2P, again");
|
||||
// A variant that reads the planes in place bakes no sampler and copies no image.
|
||||
let in_place = super::ycbcr_in_place::reads_in_place(device);
|
||||
assert_eq!(
|
||||
recorded_apart, apart,
|
||||
recorded_apart,
|
||||
apart * u64::from(!in_place),
|
||||
"YCBCR10_420_2P, again: recorded apart"
|
||||
);
|
||||
let (got, modules, _, _) = dispatched(&eight_420);
|
||||
|
||||
@@ -338,7 +338,7 @@ use crate::bind::plan::slots::{
|
||||
address_map_variant, anisotropic_variant, bindings, bound_value, buffer_use, check_slots,
|
||||
check_sparse_textures, cross_variant, cubic_variant, large_view_candidates, mark_disjoint,
|
||||
plan_buffer, psb_variant, range_variant, record_specialized, snapshot_forms, srgb_twin_variant,
|
||||
srgb_variant, storage_view_variant, used_uses, ycbcr_variant,
|
||||
srgb_variant, storage_view_variant, used_uses, ycbcr_in_place_variant, ycbcr_variant,
|
||||
};
|
||||
use crate::bind::plan::{
|
||||
AccessClass, BindingPlan, BoundKind, ByteRange, DescriptorWrite, FactorSite, FactorTemplate,
|
||||
@@ -1794,6 +1794,8 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
|
||||
| PushField::Specialized(_) => {}
|
||||
// A structure's instance count, which instantiation reads from the state.
|
||||
PushField::InstanceCount(_) => {}
|
||||
// An in-place YCbCr texture's words, which instantiation reads from the state.
|
||||
PushField::YCbCrInPlace(_) => {}
|
||||
// The encoder's stencil state, which instantiation reads from the state.
|
||||
PushField::ShadowStencilState if stage == Stage::Fragment => {}
|
||||
// The encoder's depth state, which instantiation reads from the state, and its
|
||||
@@ -2556,7 +2558,8 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
|
||||
variant.cross_class = cross_variant(&p.dependencies, &p.interface.slots, shape);
|
||||
variant.srgb_textures = srgb_variant(profile, &p.dependencies, shape, &variant.cross_class);
|
||||
variant.srgb_twins = srgb_twin_variant(profile, &variant.srgb_textures, shape);
|
||||
variant.ycbcr_textures = ycbcr_variant(&p.dependencies, shape);
|
||||
variant.ycbcr_in_place = ycbcr_in_place_variant(&p.dependencies, shape);
|
||||
variant.ycbcr_textures = ycbcr_variant(&p.dependencies, shape, &variant.ycbcr_in_place);
|
||||
variant.address_maps = address_map_variant(&p.dependencies, shape);
|
||||
variant.cubic_samplers = cubic_variant(&p.dependencies, shape)?;
|
||||
variant.anisotropic_samplers = anisotropic_variant(&p.dependencies, shape);
|
||||
|
||||
@@ -34,6 +34,7 @@ fn shape(ty: TextureType, pf: PixelFormat, samples: u32, usage: TextureUsage) ->
|
||||
address_modes: crate::metal::sampler::AddressModeMap::IDENTITY,
|
||||
offset_base_axes: 0,
|
||||
own_format_views: false,
|
||||
ycbcr_in_place: false,
|
||||
texture_type: ty,
|
||||
pixel_format: pf,
|
||||
sample_count: samples,
|
||||
|
||||
@@ -787,6 +787,25 @@ pub(crate) fn slot_field(
|
||||
.map_or(0, |s| s.instance_count);
|
||||
Some(FieldBytes::of(&count.to_le_bytes()))
|
||||
}
|
||||
// The in-place planes of the texture bound at the slot, zeros where none is (the plan
|
||||
// names the slot's variant only where one is).
|
||||
PushField::YCbCrInPlace(slot) => {
|
||||
let words = match state
|
||||
.stages
|
||||
.get(&slot.stage)
|
||||
.and_then(|t| t.textures.get(&slot.index))
|
||||
{
|
||||
Some(BoundTexture::Texture { facts, .. }) => facts
|
||||
.ycbcr_in_place
|
||||
.map_or([0; crate::bind::YCbCrInPlace::WORDS], |p| p.words()),
|
||||
_ => [0; crate::bind::YCbCrInPlace::WORDS],
|
||||
};
|
||||
let mut bytes = [0u8; 4 * crate::bind::YCbCrInPlace::WORDS];
|
||||
for (chunk, word) in bytes.as_chunks_mut::<4>().0.iter_mut().zip(words) {
|
||||
chunk.copy_from_slice(&word.to_le_bytes());
|
||||
}
|
||||
Some(FieldBytes::of(&bytes))
|
||||
}
|
||||
// The level count the plan bound.
|
||||
PushField::TextureLevels(slot) => resources
|
||||
.texture_levels
|
||||
|
||||
@@ -190,6 +190,7 @@ pub(crate) mod unused_bits;
|
||||
pub(crate) mod visibility_combine;
|
||||
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_write;
|
||||
|
||||
@@ -354,5 +355,6 @@ pub use ycbcr_convert::{
|
||||
ycbcr_convert_floats_module, ycbcr_convert_module, ycbcr_read, ycbcr_texel, YCbCrCodes,
|
||||
YCbCrConversion, YCbCrConvertModule, YCbCrMatrix, YCbCrOutput, YCbCrPlanes, YCbCrRange,
|
||||
};
|
||||
pub use ycbcr_in_place::YCbCrInPlace;
|
||||
pub use ycbcr_refresh::{ycbcr_refresh_module, YCbCrRefreshModule};
|
||||
pub use ycbcr_write::{ycbcr_store, ycbcr_write, ycbcr_write_module, YCbCrWriteModule};
|
||||
@@ -624,6 +624,12 @@ pub enum WriteSource {
|
||||
image: ImageSource,
|
||||
sampler: SamplerSource,
|
||||
},
|
||||
/// The planes of the two-plane YCbCr texture bound at `slot`, read in place
|
||||
/// (`TextureFacts::ycbcr_in_place`): a uniform texel buffer over the planes' bytes in
|
||||
/// `YCbCrInPlace::format`, from the first byte of the first plane for
|
||||
/// `YCbCrInPlace::view_bytes`. Only a slot under its in-place variant binds it
|
||||
/// (`VariantKey::ycbcr_in_place`).
|
||||
YCbCrInPlace { slot: SlotRef },
|
||||
/// The texture buffer bound at `slot`, as a texel buffer view.
|
||||
TexelBuffer {
|
||||
slot: SlotRef,
|
||||
@@ -1075,6 +1081,9 @@ pub enum AccessClass {
|
||||
Index,
|
||||
Indirect,
|
||||
Attachment,
|
||||
/// A two-plane YCbCr texture's planes, read in place through the slot's uniform texel buffer
|
||||
/// (`WriteSource::YCbCrInPlace`): a read of the planes' bytes, not of the texture's image.
|
||||
YCbCrPlanes,
|
||||
}
|
||||
|
||||
/// A byte range relative to the bound offset.
|
||||
|
||||
@@ -63,7 +63,7 @@ use super::slots::{
|
||||
address_map_variant, anisotropic_variant, bindings, bound_value, buffer_use, check_slots,
|
||||
check_sparse_textures, cross_variant, cubic_variant, mark_disjoint, plan_buffer, psb_variant,
|
||||
record_specialized, srgb_twin_variant, srgb_variant, storage_view_variant, used_uses,
|
||||
ycbcr_variant,
|
||||
ycbcr_in_place_variant, ycbcr_variant,
|
||||
};
|
||||
use super::{
|
||||
BindingPlan, BoundKind, ComputeTemplate, DescriptorWrite, FieldLocation, LocalRules,
|
||||
@@ -439,6 +439,8 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result<Bindi
|
||||
| PushField::Specialized(_) => {}
|
||||
// A structure's instance count, which instantiation reads from the state.
|
||||
PushField::InstanceCount(_) => {}
|
||||
// An in-place YCbCr texture's words, which instantiation reads from the state.
|
||||
PushField::YCbCrInPlace(_) => {}
|
||||
// A stage-in buffer's bound stride, which instantiation reads from the state.
|
||||
PushField::StageInStride(_) => {}
|
||||
other => return Err(internal(format!("a compute push field {other:?}"))),
|
||||
@@ -823,7 +825,8 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result<Bindi
|
||||
&variant.cross_class,
|
||||
);
|
||||
variant.srgb_twins = srgb_twin_variant(device.profile(), &variant.srgb_textures, shape);
|
||||
variant.ycbcr_textures = ycbcr_variant(&p.dependencies, shape);
|
||||
variant.ycbcr_in_place = ycbcr_in_place_variant(&p.dependencies, shape);
|
||||
variant.ycbcr_textures = ycbcr_variant(&p.dependencies, shape, &variant.ycbcr_in_place);
|
||||
variant.address_maps = address_map_variant(&p.dependencies, shape);
|
||||
variant.cubic_samplers = cubic_variant(&p.dependencies, shape)?;
|
||||
variant.anisotropic_samplers = anisotropic_variant(&p.dependencies, shape);
|
||||
|
||||
@@ -693,6 +693,32 @@ impl ResourcePlanner<'_> {
|
||||
WriteSource::TileMap { slot }
|
||||
}
|
||||
|
||||
/// The write of `slot`'s binding under its in-place variant: the planes' texel buffer of the
|
||||
/// two-plane YCbCr texture the shape binds there (`TextureFacts::ycbcr_in_place`), a read of
|
||||
/// their bytes; the neutral texel buffer where it binds none, which the plan's choice of the
|
||||
/// variant does not leave (`slots::ycbcr_in_place_variant`).
|
||||
fn in_place_write(&mut self, slot: SlotRef) -> (WriteSource, NeutralResource) {
|
||||
let neutral = NeutralResource::TexelBuffer {
|
||||
format: vk::Format::R8G8_UINT,
|
||||
};
|
||||
match self.texture_shape(slot) {
|
||||
Some(TextureShape::Texture {
|
||||
ycbcr_in_place: true,
|
||||
..
|
||||
}) => {
|
||||
self.uses.push(ResourceUse {
|
||||
resource: UseTarget::Slot(slot),
|
||||
access: AccessSet::READ,
|
||||
class: AccessClass::YCbCrPlanes,
|
||||
stages: (self.stage_flags)(slot.stage),
|
||||
range: None,
|
||||
});
|
||||
(WriteSource::YCbCrInPlace { slot }, neutral)
|
||||
}
|
||||
_ => (WriteSource::Neutral(neutral), neutral),
|
||||
}
|
||||
}
|
||||
|
||||
fn texture_use(&mut self, slot: SlotRef, t: &TextureSlot, storage: bool) {
|
||||
self.uses.push(ResourceUse {
|
||||
resource: UseTarget::Slot(slot),
|
||||
@@ -827,6 +853,13 @@ impl ResourcePlanner<'_> {
|
||||
ty: vk::DescriptorType,
|
||||
slot: SlotRef,
|
||||
) -> Result<(WriteSource, NeutralResource), BindError> {
|
||||
// A texture slot that is no texture buffer is declared a uniform texel buffer only under
|
||||
// its in-place variant (`VariantKey::ycbcr_in_place`).
|
||||
if ty == vk::DescriptorType::UNIFORM_TEXEL_BUFFER
|
||||
&& self.texture_slot(slot)?.texture_type != TextureType::TextureBuffer
|
||||
{
|
||||
return Ok(self.in_place_write(slot));
|
||||
}
|
||||
let levels_read = self.has_fact(RuntimeFact::StorageTextureLevels { slot });
|
||||
let write = self.plain_texture(set, binding, ty, slot, false)?;
|
||||
self.write_rounding(slot, &write.0)?;
|
||||
|
||||
@@ -92,6 +92,7 @@ fn compatibility_is_type_samples_numeric_type_and_depth() {
|
||||
address_modes: crate::metal::sampler::AddressModeMap::IDENTITY,
|
||||
offset_base_axes: 0,
|
||||
own_format_views: false,
|
||||
ycbcr_in_place: false,
|
||||
texture_type,
|
||||
pixel_format,
|
||||
sample_count,
|
||||
@@ -163,6 +164,7 @@ fn a_ulong_slot_binds_only_rg32uint_textures() {
|
||||
address_modes: crate::metal::sampler::AddressModeMap::IDENTITY,
|
||||
offset_base_axes: 0,
|
||||
own_format_views: false,
|
||||
ycbcr_in_place: false,
|
||||
texture_type: TextureType::Type2D,
|
||||
pixel_format,
|
||||
sample_count: 1,
|
||||
@@ -257,6 +259,7 @@ fn a_numeric_slot_binds_either_integer_type() {
|
||||
address_modes: crate::metal::sampler::AddressModeMap::IDENTITY,
|
||||
offset_base_axes: 0,
|
||||
own_format_views: false,
|
||||
ycbcr_in_place: false,
|
||||
texture_type: TextureType::Type2D,
|
||||
pixel_format,
|
||||
sample_count: 1,
|
||||
@@ -691,6 +694,7 @@ fn an_immutable_linear_sampler_needs_a_filterable_view() {
|
||||
address_modes: crate::metal::sampler::AddressModeMap::IDENTITY,
|
||||
offset_base_axes: 0,
|
||||
own_format_views: false,
|
||||
ycbcr_in_place: false,
|
||||
texture_type: TextureType::Type2D,
|
||||
pixel_format: pf,
|
||||
sample_count: 1,
|
||||
@@ -792,6 +796,7 @@ fn a_linear_compare_sampler_needs_no_filterable_view() {
|
||||
address_modes: crate::metal::sampler::AddressModeMap::IDENTITY,
|
||||
offset_base_axes: 0,
|
||||
own_format_views: false,
|
||||
ycbcr_in_place: false,
|
||||
texture_type: TextureType::Type2D,
|
||||
pixel_format: pf,
|
||||
sample_count: 1,
|
||||
@@ -887,6 +892,7 @@ fn bicubic_texels_follow_the_bound_format() {
|
||||
address_modes: crate::metal::sampler::AddressModeMap::IDENTITY,
|
||||
offset_base_axes: 0,
|
||||
own_format_views: false,
|
||||
ycbcr_in_place: false,
|
||||
texture_type: TextureType::Type2D,
|
||||
pixel_format: pf,
|
||||
sample_count: 1,
|
||||
@@ -982,6 +988,7 @@ fn an_explicit_cube_gradient_binding_takes_an_anisotropic_sampler_isotropically(
|
||||
address_modes: crate::metal::sampler::AddressModeMap::IDENTITY,
|
||||
offset_base_axes: 0,
|
||||
own_format_views: false,
|
||||
ycbcr_in_place: false,
|
||||
texture_type: TextureType::Cube,
|
||||
pixel_format: PixelFormat::RGBA8Unorm,
|
||||
sample_count: 1,
|
||||
@@ -1191,6 +1198,7 @@ fn texel_format_follows_the_bound_format() {
|
||||
address_modes: crate::metal::sampler::AddressModeMap::IDENTITY,
|
||||
offset_base_axes: 0,
|
||||
own_format_views: false,
|
||||
ycbcr_in_place: false,
|
||||
texture_type: TextureType::Type2D,
|
||||
pixel_format,
|
||||
sample_count: 1,
|
||||
@@ -1375,6 +1383,7 @@ fn a_separate_pair_takes_the_combined_pairs_checks() {
|
||||
address_modes: crate::metal::sampler::AddressModeMap::IDENTITY,
|
||||
offset_base_axes: 0,
|
||||
own_format_views: false,
|
||||
ycbcr_in_place: false,
|
||||
texture_type: TextureType::Type2D,
|
||||
pixel_format: pf,
|
||||
sample_count: 1,
|
||||
|
||||
@@ -435,16 +435,19 @@ pub(crate) fn cross_variant(
|
||||
/// YCbCr format, on a profile that takes the variant (`RuntimeFact::YCbCrTexture`,
|
||||
/// `ProfileFields::ycbcr_variant`), at which `shape` binds a texture of a two-plane YCbCr format
|
||||
/// (`metal::format::ycbcr_format`), whose view Metal's sampler filters as the view's format, not as
|
||||
/// Metal's filter of the YCbCr format: the plan's `VariantKey::ycbcr_textures`. The variant's
|
||||
/// Metal's filter of the YCbCr format: the plan's `VariantKey::ycbcr_textures`. A slot whose
|
||||
/// planes the function reads in place (`in_place`, [`ycbcr_in_place_variant`]) reads no image
|
||||
/// there, and its in-place variant's compile states no such fact, so it is not one. The variant's
|
||||
/// compile states the same facts, so its plan for the same shape states the same key.
|
||||
pub(crate) fn ycbcr_variant(
|
||||
dependencies: &[RuntimeDependency],
|
||||
shape: &BindShape,
|
||||
in_place: &std::collections::BTreeSet<SlotRef>,
|
||||
) -> std::collections::BTreeSet<SlotRef> {
|
||||
dependencies
|
||||
.iter()
|
||||
.filter_map(|d| match d.fact {
|
||||
RuntimeFact::YCbCrTexture { slot } => Some(slot),
|
||||
RuntimeFact::YCbCrTexture { slot } if !in_place.contains(&slot) => Some(slot),
|
||||
_ => None,
|
||||
})
|
||||
.filter(|slot| {
|
||||
@@ -454,6 +457,59 @@ pub(crate) fn ycbcr_variant(
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The texture slots whose function reads a two-plane YCbCr texture only as its in-place form
|
||||
/// reads it (`RuntimeFact::YCbCrInPlace`) at which `shape` binds a texture whose planes are read
|
||||
/// in place (`TextureShape::Texture::ycbcr_in_place`), and each runtime sampler the function
|
||||
/// samples the slot through states a filter the form reads ([`in_place_word`]): the plan's
|
||||
/// `VariantKey::ycbcr_in_place`. Any other slot binds the texture's image. The variant's compile
|
||||
/// states the same facts, so its plan for the same shape states the same key.
|
||||
pub(crate) fn ycbcr_in_place_variant(
|
||||
dependencies: &[RuntimeDependency],
|
||||
shape: &BindShape,
|
||||
) -> std::collections::BTreeSet<SlotRef> {
|
||||
dependencies
|
||||
.iter()
|
||||
.filter_map(|d| match d.fact {
|
||||
RuntimeFact::YCbCrInPlace { slot, samplers } => Some((slot, samplers)),
|
||||
_ => None,
|
||||
})
|
||||
.filter(|&(slot, samplers)| {
|
||||
let in_place = matches!(
|
||||
bound_texture(shape, slot),
|
||||
Some(TextureShape::Texture {
|
||||
ycbcr_in_place: true,
|
||||
..
|
||||
})
|
||||
);
|
||||
let stage = shape.stages.get(&slot.stage);
|
||||
let words = (0..32).filter(|n| samplers >> n & 1 != 0).map(|n| {
|
||||
stage
|
||||
.and_then(|s| s.samplers.get(&n))
|
||||
.map_or(0, |s| s.word.0)
|
||||
});
|
||||
in_place && words.into_iter().all(in_place_word)
|
||||
})
|
||||
.map(|(slot, _)| slot)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether a runtime sampler of word `word` samples a two-plane YCbCr texture in a way its
|
||||
/// in-place form reads: one filter for minification and magnification (nearest or linear), no
|
||||
/// anisotropy, no cubic filter, no comparison and the weighted-average reduction. Its mip filter
|
||||
/// and level clamps read the texture's one level, as Metal's sample of it reads it whatever its
|
||||
/// mip filter (`lower::sampler::in_place`); every address mode, border color and coordinate
|
||||
/// space is the form's to address. An unbound slot's word is 0, a nearest sampler's.
|
||||
pub(crate) fn in_place_word(word: u32) -> bool {
|
||||
use crate::metal::sampler::SamplerWord;
|
||||
let filter = word & (SamplerWord::MIN_LINEAR | SamplerWord::MAG_LINEAR);
|
||||
let one_filter = filter == 0 || filter == SamplerWord::LINEAR;
|
||||
let other = SamplerWord::CUBIC
|
||||
| SamplerWord::ANISOTROPIC
|
||||
| SamplerWord::COMPARE
|
||||
| SamplerWord::REDUCTION;
|
||||
one_filter && word & other == 0
|
||||
}
|
||||
|
||||
/// The texture slots a constexpr sampler samples (`RuntimeFact::ConstexprSampled`) at which
|
||||
/// `shape` binds a texture whose address-mode map changes a mode the slot's constexpr samplers
|
||||
/// state, each with that map restricted to those modes (every other mode to itself): the plan's
|
||||
|
||||
@@ -738,6 +738,115 @@ fn only_a_map_that_moves_a_constexpr_mode_enters_the_variant() {
|
||||
assert!(address_map_variant(&repeat, &BindShape::default()).is_empty());
|
||||
}
|
||||
|
||||
/// A slot that states the in-place form enters `VariantKey::ycbcr_in_place` only where the bound
|
||||
/// texture's planes are read in place and each runtime sampler the slot samples through states a
|
||||
/// filter the form reads: one filter, no anisotropy, cubic filter, comparison or other reduction.
|
||||
/// Such a slot leaves `VariantKey::ycbcr_textures`, whose image it no longer reads.
|
||||
#[test]
|
||||
fn the_in_place_variant_takes_a_slot_its_texture_and_samplers_read() {
|
||||
use crate::bind::state::{BoundSampler, SamplerDescriptor, TextureFacts};
|
||||
use crate::bind::ycbcr_convert::{YCbCrCodes, YCbCrMatrix, YCbCrPlanes, YCbCrRange};
|
||||
use crate::bind::YCbCrInPlace;
|
||||
use metal::{CompareFunction, SamplerMinMagFilter as F, SamplerReductionMode};
|
||||
let texture = |index| SlotRef {
|
||||
stage: Stage::Kernel,
|
||||
class: SlotClass::Texture,
|
||||
index,
|
||||
};
|
||||
let pf = metal::PixelFormat::YCBCR84202P;
|
||||
let codes = metal::format::ycbcr_format(pf)
|
||||
.and_then(YCbCrCodes::of)
|
||||
.expect("codes");
|
||||
let planes = YCbCrPlanes::new(
|
||||
[8, 4],
|
||||
[0, 16],
|
||||
[64, 16],
|
||||
(YCbCrRange::Video, YCbCrMatrix::Bt709),
|
||||
codes,
|
||||
);
|
||||
// Slot 0 and 1 bind textures whose planes are read in place, slot 2 one whose are not.
|
||||
let shape = |sampler: SamplerDescriptor| {
|
||||
let mut stage = StageShape::default();
|
||||
for (index, in_place) in [(0, true), (1, true), (2, false)] {
|
||||
let mut facts = TextureFacts::new(metal::TextureType::Type2D, pf);
|
||||
if in_place {
|
||||
facts.ycbcr_in_place = YCbCrInPlace::of(&planes);
|
||||
}
|
||||
stage.textures.insert(index, facts.shape());
|
||||
}
|
||||
stage.samplers.insert(3, BoundSampler::new(sampler).shape());
|
||||
let mut s = BindShape::default();
|
||||
s.stages.insert(Stage::Kernel, stage);
|
||||
s
|
||||
};
|
||||
let fact = |slot, samplers| RuntimeDependency {
|
||||
fact: RuntimeFact::YCbCrInPlace { slot, samplers },
|
||||
mechanism: Mechanism::Variant,
|
||||
};
|
||||
let image = |slot| RuntimeDependency {
|
||||
fact: RuntimeFact::YCbCrTexture { slot },
|
||||
mechanism: Mechanism::Variant,
|
||||
};
|
||||
// Slot 0 samples through constexpr samplers alone, slot 1 also through `[[sampler(3)]]`.
|
||||
let deps = [
|
||||
fact(texture(0), 0),
|
||||
fact(texture(1), 1 << 3),
|
||||
fact(texture(2), 0),
|
||||
image(texture(0)),
|
||||
image(texture(2)),
|
||||
];
|
||||
let linear = SamplerDescriptor {
|
||||
min_filter: F::Linear,
|
||||
mag_filter: F::Linear,
|
||||
..SamplerDescriptor::new()
|
||||
};
|
||||
let both = std::collections::BTreeSet::from([texture(0), texture(1)]);
|
||||
let s = shape(linear);
|
||||
let in_place = ycbcr_in_place_variant(&deps, &s);
|
||||
assert_eq!(in_place, both);
|
||||
assert_eq!(
|
||||
ycbcr_variant(&deps, &s, &in_place),
|
||||
std::collections::BTreeSet::from([texture(2)])
|
||||
);
|
||||
assert_eq!(
|
||||
ycbcr_in_place_variant(&deps, &shape(SamplerDescriptor::new())),
|
||||
both
|
||||
);
|
||||
// A sampler the form does not read keeps slot 1 from it, not slot 0.
|
||||
let unread = [
|
||||
SamplerDescriptor {
|
||||
min_filter: F::Linear,
|
||||
..SamplerDescriptor::new()
|
||||
},
|
||||
SamplerDescriptor {
|
||||
max_anisotropy: 4,
|
||||
..linear
|
||||
},
|
||||
SamplerDescriptor {
|
||||
min_filter: F::Cubic,
|
||||
mag_filter: F::Cubic,
|
||||
..SamplerDescriptor::new()
|
||||
},
|
||||
SamplerDescriptor {
|
||||
compare_function: CompareFunction::Less,
|
||||
..linear
|
||||
},
|
||||
SamplerDescriptor {
|
||||
reduction_mode: SamplerReductionMode::Minimum,
|
||||
..linear
|
||||
},
|
||||
];
|
||||
for sampler in unread {
|
||||
assert_eq!(
|
||||
ycbcr_in_place_variant(&deps, &shape(sampler)),
|
||||
std::collections::BTreeSet::from([texture(0)]),
|
||||
"{sampler:?}"
|
||||
);
|
||||
}
|
||||
// A slot that states no form takes none, whatever its texture.
|
||||
assert!(ycbcr_in_place_variant(&[image(texture(0))], &s).is_empty());
|
||||
}
|
||||
|
||||
/// A stage's dropped-store word reaches the shape over the slots it binds a buffer at, and is
|
||||
/// what `SpecKey::DroppedStoreSlots` takes there: a bit of a slot the state binds nothing at names
|
||||
/// nothing a store can reach, so the shape leaves it out and one set of bindings keeps one shape
|
||||
|
||||
@@ -1169,8 +1169,10 @@ impl TextureFacts {
|
||||
/// The facts of an image texture that can change a plan (its view facts): the type, the pixel
|
||||
/// format, the sample count, the usage, whether it is sparse, its level count, which decides a
|
||||
/// storage slot's level views and pushed level count, whether it is held with a depth twin, its
|
||||
/// swizzle, its address-mode map, and its [`offset_base_axes`](Self::offset_base_axes). Its
|
||||
/// array length only changes the view's subresource range, which is every layer.
|
||||
/// swizzle, its address-mode map, its [`offset_base_axes`](Self::offset_base_axes), and
|
||||
/// whether its planes are read in place ([`ycbcr_in_place`](Self::ycbcr_in_place), whose
|
||||
/// words the slot's push field carries, not the shape). Its array length only changes the
|
||||
/// view's subresource range, which is every layer.
|
||||
///
|
||||
/// The level count is stated whatever the usage: plain Metal writes a texture made without
|
||||
/// `ShaderWrite` at every level, through every write form, as one made with it.
|
||||
@@ -1190,6 +1192,7 @@ impl TextureFacts {
|
||||
address_modes: self.address_modes,
|
||||
offset_base_axes: self.offset_base_axes(),
|
||||
own_format_views: self.own_format_views,
|
||||
ycbcr_in_place: self.ycbcr_in_place.is_some(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1421,6 +1424,16 @@ pub struct TextureFacts {
|
||||
/// (`StorageImageClass::HalfBits`) the image cannot take.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub own_format_views: bool,
|
||||
/// The texture's two planes, where a function reads them in place
|
||||
/// ([`YCbCrInPlace`](crate::bind::YCbCrInPlace), the runtime's extension): a two-plane YCbCr
|
||||
/// texture of a converted 4:2:0 format whose planes the consumer views as one texel buffer.
|
||||
/// A slot whose function reads it only as the in-place form reads
|
||||
/// (`RuntimeFact::YCbCrInPlace`) takes its in-place variant (`VariantKey::ycbcr_in_place`),
|
||||
/// which binds that texel buffer ([`WriteSource::YCbCrInPlace`](crate::bind::WriteSource))
|
||||
/// and pushes these words (`PushField::YCbCrInPlace`); any other slot binds the texture's
|
||||
/// image. `None` for every other texture.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub ycbcr_in_place: Option<crate::bind::YCbCrInPlace>,
|
||||
}
|
||||
|
||||
impl TextureFacts {
|
||||
@@ -1440,6 +1453,7 @@ impl TextureFacts {
|
||||
parent_relative_level: 0,
|
||||
parent_base_size: [0; 3],
|
||||
own_format_views: false,
|
||||
ycbcr_in_place: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2056,6 +2070,11 @@ pub enum TextureShape {
|
||||
/// another choice serves.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
own_format_views: bool,
|
||||
/// The texture's planes are read in place where a slot's function reads them so
|
||||
/// ([`TextureFacts::ycbcr_in_place`]): such a slot takes its in-place variant
|
||||
/// (`VariantKey::ycbcr_in_place`).
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
ycbcr_in_place: bool,
|
||||
},
|
||||
Buffer {
|
||||
pixel_format: metal::PixelFormat,
|
||||
|
||||
@@ -337,7 +337,7 @@ pub(crate) fn conversions() -> Vec<YCbCrConversion> {
|
||||
|
||||
/// The `(kb, kr)` of red, green and blue for `range` and `matrix`, in the units of the module
|
||||
/// docs' conversion (measured, the module docs).
|
||||
fn coefficients(range: YCbCrRange, matrix: YCbCrMatrix) -> [(i32, i32); 3] {
|
||||
pub(crate) fn coefficients(range: YCbCrRange, matrix: YCbCrMatrix) -> [(i32, i32); 3] {
|
||||
match (range, matrix) {
|
||||
(YCbCrRange::Video, YCbCrMatrix::Bt601) => [(-9, 13123), (-3218, -6686), (16591, 9)],
|
||||
(YCbCrRange::Video, YCbCrMatrix::Bt709) => [(-1, 14743), (-1753, -4383), (17373, 1)],
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
//! A two-plane YCbCr texture's planes read in place: a function reads the codes from the planes'
|
||||
//! own bytes and converts each texel as Metal does, where the texture's image of converted texels
|
||||
//! (`ycbcr_convert`) would otherwise stand between them.
|
||||
//!
|
||||
//! **What it covers.** `YCBCR8_420_2P` and `YCBCR10_420_2P` (500 and 505) over a surface's two
|
||||
//! planes, read converted ([`YCbCrOutput::Converted`]): the 4:2:0 layouts of unpacked codes, a
|
||||
//! byte or the high 10 bits of a little-endian 16-bit word. A texture whose planes are those
|
||||
//! ([`YCbCrInPlace::of`]) states it in its facts (`TextureFacts::ycbcr_in_place`), and a texture
|
||||
//! slot whose function reads it only as the in-place form reads
|
||||
//! (`RuntimeFact::YCbCrInPlace`) takes the slot's in-place variant (`VariantKey::ycbcr_in_place`).
|
||||
//!
|
||||
//! **The binding.** The slot's one descriptor is a uniform texel buffer over the planes' bytes,
|
||||
//! from the first byte of the first plane in memory, in [`YCbCrInPlace::format`]: `R8G8_UINT`
|
||||
//! for 8-bit codes and `R16G16_UINT` for 10-bit ones, so one element holds two luma codes or one
|
||||
//! chroma pair. Vulkan requires `VK_FORMAT_FEATURE_UNIFORM_TEXEL_BUFFER_BIT` of both formats on
|
||||
//! every device (the specification's "Required Format Support": `R8G8_UINT` in "1-3 Byte-Sized
|
||||
//! Components", `R16G16_UINT` in "16-bit Components"). The texture's size, its planes' places
|
||||
//! and rows in elements, and its conversion are the slot's push field
|
||||
//! (`PushField::YCbCrInPlace`, [`YCbCrInPlace::words`]).
|
||||
//!
|
||||
//! **What a function reads** is Metal's texel (`ycbcr_convert`'s module docs): the luma code at
|
||||
//! the texel's place, the four nearest chroma pairs weighted 9/3/3/1 and rounded to a code, and
|
||||
//! the conversion of the surface's range and matrix, each channel a step of `1 / 2048`, alpha 1.
|
||||
//! A sample is Metal's filter of those texels on that grid (`lower::sampler::in_place`), exact,
|
||||
//! as the image's emulated filter is.
|
||||
|
||||
use super::ycbcr_convert::{YCbCrMatrix, YCbCrOutput, YCbCrPlanes, YCbCrRange};
|
||||
use crate::metal::format::ChromaSubsampling;
|
||||
use crate::vk;
|
||||
|
||||
/// A two-plane YCbCr texture's planes as a function reads them in place, where the texture's image
|
||||
/// of converted texels would otherwise stand between them: the words of its slot's push field
|
||||
/// (`PushField::YCbCrInPlace`), and the uniform texel buffer the slot binds over the planes' bytes
|
||||
/// ([`format`](Self::format), from the first byte of the first plane for
|
||||
/// [`view_bytes`](Self::view_bytes)). A texture states one in its facts
|
||||
/// (`TextureFacts::ycbcr_in_place`), and a slot whose function reads the texture only as this form
|
||||
/// does (`RuntimeFact::YCbCrInPlace`) takes the in-place variant (`VariantKey::ycbcr_in_place`),
|
||||
/// which fetches the codes and converts and filters them as Metal does: the luma code at the
|
||||
/// texel's place, the four nearest chroma pairs weighted 9/3/3/1 and rounded to a code, the
|
||||
/// surface's range and matrix, each channel a step of `1 / 2048`, alpha 1. Vulkan requires
|
||||
/// `VK_FORMAT_FEATURE_UNIFORM_TEXEL_BUFFER_BIT` of both formats on every device.
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct YCbCrInPlace {
|
||||
words: [u32; YCbCrInPlace::WORDS],
|
||||
/// The bytes the texel buffer views, from the planes' first byte: the end of the last row of
|
||||
/// codes either plane holds, rounded up to a whole element.
|
||||
bytes: u64,
|
||||
}
|
||||
|
||||
impl YCbCrInPlace {
|
||||
/// The words of the slot's push field ([`words`](Self::words)), two `uvec4`s.
|
||||
pub const WORDS: usize = 8;
|
||||
/// Word: the texture's width in texels.
|
||||
pub const WIDTH: usize = 0;
|
||||
/// Word: the texture's height in texels.
|
||||
pub const HEIGHT: usize = 1;
|
||||
/// Word: the luma plane's first element in the texel buffer.
|
||||
pub const LUMA_AT: usize = 2;
|
||||
/// Word: the elements from one luma row to the next.
|
||||
pub const LUMA_ROW: usize = 3;
|
||||
/// Word: the chroma plane's first element in the texel buffer.
|
||||
pub const CHROMA_AT: usize = 4;
|
||||
/// Word: the elements from one chroma row to the next.
|
||||
pub const CHROMA_ROW: usize = 5;
|
||||
/// Word: the conversion: the codes' bits in bits 0 to 7, full range in bit 8, and the matrix
|
||||
/// in bits 9 and 10 (0 BT.601, 1 BT.709, 2 BT.2020).
|
||||
pub const CONVERSION: usize = 6;
|
||||
|
||||
/// The in-place form of `planes`, where a function reads them so: a
|
||||
/// converted 4:2:0 layout of unpacked 8- or 10-bit codes, both planes in the bytes (a chroma
|
||||
/// plane of rows; not the conversion's row of zeros), each plane's first byte and rows a
|
||||
/// multiple of an element. `None` for any other: such a texture keeps its image of converted
|
||||
/// texels alone.
|
||||
pub fn of(planes: &YCbCrPlanes) -> Option<YCbCrInPlace> {
|
||||
let codes = planes.codes;
|
||||
if codes.output != YCbCrOutput::Converted
|
||||
|| codes.subsampling != ChromaSubsampling::Chroma420
|
||||
|| codes.packed
|
||||
|| !matches!((codes.bits, codes.bytes), (8, 1) | (10, 2))
|
||||
|| planes.chroma[1] == 0
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let element = 2 * codes.bytes;
|
||||
let [luma_at, luma_row] = planes.luma;
|
||||
let [chroma_at, chroma_row] = planes.chroma;
|
||||
if [luma_at, luma_row, chroma_at, chroma_row]
|
||||
.iter()
|
||||
.any(|v| v % element != 0)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let [w, h] = planes.size;
|
||||
if w == 0 || h == 0 {
|
||||
return None;
|
||||
}
|
||||
let [cw, ch] = planes.chroma_size().map(u64::from);
|
||||
let unit = u64::from(codes.bytes);
|
||||
let end = |at: u32, row: u32, rows: u64, bytes: u64| {
|
||||
u64::from(at) + u64::from(row) * (rows - 1) + bytes
|
||||
};
|
||||
let reach = end(luma_at, luma_row, u64::from(h), unit * u64::from(w)).max(end(
|
||||
chroma_at,
|
||||
chroma_row,
|
||||
ch,
|
||||
unit * 2 * cw,
|
||||
));
|
||||
let bytes = reach.next_multiple_of(u64::from(element));
|
||||
let mut words = [0; Self::WORDS];
|
||||
words[Self::WIDTH] = w;
|
||||
words[Self::HEIGHT] = h;
|
||||
words[Self::LUMA_AT] = luma_at / element;
|
||||
words[Self::LUMA_ROW] = luma_row / element;
|
||||
words[Self::CHROMA_AT] = chroma_at / element;
|
||||
words[Self::CHROMA_ROW] = chroma_row / element;
|
||||
words[Self::CONVERSION] = conversion_word(codes.bits, planes.range, planes.matrix);
|
||||
Some(YCbCrInPlace { words, bytes })
|
||||
}
|
||||
|
||||
/// The words of the slot's push field.
|
||||
pub fn words(&self) -> [u32; Self::WORDS] {
|
||||
self.words
|
||||
}
|
||||
|
||||
/// The codes' bits: 8 or 10.
|
||||
pub fn bits(&self) -> u32 {
|
||||
self.words[Self::CONVERSION] & 0xff
|
||||
}
|
||||
|
||||
/// The texel buffer's format: `R8G8_UINT` of 8-bit codes, `R16G16_UINT` of 10-bit ones.
|
||||
pub fn format(&self) -> vk::Format {
|
||||
match self.bits() {
|
||||
8 => vk::Format::R8G8_UINT,
|
||||
_ => vk::Format::R16G16_UINT,
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes of one element of the texel buffer: 2 of 8-bit codes, 4 of 10-bit ones.
|
||||
pub fn element_bytes(&self) -> u64 {
|
||||
match self.bits() {
|
||||
8 => 2,
|
||||
_ => 4,
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes the texel buffer views from the planes' first byte: through the last row of
|
||||
/// codes either plane holds, a whole number of elements.
|
||||
pub fn view_bytes(&self) -> u64 {
|
||||
self.bytes
|
||||
}
|
||||
|
||||
/// The elements the texel buffer holds (`maxTexelBufferElements` bounds them).
|
||||
pub fn elements(&self) -> u64 {
|
||||
self.bytes / self.element_bytes()
|
||||
}
|
||||
}
|
||||
|
||||
/// The conversion word ([`YCbCrInPlace::CONVERSION`]) of `bits`-bit codes of `range` and
|
||||
/// `matrix`.
|
||||
fn conversion_word(bits: u32, range: YCbCrRange, matrix: YCbCrMatrix) -> u32 {
|
||||
let full = match range {
|
||||
YCbCrRange::Video => 0,
|
||||
YCbCrRange::Full => 1,
|
||||
};
|
||||
let m = match matrix {
|
||||
YCbCrMatrix::Bt601 => 0,
|
||||
YCbCrMatrix::Bt709 => 1,
|
||||
YCbCrMatrix::Bt2020 => 2,
|
||||
};
|
||||
bits | full << 8 | m << 9
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::bind::ycbcr_convert::YCbCrCodes;
|
||||
use crate::metal::format::ycbcr_format;
|
||||
use crate::metal::PixelFormat;
|
||||
|
||||
fn planes(pf: PixelFormat, luma: [u32; 2], chroma: [u32; 2]) -> YCbCrPlanes {
|
||||
let codes = ycbcr_format(pf).and_then(YCbCrCodes::of).expect("codes");
|
||||
YCbCrPlanes::new(
|
||||
[7, 5],
|
||||
luma,
|
||||
chroma,
|
||||
(YCbCrRange::Full, YCbCrMatrix::Bt709),
|
||||
codes,
|
||||
)
|
||||
}
|
||||
|
||||
/// The two converted 4:2:0 formats take the form, in elements of their own width; every
|
||||
/// other layout keeps its image.
|
||||
#[test]
|
||||
fn only_converted_four_two_zero_codes_read_in_place() {
|
||||
let p8 =
|
||||
YCbCrInPlace::of(&planes(PixelFormat::YCBCR84202P, [0, 16], [96, 16])).expect("8-bit");
|
||||
assert_eq!(p8.format(), vk::Format::R8G8_UINT);
|
||||
assert_eq!(
|
||||
p8.words(),
|
||||
[
|
||||
7,
|
||||
5,
|
||||
0,
|
||||
8,
|
||||
48,
|
||||
8,
|
||||
conversion_word(8, YCbCrRange::Full, YCbCrMatrix::Bt709),
|
||||
0
|
||||
]
|
||||
);
|
||||
// The chroma plane's last row (3 rows of 4 pairs) ends at 96 + 32 + 8.
|
||||
assert_eq!(p8.view_bytes(), 136);
|
||||
assert_eq!(p8.elements(), 68);
|
||||
let p10 = YCbCrInPlace::of(&planes(PixelFormat::YCBCR104202P, [0, 16], [96, 32]))
|
||||
.expect("10-bit");
|
||||
assert_eq!(p10.format(), vk::Format::R16G16_UINT);
|
||||
assert_eq!(p10.words()[YCbCrInPlace::LUMA_ROW], 4);
|
||||
assert_eq!(p10.words()[YCbCrInPlace::CHROMA_AT], 24);
|
||||
assert_eq!(p10.bits(), 10);
|
||||
// The luma plane ends the bytes: its last row's seven codes round up to a whole element.
|
||||
let tail = YCbCrInPlace::of(&planes(PixelFormat::YCBCR84202P, [64, 16], [0, 16]))
|
||||
.expect("chroma first");
|
||||
assert_eq!(tail.view_bytes(), 64 + 4 * 16 + 8);
|
||||
for pf in [
|
||||
PixelFormat::YCBCR84222P,
|
||||
PixelFormat::YCBCR84442P,
|
||||
PixelFormat::YCBCR84202PSRGB,
|
||||
PixelFormat::RGB84202P,
|
||||
PixelFormat::YCBCR104202PPACKED,
|
||||
] {
|
||||
assert_eq!(
|
||||
YCbCrInPlace::of(&planes(pf, [0, 16], [96, 16])),
|
||||
None,
|
||||
"{pf:?}"
|
||||
);
|
||||
}
|
||||
// The conversion's row of zeros is no chroma plane.
|
||||
let zero = planes(PixelFormat::YCBCR84202P, [0, 16], [96, 0]);
|
||||
assert_eq!(YCbCrInPlace::of(&zero), None);
|
||||
}
|
||||
}
|
||||
+2
@@ -896,6 +896,7 @@ codec_enum! {
|
||||
TessellationChunk,
|
||||
MergedDrawAddress,
|
||||
AlphaTestReference,
|
||||
YCbCrInPlace(f0),
|
||||
}
|
||||
Symbol { Binding(f0), DescriptorSet(f0), Location(f0), Component(f0), SpecId(f0) }
|
||||
}
|
||||
@@ -1293,6 +1294,7 @@ codec_enum! {
|
||||
MergedDraws,
|
||||
QuadPrimitiveIds,
|
||||
PrivateList,
|
||||
YCbCrInPlace { slot, samplers },
|
||||
}
|
||||
UniformViewChoice { Viewed, Spare, Kept }
|
||||
Mechanism {
|
||||
|
||||
Vendored
+16
-2
@@ -60,7 +60,7 @@ mod tests;
|
||||
/// unchanged version, and its bless records the version. Independent of the crate's version and of
|
||||
/// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no
|
||||
/// history.
|
||||
pub const SEMANTICS_VERSION: u32 = 1867;
|
||||
pub const SEMANTICS_VERSION: u32 = 1868;
|
||||
|
||||
/// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the
|
||||
/// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another
|
||||
@@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 451;
|
||||
/// 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 = 1648;
|
||||
pub const RUNTIME_VERSION: u32 = 1649;
|
||||
|
||||
/// 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
|
||||
@@ -215,6 +215,13 @@ pub struct VariantKey {
|
||||
/// (`metal::format::ycbcr_format`). The plan of a pipeline compiled under it states it.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub ycbcr_textures: BTreeSet<SlotRef>,
|
||||
/// Texture slots whose function reads the two-plane YCbCr texture the shape binds there in
|
||||
/// place: every slot of a `RuntimeFact::YCbCrInPlace` the shape binds a texture whose planes
|
||||
/// are read so (`TextureShape::Texture::ycbcr_in_place`). Each such slot binds the planes'
|
||||
/// texel buffer alone, and its accesses read the codes and convert them as Metal does
|
||||
/// (`bind::YCbCrInPlace`). The plan of a pipeline compiled under it states it.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub ycbcr_in_place: BTreeSet<SlotRef>,
|
||||
/// Texture slots a constexpr sampler samples, each with the address-mode map of the texture
|
||||
/// the shape binds there where it is not the identity: every slot of a
|
||||
/// `RuntimeFact::ConstexprSampled` the shape binds such a texture at. The function's constexpr
|
||||
@@ -554,6 +561,7 @@ impl VariantKey {
|
||||
&& self.srgb_twins.is_empty()
|
||||
&& self.snapshot_textures.is_empty()
|
||||
&& self.ycbcr_textures.is_empty()
|
||||
&& self.ycbcr_in_place.is_empty()
|
||||
&& self.address_maps.is_empty()
|
||||
&& !self.flat_grid
|
||||
&& !self.replay_bindings
|
||||
@@ -675,6 +683,12 @@ impl VariantKey {
|
||||
.filter(|s| s.stage == stage)
|
||||
.copied()
|
||||
.collect();
|
||||
out.ycbcr_in_place = self
|
||||
.ycbcr_in_place
|
||||
.iter()
|
||||
.filter(|s| s.stage == stage)
|
||||
.copied()
|
||||
.collect();
|
||||
out.address_maps = self
|
||||
.address_maps
|
||||
.iter()
|
||||
|
||||
@@ -412,6 +412,12 @@ fn derive_fields(
|
||||
&& policy.ycbcr_filter == YCbCrFilterPolicy::Exact
|
||||
}
|
||||
},
|
||||
// The planes of a two-plane YCbCr texture read in place where the GPU reads host memory
|
||||
// with no bus between: an integrated GPU's, a CPU device's.
|
||||
ycbcr_in_place: matches!(
|
||||
desc.device_type,
|
||||
Some(vk::PhysicalDeviceType::INTEGRATED_GPU | vk::PhysicalDeviceType::CPU)
|
||||
),
|
||||
// Metal's picks where the device's minimum and maximum are measured to be Metal's or its
|
||||
// functions are Metal's own; elsewhere the device's where the policy takes them.
|
||||
min_max: if deviates(DriverDeviation::MetalMinMax)
|
||||
|
||||
@@ -188,6 +188,9 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism {
|
||||
RuntimeFact::MergedDraws => Mechanism::Variant,
|
||||
RuntimeFact::QuadPrimitiveIds => Mechanism::Variant,
|
||||
RuntimeFact::PrivateList => Mechanism::Variant,
|
||||
// Keyed by the slots bound to a texture whose planes are read in place, on a profile that
|
||||
// reads them so (`ProfileFields::ycbcr_in_place`).
|
||||
RuntimeFact::YCbCrInPlace { .. } => Mechanism::Variant,
|
||||
// The function marks the `ExecutionStatus` buffer its `ExecutionStatus` fact binds; the
|
||||
// consumer reads the bit after the command buffer.
|
||||
RuntimeFact::AbsentArgumentRead { .. } => Mechanism::None,
|
||||
|
||||
@@ -204,6 +204,15 @@ impl DeviceProfile {
|
||||
crate::memory::contain::device_drops_texel_writes(self, texel_buffer)
|
||||
}
|
||||
|
||||
/// Whether a function reads a two-plane YCbCr texture's planes in place where its slot reads
|
||||
/// the texture only so (`bind::YCbCrInPlace`): on an integrated GPU or a CPU device, which
|
||||
/// reads host memory with no bus between; elsewhere every such texture's image of converted
|
||||
/// texels is read. Both forms read Metal's texels exactly. The runtime reads it to state a
|
||||
/// texture's planes (`TextureFacts::ycbcr_in_place`).
|
||||
pub fn reads_ycbcr_planes_in_place(&self) -> bool {
|
||||
self.fields.ycbcr_in_place
|
||||
}
|
||||
|
||||
/// Whether a `half` or `float` read of a 16-bit float texture answers the texel's own bits,
|
||||
/// read through the texture's unsigned-integer alias at the slot's second binding
|
||||
/// (`DevicePolicy::half_texel_bits`,
|
||||
@@ -576,6 +585,15 @@ pub struct ProfileFields {
|
||||
/// Elsewhere the device filters such a texture as any other. Derived, so a profile that answers
|
||||
/// alike under both policies keys the same.
|
||||
pub ycbcr_variant: bool,
|
||||
/// Whether a two-plane YCbCr texture's planes may be read in place
|
||||
/// (`bind::YCbCrInPlace`): on a device whose GPU reads the planes' memory with no bus between
|
||||
/// (`VkPhysicalDeviceType` integrated or CPU), a texture slot whose function reads such a
|
||||
/// texture only as the in-place form reads records `RuntimeFact::YCbCrInPlace`, and the
|
||||
/// consumer states the planes of each texture it holds so. A discrete, virtual or other
|
||||
/// device, or one of no stated type, keeps every such texture's image of converted texels,
|
||||
/// which its refresh reads across the bus once per encoder where the in-place form would read
|
||||
/// the planes there at every pass. Both forms read Metal's texels exactly.
|
||||
pub ycbcr_in_place: bool,
|
||||
/// Whose operand Metal's minimum and maximum functions pick (`lower::arith::native_min_max`):
|
||||
/// Metal's, or the device's `NMin`, `NMax` and `NClamp` as they are (the policy's
|
||||
/// `NanMinMaxPolicy::Native`). Derived, so a device that keeps Metal's picks keys the same
|
||||
|
||||
@@ -157,6 +157,7 @@ fn every_fact() -> Vec<RuntimeFact> {
|
||||
RuntimeFact::QuadPrimitiveIds,
|
||||
RuntimeFact::RotatedWeights,
|
||||
RuntimeFact::PrivateList,
|
||||
RuntimeFact::YCbCrInPlace { slot, samplers: 1 },
|
||||
RuntimeFact::MeshLastFirst,
|
||||
RuntimeFact::AbsentArgumentRead {
|
||||
stage: Stage::Fragment,
|
||||
@@ -387,6 +388,7 @@ fn variant(f: &RuntimeFact) -> usize {
|
||||
RuntimeFact::RotatedWeights => 95,
|
||||
RuntimeFact::PrivateList => 96,
|
||||
RuntimeFact::MeshLastFirst => 97,
|
||||
RuntimeFact::YCbCrInPlace { .. } => 99,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -394,7 +396,7 @@ fn variant(f: &RuntimeFact) -> usize {
|
||||
fn mechanism_is_total_over_every_fact_and_profile() {
|
||||
let facts = every_fact();
|
||||
let covered: std::collections::BTreeSet<usize> = facts.iter().map(variant).collect();
|
||||
assert_eq!(covered, (0..99).collect(), "every_fact misses a variant");
|
||||
assert_eq!(covered, (0..100).collect(), "every_fact misses a variant");
|
||||
for (stem, _) in super::committed_profiles() {
|
||||
let dev = device(&stem);
|
||||
let p = dev.profile();
|
||||
@@ -468,6 +470,7 @@ fn mechanism_is_total_over_every_fact_and_profile() {
|
||||
| RuntimeFact::MergedDraws
|
||||
| RuntimeFact::QuadPrimitiveIds
|
||||
| RuntimeFact::PrivateList
|
||||
| RuntimeFact::YCbCrInPlace { .. }
|
||||
| RuntimeFact::ZeroedColor { .. }
|
||||
| RuntimeFact::DroppedColor { .. }
|
||||
| RuntimeFact::DepthClampRange
|
||||
|
||||
@@ -1050,6 +1050,7 @@ fn image_decl(s: &TileSlot) -> ImageDecl {
|
||||
level_views: None,
|
||||
extended: None,
|
||||
x_channel: false,
|
||||
in_place: false,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -116,6 +116,8 @@ pub const fn shape(f: PushField) -> FieldShape {
|
||||
PushField::StorageKeptChannels => FieldShape::U32,
|
||||
// A specialization key's value carried as data: every such key is a `u32` or a boolean.
|
||||
PushField::Specialized(_) => FieldShape::U32,
|
||||
// An in-place YCbCr texture's size, planes and conversion.
|
||||
PushField::YCbCrInPlace(_) => FieldShape::UVec4Array(2),
|
||||
PushField::ColorWriteRule(_) => FieldShape::U32,
|
||||
// The residual is below `min{Storage,Uniform}BufferOffsetAlignment`.
|
||||
PushField::SlotBindOffset(_) | PushField::VertexBufferStride(_) => FieldShape::U32,
|
||||
|
||||
@@ -1166,6 +1166,25 @@ pub(super) fn footprint_of_image(
|
||||
footprint_at(fb, t, &at, (size, base, image), bits, taps)
|
||||
}
|
||||
|
||||
/// [`footprint_of_image`] of an image whose base-level size `size` (a `uvec2`) the caller states:
|
||||
/// an in-place texture's (`super::in_place`), whose taps read the base level of its one level.
|
||||
pub(super) fn footprint_sized(
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
t: &Tys,
|
||||
(coord, layer, offset): (SValue, Option<SValue>, Option<(SValue, u8)>),
|
||||
(size, image): (SValue, CombinedImage),
|
||||
bits: Bits,
|
||||
(taps, parent): (&Taps<'_>, Option<OffsetBase>),
|
||||
) -> BResult<Footprint> {
|
||||
let at = At {
|
||||
coord,
|
||||
layer,
|
||||
parent,
|
||||
offset,
|
||||
};
|
||||
footprint_at(fb, t, &at, (size, None, image), bits, taps)
|
||||
}
|
||||
|
||||
/// The footprint of sample `s` over `taps` on an image of level-0 size `size` (image facts
|
||||
/// `image`), the border color seen through the channels of the bound format's treatment `bits`.
|
||||
pub(super) fn footprint_on(
|
||||
|
||||
@@ -521,6 +521,9 @@ pub(super) struct Texture {
|
||||
/// The slot's `SpecKey::OffsetBaseAxes` tests, by which a texel offset is placed
|
||||
/// (`position::offset_dropped`), where the sample reads them ([`Sample::offset_base`]).
|
||||
pub parent: Option<crate::lower::texture::OffsetBase>,
|
||||
/// The base level's size (a `uvec2`) where the image's own query does not state it: an
|
||||
/// in-place texture's, whose image is its planes' texel buffer (`super::in_place`).
|
||||
pub size: Option<SValue>,
|
||||
}
|
||||
|
||||
/// How a sample's raw texels decode: by one form, a slot's variant's, through the form's sRGB
|
||||
@@ -540,6 +543,9 @@ pub(super) enum Decode {
|
||||
/// The routine of a `float` result, and of a `half` one where the access rounds to it.
|
||||
routines: (FuncId, Option<FuncId>),
|
||||
},
|
||||
/// The planes of a two-plane YCbCr texture read in place, each tap converted as Metal reads
|
||||
/// it (`super::in_place::texel`).
|
||||
InPlace(super::in_place::Planes),
|
||||
}
|
||||
|
||||
/// Where a sample reads: its plane coordinate (two floats), a 2D array's layer (an integer), the
|
||||
@@ -739,6 +745,7 @@ fn sampled(
|
||||
flags: value(fb, flags)?,
|
||||
swizzle,
|
||||
parent,
|
||||
size: None,
|
||||
};
|
||||
let at = At {
|
||||
coord,
|
||||
@@ -846,9 +853,39 @@ fn sampled(
|
||||
swizzled(fb, &tex, x)
|
||||
}
|
||||
|
||||
/// The footprint over `taps` of the sample at `at` of `tex`, the border color seen through the
|
||||
/// channels `bits` state: its size the image's query of the taps' level, or `tex`'s stated size.
|
||||
fn footprint_of(
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
t: &Tys,
|
||||
at: &At<'_>,
|
||||
tex: &Texture,
|
||||
bits: Bits,
|
||||
taps: &Taps<'_>,
|
||||
) -> BResult<Footprint> {
|
||||
match tex.size {
|
||||
Some(size) => super::bicubic::footprint_sized(
|
||||
fb,
|
||||
t,
|
||||
(at.coord, at.layer, at.passed),
|
||||
(size, tex.image),
|
||||
bits,
|
||||
(taps, tex.parent),
|
||||
),
|
||||
None => footprint_of_image(
|
||||
fb,
|
||||
t,
|
||||
(at.coord, at.layer, at.passed),
|
||||
(tex.img, tex.image),
|
||||
bits,
|
||||
(taps, tex.parent),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// The filtered texel at `at` of `tex` (unswizzled) by `state`: a constexpr sampler's linear or
|
||||
/// nearest filter, or the filter a runtime sampler's word states.
|
||||
fn filters(
|
||||
pub(super) fn filters(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
t: &Tys,
|
||||
@@ -1126,14 +1163,7 @@ fn block_taps(
|
||||
base: TapBase::Quantized,
|
||||
level: at.level,
|
||||
};
|
||||
let fp = footprint_of_image(
|
||||
fb,
|
||||
t,
|
||||
(at.coord, at.layer, at.passed),
|
||||
(tex.img, tex.image),
|
||||
Bits::Value(tex.flags),
|
||||
(&taps, tex.parent),
|
||||
)?;
|
||||
let fp = footprint_of(fb, t, at, tex, Bits::Value(tex.flags), &taps)?;
|
||||
let [(kx, xs), (ky, ys), (kz, zs)] = &fp.axes[..] else {
|
||||
return Err(cx.fail("an extended-range 3D linear sample without three plane axes"));
|
||||
};
|
||||
@@ -1201,14 +1231,7 @@ fn quad_taps(
|
||||
base: TapBase::Quantized,
|
||||
level: at.level,
|
||||
};
|
||||
let fp = footprint_of_image(
|
||||
fb,
|
||||
t,
|
||||
(at.coord, at.layer, at.passed),
|
||||
(tex.img, tex.image),
|
||||
Bits::Value(tex.flags),
|
||||
(&taps, tex.parent),
|
||||
)?;
|
||||
let fp = footprint_of(fb, t, at, tex, Bits::Value(tex.flags), &taps)?;
|
||||
let [(kx, xs), (ky, ys)] = &fp.axes[..] else {
|
||||
return Err(cx.fail("an extended-range linear sample without two plane axes"));
|
||||
};
|
||||
@@ -1290,7 +1313,7 @@ fn level_taps(
|
||||
|
||||
/// Whether runtime sampler word `word` states linear minification and magnification (a `bool`): a
|
||||
/// mip filter, which the word's level reads, filters nothing within a level.
|
||||
fn word_linear(fb: &mut FunctionBuilder<'_>, t: &Tys, word: SValue) -> BResult<SValue> {
|
||||
pub(super) fn word_linear(fb: &mut FunctionBuilder<'_>, t: &Tys, word: SValue) -> BResult<SValue> {
|
||||
let mask = SamplerWord::MIN_LINEAR | SamplerWord::MAG_LINEAR;
|
||||
let mask = scalar(fb, t.u32_, u64::from(mask))?;
|
||||
let mask = value(fb, mask)?;
|
||||
@@ -1313,14 +1336,7 @@ fn bicubic(
|
||||
let span = cubic.span();
|
||||
let taps = cubic.taps(span);
|
||||
let bits = Bits::Value(tex.flags);
|
||||
let fp = footprint_of_image(
|
||||
fb,
|
||||
t,
|
||||
(at.coord, at.layer, at.passed),
|
||||
(tex.img, tex.image),
|
||||
bits,
|
||||
(&taps, tex.parent),
|
||||
)?;
|
||||
let fp = footprint_of(fb, t, at, tex, bits, &taps)?;
|
||||
let zero = fb.u32_const(0)?;
|
||||
let zero = value(fb, zero)?;
|
||||
let size = fb.query(ImageQuery::SizeLod(zero), tex.img)?;
|
||||
@@ -1421,14 +1437,7 @@ pub(super) fn nearest(
|
||||
base: TapBase::Floor,
|
||||
level: at.level,
|
||||
};
|
||||
let fp = footprint_of_image(
|
||||
fb,
|
||||
t,
|
||||
(at.coord, at.layer, at.passed),
|
||||
(tex.img, tex.image),
|
||||
Bits::Value(tex.flags),
|
||||
(&taps, tex.parent),
|
||||
)?;
|
||||
let fp = footprint_of(fb, t, at, tex, Bits::Value(tex.flags), &taps)?;
|
||||
// Each plane axis's one tap (a 3D texture's three).
|
||||
let mut site = Vec::with_capacity(fp.axes.len());
|
||||
for (_, taps) in &fp.axes {
|
||||
@@ -1445,7 +1454,7 @@ pub(super) fn nearest(
|
||||
let v = texel(cx, fb, &fp, tex, &site, false)?;
|
||||
crate::lower::arith::extended_range::bfloat_sample_half(fb, v)
|
||||
}
|
||||
(true, Decode::Form { .. }) => texel(cx, fb, &fp, tex, &site, true),
|
||||
(true, Decode::Form { .. } | Decode::InPlace(_)) => texel(cx, fb, &fp, tex, &site, true),
|
||||
// A heap handle's form: both roundings of the one raw texel, chosen by the form.
|
||||
(true, Decode::Heap { bfloat, .. }) => {
|
||||
let (raw, inside) = tap(fb, &fp, tex, &site)?;
|
||||
@@ -1480,14 +1489,7 @@ pub(super) fn gathered(
|
||||
base: TapBase::Quantized,
|
||||
level: at.level,
|
||||
};
|
||||
let fp = footprint_of_image(
|
||||
fb,
|
||||
t,
|
||||
(at.coord, at.layer, at.passed),
|
||||
(tex.img, tex.image),
|
||||
Bits::Value(tex.flags),
|
||||
(&taps, tex.parent),
|
||||
)?;
|
||||
let fp = footprint_of(fb, t, at, tex, Bits::Value(tex.flags), &taps)?;
|
||||
let [(_, xs), (_, ys)] = &fp.axes[..] else {
|
||||
return Err(cx.fail("an extended-range gather without two plane axes"));
|
||||
};
|
||||
@@ -1514,6 +1516,11 @@ pub(super) fn texel(
|
||||
site: &[Tap],
|
||||
half: bool,
|
||||
) -> BResult<SValue> {
|
||||
if let Decode::InPlace(planes) = tex.decode {
|
||||
let (at, inside) = fp.site(fb, site)?;
|
||||
let v = super::in_place::texel(fb, &planes, tex.img, at, half)?;
|
||||
return fp.border(fb, v, inside);
|
||||
}
|
||||
let (raw, inside) = tap(fb, fp, tex, site)?;
|
||||
let v = decoded(cx, fb, tex, raw, half)?;
|
||||
fp.border(fb, v, inside)
|
||||
@@ -1599,6 +1606,7 @@ fn decoded(
|
||||
fb.call(routine, &[raw, form, inside])?
|
||||
.ok_or_else(missing_routine)
|
||||
}
|
||||
Decode::InPlace(_) => Err(cx.fail("an in-place tap decoded as a raw texel")),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -196,6 +196,7 @@ pub(crate) fn emit(
|
||||
swizzle: None,
|
||||
// A heap element's access reads no slot's `OffsetBaseAxes`.
|
||||
parent: None,
|
||||
size: None,
|
||||
};
|
||||
let at = At {
|
||||
coord: super::emit::plane_coord(cx, fb, s)?,
|
||||
|
||||
@@ -0,0 +1,540 @@
|
||||
//! Samples of a two-plane YCbCr texture whose planes the function reads in place
|
||||
//! (`bind::YCbCrInPlace`, `LoweringInputs::ycbcr_in_place`): the slot is the planes' uniform texel
|
||||
//! buffer, and every tap of a sample is the texel Metal reads there, computed from the codes.
|
||||
//!
|
||||
//! **A tap** at texel `(x, y)` (`bind::ycbcr_convert`'s module docs, measured there): the luma
|
||||
//! code at its place, the four nearest chroma pairs (column `⌊x / 2⌋` and the one after it for an
|
||||
//! odd `x`, before it for an even one, each clamped to the plane, rows alike) weighted 9/3/3/1 and
|
||||
//! rounded to a code, `C = (S + 8) >> 4`, each code the byte or the high 10 bits of its 16-bit
|
||||
//! word; then the conversion of the surface's range and matrix (`bind::ycbcr_read`): every
|
||||
//! channel `v / 2048` exactly, alpha 1. An element of the texel buffer holds two luma codes or one
|
||||
//! chroma pair, so a tap fetches five elements. The texture's size, its planes' first elements
|
||||
//! and rows, and its conversion are the slot's push field (`PushField::YCbCrInPlace`), read once
|
||||
//! where it dominates.
|
||||
//!
|
||||
//! **A sample** is Metal's filter of those texels: a nearest sample the tap at Metal's position,
|
||||
//! a linear one the exact routine's sum of the four taps of Metal's footprint on the grid `2048`
|
||||
//! (`PackedTexels::YCbCr2048`, the class the texture's image of converted texels is filtered
|
||||
//! under), through the extended-range emulation's footprint and routines (`super::extended`), its
|
||||
//! texel offset placed as there. Metal samples such a texture's one level whatever the sampler's
|
||||
//! mip filter, level, bias or gradients, so the sample reads the base level alone. A 4:2:0
|
||||
//! texture samples repeat, mirrored repeat and mirror-clamp-to-edge as clamp-to-edge: a constexpr
|
||||
//! sampler's modes arrive mapped (`LoweringInputs::address_maps`), and a runtime sampler's word is
|
||||
//! mapped here ([`mapped_word`]). A border tap reads the border color through the format's
|
||||
//! channels, alpha 1.
|
||||
|
||||
use crate::air::ir::ValueId;
|
||||
use crate::lower::emit::EmitCx;
|
||||
use crate::metal::PixelFormat;
|
||||
use crate::pipeline::sym::{PushField, SlotRef};
|
||||
use crate::spirv::builder::constructs::{ArmEnd, ArmFn, Merged};
|
||||
use crate::spirv::builder::FunctionBuilder;
|
||||
use crate::spirv::error::BResult;
|
||||
use crate::spirv::ids::{DemoteTy, TypeId, Value as SValue};
|
||||
use crate::spirv::ir::{BinOp, ConstBits, Constant, ConvOp, GlslOp, ImageOperands, Type as SType};
|
||||
|
||||
use super::bicubic::{Addressing, Tys};
|
||||
use super::extended::{Decode, State, Texture};
|
||||
use super::{CombinedImage, Pixel};
|
||||
|
||||
/// A sample of an in-place texture slot (module docs).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Sample {
|
||||
/// The texture slot, under its in-place variant.
|
||||
pub texture: u32,
|
||||
/// The sampler's state the sample follows: a constexpr sampler's modes as the texture's map
|
||||
/// sends them, or a runtime sampler's word.
|
||||
pub state: State,
|
||||
/// The constant texel offset Metal applies, per plane axis.
|
||||
pub offset: Option<Vec<i32>>,
|
||||
/// The offset moves an axis that may repeat or mirror: it is placed by the slot's
|
||||
/// `SpecKey::OffsetBaseAxes` tests, as an extended-range sample places it.
|
||||
pub offset_base: bool,
|
||||
/// The plane coordinate: two floats.
|
||||
pub coord: ValueId,
|
||||
/// The result is `half`, else `float`.
|
||||
pub half: bool,
|
||||
/// The lowered type of the result (`{T, i8}`, its status word 0).
|
||||
pub result: DemoteTy,
|
||||
}
|
||||
|
||||
/// The census words of a slot's constants: the push field's words and the conversion's selects.
|
||||
const PREPARE_WORDS: u32 = 192;
|
||||
/// The census words of one tap: five fetches, the chroma filter, and the conversion.
|
||||
const TAP_WORDS: u32 = 224;
|
||||
/// The census words of a runtime sampler's mapped word.
|
||||
const WORD_WORDS: u32 = 96;
|
||||
|
||||
impl Sample {
|
||||
/// The census name of the sample's form.
|
||||
pub(crate) fn name(&self) -> &'static str {
|
||||
match self.state {
|
||||
State::Constant { linear: true, .. } => "sampler.ycbcr_in_place.linear",
|
||||
State::Constant { linear: false, .. } => "sampler.ycbcr_in_place.nearest",
|
||||
State::Slot { .. } => "sampler.ycbcr_in_place.runtime",
|
||||
}
|
||||
}
|
||||
|
||||
/// The estimated words of the sample: the slot's constants, a linear filter's four taps and
|
||||
/// its footprint (a runtime sampler's nearest tap and its own footprint besides, the word and
|
||||
/// its branch), and Metal's offset rule on each lane of an offset.
|
||||
pub(crate) fn words(&self) -> u32 {
|
||||
let position = 2 * super::position::POSITION_WORDS;
|
||||
let linear = super::linear::PLANE_WORDS + 4 * TAP_WORDS + position;
|
||||
let nearest = super::extended::NEAREST_WORDS + TAP_WORDS + position;
|
||||
let rule = match self.offset_base {
|
||||
true => super::position::OFFSET_RULE_WORDS + super::position::PARENT_RULE_WORDS,
|
||||
false => super::position::OFFSET_RULE_WORDS,
|
||||
};
|
||||
let offset = self.offset.as_deref().map_or(0, |o| o.len() as u32) * rule;
|
||||
let filters = match self.state {
|
||||
State::Constant { linear: true, .. } => linear,
|
||||
State::Constant { linear: false, .. } => nearest,
|
||||
State::Slot { .. } => linear + nearest + WORD_WORDS + super::extended::BRANCH_WORDS,
|
||||
};
|
||||
PREPARE_WORDS + filters + offset + 16
|
||||
}
|
||||
}
|
||||
|
||||
/// The constants of an in-place texture's taps, read from the slot's push field
|
||||
/// (`bind::YCbCrInPlace::words`).
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct Planes {
|
||||
/// The luma plane's first element and the elements between its rows (`u32`s).
|
||||
luma: [SValue; 2],
|
||||
/// The chroma plane's first element and the elements between its rows (`u32`s).
|
||||
chroma: [SValue; 2],
|
||||
/// The chroma plane's last column and row (`u32`s): `⌈w / 2⌉ - 1`, `⌈h / 2⌉ - 1`.
|
||||
last: [SValue; 2],
|
||||
/// The shift that takes an element's lane to its code: 6 of 10-bit codes, 0 of 8-bit ones.
|
||||
code_shift: SValue,
|
||||
/// The shift that counts a code as a 10-bit one: 0 of 10-bit codes, 2 of 8-bit ones.
|
||||
up: SValue,
|
||||
/// The codes are full range (a `bool`).
|
||||
full: SValue,
|
||||
/// The largest code `m = 2^b - 1`, and `⌊m / 2⌋`, of full range's luma (`u32`s).
|
||||
max: [SValue; 2],
|
||||
/// Red's, green's and blue's `(kb, kr)` (`i32`s) of the surface's range and matrix.
|
||||
k: [[SValue; 2]; 3],
|
||||
}
|
||||
|
||||
/// The scalar and vector types a tap computes in.
|
||||
struct T {
|
||||
u32_: TypeId,
|
||||
i32_: TypeId,
|
||||
f32_: TypeId,
|
||||
vec4: TypeId,
|
||||
uvec2: TypeId,
|
||||
}
|
||||
|
||||
impl T {
|
||||
fn new(fb: &mut FunctionBuilder<'_>) -> BResult<T> {
|
||||
let m = fb.module();
|
||||
let u32_ = m.ty(SType::Int {
|
||||
width: 32,
|
||||
signed: false,
|
||||
})?;
|
||||
let i32_ = m.ty(SType::Int {
|
||||
width: 32,
|
||||
signed: true,
|
||||
})?;
|
||||
let f32_ = m.ty(SType::Float { width: 32 })?;
|
||||
let vec4 = m.ty(SType::Vector { elem: f32_, len: 4 })?;
|
||||
let uvec2 = m.ty(SType::Vector { elem: u32_, len: 2 })?;
|
||||
Ok(T {
|
||||
u32_,
|
||||
i32_,
|
||||
f32_,
|
||||
vec4,
|
||||
uvec2,
|
||||
})
|
||||
}
|
||||
|
||||
fn k(&self, fb: &mut FunctionBuilder<'_>, ty: TypeId, bits: u32) -> BResult<SValue> {
|
||||
let c = fb.module().constant(Constant::Scalar {
|
||||
ty,
|
||||
bits: ConstBits(u64::from(bits)),
|
||||
})?;
|
||||
fb.module().const_value(c)
|
||||
}
|
||||
|
||||
fn u(&self, fb: &mut FunctionBuilder<'_>, v: u32) -> BResult<SValue> {
|
||||
self.k(fb, self.u32_, v)
|
||||
}
|
||||
|
||||
fn i(&self, fb: &mut FunctionBuilder<'_>, v: i32) -> BResult<SValue> {
|
||||
self.k(fb, self.i32_, v as u32)
|
||||
}
|
||||
|
||||
fn f(&self, fb: &mut FunctionBuilder<'_>, v: f32) -> BResult<SValue> {
|
||||
self.k(fb, self.f32_, v.to_bits())
|
||||
}
|
||||
}
|
||||
|
||||
/// The words of slot `slot`'s push field (`bind::YCbCrInPlace::words`), each a `u32`, in the
|
||||
/// open block.
|
||||
struct Words {
|
||||
size: [SValue; 2],
|
||||
luma: [SValue; 2],
|
||||
chroma: [SValue; 2],
|
||||
conversion: SValue,
|
||||
}
|
||||
|
||||
fn words(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, slot: SlotRef) -> BResult<Words> {
|
||||
use crate::bind::YCbCrInPlace as W;
|
||||
let field = cx.push_field(fb, PushField::YCbCrInPlace(slot))?;
|
||||
let low = fb.composite_extract(field, &[0])?;
|
||||
let high = fb.composite_extract(field, &[1])?;
|
||||
// Word `i` of the field: lane `i % 4` of its first `uvec4` or its second.
|
||||
let mut word = |i: usize| match i < 4 {
|
||||
true => fb.composite_extract(low, &[i as u32]),
|
||||
false => fb.composite_extract(high, &[(i - 4) as u32]),
|
||||
};
|
||||
Ok(Words {
|
||||
size: [word(W::WIDTH)?, word(W::HEIGHT)?],
|
||||
luma: [word(W::LUMA_AT)?, word(W::LUMA_ROW)?],
|
||||
chroma: [word(W::CHROMA_AT)?, word(W::CHROMA_ROW)?],
|
||||
conversion: word(W::CONVERSION)?,
|
||||
})
|
||||
}
|
||||
|
||||
/// The width (`axis` 0) or the height (`axis` 1) of slot `slot`'s in-place texture, a `u32`
|
||||
/// from its push field, in the open block: a size query's answer at its one level.
|
||||
pub(crate) fn extent(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
slot: SlotRef,
|
||||
axis: u8,
|
||||
) -> BResult<SValue> {
|
||||
let [width, height] = words(cx, fb, slot)?.size;
|
||||
match axis {
|
||||
0 => Ok(width),
|
||||
1 => Ok(height),
|
||||
_ => Err(cx.fail("an in-place texture's extent past its two axes")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The constants of slot `slot`'s taps (its push field's words), and the texture's size (a
|
||||
/// `uvec2`), in the open block.
|
||||
pub(crate) fn prepare(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
slot: SlotRef,
|
||||
) -> BResult<(Planes, SValue)> {
|
||||
use crate::bind::{YCbCrMatrix as M, YCbCrRange as R};
|
||||
let t = T::new(fb)?;
|
||||
let w = words(cx, fb, slot)?;
|
||||
let size = fb.composite_construct(t.uvec2, &w.size)?;
|
||||
let one = t.u(fb, 1)?;
|
||||
// The chroma plane's last column and row, `⌈n / 2⌉ - 1`.
|
||||
let last_of = |fb: &mut FunctionBuilder<'_>, n: SValue| -> BResult<SValue> {
|
||||
let up = fb.binary(BinOp::IAdd, n, one)?;
|
||||
let half = fb.binary(BinOp::ShiftRightLogical, up, one)?;
|
||||
fb.binary(BinOp::ISub, half, one)
|
||||
};
|
||||
let [width, height] = w.size;
|
||||
let last = [last_of(fb, width)?, last_of(fb, height)?];
|
||||
// The conversion word: the codes' bits, full range, the matrix.
|
||||
let field_at = |fb: &mut FunctionBuilder<'_>, shift: u32, mask: u32| -> BResult<SValue> {
|
||||
let shift = t.u(fb, shift)?;
|
||||
let mask = t.u(fb, mask)?;
|
||||
let v = fb.binary(BinOp::ShiftRightLogical, w.conversion, shift)?;
|
||||
fb.binary(BinOp::BitwiseAnd, v, mask)
|
||||
};
|
||||
let bits = field_at(fb, 0, 0xff)?;
|
||||
let ten = t.u(fb, 10)?;
|
||||
let ten = fb.binary(BinOp::IEqual, bits, ten)?;
|
||||
let pick = |fb: &mut FunctionBuilder<'_>, [a, b]: [u32; 2]| -> BResult<SValue> {
|
||||
let (a, b) = (t.u(fb, a)?, t.u(fb, b)?);
|
||||
fb.select(ten, a, b)
|
||||
};
|
||||
let code_shift = pick(fb, [6, 0])?;
|
||||
let up = pick(fb, [0, 2])?;
|
||||
let max = [pick(fb, [1023, 255])?, pick(fb, [511, 127])?];
|
||||
let full = field_at(fb, 8, 1)?;
|
||||
let full = fb.binary(BinOp::IEqual, full, one)?;
|
||||
let matrix = field_at(fb, 9, 3)?;
|
||||
let bt709 = fb.binary(BinOp::IEqual, matrix, one)?;
|
||||
let two = t.u(fb, 2)?;
|
||||
let bt2020 = fb.binary(BinOp::IEqual, matrix, two)?;
|
||||
// A coefficient of each matrix (BT.601, BT.709, BT.2020), chosen by the matrix.
|
||||
let choose = |fb: &mut FunctionBuilder<'_>, [a, b, c]: [i32; 3]| -> BResult<SValue> {
|
||||
let (a, b, c) = (t.i(fb, a)?, t.i(fb, b)?, t.i(fb, c)?);
|
||||
let low = fb.select(bt709, b, a)?;
|
||||
fb.select(bt2020, c, low)
|
||||
};
|
||||
// Per channel, each matrix's `(kb, kr)` of `range`.
|
||||
let by_channel = |range| {
|
||||
let of = crate::bind::ycbcr_convert::coefficients;
|
||||
let [[a0, a1, a2], [b0, b1, b2], [c0, c1, c2]] =
|
||||
[M::Bt601, M::Bt709, M::Bt2020].map(|m| of(range, m));
|
||||
[[a0, b0, c0], [a1, b1, c1], [a2, b2, c2]]
|
||||
};
|
||||
let sides: [fn((i32, i32)) -> i32; 2] = [|(kb, _)| kb, |(_, kr)| kr];
|
||||
let zero = t.i(fb, 0)?;
|
||||
let mut k = [[zero; 2]; 3];
|
||||
for ((video, full_range), out) in by_channel(R::Video)
|
||||
.into_iter()
|
||||
.zip(by_channel(R::Full))
|
||||
.zip(k.iter_mut())
|
||||
{
|
||||
for (side, coefficient) in sides.into_iter().zip(out.iter_mut()) {
|
||||
let v = choose(fb, video.map(side))?;
|
||||
let f = choose(fb, full_range.map(side))?;
|
||||
*coefficient = fb.select(full, f, v)?;
|
||||
}
|
||||
}
|
||||
let planes = Planes {
|
||||
luma: w.luma,
|
||||
chroma: w.chroma,
|
||||
last,
|
||||
code_shift,
|
||||
up,
|
||||
full,
|
||||
max,
|
||||
k,
|
||||
};
|
||||
Ok((planes, size))
|
||||
}
|
||||
|
||||
/// The element `at + row · y + x` of the planes' texel buffer `img` (`u32`s): a `uvec4` whose
|
||||
/// first two lanes it holds.
|
||||
fn element(
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
img: SValue,
|
||||
[at, row]: [SValue; 2],
|
||||
[x, y]: [SValue; 2],
|
||||
) -> BResult<SValue> {
|
||||
let r = fb.binary(BinOp::IMul, row, y)?;
|
||||
let e = fb.binary(BinOp::IAdd, at, r)?;
|
||||
let e = fb.binary(BinOp::IAdd, e, x)?;
|
||||
fb.fetch(img, e, &ImageOperands::default())
|
||||
}
|
||||
|
||||
/// The texel Metal reads at `at` (a `uvec2` inside the texture) of the in-place texture whose
|
||||
/// planes' texel buffer is `img` and whose constants `p` holds (module docs): a `vec4` of its
|
||||
/// converted red, green and blue, each a step of `1 / 2048`, and alpha 1. Every such step is a
|
||||
/// `half` exactly, so a `half` result's rounding leaves it, whatever `_half` asks.
|
||||
pub(crate) fn texel(
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
p: &Planes,
|
||||
img: SValue,
|
||||
at: SValue,
|
||||
_half: bool,
|
||||
) -> BResult<SValue> {
|
||||
let t = T::new(fb)?;
|
||||
let x = fb.composite_extract(at, &[0])?;
|
||||
let y = fb.composite_extract(at, &[1])?;
|
||||
let (zero, one) = (t.u(fb, 0)?, t.u(fb, 1)?);
|
||||
// The luma code: lane `x & 1` of element `⌊x / 2⌋` of its row.
|
||||
let pair_x = fb.binary(BinOp::ShiftRightLogical, x, one)?;
|
||||
let v = element(fb, img, p.luma, [pair_x, y])?;
|
||||
let odd_x = fb.binary(BinOp::BitwiseAnd, x, one)?;
|
||||
let odd_x = fb.binary(BinOp::INotEqual, odd_x, zero)?;
|
||||
let l0 = fb.composite_extract(v, &[0])?;
|
||||
let l1 = fb.composite_extract(v, &[1])?;
|
||||
let luma = fb.select(odd_x, l1, l0)?;
|
||||
let luma = fb.binary(BinOp::ShiftRightLogical, luma, p.code_shift)?;
|
||||
// On each axis, the chroma texel's own column (or row) and its neighbour: the one after it
|
||||
// for an odd index, before it for an even one, clamped to the plane.
|
||||
let near = |fb: &mut FunctionBuilder<'_>, c: SValue, last: SValue| -> BResult<[SValue; 2]> {
|
||||
let own = fb.binary(BinOp::ShiftRightLogical, c, one)?;
|
||||
let odd = fb.binary(BinOp::BitwiseAnd, c, one)?;
|
||||
let odd = fb.binary(BinOp::INotEqual, odd, zero)?;
|
||||
let after = fb.binary(BinOp::IAdd, own, one)?;
|
||||
let after = fb.glsl(GlslOp::UMin, &[after, last])?;
|
||||
let before = fb.glsl(GlslOp::UMax, &[own, one])?;
|
||||
let before = fb.binary(BinOp::ISub, before, one)?;
|
||||
Ok([own, fb.select(odd, after, before)?])
|
||||
};
|
||||
let [cx0, cx1] = near(fb, x, p.last[0])?;
|
||||
let [cy0, cy1] = near(fb, y, p.last[1])?;
|
||||
let mut sums = [zero; 2];
|
||||
for (weight, site) in [
|
||||
(9, [cx0, cy0]),
|
||||
(3, [cx1, cy0]),
|
||||
(3, [cx0, cy1]),
|
||||
(1, [cx1, cy1]),
|
||||
] {
|
||||
let v = element(fb, img, p.chroma, site)?;
|
||||
let w = t.u(fb, weight)?;
|
||||
for (lane, sum) in sums.iter_mut().enumerate() {
|
||||
let c = fb.composite_extract(v, &[lane as u32])?;
|
||||
let c = fb.binary(BinOp::ShiftRightLogical, c, p.code_shift)?;
|
||||
let c = fb.binary(BinOp::IMul, c, w)?;
|
||||
*sum = fb.binary(BinOp::IAdd, *sum, c)?;
|
||||
}
|
||||
}
|
||||
// Each chroma code `(S + 8) >> 4`, counted as a 10-bit code, less 512.
|
||||
let (eight, four, mid) = (t.u(fb, 8)?, t.u(fb, 4)?, t.i(fb, 512)?);
|
||||
let mut chroma = [mid; 2];
|
||||
for (c, sum) in chroma.iter_mut().zip(sums) {
|
||||
let s = fb.binary(BinOp::IAdd, sum, eight)?;
|
||||
let code = fb.binary(BinOp::ShiftRightLogical, s, four)?;
|
||||
let code = fb.binary(BinOp::ShiftLeftLogical, code, p.up)?;
|
||||
let code = fb.convert(ConvOp::Bitcast, code, t.i32_)?;
|
||||
*c = fb.binary(BinOp::ISub, code, mid)?;
|
||||
}
|
||||
// The luma term: video range `9576 ((Y << u) - 64)`, full `256 ⌊(32768 Y + ⌊m / 2⌋) / m⌋`.
|
||||
let video = fb.binary(BinOp::ShiftLeftLogical, luma, p.up)?;
|
||||
let video = fb.convert(ConvOp::Bitcast, video, t.i32_)?;
|
||||
let black = t.i(fb, 64)?;
|
||||
let video = fb.binary(BinOp::ISub, video, black)?;
|
||||
let scale = t.i(fb, 9576)?;
|
||||
let video = fb.binary(BinOp::IMul, video, scale)?;
|
||||
let wide = t.u(fb, 32768)?;
|
||||
let full = fb.binary(BinOp::IMul, luma, wide)?;
|
||||
let full = fb.binary(BinOp::IAdd, full, p.max[1])?;
|
||||
let full = fb.binary(BinOp::UDiv, full, p.max[0])?;
|
||||
let full = fb.convert(ConvOp::Bitcast, full, t.i32_)?;
|
||||
let step = t.i(fb, 256)?;
|
||||
let full = fb.binary(BinOp::IMul, full, step)?;
|
||||
let l = fb.select(p.full, full, video)?;
|
||||
// Each channel `clamp((L + kb Cb' + kr Cr' + 2048) >> 12, 0, 2048) / 2048`.
|
||||
let (round, twelve, low) = (t.i(fb, 2048)?, t.u(fb, 12)?, t.i(fb, 0)?);
|
||||
let grid = t.f(fb, 1.0 / 2048.0)?;
|
||||
let mut lanes = Vec::with_capacity(4);
|
||||
for [kb, kr] in p.k {
|
||||
let b = fb.binary(BinOp::IMul, kb, chroma[0])?;
|
||||
let r = fb.binary(BinOp::IMul, kr, chroma[1])?;
|
||||
let sum = fb.binary(BinOp::IAdd, l, b)?;
|
||||
let sum = fb.binary(BinOp::IAdd, sum, r)?;
|
||||
let sum = fb.binary(BinOp::IAdd, sum, round)?;
|
||||
let v = fb.binary(BinOp::ShiftRightArithmetic, sum, twelve)?;
|
||||
let v = fb.glsl(GlslOp::SClamp, &[v, low, round])?;
|
||||
let v = fb.convert(ConvOp::ConvertSToF, v, t.f32_)?;
|
||||
lanes.push(fb.binary(BinOp::FMul, v, grid)?);
|
||||
}
|
||||
lanes.push(t.f(fb, 1.0)?);
|
||||
fb.composite_construct(t.vec4, &lanes)
|
||||
}
|
||||
|
||||
/// The class bits a sample's exact routine and border texels read: the converted 4:2:0 formats'
|
||||
/// (`metal::texel_format::texel_format`), one for both widths (`one_class_for_both_widths`).
|
||||
pub(crate) fn class() -> u32 {
|
||||
crate::metal::texel_format::texel_format(PixelFormat::YCBCR84202P).0
|
||||
}
|
||||
|
||||
/// Runtime sampler word `word` with each plane axis's mode as a 4:2:0 texture samples it:
|
||||
/// mirror-clamp-to-edge (1), repeat (2) and mirrored repeat (3) as clamp-to-edge (0).
|
||||
fn mapped_word(fb: &mut FunctionBuilder<'_>, t: &T, word: SValue) -> BResult<SValue> {
|
||||
use crate::metal::sampler::SamplerWord;
|
||||
let mut w = word;
|
||||
let (one, three, seven) = (t.u(fb, 1)?, t.u(fb, 3)?, t.u(fb, 7)?);
|
||||
for shift in SamplerWord::ADDRESS_SHIFT.into_iter().take(2) {
|
||||
let s = t.u(fb, shift)?;
|
||||
let mode = fb.binary(BinOp::ShiftRightLogical, w, s)?;
|
||||
let mode = fb.binary(BinOp::BitwiseAnd, mode, seven)?;
|
||||
let above = fb.binary(BinOp::UGreaterThanEqual, mode, one)?;
|
||||
let within = fb.binary(BinOp::ULessThanEqual, mode, three)?;
|
||||
let wraps = fb.binary(BinOp::LogicalAnd, above, within)?;
|
||||
let keep = t.u(fb, !(7 << shift))?;
|
||||
let edge = fb.binary(BinOp::BitwiseAnd, w, keep)?;
|
||||
w = fb.select(wraps, edge, w)?;
|
||||
}
|
||||
Ok(w)
|
||||
}
|
||||
|
||||
/// The texel of in-place sample `s` in the open block, with its status word 0 (module docs).
|
||||
pub(crate) fn emit(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
s: &Sample,
|
||||
) -> BResult<SValue> {
|
||||
let coord = cx.operand(fb, s.coord)?;
|
||||
let (decl, img) = crate::lower::texture::slot_image(cx, fb, s.texture)?;
|
||||
let Some(slot) = cx
|
||||
.plan
|
||||
.families
|
||||
.texture
|
||||
.slots
|
||||
.get(&s.texture)
|
||||
.map(|p| p.slot)
|
||||
else {
|
||||
return Err(cx.fail(format!("texture slot {} is not planned", s.texture)));
|
||||
};
|
||||
let (planes, size) = prepare(cx, fb, slot)?;
|
||||
let t = Tys::new(fb)?;
|
||||
let tt = T::new(fb)?;
|
||||
let parent = match s.offset_base {
|
||||
true => match cx
|
||||
.decl
|
||||
.families
|
||||
.texture
|
||||
.offset_base
|
||||
.get(&s.texture)
|
||||
.copied()
|
||||
{
|
||||
Some(base) => Some(base),
|
||||
None => {
|
||||
return Err(cx.fail(format!(
|
||||
"texture slot {} has no OffsetBaseAxes specialization",
|
||||
s.texture
|
||||
)))
|
||||
}
|
||||
},
|
||||
false => None,
|
||||
};
|
||||
let flags = tt.u(fb, class())?;
|
||||
let tex = Texture {
|
||||
img,
|
||||
image: CombinedImage {
|
||||
plane: 2,
|
||||
arrayed: false,
|
||||
texel: decl.texel,
|
||||
},
|
||||
decode: Decode::InPlace(planes),
|
||||
flags,
|
||||
swizzle: None,
|
||||
parent,
|
||||
size: Some(size),
|
||||
};
|
||||
let at = super::extended::At {
|
||||
coord,
|
||||
layer: None,
|
||||
offset: s.offset.as_deref(),
|
||||
passed: None,
|
||||
level: None,
|
||||
half: s.half,
|
||||
};
|
||||
let x = match &s.state {
|
||||
State::Constant { .. } => super::extended::filters(cx, fb, &t, &at, &tex, &s.state)?,
|
||||
State::Slot { sampler } => {
|
||||
let word = super::emit::sampler_word(cx, fb, Pixel::Spec(*sampler))?;
|
||||
let word = mapped_word(fb, &tt, word)?;
|
||||
let addressing = Addressing::Word { word, axes: 2 };
|
||||
let linear = super::extended::word_linear(fb, &t, word)?;
|
||||
let (t, tex, at) = (&t, &tex, &at);
|
||||
let filtered: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, cx| {
|
||||
let x = super::extended::filtered(cx, fb, t, at, tex, addressing)?;
|
||||
Ok(ArmEnd::FallThrough(vec![x]))
|
||||
});
|
||||
let nearest: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, cx| {
|
||||
let x = super::extended::nearest(cx, fb, t, at, tex, addressing)?;
|
||||
Ok(ArmEnd::FallThrough(vec![x]))
|
||||
});
|
||||
let Merged(merged) = fb.if_(cx, linear, filtered, Some(nearest))?;
|
||||
match merged[..] {
|
||||
[x] => x,
|
||||
_ => return Err(cx.fail("an in-place sample's branch without its texel")),
|
||||
}
|
||||
}
|
||||
};
|
||||
crate::lower::texture::with_word(cx, fb, &s.result, x, None)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Both widths' converted 4:2:0 formats filter on one class, with Metal's exact sum and its
|
||||
/// border texels, so one variant serves both.
|
||||
#[test]
|
||||
fn one_class_for_both_widths() {
|
||||
use crate::metal::bicubic::BicubicTexels;
|
||||
let ten = crate::metal::texel_format::texel_format(PixelFormat::YCBCR104202P).0;
|
||||
assert_eq!(class(), ten);
|
||||
assert_ne!(class() & BicubicTexels::EXACT, 0);
|
||||
assert_ne!(class() >> BicubicTexels::BORDER & 0xfff, 0);
|
||||
}
|
||||
}
|
||||
@@ -171,6 +171,7 @@ pub mod face;
|
||||
pub mod fetched;
|
||||
pub mod footprint;
|
||||
pub mod heap_raw;
|
||||
pub mod in_place;
|
||||
pub mod level;
|
||||
pub mod linear;
|
||||
mod native;
|
||||
@@ -1705,6 +1706,7 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> {
|
||||
level_views: None,
|
||||
extended: None,
|
||||
x_channel: false,
|
||||
in_place: false,
|
||||
};
|
||||
let symbol = ResourceSlot {
|
||||
stage: cx.stage,
|
||||
|
||||
@@ -1045,6 +1045,9 @@ fn select_slot(
|
||||
}
|
||||
_ => sampler,
|
||||
};
|
||||
if let Some(sample) = select_in_place(cx, call, index, &sampler, arm)? {
|
||||
return Ok(TextureStrategy::InPlaceSample(Box::new(sample)));
|
||||
}
|
||||
match crate::lower::texture::extended_range(cx, ImageRef::Slot(index))? {
|
||||
Some(form) => select_extended(cx, call, (index, form), sampler, m),
|
||||
None => select_one(cx, call, ImageRef::Slot(index), sampler, arm, m)
|
||||
@@ -1052,6 +1055,168 @@ fn select_slot(
|
||||
}
|
||||
}
|
||||
|
||||
/// Observe sampling call `call` of texture slot `index` through `sampler` for the slot's in-place
|
||||
/// form (`slot::InPlaceReads`), and where the slot's variant reads a two-plane YCbCr texture's
|
||||
/// planes in place (`LoweringInputs::ycbcr_in_place`) select the form's sample
|
||||
/// ([`in_place_sample`]); else `None`, and the slot's other forms sample it. A call the form does
|
||||
/// not read keeps the slot from it, so its variant never meets one.
|
||||
fn select_in_place(
|
||||
cx: &mut SelectCx<'_>,
|
||||
call: Call<'_>,
|
||||
index: u32,
|
||||
sampler: &SamplerArg,
|
||||
arm: Option<bool>,
|
||||
) -> Result<Option<super::in_place::Sample>, Error> {
|
||||
let variant = crate::lower::texture::ycbcr_in_place(cx, index)?;
|
||||
let Some((sample, samplers)) = in_place_sample(cx, call, index, sampler, arm)? else {
|
||||
crate::lower::texture::not_in_place(cx, index);
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(s) = cx.families.texture.slots.get_mut(&index) else {
|
||||
return Err(cx.invariant("an unplanned texture slot"));
|
||||
};
|
||||
s.in_place.samplers |= samplers;
|
||||
if !variant {
|
||||
return Ok(None);
|
||||
}
|
||||
// The slot's planes are fetched, as a read fetches texels.
|
||||
s.observe(call.t.image, Some(TexelClass::Float))?;
|
||||
s.uses.read = true;
|
||||
s.offset_base |= sample.offset_base;
|
||||
// A runtime sampler's word states the filter, the coordinates, the address modes and the
|
||||
// border color.
|
||||
if let super::extended::State::Slot { sampler: n } = sample.state {
|
||||
let Some(r) = cx.families.sampler.slots.get_mut(&n) else {
|
||||
return Err(cx.invariant("an unplanned sampler slot"));
|
||||
};
|
||||
r.linear = true;
|
||||
}
|
||||
if !matches!(
|
||||
sample.state,
|
||||
super::extended::State::Constant { linear: false, .. }
|
||||
) {
|
||||
cx.families
|
||||
.sampler
|
||||
.bicubic_routines
|
||||
.insert(super::bicubic::routines::Routine::Quad);
|
||||
}
|
||||
Ok(Some(sample))
|
||||
}
|
||||
|
||||
/// Sampling call `call` of texture slot `index` through `sampler` as the in-place form reads it
|
||||
/// (`in_place`), with the runtime sampler slots it reads (bit `n` `[[sampler(n)]]`); `None` where
|
||||
/// the form does not: anything but a 2D texture's sample or gradient sample without comparison,
|
||||
/// with a `float` or `half` result, a constant texel offset or none, no `min_lod_clamp`, and no
|
||||
/// status word observed, through a constexpr sampler of one filter for minification and
|
||||
/// magnification (nearest or linear), no anisotropy and the weighted-average reduction, or a
|
||||
/// runtime sampler slot, whose bound word the binder holds to the same
|
||||
/// (`bind::plan::slots::in_place_word`); and not an arm of a switch-at-use. Metal's sample reads
|
||||
/// the texture's one level whatever the mip filter, the level, the bias or the gradients, so the
|
||||
/// form reads none of them.
|
||||
fn in_place_sample(
|
||||
cx: &mut SelectCx<'_>,
|
||||
call: Call<'_>,
|
||||
index: u32,
|
||||
sampler: &SamplerArg,
|
||||
arm: Option<bool>,
|
||||
) -> Result<Option<(super::in_place::Sample, u32)>, Error> {
|
||||
use super::bicubic::TapAddress;
|
||||
use super::extended::State;
|
||||
let Call { at, inst, t, args } = call;
|
||||
let ops = Operands { t, args };
|
||||
let shape = t.image;
|
||||
if arm.is_some() || shape.dim != ImageDim::D2 || shape.array || shape.ms || shape.depth {
|
||||
return Ok(None);
|
||||
}
|
||||
let has_offset = match t.op {
|
||||
TexOp::Sample {
|
||||
compare: false,
|
||||
offset,
|
||||
..
|
||||
}
|
||||
| TexOp::SampleGrad {
|
||||
compare: false,
|
||||
offset,
|
||||
} => offset,
|
||||
_ => return Ok(None),
|
||||
};
|
||||
if clamp_value(cx, &ops)?.is_some() || crate::lower::texture::observes_status(cx, at) {
|
||||
return Ok(None);
|
||||
}
|
||||
let offset = match fetch_offset(cx, &ops, has_offset, 2)? {
|
||||
None => None,
|
||||
Some(Offset::Const(k)) => Some(k),
|
||||
Some(Offset::Dynamic(..)) => return Ok(None),
|
||||
};
|
||||
let Ok((form, _)) = texel(t, 4) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let half = match form.conv {
|
||||
TexelConv::F16 => true,
|
||||
TexelConv::F32 => false,
|
||||
_ => return Ok(None),
|
||||
};
|
||||
let (state, samplers) = match *sampler {
|
||||
SamplerArg::Static(SamplerRef::Constexpr(words), _) => {
|
||||
let s = super::state_of(words)?;
|
||||
let linear = match (s.min_filter, s.mag_filter) {
|
||||
(Filter::Linear, Filter::Linear) => true,
|
||||
(Filter::Nearest, Filter::Nearest) => false,
|
||||
_ => return Ok(None),
|
||||
};
|
||||
if s.max_anisotropy > 1 || s.reduction != crate::air::abi::Reduction::WeightedAverage {
|
||||
return Ok(None);
|
||||
}
|
||||
let address = [s.address_s, s.address_t]
|
||||
.into_iter()
|
||||
.map(|m| match m {
|
||||
AddressMode::ClampToEdge => TapAddress::Edge,
|
||||
AddressMode::Repeat => TapAddress::Repeat,
|
||||
AddressMode::MirroredRepeat => TapAddress::Mirror,
|
||||
AddressMode::ClampToZero | AddressMode::ClampToBorder => TapAddress::Border,
|
||||
})
|
||||
.collect();
|
||||
let state = State::Constant {
|
||||
linear,
|
||||
address,
|
||||
border: s.border_color,
|
||||
pixel: s.coordinates == Coordinates::Pixel,
|
||||
};
|
||||
(state, 0)
|
||||
}
|
||||
SamplerArg::Static(SamplerRef::Slot(n), _) if n < 32 => {
|
||||
(State::Slot { sampler: n }, 1 << n)
|
||||
}
|
||||
_ => return Ok(None),
|
||||
};
|
||||
// An offset on an axis that may repeat or mirror is placed by Metal's rule, which reads a
|
||||
// view's parent's base-level size: the slot's `OffsetBaseAxes` states where it differs.
|
||||
let offset_base = offset.as_deref().is_some_and(|o| {
|
||||
o.iter().enumerate().any(|(a, k)| {
|
||||
*k != 0
|
||||
&& match &state {
|
||||
State::Constant { address, .. } => address
|
||||
.get(a)
|
||||
.is_some_and(|m| matches!(m, TapAddress::Repeat | TapAddress::Mirror)),
|
||||
State::Slot { .. } => true,
|
||||
}
|
||||
})
|
||||
});
|
||||
let coord = ops
|
||||
.get(TexRole::Coord)
|
||||
.ok_or_else(|| cx.invariant("a sampling call without a coordinate"))?;
|
||||
let sample = super::in_place::Sample {
|
||||
texture: index,
|
||||
state,
|
||||
offset,
|
||||
offset_base,
|
||||
coord: id(cx, coord)?,
|
||||
half,
|
||||
result: cx.lowered_repr(Value::Inst(at), inst.ty)?,
|
||||
};
|
||||
Ok(Some((sample, samplers)))
|
||||
}
|
||||
|
||||
/// Select sampling call `call` of texture slot `index`, whose variant binds the extended-range
|
||||
/// format `form`, through `sampler`: Metal's nearest or linear filter of the decoded texels,
|
||||
/// emulated by fetches of the raw texels on every device (`extended`). Built: a 2D or 2D array
|
||||
|
||||
@@ -80,6 +80,7 @@ fn value(
|
||||
return Ok(None);
|
||||
}
|
||||
TextureStrategy::ExtendedSample(e) => crate::lower::sampler::extended::emit(cx, fb, e)?,
|
||||
TextureStrategy::InPlaceSample(e) => crate::lower::sampler::in_place::emit(cx, fb, e)?,
|
||||
TextureStrategy::AbsentArgument(a) => {
|
||||
if a.marks {
|
||||
crate::lower::access::absent::mark(cx, fb)?;
|
||||
@@ -4479,6 +4480,9 @@ fn query_value(
|
||||
q: &QueryOp,
|
||||
(decl, img, storage): (&ImageDecl, SValue, bool),
|
||||
) -> BResult<SValue> {
|
||||
if decl.in_place {
|
||||
return in_place_query(cx, fb, q);
|
||||
}
|
||||
let sampled_mips =
|
||||
decl.usage == ImageUsage::Sampled && !decl.multisampled && decl.dim != Dim::Buffer;
|
||||
let n = coord_len(decl);
|
||||
@@ -4572,6 +4576,36 @@ fn query_value(
|
||||
})
|
||||
}
|
||||
|
||||
/// The answer of query `q` of a slot under its in-place variant (`sampler::in_place`): its
|
||||
/// texture's width or height from the slot's push field, at a level as at any texture's
|
||||
/// ([`level_extent`]), and its one level.
|
||||
fn in_place_query(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
q: &QueryOp,
|
||||
) -> BResult<SValue> {
|
||||
let ImageRef::Slot(index) = q.image else {
|
||||
return Err(cx.fail("an in-place query of a heap element"));
|
||||
};
|
||||
let Some(slot) = cx.plan.families.texture.slots.get(&index).map(|s| s.slot) else {
|
||||
return Err(cx.fail(format!("texture slot {index} is not planned")));
|
||||
};
|
||||
match q.kind {
|
||||
QueryKind::Size { component } => {
|
||||
let e = crate::lower::sampler::in_place::extent(cx, fb, slot, component)?;
|
||||
match q.level {
|
||||
Some(l) => {
|
||||
let l = cx.operand(fb, l)?;
|
||||
level_extent(fb, e, l)
|
||||
}
|
||||
None => Ok(e),
|
||||
}
|
||||
}
|
||||
QueryKind::Levels => u32s(fb, 1, 1),
|
||||
_ => Err(cx.fail("an in-place query the form does not answer")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The extent Metal answers at level `l` of a texture whose first level's extent is `e`:
|
||||
/// `max(1, e >> (l & 255))`, at every level, past the texture's level count too, a shift of 32 or
|
||||
/// more answering 1. Measured on an Apple M3 Max under macOS 27.0.1: the width, height, and depth
|
||||
|
||||
@@ -643,6 +643,9 @@ pub enum TextureStrategy {
|
||||
/// A sample of a texture slot bound in an extended-range format, emulated by fetches of its
|
||||
/// raw texels (`sampler::extended`).
|
||||
ExtendedSample(Box<crate::lower::sampler::extended::Sample>),
|
||||
/// A sample of a two-plane YCbCr texture slot whose variant reads its planes in place,
|
||||
/// computed from their codes (`sampler::in_place`).
|
||||
InPlaceSample(Box<crate::lower::sampler::in_place::Sample>),
|
||||
/// An operation on the absent handle: a texture or sampler a function constant removed
|
||||
/// (`memory::handles::Candidate::Absent`).
|
||||
AbsentArgument(AbsentArgument),
|
||||
@@ -900,6 +903,7 @@ impl TextureStrategy {
|
||||
TextureStrategy::ImageblockSlice(s) if s.guard => "texture.imageblock_slice_guarded",
|
||||
TextureStrategy::ImageblockSlice(_) => "texture.imageblock_slice",
|
||||
TextureStrategy::ExtendedSample(e) => e.name(),
|
||||
TextureStrategy::InPlaceSample(e) => e.name(),
|
||||
TextureStrategy::AbsentArgument(_) => AbsentArgument::NAME,
|
||||
})
|
||||
}
|
||||
@@ -967,6 +971,7 @@ impl TextureStrategy {
|
||||
TextureStrategy::Switch(s) => s.words(),
|
||||
TextureStrategy::ImageblockSlice(s) => s.words(),
|
||||
TextureStrategy::ExtendedSample(e) => e.words(),
|
||||
TextureStrategy::InPlaceSample(e) => e.words(),
|
||||
// `access::absent::AbsentRead`'s status write, and the zero, a constant.
|
||||
TextureStrategy::AbsentArgument(a) => {
|
||||
if a.marks {
|
||||
@@ -2483,6 +2488,7 @@ pub fn select(
|
||||
_ => Vec::new(),
|
||||
};
|
||||
for index in slots {
|
||||
not_in_place(cx, index);
|
||||
if extended_range(cx, ImageRef::Slot(index))?.is_some() {
|
||||
return Err(Unsupported::not_implemented(Feature::Format).into());
|
||||
}
|
||||
@@ -2524,7 +2530,9 @@ pub fn select(
|
||||
let mut arms = Vec::with_capacity(cands.len());
|
||||
for c in cands {
|
||||
let arm = match c {
|
||||
// A switch-at-use's arm reads its slot's image.
|
||||
Candidate::Texture(index) => {
|
||||
not_in_place(cx, index);
|
||||
select_image(cx, (at, inst), t, &ops, ImageRef::Slot(index), m)?
|
||||
}
|
||||
Candidate::Absent => AbsentArgument::select(cx, at, inst, t)?,
|
||||
@@ -3112,6 +3120,26 @@ pub(crate) fn extended_range(
|
||||
Ok(cx.inputs.extended_range.get(&slot).copied())
|
||||
}
|
||||
|
||||
/// Whether texture slot `index`'s variant reads a two-plane YCbCr texture's planes in place
|
||||
/// (`LoweringInputs::ycbcr_in_place`, `sampler::in_place`).
|
||||
pub(crate) fn ycbcr_in_place(cx: &SelectCx<'_>, index: u32) -> Result<bool, Error> {
|
||||
let slot = slot_of(cx, index)?.slot;
|
||||
Ok(cx.inputs.ycbcr_in_place.contains(&slot))
|
||||
}
|
||||
|
||||
/// Record an access of texture slot `index` that its in-place form does not read
|
||||
/// (`slot::InPlaceReads::blocked`): no texture is read in place there.
|
||||
pub(crate) fn not_in_place(cx: &mut SelectCx<'_>, index: u32) {
|
||||
if let Some(s) = cx.families.texture.slots.get_mut(&index) {
|
||||
s.in_place.blocked = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the function observes any of texture call `at`'s status word.
|
||||
pub(crate) fn observes_status(cx: &mut SelectCx<'_>, at: InstId) -> bool {
|
||||
status_use(cx, at).is_some()
|
||||
}
|
||||
|
||||
/// The numeric class of the texture texture slot `image`'s variant binds where it is not the
|
||||
/// class the function declares there (`LoweringInputs::cross_class`), else `None`: the slot's
|
||||
/// image is declared of that class (`slot::image_class`), and its reads, samples and gathers take
|
||||
@@ -3282,6 +3310,15 @@ fn select_image(
|
||||
m: &mut Meter,
|
||||
) -> Result<TextureStrategy, Error> {
|
||||
let shape = t.image;
|
||||
// The in-place form reads a slot's width, height and level count, and nothing else here.
|
||||
if let ImageRef::Slot(index) = image {
|
||||
if !matches!(
|
||||
t.op,
|
||||
TexOp::Query(Query::Width | Query::Height | Query::NumMipLevels)
|
||||
) {
|
||||
not_in_place(cx, index);
|
||||
}
|
||||
}
|
||||
let texel = match t.texel {
|
||||
Some(x) if matches!(t.op, TexOp::Read | TexOp::Write | TexOp::Atomic(_)) => Some(
|
||||
image_texel_conv(x.ty.elem, x.sign, cx.profile).map(|(c, class)| {
|
||||
|
||||
@@ -96,6 +96,17 @@ pub struct Uses {
|
||||
pub narrow_result: bool,
|
||||
}
|
||||
|
||||
/// How a slot's accesses read a two-plane YCbCr texture bound there, for its planes read in
|
||||
/// place (`sampler::in_place`, `RuntimeFact::YCbCrInPlace`).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub struct InPlaceReads {
|
||||
/// An access the form does not read: anything but a sample it builds (`sampler::select`'s
|
||||
/// `in_place_sample`) and a query of the width, the height or the level count.
|
||||
pub blocked: bool,
|
||||
/// The runtime sampler slots the slot's samples read, bit `n` `[[sampler(n)]]`.
|
||||
pub samplers: u32,
|
||||
}
|
||||
|
||||
/// The `OpTypeImage` a slot is declared as, and the conversion a storage image's class needs.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct ImageDecl {
|
||||
@@ -121,6 +132,10 @@ pub struct ImageDecl {
|
||||
/// after the class's conversion, its reads take alpha 1 and its writes store green in the
|
||||
/// fourth channel.
|
||||
pub x_channel: bool,
|
||||
/// The slot's variant reads a two-plane YCbCr texture's planes in place
|
||||
/// (`LoweringInputs::ycbcr_in_place`): the image is the planes' uniform texel buffer of
|
||||
/// unsigned codes (`sampler::in_place`), the texture's size its push field's.
|
||||
pub in_place: bool,
|
||||
}
|
||||
|
||||
impl ImageDecl {
|
||||
@@ -253,6 +268,8 @@ pub struct SlotPlan {
|
||||
/// specialization, which states the axes on which the base-level size the rule reads, a
|
||||
/// view's parent's, is not a power of two where the bound view's is.
|
||||
pub offset_base: bool,
|
||||
/// How its accesses read a two-plane YCbCr texture's planes in place.
|
||||
pub in_place: InPlaceReads,
|
||||
/// The declaration, set by [`finish`] for a slot that is read, written, or queried, or
|
||||
/// whose faces are fetched.
|
||||
pub decl: Option<ImageDecl>,
|
||||
@@ -285,6 +302,7 @@ impl SlotPlan {
|
||||
swizzle: false,
|
||||
constant_lanes: false,
|
||||
offset_base: false,
|
||||
in_place: InPlaceReads::default(),
|
||||
decl: None,
|
||||
}
|
||||
}
|
||||
@@ -584,6 +602,7 @@ fn declare_heap(
|
||||
level_views: None,
|
||||
extended: None,
|
||||
x_channel: false,
|
||||
in_place: false,
|
||||
};
|
||||
Ok((class, decl))
|
||||
}
|
||||
@@ -1031,6 +1050,27 @@ fn declare_slot(
|
||||
) -> Result<ImageDecl, Error> {
|
||||
let images = &cx.profile.fields().images;
|
||||
let storage = s.storage();
|
||||
// A slot under its in-place variant is the uniform texel buffer of its texture's planes, of
|
||||
// unsigned codes, with the field of their words (`sampler::in_place`).
|
||||
if cx.inputs.ycbcr_in_place.contains(&s.slot) {
|
||||
push.push(PushField::YCbCrInPlace(s.slot));
|
||||
counts.sampled_images = counts.sampled_images.saturating_add(1);
|
||||
return Ok(ImageDecl {
|
||||
dim: Dim::Buffer,
|
||||
arrayed: false,
|
||||
multisampled: false,
|
||||
depth: false,
|
||||
usage: ImageUsage::Sampled,
|
||||
format: crate::spv::ImageFormat::Unknown,
|
||||
texel: TexelClass::Uint,
|
||||
cube_as_array: false,
|
||||
class: StorageImageClass::Identity,
|
||||
level_views: None,
|
||||
extended: None,
|
||||
x_channel: false,
|
||||
in_place: true,
|
||||
});
|
||||
}
|
||||
// A slot bound in an extended-range format holds its raw texels in an unsigned integer
|
||||
// image.
|
||||
let extended = cx.inputs.extended_range.get(&s.slot).copied();
|
||||
@@ -1166,9 +1206,25 @@ fn declare_slot(
|
||||
level_views: views,
|
||||
extended,
|
||||
x_channel,
|
||||
in_place: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether every access of slot `s` is one its texture's planes read in place answer
|
||||
/// (`sampler::in_place`), on a profile that takes the form (`ProfileFields::ycbcr_in_place`): a
|
||||
/// sampled 2D texture's (not an array, multisampled or depth one), of a `float` class or only
|
||||
/// queried, used, and no access blocked ([`InPlaceReads::blocked`]).
|
||||
fn in_place_reads(cx: &SelectCx<'_>, s: &SlotPlan) -> bool {
|
||||
let used = s.uses.read || s.uses.query || s.uses.sample;
|
||||
cx.profile.fields().ycbcr_in_place
|
||||
&& used
|
||||
&& !s.in_place.blocked
|
||||
&& !s.storage()
|
||||
&& s.shape
|
||||
.is_some_and(|x| x.dim == ImageDim::D2 && !x.array && !x.ms && !x.depth)
|
||||
&& matches!(s.texel, None | Some(TexelClass::Float))
|
||||
}
|
||||
|
||||
/// Whether a slot of `shape` can have a tile map: a single-sample 2D, 2D array, or 3D color texture
|
||||
/// (`bind::SparseTileMap`), the sparse types the case model measures.
|
||||
fn tiled_shape(shape: ImageShape) -> bool {
|
||||
@@ -1246,6 +1302,22 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> {
|
||||
facts.push(RuntimeFact::CrossClassReads { slot: s.slot });
|
||||
}
|
||||
}
|
||||
// The slots whose every access the in-place form reads, on a profile that takes it: their
|
||||
// compile under the form states the same, which its plan holds to.
|
||||
for s in cx.families.texture.slots.values() {
|
||||
let reads = in_place_reads(cx, s);
|
||||
if !reads && cx.inputs.ycbcr_in_place.contains(&s.slot) {
|
||||
return Err(
|
||||
cx.invariant("an in-place texture slot whose accesses the form does not read")
|
||||
);
|
||||
}
|
||||
if reads {
|
||||
facts.push(RuntimeFact::YCbCrInPlace {
|
||||
slot: s.slot,
|
||||
samplers: s.in_place.samplers,
|
||||
});
|
||||
}
|
||||
}
|
||||
let mut heap = Vec::new();
|
||||
for (group, h) in &cx.families.texture.heap {
|
||||
let used = h.uses.read || h.uses.write || h.uses.query || h.uses.sample;
|
||||
|
||||
@@ -200,6 +200,7 @@ mod serde_round_trips {
|
||||
srgb_textures: BTreeSet::from([slot(Stage::Kernel, SlotClass::Texture, 4)]),
|
||||
srgb_twins: BTreeSet::from([slot(Stage::Kernel, SlotClass::Texture, 4)]),
|
||||
ycbcr_textures: BTreeSet::from([slot(Stage::Kernel, SlotClass::Texture, 6)]),
|
||||
ycbcr_in_place: BTreeSet::from([slot(Stage::Kernel, SlotClass::Texture, 7)]),
|
||||
flat_grid: true,
|
||||
replay_bindings: true,
|
||||
merged_draws: true,
|
||||
@@ -336,6 +337,7 @@ mod serde_round_trips {
|
||||
crate::pipeline::SnapshotForm::Half,
|
||||
)]),
|
||||
ycbcr_textures: BTreeSet::from([slot(Stage::Fragment, SlotClass::Texture, 8)]),
|
||||
ycbcr_in_place: BTreeSet::from([slot(Stage::Fragment, SlotClass::Texture, 9)]),
|
||||
viewport_index_varying: true,
|
||||
// An emulated post-tessellation vertex function's state.
|
||||
tessellation: Some(crate::pipeline::TessellationDescriptor {
|
||||
|
||||
@@ -219,6 +219,11 @@ pub fn function_key(
|
||||
.bytes(format!("{:?}", inputs.ycbcr_textures).as_bytes());
|
||||
}
|
||||
// Appended only when set, as `storage_view_slots`.
|
||||
if !inputs.ycbcr_in_place.is_empty() {
|
||||
h.bytes(b"ycbcr-in-place")
|
||||
.bytes(format!("{:?}", inputs.ycbcr_in_place).as_bytes());
|
||||
}
|
||||
// Appended only when set, as `storage_view_slots`.
|
||||
if !inputs.extended_range.is_empty() {
|
||||
h.bytes(b"extended-range")
|
||||
.bytes(format!("{:?}", inputs.extended_range).as_bytes());
|
||||
|
||||
@@ -709,6 +709,7 @@ fn the_inputs_encoding_is_the_earlier_derived_debug() {
|
||||
.replace(", srgb_twins: {}", "")
|
||||
.replace(", snapshot_textures: {}", "")
|
||||
.replace(", ycbcr_textures: {}", "")
|
||||
.replace(", ycbcr_in_place: {}", "")
|
||||
.replace(", viewport_index_varying: false", "")
|
||||
.replace(", max_call_stack_depth: None", "")
|
||||
.replace(", flat_grid: false", "")
|
||||
|
||||
@@ -828,6 +828,20 @@ pub enum RuntimeFact {
|
||||
/// `PushHole::CaptureIndexAddress`, each list position run once. Its plans state the variant
|
||||
/// the shape asks for (`BindShape::private_list`).
|
||||
PrivateList,
|
||||
/// The function reads the texture bound to the slot only as the in-place form of a two-plane
|
||||
/// YCbCr texture reads it (`bind::YCbCrInPlace`): sampled through a constexpr sampler or
|
||||
/// through the runtime sampler slots whose bits `samplers` holds (bit `n` for
|
||||
/// `[[sampler(n)]]` of the slot's stage), read, or its size queried, as a 2D `float` texture.
|
||||
/// Recorded on a profile that reads planes in place (`ProfileFields::ycbcr_in_place`). Where
|
||||
/// the binder binds a texture whose planes are read so (`TextureShape::Texture::ycbcr_in_place`)
|
||||
/// and each of those samplers states a filter the form reads (one filter for minification and
|
||||
/// magnification, no anisotropy, no cubic filter, comparison or reduction), the slot joins the
|
||||
/// plan's variant (`VariantKey::ycbcr_in_place`, `LoweringInputs::ycbcr_in_place`), under
|
||||
/// which the slot's one binding is the planes' texel buffer (`WriteSource::YCbCrInPlace`) and
|
||||
/// every access of it reads the codes and converts them as Metal does, its words in the slot's
|
||||
/// push field (`PushField::YCbCrInPlace`). Elsewhere the slot binds the texture's image as
|
||||
/// before.
|
||||
YCbCrInPlace { slot: SlotRef, samplers: u32 },
|
||||
}
|
||||
|
||||
/// What one compile made of a slot of a `RuntimeFact::UniformViewRange`.
|
||||
|
||||
@@ -179,6 +179,13 @@ pub struct LoweringInputs {
|
||||
/// Ignored on any other profile, and for a slot of no such sample.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub ycbcr_textures: BTreeSet<SlotRef>,
|
||||
/// Texture slots bound to a two-plane YCbCr texture whose planes are read in place
|
||||
/// (`VariantKey::ycbcr_in_place`, `RuntimeFact::YCbCrInPlace`): each is declared as the
|
||||
/// planes' uniform texel buffer, and its samples, reads and size queries read the codes and
|
||||
/// convert them as Metal does (`bind::YCbCrInPlace`). Ignored on a profile that does not read
|
||||
/// planes in place (`ProfileFields::ycbcr_in_place`).
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub ycbcr_in_place: BTreeSet<SlotRef>,
|
||||
/// The fragment function's render pipeline has a vertex function that writes
|
||||
/// `[[viewport_array_index]]`. That function stores `ViewportIndex` as 0 for an index at or
|
||||
/// past the draw's viewport count, where Metal draws through viewport 0 and its fragment
|
||||
|
||||
@@ -1169,6 +1169,12 @@ pub enum PushField {
|
||||
/// `BindState::alpha_test_reference`), which the function compares its color 0's alpha's code
|
||||
/// with.
|
||||
AlphaTestReference,
|
||||
/// The planes of the two-plane YCbCr texture bound to the slot, read in place
|
||||
/// (`RuntimeFact::YCbCrInPlace`, `LoweringInputs::ycbcr_in_place`): two `uvec4`s, the
|
||||
/// texture's size, its planes' first elements and rows in the slot's texel buffer, and its
|
||||
/// conversion (`bind::YCbCrInPlace::words`), from the bound texture's facts
|
||||
/// (`TextureFacts::ycbcr_in_place`).
|
||||
YCbCrInPlace(SlotRef),
|
||||
/// The value a draw or dispatch binds for specialization key `key`, carried as data rather
|
||||
/// than specialized: one `u32` holding exactly the value the binder computes for the key's
|
||||
/// specialization constant from the bound textures and samplers (a boolean key as 1 or 0; a
|
||||
|
||||
@@ -42,6 +42,7 @@ use crate::pipeline::PrecisionNote;
|
||||
use crate::spirv::interp::{run_with_images, Buffer, Config, Image, Order, Resources};
|
||||
use crate::spirv::ir::{GlobalKind, TypedModule};
|
||||
|
||||
mod in_place;
|
||||
mod levels;
|
||||
mod packed;
|
||||
mod ycbcr;
|
||||
|
||||
@@ -0,0 +1,446 @@
|
||||
//! A two-plane YCbCr texture's planes read in place (`lower::sampler::in_place`), on the CPU
|
||||
//! interpreter against Metal's texels and Metal's filter of them, bit for bit.
|
||||
//!
|
||||
//! The slot under its in-place variant (`LoweringInputs::ycbcr_in_place`) is a uniform texel
|
||||
//! buffer of the planes' codes (`R8G8_UINT` elements of 8-bit codes, `R16G16_UINT` ones of 10-bit
|
||||
//! codes, each 10-bit code the high bits of its word over junk low bits), and its push field
|
||||
//! states the texture's size, its planes' places and rows, and its conversion
|
||||
//! (`bind::YCbCrInPlace::words`). Each texel the samples read is Metal's (`ycbcr_convert`'s module
|
||||
//! docs: the luma code, the chroma pairs' 9/3/3/1 filter, the range's and the matrix's
|
||||
//! conversion), and a linear sample is Metal's filter of those steps on the grid `2048`
|
||||
//! (`super::ycbcr`'s rule); a nearest sample is the texel at Metal's position. The texel buffer
|
||||
//! traps every fetch outside it, so each tap's elements lie within the planes.
|
||||
|
||||
use super::ycbcr::{metal_step, result_bits};
|
||||
use super::*;
|
||||
use crate::bind::ycbcr_convert::{ycbcr_read, YCbCrCodes, YCbCrMatrix, YCbCrPlanes, YCbCrRange};
|
||||
use crate::bind::YCbCrInPlace;
|
||||
use crate::lower::select::LowerInputs;
|
||||
use crate::metal::format::ycbcr_format;
|
||||
use crate::pipeline::facts::RuntimeFact;
|
||||
use crate::pipeline::testing::{compile_with, typed_module_with};
|
||||
|
||||
/// The texture's width and height: odd, so the chroma plane's last pair serves one column and one
|
||||
/// row alone.
|
||||
const W: u32 = 7;
|
||||
const H: u32 = 5;
|
||||
|
||||
/// Lowering inputs with texture slot 0 under its in-place variant, or none.
|
||||
fn inputs(in_place: bool) -> LowerInputs {
|
||||
let mut i = LowerInputs::new();
|
||||
if in_place {
|
||||
i.ycbcr_in_place.insert(TEXTURE);
|
||||
}
|
||||
i
|
||||
}
|
||||
|
||||
/// One texture's planes: their codes by texel, where they lie, and the texel buffer's elements.
|
||||
struct Planes {
|
||||
planes: YCbCrPlanes,
|
||||
words: YCbCrInPlace,
|
||||
/// Each element's two lanes, as the texel buffer's format reads them.
|
||||
elements: Vec<[u32; 2]>,
|
||||
luma: Vec<u16>,
|
||||
chroma: Vec<[u16; 2]>,
|
||||
}
|
||||
|
||||
impl Planes {
|
||||
/// Random planes of `pf` (`YCBCR8_420_2P` or `YCBCR10_420_2P`) under `conversion`: the chroma
|
||||
/// plane first, three elements in, then the luma plane, each row padded past its codes.
|
||||
fn random(pf: PixelFormat, conversion: (YCbCrRange, YCbCrMatrix), rng: &mut Lcg) -> Planes {
|
||||
let codes = ycbcr_format(pf).and_then(YCbCrCodes::of).expect("codes");
|
||||
let unit = codes.bytes;
|
||||
let element = 2 * unit;
|
||||
let [cw, ch] = [W.div_ceil(2), H.div_ceil(2)];
|
||||
let chroma = [3 * element, (cw + 2) * element];
|
||||
let luma_at = (chroma[0] + ch * chroma[1]).next_multiple_of(element) + element;
|
||||
let luma = [luma_at, (W.div_ceil(2) + 1) * element];
|
||||
let planes = YCbCrPlanes::new([W, H], luma, chroma, conversion, codes);
|
||||
let words = YCbCrInPlace::of(&planes).expect("in place");
|
||||
let max = (1u64 << codes.bits) - 1;
|
||||
let mut code = || (rng.next() % (max + 1)) as u16;
|
||||
let luma_codes: Vec<u16> = (0..W * H).map(|_| code()).collect();
|
||||
let chroma_codes: Vec<[u16; 2]> = (0..cw * ch).map(|_| [code(), code()]).collect();
|
||||
// Every lane a junk value, then each code's place written: a 10-bit code is the high bits
|
||||
// of its 16-bit word.
|
||||
let n = words.elements() as usize;
|
||||
let mut lanes: Vec<u32> = (0..2 * n)
|
||||
.map(|_| (rng.next() % (1 << (8 * unit))) as u32)
|
||||
.collect();
|
||||
let shift = 8 * unit - codes.bits;
|
||||
let mut put = |byte: u32, code: u16, junk: u64| {
|
||||
let lane = (byte / unit) as usize;
|
||||
lanes[lane] = (u32::from(code) << shift) | (junk as u32 & ((1 << shift) - 1));
|
||||
};
|
||||
for y in 0..H {
|
||||
for x in 0..W {
|
||||
let c = luma_codes[(y * W + x) as usize];
|
||||
put(luma[0] + y * luma[1] + x * unit, c, rng.next());
|
||||
}
|
||||
}
|
||||
for y in 0..ch {
|
||||
for x in 0..cw {
|
||||
let [cb, cr] = chroma_codes[(y * cw + x) as usize];
|
||||
let at = chroma[0] + y * chroma[1] + 2 * x * unit;
|
||||
put(at, cb, rng.next());
|
||||
put(at + unit, cr, rng.next());
|
||||
}
|
||||
}
|
||||
let elements = lanes.as_chunks::<2>().0.to_vec();
|
||||
Planes {
|
||||
planes,
|
||||
words,
|
||||
elements,
|
||||
luma: luma_codes,
|
||||
chroma: chroma_codes,
|
||||
}
|
||||
}
|
||||
|
||||
/// Metal's texel `(x, y)`: each channel's step on the grid `2048`.
|
||||
fn texel(&self, x: i64, y: i64) -> [i64; 3] {
|
||||
let [cw, ch] = [W.div_ceil(2), H.div_ceil(2)].map(i64::from);
|
||||
// An axis's chroma texels weighted 3 and 1: its own, and the one after it for an odd
|
||||
// index, before it for an even one, clamped to the plane.
|
||||
let taps = |q: i64, n: i64| -> [(i64, u32); 2] {
|
||||
let own = q / 2;
|
||||
let other = if q % 2 == 1 { own + 1 } else { own - 1 };
|
||||
[(own, 3), (other.clamp(0, n - 1), 1)]
|
||||
};
|
||||
let mut sums = [0u32; 2];
|
||||
for (cy, wy) in taps(y, ch) {
|
||||
for (cx, wx) in taps(x, cw) {
|
||||
let pair = self.chroma[(cy * cw + cx) as usize];
|
||||
for (sum, c) in sums.iter_mut().zip(pair) {
|
||||
*sum += wx * wy * u32::from(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
let [cb, cr] = sums.map(|s| ((s + 8) >> 4) as u16);
|
||||
let luma = self.luma[(y * i64::from(W) + x) as usize];
|
||||
let p = &self.planes;
|
||||
ycbcr_read(p.codes, (p.range, p.matrix), [luma, cb, cr]).map(i64::from)
|
||||
}
|
||||
|
||||
/// The texel buffer bound at `slot`.
|
||||
fn image(&self, slot: ResourceSlot) -> Image {
|
||||
let n = self.elements.len() as u32;
|
||||
let mut image = Image::new(slot, [n, 1, 1], 1, 1, 1);
|
||||
for (x, [a, b]) in (0u32..).zip(&self.elements) {
|
||||
let i = image.index(0, 0, 0, [x, 0, 0]).expect("element");
|
||||
image.texels[i] = [*a, *b, 0, 1];
|
||||
}
|
||||
image
|
||||
}
|
||||
}
|
||||
|
||||
/// The texel buffer binding a module declares for texture slot 0.
|
||||
fn texel_buffer(m: &TypedModule) -> ResourceSlot {
|
||||
m.globals()
|
||||
.iter()
|
||||
.find_map(|g| match g.kind {
|
||||
GlobalKind::Resource(
|
||||
s @ ResourceSlot {
|
||||
kind: ResourceKind::Texture,
|
||||
index: 0,
|
||||
..
|
||||
},
|
||||
) => Some(s),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the planes' binding")
|
||||
}
|
||||
|
||||
/// Resources of a dispatch of one-thread threadgroups: `[[buffer(i)]]` holding `init[i]`, and
|
||||
/// the slot's push field holding `words`.
|
||||
fn resources(plan: &Plan, init: &[Vec<u8>], words: &YCbCrInPlace) -> Resources {
|
||||
let mut spec = BTreeMap::new();
|
||||
for axis in [Axis::X, Axis::Y, Axis::Z] {
|
||||
spec.insert(SpecKey::LocalSize(axis), 1);
|
||||
}
|
||||
spec.insert(SpecKey::FlatLocalSize, 1);
|
||||
let mut push = vec![0u8; plan.push.push_range.map_or(0, |(_, end)| end as usize)];
|
||||
let mut written = false;
|
||||
for f in &plan.push.fields {
|
||||
match (f.field, f.loc) {
|
||||
(PushField::YCbCrInPlace(TEXTURE), PushLoc::Push { offset }) => {
|
||||
let at = offset as usize;
|
||||
for (i, w) in words.words().into_iter().enumerate() {
|
||||
push[at + 4 * i..at + 4 * i + 4].copy_from_slice(&w.to_le_bytes());
|
||||
}
|
||||
written = true;
|
||||
}
|
||||
(PushField::SlotBindOffset(_) | PushField::DispatchRegion, PushLoc::Push { .. }) => {}
|
||||
(PushField::Specialized(_), _) => {}
|
||||
other => panic!("unexpected push field {other:?}"),
|
||||
}
|
||||
}
|
||||
assert!(written, "the planes' push field");
|
||||
let buffers = init
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, b)| Buffer {
|
||||
slot: Some(ResourceSlot {
|
||||
stage: Stage::Kernel,
|
||||
kind: ResourceKind::Buffer,
|
||||
index: i as u32,
|
||||
}),
|
||||
address: None,
|
||||
bytes: b.clone(),
|
||||
})
|
||||
.collect();
|
||||
Resources {
|
||||
buffers,
|
||||
push,
|
||||
spec,
|
||||
}
|
||||
}
|
||||
|
||||
/// A sampler a test samples through: a constexpr sampler's words, or a runtime sampler's word.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Through {
|
||||
Constexpr(u64),
|
||||
Runtime(u32),
|
||||
}
|
||||
|
||||
/// The word of a runtime sampler of `filter` (linear, else nearest), every axis addressed by
|
||||
/// `mode`, normalized coordinates, transparent black.
|
||||
fn word(linear: bool, mode: SamplerAddressMode) -> u32 {
|
||||
let mut w = if linear { SamplerWord::LINEAR } else { 0 };
|
||||
for shift in SamplerWord::ADDRESS_SHIFT {
|
||||
w |= mode.as_raw() << shift;
|
||||
}
|
||||
w
|
||||
}
|
||||
|
||||
/// Metal's sample of `planes` at footprint position `q` (`256 (x - 1/2)` per axis, the texel
|
||||
/// coordinate `x`) offset by `offset` texels, clamped to the edge: linear, the rule's steps of
|
||||
/// the four taps; nearest, the texel at `⌊x⌋`.
|
||||
fn metal(planes: &Planes, linear: bool, (qx, qy): (i64, i64), offset: (i64, i64)) -> [i64; 3] {
|
||||
let edge = |i: i64, n: u32| i.clamp(0, i64::from(n) - 1);
|
||||
if !linear {
|
||||
let x = edge(((qx + 128) >> 8) + offset.0, W);
|
||||
let y = edge(((qy + 128) >> 8) + offset.1, H);
|
||||
return planes.texel(x, y);
|
||||
}
|
||||
let (i, j) = ((qx >> 8) + offset.0, (qy >> 8) + offset.1);
|
||||
let (i0, i1) = (edge(i, W), edge(i + 1, W));
|
||||
let (j0, j1) = (edge(j, H), edge(j + 1, H));
|
||||
let a = if i0 == i1 { 0 } else { qx & 255 };
|
||||
let b = if j0 == j1 { 0 } else { qy & 255 };
|
||||
let taps = [
|
||||
planes.texel(i0, j0),
|
||||
planes.texel(i1, j0),
|
||||
planes.texel(i0, j1),
|
||||
planes.texel(i1, j1),
|
||||
];
|
||||
std::array::from_fn(|c| metal_step(taps.map(|t| t[c]), a, b))
|
||||
}
|
||||
|
||||
/// Every sample of each format's random planes under each conversion, through constexpr and
|
||||
/// runtime samplers (nearest and linear; a runtime sampler's repeat sampled as clamp-to-edge, as
|
||||
/// a 4:2:0 texture's), with a constant offset or none, `float` and `half` results, on lavapipe and
|
||||
/// on MoltenVK, is Metal's: a quarter of the positions past an edge.
|
||||
#[test]
|
||||
fn in_place_samples_are_metals() {
|
||||
let conversions = [
|
||||
(YCbCrRange::Video, YCbCrMatrix::Bt601),
|
||||
(YCbCrRange::Video, YCbCrMatrix::Bt709),
|
||||
(YCbCrRange::Video, YCbCrMatrix::Bt2020),
|
||||
(YCbCrRange::Full, YCbCrMatrix::Bt601),
|
||||
(YCbCrRange::Full, YCbCrMatrix::Bt709),
|
||||
(YCbCrRange::Full, YCbCrMatrix::Bt2020),
|
||||
];
|
||||
let mut rng = Lcg(0x1c_bc_7a_1e);
|
||||
let planes: Vec<Planes> = [PixelFormat::YCBCR84202P, PixelFormat::YCBCR104202P]
|
||||
.into_iter()
|
||||
.flat_map(|pf| conversions.map(|c| (pf, c)))
|
||||
.map(|(pf, c)| Planes::random(pf, c, &mut rng))
|
||||
.collect();
|
||||
// Footprint positions `q = 256 (x - 1/2)`, each axis within one and a half texels of the
|
||||
// texture; a nearest sample's off the texel edges, where `⌊x⌋` holds for any rounding.
|
||||
let positions: Vec<(i64, i64)> = (0..64)
|
||||
.map(|_| {
|
||||
let mut q = |n: u32| {
|
||||
let q = (rng.next() % (256 * u64::from(n) + 768)) as i64 - 384;
|
||||
match (q + 128) & 255 {
|
||||
0..8 => q + 8,
|
||||
248.. => q - 8,
|
||||
_ => q,
|
||||
}
|
||||
};
|
||||
(q(W), q(H))
|
||||
})
|
||||
.collect();
|
||||
let out = |q: i64, n: u32| q < 0 || q >= 256 * (i64::from(n) - 1);
|
||||
let edges = positions
|
||||
.iter()
|
||||
.filter(|&&(qx, qy)| out(qx, W) || out(qy, H))
|
||||
.count();
|
||||
assert!(edges >= positions.len() / 4, "{edges} past an edge");
|
||||
let coords: Vec<u8> = positions
|
||||
.iter()
|
||||
.flat_map(|&(qx, qy)| {
|
||||
let n = |q: i64, n: u32| (q + 128) as f32 / (256 * i64::from(n)) as f32;
|
||||
[n(qx, W).to_le_bytes(), n(qy, H).to_le_bytes()]
|
||||
})
|
||||
.flatten()
|
||||
.collect();
|
||||
let edge = SamplerAddressMode::ClampToEdge;
|
||||
let cases = [
|
||||
(
|
||||
"constexpr linear",
|
||||
Through::Constexpr(linear(1, false, 0)),
|
||||
true,
|
||||
(0, 0),
|
||||
),
|
||||
(
|
||||
"constexpr nearest",
|
||||
Through::Constexpr(sampler_words(0, 0, 1, false, 0)),
|
||||
false,
|
||||
(0, 0),
|
||||
),
|
||||
(
|
||||
"constexpr offset",
|
||||
Through::Constexpr(linear(1, false, 0)),
|
||||
true,
|
||||
(2, -1),
|
||||
),
|
||||
(
|
||||
"runtime linear",
|
||||
Through::Runtime(word(true, edge)),
|
||||
true,
|
||||
(0, 0),
|
||||
),
|
||||
(
|
||||
"runtime nearest",
|
||||
Through::Runtime(word(false, edge)),
|
||||
false,
|
||||
(0, 0),
|
||||
),
|
||||
(
|
||||
"runtime repeat",
|
||||
Through::Runtime(word(true, SamplerAddressMode::Repeat)),
|
||||
true,
|
||||
(0, 0),
|
||||
),
|
||||
];
|
||||
for (name, through, linear, offset) in cases {
|
||||
for half in [false, true] {
|
||||
let sampler = match through {
|
||||
Through::Constexpr(w) => Some(w),
|
||||
Through::Runtime(_) => None,
|
||||
};
|
||||
let form = Form::Plain {
|
||||
offset: (offset.0 as i32, offset.1 as i32),
|
||||
};
|
||||
let Some(bc) = assemble(name, &kernel_of(sampler, form, !half)) else {
|
||||
return;
|
||||
};
|
||||
for (stem, p) in [("lavapipe", lavapipe()), ("moltenvk-m3", m3())] {
|
||||
let what = format!("{name} half={half} on {stem}");
|
||||
let a = compile_with(&bc, "k", &p, &inputs(true))
|
||||
.unwrap_or_else(|e| panic!("{what}: {e}"));
|
||||
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: {e}"));
|
||||
assert!(
|
||||
a.strategies
|
||||
.entries
|
||||
.keys()
|
||||
.any(|k| k.starts_with("sampler.ycbcr_in_place.")),
|
||||
"{what}: {:?}",
|
||||
a.strategies.entries.keys().collect::<Vec<_>>()
|
||||
);
|
||||
let (plan, m) = typed_module_with(&bc, "k", &p, &inputs(true))
|
||||
.unwrap_or_else(|e| panic!("{what}: {e}"));
|
||||
let slot = texel_buffer(&m);
|
||||
let n = positions.len();
|
||||
let size = if half { 8 } else { 16 };
|
||||
for planes in &planes {
|
||||
let init = [coords.clone(), vec![0xab; size * n]];
|
||||
let res = resources(&plan, &init, &planes.words);
|
||||
let word = match through {
|
||||
Through::Runtime(w) => Some(w),
|
||||
Through::Constexpr(_) => None,
|
||||
};
|
||||
let res = with_word(res, &a, word);
|
||||
let got = run(&m, &res, &planes.image(slot), n as u32, half);
|
||||
for (q, g) in positions.iter().zip(got) {
|
||||
let want = metal(planes, linear, *q, offset);
|
||||
let p = &planes.planes;
|
||||
assert_eq!(
|
||||
g,
|
||||
result_bits(want, half, 2048),
|
||||
"{what} {:?} {}-bit q {q:?}: {g:x?}",
|
||||
(p.range, p.matrix),
|
||||
p.codes.bits,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A slot whose every access the form reads states `RuntimeFact::YCbCrInPlace` with the runtime
|
||||
/// samplers it samples through, on a profile that takes the form (lavapipe, a CPU device; MoltenVK
|
||||
/// on the M3, an integrated one) and on no other (the RTX 5080, a discrete one); a gather, a
|
||||
/// dynamic offset, `min_lod_clamp` and a 3D texture keep it from the form. Its compile under the
|
||||
/// variant states the same fact, so its plan names the same variant.
|
||||
#[test]
|
||||
fn a_slot_states_the_in_place_form_where_it_reads_only_it() {
|
||||
let fact = |samplers| RuntimeFact::YCbCrInPlace {
|
||||
slot: TEXTURE,
|
||||
samplers,
|
||||
};
|
||||
let reads = [
|
||||
(
|
||||
"linear",
|
||||
kernel(Some(linear(1, false, 0)), Form::Float),
|
||||
Some(0),
|
||||
),
|
||||
("runtime", kernel(None, Form::Float), Some(1)),
|
||||
(
|
||||
"dynamic offset",
|
||||
kernel(Some(linear(1, false, 0)), Form::DynamicOffset),
|
||||
None,
|
||||
),
|
||||
(
|
||||
"min_lod_clamp",
|
||||
kernel(Some(linear(1, false, 0)), Form::MinLodClamp),
|
||||
None,
|
||||
),
|
||||
(
|
||||
"3d",
|
||||
kernel(
|
||||
Some(linear(1, false, 0)),
|
||||
Form::ThreeD { offset: (0, 0, 0) },
|
||||
),
|
||||
None,
|
||||
),
|
||||
];
|
||||
for (name, body, samplers) in reads {
|
||||
let Some(bc) = assemble(name, &body) else {
|
||||
return;
|
||||
};
|
||||
for (stem, takes) in [
|
||||
("lavapipe", true),
|
||||
("moltenvk-m3", true),
|
||||
("nvidia-rtx5080-laptop", false),
|
||||
] {
|
||||
let p = profile(stem, EXACT_SAMPLING).expect("profile");
|
||||
assert_eq!(p.fields().ycbcr_in_place, takes, "{stem}");
|
||||
let what = format!("{name} on {stem}");
|
||||
let (plan, _) = typed_module_with(&bc, "k", &p, &inputs(false))
|
||||
.unwrap_or_else(|e| panic!("{what}: {e}"));
|
||||
let stated = plan.facts.iter().find_map(|f| match f {
|
||||
RuntimeFact::YCbCrInPlace { slot, samplers } if *slot == TEXTURE => Some(*samplers),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(stated, samplers.filter(|_| takes), "{what}");
|
||||
if let (Some(s), true) = (samplers, takes) {
|
||||
let (variant, _) = typed_module_with(&bc, "k", &p, &inputs(true))
|
||||
.unwrap_or_else(|e| panic!("{what}, in place: {e}"));
|
||||
assert!(variant.facts.contains(&fact(s)), "{what}, in place");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -69,7 +69,7 @@ fn inputs(variant: bool) -> LowerInputs {
|
||||
/// Metal's step of a 2D linear sample of a YCbCr format: the taps' steps `k` (`(i, j)`, `(i + 1,
|
||||
/// j)`, `(i, j + 1)`, `(i + 1, j + 1)`) under the fractions `a` and `b` in 1/256 steps, a merged
|
||||
/// axis's 0; a signed term and sum floored.
|
||||
fn metal_step(taps: [i64; 4], a: i64, b: i64) -> i64 {
|
||||
pub(super) fn metal_step(taps: [i64; 4], a: i64, b: i64) -> i64 {
|
||||
let w = [(256 - a) * (256 - b), a * (256 - b), (256 - a) * b, a * b];
|
||||
let t: i64 = taps.iter().zip(w).map(|(k, w)| (k * w) >> 7).sum();
|
||||
(t + 256) >> 9
|
||||
@@ -98,7 +98,7 @@ fn half_away(k: i64, d: i64) -> u16 {
|
||||
|
||||
/// The result lanes of steps `steps` on grid `d` (alpha 1): `k / d` as `f32` bits (exact), or as
|
||||
/// `half` bits rounded with ties away from zero when `half`.
|
||||
fn result_bits(steps: [i64; 3], half: bool, d: i64) -> [u32; 4] {
|
||||
pub(super) fn result_bits(steps: [i64; 3], half: bool, d: i64) -> [u32; 4] {
|
||||
let lanes = [steps[0], steps[1], steps[2], d];
|
||||
lanes.map(|k| match half {
|
||||
true => u32::from(half_away(k, d)),
|
||||
|
||||
@@ -415,6 +415,14 @@ assoc-const metal2vulkan::bind::YCbCrConvertModule::LOCAL_SIZE pub const LOCAL_S
|
||||
assoc-const metal2vulkan::bind::YCbCrConvertModule::SET pub const SET: u32
|
||||
assoc-const metal2vulkan::bind::YCbCrConvertModule::SHAPE_BINDING pub const SHAPE_BINDING: u32
|
||||
assoc-const metal2vulkan::bind::YCbCrConvertModule::SHAPE_WORDS pub const SHAPE_WORDS: u32
|
||||
assoc-const metal2vulkan::bind::YCbCrInPlace::CHROMA_AT pub const CHROMA_AT: usize
|
||||
assoc-const metal2vulkan::bind::YCbCrInPlace::CHROMA_ROW pub const CHROMA_ROW: usize
|
||||
assoc-const metal2vulkan::bind::YCbCrInPlace::CONVERSION pub const CONVERSION: usize
|
||||
assoc-const metal2vulkan::bind::YCbCrInPlace::HEIGHT pub const HEIGHT: usize
|
||||
assoc-const metal2vulkan::bind::YCbCrInPlace::LUMA_AT pub const LUMA_AT: usize
|
||||
assoc-const metal2vulkan::bind::YCbCrInPlace::LUMA_ROW pub const LUMA_ROW: usize
|
||||
assoc-const metal2vulkan::bind::YCbCrInPlace::WIDTH pub const WIDTH: usize
|
||||
assoc-const metal2vulkan::bind::YCbCrInPlace::WORDS pub const WORDS: usize
|
||||
assoc-const metal2vulkan::bind::YCbCrRefreshModule::COMPLETED pub const COMPLETED: u32
|
||||
assoc-const metal2vulkan::bind::YCbCrRefreshModule::COPY_BINDING pub const COPY_BINDING: u32
|
||||
assoc-const metal2vulkan::bind::YCbCrRefreshModule::LOCAL_SIZE pub const LOCAL_SIZE: u32
|
||||
@@ -917,6 +925,14 @@ assoc-const-value metal2vulkan::bind::YCbCrConvertModule::LOCAL_SIZE 8
|
||||
assoc-const-value metal2vulkan::bind::YCbCrConvertModule::SET 0
|
||||
assoc-const-value metal2vulkan::bind::YCbCrConvertModule::SHAPE_BINDING 1
|
||||
assoc-const-value metal2vulkan::bind::YCbCrConvertModule::SHAPE_WORDS 6
|
||||
assoc-const-value metal2vulkan::bind::YCbCrInPlace::CHROMA_AT 4
|
||||
assoc-const-value metal2vulkan::bind::YCbCrInPlace::CHROMA_ROW 5
|
||||
assoc-const-value metal2vulkan::bind::YCbCrInPlace::CONVERSION 6
|
||||
assoc-const-value metal2vulkan::bind::YCbCrInPlace::HEIGHT 1
|
||||
assoc-const-value metal2vulkan::bind::YCbCrInPlace::LUMA_AT 2
|
||||
assoc-const-value metal2vulkan::bind::YCbCrInPlace::LUMA_ROW 3
|
||||
assoc-const-value metal2vulkan::bind::YCbCrInPlace::WIDTH 0
|
||||
assoc-const-value metal2vulkan::bind::YCbCrInPlace::WORDS 8
|
||||
assoc-const-value metal2vulkan::bind::YCbCrRefreshModule::COMPLETED 3
|
||||
assoc-const-value metal2vulkan::bind::YCbCrRefreshModule::COPY_BINDING 1
|
||||
assoc-const-value metal2vulkan::bind::YCbCrRefreshModule::LOCAL_SIZE 64
|
||||
@@ -2965,7 +2981,16 @@ 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_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
|
||||
field metal2vulkan-runtime::WorkCounts.ycbcr_images_kept_layout pub ycbcr_images_kept_layout: u64
|
||||
field metal2vulkan-runtime::WorkCounts.ycbcr_images_kept_reach pub ycbcr_images_kept_reach: u64
|
||||
field metal2vulkan-runtime::WorkCounts.ycbcr_images_kept_swizzle pub ycbcr_images_kept_swizzle: u64
|
||||
field metal2vulkan-runtime::WorkCounts.ycbcr_images_kept_view pub ycbcr_images_kept_view: u64
|
||||
field metal2vulkan-runtime::WorkCounts.ycbcr_planes_bound pub ycbcr_planes_bound: u64
|
||||
field metal2vulkan-runtime::WorkCounts.ycbcr_refreshes pub ycbcr_refreshes: u64
|
||||
field metal2vulkan-runtime::WorkCounts.ycbcr_textures_in_place pub ycbcr_textures_in_place: u64
|
||||
field metal2vulkan-runtime::WorkCounts.ycbcr_whole_conversions pub ycbcr_whole_conversions: u64
|
||||
field metal2vulkan::Budget.cancel pub cancel: Option<CancelToken>
|
||||
field metal2vulkan::Budget.deadline pub deadline: Option<Instant>
|
||||
@@ -3545,6 +3570,7 @@ field metal2vulkan::bind::TextureFacts.sparse pub sparse: bool
|
||||
field metal2vulkan::bind::TextureFacts.swizzle pub swizzle: metal::TextureSwizzleChannels
|
||||
field metal2vulkan::bind::TextureFacts.texture_type pub texture_type: metal::TextureType
|
||||
field metal2vulkan::bind::TextureFacts.usage pub usage: metal::TextureUsage
|
||||
field metal2vulkan::bind::TextureFacts.ycbcr_in_place pub ycbcr_in_place: Option<crate::bind::YCbCrInPlace>
|
||||
field metal2vulkan::bind::TileReachModule.requirements pub requirements: Requirements
|
||||
field metal2vulkan::bind::TileReachModule.spirv pub spirv: Arc<[u32]>
|
||||
field metal2vulkan::bind::TileThreadgroupArgument.length pub length: u32
|
||||
@@ -3683,6 +3709,7 @@ field metal2vulkan::cache::VariantKey.storage_view_slots pub storage_view_slots:
|
||||
field metal2vulkan::cache::VariantKey.swizzled_storage pub swizzled_storage: BTreeSet<SlotRef>
|
||||
field metal2vulkan::cache::VariantKey.viewport_compensation pub viewport_compensation: Option<crate::pipeline::ViewportCompensation>
|
||||
field metal2vulkan::cache::VariantKey.window_depth_varying pub window_depth_varying: bool
|
||||
field metal2vulkan::cache::VariantKey.ycbcr_in_place pub ycbcr_in_place: BTreeSet<SlotRef>
|
||||
field metal2vulkan::cache::VariantKey.ycbcr_textures pub ycbcr_textures: BTreeSet<SlotRef>
|
||||
field metal2vulkan::cache::VariantKey.zeroed_colors pub zeroed_colors: BTreeMap<u32, crate::metal::PixelFormat>
|
||||
field metal2vulkan::device::AllocationLimits.max_buffer_size pub max_buffer_size: u64
|
||||
@@ -4284,6 +4311,7 @@ field metal2vulkan::pipeline::LoweringInputs.viewport_compensation pub viewport_
|
||||
field metal2vulkan::pipeline::LoweringInputs.viewport_index_varying pub viewport_index_varying: bool
|
||||
field metal2vulkan::pipeline::LoweringInputs.window_depth_varying pub window_depth_varying: bool
|
||||
field metal2vulkan::pipeline::LoweringInputs.word_colors pub word_colors: BTreeMap<u32, metal::format::WordAttachment>
|
||||
field metal2vulkan::pipeline::LoweringInputs.ycbcr_in_place pub ycbcr_in_place: BTreeSet<SlotRef>
|
||||
field metal2vulkan::pipeline::LoweringInputs.ycbcr_textures pub ycbcr_textures: BTreeSet<SlotRef>
|
||||
field metal2vulkan::pipeline::LoweringInputs.zeroed_colors pub zeroed_colors: BTreeMap<u32, metal::PixelFormat>
|
||||
field metal2vulkan::pipeline::MeshPipelineDescriptor.alpha_to_coverage pub alpha_to_coverage: bool
|
||||
@@ -8726,6 +8754,13 @@ method metal2vulkan::bind::YCbCrCodes::of pub fn of(format: crate::metal::format
|
||||
method metal2vulkan::bind::YCbCrCodes::units pub fn units(&self, n: u64) -> u64
|
||||
method metal2vulkan::bind::YCbCrConversion::of pub fn of(codes: YCbCrCodes, (range, matrix): (YCbCrRange, YCbCrMatrix)) -> YCbCrConversion
|
||||
method metal2vulkan::bind::YCbCrConvertModule::shape pub fn shape(planes: &YCbCrPlanes) -> [u8; Self::SHAPE_WORDS as usize * 4]
|
||||
method metal2vulkan::bind::YCbCrInPlace::bits pub fn bits(&self) -> u32
|
||||
method metal2vulkan::bind::YCbCrInPlace::element_bytes pub fn element_bytes(&self) -> u64
|
||||
method metal2vulkan::bind::YCbCrInPlace::elements pub fn elements(&self) -> u64
|
||||
method metal2vulkan::bind::YCbCrInPlace::format pub fn format(&self) -> vk::Format
|
||||
method metal2vulkan::bind::YCbCrInPlace::of pub fn of(planes: &YCbCrPlanes) -> Option<YCbCrInPlace>
|
||||
method metal2vulkan::bind::YCbCrInPlace::view_bytes pub fn view_bytes(&self) -> u64
|
||||
method metal2vulkan::bind::YCbCrInPlace::words pub fn words(&self) -> [u32; Self::WORDS]
|
||||
method metal2vulkan::bind::YCbCrPlanes::chroma_size pub fn chroma_size(&self) -> [u32; 2]
|
||||
method metal2vulkan::bind::YCbCrPlanes::conversion pub fn conversion(&self) -> YCbCrConversion
|
||||
method metal2vulkan::bind::YCbCrPlanes::new pub fn new(size: [u32; 2], luma: [u32; 2], chroma: [u32; 2], (range, matrix): (YCbCrRange, YCbCrMatrix), codes: YCbCrCodes) -> YCbCrPlanes
|
||||
@@ -8846,6 +8881,7 @@ method metal2vulkan::device::DeviceProfile::link_standalone pub fn link_standalo
|
||||
method metal2vulkan::device::DeviceProfile::module_word_bound pub fn module_word_bound(&self) -> Option<u32>
|
||||
method metal2vulkan::device::DeviceProfile::plan_entry pub fn plan_entry(&self, d: &EntryDescriptor<'_>, inputs: &LoweringInputs, budget: &Budget) -> (Result<EntryPlan, Error>, CompileReport)
|
||||
method metal2vulkan::device::DeviceProfile::reads_half_texel_bits pub fn reads_half_texel_bits(&self) -> bool
|
||||
method metal2vulkan::device::DeviceProfile::reads_ycbcr_planes_in_place pub fn reads_ycbcr_planes_in_place(&self) -> bool
|
||||
method metal2vulkan::device::DeviceProfile::simd_tier pub fn simd_tier(&self, class: &SimdClass, stage: Stage) -> Result<Tier, Unsupported>
|
||||
method metal2vulkan::device::DeviceProfile::specialized_entry pub fn specialized_entry(&self, d: &EntryDescriptor<'_>, inputs: &LoweringInputs, budget: &Budget) -> Result<Entry, Error>
|
||||
method metal2vulkan::device::DeviceProfile::spirv_validation pub fn spirv_validation(&self) -> SpirvValidation
|
||||
@@ -9661,6 +9697,7 @@ struct metal2vulkan::bind::VisibilityResolveModule #[derive(Clone, Debug, Partia
|
||||
struct metal2vulkan::bind::YCbCrCodes #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct YCbCrCodes
|
||||
struct metal2vulkan::bind::YCbCrConversion #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct YCbCrConversion
|
||||
struct metal2vulkan::bind::YCbCrConvertModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct YCbCrConvertModule
|
||||
struct metal2vulkan::bind::YCbCrInPlace #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] #[non_exhaustive] pub struct YCbCrInPlace
|
||||
struct metal2vulkan::bind::YCbCrPlanes #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct YCbCrPlanes
|
||||
struct metal2vulkan::bind::YCbCrRefreshModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct YCbCrRefreshModule
|
||||
struct metal2vulkan::bind::YCbCrWriteModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct YCbCrWriteModule
|
||||
@@ -12052,6 +12089,7 @@ variant metal2vulkan::bind::AccessClass::Storage Storage
|
||||
variant metal2vulkan::bind::AccessClass::StorageImage StorageImage
|
||||
variant metal2vulkan::bind::AccessClass::Uniform Uniform
|
||||
variant metal2vulkan::bind::AccessClass::VertexInput VertexInput
|
||||
variant metal2vulkan::bind::AccessClass::YCbCrPlanes YCbCrPlanes
|
||||
variant metal2vulkan::bind::ArgumentLayoutError::ArrayOfArrays ArrayOfArrays { id: u32 }
|
||||
variant metal2vulkan::bind::ArgumentLayoutError::Compile Compile(Error)
|
||||
variant metal2vulkan::bind::ArgumentLayoutError::ConstantBlockAlignment ConstantBlockAlignment { position: usize }
|
||||
@@ -12334,7 +12372,7 @@ variant metal2vulkan::bind::TessellationRecords::Pool Pool
|
||||
variant metal2vulkan::bind::TexelWords::ColorPlane ColorPlane
|
||||
variant metal2vulkan::bind::TexelWords::Raw Raw
|
||||
variant metal2vulkan::bind::TextureShape::Buffer Buffer { pixel_format: metal::PixelFormat, swizzle: metal::TextureSwizzleChannels }
|
||||
variant metal2vulkan::bind::TextureShape::Texture Texture { texture_type: metal::TextureType, pixel_format: metal::PixelFormat, sample_count: u32, usage: metal::TextureUsage, mipmap_level_count: u32, sparse: bool, depth_twin: bool, swizzle: metal::TextureSwizzleChannels, address_modes: metal::sampler::AddressModeMap, offset_base_axes: u8, own_format_views: bool }
|
||||
variant metal2vulkan::bind::TextureShape::Texture Texture { texture_type: metal::TextureType, pixel_format: metal::PixelFormat, sample_count: u32, usage: metal::TextureUsage, mipmap_level_count: u32, sparse: bool, depth_twin: bool, swizzle: metal::TextureSwizzleChannels, address_modes: metal::sampler::AddressModeMap, offset_base_axes: u8, own_format_views: bool, ycbcr_in_place: bool }
|
||||
variant metal2vulkan::bind::TileMapError::Region Region { level: u32, slice: u32, origin: [u32; 3], size: [u32; 3] }
|
||||
variant metal2vulkan::bind::TileMapError::Shape Shape
|
||||
variant metal2vulkan::bind::TileMapError::TextureType TextureType { texture_type: TextureType }
|
||||
@@ -12391,6 +12429,7 @@ variant metal2vulkan::bind::WriteSource::Texture Texture { slot: SlotRef, view:
|
||||
variant metal2vulkan::bind::WriteSource::TileAttachment TileAttachment { color_index: u32, format: vk::Format, view: StorageAttachmentView, view_alias: Option<vk::Format> }
|
||||
variant metal2vulkan::bind::WriteSource::TileMap TileMap { slot: SlotRef }
|
||||
variant metal2vulkan::bind::WriteSource::TileMemory TileMemory { bytes: u64 }
|
||||
variant metal2vulkan::bind::WriteSource::YCbCrInPlace YCbCrInPlace { slot: SlotRef }
|
||||
variant metal2vulkan::bind::YCbCrMatrix::Bt2020 Bt2020
|
||||
variant metal2vulkan::bind::YCbCrMatrix::Bt601 Bt601
|
||||
variant metal2vulkan::bind::YCbCrMatrix::Bt709 Bt709
|
||||
@@ -13742,6 +13781,7 @@ variant metal2vulkan::pipeline::PushField::VerticesPerPrimitive VerticesPerPrimi
|
||||
variant metal2vulkan::pipeline::PushField::ViewportCompensation ViewportCompensation
|
||||
variant metal2vulkan::pipeline::PushField::ViewportCount ViewportCount
|
||||
variant metal2vulkan::pipeline::PushField::ViewportMirrors ViewportMirrors
|
||||
variant metal2vulkan::pipeline::PushField::YCbCrInPlace YCbCrInPlace(SlotRef)
|
||||
variant metal2vulkan::pipeline::PushLoc::ArgumentTable ArgumentTable { offset: u32 }
|
||||
variant metal2vulkan::pipeline::PushLoc::Push Push { offset: u32 }
|
||||
variant metal2vulkan::pipeline::Reconvergence::Guaranteed Guaranteed
|
||||
@@ -13868,6 +13908,7 @@ variant metal2vulkan::pipeline::RuntimeFact::VertexFetch VertexFetch { attr: u32
|
||||
variant metal2vulkan::pipeline::RuntimeFact::ViewportCompensation ViewportCompensation { depth: bool, point_guard: bool, mirrors: bool, vertex_clamp: bool }
|
||||
variant metal2vulkan::pipeline::RuntimeFact::ViewportCount ViewportCount
|
||||
variant metal2vulkan::pipeline::RuntimeFact::WordInputMerge WordInputMerge { color: u32, kept: crate::vk::ColorComponentFlags }
|
||||
variant metal2vulkan::pipeline::RuntimeFact::YCbCrInPlace YCbCrInPlace { slot: SlotRef, samplers: u32 }
|
||||
variant metal2vulkan::pipeline::RuntimeFact::YCbCrTexture YCbCrTexture { slot: SlotRef }
|
||||
variant metal2vulkan::pipeline::RuntimeFact::ZeroedColor ZeroedColor { color: u32, format: crate::metal::PixelFormat }
|
||||
variant metal2vulkan::pipeline::SampledType::Float Float
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -738,6 +738,7 @@ surface! {
|
||||
fn ycbcr_read;
|
||||
struct YCbCrConvertModule N;
|
||||
struct YCbCrPlanes N;
|
||||
struct YCbCrInPlace N;
|
||||
struct YCbCrConversion N;
|
||||
struct YCbCrCodes N;
|
||||
enum YCbCrOutput N;
|
||||
|
||||
+10
@@ -785,6 +785,16 @@ for dependency in &pipeline.dependencies {
|
||||
pipeline of its own: leave out a slot bound at offsets that move, so that its draws keep one
|
||||
shape and one pipeline (the runtime leaves out each slot of a state once it finds one bound at
|
||||
an offset the alignment does not divide).
|
||||
- A two-plane YCbCr texture whose planes a function may read in place states them in its facts
|
||||
(`TextureFacts::ycbcr_in_place`, a `YCbCrInPlace` of its planes; the runtime states one on a
|
||||
device whose memory is the host's, `DeviceProfile::reads_ycbcr_planes_in_place`: an integrated
|
||||
GPU or a CPU device). A slot whose function only samples it (nearest or linear, no comparison,
|
||||
anisotropy or `min_lod_clamp`) or reads its size (`RuntimeFact::YCbCrInPlace`) takes the
|
||||
pipeline's in-place variant (`VariantKey::ycbcr_in_place`): the slot binds a uniform texel buffer
|
||||
over the planes' bytes (`WriteSource::YCbCrInPlace`, in `YCbCrInPlace::format`), its push field
|
||||
(`PushField::YCbCrInPlace`) holds `YCbCrInPlace::words`, and the function converts and filters
|
||||
the codes as Metal does, exactly. Any other slot, and any texture without the fact, binds the
|
||||
texture's image of converted texels.
|
||||
- `interface.reaches_command_buffers` and `interface.texture_writing_stages` say, provably, which
|
||||
pipelines may touch an indirect command buffer and which stages may write a texture.
|
||||
`interface.command_writes` (`CommandWrites`) says what its functions may write into the
|
||||
|
||||
+28
-1
@@ -28,7 +28,7 @@ three consumer pipelines: A2X (`a2x-s4`, `a2x-s96`), Xgc14 (`xgc14-bgra8`) and X
|
||||
| What it is | Default (fast) | Accurate switch | Recorded bound (note, code) | Cost of the accurate form (5080) |
|
||||
|---|---|---|---|---|
|
||||
| Samples, gathers and depth comparisons go to the device's own sampler: its filter, footprint, level, anisotropy, sRGB decode and comparison. An 8-bit sRGB format the device cannot sample (`R8G8_SRGB` on NVIDIA) is held as its UNORM twin: a sample the raw codes do not serve is the device's filter of the codes, decoded through Metal's table. | `sampling = SamplingPolicy::NativeDevice` | `sampling = SamplingPolicy::Exact`: Metal's sampler emulated by fetches, a pipeline per bound sampler state | Linear filter within one code (1/255) on the measured devices, sRGB within 1.83; 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`) | A2X under the four exact switches of the consumer's exact boot (sampling, texel conversion, half blend, NaN and min/max) on the RTX 5080 Laptop GPU (615.71.09): its function 572,061 words, made in 11.5-12.8 s; its anisotropic sampler's variant 659,590 words, 20.9-26.1 s on a loaded host where the function took 16.7-22.3 s; at the defaults 260,153 words, 1.1 s. On ANV both pass its compiler word bound, so it drops exact sampling for them (the row of that bound). At the switch (maths and texel conversions still exact): Xgc15 making 24.2-24.8 s exact against 12.5-13.9 s native |
|
||||
| A two-plane YCbCr texture's linear sample (`YCBCR8_420_2P` and its kin, over a surface's planes) is the device's filter of its texels, which hold Metal's reads exactly, as any other texture's is under native sampling: a draw binding one takes the pipeline a draw binding any other texture takes. Metal sums the texels' steps on the format's grid (`1/2048`, `1/8192`), each term truncated. Under native sampling, MoltenVK's included (Metal's own sampler filters the texels as an `RGBA16Float` or `RGBA32Float` texture's); with `sampling = SamplingPolicy::Exact` every module answers Metal's filter, MoltenVK's through the slot's variant. | `ycbcr_filter = YCbCrFilterPolicy::Device` | `ycbcr_filter = YCbCrFilterPolicy::Exact`: Metal's filter emulated in the slot's YCbCr variant, a pipeline the first draw binding such a texture makes | Linear filter within 1.183 codes (1/255) of Metal's filter of the format on NVIDIA (RTX 3090), 0.877 on RADV, 1.058 on ANV, 0.872 on lavapipe; within 0.498 at coordinates on the 1/256 grid. `DeviceSampling` (`device-sampling`). On MoltenVK within one step of the grid (0.125 codes on `1/2048`, 0.016 on `1/8192`), a `half` result within one `half` ulp; a `half` sample of one texel on the grid `8192` through a runtime sampler rounds to nearest even where Metal rounds ties away. `ycbcr-filter-not-exact`, `HalfTexelConversion` (`half-texel-conversion`), announced where a draw binds such a texture | One pipeline more, made at the first draw binding such a texture. A2X (`a2x-s96` with a `YCBCR8_420_2P` texture at fragment slot 3, on ANV, Iris Xe): 2 pipelines, 13.9 s at the state's creation and 37.8 s at the draw (52.3 s wall), against the creation's one drawn as made (14.3 s) |
|
||||
| A two-plane YCbCr texture's linear sample (`YCBCR8_420_2P` and its kin, over a surface's planes) is the device's filter of its texels, which hold Metal's reads exactly, as any other texture's is under native sampling: a draw binding one takes the pipeline a draw binding any other texture takes. Metal sums the texels' steps on the format's grid (`1/2048`, `1/8192`), each term truncated. Under native sampling, MoltenVK's included (Metal's own sampler filters the texels as an `RGBA16Float` or `RGBA32Float` texture's); with `sampling = SamplingPolicy::Exact` every module answers Metal's filter, MoltenVK's through the slot's variant. On a device whose memory is the host's, a sample that reads the planes in place is Metal's filter exactly under either value (the two-plane YCbCr bullet under **Costs of matching Metal**), so the row applies there only to the samples that form does not read. | `ycbcr_filter = YCbCrFilterPolicy::Device` | `ycbcr_filter = YCbCrFilterPolicy::Exact`: Metal's filter emulated in the slot's YCbCr variant, a pipeline the first draw binding such a texture makes | Linear filter within 1.183 codes (1/255) of Metal's filter of the format on NVIDIA (RTX 3090), 0.877 on RADV, 1.058 on ANV, 0.872 on lavapipe; within 0.498 at coordinates on the 1/256 grid. `DeviceSampling` (`device-sampling`). On MoltenVK within one step of the grid (0.125 codes on `1/2048`, 0.016 on `1/8192`), a `half` result within one `half` ulp; a `half` sample of one texel on the grid `8192` through a runtime sampler rounds to nearest even where Metal rounds ties away. `ycbcr-filter-not-exact`, `HalfTexelConversion` (`half-texel-conversion`), announced where a draw binds such a texture | One pipeline more, made at the first draw binding such a texture. A2X (`a2x-s96` with a `YCBCR8_420_2P` texture at fragment slot 3, on ANV, Iris Xe): 2 pipelines, 13.9 s at the state's creation and 37.8 s at the draw (52.3 s wall), against the creation's one drawn as made (14.3 s) |
|
||||
| A texel's `float` value is the device's conversion of its codes; a `half` result is the device's `float` texel rounded to nearest even. | `texel_conversion = TexelConversionPolicy::Device` | `texel_conversion = TexelConversionPolicy::Exact`: Metal's conversion by the bound format's class of every read; a sample's or gather's also with `sampling = SamplingPolicy::Exact` (under native sampling the device's sampler decodes it) | 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. `DeviceTexelConversion` (`device-texel-conversion`), `HalfTexelConversion` (`half-texel-conversion`, also recorded for heap textures and unmeasured formats) | Exact reads (the same reads): Xgc14 0.88-0.89 → 0.90-0.93 s, GPU 0.039 → 0.046 ms; Xgc15 0.65-0.66 → 0.68 s, 0.090 → 0.094 ms; A2X unchanged (no affected read). Samples: with the sampling row |
|
||||
| A normalized vertex attribute (`UCharNormalized` through `Short4Normalized` of either sign, `UChar4Normalized_BGRA`, `Int1010102Normalized`, `UInt1010102Normalized`) is converted by fixed-function vertex input, through the attribute's own Vulkan `UNORM` or `SNORM` format, not pulled from its vertex buffer and divided in the shader. Vulkan states that conversion as Metal states it (`c / (2^b - 1)` unsigned, `max(c / (2^(b-1) - 1), -1)` signed, correctly rounded), so it is the driver's implementation of it that can differ, and nothing in the attribute's Vulkan format asks for a correction after the load. The whole format is then `VertexAttribute` state that no instruction of the module names, so every format the device fetches shares one module (`pipeline::link::vertex`, item 9). | `vertex_normalized = VertexNormalizedPolicy::Device` | `vertex_normalized = VertexNormalizedPolicy::Exact`: every such attribute is pulled and its codes divided by `lower::stage_io::fetch`'s integer sequence, one module per format | One `f32` ulp at some codes on a driver that multiplies by the reciprocal: measured on llvmpipe (Mesa 26.2.4), which reads 127/255 as `0x3EFEFF00` where Metal reads `0x3EFEFEFF`, over the five 8-bit unsigned sites of `vertex-format-float4` and four of `-instance-step` (`known-gaps.tsv`); the 16-bit and packed normalized formats are exact there, and the unsigned ones are exact on RADV. Every normalized format of `vertex-format-float4`, `-half4` and `-instance-step` is Metal's on MoltenVK (Apple M3 Max, macOS 27.0.1) under both values of this switch, each case `exact` at every site. The signed formats are **unaudited** off MoltenVK under the default: they were pulled on every device until this row existed, so llvmpipe's 8-bit sites are expected to read one ulp as their unsigned twins do, and no run has taken them. Not announced: no note names the device's normalized vertex conversion. `tests::engine_vertex_variants` tests both values | Not timed. The variant count is the cost, measured on an Apple M3 Max over `cases::vertex_formats`' 45-format sweep (`tests::engine_vertex_variants`): the `float4` entry compiles 2 modules under the default and 21 under the switch, the `half4` entry 1 against 20. Each extra module is a translation of ours and a shader the driver converts once more |
|
||||
| The maths library (`sin`, `exp`, `log`, `pow`, `atan2`...), divisions and Metal's fast reciprocal, and a fused multiply-add without `OpFmaKHR` are the device's instructions, not routines of Metal's answers. Off MoltenVK a `float` multiply, and a fused multiply-add by `OpFmaKHR`, keep the device's rounding before Metal's flush: Metal flushes a result whose exact value lies below `2^-126` before rounding it. | `float_maths = FloatMathsPolicy::Native` | `float_maths = FloatMathsPolicy::Exact`; there off MoltenVK a `float` product of `±2^-126` is Metal's zero where the exact product lies below `2^-126`, decided inline without a branch by one `OpFmaKHR` on the operands' magnitudes, or by their bits without `OpFmaKHR` (`arith.float.tiny`, `dot`'s first product too), and `OpFmaKHR` is checked: a result at most `2^-126` in magnitude, zero included, is answered by a routine called only then, with `double` one that decides only the exact sum's sign and whether it lies below `2^-126`, else the integer `fma`; a module with either check, or with a fused multiply-add the translation computes itself (the `double` and integer routines without `OpFmaKHR`, and every `half` one), declares `SignedZeroInfNanPreserve` at 32 bits, and at 64 for a `double` routine, where the device supports it, so the device keeps the zero signs they answer (without it Vulkan lets the device answer a zero of either sign; else `DeviceSignedZeroInfNan`) | Vulkan's precision table (`Sin` 2^-11 absolute in [-π, π], `Exp` 3 + 2·\|x\| ulp, `Atan` 4096 ulp) against Metal's 4-6 ulp; division 2.5 ulp; `fma` one `half` ulp (a `float` one may round twice); an `f32` denormal in a maths function, `fast::fmod` among them, read as the device reads it (`DeviceDenormals`); a product or fused multiply-add 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, announced once per device as it is made. `NativeTranscendentals` (`native-transcendentals`), `NativeDivision` (`native-division`), `NativeFma` (`native-fma`), `FloatTininessAfterRounding` (`float-tininess-after-rounding`) | A2X 0.99-1.02 → 9.66-9.83 s, GPU 0.097-0.098 → 0.222-0.225 ms; Xgc14 0.87-0.90 → 12.6-13.6 s, 0.038 → 0.124-0.135 ms; Xgc15 0.63-0.65 → 9.40-9.54 s, 0.089 → 0.208 ms (measured before these modules declared `SignedZeroInfNanPreserve`, whose cost is not measured). Off MoltenVK a product's check is 12 instructions inline (23 without `OpFmaKHR`), and a checked `OpFmaKHR` adds its test, a branch and a call of a routine of about 40 instructions (with `double`), which the device's compiler copies into each use |
|
||||
@@ -138,6 +138,33 @@ recorded here.
|
||||
nothing more -- while recovering the damage by comparing frames is the copy skipping that is ruled
|
||||
out.
|
||||
|
||||
- **A two-plane YCbCr texture is read in place on an integrated GPU and converted on a discrete
|
||||
one.** Metal reads a `YCBCR8_420_2P` or `YCBCR10_420_2P` texture's texels from its surface's
|
||||
planes. On a device whose memory is the host's (Vulkan's `deviceType` an integrated GPU or a CPU),
|
||||
a function that only samples such a texture (nearest or linear, no comparison, anisotropy or
|
||||
`min_lod_clamp`) or reads its size reads the planes' codes in place, through a uniform texel
|
||||
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. Both are exact, so 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):
|
||||
|
||||
| Device | Codes | In place, 1 pass | Image, 1 pass | In place, 3 passes | Image, 3 passes |
|
||||
|---|---|---|---|---|---|
|
||||
| Radeon 780M (RADV) | 8-bit | 340 | 1178 | 1027 | 3013 |
|
||||
| Radeon 780M (RADV) | 10-bit | 457 | 1509 | 1371 | 3344 |
|
||||
| Radeon RX 7900 XTX (RADV) | 8-bit | 1819 | 1754 | 5460 | 1876 |
|
||||
| Radeon RX 7900 XTX (RADV) | 10-bit | 3614 | 3479 | 10843 | 3613 |
|
||||
| Apple M3 Max (MoltenVK) | 8-bit | 127 | 259 | 375 | 634 |
|
||||
| Apple M3 Max (MoltenVK) | 10-bit | 125 | 364 | 378 | 737 |
|
||||
|
||||
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
|
||||
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_*`).
|
||||
- **Idle dma-buf imports are released.** RADV lists every imported memory in every kernel
|
||||
submission, so a no-copy buffer's dma-buf import that only blits have read is released after its
|
||||
idle window (2 s, doubled at each import again up to 64 s). The encoding thread pays its import
|
||||
|
||||
Reference in new issue
Block a user