// One frame scan (release 30, lane P): sample, skip duplicates, read the kept // frames through a profile, derive, write the sidecar. Every effect is a dep, // so the tests run it over synthetic frames and the fake model servers. // // RESUMABLE: a reading already in the sidecar (by its grid time) is never // asked again, and a frame that duplicates a read frame is not asked at all. // The sidecar is written every few asks, so a cancelled or cut job keeps what // it read; the next run asks only the rest. // // CAPPED: the run stops before an ask that could take its spend past // `maxUsd` (an estimate per ask, from the frames' sizes and the model's // price), and again on the meter's own count. Three failed asks in a row stop // it too (a key refused, a model that cannot read images). import { readFile } from "node:fs/promises"; import path from "node:path"; import { Meter, structuredAnswer, priceOf, providerOf, type AnswerImage, type LlmConfig } from "../llm"; import { CancelledError } from "../llm/anthropic"; import { PromptTooLargeError } from "../llm/ollama"; import { duplicatesOf } from "./dhash"; import { frameProfile } from "./profiles"; import { probeDuration, sampleFrames, type Crop, type FrameIndex } from "./sample-server"; import { FRAME_SCAN_FORMAT, type Cue, type Derived, type FrameRef, type SpokenReading } from "./types"; import type { FrameScanRecord, FrameScanRun } from "../frameScan-server"; import { applyCorrections, type ReadingCorrection } from "./corrections"; export const DEFAULT_EVERY_SECONDS = 10; export const DEFAULT_MAX_FRAMES = 5000; // Asks between two writes of the sidecar. const WRITE_EVERY_ASKS = 5; const MAX_FAILED_IN_A_ROW = 3; export type FrameScanOptions = { profile: string; // The saved container (absolute) and its basename for the record. source: string; cacheDir: string; everySeconds?: number; from?: number; to?: number; maxFrames?: number; model: string; llm: LlmConfig; maxUsd: number; hints?: { hero?: string }; framesPerAsk?: number; keyframesOnly?: boolean; // The part of the picture the model reads (the poker client, not the webcam // beside it): fractions [x, y, w, h]. The hash is taken of it too. crop?: Crop; cues?: Cue[]; // Read every frame again (another model, another prompt): the readings and // duplicates so far are dropped; the runs and the spend are kept. fresh?: boolean; jobId?: string; signal?: AbortSignal; onLog?: (line: string) => void; onProgress?: (p: { phase: "sample" | "read"; current: number; total: number }) => void; now?: () => Date; }; export type FrameScanDeps = { load: () => Promise; write: (r: FrameScanRecord) => Promise; sample?: typeof sampleFrames; probe?: (file: string) => Promise; readImage?: (file: string) => Promise; // One structured ask (default: structuredAnswer). ask?: typeof structuredAnswer; }; export type FrameScanOutcome = { record: FrameScanRecord; run: FrameScanRun; spent: ReturnType }; // What one image costs on the Claude API, in input tokens: (w·h)/750 after the // API's own downscale (long edge ≤ 1568, ≤ ~1.15 MP). A JPEG's size is read // from its SOF marker; an unreadable one is priced at the most an image costs. export function claudeImageTokens(w: number, h: number): number { let s = 1; if (Math.max(w, h) > 1568) s = 1568 / Math.max(w, h); if (w * h * s * s > 1_150_000) s = Math.sqrt(1_150_000 / (w * h)); return Math.ceil((w * s * h * s) / 750); } export function jpegSize(buf: Buffer): { w: number; h: number } | null { if (buf.length < 4 || buf[0] !== 0xff || buf[1] !== 0xd8) return null; let i = 2; while (i + 9 < buf.length) { if (buf[i] !== 0xff) return null; const marker = buf[i + 1]; const len = buf.readUInt16BE(i + 2); if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) { return { h: buf.readUInt16BE(i + 5), w: buf.readUInt16BE(i + 7) }; } i += 2 + len; } return null; } // An ask's cost estimate before it is sent: its images, the prompt text and // a reading's worth of output per frame. function askEstimateUsd(model: string, images: Buffer[], promptChars: number): number { if (providerOf(model) !== "api") return 0; const p = priceOf(model); const imgTokens = images.reduce((n, b) => { const s = jpegSize(b); return n + (s ? claudeImageTokens(s.w, s.h) : 1600); }, 0); const input = imgTokens + Math.ceil(promptChars / 3.5); const output = 250 * images.length; return (input * p.input + output * p.output) / 1e6; } /** * The derived timeline of a scan's readings — the readings, the duplicates as * copies of what they show (a held stack is held on every frame, read or not), * and the spoken numbers, through the profile's pure derivation. No model, no * frame: what a scan writes and what a re-derive rewrites. */ export function deriveOf( profileId: string, readings: FrameScanRecord["readings"], duplicates: readonly [number, number][], spoken: SpokenReading[], o: { everySeconds: number; durationSeconds?: number | null; hero?: string; corrections?: readonly ReadingCorrection[] }, ): Derived { const profile = frameProfile(profileId); // A person's corrections (release 32) first, so a duplicate copies the // corrected reading (and a reading set aside is copied nowhere); then again // over the copies, for a correction made at a duplicate's own second. const corrected = applyCorrections(readings, o.corrections); const byT = new Map(corrected.map((r) => [r.t, r])); const read = new Set(readings.map((r) => r.t)); const copies = duplicates.flatMap(([t, src]) => { const r = byT.get(src); return r && !read.has(t) ? [{ ...r, t }] : []; }); const expanded = applyCorrections([...corrected, ...copies], o.corrections).sort((a, b) => a.t - b.t); return profile.derive(expanded as never, spoken, { everySeconds: o.everySeconds, ...(o.durationSeconds !== null && o.durationSeconds !== undefined ? { durationSeconds: o.durationSeconds } : {}), ...(o.hero ? { hero: o.hero } : {}), }); } /** * A scan's record with its `derived` (and, given cues, its `spoken`) worked * out again from what it holds — ZERO model calls, no frames. Its readings, * runs and spend are kept as they were; `rederivedAt` says when. After the * derivation's rules change, this is what brings an old sidecar up to date. */ export function rederiveRecord(rec: FrameScanRecord, o: { cues?: Cue[]; hero?: string; now?: () => Date } = {}): FrameScanRecord { const profile = frameProfile(rec.profile); const spoken = o.cues ? profile.spoken(o.cues) : rec.spoken; const hints = o.hero ? { ...(rec.hints ?? {}), hero: o.hero } : rec.hints; const at = (o.now ?? (() => new Date()))().toISOString(); return { ...rec, ...(hints ? { hints } : {}), spoken, derived: deriveOf(rec.profile, rec.readings, rec.duplicates ?? [], spoken, { everySeconds: rec.sampling.everySeconds, durationSeconds: rec.source.durationSeconds, hero: hints?.hero, ...(rec.corrections?.length ? { corrections: rec.corrections } : {}), }), rederivedAt: at, updatedAt: at, }; } export async function runFrameScan(o: FrameScanOptions, deps: FrameScanDeps): Promise { const log = o.onLog ?? (() => {}); const profile = frameProfile(o.profile); const every = o.everySeconds ?? DEFAULT_EVERY_SECONDS; const route: "api" | "local" = providerOf(o.model); const now = o.now ?? (() => new Date()); const meter = new Meter({ maxUsd: o.maxUsd }); const prev = await deps.load(); const duration = await (deps.probe ?? probeDuration)(o.source); const from = Math.max(0, o.from ?? 0); let to = o.to ?? duration ?? 0; if (duration !== null) to = Math.min(to, duration); if (!(to > from)) throw new Error(`nothing to scan: ${from}–${to} s${duration === null ? " (the video's length could not be read)" : ""}`); const maxFrames = o.maxFrames ?? DEFAULT_MAX_FRAMES; let stopped: FrameScanRun["stopped"]; if ((to - from) / every > maxFrames) { to = Math.round((from + maxFrames * every) * 100) / 100; stopped = "maxFrames"; log(`the range would be over ${maxFrames} frames: scanning ${from}–${to} s only (raise maxFrames or everySeconds)`); } // The crop is the scan's: a re-run that names none keeps the last run's. const crop = o.crop ?? prev?.sampling.crop; log(`sampling ${from}–${Math.round(to)} s every ${every} s at ${profile.width} px wide${crop ? `, cropped to [${crop.join(", ")}]` : ""} into ${o.cacheDir}`); const index: FrameIndex = await (deps.sample ?? sampleFrames)({ source: o.source, dir: o.cacheDir, from, to, every, width: profile.width, keyframesOnly: o.keyframesOnly ?? true, ...(crop ? { crop } : {}), signal: o.signal, onLog: log, onBatch: (d, n) => o.onProgress?.({ phase: "sample", current: d, total: n }), }); const frames = index.frames.filter((f) => f.t >= from && f.t < to).sort((a, b) => a.t - b.t); const dup = duplicatesOf(frames.map((f) => f.hash), { maxBits: profile.dupMaxBits, rereadEvery: profile.rereadEvery }); const kept = frames.filter((_, i) => dup[i] === null); const readings = new Map(); if (!o.fresh) for (const r of prev?.readings ?? []) readings.set(r.t, r); const todo = kept.filter((f) => !readings.has(f.t)); log(`${frames.length} frames, ${kept.length} kept (${frames.length - kept.length} duplicates), ${kept.length - todo.length} already read, ${todo.length} to read on ${o.model}`); const per = Math.max(1, o.framesPerAsk ?? profile.framesPerAsk[route]); // The hints are the scan's: a re-run without them keeps the last run's. const hints = { ...(prev?.hints ?? {}), ...(o.hints ?? {}) }; const system = profile.system(hints); const ask = deps.ask ?? structuredAnswer; const readImage = deps.readImage ?? ((f: string) => readFile(f)); let read = 0; let failed = 0; let inARow = 0; let asks = 0; // A duplicate frame shows what the frame it duplicates shows: [t, that t]. // Kept with the record (the cache is evictable), merged over runs. const dupPairs = new Map(); if (!o.fresh) for (const [t, src] of prev?.duplicates ?? []) if (t < from || t >= to) dupPairs.set(t, src); frames.forEach((f, i) => { const d = dup[i]; if (d !== null) dupPairs.set(f.t, frames[d].t); }); const record = (): FrameScanRecord => { const all = [...readings.values()].sort((a, b) => a.t - b.t); const duplicates = [...dupPairs].sort((a, b) => a[0] - b[0]); const spoken = o.cues ? profile.spoken(o.cues) : (prev?.spoken ?? []); return { format: FRAME_SCAN_FORMAT, version: 1, profile: profile.id, source: { savedVideo: path.basename(o.source), durationSeconds: duration }, sampling: { everySeconds: every, from, to, width: profile.width, keyframesOnly: index.keyframesOnly, ...(index.crop ? { crop: index.crop } : {}), frames: frames.length, kept: kept.length, skippedDuplicates: frames.length - kept.length, }, model: { route, model: o.model, promptVersion: profile.promptVersion }, ...(hints.hero ? { hints } : {}), costUsd: Math.round(((prev?.costUsd ?? 0) + meter.usd) * 10_000) / 10_000, runs: [...(prev?.runs ?? []), runOf()], readings: all, duplicates, spoken, derived: deriveOf(profile.id, all, duplicates, spoken, { everySeconds: every, durationSeconds: duration, hero: hints.hero, ...(prev?.corrections?.length ? { corrections: prev.corrections } : {}), }), // A person's corrections outlive every run, a fresh one included: they // say what a frame at that second shows. ...(prev?.corrections?.length ? { corrections: prev.corrections } : {}), updatedAt: now().toISOString(), }; }; const runOf = (): FrameScanRun => ({ at: now().toISOString(), ...(o.jobId ? { jobId: o.jobId } : {}), model: o.model, route, frames: frames.length, read, failed, costUsd: Math.round(meter.usd * 10_000) / 10_000, ...(stopped ? { stopped } : {}), }); for (let i = 0; i < todo.length; i += per) { if (o.signal?.aborted) { stopped = "cancelled"; break; } const chunk: FrameRef[] = todo.slice(i, i + per); const bufs = await Promise.all(chunk.map((f) => readImage(path.join(o.cacheDir, f.file)))); const user = profile.user(chunk); const schema = profile.schema(chunk.length); const estimate = askEstimateUsd(o.model, bufs, system.length + user.length + JSON.stringify(schema).length); if (meter.over() || (route === "api" && meter.usd + estimate > o.maxUsd)) { stopped = "cap"; log(`stopping at the cap: $${meter.usd.toFixed(4)} spent of $${o.maxUsd} (the next ask is ~$${estimate.toFixed(4)})`); break; } const images: AnswerImage[] = bufs.map((b) => ({ mediaType: "image/jpeg", data: b.toString("base64") })); let answer: unknown; try { answer = await ask({ llm: o.llm, model: o.model, system, user, schema, images, meter, signal: o.signal, maxTokens: 400 * chunk.length + 400 }); } catch (err) { if (o.signal?.aborted || err instanceof CancelledError) { stopped = "cancelled"; break; } failed += chunk.length; inARow++; log(`ask failed for ${chunk.map((f) => f.t).join(", ")} s: ${(err as Error).message}`); if (err instanceof PromptTooLargeError || inARow >= MAX_FAILED_IN_A_ROW) { stopped = "errors"; log(`stopping: ${inARow} failed asks in a row`); break; } continue; } inARow = 0; const list = answer && typeof answer === "object" && Array.isArray((answer as { frames?: unknown }).frames) ? ((answer as { frames: unknown[] }).frames) : []; chunk.forEach((f, k) => { // The answer's own frame numbers when it gives them, else its order. const raw = list.find((x) => x && typeof x === "object" && (x as { frame?: unknown }).frame === k + 1) ?? (list.length === chunk.length ? list[k] : undefined); const reading = profile.coerce(raw); if (!reading) { failed++; return; } readings.set(f.t, { t: f.t, ...reading }); read++; }); asks++; o.onProgress?.({ phase: "read", current: Math.min(todo.length, i + per), total: todo.length }); if (asks % WRITE_EVERY_ASKS === 0) await deps.write(record()); } const out = record(); await deps.write(out); const run = out.runs[out.runs.length - 1]; log(`read ${read} frames (${failed} failed), $${meter.usd.toFixed(4)} this run${stopped ? `, stopped: ${stopped}` : ""}; ${out.derived.events.length} events, ${out.derived.tournaments.length} tournament(s)`); return { record: out, run, spent: meter.summary() }; }