// RECORD -> FILTER -> PREVIEW (operator, 11 Nov: "run the filter and preview it seamlessly in the record UI"): a
// recording of a post item run through its character's RECORDED PRESET -- cleaned (the editor's voice-enhance), its
// edges trimmed to speech (or cut at the marks a person set), converted to the character's STOCK voice (the editor's
// voice-convert) -- WITHOUT making a take, so it can be listened to beside the raw read first. The record page's
// Filter and `umtool posts narrate
- --recording
--preview` are this one chain.
//
// /narration/.record-preview/./ the SCRATCH DIR: one per post item and voice label,
// preview.json what is in it, and what each file was made from removed on Keep, on Again, when the
// pNN.raw.wav each part as recorded, 48 kHz mono, UNTRIMMED page is left, and when the recording
// pNN.clean.wav each part cleaned, untrimmed it was made from changes; one a
// raw.wav, raw.parts/ the parts cut to their spans, joined, levelled crash left behind is removed the next
// clean.wav, clean.parts/ the same from the cleaned parts time a preview is prepared (a day old)
// filtered.wav[, filtered.parts/] clean.wav (else raw.wav) converted
//
// THE ORDER is clean -> trim -> convert: the parts are cleaned WHOLE, so moving a cut mark re-cuts the cleaned sound
// and asks the editor for the convert alone; changing the pitch asks for the convert alone too. Each step is kept
// with a key of what it was made from (`source`: the recording's files; `built`: + the spans; `convert`: + the
// engine, voice, pitch and semitones) and a step whose key still answers is not run again.
//
// KEEP (keepPreview) makes the takes `posts narrate --recording` would -- the recorded one (the original, trimmed,
// levelled), the cleaned one, the converted one, each a new take, the last picked -- FROM THE PREVIEW's FILES: nothing
// is converted again. Plain ESM; the editor is asked through narrate-via-editor.mjs askEditorOp (`ask` in a test).
import { createHash } from "node:crypto";
import { execFile } from "node:child_process";
import { copyFile, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import { promisify } from "node:util";
import { POST_DERIVE_ROUTES, derivedFileOf, nextTakeNumber, postIdOf, postNarrationDisclosure, takeIdOf, takesDirOf } from "umtool-report-to-video/post-narration";
import { convertPitchLabel, recordedPresetOf, shownNameOf } from "umtool-report-to-video/cast";
import { readManifest } from "../projects/report.mjs";
import { readLayers } from "./characterLayers.mjs";
import { convertAskOf, stepPitchOf } from "./derivePitch.mjs";
import { withEditNotes } from "./edit-guard.mjs";
import { manifestToken, updatePostNarration } from "./manifest.mjs";
import { NarrateError, findPostItem, measureTake } from "./postNarrationCli.mjs";
import { RECORD_LABEL_RE, claimRecordedTake, claimTakeName, decodePart, explicitSpan, joinRecording, partsIn, roomOf, targetLufsOf, trimSpan } from "./postRecord.mjs";
const execFileP = promisify(execFile);
const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg";
/** The scratch dirs' parent, project-relative. */
export const PREVIEW_DIR = "narration/.record-preview";
/** How many levels a part's waveform is drawn from. */
export const PREVIEW_PEAKS = 240;
/** A scratch dir nobody removed (a crash, a closed laptop) is removed after this long. */
export const PREVIEW_STALE_MS = 24 * 60 * 60 * 1000;
const sha = (v) => createHash("sha1").update(typeof v === "string" ? v : JSON.stringify(v)).digest("hex");
const pad2 = (n) => String(n).padStart(2, "0");
const checkLabel = (label) => {
if (!RECORD_LABEL_RE.test(String(label))) throw Object.assign(new NarrateError(`"${label}" is not a voice label (a-z, 0-9, - and _)`), { status: 400 });
};
/** The scratch dir of post item `entry`'s preview for voice `label` (absolute). */
export const previewDirOf = (projectDir, entry, label = "operator") => path.join(projectDir, ...PREVIEW_DIR.split("/"), `${postIdOf(entry)}.${label}`);
/** The preview's record (`preview.json`), or null: none, or unreadable. */
export async function readPreview(projectDir, entry, label = "operator") {
checkLabel(label);
try {
const doc = JSON.parse(await readFile(path.join(previewDirOf(projectDir, entry, label), "preview.json"), "utf8"));
return doc && doc.version === 1 && Array.isArray(doc.parts) ? doc : null;
} catch {
return null;
}
}
async function writePreview(dir, doc) {
const tmp = path.join(dir, `.preview.${process.pid}.${Date.now()}.json`);
await writeFile(tmp, `${JSON.stringify(doc, null, 1)}\n`, "utf8");
await rename(tmp, path.join(dir, "preview.json"));
}
/** Remove the preview of `entry` (Again, leaving the page, Keep). */
export async function discardPreview(projectDir, entry, label = "operator") {
checkLabel(label);
await rm(previewDirOf(projectDir, entry, label), { recursive: true, force: true });
}
/** Scratch dirs of this project nobody removed in PREVIEW_STALE_MS (not `keep`): gone. */
async function pruneStale(projectDir, keep, now = Date.now()) {
const root = path.join(projectDir, ...PREVIEW_DIR.split("/"));
for (const name of await readdir(root).catch(() => [])) {
const dir = path.join(root, name);
if (dir === keep) continue;
const st = await stat(path.join(dir, "preview.json")).catch(() => null) ?? (await stat(dir).catch(() => null));
if (st && now - st.mtimeMs > PREVIEW_STALE_MS) await rm(dir, { recursive: true, force: true });
}
}
/** What a recording is, for the cache: its files, their sizes and times. */
export async function sourceKeyOf(parts) {
const rows = [];
for (const p of parts) {
const st = await stat(p.file).catch(() => null);
if (!st?.isFile()) throw new NarrateError(`no recording at ${p.file}`);
rows.push([p.file, st.size, Math.round(st.mtimeMs)]);
}
return sha(rows);
}
/** A wav's levels for a waveform: PREVIEW_PEAKS values 0-1, the loudest sample of each slice. */
export async function peaksOf(wav, count = PREVIEW_PEAKS) {
const { stdout } = await execFileP(FFMPEG(), ["-nostdin", "-v", "error", "-i", wav, "-ac", "1", "-ar", "8000", "-f", "s16le", "-"], { encoding: "buffer", maxBuffer: 512 * 1024 * 1024 });
const samples = Math.floor(stdout.length / 2);
const out = new Array(count).fill(0);
if (!samples) return out;
for (let i = 0; i < samples; i += 1) {
const k = Math.min(count - 1, Math.floor((i * count) / samples));
const v = Math.abs(stdout.readInt16LE(i * 2)) / 32768;
if (v > out[k]) out[k] = v;
}
return out.map((v) => Math.round(v * 1000) / 1000);
}
/**
* PREPARE: the recording's parts decoded into the scratch dir (once: a recording that has not changed is not decoded
* again), each with its length, its waveform and the AUTO TRIM's answer -- `auto: { from, to }`, the span of its
* speech with the room kept (`trim.padMs`, else the recorder's own), or the whole part when `trim.on` is false. No
* editor, no take. Returns the preview's record.
*
* @param {{ id: string, dir: string }} project
* @param {Record} entry
* @param {Array<{ file: string, text?: string, para?: number }>} parts
* @param {{ label?: string, trim?: { on?: boolean, padMs?: number | null } | null }} [o]
*/
export async function preparePreview(project, entry, parts, { label = "operator", trim = null } = {}) {
checkLabel(label);
if (!parts.length) throw new NarrateError("nothing was recorded");
const dir = previewDirOf(project.dir, entry, label);
const source = await sourceKeyOf(parts);
let doc = await readPreview(project.dir, entry, label);
if (!doc || doc.source !== source) {
// Another recording than the one in the scratch dir (a part re-recorded, another file): everything from it goes.
await rm(dir, { recursive: true, force: true });
await mkdir(dir, { recursive: true });
await pruneStale(project.dir, dir);
doc = { version: 1, id: entry.id, label, source, at: new Date().toISOString(), parts: [], clean: null, cleaned: null, built: null, convert: null, notes: [] };
for (const [k, p] of parts.entries()) {
const raw = `p${pad2(k + 1)}.raw.wav`;
const { seconds, silences } = await decodePart(p.file, path.join(dir, raw));
doc.parts.push({ n: k + 1, para: Number.isInteger(p.para) ? p.para : k, text: String(p.text ?? ""), raw, seconds, silences, peaks: await peaksOf(path.join(dir, raw)) });
}
}
const on = trim?.on !== false;
const room = roomOf(trim);
doc.trim = { on, padMs: Number.isFinite(trim?.padMs) ? trim.padMs : null };
for (const p of doc.parts) p.auto = on ? trimSpan(p.silences, p.seconds, room) : { from: 0, to: p.seconds };
await writePreview(dir, doc);
return doc;
}
const notInstalled = (err) => err?.name === "OpNotInstalled" || /not installed/i.test(String(err?.message));
/**
* THE CHAIN, no take made: `parts` (`[{ file, text?, para? }]`, a recording in reading order) prepared, CLEANED
* (unless the character's preset or `clean` says not to; an editor with no enhance engine: said, and gone without),
* cut to `spans` (per part, `{ from, to }` in its own seconds; a part without one: the auto trim's) and joined,
* CONVERTED to the character's stock voice at `pitch` / `semitones` (each unless given: the preset's;
* derivePitch.mjs convertAskOf). The character is `as`, else the chain's (cast.mjs characterForRead). What the
* command says wins over the preset: `clean`, `trim`, `pitch`, `semitones`, `engine`, `voice`; `convert: false` stops
* after the clean.
*
* `emit("stage", { stage: "decode" | "clean" | "trim" | "convert" | "done", state, message })` says where it is --
* `state`: `running`, `cached`, `skipped`, `done`, and while the editor's job waits `queued` (behind other jobs),
* `memory` or `slot` (at the heavy slot: the gate working, not an error).
*
* Returns `{ dir, raw, clean, filtered, listen, notes, character, direction, convert, spans, lufs, cached }` -- the
* files absolute; `listen` is what to compare with `raw` (the converted read, else the cleaned one, else null).
* `out`: `listen` (else `raw`) copied there. `session: true`: the parts are the record page's session of the item
* (keepPreview says so, and its caller clears the session).
*/
export async function runPreview(project, entry, parts, {
label = "operator", as = null, clean = undefined, trim = undefined, spans = null, convert = true, pitch = undefined, semitones = undefined, engine = null, voice = null,
out = null, emit = () => {}, editor = null, ask = null, session = false,
} = {}) {
const layers = await readLayers(project.dir);
const who = layers.characterForRead(entry, as);
const character = who?.character ?? null;
if (as && !character) throw new NarrateError(`--as ${as}: no such character in this video's characters or the cast (umtool cast project ${project.id}, umtool cast ls)`);
const preset = character ? recordedPresetOf(character) : null;
const doClean = clean ?? preset?.enhance ?? true;
const doTrim = trim ?? preset?.trim ?? null;
const stage = (name, state, message, more = {}) => emit("stage", { stage: name, state, message, ...more });
const askOp = ask ?? (await import("umtool-report-to-video/narrate-via-editor")).askEditorOp;
const { opWaitOf } = await import("umtool-report-to-video/narrate-via-editor");
const waiting = (name, what) => {
let last = "";
return (st) => {
const w = opWaitOf(st);
const key = `${w.state}|${w.position ?? ""}`;
if (key === last) return;
last = key;
const say = w.state === "queued" ? `${what}: queued at the editor${w.position ? ` (position ${w.position})` : ""}`
: w.state === "memory" ? `${what}: waiting for memory (the heavy slot admits it when there is room -- not an error)`
: w.state === "slot" ? `${what}: waiting for the heavy slot (another heavy job holds it -- not an error)`
: `${what}: running`;
stage(name, w.state, say, { job: st.jobId, ...(w.line ? { line: w.line } : {}) });
};
};
const note = (_ev, f) => f?.message && emit("note", { message: f.message });
stage("decode", "running", "reading the recording");
let doc = await preparePreview(project, entry, parts, { label, trim: doTrim });
const dir = previewDirOf(project.dir, entry, label);
const abs = (name) => path.join(dir, ...String(name).split("/"));
const has = async (name) => !!(await stat(abs(name)).catch(() => null))?.isFile();
const notes = [];
const cached = { clean: false, convert: false };
// CLEAN: the parts whole, as recorded (one job of the editor's: one admission to the heavy slot).
if (!doClean) {
doc.cleaned = { state: "off" };
notes.push(clean === undefined && character ? `not cleaned: ${character.id}'s recorded preset says so (enhance off)` : "not cleaned: asked not to (--no-clean)");
stage("clean", "skipped", notes.at(-1));
} else if (doc.clean?.key === doc.source && (await Promise.all(doc.clean.files.map(has))).every(Boolean)) {
doc.cleaned = { state: "done" };
cached.clean = true;
stage("clean", "cached", "cleaned already (this recording, unchanged)");
} else {
stage("clean", "running", "cleaning: asking the editor (voice-enhance)");
const files = doc.parts.map((p) => p.raw.replace(/\.raw\.wav$/, ".clean.wav"));
try {
const { jobId, result } = await askOp(POST_DERIVE_ROUTES.enhance, {
file: abs(doc.parts[0].raw), out: abs(files[0]),
...(doc.parts.length > 1 ? { parts: doc.parts.slice(1).map((p, k) => ({ file: abs(p.raw), out: abs(files[k + 1]) })) } : {}),
}, { ...(editor ? { editor } : {}), emit: note, onState: waiting("clean", "cleaning") });
for (const f of files) if (!(await has(f))) throw new NarrateError(`the editor's job ${jobId} finished but ${f} is not there`);
doc.clean = { key: doc.source, files, engine: typeof result?.engine === "string" ? result.engine : null, job: jobId, ranAt: new Date().toISOString() };
doc.cleaned = { state: "done" };
stage("clean", "done", "cleaned");
} catch (err) {
if (!notInstalled(err)) throw err;
doc.cleaned = { state: "skipped" };
notes.push(`not cleaned: ${err.message} (archilyzer voice setup --engine deepfilternet)`);
stage("clean", "skipped", notes.at(-1));
}
await writePreview(dir, doc);
}
const cleaned = doc.cleaned.state === "done";
// TRIM: each part cut to its span -- the marks given, else the auto trim's -- the raw read and the cleaned one alike.
const cut = doc.parts.map((p, k) => explicitSpan(spans?.[k], p.seconds) ?? p.auto);
const target = targetLufsOf((await readManifest(project.dir)) ?? {});
const builtKey = sha([doc.source, cut, cleaned, target]);
if (doc.built?.key === builtKey && (await has("raw.wav")) && (!cleaned || (await has("clean.wav")))) {
stage("trim", "cached", "cut and joined already (these marks)");
} else {
stage("trim", "running", `cutting ${doc.parts.length === 1 ? "it" : `its ${doc.parts.length} parts`} to ${doc.parts.length === 1 ? "its marks" : "their marks"}`);
const sources = (file) => doc.parts.map((p, k) => ({ wav: abs(file(p, k)), ...cut[k], text: p.text, para: p.para }));
for (const f of ["raw.parts", "clean.parts", "filtered.parts"]) await rm(abs(f), { recursive: true, force: true });
for (const f of ["clean.wav", "filtered.wav"]) await rm(abs(f), { force: true });
const raw = await joinRecording(sources((p) => p.raw), { out: abs("raw.wav"), partsDir: abs("raw.parts"), target });
const cl = cleaned ? await joinRecording(sources((_p, k) => doc.clean.files[k]), { out: abs("clean.wav"), partsDir: abs("clean.parts"), target }) : null;
doc.built = { key: builtKey, spans: cut, target, raw: { file: "raw.wav", ...raw }, clean: cl ? { file: "clean.wav", ...cl } : null };
doc.convert = null;
await writePreview(dir, doc);
stage("trim", "done", `cut: ${raw.seconds} s`);
}
// CONVERT: the cleaned read (else the raw one) to the character's stock voice, at the pitch asked or the preset's.
if (!convert) {
notes.push("not converted: asked not to (--no-convert)");
stage("convert", "skipped", notes.at(-1));
} else {
const d = convertAskOf({ engine, voice, pitch, semitones }, character ? preset.convert : null, character?.id ?? null);
if (!d.ok) {
notes.push(`not converted: ${d.error} (${d.fix})`);
stage("convert", "skipped", notes.at(-1));
} else {
const a = d.value;
const key = sha([builtKey, a.engine, a.voice, a.pitch ?? null, a.semitones ?? null]);
if (doc.convert?.key === key && (await has("filtered.wav"))) {
cached.convert = true;
stage("convert", "cached", `converted already (${a.voice}${convertPitchLabel(doc.convert) ? `, pitch: ${convertPitchLabel(doc.convert)}` : ""})`);
} else {
stage("convert", "running", `converting to ${a.voice}: asking the editor (voice-convert)`);
const src = doc.built.clean ?? doc.built.raw;
const srcParts = src.file.replace(/\.wav$/, ".parts");
await rm(abs("filtered.parts"), { recursive: true, force: true });
try {
const { jobId, result } = await askOp(POST_DERIVE_ROUTES.convert, {
file: abs(src.file), out: abs("filtered.wav"), ...(a.engine ? { engine: a.engine } : {}), voice: a.voice,
...(a.pitch ? { pitch: a.pitch } : {}), ...(typeof a.semitones === "number" ? { semitones: a.semitones } : {}),
...(src.parts.length > 1 ? { parts: src.parts.map((p) => ({ file: abs(`${srcParts}/${p.name}`), out: abs(`filtered.parts/${p.name}`) })) } : {}),
}, { ...(editor ? { editor } : {}), emit: note, onState: waiting("convert", "converting") });
if (!(await has("filtered.wav"))) throw new NarrateError(`the editor's job ${jobId} finished but filtered.wav is not there`);
const m = await measureTake(abs("filtered.wav"));
doc.convert = {
key, built: builtKey, file: "filtered.wav", asked: a,
engine: a.engine ?? (typeof result?.engine === "string" ? result.engine : null), voice: a.voice, ...stepPitchOf(a, result ?? {}),
job: jobId, ranAt: new Date().toISOString(), seconds: m.seconds, ...(Number.isFinite(m.lufs) ? { lufs: m.lufs } : {}),
};
stage("convert", "done", `converted to ${a.voice}${convertPitchLabel(doc.convert) ? ` (pitch: ${convertPitchLabel(doc.convert)})` : ""}`);
} catch (err) {
if (!notInstalled(err)) throw err;
doc.convert = null;
notes.push(`not converted: ${err.message} (archilyzer voice setup --engine ${a.engine ?? "openvoice"})`);
stage("convert", "skipped", notes.at(-1));
}
}
}
}
doc.notes = notes;
// Made from the record page's session (not a file): keeping it is the end of that session.
doc.session = session === true;
doc.character = character ? { id: character.id, name: shownNameOf(character), layer: who.layer } : null;
await writePreview(dir, doc);
const listen = doc.convert ? abs(doc.convert.file) : doc.built.clean ? abs(doc.built.clean.file) : null;
let copied = null;
if (out) {
copied = path.resolve(String(out));
await mkdir(path.dirname(copied), { recursive: true });
await copyFile(listen ?? abs("raw.wav"), copied);
}
stage("done", "done", listen ? "the preview is ready: nothing was kept" : "nothing to filter it with: the raw read alone");
return {
dir, raw: abs("raw.wav"), clean: doc.built.clean ? abs("clean.wav") : null, filtered: doc.convert ? abs(doc.convert.file) : null, listen, ...(copied ? { out: copied } : {}),
notes, character: doc.character, ...(preset?.direction ? { direction: preset.direction } : {}),
convert: doc.convert ? { engine: doc.convert.engine, voice: doc.convert.voice, ...(doc.convert.pitch ? { pitch: doc.convert.pitch } : {}), ...(typeof doc.convert.semitones === "number" ? { semitones: doc.convert.semitones } : {}) } : null,
spans: cut, lufs: { raw: doc.built.raw.lufs ?? null, filtered: doc.convert?.lufs ?? doc.built.clean?.lufs ?? null }, cached,
};
}
/**
* What the record page is told of a preview (`preview.json` without the silences): each part's length, waveform, auto
* span and the span it was cut at; what was made (`raw`, `clean`, `filtered`: seconds and loudness, so both play at one
* level); the convert as it ran; the notes. `null`: none.
*/
export function previewView(doc) {
if (!doc) return null;
const made = (x) => (x ? { seconds: x.seconds ?? null, lufs: Number.isFinite(x.lufs) ? x.lufs : null } : null);
return {
id: doc.id, label: doc.label, source: doc.source, trim: doc.trim ?? { on: true, padMs: null },
parts: doc.parts.map((p, k) => ({ n: p.n, text: p.text, seconds: p.seconds, auto: p.auto, peaks: p.peaks, span: doc.built?.spans?.[k] ?? null })),
cleaned: doc.cleaned?.state ?? null,
raw: made(doc.built?.raw), clean: made(doc.built?.clean),
filtered: doc.convert && doc.convert.built === doc.built?.key ? { ...made(doc.convert), engine: doc.convert.engine, voice: doc.convert.voice, pitch: doc.convert.pitch ?? "target", semitones: doc.convert.semitones ?? 0, asked: doc.convert.asked ?? null } : null,
notes: doc.notes ?? [], character: doc.character ?? null,
};
}
/**
* The absolute file of one of a preview's sounds (`raw`, `clean`, `filtered`, or `part` + n: that part as recorded), or null.
*
* @param {string} projectDir
* @param {Record} entry
* @param {string} which
* @param {{ label?: string, n?: number | null }} [o]
*/
export async function previewFile(projectDir, entry, which, { label = "operator", n = null } = {}) {
const doc = await readPreview(projectDir, entry, label);
if (!doc) return null;
const dir = previewDirOf(projectDir, entry, label);
const name = which === "raw" ? doc.built?.raw?.file : which === "clean" ? doc.built?.clean?.file : which === "filtered" ? (doc.convert?.built === doc.built?.key ? doc.convert?.file : null)
: which === "part" ? doc.parts.find((p) => p.n === Number(n))?.raw : null;
if (!name) return null;
const f = path.join(dir, name);
return (await stat(f).catch(() => null))?.isFile() ? f : null;
}
/**
* KEEP THE PREVIEW: its files made the takes a recording made a read would be -- take-.recorded-.wav (the
* original: trimmed, joined, levelled), the cleaned one (`steps: [{op: "enhance"}]`), the converted one (`steps: [{op:
* "convert", engine, voice, pitch?, semitones?}]`) -- each a new take through the writer (an undo point each), the
* last one PICKED (a pick takes the approval away: it awaits approval). Nothing is asked of the editor. The scratch dir
* is removed. `parts`: the recording meant (the session's parts now) -- a preview of another is refused (409). Returns `{ takes: [{ step, file }], picked, notes, disclosure, character, session, entry, token }`.
*
* @param {{ id: string, dir: string }} project
* @param {Record} entry
* @param {{ label?: string, script?: string | null, note?: string | null, parts?: Array<{ file: string }> | null }} [o]
*/
export async function keepPreview(project, entry, { label = "operator", script = null, note = null, parts: meant = null } = {}) {
const doc = await readPreview(project.dir, entry, label);
if (!doc?.built) throw Object.assign(new NarrateError(`${entry.id} has no preview to keep (Filter it first: umtool posts narrate ${project.id} ${entry.id} --recording --preview)`), { status: 409 });
// The recording the caller means to keep (the record page's session, as it is NOW): a preview made from another
// one -- a part recorded again since the Filter -- is refused; its sound is not what was read last.
if (meant && (await sourceKeyOf(meant)) !== doc.source) throw Object.assign(new NarrateError(`${entry.id}'s preview is of an earlier recording (a part was recorded again since the Filter): Filter again, or keep the recording alone`), { status: 409 });
const dir = previewDirOf(project.dir, entry, label);
const pid = postIdOf(entry);
const takesDir = path.join(project.dir, ...takesDirOf(pid).split("/"));
await mkdir(takesDir, { recursive: true });
let n = nextTakeNumber(entry, await readdir(takesDir).catch(() => []));
const abs = (rel) => path.join(project.dir, ...rel.split("/"));
const multi = doc.parts.length > 1;
// One of the preview's sounds (and its parts) moved to a take's name.
const move = async (made, rel) => {
await rename(path.join(dir, made.file), abs(rel));
const partsRel = rel.replace(/\.wav$/, ".parts");
const from = path.join(dir, made.file.replace(/\.wav$/, ".parts"));
if (await stat(from).catch(() => null)) {
// A parts folder already at that name is another take's: never removed (the claim makes one unlikely; refused).
if (await stat(abs(partsRel)).catch(() => null)) throw Object.assign(new NarrateError(`${partsRel} is there already (another take's parts): nothing of it is touched -- keep it again`), { status: 409 });
await rename(from, abs(partsRel));
}
return partsRel;
};
const write = async (patch) => (await withEditNotes(project, async () => updatePostNarration(project.dir, entry.id, patch, { token: await manifestToken(project.dir) }))).result;
const takes = [];
const at = () => new Date().toISOString();
const lufs = (x) => (Number.isFinite(x?.lufs) ? { lufs: x.lufs } : {});
const text = String(script ?? entry.narration?.script ?? "");
const who = doc.character;
// The original -- its name CLAIMED (postRecord.mjs claimRecordedTake): never a recording already there, nor one kept
// at the same moment; each derived one's too (claimTakeName).
const claim = await claimRecordedTake(project.dir, entry, label);
n = claim.n;
const rel = claim.rel;
const partsRel = await move(doc.built.raw, rel);
const parts = multi ? partsIn(doc.built.raw.parts, partsRel) : null;
const recorded = {
file: rel, engine: "recorded", voice: label, label, seconds: doc.built.raw.seconds, source: { kind: "recorded", voice: label }, script: text,
at: at(), ...lufs(doc.built.raw), note: note ?? `recorded${who ? ` for ${who.name}` : ""}`, ...(parts ? { parts } : {}),
};
let result = await write({ addTake: recorded, ...(script !== null && script !== entry.narration?.script ? { script } : {}) });
takes.push({ step: "recorded", file: rel });
let from = recorded;
const derived = (file, made, step, voiceOf, partsDir, job) => ({
file, engine: "derived", voice: voiceOf, seconds: made.seconds, source: { kind: "take", from: takeIdOf(from) }, steps: [step], script: text, at: at(), ...(job ? { jobId: job } : {}), ...lufs(made),
...(parts ? { parts: parts.map((p) => ({ ...p, file: `${partsDir}/p${pad2(p.n)}.wav` })) } : {}),
});
// The cleaned one.
if (doc.built.clean) {
const c2 = await claimTakeName(project.dir, (k) => derivedFileOf(pid, k, "enhance", "default"), n + 1);
n = c2.n;
const r2 = c2.rel;
const p2 = await move(doc.built.clean, r2);
const take = derived(r2, doc.built.clean, { op: "enhance", ...(doc.clean?.engine ? { engine: doc.clean.engine } : {}), ranAt: doc.clean?.ranAt ?? at(), ...(doc.clean?.job ? { job: doc.clean.job } : {}) }, label, p2, doc.clean?.job);
result = await write({ addTake: take });
takes.push({ step: "cleaned", file: r2 });
from = take;
}
// The converted one -- when it is of these marks (a mark moved after the Filter leaves it behind).
if (doc.convert && doc.convert.built === doc.built.key && (await stat(path.join(dir, doc.convert.file)).catch(() => null))?.isFile()) {
const c = doc.convert;
const c3 = await claimTakeName(project.dir, (k) => derivedFileOf(pid, k, "convert", c.asked?.engine ?? c.asked?.voice ?? "default"), n + 1);
n = c3.n;
const r3 = c3.rel;
const p3 = await move(c, r3);
const pitched = c.pitch ? { pitch: c.pitch, ...(typeof c.semitones === "number" ? { semitones: c.semitones } : {}) } : {};
const take = derived(r3, c, { op: "convert", ...(c.engine ? { engine: c.engine } : {}), voice: c.voice, ...pitched, ranAt: c.ranAt ?? at(), ...(c.job ? { job: c.job } : {}) }, String(c.voice).split(":").pop(), p3, c.job);
result = await write({ addTake: take });
const how = convertPitchLabel(c);
takes.push({ step: `converted to ${c.voice}${how ? ` (pitch: ${how})` : ""}`, file: r3 });
}
await rm(dir, { recursive: true, force: true });
const now = findPostItem(await readManifest(project.dir), entry.id);
return { takes, picked: takes.at(-1).file, notes: doc.notes ?? [], disclosure: now ? postNarrationDisclosure(now) : null, character: who ?? null, session: doc.session === true, entry: result.entry, token: result.token };
}