// video-entry.mjs — a `video` timeline entry: a file of the project played // FULL FRAME, with its own sound, and nothing drawn over it. // // { "type": "video", "id": "fin-vid", // "src": "posts-media/ObviousRises-x/2117366108705767779/2117366108705767779_1.mp4", // "from": 32.26, // source seconds; default 0 // "to": 46.32, // source seconds; absent = the file's end // "fit": "contain", // "contain" (default: letter/pillarboxed on black) | "cover" (fills, cropped) // "audio": { "bass": 8, "gain": 0 }, // dB: a low shelf boost (100 Hz), and a gain // "enter": { "out": 0.5, "in": 0.5 }, // the join INTO it: the item before (its chrome too) fades to // // black over its last `out` s, then this fades up over `in` s; // // "cut" opts out (the cut's own transition) // "holdLast": 0, // s on its last frame after `to`; default 0 // "deck": "hidden", // default: NOTHING over it; "shown" keeps the chrome // "fileSeconds": 46.32, // the file's probed length, written by the CLI (the estimate's `to`) // "title": "…", "note": "…" } // // Where `image` is a still and a `clip` is a corpus window framed into the // deck's box, this is a plain project video as the whole 1920x1080 frame: the // deck, the header, the QR, the rail, the counters, the captions, every // overlay layer are off over it (build-video lays every chrome region with an // `enable` that leaves its span out -- `videoBlackouts`), and Play draws it // the same way. As the LAST entry the cut ENDS on its final frame: no end // fade (`render.endFade` is skipped), nothing after it. // // Its sound is levelled like a clip's: the bass boost first, the whole span // measured with it (ebur128), one gain toward the cut's level // (`videoLoudnessTarget`: `render.loudness`, else its narration's level); `audio.gain` after that levelling, as a // clip's `audio.gain` is; a boost's peaks limited under −1 dBFS. Fades only where the join needs them: the fade up after // the entrance's black, none at its end. // // A LEAF: no imports from build-video.mjs (it imports this), so umtool's // writers and Play read the same rules. import { NARRATION_DEFAULTS } from "./narration.mjs"; import { POST_NARRATION_DEFAULTS } from "./post-narration.mjs"; import { itemSpans } from "./full-frame.mjs"; const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); const fin = (v) => typeof v === "number" && Number.isFinite(v); export const VIDEO_FITS = Object.freeze(["contain", "cover"]); export const VIDEO_DECKS = Object.freeze(["hidden", "shown"]); export const VIDEO_AUDIO_LIMITS = Object.freeze({ gain: Object.freeze({ min: -20, max: 20, unit: "dB" }), bass: Object.freeze({ min: -12, max: 24, unit: "dB" }), }); export const VIDEO_ENTER_DEFAULT = Object.freeze({ out: 0.5, in: 0.5 }); export const VIDEO_ENTER_LIMITS = Object.freeze({ out: Object.freeze([0.1, 4]), in: Object.freeze([0, 4]) }); export const VIDEO_HOLD_MAX = 10; /** The bass boost: a low shelf at this frequency and width (ffmpeg `bass`). */ export const VIDEO_BASS = Object.freeze({ f: 100, w: 0.7 }); /** Bumped when the segment's drawing or sound changes, so every key changes with it. */ export const VIDEO_SEGMENT_V = 2; /** The ceiling a boosted video's sound is limited to: −1 dBFS. */ export const VIDEO_LIMIT = 0.891; /** The keys a video entry is SET by (umtool set / timeline add-video). */ export const VIDEO_SET_KEYS = Object.freeze(["src", "from", "to", "fit", "audio.bass", "audio.gain", "enter", "enter.out", "enter.in", "holdLast", "deck", "title", "note"]); export const isVideoEntry = (e) => e?.type === "video"; /** * Every reason a video entry cannot be built, as sentences naming `where`. * Its `src` is checked as a path here (relative, inside the project); whether * the file is there is the build's and the writer's (`validateVideoFiles`). */ export function validateVideoEntry(e, where = `timeline entry ${e?.id ?? "?"}`) { if (!isVideoEntry(e)) return []; const errors = []; if (typeof e.src !== "string" || !e.src.trim()) errors.push(`${where}: a video entry needs \`src\`, a file of the project`); else if (e.src.startsWith("/") || /^[a-z]+:\/\//i.test(e.src)) errors.push(`${where}.src must be a path relative to the project (got ${e.src})`); else if (e.src.split(/[\\/]/).includes("..")) errors.push(`${where}.src climbs out of the project (${e.src})`); if (e.from !== undefined && !(fin(e.from) && e.from >= 0)) errors.push(`${where}.from must be a number of seconds, 0 or more`); if (e.to !== undefined && e.to !== null && !(fin(e.to) && e.to > 0)) errors.push(`${where}.to must be a number of seconds (absent: the file's end)`); if (fin(e.to) && e.to - (fin(e.from) ? e.from : 0) < 0.2) errors.push(`${where}: to must be at least 0.2 s after from`); if (e.fileSeconds !== undefined && !(fin(e.fileSeconds) && e.fileSeconds > 0)) errors.push(`${where}.fileSeconds must be the file's length in seconds`); if (e.fit !== undefined && !VIDEO_FITS.includes(e.fit)) errors.push(`${where}.fit must be ${VIDEO_FITS.join(" or ")}`); if (e.deck !== undefined && !VIDEO_DECKS.includes(e.deck)) errors.push(`${where}.deck must be ${VIDEO_DECKS.join(" or ")}`); if (e.holdLast !== undefined && !(fin(e.holdLast) && e.holdLast >= 0 && e.holdLast <= VIDEO_HOLD_MAX)) errors.push(`${where}.holdLast must be from 0 to ${VIDEO_HOLD_MAX} seconds`); if (e.audio !== undefined && e.audio !== null) { if (!isObj(e.audio)) errors.push(`${where}.audio must be { bass, gain } in dB`); else { for (const k of Object.keys(e.audio)) if (!(k in VIDEO_AUDIO_LIMITS)) errors.push(`${where}.audio.${k} is not a video's audio setting (bass, gain)`); for (const [k, { min, max, unit }] of Object.entries(VIDEO_AUDIO_LIMITS)) { const v = e.audio[k]; if (v !== undefined && !(fin(v) && v >= min && v <= max)) errors.push(`${where}.audio.${k} must be a number from ${min} to ${max} (${unit})`); } } } if (e.enter !== undefined && e.enter !== "cut") { if (!isObj(e.enter)) errors.push(`${where}.enter must be "cut" or { out, in } in seconds`); else { for (const k of Object.keys(e.enter)) if (!(k in VIDEO_ENTER_LIMITS)) errors.push(`${where}.enter.${k} is not an entrance setting (out, in)`); for (const [k, [lo, hi]] of Object.entries(VIDEO_ENTER_LIMITS)) { const v = e.enter[k]; if (v !== undefined && !(fin(v) && v >= lo && v <= hi)) errors.push(`${where}.enter.${k} must be from ${lo} to ${hi} seconds`); } } } for (const k of ["title", "note"]) if (e[k] !== undefined && typeof e[k] !== "string") errors.push(`${where}.${k} must be text`); return errors; } /** Every video entry's problems in a manifest's timeline (and nothing for a timeline without one). */ export function validateVideoEntries(manifest) { const errors = []; (manifest?.timeline ?? []).forEach((e, i) => { if (isVideoEntry(e)) errors.push(...validateVideoEntry(e, `timeline[${i}] (${e?.id ?? "?"})`)); }); return errors; } /** Its fit: "contain" unless it says "cover". */ export const videoFit = (e) => (e?.fit === "cover" ? "cover" : "contain"); /** Is the chrome drawn over it? Only with `deck: "shown"`. */ export const videoHidesChrome = (e) => isVideoEntry(e) && e.deck !== "shown"; /** Its entrance, `{ out, in }` (the defaults filled), or null for `enter: "cut"`. */ export function videoEnter(e) { if (!isVideoEntry(e) || e.enter === "cut") return null; const o = isObj(e.enter) ? e.enter : {}; return { out: fin(o.out) ? o.out : VIDEO_ENTER_DEFAULT.out, in: fin(o.in) ? o.in : VIDEO_ENTER_DEFAULT.in }; } /** Its audio knobs, `{ bass, gain }` in dB (0 when absent). */ export function videoAudio(e) { const a = isObj(e?.audio) ? e.audio : {}; return { bass: fin(a.bass) ? a.bass : 0, gain: fin(a.gain) ? a.gain : 0 }; } /** * The source span it plays, `{ from, to }`: `to` absent is the file's end * (`fileSeconds`, the probed length the build passes, else the entry's own * `fileSeconds`). Clamped into the file when its length is known. */ export function videoSpan(e, fileSeconds = null) { const len = fin(fileSeconds) ? fileSeconds : fin(e?.fileSeconds) ? e.fileSeconds : null; const from = fin(e?.from) ? Math.max(0, e.from) : 0; let to = fin(e?.to) ? e.to : len ?? from + 5; if (len != null) to = Math.min(to, len); return { from: Math.min(from, Math.max(0, to - 0.2)), to }; } /** * The dark start of its segment, in its own clock: the dissolve into it (`D`) * when it enters with a fade -- the item before fades to black over that * dissolve (a dip, as a teaser's), so the video's first frame plays after it, * never under it. 0 for `enter: "cut"`. */ export const videoLead = (e, D = 0.5) => (videoEnter(e) ? Math.max(0, Number(D) || 0) : 0); /** * Its segment's length: the lead, the span (`to − from`) and `holdLast`. The * span is never shortened by the fades. */ export function videoSeconds(e, D = 0.5, fileSeconds = null) { const { from, to } = videoSpan(e, fileSeconds); const hold = fin(e?.holdLast) ? e.holdLast : 0; return Math.round((videoLead(e, D) + (to - from) + hold) * 10000) / 10000; } /** * Its entrance as a dip on the segment before it (deck.mjs `dipOf`'s shape, * `{ fade, black }`): the previous picture and every overlay fade to black * over `out`, with no held black (the fade up is the video's own). */ export function videoDip(e) { const en = videoEnter(e); return en ? { fade: en.out, black: 0 } : null; } /** * The ffmpeg graph for its segment: picture `[0:v]` → `[v]`, sound `[0:a]` → * `[a]` (or a silent bed when the file has none). Pure. `gainDb` is the * loudness gain the build measured (null: none); `lead` its dark start. */ export function videoSegmentGraph({ entry, render, seconds, lead = 0, hasAudio = true, gainDb = null, span }) { const { width: W, height: H, fps } = render; const n = (v) => String(Math.round(Number(v) * 1e6) / 1e6); const fit = videoFit(entry); const en = videoEnter(entry); const hold = fin(entry?.holdLast) ? entry.holdLast : 0; const scale = fit === "cover" ? [`scale=${W}:${H}:force_original_aspect_ratio=increase`, `crop=${W}:${H}`] : [`scale=${W}:${H}:force_original_aspect_ratio=decrease`, `pad=${W}:${H}:(ow-iw)/2:(oh-ih)/2:color=black`]; const v = [ `[0:v]trim=start=${n(span.from)}:end=${n(span.to)},setpts=PTS-STARTPTS`, `fps=${fps}`, ...scale, "setsar=1", ...(lead > 0 ? [`tpad=start_duration=${n(lead)}:start_mode=add:color=black`] : []), ...(hold > 0 ? [`tpad=stop_duration=${n(hold)}:stop_mode=clone`] : []), ...(en && en.in > 0 ? [`fade=t=in:st=${n(lead)}:d=${n(en.in)}`] : []), `trim=end=${n(seconds)}`, "format=yuv420p[v]", ].join(","); const { bass, gain } = videoAudio(entry); const ms = Math.round(lead * 1000); const a = hasAudio ? [ `[0:a]atrim=start=${n(span.from)}:end=${n(span.to)},asetpts=PTS-STARTPTS`, `aresample=${render.audioRate ?? 48000}`, ...(bass ? [`bass=g=${n(bass)}:f=${VIDEO_BASS.f}:w=${VIDEO_BASS.w}`] : []), ...(gainDb ? [`volume=${n(gainDb)}dB`] : []), ...(gain ? [`volume=${n(gain)}dB`] : []), // A boost's peaks under full scale (−1 dBFS): the encoder squashes what goes past it. ...(bass > 0 || gain > 0 ? [`alimiter=limit=${VIDEO_LIMIT}:level=false`] : []), ...(en && en.in > 0 ? [`afade=t=in:st=0:d=${n(en.in)}`] : []), ...(ms > 0 ? [`adelay=${ms}:all=1`] : []), `apad=whole_dur=${n(seconds)}`, `atrim=end=${n(seconds)}[a]`, ].join(",") : `anullsrc=r=${render.audioRate ?? 48000}:cl=${(render.audioChannels ?? 2) === 1 ? "mono" : "stereo"},atrim=end=${n(seconds)}[a]`; return `${v};${a}`; } /** * The loudness (LUFS) a video entry's sound is levelled to: the cut's target * (`render.loudness`, `loudnessTarget` the caller resolved) when it has one; * else the level the cut's own voice sits at -- its post items' narration * (`render.postNarration.lufs`, default −21) when it has post items, a * narrated card's (−17.7) otherwise -- so a hot meme does not jump out of the * cut. `{ target, basis }`. */ export function videoLoudnessTarget(render, timeline = [], loudnessTarget = null) { if (fin(loudnessTarget)) return { target: loudnessTarget, basis: "render.loudness" }; if ((timeline ?? []).some((e) => e?.type === "post")) { const l = render?.postNarration?.lufs; return { target: fin(l) ? l : POST_NARRATION_DEFAULTS.lufs, basis: "render.postNarration.lufs" }; } return { target: NARRATION_DEFAULTS.lufs, basis: "narration" }; } /** The audio chain the loudness is measured through: the bass boost, as the segment plays it. */ export function videoMeasureFilter(entry) { const { bass } = videoAudio(entry); return bass ? `bass=g=${bass}:f=${VIDEO_BASS.f}:w=${VIDEO_BASS.w}` : "anull"; } /** * Its segment's KEY: what it is built from -- the file (its path, size and * mtime), the span, the fit, the audio, the entrance, the hold, the lead (the * cut's transition), the frame and the loudness target. The same key: the * segment on disk is reused. */ export function videoSegmentKey({ entry, file, render, lead, target = null }) { const { from, to } = videoSpan(entry, file.seconds); return JSON.stringify({ v: VIDEO_SEGMENT_V, src: entry.src, size: file.size, mtime: file.mtimeMs, from, to, fit: videoFit(entry), audio: videoAudio(entry), enter: videoEnter(entry), holdLast: fin(entry.holdLast) ? entry.holdLast : 0, lead, frame: [render.width, render.height, render.fps, render.audioRate, render.audioChannels, render.crf ?? 20, render.preset ?? "medium"], target, }); } /** * The cut seconds the chrome is OFF over, `[a, b]` pairs from the schedule's * segments: each video entry that hides it, from the frame the dip into it * has made black (the segment's start + the dissolve − a frame; mid-dissolve * for `enter: "cut"`) to its end (mid-dissolve into the next, or the cut's * end). Empty for a cut without one -- and then nothing changes. The video * entries' share of the full-frame items (full-frame.mjs fullFrameItems, * which the build lays every chrome region's `enable` from). * * @param {{ segments: Array<{ type: string, start: number, end: number, noChrome?: boolean, dip?: object }>, total: number, fps?: number, transition?: number }} schedule */ export const videoBlackouts = (schedule) => itemSpans(schedule, "video"); /** An overlay's `enable` for blackouts in a stream whose clock starts `shift` s into the cut; "" with none. */ export function blackoutEnable(blackouts, shift = 0) { if (!blackouts?.length) return ""; const n = (v) => String(Math.round(Number(v) * 1e6) / 1e6); return `:enable='not(${blackouts.map(([a, b]) => `between(t,${n(a - shift)},${n(b - shift)})`).join("+")})'`; } /** * A video entry with `patch` applied (VIDEO_SET_KEYS; `audio.bass`, `enter.out` * dotted; `enter: "cut"` or `","`; null or "" removes a key). A new * object; the caller validates it (validateVideoEntry). Throws on a key it * does not set. */ export function applyVideoPatch(entry, patch) { const e = JSON.parse(JSON.stringify(entry)); const num = (k, v) => { const n = Number(v); if (!Number.isFinite(n)) throw new Error(`${k} must be a number (got ${v})`); return Math.round(n * 1000) / 1000; }; for (const [k, v] of Object.entries(patch ?? {})) { if (!VIDEO_SET_KEYS.includes(k)) throw new Error(`${k} is not a video entry's setting (${VIDEO_SET_KEYS.join(", ")})`); const clear = v === null || v === undefined || v === ""; const [head, sub] = k.split("."); if (sub) { if (head === "enter" && (e.enter === "cut" || !isObj(e.enter))) e.enter = {}; if (head === "audio" && !isObj(e.audio)) e.audio = {}; if (clear) delete e[head][sub]; else e[head][sub] = num(k, v); if (!Object.keys(e[head]).length) delete e[head]; continue; } if (clear) { delete e[k]; continue; } if (k === "from" || k === "to" || k === "holdLast") e[k] = num(k, v); else if (k === "enter") { if (v === "cut") e.enter = "cut"; else if (isObj(v)) e.enter = v; else { const [o, i] = String(v).split(",").map((x) => x.trim()); e.enter = { out: num("enter.out", o), ...(i !== undefined && i !== "" ? { in: num("enter.in", i) } : {}) }; } } else e[k] = String(v); } return e; }