Anees Iqbal cdf59197cc 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.
2026-10-28 17:24:19 +02:00
2026-07-22 13:15:24 +03:00

metal2vulkan

License: GPL-2.0-or-later OR LGPL-3.0-or-later

metal2vulkan runs Metal shaders and Metal programs on Vulkan. It reads Metal AIR (a metallib, or AIR bitcode) and compiles it into Vulkan pipelines, and it offers the Metal API itself on top of a Vulkan device.

Beta. The API, the command line, the pipeline JSON and the emitted SPIR-V may change during the 0.x series. Version your cached outputs.

The crates

Crate Directory What it is
metal2vulkan crates/metal2vulkan The translator. A Metal-shaped API (device, library, pipeline descriptors, binding plans) that compiles compute, render, tessellation, tile and mesh pipelines for a described Vulkan device: SPIR-V per stage, one pipeline layout, fixed-function state, and per-draw descriptor writes and push constants. The cli feature builds the metal2vulkan command.
metal2vulkan-runtime crates/metal2vulkan-runtime The Metal API on Vulkan: devices, command queues and buffers, encoders, buffers, textures, heaps, pipeline states and events, run on a Vulkan device through ash. It uses only the translator's public API.
metal2vulkan-air crates/metal2vulkan-air The AIR front end: the metallib container, the bitcode reader, a typed IR, AIR's metadata ABI, intrinsics and canonicalization. For tools that read AIR without translating it.
metal2vulkan-validation crates/metal2vulkan-validation Not published. Authored cases run on Metal and on Vulkan and compared, and bounded audits over a private corpus.
metal2vulkan-devtools crates/metal2vulkan-devtools Not published. The external-tool runner and fixture assemblers the tests share.

The three published crates share one version and are released together; metal2vulkan pins metal2vulkan-air exactly.

What the translator promises:

  • Typed refusals. Input the device cannot run exactly fails with an error that names the Metal feature and what would make it work. It never returns a module that computes something else.
  • Recorded differences. Where a pipeline gives a near-equivalent of Metal's answer, its artifact records a precision note, and the runtime announces it once with a stable code.
  • Fast by default. Off Apple's GPUs, choices that trade exactness for speed take the device's native form; each has an opt-in exact switch (docs/FAST-PATHS.md).
  • Bounded work. Every compile runs under a deadline, a cancellation token and deterministic work and memory caps.

Install

0.2.0 is not on crates.io yet (crates.io has 0.1.0, an unrelated earlier design). Depend on a git revision:

[dependencies]
metal2vulkan = { git = "https://github.com/steelbrain/metal2vulkan", rev = "<sha>" }
# For the Metal API on Vulkan:
metal2vulkan-runtime = { git = "https://github.com/steelbrain/metal2vulkan", rev = "<sha>" }

Features of metal2vulkan, none needed by the library:

  • serde: serialization of the API's plain-data values.
  • ash: conversions to and from ash::vk, and DeviceDescription::query, which reads a physical device.
  • cli: the metal2vulkan command (enables serde).

Requirements: Rust 1.98 or newer. The libraries run no external tool. The runtime opens the Vulkan loader at run time and needs a Vulkan 1.2 device.

Command line

cargo install --git https://github.com/steelbrain/metal2vulkan metal2vulkan --features cli

The command compiles one pipeline of a metallib, an AIR bitcode module or an LLVM text module (.ll) for the device a Khronos profiles JSON describes, and writes its SPIR-V:

# A kernel: one module.
metal2vulkan library.metallib kernel.spv --profile device.json --function my_kernel

# A render pipeline: one module per stage (pipeline.vert.spv, pipeline.frag.spv).
metal2vulkan shaders.air pipeline.spv --profile device.json \
  --function vertex_main --fragment fragment_main --vertex-descriptor vertex.json \
  --color-format 0:BGRA8Unorm --depth-format Depth32Float

