Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor: share beat/tempo DSP between beat grid and Music Video analyzer (#9424)
[._.]/ Adam Eivyc960aeff1a7d
diff --git a/server/lib/README.md b/server/lib/README.mdindex 7adb056319..462cbf442e 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -183,6 +183,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `catalogUniverseTags.js` | Pure transform that rewrites legacy machine universe tags (`from-universe`, `universe:<id>`) on backfilled catalog ingredients into friendly universe-NAME tags, preserving user tags + the structured `catalog_ingredient_refs` link. Used by the boot-time repair and the bible→catalog backfill. || `comicScriptParser.js` | Marvel/DC-format comic script parser. || `aspectRatio.js` | Describe a pixel canvas as the ratio phrase a prompt can use — `aspectRatioTerms(w, h)` (bounded best rational approximation, so 1096x1536 reads as 5:7 rather than 137:192) and `aspectRatioPhrase(w, h)` → `"5:7 portrait"` / `"16:9 landscape"` / `"1:1 square"`. Use it wherever a prompt has to state a framing the canvas already fixes, so the sentence and the canvas cannot drift. Pure. |+| `audioBeatDsp.js` | Shared beat/tempo DSP core (#9424) used by both `beatGrid.js` and `services/musicVideo/audioAnalysis.js`: `decodeAudioToPcm` (ffmpeg → mono f32 PCM, capped at `MAX_ANALYSIS_SEC`), Hann/FFT helpers, `onsetEnvelope` (spectral flux + RMS energy), `estimateTempo` (full-track autocorrelation over 70-180 BPM with a windowed, clustered fallback for tracks with a variable intro/outro), `fitBeats`, `pickDownbeats`. Exported as the `audioBeatDsp` namespace from the barrel. || `audioFingerprint.js` | Loudness fingerprint of a stretch of a song (#9266): `computeRmsEnvelope(path)` decodes a file once to a 100 Hz integer-dBFS RMS envelope on the song's own frame grid, `windowFingerprint(envelope, { startSec, endSec })` stores a window of it (base64 Int8Array, ≤3 KB for 30 s), and `compareWindowFingerprint(fp, envelope)` says whether a newer master still carries that window (Pearson ≥ 0.98 and mean \|ΔdB\| ≤ 1.5 above a −60 dB codec-noise floor). Lets a lip-sync take survive a re-master that changed audio outside its window. || `composeStyledPrompt.js` | Compose user prompt + negative with an optional style preset, or an array of presets layered in order. Re-exported (unmodified) by `client/src/lib/composeStyledPrompt.js`. || `scriptVideoCompiler.js` | Compiles a scene script + bible into beat-level continuous-video clip specs (duration/frame-grid snapping, byte-stable descriptor injection, chain-length fresh-cut rule). |@@ -467,7 +468,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `tailcatVersion.js` | Tailcat CLI version floor for managed install/detect: `MIN_TAILCAT_VERSION` (`0.6.0` — PSK on by default in modern `serve`), `parseTailcatVersion` (handles the CLI's `v0.6.0` banner that `parseHarnessVersion` cannot), `isTailcatVersionAtLeast`, and `tailcatVersionTooOldMessage` for operator-facing upgrade guidance. Consumed by `services/tailcatPeer.js` so Dial-them and They-dial-us refuse ≤0.5.x rather than silently timing out on TCP. || `httpsState.js` | Captures whether PortOS booted with HTTPS active. || `bareUrl.js` | `parseBareUrl(text)` — returns the normalized URL when a captured string is nothing *but* a URL (bare host gets `https://`), else null. Drives the brain-capture short-circuit that files a pasted URL straight to Links instead of running the classifier. Stricter than the client's `urlNormalize.js` `isUrl` (needs a plausible TLD; http/https/`git@` only) because it picks a storage destination rather than a hint. |-| `beatGrid.js` | Beat grid measurement for library music tracks (#8958): `getBeatGrid(absoluteAudioPath)` decodes via ffmpeg and returns `{ bpm, beats, downbeats, hits } \| null`, cached in memory per (path, mtime) so repeated calls against the same track don't re-decode. `decodeAudioToPcm` is the ffmpeg-decode step (exported for direct testing). The pure DSP core — spectral-flux onset envelope, tempo-weighted autocorrelation over 60-200 BPM, phase-aligned beat/downbeat placement, onset "hit" peak-picking — is unit-tested directly against a synthetic click track via the `__analyzeBeatGridPcm` test seam (no production caller needs raw-PCM access; every real caller goes through `getBeatGrid`). Deliberately does not import `server/services/musicVideo/audioAnalysis.js`, a structurally similar but larger pipeline for the separate Music Video feature — `server/lib/` cannot depend on `server/services/` (`layering.test.js`). |+| `beatGrid.js` | Beat grid measurement for library music tracks (#8958): `getBeatGrid(absoluteAudioPath)` decodes via ffmpeg and returns `{ bpm, beats, downbeats, hits } \| null`, cached in memory per (path, mtime) so repeated calls against the same track don't re-decode. The DSP core (decode, onset envelope, tempo incl. windowed fallback, beat/downbeat fitting) comes from `audioBeatDsp.js`; this module adds onset "hit" peak-picking and the per-file cache, and re-exports `decodeAudioToPcm` for direct testing. It is unit-tested directly against a synthetic click track via the `__analyzeBeatGridPcm` test seam (no production caller needs raw-PCM access; every real caller goes through `getBeatGrid`). || `beeperAttachmentPaths.js` | Layout rules for the Beeper attachment byte mirror (#37): `BEEPER_ATTACHMENT_MAX_BYTES` (32 MiB, matching `FEDERATED_MEDIA_ASSET_MAX_BYTES` — a constant, not a setting), `attachmentExtension({ mimeType, fileName })`, `attachmentRelativePath(sha256, ext)` (`<sha256[0..2]>/<sha256>.<ext>`, `null` for anything that is not a 64-hex digest) and `isSafeAttachmentRelativePath(p)`. Content-addressed, so one forwarded photo is one file and every delete path owes a reference check first; the extension is cosmetic because `GET /v1/assets/serve` sends no `Content-Type` and the mirror serves from the stored `mimeType` instead. || `beeperOAuthOrigin.js` | Which origin the Beeper OAuth `redirect_uri` is built from: `parseBrowserOrigin` (a bare `http(s)://host[:port]`, else null), `hostnameOf`, `isLoopbackHostname` (the loopback-spelling predicate reused by the `settings.beeper.baseUrl` gate and the OAuth token-endpoint host pin), and `resolveOAuthOrigin({ clientOrigin, requestOrigin, configuredOrigins })` → `{ origin, source, rejectedClientOrigin }`. The browser sends `window.location.origin` because the request-derived origin is the API's own under the Vite dev proxy (`changeOrigin`, no `x-forwarded-*`), which sends the consent redirect to a host the TLS cert does not cover; the value is untrusted, so it is accepted only for a loopback host, the request's own host, or a configured `PORTOS_UI_URL`/`PORTOS_API_URL` host — port unpinned, since UI and API are different ports of one install. Rejection falls back to the request origin. Pure. || `isSafeHref.js` | Pure http(s)-only scheme check (`isSafeHref`) for user-supplied URL fields that get rendered as a clickable `<a href>` — rejects `javascript:`/`data:`/etc. stored-XSS payloads. `client/src/lib/isSafeHref.js` re-exports it, and `client/src/utils/urlNormalize.js` re-exports that as `isHttpUrl`. |diff --git a/server/lib/audioBeatDsp.js b/server/lib/audioBeatDsp.jsnew file mode 100644index 0000000000..6db62ec598--- /dev/null+++ b/server/lib/audioBeatDsp.js@@ -0,0 +1,446 @@+/**+ * Shared beat/tempo DSP core (#9424).+ *+ * The ffmpeg-decode + pure-JS spectral-flux pipeline that both the Music Video+ * analyzer (`services/musicVideo/audioAnalysis.js`) and the launch-video beat+ * grid (`lib/beatGrid.js`) build on: Hann/FFT helpers, `decodeAudioToPcm`,+ * `onsetEnvelope`, windowed-fallback `estimateTempo`, `fitBeats` and+ * `pickDownbeats`. It lives in `server/lib/` so both callers import one copy+ * instead of forking it (a fork had already drifted — only one side had the+ * windowed tempo fallback). Callers keep their own concerns: sections,+ * waveform, features and manual tempo in audioAnalysis; hit peak-picking and+ * the per-file cache in beatGrid.+ */++import { spawn } from './childProcess.js';+import { findFfmpeg } from './ffmpeg.js';+import { safeChildProcessOptions } from './processEnv.js';++// Fixed analysis sample rate. 22.05kHz retains the 40Hz–8kHz spectral bands+// used for onset work and halves the sample count vs 44.1kHz. Mono — beat+// structure is shared across channels.+export const ANALYSIS_SAMPLE_RATE = 22050;++// Cap how much of a track ffmpeg decodes (issue #8973). decodeAudioToPcm+// buffers the whole decoded f32 PCM stream in memory before this module runs+// tempo/section analysis on it — unbounded, a 20+ minute track can push a+// single decode into the hundreds of MB, doubling briefly at the+// Buffer.concat below. Tempo/section analysis doesn't need the full track:+// TEMPO_WINDOW_SEC-scale windows already assume a fraction of it is enough,+// and five minutes gives the section segmentation (MAX_SECTIONS sections,+// MIN_SECTION_SEC apart) far more material than it uses. Passing `-t` lets+// ffmpeg truncate the decode itself instead of PortOS buffering (and then+// discarding) the rest of the stream.+export const MAX_ANALYSIS_SEC = 300;++// Frame hop for the onset envelope. 512 samples @ 22.05kHz → ~43 frames/sec,+// which gives ~1 BPM tempo resolution across the musical range and ~23ms beat+// placement granularity — both well within what beat-snapping needs.+export const ONSET_HOP = 512;++// Tempo search window. Most music sits here; clamping the search keeps the+// autocorrelation from latching onto sub-bass rumble (very low BPM) or+// per-note flutter (very high BPM). Half/double-time octave errors inside this+// range are handled by the tempo-preference weighting below.+const MIN_BPM = 70;+const MAX_BPM = 180;+// Log-normal tempo preference centered here disambiguates octave errors (60 vs+// 120 vs 240) — the classic Davies/Plumbley bias toward a "natural" tempo.+const PREFERRED_BPM = 120;+const TEMPO_PREF_SIGMA = 0.9; // in octaves++// Minimum normalized autocorrelation peak (`ac[lag] / ac[0]`) to accept a+// tempo. Below this the "peak" is just the strongest lag of essentially+// structureless audio (white noise, near-silence) — reporting a confident BPM+// there is worse than reporting none. Clean periodic input sits well above it+// (click tracks measure 0.4–0.9); white noise measures ~0.23.+const TEMPO_PEAK_MIN = 0.3;+// A song-wide autocorrelation can be diluted by a long rubato/ambient intro+// even when the body of the song has a stable pulse. Scan overlapping musical+// windows as a fallback and require two agreeing windows before accepting their+// tempo, so one coincidental noise peak cannot invent a beat grid.+const TEMPO_WINDOW_SEC = 30;+const TEMPO_WINDOW_STEP_SEC = 15;+const TEMPO_WINDOW_AGREEMENT = 0.04;+export const FFT_SIZE = 1024;++// Hann window cached per length. Windowing each analysis frame before measuring+// energy suppresses the spectral-leakage ripple a steady tone otherwise beats+// against the frame grid — without it, a sustained pure tone produces a periodic+// onset envelope and a confident-but-bogus tempo. Broadband transients (the+// actual beats) survive windowing, so click/percussion detection is unaffected.+const hannCache = new Map();+export const hannWindow = (len) => {+ let w = hannCache.get(len);+ if (w) return w;+ w = new Float32Array(len);+ for (let i = 0; i < len; i++) w[i] = 0.5 * (1 - Math.cos((2 * Math.PI * i) / (len - 1)));+ hannCache.set(len, w);+ return w;+};++const fftPlanCache = new Map();+export const fftPlan = (size) => {+ let plan = fftPlanCache.get(size);+ if (plan) return plan;+ const reverse = new Uint32Array(size);+ const bits = Math.log2(size);+ for (let i = 0; i < size; i++) {+ let x = i;+ let r = 0;+ for (let bit = 0; bit < bits; bit++) { r = (r << 1) | (x & 1); x >>= 1; }+ reverse[i] = r;+ }+ const cos = new Float64Array(size / 2);+ const sin = new Float64Array(size / 2);+ for (let i = 0; i < size / 2; i++) {+ const angle = (-2 * Math.PI * i) / size;+ cos[i] = Math.cos(angle);+ sin[i] = Math.sin(angle);+ }+ plan = { reverse, cos, sin };+ fftPlanCache.set(size, plan);+ return plan;+};++export function fftInPlace(real, imaginary, plan) {+ const n = real.length;+ for (let i = 0; i < n; i++) {+ const j = plan.reverse[i];+ if (j <= i) continue;+ [real[i], real[j]] = [real[j], real[i]];+ [imaginary[i], imaginary[j]] = [imaginary[j], imaginary[i]];+ }+ for (let size = 2; size <= n; size *= 2) {+ const half = size / 2;+ const twiddleStep = n / size;+ for (let start = 0; start < n; start += size) {+ for (let offset = 0; offset < half; offset++) {+ const twiddle = offset * twiddleStep;+ const even = start + offset;+ const odd = even + half;+ const oddReal = real[odd] * plan.cos[twiddle] - imaginary[odd] * plan.sin[twiddle];+ const oddImaginary = real[odd] * plan.sin[twiddle] + imaginary[odd] * plan.cos[twiddle];+ real[odd] = real[even] - oddReal;+ imaginary[odd] = imaginary[even] - oddImaginary;+ real[even] += oddReal;+ imaginary[even] += oddImaginary;+ }+ }+ }+}++/**+ * Decode an audio file to a mono Float32Array at ANALYSIS_SAMPLE_RATE via+ * ffmpeg. Returns `{ samples, sampleRate }` on success, or `null` when ffmpeg+ * is unavailable or the decode fails — callers treat `null` as "couldn't+ * analyze" rather than throwing (this runs outside the request lifecycle when+ * driven by the render queue).+ *+ * Decodes at most MAX_ANALYSIS_SEC seconds of the source (see its doc+ * comment) — a track longer than the cap gets tempo/section data from that+ * leading window only.+ *+ * @param {string} audioPath absolute path to the source audio+ * @param {{ signal?: AbortSignal, maxDurationSec?: number }} [opts]+ * `maxDurationSec` overrides MAX_ANALYSIS_SEC — a test-only seam so the+ * truncation path can be exercised against a short fixture rather than a+ * real multi-minute file; real callers should not pass it. Clamped to+ * MAX_ANALYSIS_SEC — it can only shrink the decode window, never grow it,+ * so it can't be used to defeat the memory bound.+ * @returns {Promise<{ samples: Float32Array, sampleRate: number } | null>}+ */+export async function decodeAudioToPcm(audioPath, { signal, maxDurationSec = MAX_ANALYSIS_SEC } = {}) {+ if (typeof audioPath !== 'string' || !audioPath) return null;+ // A listener added to an already-aborted signal never fires, so without this+ // guard a pre-cancelled request (plausible off the request lifecycle, under a+ // render queue) would still spawn ffmpeg and decode the whole track.+ if (signal?.aborted) return null;+ const ffmpeg = await findFfmpeg();+ if (!ffmpeg) return null;+ // Re-check: the signal may have aborted while findFfmpeg() was awaiting, so+ // the listener below would again attach to an already-aborted signal.+ if (signal?.aborted) return null;++ const boundedDurationSec = Number.isFinite(maxDurationSec) && maxDurationSec > 0+ ? Math.min(maxDurationSec, MAX_ANALYSIS_SEC)+ : MAX_ANALYSIS_SEC;++ return new Promise((resolve) => {+ const args = [+ '-v', 'error',+ '-i', audioPath,+ '-t', String(boundedDurationSec),+ '-ac', '1',+ '-ar', String(ANALYSIS_SAMPLE_RATE),+ '-f', 'f32le',+ '-acodec', 'pcm_f32le',+ 'pipe:1',+ ];+ const proc = spawn(ffmpeg, args, safeChildProcessOptions({ stdio: ['ignore', 'pipe', 'ignore'] }));+ const chunks = [];+ let onAbort = null;+ if (signal) {+ onAbort = () => proc.kill('SIGTERM');+ signal.addEventListener('abort', onAbort, { once: true });+ }+ const cleanup = () => { if (signal && onAbort) signal.removeEventListener('abort', onAbort); };++ proc.stdout.on('data', (c) => chunks.push(c));+ proc.on('error', () => { cleanup(); resolve(null); });+ proc.on('close', (code, sig) => {+ cleanup();+ if (sig || code !== 0 || chunks.length === 0) { resolve(null); return; }+ const buf = Buffer.concat(chunks);+ // Float32Array view over the decoded bytes. Guard the byte length down to+ // a multiple of 4 so a truncated final chunk can't throw on construction.+ const floats = Math.floor(buf.length / 4);+ if (floats === 0) { resolve(null); return; }+ // A view is O(1) (no per-sample copy), but Float32Array requires the byte+ // offset to be 4-aligned. Buffer.concat returns an unpooled buffer+ // (offset 0) for the multi-KB PCM we get here, so the view path is the+ // normal case; fall back to a copied slice if a pooled buffer ever lands+ // on a non-aligned offset.+ const samples = buf.byteOffset % 4 === 0+ ? new Float32Array(buf.buffer, buf.byteOffset, floats)+ : new Float32Array(buf.buffer.slice(buf.byteOffset, buf.byteOffset + floats * 4));+ resolve({ samples, sampleRate: ANALYSIS_SAMPLE_RATE });+ });+ });+}++/**+ * Compute a per-frame onset-strength envelope from spectral flux. Unlike a+ * single loudness difference, positive changes across FFT bands capture guitar+ * strums and harmonic attacks even when the song's overall volume is steady.+ * A local adaptive floor suppresses broadband noise and room tone. Raw RMS+ * energy is returned alongside it for section segmentation and the waveform.+ */+export function onsetEnvelope(samples, sampleRate, hop = ONSET_HOP) {+ const fftSize = FFT_SIZE;+ const frameCount = Math.max(0, Math.floor((samples.length - fftSize) / hop) + 1);+ const energy = new Float32Array(frameCount);+ const rawFlux = new Float32Array(frameCount);+ const win = hannWindow(fftSize);+ const plan = fftPlan(fftSize);+ const real = new Float64Array(fftSize);+ const imaginary = new Float64Array(fftSize);+ const previous = new Float64Array(fftSize / 2);+ const minBin = Math.max(1, Math.floor((40 * fftSize) / sampleRate));+ const maxBin = Math.min(fftSize / 2 - 1, Math.ceil((8000 * fftSize) / sampleRate));+ for (let f = 0; f < frameCount; f++) {+ let sum = 0;+ const base = f * hop;+ for (let i = 0; i < fftSize; i++) {+ const sample = samples[base + i];+ sum += sample * sample;+ real[i] = sample * win[i];+ imaginary[i] = 0;+ }+ energy[f] = Math.sqrt(sum / fftSize);+ fftInPlace(real, imaginary, plan);+ let flux = 0;+ for (let bin = minBin; bin <= maxBin; bin++) {+ const magnitude = Math.log1p(Math.sqrt(real[bin] * real[bin] + imaginary[bin] * imaginary[bin]));+ const rise = magnitude - previous[bin];+ if (rise > 0) flux += rise;+ previous[bin] = magnitude;+ }+ rawFlux[f] = flux / (maxBin - minBin + 1);+ }++ // Subtract a rolling ~0.75s local mean. A real note/percussion attack rises+ // above its neighborhood; stationary noise fluctuates around the floor.+ const onset = new Float32Array(frameCount);+ const radius = Math.max(1, Math.round((0.75 * sampleRate) / hop / 2));+ let rolling = 0;+ let left = 0;+ let right = 0;+ for (let f = 0; f < frameCount; f++) {+ while (right < frameCount && right <= f + radius) { rolling += rawFlux[right]; right += 1; }+ while (left < f - radius) { rolling -= rawFlux[left]; left += 1; }+ const localMean = rolling / Math.max(1, right - left);+ onset[f] = Math.max(0, rawFlux[f] - localMean);+ }+ return { onset, energy, fps: sampleRate / hop, frameCount };+}++// Fractional-lag step (frames) for the tempo autocorrelation scan. Scanning the+// period continuously instead of at integer lags is what makes the estimate+// robust: a true beat period of, say, 18.46 frames lands between integer lags,+// so integer-lag autocorrelation smears its peak across lags 18 and 19 (each+// weakened) while the sharper half-tempo lag wins — the classic half-tempo+// octave error. Interpolating at 0.25-frame resolution recovers the full+// fundamental peak, so both the significance gate and the octave fold judge it+// fairly.+const TEMPO_LAG_STEP = 0.25;++/**+ * Estimate tempo (BPM) and the beat period (in fractional frames) by+ * tempo-weighted, sub-frame autocorrelation of the onset envelope. The envelope+ * is zero-meaned first so the silence floor between hits doesn't bias the+ * correlation toward a DC peak. Returns `{ bpm: null, lag: null }` when the+ * envelope carries no usable periodicity (silence, or structureless input whose+ * strongest peak is below the significance floor).+ */+function estimateTempoCandidate(onset, fps) {+ const n = onset.length;+ if (n < 4) return null;+ let mean = 0;+ for (let i = 0; i < n; i++) mean += onset[i];+ mean /= n;+ const o = new Float32Array(n);+ let variance = 0;+ for (let i = 0; i < n; i++) { o[i] = onset[i] - mean; variance += o[i] * o[i]; }+ if (variance <= 1e-9) return null;++ // Autocorrelation at a fractional lag via linear interpolation of the shifted+ // envelope. `variance` is the zero-lag value (ac(0) = sum of squares).+ const acFrac = (lag) => {+ const lo = Math.floor(lag);+ const frac = lag - lo;+ let sum = 0;+ for (let i = 0; i + lo + 1 < n; i++) {+ sum += o[i] * (o[i + lo] * (1 - frac) + o[i + lo + 1] * frac);+ }+ return sum;+ };++ const minLag = Math.max(1, (60 * fps) / MAX_BPM);+ const maxLag = Math.min(n - 2, (60 * fps) / MIN_BPM);+ let bestLag = -1;+ let bestScore = -Infinity;+ let bestAc = 0;+ for (let lag = minLag; lag <= maxLag; lag += TEMPO_LAG_STEP) {+ const ac = acFrac(lag);+ const bpm = (60 * fps) / lag;+ const octaves = Math.log2(bpm / PREFERRED_BPM);+ const weight = Math.exp(-0.5 * (octaves / TEMPO_PREF_SIGMA) ** 2);+ const score = ac * weight;+ if (score > bestScore) { bestScore = score; bestLag = lag; bestAc = ac; }+ }+ if (bestLag < 0 || bestScore <= 0) return null;++ // NOTE — octave (half/double-tempo) ambiguity is intentionally NOT resolved+ // here. Autocorrelation peaks at every multiple of the true period, so the+ // estimate is only reliable UP TO an octave: a 140 BPM track may report 70,+ // and a phase-aligned-comb tie-break (tried) cannot separate the two for many+ // signals (a half-period grid captures comparable onset energy), while the+ // tempo-preference weight alone mis-picks other octaves. Robust octave+ // selection is a deliberate open question for a later phase (see #1760+ // "beat-snap semantics") — beat snapping still works off this grid, just at a+ // possibly-doubled/halved density. The detected period is the+ // highest-weighted autocorrelation peak in [MIN_BPM, MAX_BPM].+ const bpm = (60 * fps) / bestLag;+ return { bpm, lag: bestLag, confidence: bestAc / variance };+}++const temposAgree = (a, b) => {+ const octaveDistance = Math.abs(Math.log2(a / b));+ return Math.abs(octaveDistance - Math.round(octaveDistance)) <= Math.log2(1 + TEMPO_WINDOW_AGREEMENT);+};++const foldTempoNear = (bpm, anchor) => {+ let folded = bpm;+ while (folded * 2 <= MAX_BPM && Math.abs(Math.log2((folded * 2) / anchor)) < Math.abs(Math.log2(folded / anchor))) folded *= 2;+ while (folded / 2 >= MIN_BPM && Math.abs(Math.log2((folded / 2) / anchor)) < Math.abs(Math.log2(folded / anchor))) folded /= 2;+ return folded;+};++export function estimateTempo(onset, fps) {+ const full = estimateTempoCandidate(onset, fps);+ if (full && full.confidence >= TEMPO_PEAK_MIN) {+ return {+ ...full,+ source: 'full',+ window: { startSec: 0, endSec: onset.length / fps },+ };+ }++ const windowFrames = Math.round(TEMPO_WINDOW_SEC * fps);+ const stepFrames = Math.round(TEMPO_WINDOW_STEP_SEC * fps);+ if (onset.length < windowFrames) return { bpm: null, lag: null, confidence: full?.confidence ?? null, source: null, window: null };++ const candidates = [];+ for (let start = 0; start + windowFrames <= onset.length; start += stepFrames) {+ const candidate = estimateTempoCandidate(onset.slice(start, start + windowFrames), fps);+ if (candidate?.confidence >= TEMPO_PEAK_MIN) {+ candidates.push({+ ...candidate,+ startSec: start / fps,+ endSec: (start + windowFrames) / fps,+ });+ }+ }++ const clusters = candidates.map((anchor) => candidates.filter((candidate) => temposAgree(anchor.bpm, candidate.bpm)));+ const cluster = clusters+ .filter((group) => group.length >= 2)+ .sort((a, b) => (+ b.reduce((sum, candidate) => sum + candidate.confidence, 0)+ - a.reduce((sum, candidate) => sum + candidate.confidence, 0)+ ))[0];+ if (!cluster) return { bpm: null, lag: null, confidence: full?.confidence ?? null, source: null, window: null };++ const strongest = cluster.slice().sort((a, b) => b.confidence - a.confidence)[0];+ const weight = cluster.reduce((sum, candidate) => sum + candidate.confidence, 0);+ const bpm = cluster.reduce(+ (sum, candidate) => sum + foldTempoNear(candidate.bpm, strongest.bpm) * candidate.confidence,+ 0,+ ) / weight;+ return {+ bpm,+ lag: (60 * fps) / bpm,+ confidence: strongest.confidence,+ source: 'windowed',+ window: { startSec: strongest.startSec, endSec: strongest.endSec },+ };+}++/**+ * Fit the beat phase: slide a pulse train of the given period across the onset+ * envelope and pick the offset whose pulses sum the most onset strength.+ * Returns the beat times (seconds) for the whole track.+ */+export function fitBeats(onset, fps, bpm, durationSec) {+ const periodFrames = (60 * fps) / bpm;+ let bestOffset = 0;+ let bestSum = -Infinity;+ const maxOffset = Math.ceil(periodFrames);+ for (let off = 0; off < maxOffset; off++) {+ let sum = 0;+ for (let pos = off; pos < onset.length; pos += periodFrames) {+ sum += onset[Math.round(pos)] || 0;+ }+ if (sum > bestSum) { bestSum = sum; bestOffset = off; }+ }+ const beats = [];+ for (let pos = bestOffset; pos < onset.length; pos += periodFrames) {+ const t = pos / fps;+ if (t <= durationSec) beats.push(Number(t.toFixed(3)));+ }+ return beats;+}++/**+ * Pick downbeats assuming 4/4: of the four candidate beat phases, choose the+ * one whose beats carry the most onset strength (downbeats are typically the+ * loudest). Returns the subset of `beats` on that phase.+ */+export function pickDownbeats(beats, onset, fps) {+ if (beats.length === 0) return [];+ const beatsPerBar = 4;+ let bestPhase = 0;+ let bestSum = -Infinity;+ for (let phase = 0; phase < beatsPerBar; phase++) {+ let sum = 0;+ for (let i = phase; i < beats.length; i += beatsPerBar) {+ sum += onset[Math.round(beats[i] * fps)] || 0;+ }+ if (sum > bestSum) { bestSum = sum; bestPhase = phase; }+ }+ const downbeats = [];+ for (let i = bestPhase; i < beats.length; i += beatsPerBar) downbeats.push(beats[i]);+ return downbeats;+}+diff --git a/server/lib/beatGrid.js b/server/lib/beatGrid.jsindex 26dc190e42..671b1518c0 100644--- a/server/lib/beatGrid.js+++ b/server/lib/beatGrid.js@@ -16,62 +16,25 @@* memory per (path, mtime) so a route handler or a CoS-run prep step can call* it repeatedly without re-decoding the same track.*- * This module intentionally does not import `server/services/musicVideo/- * audioAnalysis.js`, which solves an adjacent problem (tempo + section map- * for the Music Video feature) with a structurally similar pipeline —- * `server/lib/` cannot depend on `server/services/` (see `layering.test.js`).- * The DSP core here is deliberately smaller in scope: no section- * segmentation, no waveform summary, no manual-tempo override — just the- * beat/downbeat/hit grid a launch-video render needs.+ * The DSP core (decode, onset envelope, tempo, beat/downbeat fitting) is+ * shared with the Music Video analyzer via `./audioBeatDsp.js` (#9424); this+ * module adds the hit peak-picking and the per-file cache.*/-import { spawn } from './childProcess.js';-import { findFfmpeg } from './ffmpeg.js';-import { safeChildProcessOptions } from './processEnv.js';import { stat } from 'node:fs/promises';--// Fixed analysis sample rate. 22.05kHz keeps the 40Hz-8kHz band used for-// onset work while halving the sample count against 44.1kHz. Mono — beat-// structure is shared across channels.-export const BEAT_GRID_SAMPLE_RATE = 22050;--// Cap how much of a track ffmpeg decodes (issue #8973). Buffering unbounded-// decoded f32 PCM in memory scales with track length — a 20+ minute ambient-// bed or DJ mix can push a single decode into the hundreds of MB, doubling-// briefly at the Buffer.concat in decodeAudioToPcm. Tempo/beat estimation-// doesn't need the whole track: five minutes gives autocorrelation dozens of-// bars to lock onto, far more than the TEMPO_WINDOW_SEC-scale windows other-// tempo estimators use. Passing `-t` lets ffmpeg itself truncate the decode-// instead of PortOS buffering (and then discarding) the rest of the stream.-export const MAX_ANALYSIS_SEC = 300;--// Frame hop for the onset envelope: ~43 frames/sec at 22.05kHz, giving-// sub-1-BPM tempo resolution and ~23ms beat-placement granularity.-export const ONSET_HOP = 512;--// Tempo search window (issue #8958: "estimate tempo by autocorrelation-// (60-200 BPM)"). A log-normal preference centered at PREFERRED_BPM-// disambiguates octave errors (a 90 BPM track's autocorrelation peaks at 45,-// 90, 180... equally; the preference weight favors the one closest to a-// "natural" dance tempo).-const MIN_BPM = 60;-const MAX_BPM = 200;-const PREFERRED_BPM = 120;-const TEMPO_PREF_SIGMA = 0.9; // in octaves--// Minimum normalized autocorrelation peak to accept a tempo. Below this the-// "peak" is just the strongest lag of structureless audio (silence, noise) —-// reporting a confident BPM there is worse than reporting none.-const TEMPO_PEAK_MIN = 0.3;--const FFT_SIZE = 1024;--// Fractional-lag step (frames) for the tempo autocorrelation scan. Integer-lag-// autocorrelation smears a true period that lands between two integer lags-// across both (the classic half-tempo octave error); interpolating at-// 0.25-frame resolution recovers the true peak and keeps the BPM estimate-// precise enough that a beat grid held over many bars doesn't visibly drift.-const TEMPO_LAG_STEP = 0.25;+import {+ ANALYSIS_SAMPLE_RATE,+ ONSET_HOP,+ decodeAudioToPcm,+ onsetEnvelope,+ estimateTempo,+ fitBeats,+ pickDownbeats,+} from './audioBeatDsp.js';++// Kept for existing importers; the shared pipeline owns the value.+export const BEAT_GRID_SAMPLE_RATE = ANALYSIS_SAMPLE_RATE;+export { decodeAudioToPcm };// Onset "hit" peak-picking: a local maximum must exceed the envelope's mean// by this many standard deviations, and hits must be at least this far apart@@ -79,213 +42,6 @@ const TEMPO_LAG_STEP = 0.25;const HIT_THRESHOLD_SIGMA = 1.0;const HIT_MIN_GAP_SEC = 0.08;-const hannCache = new Map();-function hannWindow(len) {- let w = hannCache.get(len);- if (w) return w;- w = new Float32Array(len);- for (let i = 0; i < len; i++) w[i] = 0.5 * (1 - Math.cos((2 * Math.PI * i) / (len - 1)));- hannCache.set(len, w);- return w;-}--const fftPlanCache = new Map();-function fftPlan(size) {- let plan = fftPlanCache.get(size);- if (plan) return plan;- const reverse = new Uint32Array(size);- const bits = Math.log2(size);- for (let i = 0; i < size; i++) {- let x = i;- let r = 0;- for (let bit = 0; bit < bits; bit++) { r = (r << 1) | (x & 1); x >>= 1; }- reverse[i] = r;- }- const cos = new Float64Array(size / 2);- const sin = new Float64Array(size / 2);- for (let i = 0; i < size / 2; i++) {- const angle = (-2 * Math.PI * i) / size;- cos[i] = Math.cos(angle);- sin[i] = Math.sin(angle);- }- plan = { reverse, cos, sin };- fftPlanCache.set(size, plan);- return plan;-}--// In-place iterative radix-2 FFT (Cooley-Tukey, decimation-in-time).-function fftInPlace(real, imaginary, plan) {- const n = real.length;- for (let i = 0; i < n; i++) {- const j = plan.reverse[i];- if (j <= i) continue;- [real[i], real[j]] = [real[j], real[i]];- [imaginary[i], imaginary[j]] = [imaginary[j], imaginary[i]];- }- for (let size = 2; size <= n; size *= 2) {- const half = size / 2;- const twiddleStep = n / size;- for (let start = 0; start < n; start += size) {- for (let offset = 0; offset < half; offset++) {- const twiddle = offset * twiddleStep;- const even = start + offset;- const odd = even + half;- const oddReal = real[odd] * plan.cos[twiddle] - imaginary[odd] * plan.sin[twiddle];- const oddImaginary = real[odd] * plan.sin[twiddle] + imaginary[odd] * plan.cos[twiddle];- real[odd] = real[even] - oddReal;- imaginary[odd] = imaginary[even] - oddImaginary;- real[even] += oddReal;- imaginary[even] += oddImaginary;- }- }- }-}--/**- * Per-frame onset-strength envelope from spectral flux: positive change- * across FFT bands, so a guitar strum or a harmonic attack registers even- * when overall loudness is steady. A rolling local mean is subtracted so a- * broadband noise floor doesn't read as a beat.- *- * @param {Float32Array} samples mono PCM- * @param {number} sampleRate- * @param {number} hop- * @returns {{ onset: Float32Array, fps: number, frameCount: number }}- */-function onsetEnvelope(samples, sampleRate, hop) {- const fftSize = FFT_SIZE;- const frameCount = Math.max(0, Math.floor((samples.length - fftSize) / hop) + 1);- const rawFlux = new Float32Array(frameCount);- const win = hannWindow(fftSize);- const plan = fftPlan(fftSize);- const real = new Float64Array(fftSize);- const imaginary = new Float64Array(fftSize);- const previous = new Float64Array(fftSize / 2);- const minBin = Math.max(1, Math.floor((40 * fftSize) / sampleRate));- const maxBin = Math.min(fftSize / 2 - 1, Math.ceil((8000 * fftSize) / sampleRate));- for (let f = 0; f < frameCount; f++) {- const base = f * hop;- for (let i = 0; i < fftSize; i++) {- real[i] = samples[base + i] * win[i];- imaginary[i] = 0;- }- fftInPlace(real, imaginary, plan);- let flux = 0;- for (let bin = minBin; bin <= maxBin; bin++) {- const magnitude = Math.log1p(Math.sqrt(real[bin] * real[bin] + imaginary[bin] * imaginary[bin]));- const rise = magnitude - previous[bin];- if (rise > 0) flux += rise;- previous[bin] = magnitude;- }- rawFlux[f] = flux / (maxBin - minBin + 1);- }-- // Subtract a rolling ~0.75s local mean so a real attack (rising above its- // neighborhood) survives while a stationary floor is suppressed.- const onset = new Float32Array(frameCount);- const fps = sampleRate / hop;- const radius = Math.max(1, Math.round((0.75 * fps) / 2));- let rolling = 0;- let left = 0;- let right = 0;- for (let f = 0; f < frameCount; f++) {- while (right < frameCount && right <= f + radius) { rolling += rawFlux[right]; right += 1; }- while (left < f - radius) { rolling -= rawFlux[left]; left += 1; }- const localMean = rolling / Math.max(1, right - left);- onset[f] = Math.max(0, rawFlux[f] - localMean);- }- return { onset, fps, frameCount };-}--/**- * Estimate tempo (BPM) via tempo-weighted, sub-frame autocorrelation of the- * onset envelope. Returns `{ bpm: null, confidence: null }` when the- * envelope carries no usable periodicity (silence, or an autocorrelation- * peak below the significance floor).- */-function estimateTempo(onset, fps) {- const n = onset.length;- if (n < 4) return { bpm: null, confidence: null };- let mean = 0;- for (let i = 0; i < n; i++) mean += onset[i];- mean /= n;- const o = new Float32Array(n);- let variance = 0;- for (let i = 0; i < n; i++) { o[i] = onset[i] - mean; variance += o[i] * o[i]; }- if (variance <= 1e-9) return { bpm: null, confidence: null };-- const acFrac = (lag) => {- const lo = Math.floor(lag);- const frac = lag - lo;- let sum = 0;- for (let i = 0; i + lo + 1 < n; i++) {- sum += o[i] * (o[i + lo] * (1 - frac) + o[i + lo + 1] * frac);- }- return sum;- };-- const minLag = Math.max(1, (60 * fps) / MAX_BPM);- const maxLag = Math.min(n - 2, (60 * fps) / MIN_BPM);- let bestLag = -1;- let bestScore = -Infinity;- let bestAc = 0;- for (let lag = minLag; lag <= maxLag; lag += TEMPO_LAG_STEP) {- const ac = acFrac(lag);- const bpm = (60 * fps) / lag;- const octaves = Math.log2(bpm / PREFERRED_BPM);- const weight = Math.exp(-0.5 * (octaves / TEMPO_PREF_SIGMA) ** 2);- const score = ac * weight;- if (score > bestScore) { bestScore = score; bestLag = lag; bestAc = ac; }- }- if (bestLag < 0 || bestScore <= 0) return { bpm: null, confidence: null };-- const confidence = Math.max(0, Math.min(1, bestAc / variance));- if (confidence < TEMPO_PEAK_MIN) return { bpm: null, confidence };- return { bpm: (60 * fps) / bestLag, confidence };-}--/**- * Fit the beat phase: slide a pulse train at the estimated period across the- * onset envelope and keep the integer-frame offset whose pulses sum the most- * onset strength. Returns beat times in seconds.- */-function fitBeats(onset, fps, bpm, durationSec) {- const periodFrames = (60 * fps) / bpm;- let bestOffset = 0;- let bestSum = -Infinity;- const maxOffset = Math.max(1, Math.ceil(periodFrames));- for (let off = 0; off < maxOffset; off++) {- let sum = 0;- for (let pos = off; pos < onset.length; pos += periodFrames) sum += onset[Math.round(pos)] || 0;- if (sum > bestSum) { bestSum = sum; bestOffset = off; }- }- const beats = [];- for (let pos = bestOffset; pos < onset.length; pos += periodFrames) {- const t = pos / fps;- if (t <= durationSec) beats.push(Number(t.toFixed(3)));- }- return beats;-}--/**- * Pick downbeats assuming 4/4: of the four candidate beat phases, choose the- * one whose beats carry the most onset strength.- */-function pickDownbeats(beats, onset, fps) {- if (beats.length === 0) return [];- const beatsPerBar = 4;- let bestPhase = 0;- let bestSum = -Infinity;- for (let phase = 0; phase < beatsPerBar; phase++) {- let sum = 0;- for (let i = phase; i < beats.length; i += beatsPerBar) sum += onset[Math.round(beats[i] * fps)] || 0;- if (sum > bestSum) { bestSum = sum; bestPhase = phase; }- }- const downbeats = [];- for (let i = bestPhase; i < beats.length; i += beatsPerBar) downbeats.push(beats[i]);- return downbeats;-}-/*** Peak-pick individual onset transients ("hits") for UI sound placement —* fills, hi-hats, and other one-off accents a quantized beat grid doesn't@@ -361,71 +117,6 @@ export function __analyzeBeatGridPcm(samples, sampleRate, { hop = ONSET_HOP } =};}-/**- * Decode an audio file to mono Float32Array PCM at BEAT_GRID_SAMPLE_RATE via- * ffmpeg. Returns `null` when ffmpeg is unavailable or the decode fails —- * callers treat that as "couldn't measure a beat grid" rather than throwing.- *- * Decodes at most MAX_ANALYSIS_SEC seconds of the source (see its doc- * comment) — a track longer than the cap gets its beat grid measured from- * that leading window only.- *- * @param {string} audioPath absolute path to the source audio- * @param {{ signal?: AbortSignal, maxDurationSec?: number }} [opts]- * `maxDurationSec` overrides MAX_ANALYSIS_SEC — a test-only seam so the- * truncation path can be exercised against a short fixture rather than a- * real multi-minute file; real callers should not pass it. Clamped to- * MAX_ANALYSIS_SEC — it can only shrink the decode window, never grow it,- * so it can't be used to defeat the memory bound.- * @returns {Promise<{ samples: Float32Array, sampleRate: number } | null>}- */-export async function decodeAudioToPcm(audioPath, { signal, maxDurationSec = MAX_ANALYSIS_SEC } = {}) {- if (typeof audioPath !== 'string' || !audioPath) return null;- if (signal?.aborted) return null;- const ffmpeg = await findFfmpeg();- if (!ffmpeg) return null;- if (signal?.aborted) return null;-- const boundedDurationSec = Number.isFinite(maxDurationSec) && maxDurationSec > 0- ? Math.min(maxDurationSec, MAX_ANALYSIS_SEC)- : MAX_ANALYSIS_SEC;-- return new Promise((resolve) => {- const args = [- '-v', 'error',- '-i', audioPath,- '-t', String(boundedDurationSec),- '-ac', '1',- '-ar', String(BEAT_GRID_SAMPLE_RATE),- '-f', 'f32le',- '-acodec', 'pcm_f32le',- 'pipe:1',- ];- const proc = spawn(ffmpeg, args, safeChildProcessOptions({ stdio: ['ignore', 'pipe', 'ignore'] }));- const chunks = [];- let onAbort = null;- if (signal) {- onAbort = () => proc.kill('SIGTERM');- signal.addEventListener('abort', onAbort, { once: true });- }- const cleanup = () => { if (signal && onAbort) signal.removeEventListener('abort', onAbort); };-- proc.stdout.on('data', (c) => chunks.push(c));- proc.on('error', () => { cleanup(); resolve(null); });- proc.on('close', (code, sig) => {- cleanup();- if (sig || code !== 0 || chunks.length === 0) { resolve(null); return; }- const buf = Buffer.concat(chunks);- const floats = Math.floor(buf.length / 4);- if (floats === 0) { resolve(null); return; }- const samples = buf.byteOffset % 4 === 0- ? new Float32Array(buf.buffer, buf.byteOffset, floats)- : new Float32Array(buf.buffer.slice(buf.byteOffset, buf.byteOffset + floats * 4));- resolve({ samples, sampleRate: BEAT_GRID_SAMPLE_RATE });- });- });-}-/*** Decode `audioPath` via ffmpeg and run the DSP analysis. Returns `null` when* the file can't be decoded (ffmpeg missing, unsupported/corrupt input). Notdiff --git a/server/lib/beatGrid.test.js b/server/lib/beatGrid.test.jsindex cb60068470..27b1f8adc8 100644--- a/server/lib/beatGrid.test.js+++ b/server/lib/beatGrid.test.js@@ -37,6 +37,27 @@ function clickTrack({ bpm, durationSec, sampleRate = BEAT_GRID_SAMPLE_RATE, offsreturn out;}+// Long beatless noise intro, then a regular pulse: the full-track+// autocorrelation peak falls below the significance floor, so only the+// windowed tempo fallback shared with the Music Video analyzer (#9424) can+// measure it.+function lateClickTrack({ bpm, introSec, rhythmicSec, sampleRate = BEAT_GRID_SAMPLE_RATE }) {+ const out = new Float32Array(Math.round((introSec + rhythmicSec) * sampleRate));+ let seed = 7;+ for (let i = 0; i < introSec * sampleRate; i++) {+ seed = (seed * 1103515245 + 12345) & 0x7fffffff;+ out[i] = ((seed / 0x7fffffff) * 2 - 1) * 0.15;+ }+ const burstLen = Math.round(0.025 * sampleRate);+ for (let t = introSec; t < introSec + rhythmicSec; t += 60 / bpm) {+ const start = Math.round(t * sampleRate);+ for (let k = 0; k < burstLen && start + k < out.length; k++) {+ out[start + k] += 0.8 * Math.exp(-k / (burstLen / 5)) * Math.sin((2 * Math.PI * 1200 * k) / sampleRate);+ }+ }+ return out;+}+/** Minimal 16-bit PCM mono WAV encoder for the ffmpeg round-trip test. */function encodeWav(samples, sampleRate) {const numSamples = samples.length;@@ -115,6 +136,15 @@ describe('__analyzeBeatGridPcm', () => {}});+ it('measures a tempo after a long beatless intro via the windowed fallback', () => {+ const samples = lateClickTrack({ bpm: 108, introSec: 45, rhythmicSec: 30 });+ const result = __analyzeBeatGridPcm(samples, BEAT_GRID_SAMPLE_RATE);+ expect(result.bpm).toBeGreaterThan(105);+ expect(result.bpm).toBeLessThan(111);+ expect(result.beats.length).toBeGreaterThan(100);+ expect(result.tempoConfidence).toBeGreaterThanOrEqual(0.3);+ });+it('reports no tempo for silence/noise rather than a bogus BPM', () => {const samples = new Float32Array(BEAT_GRID_SAMPLE_RATE * 4);const result = __analyzeBeatGridPcm(samples, BEAT_GRID_SAMPLE_RATE);diff --git a/server/lib/index.js b/server/lib/index.jsindex fdbc5b8841..c41e99046b 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -102,6 +102,7 @@ export * as catalogUniverseTags from './catalogUniverseTags.js';export * from './canonPrompt.js';export * from './comicScriptParser.js';export * from './aspectRatio.js';+export * as audioBeatDsp from './audioBeatDsp.js';export * from './audioFingerprint.js';export * from './composeStyledPrompt.js';export * from './scriptVideoCompiler.js';diff --git a/server/services/musicVideo/audioAnalysis.js b/server/services/musicVideo/audioAnalysis.jsindex d397f7a71d..a92c699a55 100644--- a/server/services/musicVideo/audioAnalysis.js+++ b/server/services/musicVideo/audioAnalysis.js@@ -25,42 +25,24 @@* thin ffmpeg-decode wrapper around it.*/-import { spawn } from '../../lib/childProcess.js';-import { findFfmpeg } from '../../lib/ffmpeg.js';-import { safeChildProcessOptions } from '../../lib/processEnv.js';--// Fixed analysis sample rate. 22.05kHz retains the 40Hz–8kHz spectral bands-// used for onset work and halves the sample count vs 44.1kHz. Mono — beat-// structure is shared across channels.-export const ANALYSIS_SAMPLE_RATE = 22050;--// Cap how much of a track ffmpeg decodes (issue #8973). decodeAudioToPcm-// buffers the whole decoded f32 PCM stream in memory before this module runs-// tempo/section analysis on it — unbounded, a 20+ minute track can push a-// single decode into the hundreds of MB, doubling briefly at the-// Buffer.concat below. Tempo/section analysis doesn't need the full track:-// TEMPO_WINDOW_SEC-scale windows already assume a fraction of it is enough,-// and five minutes gives the section segmentation (MAX_SECTIONS sections,-// MIN_SECTION_SEC apart) far more material than it uses. Passing `-t` lets-// ffmpeg truncate the decode itself instead of PortOS buffering (and then-// discarding) the rest of the stream.-export const MAX_ANALYSIS_SEC = 300;--// Frame hop for the onset envelope. 512 samples @ 22.05kHz → ~43 frames/sec,-// which gives ~1 BPM tempo resolution across the musical range and ~23ms beat-// placement granularity — both well within what beat-snapping needs.-export const ONSET_HOP = 512;--// Tempo search window. Most music sits here; clamping the search keeps the-// autocorrelation from latching onto sub-bass rumble (very low BPM) or-// per-note flutter (very high BPM). Half/double-time octave errors inside this-// range are handled by the tempo-preference weighting below.-const MIN_BPM = 70;-const MAX_BPM = 180;-// Log-normal tempo preference centered here disambiguates octave errors (60 vs-// 120 vs 240) — the classic Davies/Plumbley bias toward a "natural" tempo.-const PREFERRED_BPM = 120;-const TEMPO_PREF_SIGMA = 0.9; // in octaves+import {+ ANALYSIS_SAMPLE_RATE,+ MAX_ANALYSIS_SEC,+ ONSET_HOP,+ FFT_SIZE,+ hannWindow,+ fftPlan,+ fftInPlace,+ decodeAudioToPcm,+ onsetEnvelope,+ estimateTempo,+ fitBeats,+ pickDownbeats,+} from '../../lib/audioBeatDsp.js';++// Re-exported so existing callers/tests keep one import point for the shared+// decode step and constants (the implementations live in lib/audioBeatDsp.js).+export { ANALYSIS_SAMPLE_RATE, MAX_ANALYSIS_SEC, ONSET_HOP, decodeAudioToPcm };// Section segmentation: windows for the coarse energy profile, the minimum// musical span we will call a "section", and a cap so a noisy track doesn't@@ -69,401 +51,7 @@ const SECTION_WINDOW_SEC = 0.5;const MIN_SECTION_SEC = 8;const MAX_SECTIONS = 8;-// Minimum normalized autocorrelation peak (`ac[lag] / ac[0]`) to accept a-// tempo. Below this the "peak" is just the strongest lag of essentially-// structureless audio (white noise, near-silence) — reporting a confident BPM-// there is worse than reporting none. Clean periodic input sits well above it-// (click tracks measure 0.4–0.9); white noise measures ~0.23.-const TEMPO_PEAK_MIN = 0.3;-// A song-wide autocorrelation can be diluted by a long rubato/ambient intro-// even when the body of the song has a stable pulse. Scan overlapping musical-// windows as a fallback and require two agreeing windows before accepting their-// tempo, so one coincidental noise peak cannot invent a beat grid.-const TEMPO_WINDOW_SEC = 30;-const TEMPO_WINDOW_STEP_SEC = 15;-const TEMPO_WINDOW_AGREEMENT = 0.04;const WAVEFORM_POINTS = 512;-const FFT_SIZE = 1024;--// Hann window cached per length. Windowing each analysis frame before measuring-// energy suppresses the spectral-leakage ripple a steady tone otherwise beats-// against the frame grid — without it, a sustained pure tone produces a periodic-// onset envelope and a confident-but-bogus tempo. Broadband transients (the-// actual beats) survive windowing, so click/percussion detection is unaffected.-const hannCache = new Map();-const hannWindow = (len) => {- let w = hannCache.get(len);- if (w) return w;- w = new Float32Array(len);- for (let i = 0; i < len; i++) w[i] = 0.5 * (1 - Math.cos((2 * Math.PI * i) / (len - 1)));- hannCache.set(len, w);- return w;-};--const fftPlanCache = new Map();-const fftPlan = (size) => {- let plan = fftPlanCache.get(size);- if (plan) return plan;- const reverse = new Uint32Array(size);- const bits = Math.log2(size);- for (let i = 0; i < size; i++) {- let x = i;- let r = 0;- for (let bit = 0; bit < bits; bit++) { r = (r << 1) | (x & 1); x >>= 1; }- reverse[i] = r;- }- const cos = new Float64Array(size / 2);- const sin = new Float64Array(size / 2);- for (let i = 0; i < size / 2; i++) {- const angle = (-2 * Math.PI * i) / size;- cos[i] = Math.cos(angle);- sin[i] = Math.sin(angle);- }- plan = { reverse, cos, sin };- fftPlanCache.set(size, plan);- return plan;-};--function fftInPlace(real, imaginary, plan) {- const n = real.length;- for (let i = 0; i < n; i++) {- const j = plan.reverse[i];- if (j <= i) continue;- [real[i], real[j]] = [real[j], real[i]];- [imaginary[i], imaginary[j]] = [imaginary[j], imaginary[i]];- }- for (let size = 2; size <= n; size *= 2) {- const half = size / 2;- const twiddleStep = n / size;- for (let start = 0; start < n; start += size) {- for (let offset = 0; offset < half; offset++) {- const twiddle = offset * twiddleStep;- const even = start + offset;- const odd = even + half;- const oddReal = real[odd] * plan.cos[twiddle] - imaginary[odd] * plan.sin[twiddle];- const oddImaginary = real[odd] * plan.sin[twiddle] + imaginary[odd] * plan.cos[twiddle];- real[odd] = real[even] - oddReal;- imaginary[odd] = imaginary[even] - oddImaginary;- real[even] += oddReal;- imaginary[even] += oddImaginary;- }- }- }-}--/**- * Decode an audio file to a mono Float32Array at ANALYSIS_SAMPLE_RATE via- * ffmpeg. Returns `{ samples, sampleRate }` on success, or `null` when ffmpeg- * is unavailable or the decode fails — callers treat `null` as "couldn't- * analyze" rather than throwing (this runs outside the request lifecycle when- * driven by the render queue).- *- * Decodes at most MAX_ANALYSIS_SEC seconds of the source (see its doc- * comment) — a track longer than the cap gets tempo/section data from that- * leading window only.- *- * @param {string} audioPath absolute path to the source audio- * @param {{ signal?: AbortSignal, maxDurationSec?: number }} [opts]- * `maxDurationSec` overrides MAX_ANALYSIS_SEC — a test-only seam so the- * truncation path can be exercised against a short fixture rather than a- * real multi-minute file; real callers should not pass it. Clamped to- * MAX_ANALYSIS_SEC — it can only shrink the decode window, never grow it,- * so it can't be used to defeat the memory bound.- * @returns {Promise<{ samples: Float32Array, sampleRate: number } | null>}- */-export async function decodeAudioToPcm(audioPath, { signal, maxDurationSec = MAX_ANALYSIS_SEC } = {}) {- if (typeof audioPath !== 'string' || !audioPath) return null;- // A listener added to an already-aborted signal never fires, so without this- // guard a pre-cancelled request (plausible off the request lifecycle, under a- // render queue) would still spawn ffmpeg and decode the whole track.- if (signal?.aborted) return null;- const ffmpeg = await findFfmpeg();- if (!ffmpeg) return null;- // Re-check: the signal may have aborted while findFfmpeg() was awaiting, so- // the listener below would again attach to an already-aborted signal.- if (signal?.aborted) return null;-- const boundedDurationSec = Number.isFinite(maxDurationSec) && maxDurationSec > 0- ? Math.min(maxDurationSec, MAX_ANALYSIS_SEC)- : MAX_ANALYSIS_SEC;-- return new Promise((resolve) => {- const args = [- '-v', 'error',- '-i', audioPath,- '-t', String(boundedDurationSec),- '-ac', '1',- '-ar', String(ANALYSIS_SAMPLE_RATE),- '-f', 'f32le',- '-acodec', 'pcm_f32le',- 'pipe:1',- ];- const proc = spawn(ffmpeg, args, safeChildProcessOptions({ stdio: ['ignore', 'pipe', 'ignore'] }));- const chunks = [];- let onAbort = null;- if (signal) {- onAbort = () => proc.kill('SIGTERM');- signal.addEventListener('abort', onAbort, { once: true });- }- const cleanup = () => { if (signal && onAbort) signal.removeEventListener('abort', onAbort); };-- proc.stdout.on('data', (c) => chunks.push(c));- proc.on('error', () => { cleanup(); resolve(null); });- proc.on('close', (code, sig) => {- cleanup();- if (sig || code !== 0 || chunks.length === 0) { resolve(null); return; }- const buf = Buffer.concat(chunks);- // Float32Array view over the decoded bytes. Guard the byte length down to- // a multiple of 4 so a truncated final chunk can't throw on construction.- const floats = Math.floor(buf.length / 4);- if (floats === 0) { resolve(null); return; }- // A view is O(1) (no per-sample copy), but Float32Array requires the byte- // offset to be 4-aligned. Buffer.concat returns an unpooled buffer- // (offset 0) for the multi-KB PCM we get here, so the view path is the- // normal case; fall back to a copied slice if a pooled buffer ever lands- // on a non-aligned offset.- const samples = buf.byteOffset % 4 === 0- ? new Float32Array(buf.buffer, buf.byteOffset, floats)- : new Float32Array(buf.buffer.slice(buf.byteOffset, buf.byteOffset + floats * 4));- resolve({ samples, sampleRate: ANALYSIS_SAMPLE_RATE });- });- });-}--/**- * Compute a per-frame onset-strength envelope from spectral flux. Unlike a- * single loudness difference, positive changes across FFT bands capture guitar- * strums and harmonic attacks even when the song's overall volume is steady.- * A local adaptive floor suppresses broadband noise and room tone. Raw RMS- * energy is returned alongside it for section segmentation and the waveform.- */-function onsetEnvelope(samples, sampleRate, hop = ONSET_HOP) {- const fftSize = FFT_SIZE;- const frameCount = Math.max(0, Math.floor((samples.length - fftSize) / hop) + 1);- const energy = new Float32Array(frameCount);- const rawFlux = new Float32Array(frameCount);- const win = hannWindow(fftSize);- const plan = fftPlan(fftSize);- const real = new Float64Array(fftSize);- const imaginary = new Float64Array(fftSize);- const previous = new Float64Array(fftSize / 2);- const minBin = Math.max(1, Math.floor((40 * fftSize) / sampleRate));- const maxBin = Math.min(fftSize / 2 - 1, Math.ceil((8000 * fftSize) / sampleRate));- for (let f = 0; f < frameCount; f++) {- let sum = 0;- const base = f * hop;- for (let i = 0; i < fftSize; i++) {- const sample = samples[base + i];- sum += sample * sample;- real[i] = sample * win[i];- imaginary[i] = 0;- }- energy[f] = Math.sqrt(sum / fftSize);- fftInPlace(real, imaginary, plan);- let flux = 0;- for (let bin = minBin; bin <= maxBin; bin++) {- const magnitude = Math.log1p(Math.sqrt(real[bin] * real[bin] + imaginary[bin] * imaginary[bin]));- const rise = magnitude - previous[bin];- if (rise > 0) flux += rise;- previous[bin] = magnitude;- }- rawFlux[f] = flux / (maxBin - minBin + 1);- }-- // Subtract a rolling ~0.75s local mean. A real note/percussion attack rises- // above its neighborhood; stationary noise fluctuates around the floor.- const onset = new Float32Array(frameCount);- const radius = Math.max(1, Math.round((0.75 * sampleRate) / hop / 2));- let rolling = 0;- let left = 0;- let right = 0;- for (let f = 0; f < frameCount; f++) {- while (right < frameCount && right <= f + radius) { rolling += rawFlux[right]; right += 1; }- while (left < f - radius) { rolling -= rawFlux[left]; left += 1; }- const localMean = rolling / Math.max(1, right - left);- onset[f] = Math.max(0, rawFlux[f] - localMean);- }- return { onset, energy, fps: sampleRate / hop, frameCount };-}--// Fractional-lag step (frames) for the tempo autocorrelation scan. Scanning the-// period continuously instead of at integer lags is what makes the estimate-// robust: a true beat period of, say, 18.46 frames lands between integer lags,-// so integer-lag autocorrelation smears its peak across lags 18 and 19 (each-// weakened) while the sharper half-tempo lag wins — the classic half-tempo-// octave error. Interpolating at 0.25-frame resolution recovers the full-// fundamental peak, so both the significance gate and the octave fold judge it-// fairly.-const TEMPO_LAG_STEP = 0.25;--/**- * Estimate tempo (BPM) and the beat period (in fractional frames) by- * tempo-weighted, sub-frame autocorrelation of the onset envelope. The envelope- * is zero-meaned first so the silence floor between hits doesn't bias the- * correlation toward a DC peak. Returns `{ bpm: null, lag: null }` when the- * envelope carries no usable periodicity (silence, or structureless input whose- * strongest peak is below the significance floor).- */-function estimateTempoCandidate(onset, fps) {- const n = onset.length;- if (n < 4) return null;- let mean = 0;- for (let i = 0; i < n; i++) mean += onset[i];- mean /= n;- const o = new Float32Array(n);- let variance = 0;- for (let i = 0; i < n; i++) { o[i] = onset[i] - mean; variance += o[i] * o[i]; }- if (variance <= 1e-9) return null;-- // Autocorrelation at a fractional lag via linear interpolation of the shifted- // envelope. `variance` is the zero-lag value (ac(0) = sum of squares).- const acFrac = (lag) => {- const lo = Math.floor(lag);- const frac = lag - lo;- let sum = 0;- for (let i = 0; i + lo + 1 < n; i++) {- sum += o[i] * (o[i + lo] * (1 - frac) + o[i + lo + 1] * frac);- }- return sum;- };-- const minLag = Math.max(1, (60 * fps) / MAX_BPM);- const maxLag = Math.min(n - 2, (60 * fps) / MIN_BPM);- let bestLag = -1;- let bestScore = -Infinity;- let bestAc = 0;- for (let lag = minLag; lag <= maxLag; lag += TEMPO_LAG_STEP) {- const ac = acFrac(lag);- const bpm = (60 * fps) / lag;- const octaves = Math.log2(bpm / PREFERRED_BPM);- const weight = Math.exp(-0.5 * (octaves / TEMPO_PREF_SIGMA) ** 2);- const score = ac * weight;- if (score > bestScore) { bestScore = score; bestLag = lag; bestAc = ac; }- }- if (bestLag < 0 || bestScore <= 0) return null;-- // NOTE — octave (half/double-tempo) ambiguity is intentionally NOT resolved- // here. Autocorrelation peaks at every multiple of the true period, so the- // estimate is only reliable UP TO an octave: a 140 BPM track may report 70,- // and a phase-aligned-comb tie-break (tried) cannot separate the two for many- // signals (a half-period grid captures comparable onset energy), while the- // tempo-preference weight alone mis-picks other octaves. Robust octave- // selection is a deliberate open question for a later phase (see #1760- // "beat-snap semantics") — beat snapping still works off this grid, just at a- // possibly-doubled/halved density. The detected period is the- // highest-weighted autocorrelation peak in [MIN_BPM, MAX_BPM].- const bpm = (60 * fps) / bestLag;- return { bpm, lag: bestLag, confidence: bestAc / variance };-}--const temposAgree = (a, b) => {- const octaveDistance = Math.abs(Math.log2(a / b));- return Math.abs(octaveDistance - Math.round(octaveDistance)) <= Math.log2(1 + TEMPO_WINDOW_AGREEMENT);-};--const foldTempoNear = (bpm, anchor) => {- let folded = bpm;- while (folded * 2 <= MAX_BPM && Math.abs(Math.log2((folded * 2) / anchor)) < Math.abs(Math.log2(folded / anchor))) folded *= 2;- while (folded / 2 >= MIN_BPM && Math.abs(Math.log2((folded / 2) / anchor)) < Math.abs(Math.log2(folded / anchor))) folded /= 2;- return folded;-};--function estimateTempo(onset, fps) {- const full = estimateTempoCandidate(onset, fps);- if (full && full.confidence >= TEMPO_PEAK_MIN) {- return {- ...full,- source: 'full',- window: { startSec: 0, endSec: onset.length / fps },- };- }-- const windowFrames = Math.round(TEMPO_WINDOW_SEC * fps);- const stepFrames = Math.round(TEMPO_WINDOW_STEP_SEC * fps);- if (onset.length < windowFrames) return { bpm: null, lag: null, confidence: full?.confidence ?? null, source: null, window: null };-- const candidates = [];- for (let start = 0; start + windowFrames <= onset.length; start += stepFrames) {- const candidate = estimateTempoCandidate(onset.slice(start, start + windowFrames), fps);- if (candidate?.confidence >= TEMPO_PEAK_MIN) {- candidates.push({- ...candidate,- startSec: start / fps,- endSec: (start + windowFrames) / fps,- });- }- }-- const clusters = candidates.map((anchor) => candidates.filter((candidate) => temposAgree(anchor.bpm, candidate.bpm)));- const cluster = clusters- .filter((group) => group.length >= 2)- .sort((a, b) => (- b.reduce((sum, candidate) => sum + candidate.confidence, 0)- - a.reduce((sum, candidate) => sum + candidate.confidence, 0)- ))[0];- if (!cluster) return { bpm: null, lag: null, confidence: full?.confidence ?? null, source: null, window: null };-- const strongest = cluster.slice().sort((a, b) => b.confidence - a.confidence)[0];- const weight = cluster.reduce((sum, candidate) => sum + candidate.confidence, 0);- const bpm = cluster.reduce(- (sum, candidate) => sum + foldTempoNear(candidate.bpm, strongest.bpm) * candidate.confidence,- 0,- ) / weight;- return {- bpm,- lag: (60 * fps) / bpm,- confidence: strongest.confidence,- source: 'windowed',- window: { startSec: strongest.startSec, endSec: strongest.endSec },- };-}--/**- * Fit the beat phase: slide a pulse train of the given period across the onset- * envelope and pick the offset whose pulses sum the most onset strength.- * Returns the beat times (seconds) for the whole track.- */-function fitBeats(onset, fps, bpm, durationSec) {- const periodFrames = (60 * fps) / bpm;- let bestOffset = 0;- let bestSum = -Infinity;- const maxOffset = Math.ceil(periodFrames);- for (let off = 0; off < maxOffset; off++) {- let sum = 0;- for (let pos = off; pos < onset.length; pos += periodFrames) {- sum += onset[Math.round(pos)] || 0;- }- if (sum > bestSum) { bestSum = sum; bestOffset = off; }- }- const beats = [];- for (let pos = bestOffset; pos < onset.length; pos += periodFrames) {- const t = pos / fps;- if (t <= durationSec) beats.push(Number(t.toFixed(3)));- }- return beats;-}--/**- * Pick downbeats assuming 4/4: of the four candidate beat phases, choose the- * one whose beats carry the most onset strength (downbeats are typically the- * loudest). Returns the subset of `beats` on that phase.- */-function pickDownbeats(beats, onset, fps) {- if (beats.length === 0) return [];- const beatsPerBar = 4;- let bestPhase = 0;- let bestSum = -Infinity;- for (let phase = 0; phase < beatsPerBar; phase++) {- let sum = 0;- for (let i = phase; i < beats.length; i += beatsPerBar) {- sum += onset[Math.round(beats[i] * fps)] || 0;- }- if (sum > bestSum) { bestSum = sum; bestPhase = phase; }- }- const downbeats = [];- for (let i = bestPhase; i < beats.length; i += beatsPerBar) downbeats.push(beats[i]);- return downbeats;-}/*** Coarse section map from energy novelty. Builds a windowed energy profile,