Archilyzer · Source

archilyzer

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

commit 02cd43d832cc8d8442063363fe38b23e1dce341f
parent 69b2d2465b285385411b032ab39eb158f47868fe
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 31 Oct 2026 13:11:48 -0400

umtool: export one clip -- clean, into the project's exports/, with Download and Open folder

The clip bench's reader (on a phone too) and Play the cut (the clip at the
playhead, or a note's clip) get Export clip and raw: the clip as the cut plays
it -- the render's edges, its gaps out as jump cuts, its mute, its audio knobs
-- or its whole fetched window, with no deck chrome, re-encoded frame-exact
(x264 crf 18, AAC 192k, faststart) into <project>/exports/ as
<clip>[-raw]-<date>-<slug>.mp4. Then Download (the file as an attachment) and
Open folder (the file manager on this machine, the file selected; refused in a
container or from another device). Nothing is fetched: an unfetched clip says
"fetch it first".

lib/report/clipExport.mjs (plan, ffmpeg arguments, names), openFolder.mjs,
POST /api/report/clip-export, GET/POST /api/report/exports, cutPoints.mjs's
clipSourceOf (the build's own source resolution), `umtool export <p> <clip>
[--raw] [--take T] [--open]`, docs/knobs.md "Export one clip", unit tests and
an e2e spec.

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

Diffstat:
Aumtool/app/api/report/clip-export/route.ts | 66++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/report/exports/route.ts | 73+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/bin/umtool.mjs | 32+++++++++++++++++++++++++++++++-
Mumtool/components/projects/ClipBench.tsx | 5+++++
Aumtool/components/projects/ClipExport.tsx | 228+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/review/PlayCut.tsx | 66++++++++++++++++++++++++++++++++++++++++++++++++++++++------------
Mumtool/docs/knobs.md | 35+++++++++++++++++++++++++++++++++++
Aumtool/e2e/clip-export.spec.ts | 109+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/clipExport.mjs | 375+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/clipExport.test.mjs | 266+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/cutPoints.mjs | 46+++++++++++++++++++++++++++++++++++++++++-----
Aumtool/lib/report/openFolder.mjs | 154+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/playwright.config.ts | 5+++++
13 files changed, 1442 insertions(+), 18 deletions(-)

diff --git a/umtool/app/api/report/clip-export/route.ts b/umtool/app/api/report/clip-export/route.ts @@ -0,0 +1,66 @@ +import { projectRef } from "@/lib/projects"; +import { kindMakesTakes } from "@/lib/projects/kinds.mjs"; +import { refuseCaller } from "@/lib/report/caller"; +import { EXPORT_KINDS, ExportRefused, exportClip } from "@/lib/report/clipExport.mjs"; +import { cannotOpen, localRequest } from "@/lib/report/openFolder.mjs"; + +export const dynamic = "force-dynamic"; + +// EXPORT ONE CLIP (umtool/docs/knobs.md, "Export one clip"): a clean mp4 of a +// clip -- the cut's edges, its gaps out as jump cuts, its mute -- or its whole +// fetched window (`raw`), with no deck chrome, into <project>/exports/. +// +// POST { project, clip, take?, kind?: "cut" | "raw" } +// -> { ok, name, rel, size, seconds, summary, notes, download, canOpen, openWhy? } +// +// Answered when the file is written: one short clip, re-encoded once on this +// machine (seconds, not minutes), outside the job runner and the heavy slot, +// so it never waits behind a build. A second ask for the same file waits for +// the first. Nothing is fetched: a clip whose window is not on disk is a 409 +// saying so. Names, never paths: a project of the scan, a clip of its cut. +const headers = { "cache-control": "no-store" }; + +export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/clip-export"); + if (refused) return refused; + const body = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!body || typeof body !== "object") return Response.json({ error: "expected JSON" }, { status: 400, headers }); + const project = await projectRef(String(body.project ?? "")); + if (!project) return Response.json({ error: "no such project" }, { status: 404, headers }); + if (!kindMakesTakes(project.kind)) return Response.json({ error: "an export is made of a report video's clip" }, { status: 400, headers }); + const clip = String(body.clip ?? ""); + if (!clip) return Response.json({ error: "which clip?" }, { status: 400, headers }); + const take = typeof body.take === "string" && body.take ? body.take : null; + const kind = body.kind === undefined || body.kind === null || body.kind === "" ? "cut" : String(body.kind); + if (!(EXPORT_KINDS as readonly string[]).includes(kind)) { + return Response.json({ error: `kind is one of ${EXPORT_KINDS.join(", ")}` }, { status: 400, headers }); + } + try { + const r = await exportClip(project, clip, { take, kind: kind as "cut" | "raw" }); + const no = cannotOpen(); + const local = localRequest(request.headers); + const openWhy = no ?? (local.ok ? null : `Open folder works on the machine umtool runs on: ${local.why}`); + return Response.json( + { + ok: true, + clip: r.clip, + take: r.take, + kind: r.kind, + name: r.name, + rel: r.rel, + size: r.size, + mtimeMs: r.mtimeMs, + seconds: r.seconds, + summary: r.summary, + notes: r.notes, + download: `/api/report/exports?${new URLSearchParams({ project: project.id, name: r.name, v: String(r.mtimeMs) }).toString()}`, + canOpen: !openWhy, + ...(openWhy ? { openWhy } : {}), + }, + { headers }, + ); + } catch (e) { + const status = e instanceof ExportRefused ? e.status : 500; + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers }); + } +} diff --git a/umtool/app/api/report/exports/route.ts b/umtool/app/api/report/exports/route.ts @@ -0,0 +1,73 @@ +import path from "node:path"; +import { stat } from "node:fs/promises"; +import { projectRef } from "@/lib/projects"; +import { refuseCaller } from "@/lib/report/caller"; +import { EXPORTS_DIR, exportFileOf, listExports } from "@/lib/report/clipExport.mjs"; +import { cannotOpen, localRequest, openFolder } from "@/lib/report/openFolder.mjs"; +import { rangeResponse } from "@/lib/report/serve.mjs"; + +export const dynamic = "force-dynamic"; + +// A PROJECT'S exports/ (the clip export's Download and Open folder; the +// operator's hand-made exports live there too). +// +// GET ?project=<id> { exports: [{ name, size, mtimeMs }], canOpen, openWhy? } +// GET ?project=<id>&name=<file> the file, as an attachment (ranges) +// POST { project, name? } show exports/ in this machine's file manager, +// the file selected where it can be; refused +// in a container and from another device +// +// A name is one plain `*.mp4` under exports/ -- never a path. +const noStore = { "cache-control": "no-store" }; + +export async function GET(request: Request) { + const url = new URL(request.url); + const project = await projectRef(url.searchParams.get("project") ?? ""); + if (!project) return Response.json({ error: "no such project" }, { status: 404, headers: noStore }); + const name = url.searchParams.get("name"); + if (name === null) { + const no = cannotOpen(); + const local = localRequest(request.headers); + const openWhy = no ?? (local.ok ? null : local.why); + return Response.json({ exports: await listExports(project.dir), canOpen: !openWhy, ...(openWhy ? { openWhy } : {}) }, { headers: noStore }); + } + const abs = exportFileOf(project.dir, name); + const st = abs ? await stat(/* turbopackIgnore: true */ abs).catch(() => null) : null; + if (!abs || !st?.isFile()) return new Response(`no export ${name} in ${project.id}`, { status: 404 }); + const file = path.basename(abs); + return rangeResponse(request, { + abs, + size: st.size, + headers: { + "content-type": "video/mp4", + "accept-ranges": "bytes", + "content-disposition": `attachment; filename="${file.replace(/"/g, "")}"; filename*=UTF-8''${encodeURIComponent(file)}`, + "cache-control": url.searchParams.get("v") === String(Math.round(st.mtimeMs)) ? "private, max-age=3600, immutable" : "private, no-store", + }, + }); +} + +export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/exports"); + if (refused) return refused; + const body = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!body || typeof body !== "object") return Response.json({ error: "expected JSON" }, { status: 400, headers: noStore }); + const project = await projectRef(String(body.project ?? "")); + if (!project) return Response.json({ error: "no such project" }, { status: 404, headers: noStore }); + const local = localRequest(request.headers); + if (!local.ok) return Response.json({ error: `Open folder works on the machine umtool runs on: ${local.why} — use Download` }, { status: 403, headers: noStore }); + const dir = path.join(/* turbopackIgnore: true */ project.dir, EXPORTS_DIR); + if (!(await stat(/* turbopackIgnore: true */ dir).catch(() => null))?.isDirectory()) { + return Response.json({ error: `${project.id} has no ${EXPORTS_DIR}/ yet — export a clip first` }, { status: 404, headers: noStore }); + } + let file: string | null = null; + if (body.name !== undefined && body.name !== null && body.name !== "") { + file = exportFileOf(project.dir, body.name); + if (!file || !(await stat(/* turbopackIgnore: true */ file).catch(() => null))?.isFile()) { + return Response.json({ error: `no export ${String(body.name)} in ${project.id}` }, { status: 404, headers: noStore }); + } + } + const r = await openFolder({ dir, file }); + if (!r.ok) return Response.json({ error: r.error }, { status: 409, headers: noStore }); + return Response.json({ ok: true, how: r.how, selected: r.selected, dir: EXPORTS_DIR }, { headers: noStore }); +} diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -54,6 +54,8 @@ // umtool snapshot <project> [--label L] copy the manifest into revisions/ // umtool diff <project> <snapshot> what changed since that snapshot // umtool export <project> --format toc-bbcode|toc-markdown|description|chapters [--variant V] +// umtool export <project> <clip> [--raw] [--take T] [--open] [--json] one clip, clean, into +// <project>/exports/: the cut's edges, gaps out, mute (--raw: the whole fetched window) // umtool check-sources [<project>…] prints the re-check chain // umtool notes [<site>/<report> | <project> | --all] [--open|--resolved|--all-status] [--json] // umtool notes reply <id> "<text>" [--resolve] | resolve | wontfix | reopen <id> @@ -683,7 +685,9 @@ async function cmdDiff() { async function cmdExport() { const p = await pick(positional[0]); const format = val("--format"); - if (!format) die(`--format is one of ${EXPORT_FORMATS.join(", ")}`); + // `umtool export <project> <clip>`: one clip, clean, into <project>/exports/ (lib/report/clipExport.mjs). + if (!format && positional[1]) return cmdExportClip(p, positional[1]); + if (!format) die(`--format is one of ${EXPORT_FORMATS.join(", ")} — or name a clip: umtool export ${p.id} <clip> [--raw] [--open]`); try { const r = await exportProject(p.dir, format, val("--variant") ? { variant: val("--variant") } : {}); if (json) return out(r); @@ -694,6 +698,30 @@ async function cmdExport() { } } +// One clip, clean (umtool/docs/knobs.md, "Export one clip"): the cut's edges, +// its gaps out, its mute -- or `--raw`, the whole fetched window -- with no +// deck chrome. Runs here, with this machine's ffmpeg; nothing is fetched. +async function cmdExportClip(p, clipId) { + const { exportClip } = await import("../lib/report/clipExport.mjs"); + let r; + try { + r = await exportClip(p, clipId, { take: val("--take") ?? null, kind: has("--raw") ? "raw" : "cut" }); + } catch (e) { + die(e?.message ?? String(e), 1); + } + let opened = null; + if (has("--open")) { + const { openFolder } = await import("../lib/report/openFolder.mjs"); + opened = await openFolder({ dir: path.dirname(r.abs), file: r.abs }); + } + const { plan: _plan, ...view } = r; + if (json) return out({ ...view, ...(opened ? { opened } : {}) }); + console.log(r.abs); + console.log(` ${r.kind === "raw" ? "raw window" : "the cut's clip"}: ${r.summary} · ${(r.size / 1e6).toFixed(1)} MB`); + for (const n of r.notes) console.log(` NOTE ${n}`); + if (opened) console.log(opened.ok ? ` opened ${path.dirname(r.abs)} (${opened.how})` : ` could not open the folder: ${opened.error}`); +} + async function cmdCheckSources() { // Print, never run -- the same posture as `build`. With no arguments, the // projects the dashboard would re-check: never checked, or older than 30 d. @@ -805,6 +833,8 @@ function usage() { " umtool snapshot <project> [--label L] copy the manifest into revisions/", " umtool diff <project> <snapshot> what changed since that snapshot", " umtool export <project> --format toc-bbcode|toc-markdown|description|chapters [--variant V]", + " umtool export <project> <clip> [--raw] [--take T] [--open] one clip, clean, into <project>/exports/:", + " the cut's edges, its gaps out, its mute; --raw the whole fetched window; --open shows it", " umtool check-sources [<project>…] prints the re-check chain (never-checked/old when no args)", " umtool notes [<site>/<report>|<project>|--all] the operator's notes, as markdown (open ones)", " umtool notes reply <id> \"<text>\" [--resolve] answer one; resolve | wontfix | reopen <id>", diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx @@ -19,6 +19,7 @@ import { citationText } from "@/lib/research/facets.mjs"; import { cn } from "@/lib/utils"; import { BenchBody, VerdictBar } from "./bench/BenchShell"; import CopyCitation from "./bench/CopyCitation"; +import { ClipExportButtons, ClipExportStatus, useClipExport } from "./ClipExport"; import EdgeStrip from "./bench/EdgeStrip"; import RenderGhosts, { useRenderEdges } from "./bench/RenderGhosts"; import { GapLayer, ZoomControls, ZoomOverview, ZoomRuler, useWaveZoom, type Span } from "./bench/GapsZoom"; @@ -521,6 +522,8 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { const takeId = data.take?.id ?? null; const tq = takeId ? `&take=${encodeURIComponent(takeId)}` : ""; const takeBody = takeId ? { take: takeId } : {}; + // Export clip (ClipExport.tsx): this clip, clean, into the project's exports/ -- the take's clip on a take's walk. + const clipExport = useClipExport(data.project, takeId); const [clip, setClip] = useState<Clip>(data.clip); const [windows, setWindows] = useState<Win[]>(data.windows); const [cues, setCues] = useState<Cue[]>(data.cues); @@ -2695,6 +2698,8 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { > Play clip </button> + <ClipExportButtons exp={clipExport} clip={clip.id} surface="paper" why={cached ? null : "its window is not fetched — fetch it first"} unsaved={unsaved} /> + <ClipExportStatus exp={clipExport} surface="paper" /> </> } fine={`cites ${clock(citeAt)}${cached ? ` · clip window cached in ${cached.name}` : " · not fetched"}`} diff --git a/umtool/components/projects/ClipExport.tsx b/umtool/components/projects/ClipExport.tsx @@ -0,0 +1,228 @@ +"use client"; + +import { useCallback, useEffect, useRef, useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; +import { paperButtonVariants } from "@/components/ui/reader-pane"; +import { useHydrated } from "@/components/ui/use-hydrated"; +import { cn } from "@/lib/utils"; + +// --------------------------------------------------------------------------- +// EXPORT ONE CLIP (operator, 2026-10-31: "an export button that maybe even +// opens up the folder to let me grab a clean cropped export of any one clip"): +// the clip as the cut plays it -- its edges, its gaps out as jump cuts, its +// mute -- or its whole fetched window (raw), no deck chrome, written to the +// project's exports/ (lib/report/clipExport.mjs, POST /api/report/clip-export). +// +// Then Download (everywhere -- a phone cannot open a folder: the file served +// as an attachment by /api/report/exports) and Open folder (on the machine +// umtool runs on: the file manager shows exports/ with the file selected; +// the server says when it cannot, and why). The bench's reader footer and +// Play the cut both use it; Play exports the clip at the playhead, or the one +// a note points at, through one `useClipExport`. +// --------------------------------------------------------------------------- + +export type ClipExportKind = "cut" | "raw"; + +type Done = { + clip: string; + kind: ClipExportKind; + name: string; + rel: string; + size: number; + seconds: number; + summary: string; + notes: string[]; + download: string; + canOpen: boolean; + openWhy?: string; +}; + +export type ClipExportState = + | { k: "idle" } + | { k: "exporting"; clip: string; kind: ClipExportKind; since: number } + | { k: "ready"; done: Done; open: { k: "idle" } | { k: "opening" } | { k: "opened"; how: string } | { k: "failed"; error: string } } + | { k: "failed"; clip: string; kind: ClipExportKind; error: string }; + +export type ClipExportHandle = { + state: ClipExportState; + busy: boolean; + run: (clip: string, kind?: ClipExportKind) => Promise<void>; + openFolder: () => Promise<void>; + dismiss: () => void; +}; + +const mb = (n: number) => `${(n / 1e6).toFixed(n < 1e7 ? 1 : 0)} MB`; + +/** One project's (or take's) export: what is being made, what was, and Open folder. */ +export function useClipExport(project: string, take: string | null = null): ClipExportHandle { + const [state, setState] = useState<ClipExportState>({ k: "idle" }); + const seq = useRef(0); + const busy = state.k === "exporting"; + const run = useCallback( + async (clip: string, kind: ClipExportKind = "cut") => { + const mine = ++seq.current; + setState({ k: "exporting", clip, kind, since: Date.now() }); + try { + const r = await fetch("/api/report/clip-export", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, clip, kind, ...(take ? { take } : {}) }), + }); + const j = (await r.json().catch(() => ({}))) as Partial<Done> & { error?: string }; + if (mine !== seq.current) return; + if (!r.ok || !j.name) setState({ k: "failed", clip, kind, error: String(j.error ?? `HTTP ${r.status}`) }); + else setState({ k: "ready", done: { ...(j as Done), clip, kind }, open: { k: "idle" } }); + } catch (e) { + if (mine === seq.current) setState({ k: "failed", clip, kind, error: e instanceof Error ? e.message : String(e) }); + } + }, + [project, take], + ); + const openFolder = useCallback(async () => { + if (state.k !== "ready") return; + const done = state.done; + setState({ k: "ready", done, open: { k: "opening" } }); + try { + const r = await fetch("/api/report/exports", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, name: done.name }), + }); + const j = (await r.json().catch(() => ({}))) as { ok?: boolean; how?: string; error?: string }; + setState((s) => + s.k === "ready" && s.done.name === done.name + ? { ...s, open: r.ok && j.ok ? { k: "opened", how: String(j.how ?? "") } : { k: "failed", error: String(j.error ?? `HTTP ${r.status}`) } } + : s, + ); + } catch (e) { + setState((s) => (s.k === "ready" && s.done.name === done.name ? { ...s, open: { k: "failed", error: e instanceof Error ? e.message : String(e) } } : s)); + } + }, [project, state]); + const dismiss = useCallback(() => { + seq.current += 1; + setState({ k: "idle" }); + }, []); + return { state, busy, run, openFolder, dismiss }; +} + +type Surface = "paper" | "panel"; +const btn = (surface: Surface, quiet = false) => + surface === "paper" + ? paperButtonVariants() + : buttonVariants({ variant: quiet ? "quiet" : "outline", size: "sm" }); + +/** Export clip, and its raw choice, for `clip` (null: nothing to export here, `why` says so). */ +export function ClipExportButtons({ + exp, + clip, + surface = "panel", + why = null, + unsaved = false, +}: { + exp: ClipExportHandle; + clip: string | null; + surface?: Surface; + /** Why there is nothing to export (a card, a window not fetched): the buttons are off and say so. */ + why?: string | null; + /** The bench has an edit not saved yet: the export is of the SAVED clip. */ + unsaved?: boolean; +}) { + const hydrated = useHydrated(); + const off = !hydrated || !clip || !!why || exp.busy; + const saved = unsaved ? " — of the SAVED window: save first to export your edit" : ""; + return ( + <> + <button + type="button" + data-clip-export-go={clip ?? ""} + className={btn(surface)} + disabled={off} + title={why ?? (clip ? `a clean mp4 of ${clip} as the cut plays it — its edges, gaps out, its mute; no deck — into the project's exports/${saved}` : "")} + onClick={() => clip && void exp.run(clip, "cut")} + > + Export clip + </button> + <button + type="button" + data-clip-export-raw={clip ?? ""} + className={cn(btn(surface, true), surface === "paper" && "border-transparent")} + disabled={off} + title={why ?? (clip ? `the whole fetched window of ${clip}, as recorded: no gaps, no mute` : "")} + onClick={() => clip && void exp.run(clip, "raw")} + > + raw + </button> + </> + ); +} + +/** Exporting… / the file, Download, Open folder / failed, with the reason. */ +export function ClipExportStatus({ exp, surface = "panel", className }: { exp: ClipExportHandle; surface?: Surface; className?: string }) { + const s = exp.state; + const [, tick] = useState(0); + useEffect(() => { + if (s.k !== "exporting") return; + const t = window.setInterval(() => tick((n) => n + 1), 1000); + return () => window.clearInterval(t); + }, [s.k]); + if (s.k === "idle") return null; + const muted = surface === "paper" ? "text-reader-dim" : "text-muted"; + const link = surface === "paper" ? "font-medium text-reader-ink underline underline-offset-2" : "ink-link"; + const base = cn("basis-full min-w-0 text-[11.5px]", surface === "paper" ? "text-reader-ink" : "text-text-2", className); + if (s.k === "exporting") { + return ( + <p role="status" className={cn(base, "m-0")} data-clip-export-state="exporting"> + Exporting {s.clip} + {s.kind === "raw" ? " (raw window)" : ""}… <span className={cn("font-mono", muted)}>{Math.max(0, Math.round((Date.now() - s.since) / 1000))} s</span> + </p> + ); + } + if (s.k === "failed") { + return ( + <p role="alert" className={cn(base, "m-0 text-reject-text")} data-clip-export-state="failed"> + Export of {s.clip} failed: {s.error}{" "} + <button type="button" className={link} onClick={exp.dismiss}> + dismiss + </button> + </p> + ); + } + const d = s.done; + return ( + <div role="status" className={cn(base, "flex flex-wrap items-baseline gap-x-2 gap-y-1")} data-clip-export-state="ready" data-clip-export-name={d.name}> + <span className="min-w-0 break-all font-mono">{d.rel}</span> + <span className={cn("font-mono", muted)}> + {d.seconds.toFixed(1)} s · {mb(d.size)} + </span> + <a href={d.download} download={d.name} className={link} data-clip-export-download=""> + Download + </a> + {d.canOpen ? ( + <button + type="button" + className={link} + data-clip-export-open="" + disabled={s.open.k === "opening"} + onClick={() => void exp.openFolder()} + title="show the project's exports/ in this machine's file manager, the file selected" + > + {s.open.k === "opening" ? "Opening…" : "Open folder"} + </button> + ) : ( + <span className={muted} title={d.openWhy} data-clip-export-noopen=""> + (Open folder: on the machine umtool runs on) + </span> + )} + {s.open.k === "opened" && <span className={muted} data-clip-export-opened="">shown in the file manager</span>} + {s.open.k === "failed" && ( + <span className="text-reject-text" data-clip-export-open-error=""> + {s.open.error} + </span> + )} + <span className={cn("basis-full", muted)}> + {d.summary} + {d.notes.length ? ` · ${d.notes.join(" · ")}` : ""} + </span> + </div> + ); +} diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -22,6 +22,7 @@ import { useRenderCuts, type RenderCuts } from "./playEngine/useRenderCuts"; import type { EngineInfo, MediaRef } from "./playEngine/engine"; import ReelStrip, { type StripCounter } from "./ReelStrip"; import RejectClip from "./RejectClip"; +import { ClipExportButtons, ClipExportStatus, useClipExport } from "../ClipExport"; // --------------------------------------------------------------------------- // THE PLAY VIEW (umtool/docs/knobs.md, "Play the cut"): a screening room. The @@ -221,6 +222,8 @@ export default function PlayCut({ const router = useRouter(); const project = view.project; const take = view.take?.id ?? null; + // Export clip (ClipExport.tsx): the clip at the playhead -- or the one a note points at -- clean, into exports/. + const clipExport = useClipExport(project, take); // ---- the composition (the live preview's) --------------------------------- const [doc, setDoc] = useState<LiveDoc | null>(null); @@ -819,6 +822,15 @@ export default function PlayCut({ </button> </p> )} + {/* Export clip: the clip on screen as the cut plays it (or raw), no deck, into exports/; Download, Open folder. */} + <div className="flex flex-wrap items-center gap-1.5 text-[12px]" data-play-export=""> + <ClipExportButtons + exp={clipExport} + clip={item?.clip ? item.id : null} + why={!item?.clip ? "a card is not a clip: nothing to export" : !entry?.media ? "its window is not fetched — fetch it first" : null} + /> + <ClipExportStatus exp={clipExport} /> + </div> {/* Reject ▾ (x): the clip on screen out of the cut for a reason, on record, with an undo (the project's cut: not on a take). */} {!take && ( <RejectClip @@ -946,6 +958,12 @@ export default function PlayCut({ router.refresh(); if (view.deckOn) void compose(); }} + exportable={(id) => { + const e = entryOf.get(id); + return e?.type === "clip" && !!e.media; + }} + exporting={clipExport.busy} + onExport={(clip) => void clipExport.run(clip, "cut")} /> </aside> </div> @@ -1128,6 +1146,9 @@ function PlayNotes({ onClose, onSeek, onApplied, + exportable, + exporting, + onExport, }: { project: string; take: string | null; @@ -1141,6 +1162,10 @@ function PlayNotes({ onClose: () => void; onSeek: (n: Note) => void; onApplied: () => void; + /** Is this entry a clip whose window is on disk (a note on it offers Export)? */ + exportable: (id: string) => boolean; + exporting: boolean; + onExport: (clip: string) => void; }) { const a = useAssist(project); const reloadNotes = notes.reload; @@ -1246,18 +1271,35 @@ function PlayNotes({ busy={notes.busy} head={head(n)} actions={ - n.status === "open" ? ( - <button - type="button" - data-play-send={n.id} - disabled={notes.busy || a.busy || !!blocked || running} - title={blocked ?? "the assistant reads this note (where it was taken, what it asks for) and replies here; what it proposes waits for your Apply"} - onClick={() => void a.ask({ note: n.id, scope: askOf(n) === "look" ? "look" : "all" })} - className="ink-link disabled:opacity-40" - > - {asking === n.id ? "Asking…" : "Send to the assistant"} - </button> - ) : null + <> + {n.status === "open" ? ( + <button + type="button" + data-play-send={n.id} + disabled={notes.busy || a.busy || !!blocked || running} + title={blocked ?? "the assistant reads this note (where it was taken, what it asks for) and replies here; what it proposes waits for your Apply"} + onClick={() => void a.ask({ note: n.id, scope: askOf(n) === "look" ? "look" : "all" })} + className="ink-link disabled:opacity-40" + > + {asking === n.id ? "Asking…" : "Send to the assistant"} + </button> + ) : null} + {(() => { + const clip = (n.anchor as CutAnchor).entry; + return clip && exportable(clip) ? ( + <button + type="button" + data-play-note-export={clip} + disabled={exporting} + title={`a clean mp4 of ${clip} as the cut plays it, into the project's exports/ (under the transport: Download, Open folder)`} + onClick={() => onExport(clip)} + className="ink-link disabled:opacity-40" + > + Export {clip} + </button> + ) : null; + })()} + </> } afterReply={(r) => ( <AssistReplyApply reply={r} proposals={p} busy={a.busy} apply={apply} variant="outline" onApplied={() => void notes.write({ op: "reply", id: n.id, text: "Applied the assistant's edits" })} /> diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -361,6 +361,41 @@ it replies on the note as the agent; with no route the button says why, and the Then the cut: the Build tab's **final** preset (a full build, about an hour for a 36-clip cut), and Deliver's **Make variants**. +## Export one clip + +A clean mp4 of ONE clip, to post or hand on: the clip's footage as the cut plays it, with none of the deck — no rail, +subtitles, QR, cards or stamps — written to the project's **`exports/`** (beside the hand-made ones) as +`<clip>-<YYYY-MM-DD>-<slug>.mp4` (`<clip>-raw-…` for raw): the clip's date (its `date`, else the on-screen date, else +the upload date; today with none) and the first words of its quote (else its title, else the video id). The same name +again is written over. + +| | In umtool | From a terminal | Route | +|---|---|---|---| +| the clip as the cut plays it | the clip bench's reader, **Export clip** (on a phone too); Play the cut, **Export clip** under the transport (the clip at the playhead) or a note's **Export &lt;clip&gt;** | `umtool export <p> <clip> [--take <t>] [--json]` | `POST /api/report/clip-export {project, clip, take?, kind?: "cut"}` | +| the whole fetched window, as recorded | **raw** beside it | `umtool export <p> <clip> --raw` | `… {kind: "raw"}` | +| the file | **Download** (an attachment; the phone's way) | the path it prints | `GET /api/report/exports?project=<p>&name=<file>` (`GET …?project=<p>` lists them) | +| `exports/` in this machine's file manager, the file selected | **Open folder** | `--open` | `POST /api/report/exports {project, name?}` | + +- **The cut** (`lib/report/clipExport.mjs`): cut from the file the build would cut it from (the build's own source + resolution, `cutPoints.mjs`), at the **render's edges** (snapped to silence, as Play plays them; room's muted + picture at an edge left off) — the manifest's play window when they cannot be measured, and the answer says so — + its **`gaps`** out as jump cuts on the frame grid with the build's 25 ms join fades, its sound **silenced** where the + cut silences it (`muteFrom`, a locked edge: `mute.mjs` soundOnSegment), its `audio` knobs (offset, gain, fades) and + the cut's loudness gain. Not applied: a blur (the export is unblurred, and says so), a montage's phrase cut. +- **Raw**: the clip and the build's fetch pad either side (`render.fetchPad`, 3 s), clamped to the cached file — no + gaps, no mute, no knobs. +- **The encode**: cut on the input and re-encoded, so every cut is frame-exact — libx264 crf 18, yuv420p, AAC 192k, + `+faststart`, no metadata or chapters. A few seconds for a short clip (≈10 s for 30 s of 720p); it does not take + the heavy slot or the job runner, so it never waits behind a build. A second ask for the same file waits for the + first. +- **Nothing is fetched.** A clip whose window is not on disk is refused — "fetch it first" (the Cut tab's Fetch, + `umtool fetch <p>`); the buttons say so before you press them. On the bench the export is of the SAVED clip: save an + edge you moved first. +- **Open folder** asks the desktop: `org.freedesktop.FileManager1.ShowItems` over the session bus (the file + selected), else `xdg-open <exports/>` on Linux; `open -R` on macOS. Refused, with the reason, inside a container, + on another OS, and from any device but the machine umtool runs on (by the request's Host, Origin and + X-Forwarded-For) — use **Download** there. + ## Make variants, and the sync report | | In umtool | From a terminal | Route | diff --git a/umtool/e2e/clip-export.spec.ts b/umtool/e2e/clip-export.spec.ts @@ -0,0 +1,109 @@ +import { test, expect, type Page } from "@playwright/test"; +import { existsSync, readFileSync, rmSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// Export one clip (umtool/docs/knobs.md, "Export one clip"): Play the cut's +// Export clip writes the clip at the playhead -- clean, the cut's edges, no +// deck -- into the project's exports/ under the clip's name, then offers +// Download (the file as an attachment) and Open folder (recorded by the +// fixture's E2E_UMTOOL_OPEN_FOLDER_LOG, never a real file manager); raw is +// the whole fetched window. On a phone, the bench's reader has the same +// Export and Download. +// +// Fixtures: play-cut-fixture (c01 playvid 1.0-3.0, "24 Oct 2020") and +// phone-walk-fixture (p01 walk1 3.0-6.0). Their exports/ are removed after. +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const PLAY = "reports/play-cut-fixture"; +const WALK = "reports/phone-walk-fixture"; +const exportsOf = (project: string) => path.join(FIXTURE, ...project.split("/"), "exports"); +const OPEN_LOG = path.join(FIXTURE, "open-folder.jsonl"); + +test.beforeEach(() => { + test.setTimeout(120_000); +}); + +test.afterAll(() => { + for (const p of [PLAY, WALK]) rmSync(exportsOf(p), { recursive: true, force: true }); +}); + +const ready = async (page: Page) => { + const root = page.locator("[data-play-cut]"); + await expect(root).toHaveAttribute("data-play-state", "paused"); + await expect(root).toHaveAttribute("data-play-edges", "render", { timeout: 30_000 }); +}; + +test("Play the cut: Export clip writes the clip at the playhead to exports/; Download and Open folder; raw", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 1000 }); + await page.goto(urls.playHref(PLAY)); + await ready(page); + await expect(page.locator("[data-play-cut]")).toHaveAttribute("data-play-item", "c01"); + + const go = page.locator('[data-clip-export-go="c01"]'); + await expect(go).toBeEnabled(); + await go.click(); + const state = page.locator("[data-clip-export-state]"); + await expect(state).toHaveAttribute("data-clip-export-state", "ready", { timeout: 60_000 }); + const name = "c01-2020-10-24-this-is-a-complete-sentence.mp4"; + await expect(state).toHaveAttribute("data-clip-export-name", name); + await expect(state).toContainText(`exports/${name}`); + expect(existsSync(path.join(exportsOf(PLAY), name))).toBe(true); + + // Download: the file, as an attachment under its own name. + const href = await page.locator("[data-clip-export-download]").getAttribute("href"); + expect(href).toBeTruthy(); + const res = await page.request.get(href!); + expect(res.status()).toBe(200); + expect(res.headers()["content-type"]).toBe("video/mp4"); + expect(res.headers()["content-disposition"]).toContain(`attachment; filename="${name}"`); + expect((await res.body()).length).toBeGreaterThan(1000); + // The listing has it. + const listed = (await (await page.request.get(`/api/report/exports?project=${encodeURIComponent(PLAY)}`)).json()) as { exports: { name: string }[]; canOpen: boolean }; + expect(listed.exports.map((e) => e.name)).toContain(name); + expect(listed.canOpen).toBe(true); + // A name that is not one plain mp4 under exports/ is nothing. + expect((await page.request.get(`/api/report/exports?project=${encodeURIComponent(PLAY)}&name=..%2Fvideo.manifest.json`)).status()).toBe(404); + + // Open folder: asked of this machine's file manager (here, the log), the file selected. + await page.locator("[data-clip-export-open]").click(); + await expect(page.locator("[data-clip-export-opened]")).toBeVisible(); + const asked = readFileSync(OPEN_LOG, "utf8").trim().split("\n").map((l) => JSON.parse(l) as { dir: string; file: string | null }); + expect(asked.at(-1)?.dir).toBe(exportsOf(PLAY)); + expect(asked.at(-1)?.file).toBe(path.join(exportsOf(PLAY), name)); + // From another device it is refused, with the reason (and the page's own Host is not that device's). + const far = await page.request.post("/api/report/exports", { data: { project: PLAY, name }, headers: { "x-forwarded-for": "192.168.1.50" } }); + expect(far.status()).toBe(403); + expect(((await far.json()) as { error: string }).error).toContain("Download"); + + // raw: the whole fetched window, its own name. + await page.locator('[data-clip-export-raw="c01"]').click(); + await expect(state).toHaveAttribute("data-clip-export-name", "c01-raw-2020-10-24-this-is-a-complete-sentence.mp4", { timeout: 60_000 }); + await expect(state).toContainText("the whole window"); + await page.screenshot({ path: test.info().outputPath("play-export-1366.png") }); + + // A clip with no window on disk (c03): refused by the server with "fetch it first". + const refused = await page.request.post("/api/report/clip-export", { data: { project: PLAY, clip: "c03" } }); + expect(refused.status()).toBe(409); + expect(((await refused.json()) as { error: string }).error).toContain("fetch it first"); +}); + +test("the bench on a phone: Export clip in the reader, then Download", async ({ page }) => { + await page.setViewportSize({ width: 390, height: 844 }); + await page.goto(urls.clipBenchHref(WALK, "p01")); + await expect(page.locator('[data-bench="p01"]')).toHaveCount(1); + const go = page.locator('[data-clip-export-go="p01"]'); + await go.scrollIntoViewIfNeeded(); + await expect(go).toBeEnabled(); + await go.click(); + const state = page.locator("[data-clip-export-state]"); + await expect(state).toHaveAttribute("data-clip-export-state", "ready", { timeout: 60_000 }); + await expect(state).toHaveAttribute("data-clip-export-name", /^p01-\d{4}-\d{2}-\d{2}-and-because\.mp4$/); + await expect(page.locator("[data-clip-export-download]")).toBeVisible(); + expect(await page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth)).toBeLessThanOrEqual(0); + await page.screenshot({ path: test.info().outputPath("bench-export-390.png") }); +}); diff --git a/umtool/lib/report/clipExport.mjs b/umtool/lib/report/clipExport.mjs @@ -0,0 +1,375 @@ +// EXPORT ONE CLIP (umtool/docs/knobs.md, "Export one clip"): a clean mp4 of a +// single clip, cut from the file the build would cut it from, with none of the +// deck's chrome -- no rail, subtitles, QR or cards -- into the project's +// `exports/`, where the operator keeps the hand-made ones +// (`exports/tr3-2026-08-12-deal-with-it-autogynephiliac.mp4`). +// +// TWO KINDS. +// +// cut the clip as the cut plays it: the render's edges (cutPoints.mjs -- +// the build's own source, snap and room; the muted room at an edge is +// left off, since nothing is heard there), its `gaps` taken out as +// jump cuts on the frame grid with the build's 25 ms fades at each +// join (gaps.mjs gapFilterParts), its sound silenced where the cut +// silences it (mute.mjs soundOnSegment: `muteFrom`, a locked edge), +// its `audio` knobs (offset, gain, fades) and the cut's loudness gain. +// When the edges cannot be measured, the manifest's play window +// (noted). A blur, a montage's phrase cut and the deck are not applied. +// raw the whole fetched window -- the clip and the build's fetch pad +// either side, clamped to the file -- as recorded: no gaps, no mute, +// no knobs. +// +// Re-encoded, never stream-copied, so every cut is on the asked-for frame: +// libx264 crf 18, AAC 192k, +faststart. Light work (one short clip), so it +// does not take the heavy slot. Nothing is fetched: a clip with no window on +// disk is refused with "fetch it first". +// +// The pure half (names, the plan's ffmpeg arguments) is tested in +// clipExport.test.mjs; `exportClip` runs it. +import { spawn } from "node:child_process"; +import { mkdir, rename, rm, stat } from "node:fs/promises"; +import path from "node:path"; +import { gapFilterParts, gappedLength, gapsOf, gapsOnSegment, gapsWithin } from "umtool-report-to-video/gaps"; +import { MUTE_FADE, playEdges, soundOnSegment } from "umtool-report-to-video/mute"; +import { AUDIO_ON_CLOCK, clipAudioFilters, clipAudioOf, offsetWindow } from "umtool-report-to-video/clip-audio"; + +/** The folder under a project that exports go into. */ +export const EXPORTS_DIR = "exports"; + +/** The two kinds of export. */ +export const EXPORT_KINDS = Object.freeze(["cut", "raw"]); + +/** What a name under exports/ may be: one plain file name, an mp4. */ +export const EXPORT_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,180}\.mp4$/; + +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const n3 = (v) => Number(Number(v).toFixed(3)).toString(); + +/** + * A few words as a file-name slug: lower case, ASCII, hyphens. The bracketed + * ASR notes and bleeps a quote carries (`[ __ ]`, `[ASR; likely 'time']`) + * are left out. + * + * @param {string} text + * @param {{ words?: number, max?: number }} [opts] + */ +export function exportSlug(text, { words = 6, max = 48 } = {}) { + const plain = String(text ?? "") + .replace(/\[[^\]]*\]/g, " ") + .normalize("NFKD") + .replace(/[̀-ͯ]/g, "") + .toLowerCase() + .replace(/['’]/g, "") + .replace(/[^a-z0-9]+/g, " ") + .trim(); + if (!plain) return ""; + let out = ""; + for (const w of plain.split(/\s+/).slice(0, words)) { + const next = out ? `${out}-${w}` : w; + if (next.length > max) break; + out = next; + } + return out || plain.slice(0, max).replace(/\s+/g, "-"); +} + +const MON = { jan: 1, feb: 2, mar: 3, apr: 4, may: 5, jun: 6, jul: 7, aug: 8, sep: 9, oct: 10, nov: 11, dec: 12 }; +const ymd = (y, m, d) => `${y}-${String(m).padStart(2, "0")}-${String(d).padStart(2, "0")}`; + +/** + * The day a clip was said, as YYYY-MM-DD: its `date`, else the on-screen + * date ("12 Aug 2026"), else the upload date; null when it carries none. + * + * @param {Record<string, any>} entry + */ +export function exportDate(entry) { + const d = typeof entry?.date === "string" ? entry.date.trim() : ""; + const iso = /^(\d{4})-(\d{2})-(\d{2})/.exec(d); + if (iso) return `${iso[1]}-${iso[2]}-${iso[3]}`; + for (const t of [d, typeof entry?.onscreen?.title === "string" ? entry.onscreen.title.trim() : ""]) { + const m = /^(\d{1,2})\s+([A-Za-z]{3})[a-z]*\.?\s+(\d{4})$/.exec(t); + if (m && MON[m[2].toLowerCase()]) return ymd(m[3], MON[m[2].toLowerCase()], m[1]); + } + const u = String(entry?.uploadDate ?? ""); + return /^\d{8}$/.test(u) ? ymd(u.slice(0, 4), u.slice(4, 6), u.slice(6, 8)) : null; +} + +/** + * The export's file name: `<clipId>[-raw]-<YYYY-MM-DD>-<slug>.mp4`, the + * shape of the hand-made ones (`ss1-raw-2026-07-22-side-scrollers-full-exchange.mp4`). + * The slug is the quote's first words, else the title's, else the video id; + * the date the clip's, else `today` (YYYY-MM-DD). + * + * @param {Record<string, any>} entry + * @param {{ kind?: "cut" | "raw", today?: string }} [opts] + */ +export function exportName(entry, { kind = "cut", today = new Date().toISOString().slice(0, 10) } = {}) { + const id = exportSlug(String(entry?.id ?? "clip"), { words: 8, max: 40 }) || "clip"; + const date = exportDate(entry) ?? today; + const slug = exportSlug(entry?.quote) || exportSlug(entry?.onscreen?.title) || exportSlug(entry?.title) || exportSlug(entry?.video); + return `${[id, kind === "raw" ? "raw" : null, date, slug || null].filter(Boolean).join("-")}.mp4`; +} + +/** + * What one export cuts, in SOURCE seconds -- the arithmetic, no I/O. + * + * @typedef {{ + * kind: "cut" | "raw", + * file: string, fetchStart: number, duration?: number | null, hasVideo?: boolean, + * from: number, to: number, + * gaps: Array<{ from: number, to: number }>, + * mute: number | null, soundFrom: number | null, + * audio: null | { offset?: number, gain?: number, fadeIn?: number, fadeOut?: number }, + * gainDb: number | null, + * fps: number, + * edges: "render" | "manifest" | "window", + * notes: string[], + * }} ExportPlan + */ + +/** + * The plan for one clip, from what the caller resolved: the entry and its + * render block, the source on disk (`{path, fetchStart}`, the clock aligned), + * its probed duration and picture, and -- for a cut -- the render's cut row + * (cutPoints.mjs; null or an errored row falls back to the manifest's edges). + * + * @param {{ entry: Record<string, any>, render?: Record<string, any>, source: { path: string, fetchStart: number }, + * media?: { duration?: number | null, hasVideo?: boolean }, row?: Record<string, any> | null, kind?: "cut" | "raw" }} o + * @returns {ExportPlan} + */ +export function planExport({ entry, render = {}, source, media = {}, row = null, kind = "cut" }) { + const fps = fin(render.fps) && render.fps > 0 ? render.fps : 30; + const fileFrom = source.fetchStart; + const fileTo = fin(media.duration) ? source.fetchStart + /** @type {number} */ (media.duration) : Infinity; + const notes = []; + const base = { + kind, file: source.path, fetchStart: source.fetchStart, duration: media.duration ?? null, + hasVideo: media.hasVideo !== false, fps, notes, + }; + if (kind === "raw") { + const pad = fin(render.fetchPad) ? render.fetchPad : 3; + const from = Math.max(fileFrom, Math.max(0, entry.start - pad)); + const to = Math.min(fileTo, entry.end + pad); + return { ...base, from, to, gaps: [], mute: null, soundFrom: null, audio: null, gainDb: null, edges: "window" }; + } + let from; + let to; + let gaps; + let edges; + if (row && !row.missing && !row.error && fin(row.cutStart) && fin(row.cutEnd)) { + from = row.cutStart; + to = row.cutEnd; + // Room's muted picture at an edge is nothing heard: a clean clip leaves it off. + if (Array.isArray(row.sound) && fin(row.sound[0]) && fin(row.sound[1])) { + from = Math.max(from, row.sound[0]); + to = Math.min(to, row.sound[1]); + } + gaps = gapsWithin(Array.isArray(row.gaps) ? row.gaps : [], from, to); + edges = "render"; + if (row.montage) notes.push("a montage cuts this clip to its phrase in the render; exported as a plain cut"); + } else { + const pw = playEdges(entry, render); + from = pw.from; + to = pw.to; + gaps = gapsWithin(gapsOf(entry), from, to); + edges = "manifest"; + notes.push(row?.error ? `the render's edges could not be measured (${row.error}): the manifest's edges` : "the manifest's edges (the render's were not measured)"); + } + if (from < fileFrom - 0.02) { + notes.push(`the cut starts ${(fileFrom - from).toFixed(2)} s before the cached window: from its first frame`); + from = fileFrom; + } + if (to > fileTo + 0.02) { + notes.push(`the cut ends ${(to - fileTo).toFixed(2)} s past the cached window: to its last frame`); + to = fileTo; + } + // The gaps on the export's own frame grid (the build's rule), back in source seconds. + const local = gapsOnSegment(gaps, from, to - from, fps); + gaps = local.map((g) => ({ from: Number((from + g.from).toFixed(6)), to: Number((from + g.to).toFixed(6)) })); + const seconds = gappedLength(from, to, gaps); + const on = soundOnSegment(entry, render, from, seconds, gaps.length ? gaps : null); + const mute = on.mute != null && on.mute < seconds ? on.mute : null; + const soundFrom = on.soundFrom != null ? on.soundFrom : null; + if (entry?.blur && typeof entry.blur === "object" && render.blur !== "off") notes.push("exported unblurred: the render's blur is not applied"); + const gainDb = fin(row?.gainDb) ? row.gainDb : null; + return { ...base, from, to, gaps, mute, soundFrom, audio: clipAudioOf(entry), gainDb, edges }; +} + +/** The seconds an export plays: its span less its gaps. */ +export const planSeconds = (plan) => gappedLength(plan.from, plan.to, plan.gaps); + +/** + * The ffmpeg arguments for a plan, writing `out`. The picture is cut on the + * input (`-ss` / `-to`, the build's cutArgs), so the re-encode starts on the + * asked-for frame; the gaps come out with the build's own filter; the sound + * is laid on its clock first (AUDIO_ON_CLOCK) and read again at the shifted + * window for an `audio.offset`. + * + * @param {ExportPlan} plan + * @param {string} out + * @param {{ crf?: number, preset?: string, audioBitrate?: string }} [opts] + * @returns {string[]} + */ +export function exportArgs(plan, out, { crf = 18, preset = "medium", audioBitrate = "192k" } = {}) { + const a = Math.max(0, plan.from - plan.fetchStart); + const b = Math.max(a, plan.to - plan.fetchStart); + const seconds = b - a; + const args = ["-nostdin", "-hide_banner", "-v", "error", "-y", "-ss", n3(a), "-to", n3(b), "-i", plan.file]; + const shifted = plan.kind === "cut" ? offsetWindow(plan.audio, a, b) : null; + let ain = "[0:a]"; + if (shifted) { + if (shifted.from < 0) args.push("-itsoffset", n3(-shifted.from)); + args.push("-ss", n3(Math.max(0, shifted.from)), "-to", n3(shifted.to), "-i", plan.file); + ain = "[1:a]"; + } + const parts = [`${ain}${AUDIO_ON_CLOCK}[aclk]`]; + const local = plan.gaps.map((g) => ({ from: g.from - plan.from, to: g.to - plan.from })); + const g = gapFilterParts({ gaps: local, seconds, vIn: plan.hasVideo === false ? null : "[0:v]", aIn: "[aclk]" }); + parts.push(...g.parts); + const kept = planSeconds(plan); + const af = []; + if (plan.soundFrom != null) af.push(`afade=t=in:st=${n3(plan.soundFrom)}:d=${n3(MUTE_FADE)}`); + // The mute's fade ENDS at the mark (mute.mjs): silent from it on. + if (plan.mute != null) af.push(`afade=t=out:st=${n3(Math.max(0, plan.mute - MUTE_FADE))}:d=${n3(MUTE_FADE)}`); + if (plan.gainDb != null && plan.gainDb !== 0) af.push(`volume=${n3(plan.gainDb)}dB`); + af.push(...clipAudioFilters(plan.kind === "cut" ? plan.audio : null, kept)); + parts.push(`${g.a}${af.length ? af.join(",") : "anull"}[aout]`); + args.push("-filter_complex", parts.join(";")); + if (g.v) args.push("-map", g.v === "[0:v]" ? "0:v:0" : g.v); + args.push("-map", "[aout]"); + if (g.v) args.push("-c:v", "libx264", "-preset", preset, "-crf", String(crf), "-pix_fmt", "yuv420p"); + args.push("-c:a", "aac", "-b:a", audioBitrate, "-movflags", "+faststart", "-map_metadata", "-1", "-map_chapters", "-1", "-sn", "-dn"); + args.push(out); + return args; +} + +/** The plan in one line, for the CLI and the route's answer. */ +export function planSummary(plan) { + const parts = [`${n3(plan.from)}–${n3(plan.to)} s`]; + if (plan.gaps.length) parts.push(`${plan.gaps.length} gap${plan.gaps.length === 1 ? "" : "s"} out`); + if (plan.mute != null) parts.push(`muted from ${n3(plan.mute)} s`); + if (plan.soundFrom != null) parts.push(`sound from ${n3(plan.soundFrom)} s`); + parts.push(`${n3(planSeconds(plan))} s`); + parts.push(plan.kind === "raw" ? "the whole window" : plan.edges === "render" ? "the render's edges" : "the manifest's edges"); + return parts.join(" · "); +} + +/** + * Run ffmpeg; resolves when it exits 0, rejects with its last lines of + * stderr otherwise. + */ +function runFfmpeg(bin, args, { signal } = {}) { + return new Promise((resolve, reject) => { + const child = spawn(bin, args, { stdio: ["ignore", "ignore", "pipe"], ...(signal ? { signal } : {}) }); + let err = ""; + child.stderr.on("data", (d) => { + err = (err + d.toString()).slice(-4000); + }); + child.on("error", (e) => reject(e?.code === "ENOENT" ? new Error(`${bin} is not installed`) : e)); + child.on("close", (code, sig) => { + if (code === 0) resolve(undefined); + else reject(new Error(`ffmpeg ${sig ? `was stopped (${sig})` : `exited ${code}`}${err.trim() ? `: ${err.trim().split("\n").slice(-3).join(" ")}` : ""}`)); + }); + }); +} + +/** An export refused for a reason the caller should show as it is (no window on disk, no such clip). */ +export class ExportRefused extends Error { + /** @param {string} message @param {number} [status] */ + constructor(message, status = 409) { + super(message); + this.status = status; + } +} + +/** Exports being made in this process, by output path: a second ask waits for the first. */ +const inflight = new Map(); + +/** + * Export one clip of a project's cut (or of a take) into `<project>/exports/`. + * + * @param {{ id: string, dir: string }} project + * @param {string} clipId + * @param {{ take?: string | null, kind?: "cut" | "raw", ffmpeg?: string, today?: string }} [opts] + * @returns {Promise<{ project: string, clip: string, take: string | null, kind: "cut" | "raw", name: string, rel: string, + * abs: string, size: number, mtimeMs: number, seconds: number, summary: string, notes: string[], plan: ExportPlan }>} + */ +export async function exportClip(project, clipId, { take = null, kind = "cut", ffmpeg, today } = {}) { + if (!EXPORT_KINDS.includes(kind)) throw new ExportRefused(`an export is one of ${EXPORT_KINDS.join(", ")}`, 400); + const { clipSourceOf, cutPointsFor } = await import("./cutPoints.mjs"); + const { FFMPEG_BIN, probeMedia } = await import("umtool-report-to-video/build-video"); + const got = await clipSourceOf(project, clipId, { take }); + if (!got.entry) throw new ExportRefused(`no clip ${clipId} in ${take ? `take ${take} of ` : ""}${project.id}`, 404); + if (!got.source) { + throw new ExportRefused( + `${clipId}: its window is not on disk — fetch it first (the Cut tab's Fetch, or \`umtool fetch ${project.id}\`)`, + 409, + ); + } + const media = await probeMedia(got.source.path).catch(() => ({ hasVideo: true, duration: null })); + let row = null; + if (kind === "cut") { + try { + row = (await cutPointsFor(project, { take, clips: [clipId] })).clips?.[0] ?? null; + } catch (e) { + row = { error: e instanceof Error ? e.message : String(e) }; + } + } + const plan = planExport({ entry: got.entry, render: got.render, source: got.source, media, row, kind }); + if (!(planSeconds(plan) > 0.05)) throw new ExportRefused(`${clipId}: nothing to export (${planSummary(plan)})`, 422); + const name = exportName(got.entry, { kind, ...(today ? { today } : {}) }); + const dir = path.join(/* turbopackIgnore: true */ project.dir, EXPORTS_DIR); + const abs = path.join(/* turbopackIgnore: true */ dir, name); + const run = inflight.get(abs) ?? (async () => { + await mkdir(/* turbopackIgnore: true */ dir, { recursive: true }); + const tmp = path.join(/* turbopackIgnore: true */ dir, `.${name}.${process.pid}.part.mp4`); + try { + await runFfmpeg(ffmpeg ?? FFMPEG_BIN, exportArgs(plan, tmp)); + await rename(/* turbopackIgnore: true */ tmp, abs); + } catch (e) { + await rm(/* turbopackIgnore: true */ tmp, { force: true }).catch(() => {}); + throw e; + } + })(); + if (!inflight.has(abs)) { + inflight.set(abs, run); + run.then(() => inflight.delete(abs), () => inflight.delete(abs)); + } + await run; + const st = await stat(/* turbopackIgnore: true */ abs); + return { + project: project.id, clip: clipId, take, kind, name, rel: path.posix.join(EXPORTS_DIR, name), abs, + size: st.size, mtimeMs: Math.round(st.mtimeMs), seconds: Number(planSeconds(plan).toFixed(3)), + summary: planSummary(plan), notes: plan.notes, plan, + }; +} + +/** + * The exports a project holds, newest first: `{name, size, mtimeMs}`. + * + * @param {string} projectDir + */ +export async function listExports(projectDir) { + const { readdir } = await import("node:fs/promises"); + const dir = path.join(/* turbopackIgnore: true */ projectDir, EXPORTS_DIR); + const names = await readdir(/* turbopackIgnore: true */ dir).catch(() => []); + const out = []; + for (const name of names) { + if (!EXPORT_NAME_RE.test(name)) continue; + const st = await stat(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ dir, name)).catch(() => null); + if (st?.isFile()) out.push({ name, size: st.size, mtimeMs: Math.round(st.mtimeMs) }); + } + return out.sort((x, y) => y.mtimeMs - x.mtimeMs); +} + +/** + * An export's absolute path, from a name a request carried: one plain mp4 + * name under the project's exports/, or null. + * + * @param {string} projectDir + * @param {unknown} name + */ +export function exportFileOf(projectDir, name) { + const n = String(name ?? ""); + if (!EXPORT_NAME_RE.test(n) || n.includes("..")) return null; + return path.join(/* turbopackIgnore: true */ projectDir, EXPORTS_DIR, n); +} diff --git a/umtool/lib/report/clipExport.test.mjs b/umtool/lib/report/clipExport.test.mjs @@ -0,0 +1,266 @@ +// Export one clip (clipExport.mjs): the file name from the clip, the plan -- +// which seconds, which gaps, where the sound is silenced -- from the render's +// cut or the manifest's edges, the ffmpeg arguments that cut it, and one real +// export of a synthetic window measured back (needs ffmpeg). Open folder's +// pure half (openFolder.mjs): who may ask, and what it would run. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, readdirSync, writeFileSync } from "node:fs"; +import { rm } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; + +const CORPUS = mkdtempSync(path.join(os.tmpdir(), "clipexport-corpus-")); +const CACHE = mkdtempSync(path.join(os.tmpdir(), "clipexport-cache-")); +process.env.CHANNELS_DIR = CORPUS; +process.env.UMTOOL_CACHE_DIR = CACHE; + +const { + exportArgs, exportClip, exportDate, exportFileOf, exportName, exportSlug, listExports, planExport, planSeconds, planSummary, +} = await import("./clipExport.mjs"); +const { cannotOpen, hostName, isLoopbackHost, localRequest, openFolder, openersFor } = await import("./openFolder.mjs"); + +const roots = []; +test.after(async () => { + for (const r of [CORPUS, CACHE, ...roots]) await rm(r, { recursive: true, force: true }); +}); + +const near = (a, b, what, tol = 1e-6) => assert.ok(Math.abs(a - b) <= tol, `${what}: ${a} vs ${b}`); + +// ---- names ------------------------------------------------------------------ + +test("the slug: the first words, lower case, the bleeps and ASR notes left out", () => { + assert.equal( + exportSlug("So, actual trans people, I've got your back every day, all day. Like Senko, [ __ ] bye."), + "so-actual-trans-people-ive-got", + ); + assert.equal(exportSlug("[ __ ] deal with it [ASR; likely 'time']"), "deal-with-it"); + assert.equal(exportSlug("Café crème — très bien"), "cafe-creme-tres-bien"); + assert.equal(exportSlug(""), ""); + assert.equal(exportSlug(undefined), ""); + assert.ok(exportSlug("a".repeat(30) + " " + "b".repeat(30)).length <= 48); +}); + +test("the date: the clip's own, else the on-screen date, else the upload date", () => { + assert.equal(exportDate({ date: "2026-08-12" }), "2026-08-12"); + assert.equal(exportDate({ date: "12 Aug 2026" }), "2026-08-12"); + assert.equal(exportDate({ onscreen: { title: "2 Sept 2025" } }), "2025-09-02"); + assert.equal(exportDate({ uploadDate: "20240102" }), "2024-01-02"); + assert.equal(exportDate({}), null); +}); + +test("the name: <clip>[-raw]-<date>-<slug>.mp4, the shape of the hand-made exports", () => { + const e = { id: "tr3", date: "2026-08-12", quote: "Deal with it, autogynephiliac [ __ ] okay then bye", video: "sx5" }; + assert.equal(exportName(e), "tr3-2026-08-12-deal-with-it-autogynephiliac-okay-then.mp4"); + assert.equal(exportName(e, { kind: "raw" }), "tr3-raw-2026-08-12-deal-with-it-autogynephiliac-okay-then.mp4"); + // No date: today's; no quote: the title; neither: the video id. + assert.equal(exportName({ id: "c1", title: "A Stream", video: "v" }, { today: "2026-10-31" }), "c1-2026-10-31-a-stream.mp4"); + assert.equal(exportName({ id: "c1", video: "AbC_d" }, { today: "2026-10-31" }), "c1-2026-10-31-abc-d.mp4"); + // A clip id is made safe, never a path. + assert.match(exportName({ id: "../x y", video: "v" }, { today: "2026-10-31" }), /^x-y-2026-10-31-v\.mp4$/); +}); + +test("an export's file: one plain mp4 name under exports/, nothing else", () => { + assert.equal(exportFileOf("/p", "c1-2026-01-01-x.mp4"), path.join("/p", "exports", "c1-2026-01-01-x.mp4")); + for (const bad of ["../x.mp4", "a/b.mp4", "x.mov", ".hidden.mp4", "", null, "x..mp4"]) { + assert.equal(exportFileOf("/p", bad), null, String(bad)); + } +}); + +// ---- the plan ----------------------------------------------------------------- + +const SRC = { path: "/w/vid_100.00-140.00.mp4", fetchStart: 100 }; +const ENTRY = { type: "clip", id: "c1", video: "vid", start: 103, end: 137, cutStart: 110, cutEnd: 130, quote: "hello there" }; + +test("a cut with no render row: the manifest's play window (the lead-in before the cut), its gaps", () => { + const entry = { ...ENTRY, gaps: [{ from: 115, to: 117 }, { from: 120, to: 121.5 }] }; + const p = planExport({ entry, render: { fps: 30 }, source: SRC, media: { duration: 40, hasVideo: true } }); + assert.equal(p.edges, "manifest"); + near(p.from, 109.6, "from: cutStart less the 0.4 s lead-in"); + near(p.to, 130, "to"); + assert.deepEqual(p.gaps, [{ from: 115, to: 117 }, { from: 120, to: 121.5 }]); + near(planSeconds(p), 20.4 - 3.5, "kept seconds"); + assert.equal(p.mute, null); + assert.ok(p.notes.some((n) => /manifest/.test(n))); +}); + +test("a cut with the render's row: its snapped edges, room's muted picture left off, its gain", () => { + const row = { id: "c1", cutStart: 109.2, cutEnd: 131.0, sound: [109.2, 130.4], gaps: [{ from: 115, to: 117 }], gainDb: -2.5 }; + const p = planExport({ entry: { ...ENTRY, gaps: [{ from: 115, to: 117 }] }, render: { fps: 30 }, source: SRC, media: { duration: 40 }, row }); + assert.equal(p.edges, "render"); + near(p.from, 109.2, "from"); + near(p.to, 130.4, "to: where the sound stops, not room's tail"); + assert.deepEqual(p.gaps, [{ from: 115, to: 117 }]); + assert.equal(p.gainDb, -2.5); + assert.deepEqual(p.notes, []); +}); + +test("the mute mark: on the export's own clock, after the gaps before it", () => { + const entry = { ...ENTRY, gaps: [{ from: 115, to: 117 }], muteFrom: 125 }; + const p = planExport({ entry, render: { fps: 30 }, source: SRC, media: { duration: 40 } }); + // 125 − 109.6 − 2 s of gap. + near(p.mute, 13.4, "mute", 1e-3); +}); + +test("a cut reaching past the cached window starts at its first frame, and says so", () => { + const p = planExport({ entry: { ...ENTRY, start: 101, cutStart: 101.2 }, render: {}, source: { path: "/w/x.mp4", fetchStart: 102 }, media: { duration: 30 } }); + near(p.from, 102, "from"); + near(p.to, 130, "to"); + assert.ok(p.notes.some((n) => /before the cached window/.test(n))); +}); + +test("raw: the fetched window -- the clip and the fetch pad, clamped to the file -- with nothing applied", () => { + const entry = { ...ENTRY, gaps: [{ from: 115, to: 117 }], muteFrom: 125, audio: { gain: 3 } }; + const p = planExport({ entry, render: { fetchPad: 3 }, source: SRC, media: { duration: 36 }, kind: "raw" }); + assert.equal(p.kind, "raw"); + near(p.from, 100, "from"); + near(p.to, 136, "to: the file ends before the pad"); + assert.deepEqual(p.gaps, []); + assert.equal(p.mute, null); + assert.equal(p.audio, null); + assert.match(planSummary(p), /the whole window/); +}); + +// ---- the arguments -------------------------------------------------------------- + +test("the arguments: cut on the input, the gaps out with the build's filter, x264 crf 18, aac 192k, faststart", () => { + const entry = { ...ENTRY, gaps: [{ from: 115, to: 117 }], muteFrom: 125 }; + const p = planExport({ entry, render: { fps: 30 }, source: SRC, media: { duration: 40 } }); + const a = exportArgs(p, "/out/x.mp4"); + const at = (flag) => a[a.indexOf(flag) + 1]; + assert.equal(at("-ss"), "9.6"); + assert.equal(at("-to"), "30"); + assert.equal(at("-i"), SRC.path); + const fc = at("-filter_complex"); + assert.match(fc, /\[0:a\]aresample=async=1/); + assert.match(fc, /split=2/); + assert.match(fc, /trim=start=0:end=5.4/); + assert.match(fc, /trim=start=7.4:end=20.4/); + assert.match(fc, /concat=n=2:v=1:a=0\[gv\]/); + assert.match(fc, /afade=t=out:st=13.36:d=0.04\[aout\]/, "silent from the mute mark, the fade ending on it"); + assert.deepEqual(a.slice(a.indexOf("-map"), a.indexOf("-map") + 4), ["-map", "[gv]", "-map", "[aout]"]); + assert.equal(at("-crf"), "18"); + assert.equal(at("-c:v"), "libx264"); + assert.equal(at("-b:a"), "192k"); + assert.equal(at("-movflags"), "+faststart"); + assert.equal(a.at(-1), "/out/x.mp4"); +}); + +test("no gaps: the picture mapped straight through; an audio offset reads the sound again, shifted", () => { + const p = planExport({ entry: { ...ENTRY, audio: { offset: 200, gain: -3 } }, render: {}, source: SRC, media: { duration: 40 } }); + const a = exportArgs(p, "/o.mp4"); + assert.deepEqual(a.filter((x) => x === "-i").length, 2, "a second input for the shifted sound"); + const second = a.lastIndexOf("-ss"); + assert.equal(a[second + 1], "9.4", "the sound read 0.2 s earlier: it plays 0.2 s later"); + const fc = a[a.indexOf("-filter_complex") + 1]; + assert.match(fc, /^\[1:a\]aresample/); + assert.match(fc, /volume=-3dB/); + assert.ok(a.includes("0:v:0")); +}); + +test("a source with no picture: sound only", () => { + const p = planExport({ entry: ENTRY, render: {}, source: SRC, media: { duration: 40, hasVideo: false } }); + const a = exportArgs(p, "/o.mp4"); + assert.ok(!a.includes("libx264")); + assert.ok(!a.includes("0:v:0")); +}); + +// ---- one real export ------------------------------------------------------------ + +const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0); +const probeDuration = (file) => + Number(spawnSync("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", file]).stdout.toString().trim()); + +test("export a clip: the kept seconds land in exports/ under the clip's name; raw is the whole window", { skip: !have && "needs ffmpeg" }, async () => { + const root = mkdtempSync(path.join(os.tmpdir(), "clipexport-")); + roots.push(root); + mkdirSync(path.join(root, "out", "clips-raw"), { recursive: true }); + const raw = path.join(root, "out", "clips-raw", "vid1_0.00-12.00.mp4"); + const r = spawnSync("ffmpeg", [ + "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=s=320x180:r=30:d=12", + "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=12", + "-map", "0:v", "-map", "1:a", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", raw, + ]); + assert.equal(r.status, 0, String(r.stderr)); + writeFileSync(path.join(root, "video.manifest.json"), JSON.stringify({ + slug: "exp", title: "Export", + provenance: { channelSlug: "synth", channelsDir: CORPUS }, + render: { width: 320, height: 180, fps: 30, fetchPad: 1, transition: 0 }, + timeline: [ + { type: "clip", id: "c1", channel: "synth", video: "vid1", start: 2, end: 9, date: "2026-08-12", quote: "Deal with it", + gaps: [{ from: 4, to: 5.5 }] }, + ], + })); + const project = { id: "exp", dir: root }; + const cut = await exportClip(project, "c1", { kind: "cut" }); + assert.equal(cut.name, "c1-2026-08-12-deal-with-it.mp4"); + assert.equal(cut.rel, "exports/c1-2026-08-12-deal-with-it.mp4"); + near(probeDuration(cut.abs), cut.seconds, "the file plays the kept seconds", 0.12); + assert.ok(cut.seconds < 9 - 2, "the gap is out"); + const rawExp = await exportClip(project, "c1", { kind: "raw" }); + assert.equal(rawExp.name, "c1-raw-2026-08-12-deal-with-it.mp4"); + near(probeDuration(rawExp.abs), 9, "1 s pad either side of 2–9 s, no gap", 0.12); + const listed = await listExports(root); + assert.deepEqual(listed.map((x) => x.name).sort(), [cut.name, rawExp.name].sort()); + assert.deepEqual(readdirSync(path.join(root, "exports")).filter((n) => n.startsWith(".")), [], "no part file left"); + await assert.rejects(exportClip(project, "nope"), /no clip nope/); +}); + +test("export a clip whose window is not on disk: refused, fetch it first", async () => { + const root = mkdtempSync(path.join(os.tmpdir(), "clipexport-")); + roots.push(root); + writeFileSync(path.join(root, "video.manifest.json"), JSON.stringify({ + slug: "exp2", provenance: { channelSlug: "synth", channelsDir: CORPUS }, render: { fps: 30 }, + timeline: [{ type: "clip", id: "c9", channel: "synth", video: "nothere", start: 2, end: 9 }], + })); + await assert.rejects(exportClip({ id: "exp2", dir: root }, "c9"), (e) => e.status === 409 && /fetch it first/.test(e.message)); +}); + +// ---- open folder ---------------------------------------------------------------- + +test("who may ask to open a folder: this machine, by the headers a browser sends", () => { + const h = (o) => ({ get: (k) => o[k] ?? null }); + assert.ok(localRequest(h({ host: "localhost:3050" })).ok); + assert.ok(localRequest(h({ host: "127.0.0.1:3050", origin: "http://127.0.0.1:3050" })).ok); + assert.ok(localRequest(h({ host: "[::1]:3050" })).ok); + assert.equal(localRequest(h({ host: "192.168.1.20:3050" })).ok, false); + assert.equal(localRequest(h({ host: "localhost:3050", "x-forwarded-for": "10.0.0.5" })).ok, false); + assert.equal(localRequest(h({ host: "localhost:3050", origin: "http://phone.lan:3050" })).ok, false); + assert.equal(hostName("[::1]:3050"), "::1"); + assert.ok(isLoopbackHost("127.0.0.2")); + assert.ok(!isLoopbackHost("example.com")); +}); + +test("what would open it: the file manager's ShowItems then xdg-open on Linux, Finder on macOS, nothing elsewhere", () => { + const linux = openersFor({ dir: "/p/exports", file: "/p/exports/a b.mp4", platform: "linux" }); + assert.deepEqual(linux.map((o) => o.cmd), ["dbus-send", "xdg-open"]); + assert.ok(linux[0].args.includes("array:string:file:///p/exports/a%20b.mp4")); + assert.deepEqual(linux[1].args, ["/p/exports"]); + assert.deepEqual(openersFor({ dir: "/p/exports", platform: "linux" }).map((o) => o.cmd), ["xdg-open"]); + assert.deepEqual(openersFor({ dir: "/d", file: "/d/f.mp4", platform: "darwin" }).map((o) => o.args), [["-R", "/d/f.mp4"], ["/d"]]); + assert.deepEqual(openersFor({ dir: "/d", platform: "win32" }), []); + assert.match(cannotOpen({ platform: "linux", container: true }), /container/); + assert.match(cannotOpen({ platform: "win32", container: false }), /win32/); + assert.equal(cannotOpen({ platform: "linux", container: false }), null); +}); + +test("open folder: the first opener that answers; every one failing is the reason, never a throw", async () => { + const saved = process.env.E2E_UMTOOL_OPEN_FOLDER_LOG; + delete process.env.E2E_UMTOOL_OPEN_FOLDER_LOG; + try { + const asked = []; + const ok = await openFolder({ dir: "/d", file: "/d/f.mp4", platform: "linux", container: false, run: async (op) => (asked.push(op.cmd), { code: op.cmd === "dbus-send" ? 1 : 0 }) }); + assert.deepEqual(ok, { ok: true, how: "xdg-open", selected: false }); + assert.deepEqual(asked, ["dbus-send", "xdg-open"]); + const no = await openFolder({ dir: "/d", platform: "linux", container: false, run: async () => ({ code: null, error: "xdg-open is not installed" }) }); + assert.equal(no.ok, false); + assert.match(no.error, /xdg-open is not installed/); + const docker = await openFolder({ dir: "/d", platform: "linux", container: true, run: async () => assert.fail("must not run") }); + assert.match(docker.error, /container/); + } finally { + if (saved !== undefined) process.env.E2E_UMTOOL_OPEN_FOLDER_LOG = saved; + } +}); diff --git a/umtool/lib/report/cutPoints.mjs b/umtool/lib/report/cutPoints.mjs @@ -178,22 +178,58 @@ export async function cutPointsFor(project, { take = null, clips = null, concurr }; } -/** One clip's render cut (cutPointsFor's row). */ -async function clipCutPoints(entry, ctx) { - const { render, locals, localMedia, montage, D } = ctx; +/** + * A clip's source on disk as the build would cut it: the file, its key, the + * source second its first frame plays (`fetchStart`, the file's clock + * aligned) and the span silence detection measures. null: nothing on disk. + */ +async function diskSourceOf(entry, ctx) { + const { render, locals, localMedia } = ctx; let src = null; for (const local of locals) { src = await onDiskClipSource(entry, null, render, local, { localMedia }); if (src) break; } - if (!src) return { id: entry.id, missing: true }; + if (!src) return null; const fk = await fileKey(src.path); - if (!fk) return { id: entry.id, missing: true }; + if (!fk) return null; const { log: _log, ...disk } = src; // The file's clock (a late-starting picture moves fetchStart), once per file. const offset = await cached("offset", fk, async () => (await alignedClipSource(disk)).startOffset ?? 0); const fetchStart = disk.fetchStart + offset; const scan = disk.scan ? { from: Math.max(0, disk.scan.from - offset), to: disk.scan.to - offset } : null; + return { path: src.path, fk, fetchStart, scan }; +} + +/** + * One clip of the cut (or a take) and the file the build would cut it from + * -- the export of one clip (lib/report/clipExport.mjs) cuts from exactly + * this. `source` is null when nothing on disk holds it; `entry` null when the + * cut has no such clip. + * + * @param {{ id: string, dir: string }} project + * @param {string} clipId + * @param {{ take?: string | null }} [opts] + */ +export async function clipSourceOf(project, clipId, { take = null } = {}) { + const ctx = await cutContext(project, take); + const entry = (ctx.selected.timeline ?? []).find((e) => e && e.type === "clip" && e.id === clipId) ?? null; + const disk = entry ? await diskSourceOf(entry, ctx) : null; + return { + entry, + render: ctx.render, + provenance: ctx.provenance, + source: disk ? { path: disk.path, fetchStart: disk.fetchStart } : null, + }; +} + +/** One clip's render cut (cutPointsFor's row). */ +async function clipCutPoints(entry, ctx) { + const { render, montage, D } = ctx; + const disk = await diskSourceOf(entry, ctx); + if (!disk) return { id: entry.id, missing: true }; + const src = { path: disk.path }; + const { fk, fetchStart, scan } = disk; const k = snapKnobs(render); const sil = await cached( "silences", diff --git a/umtool/lib/report/openFolder.mjs b/umtool/lib/report/openFolder.mjs @@ -0,0 +1,154 @@ +// OPEN A FOLDER IN THE OS FILE MANAGER (the clip export's "Open folder", +// `umtool export … --open`): umtool runs on the operator's own machine, so it +// can ask that machine's desktop to show a folder -- and, where the file +// manager takes it, to select the file in it. +// +// Linux org.freedesktop.FileManager1.ShowItems over the session bus +// (dbus-send: Files, Dolphin, Nemo, Thunar … reveal and select the +// file), else `xdg-open <dir>` +// macOS `open -R <file>` (Finder, selected), else `open <dir>` +// +// REFUSED, with the reason in words: inside a container (there is no desktop +// to open it on), on any other platform, and -- for a request -- from +// anywhere but this machine (the phone has Download for that). The request +// check reads the headers a browser sends (Host, Origin, X-Forwarded-For): +// it keeps a page opened from another device from popping windows on this +// one; it is not an access control, and the route is a writer's +// (refuseCaller) besides. +import { spawn } from "node:child_process"; +import { appendFileSync, existsSync } from "node:fs"; +import { pathToFileURL } from "node:url"; + +const LOOPBACK = new Set(["localhost", "127.0.0.1", "::1", "[::1]", "0:0:0:0:0:0:0:1"]); + +/** Is this host name (no port) this machine's loopback? */ +export function isLoopbackHost(host) { + const h = String(host ?? "").trim().toLowerCase().replace(/^\[|\]$/g, ""); + return LOOPBACK.has(h) || /^127(\.\d{1,3}){3}$/.test(h) || h === "::ffff:127.0.0.1" || h.endsWith(".localhost"); +} + +/** A Host header's name without its port: `localhost:3050` → `localhost`, `[::1]:3050` → `::1`. */ +export function hostName(header) { + const v = String(header ?? "").trim(); + if (v.startsWith("[")) return v.slice(1, v.indexOf("]") > 0 ? v.indexOf("]") : undefined); + return v.split(":")[0]; +} + +/** + * Whether a request came from this machine, by the headers it carries: + * `{ ok: true }` or `{ ok: false, why }`. + * + * @param {{ get(name: string): string | null }} headers + */ +export function localRequest(headers) { + const host = hostName(headers.get("host")); + if (!isLoopbackHost(host)) return { ok: false, why: `this page is open at ${host || "an unknown host"}, not on the machine umtool runs on` }; + const fwd = (headers.get("x-forwarded-for") ?? "").split(",").map((s) => s.trim()).filter(Boolean); + const far = fwd.find((a) => !isLoopbackHost(a)); + if (far) return { ok: false, why: `the request was forwarded from ${far}` }; + const origin = headers.get("origin"); + if (origin && origin !== "null") { + try { + const o = new URL(origin).hostname; + if (!isLoopbackHost(o)) return { ok: false, why: `the request came from a page at ${o}` }; + } catch { + return { ok: false, why: "the request's origin is not a URL" }; + } + } + return { ok: true }; +} + +/** Is this process inside a container (docker, podman)? */ +export function inContainer({ exists = existsSync, env = process.env } = {}) { + return exists("/.dockerenv") || exists("/run/.containerenv") || env.container === "docker" || env.container === "podman"; +} + +/** + * The commands that would show `dir` (and select `file` in it), in the order + * to try them, for a platform. [] where there is none. + * + * @param {{ dir: string, file?: string | null, platform?: string }} o + * @returns {Array<{ cmd: string, args: string[], selects: boolean }>} + */ +export function openersFor({ dir, file = null, platform = process.platform }) { + if (platform === "linux") { + const out = []; + if (file) { + out.push({ + cmd: "dbus-send", + args: [ + "--session", "--print-reply", "--dest=org.freedesktop.FileManager1", "--type=method_call", + "/org/freedesktop/FileManager1", "org.freedesktop.FileManager1.ShowItems", + `array:string:${pathToFileURL(file).href}`, "string:", + ], + selects: true, + }); + } + out.push({ cmd: "xdg-open", args: [dir], selects: false }); + return out; + } + if (platform === "darwin") { + return [...(file ? [{ cmd: "open", args: ["-R", file], selects: true }] : []), { cmd: "open", args: [dir], selects: false }]; + } + return []; +} + +/** Why a folder cannot be opened here, or null when it can be tried. */ +export function cannotOpen({ platform = process.platform, container = inContainer() } = {}) { + // TEST-ONLY: the e2e log stands in for the file manager wherever the suite runs (a container too). + if (process.env.E2E_UMTOOL_OPEN_FOLDER_LOG) return null; + if (container) return "umtool is running in a container: there is no desktop here to open a folder on — use Download"; + if (platform !== "linux" && platform !== "darwin") return `opening a folder is not wired for ${platform} — use Download`; + return null; +} + +/** Run one opener; resolves to its exit code (null for a spawn error). */ +function tryOpen({ cmd, args }, { timeoutMs = 5000 } = {}) { + return new Promise((resolve) => { + let child; + try { + child = spawn(cmd, args, { stdio: "ignore", detached: true }); + } catch { + resolve({ code: null, error: `${cmd} could not be started` }); + return; + } + const timer = setTimeout(() => { + // Still running after the wait: it launched (xdg-open may stay with the app it opened). + child.unref(); + resolve({ code: 0 }); + }, timeoutMs); + child.on("error", (e) => { + clearTimeout(timer); + resolve({ code: null, error: e?.code === "ENOENT" ? `${cmd} is not installed` : String(e?.message ?? e) }); + }); + child.on("exit", (code) => { + clearTimeout(timer); + resolve({ code }); + }); + }); +} + +/** + * Show `dir` in the file manager, selecting `file` where it can. Resolves to + * `{ ok: true, how, selected }` or `{ ok: false, error }`; never throws. + * + * @param {{ dir: string, file?: string | null, platform?: string, container?: boolean, run?: typeof tryOpen }} o + */ +export async function openFolder({ dir, file = null, platform = process.platform, container = inContainer(), run = tryOpen }) { + // TEST-ONLY: E2E_UMTOOL_OPEN_FOLDER_LOG (umtool/playwright.config.ts) records the ask in that file and opens + // nothing -- a spec must never pop a file manager on the machine it runs on. + const log = process.env.E2E_UMTOOL_OPEN_FOLDER_LOG; + if (log) { + appendFileSync(/* turbopackIgnore: true */ log, `${JSON.stringify({ dir, file })}\n`); + return { ok: true, how: "e2e-log", selected: !!file }; + } + const no = cannotOpen({ platform, container }); + if (no) return { ok: false, error: no }; + const tried = []; + for (const op of openersFor({ dir, file, platform })) { + const r = await run(op); + if (r.code === 0) return { ok: true, how: op.cmd, selected: op.selects }; + tried.push(r.error ?? `${op.cmd} exited ${r.code}`); + } + return { ok: false, error: `no file manager answered (${tried.join("; ")}) — use Download` }; +} diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts @@ -38,6 +38,9 @@ import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs"; // E2E_CLIP_FETCH_GAP_MS set below for the whole run: the gap between two // network clip fetches in a build (build-video.mjs), // in place of the real 30–120 s +// E2E_UMTOOL_OPEN_FOLDER_LOG set below on the app server: where the clip +// export's Open folder records what it was asked to +// show, in place of a file manager (lib/report/openFolder.mjs) // The ports are common/lib/ports.mjs's (offset per worktree by // scripts/worktree.mjs), not test-only, and keep their names. const PORT = portFor("UMTOOL_E2E_PORT"); @@ -214,6 +217,8 @@ export default defineConfig({ // the middle of a job and prove that cancelling abandons the rest while // the next run resumes. Read only by bin/cut-from-cache.mjs. `E2E_UMTOOL_CUT_DELAY_MS=2000 ` + + // Open folder (a clip's export) records the ask instead of opening a file manager. + `E2E_UMTOOL_OPEN_FOLDER_LOG=${FIXTURE}/open-folder.jsonl ` + // No background refresh check (R4, lib/inbox/refresh.ts): an Inbox read // would otherwise enumerate every fixture article's corpus and add cards // other specs count. refresh.spec runs the check itself, through its route.