// Steps parts, place and cutout: the plan checked and cut into the parts each fit takes; a fit checked and its effects put // live on the timeline; a cut-out put in place under its effect. import { readFile } from "node:fs/promises"; import { copyOver } from "./output.js"; import { type Clip, cutOf, sheet, tiled, between } from "./clip.js"; import { Refused } from "./refused.js"; import { defaultsOf, emptied1, fitAsk, inPlace, mergedInto, samplesLeft, sampleTexts, } from "./fit.js"; import { isObject, type Json, type JsonObject, jsonIn, listOf, objectOf } from "./json.js"; import { APPS, type Effect, handbook, WITHOUT } from "./library.js"; import { captionBand, cutoutAt, hasCutout, layLive, type Live, madeLive } from "./layout.js"; import { wantsHands } from "./motion.js"; import { AGAIN_SECONDS, cutOutOf, EMPTY_SECONDS, emptied, inStyle, mended, mostFor, offStyle, partsOf, type Placed, sheetText, } from "./plan.js"; import { check, chosenRows, placements } from "./placements.js"; import { lightSaid } from "./clip.js"; import { faceIn, faceSaid, handsSaid, noFingers, ridesFingers } from "./said.js"; import { type Ask, imagePart } from "./read.js"; import { fitStyleText } from "./preset.js"; import type { Work } from "./work.js"; // The parts of a handbook about making the effect, not fitting it. const NOT_READ = /^##[ \t]*\d*\.?[ \t]*(?:Capabilities used|Files|On the hosted library|How to film|Examples|Beat map|用什么能力做|实例|Remix)[\s\S]*?(?=^## |^values \(effect\.json)/gm; export const answerIn = async (file: string): Promise => { const text = await readFile(file, "utf8"); try { return JSON.parse(text); } catch { try { return jsonIn(text); } catch { throw new Refused("the answer holds no JSON"); } } }; export interface PartRow extends JsonObject { id: string; effect: string; start: number; end: number; said: string; } /** The plan's small slips put right in place, and a stretch left empty closed from its spares. */ async function mend(given: JsonObject, work: Work): Promise { const clip = await work.clip(); const words = await work.words(); const spares = listOf(given.spares).filter(isObject); const rules = { allowed: await work.effects(), words, seconds: clip.seconds, most: mostFor(clip.seconds), again: AGAIN_SECONDS, fingers: await noFingers( chosenRows([...listOf(given.placements), ...spares], await work.effects()), (a, b) => work.handsIn(a, b), ), shots: await work.shots(), }; let { given: right, said } = mended(given, rules); for (const spare of spares) { const rows = listOf(right.placements) .filter(isObject) .map((r) => ({ start: Number(r.start), end: Number(r.end) })); if (!emptied(rows, clip.seconds, EMPTY_SECONDS)) break; const tried = mended( { ...right, placements: [...listOf(right.placements), spare] }, rules, ).given; if (listOf(tried.placements).length > listOf(right.placements).length) right = tried; } await work.write("mended.json", said); return right; } /** The template's own words and where each is kept, for a fit to set. */ function ownTexts(template: string): string { const found = sampleTexts(defaultsOf(template)); return found.length ? `The template's own words, each at its place in params (set every one to this clip's words, or "" where it shows none): ${found .slice(0, 40) .map(([path, text]) => `${path.join(".")} = ${JSON.stringify(text.slice(0, 60))}`) .join("; ")}` : ""; } const number = (value: number) => String(Math.round(value * 1000) / 1000); function cutAhead(made: Placed[], clip: Clip, dir: string): void { const first = cutOutOf(made); const queue = [...first, ...made.filter((p) => !first.includes(p))]; const next = async (): Promise => { for (let p = queue.shift(); p; p = queue.shift()) await cutOf(p, clip, dir).catch(() => undefined); }; for (let k = 0; k < 3; k += 1) void next(); } const needsOf = (effect: Effect): string[] => listOf(objectOf(effect.meta.footage).needs).map(String); /** The hands of every row that counts on them, begun at once: the finger checks first, then the fits' hand text. */ async function handsAhead(given: JsonObject, work: Work): Promise { const rows = chosenRows( [...listOf(given.placements), ...listOf(given.spares)], await work.effects(), ); const fingers = rows.filter((row) => ridesFingers(row.effect)); const moving = rows.filter( (row) => !fingers.includes(row) && wantsHands(row.effect.meta, needsOf(row.effect)), ); for (const row of [...fingers, ...moving]) work.handsIn(row.start, row.end).catch(() => undefined); } /** Step parts: the plan model's answer checked; on ok, the fit calls' inputs. */ export async function partsStep(work: Work, planFile: string): Promise<{ asks: string[] }> { const answer = await answerIn(planFile); if (!isObject(answer)) throw new Refused("The plan is one JSON object."); await handsAhead(answer, work); // A style's plan is taken as written: its rules are its own. const right = work.preset ? answer : await mend(answer, work); await work.write("auto-plan.json", right); const { given, made } = await placements(right, work, true); cutAhead(made, await work.clip(), work.dir); if (work.preset) await work.write("captions.json", listOf(given.captions)); else await work.write("chosen.json", { style: given.style ?? null, key: given.key ?? [] }); const clip = await work.clip(); const words = await work.words(); const motion = await work.motion(); const small = await work.small(); const stills = new Map(); await Promise.all( made.map(async (p) => stills.set(p.id, await sheet(small, between(p.start, p.end, 3), work.file(`${p.id}.jpg`), 3)), ), ); const lights = new Map( await Promise.all( made.map( async (p) => [p.id, await lightSaid(small, (p.start + p.end) / 2, clip).catch(() => "")] as const, ), ), ); const books = new Map(); await Promise.all( made.map(async (p) => { const inside = words.filter((w) => w.end > p.start && w.start < p.end); books.set( p.id, [ `== ${p.id}: ${p.effect.id} on ${p.start} to ${p.end} s (${number(p.end - p.start)} s) ==`, `words, as word@seconds from the effect's start: ${inside.map((w) => `${w.text}@${Math.max(0, w.start - p.start).toFixed(2)}`).join(" ")}`, `stills of these seconds: at clip seconds ${(stills.get(p.id) ?? []).join(", ")}`, faceSaid(faceIn(motion, clip, p.start, p.end)), wantsHands(p.effect.meta, needsOf(p.effect)) && handsSaid(await work.handsIn(p.start, p.end), p), WITHOUT[p.effect.id], lights.get(p.id), !inside.length && `Nothing is said in these seconds; the words that come next: ${words .filter((w) => w.start >= p.start) .slice(0, 14) .map((w) => w.text) .join(" ")}`, ownTexts(p.effect.template), handbook(p.effect).replace(NOT_READ, ""), ] .filter(Boolean) .join("\n\n"), ); }), ); const style = await work.style(); const preset = work.preset; const wears = preset ? fitStyleText(preset) : style ? sheetText(style, await captionBand(work)) : null; const groups = partsOf(made, made.length); const asks: string[] = []; const said = (p: Placed) => words .filter((w) => w.end > p.start && w.start < p.end) .map((w) => w.text) .join(" "); const parts: PartRow[][] = []; for (const [k, rows] of groups.entries()) { const some = rows.map((row) => made[row]!); const jpg = work.file(`plan-${k + 1}.jpg`); await tiled( some.map((p) => work.file(`${p.id}.jpg`)), jpg, 1, ); const asked = some.map((p) => ({ effect: p.effect.id, start: p.start, end: p.end, ...(p.series ? { series: p.series } : {}), })); const text = fitAsk(asked, some.map((p) => books.get(p.id) ?? "").join("\n\n"), wears); const ask: Ask = { job: "fit", parts: [{ text }, await imagePart(jpg)] }; await work.write(`fit-ask-${k + 1}.json`, JSON.stringify(ask)); asks.push(work.file(`fit-ask-${k + 1}.json`)); parts.push( some.map((p) => ({ id: p.id, effect: p.effect.id, start: p.start, end: p.end, ...(p.series ? { series: p.series } : {}), said: said(p), })), ); } await work.write("parts.json", parts); return { asks }; } export async function partsOfWork(work: Work): Promise { return listOf(await work.json("parts.json")).map((rows) => listOf(rows) .filter(isObject) .map((r) => ({ ...r, id: String(r.id), effect: String(r.effect), start: Number(r.start), end: Number(r.end), said: String(r.said ?? ""), })), ); } /** The planned placements, as checked when the plan was taken. */ export async function planned(work: Work): Promise { return work.checked("auto-plan.json", async (given) => (await placements(given, work)).made); } /** A part's rows as the fit answered them, put right by code where it can be. */ async function put(rows: PartRow[], list: Json[], work: Work): Promise { const style = await work.style(); const effects = await work.effects(); return rows.map((row, n) => { const one = objectOf(list[n]); const effect = effects.get(row.effect); const defaults = effect ? defaultsOf(effect.template) : null; let { params, slots } = inPlace(objectOf(one.params), objectOf(one.slots), defaults); const off = style && !APPS.has(row.effect) ? offStyle(style, params) : []; if (style && off.length) params = inStyle(style, params, off); const left = samplesLeft(params, slots, defaults); if (left.length) params = emptied1(params, left); return { effect: row.effect, start: row.start, end: row.end, ...(row.series ? { series: row.series } : {}), params, slots, }; }); } /** What is wrong with a part's rows, told before anything is placed. */ function checkedRows(clip: Clip, made: Placed[]): string[] { return made.flatMap((p) => { const notes = check(p, clip).filter( (note) => !(note.startsWith("still the original") && defaultsOf(p.effect.template)), ); return notes.length ? [`${p.id} (${p.effect.id}): ${notes.join("; ")}`] : []; }); } export interface Layers { type: "layers"; captions: number; effects: { id: string; effect: string; start: number; end: number; live: boolean }[]; } /** What is on the timeline now, as the run's layers event says it. */ export const layersOf = (laid: { captions: number; live: Live[] }): Layers => ({ type: "layers", captions: laid.captions, effects: laid.live.map(({ p, live }) => ({ id: p.id, effect: p.effect.id, start: p.start, end: p.end, live, })), }); export interface Placing { /** index.html as this step left it. */ layers: Layers; placed: Live[]; /** The effects waiting for their cut-out: the seconds to send, cut out of the clip. */ cutouts: { id: string; source: string }[]; dropped: { id: string; reason: string }[]; } /** Step place: the fit model's answer for part k checked; on ok, its effects live on the timeline. `last` takes an answer * with faults the code cannot put right, as the last model there is gave it. */ // fallow-ignore-next-line complexity export async function placeStep( work: Work, fitFile: string, part: number | null, last: boolean, again: string | null = null, ): Promise { const parts = await partsOfWork(work); // An answer that puts one effect right is placed with its part, found from the effect. const k = part ?? parts.findIndex((rows) => rows.some((row) => row.id === again)) + 1; if (!k) throw new Refused( again ? `${again} is not one of the planned effects.` : "Say which part the answer is for.", ); const rows = parts[k - 1]; if (!rows) throw new Refused(`There is no part ${k}: the plan has ${parts.length}.`); const answer = await answerIn(fitFile); const file = `auto-plan-${k}.json`; let made: JsonObject[]; if (again) { const before = listOf(await work.json(file)).filter(isObject); const one = objectOf(answer); const row = rows.find((r) => r.id === again); if (!row) throw new Refused(`${again} is not in part ${k}.`); made = before; const at = before.findIndex( (r) => r.effect === row.effect && Math.abs(Number(r.start) - row.start) < 0.05, ); const merged = await put( [row], [ { params: mergedInto(before[at]?.params ?? {}, one.params ?? {}), slots: mergedInto(before[at]?.slots ?? {}, one.slots ?? {}), }, ], work, ); if (at >= 0 && merged[0]) made[at] = merged[0]; } else { const list = Array.isArray(answer) ? answer : isObject(answer) ? listOf(answer.rows ?? answer.placements ?? [answer]) : []; if (list.length !== rows.length) throw new Refused(`${rows.length} objects are asked for, ${list.length} were given`); made = await put(rows, list, work); } await work.write(file, made); const clip = await work.clip(); let placed = (await placements(made, work)).made; let wrong = checkedRows(clip, placed); // What code can put right is: a slot that is not there, a nothing where the template holds several values. const gone = [ ...wrong .join("\n") .matchAll(/slot '([^']+)' is not one this template reads|(\S+) holds several values, so/g), ].map((m) => m[1] ?? m[2] ?? ""); if (gone.length) { for (const row of made) { const slots = objectOf(row.slots); const params = objectOf(row.params); for (const name of gone) { delete slots[name]; if (params[name] === null) delete params[name]; } } await work.write(file, made); placed = (await placements(made, work)).made; wrong = checkedRows(clip, placed); } if (wrong.length && !last) throw new Refused(wrong.join("\n")); const out: Omit = { placed: [], cutouts: [], dropped: [] }; const waiting = new Set( cutOutOf(placed) .filter((p) => !hasCutout(work, p)) .map((p) => p.id), ); for (const p of placed) { if (again && p.id !== again) continue; if (waiting.has(p.id)) { const source = work.file(`src-${p.id}.mp4`); await copyOver(await cutOf(p, clip, work.dir), source); out.cutouts.push({ id: p.id, source }); continue; } try { out.placed.push(await madeLive(p, work)); } catch (err) { out.dropped.push({ id: p.id, reason: err instanceof Error ? err.message : String(err) }); } } return { ...out, layers: await remember(work, out) }; } /** Step cutout: the cut-out of one effect's seconds, put under it, and the effect placed. */ export async function cutoutStep(work: Work, id: string, file: string): Promise { const parts = await partsOfWork(work); const k = parts.findIndex((rows) => rows.some((r) => r.id === id)); if (k < 0) throw new Refused(`${id} is not one of the planned effects.`); const p = (await placements(await work.json(`auto-plan-${k + 1}.json`), work)).made.find( (one) => one.id === id, ); if (!p) throw new Refused(`${id} has not been fitted: run place for part ${k + 1} first.`); await copyOver(file, cutoutAt(work, p)); const out: Omit = { placed: [], cutouts: [], dropped: [] }; try { out.placed.push(await madeLive(p, work)); } catch (err) { out.dropped.push({ id, reason: err instanceof Error ? err.message : String(err) }); } return { ...out, layers: await remember(work, out) }; } // Parts are placed side by side in a run: what they keep in here.json is written one at a time. let remembering: Promise = Promise.resolve(); /** What is on the timeline and what was left out, kept in the work folder; index.html laid again with all of it. */ function remember(work: Work, out: Omit): Promise { const next = remembering.then(() => rememberNow(work, out)); remembering = next.catch(() => undefined); return next; } async function rememberNow(work: Work, out: Omit): Promise { const here = work.has("here.json") ? objectOf(await work.json("here.json")) : {}; const notes = objectOf(here.notes); const left = objectOf(here.left_out); for (const one of out.placed) { notes[one.p.id] = one.notes; delete left[one.p.id]; } for (const one of out.dropped) { left[one.id] = one.reason; delete notes[one.id]; } await work.write("here.json", { notes, left_out: left }); return layersOf(await layHere(work)); } /** Every effect placed so far, and the captions, on the timeline. */ export async function layHere(work: Work): Promise<{ captions: number; live: Live[] }> { const here = work.has("here.json") ? objectOf(await work.json("here.json")) : {}; const notes = objectOf(here.notes); const parts = await partsOfWork(work); const live: Live[] = []; for (const [k, rows] of parts.entries()) { if (!rows.some((r) => r.id in notes) || !work.has(`auto-plan-${k + 1}.json`)) continue; const made = await work.checked( `auto-plan-${k + 1}.json`, async (given) => (await placements(given, work)).made, ); for (const p of made) if (p.id in notes) live.push({ p, live: true, notes: listOf(notes[p.id]).map(String) }); } const captions = await layLive(live, await planned(work), work); return { captions, live }; }