// A READ WITHOUT A PIECE, RE-JOINED (umtool/docs/knobs.md, "Thread reads";
// operator, 4 Nov, p-2117216053952655778 / p-2117259673917386879: "we don't
// need to read this context, or paraphrase it"; p-2116651428425150687: its
// quote's links read aloud): the picked take's kept parts cut out of its own
// file and joined again -- no TTS, nothing re-synthesized.
//
// umtool posts reread
- [--without parent:0|parent:1|quoted[,…]] [--drop-parts 3,4] [--drop-urls] [--dry-run] [--json]
//
// The parts dropped are those whose ROLE (post-thread.mjs partRoles) is a
// piece named by --without, the parts named by number, and (--drop-urls) the
// parts that are nothing but a link (post-narration.mjs isOnlyUrls). The kept
// parts' spans are cut from the take's file (ffmpeg atrim), joined with the
// pauses a read is assembled with (POST_PART_GAP: between paragraphs, inside
// one), measured, and added as a DERIVED take -- `source: {kind: "take",
// from}`, `steps: [{op: "rejoin", drop, ranAt}]` -- its parts re-timed (each
// with its role stored), its word timings moved with them (a word in a part
// dropped goes too: a beep, a zoom still find theirs), its slurs state kept;
// and picked, in ONE write (updatePostNarration: one undo point). The source
// take is never touched.
//
// Plain ESM: the CLI runs it under bare node.
import { execFile } from "node:child_process";
import { mkdir, readdir, rm, stat } from "node:fs/promises";
import path from "node:path";
import { promisify } from "node:util";
import { POST_NARRATION_LIMITS, POST_PART_GAP, derivedFileOf, isOnlyUrls, nextTakeNumber, pickedTake, postIdOf, takeIdOf, takeSourceOf, takesDirOf } from "umtool-report-to-video/post-narration";
import { partRoles } from "umtool-report-to-video/post-thread";
import { readManifest } from "../projects/report.mjs";
import { withEditNotes } from "./edit-guard.mjs";
import { manifestToken, updatePostNarration } from "./manifest.mjs";
const execFileP = promisify(execFile);
const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg";
const FFPROBE = () => process.env.FFPROBE_BIN ?? "ffprobe";
const fin = (v) => typeof v === "number" && Number.isFinite(v);
const r3 = (v) => Math.round(v * 1000) / 1000;
export const REREAD_USAGE = [
" umtool posts reread
- [--without parent:0|parent:1|quoted[,…]] [--drop-parts 3,4] [--drop-urls] [--dry-run] [--json]",
" umtool posts reread
- --tempo-for \"4-16=1.35,21-25=1.3\" | --tempo 1.3 --parts 4-16,21-25 [--stretch atempo|rubberband] [--dry-run] [--json]",
" umtool posts reread
- --yell-caps [--yell-gain 5.5] [--yell-style raise|shout|loud] [--dry-run] [--json]",
" umtool posts reread
- --pause \"20=0.45,10=0.45,4#2=0.6\" [--target post|parent:0|quoted|linked:0] [--dry-run] [--json]",
" umtool posts reread
- --revoice \"20 10 4 0\"[#n] --say \"20... 10... 4... 0...\" [--target linked:0] [--voice |auto] [--xfade 0.03] [--splice -] [--dry-run] [--json]",
" (any form, + --in-take or --take : the new take picked in a take's patch, the project's pick kept)",
" A READ WITHOUT A PIECE, RE-JOINED (no TTS): the picked take's kept parts cut out of its own file and joined with",
" the read's pauses, as a NEW take (source: the take; steps: rejoin) that is picked -- one write, undoable. --without",
" drops the parts that read the post it answers (parent:0), that one's parent (parent:1) or the quoted post;",
" --drop-parts the parts by number (as posts roles lists them); --drop-urls the parts that are nothing but a link.",
" Its parts are re-timed (roles stored), its word timings moved with them, its slurs state kept.",
" --pause: SILENCE PUT IN after each word named ([#]=, 0.05-3; #n its n-th time in the read; a",
" phrase pauses after its last word), found in the take's word timings (posts narrate --words makes them): the take",
" cut just after the word, everything after moved on (words, parts, so zooms, captions, slams, beeps keep their",
" words). On a paused take it re-cuts from the take before (=0 takes a pause away). --target counts one piece's words.",
" Each cut moves to the quietest 10 ms its word allows, and each side of the silence is faded (10 ms).",
" --revoice: ONE PHRASE RE-VOICED (TTS for --say only, the editor's; the rest of the read untouched): the phrase found",
" in the take's word timings, the original cut at the quietest 10 ms within 40 ms of each boundary, --say synthesized",
" in the voice the piece was read in (--voice overrides; the project's lexicon applied; kept in narration/parts-cache/),",
" loudness-matched to the 2 s about it (±6 dB) and spliced in with equal-power crossfades (--xfade, 0-0.2 s). Words,",
" parts and all timed on them move by the length change; the new words' timings are estimated. --dry-run: no TTS;",
" it names each cut's level -- a cut still in speech is warned of (the timings off there): --splice 65.03-66.00 sets them.",
].join("\n");
export class RereadError extends Error {
constructor(message) {
super(message);
this.name = "RereadError";
}
}
const PIECE_RE = /^(parent:\d|quoted)$/;
/**
* THE JOIN of a take's parts, pure: `keep` -- `[{ k, factor }]` in order, `k`
* the part's index in `t.parts`, `factor` the time-stretch it is read at
* (1: untouched) -- cut from `t`'s file and joined with the read's pauses
* (POST_PART_GAP: between paragraphs, inside one). Returns `{ spans, parts,
* words, script, seconds }`: `spans` in the source take's seconds (`at` the
* part's start in the new one, `len` its length there), the parts re-timed
* (roles stored, a stretched part's `tempo` its reading speed against its
* first read), the words moved -- a stretched part's scaled by its factor --
* and a word in no kept part dropped.
*
* @param {Record} t the source take
* @param {Array<{ k: number, factor: number, tempo?: number }>} keep
* @param {Array<{ role?: string | null }>} roles partRoles of the entry
*/
export function joinParts(t, keep, roles = []) {
const parts = t.parts;
const spans = [];
let cur = 0;
keep.forEach(({ k, factor, tempo }, j) => {
const p = parts[k];
const gap = j === 0 ? 0 : p.para !== parts[keep[j - 1].k].para ? POST_PART_GAP.para : POST_PART_GAP.inside;
const at = r3(cur + gap);
const f = fin(factor) && factor > 0 ? factor : 1;
const len = r3(p.seconds / f);
spans.push({ k, from: r3(p.start), to: r3(p.start + p.seconds), at, gap, ...(Math.abs(f - 1) > 1e-6 ? { factor: Math.round(f * 1e6) / 1e6 } : {}), len, tempo: fin(tempo) ? tempo : fin(p.tempo) ? p.tempo : 1 });
cur = at + len;
});
const newParts = spans.map((s, j) => {
const p = parts[s.k];
const { gapBefore: _g, role: _r, tempo: _t, ...rest } = p;
const role = roles[s.k]?.role ?? p.role ?? null;
const tempo = Math.round(s.tempo * 1000) / 1000;
return { ...rest, n: j + 1, start: s.at, seconds: s.len, ...(role ? { role } : {}), ...(Math.abs(tempo - 1) > 1e-6 ? { tempo } : {}) };
});
// Its words moved with their parts (a word is its part's when it starts inside the part's span), scaled with a stretched one.
const words = Array.isArray(t.words)
? t.words.flatMap((w) => {
const s = spans.find((x) => w.start >= x.from - 0.05 && w.start < x.to + 0.05);
if (!s) return [];
const f = s.factor ?? 1;
const at = (v) => r3(Math.min(s.at + s.len + 0.05, Math.max(0, s.at + (v - s.from) / f)));
return [{ w: w.w, start: at(w.start), end: Math.max(at(w.start), at(w.end)) }];
})
: null;
const script = spans.reduce((acc, s, j) => {
const p = parts[s.k];
const sep = j === 0 ? "" : p.para !== parts[spans[j - 1].k].para ? "\n\n" : " ";
return acc + sep + String(p.text ?? "").trim();
}, "");
return { spans, parts: newParts, words, script, seconds: r3(cur) };
}
/** The picked take's parts, all timed -- or a RereadError (a take read in one go has none). */
function timedParts(entry, t, what = "re-join") {
if (!t) throw new RereadError(`${entry?.id ?? "?"} has no take to ${what}`);
const parts = Array.isArray(t.parts) ? t.parts : [];
if (!parts.length || !parts.every((p) => fin(p?.start) && fin(p?.seconds) && p.seconds > 0)) {
throw new RereadError(`${entry.id}'s picked take was read in one go (no timed parts): re-make it on a script without the piece (umtool posts narrate
${entry.id} --take)`);
}
return parts;
}
/**
* THE RE-JOIN's PLAN, pure: which parts of `entry`'s picked take are kept and
* where each lands in the new take -- `{ take, keep: [k…], drop: [{ k, why }],
* spans: [{ k, from, to, at }], parts, words, script, seconds, steps }`.
* `spans` are in the source take's seconds (`at` the kept part's start in
* the new one). Throws RereadError when there is nothing to drop, no part
* left, or the take has no parts timed.
*
* @param {Record} entry
* @param {{ without?: string[], dropParts?: number[], dropUrls?: boolean }} o
*/
export function rereadPlan(entry, { without = [], dropParts = [], dropUrls = false } = {}) {
const t = pickedTake(entry);
const parts = timedParts(entry, t);
for (const w of without) if (!PIECE_RE.test(w)) throw new RereadError(`--without ${w}: a piece is parent:0, parent:1 or quoted`);
for (const n of dropParts) if (!(Number.isInteger(n) && n >= 1 && n <= parts.length)) throw new RereadError(`--drop-parts ${n}: ${entry.id}'s take has parts 1-${parts.length}`);
const roles = partRoles(entry);
const drop = [];
parts.forEach((p, k) => {
const role = roles[k]?.role ?? null;
if (role && without.includes(role)) drop.push({ k, why: role });
else if (dropParts.includes(k + 1)) drop.push({ k, why: `part ${k + 1}` });
else if (dropUrls && isOnlyUrls(p.text)) drop.push({ k, why: "url" });
});
if (!drop.length) throw new RereadError(`${entry.id}'s picked take reads none of that${without.length ? ` (${without.join(", ")})` : ""}: nothing to drop`);
const dropped = new Set(drop.map((d) => d.k));
const keep = parts.map((_, k) => k).filter((k) => !dropped.has(k));
if (!keep.length) throw new RereadError(`${entry.id}: that drops every part of its take -- nothing would be read`);
const j = joinParts(t, keep.map((k) => ({ k, factor: 1 })), roles);
return { take: t, keep, drop, ...j, spans: j.spans.map(({ k, from, to, at, gap }) => ({ k, from, to, at, gap })), steps: [{ op: "rejoin", drop: drop.map((d) => d.why).filter((v, i, a) => a.indexOf(v) === i), ranAt: new Date().toISOString() }] };
}
// ---------------------------------------------------------------------------
// PER-PART TEMPO (operator, 4 Nov, a 6.5-minute post: "what if we sped it up ... and then slowing back down here on the
// juicy persecution complex paragraph"; "dynamic speed over boring parts of a long message ... nothing too crazy").
// ---------------------------------------------------------------------------
/** The stretchers a tempo step may use: ffmpeg's atempo (the default, as the read's `rate` is played) or rubberband. */
export const TEMPO_STRETCHERS = Object.freeze(["atempo", "rubberband"]);
/**
* A TEMPO SPEC as the CLI writes it, pure: `"4-16=1.35,21-25=1.3"` (each run of
* parts and its tempo), or `{ tempo: 1.3, parts: "4-16,21-25" }` (one tempo for
* the runs named) -- `{ : tempo }` (1-based). Refused: a part outside
* 1-`count`, a tempo outside POST_NARRATION_LIMITS.tempo, a part named twice.
*
* @param {{ spec?: string | null, tempo?: number | string | null, parts?: string | null, count: number }} o
* @returns {Record}
*/
export function parseTempoSpec({ spec = null, tempo = null, parts = null, count }) {
const [lo, hi] = POST_NARRATION_LIMITS.tempo;
/** @type {Record} */
const out = {};
const runs = (list, where) =>
String(list).split(",").map((x) => x.trim()).filter(Boolean).flatMap((r) => {
const m = /^(\d+)(?:-(\d+))?$/.exec(r);
if (!m) throw new RereadError(`${where} ${r}: a part (4) or a run of them (4-16)`);
const a = Number(m[1]);
const b = m[2] === undefined ? a : Number(m[2]);
if (!(a >= 1 && b >= a && b <= count)) throw new RereadError(`${where} ${r}: the take has parts 1-${count}`);
return Array.from({ length: b - a + 1 }, (_, i) => a + i);
});
const put = (n, v, where) => {
if (!(fin(v) && v >= lo && v <= hi)) throw new RereadError(`${where}: a tempo is ${lo}–${hi} (1.3 reads 30% faster, its pitch kept)`);
if (out[n] !== undefined && out[n] !== v) throw new RereadError(`${where}: part ${n} is named twice`);
out[n] = v;
};
if (tempo !== null && tempo !== undefined) {
if (parts === null || parts === undefined) throw new RereadError("--tempo needs --parts (the runs it reads faster: 4-16,21-25)");
for (const n of runs(parts, "--parts")) put(n, Number(tempo), `--tempo ${tempo}`);
}
if (spec !== null && spec !== undefined) {
for (const item of String(spec).split(/[,;](?=\s*\d+(?:-\d+)?\s*=)/)) {
const m = /^\s*([\d,\s-]+?)\s*=\s*([\d.]+)\s*$/.exec(item);
if (!m) throw new RereadError(`--tempo-for ${item.trim()}: =, e.g. 4-16=1.35,21-25=1.3`);
for (const n of runs(m[1], "--tempo-for")) {
delete out[n];
put(n, Number(m[2]), `--tempo-for ${item.trim()}`);
}
}
}
if (!Object.keys(out).length) throw new RereadError("name the parts and their tempo: --tempo-for \"4-16=1.35,21-25=1.3\" (or --tempo 1.3 --parts 4-16,21-25)");
return out;
}
/** Parts' tempos as runs, pure: `[1, 1.35, 1.35, 1]` → `{ "2-3": 1.35 }` (a part at 1 left out). */
export function tempoRanges(tempos) {
const out = {};
let i = 0;
while (i < tempos.length) {
const v = tempos[i] ?? 1;
let j = i;
while (j + 1 < tempos.length && (tempos[j + 1] ?? 1) === v) j += 1;
if (Math.abs(v - 1) > 1e-6) out[i === j ? String(i + 1) : `${i + 1}-${j + 1}`] = v;
i = j + 1;
}
return out;
}
/** A take's last step, when it is one of `ops`; and the take it was made from, when that is in `takes`. */
export function lastLocalStep(takes, t, ops) {
const st = Array.isArray(t?.steps) ? t.steps[t.steps.length - 1] : null;
if (!st || !ops.includes(st.op)) return null;
const src = takeSourceOf(t);
const from = src.kind === "take" ? takes.find((x) => takeIdOf(x) === src.from) ?? null : null;
return { step: st, from };
}
/**
* THE TEMPO's PLAN, pure: `tempo` `{ : target }` (parseTempoSpec's) --
* each part named READ AT that tempo against its first read, the rest as they
* are. A tempo is absolute: on a take made by a tempo step (a re-tune) the plan
* starts from the take that one was made from (each part stretched once, never
* twice), the parts it does not name keeping the tempo they had. Every part is
* kept, joined with the read's pauses; the words scaled with their part.
* Returns rereadPlan's shape plus `base` (the take it cuts), `tempos` (each
* part's, after) and `was` (before).
*
* @param {Record} entry
* @param {{ tempo: Record, stretch?: string }} o
*/
export function tempoPlan(entry, { tempo, stretch = "atempo" }) {
const t = pickedTake(entry);
const parts = timedParts(entry, t, "re-time");
if (!TEMPO_STRETCHERS.includes(stretch)) throw new RereadError(`--stretch ${stretch}: ${TEMPO_STRETCHERS.join(" or ")}`);
const takes = entry.narration.takes;
const was = parts.map((p) => (fin(p.tempo) ? p.tempo : 1));
// A re-tune: the take before the tempo step, when it is there and has the same parts.
const up = lastLocalStep(takes, t, ["tempo"]);
const base = up?.from && Array.isArray(up.from.parts) && up.from.parts.length === parts.length && up.from.parts.every((p) => fin(p?.start) && fin(p?.seconds) && p.seconds > 0) ? { ...up.from, index: takes.indexOf(up.from) } : t;
for (const n of Object.keys(tempo)) if (!(Number(n) >= 1 && Number(n) <= parts.length)) throw new RereadError(`part ${n}: ${entry.id}'s take has parts 1-${parts.length}`);
const tempos = parts.map((_, k) => (tempo[k + 1] !== undefined ? tempo[k + 1] : was[k]));
if (tempos.every((v, k) => Math.abs(v - was[k]) < 1e-6)) throw new RereadError(`${entry.id}'s picked take reads those parts at that tempo already: nothing to change`);
const baseTempo = base.parts.map((p) => (fin(p.tempo) ? p.tempo : 1));
const roles = partRoles(entry);
const j = joinParts(base, base.parts.map((_, k) => ({ k, factor: tempos[k] / baseTempo[k], tempo: tempos[k] })), roles);
return {
take: base, picked: t, base, keep: parts.map((_, k) => k), drop: [], was, tempos, ...j, stretch,
steps: [{ op: "tempo", tempo: tempoRanges(tempos), params: { stretch }, ranAt: new Date().toISOString() }],
};
}
/** The ffmpeg arguments that cut the plan's spans out of `src` (each stretched by its factor, its length exact) and join them with silence into `out`. */
export function rejoinArgs(src, out, plan, { rate = 48000, layout = "mono", stretch = plan.stretch ?? "atempo" } = {}) {
const chains = [];
const labels = [];
plan.spans.forEach((s, j) => {
if (s.gap > 0) {
chains.push(`anullsrc=r=${rate}:cl=${layout},atrim=duration=${s.gap}[g${j}]`);
labels.push(`[g${j}]`);
}
// A stretched part: its pitch kept, then padded and trimmed to its length in the plan (sample-exact: the parts after
// it land where their word timings say).
const f = s.factor ?? 1;
const stretched = Math.abs(f - 1) > 1e-6
? `,${stretch === "rubberband" ? `rubberband=tempo=${f}:transients=mixed:pitchq=quality` : `atempo=${f}`},apad,atrim=end_sample=${Math.round(s.len * rate)},asetpts=PTS-STARTPTS`
: "";
chains.push(`[0:a]atrim=start=${s.from}:end=${s.to},asetpts=PTS-STARTPTS,aformat=sample_rates=${rate}:channel_layouts=${layout}${stretched}[a${j}]`);
labels.push(`[a${j}]`);
});
chains.push(`${labels.join("")}concat=n=${labels.length}:v=0:a=1[out]`);
return ["-nostdin", "-hide_banner", "-loglevel", "error", "-y", "-i", src, "-filter_complex", chains.join(";"), "-map", "[out]", "-c:a", "pcm_s16le", out];
}
/** A file's sample rate and channel layout (ffprobe). */
export async function audioFormat(file) {
const { stdout } = await execFileP(FFPROBE(), ["-v", "error", "-select_streams", "a:0", "-show_entries", "stream=sample_rate,channels", "-of", "default=noprint_wrappers=1", file]);
const rate = Number(/sample_rate=(\d+)/.exec(String(stdout))?.[1]) || 48000;
const ch = Number(/channels=(\d+)/.exec(String(stdout))?.[1]) || 1;
return { rate, layout: ch >= 2 ? "stereo" : "mono" };
}
/**
* WRITE A DERIVED TAKE of post item `e` from `plan` (rereadPlan's, tempoPlan's, postYell.mjs yellPlan's): `plan.take`'s
* file through `argsOf(src, out, fmt)` (ffmpeg) into take-.-.wav, measured, added with the plan's
* parts, words, script and steps -- and picked, in ONE write (updatePostNarration: one undo point). Returns `{ take,
* result }`. The source take is never touched.
*
* @param {{ id: string, dir: string }} project
* @param {Record} e
* @param {Record} plan
* `make(src, out, fmt)` in place of `argsOf`: the file written by the caller (postRevoice.mjs: a splice made in
* memory). `voice`: the take's voice label (default the source's).
*
* @param {{ op: string, argsOf?: (src: string, out: string, fmt: { rate: number, layout: string }) => string[], make?: (src: string, out: string, fmt: { rate: number, layout: string }) => Promise, voice?: string, measure?: (file: string) => Promise<{ seconds: number|null, lufs: number|null }>, verb?: string, after?: (abs: string, m: { seconds: number|null, lufs: number|null }) => Promise<{ seconds: number|null, lufs: number|null }> }} o
*/
export async function writeDerivedTake(project, e, plan, { op, argsOf = undefined, make = undefined, voice = undefined, measure = undefined, verb = "re-join", after = undefined }) {
const t = plan.take;
const pid = postIdOf(e);
const dir = path.join(project.dir, ...takesDirOf(pid).split("/"));
await mkdir(dir, { recursive: true });
const rel = derivedFileOf(pid, nextTakeNumber(e, await readdir(dir).catch(() => [])), op, t.engine === "derived" ? "take" : t.engine ?? "take");
const abs = (r) => path.join(project.dir, ...String(r).split("/"));
const src = abs(t.file);
if (!(await stat(src).catch(() => null))?.isFile()) throw new RereadError(`${e.id}'s take is not on disk: ${t.file}`);
const fmt = await audioFormat(src);
try {
if (make) await make(src, abs(rel), fmt);
else if (argsOf) await execFileP(FFMPEG(), argsOf(src, abs(rel), fmt), { maxBuffer: 1 << 24 });
else throw new Error("no way to write it (argsOf or make)");
} catch (err) {
await rm(abs(rel), { force: true });
throw new RereadError(`${make ? "could not" : "ffmpeg could not"} ${verb} ${t.file}: ${String(err?.stderr ?? err?.message ?? err).trim().split("\n").pop()}`);
}
const measureOf = measure ?? (await import("./postNarrationCli.mjs")).measureTake;
let m = await measureOf(abs(rel));
if (after) m = await after(abs(rel), m);
const take = {
file: rel,
engine: "derived",
voice: voice ?? t.voice ?? "?",
seconds: fin(m.seconds) && m.seconds > 0 ? m.seconds : plan.seconds,
source: { kind: "take", from: takeIdOf(t) },
steps: plan.steps,
script: plan.script,
at: new Date().toISOString(),
...(fin(m.lufs) ? { lufs: m.lufs } : fin(t.lufs) ? { lufs: t.lufs } : {}),
...(t.slurs ? { slurs: t.slurs } : {}),
...(plan.words ? { words: plan.words } : {}),
parts: plan.parts,
};
const { result } = await withEditNotes(project, async () => updatePostNarration(project.dir, e.id, { addTake: take }, { token: await manifestToken(project.dir) }));
return { take, result };
}
/**
* RE-JOIN post item `e`'s picked take without a piece (`opts` as rereadPlan
* takes them), or with its parts RE-TIMED (`tempo`, tempoPlan's): the file
* written, measured, the take added and picked in one write. `dryRun`: the
* plan only. Returns `{ plan, take?, result? }`.
*
* @param {{ id: string, dir: string }} project
* @param {Record} e
* @param {{ without?: string[], dropParts?: number[], dropUrls?: boolean, tempo?: Record | null, stretch?: string, dryRun?: boolean, measure?: (file: string) => Promise<{ seconds: number|null, lufs: number|null }> }} [o]
*/
export async function rereadTake(project, e, { without = [], dropParts = [], dropUrls = false, tempo = null, stretch = "atempo", dryRun = false, measure = undefined } = {}) {
if (tempo && (without.length || dropParts.length || dropUrls)) throw new RereadError("a tempo goes alone: re-join without the piece first, then re-time that take (it is picked)");
const plan = tempo ? tempoPlan(e, { tempo, stretch }) : rereadPlan(e, { without, dropParts, dropUrls });
if (dryRun) return { plan };
const { take, result } = await writeDerivedTake(project, e, plan, { op: tempo ? "tempo" : "rejoin", argsOf: (src, out, fmt) => rejoinArgs(src, out, plan, fmt), measure, verb: tempo ? "re-time" : "re-join" });
return { plan, take, result };
}
/** The pieces a set-item thread patch draws as context or hidden that `e`'s picked take reads (set-item's re-join). */
export function piecesHidden(e, thread) {
if (!thread || typeof thread !== "object") return [];
const read = new Set(partRoles(e).map((r) => r.role).filter(Boolean));
const out = [];
const off = (m) => m === "context" || m === "hidden";
if (Array.isArray(thread.parent)) thread.parent.forEach((m, i) => off(m) && read.has(`parent:${i}`) && out.push(`parent:${i}`));
else if (off(thread.parent)) for (const r of read) if (r.startsWith("parent:")) out.push(r);
if (off(thread.quoted) && read.has("quoted")) out.push("quoted");
return out;
}
/** `umtool posts reread - …`: a re-join without a piece, a tempo (`tempoSpec`, tempoPlan's), or a yell (`yell`: postYell.mjs). */
export async function rereadCommand(project, ref, { without = [], dropParts = [], dropUrls = false, tempoSpec = null, tempo = null, parts = null, stretch = "atempo", yell = null, pause = null, target = null, revoice = null, say = null, voice = null, xfade = null, cut = null, dryRun = false, json = false, out = (s) => console.log(s) } = {}) {
const manifest = await readManifest(project.dir);
if (!manifest) throw new RereadError(`${project.id} has no manifest`);
const e = (manifest.timeline ?? []).find((x) => x?.type === "post" && (x.id === ref || postIdOf(x) === ref || x.id === `p-${ref}`));
if (!e) throw new RereadError(`no post item ${ref} in ${project.id}`);
if (yell) {
if (tempoSpec !== null || tempo !== null || without.length || dropParts.length || dropUrls) throw new RereadError("--yell-caps goes alone: re-join or re-time first, then yell that take (it is picked) -- or the other way round");
const { yellCommand } = await import("./postYell.mjs");
return yellCommand(project, manifest, [e], { ...yell, dryRun, json, out });
}
if (revoice !== null || say !== null) {
if (revoice === null) throw new RereadError("--say goes with --revoice \"\" (the words it says instead)");
if (pause !== null || tempoSpec !== null || tempo !== null || without.length || dropParts.length || dropUrls) throw new RereadError("--revoice goes alone: re-voice the phrase, then pause, re-join or re-time that take (it is picked) -- or the other way round");
const { revoiceCommand } = await import("./postRevoice.mjs");
return revoiceCommand(project, e, { revoice, say, voice, xfade, cut, target, dryRun, json, out });
}
if (voice !== null || xfade !== null || cut !== null) throw new RereadError("--voice, --xfade and --splice go with --revoice");
if (pause !== null) {
if (tempoSpec !== null || tempo !== null || without.length || dropParts.length || dropUrls) throw new RereadError("--pause goes alone: re-join or re-time first, then pause that take (it is picked) -- or the other way round");
return pauseCommand(project, e, { pause, target, dryRun, json, out });
}
if (target !== null) throw new RereadError("--target names the piece --pause or --revoice counts its words in");
const timed = tempoSpec !== null || tempo !== null;
const t0 = pickedTake(e);
const spec = timed ? parseTempoSpec({ spec: tempoSpec, tempo, parts, count: Array.isArray(t0?.parts) ? t0.parts.length : 0 }) : null;
const r = await rereadTake(project, e, { without, dropParts, dropUrls, tempo: spec, stretch, dryRun });
const secs = (r.take?.seconds ?? r.plan.seconds).toFixed(2);
const was = Number((r.plan.picked ?? r.plan.take).seconds).toFixed(2);
if (json) {
out(JSON.stringify({ ok: true, id: e.id, dryRun, ...(timed ? { tempo: r.plan.steps[0].tempo, stretch: r.plan.stretch, from: takeIdOf(r.plan.take) } : { drop: r.plan.drop.map((d) => ({ part: d.k + 1, why: d.why })), keep: r.plan.keep.map((k) => k + 1) }), seconds: r.take?.seconds ?? r.plan.seconds, was: Number(was), take: r.take ?? null, token: r.result?.token ?? null }, null, 2));
return 0;
}
if (timed) {
const runs = Object.entries(r.plan.steps[0].tempo).map(([k, v]) => `${k} at ${v}x`).join(", ") || "every part at 1x";
out(`${dryRun ? "would re-time" : "re-timed"} ${e.id}'s take (${r.plan.stretch}, pitch kept): parts ${runs} -- ${secs} s (was ${was} s)${r.plan.take !== r.plan.picked ? `, cut from ${takeIdOf(r.plan.take)} (each part stretched once)` : ""}`);
} else {
const said = r.plan.drop.map((d) => `part ${d.k + 1} (${d.why})`).join(", ");
out(`${dryRun ? "would re-join" : "re-joined"} ${e.id}'s take without ${said}: ${r.plan.keep.length} part(s), ${secs} s (was ${was} s)`);
}
if (r.take) out(` ${r.take.file} -- picked (one undo point: umtool timeline ${project.id} undo)`);
return 0;
}
/** `umtool posts reread
- --pause …` (postPause.mjs): the dry run's plan, or the take made. */
async function pauseCommand(project, e, { pause, target, dryRun, json, out }) {
const { parsePauseSpec, pauseLine, pauseTake } = await import("./postPause.mjs");
const r = await pauseTake(project, e, { pauses: parsePauseSpec(pause), target, dryRun });
const p = r.plan;
const was = Number(p.picked.seconds);
const secs = r.take?.seconds ?? p.seconds;
if (json) {
out(JSON.stringify({ ok: true, id: e.id, dryRun, from: takeIdOf(p.take), recut: p.recut, target: p.target, pauses: p.pauses, added: p.added, seconds: secs, was, fixedAt: p.fixedAt, take: r.take ?? null, token: r.result?.token ?? null }, null, 2));
return 0;
}
out(`${dryRun ? "would pause" : "paused"} ${e.id}'s take${p.recut ? `, cut again from ${takeIdOf(p.take)} (each pause put in once)` : ` (${takeIdOf(p.take)})`}: ${secs.toFixed(2)} s (was ${was.toFixed(2)} s, +${p.added} s of pauses)`);
for (const x of p.pauses) out(` after ${pauseLine(x)}`);
if (p.fixedAt) out(` note: ${p.fixedAt} effect(s) of this item have a set second (at) -- they do not move with the words; check them`);
if (r.take) out(` ${r.take.file} -- picked (one undo point: umtool timeline ${project.id} undo)`);
return 0;
}