Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit a6940462fd7493349c156638f4f79ebfb9fa5a6d
parent 70341dc6d56e0f4f597c4437280af24cd5704cbc
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 14 Nov 2026 15:42:03 -0500

Merge lane/mk-reuse: an um may come back, so more notes play an um as it was said -- reuse-pass.mjs marks a note raw when a clip of its own voice already sits on its pitch and fills its slot, repeating an um only after REUSE_GAP seconds, least-used first and then the one longest quiet, with MAX_USES as an optional cap; render-poly plays a raw note with no shift and no stretch, says how far off each measured and processes one that measures too far; a plan the pass has been over is refused, as is an output over its own input; plans without the flag render as before

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Aumtool/song/rawfit.mjs | 27+++++++++++++++++++++++++++
Mumtool/song/render-poly.mjs | 37+++++++++++++++++++++++++++++++------
Aumtool/song/reuse-pass.mjs | 267+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/song/swap-clip.mjs | 4+++-
4 files changed, 328 insertions(+), 7 deletions(-)

diff --git a/umtool/song/rawfit.mjs b/umtool/song/rawfit.mjs @@ -0,0 +1,27 @@ +// What the renderer does with a note's clip BEFORE it decides how to change it: +// how long the clip may sound in its slot, and the pitch it measures off the +// part that will sound. reuse-pass.mjs has to ask the same two questions to say +// "this um can play as it was said", and an answer of its own would drift from +// the renderer's -- the way the review page's clip window once did (clipwindow.mjs). +import { regionPitch, midiOf } from "./pitch.mjs"; + +// Samples a note's clip may fill. A filling voice (the melody) takes its slot; an +// accompaniment voice plays its natural length and stops. +export function noteMaxLen(fill, p, sr) { + return Math.round((fill ? p.slotDur * 0.97 : Math.min(p.slotDur * 0.97, p.noteDur * 1.15)) * sr); +} + +// The pitch of the part of `raw` that sounds when it may fill `maxLen` samples. +export function headPitch(raw, maxLen, sr) { + const keep = Math.min(raw.length, maxLen); + return regionPitch(raw, Math.round(0.01 * sr), Math.max(Math.round(0.02 * sr), keep - 1), sr, 55, 260); +} + +// Semitones from the sounding part of `raw` up to `targetMidi`; null when no pitch +// could be measured, or the measurement is too far off to be the same note. +export function headShift(raw, maxLen, sr, targetMidi) { + const head = headPitch(raw, maxLen, sr); + if (!(head.f0 > 0)) return null; + const s = targetMidi - midiOf(head.f0); + return Math.abs(s) <= 14 ? s : null; +} diff --git a/umtool/song/render-poly.mjs b/umtool/song/render-poly.mjs @@ -7,6 +7,7 @@ import { execFile, execFileSync } from "node:child_process"; import path from "node:path"; import { regionPitch, midiOf, yinFrame } from "./pitch.mjs"; import { clipWindow } from "./clipwindow.mjs"; +import { noteMaxLen, headPitch } from "./rawfit.mjs"; // parakeet word timings, used to keep a neighbouring word out of a note const asrCache = new Map(); @@ -196,6 +197,9 @@ const master = new Float32Array(Math.ceil((Math.max(TOTAL, overlayEnd) + 1.0) * // the actual audio once the mix exists (see below). let END = TOTAL; +let rawNotes = 0, rawRefused = 0; +const RAW_GUARD = Number(process.env.RAW_GUARD ?? 0.5); +const rawOff = []; for (const v of (SKIP_AUDIO ? [] : voices)) { let n = 0; for (const p of v.plan) { @@ -225,8 +229,7 @@ for (const v of (SKIP_AUDIO ? [] : voices)) { // sounding. Stretching every note to fill left nothing to blank (only 2.2% // of PiP frames were black). const fill = v.fill !== false; - const maxLen = Math.round((fill ? p.slotDur * 0.97 - : Math.min(p.slotDur * 0.97, p.noteDur * 1.15)) * SR); + const maxLen = noteMaxLen(fill, p, SR); // A clip a little longer than its note can be TIME-COMPRESSED instead of // chopped, which keeps the whole um -- tail included -- and just plays it // slightly faster. Only mildly: past ~15% it starts to sound hurried, and @@ -237,8 +240,7 @@ for (const v of (SKIP_AUDIO ? [] : voices)) { // thing it was kept for -- so it may be squeezed harder before being cut. const floor = p.keepSide ? KEEP_COMPRESS_MIN : COMPRESS_MIN; if (ratio < 1 && ratio >= floor) stretch = ratio; - const keep = Math.min(raw.length, maxLen); - const head = regionPitch(raw, Math.round(0.01 * SR), Math.max(Math.round(0.02 * SR), keep - 1), SR, 55, 260); + const head = headPitch(raw, maxLen, SR); let shift = p.shift; if (head.f0 > 0) { const s2 = p.targetMidi - midiOf(head.f0); if (Math.abs(s2) <= 14) shift = s2; } const inF = path.join(tmp, `i.wav`), outF = path.join(tmp, `o.wav`); @@ -250,6 +252,21 @@ for (const v of (SKIP_AUDIO ? [] : voices)) { return readWav(outF).x; }; let seg = raw; + // A note the plan marks `raw` plays the um AS IT WAS SAID: no pitch shift, no + // stretch, no second correcting pass -- only the slot's chop and the fades + // below. reuse-pass.mjs sets it, after measuring this same clip against this + // same note with the two functions above; what is measured here is printed at + // the end, so a plan marked by other means cannot claim more than it plays. + // A raw note measured more than RAW_GUARD semitones off is not played untouched: + // something changed the clip or the note after the pass (a swap, a retune), and an + // um a semitone out is worse than a shifted one. It is processed, and counted. + const off0 = head.f0 > 0 ? Math.abs(p.targetMidi - midiOf(head.f0)) : 0; + const asSaid = p.raw === true && off0 <= RAW_GUARD; + if (p.raw === true && !asSaid) rawRefused += 1; + if (asSaid) { + rawNotes += 1; + if (head.f0 > 0) rawOff.push(off0); + } // Preferred path: if a straight speed change lands BOTH the pitch and a // length that fits the note, take it -- it is the only transformation here // that adds no artifacts at all. @@ -257,12 +274,14 @@ for (const v of (SKIP_AUDIO ? [] : voices)) { const resLen = raw.length / speed; const canResample = Math.abs(shift) > 0.15 && Math.abs(shift) <= 6 && resLen <= maxLen * 1.01 && resLen >= maxLen * RESAMPLE_MIN_FILL; - if (canResample) { + if (asSaid) { + // nothing: seg is raw + } else if (canResample) { try { seg = resample(raw, speed); } catch { seg = raw; } } else if (Math.abs(shift) > 0.03 || stretch > 1.02 || stretch < 0.98) { try { seg = shiftBy(shift); } catch { seg = raw; } } - try { + if (!asSaid) try { const k2 = Math.min(seg.length, maxLen); const got = regionPitch(seg, Math.round(0.01 * SR), Math.max(Math.round(0.02 * SR), k2 - 1), SR, 55, 500); if (got.f0 > 0) { @@ -312,6 +331,12 @@ for (const v of (SKIP_AUDIO ? [] : voices)) { } console.log(` voice ${v.name}: ${n}/${v.plan.length} notes mixed`); } +if (rawRefused) console.log(` ${rawRefused} notes marked raw measured more than ${RAW_GUARD} semitones off and were processed instead`); +if (rawNotes) { + const o = [...rawOff].sort((x, y) => x - y); + const q = (f) => (o.length ? o[Math.floor(f * (o.length - 1))] : 0).toFixed(2); + console.log(` ${rawNotes} notes played as said (no pitch shift, no stretch); off their note by p50 ${q(0.5)} p90 ${q(0.9)} max ${q(1)} semitones`); +} // Overlays go in BEFORE the normalise-and-trim stage below, so the master is // levelled with them included -- adding them after would push the mix over full // scale and clip exactly on the loudest hooks. diff --git a/umtool/song/reuse-pass.mjs b/umtool/song/reuse-pass.mjs @@ -0,0 +1,267 @@ +#!/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 <plan-in.json> <plan-out.json> +// +// 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=<s> seconds between two soundings of one um (default 10) +// RAW_TOL=<st> 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=<f> an untouched um must fill this much of what the note may sound +// (default 0.85; it cannot be stretched to fit) +// MAX_USES=<n> 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=<st> 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 (<plan-out>.measure.json, or MEASURE_CACHE=<file> 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 <plan-in.json> <plan-out.json>"); 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: { <maxLen>: 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}`); diff --git a/umtool/song/swap-clip.mjs b/umtool/song/swap-clip.mjs @@ -274,7 +274,9 @@ const dates = JSON.parse(readFileSync(path.join(DIR, "dates.json"), "utf8")); const date = dates[c.video]; if (!date) console.log(` WARNING: ${c.video} has no entry in dates.json; the note keeps no date`); else if (note.date && date !== note.date) console.log(` date ${note.date} -> ${date} (the slot's place in the chronology moves)`); -const { date: _oldDate, ...rest } = note; +// `raw` goes too: reuse-pass.mjs marked the OLD clip as playing untouched on this note, +// and the new one was chosen within 3 semitones, not on the pitch. +const { date: _oldDate, raw: _oldRaw, ...rest } = note; v.plan[idx] = { ...rest, ...(date ? { date } : {}), video: c.video, srcStart: c.start, srcEnd: c.end, srcDur: +dur.toFixed(3), srcF0: best.f0 ?? c.f0, srcMidi: +midi.toFixed(2), shift: +(note.targetMidi - midi).toFixed(3),