Skip to content

Vision

View .mdllms.txt

framefields runs ONNX vision models locally and exposes the results as signals that layers and effects consume like any other. Every model is pinned to an immutable revision, verified by size and SHA-256, and downloaded lazily on first use. The built-in models are Apache-2.0; prompted tracking (SAM) is an optional package, covered below.

// Whole composition → a reactive bundle
const vision = comp.withVision({
enableDetection: true, // default
enableSegmentation: true,
enablePose: true,
variant: "s", // "t" | "s" | "m"
confidence: 0.35, // default 0.3
classes: ["person"], // COCO filter
});
// One layer → render it through a mode
Layer.video("assets/footage/dancer.mp4").withVision({ mode: "matte", enableSegmentation: true });
Option Model Gives you
enableDetection RTMDet-Ins COCO-80 boxes, tracked over time → vision.objects
enableSegmentation RTMDet-Ins (same pass) soft per-instance masks → vision.masks, vision.segmentation
enablePose RTMO 17 COCO keypoints per person → track.pose, vision.poseLandmarks
enableMatte MediaPipe Selfie Segmenter fast person alpha → vision.segmentation.matte

Layer modes: passthrough, mask, matte, crop, skeleton, boxes, tracking. For cutouts, matteSource: "instance" (default; any class, merges attached parts like a dress or instrument) or "selfie" (people filling the frame only, fastest).

classes picks which instance is the subject, not which parts merge into it. COCO has no clothing class, so a flowing dress may come back as a “kite” or “umbrella” and still joins a classes: ["person"] cutout (2.2+).

For physics, particle deflection, and interactive layout, comp.vision(source, options) analyzes the raw clip frames on demand before drawing a frame. Unlike render-time withVision (which analyzes a layer’s previous rendered frame with a one-frame delay), clip vision decodes the source directly and makes poses and silhouettes available synchronously to the current frame:

const dancer = comp.vision("assets/footage/dancer.mp4", {
pose: true, // 17 COCO keypoints (default true)
mask: true, // soft silhouette including dress/held objects (default true)
maskCell: 8, // grid cell size in source px (default 8)
smoothing: 2, // keypoint temporal averaging in frames (default 2)
});
// Map into composition coordinates
const person = dancer.person.place({ width: 1920, height: 1080, fit: "cover" });
// 1. Read coordinates at any frame
const hand = person.point("rightWrist", 45); // { x, y, visibility }
// 2. Reactive signals for layers
const badge = Layer.box({ width: 80, height: 80, background: "#ff5a1f" });
badge.animate(LayerAnimation.create()
.signal("x", person.signals("nose").x)
.signal("y", person.signals("nose").y));
// 3. Silhouette alpha & gradient (for physics deflection & particles)
const sample = person.sample(45, 960, 540); // { alpha, gx, gy }

Automatic detection picks “the largest person”. Use SAM when you need a specific person or object, a description instead of a click, several people, or a whole group, and want that selection followed through the video, including crowded shots. Three models run locally through comp.vision:

SAM 2.1 Tiny (sam2) SAM 2.1 Small (sam2: { model: "small" }) SAM 3 (sam3)
Select by points and boxes points and boxes points, boxes, or text
Objects per clip 1 1 1, up to maxObjects, or a whole group as one (merge)
Model input 512² 1024² (SAM 2’s native size) 1008²
Per frame, M1 Pro (WebGPU) ~0.27 s ~1.1 s ~3.6 s image encoder + ~0.7 s per tracked object
Download ~83 MB ~112 MB ~1.75 GB on a GPU, ~1.2 GB on the CPU
Weights license Apache-2.0 Apache-2.0 Meta SAM License
Terminal window
pnpm add @framefields/vision-sam

SAM ships in @framefields/vision-sam, an optional, Apache-2.0 peer of framefields. framefields loads it only when a clip uses sam2 or sam3; without it, such a clip fails with an install message, and nothing else changes. No model weights ship in any package: they download on first use. SAM 2.1’s weights are Apache-2.0 and need no acceptance. SAM 3’s weights are under Meta’s SAM License: accept it on the clip with acceptSamLicense: true (or acceptLicense: true inside sam3), or set FRAMEFIELDS_ACCEPT_SAM_LICENSE=1, before SAM 3 downloads or runs. Sam2Tracker and Sam3Tracker, for driving SAM on your own pixel buffers, are exported from @framefields/vision-sam.

