commit fe2982232e3212c83da982d958eb4855da3164c3
parent 9472acd3cd2a835d7a5a760fc32e6788cc5c8ab7
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 9 Nov 2026 14:11:19 -0500
umtool: render.mode basic -- the footage alone, a basic preset, preset apply --replace
render.mode ("deck" | "basic", common look.mjs) is a look key like any other, so it
resolves where every layer does (preset -> manifest -> style -> take patch): the mode
a reader sees is the last layer's. A basic cut lays no brand and no intro
(selectVariant), its chrome is not checked (buildVideo, updatePreset), and the build
hands it to report-to-video/basic.mjs: each clip's played spans (Play's: cut|extent
less gaps), each cut from the window on disk that holds it (the build's own tiers,
per span), spliced at the first window's size and frame rate, render.basic.fade's
fades (audio 0.03 s at every span edge, video 0.15 s at the cut's ends), the build's
encode, the spans' files reused when their encode is the same. Post items, teasers,
cards and stills are left out with a note; a clip asking for a blur is refused unless
render.blur is off. Nothing is fetched. The heavy slot gets a basic estimate (1.2 GB).
Presets: the built-in basic ({render: {mode: basic}}); preset apply --replace clears
the manifest's own value of every key the preset sets, after an undo point.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
13 files changed, 832 insertions(+), 27 deletions(-)
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/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";
@@ -1588,32 +1588,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/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/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,290 @@
+// 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, 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. */
+export function spanFileName(n, id, k, argv) {
+ const key = createHash("sha256").update(JSON.stringify({ v: BASIC_SEGMENT_V, argv: argv.slice(0, -1) })).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 out = path.join(work, spanFileName(n, l.it.id, l.k, draft));
+ const argv = [...draft.slice(0, -1), out];
+ const have = await stat(out).then((s) => s.isFile() && s.size > 0, () => false);
+ if (!have) {
+ const tmp = `${out}.tmp.mp4`;
+ await exec(ffmpeg, [...draft.slice(0, -1), tmp]);
+ await rename(tmp, out);
+ }
+ 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 });
+ await exec(ffmpeg, concatArgs(list, dirs.final));
+ 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,186 @@
+// 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 { 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$/);
+});
+
+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);
+ // `--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 });
+ }
+});
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/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 });