5. Native boundary

hd decides the video; native executes primitives. Rust compiles slowly and hd iterates fast, so everything that can be hd is hd. Native code exists for what hd cannot do: talk to the GPU, shape fonts, decode and encode media. It never decides what a frame contains, how passes are ordered, or what to cache.

The boundary is four @host traits in src/native/mod.hd: Shaper, Gpu, Media and Output.

Capability Native does hd does
Shaper Font parsing and registration of font files hd loaded, shaping, glyph and source-cluster data, glyph outlines as path commands Font selection, fallback, line breaking, layout, text selection, morph correspondence, sampling shapes
Gpu / Canvas Device and queue, textures, storage buffers, Vello drawing, compiling supplied WGSL into compute or render pipelines, dispatches and draws, readback Shaders, geometry and their WGSL frames, pass planning and ordering, atlas packing, scope reuse, texture pooling, color policy, caching
Media Probe, demux, seek, decode, PCM extraction, surface import or transfer, codec state Clip time maps, requested timestamps, frame selection, look-ahead, proxies, audio analysis
Output / Encoder Encode and mux, bounded submissions, draining, granted file or stream sinks Export profiles, audio mix and filter plans, timestamps, delivery policy, reporting

Native owns in-flight resource lifetimes, handles, device affinity and codec state; that does not make it own components, animation, layout, particles or a timeline. An upload copies the Wasm buffer or uses an explicit stable-allocation contract; queued GPU work never keeps a pointer into movable guest memory.

The GPU command list

hd sends each frame as one list of numbers, in one call. Native executes it in order:

Command Native does
vector ops Fill, stroke, glyphs, image, layer, clip, mask, blend, push/pop transform, appended to the scene being built
texture id w h format Makes sure texture id exists at that size: straight rgba8 (a Vello target), premultiplied rgba16f, or premultiplied rgba8 (a render target). Vello draws both 8-bit kinds as images
free id Drops texture id
buffer id floats... Makes sure storage buffer id holds the floats
render id ... end Draws the vector ops between them into texture id with Vello
dispatch pipeline gx gy resources... uniforms Runs a compiled compute pipeline: binding 0 is the uniforms, then the textures, buffers and the shared bilinear sampler in order
output pipeline bytes gx gy From now on, each finished frame goes through a compiled compute pipeline (binding 0 the frame, binding 1 a storage buffer of bytes bytes) and that buffer is what reaches the encoder; hd uses it to send 4:2:0 YUV
draw pipeline target clear vertices instances resources... uniforms Runs a compiled render pipeline into texture target, premultiplied over, with the same bindings
draw texture id transform Draws texture id as an image in the scene being built
end of list Renders the frame's own scene to the output and reads it back

compile(wgsl) builds a pipeline from complete WGSL, with the layout taken from the shader, and returns its id or the compiler's message. WGSL with a @vertex entry becomes a render pipeline, built once more for each texture format it draws into and each draw mode (depth test, 4× multisampling); anything else becomes a compute pipeline. The WGSL frames around user kernels and geometry, the load and store passes, blur, particles and every look are hd strings.

hd plans a frame's shaders: it orders scopes by height (leaves first; a scope's height is one more than the tallest scope inside it), reuses identical scopes, packs each height's inputs into shared atlases drawn by one Vello render, assigns pooled textures, and emits the dispatches. Native batches consecutive dispatches into one compute pass; that is execution, not policy.

Scenes without shaders skip all of this: one Vello render, as before.

Vello

Vello stays the 2D rasterizer. Its exact-coverage antialiasing suits text, which explainer videos are mostly made of. nippo uses nearly all of its vector model. Custom pixels and geometry go around it as textures; they don't need to run inside it. 3D renders into textures and is composited the same way, as compositors such as After Effects and Nuke do.

Reopen this decision when one of these is shown in a real video:

Vello and the shader passes share one host-owned GPU context and queue.

Vello 0.12's Renderer::render_to_texture takes a device, queue, scene and texture view; its documented target is Rgba8Unorm with STORAGE_BINDING. It does not accept an arbitrary FP16 render target. register_texture uses the image-atlas path, requires RGBA8/COPY_SRC and assumes straight alpha unless the image says it is premultiplied (its fine shader handles both); it copies, so it is not a zero-copy bridge for processed images. Changed overrides require mark_override_image_dirty. Queue ordering is feasible, but the public API does not promise embedding every Vello draw and custom pass in one caller-owned command buffer. Vello Renderer API.

