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

Add a manual tempo fallback when Music Video's tempo detector finds none

[._.]/ Adam Eivyfccd4fbb55d7
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f1bdf24e19..f216ca3328 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,7 @@
## Music Video
+- **A track that "Analyze" reports as having no detectable tempo can now get a beat map by hand.** The offline detector deliberately reports no BPM rather than guessing when a track's beats aren't strong/periodic enough or its tempo falls outside its search range — which used to leave the whole beat grid (timeline, AI Plan, Auto-arrange, beat-snapped render) permanently unusable. When Analyze finds no tempo, a "set it by ear" row now appears: enter a BPM (or use Tap tempo) and the first downbeat's offset, and the same beat/downbeat/section map the auto path produces gets cached on the project.
- **[issue-3168] Music Video projects now have a Concept and Visual style field.** Set them before clicking "AI Plan" to steer the proposed scenes toward a story or theme, and every generated frame and shot prompt now carries your chosen visual style automatically.
## Local LLM installs
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index 00d0835283..f973c0e2fd 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -1,4 +1,4 @@
-import { useEffect, useState, useCallback } from 'react';
+import { useEffect, useState, useCallback, useRef } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Plus, Film, Trash2, Music, Activity, ArrowUp, ArrowDown, Image as ImageIcon, Video, Wand2, Download } from 'lucide-react';
import toast from '../components/ui/Toast';
@@ -9,6 +9,7 @@ import {
updateMusicVideoProject,
deleteMusicVideoProject,
analyzeMusicVideoProject,
+ setMusicVideoManualTempo,
planMusicVideoProject,
addMusicVideoScene,
updateMusicVideoScene,
@@ -36,6 +37,12 @@ import useYoutubeTrackImport from '../hooks/useYoutubeTrackImport.js';
import { useSseProgress, isTerminalSseFrame } from '../hooks/useSseProgress.js';
import { formatDurationSec } from '../utils/formatters.js';
import { MUSCRIPTOR_MODELS, DEFAULT_MUSCRIPTOR_MODEL } from '../lib/muscriptorModels.js';
+import { clampBpm } from '../lib/metronome.js';
+
+// Matches musicVideoManualAnalysisSchema's `bpm.max` on the server —
+// clampBpm's own ceiling (320, metronome-focused) is looser than what the
+// manual-tempo endpoint accepts.
+const MUSIC_VIDEO_MANUAL_BPM_MAX = 300;
const MODES = ['director', 'autonomous'];
@@ -301,6 +308,48 @@ export default function MusicVideo() {
.finally(() => setAnalyzing(false));
};
+ // Manual-tempo fallback: shown when the auto-detector caches `bpm: null`
+ // (see server/services/musicVideo/audioAnalysis.js for why). "Tap tempo"
+ // estimates BPM from the average interval between clicks (resets if the gap
+ // since the last tap exceeds 2s, i.e. the director paused/restarted).
+ const [manualBpm, setManualBpm] = useState('');
+ const [manualOffset, setManualOffset] = useState('0');
+ const [settingManualTempo, setSettingManualTempo] = useState(false);
+ const tapTimesRef = useRef([]);
+
+ useEffect(() => {
+ setManualBpm('');
+ setManualOffset('0');
+ tapTimesRef.current = [];
+ }, [selected?.id]);
+
+ const handleTapTempo = () => {
+ const now = Date.now();
+ const taps = tapTimesRef.current;
+ if (taps.length && now - taps[taps.length - 1] > 2000) taps.length = 0;
+ taps.push(now);
+ if (taps.length > 8) taps.shift();
+ if (taps.length >= 2) {
+ const intervals = [];
+ for (let i = 1; i < taps.length; i++) intervals.push(taps[i] - taps[i - 1]);
+ const avgMs = intervals.reduce((a, b) => a + b, 0) / intervals.length;
+ setManualBpm(String(Math.round(60000 / avgMs)));
+ }
+ };
+
+ const handleSetManualTempo = () => {
+ if (!selected) return;
+ const bpm = clampBpm(manualBpm);
+ if (bpm == null) { toast.error('Enter a BPM'); return; }
+ const boundedBpm = Math.min(bpm, MUSIC_VIDEO_MANUAL_BPM_MAX);
+ const offsetSec = Number(manualOffset) || 0;
+ setSettingManualTempo(true);
+ setMusicVideoManualTempo(selected.id, { bpm: boundedBpm, offsetSec }, { silent: true })
+ .then((proj) => { replaceProject(proj); toast.success(`Tempo set — ${proj.audioAnalysis?.bpm} BPM`); tapTimesRef.current = []; })
+ .catch((err) => toast.error(err?.message || 'Could not set tempo'))
+ .finally(() => setSettingManualTempo(false));
+ };
+
// Autonomous shot planner (#1855): propose one scene per analyzed audio
// section (energy-aware durations fall out of the section boundaries
// themselves) and seed them onto the board, optionally with a first-pass
@@ -847,6 +896,31 @@ export default function MusicVideo() {
<span>Sections: {selected.audioAnalysis.sections?.length || 0}</span>
</div>
)}
+ {selected.audioAnalysis && !selected.audioAnalysis.bpm && (
+ <div className="mt-2 flex flex-wrap items-end gap-2 text-xs bg-port-bg border border-port-border rounded-lg p-2">
+ <span className="text-port-text-muted w-full">No tempo detected — set it by ear to unlock the beat grid:</span>
+ <div>
+ <label htmlFor="mv-manual-bpm" className="block text-port-text-muted mb-1">BPM</label>
+ <input id="mv-manual-bpm" type="number" min={20} max={300} step={1} value={manualBpm}
+ onChange={(e) => setManualBpm(e.target.value)} placeholder="120"
+ className="w-16 bg-port-card border border-port-border rounded px-1.5 py-1" />
+ </div>
+ <button onClick={handleTapTempo} type="button"
+ className="bg-port-card border border-port-border rounded px-2 py-1.5 min-h-[32px] hover:bg-port-border/40">
+ Tap tempo
+ </button>
+ <div>
+ <label htmlFor="mv-manual-offset" className="block text-port-text-muted mb-1">First downbeat (s)</label>
+ <input id="mv-manual-offset" type="number" min={0} max={600} step={0.1} value={manualOffset}
+ onChange={(e) => setManualOffset(e.target.value)}
+ className="w-20 bg-port-card border border-port-border rounded px-1.5 py-1" />
+ </div>
+ <button onClick={handleSetManualTempo} disabled={settingManualTempo || !manualBpm}
+ className="bg-port-accent text-white rounded px-2 py-1.5 min-h-[32px] disabled:opacity-50">
+ {settingManualTempo ? 'Setting…' : 'Set tempo'}
+ </button>
+ </div>
+ )}
</div>
{selected.audioAnalysis && (selected.scenes || []).length > 0 && (
diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.js
index 124147c772..a449e3ad0c 100644
--- a/client/src/services/apiMusicVideo.js
+++ b/client/src/services/apiMusicVideo.js
@@ -22,6 +22,14 @@ export const analyzeMusicVideoProject = (id, options = {}) => request(`/music-vi
method: 'POST', ...options,
});
+// Manual-tempo fallback: supply a known BPM + first-downbeat offset by ear
+// when auto-detect caches `audioAnalysis.bpm === null` (see
+// server/services/musicVideo/audioAnalysis.js for why). Returns the updated
+// project with the same audioAnalysis shape the auto path produces.
+export const setMusicVideoManualTempo = (id, body, options = {}) => request(`/music-video/${encodeURIComponent(id)}/analyze/manual`, {
+ method: 'POST', body: JSON.stringify(body), ...options,
+});
+
// Autonomous shot planner (#1855): propose one scene per analyzed audio
// section and seed them onto the board. `seedPrompts` (default true) also
// best-effort asks the active provider for a first-pass framePrompt/prompt
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index aec8b4ce2c..31ff9a71df 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -96,6 +96,15 @@ export const musicVideoPlanRequestSchema = z.object({
model: z.string().max(200).optional(),
}).strict();
+// Manual-tempo fallback (see services/musicVideo/audioAnalysis.js for why bpm
+// can come back null from auto-detection). `bpm` range is loosened from the
+// detector's own search window for manual entry (20-300 covers everything
+// from a ballad to hardcore/gabber); `offsetSec` is the first downbeat, by ear.
+export const musicVideoManualAnalysisSchema = z.object({
+ bpm: z.number().min(20).max(300),
+ offsetSec: z.number().min(0).max(600).optional(),
+}).strict();
+
// MuScriptor audio → MIDI transcription request (services/audioMidiTranscription.js).
// `model` picks the MuScriptor size tier; the service clamps unknown values to
// its default, this only types the field.
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.js
index 1b6b0d3a59..5f521bbbdb 100644
--- a/server/routes/musicVideo.js
+++ b/server/routes/musicVideo.js
@@ -18,6 +18,7 @@ import {
musicVideoSceneUpdateSchema,
musicVideoSceneReorderSchema,
musicVideoPlanRequestSchema,
+ musicVideoManualAnalysisSchema,
musicVideoTranscribeMidiRequestSchema,
} from '../lib/validation.js';
import { PATHS } from '../lib/fileUtils.js';
@@ -40,7 +41,7 @@ import {
attachMidiTranscriptionSseClient,
cancelMidiTranscription,
} from '../services/audioMidiTranscription.js';
-import { analyzeAudioFile } from '../services/musicVideo/audioAnalysis.js';
+import { analyzeAudioFile, analyzeAudioFileManual, buildManualAnalysisFromCached } from '../services/musicVideo/audioAnalysis.js';
import { renderMusicVideo, attachRenderSseClient, cancelRender } from '../services/musicVideo/render.js';
import { planProject } from '../services/musicVideo/planner.js';
import { getTrack } from '../services/tracks/index.js';
@@ -109,6 +110,28 @@ router.post('/:id/analyze', asyncHandler(async (req, res) => {
res.json(updated);
}));
+// Manual-tempo fallback: lets a director supply a known BPM + first-downbeat
+// offset by ear when the auto-detector caches `bpm: null` (see
+// services/musicVideo/audioAnalysis.js `estimateTempo` for why). Reuses the
+// prior analysis's cached `sections`/`durationSec` when present — the UI only
+// offers this after a prior `/analyze` call has cached them, so this is pure
+// arithmetic in the common case rather than a second ffmpeg decode; it only
+// falls back to decoding when no usable prior analysis exists.
+router.post('/:id/analyze/manual', asyncHandler(async (req, res) => {
+ const { bpm, offsetSec } = validateRequest(musicVideoManualAnalysisSchema, req.body);
+ const project = await getProject(req.params.id);
+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ const cached = project.audioAnalysis;
+ const analysis = cached && Array.isArray(cached.sections) && typeof cached.durationSec === 'number'
+ ? buildManualAnalysisFromCached(cached, { bpm, offsetSec })
+ : await analyzeAudioFileManual(await resolveAudioPath(project), { bpm, offsetSec });
+ if (!analysis) {
+ throw new ServerError('Could not analyze audio (decode failed or ffmpeg unavailable)', { status: 422, code: 'ANALYZE_FAILED' });
+ }
+ const updated = await setProjectAnalysis(project.id, analysis);
+ res.json(updated);
+}));
+
// Autonomous shot planner (#1855, the secondary "autonomous mode" path):
// propose one scene per analyzed audio section (energy-aware durations fall
// out of the cached section boundaries) and seed them onto the director
diff --git a/server/routes/musicVideo.test.js b/server/routes/musicVideo.test.js
index 6150b8ff0b..85e91284af 100644
--- a/server/routes/musicVideo.test.js
+++ b/server/routes/musicVideo.test.js
@@ -17,8 +17,12 @@ vi.mock('../services/musicVideo/projects.js', () => ({
setProjectMidiTranscription: vi.fn(async (id, midi) => ({ id, midiTranscription: midi })),
}));
-vi.mock('../services/musicVideo/audioAnalysis.js', () => ({
+// Keeps the real `buildManualAnalysisFromCached` (pure arithmetic, worth
+// exercising for real) and only stubs the two ffmpeg-decode-backed functions.
+vi.mock('../services/musicVideo/audioAnalysis.js', async (importOriginal) => ({
+ ...(await importOriginal()),
analyzeAudioFile: vi.fn(),
+ analyzeAudioFileManual: vi.fn(),
}));
vi.mock('../services/tracks/index.js', () => ({
@@ -51,7 +55,7 @@ vi.mock('../services/musicVideo/planner.js', () => ({
}));
import * as svc from '../services/musicVideo/projects.js';
-import { analyzeAudioFile } from '../services/musicVideo/audioAnalysis.js';
+import { analyzeAudioFile, analyzeAudioFileManual } from '../services/musicVideo/audioAnalysis.js';
import { getTrack } from '../services/tracks/index.js';
import * as renderSvc from '../services/musicVideo/render.js';
import * as midiSvc from '../services/audioMidiTranscription.js';
@@ -152,6 +156,59 @@ describe('musicVideo routes', () => {
});
});
+ describe('POST /:id/analyze/manual', () => {
+ it('400s on an out-of-range BPM', async () => {
+ const r = await request(app).post('/api/music-video/mv-1/analyze/manual').send({ bpm: 400 });
+ expect(r.status).toBe(400);
+ expect(r.body.code).toBe('VALIDATION_ERROR');
+ });
+
+ it('400s when the project has no audio source', async () => {
+ svc.getProject.mockResolvedValue({ id: 'mv-1', trackId: null, uploadedAudioFilename: null });
+ const r = await request(app).post('/api/music-video/mv-1/analyze/manual').send({ bpm: 120 });
+ expect(r.status).toBe(400);
+ expect(r.body.code).toBe('NO_AUDIO');
+ });
+
+ it('422s when the decoder cannot decode', async () => {
+ svc.getProject.mockResolvedValue({ id: 'mv-1', trackId: 't1' });
+ getTrack.mockResolvedValue({ id: 't1', audioFilename: 'song.wav' });
+ analyzeAudioFileManual.mockResolvedValue(null);
+ const r = await request(app).post('/api/music-video/mv-1/analyze/manual').send({ bpm: 120 });
+ expect(r.status).toBe(422);
+ expect(r.body.code).toBe('ANALYZE_FAILED');
+ });
+
+ it('caches the manual analysis, passing bpm/offsetSec through to the builder', async () => {
+ svc.getProject.mockResolvedValue({ id: 'mv-1', trackId: 't1' });
+ getTrack.mockResolvedValue({ id: 't1', audioFilename: 'song.wav' });
+ const analysis = { bpm: 128, beats: [0.25], downbeats: [0.25], sections: [], durationSec: 5 };
+ analyzeAudioFileManual.mockResolvedValue(analysis);
+ const r = await request(app).post('/api/music-video/mv-1/analyze/manual').send({ bpm: 128, offsetSec: 0.25 });
+ expect(r.status).toBe(200);
+ expect(r.body.audioAnalysis).toEqual(analysis);
+ expect(analyzeAudioFileManual).toHaveBeenCalledWith(expect.stringContaining('song.wav'), { bpm: 128, offsetSec: 0.25 });
+ expect(svc.setProjectAnalysis).toHaveBeenCalledWith('mv-1', analysis);
+ });
+
+ it('skips the ffmpeg decode and reuses cached sections/durationSec when a prior analysis exists', async () => {
+ const cachedSections = [{ label: 'Section 1', startSec: 0, endSec: 20, energy: 1 }];
+ svc.getProject.mockResolvedValue({
+ id: 'mv-1',
+ trackId: 't1',
+ audioAnalysis: { bpm: null, beats: [], downbeats: [], sections: cachedSections, durationSec: 20 },
+ });
+ const r = await request(app).post('/api/music-video/mv-1/analyze/manual').send({ bpm: 100, offsetSec: 0.5 });
+ expect(r.status).toBe(200);
+ expect(analyzeAudioFileManual).not.toHaveBeenCalled();
+ expect(getTrack).not.toHaveBeenCalled(); // never needed to resolve the audio path
+ expect(r.body.audioAnalysis.sections).toEqual(cachedSections);
+ expect(r.body.audioAnalysis.durationSec).toBe(20);
+ expect(r.body.audioAnalysis.bpm).toBe(100);
+ expect(r.body.audioAnalysis.beats[0]).toBeCloseTo(0.5, 3);
+ });
+ });
+
describe('POST /:id/transcribe-midi', () => {
it('202s with the jobId, resolving the project audio like analyze', async () => {
svc.getProject.mockResolvedValue({ id: 'mv-1', name: 'Neon', trackId: 't1' });
diff --git a/server/services/musicVideo/audioAnalysis.js b/server/services/musicVideo/audioAnalysis.js
index fa84fedc92..14952b95fe 100644
--- a/server/services/musicVideo/audioAnalysis.js
+++ b/server/services/musicVideo/audioAnalysis.js
@@ -375,6 +375,21 @@ function segmentSections(energy, fps, durationSec) {
return sections;
}
+// The too-short guard + onset-envelope + section-segmentation pass is shared
+// by the auto-detector (analyzePcm) and the manual-tempo builder below — both
+// need the same section map, differing only in how bpm/beats are derived from
+// it. Returns `onset: null` for the too-short case so callers that need onset
+// (only analyzePcm does) can branch on it without re-checking sample length.
+function deriveSections(samples, sampleRate, hop) {
+ const durationSec = samples?.length ? samples.length / sampleRate : 0;
+ if (!samples || samples.length < hop * 4) {
+ return { sections: segmentSections(new Float32Array(0), 1, durationSec), onset: null, fps: null };
+ }
+ const { onset, energy, fps } = onsetEnvelope(samples, sampleRate, hop);
+ const sections = segmentSections(energy, fps, durationSec);
+ return { sections, onset, fps };
+}
+
/**
* Pure DSP core: analyze a mono PCM buffer and return the `audioAnalysis`
* shape. Deterministic and ffmpeg-free, so it is unit-tested directly.
@@ -389,15 +404,12 @@ function segmentSections(energy, fps, durationSec) {
export function analyzePcm(samples, sampleRate, { hop = ONSET_HOP } = {}) {
const durationSec = samples?.length ? samples.length / sampleRate : 0;
const roundedDuration = Number(durationSec.toFixed(3));
-
- // Too short to analyze: still report a single section spanning the track.
- if (!samples || samples.length < hop * 4) {
- return { bpm: null, beats: [], downbeats: [], sections: segmentSections(new Float32Array(0), 1, durationSec), durationSec: roundedDuration };
+ const { sections, onset, fps } = deriveSections(samples, sampleRate, hop);
+ if (!onset) {
+ return { bpm: null, beats: [], downbeats: [], sections, durationSec: roundedDuration };
}
- const { onset, energy, fps } = onsetEnvelope(samples, sampleRate, hop);
const { bpm } = estimateTempo(onset, fps);
- const sections = segmentSections(energy, fps, durationSec);
const roundedBpm = bpm == null ? null : Number(bpm.toFixed(2));
const beats = roundedBpm == null ? [] : fitBeats(onset, fps, bpm, durationSec);
const downbeats = roundedBpm == null ? [] : pickDownbeats(beats, onset, fps);
@@ -417,3 +429,67 @@ export async function analyzeAudioFile(audioPath, { signal } = {}) {
if (!decoded) return null;
return analyzePcm(decoded.samples, decoded.sampleRate);
}
+
+// Manual-tempo fallback (see `estimateTempo`'s TEMPO_PEAK_MIN/MIN_BPM/MAX_BPM
+// comments above for why bpm can come back null): lets a director supply a
+// known BPM + first-downbeat offset by ear instead, producing the same shape
+// the auto path does so every beat-grid consumer (BeatTimeline, auto-arrange,
+// beatSnapClips) works off it identically.
+function manualBeatTimes(bpm, offsetSec, durationSec) {
+ const period = 60 / bpm;
+ const beats = [];
+ for (let t = offsetSec; t <= durationSec; t += period) beats.push(Number(t.toFixed(3)));
+ return beats;
+}
+
+const manualDownbeats = (beats) => beats.filter((_, i) => i % 4 === 0);
+
+/**
+ * Build the manual-tempo `audioAnalysis` shape from an already-cached prior
+ * analysis's `sections`/`durationSec` — pure arithmetic, no decode. The UI
+ * only offers manual entry after a prior `/analyze` call has cached those
+ * fields (even when it found no bpm, `analyzePcm` still returns them), so this
+ * is the common path; it avoids re-decoding + re-segmenting audio the server
+ * already has a section map for.
+ *
+ * @param {{ sections: Array, durationSec: number }} cached prior audioAnalysis
+ * @param {{ bpm: number, offsetSec?: number }} tempo
+ */
+export function buildManualAnalysisFromCached({ sections, durationSec }, { bpm, offsetSec = 0 }) {
+ const beats = manualBeatTimes(bpm, offsetSec, durationSec);
+ return { bpm: Number(bpm.toFixed(2)), beats, downbeats: manualDownbeats(beats), sections, durationSec };
+}
+
+/**
+ * Build the manual-tempo `audioAnalysis` shape from raw PCM (no cached prior
+ * analysis to reuse) — `beats` are an even grid from `offsetSec` at the given
+ * BPM; `downbeats` assume 4/4 starting on the first beat; sections still come
+ * from real energy-novelty segmentation via the shared `deriveSections` pass.
+ *
+ * @param {Float32Array} samples mono PCM
+ * @param {number} sampleRate
+ * @param {{ bpm: number, offsetSec?: number, hop?: number }} opts
+ */
+export function buildManualAnalysis(samples, sampleRate, { bpm, offsetSec = 0, hop = ONSET_HOP }) {
+ const durationSec = samples?.length ? samples.length / sampleRate : 0;
+ const roundedDuration = Number(durationSec.toFixed(3));
+ const beats = manualBeatTimes(bpm, offsetSec, durationSec);
+ const { sections } = deriveSections(samples, sampleRate, hop);
+ return { bpm: Number(bpm.toFixed(2)), beats, downbeats: manualDownbeats(beats), sections, durationSec: roundedDuration };
+}
+
+/**
+ * Decode `audioPath` via ffmpeg and build the manual-tempo analysis. Returns
+ * `null` under the same conditions as `analyzeAudioFile` (decode failure).
+ * Callers that already have a cached prior analysis should prefer
+ * `buildManualAnalysisFromCached` to skip the decode entirely.
+ *
+ * @param {string} audioPath absolute path to the source audio
+ * @param {{ bpm: number, offsetSec?: number }} tempo
+ * @param {{ signal?: AbortSignal }} [opts]
+ */
+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 });
+}
diff --git a/server/services/musicVideo/audioAnalysis.test.js b/server/services/musicVideo/audioAnalysis.test.js
index eb16da5018..1dc820d1bd 100644
--- a/server/services/musicVideo/audioAnalysis.test.js
+++ b/server/services/musicVideo/audioAnalysis.test.js
@@ -6,6 +6,8 @@ import {
analyzePcm,
analyzeAudioFile,
decodeAudioToPcm,
+ buildManualAnalysis,
+ buildManualAnalysisFromCached,
ANALYSIS_SAMPLE_RATE,
} from './audioAnalysis.js';
import { findFfmpeg } from '../../lib/ffmpeg.js';
@@ -212,6 +214,72 @@ describe('analyzePcm', () => {
});
});
+describe('buildManualAnalysis (manual-tempo fallback)', () => {
+ it('builds an even beat grid from the given BPM and offset', () => {
+ // Structureless input (analyzePcm would report bpm: null on this) — the
+ // manual path must still produce a full beat grid since it never runs the
+ // autocorrelation estimator.
+ const samples = new Float32Array(ANALYSIS_SAMPLE_RATE * 16);
+ const result = buildManualAnalysis(samples, ANALYSIS_SAMPLE_RATE, { bpm: 120, offsetSec: 0.5 });
+ expect(result.bpm).toBe(120);
+ expect(result.beats[0]).toBeCloseTo(0.5, 3);
+ expect(result.beats[1] - result.beats[0]).toBeCloseTo(0.5, 3); // 60/120s
+ expect(result.beats[result.beats.length - 1]).toBeLessThanOrEqual(result.durationSec);
+ });
+
+ it('picks downbeats as every 4th beat starting at the offset', () => {
+ const samples = new Float32Array(ANALYSIS_SAMPLE_RATE * 16);
+ const { beats, downbeats } = buildManualAnalysis(samples, ANALYSIS_SAMPLE_RATE, { bpm: 100, offsetSec: 0 });
+ const idx = downbeats.map((d) => beats.indexOf(d));
+ expect(idx[0]).toBe(0);
+ for (let i = 1; i < idx.length; i++) expect(idx[i] - idx[i - 1]).toBe(4);
+ });
+
+ it('still derives sections from real energy segmentation, not the manual BPM', () => {
+ const samples = clickTrack({ bpm: 120, durationSec: 40 });
+ const half = Math.round(samples.length / 2);
+ for (let i = 0; i < half; i++) samples[i] *= 0.15;
+ const { sections } = buildManualAnalysis(samples, ANALYSIS_SAMPLE_RATE, { bpm: 90, offsetSec: 0 });
+ expect(sections.length).toBeGreaterThanOrEqual(2);
+ expect(sections[sections.length - 1].energy).toBeGreaterThan(sections[0].energy);
+ });
+
+ it('handles too-short input without throwing', () => {
+ const result = buildManualAnalysis(new Float32Array(100), ANALYSIS_SAMPLE_RATE, { bpm: 120 });
+ expect(result.bpm).toBe(120);
+ expect(result.sections.length).toBe(1);
+ });
+});
+
+describe('buildManualAnalysisFromCached (no-decode manual-tempo fast path)', () => {
+ it('builds a beat grid from a cached durationSec without touching PCM', () => {
+ const cached = { sections: [{ label: 'Section 1', startSec: 0, endSec: 16, energy: 1 }], durationSec: 16 };
+ const result = buildManualAnalysisFromCached(cached, { bpm: 120, offsetSec: 0.5 });
+ expect(result.bpm).toBe(120);
+ expect(result.durationSec).toBe(16);
+ expect(result.beats[0]).toBeCloseTo(0.5, 3);
+ expect(result.beats[1] - result.beats[0]).toBeCloseTo(0.5, 3);
+ expect(result.beats[result.beats.length - 1]).toBeLessThanOrEqual(16);
+ });
+
+ it('passes the cached sections through unchanged (does not re-segment)', () => {
+ const sections = [{ label: 'Section 1', startSec: 0, endSec: 10, energy: 0.4 }, { label: 'Section 2', startSec: 10, endSec: 20, energy: 1 }];
+ const result = buildManualAnalysisFromCached({ sections, durationSec: 20 }, { bpm: 90 });
+ expect(result.sections).toBe(sections);
+ });
+
+ it('matches buildManualAnalysis\'s beat/downbeat output for the same inputs', () => {
+ const samples = new Float32Array(ANALYSIS_SAMPLE_RATE * 16);
+ const fromPcm = buildManualAnalysis(samples, ANALYSIS_SAMPLE_RATE, { bpm: 128, offsetSec: 0.1 });
+ const fromCached = buildManualAnalysisFromCached(
+ { sections: fromPcm.sections, durationSec: fromPcm.durationSec },
+ { bpm: 128, offsetSec: 0.1 },
+ );
+ expect(fromCached.beats).toEqual(fromPcm.beats);
+ expect(fromCached.downbeats).toEqual(fromPcm.downbeats);
+ });
+});
+
describe('analyzeAudioFile (ffmpeg decode round-trip)', () => {
let ffmpeg;
let dir;