import { Composition, Layer, LayerAnimation } from "framefields";
const comp = new Composition({
width: 1920, height: 1080, fps: 25, durationFrames: 750,
backgroundColor: "#151a23",
});
const subject = Layer.video("assets/source.mp4", {
position: "absolute", x: 0, y: 0,
width: 1920, height: 1080, fit: "contain", muted: false,
}).withVision({ mode: "matte" });
comp.add(subject);
const tracked = comp.vision(subject, {
sam2: {
model: "tiny", // or "small" for small, thin or detailed subjects
category: "person",
prompts: [{
frame: 0,
points: [
{ x: 0.25, y: 0.10, label: 2 }, // box top-left
{ x: 0.70, y: 0.95, label: 3 }, // box bottom-right
{ x: 0.48, y: 0.50, label: 1 }, // foreground point
],
}],
},
pose: true, // optional RTMO pass matched to the selected silhouette
});
// Request the stable signal bundle before rendering.
const target = tracked.signals.objects.get(1);
comp.add(Layer.box({
position: "absolute", x: 0, y: 0, width: 1, height: 1,
background: "transparent", borderColor: "#00ffc3", borderWidth: 3,
}).animate(LayerAnimation.create()
.signal("x", target.bounds.screenX)
.signal("y", target.bounds.screenY)
.signal("width", target.bounds.screenWidth)
.signal("height", target.bounds.screenHeight)
.signal("opacity", target.active)));

Tiny or Small. Tiny is the fastest by far and suits a subject that is large in frame: a close-up, a dancer, a speaker. On such a subject its masks match Small’s closely (IoU 0.98 on a close-up). Pick Small, at about 4× the cost, when the subject is small, thin or detailed (a ball, hands, a bike, hair, a distant runner), or when Tiny latches onto a look-alike after a cut. If unsure, prototype with Tiny on a short trimmed stretch and switch if edges, small parts or identity fail.

By description, several objects, or a whole group (SAM 3)

Section titled “By description, several objects, or a whole group (SAM 3)”
// One person, by description
const hero = comp.vision(subject, {
acceptSamLicense: true,
sam3: { category: "person", text: "man in white shirt" },
});
// Every member as its own track, 1…N by score
const crowd = comp.vision("assets/source.mp4", {
acceptSamLicense: true,
sam3: { category: "person", text: "student in blazer", maxObjects: 5 },
});
crowd.signals.objects.get(2); // the second-best match
// A whole group as ONE object: one mask, one memory
const students = Layer.video("assets/source.mp4", { width: 1920, height: 1080, fit: "contain" })
.withVision({ mode: "matte" }); // cuts the whole group out as one entity
comp.add(students);
comp.vision(students, {
acceptSamLicense: true,
sam3: { category: "person", text: "students in black jackets", merge: true },
});

Read the request’s number first. “The man in white” is one object. “The students” or “everyone in black jackets” is a group: use one clip with one prompt and merge: true. Never select a group one member at a time, or through several clips with overlapping prompts. That re-detects the same people as duplicate, overlapping masks, at many times the cost. Use maxObjects (without merge) only when each member needs its own box or ID.

How the group modes cost:

  • merge: finds every match in one pass of the text model, combines the masks into one seed, and tracks it as one object. A whole crowd costs the same as one person. In the test below that was 4.1 s per frame on an M1 Pro.
  • maxObjects: gives each member its own memory, at about 0.7 s per member per frame.

Grammatical number in the prompt does not matter. “students in black jackets” and “student in black jacket” selected the same group (87% of the frame either way).

Text prompts are concepts: name what sets the target apart in that shot. In a crowd where every student shows a white collar, “man in white shirt” picks a student. In the same film’s wide shot, where only the main character has no blazer, it picks him. Check the first frame of every prompt. Two clips in one shot can claim the same person, so write prompts that exclude each other (“students in black jackets” left out the main character in a white shirt).

With several tracks, one image-encoder pass per frame serves every track, and where tracks overlap the more confident one keeps the pixel. signals.objects.get(k) and signals.masks carry tracks 1…N, and the clip’s matte is all tracks merged. A later text prompt re-selects every track (IDs renumber). A points prompt with object: k seeds or corrects only track k; the next unused ID adds a track. On a text prompt’s frame, each selected object outputs and remembers the selection mask itself, as SAM does.

Coordinates are normalized to the original source image: (0, 0) is top-left and (1, 1) is bottom-right. They are independent of the layer’s placement.

Label Meaning
1 Include this foreground point
0 Exclude this background point
2, 3 A box’s top-left and bottom-right corners, in that order

Prompt frames must be nonnegative, unique, increasing integers inside the source video. They use the source analysis clock (fps in clip-vision options, default composition FPS), before trimming, start offsets or time remapping. A prompt at a later source frame corrects the selection and becomes the new conditioning frame. Frames before the first prompt are empty and are not analysed. To track only a stretch of a long clip, trim the layer (and pass trimStartSec to clips created from a path) and prompt on the stretch’s first source frame. Re-prompt across cuts or when identity is lost: appearance tracking cannot guarantee re-identification after occlusion.

