commit d3cc25ac83f401f99601641fcb8c3381a8bac33d
parent 499f265a7e827c326bf88fd4b0445fd50afe0ed8
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 9 Nov 2026 15:47:49 -0500
Merge lane/output-modes: Basic output mode (the footage alone, no chrome), Quick clip, and the share line (operator, 8 Nov: "plan different output presets for umtool (e.g. basic no-chrome vs chrome)")
Redesign L1. render.mode "basic" (resolved last, after preset, manifest, style and take patch) hands the cut to
report-to-video/basic.mjs: Play's own spans, fades, the source's size and fps. A built-in basic preset and
`preset apply --replace`. `umtool clip <ch>/<vid>@<s>-<e> [--snap words]` and POST /api/report/quick-clip make a
basic project, fetch the window through the editor, render, and print the share line (platform link at the moment +
archive moment link). One Rumble folder->embed helper fixes the share line, `links --fix` and `timeline insert`.
The Look panel gains Basic | Deck; Play of a basic cut is bare footage; Copy share line on Play and take cards.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
41 files changed, 2348 insertions(+), 66 deletions(-)
diff --git a/common/lib/report/draft/videoOps.test.ts b/common/lib/report/draft/videoOps.test.ts
@@ -169,7 +169,7 @@ test("the look ops (release 38): look, slide and room through the look's own rul
assert.match(r.applied[1]!.warnings![0]!, /the slide's knobs show once the join style is blur slide/);
assert.deepEqual(
r.refused.map((x) => x.why),
- ["render.transition must be a number of seconds from 0 (a hard cut) to 3", '"chrome" is not a look setting (headerHeight, footerHeight, qr, transition, transitionStyle, loudness, captions, room, slide, blur, intro, format, vertical)'],
+ ["render.transition must be a number of seconds from 0 (a hard cut) to 3", '"chrome" is not a look setting (headerHeight, footerHeight, qr, transition, transitionStyle, loudness, captions, room, slide, blur, intro, format, vertical, mode, basic)'],
);
assert.equal((manifest.render as { transition: number }).transition, 0.4, "the input is not touched");
});
diff --git a/common/lib/report/look.d.mts b/common/lib/report/look.d.mts
@@ -4,7 +4,7 @@
type Manifest = { render?: Record<string, unknown> | null; timeline?: unknown[] } & Record<string, unknown>;
type Render = Record<string, unknown> | null | undefined;
-export type LookKey = "headerHeight" | "footerHeight" | "qr" | "transition" | "transitionStyle" | "loudness" | "captions" | "room" | "slide" | "blur" | "intro" | "format" | "vertical";
+export type LookKey = "headerHeight" | "footerHeight" | "qr" | "transition" | "transitionStyle" | "loudness" | "captions" | "room" | "slide" | "blur" | "intro" | "format" | "vertical" | "mode" | "basic";
export const LOOK_KEYS: readonly LookKey[];
export const BAND_MAX: number;
export const TRANSITION_MAX: number;
@@ -23,6 +23,14 @@ export const RENDER_BLUR_VALUES: readonly ("on" | "off")[];
export function renderBlurOn(render: Render): boolean;
export function validateRenderBlur(manifest: unknown): string[];
+export const RENDER_MODES: readonly ("deck" | "basic")[];
+export const BASIC_FADE_DEFAULTS: Readonly<{ audio: number; video: number }>;
+export const BASIC_FADE_MAX: number;
+export function renderModeOf(render: Render): "deck" | "basic";
+export function basicOn(render: Render): boolean;
+export function basicFadeOf(render: Render): { audio: number; video: number };
+export function validateRenderMode(manifest: unknown): string[];
+
export const ROOM: Readonly<{ minGap: number; maxS: number; fade: number; pad: number; detectDb: number; detectD: number }>;
export const ROOM_EDGES: readonly ("tail" | "head")[];
export const ROOM_BOUNDS: Readonly<{ minGap: readonly [number, number]; maxS: readonly [number, number] }>;
diff --git a/common/lib/report/look.mjs b/common/lib/report/look.mjs
@@ -26,7 +26,7 @@ const q = (v) => JSON.stringify(v);
const round2 = (n) => Number(Number(n).toFixed(2));
/** The render keys the Look panel writes, in its order. */
-export const LOOK_KEYS = Object.freeze(["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room", "slide", "blur", "intro", "format", "vertical"]);
+export const LOOK_KEYS = Object.freeze(["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room", "slide", "blur", "intro", "format", "vertical", "mode", "basic"]);
/** `headerHeight` / `footerHeight`: whole pixels, 0 (off) to this. */
export const BAND_MAX = 240;
@@ -104,6 +104,60 @@ export function validateRenderBlur(manifest) {
}
// ---------------------------------------------------------------------------
+// The output mode (`render.mode`, lane output-modes): "deck" (the default,
+// absent) is every render as it has always been; "basic" is the footage alone
+// -- the clips' played spans spliced, no chrome, deck, intro, QR, rail, cards
+// or brand (report-to-video/basic.mjs). It is a render key like any other, so
+// it resolves where every layer does (preset → manifest → style → take patch,
+// each a merge patch): the mode a reader sees is the one the LAST layer set,
+// and "basic" wins whatever chrome a lower layer lays. `render.basic.fade`
+// says how long the basic cut's fades are (seconds): `audio` at every span's
+// edges (no click at a join), `video` from black at the cut's first frame and
+// to black at its last.
+// ---------------------------------------------------------------------------
+
+/** `render.mode`: "deck" (the default, absent) or "basic". */
+export const RENDER_MODES = Object.freeze(["deck", "basic"]);
+/** `render.basic.fade`'s defaults, seconds. */
+export const BASIC_FADE_DEFAULTS = Object.freeze({ audio: 0.03, video: 0.15 });
+/** The most a basic fade may be, seconds. */
+export const BASIC_FADE_MAX = 3;
+
+/** The mode a render block renders in: "basic" or "deck". */
+export const renderModeOf = (render) => (render?.mode === "basic" ? "basic" : "deck");
+/** Does this render block render the footage alone? */
+export const basicOn = (render) => renderModeOf(render) === "basic";
+
+/** `render.basic.fade` with its defaults: `{ audio, video }` seconds. */
+export function basicFadeOf(render) {
+ const f = isObj(render?.basic) && isObj(render.basic.fade) ? render.basic.fade : {};
+ return {
+ audio: num(f.audio) && f.audio >= 0 ? f.audio : BASIC_FADE_DEFAULTS.audio,
+ video: num(f.video) && f.video >= 0 ? f.video : BASIC_FADE_DEFAULTS.video,
+ };
+}
+
+/** `render.mode` and `render.basic`: absent, or what the basic renderer reads. */
+export function validateRenderMode(manifest) {
+ const errors = [];
+ const r = manifest?.render;
+ const v = r?.mode;
+ if (v !== undefined && v !== null && !RENDER_MODES.includes(v)) errors.push(`render.mode must be "deck" (the default) or "basic" (the footage alone, no chrome), not ${q(v)}`);
+ const b = r?.basic;
+ if (b === undefined || b === null) return errors;
+ if (!isObj(b)) return [...errors, "render.basic must be an object {fade?: {audio?, video?}}"];
+ for (const k of Object.keys(b)) if (k !== "fade") errors.push(`render.basic.${k} is not a key (fade)`);
+ const f = b.fade;
+ if (f === undefined || f === null) return errors;
+ if (!isObj(f)) return [...errors, "render.basic.fade must be an object {audio?, video?} (seconds)"];
+ for (const [k, x] of Object.entries(f)) {
+ if (k !== "audio" && k !== "video") errors.push(`render.basic.fade.${k} is not a key (audio, video)`);
+ else if (!num(x) || x < 0 || x > BASIC_FADE_MAX) errors.push(`render.basic.fade.${k} must be seconds from 0 to ${BASIC_FADE_MAX}, not ${q(x)}`);
+ }
+ return errors;
+}
+
+// ---------------------------------------------------------------------------
// Room at a clip's edges (`render.room`, a clip's `room`) -- report-to-video/
// room.mjs says what it does to the sound and the picture.
// ---------------------------------------------------------------------------
@@ -303,7 +357,7 @@ export function validateLook(manifest) {
// render.blur (the uncensored variant's switch) is part of the look too.
return [
...validateCaptions(manifest), ...validateLoudness(manifest), ...validateVertical(manifest), ...validateRoom(manifest), ...validateRenderBlur(manifest), ...validateIntro(manifest),
- ...validateVerticalFormat(manifest),
+ ...validateVerticalFormat(manifest), ...validateRenderMode(manifest),
];
}
@@ -374,6 +428,15 @@ export function applyLookPatch(manifest, patch) {
// A style name or {style, ground?, sound?, seconds?}; validateIntro (below) says what is wrong.
render.intro = introPatchValue(v);
break;
+ case "mode":
+ // "deck" is the default: written as no key -- unless the cut stands on a
+ // look preset, whose own mode it must then beat (presets.mjs).
+ if (v === "deck") {
+ if (manifest?.preset) render.mode = "deck";
+ else delete render.mode;
+ } else if (v === "basic") render.mode = "basic";
+ else errors.push(`render.mode must be "deck" (the default) or "basic" (the footage alone, no chrome)`);
+ break;
case "format":
// "landscape" is the default: written as no key at all.
if (v === "landscape") delete render.format;
diff --git a/common/lib/report/videoAssistOps.test.ts b/common/lib/report/videoAssistOps.test.ts
@@ -5,7 +5,7 @@ import assert from "node:assert/strict";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
-import { LOOK_KEYS, SLIDE_BOUNDS, applyLookPatch, lookErrors, validateLook, validateTransitionStyle } from "./look.mjs";
+import { LOOK_KEYS, SLIDE_BOUNDS, applyLookPatch, basicFadeOf, lookErrors, renderModeOf, validateLook, validateRenderMode, validateTransitionStyle } from "./look.mjs";
import { ASSIST_OPS_SCHEMA, assistView, checkAssistOps, clipWindow, normalizeAssistOp, secondsNamedIn } from "./videoAssistOps.mjs";
import { COMPOSITION_PARAMS, chromeWithParam, compositionsOn, paramValue, paramValueError } from "./fxParams.mjs";
import { markProposals, proposalsDocOf, proposalsErrors, readAssistProposals, writeAssistProposals } from "./videoAssistProposals.mjs";
@@ -26,7 +26,23 @@ test("the look's rules: one patch function — keys refused, null removes, qr on
assert.deepEqual(bad.errors, validateTransitionStyle({ render: { slide: { blur: 9 } } }));
assert.deepEqual(applyLookPatch(m, { loudness: { target: -40 } }).errors, validateLook({ render: { loudness: { target: -40 } } }));
assert.deepEqual(lookErrors(m), []);
- assert.equal(LOOK_KEYS.length, 13);
+ assert.equal(LOOK_KEYS.length, 15);
+});
+
+test("render.mode and render.basic: deck is the default (no key), basic the footage alone; the fades checked", () => {
+ const m = { render: { transition: 0.4 }, timeline: [] };
+ assert.deepEqual(applyLookPatch(m, { mode: "basic" }).render.mode, "basic");
+ assert.equal(applyLookPatch({ render: { mode: "basic" } }, { mode: "deck" }).render.mode, undefined, "deck is written as no key");
+ assert.equal(applyLookPatch({ preset: "basic", render: {} }, { mode: "deck" }).render.mode, "deck", "over a preset, deck is written so it beats the preset's");
+ assert.match(applyLookPatch(m, { mode: "plain" }).errors[0]!, /render\.mode must be "deck"/);
+ assert.deepEqual(applyLookPatch(m, { basic: { fade: { audio: 0.05 } } }).errors, []);
+ assert.match(applyLookPatch(m, { basic: { fade: { video: 9 } } }).errors.join(), /render\.basic\.fade\.video must be seconds from 0 to 3/);
+ assert.match(applyLookPatch(m, { basic: { blur: 1 } }).errors.join(), /render\.basic\.blur is not a key/);
+ assert.deepEqual(basicFadeOf({}), { audio: 0.03, video: 0.15 });
+ assert.deepEqual(basicFadeOf({ basic: { fade: { video: 0 } } }), { audio: 0.03, video: 0 });
+ assert.equal(renderModeOf({ mode: "basic" }), "basic");
+ assert.equal(renderModeOf({}), "deck");
+ assert.deepEqual(validateRenderMode({ render: { mode: "basic", basic: { fade: { audio: 0.1, video: 0.2 } } } }), []);
});
test("the request table: every request → the model's ops → the diff lines kept and the reasons refused", () => {
diff --git a/common/lib/videoDir-server.mjs b/common/lib/videoDir-server.mjs
@@ -194,6 +194,29 @@ export async function resolveVideoDirId(channelsDir, slug, recordId, opts = {})
}
/**
+ * THE OTHER WAY ROUND: the id the ARCHIVE serves a recording under, from the
+ * directory it lives in on this disk (`resolveVideoDirId`'s inverse, for
+ * Rumble). On a Rumble channel a directory named for the URL slug holds a
+ * record whose id -- its metadata.info.json `id`, the EMBED id the archive
+ * keys by -- is another: that id is returned (a QR, a share line, an inserted
+ * clip's `siteVideo` must name it; 4 and 8 Nov the QR named the folder id).
+ * Every other directory, and a Rumble one whose metadata names itself or
+ * nothing, is its own id. Only a Rumble-shaped id costs a read.
+ * @param {string} channelsDir
+ * @param {string} slug
+ * @param {string} dirId
+ * @param {{ platform?: string | null }} [opts]
+ * @returns {Promise<string>}
+ */
+export async function recordIdOfVideoDir(channelsDir, slug, dirId, opts = {}) {
+ if (!RUMBLE_ID_RE.test(dirId)) return dirId;
+ const platform = opts.platform !== undefined ? opts.platform : await readChannelPlatform(channelsDir, slug);
+ if (platform !== "rumble") return dirId;
+ const id = idOfHead(await readHead(path.join(/* turbopackIgnore: true */ channelsDir, slug, "data", dirId, "metadata.info.json")));
+ return id && RUMBLE_ID_RE.test(id) ? id : dirId;
+}
+
+/**
* The directory a record lives in: `<channelsDir>/<slug>/data/<dir id>`.
* @param {string} channelsDir
* @param {string} slug
diff --git a/common/lib/videoDirId.test.ts b/common/lib/videoDirId.test.ts
@@ -18,7 +18,7 @@ import {
twitchVodDirId,
twitchVodRecordId,
} from "./videoId";
-import { resolveVideoDir, resolveVideoDirId, resolveVideoDirIdSync, resolveVideoDirSync } from "./videoDir-server.mjs";
+import { recordIdOfVideoDir, resolveVideoDir, resolveVideoDirId, resolveVideoDirIdSync, resolveVideoDirSync } from "./videoDir-server.mjs";
const N = "1234567890";
const META = { id: `v${N}`, webpage_url: `https://www.twitch.tv/videos/${N}` };
@@ -133,6 +133,11 @@ test("a Rumble embed id resolves to the URL-slug directory whose metadata names
// The slug id is its own directory; an id nobody names stays as it is.
assert.equal(await resolveVideoDirId(root, "rc", "v7fxp3e"), "v7fxp3e");
assert.equal(await resolveVideoDirId(root, "rc", "v9zzzzz"), "v9zzzzz");
+ // The inverse: the URL-slug directory's record id, the embed id the archive serves (lane output-modes).
+ assert.equal(await recordIdOfVideoDir(root, "rc", "v7fxp3e"), "v7drc5w");
+ assert.equal(await recordIdOfVideoDir(root, "rc", "v9zzzzz"), "v9zzzzz", "no metadata: itself");
+ assert.equal(await recordIdOfVideoDir(root, "rc", "dQw4w9WgXcQ"), "dQw4w9WgXcQ", "not Rumble-shaped: no read");
+ assert.equal(await recordIdOfVideoDir(root, "rc", "v7fxp3e", { platform: "youtube" }), "v7fxp3e", "not a Rumble channel");
// A directory added later is found once data/ changes.
mkdirSync(path.join(data, "v7gwn3w"));
writeFileSync(path.join(data, "v7gwn3w", "metadata.info.json"), JSON.stringify({ id: "v7eqa6e" }));
diff --git a/umtool/app/api/report/quick-clip/route.ts b/umtool/app/api/report/quick-clip/route.ts
@@ -0,0 +1,59 @@
+import path from "node:path";
+import { getJob, jobView, runningJob, startJob } from "@/lib/jobs";
+import { refuseCaller } from "@/lib/report/caller";
+import { UMTOOL_DIR } from "@/lib/report/driver.mjs";
+import { quickClipSpec } from "@/lib/report/quickClip.mjs";
+
+export const dynamic = "force-dynamic";
+
+// QUICK CLIP (lane output-modes; umtool/docs/knobs.md, "Quick clip"): one
+// moment of one recording to a basic-mode mp4 and its share line --
+// `umtool clip <channel>/<video>@<start>-<end> [--snap words] [--title T] [--site <id>]`
+// (lib/report/quickClip.mjs) as ONE job on the app's runner (lib/jobs.ts: one
+// at a time, a log, Stop). The command asks the editor for the window, snaps
+// the edges to the words when asked, and renders through the take maker (the
+// heavy slot); its last NDJSON event is `quick-clip` {project, output, share}.
+//
+// POST { spec: "<channel>/<video>@<start>-<end>", snap?: "words", title?, site? } -> 202 { job }
+// | 400 a spec that is not one | 409 another job is running
+// GET ?job=<id> -> { job, done?: { project, output, share: { platform, archive, text }, snapped? }, error? }
+const headers = { "cache-control": "no-store" };
+const SITE_RE = /^[a-z0-9][a-z0-9._-]*$/i;
+
+export async function POST(request: Request) {
+ const refused = refuseCaller(request, "/api/report/quick-clip");
+ 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 spec = String(body.spec ?? "").trim();
+ if (!quickClipSpec(spec)) {
+ return Response.json({ error: 'spec is <channel>/<video>@<start>-<end> in seconds, the end after the start, its ids neither "." nor starting "-"' }, { status: 400, headers });
+ }
+ const snap = body.snap === undefined || body.snap === null || body.snap === "" ? null : String(body.snap);
+ if (snap !== null && snap !== "words") return Response.json({ error: "snap is words, or nothing" }, { status: 400, headers });
+ const title = typeof body.title === "string" && body.title.trim() ? body.title.trim().slice(0, 120) : null;
+ const site = typeof body.site === "string" && body.site.trim() ? body.site.trim() : null;
+ if (site && !SITE_RE.test(site)) return Response.json({ error: "site is a site's id (transcripts/sites/<id>)" }, { status: 400, headers });
+ const running = runningJob();
+ if (running) return Response.json({ error: `a job is already running (${running.kind}) — make the clip when it is done`, running: jobView(running) }, { status: 409, headers });
+ const argv = [
+ process.execPath, path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs"), "clip", spec,
+ ...(snap ? ["--snap", snap] : []), ...(title ? ["--title", title] : []), ...(site ? ["--site", site] : []), "--progress", "ndjson",
+ ];
+ const job = startJob(`quick clip ${spec}`, [{ cwd: UMTOOL_DIR, env: {}, label: `quick clip ${spec}${snap ? " (snapped to the words)" : ""}`, argv, ndjson: true, timeoutMs: 90 * 60_000 }]);
+ return Response.json({ ok: true, job: jobView(job) }, { status: 202, headers });
+}
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const id = url.searchParams.get("job");
+ const job = id ? getJob(id) : null;
+ if (!job) return Response.json({ error: "no such job" }, { status: 404, headers });
+ const view = jobView(job, Math.max(0, job.log.length - 12));
+ const ev = [...job.events].reverse().find((e) => e.ev === "quick-clip" || e.ev === "quick-clip-failed") as Record<string, unknown> | undefined;
+ if (ev?.ev === "quick-clip") {
+ return Response.json({ job: view, done: { project: ev.project, output: ev.output, share: ev.share, ...(ev.snapped ? { snapped: ev.snapped } : {}) } }, { headers });
+ }
+ const error = ev?.ev === "quick-clip-failed" ? String(ev.error ?? "the quick clip failed") : job.state === "failed" ? (job.error ?? "the quick clip failed") : null;
+ return Response.json({ job: view, ...(error ? { error } : {}) }, { headers });
+}
diff --git a/umtool/app/api/report/render/route.ts b/umtool/app/api/report/render/route.ts
@@ -1,5 +1,6 @@
import { withEditNotes } from "@/lib/report/guard";
-import { LOOK_KEYS, RenderRefused, StaleToken, lookOf, manifestToken, updateRender, updateVariants } from "@/lib/report/manifest.mjs";
+import { LOOK_KEYS, RenderRefused, StaleToken, effectiveManifest, lookOf, manifestToken, updateRender, updateVariants } from "@/lib/report/manifest.mjs";
+import { renderModeOf } from "yt-dlp-transcript-common/lib/report/look.mjs";
import { VARIANTS_DEFAULT, variantsProblems } from "@/lib/report/knobs.mjs";
import { resolveReport } from "@/lib/report/serve.mjs";
import { deckOn } from "umtool-report-to-video/deck";
@@ -17,7 +18,9 @@ export const dynamic = "force-dynamic";
// the writer (lib/report/manifest.mjs updateRender) validates with the
// build's own checks, so a look this route accepts is one the build accepts.
//
-// GET ?project=<id> { look, deck, montage, styles, introStyles, keys, errors, token }
+// GET ?project=<id> { look, mode, preset, deck, montage, styles, introStyles, keys, errors, token }
+// `mode`: "deck" | "basic" as the build resolves it (the look preset under the
+// manifest); the Look panel's Basic | Deck switch writes `patch: {mode}`
// PUT { project, token, patch } { ok, look, token } | 409 stale | 400 { errors }
// PUT { project, token, variants } render.variants, the ladder Make variants encodes
// (null: the default ladder) → { ok, variants, token }
@@ -29,9 +32,18 @@ export async function GET(request: Request) {
const r = await resolveReport(url.searchParams.get("project") ?? "");
if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
const render = (r.manifest.render ?? {}) as Record<string, unknown>;
+ // The mode as the build reads it: over the cut's look preset, when it stands on one.
+ let mode: "deck" | "basic" = renderModeOf(render);
+ try {
+ mode = renderModeOf((effectiveManifest(r.manifest) as { render?: Record<string, unknown> }).render);
+ } catch {
+ // An unknown preset: the manifest's own word (the build says what is wrong).
+ }
return Response.json(
{
look: lookOf(render),
+ mode,
+ preset: typeof r.manifest.preset === "string" ? r.manifest.preset : null,
deck: deckOn(render),
montage: render.montage !== undefined && render.montage !== null,
styles: TRANSITION_STYLES,
diff --git a/umtool/app/api/report/share-line/route.ts b/umtool/app/api/report/share-line/route.ts
@@ -0,0 +1,31 @@
+import { projectRef } from "@/lib/projects";
+import { kindMakesTakes } from "@/lib/projects/kinds.mjs";
+import { projectShareLine } from "@/lib/report/shareLine.mjs";
+
+export const dynamic = "force-dynamic";
+
+// A CLIP'S SHARE LINE (lane output-modes): what the take panel's and Play's
+// **Copy share line** copy -- the platform's page at the first second the clip
+// plays and its moment on the archive (lib/report/shareLine.mjs; a Rumble
+// folder id as the embed id the archive serves). `umtool share <p> [<clip>]
+// [--take <t>]` is its twin.
+//
+// GET ?project=<id>[&clip=<id>][&take=<id>] -> { clip, seconds, platform, archive, text }
+const headers = { "cache-control": "no-store" };
+const ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
+
+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 });
+ if (!kindMakesTakes(project.kind)) return Response.json({ error: "a share line is a report video's clip's" }, { status: 400, headers });
+ const clip = url.searchParams.get("clip") || null;
+ const take = url.searchParams.get("take") || null;
+ if ((clip && !ID_RE.test(clip)) || (take && !ID_RE.test(take))) return Response.json({ error: "clip and take are ids" }, { status: 400, headers });
+ try {
+ const line = await projectShareLine(project, { clip, take });
+ return Response.json(line, { headers });
+ } catch (e) {
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 404, headers });
+ }
+}
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -1086,6 +1086,11 @@ function usage() {
" re-fetch an article's scope, see what changed, update: the plan (the editor's);",
" --yes starts it, one editor job (needs WORKER_TOKEN and the editor)",
" umtool refresh --check [<article>] [--force] [--json] the daily suggestion check, now",
+ " umtool clip <channel>/<video>@<start>-<end> [--snap words] [--title T] [--site <id>] [--json]",
+ " QUICK CLIP: a basic-mode project (the footage alone), its window asked of the editor, its",
+ " edges snapped to the words (--snap words), rendered as a take; prints the mp4 and its share line",
+ " umtool share <project> [<clip>] [--take <id>] [--site <id>] [--json] a clip's share line: its platform",
+ " page at the moment and its archive moment (a Rumble folder id mapped to the embed id)",
" umtool timeline <project> [ls] [--json] the cut: index, id, type, video, start–end, date title",
" umtool timeline <project> insert --after <id|-> <channel>/<video>@<start>-<end> [--id ID] [--section N]",
" [--lock] [--lock-end] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S]",
@@ -1200,6 +1205,10 @@ const COMMANDS = {
trailer: async () => process.exit(await (await import("../lib/report/trailerCli.mjs")).trailerCommand(argv.slice(argv.indexOf("trailer") + 1))),
// A vertical short (1080x1920) of a take's items, natively or reframed: lib/report/verticalCli.mjs.
vertical: async () => process.exit(await (await import("../lib/report/verticalCli.mjs")).verticalCommand(argv.slice(argv.indexOf("vertical") + 1))),
+ // Quick clip (lane output-modes): one moment to a basic-mode mp4 and its share line: lib/report/quickClip.mjs.
+ clip: async () => process.exit(await (await import("../lib/report/quickClip.mjs")).quickClipCommand(argv.slice(argv.indexOf("clip") + 1))),
+ // A clip's share line (lane output-modes): lib/report/shareLineCli.mjs.
+ share: async () => process.exit(await (await import("../lib/report/shareLineCli.mjs")).shareCommand(argv.slice(argv.indexOf("share") + 1))),
// Do the QR links open on their sites (UI notes #8): lib/report/linksCli.mjs.
links: async () => process.exit(await (await import("../lib/report/linksCli.mjs")).linksCommand(argv.slice(argv.indexOf("links") + 1))),
// The cast: characters' voices across projects, auditions, a project's voices (operator, 6 Nov): lib/report/castCli.mjs.
diff --git a/umtool/components/projects/CopyShareLine.tsx b/umtool/components/projects/CopyShareLine.tsx
@@ -0,0 +1,82 @@
+"use client";
+
+import { useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+
+// COPY SHARE LINE (lane output-modes): a clip's platform page at the moment and
+// its archive moment (GET /api/report/share-line, lib/report/shareLine.mjs),
+// copied to the clipboard and shown -- the line stays readable beside the
+// button, so a browser that refuses the clipboard still has it to select.
+// On the take panel (a take's first clip) and on Play (the clip on screen).
+// The CLI twin: `umtool share <project> [<clip>] [--take <id>]`.
+
+type Line = { clip: string; seconds: number; platform: string | null; archive: string | null; text: string };
+
+export default function CopyShareLine({
+ project,
+ clip = null,
+ take = null,
+ size = "sm",
+ testid = "",
+}: {
+ project: string;
+ clip?: string | null;
+ take?: string | null;
+ size?: "sm" | "md";
+ testid?: string;
+}) {
+ const [state, setState] = useState<"idle" | "busy" | "copied" | "shown" | "error">("idle");
+ const [line, setLine] = useState<Line | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const copy = async () => {
+ setState("busy");
+ setError(null);
+ try {
+ const q = new URLSearchParams({ project, ...(clip ? { clip } : {}), ...(take ? { take } : {}) });
+ const r = await fetch(`/api/report/share-line?${q}`, { cache: "no-store" });
+ const j = (await r.json().catch(() => ({}))) as Line & { error?: string };
+ if (!r.ok) throw new Error(j.error ?? `HTTP ${r.status}`);
+ setLine(j);
+ if (!j.text) {
+ setState("shown");
+ return;
+ }
+ try {
+ await navigator.clipboard.writeText(j.text);
+ setState("copied");
+ } catch {
+ // The clipboard refused (no permission, not a secure context): the line is shown to select.
+ setState("shown");
+ }
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ setState("error");
+ }
+ };
+ return (
+ <span className="inline-flex min-w-0 flex-wrap items-center gap-1.5" data-share-line-box={testid || clip || take || ""}>
+ <button
+ type="button"
+ data-share-copy={testid || clip || take || ""}
+ data-share-state={state}
+ disabled={state === "busy"}
+ onClick={() => void copy()}
+ className={cn(buttonVariants({ variant: "outline", size }))}
+ title={`the platform's page at the moment and its archive moment — umtool share ${project}${clip ? ` ${clip}` : ""}${take ? ` --take ${take}` : ""}`}
+ >
+ {state === "copied" ? "Copied" : "Copy share line"}
+ </button>
+ {line && (
+ <span data-share-line="" className="min-w-0 max-w-[42em] select-all break-all font-mono text-[11px] text-text-2">
+ {line.text || `${line.clip}: no platform page or archive to link`}
+ </span>
+ )}
+ {error && (
+ <span role="alert" data-share-error="" className="text-[11.5px] text-reject-text">
+ {error}
+ </span>
+ )}
+ </span>
+ );
+}
diff --git a/umtool/components/projects/TakesBench.tsx b/umtool/components/projects/TakesBench.tsx
@@ -17,6 +17,7 @@ import type { RenderView } from "@/lib/queue/view";
import { BenchBody, VerdictBar } from "./bench/BenchShell";
import { startTakeJob } from "./NewTakePanel";
import TakeActions from "./TakeActions";
+import CopyShareLine from "./CopyShareLine";
import FastRenders from "./FastRenders";
import TakeTools from "./TakeTools";
import { Advanced, Options, PanelSlot } from "@/components/ui/disclosure";
@@ -844,6 +845,10 @@ function TakeCard({
)}
{/* Fast feedback (takePreview.mjs): a preview of the whole take, a reel of what changed -- queue steps. */}
<FastRenders project={project} take={t.id} />
+ {/* Its share line (lane output-modes): the take's first clip's platform page at the moment and its archive moment. */}
+ <div className="flex flex-wrap items-center gap-1.5 text-[11.5px]">
+ <CopyShareLine project={project} take={t.id} testid={`take:${t.id}`} />
+ </div>
{(t.holds ?? []).some((h) => h.startsWith("it is rendering")) && <CancelRender project={project} take={t.id} ready={ready} onSaid={setCancelSaid} />}
<CancelSaidLine said={cancelSaid} />
{pickState?.stale && (
diff --git a/umtool/components/projects/report/LookPanel.tsx b/umtool/components/projects/report/LookPanel.tsx
@@ -25,6 +25,11 @@ import AssistBox from "./AssistBox";
// The brand intro (render.intro, report-to-video intro.mjs): the sting the
// cut opens with, by style; "none" is no intro. An intro written with its
// other knobs (ground, sound, seconds) keeps them when the style changes.
+// The OUTPUT MODE (render.mode, lane output-modes): **Basic | Deck** -- basic is
+// the footage alone (report-to-video basic.mjs: no deck, chrome, intro, QR,
+// cards or brand; post items and teasers left out), deck everything else. The
+// switch shows the mode as the build resolves it (over the cut's look preset)
+// and saves with the rest (`umtool look <p> mode=basic|deck`).
type Look = {
headerHeight?: number;
@@ -39,7 +44,8 @@ type Look = {
blur?: string;
intro?: string | { style?: string; [k: string]: unknown } | null;
};
-type View = { look: Look; deck: boolean; montage: boolean; styles: string[]; introStyles?: string[]; errors: string[]; token: string | null };
+type Mode = "deck" | "basic";
+type View = { look: Look; mode?: Mode; preset?: string | null; deck: boolean; montage: boolean; styles: string[]; introStyles?: string[]; errors: string[]; token: string | null };
/** The intro's style as written: a bare name or the object's `style`; "" for none. */
const introStyleOf = (v: Look["intro"]) => (typeof v === "string" ? v : v && typeof v === "object" ? String(v.style ?? "") : "");
@@ -67,9 +73,10 @@ type Draft = {
grain: string;
blur: "on" | "off";
intro: string;
+ mode: Mode;
};
-function draftOf(l: Look): Draft {
+function draftOf(l: Look, mode: Mode = "deck"): Draft {
const t = l.loudness?.target;
return {
header: l.headerHeight !== 0,
@@ -92,6 +99,7 @@ function draftOf(l: Look): Draft {
grain: String(l.slide?.grain ?? SLIDE_DEFAULTS.grain),
blur: l.blur === "off" ? "off" : "on",
intro: introStyleOf(l.intro),
+ mode,
};
}
@@ -137,6 +145,8 @@ function patchOf(was: Look, d: Draft, view: View): Record<string, unknown> {
(!on || ((was0?.maxS ?? ROOM.maxS) === maxS && (was0?.minGap ?? ROOM.minGap) === minGap));
if (!same) p.room = next;
}
+ // The output mode (render.mode): the writer keeps "deck" as no key unless a look preset's must be beaten.
+ if (d.mode !== (view.mode ?? "deck")) p.mode = d.mode;
// The blurred clips (render.blur): "on" is the default, written as no key.
if (d.blur !== (was.blur === "off" ? "off" : "on")) p.blur = d.blur === "off" ? "off" : null;
// The brand intro: none removes the key; a style keeps an object's other knobs.
@@ -169,7 +179,7 @@ export default function LookPanel({ project }: { project: string }) {
const j = (await r.json()) as View & { error?: string };
if (!r.ok) throw new Error(j.error ?? `HTTP ${r.status}`);
setView(j);
- setDraft(draftOf(j.look));
+ setDraft(draftOf(j.look, j.mode ?? "deck"));
}, [project]);
useEffect(() => {
load().catch((e) => setError(e instanceof Error ? e.message : String(e)));
@@ -203,8 +213,8 @@ export default function LookPanel({ project }: { project: string }) {
setError((j.errors ?? [j.error ?? `HTTP ${r.status}`]).join("; "));
return;
}
- setView({ ...view, look: j.look ?? {}, token: j.token ?? null, errors: [] });
- setDraft(draftOf(j.look ?? {}));
+ setView({ ...view, look: j.look ?? {}, mode: draft.mode, token: j.token ?? null, errors: [] });
+ setDraft(draftOf(j.look ?? {}, draft.mode));
setVersion((n) => n + 1);
setStatus("Saved — the next render uses it");
} finally {
@@ -225,6 +235,35 @@ export default function LookPanel({ project }: { project: string }) {
{view.errors.join("; ")}
</p>
)}
+ <div className="mb-3 flex flex-wrap items-center gap-x-3 gap-y-1.5" data-look-mode-row="">
+ <span className="text-[12.5px] text-text-2">Output</span>
+ <span role="group" aria-label="Output mode" className="inline-flex overflow-hidden rounded-[3px] border border-seam-2">
+ {(["basic", "deck"] as const).map((m) => (
+ <button
+ key={m}
+ type="button"
+ data-look-mode={m}
+ aria-pressed={draft.mode === m}
+ disabled={busy}
+ onClick={() => set({ mode: m })}
+ title={m === "basic" ? "the footage alone: no deck, chrome, intro, QR, cards or brand — umtool look <p> mode=basic" : "the deck and everything this panel sets — umtool look <p> mode=deck"}
+ className={
+ draft.mode === m
+ ? "bg-[var(--color-text)] px-3 py-1 text-[12px] font-semibold text-[var(--color-ground)]"
+ : "bg-transparent px-3 py-1 text-[12px] text-text-2 hover:text-text"
+ }
+ >
+ {m === "basic" ? "Basic" : "Deck"}
+ </button>
+ ))}
+ </span>
+ {draft.mode === "basic" && (
+ <span className="text-[12px] text-muted" data-look-mode-note="">
+ the footage alone — post items, teasers and cards are left out; the rest below applies to a deck render
+ </span>
+ )}
+ {view.preset && <span className="text-[12px] text-muted">look preset: {view.preset}</span>}
+ </div>
<div className="flex flex-wrap items-center gap-x-5 gap-y-2">
{check("header", "Header", "data-look-header")}
{check("footer", "Timeline footer", "data-look-footer")}
@@ -348,7 +387,7 @@ export default function LookPanel({ project }: { project: string }) {
Save the look
</button>
{dirty && (
- <button type="button" disabled={busy} onClick={() => setDraft(draftOf(view.look))} className={buttonVariants({ variant: "quiet", size: "md" })}>
+ <button type="button" disabled={busy} onClick={() => setDraft(draftOf(view.look, view.mode ?? "deck"))} className={buttonVariants({ variant: "quiet", size: "md" })}>
Undo changes
</button>
)}
diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx
@@ -39,6 +39,7 @@ import IntroCardPlayer from "./IntroCardPlayer";
import { useIntroPage } from "./useIntroPage";
import { videoStageAt, type VideoEntryPlay } from "@/lib/report/playVideo.mjs";
import ComboBadge, { type ComboInfo } from "./ComboBadge";
+import CopyShareLine from "../CopyShareLine";
// ---------------------------------------------------------------------------
// THE PLAY VIEW (umtool/docs/knobs.md, "Play the cut"): a screening room. The
@@ -167,6 +168,8 @@ export type PlayViewData = {
transition: number;
blurRendered: boolean;
deckOn: boolean;
+ /** A basic cut (render.mode "basic", report-to-video basic.mjs): the footage alone, nothing drawn over it. */
+ basic?: boolean;
segments: { id: string; start: number; duration: number; hold?: number }[];
entries: PlayEntry[];
};
@@ -1155,6 +1158,7 @@ export default function PlayCut({
// A video entry with the chrome off over it is on screen (video-entry.mjs): nothing of the deck shows.
data-play-chrome={videoNow?.video.noChrome ? "off" : undefined}
data-play-compose={composeState}
+ data-play-basic={view.basic ? "" : undefined}
data-play-edges={edges.state}
data-play-sound={engine.info?.sound ?? ""}
data-play-picture={engine.info?.picture ?? ""}
@@ -1247,14 +1251,20 @@ export default function PlayCut({
)}
</DeckFrame>
) : (
- <div className="relative w-full overflow-hidden rounded border border-seam bg-black max-md:rounded-none max-md:border-0" style={{ aspectRatio: "16 / 9" }} data-testid="play-plain">
+ <div
+ className="relative w-full overflow-hidden rounded border border-seam bg-black max-md:rounded-none max-md:border-0"
+ style={{ aspectRatio: "16 / 9" }}
+ data-testid="play-plain"
+ // A basic cut: the bare footage, as the basic render cuts it -- no card, no side post, nothing over it.
+ data-play-bare={view.basic ? "" : undefined}
+ >
{footageCanvas({ inset: 0, width: "100%", height: "100%" }, 1280, 720)}
- {postNow && <div className="absolute inset-0" style={{ background: bg }}>{postPlayer({ width: 1920, height: 1080 })}{comboBadge({ width: 1920, height: 1080 })}</div>}
- {videoUnder}
- {teaserCard}
- {introCard}
- {placeholderCard}
- {sideNow}
+ {!view.basic && postNow && <div className="absolute inset-0" style={{ background: bg }}>{postPlayer({ width: 1920, height: 1080 })}{comboBadge({ width: 1920, height: 1080 })}</div>}
+ {!view.basic && videoUnder}
+ {!view.basic && teaserCard}
+ {!view.basic && introCard}
+ {!view.basic && placeholderCard}
+ {!view.basic && sideNow}
</div>
)}
{dipVeil}
@@ -1349,6 +1359,8 @@ export default function PlayCut({
</span>
)}
{ui.waiting && <span className="text-[11.5px] text-muted" data-play-waiting="">loading…</span>}
+ {/* The clip on screen's share line: its platform page at the moment and its archive moment. */}
+ {item?.clip && <CopyShareLine key={`${item.id}:${take ?? ""}`} project={project} clip={item.id} take={take ?? null} testid="play" />}
{/* The clip on the bench, and back here after (E). */}
<button
type="button"
@@ -1377,7 +1389,7 @@ export default function PlayCut({
)}
{finaleNow && <span data-play-finale-up="">finale</span>}
{composeState === "composing" && <span>composing the chrome…</span>}
- {composeState === "no-deck" && <span>no on-screen deck: the footage alone</span>}
+ {composeState === "no-deck" && <span>{view.basic ? "basic: the footage alone, as the basic render cuts it" : "no on-screen deck: the footage alone"}</span>}
</span>
</div>
{backToast && (
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -27,7 +27,7 @@ Inbox cannot disagree about what is wrong with one.
| `window <project> <clip> --verdict confirmed\|incorrect [--correction T]` · `window <project> <clip> --reject <why> [--note T]` | what the walk said: `--reject` is the walk's **Reject ▾** kept in place (`not-matching`/`wrong-speaker`: incorrect, the note its correction; `irrelevant`/`repeats`/`weak`/`privacy`/`other`: rejected, the note its `rejectNote`); `umtool timeline <p> reject` takes it out ([report-video.md](report-video.md#verdict--what-the-walk-said)) |
| `window <project> <clip> --walk-note T` · `--star` / `--no-star` · `--repeat-of <clip>` | what the walk said that is not a verdict: an editorial note (not a correction) and the ★ favourite, a trailer candidate (`trailer <project> --candidates [--json]` lists them as beats); a deliberate repeat ([knobs.md](knobs.md#a-clip)) |
| `tighten <project> [--json] [--all] [--no-measure]` · `tighten <project> --apply <clip>[,<clip>…]` | the Cut tab's **Propose tight windows**: each clip to its sentence (the sentences its cut touches, else the whole ones inside its window) and each edge into its pause (the build's measured silences and the gaps between the recording's timed words, ≤ 1 s, inside the cached window) — before → after with the seconds, the clips that would change (`--all`: every clip); prints only. `--apply` writes the named rows through the window writer (the token, the cite that follows the edge); a lock is kept (it is against `resolve-windows`, not a person) ([knobs.md](knobs.md#tighten-to-the-sentence-snap-to-a-pause)) |
-| `links <project> [--json] [--fix]` | do the clip QRs open on their sites? `corpus.json` → the channel's manifest → `slugToPage` → the shard's record, one request at a time, shards from the cue cache; recorded in `out/links.json`, which `check` reads (`link-dead` blocking, `links-unverified`, `links-unchecked`); `--fix` rewrites a Twitch id the site serves as `v<id>`; **exit 1** when a link is dead ([knobs.md](knobs.md#do-the-qr-links-open)). The same record dates each site's deploy: a cited video newer than it is `site-deploy-behind` ([knobs.md](knobs.md#the-sites-the-links-depend-on)) |
+| `links <project> [--json] [--fix]` | do the clip QRs open on their sites? `corpus.json` → the channel's manifest → `slugToPage` → the shard's record, one request at a time, shards from the cue cache; recorded in `out/links.json`, which `check` reads (`link-dead` blocking, `links-unverified`, `links-unchecked`); `--fix` rewrites a Twitch id the site serves as `v<id>`, and a Rumble folder id (the URL slug) as the embed id the site serves (the clip gets `siteVideo`); **exit 1** when a link is dead ([knobs.md](knobs.md#do-the-qr-links-open)). The same record dates each site's deploy: a cited video newer than it is `site-deploy-behind` ([knobs.md](knobs.md#the-sites-the-links-depend-on)) |
| `link-policy <project> [--via <site id \| https://…>] [--direct <slug,…>] [--clear] [--fix] [--json]` | the project's **link policy** (`provenance.linkPolicy`): cite via site X, these channels direct. With no flag, prints it and every clip whose QR breaks it; `--fix` rewrites each one that has a fix through the window writer; new clips are written by it. **Exit 1** when a clip still breaks it ([knobs.md](knobs.md#the-link-policy)) |
| `patch-markers <project> [<file>.patch.json] [--fix] [--json]` | take patches whose deck markers name a clip not in the cut (a take made with one is refused); `--fix` gives each the `after` of the cut's marker of the same label; **exit 1** when one is left ([knobs.md](knobs.md#take-patches-follow-a-removal)) |
| `quote-check <project> [--clips a,b] [--pad S] [--json]` · `quote-check <project> --status` | **is each clip's quote in the seconds it plays?** The cut ±15 s of the source the render would cut it from, transcribed by the editor (`pnpm ops transcribe`, words on — its transcription lane), the quote found in those words and in the cues: `ok`, `moved` (heard more than 0.5 s from where the cues have it), `not-found`; rows in `quote-check.json`, stale when the cut or the quote changes; `check` blocks on `moved`/`not-found` (`clip-quote-moved`, `clip-quote-missing`), a take refuses them, `prep --status` counts them ([knobs.md](knobs.md#the-quote-check-is-the-quote-where-the-clip-plays)) |
@@ -38,7 +38,7 @@ Inbox cannot disagree about what is wrong with one.
| `intro <project> [key=value …] [--off] [--json]` · `intro <project> --take <take> --off\|--on` | **the intro** the cut opens on (`render.intro`): with no key, prints it as written, what the cut opens with (a `title-card`'s words resolved) and each version's on/off; `key=value` writes it through the look writer (`style` `seconds` 3.5–8 `mark` `ground` `sound` (`false` silent) `site` `title` `lines` (`a\|b`, ≤ 3) and the brand's keys; `key=` clears one; a new intro starts as `boot-dark`); `--off` takes it off the cut; `--take <t> --off` that version opens on no intro (its patch's `render.intro: null`), `--on` on the cut's again. **Exit 1** on a value the build refuses ([knobs.md](knobs.md#the-intro-played-and-edited)) |
| `link <project> <site>/<report>` · `link <project> --clear` | the manifest names the article it is the video of (settles `link-ambiguous`) |
| `set <project> <clip> key=value …` | a clip's **knobs**: `claim.at` `claim.hold` `claim.stamp` `claim.count` `claim.label` (the first mark's, or `--mark <id>`'s), its **marks** `mark.add=<verdict>[@<sec>]` `mark.remove=<id>` `mark.verdict=<verdict>` `marks=<json>`, `audio.offset` `audio.gain` `audio.fadeIn` `audio.fadeOut`, its picture's **blur** `blur.on=true` `blur.caption=…` `blur.strength` `blur.from` `blur.to` (`blur.on=` clears it; [knobs.md](knobs.md#a-clips-picture-blurred)), its **effects** `fx.zoom=<json>` `fx.receipts=<json>` `fx.punch=…` `fx.quote` `fx.punchIn=<json>` `fx.speakers=<json>` (`fx=<json>` all of them, `fx=` clears them; a shot is a file in the project; [knobs.md](knobs.md#effects)); `key=` clears one ([knobs.md](knobs.md#marks)) |
-| `look <project> key=value … [--unset render.<key>]…` | the cut's **knobs**: `factcheck.stamp.*`, `factcheck.verdicts.<V>.stampLabel\|label\|color`, `deck.markers=<json>`, `deck.markerLayout`, `variants=<json>`, and the look's keys ([knobs.md](knobs.md)) **The deck on, legacy keys off** (`updateRenderKeys`, one write, an undo point `revisions/…auto-render-keys…` first): `chrome.layout=deck` turns the deck on (render.chrome created when the cut has none: engine hyperframes, an empty deck), `--unset render.<key>` (repeatable) drops a legacy render key -- only `rail` `chromeEngine` `railEngine` `chromeRegions` `claimSchedule` `wordmark` `title` `finale` `cut`; the deck beside the old rail is refused in the build's words unless the same command drops it; deck.* keys in the same command land after the chrome exists. Another key named: **exit 2** |
+| `look <project> key=value … [--unset render.<key>]…` | the cut's **knobs**: `factcheck.stamp.*`, `factcheck.verdicts.<V>.stampLabel\|label\|color`, `deck.markers=<json>`, `deck.markerLayout`, `variants=<json>`, and the look's keys — `mode=basic\|deck` (the footage alone, [knobs.md](knobs.md#basic-output-the-footage-alone)) and `basic=<json>` (its fades) among them ([knobs.md](knobs.md)) **The deck on, legacy keys off** (`updateRenderKeys`, one write, an undo point `revisions/…auto-render-keys…` first): `chrome.layout=deck` turns the deck on (render.chrome created when the cut has none: engine hyperframes, an empty deck), `--unset render.<key>` (repeatable) drops a legacy render key -- only `rail` `chromeEngine` `railEngine` `chromeRegions` `claimSchedule` `wordmark` `title` `finale` `cut`; the deck beside the old rail is refused in the build's words unless the same command drops it; deck.* keys in the same command land after the chrome exists. Another key named: **exit 2** |
| `variants <project> [--take <t>] [--list] [--json]` | **Make variants**: the encode ladder of the build (or of a take's); `--list` what was made and the build's sync report, each clip's lag (past a frame flagged) ([knobs.md](knobs.md)) |
| `build <project> [--preset preview\|fast\|final] [--only ID]` | **prints** the chain |
| `build <project> --run [--url URL] [--replace] [--preset P] [--only ID] [--skip-fetch]` | **runs** it as the app's build job (POST `/api/report/build` on `--url`, else `UMTOOL_URL`, else `http://localhost:3050`), prints its log as it grows, **Ctrl-C** cancels the job (twice leaves it running); `--replace` stamps a deliverable newer than the manifest aside; exit 1 unless the job is done (release 36) |
@@ -131,7 +131,9 @@ Inbox cannot disagree about what is wrong with one.
| `timeline <project> insert (--after <id\|-> \| --to-section N \| --group G) post:<channel>/<postId> [--id ID]` | **one post item** among the cut's entries, made as `posts reel` makes one |
| `timeline <project> insert (--after <id\|-> \| --to-section N \| --group G) post-json:<json>\|post-json:@<file> [--id ID]` | **a post item made by hand** — a post no archive holds (one kept only as a picture): `{post: "<channel>/<postId>", author, handle, date, text, media: ["posts-media/…"], parents?, quoted?, subjects?, redact?}`, its media measured, its id `p-<postId>` unless `--id`; refused in the build's words (**exit 1**). Its avatar: `posts avatar <project> <handle> <file>` |
| `modules list [--json]` · `modules apply <project> [--config FILE] [--dry-run] [--json]` · `modules apply <project> [--config FILE] --take <id> [--label L] [--at S --dur S \| --full] [--quick] [--force] [--from TAKE] [--keep-frames] [--patch-out FILE]` | the **video modules** (release 39): `list` every module, its kind, slot and where its settings live; `apply` maps the project's `module-config.json` (the modules a video wants, in MODULES-DESIGN's vocabulary) into the manifest's homes (`report-to-video/modules/config-loader.mjs`) — the preset, the deck's subtitle and QR, the counter's series and each clip's marks, the stamps, the rail's markers, the chapters, the pairs, the status ledger, the intro, the finale — and lists every field with no home, by path. Without `--take` the manifest is rewritten through `replaceManifest` (a snapshot first); with `--take` it is that take's patch (`takes/<id>.modules-patch.json`, or `--patch-out`) and the take is made from it as `take` makes one, the manifest untouched. **Exit 1** when the result would not build (the build's sentences) ([knobs.md](knobs.md#look-presets)) |
-| `preset list [--json]` · `preset show <name> [--json]` · `preset save <name> --from <project> [--description D] [--force]` · `preset apply <name\|none> <project>` | the **look presets** (`umtool/presets/<name>.json`, or `UMTOOL_PRESETS_DIR`): a render block a manifest stands on (`"preset": "<name>"`), laid under it — preset → manifest → style → take patch. `save` keeps a project's look and leaves its content out; `apply` names the preset on the cut through `updatePreset` (nothing copied in), refused when the cut over it would not build ([knobs.md](knobs.md#look-presets)) |
+| `preset list [--json]` · `preset show <name> [--json]` · `preset save <name> --from <project> [--description D] [--force]` · `preset apply <name\|none> <project> [--replace] [--json]` | the **look presets** (`umtool/presets/<name>.json`, or `UMTOOL_PRESETS_DIR`; built in: `plain-deck` `huck-deck` `ember-deck` `archive-catalog` `basic`): a render block a manifest stands on (`"preset": "<name>"`), laid under it — preset → manifest → style → take patch. `save` keeps a project's look and leaves its content out; `apply` names the preset on the cut through `updatePreset` (nothing copied in), refused when the cut over it would not build (a basic cut's chrome is not checked); `--replace` also clears the manifest's own value of every key the preset sets, after an undo point (`revisions/…-auto-before-preset-replace`), and prints what went ([knobs.md](knobs.md#look-presets)) |
+| `clip <channel>/<video>@<start>-<end> [--snap words] [--title T] [--site <id>] [--folder F] [--json] [--progress ndjson]` | **quick clip**: a basic-mode project (`quick-clips/<slug>`, the footage alone), its window asked of the editor (fetch-windows, followed to its end; Rumble fetched whole), `--snap words` its edges snapped to the words heard (the editor's transcribe op), rendered as the take `clip` (`take <p> --id clip --full`: the heavy slot), then the mp4's path and the share line. `--json`: `{project, output, share: {platform, archive, text}, snapped?}`; `--progress ndjson`: events, the last `quick-clip` (the app's `POST /api/report/quick-clip` job). **Exit 0 · 1 failed (the editor, the render) · 2 usage** ([knobs.md](knobs.md#basic-output-the-footage-alone)) |
+| `share <project> [<clip>] [--take <t>] [--site <id>] [--json]` | a clip's **share line** (the clip named, else the first): its platform page at the first second it plays and its archive moment, a Rumble folder id as the embed id the archive serves — the twin of **Copy share line** (`GET /api/report/share-line`). `--json`: `{clip, seconds, platform, archive, text}` |
| `take status <project> [--id <take>] [--json] [--log] [--tail N]` | a take's **render record** (`takes/<take>/render.json`, written by every render whoever started it — a terminal, the Takes page, the queue): `state` (`running`, `waiting` at the heavy slot, `done`, `failed`, `cancelled`; `queued` or `blocked` while a queue step waits to render it), `stage` and a rough `percent`, the `error` (the first error line, not a bare "exited 1") and the log's last 40 lines (`tail`), on done the `mp4` and its measured `seconds`; `--log` prints the FULL `takes/<take>/render.log`. A "running" whose process is gone reads **failed** ("the render process is gone"); a done whose mp4 is missing or 0 bytes reads **failed**. **Exit 0 done · 3 queued, waiting or running · 1 failed, cancelled, blocked or none.** Without `--id`: every take with a record, the newest's exit ([queue and poll](#queue-and-poll-instead-of-scripting)); and its fast-feedback renders beside it, `preview` and `changes` (each one's state, mp4, seconds, log; a changes reel's piece count, its base and its list), a queued `--preview`/`--changes` step said as such -- never as the take's own render |
| `queue add [--after <qid>\|last] [--label T] [--timeout <minutes>] [--json] -- <umtool subcommand argv…>` | a **step** of the durable queue: the argv of a umtool command, one word per argument (no shell), stored under `<reports root>/.umtool-queue/` and run by the **umtool app** (its systemd unit), one step at a time, in order — so it survives the session that queued it, an app restart and a ship. Prints the qid (`q<N>`) alone on stdout. `--after` waits for that step to be **done**; when it fails or is cancelled this one is **blocked** (and so is whatever waits on it). `--timeout`: the step's limit (default 720 minutes). A step does not start while the app's own job runner is busy (a Takes-page job), and a heavy step still takes the machine's heavy slot and render mode by itself |
| `queue ls [--all] [--json]` · `queue status <qid> [--json]` · `queue wait <qid> [--timeout <s>]` · `queue log <qid> [--tail N]` · `queue cancel <qid>` · `queue retry <qid>` | the queue: `ls` the runner (is the app running it) and the steps not finished or finished in the last 24 h; `status` one step (**exit 0 done · 3 queued or running · 1 failed, blocked or cancelled**); `wait` the same after up to `<s>` seconds (default 90); `log` its FULL log (`logs/<qid>.log`; earlier attempts kept as `<qid>.<n>.log`); `cancel` a queued or blocked step at once, a running one stopped (its process group); `retry` a failed or cancelled step back in the queue with every step blocked behind it. A step that was running when the app died reads **failed** ("the step's process is gone"), its log kept — it is never re-run on its own |
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -330,6 +330,8 @@ that mentions the seizure in question and one before it. The Marks box is on eve
| `render.chrome.deck.claims[]` — his explicit claims drawn against the record on the rail, at most 6: a `count` or a `goalpost` ([below](#claim-checks-on-the-rail)) | On-screen, **claim checks**: add a count / a goalpost, the clip picker, **use the playhead**, his words, the window's dates, the record's verdict, per, the claim; a goalpost's steps (**add a step**), each its from date and due durations; remove — the build's validator under each as it is typed | `umtool look <p> deck.claims='[…]'` (`deck.claims=` none) | `PUT /api/report/chrome {project, token, claims}` |
| `posts[].thread` — `true`: a reply drawn with the post it answers above it — the capture's `shot-thread.png` beside the post's `shot` (taken by `pnpm ops capture-posts --json '{"slug":…,"ids":[…],"thread":true}'`, the replied-to author's avatar, name and handle blurred unless gold- or grey-checked or the reply's own; `"threadRedact": false` takes it unblurred), the post's own shot while there is none; needs a `shot`. In the feed a thread shot is drawn whole: the card under it leaves rather than the reply being squeezed, and one taller than the column is scaled to fit, never cut; the popup posts pan through it as through any tall shot | Media, On-screen **Posts** table: **thread** (shown once a thread shot is on disk) | `umtool posts set <p> <post> thread=on` (`thread=off` clears it) · on add: `umtool posts add <p> <channel>/<postId> --thread` | `PUT /api/report/posts {project, token, posts: {<id>: {thread}}}` |
| `posts[].shotMaxHeight` — the post's OWN **crop** of its screenshot, 120–1080 px: its top that tall, the rest cut off and **never panned to** (the deck-wide `deck.posts.shotMaxHeight` caps the viewport and a taller shot pans through it; this one does not) — what keeps a quoted post or a media thumbnail under the post's words off the screen; needs a `shot` | Play the cut, **Add post**: a hit's **crop** before Add, or a post in the cut's **crop** + **Save crop** (empty: none) | `umtool posts set <p> <post> crop=420` (`crop=off` clears it) · on add: `umtool posts add <p> <channel>/<postId> --crop 420` | `POST /api/report/post-cards {project, op: "crop", post, crop}` · `PUT /api/report/posts {…, posts: {<id>: {shotMaxHeight}}}` |
+| `render.mode` — `basic`: the FOOTAGE ALONE ([below](#basic-output-the-footage-alone)) — each clip's played spans spliced at the source's size and frame rate, no deck, chrome, intro, QR, rail, cards or brand; `deck` (the default, no key) everything else. Resolved LAST: the mode a reader sees is the last layer's (preset → manifest → style → take patch), so `basic` wins whatever chrome a layer under it sets | Build, **Look**: **Basic \| Deck** (shows the mode over the cut's look preset; saves with the rest) | `umtool look <p> mode=basic` (`mode=deck`: no key, or `"deck"` over a preset that says basic) · the preset: `umtool preset apply basic <p> [--replace]` · a take: `umtool take <p> --id basic --set render.mode=basic` | `PUT /api/report/render {project, token, patch: {mode}}` |
+| `render.basic.fade` — `{audio?, video?}` seconds (0–3): a basic cut's fades — `audio` (default 0.03) in and out at EVERY span's edges (no click at a join, a gap's jump cut too), `video` (default 0.15) from black at the cut's first frame and to black at its last | — | `umtool look <p> basic='{"fade":{"audio":0.05,"video":0.3}}'` (`basic=` the defaults) | `PUT /api/report/render {project, token, patch: {basic}}` |
| `render.blur` — `off`: every clip's picture as recorded, no caption (the uncensored variant); `on` (the default) blurs the clips that ask | Build, **Look**: **Blurred clips** | `umtool look <p> blur=off` · a take: `umtool take <p> --id uncensored --set render.blur=off` | `PUT /api/report/render {project, token, patch: {blur}}` |
| `render.intro` — the brand sting the cut opens with: a style (`boot` `boot-wipe` `boot-dark` `boot-cascade` `boot-mark` `title-card`) or `{style, ground?, mark?, sound?, seconds?, site?, swap?, url?, urlPlace?, title?, lines?}`; absent is none ([report-video.md](report-video.md#the-brand-intro-renderintro); played and edited: [The intro](#the-intro-played-and-edited)) | Build, **Look**: **Intro** · the Cut tab's intro row (**Edit intro**) | `umtool intro <p> style=boot-dark` (`--off` none) · `umtool look <p> intro=boot-dark` (`intro=` none) · a take: `umtool take <p> --id intro-wipe --set render.intro=boot-wipe` | `PUT /api/report/render {project, token, patch: {intro}}` |
| `render.intro.site` — on the chime, "Archi" becomes the cited site's name ("Jera"), "lyzer" stays, the colours go to its accent: `auto` (the site whose `siteUrl` is `provenance.siteOrigin`; none found, no swap), a site id, `{name, lead?, accent?, url?}`, or `none`/absent (the plain intro, byte for byte). `render.intro.swap` `swipe-down` (default) \| `roll` \| `wipe`; `render.intro.url` `both` (default: the site's, then archilyzer.pages.dev) \| `site` \| `project` \| `false`; `render.intro.urlPlace` `under` (default: one row under MEDIA) \| `replace` (MEDIA's place) | — (manifest or a take) | a take: `umtool take <p> --id intro-jera --set render.intro.style=boot-dark --set render.intro.mark=chime --set render.intro.site=auto` (`--set render.intro.swap=roll`, `--set render.intro.url=false`, `--set render.intro.urlPlace=replace`) · standalone: `node umtool/report-to-video/intro.mjs render --style boot-dark --mark chime --site auto --site-origin https://jeralyzer.pages.dev --swap wipe --out x.mp4` | `PUT /api/report/render {project, token, patch: {intro: {…, site}}}` |
@@ -342,6 +344,39 @@ the render unchanged. The two are not set together: on a migrated cut the series
The default ladder: `master`, `1080p` (crf 22), `720p` (crf 23), `fit24` (at most 24 MiB). `umtool look` also sets
the look's keys (`transition=0.3`, …: [report-video.md](report-video.md#the-look-captions-loudness-shorts-release-36)).
+## Basic output (the footage alone)
+
+`render.mode: "basic"` renders the cut as its footage and nothing else (`report-to-video/basic.mjs`): each clip's
+played spans — `cutStart|start` .. `cutEnd|end` less its gaps, exactly what Play plays — cut from the window on disk
+that holds each span (the build's own lookup: the raw cache, the editor's corpus windows, a saved recording through
+its clock) and spliced end to end with hard cuts, at the FIRST window's size and frame rate (a later window of
+another shape is letterboxed into it, never stretched), the build's encode (`render.crf`, `render.preset`), the
+fades of `render.basic.fade`. Every render of the cut gets it — `umtool take`, `umtool build`, the Takes page — because
+the build reads the mode off the manifest every layer resolved into, and the heavy slot is told a basic render's
+estimate (1.2 GB, render-estimate.mjs). The spans' files are kept under `out/<variant>/basic/` and reused when the
+same encode of the same window is asked again.
+
+What a basic cut does not draw is said, never dropped in silence: a post item, a teaser, a card, a still or a video
+entry is left out with a note; a clip's `audio.offset`, fades and mute mark are noted (its `audio.gain` is applied);
+a clip that asks for its picture BLURRED is refused unless the cut is the uncensored one (`umtool look <p>
+blur=off`) — basic draws no blur. It never fetches: a span no window holds fails the render by name (`umtool fetch
+<p>` first, through the editor). `--short`, `--vertical`, `--join-preview`, `--chrome-*`, `--clip-preview`,
+`--rail-only` and `--thumbnail` have no basic form and say so. Play the cut of a basic cut plays the same spans, the
+bare footage (no deck, no cards: `data-play-bare`).
+
+| | In umtool | From a terminal | Route |
+|---|---|---|---|
+| the mode | Build, **Look**: **Basic \| Deck** | `umtool look <p> mode=basic` | `PUT /api/report/render {patch: {mode}}` |
+| the built-in preset | Media, Video modules, Look preset | `umtool preset apply basic <p> [--replace]` | — |
+| a clip's **share line** — its platform page at the first second it plays (YouTube `t=<s>s`, Rumble `start=<s>`, Twitch `t=<h>h<m>m<s>s`) and its moment on the archive (`archiveMomentUrl`); a Rumble folder id (the URL slug the corpus keeps it under) goes out as the embed id the archive serves | **Copy share line**: on each take's card (its first clip) and on Play (the clip on screen); the line is shown beside the button too | `umtool share <p> [<clip>] [--take <t>] [--site <id>] [--json]` | `GET /api/report/share-line?project&clip&take` |
+| **quick clip** — one moment to a shareable mp4: a basic-mode project under `quick-clips/` (its slug from `--title`, else `<channel>-<video>-<start>`), its window ASKED OF THE EDITOR (a Rumble recording fetched whole — the editor decides), `--snap words`: the edges snapped to the words heard there (the editor's transcribe op; the first word mostly after the start, the last mostly before the end, 0.15 s before and 0.3 s after, never into a neighbour), rendered as the take `clip` (the heavy slot; its record; the take panel), then the mp4's path and the share line; `--site <id>` names the archive (else the first public site carrying the channel) | — (the route) | `umtool clip <channel>/<video>@<start>-<end> [--snap words] [--title T] [--site <id>] [--folder F] [--json]` | `POST /api/report/quick-clip {spec, snap?, title?, site?}` → 202 `{job}`; `GET ?job=<id>` → `{job, done?: {project, output, share}}` |
+
+The Rumble mapping is ONE helper (`lib/report/shareLine.mjs` `siteVideoFor`, over common `videoDir-server.mjs`
+`recordIdOfVideoDir`: the folder's `metadata.info.json` `id`) and it has three callers: the share line;
+`umtool links --fix`, which now fixes a QR naming a Rumble folder id (the clip gets `siteVideo: <embed id>`, a
+`citeUrl` that was the dead link moves with it); and `umtool timeline insert <rumble-channel>/<folder>@…`, which
+writes the inserted clip with its `siteVideo`. A clip that pins `siteVideo` is never looked up.
+
## Sections, split and flash-forward (editing the cut)
Under the deck a cut's **sections are its markers** (`render.chrome.deck.markers`): §0 runs to the first marker's
@@ -1651,13 +1686,20 @@ checks the chrome (`updateChrome` validates the chrome over the preset). A resol
| | In umtool | From a terminal |
|---|---|---|
| the presets | Media, **Video modules**, Look preset | `umtool preset list` · `umtool preset show <name>` |
-| stand the cut on one (or none) | the same list | `umtool preset apply <name\|none> <p>` |
+| stand the cut on one (or none) | the same list | `umtool preset apply <name\|none> <p> [--replace]` |
| save a project's look as one (its content — claim checks, markers, counter series, finale stats, the story modules' lists, an intro's named site — left out) | | `umtool preset save <name> --from <p> [--description D]` |
| a take on one | | `umtool take <p> --id <id> --set preset=<name>` |
Built in: `huck-deck` (quartering-huck/polemic-huck's look: the feed, verdict-coloured pips, the finale beside the
-clip), `plain-deck` (the Trisha final's: every subtitle part, the boot-dark intro, no feed), `archive-catalog` (a
-then-and-now archive look: dated subtitles, a pitched rail, the pair strip at the foot of the footage).
+clip), `plain-deck` (the Trisha final's: every subtitle part, the boot-dark intro, no feed), `ember-deck`
+(EmberParadox's, from in-her-words: 2-line subtitles, section-coloured pips, no stamps or counters, the boot-dark
+intro), `archive-catalog` (a then-and-now archive look: dated subtitles, a pitched rail, the pair strip at the foot of
+the footage), `basic` (`{render: {mode: "basic"}}`: [the footage alone](#basic-output-the-footage-alone)).
+
+`umtool preset apply <name> <p> --replace` also CLEARS the manifest's own value of every key the preset sets (each
+leaf of its render block; an object left empty goes too) so the preset's renders — after an undo point,
+`revisions/<stamp>-auto-before-preset-replace.manifest.json` — and prints what it cleared. Without it a manifest's
+own value still beats its preset's (a `render.mode: "deck"` written over a `basic` preset stays deck).
## A module-config.json
diff --git a/umtool/e2e/basic-mode.spec.ts b/umtool/e2e/basic-mode.spec.ts
@@ -0,0 +1,143 @@
+import { test, expect, type Page } from "@playwright/test";
+import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// THE BASIC OUTPUT MODE AND QUICK CLIP (lane output-modes). The Look panel's
+// Basic | Deck switch writes render.mode (read back from the manifest); Play of
+// a basic cut shows the bare footage -- no deck, no teaser card -- and Play's
+// Copy share line puts the clip's platform page and archive moment on the
+// clipboard; POST /api/report/quick-clip runs `umtool clip` as one job against
+// the stub editor (its window fetched by the stub, the cut rendered basic as a
+// take), ends `done` with the output and the share line, and the take panel's
+// Copy share line copies it. Fixture: e2e/fixtures/basic-mode-fixture.mjs.
+// E2E_BASIC_SHOTS=<dir>: the surfaces' screenshots go there (1366x768).
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const PROJECT = "reports/basic-fixture";
+const DIR = path.join(FIXTURE, "reports", "basic-fixture");
+const MANIFEST = path.join(DIR, "video.manifest.json");
+const QUICK = path.join(FIXTURE, "quick-clips");
+const QUICK_WINDOWS = path.join(FIXTURE, "channels", "basicyt", "data", "quickvid", "clips");
+const SHOTS = process.env.E2E_BASIC_SHOTS ?? "";
+const original = readFileSync(MANIFEST, "utf8");
+const manifest = () => JSON.parse(readFileSync(MANIFEST, "utf8"));
+const shot = async (page: Page, name: string) => {
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, `${name}.png`) });
+};
+
+test.beforeEach(() => writeFileSync(MANIFEST, original));
+test.afterAll(() => {
+ writeFileSync(MANIFEST, original);
+ // What the quick-clip job made: its project and the window the stub wrote. Other specs count projects.
+ rmSync(QUICK, { recursive: true, force: true });
+ rmSync(QUICK_WINDOWS, { recursive: true, force: true });
+});
+
+test("the Look panel's Basic | Deck switch writes render.mode; Play of a basic cut is the bare footage; the share line is copied", async ({ page, context }) => {
+ test.setTimeout(300_000);
+ await context.grantPermissions(["clipboard-read", "clipboard-write"]);
+ await page.setViewportSize({ width: 1366, height: 768 });
+
+ // ---- a deck cut: Play composes its deck ------------------------------------
+ await page.goto(urls.playHref(PROJECT, { bare: true }));
+ await expect(page.locator("[data-play-cut]")).toBeVisible({ timeout: 60_000 });
+ await expect(page.locator("[data-play-cut]")).not.toHaveAttribute("data-play-basic", "");
+
+ // ---- the switch -------------------------------------------------------------
+ await page.goto(urls.section(PROJECT, "build"));
+ await expect(page.locator("[data-look-panel]")).toHaveAttribute("data-look-panel", "", { timeout: 60_000 });
+ await expect(page.locator('[data-look-mode="deck"]')).toHaveAttribute("aria-pressed", "true");
+ await page.locator('[data-look-mode="basic"]').click();
+ await expect(page.locator('[data-look-mode="basic"]')).toHaveAttribute("aria-pressed", "true");
+ await expect(page.locator("[data-look-mode-note]")).toContainText("the footage alone");
+ await page.locator("[data-look-save]").click();
+ await expect(page.locator("[data-look-status]")).toHaveText("Saved — the next render uses it", { timeout: 60_000 });
+ expect(manifest().render.mode).toBe("basic");
+ expect(manifest().render.chrome?.layout, "the deck's settings are kept, not drawn").toBe("deck");
+ await page.locator("[data-look-mode-row]").scrollIntoViewIfNeeded();
+ await shot(page, "look-basic-switch");
+ // Read back on a fresh load.
+ await page.reload();
+ await expect(page.locator('[data-look-mode="basic"]')).toHaveAttribute("aria-pressed", "true");
+
+ // ---- Play: the bare footage --------------------------------------------------
+ await page.goto(urls.playHref(PROJECT, { bare: true }));
+ const root = page.locator("[data-play-cut]");
+ await expect(root).toHaveAttribute("data-play-basic", "", { timeout: 60_000 });
+ await expect(root).toHaveAttribute("data-play-compose", "no-deck");
+ await expect(page.getByTestId("play-plain")).toHaveAttribute("data-play-bare", "");
+ await expect(page.getByTestId("play-deck")).toHaveCount(0);
+ await expect(page.locator("[data-play-hud]")).toContainText("basic: the footage alone");
+ // The teaser is not in a basic cut: two clips play.
+ await expect(page.locator("[data-play-readout]")).toContainText("1/2");
+
+ // ---- the share line: copied, and shown -----------------------------------------
+ await page.locator('[data-share-copy="play"]').click();
+ await expect(page.locator('[data-share-copy="play"]')).toHaveAttribute("data-share-state", /copied|shown/, { timeout: 60_000 });
+ const line = page.locator('[data-share-line-box="play"] [data-share-line]');
+ await expect(line).toContainText("https://www.youtube.com/watch?v=basicvid&t=1s");
+ await expect(line).toContainText("archive: https://archive.example/?v=basicyt%2Fbasicvid&t=1");
+ if ((await page.locator('[data-share-copy="play"]').getAttribute("data-share-state")) === "copied") {
+ expect(await page.evaluate(() => navigator.clipboard.readText())).toBe((await line.textContent())?.trim());
+ }
+ await shot(page, "play-basic");
+
+ // ---- back to deck: the switch writes it away -------------------------------------
+ await page.goto(urls.section(PROJECT, "build"));
+ await page.locator('[data-look-mode="deck"]').click();
+ await page.locator("[data-look-save]").click();
+ await expect(page.locator("[data-look-status]")).toHaveText("Saved — the next render uses it", { timeout: 60_000 });
+ expect(manifest().render.mode, "deck is the default: no key").toBeUndefined();
+});
+
+test("quick clip: POST /api/report/quick-clip ends done -- the window asked of the editor, rendered basic, the share line; the take panel copies it", async ({ page, context }) => {
+ test.setTimeout(300_000);
+ await context.grantPermissions(["clipboard-read", "clipboard-write"]);
+ await page.setViewportSize({ width: 1366, height: 768 });
+ expect((await page.request.post("/api/report/quick-clip", { data: { spec: "basicyt/quickvid" } })).status()).toBe(400);
+ expect((await page.request.post("/api/report/quick-clip", { data: { spec: "basicyt/quickvid@10-14", snap: "letters" } })).status()).toBe(400);
+ for (const spec of ["../quickvid@10-14", "..@1-2", "-rf/quickvid@10-14", "basicyt/..@10-14", "basicyt/-x@10-14"]) {
+ expect((await page.request.post("/api/report/quick-clip", { data: { spec } })).status(), spec).toBe(400);
+ }
+
+ const started = await page.request.post("/api/report/quick-clip", { data: { spec: "basicyt/quickvid@10-14", title: "E2E quick clip" } });
+ expect(started.status(), await started.text()).toBe(202);
+ const { job } = (await started.json()) as { job: { id: string } };
+ type Done = { job: { state: string; log: string[] }; done?: { project: string; output: string; share: { platform: string | null; archive: string | null; text: string } }; error?: string };
+ let last: Done | null = null;
+ await expect
+ .poll(
+ async () => {
+ last = (await (await page.request.get(`/api/report/quick-clip?job=${encodeURIComponent(job.id)}`)).json()) as Done;
+ return last.job.state;
+ },
+ { timeout: 240_000, intervals: [1000, 2000, 3000] },
+ )
+ .not.toBe("running");
+ const r = last as unknown as Done;
+ expect(r.job.state, `${r.error ?? ""}\n${r.job.log.join("\n")}`).toBe("done");
+ expect(r.done?.project).toBe("quick-clips/e2e-quick-clip");
+ expect(r.done?.share.platform).toBe("https://www.youtube.com/watch?v=quickvid&t=10s");
+ expect(r.done?.output).toBe(path.join(QUICK, "e2e-quick-clip", "takes", "clip", "preview.mp4"));
+ expect(existsSync(String(r.done?.output))).toBe(true);
+ const made = JSON.parse(readFileSync(path.join(QUICK, "e2e-quick-clip", "video.manifest.json"), "utf8"));
+ expect(made.render.mode).toBe("basic");
+ expect(made.timeline.map((e: { id: string; video: string }) => `${e.id}:${e.video}`)).toEqual(["c01:quickvid"]);
+ // The stub editor was asked for the window (and wrote it): nothing fetched by hand.
+ const asked = JSON.parse(readFileSync(path.join(FIXTURE, "editor-stub.requests.json"), "utf8")) as { route?: string; requestedBy?: string }[];
+ expect(asked.some((q) => q.route === "fetch-windows" && q.requestedBy === "umtool:quick-clips/e2e-quick-clip")).toBe(true);
+
+ // ---- the take panel: its share line ------------------------------------------------
+ await page.goto(urls.takesHref("quick-clips/e2e-quick-clip"));
+ const copy = page.locator('[data-share-copy="take:clip"]');
+ await expect(copy).toBeVisible();
+ await copy.click();
+ await expect(copy).toHaveAttribute("data-share-state", /copied|shown/, { timeout: 60_000 });
+ await expect(page.locator('[data-share-line-box="take:clip"] [data-share-line]')).toHaveText("https://www.youtube.com/watch?v=quickvid&t=10s");
+ await shot(page, "take-share-line");
+});
diff --git a/umtool/e2e/fixtures/basic-mode-fixture.mjs b/umtool/e2e/fixtures/basic-mode-fixture.mjs
@@ -0,0 +1,55 @@
+// What basic-mode.spec.ts walks (lane output-modes): the Basic | Deck switch,
+// Play in basic, the share line, and the quick-clip job.
+//
+// basic-fixture a DECK cut on the channel basicyt (a YouTube channel in the
+// fixture's corpus, its record naming its watch page):
+// c01 basicvid 1.0–3.0 (the fixture's synthetic tone window, cached in out/clips-raw)
+// t01 a teaser (a basic cut leaves it out; Play in basic does not show it)
+// c02 basicvid 4.0–7.0
+// The spec writes render.mode and puts the manifest back.
+// basicyt/quickvid a recording with no window on disk: the quick-clip job
+// asks the stub editor for it (editor-stub-fetch-windows.mjs
+// serves basicyt), renders it basic, and the spec removes the
+// project it made (reports/quick-clips/) and the window.
+//
+// Synthetic, like every fixture.
+import { copyFileSync, mkdirSync, writeFileSync } from "node:fs";
+import path from "node:path";
+
+export const BASIC_CHANNEL = "basicyt";
+export const BASIC_PROJECT = "basic-fixture";
+
+const write = (dir, name, doc) => {
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(path.join(dir, name), JSON.stringify(doc, null, 2) + "\n");
+};
+
+/** @param {{ reports: string, channels: string, deckManifest: Function, cachedWindow: string }} o */
+export function makeBasicModeFixture({ reports, channels, deckManifest, cachedWindow }) {
+ write(path.join(channels, BASIC_CHANNEL), "config.json", { name: "Basic Fixture", platform: "youtube", url: "https://www.youtube.com/@basicfixture" });
+ const record = (id, duration) =>
+ write(path.join(channels, BASIC_CHANNEL, "data", id), "transcript.cues.json", {
+ title: `Basic fixture ${id}`,
+ uploadDate: "20260101",
+ platform: "youtube",
+ channel: "Basic Fixture",
+ webpageUrl: `https://www.youtube.com/watch?v=${id}`,
+ duration,
+ cues: [{ start: 0, end: duration, text: "a synthetic tone" }],
+ });
+ record("basicvid", 9);
+ record("quickvid", 60);
+
+ const dir = path.join(reports, BASIC_PROJECT);
+ mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true });
+ copyFileSync(cachedWindow, path.join(dir, "out", "clips-raw", "basicvid_0.00-9.00.mp4"));
+ const m = deckManifest(BASIC_PROJECT, "The Basic Fixture", [
+ { type: "clip", id: "c01", video: "basicvid", start: 1.0, end: 3.0, cite: 1, section: 0, lock: true, quote: "a synthetic tone" },
+ { type: "teaser", id: "t01", seconds: 3, lines: ["Next", "The Basic Cut"] },
+ { type: "clip", id: "c02", video: "basicvid", start: 4.0, end: 7.0, cite: 4, section: 0, lock: true, quote: "the tone again" },
+ ]);
+ m.provenance = { ...m.provenance, channelSlug: BASIC_CHANNEL };
+ m.render.fetchPad = 0;
+ write(dir, "video.manifest.json", m);
+ return { dir };
+}
diff --git a/umtool/e2e/fixtures/editor-stub-fetch-windows.mjs b/umtool/e2e/fixtures/editor-stub-fetch-windows.mjs
@@ -22,7 +22,8 @@ import path from "node:path";
// channel (testchan/vid1's clips/, the chain's windows step) changes what that
// spec's cache lookup finds — specs must stay order-independent. And the
// article chain's `windows` step relies on that 404 to stop (article-iterations.spec).
-export const FETCH_WINDOWS_CHANNELS = new Set(["opsrumble", "opsyt"]);
+// basicyt: the quick-clip job's recording (basic-mode-fixture.mjs), a channel of its own for the same reason.
+export const FETCH_WINDOWS_CHANNELS = new Set(["opsrumble", "opsyt", "basicyt"]);
const fwJobs = new Map();
let next = 1;
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -60,6 +60,7 @@ import { makePostItemsFixture } from "./post-items-fixture.mjs";
import { makePostHappyFixture } from "./post-happy-fixture.mjs";
import { makePostNarrationFixture } from "./post-narration-fixture.mjs";
import { makePresentFixture } from "./present-fixture.mjs";
+import { makeBasicModeFixture } from "./basic-mode-fixture.mjs";
import { makeTakeItemsFixture } from "./take-items-fixture.mjs";
import { makePlayPreloadFixture } from "./play-preload-fixture.mjs";
import { makePostComboFixture } from "./post-combo-fixture.mjs";
@@ -1942,6 +1943,9 @@ makePostNarrationFixture({ reports, deckManifest });
// Present mode (lib/report/present.mjs): a clip, a section, a narrated reply to a private account with a redacted
// name and a censored picture, a plain post, a teaser (present.spec.ts).
makePresentFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
+// The basic output mode and Quick clip (report-to-video/basic.mjs, lib/report/quickClip.mjs): a deck cut to switch to
+// basic, its share line, and a recording the quick-clip job asks the stub editor for (basic-mode.spec.ts).
+makeBasicModeFixture({ reports, channels: CHANNELS, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
// A take's own items (takeImport.mjs, takeScope.mjs): a post imported from another project into a draft take, edited in the take only (take-items.spec.ts).
makeTakeItemsFixture({ reports, deckManifest });
// A fast burst of narrated posts (Play's prefetch and its gate: play-preload.spec.ts).
diff --git a/umtool/lib/report/linkCheck.mjs b/umtool/lib/report/linkCheck.mjs
@@ -90,6 +90,12 @@ export function linksOf(m) {
return out;
}
+/** An archive link with its `?v=<channel>/<from>` id swapped for `to`, everything else as it was. Pure. */
+export function withArchiveId(url, from, to) {
+ const esc = String(from).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+ return String(url).replace(new RegExp(`([?&]v=[^&#]*?)(%2F|/)${esc}(?=&|#|$)`, "i"), `$1$2${to}`);
+}
+
/** A fetch that gives up: a site that hangs is a site that does not answer. */
function withTimeout(fetchImpl, ms) {
return (url, init = {}) => fetchImpl(url, { ...init, signal: AbortSignal.timeout(ms) });
@@ -105,16 +111,22 @@ const errText = (e) => {
* Resolve the links. Pure over `fetchImpl` (and the cache dir).
*
* @param {Array<{ clip: string, url: string }>} links
- * @param {{ fetchImpl?: typeof fetch, cacheDir?: string | null, now?: () => Date, log?: (s: string) => void, gapMs?: number, sleep?: (ms: number) => Promise<void> }} [opts]
+ * `siteIdOf({clip, channel, id})`: the id the archive serves a recording
+ * under when the link names the corpus's own (a Rumble URL-slug directory:
+ * its embed id, shareLine.mjs siteVideoFor), else null -- a link to the folder
+ * id is then dead with the embed id's link as its `fix` and `fixSiteVideo`.
+ *
+ * @param {{ fetchImpl?: typeof fetch, cacheDir?: string | null, now?: () => Date, log?: (s: string) => void, gapMs?: number, sleep?: (ms: number) => Promise<void>,
+ * siteIdOf?: (q: { clip: string, channel: string, id: string }) => Promise<string | null> }} [opts]
* @returns {Promise<{
* version: 1, checkedAt: string, fetched: number,
* origins: Record<string, { state: "ok" | "unreachable" | "no-corpus", error?: string, generatedAt?: string | null, title?: string | null }>,
- * links: Array<{ clip: string, url: string, state: "ok" | "dead" | "unverified" | "direct", origin?: string, why?: string, fix?: string }>,
+ * links: Array<{ clip: string, url: string, state: "ok" | "dead" | "unverified" | "direct", origin?: string, why?: string, fix?: string, fixSiteVideo?: string }>,
* }>}
*/
export async function checkLinks(
links,
- { fetchImpl = globalThis.fetch, cacheDir = DEFAULT_CACHE_DIR, now = () => new Date(), log = () => {}, gapMs = LINK_GAP_MS, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) } = {},
+ { fetchImpl = globalThis.fetch, cacheDir = DEFAULT_CACHE_DIR, now = () => new Date(), log = () => {}, gapMs = LINK_GAP_MS, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), siteIdOf = null } = {},
) {
let fetched = 0;
/** host -> when its last request was sent (ms) */
@@ -215,12 +227,18 @@ export async function checkLinks(
if (page === undefined) {
// The Twitch trap: the corpus directory is the bare id, the site's record is `v<id>`.
const alt = /^\d+$/.test(a.id) && s2p[`v${a.id}`] !== undefined ? `v${a.id}` : null;
+ // The Rumble trap: the corpus directory is the URL slug, the site's record the embed id (siteIdOf).
+ const embed = !alt && siteIdOf ? await siteIdOf({ clip, channel: a.channel, id: a.id }).catch(() => null) : null;
+ const rumble = embed && embed !== a.id && s2p[embed] !== undefined ? embed : null;
out.push({
clip, url, state: "dead", origin: a.origin,
why: alt
? `"${a.id}" is not a record on ${host}; the site's record is "${alt}"`
- : `"${a.id}" is not published in ${a.channel} on ${host}${origins[a.origin].generatedAt ? ` (deployed ${origins[a.origin].generatedAt.slice(0, 10)})` : ""}`,
+ : rumble
+ ? `"${a.id}" is the recording's folder (its Rumble URL slug), not a record on ${host}; the site's record is its embed id "${rumble}"`
+ : `"${a.id}" is not published in ${a.channel} on ${host}${origins[a.origin].generatedAt ? ` (deployed ${origins[a.origin].generatedAt.slice(0, 10)})` : ""}`,
...(alt ? { fix: url.replace(/([?&]v=[^&#]*?)(%2F|\/)(\d+)(?=&|#|$)/i, `$1$2v$3`) } : {}),
+ ...(rumble ? { fix: withArchiveId(url, a.id, rumble), fixSiteVideo: rumble } : {}),
});
continue;
}
@@ -243,6 +261,30 @@ export async function checkLinks(
}
/**
+ * A project's `siteIdOf` for checkLinks: the clip's recording, when the link
+ * names it as the corpus keeps it, looked up in the project's channels trees
+ * (its shadow, then the corpus behind it) for the id the archive serves
+ * (shareLine.mjs siteVideoFor: a Rumble folder's embed id).
+ * @param {string} dir
+ * @param {Record<string, any>} manifest
+ */
+export async function projectSiteIdOf(dir, manifest) {
+ const [{ channelsLayersFor, hasShadowChannels }, { siteVideoFor }] = await Promise.all([import("../projects/report.mjs"), import("./shareLine.mjs")]);
+ const layers = channelsLayersFor(dir, manifest, { shadowExists: await hasShadowChannels(dir) });
+ const byId = new Map((manifest?.timeline ?? []).filter((e) => e?.type === "clip").map((e) => [e.id, e]));
+ return async ({ clip, id }) => {
+ const e = byId.get(clip);
+ if (!e || e.siteVideo || String(e.video) !== id) return null;
+ const slug = e.channel ?? manifest?.provenance?.channelSlug ?? null;
+ for (const d of layers) {
+ const got = await siteVideoFor({ channelsDir: d, slug, video: id });
+ if (got) return got;
+ }
+ return null;
+ };
+}
+
+/**
* Check the project's links now and record the answer in out/links.json.
*
* @param {string} dir
@@ -250,7 +292,7 @@ export async function checkLinks(
* @param {{ fetchImpl?: typeof fetch, cacheDir?: string | null, now?: () => Date, log?: (s: string) => void }} [opts]
*/
export async function runLinkCheck(dir, manifest, opts = {}) {
- const doc = await checkLinks(linksOf(manifest), opts);
+ const doc = await checkLinks(linksOf(manifest), { siteIdOf: await projectSiteIdOf(dir, manifest), ...opts });
const file = linksFile(dir);
await mkdir(path.dirname(file), { recursive: true });
const tmp = `${file}.tmp-${process.pid}`;
diff --git a/umtool/lib/report/linksCli.mjs b/umtool/lib/report/linksCli.mjs
@@ -13,7 +13,8 @@ import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
import { readManifest } from "../projects/report.mjs";
import { kindMakesTakes } from "../projects/kinds.mjs";
import { withEditNotes } from "./edit-guard.mjs";
-import { updateClip } from "./manifest.mjs";
+import { AUTO_SNAPSHOT_PREFIX, updateClip } from "./manifest.mjs";
+import { createSnapshot } from "./snapshots.mjs";
import { runLinkCheck } from "./linkCheck.mjs";
export const LINKS_USAGE = [
@@ -79,9 +80,21 @@ export async function linksCommand(args, { root = REPORTS_ROOT, out = (s) => con
if (!m) throw new CliError(`${project.id} has no video.manifest.json`);
let doc = await runLinkCheck(project.dir, m, opts);
const fixed = [];
+ let undo = null;
if (flags.has("--fix")) {
+ // ONE undo point before the rewrites (revisions/<stamp>-auto-before-links-fix): `umtool timeline <p> undo` takes them all back.
+ if (doc.links.some((l) => l.state === "dead" && l.fix)) undo = await createSnapshot(project.dir, { label: `${AUTO_SNAPSHOT_PREFIX}links-fix` });
for (const l of doc.links) {
if (l.state !== "dead" || !l.fix) continue;
+ // A Rumble folder id (linkCheck.mjs siteIdOf): the clip names the embed id the archive serves (`siteVideo`),
+ // and a citeUrl that was the dead link moves with it; a QR built from the moment needs nothing else.
+ if (l.fixSiteVideo) {
+ const e = (m.timeline ?? []).find((x) => x?.id === l.clip);
+ const patch = { siteVideo: l.fixSiteVideo, ...(e?.citeUrl === l.url ? { citeUrl: l.fix } : {}) };
+ await withEditNotes(project, () => updateClip(project.dir, l.clip, patch));
+ fixed.push({ clip: l.clip, from: l.url, to: l.fix, siteVideo: l.fixSiteVideo });
+ continue;
+ }
await withEditNotes(project, () => updateClip(project.dir, l.clip, { citeUrl: l.fix }));
fixed.push({ clip: l.clip, from: l.url, to: l.fix });
}
@@ -92,10 +105,11 @@ export async function linksCommand(args, { root = REPORTS_ROOT, out = (s) => con
}
const dead = doc.links.filter((l) => l.state === "dead").length;
if (flags.has("--json")) {
- out(JSON.stringify({ ok: dead === 0, project: project.id, ...doc, ...(flags.has("--fix") ? { fixed } : {}) }, null, 2));
+ out(JSON.stringify({ ok: dead === 0, project: project.id, ...doc, ...(flags.has("--fix") ? { fixed, ...(undo ? { undo: undo.rel } : {}) } : {}) }, null, 2));
return dead ? 1 : 0;
}
- for (const f of fixed) out(`fixed ${f.clip}: ${f.from} -> ${f.to}`);
+ if (undo) out(`undo point: ${undo.rel}`);
+ for (const f of fixed) out(`fixed ${f.clip}: ${f.from} -> ${f.to}${f.siteVideo ? ` (siteVideo ${f.siteVideo}: the Rumble embed id)` : ""}`);
out(`${project.id} · ${linksSummary(doc)}`);
out(`recorded in out/links.json (umtool check ${project.id} reads it)`);
return dead ? 1 : 0;
diff --git a/umtool/lib/report/look.test.mjs b/umtool/lib/report/look.test.mjs
@@ -46,7 +46,7 @@ const read = async (dir) => JSON.parse(await readFile(path.join(dir, MANIFEST_NA
test("updateRender: the look's keys only, null removes one, the build's checks refuse a bad value", async () => {
const p = await project({ transition: 0.4, crf: 21 });
try {
- assert.deepEqual(LOOK_KEYS, ["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room", "slide", "blur", "intro", "format", "vertical"]);
+ assert.deepEqual(LOOK_KEYS, ["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room", "slide", "blur", "intro", "format", "vertical", "mode", "basic"]);
const token = await manifestToken(p.dir);
const r = await updateRender(p.dir, {
headerHeight: 0, footerHeight: 0, qr: false, transition: 0.5, transitionStyle: "fadeblack",
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -37,7 +37,7 @@ import {
import { validateThreadEntries } from "yt-dlp-transcript-common/lib/report/panels.mjs";
import { validateAssist } from "yt-dlp-transcript-common/lib/clips/assist.mjs";
import { verticalErrors } from "umtool-report-to-video/look";
-import { LOOK_KEYS, applyLookPatch, lookOf } from "yt-dlp-transcript-common/lib/report/look.mjs";
+import { LOOK_KEYS, applyLookPatch, basicOn, lookOf } from "yt-dlp-transcript-common/lib/report/look.mjs";
import { sideErrors } from "yt-dlp-transcript-common/lib/report/vertical.mjs";
import { validateRoom } from "umtool-report-to-video/room";
import { applyVideoPatch, validateVideoEntries, validateVideoEntry } from "umtool-report-to-video/video-entry";
@@ -455,6 +455,16 @@ export function patchClipEntry(manifest, clipId, patch, { edit = "trim", now = n
}
}
+ // The id the ARCHIVE serves the recording under, when it is not the clip's
+ // `video` (a Rumble URL-slug directory's embed id: shareLine.mjs siteVideoFor,
+ // `umtool links --fix`). Empty removes it.
+ if (patch.siteVideo !== undefined) {
+ const v = String(patch.siteVideo ?? "").trim();
+ if (!v) delete entry.siteVideo;
+ else if (!/^[A-Za-z0-9._-]{1,128}$/.test(v)) throw new Error(`siteVideo must be a recording id (letters, digits, . _ -), not \`${v}\``);
+ else entry.siteVideo = v;
+ }
+
// ---- the CUT, inside the extent ------------------------------------------
//
// `start`/`end` is the reviewed EXTENT -- how much of this recording is
@@ -1588,32 +1598,95 @@ export function effectiveManifest(manifest) {
}
/**
+ * Every leaf path a render block sets: objects walked, an array or a scalar a
+ * leaf (`[["chrome","deck","qr","links"], ["palette","bg"], …]`). Pure.
+ * @param {unknown} obj
+ * @param {string[]} [at]
+ * @returns {string[][]}
+ */
+export function leafPaths(obj, at = []) {
+ if (!isObj(obj)) return at.length ? [at] : [];
+ const keys = Object.keys(obj);
+ if (!keys.length) return at.length ? [at] : [];
+ return keys.flatMap((k) => leafPaths(/** @type {Record<string, unknown>} */ (obj)[k], [...at, k]));
+}
+
+/**
+ * `render` less every leaf `preset` sets (preset apply --replace): what the
+ * manifest set over the preset's keys goes, so the preset's value is the one
+ * that renders; an object left empty goes too. `cleared` names each path
+ * removed (`render.<path>`). Pure: returns a copy.
+ * @param {Record<string, any>} render
+ * @param {Record<string, any>} presetRender
+ */
+export function renderLessPreset(render, presetRender) {
+ const out = structuredClone(isObj(render) ? render : {});
+ const cleared = [];
+ for (const p of leafPaths(presetRender)) {
+ // The deepest node that exists along the path is the one cleared (a scalar where the preset has an object).
+ let node = out;
+ let i = 0;
+ for (; i < p.length - 1; i += 1) {
+ if (!isObj(node[p[i]])) break;
+ node = node[p[i]];
+ }
+ const key = p[i];
+ if (!Object.hasOwn(node, key)) continue;
+ delete node[key];
+ cleared.push(`render.${p.slice(0, i + 1).join(".")}`);
+ // Prune the objects this left empty, deepest first.
+ for (let j = i - 1; j >= 0; j -= 1) {
+ const parent = p.slice(0, j).reduce((o, k) => o[k], out);
+ if (isObj(parent[p[j]]) && !Object.keys(parent[p[j]]).length) delete parent[p[j]];
+ else break;
+ }
+ }
+ return { render: out, cleared: [...new Set(cleared)] };
+}
+
+/**
* Name, change or remove the cut's look preset (`preset`, presets.mjs): the
* base layer the build lays under its render block. `null` removes it. The
* preset must exist, and the cut over it must build: its chrome checked as
- * updateChrome checks it. Nothing of the preset is copied into the manifest.
+ * updateChrome checks it -- unless the cut renders basic (render.mode, the
+ * footage alone: the chrome is not drawn, so it is not checked). Nothing of
+ * the preset is copied into the manifest.
+ *
+ * `replace` (`umtool preset apply <name> <p> --replace`): the manifest's own
+ * value of every key the preset sets is CLEARED, so the preset's renders --
+ * after an undo point (createSnapshot, `revisions/<stamp>-auto-before-preset-replace`).
+ * `cleared` names what went.
*
* @param {string} dir
* @param {string | null} name
- * @param {{ token?: string | null }} [opts]
- * @returns {Promise<{ preset: string | null, token: string | null }>}
+ * @param {{ token?: string | null, replace?: boolean }} [opts]
+ * @returns {Promise<{ preset: string | null, token: string | null, cleared?: string[], snapshot?: { rel: string, name: string } | null }>}
*/
-export async function updatePreset(dir, name, { token = null } = {}) {
- if (name !== null) loadPreset(name);
+export async function updatePreset(dir, name, { token = null, replace = false } = {}) {
+ const preset = name !== null ? loadPreset(name) : null;
+ if (replace && !preset) throw new Error("--replace clears the keys a preset sets: name the preset");
return withManifestLock(async () => {
const current = await manifestToken(dir);
if (token !== null && current !== token) throw new StaleToken(token, current);
const manifest = JSON.parse(await readFile(manifestFile(dir), "utf8"));
if (name === null) delete manifest.preset;
else manifest.preset = name;
+ let cleared = [];
+ if (replace && preset) {
+ const r = renderLessPreset(manifest.render ?? {}, preset.render);
+ manifest.render = r.render;
+ cleared = r.cleared;
+ }
const seen = effectiveManifest(manifest);
const { chrome, ...rest } = seen.render ?? {};
- if (chrome !== undefined && chrome !== null) {
+ if (chrome !== undefined && chrome !== null && !basicOn(seen.render)) {
const errors = [...validateChrome(chrome, rest), ...validateDeckMarkers(seen), ...validateDeckClaims(seen), ...storyClipErrors(seen)];
if (errors.length) throw new ChromeRefused(errors);
}
+ // The undo point, once the write is known to go through: the file as it still is.
+ const snapshot = replace ? await createSnapshot(dir, { label: `${AUTO_SNAPSHOT_PREFIX}preset-replace` }) : null;
const nextToken = await writeManifestAtomic(dir, manifest);
- return { preset: manifest.preset ?? null, token: nextToken };
+ return { preset: manifest.preset ?? null, token: nextToken, ...(replace ? { cleared, snapshot } : {}) };
});
}
diff --git a/umtool/lib/report/modulesCli.mjs b/umtool/lib/report/modulesCli.mjs
@@ -45,13 +45,15 @@ export const PRESET_USAGE = [
"usage: umtool preset list [--json]",
" umtool preset show <name> [--json]",
" umtool preset save <name> --from <project> [--description D] [--force]",
- " umtool preset apply <name|none> <project>",
+ " umtool preset apply <name|none> <project> [--replace] [--json]",
"",
"A look preset (umtool/presets/<name>.json) is a render block a manifest stands on: `\"preset\": \"<name>\"`",
"at the manifest's top level lays it UNDER the manifest -- preset → manifest → style → take patch, each",
"a JSON merge patch over the one before. save keeps a project's look and leaves its content out (its",
"claim checks, markers, counter series, finale stats, the story modules' lists); apply names the preset",
- "on the cut (nothing of it is copied in), refused when the cut over it would not build.",
+ "on the cut (nothing of it is copied in), refused when the cut over it would not build. --replace also CLEARS",
+ "the manifest's own value of every key the preset sets (an undo point first, revisions/…-auto-before-preset-replace),",
+ "so the preset's renders. Built in: plain-deck, huck-deck, ember-deck, archive-catalog, basic (the footage alone).",
].join("\n");
class CliError extends Error {}
@@ -245,9 +247,17 @@ export async function presetCommand(args, { reportsRoot = REPORTS_ROOT, log = co
if (sub === "apply") {
if (!a || !b) throw new CliError("preset apply <name|none> <project>");
const project = await pickProject(b, reportsRoot);
- const r = await updatePreset(project.dir, a === "none" ? null : a);
+ const replace = p.has("--replace");
+ if (replace && a === "none") throw new CliError("--replace clears the keys a preset sets: name one, not none");
+ const r = await updatePreset(project.dir, a === "none" ? null : a, { replace });
if (json) log(JSON.stringify({ project: project.id, ...r }, null, 2));
- else log(r.preset ? `${project.id} stands on the preset ${r.preset}` : `${project.id} stands on no preset`);
+ else {
+ log(r.preset ? `${project.id} stands on the preset ${r.preset}` : `${project.id} stands on no preset`);
+ if (replace) {
+ log(r.cleared?.length ? `cleared the manifest's own ${r.cleared.join(", ")} (the preset's renders)` : "the manifest set none of the preset's keys: nothing cleared");
+ if (r.snapshot?.rel) log(`undo point: ${r.snapshot.rel}`);
+ }
+ }
return 0;
}
throw new CliError(`unknown preset command "${sub}" — list, show, save or apply`);
diff --git a/umtool/lib/report/modulesCli.test.mjs b/umtool/lib/report/modulesCli.test.mjs
@@ -85,7 +85,7 @@ test("modules list and preset list", async () => {
for (const id of ["pair", "chapter", "status", "finale", "intro"]) assert.ok(ids.includes(id), id);
const t = sink();
assert.equal(await presetCommand(["list", "--json"], t), 0);
- assert.deepEqual(JSON.parse(t.lines[0]).map((p) => p.name).sort(), ["archive-catalog", "ember-deck", "huck-deck", "plain-deck"]);
+ assert.deepEqual(JSON.parse(t.lines[0]).map((p) => p.name).sort(), ["archive-catalog", "basic", "ember-deck", "huck-deck", "plain-deck"]);
});
test("umtool look takes the story modules' keys, through updateChrome", async () => {
diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs
@@ -11,6 +11,7 @@
import { DEFAULT_VARIANT, selectVariant } from "umtool-report-to-video/build-video";
import { deckOn, estimatedDuration, estimateSchedule, scheduleFrom, transitionOf } from "umtool-report-to-video/deck";
import { resolveFactcheck } from "umtool-report-to-video/factcheck";
+import { basicOn, basicSpans } from "umtool-report-to-video/basic";
import { channelsDirFor, clipDateKey, readManifest } from "../projects/report.mjs";
import { rejectionOf } from "./rejectReasons.mjs";
import { dateKeyLabel } from "./playCut.mjs";
@@ -168,10 +169,13 @@ export async function playViewWith(project, { take = null, bare = false, postFor
}
const selected = selectVariant(manifest, DEFAULT_VARIANT);
const render = selected.render ?? {};
+ // THE BASIC OUTPUT MODE (render.mode, report-to-video basic.mjs): Play plays what the basic render cuts --
+ // the clips alone, their spans exactly (no lead-in), hard cuts, nothing drawn over the footage.
+ const basic = basicOn(render);
const post = postFor ? await postFor(selected) : null;
- const timeline = (selected.timeline ?? []).filter((e) => e && typeof e.id === "string");
- const D = transitionOf(render);
- const durs = timeline.map((e) => estimatedDuration(e, render, D));
+ const timeline = (selected.timeline ?? []).filter((e) => e && typeof e.id === "string" && (!basic || e.type === "clip"));
+ const D = basic ? 0 : transitionOf(render);
+ const durs = timeline.map((e) => (basic ? Math.max(0.5, basicSpans(e, render).reduce((n, x) => n + x.to - x.from, 0)) : estimatedDuration(e, render, D)));
const { starts } = scheduleFrom(durs, D);
const segments = timeline.map((e, i) => ({ id: e.id, start: Math.round(starts[i] * 1000) / 1000, duration: Math.round(durs[i] * 1000) / 1000 }));
const cache = await projectCache(project, manifest);
@@ -284,10 +288,12 @@ export async function playViewWith(project, { take = null, bare = false, postFor
note,
takes: await playableTakes(project.dir),
working,
- leadIn: fin(render.leadIn) ? render.leadIn : 0.4,
+ leadIn: basic ? 0 : fin(render.leadIn) ? render.leadIn : 0.4,
transition: D,
blurRendered: render.blur !== "off",
- deckOn: deckOn(render),
+ deckOn: !basic && deckOn(render),
+ // A basic cut (render.mode "basic"): the footage alone -- Play draws nothing over it.
+ basic,
segments,
entries,
};
diff --git a/umtool/lib/report/presetReplace.test.mjs b/umtool/lib/report/presetReplace.test.mjs
@@ -0,0 +1,92 @@
+// The basic preset and `umtool preset apply --replace` (lane output-modes):
+// the built-in `basic` is one key, render.mode; --replace clears the
+// manifest's own value of every key a preset sets, after an undo point, so the
+// preset's renders; the mode a writer sees is the look's (`umtool look <p>
+// mode=basic`), and a basic cut's chrome is not checked. Synthetic.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import { MANIFEST_NAME, leafPaths, renderLessPreset, updatePreset, updateRender } from "./manifest.mjs";
+import { listPresets, loadPreset } from "umtool-report-to-video/presets";
+import { presetCommand } from "./modulesCli.mjs";
+import { lookCommand } from "./knobsCli.mjs";
+
+async function project(doc) {
+ const root = await mkdtemp(path.join(tmpdir(), "umtool-preset-replace-"));
+ const dir = path.join(root, "p");
+ await import("node:fs/promises").then((fs) => fs.mkdir(dir, { recursive: true }));
+ await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(doc, null, 2) + "\n");
+ return { root, dir };
+}
+const read = async (dir) => JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8"));
+const base = (render) => ({ schemaVersion: 1, slug: "p", provenance: { channelSlug: "ch" }, render, timeline: [{ type: "clip", id: "c1", video: "v", start: 1, end: 3 }] });
+
+test("the built-in presets: plain-deck, huck-deck, ember-deck, archive-catalog and basic (render.mode basic, nothing else)", () => {
+ const names = listPresets().map((p) => p.name);
+ for (const n of ["plain-deck", "huck-deck", "ember-deck", "archive-catalog", "basic"]) assert.ok(names.includes(n), n);
+ assert.deepEqual(loadPreset("basic").render, { mode: "basic" });
+});
+
+test("leafPaths and renderLessPreset: every leaf the preset sets goes from the manifest, an emptied object with it", () => {
+ assert.deepEqual(leafPaths({ a: 1, b: { c: 2, d: { e: [1] } }, f: {} }), [["a"], ["b", "c"], ["b", "d", "e"], ["f"]]);
+ const { render, cleared } = renderLessPreset(
+ { mode: "deck", crf: 19, palette: { bg: "#000", accent: "#f00" }, chrome: { deck: { qr: { links: "x" }, markers: [{ after: "c1" }] } }, intro: "boot" },
+ { mode: "basic", palette: { bg: "#111" }, chrome: { deck: { qr: { links: "original", show: true } } }, intro: { style: "boot-dark" } },
+ );
+ assert.deepEqual(render, { crf: 19, palette: { accent: "#f00" }, chrome: { deck: { markers: [{ after: "c1" }] } } }, "the cut's own content stays");
+ assert.deepEqual(cleared.sort(), ["render.chrome.deck.qr.links", "render.intro", "render.mode", "render.palette.bg"]);
+});
+
+test("preset apply basic --replace: an undo point first, the manifest's mode cleared, the cut renders basic; its deck chrome is not checked", async () => {
+ const p = await project(base({ mode: "deck", crf: 21, chrome: { layout: "deck", engine: "hyperframes", deck: { nonsense: true } } }));
+ try {
+ // Without --replace the manifest's own "deck" beats the preset's basic -- and its broken chrome is checked.
+ await assert.rejects(updatePreset(p.dir, "basic"), /nonsense/);
+ const r = await updatePreset(p.dir, "basic", { replace: true });
+ assert.equal(r.preset, "basic");
+ assert.deepEqual(r.cleared, ["render.mode"]);
+ assert.match(r.snapshot.rel, /^revisions\/.*-auto-before-preset-replace\.manifest\.json$/);
+ const m = await read(p.dir);
+ assert.equal(m.preset, "basic");
+ assert.equal(m.render.mode, undefined);
+ assert.equal(m.render.crf, 21);
+ const before = JSON.parse(await readFile(path.join(p.dir, r.snapshot.rel), "utf8"));
+ assert.equal(before.render.mode, "deck", "the undo point is the file as it was");
+ await assert.rejects(updatePreset(p.dir, null, { replace: true }), /name the preset/);
+ } finally {
+ await rm(p.root, { recursive: true, force: true });
+ }
+});
+
+test("umtool preset apply … --replace and umtool look <p> mode=basic|deck, from a terminal", async () => {
+ const p = await project(base({ mode: "deck" }));
+ const lines = [];
+ const opts = { reportsRoot: p.root, log: (s) => lines.push(s), err: (s) => lines.push(s) };
+ try {
+ assert.equal(await presetCommand(["apply", "basic", p.dir, "--replace"], opts), 0);
+ assert.match(lines.join("\n"), /stands on the preset basic[\s\S]*cleared the manifest's own render\.mode[\s\S]*undo point: revisions\//);
+ assert.ok((await readdir(path.join(p.dir, "revisions"))).length >= 1);
+ assert.equal(await presetCommand(["apply", "none", p.dir, "--replace"], opts), 2);
+
+ const out = [];
+ assert.equal(await lookCommand([p.dir, "mode=deck"], { root: p.root, out: (s) => out.push(s), err: (s) => out.push(s) }), 0);
+ assert.equal((await read(p.dir)).render.mode, "deck", "over a preset, deck is written: it must beat the preset's basic");
+ assert.equal(await lookCommand([p.dir, "mode=basic", "basic={\"fade\":{\"video\":0.5}}"], { root: p.root, out: (s) => out.push(s), err: (s) => out.push(s) }), 0);
+ const m = await read(p.dir);
+ assert.equal(m.render.mode, "basic");
+ assert.deepEqual(m.render.basic, { fade: { video: 0.5 } });
+ assert.equal(await lookCommand([p.dir, "mode=plain"], { root: p.root, out: (s) => out.push(s), err: (s) => out.push(s) }), 1);
+ assert.match(out.join("\n"), /render\.mode must be "deck"/);
+ // The writer's door alone: deck on a cut with no preset is no key.
+ await updatePreset(p.dir, null);
+ await updateRender(p.dir, { mode: "deck" });
+ assert.equal((await read(p.dir)).render.mode, undefined);
+ } finally {
+ await rm(p.root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/report/quickClip.mjs b/umtool/lib/report/quickClip.mjs
@@ -0,0 +1,321 @@
+// QUICK CLIP (lane output-modes): one moment of one recording to a shareable
+// mp4 and a share line, in one command --
+//
+// umtool clip <channel>/<video>@<start>-<end> [--snap words] [--title T] [--site <id>] [--folder F] [--json] [--progress ndjson]
+//
+// what was done by hand on 8 Nov (occo-remarks' raw-render.mjs), as a fixed
+// verb over the app's own pieces:
+//
+// 1. a BASIC-mode project (the `umtool new` path, scaffoldReportVideo with the
+// one clip as its timeline; render.mode "basic" written by the look's
+// writer), its slug from --title, else `<channel>-<video>-<start>`, under
+// `<reports>/<folder>/` (default quick-clips);
+// 2. its window ASKED OF THE EDITOR (fetchWindows.mjs: the fetch-windows
+// batch, followed to its end; a Rumble recording is fetched whole -- the
+// editor decides), never fetched here;
+// 3. with `--snap words`, its edges snapped to the words heard there: the
+// editor's transcribe op (`{path, start, end, words: true}`, quote-check's
+// call) over the window, the first word that mostly plays after the start
+// and the last that mostly plays before the end, 0.15 s of breath before
+// and 0.3 s after (quoteCheck.mjs ALIGN_LEAD_S / ALIGN_TAIL_S), never into
+// a neighbouring word -- written as the clip's cut;
+// 4. rendered as a TAKE (`umtool take <p> --id clip --full`: the heavy slot,
+// its render record, the take panel), the basic renderer's spans;
+// 5. the output's path and its SHARE LINE (shareLine.mjs) printed; `--json`
+// prints `{project, output, share: {platform, archive, text}}`.
+//
+// `--site <id>`: the archive the share line links (transcripts/sites/<id>/
+// site.json `siteUrl`); without it, the first public site that carries the
+// channel, else none (the platform's page alone).
+//
+// The app's `POST /api/report/quick-clip` runs exactly this command as one job.
+// Plain ESM: the CLI runs it under bare node.
+import { readdir, readFile, stat } from "node:fs/promises";
+import path from "node:path";
+import { resolveVideoDirId } from "yt-dlp-transcript-common/lib/videoDir-server.mjs";
+import { resolveLocalSource } from "umtool-report-to-video/sources";
+import { CHANNELS_DIR, REPORTS_ROOT, SITES_DIR } from "../paths.mjs";
+import { parseClipSpec } from "./clipEditorModel.mjs";
+import { ALIGN_LEAD_S, ALIGN_TAIL_S } from "./quoteCheck.mjs";
+import { siteVideoFor, shareLineText, projectShareLine } from "./shareLine.mjs";
+
+export const QUICK_CLIP_USAGE = [
+ "usage: umtool clip <channel>/<video>@<start>-<end> [--snap words] [--title T] [--site <id>] [--folder F] [--json] [--progress ndjson]",
+ " one moment to a shareable mp4: a basic-mode project (the footage alone, no deck), its window asked of the",
+ " editor (a Rumble recording fetched whole), --snap words: its edges snapped to the words heard there (the",
+ " editor's transcribe op), rendered as a take (umtool take <p> --id clip --full, the heavy slot), then the",
+ " output's path and the SHARE LINE: the platform's page at the moment, and its moment on the archive.",
+ " --title names the project (else <channel>-<video>-<start>); --folder (default quick-clips); --site <id> the",
+ " archive linked (else the first public site that carries the channel). --json: {project, output, share}.",
+ " The editor: ARCHILYZER_EDITOR_URL (default http://localhost:3001), WORKER_TOKEN (else the editor's env files).",
+].join("\n");
+
+export const QUICK_CLIP_FOLDER = "quick-clips";
+export const QUICK_CLIP_TAKE = "clip";
+/** Seconds either side of the asked edges that are transcribed for --snap words. */
+export const SNAP_PAD_S = 2;
+/** How often the editor's fetch jobs are asked how they are (UMTOOL_FETCH_POLL_MS, as `umtool fetch --wait`). */
+const POLL_MS = Number(process.env.UMTOOL_FETCH_POLL_MS) > 0 ? Number(process.env.UMTOOL_FETCH_POLL_MS) : 5000;
+
+class CliError extends Error {}
+const r2 = (x) => Math.round(Number(x) * 100) / 100;
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+
+/**
+ * A quick clip's spec, parsed and checked: `<channel>/<video>@<start>-<end>`, the end after the start, and
+ * neither id a path trick -- not all dots (`..`) and not starting with `-` (an argv flag) -- so the names
+ * that reach the disk and a child's argv are ids. Null when it is not one. Pure.
+ * @param {unknown} spec
+ */
+export function quickClipSpec(spec) {
+ const c = parseClipSpec(spec);
+ if (!c || !(c.end > c.start)) return null;
+ for (const id of [c.channel, c.video]) if (/^\.+$/.test(id) || id.startsWith("-")) return null;
+ return c;
+}
+
+/** A project slug from words: lower-case letters, digits and dashes, at most 48, never `share-…` (a deliverables link's name). */
+export function quickClipSlug({ title = null, channel, video, start }) {
+ const clean = (words) => String(words).toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48).replace(/-+$/, "");
+ let slug = clean(title ?? "") || clean(`${channel}-${video}-${Math.floor(Number(start) || 0)}`) || "clip";
+ if (slug.startsWith("share-")) slug = `clip-${slug}`;
+ return slug;
+}
+
+/**
+ * The cut snapped to the words heard: the first word whose middle is at or after
+ * `start`, the last whose middle is at or before `end`; a breath before and a
+ * ring after, never into the word either side. `null` when no word is inside.
+ * Words are `{w|text, start, end}` on the CUE clock. Pure.
+ *
+ * @param {{ start: number, end: number, w?: string, text?: string }[]} words
+ * @param {number} start
+ * @param {number} end
+ * @param {{ lead?: number, tail?: number }} [o]
+ * @returns {null | { cutStart: number, cutEnd: number, first: string, last: string }}
+ */
+export function snapToWords(words, start, end, { lead = ALIGN_LEAD_S, tail = ALIGN_TAIL_S } = {}) {
+ const ws = (words ?? []).filter((w) => fin(w?.start) && fin(w?.end) && w.end >= w.start).sort((a, b) => a.start - b.start);
+ const mid = (w) => (w.start + w.end) / 2;
+ const i = ws.findIndex((w) => mid(w) >= start);
+ let j = -1;
+ for (let k = ws.length - 1; k >= 0; k -= 1) if (mid(ws[k]) <= end) { j = k; break; }
+ if (i < 0 || j < 0 || j < i) return null;
+ const prev = ws[i - 1];
+ const next = ws[j + 1];
+ const cutStart = r2(Math.max(prev ? prev.end : -Infinity, ws[i].start - lead, 0));
+ const cutEnd = r2(Math.min(next ? next.start : Infinity, ws[j].end + tail));
+ if (!(cutEnd > cutStart)) return null;
+ const say = (w) => String(w.w ?? w.text ?? "").trim();
+ return { cutStart, cutEnd, first: say(ws[i]), last: say(ws[j]) };
+}
+
+/** The first public site (a `siteUrl`) whose channels carry `slug`, as its origin; null for none. */
+export async function siteOriginFor(slug, { sitesDir = SITES_DIR } = {}) {
+ let ids;
+ try {
+ ids = (await readdir(sitesDir)).sort();
+ } catch {
+ return null;
+ }
+ for (const id of ids) {
+ const site = await readFile(path.join(/* turbopackIgnore: true */ sitesDir, id, "site.json"), "utf8").then(JSON.parse, () => null);
+ if (!site || typeof site.siteUrl !== "string" || !/^https?:\/\//.test(site.siteUrl.trim())) continue;
+ const pool = [...(Array.isArray(site.channels) ? site.channels.map((c) => (typeof c === "string" ? c : c?.slug)) : []), ...(Array.isArray(site.citedChannels) ? site.citedChannels : [])];
+ if (pool.includes(slug)) return site.siteUrl.trim().replace(/\/+$/, "");
+ }
+ return null;
+}
+
+/** A site's public origin by its id (`--site`): its site.json `siteUrl`, or a sentence why not. */
+export async function siteOriginOf(id, { sitesDir = SITES_DIR } = {}) {
+ if (!/^[a-z0-9][a-z0-9._-]*$/i.test(String(id))) throw new CliError(`--site ${id}: a site's id (transcripts/sites/<id>)`);
+ const site = await readFile(path.join(/* turbopackIgnore: true */ sitesDir, String(id), "site.json"), "utf8").then(JSON.parse, () => null);
+ if (!site) throw new CliError(`--site ${id}: no ${path.join(sitesDir, String(id), "site.json")}`);
+ if (typeof site.siteUrl !== "string" || !/^https?:\/\//.test(site.siteUrl.trim())) throw new CliError(`--site ${id}: its site.json has no public siteUrl`);
+ return site.siteUrl.trim().replace(/\/+$/, "");
+}
+
+/** Ask the editor for the project's windows and follow its jobs to the end. Throws on a window it did not fetch. */
+async function fetchThroughEditor(project, { cfg, pollMs, say }) {
+ const fw = await import("./fetchWindows.mjs");
+ const { body, skipped } = await fw.projectFetchBody(project, { reason: "quick clip", localIds: true });
+ if (!body.items.length) throw new Error(`nothing to fetch: ${skipped.map((s) => `${s.clipId} (${s.why})`).join(", ") || "the clip has no window"}`);
+ const answer = await fw.postFetchWindows(cfg, body);
+ const run = await fw.recordFetchRun(project.dir, { body, answer });
+ const s = fw.summarizeAnswer(answer);
+ if (s.unresolved.length) throw new Error(`the editor could not resolve ${s.unresolved.map((u) => `${u.clipId}: ${u.error}`).join("; ")}`);
+ if (s.refused.length) throw new Error(`the editor refused ${s.refused.map((r) => `${r.platform}: ${r.error}`).join("; ")}`);
+ say(s.jobs.length ? `asked the editor: ${s.jobs.map((j) => `job ${j.jobId} (${j.platform}, ${j.items} window(s))`).join(", ")}` : `the window is on disk already (${s.cached.join(", ") || "cached"})`);
+ for (let polls = 0; s.jobs.length || s.inFlight.length; polls += 1) {
+ const doc = await fw.readFetchRuns(project.dir);
+ const mine = doc.runs.find((x) => x.at === run.at && x.bodyHash === run.bodyHash) ?? run;
+ const states = await fw.followRun(cfg, project.dir, { ...mine, jobIds: [...(mine.jobIds ?? []), ...s.inFlight.map((f) => f.jobId)] });
+ if (states.every((st) => fw.TERMINAL.has(st.status))) {
+ const bad = states.filter((st) => st.status !== "done" || st.failed?.length);
+ if (bad.length) throw new Error(`the editor's fetch did not land the window: ${bad.map((b) => `job ${b.jobId} ${b.status}${b.failed?.length ? ` (${b.failed.map((f) => `${f.class}: ${f.message}`).join("; ")})` : ""}`).join(", ")}`);
+ say("the window is on disk");
+ return;
+ }
+ if (polls % 6 === 0) say(states.map((st) => `job ${st.jobId}: ${st.status}${st.queue?.position ? ` (queued, position ${st.queue.position})` : ""}`).join(", "));
+ await new Promise((r) => setTimeout(r, pollMs));
+ }
+}
+
+/** The editor's words over a file's span, on the file's clock (quote-check's call). */
+async function editorWords({ path: file, start, end, out }, { emit = () => {} } = {}) {
+ const { askEditorOp } = await import("umtool-report-to-video/narrate-via-editor");
+ await askEditorOp("/api/ops/transcribe", { path: file, start, end, words: true, out }, { emit });
+ const doc = JSON.parse(await readFile(out, "utf8"));
+ return Array.isArray(doc.words) ? doc.words : [];
+}
+
+/**
+ * Quick clip, start to end. Everything that talks to the editor or renders is
+ * a dependency, so a test runs the flow over its own stubs.
+ *
+ * @param {{ spec: string, snap?: "words" | null, title?: string | null, site?: string | null, folder?: string | null }} ask
+ * @param {{ root?: string, channelsDir?: string, sitesDir?: string, say?: (s: string) => void, cfg?: any, pollMs?: number, progress?: string | null,
+ * log?: (s: string) => void, err?: (s: string) => void,
+ * deps?: { fetch?: (project: { id: string, dir: string }) => Promise<void>, transcribe?: typeof editorWords, take?: (args: string[], o: any) => Promise<number>, resolve?: typeof resolveLocalSource } }} [o]
+ * @returns {Promise<{ project: string, dir: string, output: string, snapped: null | { cutStart: number, cutEnd: number, first: string, last: string }, share: { platform: string | null, archive: string | null, text: string } }>}
+ */
+export async function quickClip(ask, { root = REPORTS_ROOT, channelsDir = CHANNELS_DIR, sitesDir = SITES_DIR, say = () => {}, cfg = null, pollMs = POLL_MS, progress = null, log = console.log, err = console.error, deps = {} } = {}) {
+ const spec = quickClipSpec(ask.spec);
+ if (!spec) throw new CliError(`"${ask.spec}" is not <channel>/<video>@<start>-<end> (seconds, the end after the start; ids, not "." or "-…")`);
+ if (ask.snap && ask.snap !== "words") throw new CliError(`--snap ${ask.snap}: words is the one snap`);
+ // The recording as the corpus keeps it (a Rumble embed id: its URL-slug folder), and the id the archive serves.
+ const video = await resolveVideoDirId(channelsDir, spec.channel, spec.video).catch(() => spec.video);
+ const siteVideo = await siteVideoFor({ channelsDir, slug: spec.channel, video });
+ const origin = ask.site ? await siteOriginOf(ask.site, { sitesDir }) : await siteOriginFor(spec.channel, { sitesDir });
+
+ // 1. The project: the `umtool new` path, one clip, the footage alone.
+ const { scaffoldReportVideo } = await import("../projects/scaffold.mjs");
+ const folder = ask.folder ?? QUICK_CLIP_FOLDER;
+ const base = quickClipSlug({ title: ask.title, channel: spec.channel, video: spec.video, start: spec.start });
+ let slug = base;
+ for (let n = 2; await stat(path.join(root, folder, slug)).then(() => true, () => false); n += 1) slug = `${base}-${n}`;
+ const clip = {
+ type: "clip", id: "c01", channel: spec.channel, video, start: r2(spec.start), end: r2(spec.end), cite: Math.floor(spec.start),
+ ...(siteVideo ? { siteVideo } : {}),
+ };
+ const made = await scaffoldReportVideo({
+ root, slug, folder, title: String(ask.title ?? "").trim() || `${spec.channel}/${spec.video} at ${Math.floor(spec.start)} s`,
+ siteOrigin: origin, channelsDir, timeline: [clip],
+ });
+ const project = { id: made.id, dir: made.dir };
+ // A quick clip that fails after this point takes its project with it: a retry makes it afresh under the same
+ // name, never a pile of half-made `-2`, `-3` beside it. What failed is in the error.
+ try {
+ const { updateRender } = await import("./manifest.mjs");
+ await updateRender(project.dir, { mode: "basic" });
+ say(`project ${project.id} (basic: the footage alone)${origin ? `, archive ${origin}` : ""}`);
+
+ // 2. The window, asked of the editor.
+ if (deps.fetch) await deps.fetch(project);
+ else {
+ const fw = await import("./fetchWindows.mjs");
+ await fetchThroughEditor(project, { cfg: cfg ?? fw.editorConfig(), pollMs, say });
+ }
+
+ // 3. --snap words: the edges to the words heard.
+ let snapped = null;
+ if (ask.snap === "words") {
+ const from = Math.max(0, spec.start - SNAP_PAD_S);
+ const to = spec.end + SNAP_PAD_S;
+ // ONE CLOCK PER RECORDING: the build's lookup (resolveLocalSource) maps the span through a saved recording's
+ // time map (clock.json, common recordingClock.mjs) -- its windowStart is the CUE second the file's 0 plays --
+ // so the span is asked on the file's clock and the words come back onto the cues', as quote-check does.
+ const src = await (deps.resolve ?? resolveLocalSource)({ video, slug: spec.channel, from, to }, { rawDir: path.join(project.dir, "out", "clips-raw"), channelsDir });
+ if (!src) throw new Error(`--snap words: no window on disk holds ${from.toFixed(2)}–${to.toFixed(2)} (the fetch landed a narrower one?)`);
+ if (src.clock && !src.clock.certain) say(`--snap words: ${path.basename(src.path)}'s clock is NOT certain over this span (a step in its time map) -- check the words land (umtool quote-check)`);
+ const { mkdir } = await import("node:fs/promises");
+ const work = path.join(project.dir, "out", "quick-clip");
+ await mkdir(work, { recursive: true });
+ const a = Math.max(from, src.windowStart);
+ const b = Math.min(to, src.windowEnd);
+ const words = await (deps.transcribe ?? editorWords)({ path: src.path, start: r2(a - src.windowStart), end: r2(b - src.windowStart), out: path.join(work, "words.json") });
+ const heard = words.map((w) => ({ w: w.w ?? w.text, start: w.start + src.windowStart, end: w.end + src.windowStart }));
+ snapped = snapToWords(heard, spec.start, spec.end);
+ if (!snapped) say("--snap words: no word heard inside the edges -- they stay as asked");
+ else {
+ const { updateClip } = await import("./manifest.mjs");
+ await updateClip(project.dir, "c01", {
+ start: r2(Math.min(spec.start, snapped.cutStart)), end: r2(Math.max(spec.end, snapped.cutEnd)), cutStart: snapped.cutStart, cutEnd: snapped.cutEnd,
+ });
+ say(`snapped to the words: ${snapped.cutStart}–${snapped.cutEnd} ("${snapped.first}" … "${snapped.last}")`);
+ }
+ }
+
+ // 4. The render, as a take: the heavy slot, the record, the take panel.
+ const take = deps.take ?? (await import("./takeCli.mjs")).takeCommand;
+ const code = await take([project.id, "--id", QUICK_CLIP_TAKE, "--label", "Quick clip", "--full", ...(progress ? ["--progress", progress] : [])], { reportsRoot: root, log, err });
+ if (code !== 0) throw new Error(`the render failed (umtool take ${project.id} --id ${QUICK_CLIP_TAKE} exited ${code}; its record: umtool take status ${project.id} --id ${QUICK_CLIP_TAKE})`);
+ const { takesDirOf } = await import("./takes.mjs");
+ const output = path.join(takesDirOf(project.dir), QUICK_CLIP_TAKE, "preview.mp4");
+
+ // 5. The share line.
+ const share = await projectShareLine(project, { clip: "c01" });
+ return { project: project.id, dir: project.dir, output, snapped, share: { platform: share.platform, archive: share.archive, text: share.text || shareLineText(share) } };
+ } catch (e) {
+ const { rm } = await import("node:fs/promises");
+ await rm(project.dir, { recursive: true, force: true }).catch(() => {});
+ say(`removed the half-made project ${project.id}`);
+ throw e;
+ }
+}
+
+/**
+ * `umtool clip …`
+ * @param {string[]} args the words after `clip`
+ * @param {{ root?: string, log?: (s: string) => void, err?: (s: string) => void, deps?: any, cfg?: any, pollMs?: number, channelsDir?: string, sitesDir?: string }} [o]
+ * @returns {Promise<number>}
+ */
+export async function quickClipCommand(args, { root = REPORTS_ROOT, log = console.log, err = console.error, ...rest } = {}) {
+ const valued = new Set(["--snap", "--title", "--site", "--folder", "--progress"]);
+ const flags = new Map();
+ const words = [];
+ try {
+ for (let i = 0; i < args.length; i += 1) {
+ const a = args[i];
+ if (!a.startsWith("--")) words.push(a);
+ else if (valued.has(a)) {
+ if (i + 1 >= args.length) throw new CliError(`${a} needs a value`);
+ flags.set(a, args[++i]);
+ } else if (a === "--json" || a === "--help") flags.set(a, true);
+ else throw new CliError(`unknown flag ${a}`);
+ }
+ if (flags.has("--help")) {
+ log(QUICK_CLIP_USAGE);
+ return 0;
+ }
+ if (words.length !== 1) throw new CliError(QUICK_CLIP_USAGE);
+ const progress = flags.get("--progress") ?? null;
+ if (progress && progress !== "ndjson") throw new CliError("--progress takes ndjson");
+ const json = flags.has("--json");
+ const ndjson = progress === "ndjson";
+ // Under NDJSON, stdout is events only; the prose goes to stderr.
+ const say = ndjson ? (s) => log(JSON.stringify({ ev: "quick-clip-step", message: s })) : json ? (s) => err(s) : (s) => log(s);
+ const r = await quickClip(
+ { spec: words[0], snap: flags.get("--snap") ?? null, title: flags.get("--title") ?? null, site: flags.get("--site") ?? null, folder: flags.get("--folder") ?? null },
+ { root, say, progress, log: ndjson || !json ? log : err, err, ...rest },
+ );
+ const doc = { project: r.project, output: r.output, share: r.share, ...(r.snapped ? { snapped: r.snapped } : {}) };
+ if (ndjson) log(JSON.stringify({ ev: "quick-clip", ...doc }));
+ else if (json) log(JSON.stringify(doc, null, 2));
+ else {
+ log(r.output);
+ log(r.share.text ? `share: ${r.share.text}` : "share: (no platform page or archive to link)");
+ }
+ return 0;
+ } catch (e) {
+ if (e instanceof CliError) {
+ err(e.message);
+ return 2;
+ }
+ const message = e instanceof Error ? e.message : String(e);
+ if (flags.get("--progress") === "ndjson") log(JSON.stringify({ ev: "quick-clip-failed", error: message }));
+ err(message);
+ return 1;
+ }
+}
diff --git a/umtool/lib/report/quickClip.test.mjs b/umtool/lib/report/quickClip.test.mjs
@@ -0,0 +1,167 @@
+// Quick clip (lane output-modes): `umtool clip <ch>/<vid>@<s>-<e>` -- a
+// basic-mode project, its window asked of the editor, the edges snapped to the
+// words heard, rendered as a take, the output and its share line. The editor
+// and the render are the flow's dependencies, stubbed here; e2e
+// (basic-mode.spec.ts) runs it whole against the stub editor. Synthetic.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
+import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+const ROOT = mkdtempSync(path.join(tmpdir(), "umtool-quick-"));
+const CORPUS = path.join(ROOT, "channels");
+const SITES = path.join(ROOT, "sites");
+const REPORTS = path.join(ROOT, "reports");
+process.env.CHANNELS_DIR = CORPUS;
+process.env.SITES_DIR = SITES;
+process.env.CHANNELS_FALLBACK = "0";
+
+const { quickClip, quickClipCommand, quickClipSlug, quickClipSpec, siteOriginFor, snapToWords } = await import("./quickClip.mjs");
+const { shareCommand } = await import("./shareLineCli.mjs");
+
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+const have = spawnSync("ffmpeg", ["-version"]).status === 0;
+
+const json = (file, doc) => {
+ mkdirSync(path.dirname(file), { recursive: true });
+ writeFileSync(file, JSON.stringify(doc));
+};
+json(path.join(CORPUS, "yt", "config.json"), { platform: "youtube", url: "https://www.youtube.com/@yt" });
+json(path.join(CORPUS, "yt", "data", "vid1", "transcript.cues.json"), { webpageUrl: "https://www.youtube.com/watch?v=vid1", cues: [{ start: 40, end: 60, text: "words" }] });
+json(path.join(SITES, "a-site", "site.json"), { siteUrl: "https://a-site.example/", channels: [{ slug: "yt" }] });
+json(path.join(SITES, "private", "site.json"), { channels: [{ slug: "yt" }] });
+
+test("quickClipSlug: the title's words, else <channel>-<video>-<start>; never a share- name", () => {
+ assert.equal(quickClipSlug({ title: "Momma Occo's remarks!", channel: "c", video: "v", start: 1 }), "momma-occo-s-remarks");
+ assert.equal(quickClipSlug({ channel: "MommaOcco", video: "n8G_ysDV2bA", start: 4132.5 }), "mommaocco-n8g-ysdv2ba-4132");
+ assert.equal(quickClipSlug({ title: "Share this", channel: "c", video: "v", start: 1 }), "clip-share-this");
+ assert.equal(quickClipSlug({ title: "!!!", channel: "c", video: "v", start: 1 }), "c-v-1");
+});
+
+test("snapToWords: the first word mostly after the start, the last mostly before the end; a breath, never into a neighbour", () => {
+ const words = [
+ { w: "before", start: 9.0, end: 9.6 },
+ { w: "half", start: 9.8, end: 10.4 }, // mid 10.1: after 10.0, so the first
+ { w: "middle", start: 11, end: 12 },
+ { w: "last", start: 19.5, end: 19.9 }, // mid 19.7 ≤ 20
+ { w: "over", start: 19.95, end: 20.6 }, // mid 20.27 > 20: out
+ ];
+ const s = snapToWords(words, 10, 20);
+ assert.deepEqual(s, { cutStart: 9.65, cutEnd: 19.95, first: "half", last: "last" }, "0.15 s lead, the tail stopped at the next word");
+ assert.deepEqual(snapToWords([{ text: "solo", start: 5, end: 6 }], 4, 7), { cutStart: 4.85, cutEnd: 6.3, first: "solo", last: "solo" });
+ assert.equal(snapToWords([], 1, 2), null);
+ assert.equal(snapToWords([{ w: "x", start: 30, end: 31 }], 1, 2), null, "no word inside");
+});
+
+test("quickClipSpec: a spec of ids -- never `..`, never a leading `-`, the end after the start", () => {
+ assert.deepEqual(quickClipSpec("yt/vid1@40-60.5"), { channel: "yt", video: "vid1", start: 40, end: 60.5 });
+ for (const bad of ["../vid@1-2", "../..@1-2", "./x@1-2", "-rf/x@1-2", "yt/..@1-2", "yt/-x@1-2", "yt/v@5-2", "yt/v@5-5", "yt/v", "yt/v@a-b"]) assert.equal(quickClipSpec(bad), null, bad);
+ assert.deepEqual(quickClipSpec("a.b/v.1@1-2"), { channel: "a.b", video: "v.1", start: 1, end: 2 }, "a dot inside an id is fine");
+});
+
+test("siteOriginFor: the first public site that carries the channel", async () => {
+ assert.equal(await siteOriginFor("yt"), "https://a-site.example");
+ assert.equal(await siteOriginFor("nobody"), null);
+});
+
+test("quickClip: a basic project, the window asked, the edges snapped, the take rendered, the share line", { skip: !have && "no ffmpeg" }, async () => {
+ const asked = [];
+ const deps = {
+ // The editor's fetch, stubbed: the window it would land, in the corpus.
+ fetch: async (project) => {
+ const m = JSON.parse(await readFile(path.join(project.dir, "video.manifest.json"), "utf8"));
+ asked.push({ fetch: project.id, mode: m.render.mode, clip: m.timeline[0] });
+ const dir = path.join(CORPUS, "yt", "data", "vid1", "clips");
+ await mkdir(dir, { recursive: true });
+ const r = spawnSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=gray:s=160x90:r=10:d=26", "-f", "lavfi", "-i", "sine=duration=26", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", path.join(dir, "37.00-63.00.mp4")]);
+ assert.equal(r.status, 0, String(r.stderr));
+ },
+ // The editor's words, on the FILE's clock (the window starts at 37).
+ transcribe: async (req) => {
+ asked.push({ transcribe: req });
+ return [{ w: "so", start: 2.5, end: 2.9 }, { w: "anyway", start: 3.2, end: 3.8 }, { w: "done", start: 22.5, end: 22.9 }, { w: "next", start: 23.4, end: 23.9 }];
+ },
+ take: async (args, o) => {
+ asked.push({ take: args });
+ const dir = path.join(REPORTS, "quick-clips", args[0].split("/").pop(), "takes", "clip");
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "preview.mp4"), "mp4");
+ assert.equal(o.reportsRoot, REPORTS);
+ return 0;
+ },
+ };
+ const r = await quickClip({ spec: "yt/vid1@40-60", snap: "words", title: "A quick one" }, { root: REPORTS, channelsDir: CORPUS, sitesDir: SITES, deps });
+ assert.equal(r.project, "quick-clips/a-quick-one");
+ assert.equal(r.output, path.join(REPORTS, "quick-clips", "a-quick-one", "takes", "clip", "preview.mp4"));
+ assert.equal(asked[0].mode, "basic", "the project is basic before its window is asked for");
+ assert.deepEqual(asked[1].transcribe.start, 1, "the window's seconds: 38 - 37");
+ assert.deepEqual(asked[2].take, ["quick-clips/a-quick-one", "--id", "clip", "--label", "Quick clip", "--full"]);
+ // The words heard: "anyway" (40.2–40.8) first, "done" (59.5–59.9) last; "so" (39.5–39.9) mostly before 40.
+ assert.deepEqual(r.snapped, { cutStart: 40.05, cutEnd: 60.2, first: "anyway", last: "done" });
+ const m = JSON.parse(await readFile(path.join(r.dir, "video.manifest.json"), "utf8"));
+ assert.equal(m.render.mode, "basic");
+ assert.equal(m.provenance.siteOrigin, "https://a-site.example");
+ assert.deepEqual([m.timeline[0].start, m.timeline[0].end, m.timeline[0].cutStart, m.timeline[0].cutEnd], [40, 60.2, 40.05, 60.2], "the extent widened to hold the cut");
+ assert.deepEqual(r.share, {
+ platform: "https://www.youtube.com/watch?v=vid1&t=40s",
+ archive: "https://a-site.example/?v=yt%2Fvid1&t=40",
+ text: "https://www.youtube.com/watch?v=vid1&t=40s · archive: https://a-site.example/?v=yt%2Fvid1&t=40",
+ });
+
+ // Again: a fresh project beside it, never over it.
+ const again = await quickClip({ spec: "yt/vid1@40-60", title: "A quick one", site: "a-site" }, { root: REPORTS, channelsDir: CORPUS, sitesDir: SITES, deps });
+ assert.equal(again.project, "quick-clips/a-quick-one-2");
+ assert.equal(again.snapped, null);
+
+ // The CLI: --json, and `umtool share` (the Copy share line's twin).
+ const out = [];
+ const code = await quickClipCommand(["yt/vid1@41-59", "--json"], { root: REPORTS, channelsDir: CORPUS, sitesDir: SITES, deps, log: (s) => out.push(s), err: () => {} });
+ assert.equal(code, 0);
+ const doc = JSON.parse(out.join("\n"));
+ assert.equal(doc.project, "quick-clips/yt-vid1-41");
+ assert.equal(doc.share.platform, "https://www.youtube.com/watch?v=vid1&t=41s");
+ const lines = [];
+ assert.equal(await shareCommand([doc.project, "c01", "--site", "a-site"], { root: REPORTS, out: (s) => lines.push(s), err: (s) => lines.push(s), sitesDir: SITES }), 0);
+ assert.equal(lines[0], "https://www.youtube.com/watch?v=vid1&t=41s · archive: https://a-site.example/?v=yt%2Fvid1&t=41");
+ assert.equal(await shareCommand([doc.project, "nope"], { root: REPORTS, out: () => {}, err: () => {} }), 1);
+ // ndjson: events only on stdout, the last one the result.
+ const ev = [];
+ assert.equal(await quickClipCommand(["yt/vid1@42-58", "--progress", "ndjson"], { root: REPORTS, channelsDir: CORPUS, sitesDir: SITES, deps, log: (s) => ev.push(JSON.parse(s)), err: () => {} }), 0);
+ assert.equal(ev.at(-1).ev, "quick-clip");
+ assert.ok(ev.slice(0, -1).every((e) => e.ev === "quick-clip-step"));
+ // A quick clip whose render fails takes its half-made project with it; the retry gets the same name.
+ const failing = { ...deps, take: async () => 1 };
+ await assert.rejects(quickClip({ spec: "yt/vid1@43-57", title: "Fails once" }, { root: REPORTS, channelsDir: CORPUS, sitesDir: SITES, deps: failing }), /the render failed/);
+ const { existsSync } = await import("node:fs");
+ assert.equal(existsSync(path.join(REPORTS, "quick-clips", "fails-once")), false, "no half project left");
+ const retry = await quickClip({ spec: "yt/vid1@43-57", title: "Fails once" }, { root: REPORTS, channelsDir: CORPUS, sitesDir: SITES, deps });
+ assert.equal(retry.project, "quick-clips/fails-once", "not fails-once-2");
+ // A failed fetch too.
+ await assert.rejects(quickClip({ spec: "yt/vid1@44-56", title: "No window" }, { root: REPORTS, channelsDir: CORPUS, sitesDir: SITES, deps: { ...deps, fetch: async () => { throw new Error("the editor refused"); } } }), /the editor refused/);
+ assert.equal(existsSync(path.join(REPORTS, "quick-clips", "no-window")), false);
+ // A saved whole recording with a time map (clock.json): the span asked on the FILE's clock, the words back on the cues'.
+ const shifted = [];
+ const clocked = {
+ ...deps,
+ fetch: async () => {},
+ resolve: async (want) => ({ kind: "saved-video", path: "/saved/whole.mp4", name: "whole.mp4", windowStart: -13.1, windowEnd: 9000, clock: { id: "c1", offset: 13.1, certain: false }, want }),
+ transcribe: async (req) => {
+ shifted.push(req);
+ // On the file's clock: the cue second t plays at t + 13.1.
+ return [{ w: "first", start: 40.2 + 13.1, end: 40.8 + 13.1 }, { w: "last", start: 59.5 + 13.1, end: 59.9 + 13.1 }];
+ },
+ };
+ const said = [];
+ const c = await quickClip({ spec: "yt/vid1@40-60", snap: "words", title: "Clocked" }, { root: REPORTS, channelsDir: CORPUS, sitesDir: SITES, deps: clocked, say: (x) => said.push(x) });
+ assert.deepEqual([shifted[0].start, shifted[0].end], [51.1, 75.1], "38–62 on the cues is 51.1–75.1 in the file");
+ assert.deepEqual([c.snapped.cutStart, c.snapped.cutEnd], [40.05, 60.2], "the cut on the cue clock");
+ assert.ok(said.some((x) => /NOT certain/.test(x)), "an uncertain clock is said");
+ // Refusals: a bad spec, a site with no siteUrl.
+ assert.equal(await quickClipCommand(["yt/vid1"], { root: REPORTS, log: () => {}, err: () => {} }), 2);
+ await assert.rejects(quickClip({ spec: "yt/vid1@1-2", site: "private" }, { root: REPORTS, channelsDir: CORPUS, sitesDir: SITES, deps }), /no public siteUrl/);
+});
diff --git a/umtool/lib/report/shareLine.mjs b/umtool/lib/report/shareLine.mjs
@@ -0,0 +1,107 @@
+// THE SHARE LINE (lane output-modes): what a person pastes when they share a
+// clip -- the recording's own page at the moment (`watchUrlAt`, the link
+// policy's rule: YouTube `t=<s>s`, Twitch `t=<h>h<m>m<s>s`, Rumble
+// `start=<s>`, else `t=<s>`, over the record's webpage_url), and its moment on
+// the archive (`archiveMomentUrl`, site-links.mjs: the corner QR's and the
+// deck's). The moment is the first second the clip plays (its cut, else its
+// start), floored.
+//
+// RUMBLE'S TWO IDS: a channel downloaded from page URLs keeps a recording
+// under its URL SLUG while the archive serves the EMBED id. `siteVideoFor`
+// (common videoDir-server.mjs recordIdOfVideoDir: the directory's
+// metadata.info.json `id`) is the ONE mapping, and its three callers are this
+// line, `umtool links --fix` (linkCheck.mjs: a Rumble QR naming the folder id
+// is fixed to the embed id) and `umtool timeline insert <rumble-ch>/<folder>`
+// (timelineCli.mjs insertClip: the clip is written with its `siteVideo`). A
+// clip that pins `siteVideo` already is never looked up.
+//
+// Plain ESM: the CLI runs it under bare node; the app's share-line route too.
+import { recordIdOfVideoDir, resolveVideoDirId } from "yt-dlp-transcript-common/lib/videoDir-server.mjs";
+import { watchUrlAt } from "yt-dlp-transcript-common/lib/clips/assist.mjs";
+import { archiveMomentUrl } from "umtool-report-to-video/site-links";
+import { webpageReader } from "./linkPolicy.mjs";
+
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+
+/**
+ * The archive's id for `<slug>/<video>` when it is NOT the id the corpus keeps
+ * it under (a Rumble URL-slug directory: its embed id), else null. `video` may
+ * be either id: an embed id finds its directory first (resolveVideoDirId).
+ * @param {{ channelsDir: string | null, slug: string | null, video: string | null }} o
+ * @returns {Promise<string | null>}
+ */
+export async function siteVideoFor({ channelsDir, slug, video }) {
+ if (!channelsDir || !slug || !video) return null;
+ const dir = await resolveVideoDirId(channelsDir, slug, String(video)).catch(() => String(video));
+ const id = await recordIdOfVideoDir(channelsDir, slug, dir).catch(() => dir);
+ return id !== String(video) ? id : null;
+}
+
+/** The second a clip's share line opens at: the first it plays, floored. */
+export const shareSecondOf = (e) => Math.max(0, Math.floor(Number(fin(e?.cutStart) ? e.cutStart : e?.start) || 0));
+
+/** The line itself: the platform's page, then the archive's moment (either may be missing). */
+export function shareLineText({ platform = null, archive = null } = {}) {
+ return [platform, archive ? `archive: ${archive}` : null].filter(Boolean).join(" · ");
+}
+
+/**
+ * A clip's share line. Pure over its readers: `webpageOf(slug, video)` (the
+ * record's webpage_url) and `siteVideoOf(slug, video)` (the archive's id, or
+ * null when it is the clip's own).
+ *
+ * @param {Record<string, any>} manifest
+ * @param {Record<string, any>} entry a clip
+ * @param {{ origin?: string | null, webpageOf?: (slug: string, video: string) => Promise<string | null>, siteVideoOf?: (slug: string, video: string) => Promise<string | null> }} [o]
+ * @returns {Promise<{ clip: string, seconds: number, platform: string | null, archive: string | null, text: string }>}
+ */
+export async function shareLineOf(manifest, entry, { origin = undefined, webpageOf = async () => null, siteVideoOf = async () => null } = {}) {
+ if (entry?.type !== "clip") throw new Error(`${entry?.id ?? "?"} is not a clip: a share line is a clip's`);
+ const seconds = shareSecondOf(entry);
+ const slug = entry.channel ?? manifest?.provenance?.channelSlug ?? null;
+ const video = entry.video == null ? null : String(entry.video);
+ const platform = slug && video ? watchUrlAt(await webpageOf(slug, video), seconds) : null;
+ const site = origin !== undefined ? origin : manifest?.provenance?.siteOrigin;
+ let archive = null;
+ if (typeof site === "string" && /^https?:\/\//i.test(site.trim()) && slug && video) {
+ const siteVideo = entry.siteVideo ?? (await siteVideoOf(slug, video));
+ archive = archiveMomentUrl({ ...entry, channel: slug, ...(siteVideo ? { siteVideo } : {}) }, manifest?.provenance, seconds, { origin: site.trim().replace(/\/+$/, "") });
+ }
+ return { clip: String(entry.id), seconds, platform, archive, text: shareLineText({ platform, archive }) };
+}
+
+/**
+ * The share line of a clip of a project's cut (or a take's): the clip named,
+ * else the cut's first clip. The readers are the project's channels trees
+ * (its shadow first, then the corpus behind it).
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {{ take?: string | null, clip?: string | null, manifest?: Record<string, any> | null, origin?: string | null }} [o]
+ */
+export async function projectShareLine(project, { take = null, clip = null, manifest = null, origin = undefined } = {}) {
+ const { readManifest, channelsLayersFor, hasShadowChannels } = await import("../projects/report.mjs");
+ let m = manifest;
+ if (!m && take) m = (await (await import("./takeManifest.mjs")).resolveTakeManifest(project.dir, take)).manifest;
+ if (!m) m = await readManifest(project.dir);
+ if (!m) throw new Error(`${project.id} has no video.manifest.json`);
+ const clips = (m.timeline ?? []).filter((e) => e?.type === "clip");
+ const entry = clip ? clips.find((e) => e.id === clip) : clips[0];
+ if (!entry) throw new Error(clip ? `no clip ${clip} in ${project.id}${take ? `'s take ${take}` : ""}` : `${project.id} has no clip to share`);
+ const layers = channelsLayersFor(project.dir, m, { shadowExists: await hasShadowChannels(project.dir) });
+ const readers = layers.map((d) => webpageReader(d));
+ const webpageOf = async (slug, video) => {
+ for (const r of readers) {
+ const u = await r(slug, video);
+ if (u) return u;
+ }
+ return null;
+ };
+ const siteVideoOf = async (slug, video) => {
+ for (const d of layers) {
+ const id = await siteVideoFor({ channelsDir: d, slug, video });
+ if (id) return id;
+ }
+ return null;
+ };
+ return shareLineOf(m, entry, { origin, webpageOf, siteVideoOf });
+}
diff --git a/umtool/lib/report/shareLine.test.mjs b/umtool/lib/report/shareLine.test.mjs
@@ -0,0 +1,141 @@
+// The share line and Rumble's two ids (lane output-modes): a clip's platform
+// page at its moment and its archive moment, the Rumble folder id mapped to
+// the embed id the archive serves -- by the ONE helper the share line, `umtool
+// links --fix` and `umtool timeline insert` all call. Synthetic corpus.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
+import { readFile, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+const ROOT = mkdtempSync(path.join(tmpdir(), "umtool-share-"));
+const CORPUS = path.join(ROOT, "channels");
+process.env.CHANNELS_DIR = CORPUS;
+process.env.CHANNELS_FALLBACK = "0";
+
+const { projectShareLine, shareLineOf, shareLineText, shareSecondOf, siteVideoFor } = await import("./shareLine.mjs");
+const { checkLinks, projectSiteIdOf, withArchiveId } = await import("./linkCheck.mjs");
+const { timelineCommand } = await import("./timelineCli.mjs");
+
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const json = (file, doc) => {
+ mkdirSync(path.dirname(file), { recursive: true });
+ writeFileSync(file, JSON.stringify(doc));
+};
+// A Rumble channel downloaded from page URLs: the folder is the URL slug, the record the embed id.
+json(path.join(CORPUS, "rc", "config.json"), { platform: "rumble", url: "https://rumble.com/c/Quartering" });
+json(path.join(CORPUS, "rc", "data", "v7fn1ab", "metadata.info.json"), { id: "v7fn1aa", webpage_url: "https://rumble.com/v7fn1ab-a-title.html" });
+// A YouTube channel.
+json(path.join(CORPUS, "yt", "config.json"), { platform: "youtube", url: "https://www.youtube.com/@x" });
+json(path.join(CORPUS, "yt", "data", "n8G_ysDV2bA", "transcript.cues.json"), { webpageUrl: "https://www.youtube.com/watch?v=n8G_ysDV2bA", cues: [] });
+
+function project(name, timeline, provenance = {}) {
+ const dir = path.join(ROOT, "reports", name);
+ json(path.join(dir, "video.manifest.json"), { schemaVersion: 1, slug: name, title: name, provenance: { siteOrigin: "https://jeralyzer.example", channelsDir: CORPUS, ...provenance }, render: {}, timeline });
+ return { id: name, dir };
+}
+
+test("siteVideoFor: a Rumble folder's embed id; the embed id itself, a YouTube id, an unknown one: null", async () => {
+ assert.equal(await siteVideoFor({ channelsDir: CORPUS, slug: "rc", video: "v7fn1ab" }), "v7fn1aa");
+ assert.equal(await siteVideoFor({ channelsDir: CORPUS, slug: "rc", video: "v7fn1aa" }), null, "the embed id is the archive's already");
+ assert.equal(await siteVideoFor({ channelsDir: CORPUS, slug: "yt", video: "n8G_ysDV2bA" }), null);
+ assert.equal(await siteVideoFor({ channelsDir: CORPUS, slug: "rc", video: "v9zzzzz" }), null);
+ assert.equal(await siteVideoFor({ channelsDir: null, slug: "rc", video: "v7fn1ab" }), null);
+});
+
+test("shareLineOf: the platform's page at the first second played and the archive's moment", async () => {
+ assert.equal(shareSecondOf({ start: 4130, cutStart: 4132.5 }), 4132);
+ assert.equal(shareSecondOf({ start: 12.9 }), 12);
+ const m = { provenance: { siteOrigin: "https://site.example/", channelSlug: "yt" } };
+ const line = await shareLineOf(m, { type: "clip", id: "c01", video: "n8G_ysDV2bA", start: 4130, end: 4180, cutStart: 4132.5 }, { webpageOf: async () => "https://www.youtube.com/watch?v=n8G_ysDV2bA" });
+ assert.deepEqual(line, {
+ clip: "c01",
+ seconds: 4132,
+ platform: "https://www.youtube.com/watch?v=n8G_ysDV2bA&t=4132s",
+ archive: "https://site.example/?v=yt%2Fn8G_ysDV2bA&t=4132",
+ text: "https://www.youtube.com/watch?v=n8G_ysDV2bA&t=4132s · archive: https://site.example/?v=yt%2Fn8G_ysDV2bA&t=4132",
+ });
+ const none = await shareLineOf({ provenance: {} }, { type: "clip", id: "c", channel: "yt", video: "x", start: 1, end: 2 });
+ assert.deepEqual([none.platform, none.archive, none.text], [null, null, ""]);
+ assert.equal(shareLineText({ archive: "https://a/?v=x" }), "archive: https://a/?v=x");
+ await assert.rejects(shareLineOf(m, { type: "post", id: "p" }), /not a clip/);
+});
+
+test("projectShareLine: a Rumble clip by its folder id -- start= on its page, the embed id on the archive", async () => {
+ const p = project("sl-rumble", [{ type: "clip", id: "n01", channel: "rc", video: "v7fn1ab", start: 100.4, end: 110 }]);
+ const line = await projectShareLine(p);
+ assert.equal(line.platform, "https://rumble.com/v7fn1ab-a-title.html?start=100");
+ assert.equal(line.archive, "https://jeralyzer.example/?v=rc%2Fv7fn1aa&t=100");
+ // --site: another origin, the same moment.
+ assert.equal((await projectShareLine(p, { origin: "https://other.example" })).archive, "https://other.example/?v=rc%2Fv7fn1aa&t=100");
+ await assert.rejects(projectShareLine(p, { clip: "zz" }), /no clip zz/);
+ // A clip that pins its siteVideo is not looked up.
+ const pinned = project("sl-pinned", [{ type: "clip", id: "n01", channel: "rc", video: "v7fn1ab", siteVideo: "v7pinned", start: 1, end: 2 }]);
+ assert.equal((await projectShareLine(pinned)).archive, "https://jeralyzer.example/?v=rc%2Fv7pinned&t=1");
+});
+
+test("the link check: a QR naming the Rumble folder id is dead, its fix the embed id's link and siteVideo", async () => {
+ assert.equal(withArchiveId("https://s.example/?v=rc%2Fv7fn1ab&t=3", "v7fn1ab", "v7fn1aa"), "https://s.example/?v=rc%2Fv7fn1aa&t=3");
+ const m = { provenance: { channelsDir: CORPUS, siteOrigin: "https://s.example" }, timeline: [{ type: "clip", id: "n01", channel: "rc", video: "v7fn1ab", start: 1, end: 2 }] };
+ const siteIdOf = await projectSiteIdOf(path.join(ROOT, "reports", "sl-rumble"), m);
+ assert.equal(await siteIdOf({ clip: "n01", channel: "rc", id: "v7fn1ab" }), "v7fn1aa");
+ assert.equal(await siteIdOf({ clip: "n01", channel: "rc", id: "other" }), null, "a link naming another recording is not this clip's");
+ const docs = {
+ "https://s.example/corpus.json": { channels: [{ slug: "rc", manifests: { transcripts: "https://s.example/data/rc/manifest.json" } }] },
+ "https://s.example/data/rc/manifest.json": { slugToPage: { v7fn1aa: 0 } },
+ };
+ const fetchImpl = async (url) => {
+ const doc = docs[String(url)];
+ return doc ? new Response(JSON.stringify(doc), { status: 200, headers: { "content-type": "application/json" } }) : new Response("no", { status: 404 });
+ };
+ const doc = await checkLinks([{ clip: "n01", url: "https://s.example/?v=rc%2Fv7fn1ab&t=1" }], { fetchImpl, cacheDir: null, gapMs: 0, siteIdOf });
+ const l = doc.links[0];
+ assert.equal(l.state, "dead");
+ assert.match(l.why, /folder \(its Rumble URL slug\).*embed id "v7fn1aa"/);
+ assert.equal(l.fix, "https://s.example/?v=rc%2Fv7fn1aa&t=1");
+ assert.equal(l.fixSiteVideo, "v7fn1aa");
+});
+
+test("umtool timeline insert <rumble-ch>/<folder>: the clip carries the embed id the archive serves", async () => {
+ const p = project("ins-rumble", [{ type: "clip", id: "c01", channel: "rc", video: "v7fn1aa", start: 1, end: 3 }], { channelSlug: "rc" });
+ const lines = [];
+ const code = await timelineCommand([p.dir, "insert", "--after", "c01", "rc/v7fn1ab@10-20", "--id", "n01"], { root: path.join(ROOT, "reports"), out: (s) => lines.push(s), err: (s) => lines.push(s) });
+ assert.equal(code, 0, lines.join("\n"));
+ const m = JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8"));
+ const n01 = m.timeline.find((e) => e.id === "n01");
+ assert.equal(n01.video, "v7fn1ab");
+ assert.equal(n01.siteVideo, "v7fn1aa");
+ const yt = project("ins-yt", [], { channelSlug: "yt" });
+ assert.equal(await timelineCommand([yt.dir, "insert", "--after", "-", "yt/n8G_ysDV2bA@10-20"], { root: path.join(ROOT, "reports"), out: () => {}, err: () => {} }), 0);
+ const y = JSON.parse(await readFile(path.join(yt.dir, "video.manifest.json"), "utf8"));
+ assert.equal(y.timeline[0].siteVideo, undefined, "a YouTube clip names nothing more");
+});
+
+test("umtool links --fix: one undo point, then the Rumble clip names its embed id (siteVideo)", async () => {
+ const { linksCommand } = await import("./linksCli.mjs");
+ const p = project("links-rumble", [{ type: "clip", id: "n01", channel: "rc", video: "v7fn1ab", start: 100, end: 110, cite: 100 }], { channelSlug: "rc" });
+ const docs = {
+ "https://jeralyzer.example/corpus.json": { channels: [{ slug: "rc", manifests: { transcripts: "https://jeralyzer.example/data/rc/manifest.json" } }] },
+ "https://jeralyzer.example/data/rc/manifest.json": { slugToPage: { v7fn1aa: 0 } },
+ "https://jeralyzer.example/data/rc/page-0000.json": [{ id: "v7fn1aa" }],
+ };
+ const fetchImpl = async (url) => {
+ const doc = docs[String(url)];
+ return doc ? new Response(JSON.stringify(doc), { status: 200, headers: { "content-type": "application/json" } }) : new Response("no", { status: 404 });
+ };
+ const lines = [];
+ const code = await linksCommand([p.dir, "--fix"], { root: path.join(ROOT, "reports"), out: (s) => lines.push(s), err: () => {}, fetchImpl, cacheDir: null, gapMs: 0 });
+ const text = lines.join("\n");
+ assert.match(text, /fixed n01: .*v7fn1ab.* -> .*v7fn1aa.*siteVideo v7fn1aa/);
+ assert.match(text, /undo point: revisions\/.*-auto-before-links-fix\.manifest\.json/);
+ assert.equal(code, 0, text);
+ const m = JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8"));
+ assert.equal(m.timeline[0].siteVideo, "v7fn1aa");
+ const rel = /undo point: (\S+)/.exec(text)[1];
+ const before = JSON.parse(await readFile(path.join(p.dir, rel), "utf8"));
+ assert.equal(before.timeline[0].siteVideo, undefined, "the undo point is the cut before the fix");
+});
diff --git a/umtool/lib/report/shareLineCli.mjs b/umtool/lib/report/shareLineCli.mjs
@@ -0,0 +1,54 @@
+// `umtool share <project> [<clip>] [--take <id>] [--site <id>] [--json]` (lane
+// output-modes): a clip's SHARE LINE -- the CLI twin of the take panel's and
+// Play's **Copy share line** (GET /api/report/share-line). The clip named, else
+// the cut's (or the take's) first. shareLine.mjs builds it.
+//
+// Plain ESM: the CLI runs it under bare node.
+import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
+import { projectShareLine } from "./shareLine.mjs";
+import { siteOriginOf } from "./quickClip.mjs";
+
+export const SHARE_USAGE = [
+ "usage: umtool share <project> [<clip>] [--take <id>] [--site <id>] [--json]",
+ " a clip's share line: its platform page at the first second it plays (YouTube t=, Rumble start=) and its",
+ " moment on the archive (the manifest's siteOrigin, or --site's), a Rumble folder id as the embed id the",
+ " archive serves. The clip named, else the first; --take: the take's cut. --json: {clip, seconds, platform, archive, text}.",
+].join("\n");
+
+class CliError extends Error {}
+
+/**
+ * @param {string[]} args the words after `share`
+ * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void, sitesDir?: string }} [o]
+ * @returns {Promise<number>}
+ */
+export async function shareCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), sitesDir } = {}) {
+ try {
+ const words = [];
+ const flags = new Map();
+ for (let i = 0; i < args.length; i += 1) {
+ const a = args[i];
+ if (a === "--take" || a === "--site") {
+ if (i + 1 >= args.length) throw new CliError(`${a} needs a value`);
+ flags.set(a, args[++i]);
+ } else if (a === "--json" || a === "--help") flags.set(a, true);
+ else if (a.startsWith("--")) throw new CliError(`unknown flag ${a}`);
+ else words.push(a);
+ }
+ if (flags.has("--help") || !words.length || words.length > 2) {
+ (flags.has("--help") ? out : err)(SHARE_USAGE);
+ return flags.has("--help") ? 0 : 2;
+ }
+ const r = await resolveProject(words[0], root);
+ if (r.ambiguous) throw new CliError(`"${words[0]}" is the name of ${r.ambiguous.length} projects — pass its id`);
+ if (!r.project) throw new CliError(`no project matches "${words[0]}"`);
+ const origin = flags.has("--site") ? await siteOriginOf(String(flags.get("--site")), sitesDir ? { sitesDir } : {}) : undefined;
+ const line = await projectShareLine(r.project, { clip: words[1] ?? null, take: flags.get("--take") ?? null, ...(origin !== undefined ? { origin } : {}) });
+ if (flags.has("--json")) out(JSON.stringify(line, null, 2));
+ else out(line.text || `${line.clip}: no platform page or archive to link`);
+ return 0;
+ } catch (e) {
+ err(e instanceof Error ? e.message : String(e));
+ return e instanceof CliError || (e instanceof Error && e.constructor?.name === "CliError") ? 2 : 1;
+ }
+}
diff --git a/umtool/lib/report/timelineCli.mjs b/umtool/lib/report/timelineCli.mjs
@@ -447,6 +447,24 @@ export function attributionPatch(flags, convention = { deck: false, dateTitles:
}
/**
+ * The archive's id for a clip's recording when the corpus keeps it under
+ * another (a Rumble folder's embed id), looked up in the project's channels
+ * trees; null when it is the clip's own.
+ * @param {string} dir
+ * @param {Record<string, any>} manifest
+ * @param {Record<string, any>} entry
+ */
+export async function clipSiteVideo(dir, manifest, entry) {
+ const [{ channelsLayersFor, hasShadowChannels }, { siteVideoFor }] = await Promise.all([import("../projects/report.mjs"), import("./shareLine.mjs")]);
+ const slug = entry.channel ?? manifest?.provenance?.channelSlug ?? null;
+ for (const d of channelsLayersFor(dir, manifest, { shadowExists: await hasShadowChannels(dir) })) {
+ const id = await siteVideoFor({ channelsDir: d, slug, video: String(entry.video) });
+ if (id) return id;
+ }
+ return null;
+}
+
+/**
* INSERT ONE CLIP, as `timeline insert` does it: the entry (insertedClip, the
* clip it goes after lending its section, deck title and citation), written
* after `after` (insertEntry) -- or at the end of section `toSection` / after
@@ -475,6 +493,16 @@ export async function insertClip(project, manifest, clip, { after = null, at = n
} else like = insertNeighbour(tl, after, at);
// Into a section or a group the place names the section (the clip it goes after lends its field).
const entry = insertedClip(clip, like, { id, section: group !== null || toSection !== null ? null : section, lock, lockEnd });
+ // A Rumble recording named by its folder (its URL slug): the clip carries the embed id the archive serves
+ // (shareLine.mjs siteVideoFor), so its QR and its share line open the record (4 and 8 Nov: the QR named the folder id).
+ if (!entry.siteVideo && entry.video) {
+ const sv = await clipSiteVideo(project.dir, manifest, entry).catch((e) => {
+ // Said, not swallowed: a Rumble clip inserted without its embed id has a QR the archive does not serve.
+ process.stderr.write(`warning: ${entry.video}: could not look up the id the archive serves it under (${e instanceof Error ? e.message : String(e)}); inserted with no siteVideo -- \`umtool links <p> --fix\` checks it\n`);
+ return null;
+ });
+ if (sv) entry.siteVideo = sv;
+ }
const p = { ...patch };
// A deck title the clip already took from the clip before it is not a change to write.
if (p.onscreen !== undefined && JSON.stringify(p.onscreen) === JSON.stringify(entry.onscreen ?? null)) delete p.onscreen;
diff --git a/umtool/presets/basic.json b/umtool/presets/basic.json
@@ -0,0 +1,7 @@
+{
+ "name": "basic",
+ "description": "The footage alone: the clips' played spans spliced at their source's size and frame rate, short fades at the ends -- no deck, chrome, intro, QR, rail, cards or brand (render.mode basic).",
+ "render": {
+ "mode": "basic"
+ }
+}
diff --git a/umtool/report-to-video/basic.mjs b/umtool/report-to-video/basic.mjs
@@ -0,0 +1,309 @@
+// basic.mjs — THE BASIC OUTPUT MODE (`render.mode: "basic"`, lane output-modes):
+// the cut as the footage alone. Each clip's played spans, cut from the window
+// on disk that holds them, spliced end to end at the source's own size and
+// frame rate -- no deck, chrome, intro, QR, rail, cards or brand.
+//
+// Promoted from the hand-made `raw-render.mjs` (occo-remarks, 8 Nov). Unlike it:
+//
+// - the window is the build's own lookup (sources.mjs resolveLocalSource, via
+// build-video's localSources: the raw cache, the editor's corpus windows, a
+// saved whole recording through its clock), asked per SPAN, so a gap-joined
+// clip whose pieces are hours apart is cut from each piece's own window;
+// - the spans are Play's: `cutStart|start` .. `cutEnd|end` less the clip's
+// gaps (gaps.mjs keptSpans over renderGaps);
+// - the fades are `render.basic.fade` (look.mjs basicFadeOf): `audio` (0.03 s)
+// in and out at EVERY span's edges -- no click at a join, a gap's jump cut
+// included -- and `video` (0.15 s) from black at the cut's first frame and to
+// black at its last;
+// - the size and the frame rate are the FIRST window's (probed); a later
+// window of another shape is fitted into it (letterboxed, never stretched);
+// - the encode is the build's (`encodeArgs`), the estimate render-estimate's
+// `basic` kind, and the concat a stream copy.
+//
+// What basic does not draw is said, never silently dropped: a post item, a
+// teaser, a card, a still or a video entry is left out with a note (a later
+// option could hold them as stills). A clip asking for a BLUR is refused unless
+// the cut says `render.blur: "off"` -- basic draws no blur, and a picture that
+// asked for one is not published unblurred by accident. `audio.gain` is
+// honoured; a clip's other sound knobs (offset, fades, a mute mark) are noted.
+// It never fetches: a span no window holds fails the render by name -- fetch it
+// through the editor first (`umtool fetch <p>`).
+//
+// A LEAF for its pure half (plan, spans, filters, argv): no imports from
+// build-video.mjs, which imports this and hands `renderBasic` what it needs.
+import { createHash } from "node:crypto";
+import { execFile } from "node:child_process";
+import { mkdir, rename, rm, stat, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { promisify } from "node:util";
+import { basicFadeOf, basicOn } from "yt-dlp-transcript-common/lib/report/look.mjs";
+import { clipBlurOf } from "./clip-blur.mjs";
+import { keptSpans, renderGaps } from "./gaps.mjs";
+import { hasLocalMedia } from "./local-media.mjs";
+
+const execFileP = promisify(execFile);
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+const f3 = (n) => String(Number(Number(n).toFixed(3)));
+
+export { basicOn };
+
+/** The work dir under a variant's out dir: the spans' files, the concat list. */
+export const BASIC_WORK = "basic";
+/** Bumped when a span's encode changes, so every cached span file is made again. */
+export const BASIC_SEGMENT_V = 1;
+
+const KIND_WORDS = {
+ post: "a post item",
+ teaser: "a teaser",
+ card: "a card",
+ image: "a still",
+ video: "a video entry",
+};
+
+/**
+ * A clip's played spans, as Play has them: `cutStart|start` .. `cutEnd|end`,
+ * less its gaps (none in a montage). Source seconds. Pure.
+ * @param {Record<string, any>} entry
+ * @param {Record<string, any>} [render]
+ * @returns {{ from: number, to: number }[]}
+ */
+export function basicSpans(entry, render = {}) {
+ const from = Number(entry?.cutStart ?? entry?.start);
+ const to = Number(entry?.cutEnd ?? entry?.end);
+ if (!fin(from) || !fin(to) || !(to > from)) return [];
+ return keptSpans(from, to, renderGaps(entry, render)).filter((s) => s.to - s.from > 1e-3);
+}
+
+/**
+ * What a basic render of `manifest` cuts: each clip and its spans, in order;
+ * what it leaves out and why (`skipped`); what it refuses (`errors`); the
+ * notes it prints. `only` keeps one entry (the bench's `--only`). Pure.
+ *
+ * @param {Record<string, any>} manifest as selectVariant answers it
+ * @param {{ only?: string | null }} [o]
+ */
+export function basicPlan(manifest, { only = null } = {}) {
+ const render = manifest?.render ?? {};
+ const items = [];
+ const skipped = [];
+ const errors = [];
+ const notes = [];
+ for (const e of manifest?.timeline ?? []) {
+ if (!isObj(e)) continue;
+ if (only && e.id !== only) continue;
+ if (e.type !== "clip") {
+ skipped.push({ id: String(e.id ?? "?"), type: String(e.type ?? "entry"), why: `${KIND_WORDS[e.type] ?? `a ${e.type ?? "non-clip"} entry`}: a basic cut is the footage alone` });
+ continue;
+ }
+ const spans = basicSpans(e, render);
+ if (!spans.length) {
+ errors.push(`${e.id}: no span to play (start/end, cutStart/cutEnd)`);
+ continue;
+ }
+ if (clipBlurOf(e, render)) {
+ errors.push(`${e.id} asks for its picture blurred, and a basic cut draws no blur: render it as a deck cut, or say the basic cut is the uncensored one (umtool look <p> blur=off)`);
+ continue;
+ }
+ const a = isObj(e.audio) ? e.audio : {};
+ const unheard = [fin(a.offset) && a.offset !== 0 ? "audio.offset" : null, fin(a.fadeIn) ? "audio.fadeIn" : null, fin(a.fadeOut) ? "audio.fadeOut" : null, e.muteFrom != null ? "muteFrom" : null].filter(Boolean);
+ if (unheard.length) notes.push(`basic: ${e.id}'s ${unheard.join(", ")} not applied (the basic cut plays the sound as recorded, gain aside)`);
+ items.push({ id: String(e.id), entry: e, spans, gain: fin(a.gain) && a.gain !== 0 ? a.gain : 0 });
+ }
+ if (skipped.length) notes.push(`basic: left out ${skipped.map((s) => `${s.id} (${s.why})`).join("; ")}`);
+ if (!items.length && !errors.length) errors.push(only ? `no clip ${only} in the cut` : "a basic cut needs at least one clip: there is none in the cut");
+ return { items, skipped, errors, notes, fade: basicFadeOf(render) };
+}
+
+/**
+ * The fades of one span: its sound faded in and out over `fade.audio` (never
+ * more than a third of the span), its picture from black when it opens the
+ * cut and to black when it ends it, over `fade.video`. Pure.
+ *
+ * @param {{ seconds: number, first: boolean, last: boolean, fade: { audio: number, video: number } }} o
+ * @returns {{ video: string[], audio: string[] }} filter strings, in order
+ */
+export function spanFades({ seconds, first, last, fade }) {
+ const d = Number(seconds);
+ const a = Math.min(fade.audio, d / 3);
+ const v = Math.min(fade.video, d / 3);
+ const video = [];
+ const audio = [];
+ if (a > 0) audio.push(`afade=t=in:st=0:d=${f3(a)}`, `afade=t=out:st=${f3(Math.max(0, d - a))}:d=${f3(a)}`);
+ if (v > 0 && first) video.push(`fade=t=in:st=0:d=${f3(v)}`);
+ if (v > 0 && last) video.push(`fade=t=out:st=${f3(Math.max(0, d - v))}:d=${f3(v)}`);
+ return { video, audio };
+}
+
+/**
+ * The picture's shape a basic cut keeps: the first window's display size
+ * (its sample aspect applied), even, and its frame rate as ffprobe says it.
+ * @param {{ width: number, height: number, sar?: string | null, fps?: string | null }} probe
+ */
+export function basicShape(probe) {
+ const [n, d] = String(probe?.sar ?? "1:1").split(":").map(Number);
+ const sar = n > 0 && d > 0 ? n / d : 1;
+ const even = (x) => Math.max(2, 2 * Math.floor(x / 2));
+ const W = even(Math.round(Number(probe?.width) * sar));
+ const H = even(Number(probe?.height));
+ if (!(W > 2 && H > 2)) throw new Error("basic: the first window has no picture size");
+ const fps = /^\d+(?:\.\d+)?(?:\/\d+)?$/.test(String(probe?.fps ?? "")) && !/^0(\/|$)/.test(String(probe.fps)) ? String(probe.fps) : "30";
+ return { W, H, fps };
+}
+
+/**
+ * One span's ffmpeg argv: `seconds` of `file` from `at` (the FILE's seconds),
+ * fitted into W x H at `fps`, its fades, its gain, encoded with the build's
+ * `encode` args. `audio: false` lays silence under a window with no sound.
+ * Pure.
+ *
+ * @param {{ file: string, at: number, seconds: number, shape: { W: number, H: number, fps: string }, fades: { video: string[], audio: string[] },
+ * gain?: number, audio?: boolean, audioRate?: number, encode: string[], out: string, ffmpeg?: string }} o
+ */
+export function spanArgs({ file, at, seconds, shape, fades, gain = 0, audio = true, audioRate = 48000, encode, out }) {
+ const { W, H, fps } = shape;
+ const vf = [
+ `scale=${W}:${H}:force_original_aspect_ratio=decrease`,
+ `pad=${W}:${H}:(ow-iw)/2:(oh-ih)/2:color=black`,
+ "setsar=1",
+ `fps=${fps}`,
+ ...fades.video,
+ "format=yuv420p",
+ ].join(",");
+ const af = [`aresample=${audioRate}`, ...(gain ? [`volume=${gain}dB`] : []), ...fades.audio].join(",");
+ return [
+ "-nostdin", "-v", "error", "-y",
+ "-ss", f3(Math.max(0, at)), "-i", file,
+ ...(audio ? [] : ["-f", "lavfi", "-i", `anullsrc=r=${audioRate}:cl=stereo`]),
+ "-t", f3(seconds),
+ "-map", "0:v:0", "-map", audio ? "0:a:0" : "1:a:0",
+ "-vf", vf, "-af", af,
+ ...encode,
+ "-shortest",
+ out,
+ ];
+}
+
+/** The concat of the spans' files, stream-copied. Pure. */
+export function concatArgs(listFile, out) {
+ return ["-nostdin", "-v", "error", "-y", "-f", "concat", "-safe", "0", "-i", listFile, "-c", "copy", "-movflags", "+faststart", out];
+}
+
+/**
+ * A span file's name: its order, its clip, its piece, and the hash of what makes it -- the argv (less its out
+ * path) AND the source's identity (`source`: its size and mtime), so a window re-fetched under the same name
+ * makes the span again rather than reusing one cut from the old bytes.
+ */
+export function spanFileName(n, id, k, argv, source = null) {
+ const key = createHash("sha256").update(JSON.stringify({ v: BASIC_SEGMENT_V, argv: argv.slice(0, -1), source })).digest("hex").slice(0, 12);
+ return `${String(n).padStart(3, "0")}-${String(id).replace(/[^A-Za-z0-9_-]/g, "_")}-${k}-${key}.mp4`;
+}
+
+/** ffprobe of a window: its picture's size, aspect and rate, and whether it has sound. */
+export async function probeWindow(file, { ffprobe = "ffprobe" } = {}) {
+ const { stdout } = await execFileP(ffprobe, ["-v", "error", "-show_entries", "stream=codec_type,width,height,sample_aspect_ratio,r_frame_rate,avg_frame_rate:format=duration", "-of", "json", file]);
+ const doc = JSON.parse(stdout);
+ const v = (doc.streams ?? []).find((s) => s.codec_type === "video");
+ const hasAudio = (doc.streams ?? []).some((s) => s.codec_type === "audio");
+ const rate = [v?.avg_frame_rate, v?.r_frame_rate].find((r) => r && r !== "0/0") ?? null;
+ return {
+ width: Number(v?.width), height: Number(v?.height), sar: v?.sample_aspect_ratio && v.sample_aspect_ratio !== "0:1" ? v.sample_aspect_ratio : "1:1",
+ fps: rate, hasVideo: !!v, hasAudio, duration: Number(doc.format?.duration) || null,
+ };
+}
+
+/**
+ * The basic render. `deps` is the build's: where a span's window is (`sourceOf`,
+ * build-video's localSources over the build's tiers, a `src` clip its own
+ * file), its encode (`encodeArgs`), the binaries and the progress events.
+ * Writes `dirs.final`; its spans' files under `<dirs.dir>/basic/`, reused by
+ * the next render that asks the same encode of the same window.
+ *
+ * @param {{ manifest: Record<string, any>, dirs: { dir: string, final: string }, only?: string | null,
+ * deps: { sourceOf: (entry: Record<string, any>, span: { from: number, to: number }) => Promise<{ path: string, fetchStart: number, source?: string } | null>,
+ * encodeArgs: (render: Record<string, any>) => string[], ffmpeg?: string, ffprobe?: string, emit?: (ev: string, fields?: Record<string, any>) => void,
+ * exec?: (bin: string, args: string[]) => Promise<unknown>, probe?: typeof probeWindow } }} o
+ * @returns {Promise<{ out: string, failures: { id: string, message: string }[], seconds: number }>}
+ */
+export async function renderBasic({ manifest, dirs, only = null, deps }) {
+ const emit = deps.emit ?? (() => {});
+ const ffmpeg = deps.ffmpeg ?? "ffmpeg";
+ const exec = deps.exec ?? ((bin, args) => execFileP(bin, args, { maxBuffer: 1 << 24 }));
+ const probe = deps.probe ?? ((file) => probeWindow(file, { ffprobe: deps.ffprobe ?? "ffprobe" }));
+ const render = manifest.render ?? {};
+ const plan = basicPlan(manifest, { only });
+ for (const message of plan.notes) emit("note", { message });
+ if (plan.errors.length) throw new Error(`basic: ${plan.errors.join("; ")}`);
+
+ // Every span's window first: a cut with a span nothing holds is refused whole, by name, before an encode.
+ const located = [];
+ const missing = [];
+ for (const it of plan.items) {
+ for (const [k, span] of it.spans.entries()) {
+ const src = await deps.sourceOf(it.entry, span);
+ if (!src) missing.push(`${it.id} ${it.entry.channel ?? manifest.provenance?.channelSlug ?? "?"}/${it.entry.video ?? it.entry.src ?? "?"} ${f3(span.from)}–${f3(span.to)}`);
+ else located.push({ it, k, span, src });
+ }
+ }
+ if (missing.length) {
+ throw new Error(`basic: no window on disk holds ${missing.length === 1 ? "this span" : "these spans"} -- fetch through the editor first (umtool fetch <project>), nothing is fetched here:\n ${missing.join("\n ")}`);
+ }
+
+ const first = await probe(located[0].src.path);
+ if (!first.hasVideo) throw new Error(`basic: ${path.basename(located[0].src.path)} (${located[0].it.id}) has no picture`);
+ const shape = basicShape(first);
+ const r = { ...render, fps: shape.fps, audioRate: render.audioRate ?? 48000, audioChannels: render.audioChannels ?? 2 };
+ const encode = deps.encodeArgs(r);
+ emit("note", { message: `basic: ${located.length} span(s) of ${plan.items.length} clip(s) at ${shape.W}x${shape.H} ${shape.fps} fps (the first window's), fades audio ${plan.fade.audio}s video ${plan.fade.video}s` });
+ emit("start", { title: manifest.title, entries: plan.items.length, out: dirs.dir });
+
+ const work = path.join(dirs.dir, BASIC_WORK);
+ await mkdir(work, { recursive: true });
+ const files = [];
+ let seconds = 0;
+ const probes = new Map([[located[0].src.path, first]]);
+ for (const [n, l] of located.entries()) {
+ const p = probes.get(l.src.path) ?? (await probe(l.src.path));
+ probes.set(l.src.path, p);
+ const dur = l.span.to - l.span.from;
+ const fades = spanFades({ seconds: dur, first: n === 0, last: n === located.length - 1, fade: plan.fade });
+ const at = l.span.from - Number(l.src.fetchStart ?? 0);
+ const draft = spanArgs({ file: l.src.path, at, seconds: dur, shape, fades, gain: l.it.gain, audio: p.hasAudio, audioRate: r.audioRate, encode, out: "<out>" });
+ const st = await stat(l.src.path);
+ const out = path.join(work, spanFileName(n, l.it.id, l.k, draft, { size: st.size, mtimeMs: Math.round(st.mtimeMs) }));
+ const argv = [...draft.slice(0, -1), out];
+ const have = await stat(out).then((x) => x.isFile() && x.size > 0, () => false);
+ if (!have) {
+ const tmp = `${out}.tmp.mp4`;
+ try {
+ await exec(ffmpeg, [...draft.slice(0, -1), tmp]);
+ await rename(tmp, out);
+ } catch (e) {
+ // A failed encode leaves nothing a later render could take for a span.
+ await rm(tmp, { force: true });
+ throw e;
+ }
+ }
+ emit("fetch", { id: l.it.id, video: l.it.entry.video ?? l.it.entry.src, from: l.span.from, to: l.span.to, cached: true, source: l.src.source ?? "local", reuse: path.basename(l.src.path) });
+ emit("segment", { id: l.it.id, path: out, reused: have, argv });
+ files.push(out);
+ seconds += dur;
+ }
+ const list = path.join(work, "list.txt");
+ await writeFile(list, files.map((f) => `file '${f.replace(/'/g, "'\\''")}'`).join("\n") + "\n");
+ emit("concat", { mode: "hardcut", n: files.length });
+ await mkdir(path.dirname(dirs.final), { recursive: true });
+ // Through a temporary name: a concat that fails never leaves a half file at the deliverable's path.
+ const finalTmp = `${dirs.final}.tmp-${process.pid}.mp4`;
+ try {
+ await exec(ffmpeg, concatArgs(list, finalTmp));
+ await rename(finalTmp, dirs.final);
+ } catch (e) {
+ await rm(finalTmp, { force: true });
+ throw e;
+ }
+ const made = await probe(dirs.final).catch(() => null);
+ const size = await stat(dirs.final).then((s) => s.size, () => 0);
+ emit("done", { out: dirs.final, duration: made?.duration ?? Number(seconds.toFixed(3)), size, basic: true });
+ return { out: dirs.final, failures: [], seconds };
+}
diff --git a/umtool/report-to-video/basic.test.mjs b/umtool/report-to-video/basic.test.mjs
@@ -0,0 +1,229 @@
+// The basic output mode (basic.mjs, render.mode "basic"): the spans as Play
+// has them, the fades at the right edges, the plan's notes and refusals, the
+// mode resolved last (a preset's, a patch's), and a real render through the
+// build's own door -- the one every take and `umtool build` goes through.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
+import { rm, stat, writeFile } 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(), "rtv-basic-corpus-"));
+process.env.CHANNELS_DIR = CORPUS;
+
+const { basicPlan, basicShape, basicSpans, concatArgs, renderBasic, spanArgs, spanFades, spanFileName } = await import("./basic.mjs");
+const { buildVideo, cliEstimateMb, selectVariant, setProgressMode } = await import("./build-video.mjs");
+const { resolvePresetLayers } = await import("./presets.mjs");
+const { BASIC_ESTIMATE_MB, manifestEstimateMb } = await import("./render-estimate.mjs");
+
+test.after(() => rm(CORPUS, { recursive: true, force: true }));
+
+const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0);
+const FADE = { audio: 0.03, video: 0.15 };
+
+test("basicSpans: the cut's edges when it has them, else the extent; less the gaps; none in a montage", () => {
+ assert.deepEqual(basicSpans({ type: "clip", start: 10, end: 20 }), [{ from: 10, to: 20 }]);
+ assert.deepEqual(basicSpans({ type: "clip", start: 10, end: 20, cutStart: 12, cutEnd: 18 }), [{ from: 12, to: 18 }]);
+ assert.deepEqual(
+ basicSpans({ type: "clip", start: 10, end: 30, cutStart: 11, cutEnd: 29, gaps: [{ from: 20, to: 22 }, { from: 14, to: 15 }] }),
+ [{ from: 11, to: 14 }, { from: 15, to: 20 }, { from: 22, to: 29 }],
+ "sorted, the gaps out",
+ );
+ assert.deepEqual(basicSpans({ type: "clip", start: 10, end: 20, gaps: [{ from: 10, to: 12 }] }), [{ from: 12, to: 20 }], "a gap at the edge leaves no empty span");
+ assert.deepEqual(basicSpans({ type: "clip", start: 10, end: 20, gaps: [{ from: 12, to: 14 }] }, { montage: {} }), [{ from: 10, to: 20 }], "a montage cuts no gaps");
+ assert.deepEqual(basicSpans({ type: "clip", start: 20, end: 10 }), []);
+});
+
+test("spanFades: the sound at every span's edges, the picture from black at the cut's first frame and to black at its last", () => {
+ assert.deepEqual(spanFades({ seconds: 5, first: false, last: false, fade: FADE }), {
+ video: [],
+ audio: ["afade=t=in:st=0:d=0.03", "afade=t=out:st=4.97:d=0.03"],
+ });
+ assert.deepEqual(spanFades({ seconds: 5, first: true, last: false, fade: FADE }).video, ["fade=t=in:st=0:d=0.15"]);
+ assert.deepEqual(spanFades({ seconds: 5, first: false, last: true, fade: FADE }).video, ["fade=t=out:st=4.85:d=0.15"]);
+ assert.deepEqual(spanFades({ seconds: 5, first: true, last: true, fade: FADE }).video, ["fade=t=in:st=0:d=0.15", "fade=t=out:st=4.85:d=0.15"], "one span is the whole cut");
+ assert.deepEqual(spanFades({ seconds: 0.3, first: true, last: true, fade: FADE }).video, ["fade=t=in:st=0:d=0.1", "fade=t=out:st=0.2:d=0.1"], "never more than a third of a short span");
+ assert.deepEqual(spanFades({ seconds: 5, first: true, last: true, fade: { audio: 0, video: 0 } }), { video: [], audio: [] }, "0 is none");
+});
+
+test("basicPlan: clips and their spans in order; the rest left out by name; a blurred clip refused unless the cut is uncensored", () => {
+ const m = {
+ render: {},
+ timeline: [
+ { type: "card", id: "k1" },
+ { type: "clip", id: "c1", video: "v", start: 1, end: 3 },
+ { type: "post", id: "p1" },
+ { type: "teaser", id: "t1" },
+ { type: "clip", id: "c2", video: "v", start: 5, end: 9, gaps: [{ from: 6, to: 7 }], audio: { gain: -3, offset: 40 } },
+ ],
+ };
+ const plan = basicPlan(m);
+ assert.deepEqual(plan.items.map((i) => [i.id, i.spans.length, i.gain]), [["c1", 1, 0], ["c2", 2, -3]]);
+ assert.deepEqual(plan.skipped.map((s) => s.id), ["k1", "p1", "t1"]);
+ assert.match(plan.notes.join("\n"), /left out k1 \(a card: a basic cut is the footage alone\); p1 \(a post item/);
+ assert.match(plan.notes.join("\n"), /c2's audio\.offset not applied/);
+ assert.deepEqual(plan.errors, []);
+ assert.deepEqual(plan.fade, FADE);
+ assert.deepEqual(basicPlan(m, { only: "c2" }).items.map((i) => i.id), ["c2"]);
+
+ const blurred = { render: {}, timeline: [{ type: "clip", id: "c1", video: "v", start: 1, end: 3, blur: { on: true } }] };
+ assert.match(basicPlan(blurred).errors[0], /c1 asks for its picture blurred.*blur=off/);
+ assert.deepEqual(basicPlan({ ...blurred, render: { blur: "off" } }).errors, [], "the uncensored basic cut");
+ assert.match(basicPlan({ render: {}, timeline: [{ type: "post", id: "p1" }] }).errors[0], /needs at least one clip/);
+ assert.deepEqual(basicPlan({ render: { basic: { fade: { video: 0.5 } } }, timeline: [] }).fade, { audio: 0.03, video: 0.5 });
+});
+
+test("spanArgs: the file's seconds, fitted into the first window's shape, its fades and gain, the build's encode", () => {
+ const shape = basicShape({ width: 1920, height: 1080, sar: "1:1", fps: "60/1" });
+ assert.deepEqual(shape, { W: 1920, H: 1080, fps: "60/1" });
+ assert.deepEqual(basicShape({ width: 720, height: 480, sar: "32:27", fps: "30000/1001" }), { W: 852, H: 480, fps: "30000/1001" }, "display size, even");
+ assert.equal(basicShape({ width: 640, height: 360, fps: "0/0" }).fps, "30", "no rate: 30");
+ const argv = spanArgs({ file: "/w.mp4", at: 12.5, seconds: 4, shape, fades: spanFades({ seconds: 4, first: true, last: false, fade: FADE }), gain: -3, encode: ["-c:v", "libx264"], out: "/o.mp4" });
+ const at = (k) => argv[argv.indexOf(k) + 1];
+ assert.equal(at("-ss"), "12.5");
+ assert.equal(at("-t"), "4");
+ assert.equal(at("-vf"), "scale=1920:1080:force_original_aspect_ratio=decrease,pad=1920:1080:(ow-iw)/2:(oh-ih)/2:color=black,setsar=1,fps=60/1,fade=t=in:st=0:d=0.15,format=yuv420p");
+ assert.equal(at("-af"), "aresample=48000,volume=-3dB,afade=t=in:st=0:d=0.03,afade=t=out:st=3.97:d=0.03");
+ assert.equal(argv.at(-1), "/o.mp4");
+ const silent = spanArgs({ file: "/w.mp4", at: 0, seconds: 1, shape, fades: { video: [], audio: [] }, audio: false, encode: [], out: "/o.mp4" });
+ assert.ok(silent.includes("anullsrc=r=48000:cl=stereo") && silent.includes("1:a:0"), "a window with no sound gets silence");
+ assert.deepEqual(concatArgs("/l.txt", "/f.mp4").slice(-5), ["-c", "copy", "-movflags", "+faststart", "/f.mp4"]);
+ assert.equal(spanFileName(3, "c 1", 0, argv), spanFileName(3, "c 1", 0, [...argv.slice(0, -1), "/elsewhere.mp4"]), "the out path is not part of the key");
+ assert.match(spanFileName(3, "c 1", 0, argv), /^003-c_1-0-[0-9a-f]{12}\.mp4$/);
+ assert.notEqual(spanFileName(3, "c", 0, argv, { size: 1, mtimeMs: 1 }), spanFileName(3, "c", 0, argv, { size: 1, mtimeMs: 2 }), "a re-fetched window is another span");
+});
+
+test("the mode resolves last: a preset's basic wins its chrome, a patch's deck wins the preset; basic lays no intro or brand", () => {
+ const m = { slug: "s", preset: "basic", render: { chrome: { layout: "deck" }, intro: "boot-dark" }, timeline: [{ type: "clip", id: "c1", video: "v", start: 1, end: 2 }] };
+ const seen = selectVariant(m);
+ assert.equal(seen.render.mode, "basic");
+ assert.equal(seen.timeline.length, 1, "no intro entry prepended");
+ assert.equal(resolvePresetLayers(m, [{ render: { mode: "deck" } }]).render.mode, "deck", "a take's patch wins the preset");
+ const deck = selectVariant({ ...m, preset: undefined, render: { ...m.render } });
+ assert.ok(deck.timeline.length > 1, "a deck cut with an intro gets it");
+ assert.equal(manifestEstimateMb({ render: { mode: "basic" }, timeline: [] }, {}), BASIC_ESTIMATE_MB);
+ assert.equal(manifestEstimateMb({ render: { mode: "basic" } }, { UMTOOL_RENDER_ESTIMATE_MB: "0" }), null, "the override still speaks");
+});
+
+test("renderBasic: refuses a span no window holds, by name, before an encode", async () => {
+ const root = mkdtempSync(path.join(os.tmpdir(), "rtv-basic-miss-"));
+ try {
+ const ran = [];
+ await assert.rejects(
+ renderBasic({
+ manifest: { render: {}, provenance: { channelSlug: "ch" }, timeline: [{ type: "clip", id: "c1", video: "v1", start: 1, end: 3 }] },
+ dirs: { dir: root, final: path.join(root, "f.mp4") },
+ deps: { sourceOf: async () => null, encodeArgs: () => [], exec: async (...a) => ran.push(a) },
+ }),
+ /no window on disk holds this span.*umtool fetch[\s\S]*c1 ch\/v1 1–3/,
+ );
+ assert.equal(ran.length, 0);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("a basic cut, rendered through buildVideo: the spans spliced at the window's size and rate, no deck, chrome not checked", { skip: !have && "no ffmpeg" }, async () => {
+ const root = mkdtempSync(path.join(os.tmpdir(), "rtv-basic-"));
+ try {
+ mkdirSync(path.join(root, "out", "clips-raw"), { recursive: true });
+ const raw = path.join(root, "out", "clips-raw", "vid1_0.00-10.00.mp4");
+ const r = spawnSync("ffmpeg", [
+ "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=s=320x180:r=25:d=10", "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=10",
+ "-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"), "{}");
+ const manifestPath = path.join(root, "video.manifest.json");
+ await writeFile(manifestPath, JSON.stringify({
+ slug: "basic-test", title: "Basic", provenance: { channelSlug: "synth", channelsDir: CORPUS },
+ render: {
+ mode: "basic", width: 1920, height: 1080, fps: 30, audioRate: 48000, audioChannels: 2, preset: "ultrafast", crf: 30,
+ // A chrome the build would refuse: a basic cut does not check it.
+ chrome: { layout: "deck", engine: "hyperframes", deck: { nonsense: true } },
+ },
+ timeline: [
+ { type: "card", id: "k1", title: "left out" },
+ { type: "clip", id: "c1", channel: "synth", video: "vid1", start: 1, end: 4, gaps: [{ from: 2, to: 2.5 }] },
+ { type: "clip", id: "c2", channel: "synth", video: "vid1", start: 5, end: 9, cutStart: 6, cutEnd: 8 },
+ ],
+ }));
+ const events = [];
+ setProgressMode((e) => events.push(e));
+ const { out } = await buildVideo({ manifestPath, opts: { skipFetch: true } });
+ setProgressMode("human");
+ assert.equal(out, path.join(root, "out", "basic-test.mp4"));
+ const probe = JSON.parse(spawnSync("ffprobe", ["-v", "error", "-show_entries", "stream=codec_type,width,height,avg_frame_rate:format=duration", "-of", "json", out]).stdout.toString());
+ const v = probe.streams.find((s) => s.codec_type === "video");
+ assert.deepEqual([v.width, v.height], [320, 180], "the window's own size, not the render block's");
+ const [rn, rd] = String(v.avg_frame_rate).split("/").map(Number);
+ assert.ok(Math.abs(rn / rd - 25) < 0.5, `the window's own rate (25), not the render block's 30: ${v.avg_frame_rate}`);
+ assert.ok(probe.streams.some((s) => s.codec_type === "audio"));
+ // c1 1–4 less 2–2.5 (2.5 s) + c2's cut 6–8 (2 s).
+ assert.ok(Math.abs(Number(probe.format.duration) - 4.5) < 0.15, `duration ${probe.format.duration}`);
+ assert.ok(events.some((e) => e.ev === "note" && /left out k1/.test(e.message)));
+ assert.equal(events.filter((e) => e.ev === "segment").length, 3);
+ assert.ok(!events.some((e) => e.ev === "chrome"), "no deck");
+ // Rendered again: the spans' files are reused.
+ const again = [];
+ setProgressMode((e) => again.push(e));
+ await buildVideo({ manifestPath, opts: { skipFetch: true } });
+ setProgressMode("human");
+ assert.ok(again.filter((e) => e.ev === "segment").every((e) => e.reused));
+ assert.ok((await stat(out)).size > 0);
+ // The window re-fetched under the same name: the spans are cut again, not reused from the old bytes.
+ const r2 = spawnSync("ffmpeg", [
+ "-v", "error", "-y", "-f", "lavfi", "-i", "color=c=red:s=320x180:r=25:d=10", "-f", "lavfi", "-i", "sine=frequency=220:sample_rate=48000:duration=10",
+ "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", raw,
+ ]);
+ assert.equal(r2.status, 0, String(r2.stderr));
+ const fresh = [];
+ setProgressMode((e) => fresh.push(e));
+ await buildVideo({ manifestPath, opts: { skipFetch: true } });
+ setProgressMode("human");
+ assert.ok(fresh.filter((e) => e.ev === "segment").every((e) => !e.reused), "a new window, new spans");
+ const { readdir } = await import("node:fs/promises");
+ assert.deepEqual((await readdir(path.join(root, "out"))).filter((n) => /\.tmp/.test(n)), [], "no temporary file left beside the cut");
+ // `--only` writes beside the spans, never over the cut.
+ const only = await buildVideo({ manifestPath, opts: { skipFetch: true }, only: "c2" });
+ assert.match(only.out, /out\/sourced\/basic\/only-c2\.mp4$/);
+ await assert.rejects(buildVideo({ manifestPath, opts: { skipFetch: true, short: "c1" } }), /--short: a basic cut/);
+ assert.ok((await cliEstimateMb(manifestPath, {}, {})) <= 1200);
+ } finally {
+ setProgressMode("human");
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("renderBasic: a span whose encode fails leaves no temporary file, and the cut's file is not touched", async () => {
+ const root = mkdtempSync(path.join(os.tmpdir(), "rtv-basic-fail-"));
+ try {
+ const src = path.join(root, "w.mp4");
+ writeFileSync(src, "bytes");
+ const { readdir } = await import("node:fs/promises");
+ await assert.rejects(
+ renderBasic({
+ manifest: { render: {}, timeline: [{ type: "clip", id: "c1", video: "v1", start: 1, end: 3 }] },
+ dirs: { dir: root, final: path.join(root, "final.mp4") },
+ deps: {
+ sourceOf: async () => ({ path: src, fetchStart: 0 }),
+ encodeArgs: () => [],
+ probe: async () => ({ width: 320, height: 180, sar: "1:1", fps: "25/1", hasVideo: true, hasAudio: true }),
+ exec: async (_bin, args) => {
+ writeFileSync(args.at(-1), "half");
+ throw new Error("ffmpeg died");
+ },
+ },
+ }),
+ /ffmpeg died/,
+ );
+ assert.deepEqual((await readdir(path.join(root, "basic"))).filter((n) => n.endsWith(".mp4")), []);
+ assert.equal(existsSync(path.join(root, "final.mp4")), false);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -126,6 +126,8 @@
// Requires: yt-dlp, ffmpeg/ffprobe, ImageMagick with Pango.
import { presetManifest } from "./presets.mjs";
+// The basic output mode (render.mode "basic"): the footage alone, cut and spliced in basic.mjs.
+import { renderBasic } from "./basic.mjs";
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
import { promisify } from "node:util";
@@ -198,7 +200,7 @@ import { validateDrafted, validatePublish } from "yt-dlp-transcript-common/lib/r
import { validateAssist } from "yt-dlp-transcript-common/lib/clips/assist.mjs";
import { blurSlideEdges, validateTransitionStyle, xfadeTransitionOf } from "./transition.mjs";
import { JOIN_PREVIEW_FILE, JOIN_PREVIEW_RECORD, joinPreviewTimeline } from "./join-preview.mjs";
-import { lookOf } from "yt-dlp-transcript-common/lib/report/look.mjs";
+import { basicOn, lookOf } from "yt-dlp-transcript-common/lib/report/look.mjs";
// The look of a highlights cut (release 36 lane C): render.captions,
// render.loudness, a clip's vertical crop and the short made from it -- pure,
// in look.mjs. Every hook below runs only when its key is set.
@@ -390,7 +392,12 @@ export function selectVariant(manifest, variant = DEFAULT_VARIANT) {
// instruments' totals and the finale's hidden rows are the rows no clip is
// behind (measure-slice.mjs). A headcount manifest gains nothing.
const measureLedger = manifest.ledgerSchema?.kind === "measure" ? { measureLedger: manifest.ledger ?? [] } : {};
- return introManifest(brandManifest(presetManifest({ ...manifest, variant, timeline, ledger, ...measureLedger, ...(posts !== undefined ? { posts } : {}) })));
+ // THE OUTPUT MODE, resolved last (look.mjs renderModeOf): a basic cut -- the
+ // footage alone (basic.mjs) -- lays no brand and no intro, whatever a lower
+ // layer set.
+ const laid = presetManifest({ ...manifest, variant, timeline, ledger, ...measureLedger, ...(posts !== undefined ? { posts } : {}) });
+ if (basicOn(laid?.render)) return laid;
+ return introManifest(brandManifest(laid));
}
/**
@@ -6517,6 +6524,19 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
? { manifest: whole, left: [], matched: [], renumbered: false }
: applyMontageRulings(whole, await readMontageRulings(manifestDir), { keep: only ? [only] : [] });
const manifest = selectVariant(ruled.manifest, variant);
+ // THE BASIC OUTPUT MODE (render.mode, basic.mjs): the footage alone. Every
+ // render of the cut gets it -- a take, `umtool build`, this CLI -- because the
+ // mode is read here, off the manifest every layer resolved into. The runs
+ // that make a deck's pieces have no basic form, and say so.
+ const basic = basicOn(manifest.render);
+ if (basic) {
+ const asked = [
+ [opts.short, "--short"], [opts.vertical || verticalOn(manifest.render), "--vertical (render.format vertical)"], [opts.joinPreview, "--join-preview"],
+ [opts.chromeOnly, "--chrome-only"], [opts.chromePreview, "--chrome-preview"], [opts.clipPreview, "--clip-preview"], [opts.railOnly, "--rail-only / --preview"],
+ [opts.thumbnailOnly, "--thumbnail"], [opts.chaptersOnly, "--chapters-only"],
+ ].filter(([on]) => on).map(([, flag]) => flag);
+ if (asked.length) throw new Error(`${asked.join(", ")}: a basic cut (render.mode basic) is the footage alone, with no deck to make that from — render it as a deck cut (umtool look <p> mode=deck)`);
+ }
if (opts.short) {
const e = (manifest.timeline ?? []).find((x) => x.id === opts.short);
if (!e) throw new Error(`no timeline entry with id ${opts.short}`);
@@ -6549,7 +6569,8 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
await prepareLocalMedia(manifest.timeline, manifestDir, render);
// A `render.chrome` that cannot be built is refused here, before a single
// fetch is spent. Absent, validateChrome has nothing to say.
- if (render.chrome !== undefined && render.chrome !== null) assertChrome(render.chrome, render);
+ // A basic cut draws no chrome, so whatever chrome a layer under it set is not checked (look.mjs renderModeOf).
+ if (!basic && render.chrome !== undefined && render.chrome !== null) assertChrome(render.chrome, render);
// A batch size that cannot be read is refused as early (the env or the manifest's).
xfadeBatchSize(render);
// A clip's `muteFrom` and `render.endFade`, checked against the WHOLE
@@ -6564,7 +6585,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
];
if (errors.length) throw new Error(`manifest: ${errors.join("; ")}`);
}
- const deck = deckOn(render);
+ const deck = !basic && deckOn(render);
// Posts are drawn only under the deck, so only the deck refuses bad ones --
// against the WHOLE timeline, where an `attachTo` has to name a clip.
if (deck) {
@@ -6587,7 +6608,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
// and is a warning in any other; a hand-written narration keeps release
// 25's rule (narration-review.mjs) -- un-approved refuses once the cut's
// narration has a review, unless --narration-unreviewed.
- const lint = opts.noLint
+ const lint = opts.noLint || basic
? { errors: [], warnings: [] }
: lintManifest(manifest, {
manifestDir, whole, only: only ?? null, validators: false,
@@ -6688,6 +6709,32 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
await mkdir(path.join(outDir, d), { recursive: true });
}
+ // A BASIC cut is cut here, from what is on disk, and the build ends (basic.mjs).
+ // A bench's --fetch-only is about a moment in the corpus, not the cut's look: it goes on below.
+ if (basic && !fetchOnly) {
+ return renderBasic({
+ manifest,
+ // `--only <id>` (a bench's one clip) is written beside the spans, never over the cut's file.
+ dirs: only ? { ...dirs, final: path.join(dirs.dir, "basic", `only-${String(only).replace(/[^A-Za-z0-9_-]/g, "_")}.mp4`) } : dirs,
+ only: only ?? null,
+ deps: {
+ // A span's window: a `src` clip is its own file; any other, the build's local tiers for exactly that
+ // span (the raw cache, the corpus windows, a saved recording through its clock), its clock aligned.
+ sourceOf: async (entry, span) => {
+ if (hasLocalMedia(entry)) return { path: LOCAL.file(entry), fetchStart: 0, source: "src" };
+ const hit = await dirs.local.resolve(entry, span, { exact: false, audio: false });
+ if (!hit) return null;
+ const r = await alignedClipSource({ path: hit.path, fetchStart: hit.windowStart, source: hit.kind });
+ return { path: r.path, fetchStart: r.fetchStart, source: hit.kind };
+ },
+ encodeArgs,
+ ffmpeg: FFMPEG,
+ ffprobe: FFPROBE,
+ emit: (ev, fields) => EMIT(ev, fields),
+ },
+ });
+ }
+
// Fetch one clip's window and stop. This is what the clip bench's "fetch 20s
// more" runs, so a bench fetch and a build fetch can never disagree about
// naming, format selection, the VP9 trap or the Rumble HLS retry.
@@ -7583,6 +7630,12 @@ export async function cliEstimateMb(manifestPath, opts = {}, env = process.env)
} catch {
manifest = null;
}
+ // Its look preset laid, so a cut that stands on `basic` declares a basic render.
+ try {
+ if (manifest) manifest = presetManifest(manifest);
+ } catch {
+ // An unknown preset: the build says so; the estimate is the manifest's own.
+ }
let batch;
try {
batch = xfadeBatchSize(manifest?.render ?? {}, env);
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -23,6 +23,7 @@
"./brand": "./brand.mjs",
"./brand-ids": "./brand-ids.mjs",
"./build-video": "./build-video.mjs",
+ "./basic": "./basic.mjs",
"./vertical": "./vertical.mjs",
"./vertical-plan": "./vertical-plan.mjs",
"./reframe": "./reframe.mjs",
diff --git a/umtool/report-to-video/presets.mjs b/umtool/report-to-video/presets.mjs
@@ -16,6 +16,13 @@
// `makeTake`, takeManifest `resolveTakeManifest`). A resolved manifest
// carries `presetApplied: <name>` and no `preset`, so it is never laid twice.
//
+// THE OUTPUT MODE (`render.mode`, common lib/report/look.mjs) is a render key
+// like any other, so it resolves here with the rest: the mode a reader sees is
+// the last layer's, and a "basic" anywhere above wins whatever chrome a lower
+// layer lays -- selectVariant then lays no brand and no intro, and the build
+// hands the cut to the basic renderer (basic.mjs). The built-in `basic`
+// preset is that one key.
+//
// The presets directory is `UMTOOL_PRESETS_DIR` when set (the e2e suite's),
// else umtool/presets beside this package. Read synchronously: a preset is a
// small file, read where a manifest is (and cached by mtime).
@@ -121,7 +128,7 @@ export const PRESET_RENDER_KEYS = Object.freeze([
"width", "height", "fps", "audioRate", "audioChannels", "maxHeightSource", "fontRegular", "fontBold", "palette",
"transition", "transitionStyle", "fetchPad", "snapWindow", "silenceMinDur", "silenceRelDb", "snapLead", "snapTail", "lockedEdges",
"footerHeight", "headerHeight", "slideSeconds", "crf", "preset", "audioBitrate", "qr", "endFade", "loudness",
- "captions", "intro", "chrome", "brand",
+ "captions", "intro", "chrome", "brand", "mode", "basic",
]);
/**
diff --git a/umtool/report-to-video/render-estimate.mjs b/umtool/report-to-video/render-estimate.mjs
@@ -55,6 +55,13 @@ export const RENDER_CHROME_BASE_MB = 400;
export const RENDER_CHROME_PER_WORKER_MB = 320;
/** The ladder's one x264 re-encode at a time. */
export const LADDER_ESTIMATE_MB = 1000;
+/**
+ * A BASIC cut (render.mode "basic", basic.mjs): one span's encode at a time at
+ * the source's own size, then a stream-copied concat -- no chrome capture, no
+ * crossfade pass. One segment's encode measured 0.85 GB at 1080p30 (above);
+ * a 1080p60 source decodes twice the frames, so this carries about 40 % over it.
+ */
+export const BASIC_ESTIMATE_MB = 1200;
/** build-video's XFADE_BATCH_DEFAULT: the segments one crossfade pass opens. */
export const XFADE_BATCH = 24;
@@ -120,7 +127,7 @@ export function chromeEstimateMb(env = process.env, cores = machineCores()) {
return RENDER_CHROME_BASE_MB * Math.min(chromeLayers(env), w) + RENDER_CHROME_PER_WORKER_MB * w;
}
-const OVERRIDE = { render: "UMTOOL_RENDER_ESTIMATE_MB", ladder: "UMTOOL_LADDER_ESTIMATE_MB" };
+const OVERRIDE = { render: "UMTOOL_RENDER_ESTIMATE_MB", ladder: "UMTOOL_LADDER_ESTIMATE_MB", basic: "UMTOOL_RENDER_ESTIMATE_MB" };
/**
* The segments one pass holds open: `segments` capped by the batch size
@@ -137,14 +144,14 @@ export function openSegments(segments, batch = XFADE_BATCH) {
* The estimate (MB) a render of `kind` declares, or null to declare nothing
* (an override of `0`: the job then runs alone).
*
- * @param {"render" | "ladder"} [kind]
+ * @param {"render" | "ladder" | "basic"} [kind]
* @param {Record<string, string | undefined>} [env]
* @param {{ segments?: number | null, batch?: number, cores?: number }} [shape] what the run joins, the batch size, the machine's cores
* @returns {number | null}
*/
export function renderEstimateMb(kind = "render", env = process.env, { segments = null, batch = XFADE_BATCH, cores = machineCores() } = {}) {
const name = OVERRIDE[kind];
- if (!name) throw new Error(`renderEstimateMb: no kind '${kind}' (render, ladder)`);
+ if (!name) throw new Error(`renderEstimateMb: no kind '${kind}' (render, ladder, basic)`);
const raw = env[name];
if (raw != null && String(raw).trim() !== "") {
const n = Number(raw);
@@ -153,6 +160,7 @@ export function renderEstimateMb(kind = "render", env = process.env, { segments
// Not a size: fall through to the measured default rather than run alone.
}
if (kind === "ladder") return LADDER_ESTIMATE_MB;
+ if (kind === "basic") return BASIC_ESTIMATE_MB;
const encode = RENDER_ENCODE_BASE_MB + RENDER_ENCODE_PER_SEGMENT_MB * openSegments(segments, batch);
return Math.max(encode, chromeEstimateMb(env, cores));
}
@@ -184,6 +192,8 @@ export function manifestSegments(manifest) {
* @returns {number | null}
*/
export function manifestEstimateMb(manifest, env = process.env, { xfade = true, single = false, batch = XFADE_BATCH } = {}) {
+ // A basic cut (render.mode, as resolved: a take's render manifest carries its preset laid) is one encode at a time.
+ if (manifest?.render?.mode === "basic") return renderEstimateMb("basic", env);
const crossfades = xfade && (manifest?.render?.transition ?? 0.5) !== 0;
const segments = single || (manifest && !crossfades) ? 1 : manifestSegments(manifest);
return renderEstimateMb("render", env, { segments, batch });