// THE EFFECTS region for the deck (release 35, lane O2): eight opt-in overlay // effects drawn over the footage box by ONE HyperFrames page for the whole cut // (chrome-fx.mjs), laid over the cut like the stamps and the stats. // // render.chrome.fx: { // kineticQuote: { position, size, maxWords, clips? } the cited line word by word, the key phrase punched // redact: { position, size, maxWords, clips? } the cited line under black bars that lift as it is said // odometer: { position, label, at } rolling digits: the count goes up on each clip // scrubber: { position, thumbs } a date rail, the playhead sliding to each clip's day // glitch: { on, seconds, stamp, year, clips? } a VHS tear at each cut between years // (on "every": each cut; on "clips": the cut into each named clip; // year false: the tear bare, no big year) // thenNow: { pairs: [{ then, now }], seconds, dates } a moving divider between a THEN clip and its NOW // receipts: { position, width } a clip's screenshots fan in, a marker swipes the cited line // zoom: { width } a screenshot pushed in on its focus box // punchIn: { scale, hold, anchor, auto } the footage snaps in on a moment (a laugh), then back // whip: { on } the cut between two clips slides like a whip pan // } // timeline entry: "fx": { "punch": "…", "quote": false, "punchIn": [, …], // "speakers": [{ "at": , "who": 0 | 1 }], // "receipts": [{ "shot": "shots/a.png", "mark": [x0, y0, x1, y1], "at"?: , "hold"?: s, "label"?: "captured 30 Oct" }], // "zoom": { "shot": "shots/b.png", "focus": [x0, y0, x1, y1], "at": 1.2, "hold": 4 } } // (a zoom is up from 0.2 s into its clip's clean span -- the card rising in // over 0.38 s, its focus box drawing at +0.55 s -- pushes in at `at` (seconds // into the clip; default as soon as the box has drawn) over FX_MOTION.push, // then drifts on the detail; it leaves (a 0.3 s fade) 0.3 s before the clip's // clean span ends -- or, with `hold`, that many seconds after the push lands.) // // Every key is opt-in; `render.chrome.fx` absent (or null, or {}) draws nothing // and every schedule, graph and file is byte for byte what it was. An entry's // `fx` is inert until its effect is on. `mark` and `focus` are fractions of the // screenshot (0..1, left, top, right, bottom). // // PURE, like stats.mjs: validation, the defaults, the schedule, the geometry and // the cue list. No fs, no ffmpeg. deck.mjs imports this file -- never the other // way round -- and it imports nothing of the montage's (montage.mjs imports // deck.mjs), so the few date and phrase helpers it needs are its own. import { COMPOSITION_PARAMS } from "yt-dlp-transcript-common/lib/report/fxParams.mjs"; import { offsetIn, sourceAtOffset } from "./gaps.mjs"; import { settleFirstFrame } from "./cue-start.mjs"; /** Each effect's key under `render.chrome.fx`, in the order the page stacks them (later on top). */ export const FX_KEYS = Object.freeze(["scrubber", "receipts", "zoom", "kineticQuote", "redact", "odometer", "punchIn", "thenNow", "whip", "glitch"]); export const FX_CORNERS = Object.freeze(["top-left", "top-right", "bottom-left", "bottom-right"]); export const FX_QUOTE_POSITIONS = Object.freeze(["bottom", "top"]); export const FX_RAIL_POSITIONS = Object.freeze(["top", "bottom"]); export const FX_SIDES = Object.freeze(["right", "left"]); export const FX_GLITCH_ON = Object.freeze(["year", "every", "clips"]); /** A zoom's `hold` (seconds on the detail after the push lands): its bounds. Absent: until its clip's end. */ export const FX_ZOOM_HOLD = Object.freeze({ min: 0.5, max: 10 }); /** The most clips a glitch on "clips" may name. */ export const FX_GLITCH_CLIPS_MAX = 60; export const FX_DATES = Object.freeze(["date", "year"]); export const FX_ODOMETER_AT = Object.freeze(["phrase", "start"]); export const FX_SHOT_EXTS = Object.freeze([".png", ".jpg", ".jpeg", ".webp"]); export const FX_RECEIPTS_MAX = 4; /** The longest caption a receipt carries under its screenshot (when it was taken, what it is). */ export const FX_RECEIPT_LABEL_MAX = 80; export const FX_ANCHORS = Object.freeze(["upper", "center"]); export const FX_WHIP_ON = Object.freeze(["every", "year"]); /** A kinetic line's two voices when the manifest names none: the palette's fg, then THEN's blue. */ export const FX_VOICE_COLORS = Object.freeze([null, "#6fa8dc"]); /** The words a laugh is written as in captions (`punchIn.auto`). */ export const FX_LAUGH_RE = /^(?:(?:ha){2,}h?|(?:he){2,}|lol|lmao|lmfao|rofl|laughs?|laughing|laughter)$/i; /** Every effect's settings and their defaults. A manifest names only what it changes. */ export const FX_DEFAULTS = Object.freeze({ kineticQuote: Object.freeze({ position: "bottom", size: 54, maxWords: 12, clips: null, speakers: "auto", voices: null }), redact: Object.freeze({ position: "bottom", size: 44, maxWords: 14, clips: null }), odometer: Object.freeze({ position: "top-right", label: "times", at: "phrase" }), scrubber: Object.freeze({ position: "top", thumbs: true }), glitch: Object.freeze({ on: "year", seconds: 0.5, stamp: true, year: true, clips: null }), thenNow: Object.freeze({ pairs: Object.freeze([]), seconds: 0.6, dates: "date" }), receipts: Object.freeze({ position: "right", width: 0.36 }), zoom: Object.freeze({ width: 0.56 }), punchIn: Object.freeze({ scale: 1.2, hold: 1.4, anchor: "upper", auto: true }), whip: Object.freeze({ on: "every" }), }); /** * Each effect's TUNABLE params (release 38), keyed by effect: the settings the * video assistant's `fx` op may set by name ("fx."), with the bounds * validateFx holds them to (declared in common lib/report/fxParams.mjs; * fx-params.test.mjs keeps the two in step). */ export const FX_PARAMS = Object.freeze( Object.fromEntries(Object.entries(COMPOSITION_PARAMS).filter(([id]) => id.startsWith("fx.")).map(([id, ps]) => [id.slice(3), ps])), ); /** The motion every effect shares, in seconds. */ export const FX_MOTION = Object.freeze({ word: 0.14, // a word coming in punch: 0.32, // the key phrase's pop bar: 0.22, // a redaction bar lifting page: 0.22, // a page of words in and out roll: 0.55, // the odometer's digits rail: 0.6, // the scrubber's playhead travelling to the next day thumb: 0.25, // its thumbnail handing over fan: 0.42, // one receipt flying in fanGap: 0.18, // between two receipts marker: 0.55, // the marker swiping push: 1.0, // the zoom's push in outline: 0.45, // the zoom's focus box drawing tag: 0.3, // a THEN/NOW tag in or out hold: 1.2, // a NOW tag resting after the wipe }); /** Instant cues still take a millisecond: a zero-duration tween has its own seek rules. */ export const INSTANT = 0.001; const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); const numIn = (v, lo, hi) => typeof v === "number" && Number.isFinite(v) && v >= lo && v <= hi; const r3 = (v) => Math.round(v * 1000) / 1000; const r4 = (v) => Math.round(v * 10000) / 10000; /** The effects that are on: their keys, each with an object (not null) under `render.chrome.fx`. */ export function fxKeysOn(render) { const fx = render?.chrome?.fx; if (!isObj(fx)) return []; return FX_KEYS.filter((k) => isObj(fx[k])); } /** Is any effect on? Absent, nothing in this file runs and nothing is drawn. */ export const fxOn = (render) => fxKeysOn(render).length > 0; /** One effect's settings with every default filled in, or null when it is off. */ export function resolveFx(render, key) { const v = render?.chrome?.fx?.[key]; if (!isObj(v)) return null; return { ...FX_DEFAULTS[key], ...v }; } // --------------------------------------------------------------------------- // Validation: one validator, called by validateChrome (the render keys) and by // the build and the lint (the entries, against the whole manifest). // --------------------------------------------------------------------------- const ALLOWED = { kineticQuote: ["position", "size", "maxWords", "clips", "speakers", "voices"], redact: ["position", "size", "maxWords", "clips"], odometer: ["position", "label", "at"], scrubber: ["position", "thumbs"], glitch: ["on", "seconds", "stamp", "year", "clips"], thenNow: ["pairs", "seconds", "dates"], receipts: ["position", "width"], zoom: ["width"], punchIn: ["scale", "hold", "anchor", "auto"], whip: ["on"], }; const oneOf = (list) => list.map((x) => `"${x}"`).join(", "); /** * Every reason `render.chrome.fx` cannot be built, as sentences (empty: it * can). Unknown keys are refused, as the deck's are. validateChrome calls it. * * @returns {string[]} */ export function validateFx(fx, where = "render.chrome.fx") { if (fx === undefined || fx === null) return []; if (!isObj(fx)) return [`${where} must be an object`]; const errors = []; for (const k of Object.keys(fx)) { if (!FX_KEYS.includes(k)) { errors.push(`${where}.${k} is not an effect (${FX_KEYS.join(", ")})`); continue; } const v = fx[k]; if (v === null) continue; if (!isObj(v)) { errors.push(`${where}.${k} must be an object ({} for the defaults) or null`); continue; } const w = `${where}.${k}`; for (const key of Object.keys(v)) if (!ALLOWED[k].includes(key)) errors.push(`${w}.${key} is not a ${k} setting`); if (k === "kineticQuote" || k === "redact") { if (v.position !== undefined && !FX_QUOTE_POSITIONS.includes(v.position)) errors.push(`${w}.position must be ${oneOf(FX_QUOTE_POSITIONS)}`); if (v.size !== undefined && !numIn(v.size, 24, 96)) errors.push(`${w}.size must be from 24 to 96`); if (v.maxWords !== undefined && !(Number.isInteger(v.maxWords) && numIn(v.maxWords, 3, 30))) { errors.push(`${w}.maxWords must be a whole number from 3 to 30`); } if (v.clips !== undefined && v.clips !== null) { if (!Array.isArray(v.clips) || !v.clips.length || !v.clips.every((c) => typeof c === "string" && c)) { errors.push(`${w}.clips must be a list of clip ids, or null for every clip`); } } } if (k === "kineticQuote") { if (v.speakers !== undefined && v.speakers !== "auto" && v.speakers !== false) errors.push(`${w}.speakers must be "auto" or false`); if (v.voices !== undefined && v.voices !== null) { if (!Array.isArray(v.voices) || v.voices.length < 1 || v.voices.length > 2) errors.push(`${w}.voices must be a list of one or two { label?, color? }`); else { v.voices.forEach((x, i) => { if (!isObj(x) || Object.keys(x).some((kk) => kk !== "label" && kk !== "color")) errors.push(`${w}.voices[${i}] must be { label?, color? }`); else { if (x.label !== undefined && !(typeof x.label === "string" && x.label.trim().length <= 20)) errors.push(`${w}.voices[${i}].label must be at most 20 characters`); if (x.color !== undefined && !/^#[0-9a-fA-F]{6}$/.test(String(x.color))) errors.push(`${w}.voices[${i}].color must be a #rrggbb colour`); } }); } } } if (k === "punchIn") { if (v.scale !== undefined && !numIn(v.scale, 1.05, 2)) errors.push(`${w}.scale must be from 1.05 to 2`); if (v.hold !== undefined && !numIn(v.hold, 0.2, 6)) errors.push(`${w}.hold must be from 0.2 to 6 seconds`); if (v.anchor !== undefined && !FX_ANCHORS.includes(v.anchor)) errors.push(`${w}.anchor must be ${oneOf(FX_ANCHORS)}`); if (v.auto !== undefined && typeof v.auto !== "boolean") errors.push(`${w}.auto must be true or false`); } if (k === "whip") { if (v.on !== undefined && !FX_WHIP_ON.includes(v.on)) errors.push(`${w}.on must be ${oneOf(FX_WHIP_ON)}`); } if (k === "odometer") { if (v.position !== undefined && !FX_CORNERS.includes(v.position)) errors.push(`${w}.position must be ${oneOf(FX_CORNERS)}`); if (v.label !== undefined && !(typeof v.label === "string" && v.label.trim().length <= 24)) { errors.push(`${w}.label must be text of at most 24 characters ("" for none)`); } if (v.at !== undefined && !FX_ODOMETER_AT.includes(v.at)) errors.push(`${w}.at must be ${oneOf(FX_ODOMETER_AT)}`); } if (k === "scrubber") { if (v.position !== undefined && !FX_RAIL_POSITIONS.includes(v.position)) errors.push(`${w}.position must be ${oneOf(FX_RAIL_POSITIONS)}`); if (v.thumbs !== undefined && typeof v.thumbs !== "boolean") errors.push(`${w}.thumbs must be true or false`); } if (k === "glitch") { if (v.on !== undefined && !FX_GLITCH_ON.includes(v.on)) errors.push(`${w}.on must be ${oneOf(FX_GLITCH_ON)}`); if (v.seconds !== undefined && !numIn(v.seconds, 0.2, 1.5)) errors.push(`${w}.seconds must be from 0.2 to 1.5`); if (v.stamp !== undefined && typeof v.stamp !== "boolean") errors.push(`${w}.stamp must be true or false`); if (v.year !== undefined && typeof v.year !== "boolean") errors.push(`${w}.year must be true or false`); // `clips` is the list `on: "clips"` tears into, and nothing else's. const listed = v.clips !== undefined && v.clips !== null; if (listed && (!Array.isArray(v.clips) || !v.clips.length || v.clips.length > FX_GLITCH_CLIPS_MAX || !v.clips.every((c) => typeof c === "string" && c))) { errors.push(`${w}.clips must be a list of 1 to ${FX_GLITCH_CLIPS_MAX} clip ids`); } if (v.on === "clips" && !listed) errors.push(`${w}.clips is needed with on "clips": the clips whose cut in tears`); if (listed && v.on !== "clips") errors.push(`${w}.clips is only for on "clips" (on is "${v.on ?? FX_DEFAULTS.glitch.on}")`); } if (k === "thenNow") { if (v.seconds !== undefined && !numIn(v.seconds, 0.3, 2)) errors.push(`${w}.seconds must be from 0.3 to 2`); if (v.dates !== undefined && !FX_DATES.includes(v.dates)) errors.push(`${w}.dates must be ${oneOf(FX_DATES)}`); if (v.pairs !== undefined) { if (!Array.isArray(v.pairs) || !v.pairs.length) errors.push(`${w}.pairs must be a list of { then, now } clip ids`); else { v.pairs.forEach((p, i) => { if (!isObj(p) || typeof p.then !== "string" || !p.then || typeof p.now !== "string" || !p.now || Object.keys(p).some((x) => x !== "then" && x !== "now")) { errors.push(`${w}.pairs[${i}] must be { "then": , "now": }`); } }); } } else errors.push(`${w}.pairs is needed: which THEN clip hands over to which NOW clip`); } if (k === "receipts") { if (v.position !== undefined && !FX_SIDES.includes(v.position)) errors.push(`${w}.position must be ${oneOf(FX_SIDES)}`); if (v.width !== undefined && !numIn(v.width, 0.2, 0.6)) errors.push(`${w}.width must be from 0.2 to 0.6 (of the footage box)`); } if (k === "zoom") { if (v.width !== undefined && !numIn(v.width, 0.3, 0.9)) errors.push(`${w}.width must be from 0.3 to 0.9 (of the footage box)`); } } const kq = fx.kineticQuote, rd = fx.redact; if (isObj(kq) && isObj(rd)) { const a = Array.isArray(kq.clips) ? kq.clips : null; const b = Array.isArray(rd.clips) ? rd.clips : null; if (!a && !b) errors.push(`${where}.kineticQuote and ${where}.redact both draw every clip's line: give one of them clips`); else if (a && b && a.some((c) => b.includes(c))) { errors.push(`${where}.kineticQuote and ${where}.redact both name ${a.filter((c) => b.includes(c)).join(", ")}: one treatment a clip`); } } return errors; } const rect01 = (r) => Array.isArray(r) && r.length === 4 && r.every((v) => numIn(v, 0, 1)) && r[2] > r[0] && r[3] > r[1]; function shotError(shot, what) { if (typeof shot !== "string" || !shot.trim()) return `${what} must be a path beside the manifest`; if (/^[a-z]+:\/\//i.test(shot)) return `${what} must be a file beside the manifest, not a URL`; const ext = shot.slice(shot.lastIndexOf(".")).toLowerCase(); if (!FX_SHOT_EXTS.includes(ext)) return `${what} must be ${FX_SHOT_EXTS.join(", ")}`; return null; } /** * Every reason the entries' `fx` and the effects' clip lists cannot be built, * against the whole manifest: a bad entry `fx`, a clip list naming no clip, a * THEN/NOW pair that is not a clip and the very next entry, and the popup * posts moving the footage the effects are drawn over -- with the cut's deck * `schedule`, only while they coincide (fxShiftConflicts); `schedule: false` * leaves that to a later check against the real schedule. * * @param {Record} manifest * @param {{ schedule?: Record | false | null }} [opts] * @returns {string[]} */ export function validateFxEntries(manifest, { schedule = undefined } = {}) { const errors = []; const timeline = manifest?.timeline ?? []; const render = manifest?.render ?? {}; for (const e of timeline) { if (e?.fx === undefined) continue; // A post item's `fx` is its own list of effects (a word zoom), post-item.mjs's to judge (word-zoom.mjs). if (e.type === "post") continue; const w = `timeline entry ${e.id ?? "?"}: fx`; if (!isObj(e.fx)) { errors.push(`${w} must be an object`); continue; } if (e.type !== "clip" && e.type !== "image") errors.push(`${w} is for a clip or an image`); for (const k of Object.keys(e.fx)) { if (!["punch", "quote", "receipts", "zoom", "punchIn", "speakers"].includes(k)) errors.push(`${w}.${k} is not an effect field`); } if (e.fx.punch !== undefined && !(typeof e.fx.punch === "string" && e.fx.punch.trim() && e.fx.punch.length <= 120)) { errors.push(`${w}.punch must be the words to punch (at most 120 characters)`); } if (e.fx.quote !== undefined && typeof e.fx.quote !== "boolean") errors.push(`${w}.quote must be true or false`); if (e.fx.punchIn !== undefined) { const ok = Array.isArray(e.fx.punchIn) && e.fx.punchIn.length > 0 && e.fx.punchIn.length <= 8 && e.fx.punchIn.every((t) => typeof t === "number" && Number.isFinite(t) && t >= 0); if (!ok) errors.push(`${w}.punchIn must be a list of 1 to 8 source seconds`); else if (e.type === "clip" && Number.isFinite(e.start) && Number.isFinite(e.end) && e.fx.punchIn.some((t) => t < e.start || t > e.end)) { errors.push(`${w}.punchIn has a second outside the clip (${e.start}–${e.end})`); } } if (e.fx.speakers !== undefined) { const ok = Array.isArray(e.fx.speakers) && e.fx.speakers.length > 0 && e.fx.speakers.every((x) => isObj(x) && Number.isFinite(x.at) && (x.who === 0 || x.who === 1) && Object.keys(x).every((kk) => kk === "at" || kk === "who")); if (!ok) errors.push(`${w}.speakers must be a list of { at: , who: 0 | 1 }`); } if (e.fx.receipts !== undefined) { const r = e.fx.receipts; if (!Array.isArray(r) || !r.length || r.length > FX_RECEIPTS_MAX) { errors.push(`${w}.receipts must be a list of 1 to ${FX_RECEIPTS_MAX} screenshots`); } else { r.forEach((c, i) => { if (!isObj(c)) { errors.push(`${w}.receipts[${i}] must be { shot, mark?, at?, hold?, label? }`); return; } for (const k of Object.keys(c)) if (!["shot", "mark", "at", "hold", "label"].includes(k)) errors.push(`${w}.receipts[${i}].${k} is not a receipt field`); if (c.label !== undefined && !(typeof c.label === "string" && c.label.trim() && c.label.length <= FX_RECEIPT_LABEL_MAX)) { errors.push(`${w}.receipts[${i}].label must be a line of at most ${FX_RECEIPT_LABEL_MAX} characters`); } if (c.at !== undefined) { if (!(typeof c.at === "number" && Number.isFinite(c.at))) errors.push(`${w}.receipts[${i}].at must be a source second`); else if (e.type === "clip" && Number.isFinite(e.start) && Number.isFinite(e.end) && (c.at < e.start || c.at > e.end)) { errors.push(`${w}.receipts[${i}].at is outside the clip (${e.start}–${e.end})`); } } if (c.hold !== undefined && !numIn(c.hold, FX_ZOOM_HOLD.min, FX_ZOOM_HOLD.max)) { errors.push(`${w}.receipts[${i}].hold must be from ${FX_ZOOM_HOLD.min} to ${FX_ZOOM_HOLD.max} seconds (up after it lands), or absent for the rest of the clip`); } const se = shotError(c.shot, `${w}.receipts[${i}].shot`); if (se) errors.push(se); if (c.mark !== undefined && !rect01(c.mark)) errors.push(`${w}.receipts[${i}].mark must be [left, top, right, bottom], fractions of the shot`); }); } } if (e.fx.zoom !== undefined) { const z = e.fx.zoom; if (!isObj(z)) errors.push(`${w}.zoom must be { shot, focus, at?, hold? }`); else { for (const k of Object.keys(z)) if (!["shot", "focus", "at", "hold"].includes(k)) errors.push(`${w}.zoom.${k} is not a zoom field`); const se = shotError(z.shot, `${w}.zoom.shot`); if (se) errors.push(se); if (!rect01(z.focus)) errors.push(`${w}.zoom.focus must be [left, top, right, bottom], fractions of the shot`); if (z.at !== undefined && !numIn(z.at, 0, 600)) errors.push(`${w}.zoom.at must be seconds into the clip`); if (z.hold !== undefined && !numIn(z.hold, FX_ZOOM_HOLD.min, FX_ZOOM_HOLD.max)) { errors.push(`${w}.zoom.hold must be from ${FX_ZOOM_HOLD.min} to ${FX_ZOOM_HOLD.max} seconds (on the detail after the push), or absent for the whole clip`); } } } } const fx = render?.chrome?.fx; if (!isObj(fx)) return errors; const clipIds = new Set(timeline.filter((e) => e?.type === "clip").map((e) => e.id)); for (const k of ["kineticQuote", "redact"]) { for (const id of Array.isArray(fx[k]?.clips) ? fx[k].clips : []) { if (!clipIds.has(id)) errors.push(`render.chrome.fx.${k}.clips names ${id}, which is not a clip of the cut`); } } // A glitch on "clips" tears at the cut INTO each named clip: the entry // before it must be a clip too (a cut between two clips, as ever). if (isObj(fx.glitch) && fx.glitch.on === "clips" && Array.isArray(fx.glitch.clips)) { const w = "render.chrome.fx.glitch.clips"; const missing = fx.glitch.clips.filter((id) => !clipIds.has(id)); if (missing.length) errors.push(`${w} names ${missing.join(", ")}, which ${missing.length === 1 ? "is not a clip" : "are not clips"} of the cut`); const at = new Map(timeline.map((e, i) => [e?.id, i])); const noCut = fx.glitch.clips.filter((id) => clipIds.has(id) && timeline[at.get(id) - 1]?.type !== "clip"); if (noCut.length) errors.push(`${w} names ${noCut.join(", ")}, with no clip right before (the glitch tears at a cut between two clips)`); } if (isObj(fx.thenNow) && Array.isArray(fx.thenNow.pairs)) { const at = new Map(timeline.map((e, i) => [e?.id, i])); const used = new Set(); fx.thenNow.pairs.forEach((p, i) => { if (!isObj(p)) return; const a = at.get(p.then), b = at.get(p.now); const w = `render.chrome.fx.thenNow.pairs[${i}]`; if (a === undefined || timeline[a].type !== "clip") errors.push(`${w}.then names ${p.then}, which is not a clip of the cut`); if (b === undefined || timeline[b].type !== "clip") errors.push(`${w}.now names ${p.now}, which is not a clip of the cut`); if (a !== undefined && b !== undefined && b !== a + 1) errors.push(`${w}: ${p.now} must be the entry right after ${p.then} (the wipe is their cut)`); for (const id of [p.then, p.now]) { if (used.has(id)) errors.push(`${w}: ${id} is in another pair's cut`); } used.add(p.then); used.add(p.now); }); } // The effects are drawn over the footage box where it STAYS: the popup posts' // shift moves it aside while they are up, and an effect drawn THEN would be // drawn over the ground it left. With the cut's schedule (`schedule`) only an // effect on screen while the footage is aside is refused (fxShiftConflicts); // `schedule: false` leaves it to the caller's later check against the real // schedule; without one, any popup shift beside an effect is refused. const deck = render?.chrome?.deck ?? {}; const posts = (manifest?.posts ?? []).filter((p) => !p?.hide); const layout = deck.posts?.layout ?? "popup"; const show = deck.posts?.show ?? true; const shift = deck.posts?.shift ?? {}; if (fxOn(render) && posts.length && show && layout === "popup" && shift !== false) { if (schedule === undefined || schedule === null) { errors.push("render.chrome.fx is drawn over the footage box, which the popup posts move aside: set render.chrome.deck.posts.shift to false, or use the feed"); } else if (schedule) errors.push(...fxShiftConflicts(schedule)); } return errors; } /** * When each effect is drawn over the footage box, in cut seconds: * `[{ what, segment?, from, to }]`, from a deck schedule's `fx` (fxSchedule). * The scrubber and the odometer stand over every clip's clean span; a quote, * the receipts, a zoom and a punch-in over their own rows; the whip, the * glitch and a THEN/NOW wipe around their cut (with their tags and years). */ export function fxBoxWindows(schedule) { const fx = schedule?.fx; if (!fx) return []; const out = []; const push = (what, segment, from, to) => out.push({ what, ...(segment ? { segment } : {}), from: r3(from), to: r3(to) }); for (const s of fx.scrubber?.spans ?? []) push("the scrubber", null, s.in, s.out); for (const s of fx.odometer?.spans ?? []) push("the odometer", null, s.in, s.out); for (const q of fx.quotes ?? []) push(q.style === "kinetic" ? "the kinetic quote" : "the redacted quote", q.segment, q.in, q.out); for (const r of fx.receipts?.clips ?? []) push("the receipts", r.segment, r.in, r.out); for (const z of fx.zoom?.clips ?? []) push("the zoom", z.segment, z.in, z.out); for (const p of fx.punchIn?.punches ?? []) push("the punch-in", p.segment, p.at, p.until); for (const w of fx.whip?.cuts ?? []) push("the whip", w.segment, w.at - 0.1, w.at + w.seconds + 0.1); for (const g of fx.glitch?.bursts ?? []) push("the glitch", g.segment, g.at - g.seconds / 2 - 0.1, g.at + 2); for (const w of fx.thenNow?.wipes ?? []) push("the THEN/NOW wipe", w.now, w.at - 0.5, w.at + w.seconds + FX_MOTION.hold + FX_MOTION.tag); return out; } /** * When the popup posts hold the footage aside, in cut seconds: `[{ clips, * from, to }]` from a deck schedule's `moves` -- a persisting bar's phase * from its `at` to its glide back done (`until` + `seconds`), once however * many segments it spans; a popup's move from its `at` to its segment's mid-dissolve out. * Only the posts' moves (a finale's own are not theirs). */ export function postShiftWindows(schedule) { const posts = schedule?.posts ?? []; const onPosts = new Set(posts.map((p) => p.segment)); // A popup's moved segment is on screen to its mid-dissolve out (the deck's // handover, where the effects' clean spans start); the last one to its end. const segs = schedule?.segments ?? []; const D = Number(schedule?.transition ?? 0); const ends = new Map(segs.map((s, i) => [s.id, s.start + s.duration - (i < segs.length - 1 ? D / 2 : 0)])); const out = []; const seen = new Set(); for (const m of schedule?.moves ?? []) { if (Array.isArray(m.phases)) { for (const ph of m.phases) { const key = `${ph.at}|${ph.until}`; if (seen.has(key)) continue; seen.add(key); const clips = [...new Set(posts.filter((p) => p.appear >= ph.at - 1e-6 && p.appear < ph.until).map((p) => p.segment))]; out.push({ clips, from: r3(ph.at), to: r3(ph.until + m.seconds) }); } } else if (onPosts.has(m.segment)) { out.push({ clips: [m.segment], from: r3(m.at), to: r3(ends.get(m.segment) ?? Infinity) }); } } return out; } /** * Every effect drawn over the footage box while the popup posts hold it * aside (fxBoxWindows against postShiftWindows), as sentences naming both and * their seconds -- empty: wherever an effect is drawn, the footage is in the * box it is drawn over. At most 6, then how many more. */ export function fxShiftConflicts(schedule) { const moves = postShiftWindows(schedule); if (!moves.length) return []; const s = (v) => `${Number(v.toFixed(1))}`; const lines = []; for (const f of fxBoxWindows(schedule)) { for (const m of moves) { if (!(f.from < m.to && m.from < f.to)) continue; lines.push( `render.chrome.fx: ${f.what}${f.segment ? ` on ${f.segment}` : ""} (${s(f.from)}–${s(f.to)} s) is drawn over the footage box ` + `while the popup posts on ${m.clips.join(", ") || "?"} move it aside (${s(m.from)}–${s(m.to)} s): ` + "set render.chrome.deck.posts.shift to false, use the feed, or keep them apart", ); } } return lines.length > 6 ? [...lines.slice(0, 6), `render.chrome.fx: and ${lines.length - 6} more effect(s) over the moved footage`] : lines; } // --------------------------------------------------------------------------- // Dates, words and phrases. // --------------------------------------------------------------------------- const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; /** "20190502", "2019-05-02" (or a longer ISO stamp) → {y, m, d}; anything else → null. */ export function fxDate(v) { const m = /^(\d{4})-?(\d{2})-?(\d{2})/.exec(String(v ?? "").trim()); if (!m) return null; const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])]; if (mo < 1 || mo > 12 || d < 1 || d > 31) return null; return { y, m: mo, d }; } /** {y, m, d} → "2 May 2019". */ export const fxDateLabel = (dt) => (dt ? `${dt.d} ${MONTHS[dt.m - 1]} ${dt.y}` : ""); /** Days since the epoch, so a rail is linear in real time. */ export const fxDay = (dt) => Date.UTC(dt.y, dt.m - 1, dt.d) / 86400000; /** The day a clip's recording is dated by: `montage.date`, the clip's `date`, else its record's upload date. */ export function fxClipDate(entry, meta) { return fxDate(entry?.montage?.date) ?? fxDate(entry?.date) ?? fxDate(meta?.uploadDate); } /** A word as it is matched: lower case letters and digits only. */ export const fxNorm = (w) => String(w ?? "").toLowerCase().replace(/['’]/g, "").replace(/[^\p{L}\p{N}]+/gu, ""); /** A word as it is shown: no caption furniture (">>", "[Music]"), trimmed. */ export const fxShown = (w) => String(w ?? "").replace(/>>+/g, "").replace(/\[[^\]]*\]/g, "").trim(); /** * Timed spans (cues: a line each; whisper's words: a word each) as words, in * the spans' seconds: each word of a span takes its share of the span by its * characters, so a long word takes longer than a short one. Only the words * whose middle is in [from, to]; caption furniture dropped. * * @param {Array<{start: number, end: number, text: string}>} spans * @returns {Array<{text: string, start: number, end: number}>} */ export function fxWordsOf(spans, from = -Infinity, to = Infinity) { const out = []; const used = (spans ?? []).filter((s) => Number.isFinite(s?.start) && Number.isFinite(s?.end) && s.end >= s.start) .slice().sort((a, b) => a.start - b.start); for (const s of used) { // A speaker's turn is marked in captions as ">>" or a dash before the // words ("- Oh god, it is. - Sometimes…"): the next word carries `turn`. const words = []; let turn = false; for (const raw of String(s.text ?? "").replace(/\[[^\]]*\]/g, " ").split(/\s+/)) { if (/^(?:>>+|-|–|—)$/.test(raw)) { turn = true; continue; } if (/^>>/.test(raw)) turn = true; const w = fxShown(raw); if (!w || !fxNorm(w)) continue; words.push({ w, turn }); turn = false; } if (!words.length) continue; const chars = words.reduce((n, x) => n + x.w.length + 1, 0); let c = 0; for (const { w, turn: t } of words) { const a = s.start + ((s.end - s.start) * c) / chars; c += w.length + 1; const b = s.start + ((s.end - s.start) * (c - 1)) / chars; const mid = (a + b) / 2; if (mid >= from && mid <= to) out.push({ text: w, start: a, end: Math.max(a, b), ...(t ? { turn: true } : {}) }); } } return out; } /** * A clip's quote with no timed words: its `quote` (else its on-screen title) * spread evenly over the cited span [cutStart, cutEnd] (else the extent), in * SOURCE seconds. What an estimated schedule draws, and what a build falls * back to when the clip's words cannot be read. */ export function fxQuoteFallback(entry) { const text = typeof entry?.quote === "string" && entry.quote.trim() ? entry.quote : entry?.onscreen?.title ?? ""; const hasCut = Number.isFinite(entry?.cutStart) && Number.isFinite(entry?.cutEnd); const a = hasCut ? entry.cutStart : entry?.start, b = hasCut ? entry.cutEnd : entry?.end; if (!String(text).trim() || !Number.isFinite(a) || !Number.isFinite(b) || b <= a) return []; return fxWordsOf([{ start: a, end: b, text }]); } /** The span a clip's quote is cut from, in SOURCE seconds: the cited cut, else the extent. */ export function fxQuoteSpan(entry) { const hasCut = Number.isFinite(entry?.cutStart) && Number.isFinite(entry?.cutEnd); return hasCut ? { from: entry.cutStart, to: entry.cutEnd } : { from: entry?.start, to: entry?.end }; } /** The words a clip punches: its `fx.punch`, else its `montage.match`; null for none. */ export function fxPunchOf(entry) { const p = entry?.fx?.punch ?? entry?.montage?.match ?? null; return typeof p === "string" && p.trim() ? p : null; } /** Which of `words` are the punch phrase, every time it is said: a boolean per word. */ export function punchMask(words, phrase) { const mask = words.map(() => false); const needle = String(phrase ?? "").split(/\s+/).map(fxNorm).filter(Boolean); if (!needle.length) return mask; const hay = words.map((w) => fxNorm(w.text)); for (let i = 0; i + needle.length <= hay.length; i += 1) { let ok = true; for (let j = 0; j < needle.length && ok; j += 1) { // The last word may run on ("news" in "newsday"? no: "day" in "days"). ok = j === needle.length - 1 ? hay[i + j].startsWith(needle[j]) : hay[i + j] === needle[j]; } if (ok) for (let j = 0; j < needle.length; j += 1) mask[i + j] = true; } return mask; } /** * Words split into pages of at most `max`, preferring to break after a word * that ends a sentence or a clause once a page is half full. */ export function quotePages(words, max) { const pages = []; let cur = []; for (const w of words) { cur.push(w); const ends = /[.!?;:,]$/.test(w.text); if (cur.length >= max || (ends && cur.length >= Math.ceil(max / 2))) { pages.push(cur); cur = []; } } if (cur.length) { // A last page of one or two words joins the one before when it fits. const prev = pages[pages.length - 1]; if (prev && cur.length <= 2 && prev.length + cur.length <= max + 2) prev.push(...cur); else pages.push(cur); } return pages; } // --------------------------------------------------------------------------- // The schedule: `schedule.fx`, in the cut's seconds, written by deckSchedule // only when an effect is on. // --------------------------------------------------------------------------- /** * The effects' times. `segments` are deckSchedule's (`{id, start, duration}`, * holds included), `entries` the timeline, `metas` each entry's source * metadata (or null), `words` a Map of clip id → the clip's timed words in its * SEGMENT's seconds (second 0 = the segment's first frame) or null -- without * a clip's words its quote falls back to `fxQuoteFallback` placed by * `playWindow` (the caller passes `sourceFrom`). `hidden` says which segments * the deck slides away over (a card, the teaser): no effect is drawn there. * * @param {{ segments: Array<{id: string, start: number, duration: number}>, entries: any[], metas?: any[], * render: any, D: number, total: number, words?: Map> | null, * sourceFrom: (entry: any) => number, gapsOf?: (entry: any) => Array<{ from: number, to: number }> | null, hidden: (entry: any) => boolean, fps?: number }} args */ export function fxSchedule({ segments, entries, metas = [], render, D, total, words = null, sourceFrom, gapsOf = () => null, hidden, fps = 30 }) { const keys = fxKeysOn(render); if (!keys.length) return null; const out = { keys }; const clips = []; segments.forEach((s, i) => { const e = entries[i]; if (e?.type !== "clip" && e?.type !== "image") return; if (hidden(e)) return; // The span the clip is clean on screen: from its mid-dissolve in to its // mid-dissolve out (the deck's own handover instants). const first = i === 0, last = i === segments.length - 1; const inn = first ? s.start : s.start + D / 2; const outT = last ? Math.min(total, s.start + s.duration) : s.start + s.duration - D / 2; clips.push({ i, id: e.id, type: e.type, entry: e, meta: metas[i] ?? null, start: s.start, duration: s.duration, in: inn, out: outT }); }); const vclips = clips.filter((c) => c.type === "clip"); const spans = joinedSpans(vclips); // Each clip's words in the CUT's seconds (null: none). const cutWords = new Map(); const wordsOf = (c) => { if (cutWords.has(c.id)) return cutWords.get(c.id); let ws = words?.get(c.id) ?? null; if (!ws || !ws.length) { const fb = fxQuoteFallback(c.entry); const f0 = sourceFrom(c.entry); const g = gapsOf(c.entry); ws = fb.map((w) => ({ ...w, start: offsetIn(w.start, f0, g), end: offsetIn(w.end, f0, g) })); } const placed = (ws ?? []) .map((w) => ({ text: w.text, at: r3(c.start + w.start), end: r3(c.start + w.end), ...(w.turn ? { turn: true } : {}) })) .filter((w) => w.at < c.out - 0.05 && w.end > c.in - 0.3) .map((w) => ({ ...w, at: r3(Math.max(c.in, w.at)) })); cutWords.set(c.id, placed.length ? placed : null); return cutWords.get(c.id); }; // ---- the line: kinetic or redacted ---------------------------------------- const quoteOf = (key, style) => { const cfg = resolveFx(render, key); if (!cfg) return []; const names = Array.isArray(cfg.clips) ? new Set(cfg.clips) : null; const otherCfg = resolveFx(render, key === "kineticQuote" ? "redact" : "kineticQuote"); const otherNames = otherCfg && Array.isArray(otherCfg.clips) ? new Set(otherCfg.clips) : null; const res = []; for (const c of vclips) { if (c.entry.fx?.quote === false) continue; // Named, or (no list) every clip the other treatment does not name. if (names ? !names.has(c.id) : otherNames?.has(c.id)) continue; const ws = wordsOf(c); if (!ws) continue; const mask = punchMask(ws, fxPunchOf(c.entry)); const who = style === "kinetic" && cfg.speakers === "auto" ? speakersOf(ws, c, sourceFrom, gapsOf) : null; const marked = ws.map((w, j) => ({ ...w, punch: mask[j], ...(who ? { speaker: who[j] } : {}) })); // A page holds one speaker's words: a turn starts a new page. const runs = []; for (const w of marked) { const last = runs[runs.length - 1]; if (last && last[0].speaker === w.speaker) last.push(w); else runs.push([w]); } const pages = runs.flatMap((run) => quotePages(run, cfg.maxWords)).map((pw, p, all) => { const pin = r3(Math.max(c.in, pw[0].at - FX_MOTION.page)); const next = all[p + 1]; const pout = r3(next ? Math.max(pin + 0.3, next[0].at - FX_MOTION.page) : c.out); return { in: pin, out: pout, ...(who ? { speaker: pw[0].speaker } : {}), words: pw.map((w) => ({ text: w.text, at: r3(Math.min(Math.max(w.at, pin), pout - 0.05)), punch: w.punch })), }; }); res.push({ segment: c.id, style, in: r3(c.in), out: r3(c.out), pages }); } return res; }; const quotes = [...quoteOf("kineticQuote", "kinetic"), ...quoteOf("redact", "redact")] .sort((a, b) => a.in - b.in); if (keys.includes("kineticQuote") || keys.includes("redact")) { out.quotes = quotes; const style = (key) => { const c = resolveFx(render, key); return c ? { position: c.position, size: c.size } : null; }; out.quoteStyle = { ...(style("kineticQuote") ? { kinetic: style("kineticQuote") } : {}), ...(style("redact") ? { redact: style("redact") } : {}) }; // The two voices, only when a line has more than one speaker. const kq = resolveFx(render, "kineticQuote"); if (kq && quotes.some((q) => q.pages.some((p) => p.speaker === 1))) { out.quoteStyle.voices = [0, 1].map((i) => ({ label: String(kq.voices?.[i]?.label ?? "").trim(), color: kq.voices?.[i]?.color ?? FX_VOICE_COLORS[i], })); } } // ---- the odometer ---------------------------------------------------------- const odo = resolveFx(render, "odometer"); if (odo) { let prev = 0; const counts = vclips.map((c, k) => { const value = Number.isInteger(c.entry.montage?.n) && c.entry.montage.n > 0 ? c.entry.montage.n : k + 1; let at = c.in + 0.25; if (odo.at === "phrase") { const ws = wordsOf(c); const mask = ws ? punchMask(ws, fxPunchOf(c.entry)) : []; const j = mask.indexOf(true); if (j >= 0) at = ws[j].at; } const row = { segment: c.id, value, prev, at: r3(Math.min(Math.max(at, c.in), c.out - 0.1)) }; prev = value; return row; }); out.odometer = { position: odo.position, label: String(odo.label ?? "").trim(), digits: Math.max(1, ...counts.map((c) => String(c.value).length)), counts, spans, }; } // ---- the scrubber ------------------------------------------------------------ const scr = resolveFx(render, "scrubber"); if (scr) { const ticks = vclips .map((c) => ({ c, dt: fxClipDate(c.entry, c.meta) })) .filter((t) => t.dt) .map(({ c, dt }) => ({ segment: c.id, day: fxDay(dt), label: fxDateLabel(dt), year: dt.y, in: r3(c.in), out: r3(c.out) })); if (ticks.length) { const d0 = Math.min(...ticks.map((t) => t.day)), d1 = Math.max(...ticks.map((t) => t.day)); const pad = Math.max(1, (d1 - d0) * 0.04); const years = []; for (let y = new Date((d0 - pad) * 86400000).getUTCFullYear() + 1; fxDay({ y, m: 1, d: 1 }) <= d1 + pad; y += 1) { years.push({ year: y, day: fxDay({ y, m: 1, d: 1 }) }); } out.scrubber = { position: scr.position, thumbs: scr.thumbs, from: d0 - pad, to: d1 + pad, years, ticks: ticks.map((t) => ({ ...t })), spans, }; } } // ---- the glitch: a tear at a cut between years (every cut; the cuts into named clips) const gl = resolveFx(render, "glitch"); if (gl) { const bursts = []; const named = gl.on === "clips" ? new Set(gl.clips ?? []) : null; for (let k = 1; k < vclips.length; k += 1) { const a = vclips[k - 1], b = vclips[k]; // Consecutive in the cut: a card between them is its own break. if (b.i !== a.i + 1) continue; const da = fxClipDate(a.entry, a.meta), db = fxClipDate(b.entry, b.meta); if (gl.on === "year" && !(da && db && da.y !== db.y)) continue; if (named && !named.has(b.id)) continue; const m = segments[b.i].start + D / 2; bursts.push({ segment: b.id, at: r3(m), seconds: gl.seconds, year: db ? db.y : null, date: db ? fxDateLabel(db) : "", seed: k, }); } // `year: false` (a bare tear, no text) is written only when it is off, so // every schedule without it is byte for byte what it was. out.glitch = { stamp: gl.stamp, ...(gl.year === false ? { year: false } : {}), bursts }; } // ---- THEN / NOW --------------------------------------------------------------- const tn = resolveFx(render, "thenNow"); if (tn) { const wipes = []; for (const p of tn.pairs ?? []) { const a = clips.find((c) => c.id === p.then), b = clips.find((c) => c.id === p.now); if (!a || !b || b.i !== a.i + 1) continue; const fmt = (c) => { const dt = fxClipDate(c.entry, c.meta); return dt ? (tn.dates === "year" ? String(dt.y) : fxDateLabel(dt)) : ""; }; // With a crossfade the cut itself is a wipe (`wipeleft`, build-video's // xfadeGraph) over [start, start + D], the divider riding its edge; on a // hard cut the divider alone sweeps over `seconds` centred on the cut. const start = segments[b.i].start; const real = D > 0; const from = real ? start : start - tn.seconds / 2; const seconds = real ? D : tn.seconds; wipes.push({ then: a.id, now: b.id, at: r3(from), seconds: r4(seconds), real, thenDate: fmt(a), nowDate: fmt(b), index: b.i }); } out.thenNow = { wipes }; } // ---- the punch-in: the footage snaps in on a moment --------------------------- const pi = resolveFx(render, "punchIn"); if (pi) { const rows = []; for (const c of vclips) { const f0 = sourceFrom(c.entry); const g = gapsOf(c.entry); const seconds = new Set((Array.isArray(c.entry.fx?.punchIn) ? c.entry.fx.punchIn : []).map((t) => r3(offsetIn(t, f0, g)))); // A laugh written in the captions, when `auto`: the word's start. if (pi.auto) for (const w of wordsOf(c) ?? []) if (FX_LAUGH_RE.test(fxNorm(w.text))) seconds.add(r3(w.at - c.start)); // In the segment's clock, inside the clip's clean span; two closer than // the hold are one. const lo = c.in - c.start, hi = c.out - c.start - 0.1; let last = -Infinity; for (const t of [...seconds].sort((a, b) => a - b)) { if (t < lo || t > hi - 0.2 || t < last + pi.hold) continue; const until = Math.min(hi, t + pi.hold); rows.push({ segment: c.id, index: c.i, at: r3(c.start + t), until: r3(c.start + until), segmentAt: r3(t), segmentUntil: r3(until), scale: pi.scale, anchor: pi.anchor, }); last = t; } } out.punchIn = { punches: rows }; } // ---- the whip: a cut that slides like a whip pan -------------------------------- const wh = resolveFx(render, "whip"); if (wh) { const wipeAt = new Set((out.thenNow?.wipes ?? []).map((w) => w.index)); const cuts = []; for (let k = 1; k < vclips.length; k += 1) { const a = vclips[k - 1], b = vclips[k]; if (b.i !== a.i + 1 || wipeAt.has(b.i)) continue; if (wh.on === "year") { const da = fxClipDate(a.entry, a.meta), db = fxClipDate(b.entry, b.meta); if (!(da && db && da.y !== db.y)) continue; } const start = segments[b.i].start; // With a crossfade the cut slides (`slideleft`) over [start, start + D]; // on a hard cut the streaks alone flash across it. const real = D > 0; cuts.push({ segment: b.id, index: b.i, at: r3(real ? start : start - 0.12), seconds: r4(real ? D : 0.24), real }); } out.whip = { cuts }; } // ---- receipts and the zoom ----------------------------------------------------- const rc = resolveFx(render, "receipts"); if (rc) { const rows = []; for (const c of clips) { const list = c.entry.fx?.receipts; if (!Array.isArray(list) || !list.length) continue; const inn = c.in + 0.3, outT = c.out - 0.25; if (outT - inn < 1) continue; // A receipt with `at` (a source second, gap-aware) flies in then rather // than as the clip comes up; with `hold` on every one, they leave that // long after the last lands, not as the clip goes. const f0 = sourceFrom(c.entry), g = gapsOf(c.entry); const cards = list.map((x, j) => ({ shot: x.shot, mark: x.mark ?? null, ...(typeof x.label === "string" && x.label.trim() ? { label: x.label.trim() } : {}), at: r3(Number.isFinite(x.at) ? Math.min(outT - 1, Math.max(inn, c.start + offsetIn(x.at, f0, g))) : inn + j * FX_MOTION.fanGap), })); const timed = list.some((x) => Number.isFinite(x.at)); const first = Math.min(...cards.map((x) => x.at)), landed = Math.max(...cards.map((x) => x.at)) + FX_MOTION.fan; const out = list.every((x) => Number.isFinite(x.hold)) ? Math.min(outT, Math.max(...list.map((x, j) => cards[j].at + FX_MOTION.fan + x.hold)) + 0.38) : outT; rows.push({ segment: c.id, in: r3(timed ? first : inn), out: r3(out), cards, markAt: r3(timed ? Math.min(out - FX_MOTION.marker - 0.2, landed + 0.15) : Math.min(outT - FX_MOTION.marker - 0.2, inn + list.length * FX_MOTION.fanGap + FX_MOTION.fan + 0.15)), }); } out.receipts = { position: rc.position, width: rc.width, clips: rows }; } const zm = resolveFx(render, "zoom"); if (zm) { const rows = []; for (const c of clips) { const z = c.entry.fx?.zoom; if (!isObj(z)) continue; const inn = c.in + 0.2, outT = c.out - 0.3; if (outT - inn < 2) continue; const outline = inn + 0.55; const push = Math.min(outT - FX_MOTION.push - 0.3, Math.max(outline + FX_MOTION.outline + 0.2, Number.isFinite(z.at) ? c.start + z.at : 0)); // `hold`: that long on the detail once the push lands, then it leaves // (its 0.3 s fade ends `out`); never past the clip's own leave. const out = Number.isFinite(z.hold) ? Math.min(outT, push + FX_MOTION.push + z.hold + 0.3) : outT; rows.push({ segment: c.id, in: r3(inn), out: r3(out), shot: z.shot, focus: z.focus, outline: r3(outline), push: r3(push) }); } out.zoom = { width: zm.width, clips: rows }; } return out; } /** The clips' clean spans, with clips that follow each other joined. */ function joinedSpans(clips) { const out = []; for (const c of clips) { const last = out[out.length - 1]; if (last && last.i === c.i - 1) { last.out = r3(c.out); last.i = c.i; } else out.push({ in: r3(c.in), out: r3(c.out), i: c.i }); } return out.map(({ i: _i, ...s }) => s); } /** Which segments a THEN/NOW pair turns into a wipe: the THEN segment's index, for its join. */ export function fxWipeJoins(schedule) { return new Set((schedule?.fx?.thenNow?.wipes ?? []).filter((w) => w.real).map((w) => w.index - 1)); } /** Which segments' cut out of them is a whip (`slideleft`): the outgoing segment's index, for its join. */ export function fxWhipJoins(schedule) { return new Set((schedule?.fx?.whip?.cuts ?? []).filter((w) => w.real).map((w) => w.index - 1)); } /** Each segment's punch-ins in its own clock, for its join: index → [{at, until, scale, anchor}]. */ export function fxZoomJoins(schedule) { const out = new Map(); for (const p of schedule?.fx?.punchIn?.punches ?? []) { if (!out.has(p.index)) out.set(p.index, []); out.get(p.index).push({ at: p.segmentAt, until: p.segmentUntil, scale: p.scale, anchor: p.anchor, ...(schedule.fx.box ? { box: schedule.fx.box } : {}) }); } return out; } /** * Who says each word of a clip's line: 0 or 1. The clip's `fx.speakers` * (source seconds; each holds until the next) when it has them, else the * captions' own turn marks (">>", a dash), each turn handing over to the * other voice; the first voice is whoever speaks first in the line. Null when * the line has one voice. It says WHICH of two voices, never whose: the * labels are the manifest's (`kineticQuote.voices`). */ export function speakersOf(words, c, sourceFrom, gapsOf = () => null) { const marks = Array.isArray(c.entry?.fx?.speakers) ? [...c.entry.fx.speakers].sort((a, b) => a.at - b.at) : null; let who; if (marks?.length) { const f0 = sourceFrom(c.entry); const g = gapsOf(c.entry); who = words.map((w) => { const src = g?.length ? sourceAtOffset(w.at - c.start, f0, g) : w.at - c.start + f0; let v = marks[0].who; for (const m of marks) if (m.at <= src + 1e-6) v = m.who; return v; }); } else { let v = 0; who = words.map((w, j) => { if (j > 0 && w.turn) v = 1 - v; return v; }); } return who.some((v) => v === 1) ? who : null; } // --------------------------------------------------------------------------- // The geometry and the cue list. // --------------------------------------------------------------------------- /** * Seeded and stateless: the same seed gives the same numbers, on any worker, * in any order (mulberry32). */ export function fxRandom(seed) { let a = (seed >>> 0) || 1; return () => { a = (a + 0x6d2b79f5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } /** * Events in, seek-safe cues out: ordered by time, clamped so a cue never starts * before the last on its element ends, every `from` stated (the last `to` on * that element, or its `init`). The page plays these with `fromTo` and * `immediateRender: false`, so a seek from anywhere to anywhere lands on the * same pixels. * * @param {Record} init * @param {Array<{k: string, at: number, dur: number, to: object, ease?: string}>} events */ export function compileCues(init, events) { const ev = events.map((e, n) => ({ ...e, to: noNegZero(e.to), at: r4(e.at), dur: r4(Math.max(INSTANT, e.dur)), ease: e.ease ?? "none", n })); ev.sort((a, b) => a.at - b.at || a.n - b.n); const state = Object.fromEntries(Object.entries(init).map(([k, v]) => [k, noNegZero(v)])); const freeAt = new Map(); const cues = []; for (const e of ev) { let { at, dur } = e; const free = freeAt.get(e.k) ?? 0; if (at < free) { const end = at + dur; at = r4(free); dur = r4(Math.max(INSTANT, end - at)); } const cur = state[e.k] ?? (state[e.k] = {}); const from = {}; for (const p of Object.keys(e.to)) from[p] = cur[p] ?? defaultOf(p); Object.assign(cur, e.to); freeAt.set(e.k, r4(at + dur)); cues.push({ k: e.k, at, dur, from, to: e.to, ease: e.ease }); } return settleFirstFrame(init, cues); } /** An object's numbers with -0 as 0: the cue list is data, and JSON has no -0. */ export function noNegZero(o) { const out = {}; for (const [k, v] of Object.entries(o ?? {})) out[k] = typeof v === "number" && Object.is(v, -0) ? 0 : v; return out; } const defaultOf = (p) => (p === "scale" || p === "scaleX" || p === "scaleY" || p === "opacity" || p === "autoAlpha" ? 1 : 0); // --------------------------------------------------------------------------- // Presets: what the Takes page's Effect list and `umtool take --effect` offer. // --------------------------------------------------------------------------- /** * THEN/NOW pairs a cut offers by itself: neighbouring clips whose dates are * years apart, the widest gaps first, no clip in two pairs, at most `max`. */ export function fxSuggestPairs(manifest, max = 2) { const tl = manifest?.timeline ?? []; const cands = []; for (let i = 1; i < tl.length; i += 1) { const a = tl[i - 1], b = tl[i]; if (a?.type !== "clip" || b?.type !== "clip") continue; const da = fxClipDate(a, null), db = fxClipDate(b, null); if (!da || !db || da.y === db.y) continue; cands.push({ then: a.id, now: b.id, gap: Math.abs(fxDay(db) - fxDay(da)), i }); } cands.sort((x, y) => y.gap - x.gap || x.i - y.i); const used = new Set(); const out = []; for (const c of cands) { if (out.length >= max || used.has(c.then) || used.has(c.now)) continue; used.add(c.then); used.add(c.now); out.push(c); } return out.sort((x, y) => x.i - y.i).map(({ then, now }) => ({ then, now })); } /** * The effect presets for one manifest, each a merge patch a take applies * (`{render: {transition, chrome: {engine, layout, fx}}}`): one per effect the * cut can show, and "everything" -- the line, the rail, the tears, the wipes, * the receipts and the zoom together. The transition is the cut's own when it * has one (0.4 s when it cuts hard), so the THEN/NOW wipe has a crossfade to * ride; the deck's settings are left as they are (a merge patch keeps them). * Pure, deterministic: the same manifest, the same presets. * * @returns {Array<{ name: string, label: string, summary: string, patch: Record }>} */ export function fxPresetsFor(manifest) { const tl = manifest?.timeline ?? []; const t = Number(manifest?.render?.transition ?? 0); const transition = t > 0 ? t : 0.4; const patch = (fx) => ({ render: { transition, chrome: { engine: "hyperframes", layout: "deck", fx } } }); const pairs = fxSuggestPairs(manifest); const hasReceipts = tl.some((e) => Array.isArray(e?.fx?.receipts) && e.fx.receipts.length); const hasZoom = tl.some((e) => isObj(e?.fx?.zoom)); const out = [ { name: "kinetic-quote", label: "Kinetic quote", summary: "Each clip's line word by word as it is said, the key phrase punched", fx: { kineticQuote: {} } }, { name: "redaction", label: "Redaction reveal", summary: "Each clip's line under black bars that lift as it is said", fx: { redact: {} } }, { name: "odometer", label: "Odometer", summary: "A counter that rolls up on each clip", fx: { odometer: {} } }, { name: "scrubber", label: "Timeline scrubber", summary: "A date rail, the playhead sliding to each clip's day with its picture", fx: { scrubber: {} } }, { name: "glitch", label: "VHS glitch", summary: "A tape tear and the new year at each cut between years", fx: { glitch: {} } }, { name: "punch-in", label: "Punch-in", summary: "The picture snaps in on each marked second and each laugh in the captions", fx: { punchIn: {} } }, { name: "whip", label: "Whip cut", summary: "Every cut between clips slides like a whip pan, streaks across it", fx: { whip: {} } }, { name: "reaction", label: "Reaction highlights", summary: "Captions in each speaker's colour, punch-ins on laughs, whip cuts, a running count", fx: { kineticQuote: {}, punchIn: {}, whip: {}, odometer: {} } }, ]; if (pairs.length) { out.push({ name: "then-now", label: "THEN / NOW wipe", summary: `The cut from THEN to NOW wipes, the two dates on its edge (${pairs.map((p) => `${p.then} → ${p.now}`).join(", ")})`, fx: { thenNow: { pairs } } }); } if (hasReceipts) out.push({ name: "receipts", label: "Receipts", summary: "The clips' screenshots fan in and a marker swipes the cited line", fx: { receipts: {} } }); if (hasZoom) out.push({ name: "zoom", label: "Zoom to detail", summary: "A screenshot pushed in on its detail", fx: { zoom: {} } }); const all = { kineticQuote: {}, scrubber: {}, glitch: {} }; if (pairs.length) all.thenNow = { pairs }; if (hasReceipts) all.receipts = {}; if (hasZoom) all.zoom = {}; out.push({ name: "everything", label: "Everything", summary: `Together: ${Object.keys(all).map((k) => out.find((o) => o.fx[k])?.label).filter(Boolean).join(", ")}`, fx: all }); return out.map(({ fx, ...p }) => ({ ...p, patch: patch(fx) })); }