// THE CLIP EDITOR, server side (release 35 C2): a person hops in on the clips // an assistant made -- or on any report video's clips -- and trims, splits, // merges, adds, restores, keeps or cuts them, and says which voice is the // host. // // the view every clip of the cut with its edges, quote, `assist` // (the clip finder's provenance) and keep/cut ruling; // the clip finder's speakers and the proposals NOT in the // cut (reactions.json, when there is one) // the neighbourhood what the strip under the player draws for a span: the // speaker turns, the laughs, the words (a words file in // the project) or else the cues // the operations ONE writer each, all here: the manifest through // lib/report/manifest.mjs (updateClip / restoreClip / // splitClip / mergeClips / addClip), the rulings through // lib/report/montageRulings.mjs, a speaker's role through // ./clipEditorBridge.mjs (the clip finder's writer) // // A ruling is keyed by the clip's moment (`clipMomentKey`: its cutStart), so an // edit that moves a clip's start would orphan its keep/cut. After every edit // the rulings FOLLOW their clips: a ruling whose clip's key changed moves to // the new key; one whose clip is gone (merged away) is removed. // // Nothing here calls a model. import { readFile, stat } from "node:fs/promises"; import path from "node:path"; import { clipMomentKey } from "umtool-report-to-video/montage-rulings"; import { channelFor, channelsDirFor, clipsOf, cuesInWindow, hasShadowChannels, readManifest } from "../projects/report.mjs"; import { StaleToken, StructureRefused, addClip, cutOf, flashForward, manifestToken, mergeClips, restoreClip, splitClip, updateClaimKnobs, updateMarks, updateClip, updateOnscreen, updateRender, } from "./manifest.mjs"; import { censorRegionsOf, namesClip } from "umtool-report-to-video/clip-censor"; import { withRecording } from "./censorCli.mjs"; import { CLAIM_KNOB_DEFAULTS, markVerdictsOf, rawMarksOf, stampingEntryId } from "./knobs.mjs"; import { resolveFactcheck } from "umtool-report-to-video/factcheck"; import { momentKeysOf, readRulingsState, setMontageRuling } from "./montageRulings.mjs"; import { readReactions, reproposeAvailable, REPROPOSE_UNAVAILABLE, setSpeakerLabel, setSpeakerRole, SPEAKER_ROLES } from "./clipEditorBridge.mjs"; import { readShorts } from "./shorts.mjs"; import { readLiveProject } from "./liveProject.mjs"; import { quoteBetween, unusedProposals, wordsOf } from "./clipEditorModel.mjs"; import { WINDOW_PAD_S } from "yt-dlp-transcript-common/lib/clips/assist.mjs"; import { clipRoom } from "umtool-report-to-video/room"; import { BLUR_CAPTION_DEFAULT, BLUR_CAPTION_MAX, BLUR_STRENGTH, renderBlurOn } from "umtool-report-to-video/clip-blur"; import { CLIP_KIT_KEYS } from "umtool-report-to-video/clip-kit"; export { StaleToken, StructureRefused }; /** How far the strip reaches either side of a clip. */ export const NEIGHBOURHOOD = 60; /** The verdicts the clip editor offers (the montage deck has four). */ export const EDITOR_VERDICTS = Object.freeze(["keep", "cut"]); export const WORDS_FILE = "words.json"; const fin = (v) => typeof v === "number" && Number.isFinite(v); const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); /** A project-relative file the project names (a words file): never absolute, never `..`. */ function projectFile(dir, rel) { if (typeof rel !== "string" || !rel || path.isAbsolute(rel) || rel.split(/[\\/]/).some((s) => s === ".." || s === "")) return null; return path.join(/* turbopackIgnore: true */ dir, rel); } const wordsMemo = new Map(); /** The project's word timings (`reactions.source.words`, else words.json), or null. Memoised on mtime. */ export async function readWords(dir, reactions = null) { const rel = typeof reactions?.source?.words === "string" ? reactions.source.words : WORDS_FILE; const file = projectFile(dir, rel); if (!file) return null; const st = await stat(file).catch(() => null); if (!st?.isFile()) return null; const key = `${file}|${Math.round(st.mtimeMs)}|${st.size}`; const hit = wordsMemo.get(file); if (hit && hit.key === key) return hit.words; let words = null; try { words = wordsOf(JSON.parse(await readFile(file, "utf8"))); } catch { words = null; } wordsMemo.set(file, { key, words }); return words; } /** * @typedef {{ id: string, channel: string | null, video: string, start: number, end: number, * cutStart: number | null, cutEnd: number | null, quote: string | null, title: string | null, * assist: Record | null, key: string | null, ruling: "keep" | "cut" | string | null, montage: boolean, * vertical: { crop: number[], aspect?: number } | null, kit: Record, * room: false | { tail?: boolean, head?: boolean } | null, roomEdges: { tail: boolean, head: boolean } | null, * gaps?: Array<{ from: number, to: number }> }} EditorClip */ /** The page's data: the clips, the token, the clip finder's speakers and unused proposals. */ export async function clipEditorView(project) { const manifest = await readManifest(project.dir); if (!manifest) return null; const [token, rulings, reactions] = await Promise.all([manifestToken(project.dir), readRulingsState(project.dir), readReactions(project.dir)]); /** @type {EditorClip[]} */ const clips = clipsOf(manifest) .filter((e) => typeof e.video === "string" && fin(e.start) && fin(e.end)) .map((e) => { const key = clipMomentKey(e, manifest); return { id: e.id, channel: channelFor(manifest, e), video: e.video, start: e.start, end: e.end, cutStart: fin(e.cutStart) ? e.cutStart : null, cutEnd: fin(e.cutEnd) ? e.cutEnd : null, // Seconds cut out of its middle (gaps.mjs): the live preview's clock jumps with them. ...(Array.isArray(e.gaps) && e.gaps.length ? { gaps: e.gaps } : {}), quote: typeof e.quote === "string" ? e.quote : null, title: typeof e.title === "string" ? e.title : typeof e.onscreen?.title === "string" ? e.onscreen.title : null, assist: isObj(e.assist) ? e.assist : null, key, ruling: key ? (rulings.doc.rulings[key]?.verdict ?? null) : null, montage: isObj(e.montage), // A short's framing (release 36): fractions of the source picture. vertical: isObj(e.vertical) && Array.isArray(e.vertical.crop) ? { crop: e.vertical.crop, ...(fin(e.vertical.aspect) ? { aspect: e.vertical.aspect } : {}) } : null, // The clip kit (lane clip-kit): its own code and name for a per-clip build, as written. kit: Object.fromEntries(CLIP_KIT_KEYS.filter((k) => e[k] !== undefined).map((k) => [k, e[k]])), // Its recording's hidden regions (render.censor naming its video), for the Hide regions list. recordingCensor: (Array.isArray(manifest.render?.censor) ? manifest.render.censor : []).filter((r) => namesClip(r, e, manifest.provenance ?? {})), // Every region the cut hides on it (its own and its recording's, clip-censor.mjs): the player and the live // preview draw them over the picture. hidden: censorRegionsOf(e, manifest.render ?? {}, manifest.provenance ?? {}), // Room at its edges (release 36 lane E): the clip's own override as // written, and the edges it gets with the cut's render.room. room: e.room === false ? false : isObj(e.room) ? e.room : null, roomEdges: roomEdgesOf(e, manifest.render), // The video knobs: the claim as written (its id, verdict and knobs), // the entry that stamps it (the last carrying its id), and the sound. // `claim` / `stampsOn` are the FIRST mark's; `marks` every one, each // with the entry that stamps it (plans/clip-marks.md). ...marksView(manifest, e), audio: isObj(e.audio) ? e.audio : null, // The clip's picture, blurred at the encode (clip-blur.mjs), as written. blur: isObj(e.blur) ? e.blur : null, // The deck's words for it as written (the live preview's fields): absent keys are automatic. onscreen: isObj(e.onscreen) ? e.onscreen : null, // What a new clip made from this one's recording copies (New clip from // selection): its section, its citation link, and its channel AS // WRITTEN (null: the cut's provenance channel). section: e.section ?? null, citeUrl: typeof e.citeUrl === "string" ? e.citeUrl : null, ownChannel: typeof e.channel === "string" && e.channel ? e.channel : null, }; }); const shorts = await readShorts(project.dir, manifest); const doc = reactions.doc; const live = await readLiveProject(project.dir); return { live: live ? { status: live.status === "final" ? "final" : "live", transcribedTo: fin(live.transcribedTo) ? live.transcribedTo : 0, minedTo: fin(live.minedTo) ? live.minedTo : 0, passes: fin(live.passes) ? live.passes : 0, lastPass: typeof live.lastPass === "string" ? live.lastPass : null, flags: Array.isArray(live.flags) ? live.flags.filter(isObj) : [], } : null, clips, token, rulingsError: rulings.error, reactionsError: reactions.error, reactions: doc ? { source: isObj(doc.source) ? doc.source : null, params: isObj(doc.params) ? doc.params : null, speakers: Array.isArray(doc.speakers) ? doc.speakers.filter(isObj) : [], proposals: unusedProposals(doc, clips), proposalCount: Array.isArray(doc.proposals) ? doc.proposals.length : 0, proposedAt: typeof doc.proposedAt === "string" ? doc.proposedAt : null, rolesChangedAt: typeof doc.rolesChangedAt === "string" ? doc.rolesChangedAt : null, } : null, repropose: { available: reproposeAvailable, why: reproposeAvailable ? null : REPROPOSE_UNAVAILABLE }, shorts: Object.fromEntries(shorts.filter((x) => !x.gone).map((x) => [x.clip, { mtimeMs: x.mtimeMs, size: x.size, stale: x.stale }])), room: roomViewOf(manifest.render), // The blur's defaults and bounds (the Blur box's placeholders), and // whether this cut draws it (render.blur "off": the uncensored variant). blur: { caption: BLUR_CAPTION_DEFAULT, captionMax: BLUR_CAPTION_MAX, strength: BLUR_STRENGTH, rendered: renderBlurOn(manifest.render) }, knobs: { ...knobDefaultsOf(manifest.render), verdicts: markVerdictsOf(manifest) }, }; } /** * A clip's marks for the view: `claim` and `stampsOn` (its first mark's, as * before marks), and `marks` -- each as written, with `stampsOn`, the entry * that stamps it. */ function marksView(manifest, e) { const marks = rawMarksOf(e).filter((m) => isObj(m) && typeof m.id === "string"); const first = marks[0] ?? null; return { claim: first, stampsOn: first ? stampingEntryId(manifest, first.id) : null, marks: marks.map((m) => ({ ...m, stampsOn: stampingEntryId(manifest, m.id) })), }; } /** * What a claim knob is when the claim does not set it (the Count & stamp box's * placeholders): the cut's stamp seconds, whether the cut draws stamps at all, * the default count, and each verdict's stamp word (its `stampLabel`, else its * label). */ function knobDefaultsOf(render) { const fc = resolveFactcheck(render); const given = isObj(render?.chrome?.factcheck?.verdicts) ? render.chrome.factcheck.verdicts : {}; const labels = {}; for (const [v, x] of Object.entries(fc.verdicts)) { // A counter series carries its stamp word itself (report-to-video counter.mjs). const own = isObj(given[v]) && typeof given[v].stampLabel === "string" && given[v].stampLabel.trim() ? given[v].stampLabel.trim() : typeof x.stampLabel === "string" && x.stampLabel.trim() ? x.stampLabel.trim() : null; labels[v] = own ?? x.label; } return { hold: fc.stamp.seconds, stampShown: fc.stamp.show !== false, count: CLAIM_KNOB_DEFAULTS.count, labels }; } /** A clip's room edges (room.mjs clipRoom), or null when it has none. */ function roomEdgesOf(entry, render) { const r = clipRoom(entry, render); return r ? { tail: r.tail, head: r.head } : null; } /** * The cut's room, for the strip (release 36 lane E): render.room's edges, its * settings and the join's length -- null when the cut has no room and no * join (a montage's, or transition 0). */ function roomViewOf(render) { const r = isObj(render) ? render : {}; // The build's join (deck.mjs transitionOf): 0.5 s unless the render says; none in a montage. const D = r.montage !== undefined && r.montage !== null ? 0 : fin(r.transition) ? r.transition : 0.5; const room = isObj(r.room) ? r.room : null; return { tail: room?.tail === true, head: room?.head === true, minGap: fin(room?.minGap) ? room.minGap : null, maxS: fin(room?.maxS) ? room.maxS : null, join: D, }; } const overlapping = (list, from, to) => (Array.isArray(list) ? list : []).filter((x) => isObj(x) && fin(x.start) && fin(x.end) && x.end >= from && x.start <= to); /** * What the strip draws for [from, to] around one clip: turns, laughs, words * (or cues when the project has no word timings), and the source's length * when known. `video` (the clip bench, zoomed in): the words only when they * are THAT recording's (`reactions.source.video`) -- a project's words file * is one recording's, and another's words would be drawn in the wrong places. * * @param {{ id: string, dir: string }} project * @param {{ clip?: string | null, from: number, to: number, video?: string | null }} opts */ export async function clipNeighbourhood(project, { clip, from, to, video = null }) { if (!fin(from) || !fin(to) || to <= from) throw new Error("from and to must be seconds, from < to"); const { doc } = await readReactions(project.dir); let words = video && doc?.source?.video !== video ? null : await readWords(project.dir, doc); // The bench, zoomed in, on a recording the project has no words file for: // the corpus's words for it (report-to-video clip-words.mjs -- a words // sidecar, a whisper transcript, else the en-orig captions' word starts), // the same ones the trailer's pause snap reads. Never a cue spread by its // characters: a box drawn there would be a made-up place. let wordsFrom = words?.length ? "project" : null; let timed = words?.length ? true : null; if (video && !words?.length && clip) { const corpus = await corpusWords(project.dir, clip, video, from, to).catch(() => null); if (corpus?.words?.length) { words = corpus.words.map((w) => ({ w: w.text, start: w.start, ...(fin(w.end) ? { end: w.end } : {}) })); wordsFrom = corpus.from; timed = corpus.timed; } } const turns = overlapping(doc?.turns, from, to).map((t) => ({ start: t.start, end: t.end, speaker: t.speaker })); const laughs = overlapping(doc?.laughs, from, to).map((l) => ({ start: l.start, end: l.end, score: fin(l.score) ? l.score : null, speaker: fin(l.speaker) ? l.speaker : null })); let cues = null; let duration = fin(doc?.source?.duration) ? doc.source.duration : null; if (!words?.length || duration === null) { const c = clip ? await cuesInWindow(project.dir, clip, from, to).catch(() => null) : null; if (!words?.length) cues = c?.cues?.map((x) => ({ start: x.start, end: x.end, text: x.text })) ?? null; if (duration === null && fin(c?.duration)) duration = c.duration; } return { from, to, turns, laughs, words: words?.length ? words .filter((w) => (fin(w.end) ? w.end : w.start) >= from && w.start <= to) .map((w) => ({ w: String(w.w ?? w.word ?? w.text ?? ""), start: w.start, ...(fin(w.end) ? { end: w.end } : {}) })) : null, // Where the words came from (the project's words file, words.json / // transcript.json / captions in the corpus), and whether they carry their // ends (captions' words have only their starts). ...(video ? { wordsFrom, timed } : {}), cues, duration, }; } /** * A recording's words from the corpus (clip-words.mjs), for the bench's zoom: * the clip named, on THAT recording. */ async function corpusWords(dir, clipId, video, from, to) { const manifest = await readManifest(dir); const entry = clipsOf(manifest).find((e) => e.id === clipId); if (!entry || entry.video !== video) return null; const { clipWords } = await import("umtool-report-to-video/clip-words"); const channelsDir = channelsDirFor(dir, manifest, { shadowExists: await hasShadowChannels(dir) }); return clipWords(entry, manifest.provenance, from, to, { channelsDir }); } /** The words of a span around one clip (for a quote), from words or cues. */ async function quoteFor(project, clipId, from, to) { const n = await clipNeighbourhood(project, { clip: clipId, from: Math.max(0, from - 1), to: to + 1 }).catch(() => null); if (!n) return ""; return quoteBetween({ words: n.words, cues: n.cues }, from, to); } /** * Make the rulings follow their clips after an edit: a moved key moves its * ruling; a clip gone takes its ruling with it (unless another clip still * sits on that moment). Returns what it did, as counts. */ export async function carryRulings(dir, beforeKeys, afterKeys) { const state = await readRulingsState(dir); if (state.error) return { moved: 0, removed: 0, error: state.error }; const rulings = state.doc.rulings; const live = new Set(afterKeys.values()); let moved = 0; let removed = 0; for (const [id, k0] of beforeKeys) { const r = rulings[k0]; if (!r) continue; const k1 = afterKeys.get(id); if (k1 && k1 !== k0) { if (!rulings[k1]) { await setMontageRuling(dir, k1, { verdict: r.verdict, reason: r.reason, ...(r.match ? { match: r.match } : {}) }); moved += 1; } if (!live.has(k0)) await setMontageRuling(dir, k0, null); } else if (!k1 && !live.has(k0)) { await setMontageRuling(dir, k0, null); removed += 1; } } return { moved, removed, error: null }; } class OpError extends Error { constructor(message, status = 400) { super(message); this.status = status; } } export { OpError }; const num = (v, what) => { const x = Number(v); if (v === null || v === undefined || v === "" || !Number.isFinite(x)) throw new OpError(`${what} must be a number of seconds`); return x; }; /** * One operation of the clip editor. `body.op` is one of * trim { clip, cutStart, cutEnd } the clip's rendered span (its cut, or its * extent when it has no cut); the extent widens * to hold a cut; an assistant's clip's quote * follows its words * restore { clip } the assistant's version back * split { clip, at } two clips at that second * merge { clip } with the next clip * flash-forward { clip, from, to, after? | section?, position?, move?, quote?, id? } * a span copied elsewhere as a repeat (or * moved out of the clip: `move`), its quote * read from the words (manifest.mjs flashForward) * add { video, channel?, cutStart, cutEnd } a selection on the strip * bring-in { proposal } one of the clip finder's unused proposals * ruling { clip, verdict: "keep" | "cut" | null } * role { speaker, role | null } reactions.json, through the clip finder's writer * label { speaker, label | null } a speaker's name for the captions (reactions.json) * vertical { clip, crop | null, aspect? } the clip's 9:16 box for its short * room { clip, room: false | {tail?, head?} | null } room at this clip's edges * (null: the cut's render.room again) * claim { clip, mark?, knobs: { at?, hold?, stamp?, count?, label? } } a mark's stamp and * count (null on a knob: its default again); * `mark` its id (default: the clip's first) * marks { clip, add: { verdict, at?, id?, … } } a new mark (a new id unless given) * { clip, remove: } one mark gone * { clip, mark: , verdict } a mark's verdict (every clip carrying the id) * { clip, set: [mark, …] | null } all of them (manifest.mjs updateMarks) * audio { clip, audio: { offset?, gain?, fadeIn?, fadeOut? } | null } the clip's sound * (null on a key, or the whole: the default) * blur { clip, blur: { on?, caption?, strength?, from?, to? } | null } the clip's * picture blurred at the encode (null on a key: its * default; null, or on: false, removes it) * onscreen { clip, onscreen: { title?, subtitle? } | null } the deck's words for it * (the live preview's fields; null: automatic) * with `token` (the manifest's, from the view) on every manifest edit. * Returns `{ op, result, carried, view }`. */ export async function runClipEditorOp(project, body, { now = null } = {}) { if (!isObj(body)) throw new OpError("a body is { op, … }"); const dir = project.dir; const token = typeof body.token === "string" ? body.token : null; const manifest = await readManifest(dir); if (!manifest) throw new OpError("no manifest", 404); const beforeKeys = momentKeysOf(manifest); const clipId = typeof body.clip === "string" ? body.clip : null; const entry = clipId ? clipsOf(manifest).find((e) => e.id === clipId) : null; const needClip = () => { if (!entry) throw new OpError(`no clip ${clipId ?? "(none named)"}`, 404); return entry; }; let result; let structural = true; switch (body.op) { case "trim": { const e = needClip(); const a = num(body.cutStart, "cutStart"); const b = num(body.cutEnd, "cutEnd"); if (b - a < 0.5) throw new OpError("a clip must be at least half a second"); if (a < 0) throw new OpError("a clip cannot start before the recording"); const hasCut = fin(e.cutStart) && fin(e.cutEnd); const patch = hasCut ? { cutStart: a, cutEnd: b, start: Math.min(e.start, a), end: Math.max(e.end, b) } : { start: a, end: b }; if (isObj(e.assist)) { const q = await quoteFor(project, e.id, a, b); if (q) patch.quote = q; } result = await updateClip(dir, e.id, patch, { token, edit: "trim", now }); break; } case "restore": result = await restoreClip(dir, needClip().id, { token, now }); break; case "split": { const e = needClip(); const at = num(body.at, "at"); const { cutStart, cutEnd } = cutOf(e); const [first, second] = await Promise.all([quoteFor(project, e.id, cutStart, at), quoteFor(project, e.id, at, cutEnd)]); result = await splitClip(dir, e.id, at, { token, now, quotes: { ...(first ? { first } : {}), ...(second ? { second } : {}) } }); break; } case "merge": result = await mergeClips(dir, needClip().id, { token, now }); break; case "flash-forward": { // A span of this clip copied somewhere else in the cut (a repeat), or // moved out of it (`move`): its quote read from the words, as a split's. const e = needClip(); const a = num(body.from, "from"); const b = num(body.to, "to"); const move = body.move === true; const { cutStart, cutEnd } = cutOf(e); const [quote, restQuote] = await Promise.all([ typeof body.quote === "string" && body.quote.trim() ? body.quote : quoteFor(project, e.id, a, b), move ? (Math.abs(a - cutStart) <= 0.5 ? quoteFor(project, e.id, b, cutEnd) : quoteFor(project, e.id, cutStart, a)) : Promise.resolve(""), ]); const section = body.section === undefined || body.section === null || body.section === "" ? null : Number(body.section); result = await flashForward( dir, e.id, { from: a, to: b, after: typeof body.after === "string" ? body.after : null, section, position: body.position === "start" ? "start" : "end", move, ...(quote ? { quote } : {}), ...(restQuote ? { restQuote } : {}), ...(typeof body.id === "string" && body.id.trim() ? { id: body.id.trim() } : {}), }, { token }, ); break; } case "add": { const video = typeof body.video === "string" ? body.video : entry?.video; const channel = typeof body.channel === "string" ? body.channel : entry ? channelFor(manifest, entry) : null; if (!video) throw new OpError("add needs the video"); const a = num(body.cutStart, "cutStart"); const b = num(body.cutEnd, "cutEnd"); const near = entry ?? clipsOf(manifest).find((e) => e.video === video); const quote = near ? await quoteFor(project, near.id, a, b) : ""; result = await addClip(dir, { video, ...(channel && channel !== manifest.provenance?.channelSlug ? { channel } : {}), cutStart: a, cutEnd: b, ...(quote ? { quote } : {}) }, { token, now }); break; } case "bring-in": { const { doc, error } = await readReactions(dir); if (error) throw new OpError(error); const p = (Array.isArray(doc?.proposals) ? doc.proposals : []).find((x) => isObj(x) && x.id === body.proposal); if (!p || !fin(p.start) || !fin(p.end)) throw new OpError(`no proposal ${String(body.proposal ?? "")}`, 404); const video = doc?.source?.video; const channel = doc?.source?.channel; if (typeof video !== "string") throw new OpError("reactions.json names no source video"); // A proposal's start/end IS the cut; the window leaves the clip finder's // WINDOW_PAD_S either side for trimming, inside the recording. const cut = { cutStart: p.start, cutEnd: p.end }; const dur = fin(doc?.source?.duration) ? doc.source.duration : Infinity; const win = { start: Math.max(0, p.start - WINDOW_PAD_S), end: Math.max(p.end, Math.min(dur, p.end + WINDOW_PAD_S)) }; const near = clipsOf(manifest).find((e) => e.video === video); const quote = near ? await quoteFor(project, near.id, cut.cutStart, cut.cutEnd) : typeof p.text === "string" ? p.text : ""; result = await addClip( dir, { video, ...(typeof channel === "string" && channel !== manifest.provenance?.channelSlug ? { channel } : {}), ...cut, start: win.start, end: win.end, ...(typeof p.clipId === "string" ? { id: p.clipId } : {}), ...(quote ? { quote } : {}), proposal: { id: p.id, ...(fin(p.score) ? { score: p.score } : {}), ...(typeof p.why === "string" ? { why: p.why } : {}), start: win.start, end: win.end }, }, { token, now }, ); break; } case "ruling": { const e = needClip(); const key = clipMomentKey(e, manifest); if (!key) throw new OpError(`${e.id} has no moment to rule (no channel?)`); const v = body.verdict; if (v !== null && !EDITOR_VERDICTS.includes(v)) throw new OpError(`verdict must be ${EDITOR_VERDICTS.join(" or ")}, or null to clear it`); result = await setMontageRuling(dir, key, v === null ? null : { verdict: v, reason: typeof body.reason === "string" ? body.reason : "" }); structural = false; break; } case "role": { const index = Number(body.speaker); if (!Number.isInteger(index) || index < 0) throw new OpError("speaker is a speaker's index"); if (body.role !== null && !SPEAKER_ROLES.includes(body.role)) throw new OpError(`role must be one of ${SPEAKER_ROLES.join(", ")}, or null`); const doc = await setSpeakerRole(dir, index, body.role); result = { speaker: doc.speakers.find((x) => x?.index === index) ?? null }; structural = false; break; } case "label": { const index = Number(body.speaker); if (!Number.isInteger(index) || index < 0) throw new OpError("speaker is a speaker's index"); if (body.label !== null && typeof body.label !== "string") throw new OpError("label is a text, or null for the default"); const doc = await setSpeakerLabel(dir, index, body.label); result = { speaker: doc.speakers.find((x) => x?.index === index) ?? null }; structural = false; break; } case "vertical": { const e = needClip(); const v = body.crop === null ? null : { crop: body.crop, ...(body.aspect !== undefined ? { aspect: Number(body.aspect) } : {}) }; // A "trim" that leaves the cut where it is: the clip's assist is not touched. result = await updateClip(dir, e.id, { vertical: v }, { token, edit: "trim", now }); structural = false; break; } case "kit": { // The clip kit (lane clip-kit, clip-kit.mjs): its keys merged as `umtool set` merges them (a key null clears // it), through the same writer. A "trim" that leaves the cut where it is; not structural. const e = needClip(); if (!isObj(body.kit) || !Object.keys(body.kit).length) throw new OpError(`kit is {${CLIP_KIT_KEYS.join("?, ")}?}: the keys to set`); const bad = Object.keys(body.kit).filter((k) => !CLIP_KIT_KEYS.includes(k.split(".")[0])); if (bad.length) throw new OpError(`kit: ${bad.join(", ")} is not a clip kit key (${CLIP_KIT_KEYS.join(", ")})`); result = await updateClip(dir, e.id, body.kit, { token, edit: "trim", now }); structural = false; break; } case "censor-recording": { // The regions hidden on every clip of THIS clip's recording (render.censor; clip-censor.mjs), through the // look's writer and its checks: `censor` {boxes, style?, strength?} sets them, null removes them. const e = needClip(); if (body.censor !== null && !isObj(body.censor)) throw new OpError("censor is {boxes, style?, strength?}, or null for none"); const m = await readManifest(dir); const key = { video: e.video, channel: null }; const next = withRecording(m?.render?.censor, key, body.censor ? { video: e.video, ...body.censor } : null); const w = await updateRender(dir, { censor: next.length ? next : null }, { token }); result = { censor: w.look.censor ?? null }; structural = false; break; } case "room": { const e = needClip(); if (body.room !== null && body.room !== false && !isObj(body.room)) throw new OpError("room is false, {tail?, head?}, or null for the cut's"); // A "trim" that leaves the cut where it is, as `vertical` is. result = await updateClip(dir, e.id, { room: body.room }, { token, edit: "trim", now }); structural = false; break; } case "claim": { // The video knobs (plans/video-knobs-ui.md): when the stamp lands and the count steps, how long it stays, // whether it is drawn, how much it counts, what it says. Not structural: no clip moves. const e = needClip(); if (!isObj(body.knobs)) throw new OpError("claim needs knobs: { at?, hold?, stamp?, count?, label? }"); result = await updateClaimKnobs(dir, e.id, body.knobs, { token, mark: typeof body.mark === "string" ? body.mark : null }); structural = false; break; } case "marks": { // The clip's marks (plans/clip-marks.md): add, remove, a verdict, or all // of them. Not structural: no clip moves. const e = needClip(); const change = "add" in body ? { add: body.add } : "remove" in body ? { remove: body.remove } : "set" in body ? { set: body.set } : "mark" in body ? { mark: body.mark, verdict: body.verdict } : null; if (!change) throw new OpError("marks needs add, remove, set, or mark with verdict"); result = await updateMarks(dir, e.id, change, { token }); structural = false; break; } case "audio": { const e = needClip(); if (body.audio !== null && !isObj(body.audio)) throw new OpError("audio is { offset?, gain?, fadeIn?, fadeOut? }, or null for none"); // A "trim" that leaves the cut where it is, as `vertical` is. result = await updateClip(dir, e.id, { audio: body.audio }, { token, edit: "trim", now }); structural = false; break; } case "blur": { // The clip's picture blurred (clip-blur.mjs): merged by updateClip, as // `audio` is. A "trim" that leaves the cut where it is. Not structural. const e = needClip(); if (body.blur !== null && !isObj(body.blur)) throw new OpError("blur is { on: true, caption?, strength?, from?, to? }, or null for none"); result = await updateClip(dir, e.id, { blur: body.blur }, { token, edit: "trim", now }); structural = false; break; } case "onscreen": { // The deck's title and subtitle for this clip (the live preview's // fields), through the On-screen table's writer: a row replaces the // clip's whole `onscreen`, null removes it. Not structural. const e = needClip(); if (body.onscreen !== null && !isObj(body.onscreen)) throw new OpError("onscreen is { title?, subtitle? }, or null for the automatic words"); result = await updateOnscreen(dir, { [e.id]: body.onscreen }, { token }); structural = false; break; } default: throw new OpError("op must be trim, restore, split, merge, flash-forward, add, bring-in, ruling, role, label, vertical, kit, censor-recording, room, claim, marks, audio, blur or onscreen"); } let carried = null; if (structural) { const after = await readManifest(dir); carried = await carryRulings(dir, beforeKeys, momentKeysOf(after)); } return { op: body.op, result: summarise(result), carried, view: await clipEditorView(project) }; } /** What a route sends back of a writer's result: ids, never the whole doc. */ function summarise(r) { if (!isObj(r)) return null; const out = {}; for (const k of ["id", "second", "absorbed", "at", "source", "move", "rest", "section", "earlier", "reanchored", "patches", "sectionPatches", "snapshot"]) if (r[k] !== undefined) out[k] = r[k]; if (isObj(r.entry) && typeof r.entry.id === "string") out.id ??= r.entry.id; if (isObj(r.speaker)) out.speaker = r.speaker; if (isObj(r.claim)) out.claim = r.claim; if (typeof r.stamps === "boolean") out.stamps = r.stamps; if (Array.isArray(r.marks)) out.marks = r.marks; if (typeof r.added === "string") out.added = r.added; if (r.ruling !== undefined) out.ruling = r.ruling; return out; }