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: separate Music Video lip-sync evidence from duration parity (#9347)

Adam Eivyb72dd3da1a72
diff --git a/client/src/components/musicVideo/AutoReviewPanel.jsx b/client/src/components/musicVideo/AutoReviewPanel.jsx
index fc1ad1c7b7..829e6f9139 100644
--- a/client/src/components/musicVideo/AutoReviewPanel.jsx
+++ b/client/src/components/musicVideo/AutoReviewPanel.jsx
@@ -13,7 +13,7 @@ const STATUS_TONES = {
'needs-human': 'text-port-warning', failed: 'text-port-error', canceled: 'text-port-text-muted',
};
const CHECK_TONES = { pass: 'bg-port-success/20 text-port-success', fail: 'bg-port-error/20 text-port-error', unverified: 'bg-port-border text-port-text-muted' };
-const CHECK_LABELS = { composition: 'Composition', continuity: 'Continuity', motion: 'Motion', audioSync: 'Audio sync (stream parity)' };
+const CHECK_LABELS = { composition: 'Composition', continuity: 'Continuity', motion: 'Motion', audioSync: 'Stream-duration parity', lipSync: 'Temporal lip-sync' };
const ACTION_LABELS = {
wait: (a) => (a.on === 'generation' ? 'Waiting for the revised sections to generate…' : 'Rendering the draft…'),
reviewing: () => 'Reviewing the draft (frames + continuous excerpt)…',
@@ -64,6 +64,11 @@ function AttemptRow({ attempt }) {
{review.evidence.continuous ? ' + continuous-excerpt analysis' : ` — continuous analysis unavailable (${review.evidence.continuousError || 'not run'})`}
</p>
)}
+ {review?.evidence?.temporal && <p className="text-[10px] text-port-text-muted">
+ Temporal evidence: {review.evidence.temporal.status}
+ {review.evidence.temporal.analyzer && ` · ${review.evidence.temporal.analyzer.id} ${review.evidence.temporal.analyzer.version}`}
+ {review.evidence.temporal.reason && ` — ${review.evidence.temporal.reason}`}
+ </p>}
{review?.summary && <p className="text-port-text-muted">{review.summary}</p>}
{review?.findings?.length > 0 && (
<ul className="space-y-0.5">
diff --git a/client/src/components/musicVideo/PerformanceEvidence.jsx b/client/src/components/musicVideo/PerformanceEvidence.jsx
new file mode 100644
index 0000000000..a1d7e756ed
--- /dev/null
+++ b/client/src/components/musicVideo/PerformanceEvidence.jsx
@@ -0,0 +1,82 @@
+import { useEffect, useRef, useState } from 'react';
+import { formatTimecode } from '../../utils/formatters.js';
+
+/** One transport: muted output picture against the take's recorded source.
+ * Word windows are clip-relative; temporal evidence is excerpt-relative.
+ */
+export default function PerformanceEvidence({ clipSrc, instruction, temporal = null, excerptStartSec = 0 }) {
+ const video = useRef(null);
+ const audio = useRef(null);
+ const [sourceMuted, setSourceMuted] = useState(false);
+ const [error, setError] = useState(null);
+ const conditioning = instruction?.audio?.conditioning;
+ const filename = conditioning?.filename;
+ const source = filename ? `/data/music/${encodeURIComponent(filename)}` : null;
+ const windowStart = instruction?.audioWindow?.startSec;
+ const canSync = source && Number.isFinite(windowStart);
+ const cues = Array.isArray(instruction?.cues) ? instruction.cues : [];
+
+ useEffect(() => {
+ const picture = video.current;
+ const recording = audio.current;
+ setError(null);
+ return () => { picture?.pause(); recording?.pause(); };
+ }, [clipSrc, source]);
+
+ const sync = () => {
+ if (!canSync || !audio.current || !video.current) return;
+ const target = windowStart + video.current.currentTime;
+ if (Math.abs(audio.current.currentTime - target) > 0.05) audio.current.currentTime = target;
+ };
+ const pause = () => audio.current?.pause();
+ const play = () => {
+ if (!canSync) { setError('Recorded source unavailable — playback cannot verify sync'); video.current?.pause(); return; }
+ sync();
+ // Media events are outside React's request lifecycle.
+ audio.current.play().catch(() => { video.current?.pause(); setError('Source playback failed — check the recorded audio'); });
+ };
+ const seek = (seconds) => { if (video.current) video.current.currentTime = Math.max(0, seconds); sync(); };
+ const spans = temporal?.spans || [];
+
+ return (
+ <div className="min-w-0 w-full space-y-2 text-xs" aria-label="Performance evidence">
+ <video ref={video} src={clipSrc} controls muted playsInline preload="metadata"
+ className="w-full max-w-md aspect-video rounded border border-port-border"
+ onVolumeChange={() => { if (video.current) video.current.muted = true; }}
+ onPlay={play} onPause={pause} onEnded={pause} onSeeking={sync} onTimeUpdate={sync}
+ onLoadedMetadata={() => seek(instruction?.edit?.inSec || 0)} />
+ {source && <audio ref={audio} src={source} muted={sourceMuted} preload="metadata" onLoadedMetadata={sync}
+ onError={() => { video.current?.pause(); setError('Recorded source unavailable — check the audio file'); }} />}
+ {canSync && <button type="button" aria-pressed={sourceMuted} onClick={() => setSourceMuted((value) => !value)}
+ className="rounded border border-port-border px-2 py-1 min-h-[44px] sm:min-h-0">{sourceMuted ? 'Unmute source' : 'Mute source'}</button>}
+ <p>Speaker: {instruction?.speaker || 'Unspecified'} · Conditioning: {conditioning?.source || 'Unknown'}</p>
+ <p className="text-port-text-muted">Source and clip play together. Voice isolation is unverified; separation and equal durations do not prove correct lip-sync.</p>
+ {!canSync && <p className="text-port-warning">Recorded source unavailable — review needed</p>}
+ {error && <p role="status" className="text-port-warning">{error}</p>}
+ <div className="flex flex-wrap gap-1" aria-label="Word windows">
+ {cues.flatMap((cue, index) => (cue.words?.length ? cue.words : [cue]).map((word, i) => (
+ <button type="button" key={`${index}-${i}`} onClick={() => seek(word.startSec)}
+ className="rounded border border-port-border px-2 py-1 min-h-[44px] sm:min-h-0"
+ title={`${formatTimecode(word.startSec)}–${formatTimecode(word.endSec)} (clip time)`}>
+ {word.text} · {formatTimecode(word.startSec)}–{formatTimecode(word.endSec)}
+ </button>
+ )))}
+ </div>
+ <p className="text-port-text-muted">Temporal lip-sync: {temporal?.lipSync || 'unverified'}{temporal?.analyzer ? ` · ${temporal.analyzer.id} ${temporal.analyzer.version}` : ' · review needed'}</p>
+ {temporal && <p className="text-port-text-muted">Measured evidence: {temporal.status}</p>}
+ <ul className="space-y-1" aria-label="Temporal evidence spans">
+ {spans.map((span, i) => (
+ <li key={i}>
+ <button type="button" onClick={() => seek(span.startSec + excerptStartSec - (windowStart || 0))}
+ className="text-port-accent min-h-[44px] sm:min-h-0">
+ {formatTimecode(span.startSec + excerptStartSec)}–{formatTimecode(span.endSec + excerptStartSec)}
+ </button>
+ {' · '}{span.status}
+ {Number.isFinite(span.offsetSec) && ` · offset ${span.offsetSec.toFixed(3)}s`}
+ {Number.isFinite(span.confidence) && ` · confidence ${span.confidence.toFixed(2)}`}
+ </li>
+ ))}
+ </ul>
+ </div>
+ );
+}
diff --git a/client/src/components/musicVideo/PerformanceEvidence.test.jsx b/client/src/components/musicVideo/PerformanceEvidence.test.jsx
new file mode 100644
index 0000000000..6b365a01dd
--- /dev/null
+++ b/client/src/components/musicVideo/PerformanceEvidence.test.jsx
@@ -0,0 +1,47 @@
+import { describe, expect, it, vi } from 'vitest';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import PerformanceEvidence from './PerformanceEvidence.jsx';
+
+const instruction = {
+ speaker: 'Example Singer', audio: { conditioning: { source: 'clean-singer-stem', filename: 'singer.wav', voiceIsolation: 'unverified' } },
+ audioWindow: { startSec: 10 }, edit: { inSec: 2 },
+ cues: [{ text: 'hello world', startSec: 2, endSec: 4, words: [{ text: 'hello', startSec: 2, endSec: 3 }, { text: 'world', startSec: 3, endSec: 4 }] }],
+};
+describe('PerformanceEvidence', () => {
+ it('synchronizes recorded source play, seek and pause, and seeks words/evidence on their distinct timebases', async () => {
+ const play = vi.spyOn(HTMLMediaElement.prototype, 'play').mockResolvedValue();
+ const pause = vi.spyOn(HTMLMediaElement.prototype, 'pause').mockImplementation(() => {});
+ const temporal = { status: 'verified', analyzer: { id: 'example-analyzer', version: '1' },
+ spans: [{ startSec: 1, endSec: 2, status: 'verified', offsetSec: 0.02, confidence: 0.9 }] };
+ const { container } = render(<PerformanceEvidence clipSrc="/example.mp4" instruction={instruction} temporal={temporal} excerptStartSec={12} />);
+ const video = container.querySelector('video');
+ const audio = container.querySelector('audio');
+ fireEvent.loadedMetadata(video);
+ expect(video.currentTime).toBe(2);
+ expect(audio.currentTime).toBe(12);
+ fireEvent.play(video);
+ expect(play.mock.instances).toContain(audio);
+ video.currentTime = 2.5;
+ fireEvent.timeUpdate(video);
+ expect(audio.currentTime).toBe(12.5);
+ fireEvent.click(screen.getByRole('button', { name: /world/ }));
+ expect(video.currentTime).toBe(3);
+ expect(audio.currentTime).toBe(13);
+ fireEvent.click(screen.getByRole('button', { name: /0:13/ }));
+ expect(video.currentTime).toBe(3);
+ fireEvent.pause(video);
+ expect(pause.mock.instances).toContain(audio);
+ expect(screen.getByText(/Voice isolation is unverified/)).toBeTruthy();
+ expect(screen.getByText(/example-analyzer 1/)).toBeTruthy();
+ play.mockRejectedValueOnce(new Error('blocked'));
+ fireEvent.play(video);
+ await waitFor(() => expect(screen.getByRole('status').textContent).toContain('Source playback failed'));
+ vi.restoreAllMocks();
+ });
+
+ it('keeps legacy takes without source metadata or analyzer evidence visibly unverified', () => {
+ render(<PerformanceEvidence clipSrc="/example.mp4" instruction={{}} />);
+ expect(screen.getByText(/Temporal lip-sync: unverified/)).toBeTruthy();
+ expect(screen.getByText(/Recorded source unavailable/)).toBeTruthy();
+ });
+});
diff --git a/client/src/components/musicVideo/SceneCard.jsx b/client/src/components/musicVideo/SceneCard.jsx
index 413101e662..b84715a2f2 100644
--- a/client/src/components/musicVideo/SceneCard.jsx
+++ b/client/src/components/musicVideo/SceneCard.jsx
@@ -4,6 +4,7 @@ import { useRef, useState } from 'react';
import { Trash2, Activity, ArrowUp, ArrowDown, ChevronRight, Image as ImageIcon, Video, Maximize2, AlertTriangle, ImagePlus, Clapperboard, Scissors } from 'lucide-react';
import { formatDurationSec, formatUsd } from '../../utils/formatters.js';
import { useVideoFileSrc } from '../../hooks/useVideoFileSrc.js';
+import PerformanceEvidence from './PerformanceEvidence.jsx';
import SceneTakeStrip from './SceneTakeStrip.jsx';
import { MUSIC_VIDEO_VISUAL_LAYERS, sceneHasAuthoredSpan } from '../../lib/musicVideoLayers.js';
@@ -68,7 +69,7 @@ export default function SceneCard({
onMove, onDelete, onEditLocal, onSave,
onGenerateFrame, onGenerateVideo, onContinueVideo,
onOpenPreview, onSelectTake, onReviewTake, onImportTake, onImportClipTake, takeBusy = false, layered = false,
- lipSyncBackend = '', songDurationSec = null, onSplit, falVideoSettings = null, onSeek,
+ lipSyncBackend = '', songDurationSec = null, onSplit, falVideoSettings = null, onSeek, performanceReview = null,
}) {
// Pause the inline clip before opening the lightbox so the user can't hear
// two desynced copies — MediaLightbox autoplays unmuted, and the thumb's
@@ -116,6 +117,7 @@ export default function SceneCard({
const performanceCost = falTake?.performance ? (falCost || capability?.costLabel) : capability?.costLabel;
const splitLimit = layer === 'footage' ? shotSplitLimit(scene, lipSyncBackend) : null;
const canSplit = splitLimit != null && timedSpan != null && timedSpan > splitLimit + 1e-6;
+ const instruction = scene.takes?.find((take) => take.kind === 'video' && take.assetId === scene.videoHistoryId)?.shotInstruction;
const shotModeId = `mv-shot-mode-${scene.sceneId}`;
return (
<details className="group min-w-0 rounded-lg border border-port-border bg-port-card">
@@ -212,6 +214,15 @@ export default function SceneCard({
</>
)}
</div>
+ {performance && (
+ <div className="flex flex-wrap items-center gap-2 text-xs">
+ <label htmlFor={fieldId('speaker')}>Speaker / singer</label>
+ <input id={fieldId('speaker')} value={scene.performanceSpeaker || ''} maxLength={120}
+ onChange={(e) => onEditLocal(scene.sceneId, { performanceSpeaker: e.target.value })}
+ onBlur={() => onSave(scene.sceneId, { performanceSpeaker: scene.performanceSpeaker || null })}
+ className="bg-port-bg border border-port-border rounded px-2 py-1" placeholder="Intended singer" />
+ </div>
+ )}
<div className="flex flex-wrap gap-2 items-center text-xs">
<label htmlFor={fieldId('layer')}>Layer</label>
<select id={fieldId('layer')} value={layer} onChange={(e) => applyPatch({ visualLayer: e.target.value })}
@@ -348,7 +359,11 @@ export default function SceneCard({
onOpenPreview={onOpenPreview} />
{/* Scene clip — i2v video generated from the reference frame (Phase 1) */}
<div className="flex items-center gap-2 flex-wrap">
- {scene.videoHistoryId && (
+ {scene.videoHistoryId && performance && (
+ <PerformanceEvidence key={scene.videoHistoryId} clipSrc={clipSrc} instruction={instruction}
+ temporal={performanceReview?.shot} excerptStartSec={performanceReview?.excerptStartSec || 0} />
+ )}
+ {scene.videoHistoryId && !performance && (
<div className="relative w-40 shrink-0">
<video
ref={clipPlayerRef}
diff --git a/client/src/components/musicVideo/VocalStemControl.jsx b/client/src/components/musicVideo/VocalStemControl.jsx
index 67c9345756..211d0c098a 100644
--- a/client/src/components/musicVideo/VocalStemControl.jsx
+++ b/client/src/components/musicVideo/VocalStemControl.jsx
@@ -1,7 +1,7 @@
import { useState } from 'react';
import { Mic, Wand2, X } from 'lucide-react';
import toast from '../ui/Toast';
-import { uploadMusicVideoVocalStem, removeMusicVideoVocalStem } from '../../services/apiMusicVideo.js';
+import { uploadMusicVideoVocalStem, removeMusicVideoVocalStem, updateMusicVideoProject } from '../../services/apiMusicVideo.js';
const HELP = 'Optional. A full-length vocal bounce from the same session as the song, starting at 0:00. '
+ 'Lip-sync performance shots are conditioned on it instead of the full mix. The final video keeps the song.';
@@ -18,6 +18,8 @@ const SEPARATE_HELP = 'Split the vocal out of the song with demucs and attach it
export default function VocalStemControl({ project, hasAudio, onUpdated, separation = null }) {
const [busy, setBusy] = useState(false);
const inputId = `mv-vocal-stem-${project.id}`;
+ const sourceId = `mv-conditioning-source-${project.id}`;
+ const source = project.performanceConditioningSource || (project.vocalStemFilename ? 'vocal-stem' : 'master');
const stem = project.vocalStemFilename || null;
const separating = Boolean(separation?.active && separation.context === project.id);
const separationLabel = separating
@@ -64,9 +66,18 @@ export default function VocalStemControl({ project, hasAudio, onUpdated, separat
Cancel
</button>
)}
+ <label htmlFor={sourceId}>Conditioning source</label>
+ <select id={sourceId} value={source} disabled={disabled}
+ onChange={(e) => run(() => updateMusicVideoProject(project.id, { performanceConditioningSource: e.target.value }, { silent: true }), 'Conditioning source saved', 'Failed to save conditioning source')}
+ className="max-w-full bg-port-bg border border-port-border rounded px-2 py-1 min-h-[44px] sm:min-h-0">
+ <option value="master">Master mix</option>
+ <option value="vocal-stem" disabled={!stem}>Attached vocal stem</option>
+ <option value="clean-singer-stem" disabled={!stem}>Attached clean singer stem (user selected)</option>
+ </select>
+ <span className="text-port-text-muted">Choose a clean singer bounce explicitly. Separation, source selection and duration parity do not verify voice isolation.</span>
{stem ? (
<>
- <span className="text-port-text-muted break-all">Lip-sync uses {stem}</span>
+ <span className="text-port-text-muted break-all">{source === 'master' ? 'Lip-sync uses the full mix' : `Lip-sync uses ${stem}`}</span>
<button type="button" onClick={remove} disabled={busy || separating} aria-label="Remove vocal stem"
className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1 min-h-[44px] sm:min-h-0 disabled:opacity-50">
<X size={13} /> Remove
diff --git a/client/src/components/musicVideo/VocalStemControl.test.jsx b/client/src/components/musicVideo/VocalStemControl.test.jsx
index 90e0cfbbdf..f3b16e1c4d 100644
--- a/client/src/components/musicVideo/VocalStemControl.test.jsx
+++ b/client/src/components/musicVideo/VocalStemControl.test.jsx
@@ -7,6 +7,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
vi.mock('../../services/apiMusicVideo.js', () => ({
+ updateMusicVideoProject: vi.fn(),
uploadMusicVideoVocalStem: vi.fn(),
removeMusicVideoVocalStem: vi.fn(),
}));
@@ -73,3 +74,16 @@ describe('VocalStemControl separation', () => {
expect(running.cancel).toHaveBeenCalledOnce();
});
});
+
+it('persists the explicitly selected clean singer source without claiming isolation', async () => {
+ const saved = { ...project, vocalStemFilename: 'singer.wav', performanceConditioningSource: 'clean-singer-stem' };
+ api.updateMusicVideoProject.mockResolvedValue(saved);
+ const onUpdated = vi.fn();
+ const { rerender } = render(<VocalStemControl project={{ ...project, vocalStemFilename: 'singer.wav' }} hasAudio onUpdated={onUpdated} />);
+ fireEvent.change(screen.getByLabelText('Conditioning source'), { target: { value: 'clean-singer-stem' } });
+ await waitFor(() => expect(onUpdated).toHaveBeenCalledWith(saved));
+ expect(api.updateMusicVideoProject).toHaveBeenCalledWith(project.id, { performanceConditioningSource: 'clean-singer-stem' }, { silent: true });
+ rerender(<VocalStemControl project={saved} hasAudio onUpdated={onUpdated} />);
+ expect(screen.getByLabelText('Conditioning source').value).toBe('clean-singer-stem');
+ expect(screen.getByText(/do not verify voice isolation/)).toBeTruthy();
+});
diff --git a/client/src/components/musicVideo/stages/BoardStage.jsx b/client/src/components/musicVideo/stages/BoardStage.jsx
index 361de76144..0d7d37badd 100644
--- a/client/src/components/musicVideo/stages/BoardStage.jsx
+++ b/client/src/components/musicVideo/stages/BoardStage.jsx
@@ -13,6 +13,18 @@ import { isLayeredComposition } from '../../../lib/musicVideoLayers.js';
export default function BoardStage({ board }) {
const { project, locked, busy, sceneMedia, videoSettings, takes } = board;
const scenes = project.scenes || [];
+ const performanceReviews = new Map();
+ const attempts = (project.autoReviews || []).flatMap((run) => run.attempts || []).slice().reverse();
+ for (const attempt of attempts) {
+ const temporal = attempt.review?.evidence?.temporal;
+ for (const shot of temporal?.shots || []) {
+ const key = `${shot.sceneId}:${shot.takeId}`;
+ if (!performanceReviews.has(key)) performanceReviews.set(key, {
+ shot: { ...shot, status: temporal.status, lipSync: attempt.review.checks?.lipSync, analyzer: temporal.analyzer },
+ excerptStartSec: attempt.review.evidence.excerptStartSec,
+ });
+ }
+ }
return (
<fieldset disabled={locked} className="min-w-0 space-y-3">
<div className="rounded-lg border border-port-border bg-port-card p-3">
@@ -37,6 +49,7 @@ export default function BoardStage({ board }) {
<SceneCard
key={scene.sceneId}
scene={scene}
+ performanceReview={performanceReviews.get(`${scene.sceneId}:${scene.videoHistoryId}`)}
index={idx}
isLast={idx === scenes.length - 1}
generatingFrame={sceneMedia.genScenes[scene.sceneId]}
diff --git a/docs/README.md b/docs/README.md
index 6df650b1c6..ca4c17a5a1 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -29,6 +29,7 @@ Index of everything under `docs/`. Start with the [root README](../README.md) fo
| [MODEL_ACCESS.md](./MODEL_ACCESS.md) | Scoping a provider to the models your plan entitles you to — free tiers, allow/deny globs, gateway inheritance |
| [MODEL-COMPARISON.md](./MODEL-COMPARISON.md) | Sourced provider/model/effort comparisons, cost estimates and CoS research refresh |
| [THREEJS_MODELS.md](./THREEJS_MODELS.md) | Three.js procedural 3D model generation and trust boundary |
+| [features/music-video-temporal-evidence.md](./features/music-video-temporal-evidence.md) | Performance source provenance, synchronized playback and optional local temporal analyzer protocol |
| [features/music-renderer-benchmarks.md](./features/music-renderer-benchmarks.md) | Technical and full-length listening evidence for local music renderer profiles |
| [CONTRIBUTING.md](./CONTRIBUTING.md) | Dev setup (PostgreSQL required), code conventions |
| [CLI_REVIEW_OUTCOMES.md](./CLI_REVIEW_OUTCOMES.md) | Reviewer tiers, provider pins and bounded, authenticated CLI health reports |
diff --git a/docs/features/music-video-temporal-evidence.md b/docs/features/music-video-temporal-evidence.md
new file mode 100644
index 0000000000..f8f89938fb
--- /dev/null
+++ b/docs/features/music-video-temporal-evidence.md
@@ -0,0 +1,73 @@
+# Music Video performance evidence
+
+Stream-duration parity and temporal lip-sync are separate review checks. Equal
+audio/video lengths do not show that the singer's mouth follows the song.
+Still-frame review and correctly sliced source audio cannot establish that either.
+
+In Setup, attach a full-length bounce starting at song time zero and choose the
+conditioning source: master mix, attached vocal stem, or an explicitly selected
+clean singer stem. The last choice records the director's intent; demucs separation
+does not certify a single isolated singer. Replacing/removing a stem resets that
+choice. Each performance scene can name its intended speaker/singer. A generated
+take records this speaker, the actual source filename/hash, selection provenance,
+and unverified voice isolation in its immutable shot instruction.
+
+The Board performance preview plays the recorded conditioning audio alongside
+the muted clip on the recorded song/clip timebase. Word buttons seek clip-relative
+windows; evidence buttons seek song-time windows. Old takes without source
+metadata remain review-needed. Evidence is shown only for the reviewed take.
+
+## Optional local analyzer protocol
+
+PortOS ships the adapter contract, not a temporal model. Install a trusted native
+executable named `portos-temporal-analyzer` on the server's PATH to supply one.
+Windows batch wrappers are unsupported. PortOS never installs or downloads an
+analyzer and never invokes a paid analyzer provider. No analyzer runs at boot.
+
+The executable must answer `--capabilities` with one JSON object:
+
+```json
+{"protocolVersion":1,"id":"example-analyzer","version":"1.0","ready":true,"temporalLipSync":true,"localOnly":true}
+```
+
+Only an installed analyzer with that supported protocol and ready local models is
+used. Capability discovery has a five-second timeout. Each explicitly requested
+draft review has a sixty-second total analysis budget and at most 256 evidence
+spans. Output is bounded to 256 KiB per invocation.
+
+For each rendered performance section the adapter invokes, without a shell:
+
+```text
+portos-temporal-analyzer --analyze --video <excerpt-file> --audio <excerpt-file> --audio-start-sec 0 --start-sec <excerpt-start> --end-sec <excerpt-end> --speaker <recorded-speaker>
+```
+
+Both inputs name the actual encoded output. Compare visible mouth motion with
+its embedded song audio, not stream duration, source preparation, or a current
+master that may have changed since rendering. Times are seconds relative to the
+excerpt, not absolute song time. Positive offset means picture lags audio.
+The executable must remain local and must not install weights during analysis.
+
+Return ordered, contiguous spans covering the entire requested section:
+
+```json
+{"spans":[{"startSec":0,"endSec":5,"status":"verified","offsetSec":0.02,"confidence":0.95}]}
+```
+
+Every span requires finite times, `verified` or `unverified` status, offset in
+[-5, 5] seconds (or null), and confidence in [0, 1] (or null). Start/end must
+stay inside the section, with at most one millisecond of boundary rounding.
+Confidence below 0.8 or missing offset leaves a span unverified.
+Complete verified coverage passes temporal lip-sync only when all absolute
+offsets are at most 0.12 seconds. A larger measured offset produces a timecoded
+finding independent of duration parity.
+
+Unavailable, unsupported, failed, malformed, gapped or inconclusive evidence
+remains unverified with no invented score. The run stops as needs-human before
+opening a revision, including when the vision reviewer flags another problem.
+It cannot spend money trying to fix unknown temporal quality. A measured failure
+can enter the existing explicitly budgeted revision workflow.
+
+Analyzer identity/version, shot/source provenance, measured offsets/confidence
+and spans persist in existing auto-review records. Excerpts snapshot performance
+provenance when rendering begins, so later board edits cannot relabel evidence.
+The project sync schema is version-gated; older takes need no data migration.
diff --git a/server/lib/musicVideoShotTiming.js b/server/lib/musicVideoShotTiming.js
index b3b36110b2..0302d4e5c3 100644
--- a/server/lib/musicVideoShotTiming.js
+++ b/server/lib/musicVideoShotTiming.js
@@ -211,6 +211,9 @@ export function clipRelativeCues(cues, windowStartSec, windowEndSec) {
text: typeof cue.text === 'string' ? cue.text : '',
startSec: round6(Math.max(0, cue.startSec - windowStartSec)),
endSec: round6(Math.min(windowEndSec, end) - windowStartSec),
+ ...(Array.isArray(cue.words) ? { words: cue.words
+ .filter((word) => Number.isFinite(word.startSec) && Number.isFinite(word.endSec) && word.endSec > windowStartSec && word.startSec < windowEndSec)
+ .map((word) => ({ text: word.text, startSec: round6(Math.max(windowStartSec, word.startSec) - windowStartSec), endSec: round6(Math.min(windowEndSec, word.endSec) - windowStartSec) })) } : {}),
});
}
return out;
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index dfa4eb445c..b7be73a23f 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -792,6 +792,7 @@ export const musicVideoProjectCreateSchema = z.object({
// be created empty and have the track set later via PATCH.
trackId: z.string().max(64).nullable().optional(),
uploadedAudioFilename: z.string().max(256).nullable().optional(),
+ performanceConditioningSource: z.enum(['master', 'vocal-stem', 'clean-singer-stem']).nullable().optional(),
concept: musicVideoConceptSchema.nullable().optional(),
visualSpec: musicVideoVisualSpecSchema.optional(),
styleReferences: musicVideoStyleReferencesSchema.optional(),
@@ -812,6 +813,7 @@ export const musicVideoProjectUpdateSchema = z.object({
status: z.enum(MUSIC_VIDEO_STATUSES).optional(),
trackId: z.string().max(64).nullable().optional(),
uploadedAudioFilename: z.string().max(256).nullable().optional(),
+ performanceConditioningSource: z.enum(['master', 'vocal-stem', 'clean-singer-stem']).nullable().optional(),
concept: musicVideoConceptSchema.nullable().optional(),
visualSpec: musicVideoVisualSpecSchema.optional(),
styleReferences: musicVideoStyleReferencesSchema.optional(),
@@ -857,6 +859,7 @@ export const musicVideoSceneCreateSchema = z.object({
// recording (only a verified source-audio provider can render it); absent or
// `cutaway` = the ordinary image-to-video shot. See lib/musicVideoShotTiming.js.
shotMode: z.enum(MUSIC_VIDEO_SHOT_MODES).optional(),
+ performanceSpeaker: z.string().trim().max(120).nullable().optional(),
}).strict().refine(
(s) => s.startSec == null || s.endSec == null || s.endSec >= s.startSec,
{ message: 'endSec must be >= startSec', path: ['endSec'] },
@@ -886,6 +889,7 @@ export const musicVideoSceneUpdateSchema = z.object({
// recording (only a verified source-audio provider can render it); absent or
// `cutaway` = the ordinary image-to-video shot. See lib/musicVideoShotTiming.js.
shotMode: z.enum(MUSIC_VIDEO_SHOT_MODES).optional(),
+ performanceSpeaker: z.string().trim().max(120).nullable().optional(),
referenceImageId: z.string().max(256).nullable().optional(),
videoHistoryId: z.string().max(64).nullable().optional(),
}).strict();
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index e716e528d0..56243b7be2 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -655,7 +655,10 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// footage. Absent policy remains legacy; no existing record needs rewriting.
// v13 = authored/applied shot action contracts; older treatment writers drop intent.
// Additive optional metadata on existing project records; no backfill is needed.
- musicVideoProjects: 13,
+ // v14 = selected conditioning source/speaker and separate temporal lip-sync
+ // evidence (#9347). Older peers can drop source intent and pass equal-length
+ // misaligned output, so reject ahead transfers. Absent fields stay legacy.
+ musicVideoProjects: 14,
// 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/routes/musicVideoAutoReview.test.js b/server/routes/musicVideoAutoReview.test.js
index 61552c36ab..7a22363fd9 100644
--- a/server/routes/musicVideoAutoReview.test.js
+++ b/server/routes/musicVideoAutoReview.test.js
@@ -38,7 +38,7 @@ const h = vi.hoisted(() => {
return p;
};
return {
- procs, spawn, jobs: [], verdicts: [], review: null, analysisAvailable: true, freezeStderr: '',
+ procs, spawn, jobs: [], verdicts: [], review: null, temporalInstalled: false, temporalCapability: null, temporalResult: null, temporalCalls: [], analysisAvailable: true, freezeStderr: '',
};
});
@@ -46,12 +46,22 @@ vi.mock('../lib/childProcess.js', async (importOriginal) => {
const real = await importOriginal();
// The continuous-excerpt analysis: ffprobe stream lengths + ffmpeg freezedetect.
const execFile = Object.assign(() => { throw new Error('execFile is only used promisified here'); }, {
- [promisify.custom]: async (bin) => (bin === 'ffprobe'
+ [promisify.custom]: async (bin, args, options) => {
+ if (bin === 'temporal-analyzer-test') {
+ h.temporalCalls.push({ args, options });
+ return { stdout: JSON.stringify(args[0] === '--capabilities' ? h.temporalCapability : h.temporalResult), stderr: '' };
+ }
+ return (bin === 'ffprobe'
? { stdout: 'video,20.000000\naudio,20.010000\n', stderr: '' }
- : { stdout: '', stderr: h.freezeStderr }),
+ : { stdout: '', stderr: h.freezeStderr });
+ },
});
return { ...real, spawn: h.spawn, execFile };
});
+vi.mock('../lib/processEnv.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ findCommandOnPath: (name) => name === 'portos-temporal-analyzer' && h.temporalInstalled ? 'temporal-analyzer-test' : null,
+}));
vi.mock('../lib/ffmpeg.js', async (importOriginal) => {
const real = await importOriginal();
const { writeFileSync: write, mkdirSync: mkdir } = await import('fs');
@@ -162,6 +172,10 @@ beforeEach(() => {
h.verdicts.length = 0;
h.analysisAvailable = true;
h.freezeStderr = '';
+ h.temporalInstalled = false;
+ h.temporalCapability = { protocolVersion: 1, id: 'example-analyzer', version: '1.0', ready: true, temporalLipSync: true, localOnly: true };
+ h.temporalResult = null;
+ h.temporalCalls.length = 0;
vi.clearAllMocks();
});
afterAll(cleanupTempDataRoots);
@@ -381,3 +395,82 @@ it('cloning an active draft cannot give recovery ownership of the source render'
await finishDraft(p.id, 2);
}
});
+
+// Public workflow regressions: stream parity never certifies mouth timing,
+// and uncertain temporal evidence cannot hand out another paid generation.
+describe('temporal performance evidence (#9347)', () => {
+ const performanceProject = async () => {
+ const p = await project();
+ await projects.updateScene(p.id, 's1', { shotMode: 'performance', performanceSpeaker: 'Example Singer' });
+ await projects.updateProject(p.id, { performanceConditioningSource: 'clean-singer-stem' });
+ await projects.mutateProjectRecord(p.id, (current) => ({ project: {
+ ...current, scenes: current.scenes.map((s) => s.sceneId !== 's1' ? s : { ...s, takes: [{
+ kind: 'video', assetId: 'clip-1', shotInstruction: {
+ version: 2, shotMode: 'performance', speaker: 'Example Singer', edit: { inSec: 1, outSec: 6 },
+ audio: { conditioning: { source: 'clean-singer-stem', filename: 'singer.wav', sha256: 'a'.repeat(64), selection: 'user', voiceIsolation: 'unverified' } },
+ },
+ }] }),
+ } }));
+ return projects.getProject(p.id);
+ };
+
+ it.each([
+ ['missing analyzer', false, null],
+ ['missing evidence', true, null],
+ ['unknown span status', true, { spans: [{ startSec: 0, endSec: 5, status: 'pass', offsetSec: 0, confidence: 1 }] }],
+ ['out-of-bounds evidence', true, { spans: [{ startSec: 0, endSec: 20, status: 'verified', offsetSec: 0, confidence: 1 }] }],
+ ['gapped evidence', true, { spans: [{ startSec: 1, endSec: 5, status: 'verified', offsetSec: 0, confidence: 1 }] }],
+ ['low confidence', true, { spans: [{ startSec: 0, endSec: 5, status: 'verified', offsetSec: 0, confidence: 0.2 }] }],
+ ])('%s stops for a human even when a visual finding could trigger retries', async (_name, installed, result) => {
+ const p = await performanceProject();
+ h.temporalInstalled = installed;
+ h.temporalResult = result;
+ h.verdicts.push(FAIL_S2);
+ await start(p.id, { maxAttempts: 3, maxGenerations: 5 });
+ await finishDraft(p.id, 1);
+ const saved = await settled(p.id, (x) => expect(run(x).status).toBe('needs-human'));
+ expect(run(saved).usage).toEqual({ reviews: 1, generations: 0 });
+ expect(run(saved).attempts[0]).toMatchObject({ revisionId: null, review: {
+ verdict: 'inconclusive', checks: { audioSync: 'pass', lipSync: 'unverified' },
+ evidence: { temporal: { status: 'unverified' } },
+ } });
+ expect(saved.revisions || []).toHaveLength(0);
+ expect(h.procs).toHaveLength(1);
+ });
+
+ it('equal-length synthetic output with measured mouth offset fails only the temporal check', async () => {
+ const p = await performanceProject();
+ h.temporalInstalled = true;
+ h.temporalResult = { spans: [{ startSec: 0, endSec: 5, status: 'verified', offsetSec: 0.6, confidence: 0.95 }] };
+ h.verdicts.push(PASS);
+ await start(p.id, { maxAttempts: 1, maxGenerations: 0 });
+ await finishDraft(p.id, 1);
+ const saved = await settled(p.id, (x) => expect(run(x).attempts[0].review).toBeTruthy());
+ expect(run(saved).attempts[0].review).toMatchObject({
+ verdict: 'revise', checks: { audioSync: 'pass', lipSync: 'fail' },
+ evidence: { temporal: { analyzer: { id: 'example-analyzer', version: '1.0' },
+ shots: [{ sceneId: 's1', takeId: 'clip-1', speaker: 'Example Singer', conditioning: { source: 'clean-singer-stem', voiceIsolation: 'unverified' }, spans: [{ offsetSec: 0.6, confidence: 0.95 }] }] } },
+ });
+ expect(h.temporalCalls[1].args).toEqual(expect.arrayContaining(['--audio-start-sec', '0', '--start-sec', '0', '--end-sec', '5']));
+ expect(h.temporalCalls[1].options.env).not.toHaveProperty('PORTOS_API_TOKEN');
+ });
+
+ it('complete confident temporal evidence survives reload and passes independently of parity', async () => {
+ const p = await performanceProject();
+ h.temporalInstalled = true;
+ h.temporalResult = { spans: [{ startSec: 0, endSec: 5, status: 'verified', offsetSec: 0.02, confidence: 0.95 }] };
+ h.verdicts.push(PASS);
+ await start(p.id, { maxAttempts: 1, maxGenerations: 0 });
+ await vi.waitFor(() => expect(h.procs).toHaveLength(1));
+ // Editing the board while its older take is encoding cannot relabel the output.
+ await projects.updateScene(p.id, 's1', { shotMode: 'cutaway', performanceSpeaker: 'Another Singer', videoHistoryId: 'another-take' });
+ await finishDraft(p.id, 1);
+ const saved = await settled(p.id, (x) => expect(run(x).status).toBe('passed'));
+ expect(run(saved).attempts[0].review.evidence.temporal.shots[0]).toMatchObject({ speaker: 'Example Singer', conditioning: { selection: 'user', voiceIsolation: 'unverified' } });
+ const reloaded = (await request(app).get(base(p.id))).body;
+ expect(reloaded.performanceConditioningSource).toBe('clean-singer-stem');
+ expect(reloaded.scenes[0].performanceSpeaker).toBe('Another Singer');
+ expect(run(reloaded).attempts[0].review).toEqual(run(saved).attempts[0].review);
+ expect(run(reloaded).attempts[0].review.checks).toMatchObject({ lipSync: 'pass', audioSync: 'pass' });
+ });
+});
diff --git a/server/services/musicVideo/autoReview.js b/server/services/musicVideo/autoReview.js
index f76c7a2337..1b02b9020b 100644
--- a/server/services/musicVideo/autoReview.js
+++ b/server/services/musicVideo/autoReview.js
@@ -49,7 +49,7 @@ const AUTO_REVIEW_LIMIT_BOUNDS = Object.freeze({
const AUTO_REVIEW_STATUSES = Object.freeze(['running', 'stopped', 'limit-reached', 'passed', 'needs-human', 'failed', 'canceled']);
const RESUMABLE = new Set(['running', 'stopped', 'limit-reached']);
const ACTIVE = new Set(['running', 'stopped', 'limit-reached']);
-export const AUTO_REVIEW_CHECKS = Object.freeze(['composition', 'continuity', 'motion', 'audioSync']);
+export const AUTO_REVIEW_CHECKS = Object.freeze(['composition', 'continuity', 'motion', 'audioSync', 'lipSync']);
// Draft renders are free, but a window that fails to render every time must
// not loop forever: this many failed renders of one attempt fail the run.
const MAX_RENDER_FAILURES = 2;
diff --git a/server/services/musicVideo/autoReviewJudge.js b/server/services/musicVideo/autoReviewJudge.js
index 40c56e5ada..2cb6269f66 100644
--- a/server/services/musicVideo/autoReviewJudge.js
+++ b/server/services/musicVideo/autoReviewJudge.js
@@ -11,13 +11,9 @@
* audio/video stream-length parity that shows the song ran under the whole
* cut without being clipped or padded.
*
- * What `audioSync` can and cannot prove: the render maps the master song on
- * the same timebase as the cut and never re-cuts it (render.js), and a
- * lip-synced performance take of a stale song interval is refused before the
- * render (performanceShot.js), so the one way picture and song drift apart is
- * a stream that ends early or runs long — which the parity check measures. It
- * does not listen to the content; a problem only a listener would hear is a
- * director's call, and the UI labels the check as stream parity.
+ * `audioSync` measures stream-length parity only. It proves neither mouth
+ * timing nor isolated voice correctness. `lipSync` requires separate local
+ * temporal evidence against the encoded output, or stays unverified.
*
* A vision model cannot hear, and a set of stills cannot show motion, so the
* gate never lets frames alone pass `motion` or `audioSync`: without a
@@ -189,7 +185,7 @@ export function parseAutoReviewResponse(text) {
export function gateAutoReview({ parsed, analysis, evidence = {} }) {
const continuous = analysis?.ok === true;
const spanSec = analysis?.spanSec ?? null;
- const checks = { composition: 'unverified', continuity: 'unverified', motion: 'unverified', audioSync: 'unverified' };
+ const checks = { composition: 'unverified', continuity: 'unverified', motion: 'unverified', audioSync: 'unverified', lipSync: 'unverified' };
const findings = [...(parsed?.findings || [])];
if (parsed) {
checks.composition = parsed.checks.composition;
@@ -212,6 +208,20 @@ export function gateAutoReview({ parsed, analysis, evidence = {} }) {
}
}
}
+ const temporal = evidence.temporal;
+ // Only the local analyzer's complete, high-confidence spans can pass.
+ if (temporal?.status === 'not-applicable' && temporal.shots?.length === 0) checks.lipSync = 'pass';
+ if (temporal?.status === 'verified' && temporal.analyzer && temporal.shots?.length
+ && temporal.shots.every((shot) => shot.spans?.length && shot.spans.every((span) => span.status === 'verified'
+ && Number.isFinite(span.offsetSec) && Number.isFinite(span.confidence) && span.confidence >= 0.8))) {
+ checks.lipSync = 'pass';
+ for (const shot of temporal.shots) for (const span of shot.spans) {
+ if (Math.abs(span.offsetSec) <= 0.12) continue;
+ checks.lipSync = 'fail';
+ findings.push({ atSec: span.startSec, check: 'lipSync', severity: 'blocking', source: 'analysis',
+ note: `Measured mouth/audio offset is ${span.offsetSec.toFixed(3)}s (confidence ${span.confidence.toFixed(2)})` });
+ }
+ }
const failed = AUTO_REVIEW_CHECKS.filter((c) => checks[c] === 'fail');
const unverified = AUTO_REVIEW_CHECKS.filter((c) => checks[c] === 'unverified');
const blocking = findings.filter((f) => f.severity === 'blocking');
@@ -221,6 +231,7 @@ export function gateAutoReview({ parsed, analysis, evidence = {} }) {
summary: parsed?.summary || '',
evidence: { ...evidence, continuous, continuousError: continuous ? null : (analysis?.error || 'The continuous excerpt was not analysed'), avDriftSec: continuous ? analysis.avDriftSec ?? null : null },
};
+ if (checks.lipSync === 'unverified') return { ...base, verdict: 'inconclusive', reason: temporal?.reason || 'Lip-sync needs temporal evidence — watch the performance yourself' };
if (!parsed) return { ...base, verdict: 'inconclusive', reason: 'The reviewer returned no usable verdict — watch this draft yourself' };
// A blocking finding is something to regenerate, whatever else was verified —
// revising never claims a pass, so it needs no continuous evidence.
diff --git a/server/services/musicVideo/autoReviewService.js b/server/services/musicVideo/autoReviewService.js
index a395754c40..c0c84363f9 100644
--- a/server/services/musicVideo/autoReviewService.js
+++ b/server/services/musicVideo/autoReviewService.js
@@ -22,6 +22,8 @@
* so an event arriving mid-step can never start a second review.
*/
+import { isPerformanceScene, selectedPerformanceInstruction } from '../../lib/musicVideoShotTiming.js';
+import { analyzeTemporalPerformance } from './temporalPerformance.js';
import { unlink } from 'fs/promises';
import { existsSync } from 'fs';
import { join } from 'path';
@@ -184,7 +186,15 @@ async function reviewDraft(project, run, excerpt) {
const planned = planStripTimes(spanSec, sections, { hasContactSheet: hasSheet });
const { sheets: strip, captured: frameTimes } = await extractStripSheets(excerptPath, `mvar-${short(run.id)}-a${attemptN}`, planned).catch(() => ({ sheets: [], captured: [] }));
const screenshots = [...(hasSheet ? [sheet] : []), ...strip];
- const evidence = { boundaryFrames: hasSheet ? 1 : 0, continuousFrames: frameTimes.length };
+ const shots = sections.flatMap((section) => {
+ const scene = project.scenes?.find((s) => s.sceneId === section.sceneId);
+ const instruction = selectedPerformanceInstruction(scene);
+ const performance = 'performance' in section ? section.performance : (isPerformanceScene(scene)
+ ? { takeId: scene.videoHistoryId, speaker: instruction?.speaker || null, conditioning: instruction?.audio?.conditioning || null } : null);
+ return performance ? [{ sceneId: section.sceneId, ...performance, startSec: section.startSec, endSec: section.endSec }] : [];
+ });
+ const temporal = await analyzeTemporalPerformance({ excerptPath, shots });
+ const evidence = { boundaryFrames: hasSheet ? 1 : 0, continuousFrames: frameTimes.length, temporal, excerptStartSec: excerpt.startSec };
let parsed = null;
let reviewerError = null;
diff --git a/server/services/musicVideo/excerpt.js b/server/services/musicVideo/excerpt.js
index 23b0e4b0cb..1333d01a7a 100644
--- a/server/services/musicVideo/excerpt.js
+++ b/server/services/musicVideo/excerpt.js
@@ -22,6 +22,7 @@
* `mutateProjectRecord`'s write serialization without duplicating validation.
*/
+import { isPerformanceScene, selectedPerformanceInstruction } from '../../lib/musicVideoShotTiming.js';
import { randomUUID } from 'crypto';
import { ServerError } from '../../lib/errorHandler.js';
import { isNonBlankStr, trimTo } from '../../lib/textUtils.js';
@@ -53,7 +54,7 @@ function findExcerpt(project, excerptId) {
* project; the render job fills in `filename`/`contactSheetFilename` (or
* `error`) once the encode finishes.
*/
-export function startExcerptOnProject(project, { startSec, endSec, sections = null, partialFilename = null, renderingOn = null, aspect = null, fade = false }, now = new Date().toISOString()) {
+export function startExcerptOnProject(project, { startSec, endSec, sections = null, performanceProject = project, partialFilename = null, renderingOn = null, aspect = null, fade = false }, now = new Date().toISOString()) {
if (!(startSec >= 0) || !(endSec > startSec) || endSec > MAX_EXCERPT_SEC) {
throw excerptError(422, 'INVALID_EXCERPT_RANGE', 'endSec must be greater than startSec, and both within range');
}
@@ -75,7 +76,12 @@ export function startExcerptOnProject(project, { startSec, endSec, sections = nu
renderingOn,
// #8987: the sections the draft cuts, in ABSOLUTE song time — what a
// flagged note maps onto when the director asks for a selective revision.
- sections: Array.isArray(sections) ? sections : null,
+ sections: Array.isArray(sections) ? sections.map((section) => {
+ const scene = performanceProject.scenes?.find((s) => s.sceneId === section.sceneId);
+ const instruction = selectedPerformanceInstruction(scene);
+ return { ...section, performance: isPerformanceScene(scene) && (!section.layer || section.layer === 'footage')
+ ? { takeId: scene.videoHistoryId || null, speaker: instruction?.speaker || null, conditioning: instruction?.audio?.conditioning || null } : null };
+ }) : null,
// #9280: a social cut's frame (the project's own unless re-framed) and
// whether its audio edges fade; `width`/`height` land with the finished file.
aspect: aspect || null,
diff --git a/server/services/musicVideo/excerptRender.js b/server/services/musicVideo/excerptRender.js
index bca29b1ef8..383ce14397 100644
--- a/server/services/musicVideo/excerptRender.js
+++ b/server/services/musicVideo/excerptRender.js
@@ -143,7 +143,7 @@ async function launchSeekedExcerpt({ projectId, project: stored, startSec, endSe
}));
const renderingOn = await ensureInstanceId();
const { excerpt } = await mutateProjectRecord(projectId, (current) => {
- const started = startExcerptOnProject(current, { startSec, endSec: endClamped, sections, partialFilename: filename, renderingOn, aspect: musicVideoAspect(project), fade });
+ const started = startExcerptOnProject(current, { startSec, endSec: endClamped, sections, performanceProject: project, partialFilename: filename, renderingOn, aspect: musicVideoAspect(project), fade });
return revisionId ? { ...started, project: markRevisionRendering(started.project, revisionId, started.excerpt.id) } : started;
});
const excerptId = excerpt.id;
@@ -265,7 +265,7 @@ export async function startExcerptRender(projectId, { startSec, endSec, aspect =
// demote it (#9010).
const renderingOn = await ensureInstanceId();
const { excerpt } = await mutateProjectRecord(projectId, (current) => {
- const started = startExcerptOnProject(current, { startSec, endSec: endClamped, sections, partialFilename: filename, renderingOn });
+ const started = startExcerptOnProject(current, { startSec, endSec: endClamped, sections, performanceProject: project, partialFilename: filename, renderingOn });
return revisionId ? { ...started, project: markRevisionRendering(started.project, revisionId, started.excerpt.id) } : started;
});
const excerptId = excerpt.id;
diff --git a/server/services/musicVideo/performanceShot.js b/server/services/musicVideo/performanceShot.js
index 4f98c19919..3cef6f9012 100644
--- a/server/services/musicVideo/performanceShot.js
+++ b/server/services/musicVideo/performanceShot.js
@@ -52,7 +52,7 @@ import {
import { getProject } from './projects.js';
import { assertVocalStemTimebase, resolveVocalStemPath } from './vocalStem.js';
-export const SHOT_INSTRUCTION_VERSION = 1;
+export const SHOT_INSTRUCTION_VERSION = 2;
const hashFile = (path) => new Promise((resolve, reject) => {
const hash = createHash('sha256');
@@ -266,7 +266,9 @@ export async function preparePerformanceShot({ musicVideo, backend, sourceImageP
// An optional vocal stem conditions the provider in place of the mix. It
// is re-checked here because the file could have been replaced on disk or
// arrived from a peer since it was attached.
- const stemPath = resolveVocalStemPath(project);
+ const conditioningSource = project.performanceConditioningSource || (project.vocalStemFilename ? 'vocal-stem' : 'master');
+ const stemPath = conditioningSource === 'master' ? null : resolveVocalStemPath(project);
+ if (conditioningSource !== 'master' && !stemPath) throw refuse('Attach the selected singer stem before rendering', 'MUSIC_VIDEO_VOCAL_STEM_MISSING');
if (stemPath) assertVocalStemTimebase(await probeVideoDuration(stemPath), songDurationSec);
const audioSha256 = await hashFile(masterPath);
@@ -303,6 +305,7 @@ export async function preparePerformanceShot({ musicVideo, backend, sourceImageP
version: SHOT_INSTRUCTION_VERSION,
shotMode: 'performance',
createdAt: new Date().toISOString(),
+ speaker: scene.performanceSpeaker || null,
audio: {
source: project.trackId ? 'track' : 'upload',
sha256: audioSha256,
@@ -312,7 +315,11 @@ export async function preparePerformanceShot({ musicVideo, backend, sourceImageP
// 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 —
// and then only when `windowFingerprint` says this window changed.
- conditioning: { source: stemPath ? 'vocal-stem' : 'master', sha256: conditioningSha256 },
+ conditioning: {
+ source: conditioningSource, sha256: conditioningSha256, filename: basename(stemPath || masterPath),
+ selection: project.performanceConditioningSource ? 'user' : 'legacy-default',
+ voiceIsolation: 'unverified',
+ },
},
songInterval: { startSec: scene.startSec, endSec: scene.endSec },
audioWindow: { startSec: plan.windowStartSec, endSec: plan.windowEndSec, durationSec: plan.windowSec },
diff --git a/server/services/musicVideo/performanceShot.test.js b/server/services/musicVideo/performanceShot.test.js
index 35d2d8dabe..47d1c0c56d 100644
--- a/server/services/musicVideo/performanceShot.test.js
+++ b/server/services/musicVideo/performanceShot.test.js
@@ -76,7 +76,7 @@ const project = (sceneOver) => ({
id: 'mv-1',
uploadedAudioFilename: 'song.wav',
lyricCues: [
- { id: 'c1', text: 'hold on', startSec: 19, endSec: 20.5 },
+ { id: 'c1', text: 'hold on', startSec: 19, endSec: 20.5, words: [{ text: 'hold', startSec: 19, endSec: 20 }, { text: 'on', startSec: 20, endSec: 20.5 }] },
{ id: 'c2', text: 'later line', startSec: 40, endSec: 42 },
{ id: 'c3', text: 'untimed', startSec: null, endSec: null },
],
@@ -116,9 +116,9 @@ describe.skipIf(!ffmpeg)('music-video performance shot through the fal lip-sync
expect(si.audioWindow).toEqual({ startSec: 18.225, endSec: 23.275, durationSec: 5.05 });
expect(si.edit).toEqual({ inSec: 1.775, outSec: 3.275, targetSec: 1.5 });
expect(si.songInterval).toEqual({ startSec: 20, endSec: 21.5 });
- expect(si.cues).toEqual([{ text: 'hold on', startSec: 0.775, endSec: 2.275 }]);
+ expect(si.cues).toEqual([{ text: 'hold on', startSec: 0.775, endSec: 2.275, words: [{ text: 'hold', startSec: 0.775, endSec: 1.775 }, { text: 'on', startSec: 1.775, endSec: 2.275 }] }]);
expect(si.audio.sha256).toMatch(/^[0-9a-f]{64}$/);
- expect(si.audio.conditioning).toEqual({ source: 'master', sha256: si.audio.sha256 });
+ expect(si.audio.conditioning).toEqual({ source: 'master', sha256: si.audio.sha256, filename: 'song.wav', selection: 'legacy-default', voiceIsolation: 'unverified' });
expect(si).toMatchObject({ referenceImageId: 'frame.png', performance: 'sings the held note', generatedCoverageSec: 5.05 });
// The take's own resolution defaults to 1080P for a music video (fal's own
// default is 768P) and is recorded on the immutable instruction.
@@ -253,7 +253,13 @@ describe.skipIf(!ffmpeg)('music-video performance shot through the fal lip-sync
// Staleness still keys on the master; the stem is recorded as what the
// provider heard.
expect(si.audio.sha256).toBe(sha(songWav()));
- expect(si.audio.conditioning).toEqual({ source: 'vocal-stem', sha256: sha(stem) });
+ expect(si.audio.conditioning).toEqual({ source: 'vocal-stem', sha256: sha(stem), filename: 'vocals.wav', selection: 'legacy-default', voiceIsolation: 'unverified' });
+
+ getProject.mockResolvedValue({ ...project({ performanceSpeaker: 'Example Singer' }), vocalStemFilename: 'vocals.wav', performanceConditioningSource: 'clean-singer-stem' });
+ const clean = await preparePerformanceShot(args);
+ expect(clean.shotInstruction).toMatchObject({ version: 2, speaker: 'Example Singer',
+ audio: { conditioning: { source: 'clean-singer-stem', filename: 'vocals.wav', selection: 'user', voiceIsolation: 'unverified' } } });
+ getProject.mockResolvedValue({ ...project(), vocalStemFilename: 'vocals.wav' });
// A trimmed stem would put the syllables on the wrong frames.
await writeFile(join(PATHS.music, 'vocals.wav'), songWav({ seconds: SONG_SEC - 1 }));
diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.js
index 39203feb43..5981b944d6 100644
--- a/server/services/musicVideo/projectsLogic.js
+++ b/server/services/musicVideo/projectsLogic.js
@@ -114,6 +114,7 @@ export function buildProjectRecord(input, { id, now }) {
updatedAt: now,
trackId,
uploadedAudioFilename,
+ ...(input.performanceConditioningSource ? { performanceConditioningSource: input.performanceConditioningSource } : {}),
concept,
// #8965 — the reusable visual specification (moodboard/reference assets,
// palette, typography, camera rules). Null until the director sets one.
@@ -364,6 +365,7 @@ export function applyProjectPatch(project, patch) {
// A vocal stem is a bounce of the OLD song; conditioning a performance on
// it against the new master would sing the wrong words (#8977).
...(project.vocalStemFilename ? { vocalStemFilename: null } : {}),
+ performanceConditioningSource: 'master',
...mergedPatch,
...statusPatch,
audioAnalysis: null,
@@ -422,6 +424,7 @@ function buildScene(input, { order }) {
// #8977: cutaway (any image-to-video lane) unless the director asks for a
// lip-synced performance shot, which only a source-audio provider renders.
shotMode: input.shotMode ?? 'cutaway',
+ ...(input.performanceSpeaker ? { performanceSpeaker: input.performanceSpeaker } : {}),
referenceImageId: null,
videoHistoryId: null,
// #8965 — immutable candidate takes; the two slot fields above are the
diff --git a/server/services/musicVideo/temporalPerformance.js b/server/services/musicVideo/temporalPerformance.js
new file mode 100644
index 0000000000..8b15e34c7a
--- /dev/null
+++ b/server/services/musicVideo/temporalPerformance.js
@@ -0,0 +1,86 @@
+/**
+ * Optional LOCAL temporal analyzer protocol. Never installs, downloads or calls
+ * a paid provider. The operator installs portos-temporal-analyzer on PATH.
+ * Capability and result validation fail closed; stills and duration parity
+ * cannot supply this evidence. Times are on the encoded excerpt's timeline.
+ */
+import { promisify } from 'util';
+import { z } from 'zod';
+import { execFile } from '../../lib/childProcess.js';
+import { findCommandOnPath, safeChildProcessOptions } from '../../lib/processEnv.js';
+
+const execFileAsync = promisify(execFile);
+const identity = z.string().trim().min(1).max(128);
+const capabilities = z.object({
+ protocolVersion: z.literal(1), id: identity, version: identity,
+ ready: z.literal(true), temporalLipSync: z.literal(true), localOnly: z.literal(true),
+});
+const resultSchema = z.object({
+ spans: z.array(z.object({
+ startSec: z.number().finite().nonnegative(), endSec: z.number().finite().positive(),
+ status: z.enum(['verified', 'unverified']),
+ offsetSec: z.number().finite().min(-5).max(5).nullable(),
+ confidence: z.number().finite().min(0).max(1).nullable(),
+ })).min(1).max(256),
+});
+const unavailable = (shots, reason, analyzer = null) => ({
+ version: 1, status: 'unverified', analyzer, reason,
+ shots: shots.map((shot) => ({ ...shot, spans: [{ startSec: shot.startSec, endSec: shot.endSec, status: 'unverified', offsetSec: null, confidence: null }] })),
+});
+
+// A local executable receives only runtime essentials, never agent/provider or
+// forge credentials. All invocations are bounded and argv-only.
+const analyzerEnv = () => Object.fromEntries(
+ ['PATH', 'Path', 'HOME', 'USERPROFILE', 'SystemRoot', 'TMPDIR', 'TMP', 'TEMP', 'LANG']
+ .filter((key) => process.env[key] !== undefined).map((key) => [key, process.env[key]]),
+);
+const invoke = async (command, args, timeout) => {
+ const { stdout } = await execFileAsync(command, args, safeChildProcessOptions({
+ env: analyzerEnv(), timeout, maxBuffer: 256 * 1024,
+ }));
+ return JSON.parse(stdout);
+};
+
+/** Called only by an explicitly requested draft review. */
+export async function analyzeTemporalPerformance({ excerptPath, shots }) {
+ if (!shots.length) return { version: 1, status: 'not-applicable', analyzer: null, reason: null, shots: [] };
+ const command = findCommandOnPath('portos-temporal-analyzer');
+ if (!command || /\.(cmd|bat)$/i.test(command)) return unavailable(shots, 'No supported local temporal analyzer is installed');
+ const capability = await invoke(command, ['--capabilities'], 5000).then((value) => capabilities.safeParse(value), () => null);
+ if (!capability?.success) return unavailable(shots, 'The installed temporal analyzer is unavailable or unsupported');
+ const analyzer = { id: capability.data.id, version: capability.data.version, protocolVersion: 1 };
+ const measured = [];
+ const deadline = Date.now() + 60_000;
+ let spanCount = 0;
+ for (const shot of shots) {
+ // Analyze the ACTUAL output against its embedded song audio. Source-file
+ // preparation and the current (possibly changed) master prove no output sync.
+ const remainingMs = deadline - Date.now();
+ if (remainingMs <= 0) return unavailable(shots, 'The temporal analyzer exceeded the review time limit', analyzer);
+ const response = await invoke(command, [
+ '--analyze', '--video', excerptPath, '--audio', excerptPath,
+ '--audio-start-sec', '0', '--start-sec', String(shot.startSec), '--end-sec', String(shot.endSec),
+ '--speaker', shot.speaker || '',
+ ], remainingMs).then((value) => resultSchema.safeParse(value), () => null);
+ if (!response?.success) return unavailable(shots, 'The temporal analyzer returned missing or malformed evidence', analyzer);
+ const spans = response.data.spans;
+ spanCount += spans.length;
+ if (spanCount > 256) return unavailable(shots, 'The temporal analyzer exceeded the evidence span limit', analyzer);
+ let cursor = shot.startSec;
+ // Require complete ordered coverage. Gaps, overlaps, non-finite values and
+ // out-of-window results never become a partial pass.
+ for (const span of spans) {
+ if (Math.abs(span.startSec - cursor) > 0.001 || span.endSec <= span.startSec || span.endSec > shot.endSec) {
+ return unavailable(shots, 'The temporal analyzer returned invalid span coverage', analyzer);
+ }
+ cursor = span.endSec;
+ }
+ if (Math.abs(cursor - shot.endSec) > 0.001) return unavailable(shots, 'The temporal analyzer did not cover the performance window', analyzer);
+ measured.push({ ...shot, spans: spans.map((span) => ({
+ ...span,
+ status: span.status === 'verified' && span.offsetSec !== null && span.confidence >= 0.8 ? 'verified' : 'unverified',
+ })) });
+ }
+ const verified = measured.every((shot) => shot.spans.every((span) => span.status === 'verified'));
+ return { version: 1, status: verified ? 'verified' : 'unverified', analyzer, reason: verified ? null : 'Temporal evidence is inconclusive — review the performance by ear', shots: measured };
+}
diff --git a/server/services/musicVideo/vocalStem.js b/server/services/musicVideo/vocalStem.js
index 4602c5fd59..9c2ef84ef6 100644
--- a/server/services/musicVideo/vocalStem.js
+++ b/server/services/musicVideo/vocalStem.js
@@ -90,7 +90,7 @@ export async function attachVocalStem(projectId, { tempPath, originalName }) {
await unlink(join(PATHS.music, filename)).catch(() => {});
throw new ServerError('The project\'s song changed while the vocal stem was uploading. Upload it again.', { status: 409, code: 'MUSIC_VIDEO_AUDIO_CHANGED' });
}
- return updateProject(projectId, { vocalStemFilename: filename });
+ return updateProject(projectId, { vocalStemFilename: filename, performanceConditioningSource: 'vocal-stem' });
} finally {
await unlink(tempPath).catch(() => {});
}
@@ -103,5 +103,5 @@ export async function attachVocalStem(projectId, { tempPath, originalName }) {
export async function detachVocalStem(projectId) {
const project = await getProject(projectId);
if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
- return updateProject(projectId, { vocalStemFilename: null });
+ return updateProject(projectId, { vocalStemFilename: null, performanceConditioningSource: 'master' });
}