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
feat: extract a new voice from a stacked mix by spectral diff (#2121)
Adam Eivy67bc4aee2179
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex ddbd84c2de..56818bdb8e 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -30,7 +30,7 @@## Rounds-- **[issue-2108] Built-in rounds now document their melody variant points.** Ah Poor Bird, Rose Rose Rose Red, and Zum Gali Gali carried melody/lyric choices that differ from other printed versions with no note explaining why — so a future accuracy check (or the AI evaluate feature) could mistake a deliberate variant for an error. Their notation now spells out each variant (Ah Poor Bird's C natural vs. the harmonic-minor C♯; Rose's verse and ending-note choices; Zum Gali Gali's D-minor transposition and refrain-only form) and cites the sources it was checked against.+- **[issue-2121] Reference analysis can now pull a voice out of a stacked mix, not just solo spans.** The "analyze a reference's attached audio" workbench used to only transcribe time ranges where a voice sings *alone* — useless for the many layered TikTok builds where a new part enters over the layers already playing and never appears solo. Each segment now has a **Stacked** toggle: turn it on and set a short *backing reference* window from the moment just before the voice enters, and extraction subtracts that backing layer's spectrum (a hand-rolled FFT + spectral-diff, all pure local DSP — zero AI calls) to recover the newly-added voice's pitch line, then transcribes it onto the round's tempo/key grid exactly like the solo path. Enabling the toggle auto-seeds a sensible backing window ending right where the voice enters; you can nudge it or set it from the playhead. Solo extraction is unchanged. Ah Poor Bird, Rose Rose Rose Red, and Zum Gali Gali carried melody/lyric choices that differ from other printed versions with no note explaining why — so a future accuracy check (or the AI evaluate feature) could mistake a deliberate variant for an error. Their notation now spells out each variant (Ah Poor Bird's C natural vs. the harmonic-minor C♯; Rose's verse and ending-note choices; Zum Gali Gali's D-minor transposition and refrain-only form) and cites the sources it was checked against.## Fixeddiff --git a/client/src/components/songs/ReferenceAnalysis.jsx b/client/src/components/songs/ReferenceAnalysis.jsxindex d63fcd25cc..70d4654f49 100644--- a/client/src/components/songs/ReferenceAnalysis.jsx+++ b/client/src/components/songs/ReferenceAnalysis.jsx@@ -24,13 +24,13 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import {- ArrowLeft, AudioLines, Flag, FlagOff, Loader2, Mic, Play, Plus, Square, Trash2, Upload, Wand2, X,+ ArrowLeft, AudioLines, Flag, FlagOff, Layers, Loader2, Mic, Play, Plus, Square, Trash2, Upload, Wand2, X,} from 'lucide-react';import toast from '../ui/Toast';import ScoreSheet from './ScoreSheet.jsx';import { uploadFile, getUploadUrl } from '../../services/api';import { startMemoRecording, arrayBufferToBase64 } from '../../lib/audioRecorder';-import { proposeSegmentScore, diffScoreBars, PITCH_CLASS_NAMES } from '../../lib/referenceAnalysis';+import { proposeSegmentScore, proposeStackedSegmentScore, diffScoreBars, PITCH_CLASS_NAMES } from '../../lib/referenceAnalysis';import { scoreHasMusic, parseScore } from '../../lib/scoreNotation';import { harmonyPartLabel } from '../../lib/songCraft';@@ -256,6 +256,11 @@ function Waveform({ samples, durationMs, segments, playheadMs, onSeek }) {// "Melody" entry in scoreParts (which the parts editor deliberately excludes).const BASE_TARGET = '__base__';+// Whether a segment is set up for stacked-mix extraction: a valid backing+// window ([bgStartMs, bgEndMs)) that precedes the voice's entrance. Presence of+// the pair IS "stacked mode" — the server persists it only when valid (#2121).+const isStacked = (seg) => Number.isFinite(seg.bgStartMs) && Number.isFinite(seg.bgEndMs) && seg.bgEndMs > seg.bgStartMs;+export default function ReferenceAnalysis({reference, layers = [], scoreParts = [], baseScore = '', tempo = null, songKey = '',onUpdateReference, onApplyPart, onClose,@@ -322,6 +327,27 @@ export default function ReferenceAnalysis({setSegments(segments.filter((_, i) => i !== idx));}, [segments, setSegments]);+ // Toggle stacked-mix extraction for a segment. Enabling seeds a backing+ // window ending right where the voice enters (this segment's start) and+ // reaching back a pre-roll sized to the segment (1.5–4 s, clamped to the+ // audio's head); disabling strips the pair so the segment is solo again.+ const toggleStacked = useCallback((idx) => {+ const seg = segments[idx];+ if (isStacked(seg)) {+ const { bgStartMs: _bgStart, bgEndMs: _bgEnd, ...rest } = seg;+ setSegments(segments.map((s, i) => (i === idx ? rest : s)));+ return;+ }+ const bgEndMs = seg.startMs;+ const preRoll = Math.min(4000, Math.max(1500, seg.endMs - seg.startMs));+ const bgStartMs = Math.max(0, bgEndMs - preRoll);+ if (bgEndMs <= bgStartMs) {+ toast.error('Not enough audio before this segment for a backing reference — move the segment start later.');+ return;+ }+ setSegments(segments.map((s, i) => (i === idx ? { ...s, bgStartMs, bgEndMs } : s)));+ }, [segments, setSegments]);+const seekTo = useCallback((ms) => {const el = audioRef.current;if (!el) return;@@ -353,9 +379,12 @@ export default function ReferenceAnalysis({return layers.find((l) => l.id === layerId)?.label || layerId;}, [layers]);- // Extract a proposed score from one solo-sung segment (pure local DSP).+ // Extract a proposed score from one segment (pure local DSP). A solo segment+ // runs the offline NSDF path; a stacked segment (with a backing window) runs+ // the spectral-diff path that subtracts the earlier layers first (#2121).const extractSegment = useCallback((seg) => {if (!decoded) return;+ const stacked = isStacked(seg);setExtracting(true);// Yield a frame so the button's busy state paints before the O(n·lag) DSP.setTimeout(() => {@@ -364,17 +393,24 @@ export default function ReferenceAnalysis({// silently change the part's time signature. parseScore defaults to 4/4// when the base score declares none.const { beats: beatsPerBar, beatValue } = parseScore(baseScore).time;- const { text } = proposeSegmentScore(decoded.samples, decoded.sampleRate, {+ const common = {startMs: seg.startMs,endMs: seg.endMs,bpm: Number.isFinite(tempo) && tempo > 0 ? tempo : undefined,key: songKey || 'C',beatsPerBar,beatValue,- });+ };+ const { text } = stacked+ ? proposeStackedSegmentScore(decoded.samples, decoded.sampleRate, {+ ...common, bgStartMs: seg.bgStartMs, bgEndMs: seg.bgEndMs,+ })+ : proposeSegmentScore(decoded.samples, decoded.sampleRate, common);setExtracting(false);if (!text) {- toast.error('No clear sung pitch detected in that segment — try a tighter range around a solo voice.');+ toast.error(stacked+ ? 'No new voice recovered from the mix — check the backing window sits just before the voice enters, or try a solo span.'+ : 'No clear sung pitch detected in that segment — try a tighter range around a solo voice.');return;}setProposal({ layerId: seg.layerId, text });@@ -514,65 +550,123 @@ export default function ReferenceAnalysis({) : (<ul className="space-y-2">{segments.map((seg, idx) => (- <li key={idx} className="bg-port-card border border-port-border rounded-lg p-3 flex flex-wrap items-center gap-2">- <select- value={seg.layerId || ''}- onChange={(e) => updateSegment(idx, { layerId: e.target.value })}- aria-label="Segment layer"- className="bg-port-bg border border-port-border rounded-lg px-2 py-1.5 text-xs text-white focus:border-port-accent focus:outline-none"- >- <option value="">— Layer —</option>- {layers.map((l) => <option key={l.id} value={l.id}>{l.label}</option>)}- </select>- <label className="flex items-center gap-1 text-xs text-gray-400">- <span>from</span>- <SecondsInput- key={`start-${seg.startMs}`}- valueMs={seg.startMs}- onCommit={(ms) => updateSegment(idx, { startMs: ms })}- ariaLabel="Segment start (seconds)"- />- <span>s</span>- </label>- <button type="button" onClick={() => updateSegment(idx, { startMs: currentMs() })} title="Set start from playhead" aria-label="Set segment start from playhead" className="p-1 text-gray-500 hover:text-port-accent">- <Flag size={14} />- </button>- <label className="flex items-center gap-1 text-xs text-gray-400">- <span>to</span>- <SecondsInput- key={`end-${seg.endMs}`}- valueMs={seg.endMs}- onCommit={(ms) => updateSegment(idx, { endMs: ms })}- ariaLabel="Segment end (seconds)"- />- <span>s</span>- </label>- <button type="button" onClick={() => updateSegment(idx, { endMs: currentMs() })} title="Set end from playhead" aria-label="Set segment end from playhead" className="p-1 text-gray-500 hover:text-port-accent">- <FlagOff size={14} />- </button>- <button type="button" onClick={() => playSegment(seg)} title="Play this segment" aria-label="Play segment" className="p-1 text-gray-500 hover:text-port-accent">- <Play size={14} />- </button>- <span className="text-xs text-gray-600 flex-1 min-w-[80px]">{layerLabel(seg.layerId)}</span>- <button- type="button"- onClick={() => extractSegment(seg)}- disabled={!decoded || extracting || seg.endMs <= seg.startMs}- title={decoded ? 'Extract a proposed part from this range (local DSP)' : 'Waiting for audio to decode'}- className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs rounded-lg border border-port-accent/50 text-port-accent hover:bg-port-accent/10 disabled:opacity-40"- >- {extracting ? <Loader2 size={14} className="animate-spin" /> : <Wand2 size={14} />} Extract part- </button>- <button type="button" onClick={() => removeSegment(idx)} aria-label="Remove segment" className="p-1.5 text-gray-500 hover:text-port-error">- <Trash2 size={15} />- </button>+ <li key={idx} className="bg-port-card border border-port-border rounded-lg p-3 space-y-2">+ <div className="flex flex-wrap items-center gap-2">+ <select+ value={seg.layerId || ''}+ onChange={(e) => updateSegment(idx, { layerId: e.target.value })}+ aria-label="Segment layer"+ className="bg-port-bg border border-port-border rounded-lg px-2 py-1.5 text-xs text-white focus:border-port-accent focus:outline-none"+ >+ <option value="">— Layer —</option>+ {layers.map((l) => <option key={l.id} value={l.id}>{l.label}</option>)}+ </select>+ <label className="flex items-center gap-1 text-xs text-gray-400">+ <span>from</span>+ <SecondsInput+ key={`start-${seg.startMs}`}+ valueMs={seg.startMs}+ onCommit={(ms) => updateSegment(idx, { startMs: ms })}+ ariaLabel="Segment start (seconds)"+ />+ <span>s</span>+ </label>+ <button type="button" onClick={() => updateSegment(idx, { startMs: currentMs() })} title="Set start from playhead" aria-label="Set segment start from playhead" className="p-1 text-gray-500 hover:text-port-accent">+ <Flag size={14} />+ </button>+ <label className="flex items-center gap-1 text-xs text-gray-400">+ <span>to</span>+ <SecondsInput+ key={`end-${seg.endMs}`}+ valueMs={seg.endMs}+ onCommit={(ms) => updateSegment(idx, { endMs: ms })}+ ariaLabel="Segment end (seconds)"+ />+ <span>s</span>+ </label>+ <button type="button" onClick={() => updateSegment(idx, { endMs: currentMs() })} title="Set end from playhead" aria-label="Set segment end from playhead" className="p-1 text-gray-500 hover:text-port-accent">+ <FlagOff size={14} />+ </button>+ <button type="button" onClick={() => playSegment(seg)} title="Play this segment" aria-label="Play segment" className="p-1 text-gray-500 hover:text-port-accent">+ <Play size={14} />+ </button>+ <span className="text-xs text-gray-600 flex-1 min-w-[60px]">{layerLabel(seg.layerId)}</span>+ <button+ type="button"+ onClick={() => toggleStacked(idx)}+ aria-pressed={isStacked(seg)}+ title={isStacked(seg)+ ? 'Stacked mix: subtracting the backing layers. Click to switch back to solo extraction.'+ : 'The voice never plays alone here — subtract the earlier layers using a backing window just before it enters.'}+ className={`flex items-center gap-1 px-2 py-1.5 text-xs rounded-lg border ${isStacked(seg)+ ? 'border-port-accent bg-port-accent/10 text-port-accent'+ : 'border-port-border text-gray-400 hover:text-white'}`}+ >+ <Layers size={13} /> Stacked+ </button>+ <button+ type="button"+ onClick={() => extractSegment(seg)}+ disabled={!decoded || extracting || seg.endMs <= seg.startMs}+ title={decoded+ ? (isStacked(seg)+ ? 'Recover the new voice from the mix by spectral diff (local DSP)'+ : 'Extract a proposed part from this range (local DSP)')+ : 'Waiting for audio to decode'}+ className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs rounded-lg border border-port-accent/50 text-port-accent hover:bg-port-accent/10 disabled:opacity-40"+ >+ {extracting ? <Loader2 size={14} className="animate-spin" /> : (isStacked(seg) ? <Layers size={14} /> : <Wand2 size={14} />)}+ {isStacked(seg) ? ' Extract from mix' : ' Extract part'}+ </button>+ <button type="button" onClick={() => removeSegment(idx)} aria-label="Remove segment" className="p-1.5 text-gray-500 hover:text-port-error">+ <Trash2 size={15} />+ </button>+ </div>++ {/* Stacked-mix backing window ("voice enters at" pairing) */}+ {isStacked(seg) && (+ <div className="flex flex-wrap items-center gap-2 pl-1 border-l-2 border-port-accent/40 ml-1">+ <span className="flex items-center gap-1 text-xs text-port-accent"><Layers size={12} /> Backing ref</span>+ <label className="flex items-center gap-1 text-xs text-gray-400">+ <span>from</span>+ <SecondsInput+ key={`bg-start-${seg.bgStartMs}`}+ valueMs={seg.bgStartMs}+ onCommit={(ms) => updateSegment(idx, { bgStartMs: ms })}+ ariaLabel="Backing reference start (seconds)"+ />+ <span>s</span>+ </label>+ <button type="button" onClick={() => updateSegment(idx, { bgStartMs: currentMs() })} title="Set backing start from playhead" aria-label="Set backing start from playhead" className="p-1 text-gray-500 hover:text-port-accent">+ <Flag size={14} />+ </button>+ <label className="flex items-center gap-1 text-xs text-gray-400">+ <span>to</span>+ <SecondsInput+ key={`bg-end-${seg.bgEndMs}`}+ valueMs={seg.bgEndMs}+ onCommit={(ms) => updateSegment(idx, { bgEndMs: ms })}+ ariaLabel="Backing reference end (seconds)"+ />+ <span>s</span>+ </label>+ <button type="button" onClick={() => updateSegment(idx, { bgEndMs: currentMs() })} title="Set backing end from playhead" aria-label="Set backing end from playhead" className="p-1 text-gray-500 hover:text-port-accent">+ <FlagOff size={14} />+ </button>+ <button type="button" onClick={() => playSegment({ startMs: seg.bgStartMs, endMs: seg.bgEndMs })} title="Play the backing reference" aria-label="Play backing reference" className="p-1 text-gray-500 hover:text-port-accent">+ <Play size={14} />+ </button>+ <span className="text-xs text-gray-600">the layers already present, just before the voice enters</span>+ </div>+ )}</li>))}</ul>)}<p className="text-xs text-gray-600">- Layered builds usually expose each part solo right where it enters — mark that entrance loop.- Extraction of a voice from a stacked mix isn’t supported yet; pick solo spans.+ Mark each part’s solo entrance loop for a clean extract. When a voice never plays alone,+ turn on <span className="text-port-accent">Stacked</span> and set a backing reference from the moment just+ before it enters — the extractor subtracts those layers and recovers the new voice by spectral diff.</p></section>diff --git a/client/src/components/songs/ReferenceAnalysis.test.jsx b/client/src/components/songs/ReferenceAnalysis.test.jsxindex 202876e0c5..a5288ca89c 100644--- a/client/src/components/songs/ReferenceAnalysis.test.jsx+++ b/client/src/components/songs/ReferenceAnalysis.test.jsx@@ -1,4 +1,5 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { useState } from 'react';import { render, screen, fireEvent, waitFor } from '@testing-library/react';// The analysis view's DSP (referenceAnalysis.js) and transcription@@ -34,16 +35,39 @@ const sine = (hz, seconds) => {return out;};-// Fake Web Audio decode: any fetched bytes decode to 1 s of A3 (220 Hz).-const installFakeAudio = () => {- const samples = sine(220, 1.0);+// A voice-like tone (fundamental + 2 harmonics) so the spectral harmonic-sum+// estimator has an overtone series to lock onto.+const harmonicTone = (f0, seconds, amp = 0.5) => {+ const n = Math.round(seconds * SR);+ const out = new Float32Array(n);+ for (let i = 0; i < n; i++) {+ const t = i / SR;+ out[i] = amp * (Math.sin(2 * Math.PI * f0 * t) + 0.5 * Math.sin(2 * Math.PI * 2 * f0 * t) + 0.33 * Math.sin(2 * Math.PI * 3 * f0 * t));+ }+ return out;+};+const concatArr = (...parts) => {+ const out = new Float32Array(parts.reduce((s, p) => s + p.length, 0));+ let off = 0;+ for (const p of parts) { out.set(p, off); off += p.length; }+ return out;+};+const mixArr = (...parts) => {+ const n = Math.min(...parts.map((p) => p.length));+ const out = new Float32Array(n);+ for (let i = 0; i < n; i++) for (const p of parts) out[i] += p[i];+ return out;+};++// Fake Web Audio decode: any fetched bytes decode to the given mono samples.+const installFakeAudioBuffer = (samples, durationSec) => {window.AudioContext = function FakeAudioContext() {return {sampleRate: SR,decodeAudioData: () => Promise.resolve({getChannelData: () => samples,sampleRate: SR,- duration: 1.0,+ duration: durationSec,}),close: () => Promise.resolve(),};@@ -51,6 +75,23 @@ const installFakeAudio = () => {global.fetch = vi.fn(() => Promise.resolve({ ok: true, arrayBuffer: () => Promise.resolve(new ArrayBuffer(8)) }));};+// Default fake: 1 s of A3 (220 Hz) for the solo-path tests.+const installFakeAudio = () => installFakeAudioBuffer(sine(220, 1.0), 1.0);++// A controlled host that feeds reference updates back as props, so a toggle+// that persists through onUpdateReference re-renders the view (the parent owns+// segment state in production).+function ControlledAnalysis({ initialRef, ...props }) {+ const [ref, setRef] = useState(initialRef);+ return (+ <ReferenceAnalysis+ reference={ref}+ onUpdateReference={(id, key, val) => setRef((r) => ({ ...r, [key]: val }))}+ {...props}+ />+ );+}+const baseRef = {id: 'ref-1',url: 'https://www.tiktok.com/@u/video/1',@@ -212,6 +253,79 @@ describe('ReferenceAnalysis — extract → review → apply (solo segment)', ()});});+describe('ReferenceAnalysis — stacked-mix extraction (#2121)', () => {+ it('toggling Stacked seeds a backing window ending where the voice enters', () => {+ installFakeAudio();+ const onUpdateReference = vi.fn();+ render(+ <ReferenceAnalysis+ reference={{ ...baseRef, segments: [{ layerId: 'bass', startMs: 3000, endMs: 6000 }] }}+ layers={layers}+ scoreParts={[]}+ tempo={60}+ songKey="C"+ onUpdateReference={onUpdateReference}+ onApplyPart={vi.fn()}+ onClose={vi.fn()}+ />,+ );+ fireEvent.click(screen.getByRole('button', { name: /stacked/i }));+ expect(onUpdateReference).toHaveBeenCalledWith('ref-1', 'segments', [+ // Pre-roll clamped to the segment length (3 s → capped at 4 s), ending at+ // the segment start (the voice's entrance).+ { layerId: 'bass', startMs: 3000, endMs: 6000, bgStartMs: 0, bgEndMs: 3000 },+ ]);+ });++ it('warns when there is no audio before the segment to use as a backing ref', () => {+ installFakeAudio();+ render(+ <ReferenceAnalysis+ reference={{ ...baseRef, segments: [{ layerId: 'bass', startMs: 0, endMs: 1000 }] }}+ layers={layers}+ scoreParts={[]}+ tempo={60}+ songKey="C"+ onUpdateReference={vi.fn()}+ onApplyPart={vi.fn()}+ onClose={vi.fn()}+ />,+ );+ fireEvent.click(screen.getByRole('button', { name: /stacked/i }));+ expect(toastError).toHaveBeenCalledWith(expect.stringMatching(/not enough audio before/i));+ });++ it('recovers a new voice from a stacked mix end-to-end (toggle → extract from mix)', async () => {+ // [0, 0.8s]: C4 backing alone. [0.8, 1.8s]: C4 + a new A4 (440) on top.+ const audio = concatArr(harmonicTone(262, 0.8), mixArr(harmonicTone(262, 1.0), harmonicTone(440, 1.0)));+ installFakeAudioBuffer(audio, 1.8);+ const onApplyPart = vi.fn();+ render(+ <ControlledAnalysis+ initialRef={{ ...baseRef, segments: [{ layerId: 'bass', startMs: 800, endMs: 1800 }] }}+ layers={layers}+ scoreParts={[]}+ tempo={60}+ songKey="C"+ onApplyPart={onApplyPart}+ onClose={vi.fn()}+ />,+ );+ // Wait for decode (solo Extract enabled), then flip to stacked mode. The+ // toggle derives the backing window [0, 800] — the C4-only pre-entrance.+ await waitFor(() => expect(screen.getByRole('button', { name: /extract part/i }).disabled).toBe(false));+ fireEvent.click(screen.getByRole('button', { name: /stacked/i }));++ const extractFromMix = await screen.findByRole('button', { name: /extract from mix/i });+ fireEvent.click(extractFromMix);++ // The spectral diff subtracts the C4 backing and transcribes the new A4.+ await waitFor(() => expect(screen.getAllByTestId('scoresheet').length).toBeGreaterThan(0), { timeout: 3000 });+ expect(screen.getAllByTestId('scoresheet')[0].textContent).toMatch(/A4/);+ expect(toastError).not.toHaveBeenCalled();+ });+});+describe('ReferenceAudioAttach', () => {it('offers upload + mic capture when no audio is attached', () => {render(<ReferenceAudioAttach reference={{ id: 'r', url: 'https://x.com' }} onUpdate={vi.fn()} />);diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 506b8cdaf5..e05a65c9aa 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -110,7 +110,7 @@ grep -i "what you want to do" client/src/lib/README.md| `lossSparkline.js` | `lossSparklineGeometry(series, box)` — projects an unbounded training-loss series (`{step,loss}[]`) into SVG polyline coords, normalized to its own min/max (unlike `editorialHealth.sparklineGeometry`'s fixed 0–100 axis). Returns `{ points, coords, last, min, max }`. Drives the Render Queue's training-row loss curve (#1408). No React. || `metronome.js` | Sample-accurate Web Audio metronome — the shared timing grid for the song system and first consumer of the song `tempo` field. `createMetronome({ bpm, beatsPerBar, countInBars, onBeat, onCountInComplete })` lookahead-schedules accented click tones on the shared `AudioContext` clock (same pattern as `songPlayback.js`), emits `{ beat, bar, accent, countIn, whenAudioTime }` per beat (the beat-clock callback color-match/sing-to-score subscribe to), and tears down all timers on `stop()`. Plus `clampBpm` (20–320), `secondsPerBeat`, `timeSignatureFromScore`, `beatDescriptor`. || `pianoKeyboard.js` | Piano-keyboard geometry for the song system's Synthesia-style piano-roll visualizer (`<PianoRoll>`). Pure math, no canvas/React. `keyboardRange(midis, { minSemitones })` → `{ lowMidi, highMidi }` padded out to whole C–B octaves (min 2) so the keyboard always starts on a C / ends on a B and never collapses for a one-note part; `buildKeyboardLayout({ lowMidi, highMidi, width })` → `{ keys:[{midi,isBlack,x,w}], whiteWidth, blackWidth }` (white keys tiled edge-to-edge, black keys overlaid centered on the boundary, narrower); plus `isBlackKey(midi)`, `midiNoteName(midi)` (sharps spelling), and the `BLACK_KEY_RATIO`/`BLACK_KEY_HEIGHT_RATIO` constants. Pairs with `scorePlayback`'s per-note `midi` field. |-| `referenceAnalysis.js` | Reference-audio analysis for the Rounds workbench (#2106) — pure DSP + diff helpers behind the "analyze a reference's attached audio" view. `extractPitchTrack(samples, sampleRate, { startMs, endMs, hopMs })` frames decoded PCM through `detectFrequency` offline (faster than realtime) into the `[{ tMs, hz, clarity }]` shape `singToScore` consumes; `proposeSegmentScore(samples, sampleRate, { startMs, endMs, bpm, key })` runs the solo-segment pipeline (extract → `transcribePitchTrack` on the round's tempo/key grid) → `{ track, body, text }`; `buildScoreText({ key, tempo, body })` wraps a transcribed body in a lead-sheet header; `barPitchClasses(scoreText)` / `diffScoreBars(proposed, existing)` compare a proposed part against a stored scorePart per bar by octave-collapsed pitch-class sequence (drives the review diff highlighting). Zero LLM calls — pure local DSP. |+| `referenceAnalysis.js` | Reference-audio analysis for the Rounds workbench (#2106) — pure DSP + diff helpers behind the "analyze a reference's attached audio" view. `extractPitchTrack(samples, sampleRate, { startMs, endMs, hopMs })` frames decoded PCM through `detectFrequency` offline (faster than realtime) into the `[{ tMs, hz, clarity }]` shape `singToScore` consumes; `proposeSegmentScore(samples, sampleRate, { startMs, endMs, bpm, key })` runs the solo-segment pipeline (extract → `transcribePitchTrack` on the round's tempo/key grid) → `{ track, body, text }`; `buildScoreText({ key, tempo, body })` wraps a transcribed body in a lead-sheet header; `barPitchClasses(scoreText)` / `diffScoreBars(proposed, existing)` compare a proposed part against a stored scorePart per bar by octave-collapsed pitch-class sequence (drives the review diff highlighting). Stacked-mix extraction (#2121, spectral diff v2): `magnitudeSpectrum(frame, { fftSize })` (hand-rolled radix-2 FFT, Hann-windowed) / `averageMagnitudeSpectrum(samples, sampleRate, { startMs, endMs })` build a backing profile; `estimateSpectralF0(mag, sampleRate, fftSize)` picks the fundamental by weighted (1/k) harmonic sum (octave-robust); `extractSpectralDiffTrack(samples, sampleRate, { startMs, endMs, bgStartMs, bgEndMs })` subtracts the backing profile per frame and estimates f0 on the residual to recover a voice that never plays solo; `proposeStackedSegmentScore(...)` is its `proposeSegmentScore` counterpart. Zero LLM calls — pure local DSP. || `scoreNotation.js` | Parser for the PortOS lead-sheet notation — a dependency-free text format for melody + chords + lyrics that the `<ScoreSheet>` SVG renderer draws (no abcjs / VexFlow / OSMD). `parseScore(text)` → `{ clef, key, keySig, time, tempo, measures, errors }`; plus `parsePitch`, `diatonicStep`, `durationBeats`, `keySignature`, `DURATIONS`, and `scoreHasMusic(text)`. Forgiving: bad tokens collect into `errors` and are skipped, never thrown. Pure — the renderer only does geometry. || `scorePlayback.js` | Melody synth playback for the lead-sheet notation — companion to `songPlayback.js` (which stacks recorded vocal takes), this synthesizes the WRITTEN melody as soft `OscillatorNode` reference tones on a lazy shared `AudioContext` (no MIDI.js / Tone.js). `buildSchedule(score, bpm?)` is the pure notes→`{ midi, freq, startSec, durSec }` mapping (A4=440, quarter-beat = `(60/bpm)·(beatValue/4)` so it honors the time signature; `midi` feeds the `<PianoRoll>` key mapping); `noteToFrequency`/`midiToFreq`/`pitchToMidi` convert pitches; `createScorePlayer(score, { bpm, onNote, onEnded })` plays/pauses/stops with a lookahead scheduler and emits the now-sounding note index for the `<ScoreSheet>` playhead; `createMultiScorePlayer(parts, { bpm, onNote, onEnded })` synthesizes several parts (melody + checked harmony) together on one master bus (level backs off as voices stack) with a per-part `onNote(partId, index)` playhead, plus `position()`/`duration()` (score-seconds) for the continuous piano-roll visualizer. || `singToScore.js` | Sing-to-score transcription for the song system — turns a sung pitch track into lead-sheet notation. `segmentPitchTrack(track, opts)` groups `[{ tMs, hz, clarity }]` frames into note/rest segments (median pitch per stable span, rests where clarity drops, sub-threshold note/rest filtering); `quantizeSegments(segments, { bpm, beatValue })` snaps each duration to the nearest grid value (w/h/q/e/s) at the song tempo; `segmentsToScoreDsl(quantized, { keySig, beatsPerBar, beatValue })` spells notes enharmonically from the key signature and emits measure-grouped `\| … \|` body text; `transcribePitchTrack(track, { bpm, key, beatsPerBar, beatValue })` runs all three. Round-trips cleanly back through `parseScore`. Reuses `frequencyToNote` (pitchDetect) + the duration/key tables (scoreNotation) — no DSP/notation library. |diff --git a/client/src/lib/referenceAnalysis.js b/client/src/lib/referenceAnalysis.jsindex 9e0bd31964..f66104f363 100644--- a/client/src/lib/referenceAnalysis.js+++ b/client/src/lib/referenceAnalysis.js@@ -141,6 +141,297 @@ export const proposeSegmentScore = (samples, sampleRate, opts = {}) => {return { track, body, text: buildScoreText({ key, tempo: bpm, beatsPerBar, beatValue, body }) };};+// === Stacked-mix extraction (spectral diff, #2121) ======================+//+// Layered TikTok builds often never expose a new voice ALONE — it enters over+// a mix that already carries the earlier layers. The solo pipeline above can't+// touch those. This section extracts the NEW voice from the stacked segment by+// spectral subtraction: average the magnitude spectrum of a "backing" window+// taken just BEFORE the voice enters (the layers already present), subtract+// that static profile from each frame of the "after" window, and run+// frequency-domain f0 estimation on the residual — which is dominated by the+// newly-added harmonic series. The resulting `[{ tMs, hz, clarity }]` track+// feeds the exact same `transcribePitchTrack` half `proposeSegmentScore` uses.+//+// Still pure local DSP — a hand-rolled radix-2 FFT (PortOS keeps its audio+// stack library-free, same rationale as `pitchDetect.js`'s NSDF core) and a+// weighted harmonic-sum pitch estimator. Zero LLM calls.++// Spectral analysis window. A power of two is required by the radix-2 FFT; 2048+// spans ≥2 periods of the lowest searched pitch at both common rates and gives+// ~7–21 Hz bins (16–48 kHz) — coarse alone, but the harmonic-sum estimator+// interpolates between bins over a fine candidate grid, so effective f0+// resolution is far finer than the bin spacing.+export const DEFAULT_FFT_SIZE = 2048;++// Spectral subtraction can only estimate the backing profile; residual hiss and+// reverb tails leave the extracted voice noisier than a clean solo take, so the+// stacked pipeline defaults to a laxer clarity gate than the solo threshold.+export const STACKED_CLARITY_THRESHOLD = 0.55;++// In-place iterative radix-2 Cooley–Tukey FFT over parallel real/imag arrays+// (length must be a power of two). Decimation-in-time with an initial+// bit-reversal permutation — the textbook form, kept tiny and dependency-free.+const fftInPlace = (re, im) => {+ const n = re.length;+ // Bit-reversal permutation.+ for (let i = 1, j = 0; i < n; i++) {+ let bit = n >> 1;+ for (; j & bit; bit >>= 1) j ^= bit;+ j ^= bit;+ if (i < j) {+ const tr = re[i]; re[i] = re[j]; re[j] = tr;+ const ti = im[i]; im[i] = im[j]; im[j] = ti;+ }+ }+ // Butterflies, doubling the transform length each stage.+ for (let len = 2; len <= n; len <<= 1) {+ const ang = (-2 * Math.PI) / len;+ const wRe = Math.cos(ang);+ const wIm = Math.sin(ang);+ for (let start = 0; start < n; start += len) {+ let curRe = 1;+ let curIm = 0;+ for (let k = 0; k < len >> 1; k++) {+ const i0 = start + k;+ const i1 = i0 + (len >> 1);+ const tRe = re[i1] * curRe - im[i1] * curIm;+ const tIm = re[i1] * curIm + im[i1] * curRe;+ re[i1] = re[i0] - tRe;+ im[i1] = im[i0] - tIm;+ re[i0] += tRe;+ im[i0] += tIm;+ const nextRe = curRe * wRe - curIm * wIm;+ curIm = curRe * wIm + curIm * wRe;+ curRe = nextRe;+ }+ }+ }+};++/**+ * Hann-windowed magnitude spectrum of a real frame. Returns the first+ * `fftSize/2` magnitude bins (bin b ↔ b·sampleRate/fftSize Hz). The window+ * tapers frame edges so a note that doesn't align to the frame boundary+ * doesn't smear energy across the whole spectrum. Returns null if the frame is+ * too short for the requested (power-of-two) size.+ *+ * @param {Float32Array|number[]} frame — real PCM samples (length ≥ fftSize).+ * @param {object} [opts]+ * @param {number} [opts.fftSize] — power-of-two transform length.+ * @returns {Float32Array|null} — `fftSize/2` magnitudes, or null.+ */+export const magnitudeSpectrum = (frame, { fftSize = DEFAULT_FFT_SIZE } = {}) => {+ const size = frame?.length || 0;+ if (size < fftSize || fftSize < 2 || (fftSize & (fftSize - 1)) !== 0) return null;+ const re = new Float64Array(fftSize);+ const im = new Float64Array(fftSize);+ for (let i = 0; i < fftSize; i++) {+ // Hann window: 0.5·(1 − cos(2πi/(N−1))).+ const w = 0.5 * (1 - Math.cos((2 * Math.PI * i) / (fftSize - 1)));+ re[i] = frame[i] * w;+ }+ fftInPlace(re, im);+ const half = fftSize >> 1;+ const mag = new Float32Array(half);+ for (let b = 0; b < half; b++) mag[b] = Math.hypot(re[b], im[b]);+ return mag;+};++/**+ * Average Hann-windowed magnitude spectrum across the frames of a time window —+ * the static "backing" profile for spectral subtraction. Slides `fftSize`-wide+ * frames by `hopMs` over [startMs, endMs) and means the per-frame magnitudes.+ *+ * @returns {Float32Array|null} — mean magnitude bins, or null when the window+ * holds no full frame (too short to analyze — the caller degrades to no+ * subtraction rather than crashing).+ */+export const averageMagnitudeSpectrum = (samples, sampleRate, opts = {}) => {+ const {+ startMs = 0, endMs = null,+ fftSize = DEFAULT_FFT_SIZE, hopMs = DEFAULT_HOP_MS,+ } = opts;+ const total = samples?.length || 0;+ if (!total || !Number.isFinite(sampleRate) || sampleRate <= 0) return null;+ const startSample = Math.max(0, Math.floor((startMs / 1000) * sampleRate));+ const endSample = endMs != null+ ? Math.min(total, Math.ceil((endMs / 1000) * sampleRate))+ : total;+ const hop = Math.max(1, Math.round((hopMs / 1000) * sampleRate));++ const half = fftSize >> 1;+ const sum = new Float64Array(half);+ let frames = 0;+ for (let pos = startSample; pos + fftSize <= endSample; pos += hop) {+ const frame = samples.subarray+ ? samples.subarray(pos, pos + fftSize)+ : samples.slice(pos, pos + fftSize);+ const mag = magnitudeSpectrum(frame, { fftSize });+ if (!mag) continue;+ for (let b = 0; b < half; b++) sum[b] += mag[b];+ frames += 1;+ }+ if (!frames) return null;+ const avg = new Float32Array(half);+ for (let b = 0; b < half; b++) avg[b] = sum[b] / frames;+ return avg;+};++// Linear-interpolated magnitude at an arbitrary frequency (bins are discrete;+// a candidate f0 and its harmonics rarely land on a bin center). Out-of-range+// frequencies read as 0.+const interpMagAt = (mag, hz, sampleRate, fftSize) => {+ const bin = (hz * fftSize) / sampleRate;+ if (bin < 0 || bin >= mag.length - 1) return 0;+ const lo = Math.floor(bin);+ const frac = bin - lo;+ return mag[lo] * (1 - frac) + mag[lo + 1] * frac;+};++// Median of a Float32Array/number list (copy-sorted; small arrays here).+const medianOf = (values) => {+ if (!values.length) return 0;+ const sorted = Array.prototype.slice.call(values).sort((a, b) => a - b);+ const mid = sorted.length >> 1;+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;+};++/**+ * Estimate the fundamental frequency of a magnitude spectrum by weighted+ * harmonic sum. For each candidate f0 on a ~5-cent grid across [minHz, maxHz]+ * we sum interpolated magnitudes at its harmonics k·f0 (k = 1…H, below+ * Nyquist) weighted by 1/k. The 1/k weighting favors the TRUE fundamental over+ * its octave errors: f0/2 misses the strong first harmonic (its k=1 term lands+ * on empty spectrum) and 2·f0 drops the fundamental term entirely, so both+ * score below the real f0 — the frequency-domain analogue of the NSDF core's+ * first-strong-peak trick. `clarity` is the residual prominence of the winning+ * candidate over the grid's median score, in [0, 1]: a clean harmonic series+ * towers over a mostly-empty grid (→ 1); broadband noise scores flat (→ 0).+ *+ * @returns {{ hz:number, clarity:number }|null} — null for an empty/flat+ * spectrum with no candidate carrying energy.+ */+export const estimateSpectralF0 = (mag, sampleRate, fftSize, opts = {}) => {+ const { minHz = 70, maxHz = 1200, maxHarmonics = 8 } = opts;+ if (!mag?.length || !Number.isFinite(sampleRate) || sampleRate <= 0) return null;+ const nyquist = sampleRate / 2;+ const hiHz = Math.min(maxHz, nyquist);+ if (minHz <= 0 || hiHz <= minHz) return null;++ // ~5-cent candidate spacing (2^(5/1200)) — finer than a semitone by 20×,+ // far below the note-onset resolution the transcription grid needs.+ const step = Math.pow(2, 5 / 1200);+ const scores = [];+ let best = null;+ for (let f = minHz; f <= hiHz; f *= step) {+ let s = 0;+ for (let k = 1; k <= maxHarmonics; k++) {+ const hk = k * f;+ if (hk >= nyquist) break;+ s += interpMagAt(mag, hk, sampleRate, fftSize) / k;+ }+ scores.push(s);+ if (!best || s > best.score) best = { hz: f, score: s };+ }+ if (!best || best.score <= 0) return null;+ const floor = medianOf(scores);+ const clarity = Math.max(0, Math.min(1, 1 - floor / best.score));+ return { hz: best.hz, clarity };+};++/**+ * Extract a pitch track for a NEW voice that enters over a stacked mix (#2121).+ * Builds a backing magnitude profile from [bgStartMs, bgEndMs) — a slice just+ * before the voice enters, carrying only the earlier layers — then, per frame+ * of the [startMs, endMs) "after" window, subtracts that profile+ * (over-subtraction factor `overSubtract`, rectified at 0) and runs+ * `estimateSpectralF0` on the residual. Emits the same segment-relative+ * `[{ tMs, hz, clarity }]` shape as `extractPitchTrack`, so it drops straight+ * into `transcribePitchTrack`. With no usable backing window it degrades to+ * plain spectral f0 on the mix (no subtraction) rather than failing.+ *+ * @param {Float32Array} samples — mono PCM of the WHOLE reference audio.+ * @param {number} sampleRate+ * @param {object} opts+ * @param {number} opts.startMs / {number} opts.endMs — the stacked segment.+ * @param {number} [opts.bgStartMs] / {number} [opts.bgEndMs] — backing window.+ * @param {number} [opts.overSubtract=1] — spectral-subtraction strength.+ * @param {number} [opts.fftSize] / {number} [opts.hopMs] / {number} [opts.minHz] / {number} [opts.maxHz]+ * @returns {Array<{tMs:number, hz:number|null, clarity:number}>}+ */+export const extractSpectralDiffTrack = (samples, sampleRate, opts = {}) => {+ const {+ startMs = 0, endMs = null,+ bgStartMs = null, bgEndMs = null,+ fftSize = DEFAULT_FFT_SIZE, hopMs = DEFAULT_HOP_MS,+ minHz = 70, maxHz = 1200, overSubtract = 1,+ } = opts;+ const total = samples?.length || 0;+ if (!total || !Number.isFinite(sampleRate) || sampleRate <= 0) return [];++ // Backing profile from the pre-entrance window (null → no subtraction).+ const backing = (bgStartMs != null && bgEndMs != null && bgEndMs > bgStartMs)+ ? averageMagnitudeSpectrum(samples, sampleRate, { startMs: bgStartMs, endMs: bgEndMs, fftSize, hopMs })+ : null;++ const startSample = Math.max(0, Math.floor((startMs / 1000) * sampleRate));+ const endSample = endMs != null+ ? Math.min(total, Math.ceil((endMs / 1000) * sampleRate))+ : total;+ const hop = Math.max(1, Math.round((hopMs / 1000) * sampleRate));+ const half = fftSize >> 1;++ const track = [];+ for (let pos = startSample; pos + fftSize <= endSample; pos += hop) {+ const frame = samples.subarray+ ? samples.subarray(pos, pos + fftSize)+ : samples.slice(pos, pos + fftSize);+ const mag = magnitudeSpectrum(frame, { fftSize });+ const tMs = Math.round(((pos - startSample) / sampleRate) * 1000);+ if (!mag) { track.push({ tMs, hz: null, clarity: 0 }); continue; }+ // Spectral subtraction: rectify (max 0) so removed bins can't go negative.+ if (backing) {+ for (let b = 0; b < half; b++) {+ const r = mag[b] - overSubtract * backing[b];+ mag[b] = r > 0 ? r : 0;+ }+ }+ const res = estimateSpectralF0(mag, sampleRate, fftSize, { minHz, maxHz });+ track.push({ tMs, hz: res ? res.hz : null, clarity: res ? res.clarity : 0 });+ }+ return track;+};++/**+ * Stacked-mix counterpart of `proposeSegmentScore` (#2121): pitch-track the new+ * voice out of a stacked segment via spectral diff, then transcribe it onto the+ * round's tempo/key grid. Pure DSP — no LLM.+ *+ * @param {Float32Array} samples — mono PCM of the WHOLE reference audio.+ * @param {number} sampleRate+ * @param {object} opts — the `extractSpectralDiffTrack` bounds plus+ * `bpm`/`key`/`beatsPerBar`/`beatValue` (quantization + spelling) and an+ * optional `clarityThreshold` override.+ * @returns {{ track: Array, body: string, text: string }}+ */+export const proposeStackedSegmentScore = (samples, sampleRate, opts = {}) => {+ const {+ startMs = 0, endMs = null, bgStartMs = null, bgEndMs = null,+ bpm, key, beatsPerBar = 4, beatValue = 4,+ overSubtract = 1,+ clarityThreshold = STACKED_CLARITY_THRESHOLD,+ } = opts;+ const track = extractSpectralDiffTrack(samples, sampleRate, {+ startMs, endMs, bgStartMs, bgEndMs, overSubtract,+ });+ const body = transcribePitchTrack(track, {+ bpm, key, beatsPerBar, beatValue,+ segmentOpts: { clarityThreshold: clarityThreshold ?? DEFAULT_CLARITY_THRESHOLD },+ });+ return { track, body, text: buildScoreText({ key, tempo: bpm, beatsPerBar, beatValue, body }) };+};+// === Proposed-vs-existing bar diff ======================================// Note letter → pitch class (semitones above C), and accidental → shift.diff --git a/client/src/lib/referenceAnalysis.test.js b/client/src/lib/referenceAnalysis.test.jsindex 6328b2ed20..2a41830500 100644--- a/client/src/lib/referenceAnalysis.test.js+++ b/client/src/lib/referenceAnalysis.test.js@@ -6,6 +6,13 @@ import {barPitchClasses,diffScoreBars,REFERENCE_CLARITY_THRESHOLD,+ magnitudeSpectrum,+ averageMagnitudeSpectrum,+ estimateSpectralF0,+ extractSpectralDiffTrack,+ proposeStackedSegmentScore,+ STACKED_CLARITY_THRESHOLD,+ DEFAULT_FFT_SIZE,} from './referenceAnalysis.js';// Synthesize a sine tone as Float32 PCM. Amplitude well above the detector's@@ -26,6 +33,31 @@ const concat = (...parts) => {return out;};+// A voice-like tone: a fundamental plus a couple of decaying harmonics, so the+// harmonic-sum estimator has a real overtone series to lock onto (a pure sine+// is the degenerate one-harmonic case).+const harmonic = (f0, seconds, sampleRate, amp = 0.5) => {+ const n = Math.round(seconds * sampleRate);+ const out = new Float32Array(n);+ for (let i = 0; i < n; i++) {+ const t = i / sampleRate;+ out[i] = amp * (+ Math.sin(2 * Math.PI * f0 * t)+ + 0.5 * Math.sin(2 * Math.PI * 2 * f0 * t)+ + 0.33 * Math.sin(2 * Math.PI * 3 * f0 * t)+ );+ }+ return out;+};++// Sample-wise sum of equal-length Float32Arrays (mixing stacked layers).+const mix = (...parts) => {+ const n = Math.min(...parts.map((p) => p.length));+ const out = new Float32Array(n);+ for (let i = 0; i < n; i++) for (const p of parts) out[i] += p[i];+ return out;+};+const SR = 16000; // the mic-capture rate; keeps the fixtures smalldescribe('extractPitchTrack', () => {@@ -135,3 +167,95 @@ describe('barPitchClasses / diffScoreBars', () => {expect(rows[0].match).toBe(false);});});++// === Stacked-mix spectral-diff extraction (#2121) =========================++describe('magnitudeSpectrum', () => {+ it('peaks at the bin of a pure tone and returns fftSize/2 bins', () => {+ // 500 Hz at 16 kHz, fftSize 2048 → bin 500·2048/16000 = 64.+ const mag = magnitudeSpectrum(sine(500, 1.0, SR), { fftSize: DEFAULT_FFT_SIZE });+ expect(mag).toHaveLength(DEFAULT_FFT_SIZE / 2);+ let argmax = 0;+ for (let b = 1; b < mag.length; b++) if (mag[b] > mag[argmax]) argmax = b;+ expect(Math.abs(argmax - 64)).toBeLessThanOrEqual(1);+ });++ it('returns null when the frame is shorter than the FFT size', () => {+ expect(magnitudeSpectrum(sine(220, 0.01, SR), { fftSize: DEFAULT_FFT_SIZE })).toBeNull();+ });+});++describe('averageMagnitudeSpectrum', () => {+ it('averages to fftSize/2 magnitude bins over a window', () => {+ const avg = averageMagnitudeSpectrum(harmonic(220, 1.0, SR), SR);+ expect(avg).toHaveLength(DEFAULT_FFT_SIZE / 2);+ });++ it('returns null for a window too short to hold one frame', () => {+ expect(averageMagnitudeSpectrum(sine(220, 0.02, SR), SR)).toBeNull();+ expect(averageMagnitudeSpectrum(new Float32Array(0), SR)).toBeNull();+ });+});++describe('estimateSpectralF0', () => {+ it('locks onto the fundamental of a harmonic tone (no octave error)', () => {+ const mag = magnitudeSpectrum(harmonic(220, 1.0, SR).subarray(0, DEFAULT_FFT_SIZE), { fftSize: DEFAULT_FFT_SIZE });+ const res = estimateSpectralF0(mag, SR, DEFAULT_FFT_SIZE);+ expect(res).not.toBeNull();+ expect(res.hz).toBeGreaterThan(212); // not 110 (octave-down)+ expect(res.hz).toBeLessThan(228); // not 440 (octave-up)+ expect(res.clarity).toBeGreaterThan(0.5);+ });++ it('returns null for a flat/empty spectrum', () => {+ expect(estimateSpectralF0(new Float32Array(DEFAULT_FFT_SIZE / 2), SR, DEFAULT_FFT_SIZE)).toBeNull();+ expect(estimateSpectralF0(null, SR, DEFAULT_FFT_SIZE)).toBeNull();+ });+});++describe('extractSpectralDiffTrack', () => {+ it('recovers a new voice entering over a steady backing layer', () => {+ // [0, 0.8s]: C4 (262) alone. [0.8s, 1.8s]: C4 + a NEW A4 (440) on top.+ const backing = harmonic(262, 0.8, SR);+ const stacked = mix(harmonic(262, 1.0, SR), harmonic(440, 1.0, SR));+ const audio = concat(backing, stacked);+ const track = extractSpectralDiffTrack(audio, SR, {+ bgStartMs: 0, bgEndMs: 800, startMs: 800, endMs: 1800,+ });+ const pitched = track.filter((f) => f.hz != null).map((f) => f.hz).sort((a, b) => a - b);+ expect(pitched.length).toBeGreaterThan(5);+ const median = pitched[Math.floor(pitched.length / 2)];+ // Subtracting the backing profile leaves the new A4, not the C4 backing.+ expect(median).toBeGreaterThan(420);+ expect(median).toBeLessThan(460);+ });++ it('returns [] for empty input or a bad sample rate', () => {+ expect(extractSpectralDiffTrack(new Float32Array(0), SR, { startMs: 0, endMs: 100 })).toEqual([]);+ expect(extractSpectralDiffTrack(harmonic(220, 0.5, SR), 0, {})).toEqual([]);+ });++ it('degrades to plain spectral f0 (no subtraction) without a backing window', () => {+ const track = extractSpectralDiffTrack(harmonic(330, 1.0, SR), SR, { startMs: 0, endMs: 1000 });+ const pitched = track.filter((f) => f.hz != null);+ expect(pitched.length).toBeGreaterThan(5);+ });+});++describe('proposeStackedSegmentScore', () => {+ it('transcribes the extracted new voice into a parseable score', () => {+ const audio = concat(harmonic(262, 0.8, SR), mix(harmonic(262, 1.0, SR), harmonic(440, 1.0, SR)));+ const { track, body, text } = proposeStackedSegmentScore(audio, SR, {+ bgStartMs: 0, bgEndMs: 800, startMs: 800, endMs: 1800, bpm: 60, key: 'C',+ });+ expect(track.length).toBeGreaterThan(0);+ expect(body).toMatch(/A4/);+ expect(text).toContain('key: C');+ expect(text).toContain('tempo: 60');+ });++ it('exposes a stacked clarity gate in (0, 1)', () => {+ expect(STACKED_CLARITY_THRESHOLD).toBeGreaterThan(0);+ expect(STACKED_CLARITY_THRESHOLD).toBeLessThan(1);+ });+});diff --git a/server/routes/rounds.js b/server/routes/rounds.jsindex 9ecbe3e1a1..ea08398f9f 100644--- a/server/routes/rounds.js+++ b/server/routes/rounds.js@@ -110,10 +110,15 @@ const scorePartSchema = z.object({// One labeled time range on a reference's attached audio (#2106). The service// clamps times and drops zero/negative-length spans; the schema only types the// fields (startMs/endMs required — a span without both selects nothing).+// `bgStartMs`/`bgEndMs` are the optional stacked-mix backing window (#2121) —+// a slice just before the voice enters, used to spectral-subtract the earlier+// layers; the service drops the pair unless it forms a valid positive range.const refSegmentSchema = z.object({layerId: str(svc.ID_MAX_LENGTH).optional().default(''),startMs: z.number(),endMs: z.number(),+ bgStartMs: z.number().optional(),+ bgEndMs: z.number().optional(),});// A reference link/video (e.g. a TikTok performance). `url` is required; thediff --git a/server/routes/rounds.test.js b/server/routes/rounds.test.jsindex 8effffe46d..ea6bbd0baa 100644--- a/server/routes/rounds.test.js+++ b/server/routes/rounds.test.js@@ -173,6 +173,22 @@ describe('rounds route', () => {expect(patch.references[0].url).toBe('https://www.tiktok.com/@u/video/123');});+ it('PUT /:id passes a segment stacked-mix backing window through validation (#2121)', async () => {+ // The Zod schema strips unknown keys, so bgStartMs/bgEndMs must be typed on+ // refSegmentSchema or they'd never reach the service sanitizer.+ mocks.updateRound.mockResolvedValue({ id: 'song-1' });+ const res = await request(makeApp()).put('/api/rounds/song-1').send({+ references: [{+ url: 'https://www.tiktok.com/@u/video/123',+ audioFilename: 'ref.wav',+ segments: [{ layerId: 'alto', startMs: 8000, endMs: 16000, bgStartMs: 4000, bgEndMs: 8000 }],+ }],+ });+ expect(res.status).toBe(200);+ const [, patch] = mocks.updateRound.mock.calls[0];+ expect(patch.references[0].segments[0]).toMatchObject({ bgStartMs: 4000, bgEndMs: 8000 });+ });+it('PUT /:id rejects a reference without a url', async () => {const res = await request(makeApp()).put('/api/rounds/song-1').send({references: [{ label: 'no url' }],diff --git a/server/services/rounds.js b/server/services/rounds.jsindex fb62499570..2f875f9085 100644--- a/server/services/rounds.js+++ b/server/services/rounds.js@@ -254,6 +254,12 @@ const sanitizeRecording = (r) => {// times are clamped non-negative integers and a zero/negative-length span is// dropped (it selects no audio). Used by the client's analysis view to extract// a per-layer pitch track from the span.+//+// Optional stacked-mix backing window (#2121): `bgStartMs`/`bgEndMs` mark a+// slice just BEFORE the voice enters (the earlier layers alone) so the client+// can spectral-subtract the backing and extract a voice that never appears+// solo. Purely additive — the pair only persists together when it forms a+// valid positive-length range, so a legacy solo segment round-trips unchanged.const sanitizeRefSegment = (s) => {if (!s || typeof s !== 'object') return null;const startRaw = finiteOrNull(s.startMs);@@ -262,11 +268,22 @@ const sanitizeRefSegment = (s) => {const startMs = Math.max(0, Math.round(startRaw));const endMs = Math.max(0, Math.round(endRaw));if (endMs <= startMs) return null;- return {+ const seg = {layerId: trimField(s.layerId, ID_MAX_LENGTH),startMs,endMs,};+ const bgStartRaw = finiteOrNull(s.bgStartMs);+ const bgEndRaw = finiteOrNull(s.bgEndMs);+ if (bgStartRaw !== null && bgEndRaw !== null) {+ const bgStartMs = Math.max(0, Math.round(bgStartRaw));+ const bgEndMs = Math.max(0, Math.round(bgEndRaw));+ if (bgEndMs > bgStartMs) {+ seg.bgStartMs = bgStartMs;+ seg.bgEndMs = bgEndMs;+ }+ }+ return seg;};// One reference link/video ({ id, url, label, note }) — external studydiff --git a/server/services/rounds.test.js b/server/services/rounds.test.jsindex c0f63c27e9..6bffcca457 100644--- a/server/services/rounds.test.js+++ b/server/services/rounds.test.js@@ -391,6 +391,26 @@ describe('rounds service', () => {]);});+ it('persists a stacked-mix backing window only when valid; drops it otherwise (#2121)', () => {+ const song = svc.sanitizeRound({+ id: 'x',+ references: [{+ url: 'https://example.com',+ audioFilename: 'ref.wav',+ segments: [+ { layerId: 'lead', startMs: 8000, endMs: 16000, bgStartMs: 4000.6, bgEndMs: 8000.2 }, // valid, rounded+ { layerId: 'bass', startMs: 20000, endMs: 24000, bgStartMs: 9000, bgEndMs: 9000 }, // zero-length bg → dropped+ { layerId: 'alto', startMs: 30000, endMs: 34000, bgStartMs: 'x', bgEndMs: 29000 }, // non-finite bg → dropped+ ],+ }],+ });+ expect(song.references[0].segments).toEqual([+ { layerId: 'lead', startMs: 8000, endMs: 16000, bgStartMs: 4001, bgEndMs: 8000 },+ { layerId: 'bass', startMs: 20000, endMs: 24000 },+ { layerId: 'alto', startMs: 30000, endMs: 34000 },+ ]);+ });+it('drops malformed reference segments and bounds the list (#2106)', () => {const song = svc.sanitizeRound({id: 'x',