Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 3d3d0f76a439eb3451de3e68533d4ce564dea4ed
parent 2b1b60819e4b00eb4628f994451082af3a748ecc
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu,  5 Nov 2026 15:56:10 -0500

umtool: a `video` timeline entry -- a file of the project played full frame with its own sound, nothing drawn over it

video-entry.mjs (validation, span, segment length, key, graph, the chrome
blackouts); build-video builds its segment (fit contain/cover, bass before the
loudness level, entrance lead + fade up, holdLast), lays every chrome region
with an enable that leaves its span out, and skips the end fade when the cut
ends on one; deck.mjs: its length, hideDeck, its entrance as a dip.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mumtool/lib/report/manifest.mjs | 3+++
Mumtool/report-to-video/build-video.mjs | 93+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------
Mumtool/report-to-video/clip-audio.mjs | 3++-
Mumtool/report-to-video/deck.mjs | 10++++++++++
Mumtool/report-to-video/lint.mjs | 3++-
Mumtool/report-to-video/package.json | 1+
Aumtool/report-to-video/video-entry.mjs | 264+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
7 files changed, 361 insertions(+), 16 deletions(-)

diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -40,6 +40,7 @@ import { verticalErrors } from "umtool-report-to-video/look"; import { LOOK_KEYS, applyLookPatch, 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 { validateVideoEntries } from "umtool-report-to-video/video-entry"; import { applySectionEnter } from "./sections.mjs"; import { citeUrlAt, parseClipSpec } from "./clipEditorModel.mjs"; import { addSectionIn, followSplitMarkers, moveBoundaryIn, moveToSectionIn, placeIn, reanchorMarkers, removeBoundaryIn, sectionModel, sectionWords, setSectionIn } from "./sectionEdit.mjs"; @@ -1901,6 +1902,8 @@ function structureErrors(manifest) { // The finale is one run of the last clips: moving a clip past it is refused. ...validateFinaleEntries(manifest), ...validateTeasers(manifest), + // A video entry (video-entry.mjs): a file of the project played full frame. + ...validateVideoEntries(manifest), ...validateNarration(manifest), ...validateDrafted(manifest), ...validatePublish(manifest), diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -148,7 +148,8 @@ import { resolveLocalSource, } from "./sources.mjs"; // A clip whose media is a file beside the manifest (`src`, `cues`). -import { clipLabel, createLocalMedia, hasLocalMedia, validateLocalMedia } from "./local-media.mjs"; +import { clipLabel, createLocalMedia, hasLocalMedia, resolveManifestPath, validateLocalMedia } from "./local-media.mjs"; +import { blackoutEnable, validateVideoEntries, videoBlackouts, videoFit, videoLead, videoMeasureFilter, videoSeconds, videoSegmentGraph, videoSegmentKey, videoSpan } from "./video-entry.mjs"; import { createPostChannelResolver, resolvePostLinks } from "./post-links.mjs"; import { ensureWriteDir } from "../lib/report/storage.mjs"; // The deck (`render.chrome`): its geometry, validation and schedule are pure @@ -1163,7 +1164,7 @@ export function needsFetchMessage(missing) { // The timeline's vocabulary is OPEN; the build loop treats everything it has // no other branch for as a clip, and so does this. -const NON_CLIP_TYPES = new Set(["card", "teaser", "image", "scroll", "chart", "ledger", "intro", "post"]); +const NON_CLIP_TYPES = new Set(["card", "teaser", "image", "scroll", "chart", "ledger", "intro", "post", "video"]); const isClipEntry = (e) => !NON_CLIP_TYPES.has(e?.type); /** @@ -2587,7 +2588,7 @@ async function buildMontageWall({ M, entries, render, outDir, timeline, provenan // A post item's record (`.post.json`, its key: post-render.mjs) and its combo pass's (`.combo.json`, the badge-less // `.plain.mp4`) ride with its segment, so a take --from another reuses a post item whose key still matches (the plain one too: // without it a reused badged segment would be taken for a plain one and badged again). -export const SEGMENT_FILE_SUFFIXES = Object.freeze([".mp4", ".cut.json", ".teaser.json", ".narration.json", ".intro.json", ".quote.txt", ".attrib.txt", ".channel.txt", ".post.json", ".combo.json", ".plain.mp4"]); +export const SEGMENT_FILE_SUFFIXES = Object.freeze([".mp4", ".cut.json", ".teaser.json", ".narration.json", ".intro.json", ".quote.txt", ".attrib.txt", ".channel.txt", ".post.json", ".combo.json", ".plain.mp4", ".video.json"]); /** * Before an entry's segment is rebuilt: each of its files in `segDir` that is @@ -2915,6 +2916,57 @@ export async function buildTeaserSegment(entry, { manifestPath, render, outDir, // * It reserves the footer's rows but draws nothing in them. The marker's // position is a function of `section`, which a still does not have, and a // timeline strip whose marker vanishes for six seconds reads as a bug. +/** + * A video entry's segment (video-entry.mjs): the project file's span scaled + * to the WHOLE frame by its `fit`, nothing drawn on it, its sound with the + * bass boost, levelled toward the cut's loudness target (measured with the + * boost), its entrance's black lead (`videoLead`) and fade up, and its hold. + * Rebuilt only when its key (`<id>.video.json`) changes; every file written + * through a rename, so a take's hard-linked segment is never written through. + */ +async function buildVideoEntrySegment(entry, render, outDir, baseDir, D) { + const seg = path.join(outDir, "segments", `${entry.id}.mp4`); + const rec = path.join(outDir, "segments", `${entry.id}.video.json`); + const src = resolveManifestPath(baseDir, entry.src, { allowAbsolute: render.allowAbsoluteSrc === true }); + if (src.error) throw new Error(`${entry.id}: src ${src.error}`); + const st = await stat(src.file).catch(() => null); + if (!st?.isFile()) throw new Error(`${entry.id}: no video at ${src.file} (src: ${entry.src})`); + const media = await probeMedia(src.file); + if (!media.hasVideo) throw new Error(`${entry.id}: ${entry.src} has no picture -- a video entry plays a video`); + const { stdout: aOut } = await execFileP(FFPROBE, ["-v", "error", "-select_streams", "a", "-show_entries", "stream=index", "-of", "csv=p=0", src.file]); + const hasAudio = aOut.trim().length > 0; + const span = videoSpan(entry, media.duration); + const lead = videoLead(entry, D); + const seconds = videoSeconds(entry, D, media.duration); + const target = hasAudio ? loudnessTargetOf(render) : null; + const key = videoSegmentKey({ entry, file: { size: st.size, mtimeMs: Math.round(st.mtimeMs), seconds: media.duration }, render, lead, target }); + const was = await readFile(rec, "utf8").then((t) => JSON.parse(t), () => null); + if (was?.key === key && (await exists(seg))) { + EMIT("note", { id: entry.id, message: `${entry.id}: video segment cached (${entry.src} ${span.from.toFixed(2)}–${span.to.toFixed(2)})` }); + return seg; + } + // Even loudness, as a clip's (render.look.loudness): the span measured THROUGH the bass boost, one gain. + let level = null; + if (target != null) { + const { stderr } = await execFileP(FFMPEG, [ + "-nostdin", "-hide_banner", "-ss", span.from.toFixed(3), "-to", span.to.toFixed(3), "-i", src.file, + "-vn", "-af", `${videoMeasureFilter(entry)},ebur128`, "-f", "null", "-", + ], { maxBuffer: 1 << 26 }).catch((e) => ({ stderr: e.stderr ?? "" })); + const measured = parseIntegratedLoudness(stderr); + level = { measured, gain: loudnessGain(measured, target), target }; + } + const graph = videoSegmentGraph({ entry, render, seconds, lead, hasAudio, gainDb: level?.gain ?? null, span }); + const tmp = `${seg}.tmp-${process.pid}.mp4`; + await execFileP(FFMPEG, [ + "-nostdin", "-v", "error", "-y", "-i", src.file, + "-filter_complex", graph, "-map", "[v]", "-map", "[a]", + ...encodeArgs(render), "-t", String(seconds), tmp, + ], { maxBuffer: 1 << 26 }); + await rename(tmp, seg); + await replaceFile(rec, JSON.stringify({ version: 1, id: entry.id, key, src: entry.src, span, lead, seconds, fit: videoFit(entry), loudness: level }, null, 2) + "\n"); + return seg; +} + async function buildImageSegment(entry, render, outDir, chrome, provenance, baseDir, framing = null) { const seg = path.join(outDir, "segments", `${entry.id}.mp4`); const pal = render.palette; @@ -3625,7 +3677,9 @@ export function railFilterChain(rail, assets, times, render, inLabel, firstInput * the deadlock the rail's five chained loops hit cannot happen here. */ export function chromeOverlayChain(render, regions, inLabel, firstInputIdx, opts = {}) { - const { outLabel = "[hfout]", final = true } = opts; + const { outLabel = "[hfout]", final = true, blackouts = null, shift = 0 } = opts; + // The video entries' spans (video-entry.mjs videoBlackouts), cut seconds; "" with none. + const off = blackoutEnable(blackouts, shift); const inputs = []; const parts = []; let lab = inLabel; @@ -3680,7 +3734,7 @@ export function chromeOverlayChain(render, regions, inLabel, firstInputIdx, opts parts.push(`${src}format=rgba[hfa${i}]`); src = `[hfa${i}]`; } - parts.push(`${lab}${src}overlay=x=${r.x}:y=${r.y}:format=yuv444:${posts ? "eof_action=pass" : "shortest=1"}${out}`); + parts.push(`${lab}${src}overlay=x=${r.x}:y=${r.y}:format=yuv444:${posts ? "eof_action=pass" : "shortest=1"}${off}${out}`); lab = out; }); if (final) parts.push(`${lab}format=yuv420p[vout]`); @@ -4351,7 +4405,8 @@ export async function cutJoins({ schedule = null, entries, segments, render }) { Math.round((base?.[i]?.hold ?? 0) * render.fps); const seconds = endFadeOf(render); let fade = null; - if (seconds > 0 && segments.length) { + // A cut that ends on a video entry ENDS on its final frame (video-entry.mjs): no end fade. + if (seconds > 0 && segments.length && entries[segments.length - 1]?.type !== "video") { const last = segments.length - 1; fade = { seconds, lastFrame: (await cutFrames(last)) - 1 }; } @@ -4849,6 +4904,7 @@ export function xfadeConcatArgs({ segments, durs, render, outPath, railPlan = nu ? chromeOverlayChain(render, chromeIn.regions, vlab, main.length + railInputs, { outLabel: chromeIn.outLabel, final: !rc, + blackouts: chromeIn.blackouts ?? null, }) : null; if (hf) parts.push(hf.chain); @@ -4961,8 +5017,9 @@ export function chunkVideoArgs({ segments, durs, starts, span, D, render, joins } } const first0 = segs.length; - const hf = regions.length ? chromeOverlayChain(render, regions, "[vw]", first0, { final: true }) : null; - const hk = keyRegions.length ? chromeOverlayChain(render, keyRegions, "[vw]", first0, { final: true }) : null; + const bo = { blackouts: chrome?.blackouts ?? null, shift: a / fps }; + const hf = regions.length ? chromeOverlayChain(render, regions, "[vw]", first0, { final: true, ...bo }) : null; + const hk = keyRegions.length ? chromeOverlayChain(render, keyRegions, "[vw]", first0, { final: true, ...bo }) : null; let tail = "[vw]"; if (hf) { parts.push(hf.chain); @@ -5558,7 +5615,7 @@ async function applyRail(inPath, outPath, render, railPlan, preview, dips = null * function draws one. */ export function applyChromeArgs(inPath, outPath, render, chromePlan, preview = null, dips = null) { - const hf = chromeOverlayChain(render, chromePlan.regions, "[0:v]", 1, { final: true }); + const hf = chromeOverlayChain(render, chromePlan.regions, "[0:v]", 1, { final: true, blackouts: chromePlan.blackouts ?? null, shift: preview ? Number(preview.start) : 0 }); // The dips over the overlay: the whole frame, the panel with the footage. const dp = dipParts(hf.outLabel, dips, render.fps, { shift: preview ? Number(preview.start) : 0 }); return [ @@ -5636,7 +5693,7 @@ export function previewFromSegmentsArgs({ segments, durs, starts, D, at, dur, re const T = Number(dur).toFixed(3); parts.push(`${vlab}trim=start=${S}:duration=${T},setpts=PTS-STARTPTS[vw]`); parts.push(`${alab}atrim=start=${S}:duration=${T},asetpts=PTS-STARTPTS[aw]`); - const hf = chromeOverlayChain(render, chromePlan.regions, "[vw]", segs.length, { final: true }); + const hf = chromeOverlayChain(render, chromePlan.regions, "[vw]", segs.length, { final: true, blackouts: chromePlan.blackouts ?? null, shift: Number(at) }); parts.push(hf.chain); // The cut's dips (its whole joins and lengths), in the window's clock. const dp = dipParts(hf.outLabel, dipWindows(joins, durs, D, render.fps), render.fps, { shift: Number(at) }); @@ -5773,7 +5830,10 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro await logRebuild(outDir, { phase: "chrome", seconds: Number(((Date.now() - tAll) / 1000).toFixed(1)), workers: pool.budget, renders: CHROME_LAYERS, layers }); } - return { regions, outLabel: "[hfout]" }; + // Over a video entry the chrome is OFF (video-entry.mjs): each region's overlay leaves its span out. + // Only when the cut has one, so every other cut's graph is the one it was. + const blackouts = videoBlackouts(schedule); + return { regions, outLabel: "[hfout]", ...(blackouts.length ? { blackouts } : {}) }; } /** @@ -6387,7 +6447,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly // manifest, deck or not: both are made where the cut is joined. { const errors = [ - ...validateCutEdits(whole), ...validateTeasers(whole), ...validateClaims(whole), ...validateThreadEntries(whole), + ...validateCutEdits(whole), ...validateTeasers(whole), ...validateVideoEntries(whole), ...validateClaims(whole), ...validateThreadEntries(whole), ...validateFlipEntries(whole), ...validateNarration(whole), ...validateDrafted(whole), ...validatePublish(whole), ...validateStatsEntries(whole), ...validateMontage(whole), ...validateAssist(whole), ...validateFxEntries(whole, { schedule: false }), ...validateTransitionStyle(whole), ...validateLook(whole), ...validateClipAudioEntries(whole), ...validateClipBlurEntries(whole), ...validateFinaleEntries(whole), @@ -6518,8 +6578,8 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly // A still has nothing to fetch and is already on disk, so this is a no-op // rather than an error: a bench that walks the timeline asking for each // entry's window should not have to know which kinds have one. - if (entry?.type === "image" || entry?.type === "teaser" || entry?.type === "post" || (entry?.type === "clip" && hasLocalMedia(entry))) { - const what = entry.type === "image" ? "an image" : entry.type === "teaser" ? "a teaser" : entry.type === "post" ? "a post item (its media is in the project)" : "a clip with its own `src`"; + if (entry?.type === "image" || entry?.type === "teaser" || entry?.type === "post" || entry?.type === "video" || (entry?.type === "clip" && hasLocalMedia(entry))) { + const what = entry.type === "image" ? "an image" : entry.type === "teaser" ? "a teaser" : entry.type === "video" ? "a video (a file of the project)" : entry.type === "post" ? "a post item (its media is in the project)" : "a clip with its own `src`"; EMIT("note", { message: `${fetchOnly} is ${what} entry — nothing to fetch` }); EMIT("done", { out: null, nothingToFetch: true }); return { out: null, failures: [] }; @@ -6738,6 +6798,11 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly } // A post item (post-render.mjs) keeps a segment `--from` linked in when its key matches (its record, `.post.json`, // linked beside it) and writes every file of its own through a rename -- never through the link -- when it does not. + // A video entry (video-entry.mjs): keyed like a post item, every file written through a rename. + if (entry.type === "video") { + EMIT("card", { id: entry.id, i, n: entries.length }); + return buildVideoEntrySegment(entry, render, outDir, manifestDir, D); + } if (entry.type !== "teaser" && entry.type !== "clip" && entry.type !== "post") { await detachSegmentFiles(path.join(outDir, "segments"), entry.id); } diff --git a/umtool/report-to-video/clip-audio.mjs b/umtool/report-to-video/clip-audio.mjs @@ -63,7 +63,8 @@ export function validateClipAudio(audio, where = "audio") { export function validateClipAudioEntries(manifest) { const errors = []; (manifest?.timeline ?? []).forEach((e, i) => { - if (e?.audio === undefined) return; + // A video entry's `audio` (bass, gain) is its own: video-entry.mjs validates it. + if (e?.audio === undefined || e?.type === "video") return; const where = `timeline[${i}] (${e.id ?? "?"}).audio`; if (e.type && e.type !== "clip") { errors.push(`${where}: only a clip's sound has these settings`); return; } errors.push(...validateClipAudio(e.audio, where)); diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs @@ -23,6 +23,7 @@ import { INTRO_SECONDS } from "yt-dlp-transcript-common/lib/report/intro.mjs"; import { attributionParts, deckSubtitle, deckSubtitleLines, formatDeckDate } from "./attribution.mjs"; import { postDeckText, postItemSeconds } from "./post-item.mjs"; +import { videoDip, videoEnter, videoHidesChrome, videoSeconds } from "./video-entry.mjs"; import { claimOf, marksOf, originalUrlAt, resolveFactcheck, roundStamps, stampSchedule, stampsWithFinale, tallyOf, tallyVerdicts, validateFactcheck, } from "./factcheck.mjs"; @@ -980,6 +981,8 @@ export function estimatedDuration(entry, render = {}, D = transitionOf(render)) return Math.max(1, gappedLength(from, to, renderGaps(entry, render))); } if (entry.type === "image") return Number(entry.seconds ?? 4); + // A video entry (video-entry.mjs): its entrance's black, its span, its hold. + if (entry.type === "video") return videoSeconds(entry, D); // A post item (post-item.mjs): its reading time and its attachments, or its `hold`. if (entry.type === "post") return postItemSeconds(entry, render); // The brand intro (intro.mjs) is exactly its `seconds` (introEntry fills the default). @@ -1025,6 +1028,8 @@ export function isMultiChannel(entries, provenance = {}) { export function hidesDeck(entry, deck) { // A teaser and the brand intro are full frame: never framed into the footage box. if (entry.type === "teaser" || entry.type === "intro") return true; + // A video entry is the whole frame, nothing over it -- unless it says `deck: "shown"`. + if (entry.type === "video") return videoHidesChrome(entry); return deck.overCards === "hide" && CARD_TYPES.includes(entry.type); } @@ -1285,6 +1290,9 @@ export function deckSchedule({ ...(marksOf(e, series).some((c) => c.at !== undefined) || claimClips.has(e.id) ? { sourceFrom: round(clipClock?.get(e.id) ?? fxClock?.get(e.id) ?? playWindow(e, render).from) } : {}), + // Only on a video entry (video-entry.mjs): the chrome off over it, and how it is entered. + ...(e.type === "video" && videoHidesChrome(e) ? { noChrome: true } : {}), + ...(e.type === "video" && videoEnter(e) ? { enter: videoEnter(e) } : {}), // Only on a finale clip, likewise. ...(finIds.has(e.id) ? { finale: true } : {}), // And off the rail, when the finale says so (finale.pips: false). @@ -3053,6 +3061,8 @@ export function snapToFrames(seconds, fps = 30) { * black (`dipWindows`' `until`) all fall on the same frame. */ export function dipOf(entry, fps = 30) { + // A video entry's entrance is a dip with no black (video-entry.mjs videoDip). + if (entry?.type === "video") return videoDip(entry); if (entry?.type !== "teaser" || !isObj(entry.dip)) return null; const { fade, black } = entry.dip; if (!numIn(fade, ...DIP_LIMITS.fade) || !numIn(black, ...DIP_LIMITS.black)) return null; diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs @@ -76,6 +76,7 @@ import { existsSync } from "node:fs"; import path from "node:path"; +import { validateVideoEntries } from "./video-entry.mjs"; import { deckOn, deckQrUrl, estimateSchedule, postArchiveUrl, postNativeId, postQrUrl, resolveDeck, teaserLines, validateChrome, validateCutEdits, validateDeckMarkers, validatePosts, validateTeasers, deckClaimNotes, validateDeckClaims, @@ -298,7 +299,7 @@ function fxLintSchedule(whole) { export function validatorErrors(whole) { const errors = [ - ...validateCutEdits(whole), ...validateTeasers(whole), ...validateClaims(whole), ...validateClipAudioEntries(whole), + ...validateCutEdits(whole), ...validateTeasers(whole), ...validateVideoEntries(whole), ...validateClaims(whole), ...validateClipAudioEntries(whole), ...validateThreadEntries(whole), ...validateFlipEntries(whole), ...validateNarration(whole), // The podcast's settings: its render refuses them, and `--lint` says so first. ...validatePodcast(whole), diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -18,6 +18,7 @@ }, "exports": { "./attribution": "./attribution.mjs", + "./video-entry": "./video-entry.mjs", "./site-links": "./site-links.mjs", "./brand": "./brand.mjs", "./brand-ids": "./brand-ids.mjs", diff --git a/umtool/report-to-video/video-entry.mjs b/umtool/report-to-video/video-entry.mjs @@ -0,0 +1,264 @@ +// 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 `render.look.loudness`'s target +// when the cut has one; `audio.gain` after that levelling, as a clip's +// `audio.gain` is. 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. + +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 = 1; + +/** 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`] : []), + ...(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 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. + * + * @param {{ segments: Array<{ type: string, start: number, end: number, noChrome?: boolean, dip?: object }>, total: number, fps?: number, transition?: number }} schedule + */ +export function videoBlackouts(schedule) { + const segs = schedule?.segments ?? []; + const D = Number(schedule?.transition ?? 0) || 0; + const fps = Number(schedule?.fps ?? 30) || 30; + const out = []; + segs.forEach((s, i) => { + if (s.type !== "video" || !s.noChrome) return; + const entered = i > 0 && s.enter ? s.start + D - 1 / fps : i > 0 ? s.start + D / 2 : 0; + const last = i === segs.length - 1; + const b = last ? Number(schedule.total ?? s.end) + 1 : s.end - D / 2; + out.push([Math.max(0, Math.round(entered * 1e4) / 1e4), Math.round(b * 1e4) / 1e4]); + }); + return out; +} + +/** 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("+")})'`; +}