// THE RECORDING SESSION's store (operator, 3 Nov: "I need to do a dramatic
// reading of this starting tomorrow"): a person reading a cut's posts aloud,
// PART BY PART, on /projects/
/narration/record. Every part is written to
// disk the moment it is kept, so nothing is lost on a crash and a reload
// resumes where the reading stopped:
//
// narration/posts//.recording-/
// session.json { version, id, label, count, parts: { "": { file, text, para, at, bytes, type } } }
// p01.webm … each part as the browser recorded it (webm/opus, ogg/opus)
//
// When every part of the post is in, `finishSession` makes them one recorded
// take (postRecord.mjs keepRecording: each part trimmed of its silence, joined
// with the parts' pauses, levelled to the synthesized takes), PICKED, and
// clears the session. Plain ESM.
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import { postIdOf, takesDirOf } from "umtool-report-to-video/post-narration";
import { RECORD_LABEL_RE, keepRecording } from "./postRecord.mjs";
import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs";
/** A part is at most this large (a minute of opus is well under 1 MB). */
export const SESSION_PART_MAX = 100 * 1024 * 1024;
export const sessionDirOf = (projectDir, entry, label) => path.join(projectDir, ...takesDirOf(postIdOf(entry)).split("/"), `.recording-${label}`);
const checkLabel = (label) => {
if (!RECORD_LABEL_RE.test(String(label))) throw Object.assign(new Error(`"${label}" is not a voice label (a-z, 0-9, - and _)`), { status: 400 });
};
/** The session of `entry` for voice `label` ({ parts: {} } when none). */
export async function readSession(projectDir, entry, label = "operator") {
checkLabel(label);
const dir = sessionDirOf(projectDir, entry, label);
try {
const doc = JSON.parse(await readFile(path.join(dir, "session.json"), "utf8"));
return { version: 1, id: entry.id, label, count: null, parts: {}, ...doc };
} catch {
return { version: 1, id: entry.id, label, count: null, parts: {} };
}
}
async function writeSession(dir, doc) {
const tmp = path.join(dir, `.session.${process.pid}.${Date.now()}.json`);
await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8");
await rename(tmp, path.join(dir, "session.json"));
}
// A browser recording is webm or ogg; a sound file chosen for a part keeps what it is (ffmpeg reads it either way).
const extOf = (type) => (/ogg/.test(type) ? "ogg" : /wav/.test(type) ? "wav" : /mp4|aac|m4a/.test(type) ? "m4a" : /mpeg|mp3/.test(type) ? "mp3" : /flac/.test(type) ? "flac" : "webm");
/**
* KEEP ONE PART: its bytes written (through a rename: never half a file), the
* session updated. `n` from 1; `count` how many parts the post's read has.
*
* @param {string} projectDir
* @param {Record} entry
* @param {{ n: number, count: number, text: string, para: number, bytes: Uint8Array, type?: string, label?: string }} part
*/
export async function savePart(projectDir, entry, { n, count, text, para, bytes, type = "audio/webm", label = "operator" }) {
checkLabel(label);
if (!Number.isInteger(n) || n < 1 || !Number.isInteger(count) || count < 1 || n > count || count > 200) throw Object.assign(new Error("a part is n of count (1 ≤ n ≤ count ≤ 200)"), { status: 400 });
if (!bytes?.byteLength) throw Object.assign(new Error("the part is empty"), { status: 400 });
if (bytes.byteLength > SESSION_PART_MAX) throw Object.assign(new Error("the part is too large"), { status: 413 });
const dir = sessionDirOf(projectDir, entry, label);
await mkdir(dir, { recursive: true });
const doc = await readSession(projectDir, entry, label);
// A different split of the script (it was edited): the parts kept so far no longer line up.
if (doc.count !== null && doc.count !== count) doc.parts = {};
const name = `p${String(n).padStart(2, "0")}.${extOf(type)}`;
const tmp = tmpPathFor(path.join(dir, `.${name}`));
await writeFile(tmp, bytes);
const old = doc.parts[String(n)];
await rename(tmp, path.join(dir, name));
if (old && old.file !== name) await rm(path.join(dir, old.file), { force: true });
doc.count = count;
doc.parts[String(n)] = { file: name, text: String(text ?? ""), para: Number.isInteger(para) ? para : n - 1, at: new Date().toISOString(), bytes: bytes.byteLength, type };
await writeSession(dir, doc);
return doc;
}
/** Drop one part of the session (redo it). */
export async function discardPart(projectDir, entry, n, label = "operator") {
const dir = sessionDirOf(projectDir, entry, label);
const doc = await readSession(projectDir, entry, label);
const p = doc.parts[String(n)];
if (p) {
await rm(path.join(dir, p.file), { force: true });
delete doc.parts[String(n)];
await writeSession(dir, doc);
}
return doc;
}
/** The absolute file of a session part, or null. */
export async function partFile(projectDir, entry, n, label = "operator") {
const doc = await readSession(projectDir, entry, label);
const p = doc.parts[String(n)];
return p ? path.join(sessionDirOf(projectDir, entry, label), p.file) : null;
}
/**
* The session's parts in reading order, as keepRecording and the preview take them (`[{ file, text, para }]`, the
* files absolute). Refused, naming the missing parts, when the post's read is not all in.
*/
export async function sessionParts(projectDir, entry, label = "operator") {
const doc = await readSession(projectDir, entry, label);
const count = doc.count ?? 0;
const missing = [];
for (let n = 1; n <= count; n += 1) if (!doc.parts[String(n)]) missing.push(n);
if (!count || missing.length) throw Object.assign(new Error(count ? `parts ${missing.join(", ")} of ${count} are not recorded yet` : "nothing recorded yet"), { status: 400 });
const dir = sessionDirOf(projectDir, entry, label);
const parts = [];
for (let n = 1; n <= count; n += 1) {
const p = doc.parts[String(n)];
parts.push({ file: path.join(dir, p.file), text: p.text, para: p.para });
}
return parts;
}
/** Remove the session (its parts are a take now, or were given up). */
export async function clearSession(projectDir, entry, label = "operator") {
checkLabel(label);
await rm(sessionDirOf(projectDir, entry, label), { recursive: true, force: true });
}
/**
* FINISH: every part of the post in -> one recorded take (keepRecording),
* picked; the session cleared. Refused, naming the missing parts, otherwise.
* `spans`: the cut marks a person set on the record page, per part (`[{ from, to } | null]`); a part without one is
* trimmed as its character's recorded preset says.
*
* @param {{ id: string, dir: string }} project
* @param {Record} entry
* @param {{ label?: string, manifest?: Record | null, script?: string | null, spans?: Array<{ from: number, to: number } | null> | null }} [o]
*/
export async function finishSession(project, entry, { label = "operator", manifest = null, script = null, spans = null } = {}) {
const parts = await sessionParts(project.dir, entry, label);
// Its character's recorded preset says whether its edges are trimmed, and the room kept (characterLayers.mjs).
const { recordedTrimFor } = await import("./characterLayers.mjs");
const kept = await keepRecording(project, entry, parts, { label, manifest, script, trim: await recordedTrimFor(project.dir, entry), spans });
await clearSession(project.dir, entry, label);
return kept;
}