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

fix: bound decoded-PCM memory for long tracks in beat/audio analysis (#8973)

[._.]/ Adam Eivyb42c9a408634
diff --git a/server/lib/beatGrid.js b/server/lib/beatGrid.js
index 40520d133f..92d49cde59 100644
--- a/server/lib/beatGrid.js
+++ b/server/lib/beatGrid.js
@@ -35,6 +35,16 @@ import { stat } from 'node:fs/promises';
// 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;
@@ -356,11 +366,18 @@ export function __analyzeBeatGridPcm(samples, sampleRate, { hop = ONSET_HOP } =
* 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 }} [opts]
+ * @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.
* @returns {Promise<{ samples: Float32Array, sampleRate: number } | null>}
*/
-export async function decodeAudioToPcm(audioPath, { signal } = {}) {
+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();
@@ -371,6 +388,7 @@ export async function decodeAudioToPcm(audioPath, { signal } = {}) {
const args = [
'-v', 'error',
'-i', audioPath,
+ '-t', String(maxDurationSec),
'-ac', '1',
'-ar', String(BEAT_GRID_SAMPLE_RATE),
'-f', 'f32le',
diff --git a/server/lib/beatGrid.test.js b/server/lib/beatGrid.test.js
index cd68626b84..cb60068470 100644
--- a/server/lib/beatGrid.test.js
+++ b/server/lib/beatGrid.test.js
@@ -174,6 +174,25 @@ describe('decodeAudioToPcm (ffmpeg round-trip)', () => {
expect(result.bpm).toBeGreaterThan(120 - BPM_TOLERANCE);
expect(result.bpm).toBeLessThan(120 + BPM_TOLERANCE);
});
+
+ // Issue #8973: decodeAudioToPcm must bound decoded PCM size regardless of
+ // source track length, rather than buffering the whole file. Encoding a
+ // real multi-minute fixture would make this suite slow, so this exercises
+ // the same ffmpeg `-t` truncation path against a short fixture via the
+ // `maxDurationSec` test seam.
+ it('truncates decode to maxDurationSec instead of buffering the whole track (skipped without ffmpeg)', async () => {
+ if (!ffmpeg) { console.log('⏭️ ffmpeg not found — skipping truncation round-trip'); return; }
+ const wavSampleRate = 44100;
+ const samples = clickTrack({ bpm: 120, durationSec: 10, sampleRate: wavSampleRate });
+ const wavPath = join(tmpDir, 'click-120-long.wav');
+ await writeFile(wavPath, encodeWav(samples, wavSampleRate));
+ const decoded = await decodeAudioToPcm(wavPath, { maxDurationSec: 2 });
+ expect(decoded).not.toBeNull();
+ expect(decoded.sampleRate).toBe(BEAT_GRID_SAMPLE_RATE);
+ // Truncated to ~2s, not the full ~10s the source contains.
+ expect(decoded.samples.length).toBeGreaterThan(BEAT_GRID_SAMPLE_RATE * 1.5);
+ expect(decoded.samples.length).toBeLessThan(BEAT_GRID_SAMPLE_RATE * 3);
+ });
});
describe('getBeatGrid (mtime-keyed cache)', () => {
diff --git a/server/services/musicVideo/audioAnalysis.js b/server/services/musicVideo/audioAnalysis.js
index deb0ad8a94..bdeeb5eb03 100644
--- a/server/services/musicVideo/audioAnalysis.js
+++ b/server/services/musicVideo/audioAnalysis.js
@@ -34,6 +34,18 @@ import { safeChildProcessOptions } from '../../lib/processEnv.js';
// 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.
@@ -146,11 +158,18 @@ function fftInPlace(real, imaginary, plan) {
* 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 }} [opts]
+ * @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.
* @returns {Promise<{ samples: Float32Array, sampleRate: number } | null>}
*/
-export async function decodeAudioToPcm(audioPath, { signal } = {}) {
+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
@@ -166,6 +185,7 @@ export async function decodeAudioToPcm(audioPath, { signal } = {}) {
const args = [
'-v', 'error',
'-i', audioPath,
+ '-t', String(maxDurationSec),
'-ac', '1',
'-ar', String(ANALYSIS_SAMPLE_RATE),
'-f', 'f32le',
diff --git a/server/services/musicVideo/audioAnalysis.test.js b/server/services/musicVideo/audioAnalysis.test.js
index e963c8dd60..24fbe733ae 100644
--- a/server/services/musicVideo/audioAnalysis.test.js
+++ b/server/services/musicVideo/audioAnalysis.test.js
@@ -362,6 +362,28 @@ describe('analyzeAudioFile (ffmpeg decode round-trip)', () => {
expect(await decodeAudioToPcm('/nonexistent/path/nope.wav')).toBeNull();
expect(await analyzeAudioFile('')).toBeNull();
});
+
+ // Issue #8973: decodeAudioToPcm must bound decoded PCM size regardless of
+ // source track length, rather than buffering the whole file. Encoding a
+ // real multi-minute fixture would make this suite slow, so this exercises
+ // the same ffmpeg `-t` truncation path against a short fixture via the
+ // `maxDurationSec` test seam.
+ it('truncates decode to maxDurationSec instead of buffering the whole track (skipped without ffmpeg)', async () => {
+ if (!ffmpeg) {
+ console.log('⏭️ ffmpeg not found — skipping truncation round-trip');
+ return;
+ }
+ const samples = clickTrack({ bpm: 128, durationSec: 10 });
+ const wavPath = join(dir, 'click-128-long.wav');
+ await writeFile(wavPath, encodeWav(samples, ANALYSIS_SAMPLE_RATE));
+
+ const decoded = await decodeAudioToPcm(wavPath, { maxDurationSec: 2 });
+ expect(decoded).not.toBeNull();
+ expect(decoded.sampleRate).toBe(ANALYSIS_SAMPLE_RATE);
+ // Truncated to ~2s, not the full ~10s the source contains.
+ expect(decoded.samples.length).toBeGreaterThan(ANALYSIS_SAMPLE_RATE * 1.5);
+ expect(decoded.samples.length).toBeLessThan(ANALYSIS_SAMPLE_RATE * 3);
+ });
});
// 120 BPM grid: a beat every 0.5s, a downbeat (4/4) every 2s.