#!/usr/bin/env node // Let an um come back, so that more notes can play an um AS IT WAS SAID. // // node reuse-pass.mjs // // A finished plan gives every note its own clip, and pays for that in processing: // the clip nearest a note's pitch is rarely ON it, so nearly every um is shifted // (and most are stretched). This pass trades the "every um is unique" rule for // untouched ums, in two steps, without re-arranging: // // 1. a note whose own clip already sits on its pitch and fills its slot is marked // `raw` -- the renderer then plays it with no shift and no stretch; // 2. every other note looks for a clip of its own voice that does, and takes it // if that um has not sounded within REUSE_GAP seconds either side. The least // used um wins, so the repeats are spread over as many ums as will do. // // A note with no such um keeps its clip and its processing, exactly as it was. // // REUSE_GAP= seconds between two soundings of one um (default 10) // RAW_TOL= how far off its note an untouched um may be (default 0.15 -- // 15 cents; the clips themselves drift more than that inside one um) // MIN_FILL= an untouched um must fill this much of what the note may sound // (default 0.85; it cannot be stretched to fit) // MAX_USES= cap on soundings of one um (default: none; the gap already caps it) // REUSE=0 step 1 only: no um repeats // DRY=1 report, write no plan (measurements are still cached) // PRE= measure a clip against a note only when its whole-window pitch is // within this of the note (default 1.0; wider finds a few more fits and // measures for longer) // // The pool is the clips the plan already plays, voice by voice: each has been heard // in this song and has its word guards, and a voice keeps its own sources (one timbre, // one face). "The same um" is any two windows of one recording that overlap -- a // trimmed window is the same sound (swap-clip.mjs learned that the hard way). // // Pitch and length are asked of rawfit.mjs, which is what the renderer asks, over the // window clipwindow.mjs gives -- so "untouched" here is what plays there. Measurements // are cached beside the output (.measure.json, or MEASURE_CACHE= to share // one between runs); delete it after re-trimming. import { existsSync, readFileSync, writeFileSync } from "node:fs"; import path from "node:path"; import { SONG_DATA } from "./paths.mjs"; import { readWavMono } from "./flatness.mjs"; import { clipWindow } from "./clipwindow.mjs"; import { noteMaxLen, headPitch } from "./rawfit.mjs"; import { midiOf } from "./pitch.mjs"; const [IN, OUT] = process.argv.slice(2); if (!IN || !OUT) { console.error("usage: node reuse-pass.mjs "); process.exit(2); } // the pass refuses a plan it has been over, so writing over the plan it reads would leave nothing to run it on again if (path.resolve(IN) === path.resolve(OUT)) { console.error("the output would overwrite the plan it is made from: give another path"); process.exit(2); } // an empty value is not a setting (Number("") is 0, which would quietly turn the pass off), and none of these may be negative const num = (name, dflt) => { const raw = process.env[name]; if (raw !== undefined && raw.trim() === "") throw new Error(`${name} is set but empty`); const v = Number(raw ?? dflt); if (Number.isNaN(v) || v < 0) throw new Error(`${name} is not a number >= 0`); return v; }; const GAP = num("REUSE_GAP", 10), TOL = num("RAW_TOL", 0.15), MIN_FILL = num("MIN_FILL", 0.85); const MAX_USES = num("MAX_USES", Infinity); const REUSE = process.env.REUSE !== "0", DRY = process.env.DRY === "1"; const SR = 48000; // how far a clip's whole-window pitch may sit from a note before it is not worth // measuring against that note's own length const PRE = num("PRE", 1.0); // past this an um counts as simply "not recently heard" -- never below the gap itself, or a gap // over 30 s would refuse every um, used or not const FAR = Math.max(30, GAP); const plan = JSON.parse(readFileSync(IN, "utf8")); // A plan this pass has already been over cannot be passed again: the clips its notes // gave up are gone from it, so a second pass with other settings would keep the repeats // and could not give the ums back. Start from the plan that had every note's own clip. if (plan.voices.some((v) => v.plan.some((p) => "raw" in p))) { console.error(`${IN} has already been through reuse-pass (it has raw notes). Run the pass on the plan it was made from.`); process.exit(2); } const CACHE_FILE = process.env.MEASURE_CACHE ?? `${OUT}.measure.json`; let cache = {}; try { cache = JSON.parse(readFileSync(CACHE_FILE, "utf8")); } catch {} const asrCache = new Map(); const wordsFor = (v) => { if (!asrCache.has(v)) { let w = []; try { w = JSON.parse(readFileSync(path.join(SONG_DATA, "asr", `${v}.json`), "utf8")).words ?? []; } catch {} w.sort((a, b) => a.start - b.start); asrCache.set(v, w); } return asrCache.get(v); }; // ---- the pool: each voice's own clips, and which of them are one um -------- const clipKey = (p) => `${p.video}@${p.srcStart}-${p.srcEnd}${p.noTrim ? "!" : ""}`; const CLIP_FIELDS = ["video", "date", "srcStart", "srcEnd", "srcDur", "srcF0", "srcMidi", "spreadCents", "noTrim"]; const voices = plan.voices.map((v) => { const fill = v.fill !== false; const clips = new Map(); for (const p of v.plan) { if (!p.video) continue; const k = clipKey(p); if (!clips.has(k)) clips.set(k, { key: k, keep: !!p.keepSide, ...Object.fromEntries(CLIP_FIELDS.map((f) => [f, p[f]])) }); } return { v, fill, clips: [...clips.values()] }; }); // one um = overlapping windows of one recording, across the WHOLE plan { const all = voices.flatMap((x) => x.clips); const byVideo = new Map(); for (const c of all) { if (!byVideo.has(c.video)) byVideo.set(c.video, []); byVideo.get(c.video).push(c); } let id = 0; for (const list of byVideo.values()) { list.sort((a, b) => a.srcStart - b.srcStart); let end = -Infinity; for (const c of list) { if (c.srcStart >= end) { id += 1; end = c.srcEnd; } else end = Math.max(end, c.srcEnd); c.um = id; } } } // ---- measure ---------------------------------------------------------------- // cache[clipKey] = { len, full, at: { : midi|0 } } const wavCache = new Map(); const loadSrc = (vid) => { if (!wavCache.has(vid)) { wavCache.clear(); wavCache.set(vid, readWavMono(path.join(SONG_DATA, "wav48", `${vid}.wav`), readFileSync)); } return wavCache.get(vid); }; const segOf = (c) => { const { x, sr } = loadSrc(c.video); if (sr !== SR) throw new Error(`${c.video}.wav is ${sr} Hz, not ${SR}`); let lo, hi; if (c.noTrim) { lo = c.srcStart; hi = c.srcEnd; } else { const w = clipWindow(x, SR, { start: c.srcStart, end: c.srcEnd }, wordsFor(c.video)); lo = w.s; hi = w.e; } const a = Math.max(0, Math.round(lo * SR)), b = Math.min(x.length, Math.round(hi * SR)); return Float32Array.prototype.slice.call(x, a, b); }; const midiAt = (c, seg, maxLen) => { const m = cache[c.key]; const k = String(Math.min(m.len, maxLen)); if (!(k in m.at)) { const h = headPitch(seg(), maxLen, SR); m.at[k] = h.f0 > 0 ? +midiOf(h.f0).toFixed(4) : 0; } return m.at[k]; }; let missing = 0, measured = 0; for (const { v, fill, clips } of voices) { const notes = v.plan.filter((p) => p.video); const sorted = [...clips].sort((a, b) => a.video.localeCompare(b.video)); for (const c of sorted) { let segCache = null; const seg = () => (segCache ??= segOf(c)); try { if (!cache[c.key]) { if (!existsSync(path.join(SONG_DATA, "wav48", `${c.video}.wav`))) { missing += 1; continue; } const s = seg(); const h = headPitch(s, s.length, SR); cache[c.key] = { len: s.length, full: h.f0 > 0 ? +midiOf(h.f0).toFixed(4) : 0, at: {} }; measured += 1; } const m = cache[c.key]; if (!m.full) continue; for (const p of notes) { const own = clipKey(p) === c.key; if (!own && Math.abs(p.targetMidi - m.full) > PRE) continue; midiAt(c, seg, noteMaxLen(fill, p, SR)); } } catch (e) { console.error(` could not measure ${c.key}: ${e.message}`); missing += 1; } } } if (!DRY || measured) writeFileSync(CACHE_FILE, JSON.stringify(cache)); console.log(`measured ${measured} clips (${Object.keys(cache).length} in ${path.basename(CACHE_FILE)})` + (missing ? `; ${missing} could not be measured and are left alone` : "")); // ---- what fits what --------------------------------------------------------- // The semitones a clip would be off a note if played untouched; null = not a fit. const offBy = (c, fill, p) => { const m = cache[c.key]; if (!m || !m.full) return null; const maxLen = noteMaxLen(fill, p, SR); if (m.len < MIN_FILL * maxLen) return null; const at = m.at[String(Math.min(m.len, maxLen))]; if (!at) return null; const d = p.targetMidi - at; return Math.abs(d) <= TOL ? d : null; }; // every sounding of every um, by song time const uses = new Map(); // um -> [slotStart] const addUse = (um, t) => { if (!uses.has(um)) uses.set(um, []); uses.get(um).push(t); }; const dropUse = (um, t) => { const a = uses.get(um), i = a.indexOf(t); if (i < 0) throw new Error(`um ${um} has no sounding at ${t}`); a.splice(i, 1); }; const clipOf = new Map(voices.flatMap((x) => x.clips.map((c) => [c.key, c]))); for (const { v } of voices) for (const p of v.plan) if (p.video) addUse(clipOf.get(clipKey(p)).um, p.slotStart); const before = voices.map(({ v }) => new Set(v.plan.filter((p) => p.video).map((p) => clipOf.get(clipKey(p)).um)).size); const report = []; for (const [vi, { v, fill, clips }] of voices.entries()) { const notes = v.plan.filter((p) => p.video); let own = 0, swapped = 0; // step 1: its own clip, untouched const rest = []; for (const p of notes) { const c = clipOf.get(clipKey(p)); // A clip kept for its stray word stays as it was: the renderer starts it early or // chops it from the front, and neither is what was measured here. const d = p.keepSide ? null : offBy(c, fill, p); if (d !== null) { p.raw = true; p.shift = +d.toFixed(3); own += 1; } else rest.push(p); } // step 2: another um of this voice, if it has been quiet long enough if (REUSE) { const pool = clips.filter((c) => !c.keep); const fits = new Map(rest.map((p) => [p, pool.map((c) => ({ c, d: offBy(c, fill, p) })).filter((x) => x.d !== null)])); // the notes with the fewest ums to choose from choose first const order = rest.filter((p) => fits.get(p).length).sort((a, b) => fits.get(a).length - fits.get(b).length || a.slotStart - b.slotStart); let changed = true; const done = new Set(); while (changed) { changed = false; for (const p of order) { if (done.has(p)) continue; const mine = clipOf.get(clipKey(p)).um; let best = null; for (const { c, d } of fits.get(p)) { // its own um does not count against itself: the note is leaving it const others = [...(uses.get(c.um) ?? [])]; if (c.um === mine) others.splice(others.indexOf(p.slotStart), 1); const n = others.length; if (n >= MAX_USES) continue; // how long this um has been quiet around this note; every candidate is already // on the pitch, so among equally-used ums the one furthest from its other // soundings wins, and then the one whose length is nearest the note's const far = Math.min(FAR, ...others.map((u) => Math.abs(u - p.slotStart))); if (far < GAP) continue; const fit = Math.abs(Math.log(cache[c.key].len / noteMaxLen(fill, p, SR))); if (!best || n < best.n || (n === best.n && (far > best.far || (far === best.far && fit < best.fit)))) best = { c, d, n, far, fit }; } if (!best) continue; dropUse(mine, p.slotStart); addUse(best.c.um, p.slotStart); for (const f of CLIP_FIELDS) p[f] = best.c[f]; p.keepSide = 0; p.headOffset = 0; p.shift = +best.d.toFixed(3); p.raw = true; done.add(p); swapped += 1; changed = true; } } } const after = new Set(notes.map((p) => clipOf.get(clipKey(p)).um)).size; report.push({ voice: v.name, notes: notes.length, own, swapped, before: before[vi], after }); } // ---- say what happened, and check the rule it promises ------------------------ for (const r of report) { console.log(`${r.voice.padEnd(7)} ${r.notes} notes: ${r.own + r.swapped} as said (${r.own} their own um, ${r.swapped} a repeated or freed um), ` + `${r.notes - r.own - r.swapped} still processed; distinct ums ${r.before} -> ${r.after}`); } const counts = [...uses.values()].map((a) => a.length).filter((n) => n > 0); const hist = {}; for (const n of counts) hist[n] = (hist[n] ?? 0) + 1; let minGap = Infinity; for (const a of uses.values()) { a.sort((x, y) => x - y); for (let i = 1; i < a.length; i += 1) minGap = Math.min(minGap, a[i] - a[i - 1]); } console.log(`ums by times sounded: ${Object.entries(hist).map(([n, k]) => `${n}x ${k}`).join(", ")}`); console.log(`closest repeat of one um: ${Number.isFinite(minGap) ? `${minGap.toFixed(2)} s` : "none repeats"} (REUSE_GAP ${GAP} s, RAW_TOL ${TOL} st, MIN_FILL ${MIN_FILL})`); if (Number.isFinite(minGap) && minGap < GAP) { // only a plan that ALREADY repeated an um closer than this can get here: the pass // never places one, and it does not undo what it was handed console.log(` note: the plan it was given already had an um repeating within ${GAP} s`); } if (DRY) { console.log("DRY=1: nothing written"); process.exit(0); } writeFileSync(OUT, JSON.stringify(plan, null, 1)); console.log(`-> ${OUT}`);