SAM supplies masks, not skeletons. Pose is off in SAM mode; pose: true runs RTMO and associates its result with the selection. tracked.person.place(...) maps silhouette sampling and optional pose landmarks into a layer’s placement. The object/mask bundle in tracked.signals uses source geometry on the composition clock, so the bounding-box example above assumes a full-frame layer at source dimensions.

  • The first request runs inference from the earliest prompt through every required intervening source frame, in order, so seeking forward can take time. Reverse playback, holds and time remapping read the cached source-frame results.
  • Lower analysis FPS repeats the preceding analysis mask at intermediate playback frames. Default smoothing is zero in SAM mode; an absent object remains empty instead of inheriting another person’s mask.
  • A default withVision({ mode: "matte" }) layer of the same source reuses the selection’s masks; with several SAM clips of one source, it links to the first one created. Preserve the source aspect ratio through matting and crop afterward. An explicit selection fails clearly if its mask cannot align, rather than switching to automatic detection.
  • Masks are binary object masks, not alpha matting: fine hair, thin objects and heavy occlusion can need corrections, SAM 2.1 Small, or a higher-detail workflow.
  • Full-resolution masks are kept as compressed history and decoded lazily for signals. Cache identity includes the source file, options, all prompts, the pinned model revisions and the SAM 3 encoder precision. tracked.release() frees inference sessions while leaving analyzed results readable; further uncached requests replay temporal memory.

All SAM assets download lazily into the normal model cache, verified by size and SHA-256; modelsDir, baseUrl and the vision provider settings apply. SAM 3 downloads only the image encoder its backend runs fastest:

Backend SAM 3 image encoder Why
WebGPU (Macs, the preview) fp16, 935 MB Measured on an M1 Pro for one 1008² frame: fp16 3.65 s, q4f16 4.43 s, q4 6.63 s, int8 140 s (its ops fall back to the CPU). 4-bit weights are dequantized before every matmul on WebGPU, so they save memory, not time.
CUDA (Linux, NVIDIA) fp16 fp16 is what NVIDIA’s tensor cores are built for
CPU q4, 369 MB CPUs have no fast fp16 path; about 9× slower than WebGPU, so a last resort

Override with sam3: { precision: "fp16" | "q4f16" | "q4" }. Every SAM 3 clip in a process shares one image encoder and reuses its result per frame, so a main character and a crowd from one source cost one encoder pass. Setup takes about 2 minutes on an M1 Pro: loading the models, then text selection on the prompt frame. After that, measured on an M1 Pro: 20 frames with 6 tracks took about 5 minutes, and a whole group with merge took 4.1 s per frame. Prototype prompts on a short trimmed stretch; results are cached, so re-rendering after changing layout, colours or effects skips SAM entirely.

SAM runs in the preview too, on the browser’s WebGPU, with models served from the local cache. For a clip outside the project, add its folder to startPreview(…, { root: [process.cwd(), dir] }).

pnpm --filter @framefields/vision-sam test:sam2 (Tiny and Small) and test:sam3 in the engine repository run opt-in native-Dawn tests with real weights and a moving target plus distractor.

Results are cached on disk in ~/.cache/framefields/vision (or $FRAMEFIELDS_VISION_CACHE_DIR) keyed by file size, modification time, and options. A second run, or a final render after a browser preview, reuses cached results for frames already analyzed. SAM masks are stored separately from silhouette/pose data; new uncached frames may require replaying temporal memory.

  • Live physics worlds: When used with world.live(comp), the simulation advances frame-by-frame alongside vision preparation, so preview starts immediately without waiting to analyze the whole video first.
  • GPU particles: Pass push: { person, strength, sweep } to Layer.particles to have the performer push particles away from their moving silhouette.
  • Initial layout: Call await dancer.ready(0) up front if you need the initial pose at frame 0 to position elements before the animation starts.
// Pin a label to the main subject
Layer.text("SUBJECT 01", { fontSize: 40, fill: "#f8fafc" }).pinToObject(vision.objects.primary, {
anchor: "topCenter", offsetY: -48, smoothFrames: 5, hideWhenLost: true,
});
// Drive an effect from mask coverage
Layer.box({ width: 1920, height: 1080, background: "#000" })
.withEffect(new Vignette({ strength: vision.segmentation.subject.coverage, radius: 0.9 }));
// Editorial one-liners
comp.addSubjectSandwich({ source: "assets/footage/dancer.mp4", behind: [headline], feather: 4, fit: "cover" }); // text behind subject
comp.addSmartFraming({ source: "assets/footage/action.mp4", target: vision.objects.primary, targetAspect: 9 / 16, damping: 0.15 });
comp.addSubjectOutline(vision.segmentation.subject, { source: "assets/footage/character.mp4", color: "#ff5a1f", width: 6, blur: 12 });
layer.blurRegion(vision.objects.byCategory("person"), { strength: 30 }); // anonymize

