Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat([issue-2106]): reference-audio analysis — attach audio to round references and extract per-layer parts

Adam Eivycff485c79547
diff --git a/client/src/components/songs/ReferenceAnalysis.jsx b/client/src/components/songs/ReferenceAnalysis.jsx
new file mode 100644
index 0000000000..2ebf6a88d2
--- /dev/null
+++ b/client/src/components/songs/ReferenceAnalysis.jsx
@@ -0,0 +1,617 @@
+/**
+ * ReferenceAnalysis — analyze a round reference's attached audio (#2106).
+ *
+ * The workbench view behind `/rounds/:id?analyze=<refId>`: waveform + playback
+ * of the reference audio, labeled time-range segments ("0:00–0:14 melody
+ * alone"), per-segment offline pitch extraction (the solo-segment path — pure
+ * local DSP through `referenceAnalysis.js`, zero LLM calls), and a
+ * side-by-side review diff of the proposed part against a stored scorePart
+ * with per-bar pitch-class mismatch highlighting. Nothing auto-applies:
+ * "Apply" merges the proposed part into the parent's scoreParts DRAFT and the
+ * user persists it with the editor's normal Save (the same explicit-save model
+ * every other Rounds surface uses).
+ *
+ * Also exports `ReferenceAudioAttach` — the edit-tab controls that get audio
+ * ONTO a reference in the first place: file upload (screen-record / download
+ * with your own tools) or mic capture while the reference video plays (the
+ * zero-dependency path). Both ride the same /api/uploads flow recordings use.
+ *
+ * State model: this component owns only ephemeral analysis state (decoded
+ * PCM, the in-review proposal). All persisted fields (audioFilename,
+ * segments) round-trip through the parent's draft via `onUpdateReference`,
+ * so the header Save button persists everything at once.
+ */
+
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import {
+ ArrowLeft, AudioLines, Flag, FlagOff, 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 { scoreHasMusic } from '../../lib/scoreNotation';
+import { harmonyPartLabel } from '../../lib/songCraft';
+
+// Client-side guard for the base64-JSON upload path: the server body limit is
+// 55 MB and base64 inflates ~4/3, so cap the raw file well under that.
+const MAX_AUDIO_BYTES = 35 * 1024 * 1024;
+
+// Mirror services/rounds.js REF_SEGMENTS_MAX / SCORE_PARTS_MAX — used only to
+// disable adding more client-side; the server enforces the real bounds.
+const REF_SEGMENTS_MAX = 24;
+
+const msToSec = (ms) => (Math.max(0, ms) / 1000).toFixed(1);
+const secToMs = (raw) => {
+ const n = Number(raw);
+ return Number.isFinite(n) ? Math.max(0, Math.round(n * 1000)) : 0;
+};
+
+// --- Attach controls (edit-tab reference card) ------------------------------
+
+/**
+ * Upload-or-record controls for attaching audio to one reference. Calls
+ * `onUpdate(key, value)` against the parent draft (same contract as the other
+ * reference fields); the file itself is uploaded immediately so it exists,
+ * matching the recordings flow (upload now, persist the filename on Save).
+ */
+export function ReferenceAudioAttach({ reference, onUpdate }) {
+ const [busy, setBusy] = useState(false);
+ const [recording, setRecording] = useState(false);
+ const fileRef = useRef(null);
+ const handleRef = useRef(null);
+
+ // Never leave the mic open on unmount (deferred-work cleanup rule).
+ useEffect(() => () => { handleRef.current?.cancel(); }, []);
+
+ const saveUpload = useCallback(async (base64, name) => {
+ setBusy(true);
+ const result = await uploadFile(base64, name, { silent: true }).catch((err) => {
+ toast.error(err?.message || 'Failed to upload audio');
+ return null;
+ });
+ setBusy(false);
+ if (!result?.filename) return;
+ onUpdate('audioFilename', result.filename);
+ toast.success('Audio attached — Save the song to keep it');
+ }, [onUpdate]);
+
+ const onFile = useCallback(async (e) => {
+ const file = e.target.files?.[0];
+ e.target.value = ''; // allow re-picking the same file
+ if (!file) return;
+ if (file.size > MAX_AUDIO_BYTES) {
+ toast.error(`Audio file too large (max ${Math.round(MAX_AUDIO_BYTES / 1024 / 1024)} MB)`);
+ return;
+ }
+ const bytes = await file.arrayBuffer();
+ await saveUpload(arrayBufferToBase64(bytes), file.name || 'reference-audio');
+ }, [saveUpload]);
+
+ const startRecord = useCallback(async () => {
+ const handle = await startMemoRecording().catch((err) => {
+ toast.error(err?.message || 'Microphone access denied');
+ return null;
+ });
+ if (!handle) return;
+ handleRef.current = handle;
+ setRecording(true);
+ }, []);
+
+ const stopRecord = useCallback(async () => {
+ const handle = handleRef.current;
+ if (!handle) return;
+ handleRef.current = null;
+ setRecording(false);
+ const take = await handle.stop().catch((err) => {
+ toast.error(err?.message || 'Recording failed');
+ return null;
+ });
+ if (!take) return;
+ const ts = new Date().toISOString().replace(/[:.]/g, '-');
+ await saveUpload(take.audioBase64, `ref-${ts}.wav`);
+ }, [saveUpload]);
+
+ if (reference.audioFilename) {
+ return (
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="flex items-center gap-1.5 text-xs text-port-success">
+ <AudioLines size={14} /> Audio attached
+ </span>
+ <audio controls preload="none" src={getUploadUrl(reference.audioFilename)} className="h-8 max-w-[180px]" />
+ <button
+ type="button"
+ onClick={() => onUpdate('audioFilename', '')}
+ className="flex items-center gap-1 px-2 py-1 text-xs rounded-lg border border-port-border text-gray-400 hover:text-port-error"
+ >
+ <X size={13} /> Remove audio
+ </button>
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-wrap items-center gap-2">
+ <input ref={fileRef} type="file" accept="audio/*" onChange={onFile} className="hidden" aria-label="Upload reference audio file" />
+ <button
+ type="button"
+ onClick={() => fileRef.current?.click()}
+ disabled={busy || recording}
+ className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50 disabled:opacity-50"
+ >
+ {busy ? <Loader2 size={14} className="animate-spin" /> : <Upload size={14} />} Upload audio
+ </button>
+ {recording ? (
+ <button type="button" onClick={stopRecord} className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs rounded-lg bg-port-error text-white hover:bg-port-error/90 animate-pulse">
+ <Square size={14} /> Stop capture
+ </button>
+ ) : (
+ <button
+ type="button"
+ onClick={startRecord}
+ disabled={busy}
+ title="Record through the mic while the reference video plays"
+ className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50 disabled:opacity-50"
+ >
+ <Mic size={14} /> Capture from mic
+ </button>
+ )}
+ <span className="text-xs text-gray-600">Upload a screen-recording’s audio, or capture the mic while the video plays.</span>
+ </div>
+ );
+}
+
+// --- Waveform ----------------------------------------------------------------
+
+// Static min/max-peak waveform with segment bands. Click seeks; the playhead
+// is an overlaid div driven by the <audio> timeupdate (no rAF loop needed).
+function Waveform({ samples, durationMs, segments, playheadMs, onSeek }) {
+ const canvasRef = useRef(null);
+
+ useEffect(() => {
+ const canvas = canvasRef.current;
+ if (!canvas || !samples?.length) return;
+ const ctx = canvas.getContext('2d');
+ if (!ctx) return; // jsdom / non-canvas environments
+ const { width: w, height: h } = canvas;
+ ctx.clearRect(0, 0, w, h);
+ // Segment bands under the peaks.
+ for (const seg of segments || []) {
+ const x0 = (seg.startMs / durationMs) * w;
+ const x1 = (seg.endMs / durationMs) * w;
+ ctx.fillStyle = 'rgba(59, 130, 246, 0.18)'; // port-accent @ low alpha
+ ctx.fillRect(x0, 0, Math.max(1, x1 - x0), h);
+ }
+ // Min/max peaks per column.
+ const per = Math.max(1, Math.floor(samples.length / w));
+ ctx.fillStyle = 'rgba(148, 163, 184, 0.9)';
+ for (let x = 0; x < w; x++) {
+ let min = 1;
+ let max = -1;
+ const start = x * per;
+ const end = Math.min(samples.length, start + per);
+ for (let i = start; i < end; i++) {
+ const v = samples[i];
+ if (v < min) min = v;
+ if (v > max) max = v;
+ }
+ if (min > max) continue;
+ const y0 = ((1 - max) / 2) * h;
+ const y1 = ((1 - min) / 2) * h;
+ ctx.fillRect(x, y0, 1, Math.max(1, y1 - y0));
+ }
+ }, [samples, durationMs, segments]);
+
+ const seek = (e) => {
+ if (!durationMs || !onSeek) return;
+ const rect = e.currentTarget.getBoundingClientRect();
+ const ratio = Math.min(1, Math.max(0, (e.clientX - rect.left) / rect.width));
+ onSeek(ratio * durationMs);
+ };
+
+ return (
+ <div className="relative w-full cursor-pointer" onClick={seek} role="presentation">
+ <canvas ref={canvasRef} width={800} height={96} className="w-full h-24 rounded-lg bg-port-bg border border-port-border" />
+ {durationMs > 0 && playheadMs != null && (
+ <div
+ aria-hidden="true"
+ className="absolute top-0 bottom-0 w-px bg-port-accent"
+ style={{ left: `${Math.min(100, (playheadMs / durationMs) * 100)}%` }}
+ />
+ )}
+ </div>
+ );
+}
+
+// --- Analysis view -----------------------------------------------------------
+
+export default function ReferenceAnalysis({
+ reference, layers = [], scoreParts = [], tempo = null, songKey = '',
+ onUpdateReference, onApplyPart, onClose,
+}) {
+ const audioRef = useRef(null);
+ const [decoded, setDecoded] = useState(null); // { samples, sampleRate, durationMs }
+ const [decodeError, setDecodeError] = useState(null);
+ const [playheadMs, setPlayheadMs] = useState(0);
+ const playUntilRef = useRef(null); // stop time (ms) for "play segment"
+ const [extracting, setExtracting] = useState(false);
+ // The in-review proposal: { layerId, text } — text is user-editable.
+ const [proposal, setProposal] = useState(null);
+ const [compareId, setCompareId] = useState('');
+
+ const segments = reference?.segments || [];
+ const audioFilename = reference?.audioFilename || '';
+
+ // Decode the attached audio once per filename — mono PCM for the extractor
+ // and the waveform. Errors degrade to a message (segments stay editable).
+ useEffect(() => {
+ let cancelled = false;
+ setDecoded(null);
+ setDecodeError(null);
+ if (!audioFilename) return undefined;
+ const Ctx = window.AudioContext || window.webkitAudioContext;
+ if (!Ctx) { setDecodeError('Web Audio is not available in this browser.'); return undefined; }
+ (async () => {
+ const res = await fetch(getUploadUrl(audioFilename));
+ if (!res.ok) throw new Error(`Audio fetch failed (${res.status})`);
+ const bytes = await res.arrayBuffer();
+ const ctx = new Ctx();
+ const buffer = await ctx.decodeAudioData(bytes).finally(() => { ctx.close().catch(() => {}); });
+ if (cancelled) return;
+ setDecoded({
+ samples: buffer.getChannelData(0),
+ sampleRate: buffer.sampleRate,
+ durationMs: Math.round(buffer.duration * 1000),
+ });
+ })().catch((err) => {
+ if (!cancelled) setDecodeError(err?.message || 'Could not decode the reference audio.');
+ });
+ return () => { cancelled = true; };
+ }, [audioFilename]);
+
+ const durationMs = decoded?.durationMs || 0;
+
+ const setSegments = useCallback((next) => {
+ onUpdateReference?.(reference.id, 'segments', next);
+ }, [onUpdateReference, reference?.id]);
+
+ const currentMs = () => Math.round((audioRef.current?.currentTime || 0) * 1000);
+
+ const addSegment = useCallback(() => {
+ const start = currentMs();
+ const end = Math.min(durationMs || start + 8000, start + 8000);
+ setSegments([...segments, { layerId: '', startMs: start, endMs: Math.max(end, start + 1000) }]);
+ }, [segments, setSegments, durationMs]);
+
+ const updateSegment = useCallback((idx, patch) => {
+ setSegments(segments.map((s, i) => (i === idx ? { ...s, ...patch } : s)));
+ }, [segments, setSegments]);
+
+ const removeSegment = useCallback((idx) => {
+ setSegments(segments.filter((_, i) => i !== idx));
+ }, [segments, setSegments]);
+
+ const seekTo = useCallback((ms) => {
+ const el = audioRef.current;
+ if (!el) return;
+ el.currentTime = ms / 1000;
+ setPlayheadMs(ms);
+ }, []);
+
+ const playSegment = useCallback((seg) => {
+ const el = audioRef.current;
+ if (!el) return;
+ playUntilRef.current = seg.endMs;
+ el.currentTime = seg.startMs / 1000;
+ el.play().catch(() => { /* browser autoplay policy — user can press play */ });
+ }, []);
+
+ const onTimeUpdate = useCallback(() => {
+ const el = audioRef.current;
+ if (!el) return;
+ const ms = el.currentTime * 1000;
+ setPlayheadMs(ms);
+ if (playUntilRef.current != null && ms >= playUntilRef.current) {
+ playUntilRef.current = null;
+ el.pause();
+ }
+ }, []);
+
+ const layerLabel = useCallback((layerId) => {
+ if (!layerId) return 'Unassigned';
+ return layers.find((l) => l.id === layerId)?.label || layerId;
+ }, [layers]);
+
+ // Extract a proposed score from one solo-sung segment (pure local DSP).
+ const extractSegment = useCallback((seg) => {
+ if (!decoded) return;
+ setExtracting(true);
+ // Yield a frame so the button's busy state paints before the O(n·lag) DSP.
+ setTimeout(() => {
+ const { text } = proposeSegmentScore(decoded.samples, decoded.sampleRate, {
+ startMs: seg.startMs,
+ endMs: seg.endMs,
+ bpm: Number.isFinite(tempo) && tempo > 0 ? tempo : undefined,
+ key: songKey || 'C',
+ });
+ setExtracting(false);
+ if (!text) {
+ toast.error('No clear sung pitch detected in that segment — try a tighter range around a solo voice.');
+ return;
+ }
+ setProposal({ layerId: seg.layerId, text });
+ // Default the comparison to the stored part whose role matches the
+ // segment's layer (layer ids double as harmony-part roles).
+ const match = scoreParts.find((p) => p.role === seg.layerId);
+ setCompareId(match?.id || '');
+ }, 30);
+ }, [decoded, tempo, songKey, scoreParts]);
+
+ const comparePart = useMemo(
+ () => scoreParts.find((p) => p.id === compareId) || null,
+ [scoreParts, compareId],
+ );
+
+ const diffRows = useMemo(() => {
+ if (!proposal?.text || !comparePart?.score) return null;
+ return diffScoreBars(proposal.text, comparePart.score);
+ }, [proposal?.text, comparePart?.score]);
+
+ const pcNames = (pcs) => (pcs && pcs.length ? pcs.map((pc) => PITCH_CLASS_NAMES[pc]).join(' ') : '—');
+
+ const applyProposal = useCallback(() => {
+ if (!proposal?.text || !scoreHasMusic(proposal.text)) {
+ toast.error('The proposed part has no parseable notes to apply.');
+ return;
+ }
+ onApplyPart?.({
+ id: comparePart?.id || '',
+ label: comparePart?.label || (proposal.layerId ? harmonyPartLabel(proposal.layerId) : 'Extracted part'),
+ role: comparePart?.role ?? (proposal.layerId || ''),
+ score: proposal.text,
+ });
+ }, [proposal, comparePart, onApplyPart]);
+
+ // Deep-link fallbacks: stale ?analyze= id, or a reference with no audio yet.
+ if (!reference) {
+ return (
+ <div className="max-w-3xl mx-auto p-6 space-y-3">
+ <p className="text-sm text-gray-400">That reference no longer exists on this round.</p>
+ <button type="button" onClick={onClose} className="flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg border border-port-border text-gray-300 hover:text-white">
+ <ArrowLeft size={14} /> Back to round
+ </button>
+ </div>
+ );
+ }
+ if (!audioFilename) {
+ return (
+ <div className="max-w-3xl mx-auto p-6 space-y-3">
+ <p className="text-sm text-gray-400">This reference has no attached audio yet. Attach audio from the Edit tab’s reference card first.</p>
+ <button type="button" onClick={onClose} className="flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg border border-port-border text-gray-300 hover:text-white">
+ <ArrowLeft size={14} /> Back to round
+ </button>
+ </div>
+ );
+ }
+
+ return (
+ <div className="max-w-5xl mx-auto space-y-5">
+ <div className="flex items-center gap-3 flex-wrap">
+ <button type="button" onClick={onClose} className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs rounded-lg border border-port-border text-gray-300 hover:text-white" aria-label="Back to round">
+ <ArrowLeft size={14} /> Back
+ </button>
+ <h2 className="flex items-center gap-2 text-sm font-semibold text-white">
+ <AudioLines size={15} className="text-port-accent" /> Analyze reference audio
+ </h2>
+ <span className="text-xs text-gray-500 truncate">{reference.label || reference.url}</span>
+ </div>
+ <p className="text-xs text-gray-500">
+ Mark the time ranges where a voice sings alone, then extract each range into a proposed part on this
+ round’s tempo and key grid. Everything here edits the draft — use the header Save to persist.
+ </p>
+
+ {/* Waveform + transport */}
+ <section className="space-y-2">
+ {decodeError ? (
+ <p className="text-xs text-port-error">{decodeError}</p>
+ ) : !decoded ? (
+ <p className="flex items-center gap-2 text-xs text-gray-500"><Loader2 size={14} className="animate-spin" /> Decoding audio…</p>
+ ) : (
+ <Waveform
+ samples={decoded.samples}
+ durationMs={durationMs}
+ segments={segments}
+ playheadMs={playheadMs}
+ onSeek={seekTo}
+ />
+ )}
+ <audio
+ ref={audioRef}
+ controls
+ preload="metadata"
+ src={getUploadUrl(audioFilename)}
+ onTimeUpdate={onTimeUpdate}
+ className="w-full h-9"
+ />
+ </section>
+
+ {/* Segments */}
+ <section className="space-y-2">
+ <div className="flex items-center justify-between">
+ <h3 className="text-sm font-semibold text-white">Segments</h3>
+ <button
+ type="button"
+ onClick={addSegment}
+ disabled={segments.length >= REF_SEGMENTS_MAX}
+ className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50 disabled:opacity-40"
+ >
+ <Plus size={14} /> Add segment at playhead
+ </button>
+ </div>
+ {segments.length === 0 ? (
+ <p className="text-xs text-gray-500">
+ No segments yet. Play the audio, pause where a voice enters alone, and add a segment.
+ </p>
+ ) : (
+ <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>
+ <input
+ type="number"
+ min={0}
+ step={0.1}
+ value={msToSec(seg.startMs)}
+ onChange={(e) => updateSegment(idx, { startMs: secToMs(e.target.value) })}
+ aria-label="Segment start (seconds)"
+ className="w-20 bg-port-bg border border-port-border rounded-lg px-2 py-1 text-xs text-white focus:border-port-accent focus:outline-none"
+ />
+ <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>
+ <input
+ type="number"
+ min={0}
+ step={0.1}
+ value={msToSec(seg.endMs)}
+ onChange={(e) => updateSegment(idx, { endMs: secToMs(e.target.value) })}
+ aria-label="Segment end (seconds)"
+ className="w-20 bg-port-bg border border-port-border rounded-lg px-2 py-1 text-xs text-white focus:border-port-accent focus:outline-none"
+ />
+ <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>
+ ))}
+ </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.
+ </p>
+ </section>
+
+ {/* Proposal review + diff */}
+ {proposal && (
+ <section className="space-y-3 border-t border-port-border pt-4">
+ <div className="flex items-center justify-between flex-wrap gap-2">
+ <h3 className="text-sm font-semibold text-white">Proposed part · {layerLabel(proposal.layerId)}</h3>
+ <div className="flex items-center gap-2">
+ <label htmlFor="ref-compare-part" className="text-xs text-gray-400">Compare / apply to</label>
+ <select
+ id="ref-compare-part"
+ value={compareId}
+ onChange={(e) => setCompareId(e.target.value)}
+ 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="">New part</option>
+ {scoreParts.map((p) => <option key={p.id} value={p.id}>{p.label || p.role || p.id}</option>)}
+ </select>
+ </div>
+ </div>
+
+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
+ <div className="space-y-2">
+ <h4 className="text-xs font-semibold uppercase tracking-wide text-port-accent">Proposed (from audio)</h4>
+ <div className="bg-port-card border border-port-border rounded-lg p-3 overflow-x-auto">
+ <ScoreSheet text={proposal.text} />
+ </div>
+ <textarea
+ value={proposal.text}
+ onChange={(e) => setProposal((prev) => ({ ...prev, text: e.target.value }))}
+ rows={4}
+ aria-label="Proposed part notation"
+ className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-xs text-white font-mono focus:border-port-accent focus:outline-none"
+ />
+ </div>
+ <div className="space-y-2">
+ <h4 className="text-xs font-semibold uppercase tracking-wide text-gray-400">
+ {comparePart ? `Current · ${comparePart.label || comparePart.role}` : 'No stored part selected'}
+ </h4>
+ {comparePart ? (
+ <div className="bg-port-card border border-port-border rounded-lg p-3 overflow-x-auto">
+ <ScoreSheet text={comparePart.score} />
+ </div>
+ ) : (
+ <p className="text-xs text-gray-500">Applying will add this as a new harmony part.</p>
+ )}
+ </div>
+ </div>
+
+ {/* Per-bar pitch-class diff */}
+ {diffRows && (
+ <div className="space-y-1">
+ <h4 className="text-xs font-semibold text-white">Bar-by-bar pitch classes</h4>
+ <div className="flex flex-wrap gap-1.5">
+ {diffRows.map((row) => (
+ <span
+ key={row.bar}
+ title={`Bar ${row.bar} — proposed: ${pcNames(row.proposed)} · current: ${pcNames(row.existing)}`}
+ className={`px-2 py-0.5 text-xs rounded border ${row.match
+ ? 'border-port-success/50 text-port-success'
+ : 'border-port-error/60 text-port-error'}`}
+ >
+ {row.bar}{row.match ? ' ✓' : ' ✕'}
+ </span>
+ ))}
+ </div>
+ <p className="text-xs text-gray-600">
+ ✓ = same pitch classes in order (octave-insensitive). Hover a bar for the notes on each side.
+ </p>
+ </div>
+ )}
+
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={applyProposal}
+ className="flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg bg-port-accent text-white hover:bg-port-accent/90"
+ >
+ {comparePart ? 'Apply to current part' : 'Add as new part'}
+ </button>
+ <button
+ type="button"
+ onClick={() => setProposal(null)}
+ className="px-3 py-1.5 text-xs rounded-lg border border-port-border text-gray-300 hover:text-white"
+ >
+ Discard proposal
+ </button>
+ </div>
+ </section>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/songs/ReferenceAnalysis.test.jsx b/client/src/components/songs/ReferenceAnalysis.test.jsx
new file mode 100644
index 0000000000..f4677003b4
--- /dev/null
+++ b/client/src/components/songs/ReferenceAnalysis.test.jsx
@@ -0,0 +1,200 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+
+// The analysis view's DSP (referenceAnalysis.js) and transcription
+// (singToScore.js) stay REAL — we fake only the browser seams jsdom lacks:
+// fetch (the uploaded audio bytes), AudioContext.decodeAudioData (returns a
+// synthesized sine buffer), and the heavy ScoreSheet SVG renderer.
+
+vi.mock('./ScoreSheet.jsx', () => ({
+ default: ({ text }) => <pre data-testid="scoresheet">{text}</pre>,
+}));
+
+vi.mock('../../services/api', () => ({
+ uploadFile: vi.fn(() => Promise.resolve({ filename: 'up.wav' })),
+ getUploadUrl: (f) => `/api/uploads/${f}`,
+}));
+
+const toastError = vi.fn();
+const toastSuccess = vi.fn();
+vi.mock('../ui/Toast', () => ({ default: { success: (...a) => toastSuccess(...a), error: (...a) => toastError(...a) } }));
+
+vi.mock('../../lib/audioRecorder', () => ({
+ startMemoRecording: vi.fn(),
+ arrayBufferToBase64: vi.fn(() => 'b64'),
+}));
+
+import ReferenceAnalysis, { ReferenceAudioAttach } from './ReferenceAnalysis.jsx';
+
+const SR = 16000;
+const sine = (hz, seconds) => {
+ const n = Math.round(seconds * SR);
+ const out = new Float32Array(n);
+ for (let i = 0; i < n; i++) out[i] = 0.5 * Math.sin((2 * Math.PI * hz * i) / SR);
+ 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);
+ window.AudioContext = function FakeAudioContext() {
+ return {
+ sampleRate: SR,
+ decodeAudioData: () => Promise.resolve({
+ getChannelData: () => samples,
+ sampleRate: SR,
+ duration: 1.0,
+ }),
+ close: () => Promise.resolve(),
+ };
+ };
+ global.fetch = vi.fn(() => Promise.resolve({ ok: true, arrayBuffer: () => Promise.resolve(new ArrayBuffer(8)) }));
+};
+
+const baseRef = {
+ id: 'ref-1',
+ url: 'https://www.tiktok.com/@u/video/1',
+ label: 'Layered build',
+ note: '',
+ audioFilename: 'abc-ref.wav',
+ segments: [{ layerId: 'bass', startMs: 0, endMs: 1000 }],
+};
+const layers = [
+ { id: 'melody', label: 'Melody', part: '', notes: '' },
+ { id: 'bass', label: 'Bass', part: '', notes: '' },
+];
+
+const originalAudioContext = window.AudioContext;
+const originalFetch = global.fetch;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+afterEach(() => {
+ window.AudioContext = originalAudioContext;
+ global.fetch = originalFetch;
+});
+
+describe('ReferenceAnalysis — fallbacks', () => {
+ it('shows a stale-reference fallback and closes', () => {
+ const onClose = vi.fn();
+ render(<ReferenceAnalysis reference={null} onClose={onClose} />);
+ expect(screen.getByText(/no longer exists/i)).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: /back to round/i }));
+ expect(onClose).toHaveBeenCalled();
+ });
+
+ it('shows a no-audio hint for a reference without audio', () => {
+ render(<ReferenceAnalysis reference={{ ...baseRef, audioFilename: '' }} onClose={vi.fn()} />);
+ expect(screen.getByText(/no attached audio yet/i)).toBeTruthy();
+ });
+
+ it('degrades to a decode error when audio cannot be decoded, keeping segments editable', async () => {
+ // jsdom has no AudioContext, so the decode effect reports the Web Audio
+ // gate — the same degraded path a fetch/decode failure lands on.
+ const onUpdateReference = vi.fn();
+ render(
+ <ReferenceAnalysis
+ reference={baseRef}
+ layers={layers}
+ onUpdateReference={onUpdateReference}
+ onClose={vi.fn()}
+ />,
+ );
+ await waitFor(() => expect(screen.getByText(/web audio is not available/i)).toBeTruthy());
+ // The segment row still renders and edits still flow to the parent draft.
+ const layerSelect = screen.getByLabelText('Segment layer');
+ fireEvent.change(layerSelect, { target: { value: 'melody' } });
+ expect(onUpdateReference).toHaveBeenCalledWith('ref-1', 'segments', [
+ { layerId: 'melody', startMs: 0, endMs: 1000 },
+ ]);
+ // Extraction is gated on decoded audio.
+ expect(screen.getByRole('button', { name: /extract part/i }).disabled).toBe(true);
+ });
+});
+
+describe('ReferenceAnalysis — extract → review → apply (solo segment)', () => {
+ it('extracts a proposed part from a solo tone segment and applies it as a new part', async () => {
+ installFakeAudio();
+ const onApplyPart = vi.fn();
+ render(
+ <ReferenceAnalysis
+ reference={baseRef}
+ layers={layers}
+ scoreParts={[]}
+ tempo={60}
+ songKey="C"
+ onUpdateReference={vi.fn()}
+ onApplyPart={onApplyPart}
+ onClose={vi.fn()}
+ />,
+ );
+ // Wait for the decode to land (Extract becomes enabled).
+ const extract = screen.getByRole('button', { name: /extract part/i });
+ await waitFor(() => expect(extract.disabled).toBe(false));
+
+ fireEvent.click(extract);
+ // The proposal renders the transcribed score (220 Hz → A3) once the
+ // deferred DSP tick runs.
+ await waitFor(() => expect(screen.getAllByTestId('scoresheet').length).toBeGreaterThan(0), { timeout: 3000 });
+ const sheets = screen.getAllByTestId('scoresheet');
+ expect(sheets[0].textContent).toMatch(/A3/);
+ expect(sheets[0].textContent).toContain('key: C');
+
+ // No stored parts → applying adds a new part carrying the segment's layer role.
+ fireEvent.click(screen.getByRole('button', { name: /add as new part/i }));
+ expect(onApplyPart).toHaveBeenCalledTimes(1);
+ const part = onApplyPart.mock.calls[0][0];
+ expect(part.id).toBe('');
+ expect(part.role).toBe('bass');
+ expect(part.score).toMatch(/A3/);
+ });
+
+ it('defaults the comparison to the stored part matching the segment layer and diffs bars', async () => {
+ installFakeAudio();
+ const existing = { id: 'part-bass', label: 'Bass', role: 'bass', score: '| A3q |' };
+ const onApplyPart = vi.fn();
+ render(
+ <ReferenceAnalysis
+ reference={baseRef}
+ layers={layers}
+ scoreParts={[existing]}
+ tempo={60}
+ songKey="C"
+ onUpdateReference={vi.fn()}
+ onApplyPart={onApplyPart}
+ onClose={vi.fn()}
+ />,
+ );
+ const extract = screen.getByRole('button', { name: /extract part/i });
+ await waitFor(() => expect(extract.disabled).toBe(false));
+ fireEvent.click(extract);
+ await waitFor(() => expect(screen.getAllByTestId('scoresheet').length).toBeGreaterThan(0), { timeout: 3000 });
+
+ // Comparison select defaulted to the matching stored part → diff chips render.
+ expect(screen.getByLabelText(/compare \/ apply to/i).value).toBe('part-bass');
+ expect(screen.getByText(/bar-by-bar pitch classes/i)).toBeTruthy();
+
+ // Applying to the existing part carries its id (replace, not append).
+ fireEvent.click(screen.getByRole('button', { name: /apply to current part/i }));
+ const part = onApplyPart.mock.calls[0][0];
+ expect(part.id).toBe('part-bass');
+ expect(part.role).toBe('bass');
+ });
+});
+
+describe('ReferenceAudioAttach', () => {
+ it('offers upload + mic capture when no audio is attached', () => {
+ render(<ReferenceAudioAttach reference={{ id: 'r', url: 'https://x.com' }} onUpdate={vi.fn()} />);
+ expect(screen.getByRole('button', { name: /upload audio/i })).toBeTruthy();
+ expect(screen.getByRole('button', { name: /capture from mic/i })).toBeTruthy();
+ });
+
+ it('shows the attached state and clears via Remove audio', () => {
+ const onUpdate = vi.fn();
+ render(<ReferenceAudioAttach reference={{ id: 'r', url: 'https://x.com', audioFilename: 'a.wav' }} onUpdate={onUpdate} />);
+ expect(screen.getByText(/audio attached/i)).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: /remove audio/i }));
+ expect(onUpdate).toHaveBeenCalledWith('audioFilename', '');
+ });
+});
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 0231374f8e..506b8cdaf5 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -110,6 +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. |
| `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/index.js b/client/src/lib/index.js
index 1211550e9f..01666ca05c 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -77,6 +77,7 @@ export * from './lossSparkline.js';
export * from './metronome.js';
export * from './pianoKeyboard.js';
export * from './pitchDetect.js';
+export * from './referenceAnalysis.js';
export * from './scoreNotation.js';
export * from './scorePlayback.js';
export * from './singToScore.js';
diff --git a/client/src/lib/referenceAnalysis.js b/client/src/lib/referenceAnalysis.js
new file mode 100644
index 0000000000..9e0bd31964
--- /dev/null
+++ b/client/src/lib/referenceAnalysis.js
@@ -0,0 +1,197 @@
+// Reference-audio analysis (#2106) — pure helpers behind the Rounds
+// "analyze a reference's attached audio" view. Three concerns, all
+// side-effect-free and unit-tested (no Web Audio here — callers hand us the
+// decoded Float32 samples):
+//
+// 1. extractPitchTrack — offline f0 extraction over decoded PCM: frame the
+// samples, run `detectFrequency` (the shared McLeod/NSDF core the live
+// tuner uses) per frame, and emit the same `[{ tMs, hz, clarity }]` track
+// shape `singToScore` consumes. Runs much faster than realtime because
+// it never waits on an analyser loop.
+// 2. proposeSegmentScore — the solo-segment pipeline: extract a track from a
+// labeled time range, transcribe it through `transcribePitchTrack`
+// (segment → quantize to the round's tempo grid → key-aware spelling),
+// and wrap the body in a score header so it renders/plays standalone.
+// 3. diffScoreBars — the review-side comparison: per-bar pitch-class
+// sequences of a proposed part vs the stored `scorePart`, so the UI can
+// highlight exactly which bars disagree before the user applies anything.
+//
+// Pure local DSP — zero LLM calls (the AI Provider Usage Policy applies to the
+// feature this backs; nothing here touches a provider).
+
+import { detectFrequency } from './pitchDetect.js';
+import { transcribePitchTrack, DEFAULT_CLARITY_THRESHOLD } from './singToScore.js';
+import { parseScore } from './scoreNotation.js';
+
+// === Offline pitch extraction ==========================================
+
+// Analysis window per frame. 2048 samples spans ≥2 periods of the lowest
+// searched pitch at both common rates (16 kHz mic captures, 44.1/48 kHz file
+// uploads), matching the live tuner's analyser fftSize.
+export const DEFAULT_FRAME_SIZE = 2048;
+// Hop between frames, in ms — ~25 ms (~40 tracks/sec) resolves note onsets
+// well below singToScore's 70 ms minimum-note floor without paying for the
+// O(frame·lag) NSDF on every sample.
+export const DEFAULT_HOP_MS = 25;
+
+/**
+ * Extract a pitch track from decoded mono PCM — the offline counterpart of the
+ * live `createPitchTracker`, producing the exact frame shape `singToScore`
+ * consumes. Unclear/silent frames are kept (hz: null) so rests survive into
+ * segmentation.
+ *
+ * @param {Float32Array|number[]} samples — mono PCM (one AudioBuffer channel).
+ * @param {number} sampleRate — samples per second of `samples`.
+ * @param {object} [opts]
+ * @param {number} [opts.startMs=0] — analyze from this offset.
+ * @param {number} [opts.endMs] — analyze up to this offset (default: the end).
+ * @param {number} [opts.frameSize] — analysis window in samples.
+ * @param {number} [opts.hopMs] — hop between frames in ms.
+ * @param {number} [opts.minHz=70] / [opts.maxHz=1200] — vocal search band
+ * (the live tracker's defaults).
+ * @returns {Array<{tMs:number, hz:number|null, clarity:number}>} — `tMs` is
+ * relative to `startMs`, so a segment's track starts at 0.
+ */
+export const extractPitchTrack = (samples, sampleRate, opts = {}) => {
+ const {
+ startMs = 0,
+ endMs = null,
+ frameSize = DEFAULT_FRAME_SIZE,
+ hopMs = DEFAULT_HOP_MS,
+ minHz = 70,
+ maxHz = 1200,
+ } = opts;
+ const total = samples?.length || 0;
+ if (!total || !Number.isFinite(sampleRate) || sampleRate <= 0) return [];
+
+ 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 track = [];
+ for (let pos = startSample; pos + frameSize <= endSample; pos += hop) {
+ const frame = samples.subarray
+ ? samples.subarray(pos, pos + frameSize)
+ : samples.slice(pos, pos + frameSize);
+ const res = detectFrequency(frame, { sampleRate, minHz, maxHz });
+ track.push({
+ tMs: Math.round(((pos - startSample) / sampleRate) * 1000),
+ hz: res ? res.hz : null,
+ clarity: res ? res.clarity : 0,
+ });
+ }
+ return track;
+};
+
+// === Score-text assembly ================================================
+
+/**
+ * Wrap a transcribed measure body in a lead-sheet header (key/tempo/time) so
+ * the proposed part renders and plays standalone through ScoreSheet /
+ * parseScore, matching the header shape the stored scoreParts carry. Returns
+ * '' when there's no body (nothing was sung in the segment).
+ */
+export const buildScoreText = ({ key, tempo, beatsPerBar = 4, beatValue = 4, body } = {}) => {
+ if (!body) return '';
+ const lines = [];
+ if (key) lines.push(`key: ${key}`);
+ if (Number.isFinite(tempo) && tempo > 0) lines.push(`tempo: ${tempo}`);
+ if (beatsPerBar !== 4 || beatValue !== 4) lines.push(`time: ${beatsPerBar}/${beatValue}`);
+ lines.push('', body);
+ return lines.join('\n').trimStart();
+};
+
+// Reference audio (a phone speaker re-recorded through a mic, or a screen
+// recording's compressed track) is noisier than a direct vocal take, so the
+// solo-segment pipeline defaults to a slightly laxer clarity gate than the
+// live sing-to-score threshold — strict enough to reject hiss, loose enough
+// that a clean sung note through a speaker still registers.
+export const REFERENCE_CLARITY_THRESHOLD = 0.75;
+
+/**
+ * Solo-segment extraction (#2106 Stage 3): pitch-track a labeled time range of
+ * decoded reference audio and transcribe it into a proposed lead-sheet score
+ * on 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
+ * @param {number} opts.startMs / {number} opts.endMs — the segment bounds.
+ * @param {number} [opts.bpm] — the round's tempo (quantization grid).
+ * @param {string} [opts.key] — the round's key (enharmonic spelling + header).
+ * @param {number} [opts.beatsPerBar=4] / [opts.beatValue=4]
+ * @param {number} [opts.clarityThreshold] — override the reference gate.
+ * @returns {{ track: Array, body: string, text: string }} — the raw pitch
+ * track (for debugging/inspection), the bare measure body, and the
+ * header-wrapped score text ready for ScoreSheet / scoreParts.
+ */
+export const proposeSegmentScore = (samples, sampleRate, opts = {}) => {
+ const {
+ startMs = 0, endMs = null, bpm, key,
+ beatsPerBar = 4, beatValue = 4,
+ clarityThreshold = REFERENCE_CLARITY_THRESHOLD,
+ } = opts;
+ const track = extractPitchTrack(samples, sampleRate, { startMs, endMs });
+ 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.
+// Mirrors pitchDetect's tables (kept local — they aren't exported there).
+const LETTER_PC = { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 };
+const ACCIDENTAL_SHIFT = { '': 0, n: 0, '#': 1, '##': 2, b: -1, bb: -2 };
+
+// Display names for pitch classes (sharp spelling — labels only; the score
+// text itself is already spelled from the key signature).
+export const PITCH_CLASS_NAMES = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
+
+// Pitch class (0–11) of a parsed note's pitch, or null when unmappable.
+const notePitchClass = (pitch) => {
+ const base = LETTER_PC[pitch?.letter];
+ const shift = ACCIDENTAL_SHIFT[pitch?.accidental || ''];
+ if (base == null || shift == null) return null;
+ return ((base + shift) % 12 + 12) % 12;
+};
+
+/**
+ * Per-bar pitch-class sequences of a score — one array of pitch classes
+ * (rests skipped, octaves collapsed) per measure. The octave collapse is
+ * deliberate: a reference singer and the stored part may sit an octave apart
+ * while still being "the same part".
+ */
+export const barPitchClasses = (scoreText) =>
+ parseScore(scoreText).measures.map((m) =>
+ m.notes.filter((n) => !n.rest).map((n) => notePitchClass(n.pitch)).filter((pc) => pc != null));
+
+/**
+ * Compare a proposed part against an existing scorePart, bar by bar (#2106
+ * Stage 4). A bar matches when both scores have that measure AND the ordered
+ * pitch-class sequences agree (rhythm differences within a bar don't flag —
+ * the review staffs make those visible; the highlight is for wrong NOTES).
+ *
+ * @returns {Array<{bar:number, proposed:number[]|null, existing:number[]|null, match:boolean}>}
+ * — one row per bar of the longer score; a side missing that bar is null
+ * (and the bar can't match).
+ */
+export const diffScoreBars = (proposedText, existingText) => {
+ const a = barPitchClasses(proposedText);
+ const b = barPitchClasses(existingText);
+ const bars = Math.max(a.length, b.length);
+ const out = [];
+ for (let i = 0; i < bars; i++) {
+ const proposed = i < a.length ? a[i] : null;
+ const existing = i < b.length ? b[i] : null;
+ const match = proposed != null && existing != null
+ && proposed.length === existing.length
+ && proposed.every((pc, j) => pc === existing[j]);
+ out.push({ bar: i + 1, proposed, existing, match });
+ }
+ return out;
+};
diff --git a/client/src/lib/referenceAnalysis.test.js b/client/src/lib/referenceAnalysis.test.js
new file mode 100644
index 0000000000..6328b2ed20
--- /dev/null
+++ b/client/src/lib/referenceAnalysis.test.js
@@ -0,0 +1,137 @@
+import { describe, it, expect } from 'vitest';
+import {
+ extractPitchTrack,
+ proposeSegmentScore,
+ buildScoreText,
+ barPitchClasses,
+ diffScoreBars,
+ REFERENCE_CLARITY_THRESHOLD,
+} from './referenceAnalysis.js';
+
+// Synthesize a sine tone as Float32 PCM. Amplitude well above the detector's
+// silence floor; a pure tone gives NSDF clarity ≈ 1.
+const sine = (hz, seconds, sampleRate, amp = 0.5) => {
+ const n = Math.round(seconds * sampleRate);
+ const out = new Float32Array(n);
+ for (let i = 0; i < n; i++) out[i] = amp * Math.sin((2 * Math.PI * hz * i) / sampleRate);
+ return out;
+};
+
+// Concatenate Float32Arrays (tone + silence + tone fixtures).
+const concat = (...parts) => {
+ const total = parts.reduce((s, p) => s + p.length, 0);
+ const out = new Float32Array(total);
+ let off = 0;
+ for (const p of parts) { out.set(p, off); off += p.length; }
+ return out;
+};
+
+const SR = 16000; // the mic-capture rate; keeps the fixtures small
+
+describe('extractPitchTrack', () => {
+ it('detects a steady tone with high clarity and monotonic tMs', () => {
+ const track = extractPitchTrack(sine(220, 1.0, SR), SR);
+ expect(track.length).toBeGreaterThan(20);
+ const pitched = track.filter((f) => f.hz != null);
+ expect(pitched.length).toBeGreaterThan(track.length * 0.8);
+ for (const f of pitched) {
+ expect(f.hz).toBeGreaterThan(215);
+ expect(f.hz).toBeLessThan(225);
+ expect(f.clarity).toBeGreaterThan(0.9);
+ }
+ for (let i = 1; i < track.length; i++) expect(track[i].tMs).toBeGreaterThan(track[i - 1].tMs);
+ expect(track[0].tMs).toBe(0);
+ });
+
+ it('reports silence as unpitched frames (hz null, clarity 0)', () => {
+ const track = extractPitchTrack(new Float32Array(SR), SR); // 1 s of silence
+ expect(track.length).toBeGreaterThan(0);
+ expect(track.every((f) => f.hz === null && f.clarity === 0)).toBe(true);
+ });
+
+ it('slices by startMs/endMs with segment-relative timestamps', () => {
+ // 0.5 s silence, then 0.5 s of A3 — extracting only the tone half.
+ const samples = concat(new Float32Array(SR / 2), sine(220, 0.5, SR));
+ const track = extractPitchTrack(samples, SR, { startMs: 500, endMs: 1000 });
+ expect(track[0].tMs).toBe(0);
+ const pitched = track.filter((f) => f.hz != null);
+ expect(pitched.length).toBeGreaterThan(track.length * 0.7);
+ expect(Math.abs(pitched[0].hz - 220)).toBeLessThan(5);
+ });
+
+ it('returns [] for empty input or a bad sample rate', () => {
+ expect(extractPitchTrack(new Float32Array(0), SR)).toEqual([]);
+ expect(extractPitchTrack(sine(220, 0.2, SR), 0)).toEqual([]);
+ expect(extractPitchTrack(null, SR)).toEqual([]);
+ });
+});
+
+describe('buildScoreText', () => {
+ it('wraps a body with key/tempo headers and omits a 4/4 time line', () => {
+ const text = buildScoreText({ key: 'G', tempo: 90, body: '| G4q A4q B4q G4q |' });
+ expect(text).toContain('key: G');
+ expect(text).toContain('tempo: 90');
+ expect(text).not.toContain('time:');
+ expect(text).toContain('| G4q A4q B4q G4q |');
+ });
+
+ it('emits a time header for non-4/4 and returns "" without a body', () => {
+ expect(buildScoreText({ key: 'C', beatsPerBar: 3, beatValue: 4, body: '| C4h. |' })).toContain('time: 3/4');
+ expect(buildScoreText({ key: 'C', tempo: 100 })).toBe('');
+ });
+});
+
+describe('proposeSegmentScore', () => {
+ it('transcribes a solo tone segment into a parseable score in the round key', () => {
+ // 1 s of A3 at 60 BPM → one bar containing an A3 (a quarter at minimum).
+ const { track, body, text } = proposeSegmentScore(sine(220, 1.0, SR), SR, {
+ startMs: 0, endMs: 1000, bpm: 60, key: 'C',
+ });
+ expect(track.length).toBeGreaterThan(0);
+ expect(body).toMatch(/A3/);
+ expect(text).toContain('key: C');
+ expect(text).toContain('tempo: 60');
+ });
+
+ it('produces an empty proposal from a silent segment', () => {
+ const { body, text } = proposeSegmentScore(new Float32Array(SR), SR, { bpm: 90, key: 'C' });
+ expect(body).toBe('');
+ expect(text).toBe('');
+ });
+
+ it('defaults the clarity gate to the reference threshold', () => {
+ expect(REFERENCE_CLARITY_THRESHOLD).toBeGreaterThan(0);
+ expect(REFERENCE_CLARITY_THRESHOLD).toBeLessThan(1);
+ });
+});
+
+describe('barPitchClasses / diffScoreBars', () => {
+ it('collapses octaves and skips rests per bar', () => {
+ const bars = barPitchClasses('| C4q E4q rq G5q | Bb3h rh |');
+ expect(bars).toEqual([[0, 4, 7], [10]]);
+ });
+
+ it('flags matching and mismatching bars, octave-insensitively', () => {
+ const proposed = '| C3q E3q G3q C4q | D3h A3h |';
+ const existing = '| C4q E4q G4q C5q | D4h B4h |'; // bar 1 same classes, bar 2 differs
+ const rows = diffScoreBars(proposed, existing);
+ expect(rows).toHaveLength(2);
+ expect(rows[0].match).toBe(true);
+ expect(rows[1].match).toBe(false);
+ expect(rows[1].proposed).toEqual([2, 9]);
+ expect(rows[1].existing).toEqual([2, 11]);
+ });
+
+ it('marks bars missing on one side as non-matching', () => {
+ const rows = diffScoreBars('| C4q |', '| C4q | G4q |');
+ expect(rows).toHaveLength(2);
+ expect(rows[0].match).toBe(true);
+ expect(rows[1].match).toBe(false);
+ expect(rows[1].proposed).toBeNull();
+ });
+
+ it('treats different note counts in a bar as a mismatch', () => {
+ const rows = diffScoreBars('| C4q C4q |', '| C4q |');
+ expect(rows[0].match).toBe(false);
+ });
+});
diff --git a/client/src/pages/RoundEditor.jsx b/client/src/pages/RoundEditor.jsx
index 452c0705d0..8c944a2261 100644
--- a/client/src/pages/RoundEditor.jsx
+++ b/client/src/pages/RoundEditor.jsx
@@ -26,7 +26,7 @@ import { useState, useEffect, useCallback, useMemo, useRef, useId } from 'react'
import { useParams, useNavigate, useSearchParams, Link } from 'react-router-dom';
import {
Music, ArrowLeft, Plus, Trash2, Save, BookOpen, CheckCircle2, Circle, Layers, Eye, Pencil,
- Sparkles, RefreshCw, Video, ExternalLink,
+ Sparkles, RefreshCw, Video, ExternalLink, AudioLines,
} from 'lucide-react';
import toast from '../components/ui/Toast';
import { useAsyncAction } from '../hooks/useAsyncAction';
@@ -38,6 +38,7 @@ import SongRecordings from '../components/songs/SongRecordings';
import SongTraining from '../components/songs/SongTraining';
import SongScoreEditor from '../components/songs/SongScoreEditor';
import SongScoreParts from '../components/songs/SongScoreParts';
+import ReferenceAnalysis, { ReferenceAudioAttach } from '../components/songs/ReferenceAnalysis';
import ScoreSheet from '../components/songs/ScoreSheet';
import PianoRoll, { layerColor } from '../components/songs/PianoRoll';
import RoundStack from '../components/songs/RoundStack';
@@ -48,6 +49,9 @@ import { harmonyPartOrder } from '../lib/songCraft';
// Cap on partner songs — mirrors services/rounds.js PARTNERS_MAX. Used only to
// disable adding more in the editor; the server enforces the real bound.
const PARTNERS_MAX = 12;
+// Cap on harmony parts — mirrors services/rounds.js SCORE_PARTS_MAX. Used only
+// to refuse applying an extracted part past the bound; the server enforces it.
+const SCORE_PARTS_MAX = 12;
// Extract a TikTok video id from a share/watch URL so we can render TikTok's
// documented iframe Embed Player (https://www.tiktok.com/player/v1/<id>)
@@ -123,6 +127,17 @@ export default function RoundEditor() {
return next;
}, { replace: true });
}, [setSearchParams]);
+ // Reference-audio analysis view (#2106) lives in the URL too (?analyze=<refId>)
+ // so a specific reference's analysis workbench is deep-linkable.
+ const analyzeId = searchParams.get('analyze');
+ const setAnalyze = useCallback((refId) => {
+ setSearchParams((prev) => {
+ const next = new URLSearchParams(prev);
+ if (refId) next.set('analyze', refId);
+ else next.delete('analyze');
+ return next;
+ }, { replace: true });
+ }, [setSearchParams]);
const [song, setSong] = useState(null);
const [loading, setLoading] = useState(true);
// The last server-persisted base melody (score + key). Used to gate the AI
@@ -291,6 +306,30 @@ export default function RoundEditor() {
...prev, references: prev.references.filter((r) => r.id !== rid),
}));
+ // Apply an extracted reference part into the scoreParts DRAFT (#2106). An
+ // `id` targeting an existing part replaces its score; otherwise the part is
+ // appended with a temp id (stripped on save). Nothing persists until the
+ // header Save — the same explicit-save model as recordings and AI derive.
+ const applyProposedPart = useCallback((part) => {
+ const parts = song?.scoreParts || [];
+ const exists = part.id && parts.some((p) => p.id === part.id);
+ if (!exists && parts.length >= SCORE_PARTS_MAX) {
+ toast.error(`This round already has ${SCORE_PARTS_MAX} parts — remove one first.`);
+ return;
+ }
+ setSong((prev) => {
+ const cur = prev.scoreParts || [];
+ if (part.id && cur.some((p) => p.id === part.id)) {
+ return { ...prev, scoreParts: cur.map((p) => (p.id === part.id ? { ...p, score: part.score } : p)) };
+ }
+ return {
+ ...prev,
+ scoreParts: [...cur, { id: localId('part'), label: part.label || 'Part', role: part.role || '', score: part.score }],
+ };
+ });
+ toast.success('Part applied to the draft — Save the song to keep it');
+ }, [song?.scoreParts]);
+
// Layer presets the user hasn't added yet, in foundation-first order. Match
// on the preset id: preset layers (seed or ladder-added) carry the bare
// preset id like `lead`, so renaming a layer's label can't make its preset
@@ -369,7 +408,23 @@ export default function RoundEditor() {
{/* Scrollable body */}
<div className="flex-1 overflow-y-auto p-4 md:p-6">
- {!editing && (
+ {/* Reference-audio analysis workbench (#2106) — replaces the reading/
+ editing surface while ?analyze=<refId> is set, like ?stack does.
+ Renders its own fallbacks for a stale id or a no-audio reference. */}
+ {analyzeId && (
+ <ReferenceAnalysis
+ reference={(song.references || []).find((r) => r.id === analyzeId) || null}
+ layers={song.layers || []}
+ scoreParts={song.scoreParts || []}
+ tempo={song.tempo ?? null}
+ songKey={song.key || ''}
+ onUpdateReference={updateReference}
+ onApplyPart={applyProposedPart}
+ onClose={() => setAnalyze(null)}
+ />
+ )}
+
+ {!analyzeId && !editing && (
<ReadView
song={song}
setField={setField}
@@ -378,10 +433,11 @@ export default function RoundEditor() {
partnerSongs={partnerSongs}
stackOpen={stackOpen}
onToggleStack={setStack}
+ onAnalyze={setAnalyze}
/>
)}
- {editing && (
+ {!analyzeId && editing && (
<div className="max-w-5xl mx-auto space-y-6">
{song.builtIn && <BuiltInBanner onRefresh={refreshTemplate} refreshing={refreshing} />}
{/* Metadata */}
@@ -647,6 +703,21 @@ export default function RoundEditor() {
/>
</div>
{tiktokVideoId(r.url) && <p className="text-xs text-port-success">✓ TikTok video — embeds in View</p>}
+ {/* Reference-audio analysis (#2106): attach audio (upload or
+ mic capture while the video plays), then analyze it into
+ per-layer proposed parts. */}
+ <div className="flex flex-wrap items-center gap-2 pt-1 border-t border-port-border/60">
+ <ReferenceAudioAttach reference={r} onUpdate={(key, value) => updateReference(r.id, key, value)} />
+ {r.audioFilename && (
+ <button
+ type="button"
+ onClick={() => setAnalyze(r.id)}
+ 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"
+ >
+ <AudioLines size={14} /> Analyze audio
+ </button>
+ )}
+ </div>
</div>
))}
</div>
@@ -703,7 +774,7 @@ export default function RoundEditor() {
// (no sub-scrollable textareas) and laid out in a responsive grid so short
// sections sit side-by-side and use the available desktop width. The recorder
// stays interactive (recording mutates the draft; the header Save persists it).
-function ReadView({ song, setField, onRefreshTemplate, refreshing, partnerSongs = [], stackOpen = false, onToggleStack }) {
+function ReadView({ song, setField, onRefreshTemplate, refreshing, partnerSongs = [], stackOpen = false, onToggleStack, onAnalyze }) {
const sections = song.sections || [];
const layers = song.layers || [];
const references = song.references || [];
@@ -859,7 +930,7 @@ function ReadView({ song, setField, onRefreshTemplate, refreshing, partnerSongs
<Video size={15} className="text-port-accent" /> Reference material
</h2>
<div className="flex flex-wrap gap-4">
- {references.map((r) => <ReferenceCard key={r.id} reference={r} />)}
+ {references.map((r) => <ReferenceCard key={r.id} reference={r} onAnalyze={onAnalyze} />)}
</div>
</section>
)}
@@ -1107,11 +1178,22 @@ function LayeredSheetMusic({ tabs }) {
}
// One reference: a TikTok video renders as the official embed iframe; any other
-// URL renders as a link card (label + note + the raw URL).
-function ReferenceCard({ reference }) {
+// URL renders as a link card (label + note + the raw URL). A reference with
+// attached audio grows an "Analyze audio" action (#2106) that deep-links to
+// the analysis workbench (?analyze=<refId>).
+function ReferenceCard({ reference, onAnalyze }) {
const ttId = tiktokVideoId(reference.url);
const title = reference.label || reference.url;
const safeHref = isHttpUrl(reference.url);
+ const analyzeButton = reference.audioFilename && onAnalyze ? (
+ <button
+ type="button"
+ onClick={() => onAnalyze(reference.id)}
+ 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 w-fit"
+ >
+ <AudioLines size={14} /> Analyze audio
+ </button>
+ ) : null;
if (ttId) {
return (
<div className="w-full sm:w-80 lg:w-96 max-w-[45vh] space-y-2">
@@ -1129,6 +1211,7 @@ function ReferenceCard({ reference }) {
{reference.note && <p className="text-xs text-gray-500">{reference.note}</p>}
</div>
)}
+ {analyzeButton}
</div>
);
}
@@ -1139,17 +1222,20 @@ function ReferenceCard({ reference }) {
? { href: reference.url, target: '_blank', rel: 'noopener noreferrer' }
: {};
return (
- <Wrapper
- {...wrapperProps}
- className={`w-full sm:w-80 lg:w-96 bg-port-card border border-port-border rounded-lg p-4 ${safeHref ? 'hover:border-port-accent/50 transition-colors' : ''}`}
- >
- <div className="flex items-center gap-2 text-white">
- <ExternalLink size={15} className="text-port-accent shrink-0" />
- <span className="text-sm truncate">{title}</span>
- </div>
- {reference.note && <p className="mt-1 text-xs text-gray-500">{reference.note}</p>}
- <p className="mt-1 text-xs text-gray-600 truncate">{reference.url}</p>
- </Wrapper>
+ <div className="w-full sm:w-80 lg:w-96 space-y-2">
+ <Wrapper
+ {...wrapperProps}
+ className={`block bg-port-card border border-port-border rounded-lg p-4 ${safeHref ? 'hover:border-port-accent/50 transition-colors' : ''}`}
+ >
+ <div className="flex items-center gap-2 text-white">
+ <ExternalLink size={15} className="text-port-accent shrink-0" />
+ <span className="text-sm truncate">{title}</span>
+ </div>
+ {reference.note && <p className="mt-1 text-xs text-gray-500">{reference.note}</p>}
+ <p className="mt-1 text-xs text-gray-600 truncate">{reference.url}</p>
+ </Wrapper>
+ {analyzeButton}
+ </div>
);
}
diff --git a/server/routes/rounds.js b/server/routes/rounds.js
index 96fba5f9e1..9ecbe3e1a1 100644
--- a/server/routes/rounds.js
+++ b/server/routes/rounds.js
@@ -107,13 +107,27 @@ const scorePartSchema = z.object({
score: str(svc.SCORE_MAX_LENGTH),
});
+// 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).
+const refSegmentSchema = z.object({
+ layerId: str(svc.ID_MAX_LENGTH).optional().default(''),
+ startMs: z.number(),
+ endMs: z.number(),
+});
+
// A reference link/video (e.g. a TikTok performance). `url` is required; the
// client renders TikTok urls as embeds and everything else as a link.
+// `audioFilename`/`segments` are the optional reference-audio analysis fields
+// (#2106) — absent on legacy references; the service omits empty values so
+// pre-feature records round-trip unchanged.
const referenceSchema = z.object({
id: str(svc.ID_MAX_LENGTH).optional(),
url: str(svc.URL_MAX_LENGTH),
label: str(svc.LABEL_MAX_LENGTH).optional().default(''),
note: str(svc.FIELD_MAX_LENGTH).optional().default(''),
+ audioFilename: str(svc.URL_MAX_LENGTH).optional(),
+ segments: z.array(refSegmentSchema).max(svc.REF_SEGMENTS_MAX).optional(),
});
// No `.default('')` on these fields: `.partial()` (used for PUT) materializes a
diff --git a/server/services/rounds.js b/server/services/rounds.js
index 85cf1cfaf8..efa8fe68f7 100644
--- a/server/services/rounds.js
+++ b/server/services/rounds.js
@@ -50,6 +50,11 @@ export const RECORDINGS_MAX = 64; // saved vocal takes for layered playback
export const REFERENCES_MAX = 12; // reference links/videos (e.g. TikTok)
export const PARTNERS_MAX = 12; // partner-song ids (rounds sung together)
export const URL_MAX_LENGTH = 512; // uploaded-file path/url
+// Reference-audio analysis (#2106): labeled time ranges on a reference's
+// attached audio ("0:00–0:14 melody alone"). Bounded so a hand-edited file
+// can't balloon a reference; a layered TikTok build rarely has more than a
+// handful of voice entrances.
+export const REF_SEGMENTS_MAX = 24; // labeled time ranges per reference
// Per-take pitch analysis (#1027). The pitch track is a DOWNSAMPLED tuner trace
// kept for replay/training so it isn't recomputed on every open; bound it so a
// long take can't bloat data/rounds.json. `accuracy.perNote` mirrors the
@@ -243,11 +248,38 @@ const sanitizeRecording = (r) => {
return rec;
};
+// One labeled time range on a reference's attached audio (#2106):
+// `{ layerId, startMs, endMs }` — "this span is the bass part alone". `layerId`
+// ties the span to a voice layer (free text, same convention as recordings);
+// 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.
+const sanitizeRefSegment = (s) => {
+ if (!s || typeof s !== 'object') return null;
+ const startRaw = finiteOrNull(s.startMs);
+ const endRaw = finiteOrNull(s.endMs);
+ if (startRaw === null || endRaw === null) return null;
+ const startMs = Math.max(0, Math.round(startRaw));
+ const endMs = Math.max(0, Math.round(endRaw));
+ if (endMs <= startMs) return null;
+ return {
+ layerId: trimField(s.layerId, ID_MAX_LENGTH),
+ startMs,
+ endMs,
+ };
+};
+
// One reference link/video ({ id, url, label, note }) — external study
// material for the song (a TikTok performance, a tutorial, a chord chart).
// `url` is required (a reference without a target is meaningless); label/note
// are free text. The client decides how to render each url (TikTok videos
// embed; everything else is a link).
+//
+// Optional reference-audio analysis (#2106): `audioFilename` (an /api/uploads
+// file, same convention as recordings[].filename) and `segments` (bounded
+// labeled time ranges) only appear when set — absent keys stay absent so a
+// legacy/pre-feature reference round-trips byte-identical (purely additive,
+// no migration).
const sanitizeReference = (r) => {
if (!r || typeof r !== 'object') return null;
const url = trimField(r.url, URL_MAX_LENGTH);
@@ -255,12 +287,17 @@ const sanitizeReference = (r) => {
// non-PortOS writer can't persist a javascript:/data: URL that a renderer
// might trust (mirrors the client's isHttpUrl guard).
if (!/^https?:\/\//i.test(url)) return null;
- return {
+ const ref = {
id: trimField(r.id, ID_MAX_LENGTH) || `ref-${randomUUID().slice(0, 8)}`,
url,
label: trimField(r.label, LABEL_MAX_LENGTH),
note: trimField(r.note, FIELD_MAX_LENGTH),
};
+ const audioFilename = trimField(r.audioFilename, URL_MAX_LENGTH);
+ if (audioFilename) ref.audioFilename = audioFilename;
+ const segments = sanitizeList(r.segments, sanitizeRefSegment, REF_SEGMENTS_MAX);
+ if (segments.length) ref.segments = segments;
+ return ref;
};
// One sheet-music part — a harmony variation of the song's base score
diff --git a/server/services/rounds.test.js b/server/services/rounds.test.js
index f2e14ae0ca..65e918c21a 100644
--- a/server/services/rounds.test.js
+++ b/server/services/rounds.test.js
@@ -365,6 +365,68 @@ describe('rounds service', () => {
expect(song.references[1].id).toBe('ref-keep');
});
+ it('reference audioFilename/segments round-trip; absent keys stay absent (#2106)', () => {
+ const song = svc.sanitizeRound({
+ id: 'x',
+ references: [
+ { url: 'https://example.com/plain' }, // legacy — no analysis fields
+ {
+ url: 'https://www.tiktok.com/@u/video/9',
+ audioFilename: ' abc123-ref.wav ',
+ segments: [
+ { layerId: 'lead', startMs: 0, endMs: 14000 },
+ { layerId: 'bass', startMs: 14000.7, endMs: 29000.2 }, // rounded
+ ],
+ },
+ ],
+ });
+ // Legacy reference: the new keys must not appear at all.
+ expect('audioFilename' in song.references[0]).toBe(false);
+ expect('segments' in song.references[0]).toBe(false);
+ // Analysis reference: trimmed filename + clamped/rounded segments.
+ expect(song.references[1].audioFilename).toBe('abc123-ref.wav');
+ expect(song.references[1].segments).toEqual([
+ { layerId: 'lead', startMs: 0, endMs: 14000 },
+ { layerId: 'bass', startMs: 14001, endMs: 29000 },
+ ]);
+ });
+
+ it('drops malformed reference segments and bounds the list (#2106)', () => {
+ const song = svc.sanitizeRound({
+ id: 'x',
+ references: [{
+ url: 'https://example.com',
+ segments: [
+ { layerId: 'a', startMs: 5000, endMs: 5000 }, // zero-length → dropped
+ { layerId: 'b', startMs: 9000, endMs: 1000 }, // inverted → dropped
+ { layerId: 'c', startMs: 'x', endMs: 2000 }, // non-finite → dropped
+ { layerId: 'd', startMs: -50, endMs: 2000 }, // clamped to 0
+ 'not-an-object', // shapeless → dropped
+ ],
+ }],
+ });
+ expect(song.references[0].segments).toEqual([
+ { layerId: 'd', startMs: 0, endMs: 2000 },
+ ]);
+ // An all-invalid list leaves the key absent (no empty-array husk).
+ const empty = svc.sanitizeRound({
+ id: 'y',
+ references: [{ url: 'https://example.com', segments: [{ startMs: 1, endMs: 1 }] }],
+ });
+ expect('segments' in empty.references[0]).toBe(false);
+ // Bound: more than REF_SEGMENTS_MAX spans are truncated.
+ const many = svc.sanitizeRound({
+ id: 'z',
+ references: [{
+ url: 'https://example.com',
+ segments: Array.from({ length: svc.REF_SEGMENTS_MAX + 5 }, (_, i) => ({
+ layerId: `l${i}`, startMs: i * 1000, endMs: i * 1000 + 500,
+ })),
+ }],
+ });
+ expect(many.references[0].segments).toHaveLength(svc.REF_SEGMENTS_MAX);
+ });
+
it('refreshes a built-in from template, preserving recordings + learned', async () => {
await svc.listRounds(); // seed
const seedId = [...svc.BUILTIN_ROUND_IDS][0];