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:
- HDR or linear-light delivery becomes a product requirement. Vello composites in 8-bit sRGB.
- Text composited onto 3D at its projected pixel density looks wrong.
- The offscreen-and-copy path dominates frame time in a realistic effect-heavy 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:
- Jobs.
nippo job NAMEsplits the frames into segments (--segment-seconds, default 4). It renders each segment toOUT.parts/seg-NNNN.EXT, picture only. A segment counts as finished only when the file is there and its.idmatches. The.idhashes the export settings,effect_scale, the frame range and the programs drawn at the segment's first and last frames. An edit that changes what a segment shows renders it again;--freshrenders all. A segment renders under.partialand is renamed when done, so an interrupted job never trusts a half-written file. The coordinator computes every identity, because programs name fonts by registration order, which differs between processes.pkg.render.assemble!joins the segments with ffmpeg's concat demuxer, copying the picture without re-encoding. It mixes and levels the sound once over the whole, as a single render does. - Concurrency from measurement. A job renders its
pending segments in contiguous runs: the coordinator renders one run and
worker processes (
hd run -- segment ... --segments 3,4,5) render the rest, overlapped withmap_join!. Each run with two or more segments records frames a second by process count inOUT.parts/profile.pkg.job.choose_workerstries two processes, then one, then keeps the faster;--workersoverrides. Two processes help when the encoder or hd's frame building is the limit, since each process runs its own encoder and hd instance. When the GPU is the limit they don't, and the profile shows it. - Bounded caches. The resolver's shaped-text cache
keeps two generations of
SHAPED_LIMIT(2,048) entries each; a hit in the older generation moves back.Mediakeeps at mostLIVE(8) decoder processes beyond what one frame needs, stopping the one used least recently. Each decoder readsAHEAD(4) frames ahead on its own thread, so decoding overlaps drawing with a fixed memory cost per slot. - The canvas has its own thread.
Gpucalls run on a thread that owns the canvas, so hd builds the next frame while this one is encoded for Vello, drawn and read back.drawandrepeatare posted (hd runs at most one frame ahead; a failure is reported by the next call); every other call waits for its answer. A posted frame carries its own copy of the footage-frame table, whichMediafills for the next frame meanwhile. - Vello's image atlas is cleared before it drops an
image. Effect results reach Vello as images, copied into its
atlas. Their sizes animate, so the atlas fragments; at its largest size
(8192²) Vello used to skip an image that didn't fit, and the frame lost
that effect's whole subtree.
vello_encodingis vendored beside Vello (changes markednippo:): before skipping, the atlas is cleared once and refilled with what the render draws. - One submission a frame. Everything a frame does on
the GPU (offscreen Vello renders, dispatches and draws, the frame's own
render and its readback copy) goes to the queue as one submission. Vello
is vendored (
native/vendor/vello, changes markednippo:) for that: while a batch is open its renders record command buffers instead of submitting them, and the buffers they free return to its pool only once the batch is submitted, so a later render in the frame can't write into a buffer an earlier one still reads. Dispatch uniforms are filled at creation for the same reason: queued writes all land before the submission. The vendored Vello also keeps the textures a render frees (its image atlas and gradient ramps) in a pool for later renders, since a new texture costs a driver mapping and a zero fill every render, and runs consecutive dispatches in one compute pass. - Media batching. The paint loop collects every
footage draw of a frame and makes one
Media.frames(requests)call withhandle pts slottriples. Decoders in the batch are never stopped for each other. Every decoder that must start or seek starts before any is waited on, so their start-up overlaps. Frames are shared with the upload as reference-counted buffers, not copied.Media.frameis a batch of one.
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:
- Color. Every YUV export converts with the BT.709
matrix, limited range
(
scale=out_color_matrix=bt709:out_range=tv).setparamstags primaries, transfer, matrix and range, so players decode the colors drawn.Mediadecodes untagged HD (720 lines and up) as BT.709, as players do, and tagged streams by their tags. - Loudness.
Video.loudness(Loudness::streaming() | podcast() | broadcast()).pkg.delivery.program!mixes the tracks in hd the way the audio graph will.pkg.loudnessmeasures it (BS.1770: K-weighting, 400 ms blocks, absolute and relative gates). The graph then applies one gain, plus analimiteronly when the gain would cross the peak ceiling. The limiter holds the ceiling lessCODEC_HEADROOM(1 dB), because AAC overshoots the samples it is given on sharp transients. When it limits,leveling!runs the gained sound through a model of the limiter (5 ms lookahead, 50 ms release) and raises the gain by the loudness it takes, until the result meets the target. Dynamics stay as mixed; this is the two-pass result without a second encode. - Codecs.
--codec h264 | hevc | h264-hw | hevc-hw | prores | vp9.-hwis VideoToolbox at constant quality (--quality, default 65). ProRes 4444 and VP9 carry alpha;Mediadecodes VP9 with libvpx, which keeps alpha. - Delivery checks.
nippo deliverrenders, then checks the file. It confirms size, rate, length and that a sound stream is present. Three stills drawn again must match the export decoded as a player decodes it. The measure is the mean difference of 16×16 block averages, within 2.5 levels per channel, alpha included for alpha profiles. Block averages cancel the codec's loss on edges and fine detail; a wrong color matrix shifts whole areas and stays. Measured loudness must be within 1 LU of the target, sample peak within 0.5 dB of the ceiling.Media.pixelsis the primitive behind the frame comparison.
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.