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