Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: lip-synced performance shots and provider-aware music-video timing (#8977)
[._.]/ Adam Eivy820a4e2c4153
diff --git a/client/src/components/musicVideo/SceneCard.jsx b/client/src/components/musicVideo/SceneCard.jsxindex c71c8a2d5d..9ea0e1fa35 100644--- a/client/src/components/musicVideo/SceneCard.jsx+++ b/client/src/components/musicVideo/SceneCard.jsx@@ -8,6 +8,9 @@ import { MUSIC_VIDEO_VISUAL_LAYERS, sceneHasAuthoredSpan } from '../../lib/music// #8985: what a composed render shows for this scene's span.const LAYER_LABELS = { footage: 'Footage', still: 'Still image', card: 'Title card' };const STILL_MOVE_LABELS = [['hold', 'Hold'], ['push', 'Push in'], ['pan', 'Pan']];+import {+ grokCoverage, isPerformanceScene, performanceBlockedReason, performanceCapability, planPerformanceWindow,+} from '../../lib/musicVideoShotTiming.js';// The two timeline-bound scene fields rendered as identical number inputs.const SCENE_TIME_FIELDS = [['Start', 'startSec'], ['End', 'endSec']];@@ -34,6 +37,12 @@ const COVERAGE_TOLERANCE_SEC = 0.25;* The layer picker (#8985) chooses what a composed render (`layered`) shows* for the scene's span: its footage, its selected frame with a camera move, or* a title card. A plain render always plays footage, and says so.+ * The shot mode (#8977) picks Cutaway (any image-to-video lane) or Performance+ * (a singer lip-synced to the master recording). `lipSyncBackend` is the lane a+ * render would use ('' = install default); a performance shot on a lane without+ * verified source-audio conditioning is blocked here with the reason, and a+ * capable one names the provider, model, song window and cost before the+ * director spends anything. `songDurationSec` bounds the planned window.*/export default function SceneCard({scene, index, isLast, generatingFrame, generatingVideo,@@ -41,6 +50,7 @@ export default function SceneCard({onMove, onDelete, onEditLocal, onSave,onGenerateFrame, onGenerateVideo, onContinueVideo,onOpenPreview, onSelectTake, onReviewTake, onImportTake, onImportClipTake, takeBusy = false, layered = false,+ lipSyncBackend = '', songDurationSec = 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@@ -69,6 +79,19 @@ export default function SceneCard({const applyPatch = (patch) => { onEditLocal(scene.sceneId, patch); onSave(scene.sceneId, patch); };const layer = MUSIC_VIDEO_VISUAL_LAYERS.includes(scene.visualLayer) ? scene.visualLayer : 'footage';const fieldId = (name) => `mv-scene-${scene.sceneId}-${name}`;+ const performance = isPerformanceScene(scene);+ const capability = performance ? performanceCapability(lipSyncBackend) : null;+ const timedSpan = typeof scene.startSec === 'number' && typeof scene.endSec === 'number' && scene.endSec > scene.startSec+ ? scene.endSec - scene.startSec+ : null;+ const plan = capability+ ? planPerformanceWindow({ startSec: scene.startSec, endSec: scene.endSec, songDurationSec: songDurationSec ?? Infinity, capability })+ : null;+ const performanceBlocked = performance+ ? (capability ? (plan.ok ? null : plan.message) : performanceBlockedReason(lipSyncBackend))+ : null;+ const grokPlan = !performance && lipSyncBackend === 'grok' && timedSpan != null ? grokCoverage(timedSpan) : null;+ const shotModeId = `mv-shot-mode-${scene.sceneId}`;return (<div className="bg-port-card border border-port-border rounded-lg p-3 space-y-2"><div className="flex items-center justify-between gap-2">@@ -123,9 +146,17 @@ export default function SceneCard({Beat-aligned</label><label className="flex items-center gap-1" title="Repeat the generated clip to fill a span longer than the clip. Off: the shot must be covered by its clip (trim, continue, or replace it).">- <input type="checkbox" checked={loops} onChange={(e) => applyPatch({ loop: e.target.checked })} />+ <input type="checkbox" checked={loops} disabled={performance} onChange={(e) => applyPatch({ loop: e.target.checked })} />Loop clip</label>+ <label htmlFor={shotModeId} className="flex items-center gap-1">Shot</label>+ <select id={shotModeId} value={performance ? 'performance' : 'cutaway'}+ onChange={(e) => applyPatch({ shotMode: e.target.value })}+ className="bg-port-bg border border-port-border rounded px-1 py-1 min-h-[44px] sm:min-h-0"+ title="Cutaway: any video lane animates the frame under the song. Performance: a singer lip-synced to the song itself (needs a source-audio provider).">+ <option value="cutaway">Cutaway</option>+ <option value="performance">Performance (lip-sync)</option>+ </select></div><div className="flex flex-wrap gap-2 items-center text-xs"><label htmlFor={fieldId('layer')}>Layer</label>@@ -168,6 +199,24 @@ export default function SceneCard({Set a start and end — a {layer === 'card' ? 'title card' : 'still'} runs for exactly its span.</p>)}+ {performance && performanceBlocked && (+ <div role="alert" className="flex items-start gap-2 rounded border border-port-warning/40 bg-port-warning/10 px-2 py-1.5 text-xs text-port-warning">+ <AlertTriangle size={13} className="shrink-0 mt-0.5" />+ <span className="min-w-0 break-words">{performanceBlocked}</span>+ </div>+ )}+ {performance && !performanceBlocked && (+ <p className="text-[11px] text-port-text-muted break-words" data-testid="performance-plan">+ Lip-sync via {capability.label} ({capability.modelId}) · song {formatDurationSec(plan.windowStartSec)}–{formatDurationSec(plan.windowEndSec)}+ {plan.editInSec > 0 ? ` · shot starts ${plan.editInSec.toFixed(2)}s into the take` : ''} · {capability.costLabel}+ </p>+ )}+ {grokPlan && (+ <p className={`text-[11px] break-words ${grokPlan.needsSplit ? 'text-port-warning' : 'text-port-text-muted'}`}>+ Grok renders a {grokPlan.requestSec}s clip for this {timedSpan.toFixed(1)}s cutaway+ {grokPlan.needsSplit ? ` — ${grokPlan.uncoveredSec.toFixed(1)}s uncovered; split the scene rather than loop it` : ''}. Motion timing in the prompt is approximate.+ </p>+ )}{underCovered && (<div role="alert" className="flex flex-wrap items-center gap-2 rounded border border-port-warning/40 bg-port-warning/10 px-2 py-1.5 text-xs text-port-warning"><AlertTriangle size={13} className="shrink-0" />@@ -266,10 +315,12 @@ export default function SceneCard({</div>)}<button onClick={() => onGenerateVideo(scene)}- disabled={settingsSaving || !scene.referenceImageId || !!generatingVideo || !!videoBlockedReason}+ disabled={settingsSaving || !scene.referenceImageId || !!generatingVideo || !!videoBlockedReason || !!performanceBlocked}className="flex items-center gap-1 bg-port-border hover:bg-port-border/70 disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0 whitespace-nowrap"- title={videoBlockedReason- || (scene.referenceImageId ? "Generate this scene's video from its reference frame (i2v)" : 'Generate a reference frame first')}>+ title={videoBlockedReason || performanceBlocked+ || (!scene.referenceImageId ? 'Generate a reference frame first'+ : performance ? `Lip-sync this scene's frame to the song via ${capability.label} — ${capability.costLabel}`+ : "Generate this scene's video from its reference frame (i2v)")}>{generatingVideo ? <Activity size={14} className="animate-spin" /> : <Video size={14} />}{generatingVideo ? 'Generating video…' : (scene.videoHistoryId ? 'New video take' : 'Generate video')}</button>diff --git a/client/src/components/musicVideo/VideoRenderSettings.jsx b/client/src/components/musicVideo/VideoRenderSettings.jsxindex acf9e96b95..6a00002478 100644--- a/client/src/components/musicVideo/VideoRenderSettings.jsx+++ b/client/src/components/musicVideo/VideoRenderSettings.jsx@@ -31,7 +31,9 @@ export default function VideoRenderSettings({ videoSettings, generating }) {><option value="">Install default</option><option value="local">Local video</option>- <option value="grok">Grok video</option>+ {/* Grok's CLI lane takes no audio, so it renders cutaways only —+ performance (lip-sync) shots need fal.ai (#8977). */}+ <option value="grok">Grok video (cutaway only)</option><option value="fal">fal.ai video</option></select>{settings.backend === 'local' && (diff --git a/client/src/hooks/useMusicVideoSceneMedia.js b/client/src/hooks/useMusicVideoSceneMedia.jsindex 37901ecb37..65b63b01bb 100644--- a/client/src/hooks/useMusicVideoSceneMedia.js+++ b/client/src/hooks/useMusicVideoSceneMedia.js@@ -5,6 +5,9 @@ import { generateVideo } from '../services/apiImageVideo.js';import useSceneRenderLifecycle from './useSceneRenderLifecycle.js';import { isLtx2FamilyRuntime } from '../lib/runnerFamilies';import { sceneVisualLayer } from '../lib/musicVideoLayers.js';+import {+ approximateMotionCues, grokCoverage, isPerformanceScene, performanceBlockedReason,+} from '../lib/musicVideoShotTiming.js';// Audio-reactive generation conditions motion on the song itself, so the prompt// has to rule out anything that reads as a performance of it.@@ -45,6 +48,11 @@ export function conditioningReferences(spec) {return (spec?.references || []).filter((ref) => ref.condition).slice(0, MAX_CONDITIONING_REFERENCES);}+// A scene's authored span on the song, or null while it is untimed.+const sceneSpanSec = (scene) => (typeof scene.startSec === 'number' && typeof scene.endSec === 'number' && scene.endSec > scene.startSec+ ? scene.endSec - scene.startSec+ : null);+/*** Per-scene media generation for a music-video project: the reference-frame* (image) lane and the scene-clip (i2v / a2v / native-extend) lane.@@ -186,20 +194,36 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applySif (!basePrompt) { toast.error('Add a shot prompt first'); return; }const { settings, audioReactiveSelected, detectedAudioReactiveLora, videoBlockedReason } = videoSettings;if (videoBlockedReason) { toast.error(videoBlockedReason); return; }+ // #8977: a performance shot lip-syncs to the master recording, which only a+ // verified source-audio provider can do — never a cutaway lane with an+ // invented voice. The server slices the song and re-checks the capability.+ const performance = isPerformanceScene(scene);+ const performanceBlocked = performance+ ? (audioReactiveSelected ? performanceBlockedReason('local') : performanceBlockedReason(settings.backend))+ : null;+ if (performanceBlocked) { toast.error(performanceBlocked); return; }+ const spanSec = sceneSpanSec(scene);+ // Grok's CLI lane takes no timed controls: phrase intents ride as prose+ // whose timing is explicitly approximate. The environmental-motion guard+ // stays exclusive to the audio-reactive lane.+ const motionCues = settings.backend === 'grok' ? approximateMotionCues(project?.phrases, scene.startSec, scene.endSec) : '';const prompt = audioReactiveSelected? `${basePrompt}. ${AUDIO_REACTIVE_PERFORMANCE_GUARD}`- : basePrompt;+ : [basePrompt, motionCues].filter(Boolean).join('. ');videoLane.startScene(scene.sceneId);generateVideo({prompt,...(settings.backend ? { backend: settings.backend } : {}),...(settings.backend === 'grok'- ? { grokDuration: settings.grokDuration }+ // Request the 6/10s clip that COVERS this shot; the saved pin is only+ // the fallback for a scene not yet timed on the song.+ ? { grokDuration: spanSec != null ? grokCoverage(spanSec).requestSec : settings.grokDuration }// fal.ai (#8968) — image-to-video only (see VideoRenderSettings); an// absent falDuration lets the server fall back to the resolved// model's own default rather than forcing a value.: settings.backend === 'fal'- ? { falDuration: settings.falDuration || undefined }+ // A performance clip's length follows its song slice (server-side).+ ? (performance ? {} : { falDuration: settings.falDuration || undefined }): settings.backend === 'local'? { modelId: settings.modelId || undefined, disableAudio: true }// A named model is local-only machinery at the server boundary and@@ -266,8 +290,16 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applyS};const generateMissingVideos = () => {- const pending = footageScenes.filter((scene) =>+ const candidates = footageScenes.filter((scene) =>scene.referenceImageId && !scene.videoHistoryId && !genVideoScenes[scene.sceneId] && buildShotPrompt(scene));+ // Performance shots the current lane cannot lip-sync are skipped with one+ // notice rather than a toast per scene (#8977).+ const { settings, audioReactiveSelected } = videoSettings;+ const lipSyncBlocked = performanceBlockedReason(audioReactiveSelected ? 'local' : settings.backend);+ const pending = lipSyncBlocked ? candidates.filter((scene) => !isPerformanceScene(scene)) : candidates;+ const skipped = candidates.length - pending.length;+ if (skipped > 0) toast.info(`Skipped ${skipped} performance shot${skipped === 1 ? '' : 's'}: ${lipSyncBlocked}`);+ if (pending.length === 0 && skipped > 0) return;if (pending.length === 0) {const referenceFrameCount = footageScenes.filter((scene) => scene.referenceImageId).length;toast.info(referenceFrameCount < footageScenes.lengthdiff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex abc2fe8464..9899bafedb 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -60,6 +60,7 @@ grep -i "what you want to do" client/src/lib/README.md| `beatGrid.js` | Music-video beat-quantized timeline arranger (#1854). `buildBeatGridPoints(audioAnalysis)` merges beats/downbeats/section edges into one ranked snap-point list; `snapTimeToGrid(timeSec, gridPoints, toleranceSec)` finds the nearest point within tolerance; `computeSceneSpans(scenes, durationSec)` lays out scenes without a persisted `startSec`/`endSec` contiguously as a display-only fallback; `computeDragSpan({kind, startSpan, deltaSec, gridPoints, ...})` resolves a timeline drag gesture (`'move'` or `'right'` — no `'left'`, since the render can only trim from a clip's own frame 0) into a new span; `shouldMarkBeatAligned({kind, snapped, wasPersisted})` gates the `beatAligned` flag so a reposition-only drag can't silently promote an unpersisted scene's placeholder fallback duration into a "saved exactly" render duration; `autoArrangeScenes(scenes, audioAnalysis)` proposes a full `{ sceneId, startSec, endSec, beatAligned }[]` arrangement by distributing scenes across song sections weighted by each section's `energy` (#1915). Used by `components/musicVideo/BeatTimeline.jsx` and `pages/MusicVideo.jsx`. || `musicVideoLayers.js` | Music-video per-scene visual layers (#8985), re-exported from `server/lib/musicVideoLayers.js`: `MUSIC_VIDEO_VISUAL_LAYERS`, `MUSIC_VIDEO_STILL_MOVES`, `sceneVisualLayer(scene, { layered })`, `sceneHasAuthoredSpan`, `sceneRenderReady(scene, { layered })`. Used by `components/musicVideo/SceneCard.jsx`, `ProjectToolbar.jsx` and `hooks/useMusicVideoSceneMedia.js`. || `musicVideoTakes.js` | Music-video scene takes view helpers (#8965): `sceneTakeList(scene, kind)` lists a scene's image/video takes with an un-materialized pre-takes selection appended as a read-only `legacy` take; `takePreviewKey`, `takeThumbUrl`, `takeProvenance`; `TAKE_SLOT` maps a take kind to its selection field. Used by `components/musicVideo/SceneTakeStrip.jsx` and `pages/MusicVideo.jsx`. |+| `musicVideoShotTiming.js` | Re-export of `server/lib/musicVideoShotTiming.js` (#8977) — shot modes, the verified source-audio lip-sync capability table, `performanceBlockedReason`, `planPerformanceWindow`, `grokCoverage`, `approximateMotionCues`. Used by `hooks/useMusicVideoSceneMedia.js` and `components/musicVideo/SceneCard.jsx`. || `musicVideoUniverseRefs.js` | `pullUniverseCanonReferences(universe, existingReferences)` (#8978) maps a linked universe's characters/places/objects to visual-spec references (character/set/prop roles), skipping images already present and capping at `MUSIC_VIDEO_MAX_REFERENCES` (24, mirrors the server schema). Returns `{ next, added, skipped }`; the caller persists `next` via the ordinary visualSpec PATCH. Used by `components/musicVideo/VisualSpecPanel.jsx`. || `bibleLimits.js` | `BIBLE_LIMITS` re-exported from the pure leaf `server/lib/bibleLimits.js`, plus the client-only `capImageRefs` / `appendImageRefById` for the optimistic imageRefs-append paths. || `characterEvolution.js` | The five-stage character evolution lens as the editors consume it. Re-exports `EVOLUTION_STAGES` / `EVOLUTION_OUTCOMES` / `EVOLUTION_STAGE_LABELS` / `EVOLUTION_STAGE_TEXT_FIELDS` / `EVOLUTION_EVIDENCE_FIELDS` / `EVOLUTION_EVIDENCE_STATUSES` / `CHARACTER_EVOLUTION_LIMITS` / `evolutionEvidenceStatus` / `isDeclaredEvolution` from the pure leaf `server/lib/characterEvolution.js` (a guard in `server/lib/characterEvolution.test.js` fails if this file ever restates a vocabulary instead of re-exporting it), adds the editor descriptors `EVOLUTION_STAGE_EDITOR_FIELDS` / `EVOLUTION_OUTCOME_HINTS` (#6440), and the draft-mutation helpers `evolutionStage` / `patchEvolution` / `patchEvolutionStage` / `patchEvolutionEvidence` that keep an editor's draft collapsing to the same shape the server sanitizer produces — so a present-but-empty field is a real clear (#6441). |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex c2503c0448..ac2e9c0a14 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -68,6 +68,7 @@ export * from './musicDuration.js';export * from './muscriptorModels.js';export * from './musicVideoLayers.js';export * from './musicVideoTakes.js';+export * from './musicVideoShotTiming.js';export * from './musicVideoUniverseRefs.js';export * from './pipelineImageDefaults.js';export * from './reverseOutlineGrid.js';diff --git a/client/src/lib/musicVideoShotTiming.js b/client/src/lib/musicVideoShotTiming.jsnew file mode 100644index 0000000000..ed2f28a0e6--- /dev/null+++ b/client/src/lib/musicVideoShotTiming.js@@ -0,0 +1,18 @@+/**+ * Music Video shot modes and provider-aware timing (#8977).+ *+ * Re-export of `server/lib/musicVideoShotTiming.js` — the one definition of+ * which backends can render a lip-synced performance shot and of the window /+ * coverage math, imported rather than copied so the board and the server's+ * submission gate cannot disagree.+ */+export {+ MUSIC_VIDEO_SHOT_MODES,+ SOURCE_AUDIO_LIPSYNC,+ approximateMotionCues,+ grokCoverage,+ isPerformanceScene,+ performanceBlockedReason,+ performanceCapability,+ planPerformanceWindow,+} from '../../../server/lib/musicVideoShotTiming.js';diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex b778051c88..a34dbe083c 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -717,6 +717,8 @@ export default function MusicVideo() {generatingVideo={sceneMedia.genVideoScenes[scene.sceneId]}settingsSaving={videoSettings.saving}videoBlockedReason={videoSettings.videoBlockedReason}+ lipSyncBackend={videoSettings.audioReactiveSelected ? 'local' : videoSettings.settings.backend}+ songDurationSec={selected.audioAnalysis?.durationSec ?? null}canContinueShot={canContinueShot}onMove={moveScene}onDelete={handleDeleteScene}diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsxindex c1be2826d3..3d8119e926 100644--- a/client/src/pages/MusicVideo.test.jsx+++ b/client/src/pages/MusicVideo.test.jsx@@ -536,6 +536,76 @@ describe('MusicVideo project video renderer', () => {expect(generateVideo).not.toHaveBeenCalled();});+ describe('performance shots (#8977)', () => {+ const PERFORMANCE_SCENE = {+ sceneId: 's1', order: 0, prompt: 'singer at the mic', referenceImageId: 'img1', videoHistoryId: null,+ shotMode: 'performance', startSec: 20, endSec: 21.5,+ };+ const performanceProject = (videoSettings) => ({+ ...PROJECT_NO_CLIP,+ audioAnalysis: { bpm: 120, beats: [], downbeats: [], sections: [], durationSec: 30 },+ videoSettings,+ scenes: [PERFORMANCE_SCENE],+ });++ it('labels Grok cutaway-only and blocks a performance shot on it without calling the provider', async () => {+ await openProject(performanceProject({ backend: 'grok', grokDuration: 6 }));++ expect(await screen.findByRole('option', { name: 'Grok video (cutaway only)' })).toBeTruthy();+ expect(await screen.findByText(/Grok video is cutaway-only/)).toBeTruthy();+ const generate = await screen.findByRole('button', { name: /^Generate video$/ });+ expect(generate).toBeDisabled();+ fireEvent.click(generate);+ expect(generateVideo).not.toHaveBeenCalled();+ });++ it('names the lip-sync provider, model, song window and cost, then renders on fal.ai without a clip-length pin', async () => {+ getVideoGenStatus.mockResolvedValueOnce({+ connected: true, defaultModel: 'ltx23_distilled_q4', falEnabled: true,+ models: [{ id: 'ltx23_distilled_q4', name: 'LTX-2.3 Distilled Q4', runtime: 'ltx2' }],+ });+ generateVideo.mockResolvedValue({ jobId: 'fal-lipsync-job' });+ await openProject(performanceProject({ backend: 'fal', falDuration: 6 }));++ const plan = await screen.findByTestId('performance-plan');+ expect(plan.textContent).toContain('minimax/h3-max/lip-sync/image-to-video');+ expect(plan.textContent).toMatch(/shot starts 1\.7[78]s into the take/);+ expect(plan.textContent).toContain('cost unknown');+ fireEvent.click(await findEnabledByRole('button', { name: /^Generate video$/ }));+ await waitFor(() => expect(generateVideo).toHaveBeenCalledWith(expect.objectContaining({+ backend: 'fal', mode: 'image', sourceImageFile: 'img1',+ })));+ expect(generateVideo.mock.calls.at(-1)[0]).not.toHaveProperty('falDuration');+ });++ it('persists a scene switched to a performance shot', async () => {+ updateMusicVideoScene.mockResolvedValue({ ...PROJECT_NO_CLIP.scenes[0], shotMode: 'performance' });+ await openProject(PROJECT_NO_CLIP);++ fireEvent.change(await screen.findByLabelText('Shot'), { target: { value: 'performance' } });+ await waitFor(() => expect(updateMusicVideoScene).toHaveBeenCalledWith(+ 'mv-2', 's1', { shotMode: 'performance' }, expect.anything(),+ ));+ });++ it('requests the Grok clip that covers a cutaway and adds approximate motion timing', async () => {+ generateVideo.mockResolvedValue({ jobId: 'grok-job' });+ await openProject({+ ...PROJECT_NO_CLIP,+ videoSettings: { backend: 'grok', grokDuration: 6 },+ phrases: [{ id: 'p1', startSec: 12, endSec: 15, intent: 'camera pushes in' }],+ scenes: [{ ...PROJECT_NO_CLIP.scenes[0], startSec: 10, endSec: 17.2 }],+ });++ expect(await screen.findByText(/Grok renders a 10s clip for this 7\.2s cutaway/)).toBeTruthy();+ fireEvent.click(await findEnabledByRole('button', { name: /^Generate video$/ }));+ await waitFor(() => expect(generateVideo).toHaveBeenCalledWith(expect.objectContaining({+ backend: 'grok', grokDuration: 10,+ prompt: expect.stringContaining('around 2.0s: camera pushes in'),+ })));+ });+ });+it('warns when ready scenes reuse the same frames and clips', async () => {await openProject({...PROJECT_WITH_CLIP,diff --git a/docs/features/product-surfaces.md b/docs/features/product-surfaces.mdindex e647bdf83c..e5bed5348c 100644--- a/docs/features/product-surfaces.md+++ b/docs/features/product-surfaces.md@@ -110,7 +110,7 @@ An end-to-end creative production suite for authors, worldbuilders, filmmakers,| **SongBook** | `/songbook` | Interactive chord charts, guitar tablature, lyric repertoire, and auto-scrolling practice sheet music. | — || **Creative Director** | `/creative-director` | Multi-scene episodic video production orchestrator: turn briefs into treatments, storyboards, render plans, and completed episodes. | — || **Creative Commissions** | `/creative-commission` | Standing briefs and scheduled/nightly autonomous media generation aligning with personal taste profiles and feedback. A universe and/or mood board can be picked as the style source: each run loads its style tags and reference images as the Creative Director's art-direction base, attaches those images to vision scene evaluation, and conditions local image renders on them. | — |-| **Music Video Studio** | `/music-video` | Audio-reactive video creation, beat-detection synchronization, scene choreography, and tempo alignment. | — |+| **Music Video Studio** | `/music-video` | Audio-reactive video creation, beat-detection synchronization, scene choreography, and tempo alignment. Scenes are cutaways or lip-synced performance shots; a performance shot renders only on a verified source-audio provider (fal.ai MiniMax H3 lip-sync, 5–14.8s song slices placed at an exact edit in-point) — Grok video is cutaway-only. | — || **Sharing & Conflict Resolution** | `/sharing`, `/sharing/duplicates`, `/sharing/conflicts` | Collaborative asset exchange via cloud storage buckets (Google Drive, Dropbox, iCloud, Syncthing) with duplicate reconciliation and conflict recovery journals. | — |---diff --git a/server/lib/README.md b/server/lib/README.mdindex e2fc9bb025..83e4f66df3 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -298,6 +298,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `cursor.js` | Cursor Agent (`cursor-agent`) provider helpers — the `CURSOR_COMMAND` binary constant, the `isCursorCommand` predicate, and the `ensureCursorHeadlessArgs` (`--print --force`, folding any pinned reasoning effort into `--model`) / `ensureCursorTuiArgs` (`--force`) argv builders. `--force` is load-bearing beyond approvals: it also clears cursor's workspace-trust gate, which otherwise EXITS a headless run before any work happens. The prompt rides raw stdin (like claude/codex, unlike grok/kimi), and cursor needs no configured-default sentinel — its `auto` router is a real model id passed straight to `--model`. || `grok.js` | xAI Grok Build (`grok`) provider helpers — id/endpoint constants (`GROK_API_ID`/`GROK_CLI_ID`/`GROK_TUI_ID`/`GROK_API_ENDPOINT`), `isGrokCommand`/`isGrokCliProvider`/`isGrokTuiProvider` predicates, `ensureGrokHeadlessArgs`/`ensureGrokTuiArgs` argv builders (grok reads its prompt from `--prompt-file /dev/stdin`, not raw stdin; model selection uses the `GROK_CONFIGURED_DEFAULT` sentinel in `providerModels.js` so PortOS omits `--model` like Antigravity), and `prepareGrokPromptFile` (Windows temp-file delivery fallback). || `grokVideoClip.js` | Clip lengths grok's `image_to_video` actually delivers — `GROK_VIDEO_DURATIONS` (`[6, 10]`, measured in #3022: a 2s/3s request returns the same 6.04s clip), `GROK_VIDEO_DEFAULT_DURATION`, `resolveGrokDuration()` (validate an already-grok-shaped request, else default), and `nearestGrokDuration()` (round a length authored against another backend's continuous contract UP to the shortest clip that covers it — for translating a CD/commission `targetDurationSeconds`). Dependency-free so `validation.js` / `routes/videoGen.js` can derive their schemas from the same list the services gate on. |+| `musicVideoShotTiming.js` | Music Video shot modes (#8977): `MUSIC_VIDEO_SHOT_MODES` (`cutaway`/`performance`), `isPerformanceScene`, `SOURCE_AUDIO_LIPSYNC` (verified source-audio lip-sync lanes — only fal.ai MiniMax H3 lip-sync, 5–14.8s), `performanceCapability(backend)`, `performanceBlockedReason(backend)` (Grok is cutaway-only), `planPerformanceWindow()` (provider-bounded audio window + clip-relative edit in/out points; refuses over-long shots instead of relying on provider truncation), `clipRelativeCues()`, `grokCoverage(spanSec)` (covering 6/10s request, flags spans needing a split), `approximateMotionCues()`. Dependency-free; the client re-exports it. || `reactorStartingFrame.js` | Fits a reactor.inc `starting_frame` to the fast-h3 session canvas before it is uploaded. `readImageSize(path)` → `{width,height}` or `null` (never a guessed dimension), and `prepareReactorStartingFrame(sourceImagePath, requestedAspect, outputPath)` → `{ aspect, canvas, framePath, fittedPath }`: an absent `requestedAspect` DERIVES the canvas from the frame's own shape (`nearestReactorAspect`), then centre cover-crops the frame to that canvas's exact pixel size so reactor's own "fitted to the session canvas" step is a no-op. `fittedPath` is the temp file the caller deletes; `null` means the original was uploaded unchanged. A frame sharp cannot decode (or a resize that fails) passes through untouched on the default canvas rather than failing a render PortOS merely could not measure — reactor decodes more containers than sharp does. || `reactorVideoClip.js` | The reactor.inc `fast-h3` clip contract, dependency-free so the route schema, the FableLoom prompt compiler and the VideoGen picker all read one copy — `REACTOR_MAX_PROMPT_LENGTH` (800; the API rejects a longer prompt rather than truncating it), `REACTOR_MIN_CLIP_SECONDS` / `REACTOR_MAX_CLIP_SECONDS` (5.167–14.375, i.e. 124–345 frames at the `REACTOR_CLIP_FPS` 24 it delivers), `REACTOR_MAX_CLIP_ID_LENGTH`, and the picker list `REACTOR_CLIP_LENGTHS` + `REACTOR_DEFAULT_CLIP_LENGTH` + `reactorClipLengthLabel()` (the two exact endpoints plus every whole second between them, since the accepted range is continuous but starts and ends off a round number). Also the CANVAS contract `set_canvas` accepts: `REACTOR_CANVASES` (`16:9` 1344×768, `4:3` 1024×768, `1:1` 768×768, `9:16` 768×1344 — every one a 768px short edge, so the aspect string is the whole choice), `REACTOR_ASPECTS`, `REACTOR_DEFAULT_ASPECT`, `reactorCanvas(aspect)` and `nearestReactorAspect(width, height)` (closest canvas in log-ratio space; anything unmeasurable answers the default rather than deriving one). Mirrored to `client/src/lib/reactorVideoClip.js`, parity pinned by `reactorVideoClip.test.js`. || `kimi.js` | Moonshot AI Kimi Code (`kimi`) provider helpers — id constants (`KIMI_CLI_ID`/`KIMI_TUI_ID`), `isKimiCommand`/`isKimiCliProvider`/`isKimiTuiProvider` predicates, `ensureKimiHeadlessArgs` (model flag only — non-interactive mode is implicit in `--prompt`, and kimi has no `--print`/`--afk` and refuses approval flags alongside `--prompt`) / `ensureKimiTuiArgs` (`--yolo`) argv builders (model selection uses the `KIMI_CONFIGURED_DEFAULT` sentinel in `providerModels.js` so PortOS omits `--model` like Grok/Antigravity), and `prepareKimiPrompt` (delivers the prompt as the `--prompt <value>` argv, not stdin). |@@ -400,7 +401,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `httpDrain.js` | `createHttpDrain(servers)` tracks every ordinary request the HTTP listeners accept; `begin(windowMs)` is the synchronous shutdown step that stops intake on all of them (`server.close()` plus a 503 `Connection: close` gate for requests arriving on still-open keep-alive sockets), turns off keep-alive on in-flight responses, drops open SSE streams, and resolves `{ remaining }` once accepted requests finish or the window ends (#8323). || `httpCompression.js` | `httpCompression` negotiates Brotli/gzip for API and static responses while preserving streaming, ranges, existing encodings, and `no-transform`. || `execGit.js` | `execGit(args, cwd, options)` and `execGitSafe(args, cwd, options)` shared process boundary for Git operations, worktrees, and `services/forgeAuth.js` credential resolution. The safe variant converts rejections into `{ exitCode: 1, stdout: '', stderr }`; `services/git.js` re-exports both for compatibility. `cwd` is REQUIRED — it rejects on a missing/blank one rather than letting `spawn` fall back to `process.cwd()` and run git against PortOS's own checkout (#4554). |-| `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). `generateThumbnail(videoPath, jobId, { atSec } = {})` accepts a clamped poster seek while preserving the single-clip default. Includes `probeFrameCount(videoPath)` (metadata `nb_frames`, falling back to a real `-count_frames` pass — expensive, so call it once per file) and `trimVideoFromFrame(videoPath, outPath, {startFrame, fps})` — a frame-EXACT head cut via the `trim` filter (an `-ss` seek can drift a frame, which reads as a stutter at a stitch seam), keeping audio in sync with `atrim` when the clip has a soundtrack and taking `-an` when it doesn't. Re-encodes by necessity, so a later concat must re-encode too; `outPath` may equal the input (temp-file + rename install). Used by the chained-render context window — see `videoContinuity.js`. `buildTrimConcatArgs({inputs, outPath, width, height, fps, withAudio})` builds the argv for the other half of that job: a concat that drops leading frames from some of its inputs inside a `filter_complex` graph, so the cuts ride along with the timeline encode instead of costing one pre-encode per clip (pass `withAudio` only when EVERY input has an audio stream — check with `hasAudioStream`). `H264_ENCODE_ARGS` / `AAC_ENCODE_ARGS` are the shared encode profile: clips produced by different paths here get concatenated together, so a mismatch shows up as one segment graded differently from its neighbours — spread these rather than re-typing the flags. Every re-encode here also pins BT.709: `BT709_CONTAINER_ARGS` (the `colr` atom, always emitted) plus `bt709TagFilter()` → the `BT709_TAG_FILTER` `setparams=…` string, or `null` on an ffmpeg without that filter (`supportsSetparamsFilter()` probes `-filters` once per process; `null` = not probed, and a probe that couldn't run stays uncached). Both halves are required — from ffmpeg 8 the encoder reads color properties off the FRAMES, silently overriding the container flags, so a flags-only output decodes washed-out. `buildTrimConcatArgs` takes the filter as its `colorTagFilter` option rather than probing, to stay pure. `installEncodedVideo(tmpPath, targetPath, label)` is the shared in-place install: move the original aside to a `.bak` on Windows (where `fs.rename` refuses an existing destination), rename the new file over it, and restore the backup — plus unlink the temp — on any failure, returning `{ok:true,outPath}` / `{ok:false,reason}` so the worst case is "skipped", never "the video is gone". Use it for EVERY replace-a-video-with-its-re-encode path; `pipeline/audioMux.js` is the out-of-module caller. |+| `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). `probeVideoGeometry(videoPath)` measures a finished clip's `{ width, height, fps, numFrames, durationSec }` (null when any axis is unreadable) for hosted renders that record no frame count. `generateThumbnail(videoPath, jobId, { atSec } = {})` accepts a clamped poster seek while preserving the single-clip default. Includes `probeFrameCount(videoPath)` (metadata `nb_frames`, falling back to a real `-count_frames` pass — expensive, so call it once per file) and `trimVideoFromFrame(videoPath, outPath, {startFrame, fps})` — a frame-EXACT head cut via the `trim` filter (an `-ss` seek can drift a frame, which reads as a stutter at a stitch seam), keeping audio in sync with `atrim` when the clip has a soundtrack and taking `-an` when it doesn't. Re-encodes by necessity, so a later concat must re-encode too; `outPath` may equal the input (temp-file + rename install). Used by the chained-render context window — see `videoContinuity.js`. `buildTrimConcatArgs({inputs, outPath, width, height, fps, withAudio})` builds the argv for the other half of that job: a concat that drops leading frames from some of its inputs inside a `filter_complex` graph, so the cuts ride along with the timeline encode instead of costing one pre-encode per clip (pass `withAudio` only when EVERY input has an audio stream — check with `hasAudioStream`). `H264_ENCODE_ARGS` / `AAC_ENCODE_ARGS` are the shared encode profile: clips produced by different paths here get concatenated together, so a mismatch shows up as one segment graded differently from its neighbours — spread these rather than re-typing the flags. Every re-encode here also pins BT.709: `BT709_CONTAINER_ARGS` (the `colr` atom, always emitted) plus `bt709TagFilter()` → the `BT709_TAG_FILTER` `setparams=…` string, or `null` on an ffmpeg without that filter (`supportsSetparamsFilter()` probes `-filters` once per process; `null` = not probed, and a probe that couldn't run stays uncached). Both halves are required — from ffmpeg 8 the encoder reads color properties off the FRAMES, silently overriding the container flags, so a flags-only output decodes washed-out. `buildTrimConcatArgs` takes the filter as its `colorTagFilter` option rather than probing, to stay pure. `installEncodedVideo(tmpPath, targetPath, label)` is the shared in-place install: move the original aside to a `.bak` on Windows (where `fs.rename` refuses an existing destination), rename the new file over it, and restore the backup — plus unlink the temp — on any failure, returning `{ok:true,outPath}` / `{ok:false,reason}` so the worst case is "skipped", never "the video is gone". Use it for EVERY replace-a-video-with-its-re-encode path; `pipeline/audioMux.js` is the out-of-module caller. || `forgeAccessErrors.js` | `isForgeNoAccessError(err)` / `isForgeNoAccessMessage(text)` / `logForgeNoAccessOnce(scope, repoSpec, detail)` / `forgeNoAccessRemedy(repoSpec)` — tells a PERMANENT `gh` no-access 404 (`Could not resolve to a Repository`, `HTTP 404`) apart from a transient blip. `execGh` stamps `ghNoAccess` on the rejection and keeps it OUT of the consecutive-failure backoff (which caps at 15 min and then re-fires forever), and the polling jobs (`branchReconcile`, `prWatcher`) narrate it exactly once per scope+repo per process with a remedy line instead of once per tick. `__resetForgeNoAccessLog()` is the test seam. || `forkHead.js` | `normalizeForkHead(value)` / `forkRemoteName(ownerLogin)` / `resolveTaskForkHead(metadata)` — the validated `{remoteUrl, ownerLogin}` address of a cross-repository PR's head branch, which has no `origin/<branch>` to attach to. Fail-closed: anything that isn't a usable pair (or that starts with `-`, which git would read as an option) is `null`, so every caller falls back to origin-only behavior instead of guessing. `forkRemoteName` is the deterministic `fork-<owner>` remote name that makes a re-attach reuse the remote it already added. Shared by `appPullRequests.js` (produces), `agentWorktreeCleanup.js`/`prRemediationFollowUp.js` (persist in task metadata), `agentWorkspacePrep.js` (threads), and `worktreeManager.js` (consumes — it has no forge client of its own). `resolveTaskForkHead` is the single reader of the generic `forkHead` task-metadata key, the fork-side counterpart to `taskTargetBranch.js`. || `frameQuality.js` | Scores decoded video frames so a chained render can CHOOSE its continuation anchor instead of taking whatever an end-seek lands on. `scoreFrame({width,height,data},{recency})` combines three terms over a raw single-channel buffer: log-compressed `gradientVariance` (focus), distance of `meanLuma` from mid-grey (exposure penalty, which rejects a fade-to-black or a blown highlight), and a small linear recency bonus that keeps the anchor near the cut when candidates are comparably clean. Usability and ranking are deliberately separate: `usable` gates on raw gradient variance against `MIN_SIGNAL_VARIANCE` alone, so only a mathematically degenerate frame is rejected and a legitimately dark low-key tail still qualifies — the same contract `imageFrameStats.js` keeps. Gating on the composite score instead would reject every night scene on the exposure term. `TAIL_WINDOW_SECONDS` is capped at the reach of the single `-sseof -1.0` seek this replaces: focus is systematically highest at the OLDEST candidate, so a wider window would widen the backward jump at each chain seam rather than tightening it. `pickBestFrame(paths)` decodes each candidate through `sharp` and returns the winner (or `null` when nothing decodes or every candidate is degenerate, so the caller degrades rather than failing a render); its `index` is the position in the array AS PASSED, because the caller turns that into the anchor's time offset. `MAX_CANDIDATES` is derived from the window, never set independently — the ffmpeg-side `-frames:v` cap truncates from the NEWEST end, exactly the frames recency prefers. `TAIL_WINDOW_SECONDS` / `CANDIDATE_FPS` / `MAX_CANDIDATES` define the window the caller decodes from. Consumer: `services/videoGen/local.js#extractLastFrame`. |diff --git a/server/lib/ffmpeg.js b/server/lib/ffmpeg.jsindex cab09165fb..9677a1b468 100644--- a/server/lib/ffmpeg.js+++ b/server/lib/ffmpeg.js@@ -302,6 +302,22 @@ export const probeVideoStreamInfo = async (videoPath) => {};};+// The playable geometry of a finished clip — `{ width, height, fps, numFrames,+// durationSec }` — or null when any axis cannot be measured. For entries whose+// producer never recorded a frame count (hosted Grok/fal/reactor renders), so a+// consumer that trims by numFrames/fps measures the file instead of guessing.+export const probeVideoGeometry = async (videoPath) => {+ const [stream, durationSec] = await Promise.all([probeVideoStreamInfo(videoPath), probeDurationSeconds(videoPath)]);+ if (!stream.width || !stream.height || !stream.fps || !durationSec) return null;+ return {+ width: stream.width,+ height: stream.height,+ fps: stream.fps,+ numFrames: stream.frameCount || Math.round(durationSec * stream.fps),+ durationSec,+ };+};+// Sanity-check that a rendered video file is actually playable: the file// exists on disk, has non-zero bytes, and ffprobe can decode at least one// video frame from it. Returns `{ ok: true }` on success anddiff --git a/server/lib/index.js b/server/lib/index.jsindex c755489dd1..de0ab46550 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -188,6 +188,7 @@ export * from './contextBudget.js';export * from './cursor.js';export * from './grok.js';export * from './grokVideoClip.js';+export * from './musicVideoShotTiming.js';export * from './reactorStartingFrame.js';export * from './reactorVideoClip.js';export * from './heavyJobClaim.js';diff --git a/server/lib/musicVideoShotTiming.js b/server/lib/musicVideoShotTiming.jsnew file mode 100644index 0000000000..c5d3ff27cb--- /dev/null+++ b/server/lib/musicVideoShotTiming.js@@ -0,0 +1,191 @@+/**+ * Music Video shot modes and provider-aware timing (#8977).+ *+ * A scene is either a CUTAWAY (the default — any image-to-video lane animates+ * the reference frame; the master song is laid under it at render time) or a+ * PERFORMANCE shot: a visible singer whose mouth must follow the actual master+ * recording. Prompting cannot deliver that; only a provider that accepts the+ * exact song audio as conditioning can. This module is the one definition of+ * which lanes can, and of the timing math both runtimes share:+ *+ * - `SOURCE_AUDIO_LIPSYNC` — the capability snapshot per backend. Only fal.ai's+ * documented MiniMax H3 lip-sync route (image_url + audio_url, at least 5s of+ * audio, silently clipped beyond 14.8s, output length follows the clipped+ * audio) is listed. Grok's CLI image_to_video lane takes no audio at all, so+ * it is cutaway-only here until an actual adapter proves exact-source-audio+ * conditioning — REST documentation for a different Grok surface is not that+ * proof. Local runtimes are absent for the same reason.+ * - `planPerformanceWindow` — the audio window a performance shot submits:+ * inside the provider's limits (never relying on its silent truncation), a+ * short shot padded to a supported contextual window with an explicit edit+ * in-point, a long shot refused so the director splits it on a lyric/phrase+ * boundary. Nothing is looped or time-stretched to fill a slot.+ * - `grokCoverage` — the 6/10-second Grok request that COVERS a cutaway shot+ * (reusing `nearestGrokDuration`), flagging spans a single clip cannot cover.+ *+ * Dependency-free (only grokVideoClip.js, itself dependency-free) so the client+ * re-exports it from `client/src/lib/musicVideoShotTiming.js` and the two sides+ * cannot drift.+ */++import { GROK_VIDEO_DURATIONS, nearestGrokDuration } from './grokVideoClip.js';++export const MUSIC_VIDEO_SHOT_MODES = Object.freeze(['cutaway', 'performance']);++/** A scene with no `shotMode` (every pre-#8977 record) is a cutaway. */+export const isPerformanceScene = (scene) => scene?.shotMode === 'performance';++// Safety margin kept inside the provider's documented bounds so ffmpeg's+// sample rounding can never land a window a hair under the minimum (rejected)+// or over the maximum (silently clipped by the provider).+export const PERFORMANCE_WINDOW_MARGIN_SEC = 0.05;++/** Verified source-audio lip-sync lanes, keyed by Music Video backend. */+export const SOURCE_AUDIO_LIPSYNC = Object.freeze({+ fal: Object.freeze({+ provider: 'fal',+ label: 'fal.ai MiniMax H3 lip-sync',+ modelId: 'minimax/h3-max/lip-sync/image-to-video',+ minAudioSec: 5,+ maxAudioSec: 14.8,+ transcription: true,+ // fal.ai publishes no per-request price PortOS can read; say so plainly+ // rather than inventing an estimate.+ costLabel: 'cost unknown — billed to your fal.ai account',+ }),+});++/** The lip-sync capability a backend offers, or null. */+export const performanceCapability = (backend) => (+ Object.prototype.hasOwnProperty.call(SOURCE_AUDIO_LIPSYNC, backend || '') ? SOURCE_AUDIO_LIPSYNC[backend] : null+);++/**+ * Why a performance shot cannot render on `backend`, or null when it can.+ * `backend` is the project's pinned Music Video backend ('' / null = the+ * install default, which is never assumed to be a lip-sync provider).+ */+export function performanceBlockedReason(backend) {+ if (performanceCapability(backend)) return null;+ if (backend === 'grok') {+ return 'Grok video is cutaway-only: it cannot synchronize a singer to the song. Pin fal.ai for performance shots, or switch this scene to Cutaway.';+ }+ if (backend === 'local') {+ return 'Local video models cannot lip-sync to the song. Pin fal.ai for performance shots, or switch this scene to Cutaway.';+ }+ return 'Performance shots need a source-audio lip-sync provider — pin fal.ai as this project\'s video backend.';+}++const round6 = (n) => Math.round(n * 1e6) / 1e6;++/**+ * The audio window a performance shot submits, for a scene spanning+ * `[startSec, endSec]` of a song `songDurationSec` long.+ *+ * Returns `{ ok: true, spanSec, windowStartSec, windowEndSec, windowSec,+ * editInSec, editOutSec }` — the window is absolute song time; the edit in/out+ * points are relative to the generated clip (whose length follows the window).+ * Returns `{ ok: false, code, message }` when the shot cannot be planned.+ */+export function planPerformanceWindow({ startSec, endSec, songDurationSec, capability }) {+ if (!capability) {+ return { ok: false, code: 'MUSIC_VIDEO_PERFORMANCE_UNSUPPORTED', message: performanceBlockedReason(null) };+ }+ if (typeof startSec !== 'number' || typeof endSec !== 'number' || !(endSec > startSec) || startSec < 0) {+ return { ok: false, code: 'MUSIC_VIDEO_PERFORMANCE_UNTIMED', message: 'A performance shot needs a timed start and end on the song.' };+ }+ if (!(songDurationSec > 0) || endSec > songDurationSec + 1e-6) {+ return { ok: false, code: 'MUSIC_VIDEO_PERFORMANCE_OUT_OF_RANGE', message: 'The performance shot runs past the end of the song.' };+ }+ const minSec = capability.minAudioSec + PERFORMANCE_WINDOW_MARGIN_SEC;+ const maxSec = capability.maxAudioSec - PERFORMANCE_WINDOW_MARGIN_SEC;+ const spanSec = endSec - startSec;+ if (spanSec > maxSec) {+ return {+ ok: false,+ code: 'MUSIC_VIDEO_PERFORMANCE_TOO_LONG',+ message: `This performance shot runs ${spanSec.toFixed(2)}s, but ${capability.label} synchronizes at most ${maxSec.toFixed(2)}s of audio per take. Split the scene on a lyric or phrase boundary.`,+ };+ }+ if (songDurationSec < minSec) {+ return {+ ok: false,+ code: 'MUSIC_VIDEO_PERFORMANCE_SONG_TOO_SHORT',+ message: `${capability.label} needs at least ${minSec.toFixed(2)}s of audio; the song is only ${songDurationSec.toFixed(2)}s.`,+ };+ }+ let windowStartSec = startSec;+ let windowEndSec = endSec;+ if (spanSec < minSec) {+ // Pad a short shot to a supported contextual window, centered on the shot+ // where the song allows, then shifted to stay inside it. The edit in-point+ // records exactly where the shot starts inside the generated clip.+ const pad = minSec - spanSec;+ windowStartSec = Math.max(0, startSec - pad / 2);+ windowEndSec = windowStartSec + minSec;+ if (windowEndSec > songDurationSec) {+ windowEndSec = songDurationSec;+ windowStartSec = songDurationSec - minSec;+ }+ }+ return {+ ok: true,+ spanSec: round6(spanSec),+ windowStartSec: round6(windowStartSec),+ windowEndSec: round6(windowEndSec),+ windowSec: round6(windowEndSec - windowStartSec),+ editInSec: round6(startSec - windowStartSec),+ editOutSec: round6(endSec - windowStartSec),+ };+}++/**+ * Lyric cues overlapping `[windowStartSec, windowEndSec]`, re-timed relative to+ * the window start and clamped to it. Untimed cues are dropped.+ */+export function clipRelativeCues(cues, windowStartSec, windowEndSec) {+ const out = [];+ for (const cue of Array.isArray(cues) ? cues : []) {+ if (typeof cue?.startSec !== 'number') continue;+ const end = typeof cue.endSec === 'number' ? cue.endSec : cue.startSec;+ if (end < windowStartSec || cue.startSec > windowEndSec) continue;+ out.push({+ text: typeof cue.text === 'string' ? cue.text : '',+ startSec: round6(Math.max(0, cue.startSec - windowStartSec)),+ endSec: round6(Math.min(windowEndSec, end) - windowStartSec),+ });+ }+ return out;+}++/**+ * The Grok CLI request that covers a cutaway shot of `spanSec`: the shortest+ * deliverable clip at least that long (6 or 10s), or the longest when none is.+ * `uncoveredSec > 0` means one clip cannot cover the shot — split the scene+ * rather than loop or stretch the clip.+ */+export function grokCoverage(spanSec) {+ const requestSec = nearestGrokDuration(spanSec);+ const longest = GROK_VIDEO_DURATIONS[GROK_VIDEO_DURATIONS.length - 1];+ const span = Number(spanSec);+ const uncoveredSec = Number.isFinite(span) && span > longest ? round6(span - longest) : 0;+ return { requestSec, uncoveredSec, needsSplit: uncoveredSec > 0 };+}++/**+ * Phrase intents overlapping a cutaway shot, as approximate clip-relative motion+ * prose for providers that take no timed controls (Grok's CLI lane). The timing+ * is explicitly approximate — the provider is not bound to it.+ */+export function approximateMotionCues(phrases, startSec, endSec) {+ if (typeof startSec !== 'number' || typeof endSec !== 'number' || !(endSec > startSec)) return '';+ const beats = [];+ for (const phrase of Array.isArray(phrases) ? phrases : []) {+ const intent = typeof phrase?.intent === 'string' ? phrase.intent.trim() : '';+ if (!intent || typeof phrase.startSec !== 'number') continue;+ const phraseEnd = typeof phrase.endSec === 'number' ? phrase.endSec : phrase.startSec;+ if (phraseEnd <= startSec || phrase.startSec >= endSec) continue;+ beats.push(`around ${Math.max(0, phrase.startSec - startSec).toFixed(1)}s: ${intent}`);+ }+ return beats.length ? `Approximate motion timing within the clip — ${beats.join('; ')}.` : '';+}diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex 7b44398967..4439ce76c4 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -10,6 +10,7 @@import { z } from 'zod';import { MUSIC_VIDEO_STILL_MOVES, MUSIC_VIDEO_VISUAL_LAYERS } from './musicVideoLayers.js';+import { MUSIC_VIDEO_SHOT_MODES } from './musicVideoShotTiming.js';// A project is authored hands-on (director) or seeded by the AI planner// (autonomous); both share the same record + scene board.@@ -275,6 +276,10 @@ export const musicVideoSceneCreateSchema = z.object({lyricText: z.string().max(2000).nullable().optional(),visualIntent: z.string().max(2000).nullable().optional(),...sceneLayerFields,+ // #8977: `performance` = a lip-synced singer that must follow the master+ // 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(),}).strict().refine((s) => s.startSec == null || s.endSec == null || s.endSec >= s.startSec,{ message: 'endSec must be >= startSec', path: ['endSec'] },@@ -300,6 +305,10 @@ export const musicVideoSceneUpdateSchema = z.object({lyricText: z.string().max(2000).nullable().optional(),visualIntent: z.string().max(2000).nullable().optional(),...sceneLayerFields,+ // #8977: `performance` = a lip-synced singer that must follow the master+ // 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(),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.jsindex 72d61a292b..5c16b94445 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -595,7 +595,14 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// Gating makes a v2 receiver reject the ahead-version transfer until it// upgrades; pre-#8965 records need no rewrite (a selected slot with no take// is materialized as a `legacy` take on first use).- musicVideoProjects: 3,+ // v4 = performance shots (#8977): `scene.shotMode` and a video take's+ // immutable `shotInstruction`. A v3 receiver stores both verbatim but+ // mis-executes them: it renders a performance take from frame 0 instead of+ // its edit in-point (and may loop it), desyncing the singer from the song,+ // and submits performance scenes to a cutaway-only lane — edits that then win+ // LWW onto the upgraded peer. Pre-#8977 records need no rewrite (absent+ // `shotMode` = cutaway; takes without an instruction render as before).+ musicVideoProjects: 4,// 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/musicVideo.test.js b/server/routes/musicVideo.test.jsindex 1442dbcfbb..5ed607660b 100644--- a/server/routes/musicVideo.test.js+++ b/server/routes/musicVideo.test.js@@ -173,6 +173,15 @@ describe('musicVideo routes', () => {expect(svc.updateProject).not.toHaveBeenCalled();});+ it('PATCH /:id/scenes/:sceneId sets a scene to a performance shot and rejects an unknown shot mode (#8977)', async () => {+ const ok = await request(app).patch('/api/music-video/mv-1/scenes/mvs-1').send({ shotMode: 'performance' });+ expect(ok.status).toBe(200);+ expect(svc.updateScene).toHaveBeenCalledWith('mv-1', 'mvs-1', { shotMode: 'performance' });+ const bad = await request(app).patch('/api/music-video/mv-1/scenes/mvs-1').send({ shotMode: 'karaoke' });+ expect(bad.status).toBe(400);+ expect(svc.updateScene).toHaveBeenCalledTimes(1);+ });+it('PATCH /:id accepts null to clear the project video-backend pin', async () => {const videoSettings = { backend: null };const r = await request(app).patch('/api/music-video/mv-1').send({ videoSettings });diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.jsindex f445483e35..4963dc81d4 100644--- a/server/services/mediaJobQueue/index.test.js+++ b/server/services/mediaJobQueue/index.test.js@@ -58,6 +58,7 @@ vi.mock('../../lib/systemCapabilities.js', async (importOriginal) => ({const stubs = {generateVideo: vi.fn(async () => ({ jobId: 'whatever' })),generateVideoGrok: vi.fn(async () => ({ jobId: 'whatever' })),+ generateVideoFal: vi.fn(async () => ({ jobId: 'whatever' })),generateChainedVideo: vi.fn(async () => ({ jobId: 'whatever' })),generateImage: vi.fn(async () => ({ jobId: 'whatever' })),generateImageCodex: vi.fn(async () => ({ jobId: 'whatever' })),@@ -109,6 +110,11 @@ vi.mock('../videoGen/grok.js', () => ({cancel: (...args) => stubs.cancelVideo(...args),}));+vi.mock('../videoGen/fal.js', () => ({+ generateVideo: (...args) => stubs.generateVideoFal(...args),+ cancel: (...args) => stubs.cancelVideo(...args),+}));+vi.mock('../imageGen/local.js', () => ({generateImage: (...args) => stubs.generateImage(...args),cancel: (...args) => stubs.cancelImage(...args),@@ -892,6 +898,31 @@ describe('mediaJobQueue', () => {expect(recovered.error).toMatch(/interrupted by restart/);});+ it('boot recovery (#8977): an interrupted paid fal performance render is failed, never resubmitted, and its song slice released', async () => {+ const interruptedId = '00000000-0000-4000-8000-000000000003';+ const slice = join(tempDataDir, 'uploads', 'mv-performance-example.wav');+ mkdirSync(join(tempDataDir, 'uploads'), { recursive: true });+ writeFileSync(slice, 'wav');+ writeFileSync(join(tempDataDir, 'media-jobs.json'), JSON.stringify({+ jobs: [{+ id: interruptedId, kind: 'video', status: 'running',+ queuedAt: '2026-04-30T10:00:00.000Z', startedAt: '2026-04-30T10:00:01.000Z',+ params: {+ mode: 'fal', videoMode: 'image', prompt: 'singer', audioFilePath: slice,+ musicVideo: { projectId: 'mv-1', sceneId: 'mvs-1' },+ shotInstruction: { version: 1, shotMode: 'performance', edit: { inSec: 1, outSec: 2 } },+ },+ }],+ }));++ await importFresh();+ await mediaJobQueue.initMediaJobQueue();++ expect(mediaJobQueue.getJob(interruptedId)).toMatchObject({ status: 'failed', error: expect.stringMatching(/interrupted by restart/) });+ await waitFor(() => !existsSync(slice));+ expect(stubs.generateVideoFal).not.toHaveBeenCalled();+ });+it('boot recovery (#1332): a "running" training job whose trainer survived is re-enqueued for re-attach', async () => {const runId = 'run-survivor-1';const trainingId = '00000000-0000-4000-8000-000000000010';diff --git a/server/services/musicVideo/performanceShot.js b/server/services/musicVideo/performanceShot.jsnew file mode 100644index 0000000000..f688e10b8f--- /dev/null+++ b/server/services/musicVideo/performanceShot.js@@ -0,0 +1,162 @@+/**+ * Music Video performance shots (#8977) — the submission-boundary half.+ *+ * A performance scene (`scene.shotMode === 'performance'`) is a visible singer+ * that must follow the MASTER recording. At the moment a scene render is+ * submitted this module:+ *+ * 1. refuses the render unless the resolved backend has a verified+ * source-audio lip-sync capability (lib/musicVideoShotTiming.js) — Grok and+ * local lanes are cutaway-only, and nothing silently falls back to a lane+ * that would invent an unrelated voice or ignore the song;+ * 2. plans the provider-bounded audio window (a short shot is padded to a+ * supported contextual window with an explicit edit in-point; an over-long+ * shot is refused so it is split rather than truncated by the provider);+ * 3. slices exactly that window out of the master with ffmpeg — decoded from+ * the start and cut with `atrim` on sample timestamps, written as PCM WAV+ * (no encoder priming delay), so the clip's audio timebase IS the song's;+ * 4. builds the immutable shot instruction record the finished take carries:+ * the audio revision (content hash), absolute song interval, window, edit+ * in/out points, clip-relative lyric cues, reference frame, intended+ * performance, capability snapshot, target edit duration and the coverage+ * the provider will generate.+ *+ * The sliced WAV is staged under data/uploads so the media-job queue owns and+ * deletes it on every terminal path (completion, failure, cancel, restart).+ * The master stays untouched and remains the only audio in the final render.+ */++import { createHash, randomUUID } from 'crypto';+import { createReadStream } 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 {+ clipRelativeCues,+ isPerformanceScene,+ performanceBlockedReason,+ performanceCapability,+ planPerformanceWindow,+} from '../../lib/musicVideoShotTiming.js';+import { getProject } from './projects.js';++export const SHOT_INSTRUCTION_VERSION = 1;++const hashFile = (path) => new Promise((resolve, reject) => {+ const hash = createHash('sha256');+ createReadStream(path)+ .on('data', (chunk) => hash.update(chunk))+ .on('error', reject)+ .on('end', () => resolve(hash.digest('hex')));+});++/**+ * Cut `[startSec, endSec]` of `sourcePath` into a new PCM WAV at `outPath`.+ * Exported for the synthetic-audio contract test; production callers go+ * through `preparePerformanceShot`.+ */+export async function sliceAudioWindow(sourcePath, outPath, { startSec, endSec }) {+ const ffmpeg = await findFfmpeg();+ if (!ffmpeg) throw new ServerError('ffmpeg is required to slice the song for a performance shot', { status: 500, code: 'FFMPEG_MISSING' });+ const result = await runFfmpegProcess({+ bin: ffmpeg,+ args: [+ '-v', 'error',+ '-i', sourcePath,+ '-vn',+ '-af', `atrim=start=${startSec}:end=${endSec},asetpts=PTS-STARTPTS`,+ '-c:a', 'pcm_s16le',+ '-y', outPath,+ ],+ });+ if (!result.ok) {+ await unlink(outPath).catch(() => {});+ throw new ServerError(`Failed to slice the song for a performance shot: ${result.reason}`, { status: 500, code: 'MUSIC_VIDEO_AUDIO_SLICE_FAILED' });+ }+ return outPath;+}++const refuse = (message, code, status = 400) => new ServerError(message, { status, code });++/**+ * Prepare a Music Video scene render's performance inputs.+ *+ * Returns `null` for a cutaway scene (nothing to add), or+ * `{ audioFilePath, shotInstruction, modelId, enableTranscription }` for a+ * performance scene on a capable backend. Throws a 4xx ServerError when the+ * scene is a performance shot the backend or its timing cannot deliver.+ */+export async function preparePerformanceShot({ musicVideo, backend, sourceImagePath, mode }) {+ if (!musicVideo?.projectId || !musicVideo?.sceneId) return null;+ const project = await getProject(musicVideo.projectId);+ const scene = project?.scenes?.find((s) => s.sceneId === musicVideo.sceneId);+ if (!project || !scene) throw refuse('Music-video project or scene not found', 'NOT_FOUND', 404);+ if (!isPerformanceScene(scene)) return null;++ const capability = performanceCapability(backend);+ if (!capability) throw refuse(performanceBlockedReason(backend), 'MUSIC_VIDEO_PERFORMANCE_UNSUPPORTED');+ // The lip-sync route is image + source audio; any other semantic mode would+ // ask it for something it does not do.+ if (mode && mode !== 'image') {+ throw refuse(`A performance shot renders from its reference frame and the song — mode '${mode}' is not supported.`, 'MUSIC_VIDEO_PERFORMANCE_MODE_UNSUPPORTED');+ }++ // Lazy: render.js pulls the whole render pipeline, which a cutaway+ // submission (the common case) never needs.+ const { resolveMasterAudioPath } = await import('./render.js');+ const masterPath = await resolveMasterAudioPath(project);+ const songDurationSec = await probeVideoDuration(masterPath);+ if (songDurationSec == null) throw refuse('Could not read the song duration for this performance shot', 'MUSIC_VIDEO_AUDIO_UNREADABLE');+ const plan = planPerformanceWindow({ startSec: scene.startSec, endSec: scene.endSec, songDurationSec, capability });+ if (!plan.ok) throw refuse(plan.message, plan.code);++ const audioSha256 = await hashFile(masterPath);+ await ensureDir(PATHS.uploads);+ const audioFilePath = join(PATHS.uploads, `mv-performance-${randomUUID()}.wav`);+ await sliceAudioWindow(masterPath, audioFilePath, { startSec: plan.windowStartSec, endSec: plan.windowEndSec });+ // Verify the cut before anything is paid for: the provider rejects short+ // audio and silently clips long audio, and both would break the edit points.+ const slicedSec = await probeVideoDuration(audioFilePath);+ if (slicedSec == null || slicedSec < capability.minAudioSec || slicedSec > capability.maxAudioSec) {+ await unlink(audioFilePath).catch(() => {});+ throw refuse(+ `The sliced performance audio is ${slicedSec == null ? 'unreadable' : `${slicedSec.toFixed(3)}s`} — outside ${capability.label}'s ${capability.minAudioSec}–${capability.maxAudioSec}s window.`,+ 'MUSIC_VIDEO_PERFORMANCE_AUDIO_INVALID',+ 500,+ );+ }++ const shotInstruction = {+ version: SHOT_INSTRUCTION_VERSION,+ shotMode: 'performance',+ createdAt: new Date().toISOString(),+ audio: {+ source: project.trackId ? 'track' : 'upload',+ sha256: audioSha256,+ songDurationSec,+ },+ songInterval: { startSec: scene.startSec, endSec: scene.endSec },+ audioWindow: { startSec: plan.windowStartSec, endSec: plan.windowEndSec, durationSec: plan.windowSec },+ edit: { inSec: plan.editInSec, outSec: plan.editOutSec, targetSec: plan.spanSec },+ cues: clipRelativeCues(project.lyricCues, plan.windowStartSec, plan.windowEndSec),+ referenceImageId: typeof sourceImagePath === 'string' ? basename(sourceImagePath) : null,+ performance: (scene.visualIntent || scene.prompt || '').slice(0, 2000),+ capability: {+ provider: capability.provider,+ modelId: capability.modelId,+ minAudioSec: capability.minAudioSec,+ maxAudioSec: capability.maxAudioSec,+ transcription: capability.transcription,+ },+ // The provider's output length follows the submitted audio.+ generatedCoverageSec: plan.windowSec,+ };+ return {+ audioFilePath,+ shotInstruction,+ modelId: capability.modelId,+ enableTranscription: capability.transcription === true,+ };+}diff --git a/server/services/musicVideo/performanceShot.test.js b/server/services/musicVideo/performanceShot.test.jsnew file mode 100644index 0000000000..81cc2b6138--- /dev/null+++ b/server/services/musicVideo/performanceShot.test.js@@ -0,0 +1,229 @@+/**+ * Music Video performance shots (#8977), end to end against real ffmpeg and a+ * synthetic song: submission gate → exact song slice → fal lip-sync payload →+ * measured delivery → edit-point trim on the final timeline. The provider is a+ * stubbed `fetch`; nothing leaves the machine and no money is spent. Mocked+ * durations cannot certify lip-sync QUALITY — this pins the timebase contract.+ */+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { execFileSync } from 'node:child_process';+import { existsSync } from 'node:fs';+import { mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';+import { join } from 'node:path';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';++vi.mock('../../lib/fileUtils.js', async (importOriginal) => makePathsProxy(await importOriginal(), {+ dataRoot: () => lazyTempDataRoot('portos-mv-performance-'),+}));+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 () => ({})) }));+// 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 () => {+ const history = await import('../videoGen/history.js');+ return { loadHistory: history.loadHistory, mutateVideoHistory: history.mutateVideoHistory };+});++const { PATHS } = await import('../../lib/fileUtils.js');+const { findFfmpeg, probeVideoStreamInfo } = await import('../../lib/ffmpeg.js');+const { preparePerformanceShot } = await import('./performanceShot.js');+const fal = await import('../videoGen/fal.js');+const { videoGenEvents } = await import('../videoGen/events.js');+const { buildMusicVideoFfmpegArgs, beatSnapClips, resolveSceneClips } = await import('./render.js');+const { appendSceneTakes } = await import('./takes.js');++const ffmpeg = await findFfmpeg();+const RATE = 48000;+const SONG_SEC = 30;+// One full-scale impulse marks an exact song instant (sample 960000 = 20.000s).+const MARKER_SEC = 20;++// A mono 16-bit PCM WAV built sample-by-sample, so the marker's position is+// known exactly without trusting any encoder.+function songWav() {+ 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);+ buf.writeInt16LE(30000, 44 + MARKER_SEC * RATE * 2);+ return buf;+}++// PCM samples of a WAV, located by its `data` chunk (ffmpeg may add a LIST chunk).+function pcm(wav) {+ let at = 12;+ while (at < wav.length) {+ const id = wav.toString('ascii', at, at + 4);+ const size = wav.readUInt32LE(at + 4);+ if (id === 'data') return wav.subarray(at + 8, at + 8 + size);+ at += 8 + size + (size % 2);+ }+ throw new Error('no data chunk');+}++const scene = (over = {}) => ({+ sceneId: 'mvs-1', order: 0, shotMode: 'performance', startSec: 20, endSec: 21.5, beatAligned: true,+ prompt: 'singer at the mic', visualIntent: 'sings the held note', referenceImageId: 'frame.png', takes: [], ...over,+});+const project = (sceneOver) => ({+ id: 'mv-1',+ uploadedAudioFilename: 'song.wav',+ lyricCues: [+ { id: 'c1', text: 'hold on', startSec: 19, endSec: 20.5 },+ { id: 'c2', text: 'later line', startSec: 40, endSec: 42 },+ { id: 'c3', text: 'untimed', startSec: null, endSec: null },+ ],+ scenes: [scene(sceneOver)],+});++const jsonResponse = (body) => ({ ok: true, status: 200, json: async () => body });+const waitForTerminal = (jobId) => new Promise((resolve) => {+ const on = (type) => (event) => { if (event.generationId === jobId) resolve({ type, ...event }); };+ videoGenEvents.on('completed', on('completed'));+ videoGenEvents.on('failed', on('failed'));+});++beforeEach(async () => {+ vi.unstubAllGlobals();+ videoGenEvents.removeAllListeners();+ getProject.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 });+ await writeFile(join(PATHS.music, 'song.wav'), songWav());+});++afterAll(() => cleanupTempDataRoots());++describe.skipIf(!ffmpeg)('music-video performance shot through the fal lip-sync lane (#8977)', () => {+ it('slices the exact song window, submits it once, and trims the delivered take at its edit points', async () => {+ getProject.mockResolvedValue(project());+ const prepared = await preparePerformanceShot({+ musicVideo: { projectId: 'mv-1', sceneId: 'mvs-1' }, backend: 'fal', sourceImagePath: join(PATHS.images, 'frame.png'), mode: 'image',+ });++ // A 1.5s shot is padded to the 5s provider minimum (+ margin), centered:+ // window 18.225–23.275, shot at clip time 1.775–3.275.+ const { shotInstruction: si } = prepared;+ 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.audio.sha256).toMatch(/^[0-9a-f]{64}$/);+ expect(si).toMatchObject({ referenceImageId: 'frame.png', performance: 'sings the held note', generatedCoverageSec: 5.05 });+ expect(si.capability).toMatchObject({ provider: 'fal', minAudioSec: 5, maxAudioSec: 14.8 });++ // Sample-exact window content: exactly 5.05s of samples, the song marker at+ // the in-point, and the slice staged where the queue will clean it up.+ expect(prepared.audioFilePath.startsWith(PATHS.uploads)).toBe(true);+ const sliceWav = await readFile(prepared.audioFilePath);+ const samples = pcm(sliceWav);+ expect(samples.length / 2).toBe(Math.round(5.05 * RATE));+ let peak = 0;+ for (let i = 1; i < samples.length / 2; i++) if (samples.readInt16LE(i * 2) > samples.readInt16LE(peak * 2)) peak = i;+ expect(peak).toBe(Math.round((MARKER_SEC - 18.225) * RATE));++ // Generation payload: the reference frame plus these exact bytes, with no+ // prompt/duration a lip-sync route would contradict. Submitted exactly once.+ await mkdir(PATHS.images, { recursive: true });+ await writeFile(join(PATHS.images, 'frame.png'), Buffer.from('89504e470d0a1a0a', 'hex'));+ const deliveredPath = join(PATHS.data, 'delivered.mp4');+ execFileSync(ffmpeg, ['-v', 'error', '-f', 'lavfi', '-i', 'color=red:s=64x64:r=24:d=5.05', '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-y', deliveredPath]);+ const delivered = await readFile(deliveredPath);+ const posts = [];+ vi.stubGlobal('fetch', vi.fn(async (url, opts) => {+ if (opts?.method === 'POST') {+ posts.push({ url, body: JSON.parse(opts.body) });+ return jsonResponse({ request_id: 'r1', status_url: 'https://queue.fal.run/s', response_url: 'https://queue.fal.run/r' });+ }+ if (url === 'https://queue.fal.run/s') return jsonResponse({ status: 'COMPLETED' });+ if (url === 'https://queue.fal.run/r') return jsonResponse({ video: { url: 'https://cdn.example.com/out.mp4' } });+ if (url === 'https://cdn.example.com/out.mp4') return { ok: true, status: 200, arrayBuffer: async () => Uint8Array.from(delivered).buffer };+ throw new Error(`unexpected fetch: ${url}`);+ }));+ const job = await fal.generateVideo({+ apiKey: 'test-key', modelId: prepared.modelId, prompt: 'singer at the mic',+ sourceImagePath: join(PATHS.images, 'frame.png'), audioFilePath: prepared.audioFilePath,+ lipSync: { enableTranscription: prepared.enableTranscription }, shotInstruction: si,+ });+ expect(await waitForTerminal(job.jobId)).toMatchObject({ type: 'completed' });+ expect(posts).toHaveLength(1);+ expect(posts[0].url).toBe('https://queue.fal.run/minimax/h3-max/lip-sync/image-to-video');+ expect(Object.keys(posts[0].body).sort()).toEqual(['audio_url', 'enable_transcription', 'image_url']);+ expect(Buffer.from(posts[0].body.audio_url.replace(/^data:audio\/wav;base64,/, ''), 'base64').equals(sliceWav)).toBe(true);++ // Final timeline: the take lands with its instruction, the renderer reads+ // the measured clip, and the edit trims exactly the shot's frames.+ const { scene: withTake } = appendSceneTakes(project({ referenceImageId: 'frame.png' }), 'mvs-1', [{+ kind: 'video', assetId: job.jobId, source: 'generated', shotInstruction: si,+ }]);+ const [clip] = beatSnapClips(await resolveSceneClips({ scenes: [withTake] }), [], { scenes: [withTake] });+ expect(clip).toMatchObject({ inSec: 1.775, loop: false });+ const outPath = join(PATHS.data, 'final.mp4');+ const { args } = buildMusicVideoFfmpegArgs([clip], join(PATHS.music, 'song.wav'), outPath);+ execFileSync(ffmpeg, ['-v', 'error', ...args.filter((a, i) => a !== '-progress' && args[i - 1] !== '-progress')]);+ const out = await probeVideoStreamInfo(outPath);+ // 1.5s at 24fps = 36 frames; covered within one frame.+ const frames = Number(execFileSync(ffmpeg.replace(/ffmpeg(\.exe)?$/, 'ffprobe$1'), [+ '-v', 'error', '-count_frames', '-select_streams', 'v:0', '-show_entries', 'stream=nb_read_frames', '-of', 'csv=p=0', outPath,+ ]).toString().trim());+ expect(out.fps).toBe(24);+ expect(Math.abs(frames - 36)).toBeLessThanOrEqual(1);+ }, 60_000);++ it('uses the full span of a long shot and stays under the provider maximum', async () => {+ getProject.mockResolvedValue(project({ startSec: 10, endSec: 24.7 }));+ const { shotInstruction: si } = await preparePerformanceShot({+ musicVideo: { projectId: 'mv-1', sceneId: 'mvs-1' }, backend: 'fal', sourceImagePath: '/x/frame.png', mode: 'image',+ });+ expect(si.audioWindow).toEqual({ startSec: 10, endSec: 24.7, durationSec: 14.7 });+ expect(si.edit.inSec).toBe(0);+ });++ it('refuses a shot longer than the provider synchronizes instead of letting it truncate', async () => {+ getProject.mockResolvedValue(project({ startSec: 5, endSec: 20 }));+ await expect(preparePerformanceShot({+ musicVideo: { projectId: 'mv-1', sceneId: 'mvs-1' }, backend: 'fal', sourceImagePath: '/x/frame.png',+ })).rejects.toMatchObject({ status: 400, code: 'MUSIC_VIDEO_PERFORMANCE_TOO_LONG' });+ });++ it('refuses a performance shot on a lane without source-audio conditioning, before slicing anything', async () => {+ getProject.mockResolvedValue(project());+ for (const backend of ['grok', 'local']) {+ await expect(preparePerformanceShot({+ musicVideo: { projectId: 'mv-1', sceneId: 'mvs-1' }, backend, sourceImagePath: '/x/frame.png',+ })).rejects.toMatchObject({ status: 400, code: 'MUSIC_VIDEO_PERFORMANCE_UNSUPPORTED', message: expect.stringMatching(backend === 'grok' ? /cutaway-only/ : /cannot lip-sync/) });+ }+ const staged = existsSync(PATHS.uploads) ? (await readdir(PATHS.uploads)).filter((f) => f.startsWith('mv-performance-')) : [];+ expect(staged).toEqual([]);+ });++ it('leaves a cutaway scene untouched', async () => {+ getProject.mockResolvedValue(project({ shotMode: undefined }));+ await expect(preparePerformanceShot({+ musicVideo: { projectId: 'mv-1', sceneId: 'mvs-1' }, backend: 'grok', sourceImagePath: '/x/frame.png',+ })).resolves.toBeNull();+ });++ it('never submits a paid request when cancelled while its inputs are still being read', async () => {+ getProject.mockResolvedValue(project());+ const prepared = await preparePerformanceShot({+ musicVideo: { projectId: 'mv-1', sceneId: 'mvs-1' }, backend: 'fal', sourceImagePath: join(PATHS.images, 'frame.png'),+ });+ await mkdir(PATHS.images, { recursive: true });+ await writeFile(join(PATHS.images, 'frame.png'), Buffer.from('89504e470d0a1a0a', 'hex'));+ const fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);+ const job = await fal.generateVideo({+ apiKey: 'test-key', modelId: prepared.modelId, prompt: 'x', sourceImagePath: join(PATHS.images, 'frame.png'),+ audioFilePath: prepared.audioFilePath, lipSync: { enableTranscription: true },+ });+ const terminal = waitForTerminal(job.jobId);+ expect(fal.cancel(job.jobId)).toBe(true);+ expect(await terminal).toMatchObject({ type: 'failed' });+ expect(fetchMock).not.toHaveBeenCalled();+ });+});diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.jsindex fbc0fd078a..a578632f41 100644--- a/server/services/musicVideo/projectsLogic.js+++ b/server/services/musicVideo/projectsLogic.js@@ -315,6 +315,9 @@ function buildScene(input, { order }) {stillMove: input.stillMove ?? 'hold',cardText: input.cardText ?? null,cardColor: input.cardColor ?? null,+ // #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',referenceImageId: null,videoHistoryId: null,// #8965 — immutable candidate takes; the two slot fields above are thediff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.jsindex a90747d8b4..4b070275e0 100644--- a/server/services/musicVideo/render.js+++ b/server/services/musicVideo/render.js@@ -28,7 +28,7 @@ import { randomUUID } from 'crypto';import { ensureDir, PATHS } from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';-import { findFfmpeg, safeUnder, generateThumbnail, probeVideoDuration } from '../../lib/ffmpeg.js';+import { findFfmpeg, safeUnder, generateThumbnail, probeVideoDuration, probeVideoGeometry } from '../../lib/ffmpeg.js';import { safeChildProcessOptions } from '../../lib/processEnv.js';import { killWithEscalation } from '../../lib/killWithEscalation.js';import { attachFfmpegRenderGuard } from '../../lib/ffmpegRenderGuard.js';@@ -70,6 +70,18 @@ export const attachRenderSseClient = (jobId, res) => attachSse(jobs, jobId, res)const sceneLoops = (scene) => scene?.loop !== false;const round3 = (n) => Math.round(n * 1000) / 1000;+// #8977: a performance take is placed by the immutable shot instruction it was+// generated with — its footage starts `edit.inSec` into the clip (the audio+// window was padded to the provider minimum) and ends at `edit.outSec`. It+// never loops: repeating a sung take would desync the mouth from the song.+function performanceEdit(scene) {+ const take = (Array.isArray(scene.takes) ? scene.takes : [])+ .find((t) => t?.kind === 'video' && t.assetId === scene.videoHistoryId);+ const instruction = take?.shotInstruction;+ const edit = instruction?.edit;+ if (instruction?.shotMode !== 'performance' || !Number.isFinite(edit?.inSec) || !Number.isFinite(edit?.outSec)) return null;+ return edit.outSec > edit.inSec && edit.inSec >= 0 ? edit : null;+}// A non-looping shot may run this much past its source clip; the gap holds the// final frame (tpad) rather than repeating footage. Longer shortfalls block the@@ -185,25 +197,34 @@ export async function resolveSceneClips(project, { layered = false } = {}) {const entry = historyMap.get(scene.videoHistoryId);const videoPath = entry && entry.filename ? safeUnder(PATHS.videos, entry.filename) : null;if (!entry || !videoPath || !existsSync(videoPath)) { missing.push(scene.videoHistoryId); continue; }- const duration = entry.numFrames && entry.fps ? entry.numFrames / entry.fps : null;+ // Hosted renders (Grok/fal/reactor) record no frame count or dimensions;+ // measure the file itself rather than reject a clip that exists (#8977).+ const measured = entry.numFrames && entry.fps && entry.width && entry.height+ ? entry+ : { ...entry, ...(await probeVideoGeometry(videoPath)) };+ const duration = measured.numFrames && measured.fps ? measured.numFrames / measured.fps : null;if (!duration || duration <= 0) { missing.push(scene.videoHistoryId); continue; }// A dimensionless history entry would make buildMusicVideoFfmpegArgs emit// `scale=undefined:undefined` (opaque ffmpeg failure); treat it as a missing// clip so the caller gets the clean MISSING_CLIPS 4xx, matching the duration guard.- if (!entry.width || entry.width <= 0 || !entry.height || entry.height <= 0) { missing.push(scene.videoHistoryId); continue; }+ if (!measured.width || measured.width <= 0 || !measured.height || measured.height <= 0) { missing.push(scene.videoHistoryId); continue; }+ const edit = performanceEdit(scene);+ const inSec = edit ? Math.min(edit.inSec, duration) : 0;+ const outSec = edit ? Math.min(edit.outSec, duration) : duration;clips.push({sceneId: scene.sceneId,videoPath,- width: entry.width,- height: entry.height,- fps: entry.fps || 24,- duration,- // The native source length survives the snap below (which rewrites- // `duration` to the rendered span) so coverage can be judged against it.- sourceSec: duration,- loop: sceneLoops(scene),- inSec: 0,- outSec: duration,+ width: measured.width,+ height: measured.height,+ fps: measured.fps || 24,+ duration: outSec - inSec,+ // The playable source length (from the in-point on) survives the snap+ // below (which rewrites `duration` to the rendered span) so coverage can+ // be judged against it.+ sourceSec: duration - inSec,+ loop: edit ? false : sceneLoops(scene),+ inSec,+ outSec,});}if (missing.length > 0) {@@ -264,9 +285,12 @@ export function beatSnapClips(clips, beats, { toleranceSec = 0.12, minClipSec =// looping input, so the authored timeline duration is allowed to exceed// the source duration instead of silently truncating the final song. A// non-looping shot that does so is refused before render (#8964).- const outSec = Math.max(minClipSec, scene.endSec - scene.startSec);- running += outSec;- return { ...clip, inSec: 0, outSec, duration: outSec };+ // A performance clip (#8977) keeps its edit in-point; every other clip+ // starts at 0 as before.+ const inSec = clip.inSec || 0;+ const spanSec = Math.max(minClipSec, scene.endSec - scene.startSec);+ running += spanSec;+ return { ...clip, inSec, outSec: inSec + spanSec, duration: spanSec };}if (grid.length === 0) {running += clip.duration;@@ -279,16 +303,17 @@ export function beatSnapClips(clips, beats, { toleranceSec = 0.12, minClipSec =if (beat > naturalEnd) break;best = beat;}+ const inSec = clip.inSec || 0;let outSec = clip.outSec;if (best != null&& (naturalEnd - best) <= toleranceSec&& (best - running) >= minClipSec) {- outSec = best - running; // trim relative to the clip's own start (inSec=0)+ outSec = inSec + (best - running); // trim relative to the clip's in-pointrunning = best;} else {running = naturalEnd;}- return { ...clip, inSec: 0, outSec, duration: outSec };+ return { ...clip, inSec, outSec, duration: outSec - inSec };});}diff --git a/server/services/musicVideo/render.test.js b/server/services/musicVideo/render.test.jsindex 9cb0765f76..20d9db7f14 100644--- a/server/services/musicVideo/render.test.js+++ b/server/services/musicVideo/render.test.js@@ -8,6 +8,7 @@ vi.mock('../../lib/ffmpeg.js', () => ({safeUnder: (root, name) => (name ? `${root}/${name}` : null),generateThumbnail: vi.fn(async () => 'thumb.jpg'),probeVideoDuration: vi.fn(async () => 30),+ probeVideoGeometry: vi.fn(async () => null),}));vi.mock('../videoGen/local.js', () => ({ loadHistory: vi.fn(), saveHistory: vi.fn(async () => {}) }));vi.mock('../tracks/index.js', () => ({ getTrack: vi.fn() }));@@ -21,7 +22,7 @@ import {resolveMasterAudioPath,renderMusicVideo,} from './render.js';-import { findFfmpeg } from '../../lib/ffmpeg.js';+import { findFfmpeg, probeVideoGeometry } from '../../lib/ffmpeg.js';import { loadHistory } from '../videoGen/local.js';import { getTrack } from '../tracks/index.js';import { getProject } from './projects.js';@@ -200,6 +201,37 @@ describe('resolveSceneClips', () => {await expect(resolveSceneClips({ scenes: [{ sceneId: 's1', order: 0, videoHistoryId: 'h1' }] })).rejects.toMatchObject({ status: 404, code: 'MISSING_CLIPS' });});++ it('measures a hosted clip whose history entry records no frame count (#8977)', async () => {+ // Grok/fal entries carry only the requested duration; the renderer probes the file.+ loadHistory.mockResolvedValue([{ id: 'h1', filename: 'a.mp4', modelId: 'grok', duration: 6 }]);+ probeVideoGeometry.mockResolvedValueOnce({ width: 1280, height: 720, fps: 24, numFrames: 145, durationSec: 6.04 });+ const [c] = await resolveSceneClips({ scenes: [{ sceneId: 's1', order: 0, videoHistoryId: 'h1' }] });+ expect(c).toMatchObject({ width: 1280, height: 720, inSec: 0 });+ expect(c.duration).toBeCloseTo(145 / 24, 6);+ });++ it('places a performance take at its edit in-point and never loops it (#8977)', async () => {+ // A 1.5s shot at song 20.0–21.5 generated from a padded 5.05s window+ // starting at 18.225: the shot occupies clip time 1.775–3.275.+ loadHistory.mockResolvedValue([{ id: 'h1', filename: 'a.mp4', width: 768, height: 512, fps: 24, numFrames: 121 }]);+ const scene = {+ sceneId: 's1', order: 0, videoHistoryId: 'h1', loop: true, shotMode: 'performance',+ startSec: 20, endSec: 21.5, beatAligned: true,+ takes: [{ takeId: 't1', kind: 'video', assetId: 'h1', shotInstruction: { shotMode: 'performance', edit: { inSec: 1.775, outSec: 3.275, targetSec: 1.5 } } }],+ };+ const [c] = await resolveSceneClips({ scenes: [scene] });+ expect(c).toMatchObject({ inSec: 1.775, outSec: 3.275, loop: false });+ // The authored span keeps the in-point through the beat-aligned snap, so+ // the ffmpeg trim cuts the exact sung frames.+ const [snapped] = beatSnapClips([c], [], { scenes: [scene] });+ expect(snapped.inSec).toBe(1.775);+ expect(snapped.outSec).toBeCloseTo(3.275, 9);+ const { args } = buildMusicVideoFfmpegArgs([snapped], '/music/song.wav', '/o.mp4');+ const fc = args[args.indexOf('-filter_complex') + 1];+ expect(fc).toContain('trim=start=1.775:end=3.275');+ expect(args).not.toContain('-stream_loop');+ });});describe('renderMusicVideo mutex (#1760 re-entrancy guard)', () => {diff --git a/server/services/musicVideo/takes.js b/server/services/musicVideo/takes.jsindex 2b681a9d04..d0a8049994 100644--- a/server/services/musicVideo/takes.js+++ b/server/services/musicVideo/takes.js@@ -39,7 +39,7 @@ const clip = (v, max) => (isNonBlankStr(v) ? trimTo(v, max) : null);// A basename only — an imported file's name is provenance, never a path.const takeOriginalName = (name) => (isNonBlankStr(name) ? clip(name.split(/[\\/]/).pop(), 200) : null);-function buildTake({ kind, assetId, source, provider = null, jobId = null, prompt = null, sourceImageId = null, originalName = null, now }) {+function buildTake({ kind, assetId, source, provider = null, jobId = null, prompt = null, sourceImageId = null, originalName = null, shotInstruction = null, now }) {return {takeId: `mvt-${randomUUID()}`,kind,@@ -53,6 +53,10 @@ function buildTake({ kind, assetId, source, provider = null, jobId = null, prompstatus: 'candidate',note: null,createdAt: now,+ // #8977: the immutable record of what a performance take was generated+ // against (audio revision, song interval, edit in/out, cues, capability).+ // Present only on takes that carry one, so other takes keep their shape.+ ...(shotInstruction && typeof shotInstruction === 'object' ? { shotInstruction: structuredClone(shotInstruction) } : {}),};}diff --git a/server/services/musicVideoSceneVideoHook.js b/server/services/musicVideoSceneVideoHook.jsindex 3a479c8fb4..05a5256b04 100644--- a/server/services/musicVideoSceneVideoHook.js+++ b/server/services/musicVideoSceneVideoHook.js@@ -71,6 +71,10 @@ const hook = createMediaJobImageHook({// The frame this clip was generated from — a basename only; job params// carry the server's absolute path, which never belongs on a synced record.sourceImageId: typeof job.params?.sourceImagePath === 'string' ? basename(job.params.sourceImagePath) : null,+ // #8977: a performance take keeps the immutable record of the song slice,+ // edit in/out points and capability it was generated against — the+ // renderer places the take by it, so a later retime can't misalign lips.+ shotInstruction: job.params?.shotInstruction ?? null,}]),onAttached: ({ projectId, sceneId, videoHistoryId }, { scene, appended }) => {musicVideoEvents.emit('scene-video', {diff --git a/server/services/videoGen/fal.js b/server/services/videoGen/fal.jsindex 52e0d11a27..ccd851582c 100644--- a/server/services/videoGen/fal.js+++ b/server/services/videoGen/fal.js@@ -26,6 +26,7 @@ import { anyAbortSignal } from '../../lib/requestAbort.js';import { describeFetchError } from '../../lib/fetchErrorChain.js';import { fetchWithTimeout } from '../../lib/fetchWithTimeout.js';import { detectImageFormat } from '../../lib/mimeTypes.js';+import { probeVideoGeometry } from '../../lib/ffmpeg.js';import { attachSseClient as attachSse, closeJobAfterDelay, createJobFailureFinalizer } from '../../lib/sseUtils.js';import { videoGenEvents } from './events.js';import { finalizeGeneratedVideo, emitCloudRenderStatus, CLOUD_RENDER_PHASE } from './generateVideoHelpers.js';@@ -143,6 +144,18 @@ async function toDataUri(imagePath) {return `data:${mime};base64,${buf.toString('base64')}`;}+// Source-audio lip-sync (#8977, fal's MiniMax H3 lip-sync route): the request+// is the reference frame plus the exact song slice. The route takes no prompt,+// duration or aspect ratio — its output length follows the submitted audio, and+// the frame's own aspect ratio carries through.+function buildLipSyncRequestBody({ imageDataUri, audioDataUri, enableTranscription }) {+ return {+ image_url: imageDataUri,+ audio_url: audioDataUri,+ ...(enableTranscription ? { enable_transcription: true } : {}),+ };+}+function buildRequestBody({ prompt, negativePrompt, duration, aspectRatio, imageDataUri }) {// fal.ai's queue REST API has no dedicated negative-prompt field for these// models — fold it into the prompt as an "Avoid:" clause, same fallback@@ -216,6 +229,7 @@ export async function generateVideo({apiKey: providedApiKey, settings, modelId: requestedModelId,prompt = '', negativePrompt, duration, aspectRatio, width, height,sourceImagePath = null, jobId: providedJobId = null,+ audioFilePath = null, lipSync = null, shotInstruction = null,}) {await ensureDir(PATHS.videos);const renderStartedAtMs = Date.now();@@ -223,6 +237,11 @@ export async function generateVideo({if (!prompt?.trim()) {throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });}+ // A lip-sync render conditions a reference frame on source audio; either+ // input alone is not a request this route can honor.+ if (audioFilePath && !sourceImagePath) {+ throw new ServerError('A fal.ai lip-sync render needs a reference frame', { status: 400, code: 'VALIDATION_ERROR' });+ }// The queue only persists the resolved provider CONFIG a job needs (mirrors// grokPath on the grok lane) — never a secret — so the key is re-resolved// from live settings here, exactly like mediaJobQueue's own pythonPath@@ -253,6 +272,8 @@ export async function generateVideo({filename,createdAt: new Date().toISOString(),mode: sourceImagePath ? 'image' : 'text',+ ...(audioFilePath ? { lipSync: true } : {}),+ ...(shotInstruction?.audioWindow ? { audioWindow: shotInstruction.audioWindow } : {}),};const job = { ...meta, clients: [], status: 'running', renderStartedAtMs };jobs.set(jobId, job);@@ -262,7 +283,10 @@ export async function generateVideo({activeJobs.set(jobId, { ...meta, generationId: jobId, totalSteps: 1, step: 0, progress: 0 });emitCloudRenderStatus(job, jobId, CLOUD_RENDER_PHASE.SUBMIT, 'Submitting to fal.ai…');- runFalVideo(job, jobId, { apiKey, modelId, prompt, negativePrompt, duration, aspectRatio: effectiveAspectRatio, sourceImagePath, outputPath, filename, meta })+ runFalVideo(job, jobId, {+ apiKey, modelId, prompt, negativePrompt, duration, aspectRatio: effectiveAspectRatio, sourceImagePath, outputPath, filename, meta,+ audioFilePath, enableTranscription: lipSync?.enableTranscription === true,+ }).catch((err) => {console.error(`❌ fal video run failed [${jobId.slice(0, 8)}]: ${err?.message}`);});@@ -274,7 +298,10 @@ export async function generateVideo({};}-async function runFalVideo(job, jobId, { apiKey, modelId, prompt, negativePrompt, duration, aspectRatio, sourceImagePath, outputPath, filename, meta }) {+async function runFalVideo(job, jobId, {+ apiKey, modelId, prompt, negativePrompt, duration, aspectRatio, sourceImagePath, outputPath, filename, meta,+ audioFilePath = null, enableTranscription = false,+}) {const entry = {apiKey, controller: new AbortController(), aborted: false, cancelUrl: null, canceledRemote: false, remoteTerminal: false,};@@ -282,7 +309,16 @@ async function runFalVideo(job, jobId, { apiKey, modelId, prompt, negativePromptconst deadline = Date.now() + FAL_RENDER_TIMEOUT_MS;try {const imageDataUri = sourceImagePath ? await toDataUri(sourceImagePath) : null;- const body = buildRequestBody({ prompt, negativePrompt, duration, aspectRatio, imageDataUri });+ const body = audioFilePath+ ? buildLipSyncRequestBody({+ imageDataUri,+ audioDataUri: `data:audio/wav;base64,${(await readFile(audioFilePath)).toString('base64')}`,+ enableTranscription,+ })+ : buildRequestBody({ prompt, negativePrompt, duration, aspectRatio, imageDataUri });+ // Cancelled while the inputs were being read: nothing was submitted, so+ // there is nothing to pay for or cancel remotely.+ if (entry.aborted) return finalizeCanceled(job, jobId);const submitted = await submitFalJob({ apiKey, modelId, body });entry.cancelUrl = submitted.cancel_url || `${FAL_QUEUE_BASE}/${modelId}/requests/${submitted.request_id}/cancel`;const statusUrl = submitted.status_url || `${FAL_QUEUE_BASE}/${modelId}/requests/${submitted.request_id}/status`;@@ -344,9 +380,17 @@ async function runFalVideo(job, jobId, { apiKey, modelId, prompt, negativePromptreturn finalizeCanceled(job, jobId);}+ // Record what the provider actually delivered: fal reports no frame count,+ // and the Music Video renderer trims every clip by numFrames/fps — the+ // measured length is also what a performance take's edit points index.+ const measured = (await probeVideoGeometry(outputPath)) || {};+ const expectedSec = meta.audioWindow?.durationSec;+ if (expectedSec && measured.durationSec && measured.durationSec + 0.1 < expectedSec) {+ console.warn(`⚠️ fal lip-sync [${jobId.slice(0, 8)}] delivered ${measured.durationSec.toFixed(2)}s for a ${expectedSec.toFixed(2)}s audio window`);+ }activeRequests.delete(jobId);activeJobs.delete(jobId);- await finalizeGeneratedVideo({ job, jobId, outputPath, filename, meta, actualSeed: null, mutateHistory: mutateVideoHistory });+ await finalizeGeneratedVideo({ job, jobId, outputPath, filename, meta: { ...meta, ...measured }, actualSeed: null, mutateHistory: mutateVideoHistory });closeJobAfterDelay(jobs, jobId);} catch (err) {// Best-effort: an unanticipated throw (e.g. from fetchFalResult or the@@ -380,5 +424,6 @@ const finalizeCanceled = finalizeJobFailure.canceled;// Test-only handles.export const _internals = {buildRequestBody,+ buildLipSyncRequestBody,toDataUri,};diff --git a/server/services/videoGen/submitJob.js b/server/services/videoGen/submitJob.jsindex 2394a53f8b..ba925d8bbc 100644--- a/server/services/videoGen/submitJob.js+++ b/server/services/videoGen/submitJob.js@@ -4,6 +4,7 @@* owns every subsequent orchestration and rollback decision.*/+import { unlink } from 'fs/promises';import { ServerError } from '../../lib/errorHandler.js';import { buildFederatedMediaRequest } from '../../lib/federatedMediaRequest.js';import { asFableLoomRenderSettings } from '../../lib/fableLoomProduction.js';@@ -22,6 +23,7 @@ import {import { VIDEO_GEN_MODE } from './modes.js';import { HOSTED_VIDEO_SUBMISSIONS } from './hostedSubmission.js';import { enqueueJob } from '../mediaJobQueue/index.js';+import { preparePerformanceShot } from '../musicVideo/performanceShot.js';import {cleanupMultipartTemp,prepareVideoGenParams,@@ -160,8 +162,37 @@ const submitValidatedVideoGenJob = async (body, uploads) => {}}+ // Music Video performance shots (#8977): a lip-synced scene renders only on a+ // verified source-audio provider, from the exact slice of the master song.+ // A cutaway scene (or any non-music-video render) gets null and is untouched;+ // a performance scene on an incapable backend is refused here rather than+ // rendered as an unrelated voice or a silent cutaway.+ const performance = body.musicVideo+ ? await preparePerformanceShot({+ musicVideo: body.musicVideo,+ backend,+ sourceImagePath: prepared.sourceImagePath,+ mode: body.mode,+ }).catch(async (error) => {+ await cleanupStaged();+ throw error;+ })+ : null;+ const performanceParams = performance ? {+ modelId: performance.modelId,+ // The output length follows the submitted audio window; a clip-length pin+ // would contradict it, so none is sent.+ duration: undefined,+ audioFilePath: performance.audioFilePath,+ lipSync: { enableTranscription: performance.enableTranscription },+ shotInstruction: performance.shotInstruction,+ } : null;+const enqueue = (params) => withStagedRollback(- cleanupStaged,+ async () => {+ if (performance) await unlink(performance.audioFilePath).catch(() => {});+ await cleanupStaged();+ },() => enqueueJob({ kind: 'video', params }),);@@ -180,6 +211,7 @@ const submitValidatedVideoGenJob = async (body, uploads) => {...(body.fableLoom ? { fableLoom: body.fableLoom } : {}),...(body.visualConditioning ? { visualConditioning: body.visualConditioning } : {}),...hosted.buildParams(body, prepared),+ ...performanceParams,});return {jobId,diff --git a/server/services/videoGen/submitJob.test.js b/server/services/videoGen/submitJob.test.jsindex 6fe03bc287..cbf39c4a6f 100644--- a/server/services/videoGen/submitJob.test.js+++ b/server/services/videoGen/submitJob.test.js@@ -10,6 +10,7 @@ const mocks = vi.hoisted(() => ({getLoom: vi.fn(async () => null),prepareRemoteMediaJob: vi.fn(),prepareVideoGenParams: vi.fn(),+ preparePerformanceShot: vi.fn(async () => null),}));vi.mock('../../lib/federatedMediaRequest.js', () => ({@@ -27,6 +28,7 @@ vi.mock('../fableLoom/visualConditioning.js', () => ({fableLoomVideoCapabilities: mocks.fableLoomVideoCapabilities,}));vi.mock('../mediaJobQueue/index.js', () => ({ enqueueJob: mocks.enqueueJob }));+vi.mock('../musicVideo/performanceShot.js', () => ({ preparePerformanceShot: mocks.preparePerformanceShot }));vi.mock('./prepareParams.js', async (importOriginal) => ({...await importOriginal(),cleanupMultipartTemp: mocks.cleanupMultipartTemp,@@ -63,6 +65,7 @@ describe('submitVideoGenJob', () => {beforeEach(() => {vi.clearAllMocks();mocks.enqueueJob.mockReturnValue(queued);+ mocks.preparePerformanceShot.mockResolvedValue(null);});it('submits a federated job with only the remote-media marker', async () => {@@ -185,4 +188,44 @@ describe('submitVideoGenJob', () => {}, {})).rejects.toBe(failure);expect(prepared.cleanupStaged).toHaveBeenCalledTimes(1);});++ describe('music-video performance shots (#8977)', () => {+ const musicVideo = { projectId: 'mv-1', sceneId: 'mvs-1' };+ const falPrepared = () => ({+ backend: 'fal', cleanupStaged: vi.fn(async () => {}),+ sourceImagePath: '/example/images/frame.png', uploadedTempPath: null,+ });++ it('enqueues the lip-sync model, song slice and shot instruction instead of a clip-length pin', async () => {+ const shotInstruction = { version: 1, shotMode: 'performance', edit: { inSec: 1.775, outSec: 3.275 } };+ mocks.prepareVideoGenParams.mockResolvedValue(falPrepared());+ mocks.preparePerformanceShot.mockResolvedValue({+ audioFilePath: '/example/uploads/mv-performance-1.wav', shotInstruction,+ modelId: 'minimax/h3-max/lip-sync/image-to-video', enableTranscription: true,+ });++ await submitVideoGenJob({ prompt: 'singer', backend: 'fal', falDuration: 6, musicVideo, mode: 'image' }, {});+ expect(mocks.preparePerformanceShot).toHaveBeenCalledWith({+ musicVideo, backend: 'fal', sourceImagePath: '/example/images/frame.png', mode: 'image',+ });+ const { params } = mocks.enqueueJob.mock.calls[0][0];+ expect(params).toMatchObject({+ mode: 'fal', modelId: 'minimax/h3-max/lip-sync/image-to-video',+ audioFilePath: '/example/uploads/mv-performance-1.wav',+ lipSync: { enableTranscription: true }, shotInstruction, musicVideo,+ });+ expect(params.duration).toBeUndefined();+ });++ it('refuses a performance shot the backend cannot render and releases what was staged', async () => {+ const prepared = { ...falPrepared(), backend: 'grok', grok: { grokPath: '/example/grok' } };+ mocks.prepareVideoGenParams.mockResolvedValue(prepared);+ const refusal = Object.assign(new Error('Grok video is cutaway-only'), { status: 400, code: 'MUSIC_VIDEO_PERFORMANCE_UNSUPPORTED' });+ mocks.preparePerformanceShot.mockRejectedValue(refusal);++ await expect(submitVideoGenJob({ prompt: 'singer', backend: 'grok', musicVideo }, {})).rejects.toBe(refusal);+ expect(prepared.cleanupStaged).toHaveBeenCalledTimes(1);+ expect(mocks.enqueueJob).not.toHaveBeenCalled();+ });+ });});