// 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

`). // // 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 { censorRegionsOf } from "./clip-censor.mjs"; import { keptSpans, renderGaps } from "./gaps.mjs"; import { hasLocalMedia } from "./local-media.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.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} entry * @param {Record} [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} 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; } // Its hidden regions (clip-censor.mjs): a basic cut draws none, and privacy is not switched off by a mode -- // refused by name, whatever render.blur says. const boxes = censorRegionsOf(e, render, manifest?.provenance ?? {}); if (boxes.length) { errors.push(`${e.id} hides ${boxes.length} region(s) of its picture (render.censor / its censor), and a basic cut draws none: render it as a deck cut, or take the boxes off only if the regions may show`); 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

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 `/basic/`, reused by * the next render that asks the same encode of the same window. * * @param {{ manifest: Record, dirs: { dir: string, final: string }, only?: string | null, * deps: { sourceOf: (entry: Record, span: { from: number, to: number }) => Promise<{ path: string, fetchStart: number, source?: string } | null>, * encodeArgs: (render: Record) => string[], ffmpeg?: string, ffprobe?: string, emit?: (ev: string, fields?: Record) => void, * exec?: (bin: string, args: string[]) => Promise, 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 ), 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: "" }); 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 = tmpPathFor(dirs.final, { ext: ".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 }; }