Skip to content

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

feat: split over-long music-video shots on lyric and phrase boundaries (#8977)

[._.]/ Adam Eivy567918df5697
diff --git a/client/src/components/musicVideo/SceneCard.jsx b/client/src/components/musicVideo/SceneCard.jsx
index 69343836af..f3f72ed789 100644
--- a/client/src/components/musicVideo/SceneCard.jsx
+++ b/client/src/components/musicVideo/SceneCard.jsx
@@ -1,5 +1,5 @@
import { useRef, useState } from 'react';
-import { Trash2, Activity, ArrowUp, ArrowDown, Image as ImageIcon, Video, Maximize2, AlertTriangle, ImagePlus, Clapperboard } from 'lucide-react';
+import { Trash2, Activity, ArrowUp, ArrowDown, Image as ImageIcon, Video, Maximize2, AlertTriangle, ImagePlus, Clapperboard, Scissors } from 'lucide-react';
import { formatDurationSec } from '../../utils/formatters.js';
import { useVideoFileSrc } from '../../hooks/useVideoFileSrc.js';
import SceneTakeStrip from './SceneTakeStrip.jsx';
@@ -9,7 +9,7 @@ import { MUSIC_VIDEO_VISUAL_LAYERS, sceneHasAuthoredSpan } from '../../lib/music
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,
+ grokCoverage, isPerformanceScene, performanceBlockedReason, performanceCapability, planPerformanceWindow, shotSplitLimit,
} from '../../lib/musicVideoShotTiming.js';
// The two timeline-bound scene fields rendered as identical number inputs.
@@ -43,6 +43,9 @@ const COVERAGE_TOLERANCE_SEC = 0.25;
* 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.
+ * A shot longer than that lane renders in one take (the lip-sync audio window,
+ * or Grok's longest clip) offers `onSplit(sceneId, backend)`, which cuts it
+ * into contiguous scenes at lyric pauses / phrase boundaries server-side.
*/
export default function SceneCard({
scene, index, isLast, generatingFrame, generatingVideo,
@@ -50,7 +53,7 @@ export default function SceneCard({
onMove, onDelete, onEditLocal, onSave,
onGenerateFrame, onGenerateVideo, onContinueVideo,
onOpenPreview, onSelectTake, onReviewTake, onImportTake, onImportClipTake, takeBusy = false, layered = false,
- lipSyncBackend = '', songDurationSec = null,
+ lipSyncBackend = '', songDurationSec = null, onSplit,
}) {
// Pause the inline clip before opening the lightbox so the user can't hear
// two desynced copies — MediaLightbox autoplays unmuted, and the thumb's
@@ -91,6 +94,8 @@ export default function SceneCard({
? (capability ? (plan.ok ? null : plan.message) : performanceBlockedReason(lipSyncBackend))
: null;
const grokPlan = !performance && lipSyncBackend === 'grok' && timedSpan != null ? grokCoverage(timedSpan) : null;
+ const splitLimit = layer === 'footage' ? shotSplitLimit(scene, lipSyncBackend) : null;
+ const canSplit = splitLimit != null && timedSpan != null && timedSpan > splitLimit + 1e-6;
const shotModeId = `mv-shot-mode-${scene.sceneId}`;
return (
<div className="bg-port-card border border-port-border rounded-lg p-3 space-y-2">
@@ -229,6 +234,13 @@ export default function SceneCard({
{grokPlan.needsSplit ? ` — ${grokPlan.uncoveredSec.toFixed(1)}s uncovered; split the scene rather than loop it` : ''}. Motion timing in the prompt is approximate.
</p>
)}
+ {canSplit && onSplit && (
+ <button type="button" onClick={() => onSplit(scene.sceneId, lipSyncBackend || null)}
+ className="inline-flex items-center gap-1 rounded bg-port-bg border border-port-border hover:bg-port-border/40 px-2 py-1 text-xs min-h-[44px] sm:min-h-0"
+ title={`Cut this ${timedSpan.toFixed(1)}s shot into scenes of at most ${splitLimit.toFixed(2)}s at lyric pauses or phrase boundaries — nothing is looped or stretched`}>
+ <Scissors size={13} /> Split on lyric boundaries
+ </button>
+ )}
{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" />
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 9899bafedb..4c689164d6 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -60,7 +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`. |
+| `musicVideoShotTiming.js` | Re-export of `server/lib/musicVideoShotTiming.js` (#8977) — shot modes, the verified source-audio lip-sync capability table, `performanceBlockedReason`, `planPerformanceWindow`, `grokCoverage`, `approximateMotionCues`, `shotSplitLimit` (when a scene offers a lyric-boundary split). 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/musicVideoShotTiming.js b/client/src/lib/musicVideoShotTiming.js
index ed2f28a0e6..e2457de01d 100644
--- a/client/src/lib/musicVideoShotTiming.js
+++ b/client/src/lib/musicVideoShotTiming.js
@@ -15,4 +15,5 @@ export {
performanceBlockedReason,
performanceCapability,
planPerformanceWindow,
+ shotSplitLimit,
} from '../../../server/lib/musicVideoShotTiming.js';
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index d6ce0fcbc6..c4e591b829 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -15,6 +15,7 @@ import {
addMusicVideoScene,
updateMusicVideoScene,
deleteMusicVideoScene,
+ splitMusicVideoScene,
reorderMusicVideoScenes,
importMusicVideoLyrics,
} from '../services/apiMusicVideo.js';
@@ -440,6 +441,17 @@ export default function MusicVideo() {
.catch((err) => toast.error(err?.message || 'Failed to delete scene'));
};
+ // #8977: split a shot its backend cannot render in one take on lyric/phrase
+ // boundaries. `backend` is the lane the card measured against.
+ const handleSplitScene = (sceneId, backend) => {
+ splitMusicVideoScene(selected.id, sceneId, backend, { silent: true })
+ .then(({ project, scenes }) => {
+ replaceProject(project);
+ toast.success(`Split into ${scenes.length} shots`);
+ })
+ .catch((err) => toast.error(err?.message || 'Failed to split scene'));
+ };
+
const moveScene = (idx, dir) => {
const scenes = selected.scenes || [];
const target = idx + dir;
@@ -753,6 +765,7 @@ export default function MusicVideo() {
canContinueShot={canContinueShot}
onMove={moveScene}
onDelete={handleDeleteScene}
+ onSplit={handleSplitScene}
onEditLocal={editSceneLocal}
onSave={saveScene}
onGenerateFrame={sceneMedia.generateFrame}
diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsx
index a7a41a6d55..3d48250063 100644
--- a/client/src/pages/MusicVideo.test.jsx
+++ b/client/src/pages/MusicVideo.test.jsx
@@ -51,6 +51,7 @@ vi.mock('../services/apiMusicVideo.js', () => ({
updateMusicVideoScene: vi.fn(),
deleteMusicVideoScene: vi.fn(),
reorderMusicVideoScenes: vi.fn(),
+ splitMusicVideoScene: vi.fn(),
importMusicVideoLyrics: vi.fn(),
renderMusicVideoProject: vi.fn(async () => ({ jobId: 'job-1' })),
musicVideoRenderEventsUrl: (jobId) => `/api/music-video/render/${jobId}/events`,
@@ -158,7 +159,7 @@ import MusicVideo from './MusicVideo.jsx';
import {
listMusicVideoProjects, createMusicVideoProject, cloneMusicVideoProject, renderMusicVideoProject, planMusicVideoProject, updateMusicVideoProject,
deleteMusicVideoProject, transcribeMusicVideoMidi, cancelMusicVideoRender,
- importMusicVideoLyrics, updateMusicVideoScene,
+ importMusicVideoLyrics, updateMusicVideoScene, splitMusicVideoScene,
selectMusicVideoSceneTake, reviewMusicVideoSceneTake, importMusicVideoHandoff,
addMusicVideoSceneTake, getMusicVideoHandoffBundle,
renderMusicVideoExcerpt, deleteMusicVideoExcerpt, addMusicVideoExcerptNote,
@@ -761,6 +762,24 @@ describe('MusicVideo project video renderer', () => {
));
});
+ it('offers a lyric-boundary split for a shot longer than one lip-sync take and applies the split board', async () => {
+ const longShot = { ...PERFORMANCE_SCENE, startSec: 2, endSec: 26 };
+ const project = { ...performanceProject({ backend: 'fal' }), scenes: [longShot] };
+ const pieces = [
+ { ...longShot, label: 'Verse · 1/2', endSec: 14 },
+ { ...longShot, sceneId: 's1b', order: 1, label: 'Verse · 2/2', startSec: 14, videoHistoryId: null },
+ ];
+ splitMusicVideoScene.mockResolvedValue({ project: { ...project, scenes: pieces }, scenes: pieces });
+ await openProject(project);
+
+ // The too-long refusal stays, now with a way out that never loops or stretches.
+ expect(await screen.findByText(/Split the scene on a lyric or phrase boundary/)).toBeTruthy();
+ fireEvent.click(await screen.findByRole('button', { name: /Split on lyric boundaries/ }));
+ await waitFor(() => expect(splitMusicVideoScene).toHaveBeenCalledWith('mv-2', 's1', 'fal', expect.anything()));
+ expect(await screen.findByText('Verse · 2/2')).toBeTruthy();
+ expect(screen.queryByRole('button', { name: /Split on lyric boundaries/ })).toBeNull();
+ });
+
it('requests the Grok clip that covers a cutaway and adds approximate motion timing', async () => {
generateVideo.mockResolvedValue({ jobId: 'grok-job' });
await openProject({
diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.js
index fc63796dfb..846b76a3de 100644
--- a/client/src/services/apiMusicVideo.js
+++ b/client/src/services/apiMusicVideo.js
@@ -64,6 +64,12 @@ export const reorderMusicVideoScenes = (id, sceneIds, options = {}) =>
request(`/music-video/${encodeURIComponent(id)}/scenes/reorder`, {
method: 'POST', body: JSON.stringify({ sceneIds }), ...options,
});
+// Split a shot its backend cannot render in one take on lyric/phrase
+// boundaries (#8977) → { project, scenes }. `backend` omitted = project pin.
+export const splitMusicVideoScene = (id, sceneId, backend, options = {}) =>
+ request(`/music-video/${encodeURIComponent(id)}/scenes/${encodeURIComponent(sceneId)}/split`, {
+ method: 'POST', body: JSON.stringify(backend ? { backend } : {}), ...options,
+ });
// ---- Scene takes (#8965) ----
// Every render/import for a scene slot is an immutable take; the scene's
diff --git a/server/lib/README.md b/server/lib/README.md
index bd2259edac..ee7e3439f8 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -298,7 +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`, `selectedPerformanceInstruction(scene)` (the selected take's shot instruction, performance scenes only), `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. |
+| `musicVideoShotTiming.js` | Music Video shot modes (#8977): `MUSIC_VIDEO_SHOT_MODES` (`cutaway`/`performance`), `isPerformanceScene`, `selectedPerformanceInstruction(scene)` (the selected take's shot instruction, performance scenes only), `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()`, `shotSplitLimit(scene, backend)` (per-take limit: lip-sync window or Grok's longest clip), `planShotSplit()` (contiguous pieces cut at lyric pauses → line/phrase boundaries → beats; one extra piece at most to avoid cutting a sung line). 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). |
diff --git a/server/lib/musicVideoShotTiming.js b/server/lib/musicVideoShotTiming.js
index 3aca1c88ba..1a6c6eadc3 100644
--- a/server/lib/musicVideoShotTiming.js
+++ b/server/lib/musicVideoShotTiming.js
@@ -22,6 +22,9 @@
* 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.
+ * - `shotSplitLimit` / `planShotSplit` — how such an over-long shot is split:
+ * contiguous pieces within the lane's per-take limit, cut at a pause between
+ * sung lines, a lyric/phrase boundary or a beat (in that order).
*
* Dependency-free (only grokVideoClip.js, itself dependency-free) so the client
* re-exports it from `client/src/lib/musicVideoShotTiming.js` and the two sides
@@ -209,3 +212,124 @@ export function approximateMotionCues(phrases, startSec, endSec) {
}
return beats.length ? `Approximate motion timing within the clip — ${beats.join('; ')}.` : '';
}
+
+/**
+ * The longest single shot `backend` can render for `scene` without losing song
+ * coverage, or null when no per-take limit applies: a performance shot is bound
+ * by its lip-sync provider's audio window (inside the safety margin), a Grok
+ * footage cutaway by the longest clip Grok delivers. Other lanes — and a
+ * performance shot on a lane that cannot lip-sync at all, which is blocked
+ * outright rather than split — have no limit here.
+ */
+export function shotSplitLimit(scene, backend) {
+ if (isPerformanceScene(scene)) {
+ const capability = performanceCapability(backend);
+ return capability ? round6(capability.maxAudioSec - PERFORMANCE_WINDOW_MARGIN_SEC) : null;
+ }
+ const footage = scene?.visualLayer == null || scene.visualLayer === 'footage';
+ return backend === 'grok' && footage ? GROK_VIDEO_DURATIONS[GROK_VIDEO_DURATIONS.length - 1] : null;
+}
+
+// Shortest piece a split may produce, so a cut never strands a sliver shot.
+export const SHOT_SPLIT_MIN_PIECE_SEC = 1;
+
+// Cut-point preference, best first: a pause between sung lines, a lyric line
+// or phrase boundary, a beat; the even-split fallback ranks below all three.
+const CUT_RANK = Object.freeze({ pause: 0, line: 1, beat: 2 });
+const CUT_KIND = Object.freeze(['pause', 'line', 'beat']);
+
+const timedNumber = (v) => typeof v === 'number' && Number.isFinite(v);
+
+function splitCandidates({ lyricCues, phrases, beats }) {
+ const out = [];
+ const timedCues = (Array.isArray(lyricCues) ? lyricCues : [])
+ .filter((cue) => timedNumber(cue?.startSec))
+ .map((cue) => ({ startSec: cue.startSec, endSec: timedNumber(cue.endSec) ? cue.endSec : cue.startSec }))
+ .sort((a, b) => a.startSec - b.startSec);
+ let sungUntil = -Infinity;
+ for (const cue of timedCues) {
+ // The middle of the silence between one line and the next is the cleanest
+ // cut: neither take has to start or stop mid-word.
+ if (cue.startSec > sungUntil && Number.isFinite(sungUntil)) out.push({ t: (sungUntil + cue.startSec) / 2, rank: CUT_RANK.pause });
+ out.push({ t: cue.startSec, rank: CUT_RANK.line });
+ sungUntil = Math.max(sungUntil, cue.endSec);
+ }
+ for (const phrase of Array.isArray(phrases) ? phrases : []) {
+ if (timedNumber(phrase?.startSec)) out.push({ t: phrase.startSec, rank: CUT_RANK.line });
+ if (timedNumber(phrase?.endSec)) out.push({ t: phrase.endSec, rank: CUT_RANK.line });
+ }
+ for (const beat of Array.isArray(beats) ? beats : []) {
+ if (timedNumber(beat)) out.push({ t: beat, rank: CUT_RANK.beat });
+ }
+ // A point strictly inside a sung line is never a lyric/phrase boundary; a
+ // beat may still land there, but that cut is not clean (it splits a word).
+ const insideLine = (t) => timedCues.some((cue) => t > cue.startSec + 1e-6 && t < cue.endSec - 1e-6);
+ return out
+ .map((c) => ({ ...c, clean: !insideLine(c.t) }))
+ .filter((c) => c.rank === CUT_RANK.beat || c.clean);
+}
+
+// Cut `[startSec, endSec]` into exactly `count` pieces of at most `maxSec`,
+// or null when that count cannot keep every piece at least `minPieceSec`.
+function cutPieces({ startSec, endSec, maxSec, minPieceSec, count, candidates }) {
+ if ((endSec - startSec) / count < minPieceSec) return null;
+ const pieces = [];
+ let clean = true;
+ let cursor = startSec;
+ for (let remaining = count; remaining > 1; remaining -= 1) {
+ // Any cut in [lo, hi] leaves the rest coverable by `remaining - 1` pieces
+ // and keeps both sides at least `minPieceSec` long.
+ const lo = Math.max(cursor + minPieceSec, endSec - (remaining - 1) * maxSec);
+ const hi = Math.min(cursor + maxSec, endSec - minPieceSec);
+ const target = cursor + (endSec - cursor) / remaining;
+ let best = null;
+ for (const c of candidates) {
+ if (c.t < lo - 1e-6 || c.t > hi + 1e-6) continue;
+ if (!best || c.rank < best.rank || (c.rank === best.rank && Math.abs(c.t - target) < Math.abs(best.t - target))) best = c;
+ }
+ clean = clean && Boolean(best?.clean);
+ const at = round6(Math.min(hi, Math.max(lo, best ? best.t : target)));
+ pieces.push({ startSec: round6(cursor), endSec: at, cut: best ? CUT_KIND[best.rank] : 'even' });
+ cursor = at;
+ }
+ pieces.push({ startSec: round6(cursor), endSec: round6(endSec), cut: null });
+ return { pieces, clean };
+}
+
+// How many pieces beyond the minimum a split may add to avoid cutting a sung
+// line mid-word. Each piece is a separate (possibly paid) take, so the search
+// stays tight: one extra take for a clean cut, never more.
+export const SHOT_SPLIT_MAX_EXTRA_PIECES = 1;
+
+/**
+ * Split a shot spanning `[startSec, endSec]` into contiguous pieces of at most
+ * `maxSec` each, cutting on musical boundaries: the pause between two timed
+ * lyric lines first, then a line or phrase boundary, then a beat, and only
+ * when none lies in reach an even cut. It uses the fewest pieces unless one
+ * more (`SHOT_SPLIT_MAX_EXTRA_PIECES`) is what lets every cut avoid splitting
+ * a sung line. Pieces cover the span exactly — no gap, no overlap — so nothing
+ * is looped, stretched or dropped.
+ *
+ * Returns `{ ok: true, pieces: [{ startSec, endSec, cut }] }` — `cut` names what
+ * the piece's END was cut on (`pause` | `line` | `beat` | `even`; null for
+ * the last piece, which ends where the shot did) — or `{ ok: false, code,
+ * message }` when the shot is untimed or already fits.
+ */
+export function planShotSplit({ startSec, endSec, maxSec, lyricCues, phrases, beats, minPieceSec = SHOT_SPLIT_MIN_PIECE_SEC }) {
+ if (!timedNumber(startSec) || !timedNumber(endSec) || !(endSec > startSec)) {
+ return { ok: false, code: 'MUSIC_VIDEO_SPLIT_UNTIMED', message: 'Set a start and end before splitting a shot.' };
+ }
+ if (!(maxSec > 0) || endSec - startSec <= maxSec + 1e-6) {
+ return { ok: false, code: 'MUSIC_VIDEO_SPLIT_NOT_NEEDED', message: 'This shot already fits in a single take.' };
+ }
+ const candidates = splitCandidates({ lyricCues, phrases, beats });
+ const fewest = Math.ceil(round6((endSec - startSec) / maxSec));
+ const base = { startSec, endSec, maxSec, minPieceSec, candidates };
+ const first = cutPieces({ ...base, count: fewest });
+ let chosen = first;
+ for (let extra = 1; !chosen.clean && extra <= SHOT_SPLIT_MAX_EXTRA_PIECES; extra += 1) {
+ const more = cutPieces({ ...base, count: fewest + extra });
+ if (more?.clean) chosen = more;
+ }
+ return { ok: true, pieces: chosen.pieces };
+}
diff --git a/server/lib/musicVideoShotTiming.test.js b/server/lib/musicVideoShotTiming.test.js
new file mode 100644
index 0000000000..b9c49c9cc6
--- /dev/null
+++ b/server/lib/musicVideoShotTiming.test.js
@@ -0,0 +1,82 @@
+import { describe, it, expect } from 'vitest';
+import { planShotSplit, shotSplitLimit, SOURCE_AUDIO_LIPSYNC, PERFORMANCE_WINDOW_MARGIN_SEC } from './musicVideoShotTiming.js';
+
+// The split planner is an algorithm with a real input matrix (#8977): which
+// boundary wins, how many pieces, and exact coverage are each ambiguous when
+// seen only through the scene-split route, which asserts the record outcome.
+
+const coverage = (pieces) => pieces.map((p) => [p.startSec, p.endSec]);
+const expectContiguous = (pieces, startSec, endSec, maxSec) => {
+ expect(pieces[0].startSec).toBe(startSec);
+ expect(pieces.at(-1).endSec).toBe(endSec);
+ for (let i = 1; i < pieces.length; i += 1) expect(pieces[i].startSec).toBe(pieces[i - 1].endSec);
+ for (const p of pieces) expect(p.endSec - p.startSec).toBeLessThanOrEqual(maxSec + 1e-6);
+};
+
+describe('planShotSplit', () => {
+ it('cuts in the pause between two sung lines rather than at the even midpoint', () => {
+ const lyricCues = [
+ { text: 'first line', startSec: 40, endSec: 47 },
+ { text: 'second line', startSec: 49, endSec: 58 },
+ ];
+ const plan = planShotSplit({ startSec: 40, endSec: 60, maxSec: 14.75, lyricCues });
+ expect(plan.ok).toBe(true);
+ expect(coverage(plan.pieces)).toEqual([[40, 48], [48, 60]]);
+ expect(plan.pieces.map((p) => p.cut)).toEqual(['pause', null]);
+ });
+
+ it('never cuts inside a sung line on a lyric/phrase boundary; falls to a beat, then an even cut', () => {
+ // One long line covers the whole reachable cut range — only a beat may land inside it.
+ const lyricCues = [{ text: 'held note', startSec: 0, endSec: 20 }];
+ const phrases = [{ startSec: 9, endSec: 11, intent: 'turn' }];
+ const onBeat = planShotSplit({ startSec: 0, endSec: 20, maxSec: 10.5, lyricCues, phrases, beats: [9.5, 10.2] });
+ expect(coverage(onBeat.pieces)).toEqual([[0, 10.2], [10.2, 20]]);
+ expect(onBeat.pieces[0].cut).toBe('beat');
+ const even = planShotSplit({ startSec: 0, endSec: 20, maxSec: 10.5, lyricCues, phrases });
+ expect(coverage(even.pieces)).toEqual([[0, 10], [10, 20]]);
+ expect(even.pieces[0].cut).toBe('even');
+ });
+
+ it('uses the fewest pieces, each within the limit, covering the span exactly', () => {
+ const plan = planShotSplit({ startSec: 12.5, endSec: 43.7, maxSec: 10 });
+ expect(plan.pieces).toHaveLength(4);
+ expectContiguous(plan.pieces, 12.5, 43.7, 10);
+ // A phrase boundary out of reach of a feasible cut is ignored rather than
+ // leaving a remainder too long for the pieces left.
+ const reach = planShotSplit({ startSec: 0, endSec: 29, maxSec: 10, phrases: [{ startSec: 2, endSec: 3 }] });
+ expect(reach.pieces).toHaveLength(3);
+ expectContiguous(reach.pieces, 0, 29, 10);
+ });
+
+ it('adds at most one piece to keep every cut out of a sung line', () => {
+ // Two pieces would have to cut inside the 9–21 line; three cut at 8.5 and 21.5.
+ const lyricCues = [
+ { text: 'a', startSec: 0, endSec: 8 },
+ { text: 'b', startSec: 9, endSec: 21 },
+ { text: 'c', startSec: 22, endSec: 28 },
+ ];
+ const clean = planShotSplit({ startSec: 0, endSec: 28, maxSec: 14.75, lyricCues });
+ expect(coverage(clean.pieces)).toEqual([[0, 8.5], [8.5, 21.5], [21.5, 28]]);
+ // A single 20s line cannot be cleanly cut even with an extra piece: keep the fewest.
+ const held = planShotSplit({ startSec: 0, endSec: 20, maxSec: 14.75, lyricCues: [{ text: 'held', startSec: 0, endSec: 20 }] });
+ expect(held.pieces).toHaveLength(2);
+ });
+
+ it('refuses an untimed shot and one that already fits the limit (boundary inclusive)', () => {
+ expect(planShotSplit({ startSec: null, endSec: 30, maxSec: 10 })).toMatchObject({ ok: false, code: 'MUSIC_VIDEO_SPLIT_UNTIMED' });
+ expect(planShotSplit({ startSec: 5, endSec: 15, maxSec: 10 })).toMatchObject({ ok: false, code: 'MUSIC_VIDEO_SPLIT_NOT_NEEDED' });
+ expect(planShotSplit({ startSec: 5, endSec: 15.01, maxSec: 10 }).pieces).toHaveLength(2);
+ });
+});
+
+describe('shotSplitLimit', () => {
+ it('bounds a performance by the lip-sync window and a Grok footage cutaway by its longest clip', () => {
+ const fal = SOURCE_AUDIO_LIPSYNC.fal;
+ expect(shotSplitLimit({ shotMode: 'performance' }, 'fal')).toBeCloseTo(fal.maxAudioSec - PERFORMANCE_WINDOW_MARGIN_SEC, 6);
+ expect(shotSplitLimit({ shotMode: 'cutaway' }, 'grok')).toBe(10);
+ // Blocked outright (not split) or unbounded lanes have no limit.
+ expect(shotSplitLimit({ shotMode: 'performance' }, 'grok')).toBeNull();
+ expect(shotSplitLimit({ shotMode: 'cutaway' }, 'fal')).toBeNull();
+ expect(shotSplitLimit({ shotMode: 'cutaway', visualLayer: 'still' }, 'grok')).toBeNull();
+ });
+});
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index 765263ed4b..ab54952f45 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -480,6 +480,12 @@ export const musicVideoSceneReorderSchema = z.object({
sceneIds: z.array(z.string().min(1).max(64)).min(1).max(500),
}).strict();
+// Split an over-long shot on lyric/phrase boundaries (#8977). `backend` is
+// the lane the director will render with; omitted/null = the project's pin.
+export const musicVideoSceneSplitSchema = z.object({
+ backend: z.enum(['local', 'grok', 'fal']).nullable().optional(),
+}).strict();
+
// Autonomous shot planner (#1855): propose a scene per analyzed audio section.
// `seedPrompts` (default true) additionally asks the active/given AI provider
// for a first-pass framePrompt/prompt per scene — best-effort, never fails the
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.js
index 84c572b4fe..1ba85503c2 100644
--- a/server/routes/musicVideo.js
+++ b/server/routes/musicVideo.js
@@ -18,6 +18,7 @@ import {
musicVideoSceneCreateSchema,
musicVideoSceneUpdateSchema,
musicVideoSceneReorderSchema,
+ musicVideoSceneSplitSchema,
musicVideoPlanRequestSchema,
musicVideoManualAnalysisSchema,
musicVideoTranscribeMidiRequestSchema,
@@ -52,6 +53,7 @@ import {
updateScene,
deleteScene,
reorderProjectScenes,
+ splitProjectScene,
setProjectMidiTranscription,
appendSceneTakes,
appendTakesAcrossScenes,
@@ -418,6 +420,13 @@ router.post('/:id/scenes/reorder', asyncHandler(async (req, res) => {
res.json(updated);
}));
+// Split a shot its backend cannot render in one take (#8977): a performance
+// longer than the lip-sync window, a Grok cutaway longer than its longest clip.
+router.post('/:id/scenes/:sceneId/split', asyncHandler(async (req, res) => {
+ const { backend } = validateRequest(musicVideoSceneSplitSchema, req.body ?? {});
+ res.json(await splitProjectScene(req.params.id, req.params.sceneId, { backend }));
+}));
+
// --- Scene takes (#8965) ---
// Every render or import for a scene slot is kept as an immutable take; the
// slot field is the director's explicit selection among them. A take's asset
diff --git a/server/routes/musicVideo.test.js b/server/routes/musicVideo.test.js
index e31a5e7424..a346fa9120 100644
--- a/server/routes/musicVideo.test.js
+++ b/server/routes/musicVideo.test.js
@@ -17,6 +17,8 @@ vi.mock('../services/musicVideo/projects.js', () => ({
updateScene: vi.fn(async (id, sceneId, p) => ({ sceneId, ...p })),
deleteScene: vi.fn(async (id) => ({ id, scenes: [] })),
reorderProjectScenes: vi.fn(async (id, ids) => ({ id, scenes: ids.map((sceneId, order) => ({ sceneId, order })) })),
+ // Scene split (#8977) — exercised against the real store in musicVideoSceneSplit.test.js.
+ splitProjectScene: vi.fn(),
setProjectMidiTranscription: vi.fn(async (id, midi) => ({ id, midiTranscription: midi })),
// Scene takes (#8965) — exercised against the real store in musicVideoTakes.test.js.
appendSceneTakes: vi.fn(),
diff --git a/server/routes/musicVideoSceneSplit.test.js b/server/routes/musicVideoSceneSplit.test.js
new file mode 100644
index 0000000000..1416192293
--- /dev/null
+++ b/server/routes/musicVideoSceneSplit.test.js
@@ -0,0 +1,99 @@
+/**
+ * Music Video scene split route (#8977), through the real router and the real
+ * file-backed project store: an over-long performance shot (fal lip-sync) and
+ * an over-long Grok cutaway become contiguous scenes cut on lyric boundaries,
+ * the original keeps its id and takes, new pieces carry the direction and the
+ * selected frame but no clip, and a shot that fits one take is refused.
+ */
+
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import express from 'express';
+import { mkdirSync, rmSync, writeFileSync } from 'fs';
+import { join } from 'path';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots } from '../lib/mockPathsDataRoot.js';
+
+const ROOT = () => lazyTempDataRoot('mv-split-route-test-');
+vi.mock('../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), { dataRoot: ROOT }));
+vi.mock('../services/settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));
+
+const { default: musicVideoRoutes } = await import('./musicVideo.js');
+const projects = await import('../services/musicVideo/projects.js');
+
+const app = express();
+app.use(express.json());
+app.use('/api/music-video', musicVideoRoutes);
+app.use(errorMiddleware);
+
+const LYRICS = [
+ { text: 'first line', startSec: 30, endSec: 37 },
+ { text: 'second line', startSec: 39, endSec: 46 },
+ { text: 'third line', startSec: 47.5, endSec: 55 },
+];
+
+let project;
+beforeEach(async () => {
+ rmSync(join(ROOT(), 'music-video-projects.json'), { force: true });
+ mkdirSync(join(ROOT(), 'images'), { recursive: true });
+ writeFileSync(join(ROOT(), 'images', 'singer.png'), 'png-bytes');
+ writeFileSync(join(ROOT(), 'video-history.json'), JSON.stringify([]));
+ project = await projects.createProject({ name: 'Example Video' });
+ await projects.updateProject(project.id, { lyricCues: LYRICS, videoSettings: { backend: 'fal' } });
+});
+afterAll(cleanupTempDataRoots);
+
+const split = (sceneId, body = {}) => request(app).post(`/api/music-video/${project.id}/scenes/${sceneId}/split`).send(body);
+
+describe('POST /:id/scenes/:sceneId/split', () => {
+ it('splits an over-long performance shot at the lyric pauses, keeping the original id, takes and neighbours', async () => {
+ const before = await projects.addProjectScene(project.id, { label: 'Intro', startSec: 0, endSec: 30 });
+ const shot = await projects.addProjectScene(project.id, {
+ label: 'Verse', prompt: 'singer at the mic', startSec: 30, endSec: 56, shotMode: 'performance', loop: false,
+ });
+ const after = await projects.addProjectScene(project.id, { label: 'Outro', startSec: 56, endSec: 70 });
+ await projects.updateScene(project.id, shot.sceneId, { referenceImageId: 'singer.png' });
+
+ // No backend in the body: the project's pinned fal lane bounds the take.
+ const res = await split(shot.sceneId);
+ expect(res.status).toBe(200);
+ const pieces = res.body.scenes;
+ // 26s over a ~14.75s lip-sync window fits two takes, but any two-way cut
+ // lands inside "second line" — so it takes a third and cuts in both pauses.
+ expect(pieces.map((p) => [p.startSec, p.endSec])).toEqual([[30, 38], [38, 46.75], [46.75, 56]]);
+ expect(pieces[0].sceneId).toBe(shot.sceneId);
+ expect(pieces.map((p) => p.label)).toEqual(['Verse · 1/3', 'Verse · 2/3', 'Verse · 3/3']);
+ expect(pieces.map((p) => p.lyricText)).toEqual(['first line', 'second line', 'third line']);
+ expect(pieces[1]).toMatchObject({ shotMode: 'performance', prompt: 'singer at the mic', loop: false, referenceImageId: 'singer.png', videoHistoryId: null });
+ expect(pieces[1].takes.map((t) => [t.kind, t.assetId])).toEqual([['image', 'singer.png']]);
+
+ const stored = await projects.getProject(project.id);
+ expect(stored.scenes.map((s) => [s.sceneId, s.order])).toEqual([
+ [before.sceneId, 0], [shot.sceneId, 1], [pieces[1].sceneId, 2], [pieces[2].sceneId, 3], [after.sceneId, 4],
+ ]);
+ expect(stored.scenes[1].takes.map((t) => t.assetId)).toEqual(['singer.png']);
+ });
+
+ it('splits a Grok cutaway at its 10-second clip limit when the director renders on Grok', async () => {
+ const shot = await projects.addProjectScene(project.id, { label: 'Bridge', startSec: 30, endSec: 55 });
+ const res = await split(shot.sceneId, { backend: 'grok' });
+ expect(res.status).toBe(200);
+ const pieces = res.body.scenes;
+ expect(pieces).toHaveLength(3);
+ for (const p of pieces) expect(p.endSec - p.startSec).toBeLessThanOrEqual(10);
+ expect(pieces[0].startSec).toBe(30);
+ expect(pieces.at(-1).endSec).toBe(55);
+ });
+
+ it('refuses a shot that fits one take, a lane with no per-take limit, a bad backend and an unknown scene', async () => {
+ const fits = await projects.addProjectScene(project.id, { startSec: 30, endSec: 40, shotMode: 'performance' });
+ expect((await split(fits.sceneId)).body.code).toBe('MUSIC_VIDEO_SPLIT_NOT_NEEDED');
+ const cutaway = await projects.addProjectScene(project.id, { startSec: 0, endSec: 60 });
+ const unbounded = await split(cutaway.sceneId);
+ expect(unbounded.status).toBe(400);
+ expect(unbounded.body.code).toBe('MUSIC_VIDEO_SPLIT_NOT_NEEDED');
+ expect((await split(cutaway.sceneId, { backend: 'sora' })).status).toBe(400);
+ expect((await split('mvs-missing')).status).toBe(404);
+ expect((await projects.getProject(project.id)).scenes).toHaveLength(2);
+ });
+});
diff --git a/server/services/musicVideo/projects.js b/server/services/musicVideo/projects.js
index 645753fa6a..6b897c8a16 100644
--- a/server/services/musicVideo/projects.js
+++ b/server/services/musicVideo/projects.js
@@ -157,6 +157,16 @@ export async function reorderProjectScenes(id, orderedIds) {
return next;
}
+/**
+ * Split a shot longer than its backend renders in one take into contiguous
+ * scenes on lyric/phrase boundaries (#8977, projectsLogic.splitScene).
+ * Returns `{ project, scenes }` — the persisted project and the pieces.
+ */
+export async function splitProjectScene(id, sceneId, options = {}) {
+ const { splitScene } = await import('./projectsLogic.js');
+ return mutateProjectRecord(id, (current) => splitScene(current, sceneId, options));
+}
+
// ---- scene takes (#8965) ----
// Append candidate takes to one scene: `{ scene, appended }`. A take fills its
// slot only while the slot is empty — never replaces a selection (takes.js).
diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.js
index 11a84aeba9..499ede3fcf 100644
--- a/server/services/musicVideo/projectsLogic.js
+++ b/server/services/musicVideo/projectsLogic.js
@@ -29,6 +29,7 @@ import { stripMusicVideoLocalRenderPins } from '../../lib/syncWire.js';
import { persistedRenderPinFields } from '../../lib/renderTargets.js';
import { sanitizeProjectForSync } from '../../lib/projectStoreKit.js';
import { isStr } from '../../lib/textUtils.js';
+import { planShotSplit, shotSplitLimit } from '../../lib/musicVideoShotTiming.js';
import { normalizeLyricCues, normalizePhrases, invalidateTimedText } from './timedText.js';
import { ensureSceneTakes, TAKE_SLOT } from './takes.js';
import { normalizeComposition, invalidateCompositionTiming } from './composition.js';
@@ -441,6 +442,96 @@ export function reorderScenes(project, orderedIds) {
return touch(project, { scenes: nextScenes });
}
+// Label suffix budget: the scene label schema caps at 120 characters.
+const SCENE_LABEL_MAX = 120;
+
+/** The timed lyric lines sung inside `[startSec, endSec]`, joined, or null. */
+function lyricTextWithin(cues, startSec, endSec) {
+ const lines = (Array.isArray(cues) ? cues : [])
+ .filter((cue) => typeof cue?.startSec === 'number' && cue.startSec >= startSec - 1e-6 && cue.startSec < endSec - 1e-6)
+ .map((cue) => (typeof cue.text === 'string' ? cue.text.trim() : ''))
+ .filter(Boolean);
+ return lines.length ? lines.join(' / ').slice(0, 2000) : null;
+}
+
+/**
+ * Split a shot longer than its backend can render in one take (#8977) into
+ * contiguous scenes on musical boundaries (lib/musicVideoShotTiming.js
+ * `planShotSplit`): a performance shot at its lip-sync provider's audio
+ * window, a Grok cutaway at the longest Grok clip. `backend` is the lane the
+ * director will render with ('' / null = the project's pinned backend).
+ *
+ * The original scene keeps its id, takes and selections and becomes the first
+ * piece; each later piece is a new scene placed right after it, carrying the
+ * shot's direction and the selected reference frame (as a take, so the frame
+ * is ready to animate) but no clip — the old clip was generated for the whole
+ * span. A performance take on the first piece is then correctly refused by the
+ * render as re-timed, never silently re-cut. Each piece's `lyricText` is the
+ * timed lines sung inside it. Returns `{ project, scenes }` (all pieces, in
+ * order); throws 400 when the shot is untimed or already fits one take.
+ */
+export function splitScene(project, sceneId, { backend = null } = {}) {
+ const scenes = project.scenes || [];
+ const idx = scenes.findIndex((s) => s.sceneId === sceneId);
+ if (idx < 0) throw new ServerError('Scene not found', { status: 404, code: 'NOT_FOUND' });
+ const scene = scenes[idx];
+ const lane = backend || project.videoSettings?.backend || null;
+ const maxSec = shotSplitLimit(scene, lane);
+ if (maxSec == null) {
+ throw new ServerError('This backend renders the shot at any length — there is nothing to split.', { status: 400, code: 'MUSIC_VIDEO_SPLIT_NOT_NEEDED' });
+ }
+ const plan = planShotSplit({
+ startSec: scene.startSec,
+ endSec: scene.endSec,
+ maxSec,
+ lyricCues: project.lyricCues,
+ phrases: project.phrases,
+ beats: project.audioAnalysis?.beats,
+ });
+ if (!plan.ok) throw new ServerError(plan.message, { status: 400, code: plan.code });
+
+ const now = new Date().toISOString();
+ const count = plan.pieces.length;
+ // Re-splitting a piece numbers it afresh rather than stacking suffixes.
+ const baseLabel = (scene.label || scene.sectionLabel || `Scene ${idx + 1}`).replace(/ · \d+\/\d+$/, '');
+ const pieceLabel = (i) => {
+ const suffix = ` · ${i + 1}/${count}`;
+ return `${baseLabel.slice(0, SCENE_LABEL_MAX - suffix.length)}${suffix}`;
+ };
+ const hasTimedCues = (project.lyricCues || []).some((cue) => typeof cue?.startSec === 'number');
+ const pieceLyrics = (piece) => (hasTimedCues ? lyricTextWithin(project.lyricCues, piece.startSec, piece.endSec) : scene.lyricText ?? null);
+
+ const pieces = plan.pieces.map((piece, i) => {
+ const timing = { label: pieceLabel(i), startSec: piece.startSec, endSec: piece.endSec, lyricText: pieceLyrics(piece) };
+ if (i === 0) return { ...scene, ...timing, takes: ensureSceneTakes(scene, now) };
+ const fresh = buildScene({
+ ...parseSceneOrThrow(musicVideoSceneCreateSchema, {
+ sectionLabel: scene.sectionLabel ?? null,
+ prompt: scene.prompt ?? '',
+ framePrompt: scene.framePrompt ?? null,
+ beatAligned: scene.beatAligned ?? false,
+ loop: scene.loop ?? false,
+ sectionIndex: scene.sectionIndex ?? null,
+ visualIntent: scene.visualIntent ?? null,
+ visualLayer: scene.visualLayer ?? 'footage',
+ shotMode: scene.shotMode ?? 'cutaway',
+ ...timing,
+ }),
+ }, { order: 0 });
+ const seeded = {
+ ...fresh,
+ ...(scene.direction ? { direction: structuredClone(scene.direction) } : {}),
+ referenceImageId: scene.referenceImageId ?? null,
+ };
+ return { ...seeded, takes: ensureSceneTakes(seeded, now, 'manual') };
+ });
+
+ const nextScenes = [...scenes.slice(0, idx), ...pieces, ...scenes.slice(idx + 1)]
+ .map((s, i) => ({ ...s, order: i }));
+ const next = touch(project, { scenes: nextScenes });
+ return { project: next, scenes: nextScenes.slice(idx, idx + count) };
+}
+
// ---- peer-sync federation (#1770) -----------------------------------------
// Mirrors the Creative Director store (creativeDirector/projectsLogic.js): a
// project is a whole-record LWW kind (no item-union, no ephemeral flag), so the