So a scope's first kernel converts Vello's straight 8-bit output to premultiplied working color as it reads, passes between kernels hold premultiplied half floats, and its last kernel converts back to straight 8-bit as it writes: each kernel compiles twice, once writing half floats and once as a last pass. A scope with one kernel is one dispatch. Only a scope without kernels runs the separate load and store passes. FP16 intermediates can improve subsequent glow accumulation; they cannot restore precision or range already lost upstream. Establish the selected path's transfer/alpha behavior with small color-ramp and blend fixtures: Unorm alone does not specify image meaning. Preserve the fast vector-only route for scenes that do not need extra passes.

Preparation, footage and sound

Preparation resolves assets, font manifests, media metadata, speech duration, caption alignment, morph correspondence and expensive static layouts before rendering. Store content hashes and relevant tool/model/settings versions alongside the actual generated bytes. Reproducibility depends on retained results; a prompt and seed do not guarantee that a service will regenerate identical media later. Network requests remain outside frame evaluation.

A prepared VideoAsset should record its stream identity, exact time base, presentation timestamps, available source interval, orientation, pixel aspect ratio and color/alpha interpretation. The pure component requests an image at source time. Native performs the stateful packet, seek, reference-frame and reorder work. Real underlying APIs include avformat_seek_file, avcodec_send_packet and avcodec_receive_frame; AVFrame carries presentation and color metadata. FFmpeg demux APIs; send/receive contract; AVFrame.

For variable-frame-rate footage, select by presentation interval, not seconds × nominal_fps. Seek to an appropriate earlier decode point, then decode through to the required presentation time. Reverse playback should use bounded decoded windows or prepared proxies. A random-access public interface must not imply constant-time seeks. Cache decoded surfaces by asset, stream, timestamp and conversion format, with explicit memory limits.

Built: prepare_footage!(path) hands the file to Media.open, which keeps it in a file of its own and probes it with ffprobe (size, nominal rate, duration, sound). Footage.at(t) and Footage.play() (at the local clock) give a Footage node; the resolver gives every footage draw in a frame its own slot; before the frame draws, the render loop calls Media.frame(handle, microseconds, slot), which decodes through an ffmpeg child process per (clip, slot), forward, holding the last frame and restarting at a seek when asked to go back or more than two seconds ahead; played backwards (each request a few frames behind the last), it decodes the run of up to 30 frames ending at the one asked for (at most 128 MB) and serves the next requests from it, one seek per run; and the program's UPLOAD texture slot time copies the frame into texture FOOTAGE + slot, drawn by DRAW_TEXTURE. Frames are resampled to the nominal rate (constant frame rate); rotation metadata is ignored. Footage.sound() is an AudioClip (with from to start inside the file), and analyze_footage! decodes mono 48 kHz samples through Media.pcm for the same RMS and onset analysis as WAV.

Still images: prepare_image!(path, name) reads PNG or JPEG bytes and takes the size from the header in hd, so layout and checks need no GPU. Video.images([...]) lists them; rendering registers each once with Gpu.image, and image(name) or Still.draw() draws one.

Support three honestly reported paths: software decode plus upload; hardware decode plus compatible GPU import; and hardware decode plus transfer/upload. FFmpeg distinguishes av_hwframe_map from av_hwframe_transfer_data; neither establishes universal zero-copy interoperability with wgpu. The native boundary reports format, device, transfer and lifetime requirements, while hd selects policy. Software codecs remain compatible with mandatory GPU rasterization. FFmpeg hardware-frame APIs.

Audio remains a separate timed signal. Footage convenience functions can pair picture/audio trims and retiming under a documented pitch policy. A visual echo never implicitly echoes sound. Keep mix decisions in hd, including generation of the existing FFmpeg filter graph. Prepare waveform min/max pyramids, RMS envelopes, spectrum windows and onset/beat estimates once; record window/hop/sample-rate conventions and expose confidence or manual overrides. Rendering samples these immutable arrays.