# The pipeline's layout, interface, dependencies and stages as JSON.
metal2vulkan kernel.ll kernel.spv --profile device.json --emit-meta kernel.json
  • --profile is required: the crate ships no device description. Any Khronos profiles JSON works; crates/metal2vulkan-validation/profiles/ has examples, from a bare Vulkan 1.2 device to desktop GPUs and MoltenVK.
  • Without --function it compiles the library's only kernel or vertex function. A kernel with --color-format compiles as a tile pipeline. A post-tessellation vertex function adds .tesc.spv and .tese.spv modules on a device with tessellationShader; on one without, it is the .vert.spv module itself, which draws the tessellator's triangles.
  • A compile that needs a pipeline input fails naming it and the option that supplies it: --constant ID:TYPE:VALUE for a function constant, --stage-input FILE or --vertex-descriptor FILE for a stage-input or vertex descriptor (as JSON).
  • A .ll input is assembled with llvm-as (LLVM 21 or newer). Each module written is checked with spirv-val when it is found, under the environments the library states for the device; --no-spirv-val skips it. Both tools come from PATH, or from METAL2VULKAN_LLVM_AS and METAL2VULKAN_SPIRV_VAL.
  • Success prints a line with PASS and exits 0. Failure prints metal2vulkan: FALLBACK (<why>), writes nothing, and exits 2; a failure after the inputs are read also writes a repro bundle under $TMPDIR/metal2vulkan-repros (or METAL2VULKAN_REPRO_DIR).
  • metal2vulkan --help lists every option.

Library

The flow follows Metal's object lifecycle: describe the device, parse a library, compile a pipeline, then plan and instantiate each dispatch or draw.

use metal2vulkan::device::{Device, DeviceDescription, DevicePolicy};
use metal2vulkan::library::Library;
use metal2vulkan::pipeline::{ComputePipelineDescriptor, FunctionDescriptor, StageSource};
use metal2vulkan::Budget;

let description = DeviceDescription::from_khronos_json(&profile_json, None)?;
let device = Device::new(description, DevicePolicy::default())?;
let library = Library::parse(&metallib_bytes)?;
let kernel = FunctionDescriptor::new(library.function("my_kernel")?);
let descriptor = ComputePipelineDescriptor::new(StageSource::Function(kernel));
let pipeline = device.compile_compute_pipeline(&descriptor, &Budget::standard())?;
// pipeline.stage.spirv, pipeline.layout, pipeline.interface: create the Vulkan objects from these,
// then pipeline.plan(...) and plan.instantiate_dispatch(...) per dispatch.

docs/API.md walks the whole flow on a runnable example, examples/api_preview.rs:

cargo run -p metal2vulkan --example api_preview   # needs llvm-as on PATH

For the runtime, start at its README.

Documentation

Document Read it when
docs/API.md You use the translator's API: devices, libraries, pipelines, binding, caching, errors; and the runtime's degrade notices
Runtime README You use the Metal API on Vulkan
docs/HOWTO.md You integrate: tools, caching, failures, isolation, the runtime's shader cache
docs/RUNTIME-PORTING.md You port Metal calls (Objective-C or metal-rs) to the runtime
docs/FAST-PATHS.md You need every speed-for-accuracy default and its exact switch
docs/METAL-COVERAGE.md You ask whether a Metal API item is covered
docs/REFUSALS.md You ask what Metal accepts that the code refuses
docs/ARCHITECTURE.md You change the translator
docs/VALIDATION.md You check behavior against Metal
CONTRIBUTING.md You build and test the repository

The rustdoc of each crate (cargo doc --workspace --all-features --open) documents every public item; each runtime item names its Metal counterpart.

Shaders in this repository

The repository ships no third-party shaders. Tests use synthetic fixtures written for it. Passing spirv-val shows a module is valid, not that it computes what Metal computes; that claim needs the authored validation cases (docs/VALIDATION.md).

License

metal2vulkan is dual-licensed: you can redistribute it and/or modify it under the terms of either of these licenses, at your choice (LICENSE):

As an SPDX expression: GPL-2.0-or-later OR LGPL-3.0-or-later. Each published crate carries the notice and the three texts.

Metal is a trademark of Apple Inc. metal2vulkan is an independent project and is not affiliated with, sponsored by, or endorsed by Apple Inc.

S
Description
No description provided
Readme
1.7 GiB
0 Stars 1 Watchers 0 Forks
Languages
Rust 61.3%
LLVM 31.7%
Metal 3%
Objective-C 2.2%
Python 1.2%
Other 0.5%