Skip to content

Code-first video & image, rendered natively on WebGPU.

feat(vision-sam): re-detect SAM 3 text matches every N frames

okanaslc785aa143d63
diff --git a/.changeset/sam3-redetect.md b/.changeset/sam3-redetect.md
new file mode 100644
index 00000000..f0531237
--- /dev/null
+++ b/.changeset/sam3-redetect.md
@@ -0,0 +1,6 @@
+---
+"@framefields/vision-sam": minor
+"framefields": minor
+---
+
+`sam3: { redetect: N }` runs the last text prompt again every N frames and adds the instances no tracked object covers yet: people who walk in, step out from behind someone, or were lost. With `merge` they join the one object (what it already tracks stays at full resolution); otherwise they become new track IDs up to `maxObjects`. The text features are encoded once per prompt.
diff --git a/packages/framefields/src/clip-vision.ts b/packages/framefields/src/clip-vision.ts
index 8a77ab88..fb846bd4 100644
--- a/packages/framefields/src/clip-vision.ts
+++ b/packages/framefields/src/clip-vision.ts
@@ -644,6 +644,7 @@ export class ClipVision implements ClipSubjectSource {
textThreshold: settings.textThreshold,
maxObjects: settings.maxObjects,
merge: settings.merge,
+ redetect: settings.redetect,
precision: settings.precision,
acceptLicense:
this.options.acceptSamLicense ?? this.options.sam3?.acceptLicense,
diff --git a/packages/vision-sam/src/sam3/sam3.test.ts b/packages/vision-sam/src/sam3/sam3.test.ts
index 4ac865f2..09e11315 100644
--- a/packages/vision-sam/src/sam3/sam3.test.ts
+++ b/packages/vision-sam/src/sam3/sam3.test.ts
@@ -50,6 +50,12 @@ describe("SAM 3 video tracker", () => {
textThreshold: 1.5,
}),
).toThrow("textThreshold must be between zero and one");
+ expect(() =>
+ validateSam3Prompts({
+ prompts: [{ frame: 0, text: "valid" }],
+ redetect: 2.5,
+ }),
+ ).toThrow("redetect must be a nonnegative integer");
});
it("computes 2D sinusoidal position embeddings with expected dimension", () => {
diff --git a/packages/vision-sam/src/sam3/selection.test.ts b/packages/vision-sam/src/sam3/selection.test.ts
index 442e7a86..edcc4c5e 100644
--- a/packages/vision-sam/src/sam3/selection.test.ts
+++ b/packages/vision-sam/src/sam3/selection.test.ts
@@ -1,5 +1,11 @@
import { describe, expect, it } from "vitest";
-import { mergeSelections } from "./selection.js";
+import {
+ coveredCells,
+ keepTracked,
+ MASK_LOGIT,
+ mergeSelections,
+ uncovered,
+} from "./selection.js";
describe("mergeSelections", () => {
it("keeps every instance in one mask, at its most confident logit", () => {
@@ -20,3 +26,48 @@ describe("mergeSelections", () => {
expect(Array.from(mergeSelections([a]))).toEqual([2, -2]);
});
});
+
+/** 1008² logits, positive inside the rectangle (in 1008 px). */
+function tracked(x0: number, x1: number, score = 5) {
+ const logits = new Float32Array(1008 * 1008).fill(-MASK_LOGIT);
+ for (let y = 0; y < 1008; y++)
+ for (let x = x0; x < x1; x++) logits[y * 1008 + x] = MASK_LOGIT;
+ return { logits, score };
+}
+
+/** A 288² instance, positive over columns [x0, x1). */
+function instance(x0: number, x1: number): Float32Array {
+ const logits = new Float32Array(288 * 288).fill(-3);
+ for (let y = 0; y < 288; y++)
+ for (let x = x0; x < x1; x++) logits[y * 288 + x] = 3;
+ return logits;
+}
+
+describe("re-detection", () => {
+ it("adds only instances the tracked objects do not already cover", () => {
+ // Tracked: the left half. Instances: inside it, straddling (mostly outside), and outside.
+ const covered = coveredCells([tracked(0, 504)]);
+ const inside = instance(20, 100);
+ const straddling = instance(130, 200);
+ const outside = instance(200, 280);
+ expect(uncovered([inside, straddling, outside], covered)).toEqual([
+ straddling,
+ outside,
+ ]);
+ });
+
+ it("treats a lost object (negative presence) as covering nothing", () => {
+ const covered = coveredCells([tracked(0, 1008, -1)]);
+ expect(uncovered([instance(0, 288)], covered)).toHaveLength(1);
+ });
+
+ it("keeps the tracked mask at full resolution and adds new instances to it", () => {
+ const added = new Float32Array(1008 * 1008).fill(-MASK_LOGIT);
+ added[1008 * 1008 - 1] = MASK_LOGIT;
+ const seed = keepTracked(tracked(0, 2), added);
+ expect(seed[0]).toBe(MASK_LOGIT);
+ expect(seed[2]).toBe(-MASK_LOGIT);
+ expect(seed[1008 * 1008 - 1]).toBe(MASK_LOGIT);
+ expect(keepTracked(tracked(0, 2, -1), added)).toBe(added);
+ });
+});
diff --git a/packages/vision-sam/src/sam3/selection.ts b/packages/vision-sam/src/sam3/selection.ts
index 3d3300d7..3d92750c 100644
--- a/packages/vision-sam/src/sam3/selection.ts
+++ b/packages/vision-sam/src/sam3/selection.ts
@@ -9,3 +9,58 @@ export function mergeSelections(masks: readonly Float32Array[]): Float32Array {
merged[i] = Math.max(merged[i] ?? -Infinity, mask[i] ?? -Infinity);
return merged;
}
+
+/** Logit SAM uses for a given mask's pixels (and its object score): ±10. */
+export const MASK_LOGIT = 10;
+
+/** A re-detected instance is new while tracked objects cover less than this share of it. */
+const NEW_OBJECT_COVERAGE = 0.5;
+
+/** A tracked object's 1008² logits and presence logit. */
+export interface TrackedMask {
+ readonly logits: Float32Array;
+ readonly score: number;
+}
+
+/** Where any present tracked object is, on the 288² concept grid, as ±10 logits. */
+export function coveredCells(tracked: readonly TrackedMask[]): Float32Array {
+ const covered = new Float32Array(288 * 288).fill(-MASK_LOGIT);
+ for (const { logits, score } of tracked) {
+ if (score <= 0) continue;
+ for (let y = 0; y < 288; y++) {
+ const row = Math.floor(((y + 0.5) * 1008) / 288) * 1008;
+ for (let x = 0; x < 288; x++)
+ if ((logits[row + Math.floor(((x + 0.5) * 1008) / 288)] ?? 0) > 0)
+ covered[y * 288 + x] = MASK_LOGIT;
+ }
+ }
+ return covered;
+}
+
+/** Re-detected 288² instances that the covered cells do not already hold. */
+export function uncovered(
+ found: readonly Float32Array[],
+ covered: Float32Array,
+): Float32Array[] {
+ return found.filter((instance) => {
+ let inside = 0;
+ let area = 0;
+ for (let i = 0; i < instance.length; i++) {
+ if ((instance[i] ?? 0) <= 0) continue;
+ area++;
+ if ((covered[i] ?? 0) > 0) inside++;
+ }
+ return area > 0 && inside / area < NEW_OBJECT_COVERAGE;
+ });
+}
+
+/** 1008² seed logits that keep a present tracked mask at full resolution and add `added` to it. */
+export function keepTracked(
+ tracked: TrackedMask | undefined,
+ added: Float32Array,
+): Float32Array {
+ if (!tracked || tracked.score <= 0) return added;
+ return Float32Array.from(added, (value, i) =>
+ (tracked.logits[i] ?? 0) > 0 ? MASK_LOGIT : value,
+ );
+}
diff --git a/packages/vision-sam/src/sam3/text-selector.ts b/packages/vision-sam/src/sam3/text-selector.ts
index df0eed57..d03c0dfb 100644
--- a/packages/vision-sam/src/sam3/text-selector.ts
+++ b/packages/vision-sam/src/sam3/text-selector.ts
@@ -29,6 +29,11 @@ export async function sam3Run(
/** Semantic model is separate from the visual tracker and loads only for text prompts. */
export class Sam3TextSelector {
private readonly sessions: VisionSession[] = [];
+ private encoded?: {
+ text: string;
+ features: Float32Array;
+ mask: BigInt64Array;
+ };
private constructor(private readonly tokenizer: Tokenizer) {}
static async create(
@@ -73,37 +78,26 @@ export class Sam3TextSelector {
/**
* Mask logits (288²) of the instances matching `text` with sigmoid score of at least
* `threshold`, best first and at most `max`. Queries that repeat an accepted instance
- * (mask IoU above 0.5) are skipped.
+ * (mask IoU above 0.5) are skipped. Throws when nothing matches unless `required` is false.
*/
async select(
pixels: Float32Array,
text: string,
threshold: number,
max = 1,
+ required = true,
): Promise<Float32Array[]> {
const [visionSession, textSession, decoder] = this.sessions;
if (!visionSession || !textSession || !decoder)
throw new Error("SAM 3 text selector has been released.");
- const tokens: readonly number[] = this.tokenizer.encode(text).ids;
- if (tokens.length > 32)
- throw new Error("SAM 3 text prompts must fit within 32 CLIP tokens.");
- const ids = new BigInt64Array(32).fill(49407n),
- mask = new BigInt64Array(32);
- tokens.forEach((id, i) => {
- ids[i] = BigInt(id);
- mask[i] = 1n;
- });
- const encoded = await sam3Run(textSession, [
- { name: "input_ids", data: ids, dims: [1, 32] },
- { name: "attention_mask", data: mask, dims: [1, 32] },
- ]);
+ const { features, mask } = await this.encodeText(textSession, text);
const vision = await sam3Run(visionSession, [
{ name: "pixel_values", data: pixels, dims: [1, 3, 1008, 1008] },
]);
const inputs: VisionTensorInput[] = [
{
name: "text_features",
- data: sam3Floats(encoded, "text_features"),
+ data: features,
dims: [1, 32, 256],
},
{ name: "attention_mask", data: mask, dims: [1, 32] },
@@ -127,6 +121,7 @@ export class Sam3TextSelector {
(a, b) => (scores[b] ?? -Infinity) - (scores[a] ?? -Infinity),
);
const best = 1 / (1 + Math.exp(-(scores[ranked[0] ?? 0] ?? -Infinity)));
+ if (best < threshold && !required) return [];
if (best < threshold)
throw new Error(
`SAM 3 found no confident instance for text ${JSON.stringify(text)} (score ${best.toFixed(3)}, threshold ${threshold}).`,
@@ -142,9 +137,37 @@ export class Sam3TextSelector {
return selected;
}
+ /** Text features for a prompt; the last one is kept, since re-detection repeats it every few frames. */
+ private async encodeText(
+ session: VisionSession,
+ text: string,
+ ): Promise<{ features: Float32Array; mask: BigInt64Array }> {
+ if (this.encoded?.text === text) return this.encoded;
+ const tokens: readonly number[] = this.tokenizer.encode(text).ids;
+ if (tokens.length > 32)
+ throw new Error("SAM 3 text prompts must fit within 32 CLIP tokens.");
+ const ids = new BigInt64Array(32).fill(49407n),
+ mask = new BigInt64Array(32);
+ tokens.forEach((id, i) => {
+ ids[i] = BigInt(id);
+ mask[i] = 1n;
+ });
+ const encoded = await sam3Run(session, [
+ { name: "input_ids", data: ids, dims: [1, 32] },
+ { name: "attention_mask", data: mask, dims: [1, 32] },
+ ]);
+ this.encoded = {
+ text,
+ features: sam3Floats(encoded, "text_features").slice(),
+ mask,
+ };
+ return this.encoded;
+ }
+
release(): void {
for (const session of this.sessions) session.release();
this.sessions.length = 0;
+ this.encoded = undefined;
}
}
diff --git a/packages/vision-sam/src/sam3/tracker.ts b/packages/vision-sam/src/sam3/tracker.ts
index 1c610669..c4cd02a0 100644
--- a/packages/vision-sam/src/sam3/tracker.ts
+++ b/packages/vision-sam/src/sam3/tracker.ts
@@ -20,7 +20,13 @@ import type { Sam2Point } from "../sam2/types.js";
import { holdSam3Encoder, type Sam3EncoderHandle } from "./encoder.js";
import { sam3DenseDecoder, sam3SupportGraphs } from "./graphs.js";
import { Sam3MemoryBank, sam3Position } from "./memory.js";
-import { mergeSelections } from "./selection.js";
+import {
+ coveredCells,
+ keepTracked,
+ MASK_LOGIT,
+ mergeSelections,
+ uncovered,
+} from "./selection.js";
import { Sam3TextSelector, sam3Floats, sam3Run } from "./text-selector.js";
import {
type Sam3FrameResult,
@@ -51,6 +57,8 @@ export interface Sam3TrackerOptions extends VisionModelStoreOptions {
readonly maxObjects?: number;
/** Track every instance a text prompt selects as one object (one mask, one memory). */
readonly merge?: boolean;
+ /** Re-run the last text prompt every this many frames and add what no object covers (see `Sam3Options`). */
+ readonly redetect?: number;
/** Image-encoder weights; defaults to the fastest for the provider's backend (`SAM3_ENCODER`). */
readonly precision?: Sam3Precision;
/** Explicitly agree to Meta's SAM License terms to download or run SAM 3's weights. */
@@ -76,8 +84,13 @@ interface Seed {
readonly mask?: Float32Array;
}
-/** Logit SAM uses for a given mask's pixels (and its object score): ±10. */
-const MASK_LOGIT = 10;
+/** One object's decoded frame, before it is remembered. */
+interface Tracked {
+ readonly seed?: Seed;
+ readonly decoded: VisionTensorOutputs;
+ readonly logits: Float32Array;
+ readonly score: number;
+}
function tensor(
name: string,
@@ -99,6 +112,8 @@ export class Sam3Tracker {
private temporal?: Float32Array;
private noMemory?: Float32Array;
private selector?: Sam3TextSelector;
+ /** The last text prompt and its frame, which re-detection repeats. */
+ private text?: { value: string; frame: number };
private lastFrame = -1;
private released = false;
@@ -128,6 +143,13 @@ export class Sam3Tracker {
(!Number.isSafeInteger(options.maxObjects) || options.maxObjects < 1)
)
throw new Error("SAM 3 maxObjects must be a positive integer.");
+ if (
+ options.redetect !== undefined &&
+ (!Number.isSafeInteger(options.redetect) || options.redetect < 0)
+ )
+ throw new Error(
+ "SAM 3 redetect must be a nonnegative integer frame interval.",
+ );
const store =
options.store ??
@@ -210,18 +232,22 @@ export class Sam3Tracker {
tensor("feats0", feats0, [1, 32, 288, 288]),
tensor("feats1", feats1, [1, 64, 144, 144]),
];
- const seeds = await this.seeds(pixels, prompt);
- const objects: Sam3ObjectResult[] = [];
+ const seeds = await this.seeds(pixels, frame, prompt);
+ const tracked: Tracked[] = [];
for (const [index, bank] of this.banks.entries()) {
const seed = seeds.get(index);
const features = seed
? this.initialFeatures(raw)
: await this.condition(raw, frame, bank);
- const decoded = await this.decode(shared, features, seed);
- const logits = seed?.mask ?? sam3Floats(decoded, "high_res_masks");
- const score = seed?.mask
- ? MASK_LOGIT
- : (sam3Floats(decoded, "object_score_logits")[0] ?? -Infinity);
+ tracked.push(this.track(seed, await this.decode(shared, features, seed)));
+ }
+ if (!prompt) await this.redetect(pixels, frame, tracked, shared, raw);
+
+ const objects: Sam3ObjectResult[] = [];
+ for (const [index, bank] of this.banks.entries()) {
+ const item = tracked[index];
+ if (!item) continue;
+ const { seed, decoded, logits, score } = item;
await this.remember(bank, raw, decoded, frame, seed, logits, score);
objects.push({
id: index + 1,
@@ -234,9 +260,92 @@ export class Sam3Tracker {
return { width: image.width, height: image.height, objects };
}
+ private track(seed: Seed | undefined, decoded: VisionTensorOutputs): Tracked {
+ return {
+ seed,
+ decoded,
+ logits: seed?.mask ?? sam3Floats(decoded, "high_res_masks"),
+ score: seed?.mask
+ ? MASK_LOGIT
+ : (sam3Floats(decoded, "object_score_logits")[0] ?? -Infinity),
+ };
+ }
+
+ /**
+ * On a `redetect` frame, runs the last text prompt again and seeds what no tracked object
+ * covers: merged into the one object (keeping what it tracks), or as new objects.
+ */
+ private async redetect(
+ pixels: Float32Array,
+ frame: number,
+ tracked: Tracked[],
+ shared: readonly VisionTensorInput[],
+ raw: Float32Array,
+ ): Promise<void> {
+ const every = this.options.redetect ?? 0;
+ if (!this.text || every <= 0 || (frame - this.text.frame) % every !== 0)
+ return;
+ const room = this.options.merge
+ ? Infinity
+ : (this.options.maxObjects ?? 1) - this.banks.length;
+ if (room <= 0) return;
+ const selector = await this.textSelector();
+ const found = await selector.select(
+ pixels,
+ this.text.value,
+ this.options.textThreshold ?? 0.5,
+ Infinity,
+ false,
+ );
+ const covered = coveredCells(tracked);
+ const fresh = uncovered(found, covered).slice(0, room);
+ if (!fresh.length) return;
+
+ const seeded = async (seed: Seed): Promise<Tracked> =>
+ this.track(
+ seed,
+ await this.decode(shared, this.initialFeatures(raw), seed),
+ );
+ if (this.options.merge) {
+ // One object: what it tracks (at full resolution) plus every new instance.
+ const added = mergeSelections(fresh);
+ const kept = tracked[0];
+ if (!kept) this.banks.push(this.newBank());
+ tracked[0] = await seeded({
+ dense: await this.densePrompt(mergeSelections([added, covered])),
+ mask: keepTracked(kept, seedLogits(added)),
+ });
+ return;
+ }
+ for (const logits of fresh) {
+ this.banks.push(this.newBank());
+ tracked.push(await seeded(await this.textSeed(logits)));
+ }
+ }
+
+ private async textSelector(): Promise<Sam3TextSelector> {
+ this.selector ??= await Sam3TextSelector.create(this.store, this.provider);
+ if (!this.options.store) this.store.clearMemoryCache();
+ return this.selector;
+ }
+
+ /** A 288² concept mask as a seed that outputs (and remembers) that mask. */
+ private async textSeed(logits: Float32Array): Promise<Seed> {
+ return { dense: await this.densePrompt(logits), mask: seedLogits(logits) };
+ }
+
+ private async densePrompt(logits: Float32Array): Promise<Float32Array> {
+ const binary = Float32Array.from(logits, (v) => (v > 0 ? 1 : 0));
+ const dense = await this.run("dense_prompt", [
+ tensor("mask", binary, [1, 1, 288, 288]),
+ ]);
+ return sam3Floats(dense, "dense_prompt");
+ }
+
/** Objects a prompt (re)seeds, by index. Text re-selects every object; points address one. */
private async seeds(
pixels: Float32Array,
+ frame: number,
prompt?: Omit<Sam3Prompt, "frame">,
): Promise<Map<number, Seed>> {
const seeds = new Map<number, Seed>();
@@ -250,29 +359,19 @@ export class Sam3Tracker {
seeds.set(index, { points: prompt.points });
}
if (prompt?.text !== undefined) {
- this.selector ??= await Sam3TextSelector.create(
- this.store,
- this.provider,
- );
- if (!this.options.store) this.store.clearMemoryCache();
- const selected = await this.selector.select(
+ const selector = await this.textSelector();
+ const selected = await selector.select(
pixels,
prompt.text,
this.options.textThreshold ?? 0.5,
this.options.maxObjects ?? (this.options.merge ? Infinity : 1),
);
const masks = this.options.merge ? [mergeSelections(selected)] : selected;
+ this.text = { value: prompt.text, frame };
this.banks.length = 0;
for (const [index, logits] of masks.entries()) {
this.banks.push(this.newBank());
- const binary = Float32Array.from(logits, (v) => (v > 0 ? 1 : 0));
- const dense = await this.run("dense_prompt", [
- tensor("mask", binary, [1, 1, 288, 288]),
- ]);
- seeds.set(index, {
- dense: sam3Floats(dense, "dense_prompt"),
- mask: seedLogits(logits),
- });
+ seeds.set(index, await this.textSeed(logits));
}
}
return seeds;
diff --git a/packages/vision-sam/src/sam3/types.ts b/packages/vision-sam/src/sam3/types.ts
index 6565df65..55edc8a3 100644
--- a/packages/vision-sam/src/sam3/types.ts
+++ b/packages/vision-sam/src/sam3/types.ts
@@ -33,6 +33,13 @@ export interface Sam3Options extends SamLicenseOptions {
* tracking costs the same as a single object however many match (e.g. a whole crowd).
*/
readonly merge?: boolean;
+ /**
+ * Every this many frames after a text prompt, run that text again and add the instances no
+ * tracked object covers yet (people who walk in, turn up from behind someone, or were lost):
+ * into the one object with `merge`, otherwise as new track IDs up to `maxObjects`. Each
+ * detection pass costs about one text prompt. Default 0: select once, then only track.
+ */
+ readonly redetect?: number;
/** Image-encoder weights; defaults to the fastest for the backend in use (`SAM3_ENCODER`). */
readonly precision?: Sam3Precision;
}
@@ -68,6 +75,11 @@ export function validateSam3Prompts(options: Sam3Options): void {
const maxObjects = options.maxObjects ?? 1;
if (!Number.isSafeInteger(maxObjects) || maxObjects < 1)
throw new Error("SAM 3 maxObjects must be a positive integer.");
+ const redetect = options.redetect ?? 0;
+ if (!Number.isSafeInteger(redetect) || redetect < 0)
+ throw new Error(
+ "SAM 3 redetect must be a nonnegative integer frame interval.",
+ );
const threshold = options.textThreshold ?? 0.5;
if (!Number.isFinite(threshold) || threshold <= 0 || threshold >= 1)
throw new Error("SAM 3 textThreshold must be between zero and one.");
diff --git a/plugins/framefields/skills/framefields-vision/SKILL.md b/plugins/framefields/skills/framefields-vision/SKILL.md
index d3947c01..b16f17a5 100644
--- a/plugins/framefields/skills/framefields-vision/SKILL.md
+++ b/plugins/framefields/skills/framefields-vision/SKILL.md
@@ -93,7 +93,7 @@ const vision = comp.withVision({ enableSegmentation: true, enablePose: true });
Layer.video("assets/dancer.mp4").withVision({ mode: "matte", enableSegmentation: true });
```
-Node modes: `passthrough`, `mask`, `matte`, `crop`, `skeleton`, `boxes`, `tracking`. For `mask` / `matte` / `crop`, `matteSource: "instance"` (default; any COCO class, overlapping parts such as a dress merged into the subject) or `"selfie"` (people only, fastest). `confidence` (default 0.3) and `classes: ["person", …]` filter detections.
+Node modes: `passthrough`, `mask`, `matte`, `crop`, `skeleton`, `boxes`, `tracking`. `skeleton` draws only the pose on transparency: the first person detected, or, for a layer of a `comp.vision` clip, the pose that clip matched to its selection. For `mask` / `matte` / `crop`, `matteSource: "instance"` (default; any COCO class, overlapping parts such as a dress merged into the subject) or `"selfie"` (people only, fastest). `confidence` (default 0.3) and `classes: ["person", …]` filter detections.
Measured per 1280–2048 px frame on CPU (`onnxruntime-node`); the GPU is faster:
@@ -223,10 +223,11 @@ Layer.box({
- **Text prompts are concepts.** Name what sets the target apart in that shot. In a crowd where everyone shows a white collar, "man in white shirt" picks a student. In the same film's wide shot, where only he has no blazer, it picks him. Check the first frame of every prompt.
- **Several objects** (`maxObjects`): one encoder pass per frame serves every track, and each track keeps its own memory. Where tracks overlap, the more confident one keeps the pixel. `signals.objects.get(k)` and `signals.masks` carry tracks `1…N`; the clip's matte and subject are all tracks merged. A later text prompt re-selects every track (IDs renumber); a points prompt with `object: k` seeds or corrects track `k` only (the next unused ID adds one).
- **One entity for a whole group** (`merge: true`): every instance the text matches (up to `maxObjects`, default all) becomes one seed mask, tracked as one object with one memory. Use it when you need the group's mask or matte (cut out a crowd, grade everyone but the hero), not each member's box; it costs the same as one track however many match (4.1 s per frame for a whole crowd of students on an M1 Pro). Use `maxObjects` without `merge` when each member needs its own track, at about 0.7 s per member per frame.
+- **People who appear later** (`redetect: N`): a text selection is made once, on the prompt frame; anyone missed there, uncovered later, or lost by the tracker never joins on their own. `redetect: N` runs the text again every N frames and adds what no track covers: into the one object with `merge`, as new track IDs up to `maxObjects` otherwise. On a 4 s close-up where the man in front bends away, a merged "students in black blazers" group kept 46–61% of the frame through the end instead of falling to 22–33%. Each pass costs about as much as the prompt frame's selection (about 50 s on an M1 Pro), so pick N for how fast people enter the shot (10–25 frames), not 1.
- Two text-prompted clips of one shot can claim the same person (a "student" track on the hero). Prefer prompts that exclude each other.
- **Corrections and cuts.** A prompt on a later frame resets that object's memory. Re-prompt after hard cuts or long occlusions; appearance tracking cannot guarantee re-identification.
- An explicit selection never falls back to another detected person. If its mask cannot align with a matte layer (a different aspect ratio), the render fails. Matte at the source aspect ratio and crop afterwards.
-- SAM gives masks, not skeletons: `pose: true` matches an RTMO pose to the selection. Default smoothing is 0, and an absent object stays empty.
+- SAM gives masks, not skeletons: `pose: true` (opt-in for SAM clips) matches an RTMO pose to the selection, the person whose keypoints fall most inside its mask. A `withVision({ mode: "skeleton" })` layer of the same clip draws that matched pose for the frame on screen; without `pose: true` on a SAM clip it fails instead of drawing whoever is detected first. Default smoothing is 0, and an absent object stays empty.
- `clip.release()` frees the SAM sessions. Analysed frames stay readable.
### Singular or plural: one selection per group