Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 2472479d18dd84de3d1881cef2e05c4565e978b6
parent 74b1806b9fb5c83e2b6e41895d9b9f2d05282099
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  2 Nov 2026 16:56:48 -0500

umtool: "use a file" -- a rendered file of the project served to a bench: the picture, a span's envelope, a span's sound

GET /api/report/file?project&path&v (range, the video route's `v`), and a
`path` form of the peaks route (a span of the file's analysed envelope, on
the file's clock) and of the audio route (a span decoded by the build's
ffmpeg to WAV). `path` is relative to the project and resolved by
lib/report/projectFile.mjs: lexically inside it, a media file, and its real
path under the project or one of its own directories on the way (a take's
out/ may be a link to the media drive). The bench's renderedFileMedia
adapter reads all three; the take's master is the first file it plays.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mumtool/app/api/report/audio/route.ts | 42+++++++++++++++++++++++++++++++++++++-----
Aumtool/app/api/report/file/route.ts | 28++++++++++++++++++++++++++++
Mumtool/app/api/report/peaks/route.ts | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------
Aumtool/lib/report/projectFile.mjs | 46++++++++++++++++++++++++++++++++++++++++++++++
4 files changed, 168 insertions(+), 19 deletions(-)

diff --git a/umtool/app/api/report/audio/route.ts b/umtool/app/api/report/audio/route.ts @@ -1,8 +1,9 @@ import { spawn } from "node:child_process"; import { stat } from "node:fs/promises"; import { - absOf, ensureWindowFile, notModified, pickWindow, resolveClip, windowCacheControl, windowEtag, windowVersion, windowsFor, + absOf, ensureWindowFile, notModified, pickWindow, resolveClip, resolveReport, windowCacheControl, windowEtag, windowVersion, windowsFor, } from "@/lib/report/serve.mjs"; +import { resolveProjectFile } from "@/lib/report/projectFile.mjs"; import { MAX_DECODE_SPAN, wavHeader } from "@/lib/report/playback.mjs"; import { FFMPEG_BIN } from "umtool-report-to-video/build-video"; @@ -33,6 +34,7 @@ const CHANNELS = 2; export async function GET(request: Request) { const url = new URL(request.url); + if (url.searchParams.get("path")) return fileAudio(request, url); // `take` (the Play view playing a take): the take's clip, its window as the take has it -- as /api/report/raw. const r = await resolveClip(url.searchParams.get("project") ?? "", url.searchParams.get("clip") ?? "", { take: url.searchParams.get("take") || null, @@ -78,6 +80,37 @@ export async function GET(request: Request) { ); } + return wavOf(request, { abs, seek: from - win.from, from, to, headers: { ...cache, "x-window": win.name } }); +} + +/** + * "Use a file" (lane/reel-bench): `?project&path&from&to` -- the sound of a + * span of a rendered FILE of the project, on the file's clock + * (lib/report/projectFile.mjs says what may be read). + */ +async function fileAudio(request: Request, url: URL) { + const r = await resolveReport(url.searchParams.get("project") ?? ""); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const f = await resolveProjectFile(r.project, url.searchParams.get("path") ?? ""); + if ("error" in f) return Response.json({ error: f.error }, { status: f.status }); + const from = Math.max(0, Number(url.searchParams.get("from") ?? 0)); + const to = Number(url.searchParams.get("to") ?? from + MAX_DECODE_SPAN); + if (!Number.isFinite(from) || !Number.isFinite(to) || to <= from) return Response.json({ error: "bad span" }, { status: 400 }); + if (to - from > MAX_DECODE_SPAN + 0.5) { + return Response.json({ error: `asked for ${Math.round(to - from)} s; the bench decodes at most ${MAX_DECODE_SPAN} s at once` }, { status: 400 }); + } + const etag = `"af-${f.mtimeMs}-${f.size}"`; + const cache = { "cache-control": url.searchParams.get("v") === String(f.mtimeMs) ? "private, max-age=3600, immutable" : "private, no-cache", etag }; + if (notModified(request, etag)) return new Response(null, { status: 304, headers: cache }); + return wavOf(request, { abs: f.abs, seek: from, from, to, headers: { ...cache, "x-file": f.rel } }); +} + +/** + * [from, to) of `abs` -- `seek` seconds into the file -- decoded by the + * build's ffmpeg to 16-bit PCM WAV; `x-audio-from`/`x-audio-to` say what was + * decoded, on the caller's clock (`from`). + */ +async function wavOf(request: Request, { abs, seek, from, to, headers }: { abs: string; seek: number; from: number; to: number; headers: Record<string, string> }) { // Input seeking with a decode is sample-accurate in ffmpeg: it seeks to the // keyframe before and discards up to the requested time. The build's ffmpeg // (FFMPEG_BIN), so an override reaches this decode too; killed when the @@ -87,7 +120,7 @@ export async function GET(request: Request) { const code = await new Promise<number>((resolve) => { const ff = spawn(FFMPEG_BIN, [ "-nostdin", "-v", "error", - "-ss", (from - win.from).toFixed(6), + "-ss", seek.toFixed(6), "-i", abs, "-t", (to - from).toFixed(6), "-map", "a:0", @@ -124,14 +157,13 @@ export async function GET(request: Request) { return new Response(body, { headers: { "content-type": "audio/wav", - // Cached as hard as the raw file is: immutable under the current `v`, else revalidated. - ...cache, + // Cached as hard as the file is: immutable under the current `v`, else revalidated. + ...headers, // What was actually decoded, in absolute source seconds: the client // places the buffer on the source clock from these, not from what it // asked for. "x-audio-from": String(from), "x-audio-to": String(from + dataBytes / frameBytes / RATE), - "x-window": win.name, }, }); } diff --git a/umtool/app/api/report/file/route.ts b/umtool/app/api/report/file/route.ts @@ -0,0 +1,28 @@ +import { resolveProjectFile } from "@/lib/report/projectFile.mjs"; +import { rangeResponse, resolveReport } from "@/lib/report/serve.mjs"; + +export const dynamic = "force-dynamic"; + +// A rendered FILE of the project to a <video> element ("use a file", +// lane/reel-bench): ?project&path&v, `path` relative to the project +// (lib/report/projectFile.mjs says what may be served). `v` is the video +// route's contract: the mtime the client was told (`x-video-mtime`); only a +// match is cached, so a re-render under the same name is a new file. +export async function GET(request: Request) { + const url = new URL(request.url); + const r = await resolveReport(url.searchParams.get("project") ?? ""); + if ("error" in r) return new Response(r.error, { status: r.status }); + const f = await resolveProjectFile(r.project, url.searchParams.get("path") ?? ""); + if ("error" in f) return new Response(f.error, { status: f.status }); + const fresh = url.searchParams.get("v") === String(f.mtimeMs); + return rangeResponse(request, { + abs: f.abs, + size: f.size, + headers: { + "content-type": /\.(m4a|mp3|wav)$/i.test(f.rel) ? "audio/mp4" : "video/mp4", + "accept-ranges": "bytes", + "cache-control": fresh ? "private, max-age=3600, immutable" : "private, no-store", + "x-video-mtime": String(f.mtimeMs), + }, + }); +} diff --git a/umtool/app/api/report/peaks/route.ts b/umtool/app/api/report/peaks/route.ts @@ -1,8 +1,9 @@ import { stat } from "node:fs/promises"; import { - absOf, ensureWindowFile, notModified, pickWindow, projectCache, resolveClip, windowCacheControl, windowEtag, windowVersion, windowsFor, + absOf, ensureWindowFile, notModified, pickWindow, projectCache, resolveClip, resolveReport, windowCacheControl, windowEtag, windowVersion, windowsFor, } from "@/lib/report/serve.mjs"; import { ENV_RATE, analyseMedia } from "@/lib/media"; +import { resolveProjectFile } from "@/lib/report/projectFile.mjs"; export const dynamic = "force-dynamic"; @@ -17,8 +18,59 @@ export const dynamic = "force-dynamic"; // keyed by the file's version, not its name (serve.mjs, "A REPLACED FILE IS A // NEW FILE"): a refetch writes new bytes under the same window name. +/** The envelope as `buckets` min/max pairs over [i0, i1) of it. */ +function bucketsOf(env: ArrayLike<number>, i0: number, i1: number, buckets: number) { + const n = Math.max(1, i1 - i0); + const min: number[] = []; + const max: number[] = []; + for (let b = 0; b < buckets; b += 1) { + const a = i0 + Math.floor((b / buckets) * n); + const z = Math.max(a + 1, i0 + Math.floor(((b + 1) / buckets) * n)); + let p = 0; + for (let i = a; i < z && i < i1; i += 1) if (env[i] > p) p = env[i]; + max.push(p); + min.push(-p); + } + return { min, max }; +} + +/** + * "Use a file" (lane/reel-bench): `?project&path&from&to&n&v` -- the envelope + * of a span of a rendered FILE of the project, on the FILE's clock (the + * bench maps it onto the source; components/projects/bench/benchMedia.ts). + * The whole file is analysed once and cached (analyseMedia, keyed by its + * path, mtime and size); a span is a slice of that. + */ +async function filePeaks(request: Request, url: URL) { + const r = await resolveReport(url.searchParams.get("project") ?? ""); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const f = await resolveProjectFile(r.project, url.searchParams.get("path") ?? ""); + if ("error" in f) return Response.json({ error: f.error }, { status: f.status }); + const buckets = Math.max(64, Math.min(4000, Number(url.searchParams.get("n") ?? 1200))); + const fromQ = Number(url.searchParams.get("from") ?? 0); + const toQ = Number(url.searchParams.get("to") ?? Number.POSITIVE_INFINITY); + if (!Number.isFinite(fromQ) || !(toQ > fromQ)) return Response.json({ error: "bad span" }, { status: 400 }); + const etag = `"pf-${f.mtimeMs}-${f.size}-${fromQ}-${toQ}-${buckets}"`; + const cache = { "cache-control": url.searchParams.get("v") === String(f.mtimeMs) ? "private, max-age=3600, immutable" : "private, no-cache", etag }; + if (notModified(request, etag)) return new Response(null, { status: 304, headers: cache }); + let analysis; + try { + analysis = await analyseMedia(f.abs); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 500 }); + } + const env = analysis.peak; + const i0 = Math.max(0, Math.min(env.length, Math.floor(fromQ * ENV_RATE))); + const i1 = Math.max(i0, Math.min(env.length, Math.ceil(Math.min(toQ, env.length / ENV_RATE) * ENV_RATE))); + return Response.json( + { from: i0 / ENV_RATE, to: i1 / ENV_RATE, duration: analysis.duration, path: f.rel, ...bucketsOf(env, i0, i1, buckets) }, + { headers: cache }, + ); +} + export async function GET(request: Request) { const url = new URL(request.url); + if (url.searchParams.get("path")) return filePeaks(request, url); // `take` (walk a take): the take's clip, its window as the take has it -- as /raw. const take = url.searchParams.get("take") || null; const r = await resolveClip(url.searchParams.get("project") ?? "", url.searchParams.get("clip") ?? "", { take }); @@ -54,19 +106,10 @@ export async function GET(request: Request) { const env = analysis.peak; const n = env.length; - const min: number[] = []; - const max: number[] = []; - for (let b = 0; b < buckets; b += 1) { - const i0 = Math.floor((b / buckets) * n); - const i1 = Math.max(i0 + 1, Math.floor(((b + 1) / buckets) * n)); - let p = 0; - for (let i = i0; i < i1 && i < n; i += 1) if (env[i] > p) p = env[i]; - max.push(p); - // analyseMedia's envelope is positive-only. Mirroring it is what makes the - // canvas draw the symmetric shape a waveform is expected to be, rather than - // a row of upward spikes. - min.push(-p); - } + // analyseMedia's envelope is positive-only. Mirroring it (bucketsOf) is what + // makes the canvas draw the symmetric shape a waveform is expected to be, + // rather than a row of upward spikes. + const { min, max } = bucketsOf(env, 0, n, buckets); return Response.json( { diff --git a/umtool/lib/report/projectFile.mjs b/umtool/lib/report/projectFile.mjs @@ -0,0 +1,46 @@ +// A FILE OF THE PROJECT, served to a bench ("use a file", lane/reel-bench): a +// rendered file -- a take's master first -- that a bench plays, decodes and +// draws the envelope of, named by its path RELATIVE to the project. +// +// The path is lexical first (inside the project, no `..`, a media file by its +// extension), then real: the file's real path must stay under the real path +// of the project or of one of its own directories on the way to it -- a +// take's out/ may be a link to the media drive, and that link is the +// project's own decision; nothing else is followed out of it. +// +// Plain ESM. +import { realpath, stat } from "node:fs/promises"; +import path from "node:path"; + +/** What a bench may play. */ +export const PROJECT_MEDIA = /\.(mp4|m4v|mov|mkv|webm|m4a|mp3|wav)$/i; + +/** + * @param {{ dir: string }} project + * @param {string} rel + * @returns {Promise<{ abs: string, rel: string, size: number, mtimeMs: number } | { error: string, status: number }>} + */ +export async function resolveProjectFile(project, rel) { + const r = String(rel ?? "").replace(/\\/g, "/"); + if (!r || r.startsWith("/") || r.split("/").some((s) => s === ".." || s === "" || s === ".")) return { error: "path is a file inside the project, relative to it", status: 400 }; + if (!PROJECT_MEDIA.test(r)) return { error: "path names a media file (mp4, mov, mkv, webm, m4a, mp3, wav)", status: 400 }; + const lexical = path.join(project.dir, ...r.split("/")); + const real = await realpath(lexical).catch(() => null); + if (!real) return { error: `no ${r} in this project`, status: 404 }; + // The project's own directories on the way to the file, each by its real path. + const segs = r.split("/").slice(0, -1); + const roots = [project.dir]; + for (let k = 1; k <= segs.length; k += 1) roots.push(path.join(project.dir, ...segs.slice(0, k))); + let ok = false; + for (const d of roots) { + const rd = await realpath(d).catch(() => null); + if (rd && real.startsWith(`${rd}${path.sep}`)) { + ok = true; + break; + } + } + if (!ok) return { error: "not served", status: 403 }; + const st = await stat(real).catch(() => null); + if (!st?.isFile()) return { error: "gone", status: 404 }; + return { abs: real, rel: r, size: st.size, mtimeMs: Math.round(st.mtimeMs) }; +}