TTS, transcription and forced alignment are preparation adapters returning retained audio and timing data. Provider alignment may require conversion to word intervals; preserve the source mapping. ElevenLabs' real convert-with-timestamps endpoint is one such adapter input, not a native framework dependency. Screen-recording zoom can similarly use a prepared pointer/click sidecar or an authored focus curve, with maximum zoom and caption-safe framing. Timed speech API; Screen Studio auto zoom.

Sampling, caches and parallel work

Built:

Cache preparation separately from frame results: fonts/shaping, endpoint layouts, parsed assets, geometry and reusable draw commands have different lifetimes from decoded surfaces or processed images. A cached image must match content, captured immutable inputs, local sample time, viewport/resolution, quality, effect/kernel version and color/alpha contract. Include every upstream dependency, including an explicit glass backdrop or the additional times requested by echo. An unchanged node ID does not establish unchanged pixels.

Source identity must survive repeated samples. Construct retained clips during video construction, or use explicit stable source identities; a new closure allocation is not automatically a cache key. Arbitrary pure callbacks remain valid and may rebuild nodes each sample. The implementation must not promise static dependency extraction from arbitrary hd code. Cache what can be proven equivalent and evaluate the rest conservatively.

Retiming maps a component's local time to its upstream source time. Cache keys must reflect that mapping and source duration metadata. A frozen source can be reused while downstream grain still changes. Temporal effects request declared neighboring samples, including signed shutter offsets; they do not consume whichever frame happened to render last. A blur samples its complete input scope, so an animated transform contributes only when inside that scope. Group opacity, mask/glow order and semantic editing must remain unchanged by optimization.

Use a bounded pool of independent Wasmtime stores/instances for parallel frame building, sharing compiled modules and immutable host assets where appropriate. Do not concurrently enter one mutable store. Wasmtime's multithreaded embedding example uses shared engine/module state with separate stores. Coordinate one GPU queue and bounded in-flight resources first; additional CPU workers help only while building frames is limiting. Decoder request ordering and output presentation ordering remain explicit. Wasmtime multithreaded embedding.

Distributed rendering comes after local measurement. Lock project/assets, output range, seeds, quality and backend versions. Assign contiguous frame ranges to reduce seeks, include temporal dependencies, and discard duplicated boundary outputs. Stateful simulations require prepared bakes or defined checkpoints. Compressed chunks need compatible encoding and timestamp/mux handling; byte concatenation is not a general assembly method. Mix and normalize audio once. Promise stable semantic requests and tested pixel tolerances, not universal byte identity across GPUs or hardware encoders.

Color, alpha, codecs and loudness

Built:

Make transfer function, primaries, range, alpha convention and bit depth part of surface metadata. Use an explicitly defined working space and premultiplied compositing, with deliberate conversions at straight-alpha/file boundaries. Specify the working domain for artistic blend modes. Begin with a validated SDR path; end-to-end HDR needs an audited vector boundary, luminance convention, gamut/tone mapping, PQ/HLG conversion and delivery metadata. Neither a floating-point intermediate nor a ten-bit codec option is sufficient.

Named export profiles should expose their resolved settings and validate codec, container and pixel format together. Keep H.264/x264 as the controlled baseline, then offer HEVC/AV1 where the selected build supports them. Alpha profiles can wrap real options such as prores_ks -profile:v 4444 -pix_fmt yuva444p10le -alpha_bits 16 and libvpx-vp9 -pix_fmt yuva420p. FFmpeg documents ProRes 4444/4444XQ and alpha-bit choices; its libvpx encoder implements alpha formats. Probe the installed build and verify transparent output after decoding in intended consumers. FFmpeg codec options; libvpx encoder source.

Keep effects on the GPU and permit one bounded final readback when required. Raw RGBA sent through FFmpeg stdin is not zero-copy. A hardware encoder using compatible surfaces is a separate measured path with its own quality, format and lifetime constraints. Output should accept a granted file or stream sink so finishing a movie does not require returning the entire file through Wasm memory.

Normalize the final audio mix when a delivery profile requests measured integrated loudness and a true-peak ceiling. FFmpeg's loudnorm supports measurement and a second pass using measured_I, measured_LRA, measured_TP and measured_thresh; linear mode can fall back to dynamic when constraints cannot be satisfied. Set output sample rate explicitly. Targets are configurable delivery choices, not one universal social-video standard. FFmpeg loudnorm.

This page’s source on GitHub