Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: anchor music video lyrics to vocal phrases (#9255)
Adam Eivyae100c60764f
diff --git a/client/src/components/musicVideo/LyricsPanel.jsx b/client/src/components/musicVideo/LyricsPanel.jsxindex 9395cc7b59..d33442dba6 100644--- a/client/src/components/musicVideo/LyricsPanel.jsx+++ b/client/src/components/musicVideo/LyricsPanel.jsx@@ -129,6 +129,7 @@ export default function LyricsPanel({ project, onEditLocal, onSave, onImport, imlyricCues: cues.map((c) => {if (c.id !== id) return c;const next = { ...c, ...patch };+ if (Object.hasOwn(patch, 'text') && patch.text !== c.text) delete next.matched;if (Object.hasOwn(patch, 'words') && patch.words == null) delete next.words;return next;}),@@ -279,6 +280,11 @@ export default function LyricsPanel({ project, onEditLocal, onSave, onImport, im<button type="button" onClick={() => replaceCues(cues.filter((c) => c.id !== cue.id))}aria-label={`Delete line ${i + 1}`} className="min-h-[44px] min-w-[44px] sm:min-h-0 sm:min-w-0 p-1 text-port-error"><Trash2 size={12} /></button></div>+ {typeof cue.matched === 'number' && cue.matched < 0.5 && (+ <span className="inline-block rounded bg-port-warning/10 px-1.5 py-0.5 text-port-warning">+ Low confidence — check by ear+ </span>+ )}<WordTimingRow cue={cue}onPreview={(words) => editWords(cue.id, words, false)}onCommit={(words) => editWords(cue.id, words, true)} />diff --git a/client/src/components/musicVideo/LyricsPanel.test.jsx b/client/src/components/musicVideo/LyricsPanel.test.jsxindex 003c7786a6..bc79e67637 100644--- a/client/src/components/musicVideo/LyricsPanel.test.jsx+++ b/client/src/components/musicVideo/LyricsPanel.test.jsx@@ -42,6 +42,19 @@ describe('LyricsPanel word alignment', () => {expect(await screen.findByRole('alert')).toHaveTextContent(/Settings → Voice/);});+ it('flags only measured low confidence, and clears the badge data when the lyric text changes', () => {+ const cues = [+ { ...PROJECT.lyricCues[0], matched: 0.4 },+ { id: 'b', text: 'new line', startSec: null, endSec: null },+ { id: 'c', text: 'confident line', startSec: 5, endSec: 6, matched: 0.5 },+ ];+ const { onEditLocal } = renderPanel({ project: { ...PROJECT, lyricCues: cues } });+ expect(screen.getAllByText('Low confidence — check by ear')).toHaveLength(1);+ fireEvent.change(screen.getByRole('textbox', { name: 'Line 1 text' }), { target: { value: 'changed line' } });+ expect(onEditLocal.mock.lastCall[0].lyricCues[0].matched).toBeUndefined();+ expect(onEditLocal.mock.lastCall[0].lyricCues[0].words).toBeUndefined();+ });+it('re-aligns one line and nudges a word boundary into the save', () => {const { onAlign, onSave } = renderPanel();fireEvent.click(screen.getByRole('button', { name: 'Re-align line 1' }));diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex bc11677485..c1bba70e97 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -101,6 +101,7 @@ export const musicVideoLyricCueSchema = z.object({startSec: timedSec,endSec: timedSec,words: z.array(lyricWordSchema).max(400).optional(),+ matched: z.number().min(0).max(1).optional(),}).strict();// A musical-phrase annotation: a span of the song with an optional visualdiff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex ffa68ec536..5c6bb9c1f7 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -647,7 +647,10 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// under this install's data/music-video/<projectId>/composition/ and are not// in the asset manifest, so a peer keeps its own pointer (or none, and then// refuses to render with COMPOSITION_DOCUMENT_MISSING).- musicVideoProjects: 10,+ // v11 = phrase-alignment confidence (`lyricCues[].matched`). Older peers+ // drop it on edits or retain stale confidence after audio changes. Existing+ // records need no rewrite: absent means alignment has not measured it.+ musicVideoProjects: 11,// v1 = Creative Commission FEEDBACK federation (PostgreSQL `commission_feedback`)// via the per-record peer-sync push pipeline (record kind `commissionFeedback`,// sync category `commissionFeedback`, #2686 — split-record follow-up to #2657).diff --git a/server/services/musicVideo/lyricAlign.js b/server/services/musicVideo/lyricAlign.jsindex c01e3baae4..08783126d0 100644--- a/server/services/musicVideo/lyricAlign.js+++ b/server/services/musicVideo/lyricAlign.js@@ -6,9 +6,9 @@* 16 kHz mono PCM; a whisper runner (lyricTranscriber.js — whisper-cli with a* music-grade model, the voice STT endpoint, or a temporary whisper-server)* returns word timings, and those timings are aligned to the director's- * spelling. With a vocal stem attached, both the stem and the mix are- * transcribed and merged, so a recognizer that loops on the isolated vocal is- * outvoted by the mix. A line the singer skipped stays inside its own window+ * spelling. With a vocal stem attached, its phrases anchor short mix windows+ * so post-silence words cannot drift back into the instrumental gap. A line+ * the singer skipped stays inside its own window* and does not move the lines around it. Times the director already set are* kept. A whole-song alignment also names the analysis sections after the* lyric sheet's `[Verse]`/`[Chorus]` headers (lyricMarkers.js).@@ -24,7 +24,13 @@ import { getProject, updateProject } from './projects.js';import {alignDirectorWords,lyricAlignFfmpegArgs,+ dropNonLyricWords,mergeTranscripts,+ detectVocalPhrases,+ phraseWindows,+ snapLineStarts,+ vocalPcm,+ wavDurationSec,pickAlignmentPath,} from './lyricAlignCore.js';import { relabelAnalysisSections } from './lyricMarkers.js';@@ -107,18 +113,38 @@ export async function alignProjectLyrics(projectId, options = {}) {const region = windowed || { startSec: 0, endSec: null };const promptCues = windowed ? [cue] : cues;const prompt = alignmentPrompt(promptCues);- const lyricText = promptCues.map((entry) => entry.text).join('\n');+ const phrases = mixWav ? detectVocalPhrases(vocalPcm(wav)) : [];+ const windows = mixWav ? phraseWindows(phrases, wavDurationSec(mixWav)) : [];const transcriber = await deps.resolveTranscriber();let recognized;try {- const primary = await transcriber.transcribe(wav, { ...region, prompt });- const mix = mixWav ? await transcriber.transcribe(mixWav, { ...region, prompt }) : [];- recognized = mergeTranscripts(primary, mix, lyricText);+ if (mixWav) {+ recognized = [];+ // The runner already slices and offsets each result onto the song clock.+ // Sequential calls bound memory/GPU use and release one runner per song.+ for (const [index, window] of windows.entries()) {+ if (windowed && (window.endSec <= windowed.startSec || window.startSec >= windowed.endSec)) continue;+ const startSec = Math.max(window.startSec, windowed?.startSec ?? 0);+ const endSec = Math.min(window.endSec, windowed?.endSec ?? Infinity);+ const words = await transcriber.transcribe(mixWav, { startSec, endSec, prompt });+ const previous = windows[index - 1];+ const following = windows[index + 1];+ const ownStart = Math.max(startSec, previous ? (previous.endSec + window.startSec) / 2 : startSec);+ const ownEnd = Math.min(endSec, following ? (window.endSec + following.startSec) / 2 : endSec);+ recognized.push(...words.filter((word) => {+ const midpoint = (word.startSec + word.endSec) / 2;+ return midpoint >= ownStart && midpoint < ownEnd;+ }));+ }+ recognized = dropNonLyricWords(recognized);+ } else {+ recognized = mergeTranscripts(await transcriber.transcribe(wav, { ...region, prompt }), [], promptCues.map((entry) => entry.text).join('\n'));+ }} finally {await Promise.resolve(transcriber.release?.()).catch((err) => console.error(`❌ Could not stop the alignment runner: ${err.message}`));}- if (!windowed && recognized.length === 0) {+ if (!mixWav && !windowed && recognized.length === 0) {throw new ServerError('Speech-to-text heard no words in this audio. Check the song has vocals, then try Align words again.',{ status: 422, code: 'LYRIC_ALIGN_EMPTY' },@@ -134,12 +160,16 @@ export async function alignProjectLyrics(projectId, options = {}) {throw new ServerError('The lyric lines changed while they were aligning. Run Align words again.', { status: 409, code: 'LYRIC_ALIGN_TEXT_CHANGED' });}+ const align = (entries) => {+ const aligned = alignDirectorWords(entries, recognized, { phraseAnchored: Boolean(mixWav) });+ return mixWav ? snapLineStarts(aligned, phrases.map((phrase) => phrase.startSec), entries) : aligned;+ };let nextCues;if (windowed) {- const [aligned] = alignDirectorWords([cue], recognized);+ const [aligned] = align([freshCues.find((entry) => entry.id === cue.id)]);nextCues = freshCues.map((entry) => (entry.id === cue.id ? { ...entry, ...aligned, id: entry.id } : entry));} else {- const aligned = alignDirectorWords(freshCues, recognized);+ const aligned = align(freshCues);nextCues = cueId ? freshCues.map((entry, index) => (entry.id === cueId ? aligned[index] : entry)) : aligned;}const matched = nextCues.reduce((sum, entry) => sum + (entry.words || []).filter((word) => word.conf === 'matched').length, 0);diff --git a/server/services/musicVideo/lyricAlign.test.js b/server/services/musicVideo/lyricAlign.test.jsindex af567dee2e..2b1859b808 100644--- a/server/services/musicVideo/lyricAlign.test.js+++ b/server/services/musicVideo/lyricAlign.test.js@@ -300,23 +300,56 @@ describe('alignProjectLyrics', () => {expect(release).toHaveBeenCalledOnce();});- it('transcribes the stem and the mix, and aligns to their merge', async () => {- const transcribe = vi.fn()- .mockResolvedValueOnce([- { text: 'walking', startSec: 0.5, endSec: 1 },- { text: 'no', startSec: 1.2, endSec: 1.3 }, { text: 'no', startSec: 1.3, endSec: 1.4 },- { text: 'no', startSec: 1.4, endSec: 1.5 }, { text: 'no', startSec: 1.5, endSec: 1.6 },- ])- .mockResolvedValueOnce([- { text: 'walking', startSec: 0.5, endSec: 1 },- { text: 'home', startSec: 1.1, endSec: 1.6 },- ]);- const { run, decodeAudio } = harness(transcribe, project, {+ it('anchors a post-silence line to the stem while transcribing only sequential mix windows', async () => {+ const record = { ...project, lyricCues: [+ { id: 'a', text: 'hello morning', startSec: null, endSec: null },+ { id: 'b', text: 'gently awaken', startSec: null, endSec: null },+ { id: 'c', text: 'absent lyric', startSec: 8, endSec: 9 },+ ] };+ const stem = encodePcm16Wav(16000 * 10);+ for (const [start, end] of [[1, 2], [4, 5]]) {+ for (let i = start * 16000; i < end * 16000; i++) stem.writeInt16LE(5000, 44 + i * 2);+ }+ const mix = encodePcm16Wav(16000 * 10);+ let active = false;+ const transcribe = vi.fn(async (wav, region) => {+ expect(wav).toBe(mix);+ expect(active).toBe(false);+ active = true;+ await Promise.resolve();+ active = false;+ // Mimic whisper's bias: first word starts at the slice's beginning.+ const text = region.startSec < 2 ? ['hello', 'morning'] : region.startSec < 5 ? ['gently', 'awaken'] : [];+ return text.map((word, i) => ({ text: word, startSec: region.startSec + i * 0.4, endSec: region.startSec + (i + 1) * 0.4 }));+ });+ const h = harness(transcribe, record, {resolveAudio: async () => ({ path: 'stem.wav', source: 'vocal-stem', mixPath: 'song.wav' }),});- const saved = await run();- expect(decodeAudio.mock.calls.map(([path]) => path)).toEqual(['stem.wav', 'song.wav']);- expect(saved.lyricCues[0].words[1]).toMatchObject({ w: 'home', startSec: 1.1, conf: 'matched' });+ h.decodeAudio.mockImplementation(async (path) => path === 'stem.wav' ? stem : mix);+ const saved = await h.run();+ expect(h.decodeAudio.mock.calls.map(([path]) => path)).toEqual(['stem.wav', 'song.wav']);+ expect(Math.abs(saved.lyricCues[1].startSec - 4)).toBeLessThanOrEqual(0.06);+ expect(saved.lyricCues[1].matched).toBe(1);+ expect(saved.lyricCues[1].words[0].startSec).toBe(saved.lyricCues[1].startSec);+ expect(saved.lyricCues[2]).toEqual({ ...record.lyricCues[2], matched: 0 });+ expect(transcribe.mock.calls.every(([, window]) => window.endSec - window.startSec <= 11)).toBe(true);+ expect(h.release).toHaveBeenCalledOnce();+ });++ it('keeps current director times on a stem re-alignment, including edits made during transcription', async () => {+ const record = { ...project, lyricCues: [{ id: 'a', text: 'walking home', startSec: 1, endSec: 2 }] };+ const transcribe = vi.fn(async () => {+ record.lyricCues = [{ ...record.lyricCues[0], startSec: 1.2, endSec: 2.5 }];+ return [{ text: 'walking', startSec: 1, endSec: 1.5 }, { text: 'home', startSec: 1.5, endSec: 2 }];+ });+ const h = harness(transcribe, record, {+ resolveAudio: async () => ({ path: 'stem.wav', source: 'vocal-stem', mixPath: 'song.wav' }),+ });+ const stem = encodePcm16Wav(16000 * 3);+ for (let i = 16000; i < 32000; i++) stem.writeInt16LE(5000, 44 + i * 2);+ h.decodeAudio.mockResolvedValue(stem);+ const saved = await h.run({ cueId: 'a' });+ expect(saved.lyricCues[0]).toMatchObject({ startSec: 1.2, endSec: 2.5, matched: 1 });});it('names the analysis sections after the lyric sheet once the lines are timed', async () => {diff --git a/server/services/musicVideo/lyricAlignCore.js b/server/services/musicVideo/lyricAlignCore.jsindex 59fca3c940..52a376e092 100644--- a/server/services/musicVideo/lyricAlignCore.js+++ b/server/services/musicVideo/lyricAlignCore.js@@ -508,20 +508,21 @@ function applyWordTimes(cue, words) {* window keeps a fully unmatched run inside that window.* A cue's startSec/endSec is filled from its words only when that side is null.*/-function alignDirectorWords(cues, recognizedWords) {+function alignDirectorWords(cues, recognizedWords, { phraseAnchored = false } = {}) {const list = Array.isArray(cues) ? cues : [];const director = [];list.forEach((cue, cueIndex) => {for (const token of lyricTokens(cue?.text)) director.push({ ...token, cueIndex });});const recognized = recognizedTokens(recognizedWords);- const matchOf = alignTokenIndexes(director, recognized);+ const matches = phraseAnchored ? dpAlignWords(director, recognizedWords) : null;+ const matchOf = matches ? null : alignTokenIndexes(director, recognized);const byCue = list.map(() => []);director.forEach((token, index) => {- const recIndex = matchOf[index];+ const recIndex = matchOf?.[index] ?? -1;byCue[token.cueIndex].push({w: token.w,- match: recIndex >= 0 ? recognized[recIndex] : null,+ match: matches ? matches[index] : recIndex >= 0 ? recognized[recIndex] : null,});});const placed = placeAll(list, byCue, recognized);@@ -532,10 +533,198 @@ function alignDirectorWords(cues, recognizedWords) {delete cleared.words;return cleared;}- return applyWordTimes(cue, words);+ if (!phraseAnchored) return applyWordTimes(cue, words);+ const matched = words.filter((word) => word.conf === 'matched').length / words.length;+ // A weak recognition must not overwrite even an untimed line with invented+ // timing. Keep its previous word boundaries too, if any.+ if (matched < 0.5) return { ...cue, matched };+ return { ...applyWordTimes(cue, words), matched };});}+/** RMS phrases from normalized mono PCM (10 ms hop, centered 30 ms smoothing). */+export function detectVocalPhrases(pcm, sampleRate = LYRIC_ALIGN_SAMPLE_RATE) {+ const hop = Math.max(1, Math.round(sampleRate * 0.01));+ const power = [];+ for (let i = 0; i < pcm.length; i += hop) {+ let sum = 0;+ const end = Math.min(pcm.length, i + hop);+ for (let j = i; j < end; j++) sum += pcm[j] * pcm[j];+ power.push(sum / (end - i));+ }+ const rms = power.map((v, i) => Math.sqrt(((power[i - 1] ?? v) + v + (power[i + 1] ?? v)) / 3));+ const threshold = 10 ** (-40 / 20);+ const onsetThreshold = 10 ** (-46 / 20);+ const phrases = [];+ const emit = (start, end) => {+ if (end - start < 15) return;+ // Bound each split away from the edges so even a flat sustained vocal+ // makes progress; equal-depth dips prefer the middle.+ while (end - start > 700) {+ const limit = Math.min(start + 700, end - 15);+ let dip = start + Math.floor((limit - start) / 2);+ for (let i = start + 15; i <= limit; i++) if (rms[i] < rms[dip]) dip = i;+ phrases.push({ startSec: round3(start * hop / sampleRate), endSec: round3(dip * hop / sampleRate) });+ start = dip;+ }+ phrases.push({ startSec: round3(start * hop / sampleRate), endSec: round3(Math.min(pcm.length, end * hop) / sampleRate) });+ };+ let start = null;+ let silent = 0;+ for (let i = 0; i < rms.length; i++) {+ if (rms[i] >= threshold) {+ if (start == null) {+ start = i;+ while (start > 0 && rms[start - 1] >= onsetThreshold) start--;+ }+ silent = 0;+ } else if (start != null && ++silent >= 10) {+ emit(start, i - silent + 1);+ start = null;+ silent = 0;+ }+ }+ if (start != null) emit(start, rms.length - silent);+ return phrases;+}++/** Windows on the song clock. Long gaps start a new anchor, even below 11 s. */+export function phraseWindows(phrases, durationSec = phrases.at(-1)?.endSec ?? 0) {+ const windows = [];+ for (const phrase of phrases) {+ const startSec = Math.max(0, phrase.startSec - 0.08);+ const endSec = Math.min(durationSec, phrase.endSec + 0.08);+ const last = windows.at(-1);+ // Do not put a post-silence phrase inside an earlier window: whisper+ // would again attach its first word to that silence.+ if (last && startSec - last.endSec <= 0.1 && endSec - last.startSec <= 11) last.endSec = endSec;+ else if (endSec > startSec) windows.push({ startSec: round3(startSec), endSec: round3(endSec) });+ }+ const gaps = [];+ let cursor = 0;+ for (const window of [...windows, { startSec: durationSec, endSec: durationSec }]) {+ if (window.startSec - cursor > 3) {+ for (let start = cursor; start < window.startSec; start += 11) {+ gaps.push({ startSec: round3(start), endSec: round3(Math.min(start + 11, window.startSec)) });+ }+ }+ cursor = Math.max(cursor, window.endSec);+ }+ return [...windows, ...gaps].sort((a, b) => a.startSec - b.startSec);+}++// SequenceMatcher-style ratio: recursively count longest common contiguous+// blocks, rather than making one edit the only tolerated recognition error.+function wordRatio(a, b) {+ const pending = [[0, a.length, 0, b.length]];+ let matched = 0;+ while (pending.length) {+ const [alo, ahi, blo, bhi] = pending.pop();+ let best = 0, ai = alo, bi = blo;+ let previous = new Uint16Array(bhi - blo + 1);+ for (let i = alo; i < ahi; i++) {+ const row = new Uint16Array(bhi - blo + 1);+ for (let j = blo; j < bhi; j++) {+ if (a[i] !== b[j]) continue;+ const size = previous[j - blo] + 1;+ row[j - blo + 1] = size;+ if (size > best) { best = size; ai = i - size + 1; bi = j - size + 1; }+ }+ previous = row;+ }+ if (!best) continue;+ matched += best;+ if (alo < ai && blo < bi) pending.push([alo, ai, blo, bi]);+ if (ai + best < ahi && bi + best < bhi) pending.push([ai + best, ahi, bi + best, bhi]);+ }+ return 2 * matched / (a.length + b.length || 1);+}++const WORD_ALIASES = new Set(['a:of', 'of:a', 'swarm:sword', 'sword:swarm']);++/** Global Needleman–Wunsch alignment; result has one match (or null) per lyric word. */+function dpAlignWords(lyricWords, recognised) {+ const director = lyricWords.map((word) => typeof word === 'string' ? lyricKey(word) : word.key);+ const vocab = new Set(director);+ const tokens = recognizedTokens(recognised);+ const words = [];+ for (let i = 0; i < tokens.length; i++) {+ const word = tokens[i];+ const next = tokens[i + 1];+ // Only glue fragments into a word the director actually supplied; never+ // collapse two independently valid lyric words.+ if (next && next.startSec - word.endSec <= 0.15 && !vocab.has(word.key) && vocab.has(word.key + next.key)) {+ words.push({ ...word, key: word.key + next.key, endSec: next.endSec });+ i++;+ } else words.push(word);+ }+ const n = director.length, m = words.length, width = m + 1;+ if ((n + 1) * width > MAX_ALIGN_DP_CELLS) {+ throw new ServerError('Too many words to align at once. Re-align individual lines.', { status: 422, code: 'LYRIC_ALIGN_TOO_LARGE' });+ }+ const score = new Float64Array((n + 1) * width);+ const step = new Uint8Array(score.length);+ const cache = new Map();+ const similarity = (a, b) => {+ if (a === b || WORD_ALIASES.has(`${a}:${b}`)) return 1;+ const key = `${a}:${b}`;+ if (cache.size >= 50_000) cache.clear();+ if (!cache.has(key)) cache.set(key, wordRatio(a, b));+ return cache.get(key);+ };+ for (let i = 1; i <= n; i++) score[i * width] = -0.4 * i;+ for (let j = 1; j <= m; j++) score[j] = -0.2 * j;+ for (let i = 1; i <= n; i++) {+ for (let j = 1; j <= m; j++) {+ const cell = i * width + j;+ const up = score[cell - width] - 0.4;+ const left = score[cell - 1] - 0.2;+ score[cell] = Math.max(up, left);+ step[cell] = up >= left ? 1 : 2;+ const ratio = similarity(director[i - 1], words[j - 1].key);+ const diag = score[cell - width - 1] + ratio;+ if (ratio >= 0.6 && diag >= score[cell]) { score[cell] = diag; step[cell] = 3; }+ }+ }+ const matches = new Array(n).fill(null);+ let i = n, j = m;+ while (i > 0 && j > 0) {+ const direction = step[i * width + j];+ if (direction === 3) { matches[--i] = words[--j]; }+ else if (direction === 1) i--;+ else j--;+ }+ return matches;+}++/** Snap generated line starts and all words by one delta; authored sides stay fixed. */+export function snapLineStarts(lines, onsets, originals = []) {+ return lines.map((line, index) => {+ const original = originals[index] || {};+ if (line.matched < 0.5 || !line.words?.length) return line;+ const first = line.words[0].startSec;+ const onset = onsets.filter((t) => t >= first - 0.35 && t <= first + 0.25)+ .sort((a, b) => Math.abs(a - first) - Math.abs(b - first))[0];+ if (onset == null) return line;+ const delta = onset - first;+ return {+ ...line,+ startSec: original.startSec ?? round3(onset),+ endSec: original.endSec ?? (line.endSec == null ? null : round3(line.endSec + delta)),+ words: line.words.map((word) => ({ ...word, startSec: round3(word.startSec + delta), endSec: round3(word.endSec + delta) })),+ };+ });+}++/** Read the ffmpeg-decoded WAV without assuming a fixed-size RIFF header. */+export function vocalPcm(wav) {+ const info = wavInfo(wav);+ if (!info || info.blockAlign !== 2 || info.sampleRate !== LYRIC_ALIGN_SAMPLE_RATE) {+ throw new ServerError('Decoded audio was not 16 kHz mono PCM.', { status: 422, code: 'LYRIC_ALIGN_DECODE_FAILED' });+ }+ return Float32Array.from({ length: info.sampleCount }, (_, i) => wav.readInt16LE(info.dataOffset + i * 2) / 32768);+}+function encodePcm16Wav(sampleCount, sampleRate = LYRIC_ALIGN_SAMPLE_RATE) {const count = Math.max(0, sampleCount | 0);const dataBytes = count * 2;@@ -610,8 +799,7 @@ export async function pickAlignmentPath(project, io = {}) {return resolveMasterAudioPath(record);});const stem = resolveStem(project);- // With a stem, the mix is transcribed too: the two transcripts are merged so- // a recognizer that loops on the isolated vocal is outvoted (mergeTranscripts).+ // The stem supplies phrase onsets; the mix supplies recognized words.if (stem) return { path: stem, source: 'vocal-stem', mixPath: await resolveMaster(project) };return { path: await resolveMaster(project), source: 'master', mixPath: null };}diff --git a/server/services/musicVideo/lyricAlignCore.test.js b/server/services/musicVideo/lyricAlignCore.test.jsnew file mode 100644index 0000000000..290eb89e68--- /dev/null+++ b/server/services/musicVideo/lyricAlignCore.test.js@@ -0,0 +1,80 @@+import { describe, expect, it } from 'vitest';+import { musicVideoLyricCueSchema } from '../../lib/musicVideoValidation.js';+import { PORTOS_SCHEMA_VERSIONS } from '../../lib/schemaVersions.js';+import { alignDirectorWords, detectVocalPhrases, phraseWindows, snapLineStarts } from './lyricAlignCore.js';++function signal(duration, spans) {+ const pcm = new Float32Array(duration * 16000);+ for (const [start, end, amplitude = 0.2] of spans) pcm.fill(amplitude, start * 16000, end * 16000);+ return pcm;+}+const words = (text, start = 1) => text.split(' ').map((text, i) => ({ text, startSec: start + i * 0.3, endSec: start + (i + 1) * 0.3 }));++describe('vocal phrase anchors', () => {+ it('drops short noise, bridges short breaths, and locates the quieter onset before a loud phrase', () => {+ const pcm = signal(5, [[0.2, 0.25], [1, 1.2, 0.007], [1.2, 2], [2.05, 2.4], [3, 4]]);+ const phrases = detectVocalPhrases(pcm);+ expect(phrases).toHaveLength(2);+ expect(phrases[0].startSec).toBeCloseTo(1, 1);+ expect(phrases[0].endSec).toBeCloseTo(2.4, 1);+ expect(phrases[1].startSec).toBeCloseTo(3, 1);+ expect(detectVocalPhrases(new Float32Array(16000))).toEqual([]);+ });++ it('splits a long sustained phrase at its deepest dip and bounds flat phrases', () => {+ const pcm = signal(17, [[0, 17]]);+ pcm.fill(0.012, 6 * 16000, 6.04 * 16000);+ const phrases = detectVocalPhrases(pcm);+ expect(phrases[0].endSec).toBeCloseTo(6.02, 1);+ expect(phrases.every((p) => p.endSec - p.startSec <= 7)).toBe(true);+ expect(phrases.at(-1).endSec).toBe(17);+ });++ it('anchors after a two-second gap and covers long unanchored stretches without exceeding 11 seconds', () => {+ const windows = phraseWindows([+ { startSec: 2, endSec: 3 }, { startSec: 5, endSec: 6 },+ { startSec: 6.1, endSec: 8 }, { startSec: 24, endSec: 25 },+ ], 40);+ expect(windows).toContainEqual({ startSec: 4.92, endSec: 8.08 });+ expect(windows.every((w) => w.endSec - w.startSec <= 11)).toBe(true);+ expect(windows.at(-1).endSec).toBe(40);+ for (let i = 1; i < windows.length; i++) {+ expect(windows[i].startSec - windows[i - 1].endSec).toBeLessThanOrEqual(3);+ expect(windows[i].startSec).toBeGreaterThanOrEqual(windows[i - 1].endSec);+ }+ });+});++describe('phrase lyric matching', () => {+ it('merges contractions and fragments, accepts aliases and fuzzy words, and skips unrelated recognition', () => {+ const [line] = alignDirectorWords([{ text: "I'm prompt of swarm shining" }], words("I 'm Prom pt a sword unrelated shinning"), { phraseAnchored: true });+ expect(line.matched).toBe(1);+ expect(line.words.map((word) => word.w)).toEqual(["I'm", 'prompt', 'of', 'swarm', 'shining']);+ expect(line.words[1]).toMatchObject({ startSec: 1.6, endSec: 2.2 });+ expect(line.words.at(-1).startSec).toBe(3.1);+ });++ it('keeps repeated verses in order without letting a missing word consume the next verse', () => {+ const [line] = alignDirectorWords([{ text: 'hello the morning hello the morning' }], words('hello morning hello the morning'), { phraseAnchored: true });+ expect(line.words.map((word) => word.conf)).toEqual(['matched', 'interpolated', 'matched', 'matched', 'matched', 'matched']);+ expect(line.words[3].startSec).toBeCloseTo(1.6);+ });++ it('preserves low-confidence prior times and words, while snapping confident words together and honoring authored sides', () => {+ const cues = [+ { text: 'hello morning', startSec: null, endSec: null },+ { text: 'missing completely elsewhere', startSec: 4, endSec: 5, words: [{ w: 'old', startSec: 4, endSec: 5 }] },+ { text: 'quiet evening', startSec: 7, endSec: 9 },+ ];+ const aligned = alignDirectorWords(cues, [...words('hello morning', 2), ...words('quiet evening', 7.1)], { phraseAnchored: true });+ const snapped = snapLineStarts(aligned, [2.2, 7.2], cues);+ expect(snapped[0]).toMatchObject({ startSec: 2.2, endSec: 2.8, matched: 1 });+ expect(snapped[0].words[1].startSec).toBe(2.5);+ expect(snapped[1]).toEqual({ ...cues[1], matched: 0 });+ expect(musicVideoLyricCueSchema.safeParse(snapped[0]).success).toBe(true);+ expect(PORTOS_SCHEMA_VERSIONS.musicVideoProjects).toBeGreaterThanOrEqual(11);+ expect(snapped[2]).toMatchObject({ startSec: 7, endSec: 9, matched: 1 });+ expect(snapped[2].words[0].startSec).toBe(7.2);+ expect(snapLineStarts(aligned, [1, 3, 10], cues)).toEqual(aligned);+ });+});diff --git a/server/services/musicVideo/lyricTranscriber.js b/server/services/musicVideo/lyricTranscriber.jsindex a8c2f57763..71a077c0c2 100644--- a/server/services/musicVideo/lyricTranscriber.js+++ b/server/services/musicVideo/lyricTranscriber.js@@ -5,9 +5,9 @@* model is `base.en`, which is too weak for a sung vocal. Alignment therefore* brings its own runner and never asks the director to enable voice:*- * 1. `whisper-cli` on PATH → one-shot run over the whole decoded song with a+ * 1. `whisper-cli` on PATH → one-shot run over each requested audio window with a* music-grade model (large-v3-turbo), word timestamps from its `-ojf`- * JSON. A 3–4 minute song takes seconds on Apple Silicon.+ * JSON. Phrase-window orchestration lives in lyricAlign.js.* 2. The configured voice STT endpoint, when something answers there.* 3. `whisper-server` on PATH → a temporary loopback server on a free port* with the music-grade model, stopped when the alignment finishes.diff --git a/server/services/musicVideo/projectsFile.test.js b/server/services/musicVideo/projectsFile.test.jsindex fa7e429267..6ff1a619a2 100644--- a/server/services/musicVideo/projectsFile.test.js+++ b/server/services/musicVideo/projectsFile.test.js@@ -177,25 +177,28 @@ describe('projectsFile federation (#1770)', () => {{ w: 'home', startSec: 1.55, endSec: 2, conf: 'matched' },];await file.updateProject(p.id, {- lyricCues: [{ id: 'lc-1', text: 'walking home', startSec: 1, endSec: 2, words: nudged }],+ lyricCues: [{ id: 'lc-1', text: 'walking home', startSec: 1, endSec: 2, words: nudged, matched: 0.4 }],});const saved = await file.getProject(p.id);expect(saved.lyricCues[0].words).toEqual(nudged);expect(saved.lyricCues[0].text).toBe('walking home');+ expect(saved.lyricCues[0].matched).toBe(0.4);expect((await file.cloneProject(p.id)).lyricCues[0].words).toEqual(nudged);const retitled = await file.updateProject(p.id, {- lyricCues: [{ id: 'lc-1', text: 'walking house', startSec: 1, endSec: 2, words: nudged }],+ lyricCues: [{ id: 'lc-1', text: 'walking house', startSec: 1, endSec: 2, words: nudged, matched: 0.4 }],});expect(retitled.lyricCues[0]).toMatchObject({ text: 'walking house', startSec: 1, endSec: 2 });expect(retitled.lyricCues[0].words).toBeUndefined();+ expect(retitled.lyricCues[0].matched).toBeUndefined();await file.updateProject(p.id, {- lyricCues: [{ id: 'lc-1', text: 'walking home', startSec: 1, endSec: 2, words: nudged }],+ lyricCues: [{ id: 'lc-1', text: 'walking home', startSec: 1, endSec: 2, words: nudged, matched: 0.4 }],});const swapped = await file.updateProject(p.id, { trackId: 't2' });expect(swapped.lyricCues[0].text).toBe('walking home');expect(swapped.lyricCues[0].words).toBeUndefined();+ expect(swapped.lyricCues[0].matched).toBeUndefined();expect(swapped.lyricCues[0].startSec).toBeNull();expect(swapped.lyricCues[0].endSec).toBeNull();});diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.jsindex 04e06e12e4..7797f0ef79 100644--- a/server/services/musicVideo/projectsLogic.js+++ b/server/services/musicVideo/projectsLogic.js@@ -272,7 +272,11 @@ export function applyProjectPatch(project, patch) {...('automation' in patch ? {automation: patch.automation ? normalizeMusicVideoAutomation(patch.automation, project.automation) : null,} : {}),- ...(Array.isArray(patch.lyricCues) ? { lyricCues: normalizeLyricCues(patch.lyricCues) } : {}),+ ...(Array.isArray(patch.lyricCues) ? { lyricCues: normalizeLyricCues(patch.lyricCues).map((cue) => {+ const previous = project.lyricCues?.find((entry) => entry.id === cue.id);+ if (previous && previous.text !== cue.text) delete cue.matched;+ return cue;+ }) } : {}),...(Array.isArray(patch.lyricMarkers) ? { lyricMarkers: normalizeLyricMarkers(patch.lyricMarkers) } : {}),...(Array.isArray(patch.phrases) ? { phrases: normalizePhrases(patch.phrases) } : {}),// #8984 — the composition manifest is replaced whole; null clears it.diff --git a/server/services/musicVideo/timedText.js b/server/services/musicVideo/timedText.jsindex cb79b906f3..4c8ea1dd38 100644--- a/server/services/musicVideo/timedText.js+++ b/server/services/musicVideo/timedText.js@@ -95,7 +95,9 @@ export const normalizeLyricCues = (cues) => normalizeList(cues, 'lc', (cue) => {const text = trimTo(cue.text, MAX_CUE_TEXT);if (!text) return null;const words = normalizeWords(text, cue.words);- return words ? { text, words } : { text };+ const matched = Number.isFinite(cue.matched) && cue.matched >= 0 && cue.matched <= 1+ ? { matched: cue.matched } : {};+ return { text, ...(words ? { words } : {}), ...matched };});/** Normalize an edited phrase list: keep ids, trim label/intent. */@@ -112,6 +114,7 @@ export function invalidateTimedText(project) {const clearCues = (list) => (Array.isArray(list) ? list.map((e) => {const next = { ...e, startSec: null, endSec: null };delete next.words;+ delete next.matched;return next;}) : list);return {