// After an effect is taken off, a long stretch with nothing on it is filled without asking a model: a punch-in on the // stretch's key word, where a cut-out of those seconds is already made, so nothing waits for HeyGen; else a title of one // line carrying the words said from that key word on. A stretch is never left empty while a title can go in it. import { readdirSync } from "node:fs"; import { cutPart } from "./clip.js"; import { onGrid } from "./grid.js"; import { isObject, type JsonObject, listOf, objectOf, round } from "./json.js"; import { cutoutAt, type Live, madeLive } from "./layout.js"; import { FILLED_FILE } from "./layoutKept.js"; import { placements } from "./placements.js"; import { type Effect, isKind, TITLES } from "./library.js"; import { keyWordIn, shownIn, titleRow } from "./planFill.js"; import { layHere, partsOfWork, planned, remember } from "./steps.js"; import { fillKindAt, leastFor } from "./count.js"; import type { Word } from "./words.js"; import type { Work } from "./work.js"; const GAP_SECONDS = 10; const PUNCH = "punch-in"; const PUNCHES = 2; const PUNCH_SECONDS = 2.2; const LEAD = 0.3; // The opening is never left empty for longer than this, and what fills it lands by OPENS_BY. const OPENING_EMPTY = 3; const OPENS_BY = 1.5; export interface Filled extends JsonObject { from: number; to: number; added: string | null; start: number | null; end: number | null; word: string | null; why: string; } /** The stretches longer than `longest` s with no effect on them, the opening and the end included. */ export function gapsOf( rows: { start: number; end: number }[], seconds: number, longest = GAP_SECONDS, ): [number, number][] { const out: [number, number][] = []; let at = 0; for (const row of [...rows].sort((a, b) => a.start - b.start)) { if (row.start - at > (at === 0 ? Math.min(longest, OPENING_EMPTY) : longest)) out.push([at, row.start]); at = Math.max(at, row.end); } if (seconds - at > longest) out.push([at, seconds]); return out; } /** A cut-out already made whose seconds hold `from` to `to`. */ export function cutoutHolding( names: string[], from: number, to: number, ): { file: string; start: number } | null { for (const file of names) { const found = /^cutout-([\d.]+)-([\d.]+)\.webm$/.exec(file); if (found && Number(found[1]) <= from + 1e-3 && Number(found[2]) >= to - 1e-3) return { file, start: Number(found[1]) }; } return null; } interface Chosen { start: number; end: number; word: Word; cut: { file: string; start: number }; } /** Where a punch-in can go in the stretch, or why none goes there. */ function chosenIn( from: number, to: number, word: Word | null, punches: number, most: number, names: string[], ): Chosen | string { if (!word) return "nothing is said in it"; if (punches >= most) return `the video has its ${most} punch-ins`; const lead = Math.max(from, word.start - LEAD); const start = onGrid(from === 0 ? Math.min(lead, OPENS_BY) : lead); const end = onGrid(Math.min(to, start + PUNCH_SECONDS)); const cut = cutoutHolding(names, start, end); return cut ? { start, end, word, cut } : "no cut-out of these seconds is made, and making one would wait for HeyGen"; } const nearest = (heads: number[][], t: number): number[] | null => heads.reduce( (best, h) => (!best || Math.abs((h[0] ?? 0) - t) < Math.abs((best[0] ?? 0) - t) ? h : best), null, ); /** The library's effects, those the plan was shown first. */ async function inShownOrder(work: Work): Promise { const all = await work.effects(); const ask = work.has("plan-ask.json") ? objectOf(await work.json("plan-ask.json")) : {}; const text = listOf(ask.parts) .filter(isObject) .map((part) => String(part.text ?? "")) .join("\n"); const shown = shownIn(text); return [ ...shown.flatMap((id) => all.get(id) ?? []), ...[...all.values()].filter((e) => !shown.includes(e.id)), ]; } /** A row placed as a part of its own, on the timeline; a punch-in gets the part of the cut-out its seconds need. */ async function addedPart( work: Work, row: JsonObject, said: string, cut?: Chosen["cut"], ): Promise { const parts = await partsOfWork(work); const taken = new Set(parts.flat().map((one) => one.id)); // An effect's id comes from its start: one taken off there keeps its id, so the fill starts a frame later instead. for (let k = 0; k < 10 && taken.has(`p${Math.round(Number(row.start) * 10)}`); k += 1) row = { ...row, start: round(Number(row.start) + 0.1, 3) }; if (taken.has(`p${Math.round(Number(row.start) * 10)}`)) return false; const p = (await placements([row], work)).made[0]; if (!p) return false; if (cut) await cutPart(work.file(cut.file), cut.start, p.start, p.end, cutoutAt(work, p)); await work.write(`auto-plan-${parts.length + 1}.json`, [row]); await work.write("parts.json", [ ...parts, [{ id: p.id, effect: p.effect.id, start: p.start, end: p.end, said }], ]); await remember(work, { placed: [await madeLive(p, work)], cutouts: [], dropped: [] }); return true; } /** A punch-in placed as a part of its own, on the timeline. */ async function punchedIn(work: Work, chosen: Chosen): Promise { const { start, end, word, cut } = chosen; const head = nearest((await work.motion()).heads, word.start); const row: JsonObject = { effect: PUNCH, start, end, params: { at: round(word.start - start, 3), zoom: 1.4, fx: round(head?.[1] ?? 0.5, 3), fy: round(head?.[2] ?? 0.35, 3), }, slots: {}, }; return addedPart(work, row, word.text, cut); } /** filled.json with one entry for each stretch, the latest. */ export const withFilled = (before: JsonObject[], now: Filled[]): JsonObject[] => [ ...before.filter((one) => !now.some((n) => n.from === one.from && n.to === one.to)), ...now, ]; interface Filling { work: Work; words: Word[]; key: number[][]; effects: Effect[]; used: Set; /** What is on the video, in time order, for the kinds to take turns. */ around: { effect: string; start: number; title: boolean }[]; punches: number; /** Punch-ins a fill may still add: the long-stretch fills keep to their two, the floor's are counted by turns. */ punchesMost: number; } /** One stretch filled with a punch-in or a title, the kind not the one beside it; what was done, or why nothing. */ // fallow-ignore-next-line complexity async function filledStretch(from: number, to: number, why: string, f: Filling): Promise { const word = from === 0 ? (keyWordIn(f.words, f.key, 0, Math.min(to, OPENS_BY + 2)) ?? f.words.find((w) => w.start < to) ?? null) : (keyWordIn(f.words, f.key, from, to) ?? f.words.find((w) => w.start >= from && w.start < to) ?? null); const gap = { from: round(from, 2), to: round(to, 2), word: word?.text ?? null }; const tryPunch = async (): Promise => { const chosen = chosenIn(from, to, word, f.punches, f.punchesMost, readdirSync(f.work.dir)); if (typeof chosen === "string") return chosen; if (!(await punchedIn(f.work, chosen))) return "the punch-in could not be placed"; f.punches += 1; f.around.push({ effect: PUNCH, start: chosen.start, title: false }); return { ...gap, added: PUNCH, start: chosen.start, end: chosen.end, why: `${why}; a punch-in lands on "${chosen.word.text}"`, }; }; const tryTitle = async (): Promise => { const title = word && titleRow(from, to, word, f.words, f.effects, f.used); if (!(title && word && (await addedPart(f.work, title, word.text)))) return null; f.used.add(String(title.effect)); f.around.push({ effect: String(title.effect), start: Number(title.start), title: true }); return { ...gap, added: String(title.effect), start: Number(title.start), end: Number(title.end), why: `${why}; a title lands on "${word.text}"`, }; }; let noPunch = ""; if (fillKindAt(f.around, from) === "punch") { const punched = await tryPunch(); if (typeof punched !== "string") return punched; noPunch = punched; const titled = await tryTitle(); if (titled) return { ...titled, why: `${titled.why} (no punch-in: ${noPunch})` }; } else { const titled = await tryTitle(); if (titled) return titled; const punched = await tryPunch(); if (typeof punched !== "string") return punched; noPunch = punched; } return { ...gap, added: null, start: null, end: null, why: `${noPunch}, and no title fits` }; } async function fillingOf(work: Work, live: Live[], punchesMost: number): Promise { const hasPunch = (await work.effects()).has(PUNCH); return { work, words: await work.words(), key: await work.key(), effects: await inShownOrder(work), used: new Set(live.map((one) => one.p.effect.id)), around: live.map((one) => ({ effect: one.p.effect.id, start: one.p.start, title: isKind(one.p.effect.id, TITLES), })), punches: hasPunch ? live.filter((one) => one.p.effect.id === PUNCH).length : punchesMost, punchesMost, }; } async function keptFilled(work: Work, filled: Filled[]): Promise { const before = work.has(FILLED_FILE) ? listOf(await work.json(FILLED_FILE)).filter(isObject) : []; await work.write(FILLED_FILE, withFilled(before, filled)); } /** Fills each long empty stretch it can, and keeps what it did and why in filled.json. */ export async function filledGaps(work: Work): Promise { const { live } = await layHere(work); const clip = await work.clip(); const f = await fillingOf(work, live, PUNCHES); const filled: Filled[] = []; for (const [from, to] of gapsOf( live.map((one) => one.p), clip.seconds, )) filled.push( await filledStretch( from, to, `${round(to - from, 1)} s had no effect after one was taken off`, f, ), ); await keptFilled(work, filled); return filled; } /** A video left under five effects a minute gets one back at each place an effect was taken off, until it has five. */ export async function flooredGaps(work: Work): Promise { const { live } = await layHere(work); const least = leastFor((await work.clip()).seconds); if (live.length >= least) return []; const on = live.map((one) => one.p); const off = (await planned(work)) .filter((p) => !on.some((one) => one.id === p.id)) .sort((a, b) => a.start - b.start); const f = await fillingOf(work, live, Number.POSITIVE_INFINITY); const filled: Filled[] = []; let count = live.length; for (const p of off) { if (count >= least) break; const busy = [...on, ...filled.flatMap((x) => (x.start === null ? [] : [x]))]; const next = busy .map((one) => Number(one.start)) .filter((t) => t > p.start) .sort((a, b) => a - b)[0]; const to = Math.min(p.end, next ?? p.end); if (busy.some((one) => Number(one.start) < to && Number(one.end) > p.start)) continue; const one = await filledStretch( p.start, to, `the video had ${count} effects, under ${least}, after ${p.effect.id} was taken off`, f, ); filled.push(one); if (one.added) count += 1; } await keptFilled(work, filled); return filled; }