Skip to content

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

feat: analyze per-band loudness envelopes and drum onsets as a seekable song feature track (#9073)

[._.]/ Adam Eivy12e86455a76c
diff --git a/client/src/components/musicVideo/AnalysisPanel.jsx b/client/src/components/musicVideo/AnalysisPanel.jsx
index 9db88b5647..d3812ab1d3 100644
--- a/client/src/components/musicVideo/AnalysisPanel.jsx
+++ b/client/src/components/musicVideo/AnalysisPanel.jsx
@@ -3,9 +3,12 @@ import { formatDurationSec } from '../../utils/formatters.js';
/**
* Beat-grid readout for the analyzed track, the "cuts are too long" nudge, and
* the manual-tempo fallback shown when the auto-detector found no BPM.
- * `tempo` is the useMusicVideoManualTempo slot.
+ * `tempo` is the useMusicVideoManualTempo slot. The song feature track (#9073)
+ * is null on analyses cached before it existed — shown as "not analyzed" with a
+ * Re-analyze action, never as zero-energy data.
*/
-export default function AnalysisPanel({ audioAnalysis, scenes, tempo }) {
+export default function AnalysisPanel({ audioAnalysis, scenes, tempo, onReanalyze, analyzing = false }) {
+ const features = audioAnalysis?.features ?? null;
const authoredCutDurations = scenes
.filter((scene) => typeof scene.startSec === 'number' && typeof scene.endSec === 'number' && scene.endSec > scene.startSec)
.map((scene) => scene.endSec - scene.startSec);
@@ -24,6 +27,29 @@ export default function AnalysisPanel({ audioAnalysis, scenes, tempo }) {
{averageCutSec != null && <span>Average cut: {averageCutSec.toFixed(1)}s</span>}
</div>
)}
+ {audioAnalysis && (
+ <div data-testid="song-features" className="text-xs text-port-text-muted mt-1 flex flex-wrap items-center gap-x-4 gap-y-1">
+ {features ? (
+ <>
+ <span>Song features: {features.onsets.low.length} kick-ish · {features.onsets.mid.length} snare-ish · {features.onsets.high.length} hat-ish hits</span>
+ {features.truncatedAtSec != null && (
+ <span className="text-port-warning">Covers the first {formatDurationSec(features.truncatedAtSec)} only</span>
+ )}
+ </>
+ ) : (
+ <>
+ <span>Song features (loudness bands, drum hits): not analyzed</span>
+ {onReanalyze && (
+ <button type="button" onClick={onReanalyze} disabled={analyzing}
+ title="Re-runs the offline analysis, including tempo detection (replaces a manually set tempo)"
+ className="bg-port-card border border-port-border rounded px-2 py-1 min-h-[32px] hover:bg-port-border/40 disabled:opacity-50">
+ {analyzing ? 'Analyzing…' : 'Re-analyze'}
+ </button>
+ )}
+ </>
+ )}
+ </div>
+ )}
{longCutCount > 0 && (
<p className="mt-2 rounded border border-port-warning/40 bg-port-warning/10 px-2 py-1.5 text-xs text-port-warning">
{longCutCount} authored cut{longCutCount === 1 ? ' is' : 's are'} longer than 10s.
diff --git a/client/src/components/musicVideo/AnalysisPanel.test.jsx b/client/src/components/musicVideo/AnalysisPanel.test.jsx
new file mode 100644
index 0000000000..13ffec9e06
--- /dev/null
+++ b/client/src/components/musicVideo/AnalysisPanel.test.jsx
@@ -0,0 +1,29 @@
+import { describe, it, expect, vi } from 'vitest';
+import { render, screen, fireEvent } from '@testing-library/react';
+import AnalysisPanel from './AnalysisPanel.jsx';
+
+const BASE = { bpm: 120, beats: [0, 0.5], downbeats: [0], sections: [], durationSec: 30 };
+const TEMPO = { bpm: '', offset: '0', setBpm: vi.fn(), setOffset: vi.fn(), tap: vi.fn(), submit: vi.fn(), saving: false };
+
+describe('AnalysisPanel song features (#9073)', () => {
+ it('offers Re-analyze, and shows no hit counts, for an analysis cached without a feature track', () => {
+ const onReanalyze = vi.fn();
+ render(<AnalysisPanel audioAnalysis={BASE} scenes={[]} tempo={TEMPO} onReanalyze={onReanalyze} />);
+ expect(screen.getByText(/not analyzed/)).toBeTruthy();
+ expect(screen.queryByText(/kick-ish/)).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'Re-analyze' }));
+ expect(onReanalyze).toHaveBeenCalledTimes(1);
+ });
+
+ it('summarizes onsets and flags a truncated feature track', () => {
+ const features = {
+ envelopes: { fps: 30, rms: [0], low: [0], mid: [0], high: [0] },
+ onsets: { low: [0.5, 1], mid: [0.75], high: [] },
+ truncatedAtSec: 300,
+ };
+ render(<AnalysisPanel audioAnalysis={{ ...BASE, features }} scenes={[]} tempo={TEMPO} onReanalyze={vi.fn()} />);
+ expect(screen.getByText(/2 kick-ish · 1 snare-ish · 0 hat-ish/)).toBeTruthy();
+ expect(screen.getByText(/Covers the first/)).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'Re-analyze' })).toBeNull();
+ });
+});
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index b97e387eb7..4c843c6a20 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -855,6 +855,8 @@ export default function MusicVideo() {
audioAnalysis={selected.audioAnalysis}
scenes={selected.scenes || []}
tempo={tempo}
+ onReanalyze={handleAnalyze}
+ analyzing={analyzing}
/>
</div>
diff --git a/docs/HTML_COMPOSITIONS.md b/docs/HTML_COMPOSITIONS.md
index 7c0f2e83e4..4d5eb51497 100644
--- a/docs/HTML_COMPOSITIONS.md
+++ b/docs/HTML_COMPOSITIONS.md
@@ -132,6 +132,11 @@ helper script for compositions. Copy it beside `index.html`, load it with
motion-blur shutter; key per-frame flicker to it.
- `rng(seed)` — seeded noise (mulberry32); never use `Math.random`.
- `beats(bpm)` — a beat grid (`at`, `bar`, `index`, `phase`, `list`).
+- `song(audioAnalysis)` — seekable song lookups from a music-video project's
+ analysis JSON: `env('rms'|'low'|'mid'|'high', t)` (interpolated 0..1),
+ `hit('kick'|'snare'|'hat', t, halfLife)` (decaying pulses from past onsets;
+ band heuristics, not stems), `beatAt`, `barAt`, `beatPhase`, `sectionAt`.
+ `ready` is false when the analysis has no feature track (re-analyze).
- `renderCues({ sampleRate, durationSec, cues })`, `mixCues`, `toPcm` —
synthesized `click`, `tick`, `pop`, `thump`, `whoosh` and `riser` cues
that return the plain PCM array `renderAudio` needs.
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index c4cdd5c2fe..36c555881f 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -638,7 +638,33 @@ export const musicVideoMidiTranscriptionSchema = z.object({
// The cached beat/tempo/section map (audioAnalysis.js output). Validated when a
// record round-trips so a hand-edited/legacy project can't carry a malformed
// analysis; the analyzer itself produces this shape.
+// Per-band loudness envelopes (0..1 on a fixed fps grid) and onset times for
+// the seekable song feature track (#9073). `null`/absent means "not analyzed"
+// (an analysis cached before the feature track existed); an empty array is
+// never used as that sentinel.
+const envelopeSeriesSchema = z.array(z.number().min(0).max(1)).max(200000);
+const onsetTimesSchema = z.array(z.number().min(0)).max(100000);
+export const musicVideoSongFeaturesSchema = z.object({
+ envelopes: z.object({
+ fps: z.number().positive(),
+ rms: envelopeSeriesSchema,
+ low: envelopeSeriesSchema,
+ mid: envelopeSeriesSchema,
+ high: envelopeSeriesSchema,
+ }).strict(),
+ onsets: z.object({
+ low: onsetTimesSchema,
+ mid: onsetTimesSchema,
+ high: onsetTimesSchema,
+ }).strict(),
+ // Set when the decode was capped, so the tracks stop before the song does.
+ truncatedAtSec: z.number().min(0).nullable().optional(),
+}).strict();
+
export const musicVideoAudioAnalysisSchema = z.object({
+ // Shape version: absent = 1 (pre feature track), 2 = carries `features`.
+ version: z.number().int().min(1).optional(),
+ features: musicVideoSongFeaturesSchema.nullable().optional(),
bpm: z.number().nullable(),
beats: z.array(z.number()),
downbeats: z.array(z.number()),
diff --git a/server/services/htmlComposition/kit/portos-motion.js b/server/services/htmlComposition/kit/portos-motion.js
index 10e6cbb543..22496f89dc 100644
--- a/server/services/htmlComposition/kit/portos-motion.js
+++ b/server/services/htmlComposition/kit/portos-motion.js
@@ -103,6 +103,93 @@
});
}
+ // Index of the last entry of a sorted array that is <= t, or -1.
+ function lastAtOrBefore(sorted, t) {
+ let lo = 0;
+ let hi = sorted.length - 1;
+ let found = -1;
+ while (lo <= hi) {
+ const mid = (lo + hi) >> 1;
+ if (sorted[mid] <= t) { found = mid; lo = mid + 1; } else hi = mid - 1;
+ }
+ return found;
+ }
+
+ // Loud-band aliases for the onset lists: "kick-ish", "snare-ish", "hat-ish".
+ // Frequency-band heuristics, not stem separation.
+ const HIT_BANDS = Object.freeze({ kick: 'low', snare: 'mid', hat: 'high', low: 'low', mid: 'mid', high: 'high' });
+
+ // Pure lookups over a song's analysis JSON (the project's `audioAnalysis`),
+ // so a scrubbed or re-rendered frame reads exactly the same values: nothing
+ // here holds state or listens to audio. `data.features` may be null (analysis
+ // predates the feature track); `ready` says so and env/hit then return 0.
+ function song(data = {}) {
+ const features = data && data.features;
+ const envelopes = features && features.envelopes;
+ const onsets = (features && features.onsets) || {};
+ const fps = envelopes && envelopes.fps > 0 ? envelopes.fps : 0;
+ const beatTimes = (data && data.beats) || [];
+ const barTimes = (data && data.downbeats) || [];
+ const sections = (data && data.sections) || [];
+
+ // Envelope value at time t: linear between frames, 0 outside the covered span.
+ function env(name, t) {
+ const series = envelopes && envelopes[name];
+ if (!series || !series.length || t < 0) return 0;
+ const pos = t * fps;
+ const i = Math.floor(pos);
+ if (i >= series.length) return 0;
+ const a = series[i];
+ const b = i + 1 < series.length ? series[i + 1] : a;
+ return a + (b - a) * (pos - i);
+ }
+
+ // Decaying pulse: each onset at or before t contributes 0.5 ** (age / halfLife).
+ // Sums are capped at 12 half-lives back, where a pulse is below 0.03%.
+ function hit(kind, t, halfLife = 0.12) {
+ const times = onsets[HIT_BANDS[kind] || kind];
+ if (!times || !times.length || !(halfLife > 0)) return 0;
+ let total = 0;
+ for (let i = lastAtOrBefore(times, t); i >= 0 && t - times[i] <= halfLife * 12; i--) {
+ total += Math.pow(0.5, (t - times[i]) / halfLife);
+ }
+ return total;
+ }
+
+ // Index of the beat (or bar) that started most recently, -1 before the first.
+ const beatAt = (t) => lastAtOrBefore(beatTimes, t);
+ const barAt = (t) => lastAtOrBefore(barTimes, t);
+
+ // 0..1 progress through the current beat. Before the first / after the last
+ // beat the nearest interval is extended so the phase keeps cycling.
+ function beatPhase(t) {
+ const n = beatTimes.length;
+ if (n === 0) return 0;
+ const i = beatAt(t);
+ if (i >= 0 && i < n - 1) return (t - beatTimes[i]) / (beatTimes[i + 1] - beatTimes[i]);
+ const interval = n > 1 ? (i < 0 ? beatTimes[1] - beatTimes[0] : beatTimes[n - 1] - beatTimes[n - 2]) : (data.bpm ? 60 / data.bpm : 0);
+ return interval > 0 ? loopT(t - beatTimes[i < 0 ? 0 : n - 1], interval) / interval : 0;
+ }
+
+ // The section containing t as { index, label, startSec, endSec, energy,
+ // progress } (progress 0..1), or null between/outside sections.
+ function sectionAt(t) {
+ for (let index = 0; index < sections.length; index++) {
+ const section = sections[index];
+ if (t >= section.startSec && t < section.endSec) {
+ return { ...section, index, progress: (t - section.startSec) / (section.endSec - section.startSec) };
+ }
+ }
+ return null;
+ }
+
+ return Object.freeze({
+ ready: !!envelopes,
+ truncatedAtSec: (features && features.truncatedAtSec) ?? null,
+ env, hit, beatAt, barAt, beatPhase, sectionAt,
+ });
+ }
+
// Synthesized UI sound effects: [lengthSec, (localTime, noise) => sample].
const VOICES = Object.freeze({
click: [0.05, (t) => Math.sin(2 * Math.PI * 1800 * t) * Math.exp(-t * 90) * 0.5],
@@ -148,6 +235,6 @@
root.PortosMotion = Object.freeze({
clamp, spring, SPRINGS, preset, track, indicator, swapAlpha, loopT, frameIdx, rng, beats,
- VOICES, mixCues, toPcm, renderCues,
+ VOICES, mixCues, toPcm, renderCues, song,
});
})(globalThis);
diff --git a/server/services/htmlComposition/motionKit.test.js b/server/services/htmlComposition/motionKit.test.js
index 2380211c57..220025afb5 100644
--- a/server/services/htmlComposition/motionKit.test.js
+++ b/server/services/htmlComposition/motionKit.test.js
@@ -31,4 +31,59 @@ describe('PortOS motion kit', () => {
expect(first.every(value => value >= 0 && value < 1)).toBe(true);
expect(rng(8)()).not.toBe(first[0]);
});
+
+ describe('song()', () => {
+ const analysis = {
+ bpm: 120,
+ beats: [0.5, 1, 1.5, 2],
+ downbeats: [0.5, 2.5],
+ sections: [{ label: 'a', startSec: 0, endSec: 1, energy: 0.2 }, { label: 'b', startSec: 1, endSec: 3, energy: 0.9 }],
+ features: {
+ envelopes: { fps: 10, rms: [0, 0.5, 1], low: [0, 1, 0], mid: [0.2, 0.2, 0.2], high: [0, 0, 0] },
+ onsets: { low: [0.5, 1], mid: [0.75], high: [] },
+ truncatedAtSec: null,
+ },
+ };
+ const song = globalThis.PortosMotion.song(analysis);
+
+ it('returns identical values for the same t regardless of query order', () => {
+ const times = Array.from({ length: 40 }, (_, i) => i * 0.0625 - 0.2);
+ const read = (t) => [song.env('low', t), song.hit('kick', t), song.hit('snare', t, 0.3), song.beatAt(t), song.beatPhase(t), song.barAt(t)];
+ const forward = times.map(read);
+ const order = times.map((_, i) => i).sort((a, b) => ((a * 7) % 13) - ((b * 7) % 13));
+ const shuffled = [];
+ for (const i of order) shuffled[i] = read(times[i]);
+ expect(shuffled).toEqual(forward);
+ });
+
+ it('interpolates envelopes, decays hit pulses from past onsets only, and reads 0 outside the song', () => {
+ expect(song.env('low', 0.05)).toBeCloseTo(0.5, 6);
+ expect(song.env('low', 0.1)).toBeCloseTo(1, 6);
+ expect(song.env('low', -1)).toBe(0);
+ expect(song.env('low', 5)).toBe(0);
+ expect(song.hit('kick', 0.49)).toBe(0); // before any onset
+ expect(song.hit('kick', 0.5)).toBeCloseTo(1, 6);
+ expect(song.hit('kick', 0.62, 0.12)).toBeCloseTo(0.5, 6);
+ expect(song.hit('low', 1.0, 0.12)).toBeCloseTo(1 + 0.5 ** (0.5 / 0.12), 6);
+ expect(song.hit('hat', 1)).toBe(0);
+ });
+
+ it('locates beat, bar, phase and section', () => {
+ expect(song.beatAt(0.4)).toBe(-1);
+ expect(song.beatAt(1.25)).toBe(1);
+ expect(song.barAt(2.6)).toBe(1);
+ expect(song.beatPhase(1.25)).toBeCloseTo(0.5, 6);
+ expect(song.beatPhase(0.25)).toBeCloseTo(0.5, 6); // extends the first interval backwards
+ expect(song.sectionAt(1.5)).toMatchObject({ index: 1, label: 'b', progress: 0.25 });
+ expect(song.sectionAt(9)).toBeNull();
+ });
+
+ it('is not ready, and reads as silence, when the analysis has no feature track', () => {
+ const legacy = globalThis.PortosMotion.song({ bpm: 120, beats: [0], features: null });
+ expect(legacy.ready).toBe(false);
+ expect(legacy.env('low', 1)).toBe(0);
+ expect(legacy.hit('kick', 1)).toBe(0);
+ expect(song.ready).toBe(true);
+ });
+ });
});
diff --git a/server/services/musicVideo/audioAnalysis.js b/server/services/musicVideo/audioAnalysis.js
index a5395370cc..a3df54cfcb 100644
--- a/server/services/musicVideo/audioAnalysis.js
+++ b/server/services/musicVideo/audioAnalysis.js
@@ -590,23 +590,196 @@ function deriveSections(samples, sampleRate, hop) {
return { sections, waveform: summarizeWaveform(energy), onset, fps };
}
+// --- Song feature track (#9073) ----------------------------------------------
+//
+// Per-band loudness envelopes plus per-band onset times, so a code-rendered
+// scene can swell with the bass or flash on a snare-ish hit at any time `t`
+// without analysing audio live (live analysis is neither deterministic nor
+// available in an offline render). Computed once from the same decoded PCM.
+//
+// Bands are fixed FFT-bin splits, not stem separation: "low" is kick/bass-ish,
+// "mid" is snare/body-ish and "high" is hat/air-ish.
+
+// Persisted audioAnalysis shape version. A cached analysis without `version`
+// predates the feature track (implicitly 1) and reads as "features not analyzed".
+export const ANALYSIS_VERSION = 2;
+
+export const FEATURE_ENVELOPE_FPS = 30;
+export const FEATURE_BANDS = Object.freeze({
+ low: [40, 250],
+ mid: [250, 2000],
+ high: [2000, 10000],
+});
+const FEATURE_ONSET_HOP = 256; // ~11.6ms: finer than the 30fps envelope so onset times stay tight
+const FEATURE_CEILING_PERCENTILE = 0.95;
+const ONSET_SMOOTH_SEC = 0.5; // rolling-mean floor subtracted from band flux
+const ONSET_PEAK_RADIUS_SEC = 0.04; // a pick must be the local maximum within this span
+const ONSET_MIN_GAP_SEC = 0.08;
+const ONSET_STD_FACTOR = 1.5;
+const ONSET_MAX_RELATIVE_FLOOR = 0.2; // ignore picks under this fraction of the band's strongest flux
+const ONSET_ABS_FLOOR = 0.02; // mean log-magnitude rise per bin; below this is numerical noise
+
+const bandBins = (sampleRate) => Object.entries(FEATURE_BANDS).map(([name, [loHz, hiHz]]) => ({
+ name,
+ lo: Math.max(1, Math.ceil((loHz * FFT_SIZE) / sampleRate)),
+ hi: Math.min(FFT_SIZE / 2 - 1, Math.floor((hiHz * FFT_SIZE) / sampleRate)),
+}));
+
+/**
+ * Windowed STFT reduced to per-band values. Frames are centred on `f * hop`
+ * (out-of-range samples read as silence) so frame f describes time f*hop/rate.
+ * Returns per frame: `rms` (time-domain), per-band amplitude, and per-band
+ * spectral flux (mean positive rise of log-magnitude across the band's bins).
+ */
+function bandFrames(samples, sampleRate, hop) {
+ const frameCount = Math.floor(samples.length / hop) + 1;
+ const bands = bandBins(sampleRate);
+ const rms = new Float32Array(frameCount);
+ const amp = Object.fromEntries(bands.map(({ name }) => [name, new Float32Array(frameCount)]));
+ const flux = Object.fromEntries(bands.map(({ name }) => [name, new Float32Array(frameCount)]));
+ const win = hannWindow(FFT_SIZE);
+ const plan = fftPlan(FFT_SIZE);
+ const real = new Float64Array(FFT_SIZE);
+ const imaginary = new Float64Array(FFT_SIZE);
+ const previous = new Float64Array(FFT_SIZE / 2);
+ const half = FFT_SIZE / 2;
+ for (let f = 0; f < frameCount; f++) {
+ const base = f * hop - half;
+ let sum = 0;
+ for (let i = 0; i < FFT_SIZE; i++) {
+ const idx = base + i;
+ const sample = idx >= 0 && idx < samples.length ? samples[idx] : 0;
+ sum += sample * sample;
+ real[i] = sample * win[i];
+ imaginary[i] = 0;
+ }
+ rms[f] = Math.sqrt(sum / FFT_SIZE);
+ fftInPlace(real, imaginary, plan);
+ for (const { name, lo, hi } of bands) {
+ let power = 0;
+ let rise = 0;
+ for (let bin = lo; bin <= hi; bin++) {
+ const magnitude = Math.sqrt(real[bin] * real[bin] + imaginary[bin] * imaginary[bin]);
+ power += magnitude * magnitude;
+ const logMag = Math.log1p(magnitude);
+ const delta = logMag - previous[bin];
+ if (delta > 0) rise += delta;
+ previous[bin] = logMag;
+ }
+ const count = hi - lo + 1;
+ amp[name][f] = Math.sqrt(power / count) / FFT_SIZE;
+ flux[name][f] = rise / count;
+ }
+ }
+ return { rms, amp, flux };
+}
+
+// Scale to 0..1 against a percentile ceiling (one loud peak must not flatten
+// everything else). A silent series stays all zeros.
+function normalizeToPercentile(values) {
+ const ranked = Float32Array.from(values).sort();
+ const ceiling = ranked.length ? ranked[Math.min(ranked.length - 1, Math.floor(ranked.length * FEATURE_CEILING_PERCENTILE))] : 0;
+ return Array.from(values, (v) => (ceiling <= 1e-9 ? 0 : Number(Math.min(1, v / ceiling).toFixed(3))));
+}
+
+// Peak-pick one band's flux into onset times (seconds).
+function pickBandOnsets(fluxSeries, hopSec) {
+ const n = fluxSeries.length;
+ if (n < 3) return [];
+ // Subtract a rolling mean so sustained/noisy passages don't read as attacks.
+ const radius = Math.max(1, Math.round(ONSET_SMOOTH_SEC / hopSec / 2));
+ const onset = new Float32Array(n);
+ let rolling = 0;
+ let left = 0;
+ let right = 0;
+ for (let f = 0; f < n; f++) {
+ while (right < n && right <= f + radius) { rolling += fluxSeries[right]; right += 1; }
+ while (left < f - radius) { rolling -= fluxSeries[left]; left += 1; }
+ onset[f] = Math.max(0, fluxSeries[f] - rolling / Math.max(1, right - left));
+ }
+ let mean = 0;
+ let max = 0;
+ for (let f = 0; f < n; f++) { mean += onset[f]; if (onset[f] > max) max = onset[f]; }
+ mean /= n;
+ let variance = 0;
+ for (let f = 0; f < n; f++) variance += (onset[f] - mean) ** 2;
+ const threshold = Math.max(ONSET_ABS_FLOOR, ONSET_MAX_RELATIVE_FLOOR * max, mean + ONSET_STD_FACTOR * Math.sqrt(variance / n));
+ const peakRadius = Math.max(1, Math.round(ONSET_PEAK_RADIUS_SEC / hopSec));
+ const minGap = Math.max(1, Math.round(ONSET_MIN_GAP_SEC / hopSec));
+ const picks = [];
+ for (let f = 0; f < n; f++) {
+ const value = onset[f];
+ if (value < threshold) continue;
+ let isPeak = true;
+ for (let k = Math.max(0, f - peakRadius); k <= Math.min(n - 1, f + peakRadius); k++) {
+ // Strictly greater to the left, >= to the right: a plateau yields one pick.
+ if (k < f ? onset[k] >= value : onset[k] > value) { isPeak = false; break; }
+ }
+ if (!isPeak) continue;
+ const last = picks[picks.length - 1];
+ if (last != null && f - last < minGap) {
+ if (value > onset[last]) picks[picks.length - 1] = f;
+ continue;
+ }
+ picks.push(f);
+ }
+ return picks.map((f) => Number((f * hopSec).toFixed(3)));
+}
+
+/**
+ * Pure DSP: per-band loudness envelopes (~30fps grid, 0..1 per song with a
+ * 95th-percentile ceiling) and per-band onset times. Returns `null` when the
+ * audio is too short to analyse — never empty arrays, so "not analysed" and
+ * "analysed, silent" cannot be confused. `envelopes.fps` is the exact frame
+ * rate (sampleRate / integer hop); frame i is centred on i / fps seconds.
+ *
+ * @param {Float32Array} samples mono PCM
+ * @param {number} sampleRate
+ * @param {{ truncatedAtSec?: number|null }} [opts] set when the decode was cut short
+ */
+export function computeSongFeatures(samples, sampleRate, { truncatedAtSec = null } = {}) {
+ if (!samples || samples.length < FFT_SIZE) return null;
+ const envHop = Math.round(sampleRate / FEATURE_ENVELOPE_FPS);
+ const env = bandFrames(samples, sampleRate, envHop);
+ const flux = bandFrames(samples, sampleRate, FEATURE_ONSET_HOP).flux;
+ const onsetHopSec = FEATURE_ONSET_HOP / sampleRate;
+ return {
+ envelopes: {
+ fps: Number((sampleRate / envHop).toFixed(4)),
+ rms: normalizeToPercentile(env.rms),
+ low: normalizeToPercentile(env.amp.low),
+ mid: normalizeToPercentile(env.amp.mid),
+ high: normalizeToPercentile(env.amp.high),
+ },
+ onsets: {
+ low: pickBandOnsets(flux.low, onsetHopSec),
+ mid: pickBandOnsets(flux.mid, onsetHopSec),
+ high: pickBandOnsets(flux.high, onsetHopSec),
+ },
+ truncatedAtSec: truncatedAtSec == null ? null : Number(truncatedAtSec.toFixed(3)),
+ };
+}
+
+
/**
* Pure DSP core: analyze a mono PCM buffer and return the `audioAnalysis`
* shape. Deterministic and ffmpeg-free, so it is unit-tested directly.
*
* @param {Float32Array} samples mono PCM
* @param {number} sampleRate
- * @param {{ hop?: number }} [opts]
- * @returns {{ bpm: number|null, beats: number[], downbeats: number[], waveform: number[],
+ * @param {{ hop?: number, truncatedAtSec?: number|null }} [opts]
+ * @returns {{ version: number, features: object|null, bpm: number|null, beats: number[], downbeats: number[], waveform: number[],
* sections: Array<{label:string,startSec:number,endSec:number,energy:number}>,
* durationSec: number }}
*/
-export function analyzePcm(samples, sampleRate, { hop = ONSET_HOP } = {}) {
+export function analyzePcm(samples, sampleRate, { hop = ONSET_HOP, truncatedAtSec = null } = {}) {
const durationSec = samples?.length ? samples.length / sampleRate : 0;
const roundedDuration = Number(durationSec.toFixed(3));
const { sections, waveform, onset, fps } = deriveSections(samples, sampleRate, hop);
if (!onset) {
return {
+ version: ANALYSIS_VERSION,
+ features: null,
bpm: null,
beats: [],
downbeats: [],
@@ -624,6 +797,8 @@ export function analyzePcm(samples, sampleRate, { hop = ONSET_HOP } = {}) {
const beats = roundedBpm == null ? [] : fitBeats(onset, fps, bpm, durationSec);
const downbeats = roundedBpm == null ? [] : pickDownbeats(beats, onset, fps);
return {
+ version: ANALYSIS_VERSION,
+ features: computeSongFeatures(samples, sampleRate, { truncatedAtSec }),
bpm: roundedBpm,
beats,
downbeats,
@@ -638,6 +813,14 @@ export function analyzePcm(samples, sampleRate, { hop = ONSET_HOP } = {}) {
};
}
+// The decode is capped at MAX_ANALYSIS_SEC. A buffer that filled the cap may
+// have been cut off (a track of exactly that length is indistinguishable), so
+// the feature track says how far it covers instead of pretending to be complete.
+const truncatedAtSecFor = ({ samples, sampleRate }) => {
+ const durationSec = samples.length / sampleRate;
+ return durationSec >= MAX_ANALYSIS_SEC - 0.1 ? durationSec : null;
+};
+
/**
* Decode `audioPath` via ffmpeg and run the DSP analysis. Returns the
* `audioAnalysis` shape, or `null` when the file can't be decoded (ffmpeg
@@ -649,7 +832,7 @@ export function analyzePcm(samples, sampleRate, { hop = ONSET_HOP } = {}) {
export async function analyzeAudioFile(audioPath, { signal } = {}) {
const decoded = await decodeAudioToPcm(audioPath, { signal });
if (!decoded) return null;
- return analyzePcm(decoded.samples, decoded.sampleRate);
+ return analyzePcm(decoded.samples, decoded.sampleRate, { truncatedAtSec: truncatedAtSecFor(decoded) });
}
// Manual-tempo fallback (see `estimateTempo`'s TEMPO_PEAK_MIN/MIN_BPM/MAX_BPM
@@ -677,9 +860,12 @@ const manualDownbeats = (beats) => beats.filter((_, i) => i % 4 === 0);
* @param {{ sections: Array, durationSec: number }} cached prior audioAnalysis
* @param {{ bpm: number, offsetSec?: number }} tempo
*/
-export function buildManualAnalysisFromCached({ sections, durationSec, waveform = [] }, { bpm, offsetSec = 0 }) {
+export function buildManualAnalysisFromCached({ sections, durationSec, waveform = [], features = null }, { bpm, offsetSec = 0 }) {
const beats = manualBeatTimes(bpm, offsetSec, durationSec);
return {
+ // A prior analysis without a feature track stays "not analyzed" (null).
+ version: ANALYSIS_VERSION,
+ features,
bpm: Number(bpm.toFixed(2)),
beats,
downbeats: manualDownbeats(beats),
@@ -702,12 +888,14 @@ export function buildManualAnalysisFromCached({ sections, durationSec, waveform
* @param {number} sampleRate
* @param {{ bpm: number, offsetSec?: number, hop?: number }} opts
*/
-export function buildManualAnalysis(samples, sampleRate, { bpm, offsetSec = 0, hop = ONSET_HOP }) {
+export function buildManualAnalysis(samples, sampleRate, { bpm, offsetSec = 0, hop = ONSET_HOP, truncatedAtSec = null }) {
const durationSec = samples?.length ? samples.length / sampleRate : 0;
const roundedDuration = Number(durationSec.toFixed(3));
const beats = manualBeatTimes(bpm, offsetSec, durationSec);
const { sections, waveform } = deriveSections(samples, sampleRate, hop);
return {
+ version: ANALYSIS_VERSION,
+ features: computeSongFeatures(samples, sampleRate, { truncatedAtSec }),
bpm: Number(bpm.toFixed(2)),
beats,
downbeats: manualDownbeats(beats),
@@ -733,7 +921,7 @@ export function buildManualAnalysis(samples, sampleRate, { bpm, offsetSec = 0, h
export async function analyzeAudioFileManual(audioPath, { bpm, offsetSec = 0 }, { signal } = {}) {
const decoded = await decodeAudioToPcm(audioPath, { signal });
if (!decoded) return null;
- return buildManualAnalysis(decoded.samples, decoded.sampleRate, { bpm, offsetSec });
+ return buildManualAnalysis(decoded.samples, decoded.sampleRate, { bpm, offsetSec, truncatedAtSec: truncatedAtSecFor(decoded) });
}
// --- Section → beat-grid snapping (#4664) -----------------------------------
diff --git a/server/services/musicVideo/audioAnalysis.test.js b/server/services/musicVideo/audioAnalysis.test.js
index 24fbe733ae..58d5ffcc62 100644
--- a/server/services/musicVideo/audioAnalysis.test.js
+++ b/server/services/musicVideo/audioAnalysis.test.js
@@ -4,6 +4,8 @@ import { tmpdir } from 'os';
import { join } from 'path';
import {
analyzePcm,
+ computeSongFeatures,
+ ANALYSIS_VERSION,
analyzeAudioFile,
decodeAudioToPcm,
buildManualAnalysis,
@@ -544,3 +546,85 @@ describe('snapSectionsToGrid', () => {
expect(result.beatAligned).toEqual([true, true]);
});
});
+
+describe('computeSongFeatures / analyzePcm feature track (#9073)', () => {
+ const SR = ANALYSIS_SAMPLE_RATE;
+ const HOP_SEC = 1 / 30;
+
+ // (Starts a quarter second in: a hit at sample 0 is an onset from silence in every band.)
+ // A 60Hz thump on every beat plus a noise burst on beats 2 and 4 of each bar.
+ function drumTrack({ bpm = 120, durationSec = 16, offsetSec = 0.25 } = {}) {
+ const out = new Float32Array(Math.round(durationSec * SR));
+ let seed = 99;
+ const rand = () => { seed = (seed * 1103515245 + 12345) & 0x7fffffff; return (seed / 0x7fffffff) * 2 - 1; };
+ const period = 60 / bpm;
+ const kicks = [];
+ const noises = [];
+ for (let beat = 0; offsetSec + beat * period < durationSec - 0.3; beat++) {
+ const t = offsetSec + beat * period;
+ const start = Math.round(t * SR);
+ kicks.push(t);
+ for (let k = 0; k < 0.08 * SR; k++) out[start + k] += 0.8 * Math.exp(-k / (0.03 * SR)) * Math.sin((2 * Math.PI * 60 * k) / SR);
+ if (beat % 2 === 1) {
+ noises.push(t);
+ for (let k = 0; k < 0.04 * SR; k++) out[start + k] += 0.5 * Math.exp(-k / (0.015 * SR)) * rand();
+ }
+ }
+ return { samples: out, kicks, noises };
+ }
+
+ const nearest = (times, t) => Math.min(...times.map((x) => Math.abs(x - t)));
+
+ it('finds low onsets on every beat and mid/high onsets on the noise bursts, each within one hop', () => {
+ const { samples, kicks, noises } = drumTrack();
+ const { features } = analyzePcm(samples, SR);
+ expect(features.onsets.low.length).toBeGreaterThan(0);
+ for (const kick of kicks) expect(nearest(features.onsets.low, kick)).toBeLessThanOrEqual(HOP_SEC);
+ for (const band of ['mid', 'high']) {
+ for (const noise of noises) expect(nearest(features.onsets[band], noise)).toBeLessThanOrEqual(HOP_SEC);
+ // Nothing fires where only the low thump plays (beats 1 and 3).
+ const thumpOnly = kicks.filter((t) => !noises.includes(t));
+ for (const t of thumpOnly) expect(features.onsets[band].every((o) => Math.abs(o - t) > HOP_SEC)).toBe(true);
+ }
+ });
+
+ it('emits normalized 0..1 envelopes on the fixed grid that cover the whole song', () => {
+ const { samples } = drumTrack({ durationSec: 10 });
+ const { features, version } = analyzePcm(samples, SR);
+ const { envelopes } = features;
+ expect(version).toBe(ANALYSIS_VERSION);
+ expect(envelopes.fps).toBeCloseTo(30, 1);
+ for (const name of ['rms', 'low', 'mid', 'high']) {
+ expect(envelopes[name].length).toBeGreaterThanOrEqual(Math.floor(10 * envelopes.fps));
+ expect(Math.min(...envelopes[name])).toBeGreaterThanOrEqual(0);
+ expect(Math.max(...envelopes[name])).toBeLessThanOrEqual(1);
+ }
+ // Bass energy peaks on the thump, not between beats.
+ const at = (t) => envelopes.low[Math.round(t * envelopes.fps)];
+ expect(at(1.27)).toBeGreaterThan(at(1.5) + 0.3);
+ expect(features.truncatedAtSec).toBeNull();
+ });
+
+ it('records where a capped decode stopped rather than returning empty arrays', () => {
+ const { samples } = drumTrack({ durationSec: 4 });
+ const { features } = analyzePcm(samples, SR, { truncatedAtSec: 4 });
+ expect(features.truncatedAtSec).toBe(4);
+ expect(features.envelopes.low.length).toBeGreaterThan(0);
+ });
+
+ it('reports null features (never empty arrays) for audio too short to analyse, and zeros for silence', () => {
+ expect(analyzePcm(new Float32Array(100), SR).features).toBeNull();
+ expect(computeSongFeatures(new Float32Array(SR), SR).envelopes.low.every((v) => v === 0)).toBe(true);
+ expect(computeSongFeatures(new Float32Array(SR), SR).onsets.low).toEqual([]);
+ });
+
+ it('carries a prior feature track (or its absence) through a manual tempo override', () => {
+ const { samples } = drumTrack({ durationSec: 8 });
+ const auto = analyzePcm(samples, SR);
+ const manual = buildManualAnalysisFromCached(auto, { bpm: 100, offsetSec: 0 });
+ expect(manual.features).toEqual(auto.features);
+ const legacy = buildManualAnalysisFromCached({ sections: [], durationSec: 8 }, { bpm: 100 });
+ expect(legacy.features).toBeNull();
+ expect(buildManualAnalysis(samples, SR, { bpm: 100 }).features).not.toBeNull();
+ });
+});
diff --git a/server/services/musicVideo/projectsLogic.test.js b/server/services/musicVideo/projectsLogic.test.js
index 157e6c5caf..9b6090c580 100644
--- a/server/services/musicVideo/projectsLogic.test.js
+++ b/server/services/musicVideo/projectsLogic.test.js
@@ -341,6 +341,19 @@ describe('setAudioAnalysis', () => {
expect(next.status).toBe('analyzed');
});
+ it('keeps a feature track through validation, drops it with the audio source, and leaves legacy analyses without one (#9073)', () => {
+ const features = {
+ envelopes: { fps: 30, rms: [0, 1], low: [0, 1], mid: [0, 1], high: [0, 1] },
+ onsets: { low: [0.5], mid: [], high: [] },
+ truncatedAtSec: null,
+ };
+ const withFeatures = setAudioAnalysis({ ...baseProject(), trackId: 't1' }, { ...analysis, version: 2, features });
+ expect(withFeatures.audioAnalysis.features).toEqual(features);
+ expect(setAudioAnalysis(baseProject(), analysis).audioAnalysis.features).toBeUndefined();
+ expect(() => setAudioAnalysis(baseProject(), { ...analysis, features: { ...features, envelopes: { ...features.envelopes, low: [2] } } })).toThrow();
+ expect(applyProjectPatch(withFeatures, { trackId: 't2' }).audioAnalysis).toBeNull();
+ });
+
it('does not regress a later lifecycle status', () => {
const ready = { ...baseProject(), status: 'ready' };
expect(setAudioAnalysis(ready, analysis).status).toBe('ready');