Anchors: center, topCenter, bottomCenter, topLeft, topRight, bottomLeft, bottomRight, centerLeft, centerRight. pinToLandmark(coord, { offsetX, offsetY }) pins to a pose keypoint.

Group Highlights
objects primary, get(trackId), byCategory(cat, rank), count, hasCategory
objects.*.bounds x, y, width, height, screenX/Y/Width/Height, area, aspectRatio
objects.*.kinematics vx, vy, speed, acceleration, headingDeg
objects.*.pose 17 keypoints, hasPose, wristSpeed, handRaised, bodyTiltAngle
masks subject, get(trackId), count; per mask area, coverage, solidity
segmentation subject, humanSilhouette, instanceMasks, matte.coverage
classes per class count, maxConfidence, present

vision.summary(frame) returns a deterministic, serializable snapshot — safe inside a frame hook.

const report = await comp.analyzeVisionSequence("assets/footage/street.mp4", { tasks: ["detect", "pose"], categories: ["person"] });
report.tracks; // [{ trackId, category, frames: [start, end], centerPath, … }]

A zod-serializable report of what is in the clip, without ffmpeg — use it to decide where to place things.

Timing: rendered-frame and source-frame analysis

Section titled “Timing: rendered-frame and source-frame analysis”

Unlinked render-time withVision reads each layer’s previous rendered frame. Frame 0 has no results, and masks trail the plate by one frame. The following rules apply to that path:

  • renderVideo renders in order and handles this.
  • For stills, render at least two consecutive frames with the same HeadlessMediaRenderer and keep the last.
  • Don’t verify vision with renderFrameGrid: jumping between frames cuts out pixels from another frame and shows a ghosted double.

comp.vision analyzes the source before the current frame draws. A linked clip matte, including SAM, uses that frame’s cached mask without the one-frame delay. A cached absent subject is authoritative and renders empty.

On framefields 2.2+, detection, segmentation and pose can run through WebGPU (onnxruntime-web, installed with framefields) on the renderer’s device. Inputs that are already GPU textures can stay on the GPU for preprocessing. The automatic provider picks its backend once per process, before any model downloads: on Linux with the NVIDIA driver loaded it tries CUDA first (onnxruntime-node, needs CUDA 12 and cuDNN 9), then WebGPU, then the CPU. Clip vision decodes each clip’s source separately; SAM’s video pipeline keeps its temporal memory in bounded host arrays. To require WebGPU and surface initialization failures, set FRAMEFIELDS_VISION_PROVIDER=webgpu. The log tells you which backend runs and, on a fallback, why:

{"backend":"webgpu","sharedDevice":true,"msg":"[vision] Inference on the GPU (WebGPU)"}
Env Effect
FRAMEFIELDS_VISION_PROVIDER auto (default: CUDA first on Linux with the NVIDIA driver, then WebGPU, then CPU), webgpu, cpu, or cuda (Linux x64; needs CUDA 12 and cuDNN 9). A forced backend that fails throws instead of falling back
FRAMEFIELDS_VISION_THREADS CPU threads per model (default on Linux: the CPUs the process may use)

Measured on the GPU, three vision layers, 60 frames at 1280×720: about 17 s on an M1 Pro, about 7 s on an RTX 3070.

Task (on the CPU, per ~2K frame) t s m
detect + segment (one pass) 150–300 ms 200–340 ms 420–700 ms
pose ~50 ms ~120 ms ~280 ms
matte ~20 ms ~20 ms ~20 ms
  • Start with "s"; use "m" for fast motion or busy backgrounds.
  • Raise confidence to ~0.5 on stylized footage; restrict classes to stop the subject switching.
  • Garment drops out of a cutout → variant: "m" or keyBackground: true. Halo on dark backgrounds → lower featherRadius or raise maskThreshold.

Models cache in $FRAMEFIELDS_MODELS_DIR (default ~/.cache/framefields/models). For CI or air-gapped renders, preload once or point FRAMEFIELDS_MODELS_BASE_URL at a mirror.

import { VisionRunner } from "@framefields/vision";
const runner = VisionRunner.create({ variant: "s" }); // zero I/O until used
await runner.preload(["detect", "pose"]); // downloads + verifies SHA-256 (~380 MB for all models)
runner.close();

For SAM model assets without creating inference sessions (here SAM 2.1 Tiny; SAM_MODELS lists every SAM file with its URL, size and SHA-256):

import { VisionModelStore } from "@framefields/vision";
import { ensureSamModelsRegistered, SAM_MODELS } from "@framefields/vision-sam";
ensureSamModelsRegistered();
const store = new VisionModelStore({ acceptLicense: true });
for (const model of SAM_MODELS) {
if (model.key.startsWith("sam2.1-tiny-")) await store.ensure(model.key);
}