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
fix: make music video beat timeline musical
[._.]/ Adam Eivyd62874ad025f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 745b2145d7..398a8b2b98 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -28,6 +28,7 @@## Fixed+- **Music Video analysis now finds the beat in guitar-led songs and shows its evidence.** The offline detector uses spectral change instead of whole-track loudness changes, with later-window consensus for quiet or rubato intros. The director timeline now includes a full-song energy waveform, beat/downbeat markers, section energy, time rulers, a clickable overview, and an explicit 4/4-grid assumption instead of presenting an empty “beat-quantized” strip when the cached analysis contains no visible musical information.- **Music Video final renders now honor the authored song timeline.** Scene clips loop when their generated source is shorter than the beat-aligned cut, so an arrangement can cover the full track instead of being silently truncated to each model's native clip length.- **The task form's Screenshot and Attach buttons work again — a stuck notification was eating the clicks.** A notice that never goes away (the "Install out of sync" warning, "Update available", "New build available") parks in the bottom-right corner, and on a desktop window it landed on top of the Chief of Staff task form and silently absorbed every click meant for the buttons underneath. They did nothing at all — no file picker, no error, nothing in the browser console — which is why it read as a broken button rather than something covering one, and why the same page still worked on a phone, where the layout puts those buttons elsewhere. On a 1280×720 window the notice covered a 520×86px block starting at the exact pixel the Attach button begins. Notices that never dismiss themselves now fold into a small badge in the corner after 8 seconds (1600px², clear of the page); clicking the badge brings the message back, and it stays open while you hover it or use its buttons. Toasts with a set lifetime — including the manuscript Undo prompt — are untouched.- **CoS agent PRs no longer open with TUI startup noise as their description.** A PR that PortOS opened for a Codex/Antigravity/OpenCode agent led with the session's own lifecycle log — `📟 TUI session started: … (codex …)`, `💡 Open the Shell tab…`, `📟 Prompt pasted…` — before getting to what the agent actually did. The PR description now starts at the agent's completion summary and drops PortOS's status lines, along with the trailing `## Branch` / `## PR` section that only repeats what the PR page already shows.diff --git a/client/src/components/musicVideo/BeatTimeline.jsx b/client/src/components/musicVideo/BeatTimeline.jsxindex 1f3f132533..f2ac78cfdb 100644--- a/client/src/components/musicVideo/BeatTimeline.jsx+++ b/client/src/components/musicVideo/BeatTimeline.jsx@@ -1,5 +1,6 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { buildBeatGridPoints, computeDragSpan, computeSceneSpans, shouldMarkBeatAligned } from '../../lib/beatGrid.js';+import { formatTimecode } from '../../utils/formatters.js';// Beat-quantized timeline arranger for a music-video project's scene board// (#1854). Renders a beat-grid overlay (section bands, beat/downbeat ticks)@@ -29,6 +30,7 @@ export default function BeatTimeline({ audioAnalysis, scenes, onCommit }) {// tripping through the parent's `scenes` prop on every pixel of movement.const [liveSpan, setLiveSpan] = useState(null);const dragRef = useRef(null);+ const scrollRef = useRef(null);const spans = baseSpans.map((span) => (liveSpan && liveSpan.sceneId === span.sceneId ? { ...span, ...liveSpan } : span@@ -36,6 +38,11 @@ export default function BeatTimeline({ audioAnalysis, scenes, onCommit }) {const totalDurationSec = Math.max(audioAnalysis?.durationSec || 0, ...spans.map((s) => s.endSec), 1);const widthPx = Math.ceil(totalDurationSec * PX_PER_SEC) + 40;+ const waveform = Array.isArray(audioAnalysis?.waveform) ? audioAnalysis.waveform : [];+ const timeMarks = useMemo(() => {+ const interval = totalDurationSec > 180 ? 30 : totalDurationSec > 60 ? 15 : 5;+ return Array.from({ length: Math.floor(totalDurationSec / interval) + 1 }, (_, i) => i * interval);+ }, [totalDurationSec]);const onPointerMove = useCallback((e) => {const drag = dragRef.current;@@ -78,16 +85,104 @@ export default function BeatTimeline({ audioAnalysis, scenes, onCommit }) {window.addEventListener('pointerup', onPointerUp);};+ const jumpToOverviewTime = (e) => {+ const scroller = scrollRef.current;+ if (!scroller) return;+ const rect = e.currentTarget.getBoundingClientRect();+ if (rect.width <= 0) return;+ const timeSec = Math.max(0, Math.min(totalDurationSec, ((e.clientX - rect.left) / rect.width) * totalDurationSec));+ scroller.scrollTo({ left: Math.max(0, timeSec * PX_PER_SEC - scroller.clientWidth / 2), behavior: 'smooth' });+ };+if (!audioAnalysis || !scenes || scenes.length === 0) return null;return (- <div className="space-y-1">- <div className="flex items-center justify-between text-xs text-port-text-muted">- <span>Beat-quantized timeline — drag a scene's right edge to trim its length, or its body to reposition</span>- {audioAnalysis.bpm && <span>{audioAnalysis.bpm} BPM</span>}+ <div className="space-y-2">+ <div className="flex flex-wrap items-start justify-between gap-1 text-xs text-port-text-muted">+ <span>+ Music timeline — waveform, sections, and 4/4 beat-grid assumption.+ Drag a scene's right edge to trim, or its body to reposition.+ </span>+ <span className="whitespace-nowrap">+ {audioAnalysis.bpm ? `${audioAnalysis.bpm} BPM` : 'Waveform only · no beat grid'}+ {audioAnalysis.tempoSource === 'windowed' && audioAnalysis.tempoWindow && (+ <> · detected near {formatTimecode(audioAnalysis.tempoWindow.startSec)}–{formatTimecode(audioAnalysis.tempoWindow.endSec)}</>+ )}+ {audioAnalysis.tempoSource === 'manual' && <> · director-set</>}+ </span></div>- <div className="overflow-x-auto border border-port-border rounded-lg bg-port-bg">- <div className="relative h-28" style={{ width: `${widthPx}px`, touchAction: 'none' }}>++ <button+ type="button"+ className="relative block h-16 w-full overflow-hidden rounded-lg border border-port-border bg-port-bg text-left"+ onClick={jumpToOverviewTime}+ title="Song overview — click to center the detailed timeline"+ >+ <svg+ viewBox="0 0 1000 64"+ preserveAspectRatio="none"+ className="absolute inset-0 h-full w-full"+ role="img"+ aria-label={`Audio waveform overview with ${(audioAnalysis.beats || []).length} beats and ${(audioAnalysis.downbeats || []).length} downbeats`}+ >+ {(audioAnalysis.sections || []).map((section, i) => (+ <rect+ key={`overview-sec-${i}`}+ x={(section.startSec / totalDurationSec) * 1000}+ y="0"+ width={Math.max(1, ((section.endSec - section.startSec) / totalDurationSec) * 1000)}+ height="64"+ className="fill-port-accent/10"+ opacity={0.25 + 0.45 * (section.energy ?? 0.5)}+ />+ ))}+ {waveform.map((level, i) => {+ const x = waveform.length === 1 ? 0 : (i / (waveform.length - 1)) * 1000;+ const halfHeight = 2 + level * 23;+ return (+ <line+ key={`overview-wave-${i}`}+ x1={x}+ x2={x}+ y1={32 - halfHeight}+ y2={32 + halfHeight}+ className="stroke-port-text-muted/70"+ strokeWidth={Math.max(1, 1000 / Math.max(waveform.length, 1))}+ />+ );+ })}+ {(audioAnalysis.beats || []).map((t, i) => (+ <line key={`overview-beat-${i}`} x1={(t / totalDurationSec) * 1000} x2={(t / totalDurationSec) * 1000}+ y1="42" y2="64" className="stroke-port-border" strokeWidth="1" />+ ))}+ {(audioAnalysis.downbeats || []).map((t, i) => (+ <line key={`overview-downbeat-${i}`} x1={(t / totalDurationSec) * 1000} x2={(t / totalDurationSec) * 1000}+ y1="34" y2="64" className="stroke-port-accent" strokeWidth="2" />+ ))}+ {spans.map((span) => (+ <line key={`overview-scene-${span.sceneId}`} x1={(span.startSec / totalDurationSec) * 1000}+ x2={(span.startSec / totalDurationSec) * 1000} y1="0" y2="12"+ className="stroke-port-success/80" strokeWidth="1.5" />+ ))}+ </svg>+ {waveform.length === 0 && (+ <span className="absolute inset-0 flex items-center justify-center text-xs text-port-text-muted">+ Re-run Analyze to add the waveform to this cached project+ </span>+ )}+ <span className="absolute bottom-0.5 left-1 text-[10px] text-port-text-muted">0:00</span>+ <span className="absolute bottom-0.5 right-1 text-[10px] text-port-text-muted">{formatTimecode(totalDurationSec)}</span>+ </button>++ <div className="flex flex-wrap gap-x-3 gap-y-1 text-[10px] text-port-text-muted" aria-label="Timeline legend">+ <span><i className="mr-1 inline-block h-2 w-3 bg-port-text-muted/60" />waveform energy</span>+ <span><i className="mr-1 inline-block h-3 w-px bg-port-border" />beat</span>+ <span><i className="mr-1 inline-block h-3 w-0.5 bg-port-accent" />downbeat</span>+ <span><i className="mr-1 inline-block h-2 w-3 bg-port-success/40" />scene start</span>+ </div>++ <div ref={scrollRef} className="overflow-x-auto border border-port-border rounded-lg bg-port-bg">+ <div className="relative h-36" style={{ width: `${widthPx}px`, touchAction: 'none' }}>{(audioAnalysis.sections || []).map((section, i) => (<div key={`sec-${i}`}className="absolute top-0 h-6 border-r border-port-border/60 overflow-hidden"@@ -96,19 +191,41 @@ export default function BeatTimeline({ audioAnalysis, scenes, onCommit }) {<span className="absolute top-0.5 left-1 text-[10px] text-port-text-muted truncate max-w-full">{section.label}</span></div>))}+ {waveform.map((level, i) => {+ const x = waveform.length === 1 ? 0 : (i / (waveform.length - 1)) * totalDurationSec * PX_PER_SEC;+ const height = Math.max(1, level * 42);+ return (+ <div+ key={`wave-${i}`}+ className="pointer-events-none absolute bg-port-text-muted/45"+ style={{+ left: x,+ top: 50 - height / 2,+ width: Math.max(1, (totalDurationSec * PX_PER_SEC) / Math.max(waveform.length, 1)),+ height,+ }}+ />+ );+ })}{(audioAnalysis.beats || []).map((t, i) => (<div key={`b-${i}`} className="absolute top-7 bottom-0 w-px bg-port-border" style={{ left: t * PX_PER_SEC }} />))}{(audioAnalysis.downbeats || []).map((t, i) => (<div key={`db-${i}`} className="absolute top-6 bottom-0 w-px bg-port-accent/60" style={{ left: t * PX_PER_SEC }} />))}+ {timeMarks.map((t) => (+ <div key={`time-${t}`} className="pointer-events-none absolute top-[74px] text-[9px] text-port-text-muted"+ style={{ left: t * PX_PER_SEC }}>+ <span className="-translate-x-1/2 inline-block">{formatTimecode(t)}</span>+ </div>+ ))}{spans.map((span, i) => {const scene = scenes.find((s) => s.sceneId === span.sceneId);const dragging = liveSpan?.sceneId === span.sceneId;const snappedNow = dragging && liveSpan.snapped;return (<div key={span.sceneId}- className={`absolute top-14 h-12 rounded border bg-port-card/90 select-none ${snappedNow ? 'border-port-success' : 'border-port-accent'}`}+ className={`absolute top-[92px] h-11 rounded border bg-port-card/90 select-none ${snappedNow ? 'border-port-success' : 'border-port-accent'}`}style={{ left: span.startSec * PX_PER_SEC, width: Math.max(6, (span.endSec - span.startSec) * PX_PER_SEC) }}><div role="presentation"className="absolute inset-0 flex items-center justify-center text-[10px] px-2 cursor-grab truncate"diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsxindex d07276e520..79798ce474 100644--- a/client/src/pages/MusicVideo.test.jsx+++ b/client/src/pages/MusicVideo.test.jsx@@ -109,7 +109,17 @@ const PROJECT_ANALYZED = {...PROJECT_NO_CLIP,id: 'mv-3',name: 'Analyzed Track',- audioAnalysis: { bpm: 120, beats: [], downbeats: [], sections: [{ label: 'Intro', startSec: 0, endSec: 10, energy: 0.5 }], durationSec: 10 },+ audioAnalysis: {+ bpm: 120,+ beats: [0, 0.5, 1, 1.5],+ downbeats: [0],+ waveform: [0.1, 0.4, 1, 0.6, 0.2],+ sections: [{ label: 'Intro', startSec: 0, endSec: 10, energy: 0.5 }],+ durationSec: 10,+ tempoSource: 'windowed',+ tempoConfidence: 0.72,+ tempoWindow: { startSec: 40, endSec: 70 },+ },};// The page now selects the open project via the route param@@ -352,6 +362,16 @@ describe('MusicVideo audio preview + download', () => {});});+describe('MusicVideo musical timeline', () => {+ it('renders waveform, beat evidence, legend, and the detected rhythmic window', async () => {+ await openProject(PROJECT_ANALYZED);+ expect(screen.getByRole('img', { name: /audio waveform overview with 4 beats and 1 downbeats/i })).toBeTruthy();+ expect(screen.getByText(/waveform, sections, and 4\/4 beat-grid assumption/i)).toBeTruthy();+ expect(screen.getByText(/detected near 0:40\.00–1:10\.00/i)).toBeTruthy();+ expect(screen.getByLabelText('Timeline legend')).toBeTruthy();+ });+});+describe('MusicVideo audio → MIDI transcription (MuScriptor)', () => {it('disables the MIDI button when the project has no audio source', async () => {await openProject({ ...PROJECT_WITH_CLIP, trackId: null, uploadedAudioFilename: null });diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex 262b37d25e..153ba73865 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -153,6 +153,9 @@ export const musicVideoAudioAnalysisSchema = z.object({bpm: z.number().nullable(),beats: z.array(z.number()),downbeats: z.array(z.number()),+ // Compact normalized loudness envelope for the director timeline. Optional+ // so cached analyses from older installs remain readable.+ waveform: z.array(z.number().min(0).max(1)).max(1024).optional(),sections: z.array(z.object({label: z.string(),startSec: z.number(),@@ -162,4 +165,12 @@ export const musicVideoAudioAnalysisSchema = z.object({energy: z.number().min(0).optional(),})),durationSec: z.number(),+ // Explain whether the beat grid came from the full track, consensus among+ // later rhythmic windows, or the director's manual tap/entry fallback.+ tempoSource: z.enum(['full', 'windowed', 'manual']).nullable().optional(),+ tempoConfidence: z.number().min(0).max(1).nullable().optional(),+ tempoWindow: z.object({+ startSec: z.number().min(0),+ endSec: z.number().min(0),+ }).nullable().optional(),}).strict();diff --git a/server/services/musicVideo/audioAnalysis.js b/server/services/musicVideo/audioAnalysis.jsindex 14952b95fe..fcb857b783 100644--- a/server/services/musicVideo/audioAnalysis.js+++ b/server/services/musicVideo/audioAnalysis.js@@ -13,7 +13,7 @@** Pipeline:* 1. ffmpeg decodes the track to mono f32 PCM at a fixed analysis rate.- * 2. An onset-strength envelope (half-wave-rectified energy flux) is framed.+ * 2. A spectral-flux onset envelope captures percussion and harmonic attacks.* 3. Tempo is estimated by tempo-weighted autocorrelation of the envelope.* 4. The beat phase is fit by sliding a pulse train against the envelope.* 5. Downbeats are picked as the strongest of the four 4/4 beat phases.@@ -29,9 +29,9 @@ import { spawn } from 'child_process';import { findFfmpeg } from '../../lib/ffmpeg.js';import { safeChildProcessEnv } from '../../lib/processEnv.js';-// Fixed analysis sample rate. 22.05kHz is plenty for tempo/onset work (we care-// about energy flux, not high-frequency fidelity) and halves the sample count-// vs 44.1kHz. Mono — beat structure is shared across channels.+// 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;// Frame hop for the onset envelope. 512 samples @ 22.05kHz → ~43 frames/sec,@@ -63,6 +63,15 @@ const MAX_SECTIONS = 8;// 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@@ -79,6 +88,57 @@ const hannWindow = (len) => {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@@ -145,26 +205,57 @@ export async function decodeAudioToPcm(audioPath, { signal } = {}) {}/**- * Compute a per-frame onset-strength envelope: half-wave-rectified positive- * change in short-time energy. Energy rises sharply at note/percussion onsets,- * so its rectified first difference peaks on the beat. Returns the envelope- * plus the raw per-frame energy (reused for section segmentation) and the- * frame 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 frameCount = Math.floor(samples.length / hop);+ const fftSize = FFT_SIZE;+ const frameCount = Math.max(0, Math.floor((samples.length - fftSize) / hop) + 1);const energy = new Float32Array(frameCount);- const win = hannWindow(hop);+ 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 < hop; i++) { const s = samples[base + i] * win[i]; sum += s * s; }- energy[f] = Math.sqrt(sum / 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);- for (let f = 1; f < frameCount; f++) {- const d = energy[f] - energy[f - 1];- onset[f] = d > 0 ? d : 0;+ 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 };}@@ -187,16 +278,16 @@ const TEMPO_LAG_STEP = 0.25;* envelope carries no usable periodicity (silence, or structureless input whose* strongest peak is below the significance floor).*/-function estimateTempo(onset, fps) {+function estimateTempoCandidate(onset, fps) {const n = onset.length;- if (n < 4) return { bpm: null, lag: null };+ 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 { bpm: null, lag: null };+ 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).@@ -223,12 +314,7 @@ function estimateTempo(onset, fps) {const score = ac * weight;if (score > bestScore) { bestScore = score; bestLag = lag; bestAc = ac; }}- if (bestLag < 0 || bestScore <= 0) return { bpm: null, lag: null };-- // Significance gate. Structureless input (white noise) still has a strongest- // lag, but it sits far below a real periodicity — emit `null` rather than a- // confident bogus tempo + beat grid.- if (bestAc / variance < TEMPO_PEAK_MIN) return { bpm: null, lag: null };+ 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@@ -241,7 +327,69 @@ function estimateTempo(onset, fps) {// 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 };+ 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 },+ };}/**@@ -375,6 +523,27 @@ function segmentSections(energy, fps, durationSec) {return sections;}+// Persist a small normalized loudness envelope so the timeline can show the+// musical evidence behind its sections and beats without shipping raw PCM.+// Mean RMS energy per bin keeps song-shape dynamics visible; normalization to+// the 95th percentile prevents one transient from flattening the whole display.+function summarizeWaveform(energy, targetPoints = WAVEFORM_POINTS) {+ if (!energy?.length) return [];+ const count = Math.min(targetPoints, energy.length);+ const bins = new Array(count);+ for (let bin = 0; bin < count; bin++) {+ const start = Math.floor((bin * energy.length) / count);+ const end = Math.max(start + 1, Math.floor(((bin + 1) * energy.length) / count));+ let sum = 0;+ for (let i = start; i < end; i++) sum += energy[i] || 0;+ bins[bin] = sum / (end - start);+ }+ const ranked = bins.slice().sort((a, b) => a - b);+ const reference = ranked[Math.min(ranked.length - 1, Math.floor(ranked.length * 0.95))] || 0;+ if (reference <= 1e-9) return bins.map(() => 0);+ return bins.map((value) => Number(Math.min(1, value / reference).toFixed(3)));+}+// 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@@ -383,11 +552,16 @@ function segmentSections(energy, fps, durationSec) {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 };+ return {+ sections: segmentSections(new Float32Array(0), 1, durationSec),+ waveform: [],+ onset: null,+ fps: null,+ };}const { onset, energy, fps } = onsetEnvelope(samples, sampleRate, hop);const sections = segmentSections(energy, fps, durationSec);- return { sections, onset, fps };+ return { sections, waveform: summarizeWaveform(energy), onset, fps };}/**@@ -397,23 +571,45 @@ function deriveSections(samples, sampleRate, hop) {* @param {Float32Array} samples mono PCM* @param {number} sampleRate* @param {{ hop?: number }} [opts]- * @returns {{ bpm: number|null, beats: number[], downbeats: number[],+ * @returns {{ 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 } = {}) {const durationSec = samples?.length ? samples.length / sampleRate : 0;const roundedDuration = Number(durationSec.toFixed(3));- const { sections, onset, fps } = deriveSections(samples, sampleRate, hop);+ const { sections, waveform, onset, fps } = deriveSections(samples, sampleRate, hop);if (!onset) {- return { bpm: null, beats: [], downbeats: [], sections, durationSec: roundedDuration };+ return {+ bpm: null,+ beats: [],+ downbeats: [],+ waveform,+ sections,+ durationSec: roundedDuration,+ tempoSource: null,+ tempoConfidence: null,+ tempoWindow: null,+ };}- const { bpm } = estimateTempo(onset, fps);+ const { bpm, source, confidence, window } = estimateTempo(onset, fps);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);- return { bpm: roundedBpm, beats, downbeats, sections, durationSec: roundedDuration };+ return {+ bpm: roundedBpm,+ beats,+ downbeats,+ waveform,+ sections,+ durationSec: roundedDuration,+ tempoSource: source,+ tempoConfidence: confidence == null ? null : Number(Math.max(0, Math.min(1, confidence)).toFixed(3)),+ tempoWindow: window+ ? { startSec: Number(window.startSec.toFixed(3)), endSec: Number(Math.min(durationSec, window.endSec).toFixed(3)) }+ : null,+ };}/**@@ -455,9 +651,19 @@ 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 }, { bpm, offsetSec = 0 }) {+export function buildManualAnalysisFromCached({ sections, durationSec, waveform = [] }, { bpm, offsetSec = 0 }) {const beats = manualBeatTimes(bpm, offsetSec, durationSec);- return { bpm: Number(bpm.toFixed(2)), beats, downbeats: manualDownbeats(beats), sections, durationSec };+ return {+ bpm: Number(bpm.toFixed(2)),+ beats,+ downbeats: manualDownbeats(beats),+ waveform,+ sections,+ durationSec,+ tempoSource: 'manual',+ tempoConfidence: null,+ tempoWindow: null,+ };}/**@@ -474,8 +680,18 @@ export function buildManualAnalysis(samples, sampleRate, { bpm, offsetSec = 0, hconst 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 };+ const { sections, waveform } = deriveSections(samples, sampleRate, hop);+ return {+ bpm: Number(bpm.toFixed(2)),+ beats,+ downbeats: manualDownbeats(beats),+ waveform,+ sections,+ durationSec: roundedDuration,+ tempoSource: 'manual',+ tempoConfidence: null,+ tempoWindow: null,+ };}/**diff --git a/server/services/musicVideo/audioAnalysis.test.js b/server/services/musicVideo/audioAnalysis.test.jsindex 1dc820d1bd..831323a203 100644--- a/server/services/musicVideo/audioAnalysis.test.js+++ b/server/services/musicVideo/audioAnalysis.test.js@@ -40,6 +40,28 @@ function clickTrack({ bpm, durationSec, sampleRate = ANALYSIS_SAMPLE_RATE, offsereturn out;}+// A deliberately hostile song shape for the detector: a long broadband,+// beatless intro followed by a shorter regular pulse. This mirrors recordings+// whose rhythm only becomes obvious after an ambient/rubato opening.+function lateClickTrack({ bpm, introSec, rhythmicSec, sampleRate = ANALYSIS_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;@@ -92,6 +114,24 @@ describe('analyzePcm', () => {expect(result.bpm).toBeLessThan(92);});+ it('finds a stable tempo after a long beatless intro', () => {+ const samples = lateClickTrack({ bpm: 108, introSec: 45, rhythmicSec: 30 });+ const result = analyzePcm(samples, ANALYSIS_SAMPLE_RATE);+ expect(result.bpm).toBeGreaterThan(105);+ expect(result.bpm).toBeLessThan(111);+ expect(result.beats.length).toBeGreaterThan(100);+ expect(result.tempoSource).toMatch(/^(full|windowed)$/);+ expect(result.tempoConfidence).toBeGreaterThanOrEqual(0.3);+ });++ it('returns a bounded compact waveform for timeline visualization', () => {+ const result = analyzePcm(clickTrack({ bpm: 120, durationSec: 16 }), ANALYSIS_SAMPLE_RATE);+ expect(result.waveform.length).toBeGreaterThan(100);+ expect(result.waveform.length).toBeLessThanOrEqual(512);+ expect(Math.max(...result.waveform)).toBe(1);+ expect(result.waveform.every((level) => level >= 0 && level <= 1)).toBe(true);+ });+// Tempo is reliable only UP TO an octave (autocorrelation peaks at every// multiple of the true period) — a deliberate Phase 0 limitation (#1760).// This matches the detected BPM against the true BPM allowing a power-of-2@@ -253,13 +293,19 @@ describe('buildManualAnalysis (manual-tempo fallback)', () => {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 cached = {+ sections: [{ label: 'Section 1', startSec: 0, endSec: 16, energy: 1 }],+ waveform: [0.1, 0.8],+ 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);+ expect(result.waveform).toEqual(cached.waveform);+ expect(result.tempoSource).toBe('manual');});it('passes the cached sections through unchanged (does not re-segment)', () => {