macOS Backend
Verified against: 47bf306bc + working tree Covers: crates/passtape-macos
passtape-macos connects Passtape’s backend-neutral execution contracts to
macOS media surfaces.
video file -> MacVideoSourceProvider
-> MacVideoSurface (retained CVPixelBuffer)
-> prepared Metal passes through MacVideoBackend
-> MacMediaOutput (GPU surface, packed CPU frame, or tensor)
-> VideoOutputSession
-> MacVideoFile -> H.264, HEVC, or ProRes
audio file -> MacAudioSourceProvider
-> MacAudioBlock (shared planar f32 samples)
-> prepared CPU work through MacAudioBackend
-> AudioOutputSession
-> MacAudioFile -> AAC, Apple Lossless, FLAC, Opus, or PCM
video and/or audio -> MediaOutputSession
-> MacMediaFile -> encoded video and/or audio
new_runtime() configures both paths. Video and audio sources are registered
independently because a graph may use either stream or assign different source
identities and timeline ranges to them.
MacVideoSourceProvider::add_file opens a video and registers it under the
identity used by a graph’s VideoSource. AVFoundation reads compressed samples
from the container, and a reusable VideoToolbox session decodes them into
Metal-compatible Core Video surfaces. The returned descriptor copies the
identity and decoded format into the graph without storing a path or decoder
object there. VideoToolbox prefers dedicated decoder hardware and may use its
codec fallback when that hardware does not support the stream.
add_file_stream selects a zero-based video track when a container holds more
than one; MacAudioSourceProvider provides the equivalent audio-track API.
Phones record portrait video as landscape pictures with a quarter-turn
rotation in the track header. The provider reads the track’s display
transform and reports the source at its upright size, so the descriptor,
clip fitting, thumbnails, and proxies all see a portrait picture. The
descriptor carries the rotation as a VideoRotation, and preparation always
places a conversion pass after a rotated source, even when the formats
already match; the conversion kernels read each upright pixel from its
stored position, so turning a frame costs no extra pass or surface. The
decoded surface keeps its stored layout and reports the upright size, and
the provider refuses a frame request whose descriptor lost the rotation.
Files decode to 8- or 10-bit 4:2:0 YUV, 10-bit 4:2:2 YUV, BGRA, or RGBA16F, and the
conversion pass accepts each of those into every output format, so a rotated
clip can be exported as anything, 10-bit 4:2:2 ProRes too, with no operation
applied. A turn moves a 4:2:2 source’s full-resolution chroma rows into
half-resolution columns, so only a 180-degree clip keeps every chroma row in a
4:2:2 export. Opening a track whose transform mirrors, scales, or turns other
than by quarter turns fails.
MacVideoSourceProvider::add_image_file decodes a still image once with
ImageIO, applies its stored orientation, and keeps the resulting
Metal-compatible surface. An ImageSource reuses those pixels for every frame
in its graph node’s active timeline range.
Data images live in Core Video’s 32-bit float IOSurfaces, one, two or four
channels, which Metal wraps as R32Float, RG32Float or RGBA32Float
textures with no copy. add_data_image copies a tightly packed f32 buffer
into one, row by row, and registers it as an ImageSource.
add_exr_data_image decodes named channels of any OpenEXR layer, color or
data, as raw 32-bit floats into the narrowest data format for their count,
and an OpenEXR sequence opened with raw channels plays them the same way, so
the R and G of an RGB STMap reach a warp as its two map channels. A still is
uploaded once, when it is registered, and costs no decode or upload per
frame. A graph output of
media type Data reads it back into a CpuVideoFrame of the same format.
Neither copy changes a bit: denormals, NaN payloads and signed zeros survive.
The data kernels, media.data.range, media.data.preview,
media.data.depth_matte, media.video.depth_mask, media.video.stmap_warp
and media.data.lens_map, read texels with integer loads, never through a sampler, and are compiled
into their own library with fast math off, so NaN and infinities are never
assumed away. The warp filters in shader code and fuses every product added
to a sum with fma, as its Rust reference does, so the compiler cannot round
it another way. The lens map is compiled once per lens polynomial through a
function constant: one pipeline holding all three took more than twice as
long, since every pixel paid for the largest polynomial’s registers. An
undistort map’s inverse table is solved by passtape-engine and copied into
a shared buffer, and the last eight tables stay with their buffers.
add_half_float_image uploads an
Rgba16Float color image from f32 values the same way, for tests and the
parity bench.
add_bgra_file is the alpha-preserving alternative for foreground media.
ProRes 4444 and 4444 XQ files decode to RGBA16F, retaining full chroma resolution
instead of converting to subsampled YUV. This uses the existing half-float surface
and conversion path. It does not promise bit-exact recovery of the codec’s samples:
decoder colour conversion and half-float rounding still affect measurements of noise.
A decoded frame occupies 8 bytes per pixel before allocator overhead; the decoder’s
existing byte limit reduces its pending-frame count accordingly. The explicitly
requested straight-alpha BGRA route remains BGRA.
Other ordinary files prefer native bi-planar 4:2:0 YUV surfaces and fall back to BGRA
when a decoder does not declare how its chroma samples are positioned. ProRes
422 and HEVC 4:2:2 files decode to bi-planar 10-bit 4:2:2 instead, so they keep
their full vertical chroma resolution; an 8-bit 4:2:2 stream widens to ten bits
without loss. Every 4:2:2 video standard sites chroma with the even luma
columns, so these surfaces assume that siting when the decoder declares none,
as ProRes does, rather than falling back to BGRA. VideoToolbox decodes no H.264
4:2:2. Alpha
foregrounds decode to straight-alpha BGRA, and preparation converts them as
operations require.
The provider reuses its active compressed reader and VideoToolbox decoder for
nearby forward requests. On a distant or backward request, it keeps the parsed
asset and reuses an AVSampleBufferGenerator, positioning a sample cursor at
the full sync sample the requested frame depends on. This avoids rebuilding
AVAssetReader for each seek. Before restarting from that sync sample, it drains
outstanding decoder callbacks and clears the previous display-order queue, so
it can reuse the VideoToolbox session too. A rejected reuse attempt falls back
to opening and validating a fresh reader. Generated samples are read in decode order, one
at a time, and their timestamps are shifted from media time to track time
when the edit list specifies a constant offset. Intraframe media such as
ProRes then decodes only the requested frame. Samples displayed before that
sync sample are an open GOP’s leading frames; they reference the previous GOP
and are skipped, as are frames before the target that no other frame
references: the container marks them, or for H.264 the slice’s nal_ref_idc
is zero. The decoder holds back only as many frames as the file’s sample table
shows any frame being reordered by, rather than the codec maximum of sixteen.
Reverse playback, and tracks whose edit list is more than one unscaled segment,
instead use AVAssetReader and preroll from one second before the request.
Tracks without usable sample cursors also use that path. If a
reopened reader cannot produce the preceding frame, it restarts at the
beginning to preserve frame selection.
Backward scrubbing of an ordinary forward-playing clip retains the frames already decoded between the sync sample and the requested frame. Nearby backward requests (at most one second apart) reuse that history, bounded to 120 frames and 256 MiB per reader; forward movement releases it. These seeks decode non-reference frames too so cached ranges never cover skipped pictures. Scrub direction does not change frame selection: forward-playing clips still select the frame starting at an exact sample boundary, while reverse-playing clips select the preceding frame.
Each registered file owns one serial decode worker. After nearby forward
requests establish sequential playback, that worker retains at most three
future frames while the calling thread renders and submits the current frame.
Between output sessions, applications can retire an obsolete source with
remove_source(identity) on either provider. This releases its reader and, for
video files, joins its decode worker. Retire plans using that identity first;
unchanged sources remain open, and a removed identity can be registered again.
The VideoToolbox decoder separately retains a bounded set of codec reference,
reordering, and callback frames. VideoToolbox compression and movie writing
also have their own bounded queues, so these stages can overlap without an
unbounded frame backlog. A request still waits synchronously when its frame has
not finished decoding, and file registration waits for initial inspection.
Source descriptors do not assume that files stay unchanged. Call
deterministic_descriptor(content_revision) when the application controls the
file and updates the revision whenever its contents change; this enables
decoded-frame and rendered-output reuse.
MacVideoSurface owns each Core Video pixel buffer through Apple’s reference
counted handle, so moving a frame through Passtape does not copy its pixels.
Metal uses texture views over that storage and allocates intermediate frames
from reusable Core Video pools.
AVFoundation color tags are stored in each source’s VideoFormat and preserved
through prepared surfaces and format-preserving operations. Missing color
characteristics remain unspecified; the missing full-range flag means video
range according to Core Media. Encoders write the prepared tags. PQ and HLG
are preserved by HEVC Main 10 and ProRes output.
HLG RGB conversion uses BT.2100’s luminance-coupled display gain with BT.2020 weights, nominal 1,000-nit peak and gamma 1.2. Linear 1.0 represents 100 nits. The gain is shared across RGB, not applied as independent channel gamma; shared Metal/Vulkan tests check neutral and saturated values in both directions.
Apple Log files leave the transfer tag unspecified and name the curve in Core
Media’s log-transfer extension, which the source reads as Apple Log. Apple Log
2, whose gamut Passtape does not know yet, is refused like any other
unrecognised tag. Other cameras rarely tag their log footage, so
MacVideoSourceProvider::add_file_as registers a file read as the primaries
and transfer an application gives, keeping the file’s matrix and range.
When complete color metadata or pixel storage differs between inputs or outputs, preparation adds an explicit conversion pass. Built-in video operations declare the working representation they need. All of them use half-float RGB, so values outside 0 to 1 survive between operations: drawing, blending, color adjustment, and HDR tone mapping in linear light, and transforms, blur, mix, opacity, masks, and alpha-over in whatever color their input carries. Grading and tone mapping run in linear BT.2020, where HDR and wide-gamut footage stays nonnegative. Source-only encoded output stays in its bi-planar YUV storage and avoids unnecessary conversion.
A conversion into linear half-float keeps values outside 0 to 1: colors outside the target primaries become negative and highlights above reference white exceed 1. Every other output, BGRA, YUV, and transfer-encoded half-float, is clamped to 0 to 1 after encoding.
The conversion shaders support 8- and 10-bit 4:2:0 YUV, 10-bit 4:2:2 YUV,
BGRA, and half-float RGBA. YUV surfaces retain their Core Video chroma
location. Converted 4:2:0 output averages each 2×2 block and is sited at its
center. Converted 4:2:2 output is sited with the even columns, the siting
4:2:2 decode assumes, and filters each chroma sample [1 2 1] across its column
and the two beside it; ProRes stores no siting, so other siting would shift
color on every reimport. PQ and HLG values pass through unchanged when their metadata is
unchanged. Their transfer functions can also be decoded into linear light for
an explicit media.video.tone_map operation before SDR output conversion.
Camera log encodings are decoded in the same conversion, never encoded; see
Video Color Metadata.
Gaussian blur uses two Metal Performance Shaders convolutions with normalized Gaussian weights, sigma = radius / 3, ceil(radius) taps on each side and clamped edges. A half-float temporary texture separates the horizontal and vertical passes, matching WebGPU’s finite filter rather than Apple’s approximate Gaussian. The temporary belongs to the command buffer and is released for reuse after its last encoded read. Its dense size is 8 bytes/pixel for colour (15.82 MiB at 1080p, 112.50 MiB at 5120×2880) or 2 bytes/pixel for a mask. These are scratch costs, not total residency or a measured increase over Apple’s private implementation. Constant radii keep their exact value; animated radii retain prebuilt half-pixel steps so rendering never creates a filter on the frame path. A zero radius uses the existing Metal copy path.
2D transforms use a bilinear Metal pass. They preserve the frame size and sample transparent pixels beyond the source bounds.
Alpha compositing runs as a Metal pass over premultiplied half-float inputs. The foreground alpha selects how much of the background remains at each pixel.
Before an output session starts, the backend reads the prepared surface working set and prewarms each Core Video pool for the session’s bounded in-flight frames. The bound accounts for frame count and estimated surface bytes, including surfaces created only for output resizing. AVFoundation separately owns the codec’s reference surfaces.
When run_with_control is cancelled, the macOS sink tells AVAssetWriter to
abandon the incomplete file. Cancellation is also observed while the writer is
finalizing.
Output materialization can resize each supported pixel format with bilinear Metal kernels. YUV resizing samples its luma and chroma planes directly and accounts for 4:2:0 or 4:2:2 subsampling and chroma location. The resized surface comes from the same reusable Core Video pool system and stays on the GPU path before display or encoding.
Passtape’s custom Metal kernels live in src/shaders and are compiled into one
library when the backend initializes, except the data kernels, which compile
into their own library with safe math to preserve NaN and infinity handling
and the explicit arithmetic used for parity with the web kernels. Gaussian blur uses Apple’s optimized
Metal Performance Shaders implementation instead of a custom sampling loop.
For each rendered frame, the backend records its operations and output resizing into at most one Metal command buffer. Sequential output sessions retain a bounded FIFO of submitted frames and wait for the oldest frame before handing it to the destination. This overlaps Metal execution with later decoding and command recording without allowing surface residency to grow without limit. Direct and interactive frame requests still wait before returning. A source-only frame that needs no GPU work creates no command buffer.
Supported graph operations and their parameters are listed in the operation catalog. The macOS backend executes video operations with Metal while retaining frame storage in Core Video surfaces.
OpenEXR sources
EXR stills and sequences use the shared codec and a CPU chunk-decode pool rather than VideoToolbox. Colour decodes to premultiplied linear BT.2020 half-float IOSurfaces; data uses unconverted 32-bit float surfaces. Sequences have their own byte-bounded look-ahead, reader and scheduler. A cache miss may wait for the requested decode, but decompression runs on the pool. See OpenEXR sources and export for window handling, scheduling, half-float sequence export and measurement limits.
Application-defined Metal effects
MacRuntimeConfiguration pairs a platform-neutral OperationDescriptor with
a MetalEffectImplementation before creating a runtime generation. The graph
continues to store only the semantic operation identity, inputs, outputs, and
parameters; Metal remains confined to this crate.
let descriptor = OperationDescriptor::new(
OpRef::new("editor.effect.agent-created", 1),
"Agent-created Effect",
&[MediaType::Video],
OutputDescriptor::new("output", MediaType::Video),
)
.with_parameter_schema(&[
ParameterDescriptor::new("amount", ParameterType::Scalar),
]);
let metal = MetalEffectImplementation::from_source(
descriptor.op_ref().clone(),
shader_source,
"agent_created_effect",
);
let mut configuration = MacRuntimeConfiguration::new();
configuration.register_effect(descriptor, metal)?;
let pending = configuration.prepare_concurrent_generation(graph, &request)?;
// Native preparation runs on the candidate's video and audio owners while the
// currently published generation remains available for playback.
let next_generation = pending.wait()?;
let generations = MacRuntimeGenerationSlot::new(next_generation);
Custom kernels receive required video inputs at consecutive texture indices,
followed by their output texture. Buffer zero always holds 256 float4: one
per parameter in descriptor order, then zeros. Scalar values use .x, points
.xy, and RGB values .xyz. Textures are straight-alpha, linear-light
RGBA16Float with BT.2020 primaries, Passtape’s working space, and may hold
values outside 0 to 1.
MetalEffectImplementation::from_wgsl builds a kernel from WGSL instead,
translated with naga with every index and texel load clamped in bounds, as
WebGPU keeps them. Every configuration starts with Passtape’s built-in
effects, passtape.shape.rounded_rect and passtape.composite.draw_image:
hand-written Metal kernels that draw the same pixels as the WGSL the web backend
runs, which a test checks. An effect’s inputs take textures 0 and up, and its
output the next; WGSL reads a second input at binding 3. Inputs after the first
keep their own size; the output takes the first’s.
Candidate preparation
compiles only effects used by its graph, caches identical pipelines across
generations from that configuration on the same Metal device, and preserves
Metal’s compiler diagnostic in MacRuntimeGenerationError.
Each call that creates a runtime freezes a generation-specific registry and
backend identity. An editor may continue using its existing generation while
an agent adds an effect to the configuration, creates and validates a later
generation, reprepares the graph, and then publishes the ready runtime and plan
together with MacRuntimeGenerationSlot::publish. Readers that already loaded
the previous generation can finish with it; previously created runtimes are
not mutated.
A request with VideoOutputDestination::CpuBuffer returns a MacMediaOutput
containing a CpuVideoFrame; callers access it with as_cpu_frame or
into_cpu_frame. The backend waits for Metal, copies only the pixel bytes from
each Core Video row, and removes platform-specific row padding. This path is
useful for thumbnails and pixel analysis; encoded-file targets keep surfaces
on the GPU and do not perform the copy.
MacVideoFile supports H.264, HEVC Main/Main 10, HEVC with alpha, and the
ProRes 422 and 4444 families. Main 10 and ProRes 422 use native 10-bit YUV
surfaces; alpha codecs use an alpha-preserving RGB surface. H.264 and ordinary
HEVC support MOV and MP4. HEVC with alpha and ProRes use MOV.
MacH264Mov remains a convenience preset.
VideoOutputSession handles frame submission, backpressure, and finalization.
Finalization blocks, so the session should run on a worker thread.
MacVideoFileSpecification holds the codec, container, and preparation
request without a path. Calling at(path) creates the execution target. Audio
and combined outputs provide matching specification types, which lets an
application prepare once and choose an atomic staging path only when execution
starts.
VideoToolbox compresses rendered Core Video surfaces asynchronously.
AVAssetWriter only places the compressed samples into the MOV or MP4
container. Passtape’s generic encoded-video pipeline moves packets between
those two components in order. Both its packet queue and VideoToolbox’s input
window are bounded; when either fills, the output session pauses rendering
until space is available.
MacVideoFileEncoder is the lower-level sink for callers that
need to drive prepared frames themselves.
3D scenes
A scene pass (passtape.scene.render) draws glTF models, lights, and flat
card pictures by depth through one camera. Its shader is the engine’s
scene.wgsl, translated by naga and compiled with Metal’s default fast math,
which is how Chrome compiles its own translation, so the web backend shades
with the same math. A pass draws into 4× multisampled colour and reverse-Z
Depth32Float depth, both memoryless so they live only in tile memory, and
resolves into the output surface. Opaque draws go first and write depth;
blended materials and cards follow back to front and only test it. A member
whose transform mirrors keeps its front faces, as glTF specifies. The output
is the scene’s display window plus the overscan margin its description
carries; the camera continues its projection into the margin, so the filmback
and film offset still map onto the display window alone.
MacVideoSourceProvider::add_model_file registers a .glb under the identity
scenes name it by. A background thread reads the file, parses it, and uploads
its meshes and mipmapped textures, so the call returns at once and no frame
waits on an upload. A frame drawing the model waits until it is ready, and
fails, naming the model and the reason, if it never loads. A file with the
same content as one already loaded is loaded once. Its uploads are released
when remove_model or a replacement drops the last identity using it and no
frame in flight still reads them. A backend created outside a runtime draws
the models of a provider given to MacVideoBackend::with_models_of.
Offline hosts can call MacVideoSourceProvider::prepare_model after registration
to wait for parsing and GPU upload before accepting a job. It returns the model
loader’s warnings, or an error naming the model and why loading failed. Foxberry
snapshot preparation rejects both failures and warnings so unsupported model
features cannot silently disappear from a published render.
Audio
MacAudioSourceProvider reads 16-bit and 32-bit float WAV files directly: a
block at any sample is one seek and one copy. Other files decode to native
planar f32 PCM through AVFoundation. Nearby requests reuse the decoder;
distant or backward requests reopen it near the requested time, which takes
milliseconds. When a file declares its speaker order, Passtape preserves that
order. Missing or unrecognized layout metadata remains discrete rather than
being guessed from channel count alone.
Real-time playback should not wait for a decoder to reopen. conform_audio_stream
decodes one audio stream once into a 32-bit float WAV at its own sample rate and
channel layout, through a staging file that is renamed into place only when
complete; reads_audio_directly says whether a file needs it. Editors conform
compressed audio in the background and play the WAV. The WAV writer stores any
channel count: layouts a WAV channel mask cannot state exactly, such as other
role orders and discrete channels, keep their roles in a private plyt chunk,
and files whose data passes 4 GiB are written as RF64. The direct reader reads
both.
Preparation inserts CPU passes when the sample rate, speaker layout, or channel
storage order must change. Common mono, stereo, 5.1, and 7.1 layouts are
supported. Downmixing omits LFE and routes center and surround channels at
-3 dB; upmixing leaves speakers absent from the source silent.
MacAudioBackend executes these conversions and audio graph operations. A
matching source-only block can pass through without copying its samples.
MacAudioFile writes AAC, Apple Lossless, FLAC, Opus, or linear PCM. Supported
audio containers are M4A, CAF, WAV, AIFF, native FLAC, MOV, and MP4, subject to
the selected codec. AAC and Apple Lossless support 5.1, and linear PCM supports
7.1. FLAC and Opus output currently support mono and stereo. MacAacM4a
remains the AAC convenience target.
AudioToolbox compresses audio before container writing. PCM is explicitly
interleaved and packetized. MOV, MP4, and M4A use AVAssetWriter; CAF, WAV,
AIFF, and FLAC use Core Audio file services. Codec priming and final padding are
stored as container metadata rather than becoming audible samples.
MacAacM4a is an audio output target. Its PCM format becomes part of the
preparation request. It accepts mono, stereo, or 5.1 planar f32 blocks from
AudioOutputSession and writes AAC in an .m4a file.
Combined movies
MacMediaFileSpecification connects a non-empty selection of prepared video
and/or audio outputs to one MacMediaFile. Keeping the specification attached
to the destination ensures the encoder consumes the exact formats requested
during preparation. VideoToolbox compresses video, while AVAssetWriter muxes
the selected tracks. MOV and MP4 support depends on the chosen codecs.
MacH264AacMov remains a convenience preset.
MediaOutputSession feeds each selected track according to its own
backpressure and timeline.
MOV and MP4 outputs can also carry multiple selectable WebVTT caption tracks.
Attach text graph outputs with RequestedMediaOutput::with_text_tracks; each
track can declare a BCP 47 language and at most one track can be enabled by
default. Text cues are compiled during preparation and muxed without entering
the per-frame render loop.
MacAudioVideoFileEncoder exposes the same two-track writer for callers that
drive prepared media themselves. Each writer input is marked complete when its
stream ends, even when the other stream is longer.