Skip to content

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

fix: align music video clip coverage with render timing

[._.]/ Adam Eivy269918f49116
diff --git a/client/src/components/musicVideo/SceneCard.test.jsx b/client/src/components/musicVideo/SceneCard.test.jsx
index 9c4f8abc4d..e245430d81 100644
--- a/client/src/components/musicVideo/SceneCard.test.jsx
+++ b/client/src/components/musicVideo/SceneCard.test.jsx
@@ -503,6 +503,39 @@ describe('clip playback and coverage', () => {
};
const coverage = () => screen.queryByText(/Shot runs .* but its clip is/);
+ it('clears both coverage warnings when the director holds the last frame, and restores them when cleared', () => {
+ const onSave = vi.fn();
+ function Harness() {
+ const [current, setCurrent] = useState(scene);
+ return <SceneCard scene={current} index={0} expanded
+ onEditLocal={(_id, patch) => setCurrent((value) => ({ ...value, ...patch }))} onSave={onSave} />;
+ }
+ const { container } = render(<Harness />);
+ metadata(container.querySelector('video'), 4);
+ expect(coverage()).toBeTruthy();
+ expect(screen.getByText('Clip too short')).toBeTruthy();
+ fireEvent.click(screen.getByLabelText(/Hold last frame/));
+ expect(onSave).toHaveBeenLastCalledWith('s1', { holdLastFrame: true });
+ expect(coverage()).toBeNull();
+ expect(screen.queryByText('Clip too short')).toBeNull();
+ fireEvent.click(screen.getByLabelText(/Hold last frame/));
+ expect(coverage()).toBeTruthy();
+ expect(screen.getByText('Clip too short')).toBeTruthy();
+ });
+
+ it('measures the selected performance take from its in-point and offers no ineffective loop repair', () => {
+ const trimmed = { ...scene, startSec: 0, endSec: 3, loop: true, takes: [
+ { kind: 'video', assetId: 'clip-1', shotInstruction: { shotMode: 'performance', edit: { inSec: 2, outSec: 4 } } },
+ ] };
+ const props = { index: 0, expanded: true, lipSyncBackend: 'fal', songDurationSec: 30, onEditLocal: vi.fn(), onSave: vi.fn() };
+ const { container, rerender } = render(<SceneCard {...props} scene={trimmed} />);
+ metadata(container.querySelector('video'), 4);
+ rerender(<SceneCard {...props} scene={{ ...trimmed, shotMode: 'performance' }} />);
+ expect(coverage().textContent).toContain('clip is 2.0s');
+ expect(screen.getByText('Clip too short')).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'Loop clip' })).toBeNull();
+ });
+
// Catches coverage based on raw file length, a stale clip's measurement, or a trim
// save that loses millisecond rounding; also pins metadata lifetime across hidden previews.
it('measures adjusted playback, retains it while hidden, invalidates a replacement, and trims the shot', () => {
@@ -516,7 +549,8 @@ describe('clip playback and coverage', () => {
expect(coverage()).toBeNull();
metadata(container.querySelector('video'), 4.567);
expect(container.querySelector('video').playbackRate).toBeCloseTo(32 / 24);
- expect(coverage().textContent).toContain('clip is 3.1s');
+ // The render rounds the 3.05025s source window to 3.050s before display.
+ expect(coverage().textContent).toContain('clip is 3.0s');
expect(screen.getByLabelText('Not 16:9')).toBeTruthy();
rerender(<SceneCard {...props} scene={{ ...adjusted, visualLayer: 'still' }} />);
expect(container.querySelector('section[aria-label="Render"] video')).toBeNull();
diff --git a/client/src/components/musicVideo/SceneClipCoverageNotice.jsx b/client/src/components/musicVideo/SceneClipCoverageNotice.jsx
index 81e7b9918e..f9f14c95d2 100644
--- a/client/src/components/musicVideo/SceneClipCoverageNotice.jsx
+++ b/client/src/components/musicVideo/SceneClipCoverageNotice.jsx
@@ -1,19 +1,18 @@
import { AlertTriangle } from 'lucide-react';
-import { clipReversed } from '../../lib/musicVideoLayers.js';
/** The native clip's usable duration compared with the authored shot span. */
export default function SceneClipCoverageNotice({ scene, playback, onChange }) {
- const { underCovered, spanSec, playedSec } = playback;
+ const { underCovered, spanSec, playedSec, canLoop } = playback;
return 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" />
<span className="min-w-0 flex-1 basis-48">
Shot runs {spanSec.toFixed(1)}s but its clip is {playedSec.toFixed(1)}s — the render won&apos;t repeat it.
- Trim the shot, continue or regenerate a longer clip, or loop it on purpose.
+ Trim the shot, continue or regenerate a longer clip{canLoop ? ', or loop it on purpose.' : '.'}
</span>
<button type="button" onClick={() => onChange({ endSec: Math.round((scene.startSec + playedSec) * 1000) / 1000 })}
className="rounded bg-port-bg border border-port-border px-2 py-1 min-h-[44px] sm:min-h-0 text-port-text">Trim to clip</button>
- {!clipReversed(scene) && (
+ {canLoop && (
<button type="button" onClick={() => onChange({ loop: true })}
className="rounded bg-port-bg border border-port-border px-2 py-1 min-h-[44px] sm:min-h-0 text-port-text">Loop clip</button>
)}
diff --git a/client/src/hooks/useSceneClipPlayback.js b/client/src/hooks/useSceneClipPlayback.js
index a52e9402c6..9d8ca7f7b5 100644
--- a/client/src/hooks/useSceneClipPlayback.js
+++ b/client/src/hooks/useSceneClipPlayback.js
@@ -1,7 +1,7 @@
import { useEffect, useRef, useState } from 'react';
import { useVideoFileSrc } from './useVideoFileSrc.js';
-import { clipOffsetSec, clipReversed, clipSpeedRate } from '../lib/musicVideoLayers.js';
-import { COVERAGE_TOLERANCE_SEC } from '../lib/musicVideoSceneAttention.js';
+import { clipCanLoop, clipLoops, clipNeedsMoreFootage, clipPlaybackWindow, clipSpeedRate } from '../lib/musicVideoLayers.js';
+import { selectedPerformanceInstruction } from '../lib/musicVideoShotTiming.js';
/** A shot's native clip metadata and render-adjusted coverage. Keep mounted with the card. */
export default function useSceneClipPlayback(scene) {
@@ -17,16 +17,15 @@ export default function useSceneClipPlayback(scene) {
const [clipMeta, setClipMeta] = useState(null);
const clipSec = clipMeta && clipMeta.id === scene.videoHistoryId ? clipMeta.sec : null;
const clipSize = clipMeta && clipMeta.id === scene.videoHistoryId && clipMeta.width > 0 ? { width: clipMeta.width, height: clipMeta.height } : null;
- // Absent loop preserves legacy loop-to-fill; reverse always plays once.
- const loops = scene.loop !== false && !clipReversed(scene);
+ const edit = selectedPerformanceInstruction(scene)?.edit;
+ const canLoop = clipCanLoop(scene, edit);
+ const loops = clipLoops(scene, edit);
const spanSec = scene.beatAligned && typeof scene.startSec === 'number' && typeof scene.endSec === 'number'
? scene.endSec - scene.startSec
: null;
const clipRate = clipSpeedRate(scene);
- const clipLead = clipOffsetSec(scene);
- const playedSec = clipSec != null ? Math.max(0, -clipLead) + Math.max(0, clipSec - Math.max(0, clipLead)) / clipRate : null;
- const shortBySec = !loops && spanSec != null && playedSec != null ? spanSec - playedSec : 0;
- const underCovered = shortBySec > COVERAGE_TOLERANCE_SEC;
+ const playedSec = clipSec != null ? clipPlaybackWindow(scene, edit, clipSec).sourceSec : null;
+ const underCovered = clipNeedsMoreFootage({ loop: loops, holdLastFrame: scene.holdLastFrame, spanSec, clipSec: playedSec });
useEffect(() => { if (clipPlayerRef.current) clipPlayerRef.current.playbackRate = clipRate; }, [clipRate]);
const onLoadedMetadata = (e) => {
@@ -36,5 +35,5 @@ export default function useSceneClipPlayback(scene) {
if (Number.isFinite(sec) && sec > 0) setClipMeta({ id: scene.videoHistoryId, sec, width, height });
};
- return { clipPlayerRef, clipSrc, clipSec, clipSize, loops, spanSec, playedSec, underCovered, onLoadedMetadata };
+ return { clipPlayerRef, clipSrc, clipSec, clipSize, canLoop, loops, spanSec, playedSec, underCovered, onLoadedMetadata };
}
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 96f6b7bbfe..8163ba37e4 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -63,7 +63,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `musicVideoFiling.js` | Which music video an Image Gen / Video Gen render is for: `MUSIC_VIDEO_FILING_PARAM` (the `musicVideo` URL param), `musicVideoFilingFields(searchParams)` (the `musicVideoProjectId` request field), `musicVideoOf(item)` (a record's video). Used by `components/media/MusicVideoFilingSelect.jsx`, `hooks/useMediaPreviewActions.js` and the two generate pages. |
| `musicVideoMotion.js` | Re-export of `server/lib/musicVideoMotion.js` (`MOTION_CONTINUITY_CLAUSE`, `AUDIO_REACTIVE_PERFORMANCE_GUARD`, `silentMotionPrompt`) for board motion prompts. |
| `musicVideoBatchPlan.js` | Pure helpers for the Music Video missing-frame / missing-clip batches (#10153): `videoBatchPreview` (count + fal estimate summed from `falSceneTake`, unpriced count), `scenesWaitingForFrame`, `videosButtonLabel`, `batchSummary`, `batchActive`, `batchSceneName`. Used by `components/musicVideo/ProjectActionGroups.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`, `MUSIC_VIDEO_TEXT_ZONES` / `MUSIC_VIDEO_LYRIC_ROLES` (#10583 lyric type per shot), `sceneVisualLayer(scene, { layered })`, `sceneHasAuthoredSpan`, `sceneRenderReady(scene, { layered })`, and a footage shot's hand-set clip speed, offset and reverse (`clipSpeedRate`, `clipOffsetSec`, `clipReversed`). `stillFrameTransform(scene, songTime, { fps, startSec, endSec })` gives the animatic the composed render's frame-clamped push/pan transform (explicit Move before planned camera). Used by `components/musicVideo/SceneCard.jsx`, `StoryboardAnimatic.jsx`, `ProjectActionGroups.jsx` and `hooks/useMusicVideoSceneMedia.js`. |
+| `musicVideoLayers.js` | Music-video per-scene visual layers (#8985), re-exported from `server/lib/musicVideoLayers.js`: `MUSIC_VIDEO_VISUAL_LAYERS`, `MUSIC_VIDEO_STILL_MOVES`, `MUSIC_VIDEO_TEXT_ZONES` / `MUSIC_VIDEO_LYRIC_ROLES` (#10583 lyric type per shot), `sceneVisualLayer(scene, { layered })`, `sceneHasAuthoredSpan`, `sceneRenderReady(scene, { layered })`, and a footage shot's hand-set clip speed, offset and reverse (`clipSpeedRate`, `clipOffsetSec`, `clipReversed`). `stillFrameTransform(scene, songTime, { fps, startSec, endSec })` gives the animatic the composed render's frame-clamped push/pan transform (explicit Move before planned camera). Used by `components/musicVideo/SceneCard.jsx`, `StoryboardAnimatic.jsx`, `ProjectActionGroups.jsx` and `hooks/useMusicVideoSceneMedia.js`. `clipPlaybackWindow(scene, edit, duration)` / `clipLoops` / `clipCanLoop` share source timing and loop eligibility; `clipNeedsMoreFootage` and `COVERAGE_TOLERANCE_SEC` keep held-clip coverage identical in the card and render preflight. |
| `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`, `takeClipUrl` (hover-preview clip), `sceneHasPendingDecision` (contact-sheet filter), `takeProvenance`; `TAKE_SLOT` maps a take kind to its selection field. Used by `components/musicVideo/SceneTakeStrip.jsx` and `pages/MusicVideo.jsx`. |
| `musicVideoSceneAttention.js` | Music Video per-scene attention model (#10152): `sceneAttention(scene, ctx)` returns the codes (`missing-frame`, `missing-clip`, `under-covered`, `contract-problem`, `perf-blocked`, `candidates-pending`, `plate-unverified`, `no-span`, `last-failure`) behind the collapsed scene-row chips, the Board `?scenes=attention\|missing\|all` filter (`parseSceneFilter`, `sceneMatchesFilter`) and the Produce per-shot strip; `SCENE_ATTENTION_LABELS`; `sceneMediaKind` (`clip` / `image` / `code` / `card`) and `SCENE_MEDIA_LABELS` for the Board thumbnail badges. Used by `components/musicVideo/SceneCard.jsx`, `stages/BoardStage.jsx` and `stages/ProduceStage.jsx`. |
| `musicVideoCoverOverlay.js` | Cover-art lettering preview (#10345): re-export of `server/lib/musicVideoCoverOverlay.js` (the design vocabulary, `normalizeCoverDesign`, `coverOverlaySvg`) plus `canvasCoverWidths(design, texts, fonts)`, which measures text with a canvas so the live preview wraps and sizes the title the way the server's measured render does. |
diff --git a/client/src/lib/musicVideoLayers.js b/client/src/lib/musicVideoLayers.js
index 6a0cc56822..0069961676 100644
--- a/client/src/lib/musicVideoLayers.js
+++ b/client/src/lib/musicVideoLayers.js
@@ -26,6 +26,11 @@ export {
clipSpeedRate,
clipOffsetSec,
clipReversed,
+ COVERAGE_TOLERANCE_SEC,
+ clipCanLoop,
+ clipLoops,
+ clipPlaybackWindow,
+ clipNeedsMoreFootage,
} from '../../../server/lib/musicVideoLayers.js';
/** The composed render's cover-fitted still move at a song time, clamped to its last frame. */
diff --git a/client/src/lib/musicVideoSceneAttention.js b/client/src/lib/musicVideoSceneAttention.js
index 087204276d..326f064faf 100644
--- a/client/src/lib/musicVideoSceneAttention.js
+++ b/client/src/lib/musicVideoSceneAttention.js
@@ -9,12 +9,11 @@
import { shotActionContractProblem } from '../../../server/lib/musicVideoActionContract.js';
import { currentPlateEvidence } from '../../../server/lib/musicVideoPlateEvidence.js';
import { isEndFrameImageEffect } from './musicVideoImageEffects.js';
-import { clipReversed, isSelfDrawnLayer, sceneVisualLayer, sceneHasAuthoredSpan } from './musicVideoLayers.js';
-import { performanceBlockedReason, performanceCapability, planPerformanceWindow, isPerformanceScene } from './musicVideoShotTiming.js';
+import { clipLoops, clipNeedsMoreFootage, isSelfDrawnLayer, sceneVisualLayer, sceneHasAuthoredSpan } from './musicVideoLayers.js';
+import { performanceBlockedReason, performanceCapability, planPerformanceWindow, isPerformanceScene, selectedPerformanceInstruction } from './musicVideoShotTiming.js';
import { sceneHasPendingDecision, sceneTakeList } from './musicVideoTakes.js';
-// Mirrors render.js COVERAGE_TOLERANCE_SEC (#8964): a non-looping shot may run this far past its clip.
-export const COVERAGE_TOLERANCE_SEC = 0.25;
+export { COVERAGE_TOLERANCE_SEC } from './musicVideoLayers.js';
export const SCENE_ATTENTION_LABELS = Object.freeze({
'missing-frame': 'No frame',
@@ -100,9 +99,9 @@ export function sceneAttention(scene, ctx = {}) {
if (!isSelfDrawnLayer(layer) && !scene.referenceImageId && !codeRendered) codes.push('missing-frame');
if (layer === 'footage' && !footageOptional && !scene.videoHistoryId) codes.push('missing-clip');
if (layer !== 'footage' && !sceneHasAuthoredSpan(scene)) codes.push('no-span');
- if (layer === 'footage' && (scene.loop === false || clipReversed(scene)) && scene.beatAligned && clipSec != null
- && typeof scene.startSec === 'number' && typeof scene.endSec === 'number'
- && scene.endSec - scene.startSec - clipSec > COVERAGE_TOLERANCE_SEC) codes.push('under-covered');
+ if (layer === 'footage' && scene.beatAligned && sceneHasAuthoredSpan(scene)
+ && clipNeedsMoreFootage({ loop: clipLoops(scene, selectedPerformanceInstruction(scene)?.edit),
+ holdLastFrame: scene.holdLastFrame, spanSec: scene.endSec - scene.startSec, clipSec })) codes.push('under-covered');
const contract = scene.direction?.actionContract;
if (contract && shotActionContractProblem(contract, scene)) codes.push('contract-problem');
if (layer === 'footage' && isPerformanceScene(scene) && performanceBlocked(scene, { lipSyncBackend, songDurationSec, videoSettings })) codes.push('perf-blocked');
diff --git a/client/src/lib/musicVideoSceneAttention.test.js b/client/src/lib/musicVideoSceneAttention.test.js
index 2d77da9c57..b5627a325c 100644
--- a/client/src/lib/musicVideoSceneAttention.test.js
+++ b/client/src/lib/musicVideoSceneAttention.test.js
@@ -31,6 +31,8 @@ describe('sceneAttention', () => {
expect(sceneAttention(shot, { clipSec: 9.9 })).toEqual([]);
expect(sceneAttention(shot)).toEqual([]);
expect(sceneAttention({ ...shot, loop: true }, { clipSec: 5 })).toEqual([]);
+ expect(sceneAttention({ ...shot, holdLastFrame: true }, { clipSec: 5 })).toEqual([]);
+ expect(sceneAttention({ ...shot, reverse: true, holdLastFrame: true }, { clipSec: 5 })).toEqual([]);
});
it('flags a blocked performance, pending candidates, failures and an unverified plate', () => {
diff --git a/server/lib/README.md b/server/lib/README.md
index cacd21a4fb..51a5e5ede6 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -610,7 +610,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `claimFlowTaskTypes.js` | `hasClaimFlowContract(task)` shares trusted claim identity across registration, completion and resume. `CLAIM_FLOW_TASK_TYPES` — the ONE list of task kinds whose prompts own their own `claim/<item>` worktree and push/PR/MR/review lifecycle (#6613). `services/cosTaskGenerator.js` stamps `metadata.claimFlow` from it (WRITE side); `services/agentPromptBuilder.js` reads it back through `isClaimFlowTask()` to pick a run's claim posture (READ side). It lived as two byte-identical copies, so a new claim type added to one silently split the writer from the reader — no error, just a claim run treated as a plain commit-only handoff; `claimFlowTaskTypes.test.js` fails if a local copy reappears. Imports nothing. |
| `chiptuneRender.js` | Deterministic chiptune score → mono PCM → 16-bit WAV buffer (pure Node, no audio deps); `renderScoreToPcm` / `pcmToWavBuffer` / `renderScoreToWav`. |
| `chiptuneScore.js` | Chiptune score contract (#2911): `chiptuneScoreSchema` (Zod) + `sanitizeChiptuneScore`, `buildScoreEvents` — the pattern/order → absolute-time flatten mirrored by `client/src/lib/chiptunePlayback.js`. |
-| `musicVideoLayers.js` | Music Video per-scene visual layers (#8985): `MUSIC_VIDEO_VISUAL_LAYERS` (`footage`/`still`/`card`/`code`), `MUSIC_VIDEO_STILL_MOVES` (`hold`/`push`/`pan`), `STILL_PUSH_ZOOM` / `STILL_PAN_TRAVEL` (shared render/animatic motion amounts), `MUSIC_VIDEO_FRAME_FITS` (`fill`/`still`/`vhs`/`black`: how an off-shape clip fills the frame), `sceneVisualLayer(scene, { layered })` (only a composed render honors a still/card), `sceneHasAuthoredSpan`, and `sceneRenderReady(scene, { layered })`. `clipSpeedRate(scene)` / `clipOffsetSec(scene)` / `clipReversed(scene)` read a footage shot's hand-set `speedFps`, `offsetFrames` and `reverse` on the 24 fps grid (`CLIP_TIMING_FPS`, `CLIP_SPEED_FPS_RANGE`, `CLIP_OFFSET_FRAMES_RANGE`). Pure leaf shared by `services/musicVideo/render.js` and the client board (`client/src/lib/musicVideoLayers.js`). |
+| `musicVideoLayers.js` | Music Video per-scene visual layers (#8985): `MUSIC_VIDEO_VISUAL_LAYERS` (`footage`/`still`/`card`/`code`), `MUSIC_VIDEO_STILL_MOVES` (`hold`/`push`/`pan`), `STILL_PUSH_ZOOM` / `STILL_PAN_TRAVEL` (shared render/animatic motion amounts), `MUSIC_VIDEO_FRAME_FITS` (`fill`/`still`/`vhs`/`black`: how an off-shape clip fills the frame), `sceneVisualLayer(scene, { layered })` (only a composed render honors a still/card), `sceneHasAuthoredSpan`, and `sceneRenderReady(scene, { layered })`. `clipSpeedRate(scene)` / `clipOffsetSec(scene)` / `clipReversed(scene)` read a footage shot's hand-set `speedFps`, `offsetFrames` and `reverse` on the 24 fps grid (`CLIP_TIMING_FPS`, `CLIP_SPEED_FPS_RANGE`, `CLIP_OFFSET_FRAMES_RANGE`). Pure leaf shared by `services/musicVideo/render.js` and the client board (`client/src/lib/musicVideoLayers.js`). `clipPlaybackWindow(scene, edit, duration)` / `clipLoops` / `clipCanLoop` share source timing and loop eligibility; `clipNeedsMoreFootage` and `COVERAGE_TOLERANCE_SEC` keep held-clip coverage identical in the card and render preflight. |
| `musicVideoLyricAnchors.js` | Music Video lyric anchors: `cuesSungWithin(cues, startSec, endSec)` and `sungLyricTextWithin(cues, startSec, endSec)` (shot text, capped at 2,000 characters), the lines a shot's span anchors, each counted from its first sung word to its last when it has word timing, else its line window. Shared by the storyboard anchor check and the retime anchor sync. |
| `musicVideoImageEffects.js` | Music Video image effects: a code-drawn effect a still shot plays instead of a generated clip (`imageEffect`: `flash-develop`, a camera flash then the picture develops like an instant photo over `imageEffectSec`; or a fade, flash or glitch from the start frame to the end frame). `sceneImageEffect(scene, { layered })`, `imageEffectState` (the effect at a time into the shot, painted by the storyboard animatic) and `musicVideoImageEffectFilter` (the same curves as ffmpeg filters for the final render). Browser-safe and import-free: document videos ship it as is. |
| `musicVideoTransitions.js` | Music Video cut transitions: VHS glitch styles a shot sets on the cut into (`transitionIn`) or out of (`transitionOut`) it, `transitionGlitchFrames` (the glitched frames of a cut timeline, never moving a cut), `transitionFrameAt`, `sceneTransitionSections`, `imageEffectGlitchFrames`/`mergeGlitchFrames` (end-frame glitch effects in the same shape), `shotGlitchFrames`/`sceneShotGlitchFrames` (glitches a shot sets at moments inside it, `scene.glitches`), `blockBox`, `edgeGlows` (an effect's edge glows as fading ramps) and `musicVideoTransitionFilter` (per-frame ffmpeg filters for the final render). Styles span VHS, film and camera looks. Browser-safe; the storyboard animatic paints the same frames. |
diff --git a/server/lib/musicVideoLayers.js b/server/lib/musicVideoLayers.js
index 99a8296a8f..7443be0161 100644
--- a/server/lib/musicVideoLayers.js
+++ b/server/lib/musicVideoLayers.js
@@ -119,3 +119,39 @@ export const clipSpeedRate = (scene) => (CLIP_TIMING_FPS + whole(scene?.speedFps
export const clipOffsetSec = (scene) => whole(scene?.offsetFrames, CLIP_OFFSET_FRAMES_RANGE) / CLIP_TIMING_FPS;
// A footage shot's clip set to play backwards. A lip-sync performance never reverses: its mouth follows the song.
export const clipReversed = (scene) => scene?.reverse === true && scene?.shotMode !== 'performance';
+
+export const COVERAGE_TOLERANCE_SEC = 0.25;
+
+/** Performance edits and reversed clips read their source once. */
+export const clipCanLoop = (scene, edit = null) => !edit && !clipReversed(scene);
+// An absent loop preserves playback for projects saved before shot planning.
+export const clipLoops = (scene, edit = null) => clipCanLoop(scene, edit) && scene?.loop !== false;
+
+/**
+ * Source trim on the render's output clock, shared with card coverage. Only
+ * retimed clips round to milliseconds; untouched performance edits retain
+ * their original precision. sourceSec includes footage after the edit out-point.
+ */
+export function clipPlaybackWindow(scene, edit, duration) {
+ const round3 = (n) => Math.round(n * 1000) / 1000;
+ const sourceInSec = edit ? Math.min(edit.inSec, duration) : 0;
+ const sourceOutSec = edit ? Math.min(edit.outSec, duration) : duration;
+ const rate = clipSpeedRate(scene);
+ const offsetSourceInSec = sourceInSec + clipOffsetSec(scene);
+ const retimed = rate !== 1 || offsetSourceInSec !== sourceInSec;
+ const leadSec = retimed ? round3(Math.max(0, -offsetSourceInSec)) : 0;
+ const clampedSourceInSec = Math.min(duration, Math.max(0, offsetSourceInSec));
+ return {
+ rate,
+ leadSec,
+ inSec: retimed ? round3(clampedSourceInSec / rate) : sourceInSec,
+ outSec: retimed ? round3(leadSec + Math.max(clampedSourceInSec, sourceOutSec) / rate) : sourceOutSec,
+ sourceSec: retimed ? round3(leadSec + (duration - clampedSourceInSec) / rate) : duration - sourceInSec,
+ };
+}
+
+/** Unknown measurements cannot establish a shortfall; an authored hold covers any gap. */
+export function clipNeedsMoreFootage({ loop, holdLastFrame, spanSec, clipSec }, toleranceSec = COVERAGE_TOLERANCE_SEC) {
+ return loop === false && !holdLastFrame && Number.isFinite(spanSec) && Number.isFinite(clipSec)
+ && spanSec - clipSec > toleranceSec;
+}
diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.js
index 9883091d33..be013c79bd 100644
--- a/server/services/musicVideo/render.js
+++ b/server/services/musicVideo/render.js
@@ -44,7 +44,7 @@ import { getTrack } from '../tracks/index.js';
import { getProject, listProjects, updateProject, mutateProjectRecord } from './projects.js';
import { requireProject } from './requireProject.js';
import { applyProjectPatch } from './projectsLogic.js';
-import { MUSIC_VIDEO_FRAME_FITS, STILL_PAN_TRAVEL, STILL_PUSH_ZOOM, clipOffsetSec, clipReversed, clipSpeedRate, isSelfDrawnLayer, sceneHasAuthoredSpan, sceneVisualLayer } from '../../lib/musicVideoLayers.js';
+import { COVERAGE_TOLERANCE_SEC, MUSIC_VIDEO_FRAME_FITS, STILL_PAN_TRAVEL, STILL_PUSH_ZOOM, clipLoops, clipNeedsMoreFootage, clipPlaybackWindow, clipReversed, isSelfDrawnLayer, sceneHasAuthoredSpan, sceneVisualLayer } from '../../lib/musicVideoLayers.js';
import { musicVideoAspect, musicVideoRenderCanvas } from '../../lib/musicVideoAspect.js';
import { encodeCodeComposition, prepareCodeRender, writeCodeProofSheet } from './codeRender.js';
import { documentRenderInitScripts, encodeDocumentComposition, prepareDocumentRender, sweepDocumentScratch } from './documentRender.js';
@@ -113,12 +113,6 @@ const emitRenderSettled = (projectId, job) => musicVideoEvents.emit('render', {
export const attachRenderSseClient = (jobId, res) => attachSse(jobs, jobId, res);
-// #8964 loop semantics. A scene saved before shot planning existed has no
-// `loop` key and keeps the legacy behavior — its clip repeats to fill the
-// authored span — so existing projects render exactly as they did. A scene
-// created since carries an explicit boolean, and only `loop: true` repeats.
-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
@@ -131,10 +125,6 @@ const cutEffectOf = (scene, planned) => {
return effect?.enabled ? { cutEffect: effect } : {};
};
-// 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
-// render until the director resolves them.
-const COVERAGE_TOLERANCE_SEC = 0.25;
const COVERAGE_RESOLUTIONS = Object.freeze(['hold', 'trim', 'continue', 'replace', 'loop']);
/**
@@ -145,10 +135,10 @@ const COVERAGE_RESOLUTIONS = Object.freeze(['hold', 'trim', 'continue', 'replace
function findCoverageShortfalls(clips, { toleranceSec = COVERAGE_TOLERANCE_SEC } = {}) {
const out = [];
for (const clip of Array.isArray(clips) ? clips : []) {
- if (clip.layer || clip.loop !== false || clip.holdLastFrame) continue;
+ if (clip.layer) continue;
const spanSec = clip.outSec - clip.inSec;
const clipSec = clip.sourceSec ?? clip.duration;
- if (spanSec - clipSec > toleranceSec) {
+ if (clipNeedsMoreFootage({ loop: clip.loop, holdLastFrame: clip.holdLastFrame, spanSec, clipSec }, toleranceSec)) {
const round = (n) => Math.round(n * 100) / 100;
out.push({ sceneId: clip.sceneId, spanSec: round(spanSec), clipSec: round(clipSec), shortBySec: round(spanSec - clipSec) });
}
@@ -273,36 +263,12 @@ async function footageGeometry(entry) {
return { videoPath, width: measured.width, height: measured.height, fps: measured.fps || 24, duration };
}
-// Where a footage clip plays on the output timebase. A performance edit trims
-// the source; a hand-set speed and offset (clipSpeedRate / clipOffsetSec)
-// retime it: sectionChain plays it at `rate` and holds its first frame for
-// `leadSec` before the trim, so the in/out points here are output seconds.
-// Source coordinates stay immutable: only retimed clips round to milliseconds,
-// an untouched performance edit keeps its original precision. `sourceSec` is
-// the playable source length from the in-point on.
-function playbackWindow(scene, edit, duration) {
- const sourceInSec = edit ? Math.min(edit.inSec, duration) : 0;
- const sourceOutSec = edit ? Math.min(edit.outSec, duration) : duration;
- const rate = clipSpeedRate(scene);
- const offsetSourceInSec = sourceInSec + clipOffsetSec(scene);
- const retimed = rate !== 1 || offsetSourceInSec !== sourceInSec;
- const leadSec = retimed ? round3(Math.max(0, -offsetSourceInSec)) : 0;
- const clampedSourceInSec = Math.min(duration, Math.max(0, offsetSourceInSec));
- return {
- rate,
- leadSec,
- inSec: retimed ? round3(clampedSourceInSec / rate) : sourceInSec,
- outSec: retimed ? round3(leadSec + Math.max(clampedSourceInSec, sourceOutSec) / rate) : sourceOutSec,
- sourceSec: retimed ? round3(leadSec + (duration - clampedSourceInSec) / rate) : duration - sourceInSec,
- };
-}
-
// A footage shot's render clip, or `missing-clip` when its selected take cannot be read.
async function footageClip(scene, entry, planned) {
const geometry = await footageGeometry(entry);
if (!geometry) return { problem: 'missing-clip' };
const edit = performanceEdit(scene);
- const { rate, leadSec, inSec, outSec, sourceSec } = playbackWindow(scene, edit, geometry.duration);
+ const { rate, leadSec, inSec, outSec, sourceSec } = clipPlaybackWindow(scene, edit, geometry.duration);
return { clip: {
sceneId: scene.sceneId,
videoPath: geometry.videoPath,
@@ -314,7 +280,7 @@ async function footageClip(scene, entry, planned) {
// `duration` to the rendered span) so coverage can be judged against it.
sourceSec,
// A reversed clip is read once, backwards, and holds its last frame rather than looping.
- loop: edit || clipReversed(scene) ? false : sceneLoops(scene),
+ loop: clipLoops(scene, edit),
...(clipReversed(scene) ? { reverse: true } : {}),
// The director chose to hold the last frame over a shot longer than its clip.
...(scene.holdLastFrame === true ? { holdLastFrame: true } : {}),
diff --git a/server/services/musicVideo/render.terminal.test.js b/server/services/musicVideo/render.terminal.test.js
index 7c8e382e8b..a1ef96da1b 100644
--- a/server/services/musicVideo/render.terminal.test.js
+++ b/server/services/musicVideo/render.terminal.test.js
@@ -67,6 +67,7 @@ vi.mock('./compositionRender.js', () => ({
sweepCompositionScratch: vi.fn(async () => {}),
}));
vi.mock('./projects.js', () => ({ getProject: vi.fn(), listProjects: vi.fn(async () => []), updateProject: vi.fn(async () => ({})), mutateProjectRecord: vi.fn() }));
+vi.mock('./renderCleanup.js', () => ({ cleanupSupersededFinals: vi.fn(async () => ({})) }));
vi.mock('../instanceIdentity.js', () => ({ ensureInstanceId: vi.fn(async () => 'inst-self') }));
// A composed render goes shot by shot (shotSegments.js): the segment work is
// held open until a test settles it, or rejects on the render's abort signal.