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

fix: judge lip-sync take staleness on its own sung window, not the whole master (#9266)

Adam Eivy2fe9c6e09ff3
diff --git a/server/lib/README.md b/server/lib/README.md
index a13dbe2796..2f620dcc55 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -179,6 +179,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `catalogUniverseTags.js` | Pure transform that rewrites legacy machine universe tags (`from-universe`, `universe:<id>`) on backfilled catalog ingredients into friendly universe-NAME tags, preserving user tags + the structured `catalog_ingredient_refs` link. Used by the boot-time repair and the bible→catalog backfill. |
| `comicScriptParser.js` | Marvel/DC-format comic script parser. |
| `aspectRatio.js` | Describe a pixel canvas as the ratio phrase a prompt can use — `aspectRatioTerms(w, h)` (bounded best rational approximation, so 1096x1536 reads as 5:7 rather than 137:192) and `aspectRatioPhrase(w, h)` → `"5:7 portrait"` / `"16:9 landscape"` / `"1:1 square"`. Use it wherever a prompt has to state a framing the canvas already fixes, so the sentence and the canvas cannot drift. Pure. |
+| `audioFingerprint.js` | Loudness fingerprint of a stretch of a song (#9266): `computeRmsEnvelope(path)` decodes a file once to a 100 Hz integer-dBFS RMS envelope on the song's own frame grid, `windowFingerprint(envelope, { startSec, endSec })` stores a window of it (base64 Int8Array, ≤3 KB for 30 s), and `compareWindowFingerprint(fp, envelope)` says whether a newer master still carries that window (Pearson ≥ 0.98 and mean \|ΔdB\| ≤ 1.5 above a −60 dB codec-noise floor). Lets a lip-sync take survive a re-master that changed audio outside its window. |
| `composeStyledPrompt.js` | Compose user prompt + negative with an optional style preset, or an array of presets layered in order. Re-exported (unmodified) by `client/src/lib/composeStyledPrompt.js`. |
| `scriptVideoCompiler.js` | Compiles a scene script + bible into beat-level continuous-video clip specs (duration/frame-grid snapping, byte-stable descriptor injection, chain-length fresh-cut rule). |
| `creativeDirectorPresets.js` | Locked-at-creation aspect ratio + quality presets for the Creative Director. |
diff --git a/server/lib/audioFingerprint.js b/server/lib/audioFingerprint.js
new file mode 100644
index 0000000000..a13f382fe4
--- /dev/null
+++ b/server/lib/audioFingerprint.js
@@ -0,0 +1,140 @@
+/**
+ * Loudness fingerprints of a stretch of a song (#9266).
+ *
+ * A lip-sync take is valid for the audio it was cut from, not for the whole
+ * file: a re-mastered song that only changes bars outside a take's window must
+ * not invalidate the take. The fingerprint is a 100 Hz RMS envelope in integer
+ * dBFS (−90..0), laid on the SONG's own frame grid (frame k covers
+ * [k/100, (k+1)/100) s), so one decode of a master serves every take and two
+ * fingerprints of the same song time line up frame for frame.
+ *
+ * Stored shape: `{ version, rateHz, startFrame, db }` where `db` is base64 of an
+ * Int8Array — at most 3,000 bytes for a 30 s window.
+ */
+
+import { spawn } from './childProcess.js';
+import { findFfmpeg } from './ffmpeg.js';
+import { safeChildProcessOptions } from './processEnv.js';
+
+export const AUDIO_FINGERPRINT_VERSION = 1;
+export const FINGERPRINT_RATE_HZ = 100;
+const DECODE_RATE_HZ = 8000;
+const SAMPLES_PER_FRAME = DECODE_RATE_HZ / FINGERPRINT_RATE_HZ;
+const FLOOR_DB = -90;
+// Below this level the envelope is codec noise and dither, which a re-encode
+// moves by tens of dB without anything audible changing — compare above it.
+const COMPARE_FLOOR_DB = -60;
+// A window whose envelope barely moves (sustained tone, silence) has no shape
+// to correlate; the mean level difference alone judges it.
+const MIN_SHAPE_STD_DB = 1;
+export const FINGERPRINT_MIN_CORRELATION = 0.98;
+export const FINGERPRINT_MAX_MEAN_DELTA_DB = 1.5;
+
+/**
+ * Decode `path` to 8 kHz mono and return its whole 100 Hz RMS envelope as an
+ * Int8Array of dBFS. The PCM is folded into frames as it streams, so memory is
+ * one byte per 10 ms whatever the song length. Throws when ffmpeg is missing
+ * or the decode fails.
+ */
+export async function computeRmsEnvelope(path) {
+ const ffmpeg = await findFfmpeg();
+ if (!ffmpeg) throw new Error('ffmpeg is required to fingerprint audio');
+ return new Promise((resolve, reject) => {
+ const proc = spawn(ffmpeg, [
+ '-v', 'error', '-i', path, '-vn', '-ac', '1', '-ar', String(DECODE_RATE_HZ), '-f', 's16le', '-acodec', 'pcm_s16le', 'pipe:1',
+ ], safeChildProcessOptions({ stdio: ['ignore', 'pipe', 'pipe'] }));
+ const frames = [];
+ let sumSq = 0;
+ let count = 0;
+ let carry = null;
+ let stderr = '';
+ const pushFrame = () => {
+ const rms = Math.sqrt(sumSq / count) / 32768;
+ frames.push(rms > 0 ? Math.max(FLOOR_DB, Math.min(0, Math.round(20 * Math.log10(rms)))) : FLOOR_DB);
+ sumSq = 0;
+ count = 0;
+ };
+ proc.stdout.on('data', (chunk) => {
+ const buf = carry ? Buffer.concat([carry, chunk]) : chunk;
+ const whole = buf.length - (buf.length % 2);
+ carry = whole < buf.length ? buf.subarray(whole) : null;
+ for (let at = 0; at < whole; at += 2) {
+ const s = buf.readInt16LE(at);
+ sumSq += s * s;
+ if (++count === SAMPLES_PER_FRAME) pushFrame();
+ }
+ });
+ proc.stderr.on('data', (chunk) => { stderr = (stderr + chunk.toString()).slice(-500); });
+ proc.on('error', reject);
+ proc.on('close', (code) => {
+ if (code !== 0) { reject(new Error(`ffmpeg could not decode the audio: ${stderr.trim() || `exit ${code}`}`)); return; }
+ resolve(Int8Array.from(frames));
+ });
+ });
+}
+
+// Whole frames inside [startSec, endSec).
+const windowFrames = ({ startSec, endSec }) => {
+ const start = Math.ceil(startSec * FINGERPRINT_RATE_HZ - 1e-6);
+ const end = Math.floor(endSec * FINGERPRINT_RATE_HZ + 1e-6);
+ return { start, end };
+};
+
+/** The stored fingerprint of `window` cut from a whole-song envelope, or null when the song is shorter than the window. */
+export function windowFingerprint(envelope, window) {
+ const { start, end } = windowFrames(window);
+ if (!(end > start) || end > envelope.length) return null;
+ const db = envelope.slice(start, end);
+ return {
+ version: AUDIO_FINGERPRINT_VERSION,
+ rateHz: FINGERPRINT_RATE_HZ,
+ startFrame: start,
+ db: Buffer.from(db.buffer, db.byteOffset, db.byteLength).toString('base64'),
+ };
+}
+
+const decodeFingerprint = (fingerprint) => {
+ if (fingerprint?.version !== AUDIO_FINGERPRINT_VERSION || fingerprint.rateHz !== FINGERPRINT_RATE_HZ) return null;
+ if (!Number.isInteger(fingerprint.startFrame) || fingerprint.startFrame < 0 || typeof fingerprint.db !== 'string') return null;
+ const bytes = Buffer.from(fingerprint.db, 'base64');
+ return bytes.length > 0 ? new Int8Array(bytes.buffer, bytes.byteOffset, bytes.length) : null;
+};
+
+/**
+ * Does `envelope` (a whole song) still carry the audio a stored fingerprint
+ * recorded? Returns `{ same, correlation, meanDeltaDb }`; `same` is false when
+ * the fingerprint is unreadable or the song no longer reaches the window.
+ * Pearson correlation below 0.98 or a mean |ΔdB| above 1.5 dB is a change.
+ */
+export function compareWindowFingerprint(fingerprint, envelope) {
+ const stored = decodeFingerprint(fingerprint);
+ if (!stored || fingerprint.startFrame + stored.length > envelope.length) return { same: false, correlation: null, meanDeltaDb: null };
+ const n = stored.length;
+ const a = new Float64Array(n);
+ const b = new Float64Array(n);
+ let sumA = 0;
+ let sumB = 0;
+ let sumDelta = 0;
+ for (let i = 0; i < n; i++) {
+ a[i] = Math.max(COMPARE_FLOOR_DB, stored[i]);
+ b[i] = Math.max(COMPARE_FLOOR_DB, envelope[fingerprint.startFrame + i]);
+ sumA += a[i];
+ sumB += b[i];
+ sumDelta += Math.abs(a[i] - b[i]);
+ }
+ const meanA = sumA / n;
+ const meanB = sumB / n;
+ let cov = 0;
+ let varA = 0;
+ let varB = 0;
+ for (let i = 0; i < n; i++) {
+ cov += (a[i] - meanA) * (b[i] - meanB);
+ varA += (a[i] - meanA) ** 2;
+ varB += (b[i] - meanB) ** 2;
+ }
+ const shaped = Math.sqrt(varA / n) >= MIN_SHAPE_STD_DB && Math.sqrt(varB / n) >= MIN_SHAPE_STD_DB;
+ const correlation = shaped ? cov / Math.sqrt(varA * varB) : null;
+ const meanDeltaDb = sumDelta / n;
+ const same = meanDeltaDb <= FINGERPRINT_MAX_MEAN_DELTA_DB && (correlation == null || correlation >= FINGERPRINT_MIN_CORRELATION);
+ return { same, correlation, meanDeltaDb };
+}
diff --git a/server/lib/audioFingerprint.test.js b/server/lib/audioFingerprint.test.js
new file mode 100644
index 0000000000..783dcc1a46
--- /dev/null
+++ b/server/lib/audioFingerprint.test.js
@@ -0,0 +1,77 @@
+/**
+ * Window fingerprints against real ffmpeg (#9266): a lossy re-encode of the
+ * same master must compare as the same audio, and a changed stretch must not.
+ */
+import { afterAll, describe, expect, it } from 'vitest';
+import { execFileSync } from 'node:child_process';
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { findFfmpeg } from './ffmpeg.js';
+import { compareWindowFingerprint, computeRmsEnvelope, windowFingerprint } from './audioFingerprint.js';
+
+const ffmpeg = await findFfmpeg();
+const RATE = 48000;
+const SONG_SEC = 10;
+const dir = await mkdtemp(join(tmpdir(), 'portos-audio-fp-'));
+afterAll(() => rm(dir, { recursive: true, force: true }));
+
+// A "sung" line: a 220 Hz tone whose loudness steps every 250 ms through a
+// fixed pattern, so the window has a real envelope shape to correlate.
+// `silence` blanks [startSec, endSec) — the changed bar of a new mix.
+function songWav({ silence = null } = {}) {
+ const samples = SONG_SEC * RATE;
+ const buf = Buffer.alloc(44 + samples * 2);
+ buf.write('RIFF', 0); buf.writeUInt32LE(36 + samples * 2, 4); buf.write('WAVE', 8);
+ buf.write('fmt ', 12); buf.writeUInt32LE(16, 16); buf.writeUInt16LE(1, 20); buf.writeUInt16LE(1, 22);
+ buf.writeUInt32LE(RATE, 24); buf.writeUInt32LE(RATE * 2, 28); buf.writeUInt16LE(2, 32); buf.writeUInt16LE(16, 34);
+ buf.write('data', 36); buf.writeUInt32LE(samples * 2, 40);
+ const levels = [0.05, 0.4, 0.15, 0.7, 0.25, 0.02, 0.5, 0.1];
+ for (let i = 0; i < samples; i++) {
+ const t = i / RATE;
+ const muted = silence && t >= silence.startSec && t < silence.endSec;
+ const amp = muted ? 0 : levels[Math.floor(t * 4) % levels.length];
+ buf.writeInt16LE(Math.round(amp * 30000 * Math.sin(2 * Math.PI * 220 * t)), 44 + i * 2);
+ }
+ return buf;
+}
+
+const WINDOW = { startSec: 2.225, endSec: 7.275 };
+
+describe.skipIf(!ffmpeg)('audio window fingerprints', () => {
+ it('matches a lossy re-encode of the same window and rejects a changed one', async () => {
+ const master = join(dir, 'master.wav');
+ await writeFile(master, songWav());
+ const fp = windowFingerprint(await computeRmsEnvelope(master), WINDOW);
+ // Frames on the song's own 100 Hz grid, fully inside the window.
+ expect(fp).toMatchObject({ version: 1, rateHz: 100, startFrame: 223 });
+ expect(Buffer.from(fp.db, 'base64')).toHaveLength(727 - 223);
+
+ // The same master through AAC — codec noise, no content change.
+ const reencoded = join(dir, 'master.m4a');
+ execFileSync(ffmpeg, ['-v', 'error', '-i', master, '-c:a', 'aac', '-b:a', '128k', '-y', reencoded]);
+ const aac = compareWindowFingerprint(fp, await computeRmsEnvelope(reencoded));
+ expect(aac.same).toBe(true);
+ expect(aac.correlation).toBeGreaterThan(0.98);
+
+ // A new mix whose change sits outside the window keeps the window; one
+ // that blanks a second inside it does not.
+ const outside = join(dir, 'outside.wav');
+ await writeFile(outside, songWav({ silence: { startSec: 8, endSec: 9 } }));
+ expect(compareWindowFingerprint(fp, await computeRmsEnvelope(outside)).same).toBe(true);
+ const inside = join(dir, 'inside.wav');
+ await writeFile(inside, songWav({ silence: { startSec: 4, endSec: 5 } }));
+ expect(compareWindowFingerprint(fp, await computeRmsEnvelope(inside)).same).toBe(false);
+ }, 30_000);
+
+ it('treats a song that no longer reaches the window, or an unreadable fingerprint, as changed', async () => {
+ const master = join(dir, 'short-master.wav');
+ await writeFile(master, songWav());
+ const envelope = await computeRmsEnvelope(master);
+ expect(windowFingerprint(envelope, { startSec: 8, endSec: 12 })).toBeNull();
+ const fp = windowFingerprint(envelope, WINDOW);
+ expect(compareWindowFingerprint(fp, envelope.slice(0, 500)).same).toBe(false);
+ expect(compareWindowFingerprint({ ...fp, version: 99 }, envelope).same).toBe(false);
+ expect(compareWindowFingerprint(null, envelope).same).toBe(false);
+ }, 30_000);
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index b360d16598..056651a2aa 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -99,6 +99,7 @@ export * as catalogUniverseTags from './catalogUniverseTags.js';
export * from './canonPrompt.js';
export * from './comicScriptParser.js';
export * from './aspectRatio.js';
+export * from './audioFingerprint.js';
export * from './composeStyledPrompt.js';
export * from './scriptVideoCompiler.js';
export * from './creativeDirectorPresets.js';
diff --git a/server/services/musicVideo/excerptRender.js b/server/services/musicVideo/excerptRender.js
index 175827de4f..a0f39241a5 100644
--- a/server/services/musicVideo/excerptRender.js
+++ b/server/services/musicVideo/excerptRender.js
@@ -29,6 +29,7 @@ import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { safeUnder } from '../../lib/ffmpeg.js';
import { encodeFileContactSheetAtTimes } from '../htmlComposition/encode.js';
import { getProject, listProjects, mutateProjectRecord } from './projects.js';
+import { assertCurrentPerformanceTakes } from './performanceShot.js';
import { planMusicVideoRender, buildMusicVideoFfmpegArgs, excerptBoundaryTimes, isLocalRenderMark, resolveMasterAudioPath, resolveSoundBedPath } from './render.js';
import { encodeCodeComposition, prepareCodeRender, writeCodeProofSheet } from './codeRender.js';
import { encodeDocumentComposition, prepareDocumentRender } from './documentRender.js';
@@ -97,6 +98,7 @@ const SEEKED_EXCERPTS = Object.freeze({
document: {
label: 'composition document',
soundBed: true,
+ performanceTakes: true,
prepare: async (project) => {
const plan = await prepareDocumentRender(project);
const songSections = (project.scenes || [])
@@ -115,6 +117,7 @@ async function launchSeekedExcerpt({ projectId, project, startSec, endSec, revis
// Same order as a full render: a missing master throws before the
// excerpt is marked rendering.
const audioPath = await resolveMasterAudioPath(project);
+ if (renderer.performanceTakes) await assertCurrentPerformanceTakes(project, audioPath);
const soundBed = renderer.soundBed ? await resolveSoundBedPath(project) : null;
if (!(startSec >= 0) || !(endSec > startSec) || endSec > prepared.totalSec + 1e-6) {
throw new ServerError(
diff --git a/server/services/musicVideo/performanceShot.js b/server/services/musicVideo/performanceShot.js
index 9f7102aee5..f3ced656f2 100644
--- a/server/services/musicVideo/performanceShot.js
+++ b/server/services/musicVideo/performanceShot.js
@@ -32,12 +32,13 @@
*/
import { createHash, randomUUID } from 'crypto';
-import { createReadStream } from 'fs';
+import { createReadStream, existsSync } from 'fs';
import { unlink } from 'fs/promises';
import { basename, join } from 'path';
import { ServerError } from '../../lib/errorHandler.js';
import { ensureDir, PATHS } from '../../lib/fileUtils.js';
-import { findFfmpeg, probeVideoDuration, runFfmpegProcess } from '../../lib/ffmpeg.js';
+import { findFfmpeg, probeVideoDuration, runFfmpegProcess, safeUnder } from '../../lib/ffmpeg.js';
+import { compareWindowFingerprint, computeRmsEnvelope, windowFingerprint } from '../../lib/audioFingerprint.js';
import { getFalVideoModel } from '../../lib/falVideoModels.js';
import {
clipRelativeCues,
@@ -89,34 +90,135 @@ const refuse = (message, code, status = 400) => new ServerError(message, { statu
// Recorded vs current scene times agree within a millisecond.
const SAME_TIME_SEC = 0.001;
+const STALE_REASON_LABELS = Object.freeze({
+ 'not-lip-synced': 'not lip-synced',
+ retimed: 're-timed',
+ 'audio-changed': 'sung window changed in the song',
+});
+
+// A take made before #9266 carries no window fingerprint. Its old master can
+// still be found among the linked track's earlier renders (the library keeps
+// every take's bytes under data/music/), matched by the content hash the take
+// recorded. Hashes and envelopes are computed at most once per file per check.
+function legacyMasterLookup(project, masterPath) {
+ let candidates = null;
+ const envelopes = new Map();
+ const listCandidates = async () => {
+ if (candidates) return candidates;
+ candidates = [];
+ if (!project?.trackId) return candidates;
+ const { getTrack } = await import('../tracks/index.js');
+ const track = await getTrack(project.trackId).catch(() => null);
+ const seen = new Set([masterPath]);
+ for (const render of Array.isArray(track?.renders) ? track.renders : []) {
+ const path = render?.audioFilename ? safeUnder(PATHS.music, render.audioFilename) : null;
+ if (!path || seen.has(path) || !existsSync(path)) continue;
+ seen.add(path);
+ candidates.push({ path, sha256: null });
+ }
+ return candidates;
+ };
+ return async function envelopeForSha(sha256) {
+ if (typeof sha256 !== 'string' || !sha256) return null;
+ if (envelopes.has(sha256)) return envelopes.get(sha256);
+ let envelope = null;
+ for (const candidate of await listCandidates()) {
+ candidate.sha256 ??= await hashFile(candidate.path).catch(() => '');
+ if (candidate.sha256 !== sha256) continue;
+ envelope = await computeRmsEnvelope(candidate.path);
+ break;
+ }
+ envelopes.set(sha256, envelope);
+ return envelope;
+ };
+}
+
/**
- * Performance scenes whose SELECTED clip cannot be rendered as a lip-synced
- * shot: a take with no performance instruction (a cutaway render or an import
- * made before the scene became a performance), or one generated against a
- * different song interval (the scene was re-timed) or a different recording
- * (the song was replaced). Returns
- * `[{ sceneId, reason: 'not-lip-synced' | 'retimed' | 'audio-changed' }]`;
- * the master is hashed only when there is a performance take to check.
+ * Review every performance scene's SELECTED clip against the current master.
+ * Returns `[{ sceneId, reason, stale }]`:
+ *
+ * - `not-lip-synced` (stale) — no performance instruction: a cutaway render
+ * or an import made before the scene became a performance;
+ * - `audio-changed` (stale) — the master was replaced AND the take's own
+ * audio window sounds different in it;
+ * - `retimed` (stale) — the scene's song interval moved since the take;
+ * - `audio-rehashed` (NOT stale, informational) — the master's bytes
+ * changed (a re-master or re-encode) but the take's window did not.
+ *
+ * Staleness is judged on the take's window, not the whole file (#9266): the
+ * take's stored loudness fingerprint (or, for an older take, the same window
+ * of its old master when that file is still in the track's render history)
+ * is compared with the new master. With neither, a changed master is stale.
+ * The master is hashed only when there is a performance take to check, and
+ * decoded only when its hash changed.
*/
-export async function findStalePerformanceTakes(project, masterPath) {
- const stale = [];
+export async function reviewPerformanceTakes(project, masterPath) {
+ const results = [];
const selected = [];
for (const scene of Array.isArray(project?.scenes) ? project.scenes : []) {
if (!isPerformanceScene(scene) || !scene.videoHistoryId) continue;
const instruction = selectedPerformanceInstruction(scene);
if (instruction) selected.push({ scene, instruction });
- else stale.push({ sceneId: scene.sceneId, reason: 'not-lip-synced' });
+ else results.push({ sceneId: scene.sceneId, reason: 'not-lip-synced', stale: true });
}
- if (selected.length === 0) return stale;
+ if (selected.length === 0) return results;
const sha256 = await hashFile(masterPath);
+ let currentEnvelope = null;
+ const oldEnvelope = legacyMasterLookup(project, masterPath);
+ const windowUnchanged = async (instruction) => {
+ let fingerprint = instruction.audio?.windowFingerprint;
+ if (!fingerprint) {
+ const envelope = await oldEnvelope(instruction.audio?.sha256);
+ fingerprint = envelope && instruction.audioWindow ? windowFingerprint(envelope, instruction.audioWindow) : null;
+ if (!fingerprint) return false;
+ }
+ currentEnvelope ??= await computeRmsEnvelope(masterPath);
+ return compareWindowFingerprint(fingerprint, currentEnvelope).same;
+ };
for (const { scene, instruction } of selected) {
const interval = instruction.songInterval || {};
- if (instruction.audio?.sha256 !== sha256) stale.push({ sceneId: scene.sceneId, reason: 'audio-changed' });
+ const rehashed = instruction.audio?.sha256 !== sha256;
+ // A window that cannot be compared (decode failure) stays stale — the
+ // pre-#9266 answer — rather than rendering a take out of sync.
+ const unchanged = !rehashed || await windowUnchanged(instruction).catch((err) => {
+ console.warn(`⚠️ Music Video: could not compare scene ${scene.sceneId}'s sung window with the new master: ${err.message}`);
+ return false;
+ });
+ if (!unchanged) results.push({ sceneId: scene.sceneId, reason: 'audio-changed', stale: true });
else if (!(Math.abs(interval.startSec - scene.startSec) <= SAME_TIME_SEC && Math.abs(interval.endSec - scene.endSec) <= SAME_TIME_SEC)) {
- stale.push({ sceneId: scene.sceneId, reason: 'retimed' });
- }
+ results.push({ sceneId: scene.sceneId, reason: 'retimed', stale: true });
+ } else if (rehashed) results.push({ sceneId: scene.sceneId, reason: 'audio-rehashed', stale: false });
}
- return stale;
+ return results;
+}
+
+/** The stale entries of `reviewPerformanceTakes`: `[{ sceneId, reason }]`. */
+export async function findStalePerformanceTakes(project, masterPath) {
+ return (await reviewPerformanceTakes(project, masterPath))
+ .filter((r) => r.stale)
+ .map(({ sceneId, reason }) => ({ sceneId, reason }));
+}
+
+/**
+ * The one staleness gate every renderer that draws performance takes runs
+ * (concat, composed, document, and their excerpts): a performance take sings
+ * one stretch of one recording, so a re-timed scene or a changed sung window
+ * would put mouth motion over the wrong audio. Throws 422
+ * STALE_PERFORMANCE_TAKES naming each scene's reason.
+ */
+export async function assertCurrentPerformanceTakes(project, masterPath) {
+ const reviewed = await reviewPerformanceTakes(project, masterPath);
+ const rehashed = reviewed.filter((r) => r.reason === 'audio-rehashed').length;
+ if (rehashed > 0) console.log(`🎵 Music Video: ${rehashed} lip-sync take${rehashed === 1 ? '' : 's'} still match${rehashed === 1 ? 'es' : ''} the re-mastered song in ${rehashed === 1 ? 'its' : 'their'} sung window`);
+ const stale = reviewed.filter((r) => r.stale).map(({ sceneId, reason }) => ({ sceneId, reason }));
+ if (stale.length === 0) return;
+ const counts = new Map();
+ for (const { reason } of stale) counts.set(reason, (counts.get(reason) || 0) + 1);
+ const why = [...counts].map(([reason, n]) => `${n} ${STALE_REASON_LABELS[reason] || reason}`).join(', ');
+ throw new ServerError(
+ `${stale.length} performance shot${stale.length === 1 ? ' has' : 's have'} no lip-synced take of the current song interval and recording (${why}) — regenerate ${stale.length === 1 ? 'it' : 'them'}, or switch to Cutaway, before rendering`,
+ { status: 422, code: 'STALE_PERFORMANCE_TAKES', context: { stale } },
+ );
}
/**
@@ -165,6 +267,15 @@ export async function preparePerformanceShot({ musicVideo, backend, sourceImageP
if (stemPath) assertVocalStemTimebase(await probeVideoDuration(stemPath), songDurationSec);
const audioSha256 = await hashFile(masterPath);
+ // #9266: the MASTER's loudness over this window, so a later re-master that
+ // leaves these bars alone keeps the take. Best-effort — a take without one
+ // falls back to the old-master lookup, and then to whole-file staleness.
+ const windowFingerprintRecord = await computeRmsEnvelope(masterPath)
+ .then((envelope) => windowFingerprint(envelope, { startSec: plan.windowStartSec, endSec: plan.windowEndSec }))
+ .catch((err) => {
+ console.warn(`⚠️ Music Video: could not fingerprint the performance window for scene ${scene.sceneId}: ${err.message}`);
+ return null;
+ });
const conditioningSha256 = stemPath ? await hashFile(stemPath) : audioSha256;
await ensureDir(PATHS.uploads);
const audioFilePath = join(PATHS.uploads, `mv-performance-${randomUUID()}.wav`);
@@ -189,9 +300,11 @@ export async function preparePerformanceShot({ musicVideo, backend, sourceImageP
source: project.trackId ? 'track' : 'upload',
sha256: audioSha256,
songDurationSec,
+ windowFingerprint: windowFingerprintRecord,
// What the provider heard: the master itself, or a vocal stem on the
// master's timebase. `sha256` above stays the master's, so a take
- // is stale only when the song changes, not when a stem is swapped.
+ // is stale only when the song changes, not when a stem is swapped —
+ // and then only when `windowFingerprint` says this window changed.
conditioning: { source: stemPath ? 'vocal-stem' : 'master', sha256: conditioningSha256 },
},
songInterval: { startSec: scene.startSec, endSec: scene.endSec },
diff --git a/server/services/musicVideo/performanceShot.test.js b/server/services/musicVideo/performanceShot.test.js
index 97d083b5c3..1bd0e73349 100644
--- a/server/services/musicVideo/performanceShot.test.js
+++ b/server/services/musicVideo/performanceShot.test.js
@@ -19,6 +19,9 @@ vi.mock('../../lib/fileUtils.js', async (importOriginal) => makePathsProxy(await
const getProject = vi.fn();
vi.mock('./projects.js', () => ({ getProject: (...a) => getProject(...a), listProjects: vi.fn(async () => []), updateProject: vi.fn() }));
vi.mock('../settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));
+// A pre-#9266 take's old master is found through the linked track's renders.
+const getTrack = vi.fn(async () => null);
+vi.mock('../tracks/index.js', () => ({ getTrack: (...a) => getTrack(...a) }));
// render.js reads clip history through local.js; point it at the real history
// store the fal lane writes, without loading the local runtime.
vi.mock('../videoGen/local.js', async () => {
@@ -91,6 +94,7 @@ beforeEach(async () => {
vi.unstubAllGlobals();
videoGenEvents.removeAllListeners();
getProject.mockReset();
+ getTrack.mockReset();
// Queue-owned slices are deleted by the media-job queue, which these tests bypass.
await rm(PATHS.uploads, { recursive: true, force: true });
await mkdir(PATHS.music, { recursive: true });
@@ -192,11 +196,38 @@ describe.skipIf(!ffmpeg)('music-video performance shot through the fal lip-sync
expect(await findStalePerformanceTakes({ scenes: [withTake] }, songPath)).toEqual([]);
expect(await findStalePerformanceTakes({ scenes: [{ ...withTake, endSec: 22 }] }, songPath))
.toEqual([{ sceneId: 'mvs-1', reason: 'retimed' }]);
- const replaced = songWav();
- replaced.writeInt16LE(1000, 44 + 2);
- await writeFile(songPath, replaced);
+ // #9266: a re-master that changes the song OUTSIDE the take's window
+ // (18.225–23.275) keeps the take; one that changes its sung window does not.
+ const original = await readFile(songPath);
+ const remastered = songWav();
+ for (let i = 0; i < RATE; i++) remastered.writeInt16LE(Math.round(20000 * Math.sin(i / 8)), 44 + (5 * RATE + i) * 2);
+ await writeFile(songPath, remastered);
+ expect(await findStalePerformanceTakes({ scenes: [withTake] }, songPath)).toEqual([]);
+ const resung = songWav();
+ for (let i = 0; i < RATE; i++) resung.writeInt16LE(Math.round(20000 * Math.sin(i / 8)), 44 + (21 * RATE + i) * 2);
+ await writeFile(songPath, resung);
expect(await findStalePerformanceTakes({ scenes: [withTake] }, songPath))
.toEqual([{ sceneId: 'mvs-1', reason: 'audio-changed' }]);
+
+ // A take made before window fingerprints existed is compared against its
+ // old master when the track's render history still holds it, and is stale
+ // when that file is gone.
+ const legacyInstruction = { ...si, audio: { ...si.audio, windowFingerprint: undefined } };
+ const { scene: legacyScene } = appendSceneTakes(project({ referenceImageId: 'frame.png' }), 'mvs-1', [{
+ kind: 'video', assetId: job.jobId, source: 'generated', shotInstruction: legacyInstruction,
+ }]);
+ const legacyProject = { trackId: 'trk-1', scenes: [legacyScene] };
+ await writeFile(join(PATHS.music, 'song-v1.wav'), original);
+ await writeFile(songPath, remastered);
+ getTrack.mockResolvedValue({ id: 'trk-1', audioFilename: 'song.wav', renders: [{ audioFilename: 'song.wav' }, { audioFilename: 'song-v1.wav' }] });
+ expect(await findStalePerformanceTakes(legacyProject, songPath)).toEqual([]);
+ await writeFile(songPath, resung);
+ expect(await findStalePerformanceTakes(legacyProject, songPath))
+ .toEqual([{ sceneId: 'mvs-1', reason: 'audio-changed' }]);
+ await writeFile(songPath, remastered);
+ getTrack.mockResolvedValue({ id: 'trk-1', audioFilename: 'song.wav', renders: [{ audioFilename: 'song.wav' }] });
+ expect(await findStalePerformanceTakes(legacyProject, songPath))
+ .toEqual([{ sceneId: 'mvs-1', reason: 'audio-changed' }]);
// A performance scene whose selected clip is not a lip-sync take is refused too.
expect(await findStalePerformanceTakes({ scenes: [{ ...withTake, takes: [] }] }, songPath))
.toEqual([{ sceneId: 'mvs-1', reason: 'not-lip-synced' }]);
diff --git a/server/services/musicVideo/render.document.test.js b/server/services/musicVideo/render.document.test.js
index f309fca75d..94b60e40b9 100644
--- a/server/services/musicVideo/render.document.test.js
+++ b/server/services/musicVideo/render.document.test.js
@@ -65,4 +65,21 @@ describe('composition-document render plan', () => {
expect(call).not.toHaveProperty('windowStart');
await vi.waitFor(async () => expect((await projects.getProject(id)).renderHistoryId).toBe(jobId));
});
+
+ it('refuses a full render and an excerpt over a stale performance take, like a footage render (#9266)', async () => {
+ const id = await documentProject();
+ await importDocumentTemplate(id);
+ await projects.mutateProjectRecord(id, (current) => ({ project: {
+ ...current,
+ scenes: [{ sceneId: 'mvs-1', order: 0, shotMode: 'performance', startSec: 1, endSec: 3, videoHistoryId: 'clip-1', takes: [] }],
+ } }));
+ encodeDocumentComposition.mockClear();
+ for (let attempt = 0; attempt < 2; attempt++) {
+ await expect(renderMusicVideo(id)).rejects.toMatchObject({
+ status: 422, code: 'STALE_PERFORMANCE_TAKES', context: { stale: [{ sceneId: 'mvs-1', reason: 'not-lip-synced' }] },
+ });
+ await expect(startExcerptRender(id, { startSec: 1, endSec: 3 })).rejects.toMatchObject({ status: 422, code: 'STALE_PERFORMANCE_TAKES' });
+ }
+ expect(encodeDocumentComposition).not.toHaveBeenCalled();
+ });
});
diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.js
index 90b32a8c85..e77cfc8e54 100644
--- a/server/services/musicVideo/render.js
+++ b/server/services/musicVideo/render.js
@@ -42,7 +42,7 @@ import { encodeCodeComposition, prepareCodeRender, writeCodeProofSheet } from '.
import { encodeDocumentComposition, prepareDocumentRender, sweepDocumentScratch } from './documentRender.js';
import { renderTypographyOverlays, removeCompositionScratch, sweepCompositionScratch, renderSongComposition } from './compositionRender.js';
import { selectedPerformanceInstruction } from '../../lib/musicVideoShotTiming.js';
-import { findStalePerformanceTakes } from './performanceShot.js';
+import { assertCurrentPerformanceTakes } from './performanceShot.js';
import { ensureInstanceId } from '../instanceIdentity.js';
import { AUDIO_NORM, buildAudioBedMix } from '../videoTimeline/audioBedMix.js';
import { projectSoundBed } from './soundBed.js';
@@ -567,16 +567,9 @@ export async function planMusicVideoRender(project) {
if (!ffmpeg) throw new ServerError('ffmpeg not found on PATH', { status: 500, code: 'FFMPEG_MISSING' });
const audioPath = await resolveMasterAudioPath(project);
- // #8977: a performance take sings one stretch of one recording. If the
- // scene was re-timed or the song replaced since, its mouth motion no longer
- // matches the audio under it — refuse rather than render it out of sync.
- const stale = await findStalePerformanceTakes(project, audioPath);
- if (stale.length > 0) {
- throw new ServerError(
- `${stale.length} performance shot${stale.length === 1 ? ' has' : 's have'} no lip-synced take of the current song interval and recording — regenerate ${stale.length === 1 ? 'it' : 'them'}, or switch to Cutaway, before rendering`,
- { status: 422, code: 'STALE_PERFORMANCE_TAKES', context: { stale } },
- );
- }
+ // #8977/#9266: refuse a performance take whose scene was re-timed or whose
+ // sung window changed in the current master.
+ await assertCurrentPerformanceTakes(project, audioPath);
// #8985: a composed render cuts still and card sections into the same
// timebase as the footage; plain concat renders footage only, as before.
const composed = project.composition?.mode === 'composed';
@@ -640,6 +633,9 @@ const SEEKED_RENDERERS = Object.freeze({
label: 'composition document',
modelId: 'music-video-document',
soundBed: true,
+ // A document draws the scenes' selected takes, so it runs the same
+ // performance-take gate as a footage render (#9266).
+ performanceTakes: true,
prepare: (project) => prepareDocumentRender(project),
encode: ({ plan, project, jobId, audioPath, soundBed, outputPath, signal, onProgress }) => encodeDocumentComposition({
project, plan, jobId, audioPath, soundBed, outputPath, signal, onProgress,
@@ -655,6 +651,7 @@ async function renderSeekedMode(projectId, project, handOff, renderer) {
// Resolve the master before any rendering mark. A missing track throws here
// and the caller releases the pending slot without leaving a job running.
const audioPath = await resolveMasterAudioPath(project);
+ if (renderer.performanceTakes) await assertCurrentPerformanceTakes(project, audioPath);
const soundBed = renderer.soundBed ? await resolveSoundBedPath(project) : null;
await ensureDir(PATHS.videos);
await ensureDir(PATHS.videoThumbnails);