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

Shot card redesign: swap from unused takes, start/end frame pair, per-shot render model and length (#11256)

[._.]/62c7d934b571
diff --git a/client/src/components/musicVideo/SceneCard.jsx b/client/src/components/musicVideo/SceneCard.jsx
index 92bdfa60d7..4ecaeb00af 100644
--- a/client/src/components/musicVideo/SceneCard.jsx
+++ b/client/src/components/musicVideo/SceneCard.jsx
@@ -3,13 +3,15 @@ import ShotActionInspector from './ShotActionInspector.jsx';
import SceneCameraControls from './SceneCameraControls.jsx';
import { MUSIC_VIDEO_MEDIUM_LABELS } from '../../../../server/lib/musicVideoMediumPlan.js';
import { useEffect, useRef, useState } from 'react';
-import { Trash2, Activity, ArrowUp, ArrowDown, ChevronRight, Image as ImageIcon, Video, Maximize2, AlertTriangle, ImagePlus, Clapperboard, SkipForward } from 'lucide-react';
+import { Trash2, Activity, ArrowUp, ArrowDown, ChevronRight, Image as ImageIcon, Video, Maximize2, AlertTriangle, ImagePlus, Clapperboard, SkipForward, Shuffle, ArrowRight } from 'lucide-react';
+import OverflowMenu from '../ui/OverflowMenu.jsx';
+import SceneTakePicker from './SceneTakePicker.jsx';
import { formatDurationSec } from '../../utils/formatters.js';
import { useVideoFileSrc } from '../../hooks/useVideoFileSrc.js';
import PerformanceEvidence from './PerformanceEvidence.jsx';
-import { planPerformanceRepair } from '../../lib/musicVideoShotTiming.js';
+import { isPerformanceScene, planPerformanceRepair } from '../../lib/musicVideoShotTiming.js';
import SceneTakeStrip from './SceneTakeStrip.jsx';
-import SceneEndFrame from './SceneEndFrame.jsx';
+import SceneEndFrame, { sceneEndFramePlanFor } from './SceneEndFrame.jsx';
import { MUSIC_VIDEO_LYRIC_ROLES, MUSIC_VIDEO_TEXT_ZONES, MUSIC_VIDEO_VISUAL_LAYERS, sceneHasAuthoredSpan } from '../../lib/musicVideoLayers.js';
// #8985: what a composed render shows for this scene's span.
@@ -18,6 +20,9 @@ const STILL_MOVE_LABELS = [['hold', 'Hold'], ['push', 'Push in'], ['pan', 'Pan']
// #10583: the shared lyric type's zone and style for this shot (composition documents).
const TEXT_ZONE_LABELS = { 'lower-left': 'Lower left', 'upper-right': 'Upper right', upper: 'Upper centre', lower: 'Lower centre', center: 'Centre', none: 'No lyrics' };
const LYRIC_ROLE_LABELS = { line: 'Sung line', hook: 'Hook slam', stamp: 'Stamp', data: 'Data caption' };
+const SHOT_MODE_LABELS = { cutaway: 'Cutaway', performance: 'Performance (lip-sync)', music: 'Performance (music-driven)' };
+const PRIMARY_BUTTON = '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';
+const SECONDARY_BUTTON = 'flex items-center gap-1 bg-port-bg border border-port-border hover:bg-port-border/40 disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0 whitespace-nowrap';
import { buildSceneTimingPresentation } from '../../lib/musicVideoSceneTiming.js';
import SceneTimingPlan from './SceneTimingPlan.jsx';
import SceneRenderProgress from './SceneRenderProgress.jsx';
@@ -26,6 +31,27 @@ import { ShotLockButton, useShotLock } from './ShotLock.jsx';
import ScenePoster from './ScenePoster.jsx';
import SceneRenderTarget, { renderTargetOverrides } from './SceneRenderTarget.jsx';
+/** One of a shot's two frames: tap to work on it, the corner button to see it full size. */
+function FrameTile({ label, imageId, empty, active, onPick, onOpen, openLabel }) {
+ return (
+ <div className="relative min-w-0">
+ <button type="button" onClick={onPick} aria-pressed={active} aria-label={`${label} frame${imageId ? '' : `: ${empty}`}`}
+ className={`block w-full overflow-hidden rounded border ${active ? 'border-port-accent ring-2 ring-port-accent' : 'border-port-border'} focus:outline-none focus:ring-2 focus:ring-port-accent`}>
+ {imageId
+ ? <img src={`/data/images/${encodeURIComponent(imageId)}`} alt="" className="block aspect-video w-full bg-black object-cover" />
+ : <span className="flex aspect-video w-full items-center justify-center border border-dashed border-transparent text-[11px] text-port-text-muted">{empty}</span>}
+ <span className="port-media-overlay-strong absolute left-1 top-1 rounded px-1 text-[10px] leading-tight">{label}</span>
+ </button>
+ {imageId && (
+ <button type="button" onClick={onOpen} aria-label={openLabel} title={openLabel}
+ className="port-media-overlay-strong absolute right-1 top-1 flex min-h-[44px] min-w-[44px] items-center justify-center rounded p-1 sm:min-h-0 sm:min-w-0">
+ <Maximize2 className="h-3 w-3" />
+ </button>
+ )}
+ </div>
+ );
+}
+
// The two timeline-bound scene fields rendered as identical number inputs.
const SCENE_TIME_FIELDS = [['Start', 'startSec'], ['End', 'endSec']];
@@ -66,12 +92,17 @@ const SCENE_TIME_FIELDS = [['Start', 'startSec'], ['End', 'endSec']];
* it is hidden when the joined span would exceed that lane's longest take.
*
* The card is a disclosure: collapsed it is one row — frame thumbnail, title,
- * timing, lyric line and status — and it opens on tap to the full editor.
+ * timing, lyric line and status — and it opens on tap to the full editor:
+ * the lock and a "…" menu (move, delete), then the Still and the Clip side by
+ * side (stacked on a phone), each with its selected picture large, its make /
+ * "Swap from unused" / import buttons and its takes. Swap from unused
+ * (`onPlacePoolItem(scene, { kind, assetId, withAssetId? })`) opens
+ * SceneTakePicker over the project's unused stills or clips. Timing, shot
+ * mode, layer and camera sit in a collapsed Shot settings row that names what
+ * is set; intent and the action contract in a collapsed Direction row.
* Opening or closing it also calls `onSeek(scene)`, so the docked preview
* jumps to the scene's start.
*/
-const MOVE_DOCUMENT_TITLE = "This video's shot order comes from its composition document";
-
// #11040: the one owner of whether a video render may start. The server reloads
// the persisted scene (and its speaker), so an unsaved or failed speaker edit
// must hold back every video entry point — Generate video and the failure Retry.
@@ -92,7 +123,7 @@ export default function SceneCard({
settingsSaving, videoBlockedReason, videoBlockedReasonFor = null, canContinueShot,
onMove, onDelete, onEditLocal, onSave,
onGenerateFrame, onGenerateVideo, onContinueVideo, onGenerateEndFrame, generatingEndFrame = false, onContinueFromPrevious, previousHasClip = false,
- onOpenPreview, onSelectTake, onReviewTake, onImportTake, onImportClipTake, takeBusy = false, layered = false, documentComposition = false,
+ onOpenPreview, onSelectTake, onReviewTake, onImportTake, onImportClipTake, onPlacePoolItem, projectId = null, videoModels = [], defaultVideoModel = '', shotNumbers = undefined, takeBusy = false, layered = false, documentComposition = false,
lipSyncBackend = '', songDurationSec = null, onSplit, onMergeNext, nextEndSec = null, falVideoSettings = null, onSeek, performanceReview = null, onRepairPerformance, repairBusy = false,
expanded, onToggleExpand, footageOptional = false, failedScenes = null, songReview = null,
}) {
@@ -123,6 +154,10 @@ export default function SceneCard({
const [keepStillAsEnd, setKeepStillAsEnd] = useState(false);
const [speakerSaving, setSpeakerSaving] = useState(false);
const [clipMeta, setClipMeta] = useState(null);
+ // Which slot's "Swap from unused" picker is open: 'image', 'video' or null.
+ const [swapKind, setSwapKind] = useState(null);
+ // Which of the shot's two frames the Frames section works on.
+ const [frameSide, setFrameSide] = useState('start');
const clipSec = clipMeta && clipMeta.id === scene.videoHistoryId ? clipMeta.sec : null;
// Pre-#8964 scenes have no `loop` key and keep the legacy loop-to-fill render.
const loops = scene.loop !== false;
@@ -138,7 +173,9 @@ export default function SceneCard({
const codeShot = layered && layer === 'code';
// Where this shot's clip renders: the project's saved renderer unless the card picks another for this shot.
const [renderPick, setRenderPick] = useState('');
- const renderOverrides = renderTargetOverrides(renderPick, falVideoSettings || {});
+ const [renderOptions, setRenderOptions] = useState({});
+ const renderOverrides = renderTargetOverrides(renderPick, falVideoSettings || {}, renderOptions,
+ { models: videoModels, defaultModel: defaultVideoModel, performance: isPerformanceScene(scene), scene });
const renderSettings = renderOverrides ? { ...falVideoSettings, ...renderOverrides } : falVideoSettings;
const renderLane = renderOverrides
? (renderSettings.backend === 'local' && renderSettings.generationMode === 'audioReactive' ? 'local' : renderSettings.backend)
@@ -177,6 +214,18 @@ export default function SceneCard({
else onGenerateVideo?.(scene);
};
const renderCost = performance ? performanceCost : timing.falCost;
+ // A footage shot's start and end frames show as a pair; the end frame is optional.
+ const endFrames = Boolean(onGenerateEndFrame) && layer === 'footage';
+ const endFramePlan = sceneEndFramePlanFor(scene, renderSettings || {});
+ const shotModeValue = performance ? (scene.performanceStyle === 'music' ? 'music' : 'performance') : 'cutaway';
+ // The collapsed Shot settings row says what is set, so it rarely needs opening.
+ const settingsSummary = [
+ layer === 'footage' ? SHOT_MODE_LABELS[shotModeValue] : LAYER_LABELS[layer],
+ typeof scene.startSec === 'number' && typeof scene.endSec === 'number' ? `${scene.startSec.toFixed(2)}–${scene.endSec.toFixed(2)}s` : null,
+ scene.beatAligned ? 'beat-aligned' : null,
+ layer === 'footage' && loops && !performance ? 'loops' : null,
+ scene.camera?.move ? `camera ${scene.camera.move}` : null,
+ ].filter(Boolean).join(' · ');
const promptField = (
<textarea
aria-label="Shot prompt"
@@ -236,49 +285,258 @@ export default function SceneCard({
<SceneRenderProgress kind="Frame" generating={generatingFrame} progress={frameProgress} />
<SceneRenderProgress kind="Video" generating={generatingVideo} progress={videoProgress} />
</summary>
- <div className="space-y-2 p-3 pt-0">
- {/* A move swaps this shot with its neighbor; the song timing and lyric stay with the slot. */}
- <div className="flex items-center justify-end gap-2">
+ <div className="space-y-3 p-3 pt-0">
+ {/* Locks first; reorder and delete wait behind the overflow menu. A move swaps this
+ shot with its neighbor; the song timing and lyric stay with the slot. */}
+ <div className="flex items-center gap-2">
<ShotLockButton scene={scene} className="mr-auto" />
{documentComposition && (
<span className="mr-auto text-[11px] text-gray-400">Shot order comes from the composition document, so it can't be reordered here.</span>
)}
- <button type="button" onClick={() => onMove(index, -1)} disabled={index === 0 || documentComposition} title={documentComposition ? MOVE_DOCUMENT_TITLE : "Swap with the previous shot; the song timing stays put"}
- className="min-h-[44px] inline-flex items-center justify-center gap-1 rounded border border-port-border px-2 text-xs disabled:opacity-30 sm:min-h-0 sm:py-1">
- <ArrowUp size={14} aria-hidden="true" /> Move earlier
- </button>
- <button type="button" onClick={() => onMove(index, 1)} disabled={isLast || documentComposition} title={documentComposition ? MOVE_DOCUMENT_TITLE : "Swap with the next shot; the song timing stays put"}
- className="min-h-[44px] inline-flex items-center justify-center gap-1 rounded border border-port-border px-2 text-xs disabled:opacity-30 sm:min-h-0 sm:py-1">
- <ArrowDown size={14} aria-hidden="true" /> Move later
- </button>
- <button onClick={() => onDelete(scene.sceneId)} aria-label="Delete scene" className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1 text-port-error" title="Delete scene"><Trash2 size={14} /></button>
+ <OverflowMenu label="Shot actions" items={[
+ { id: 'earlier', label: 'Move earlier', icon: ArrowUp, onSelect: () => onMove(index, -1), disabled: index === 0 || documentComposition },
+ { id: 'later', label: 'Move later', icon: ArrowDown, onSelect: () => onMove(index, 1), disabled: isLast || documentComposition },
+ { id: 'delete', label: 'Delete shot', icon: Trash2, tone: 'danger', onSelect: () => onDelete(scene.sceneId) },
+ ]} />
</div>
- {/* A footage shot's prompt is its motion, edited beside its Render button below. */}
+ {songChange && !songChange.resolved && songChange.status !== 'kept' && (
+ <p className="break-words text-[11px] text-port-warning">{songChange.status === 'new' ? 'New shot for lines the revised song added.' : `Before the song revision: ${songChange.previousLyricText ? `♪ ${songChange.previousLyricText}` : 'instrumental'}`}</p>
+ )}
{(layer !== 'footage' || codeShot) && promptField}
- {(scene.lyricText || scene.visualIntent || scene.direction) && (
- <div className="text-[11px] text-port-text-muted space-y-0.5">
- {scene.lyricText && <p className="italic break-words">♪ {scene.lyricText}</p>}
- {songChange && !songChange.resolved && songChange.status !== 'kept' && (
- <p className="break-words text-port-warning">{songChange.status === 'new' ? 'New shot for lines the revised song added.' : `Before the song revision: ${songChange.previousLyricText ? `♪ ${songChange.previousLyricText}` : 'instrumental'}`}</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" />
+ <span className="min-w-0 flex-1 basis-48">
+ Shot runs {spanSec.toFixed(1)}s but its clip is {clipSec.toFixed(1)}s — the render won&apos;t repeat it.
+ Trim the shot, continue or regenerate a longer clip, or loop it on purpose.
+ </span>
+ <button type="button" onClick={() => applyPatch({ endSec: Math.round((scene.startSec + clipSec) * 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>
+ <button type="button" onClick={() => applyPatch({ 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>
+ </div>
+ )}
+ {layer !== 'footage' && layered && !sceneHasAuthoredSpan(scene) && (
+ <p role="alert" className="text-[11px] text-port-warning">
+ Set a start and end — a {{ card: 'title card', code: 'code-drawn shot' }[layer] || 'still'} runs for exactly its span.
+ </p>
+ )}
+ {codeShot ? (
+ <p className="text-xs text-port-text-muted" data-testid="code-shot-note">
+ The composition draws this shot, so it needs no frame or clip.
+ {!documentComposition && ' A composed render shows it as a black frame under the typography; render from a composition document to draw it.'}
+ </p>
+ ) : (
+ <div className="grid gap-3 @3xl:grid-cols-2">
+ {/* Frames: the still this shot starts from (Phase 1b) and, optionally, the one it ends on
+ (#11173). Tap a frame to work on it; its takes and actions follow. */}
+ <section aria-label="Still" className="min-w-0 space-y-2">
+ <h4 className="text-xs font-medium">{endFrames ? 'Frames' : 'Still'}</h4>
+ {endFrames ? (
+ <div className="grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center gap-1" role="group" aria-label="Start and end frames">
+ <FrameTile label="Start" imageId={scene.referenceImageId} empty="No still yet" active={frameSide === 'start'}
+ onPick={() => setFrameSide('start')} onOpen={() => onOpenPreview?.(`image:${scene.referenceImageId}`)}
+ openLabel={`View scene ${index + 1} reference frame full size`} />
+ <ArrowRight size={14} aria-hidden="true" className="text-port-text-muted" />
+ <FrameTile label="End" imageId={scene.endImageId} empty="Optional" active={frameSide === 'end'}
+ onPick={() => setFrameSide('end')} onOpen={() => onOpenPreview?.(`image:${scene.endImageId}`)}
+ openLabel={`View scene ${index + 1} end frame full size`} />
+ </div>
+ ) : scene.referenceImageId ? (
+ <button type="button" onClick={() => onOpenPreview?.(`image:${scene.referenceImageId}`)}
+ aria-label={`View scene ${index + 1} reference frame full size`} title={`View scene ${index + 1} reference frame full size`}
+ className="block w-full overflow-hidden rounded border border-port-border focus:outline-none focus:ring-2 focus:ring-port-accent">
+ <img src={`/data/images/${scene.referenceImageId}`} alt="" className="block aspect-video w-full bg-black object-cover" />
+ </button>
+ ) : (
+ <div className="flex aspect-video w-full items-center justify-center rounded border border-dashed border-port-border text-xs text-port-text-muted">No still yet</div>
+ )}
+ {endFrames && frameSide === 'end' ? (
+ <SceneEndFrame scene={scene} index={index} generating={!!generatingEndFrame} onGenerate={onGenerateEndFrame}
+ onEditLocal={onEditLocal} onSave={onSave} onOpenPreview={onOpenPreview} takeBusy={takeBusy}
+ onSelectTake={onSelectTake} onReviewTake={onReviewTake} disabled={shotLock?.clip === 'locked'}
+ onSwap={onPlacePoolItem ? () => setSwapKind('endImage') : null} />
+ ) : (
+ <>
+ <div className="flex flex-wrap gap-2">
+ <button onClick={() => onGenerateFrame(scene)} disabled={!!generatingFrame}
+ className={PRIMARY_BUTTON}
+ title={scene.referenceImageId
+ ? 'Render another candidate frame — your selected frame stays until you pick a new one'
+ : 'Generate a still reference frame for this scene'}>
+ {generatingFrame ? <Activity size={14} className="animate-spin" /> : <ImageIcon size={14} />}
+ {generatingFrame ? 'Generating frame…' : (scene.referenceImageId ? 'New frame take' : 'Generate frame')}
+ </button>
+ {onPlacePoolItem && (
+ <button type="button" onClick={() => setSwapKind('image')} disabled={takeBusy || shotLock?.clip === 'locked'} className={SECONDARY_BUTTON}
+ title={shotLock?.clip === 'locked' ? 'Video locked. Unlock the video to change it.' : "Pick a still made for this video that no shot uses: this shot's other takes, other shots', or the floor"}>
+ <Shuffle size={14} /> Swap from unused
+ </button>
+ )}
+ {onImportTake && (
+ <button type="button" onClick={() => onImportTake(scene)} disabled={takeBusy} className={SECONDARY_BUTTON}
+ title="Add a frame from the gallery or an upload (e.g. made in an external tool) as a take">
+ <ImagePlus size={14} /> Import take
+ </button>
+ )}
+ {onContinueFromPrevious && layer === 'footage' && index > 0 && (
+ <button type="button" onClick={() => onContinueFromPrevious(scene, { keepStillAsEnd: keepStillAsEnd && Boolean(scene.referenceImageId) })}
+ disabled={takeBusy || !previousHasClip} className={SECONDARY_BUTTON}
+ title={previousHasClip ? 'Start this shot from the last frame the previous shot shows in the cut' : 'The previous shot needs a clip first'}>
+ <SkipForward size={14} /> From previous shot
+ </button>
+ )}
+ </div>
+ {onContinueFromPrevious && layer === 'footage' && index > 0 && scene.referenceImageId && (
+ <label htmlFor={`mv-scene-${scene.sceneId}-keep-still-end`} className="flex items-center gap-1 text-[11px] text-port-text-muted min-h-[44px] sm:min-h-0">
+ <input id={`mv-scene-${scene.sceneId}-keep-still-end`} type="checkbox" checked={keepStillAsEnd}
+ onChange={(e) => setKeepStillAsEnd(e.target.checked)} />
+ From previous shot: keep this frame as the end frame
+ </label>
)}
- {scene.visualIntent && <p className="break-words">Intent: {scene.visualIntent}</p>}
- {/* Applied treatment direction (#8980) — appended to both generated prompts. */}
- {scene.direction && (
- <p className="break-words" title={scene.direction.frameClause}>
- Direction: {scene.direction.mode}{scene.direction.medium ? ` · planned ${MUSIC_VIDEO_MEDIUM_LABELS[scene.direction.medium] || scene.direction.medium}${scene.direction.mediumPinned ? ' (pinned)' : ''}` : ''}{scene.direction.focalSubject ? ` · ${scene.direction.focalSubject}` : ''}
- {scene.direction.typographyRole !== 'none' ? ` · ${scene.direction.typographyRole} text, ${scene.direction.negativeSpace} region kept clear` : ' · no text'}
- </p>
+ <SceneTakeStrip scene={scene} kind="image" busy={takeBusy}
+ onSelect={(take) => onSelectTake?.(scene, take)}
+ onReview={(take, review) => onReviewTake?.(scene, take, review)}
+ onOpenPreview={onOpenPreview} />
+ <details className="group/prompt">
+ <summary className="flex min-h-[44px] cursor-pointer items-center gap-1 text-[11px] text-port-text-muted marker:content-none sm:min-h-0 [&::-webkit-details-marker]:hidden">
+ <ChevronRight size={12} aria-hidden="true" className="shrink-0 transition-transform group-open/prompt:rotate-90" />
+ <span className="shrink-0">Still prompt</span>
+ <span className="min-w-0 truncate">{scene.framePrompt ? `· ${scene.framePrompt}` : '· from the shot prompt'}</span>
+ </summary>
+ <textarea
+ aria-label="Reference frame prompt"
+ value={scene.framePrompt || ''} rows={4}
+ onChange={(e) => onEditLocal(scene.sceneId, { framePrompt: e.target.value })}
+ onBlur={(e) => onSave(scene.sceneId, { framePrompt: e.target.value || null })}
+ placeholder="Reference frame prompt — the still that seeds this shot (defaults to the shot prompt)"
+ className="mt-1 w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm"
+ />
+ </details>
+ </>
+ )}
+ </section>
+ {/* Clip: the motion prompt, where this shot renders and what it costs, then its clip (Phase 1). */}
+ <section aria-label="Render" className="min-w-0 space-y-2">
+ <h4 className="text-xs font-medium">Clip</h4>
+ {scene.videoHistoryId && performance && (
+ <PerformanceEvidence key={scene.videoHistoryId} clipSrc={clipSrc} instruction={instruction}
+ temporal={performanceReview?.shot} excerptStartSec={performanceReview?.excerptStartSec || 0}
+ repair={repairPlan} repairBusy={repairBusy || settingsSaving || generatingVideo || takeBusy}
+ onRepair={onRepairPerformance ? () => onRepairPerformance(scene.sceneId, {
+ excerptId: performanceReview.excerptId, sourceAssetId: repairPlan.sourceAssetId, boundarySec: repairPlan.boundarySec,
+ }) : null} />
+ )}
+ {scene.videoHistoryId && !performance && (
+ <div className="relative w-full">
+ <video
+ ref={clipPlayerRef}
+ src={clipSrc}
+ className="block w-full aspect-video object-cover rounded border border-port-border bg-black"
+ muted
+ playsInline
+ preload="metadata"
+ controls
+ onLoadedMetadata={(e) => {
+ const sec = e.currentTarget.duration;
+ if (Number.isFinite(sec) && sec > 0) setClipMeta({ id: scene.videoHistoryId, sec });
+ }}
+ />
+ {/* Corner expand — do not put the open handler on <video> itself;
+ that would fight native play/pause controls. Pause first so the
+ lightbox's unmuted autoplay doesn't double-play the audio. */}
+ <button
+ type="button"
+ onClick={() => {
+ clipPlayerRef.current?.pause();
+ onOpenPreview?.(`video:${scene.videoHistoryId}`);
+ }}
+ aria-label={`View scene ${index + 1} clip full size`}
+ title={`View scene ${index + 1} clip full size`}
+ className="always-dark absolute top-1 right-1 min-h-[44px] min-w-[44px] sm:min-h-0 sm:min-w-0 p-1 flex items-center justify-center rounded bg-black/50 text-white hover:bg-black/80 focus:outline-none focus:ring-2 focus:ring-port-accent"
+ >
+ <Maximize2 className="w-3 h-3" />
+ </button>
+ </div>
+ )}
+ {!scene.videoHistoryId && layer === 'footage' && (
+ <div className="flex aspect-video w-full items-center justify-center rounded border border-dashed border-port-border text-xs text-port-text-muted">No clip yet</div>
+ )}
+ {layer === 'footage' && promptField}
+ <div className="flex flex-wrap items-center gap-2">
+ <SceneRenderTarget id={fieldId('render-on')} value={renderPick} onChange={setRenderPick} performance={performance}
+ options={renderOptions} onOptionsChange={setRenderOptions} scene={scene} models={videoModels} defaultModel={defaultVideoModel}
+ saved={falVideoSettings || {}} disabled={!!generatingVideo} />
+ {renderCost && <span className="text-[11px] text-port-text-muted">{renderCost}</span>}
+ </div>
+ {endFramePlan.endImageId && (
+ <p className={`text-[11px] ${endFramePlan.used ? 'text-port-text-muted' : 'text-port-warning'}`} data-testid="end-frame-plan">
+ {endFramePlan.used ? 'The clip ends on the end frame.' : `${endFramePlan.reason}.`}
+ </p>
+ )}
+ <div className="flex flex-wrap items-center gap-2">
+ <button onClick={generateVideo}
+ disabled={!!videoRefusal}
+ className={PRIMARY_BUTTON}
+ title={videoRefusal
+ || (performance ? `${capability.style === 'music' ? "Animate this scene's frame to the song" : "Lip-sync this scene's frame to the song"} via ${capability.label} — ${performanceCost}`
+ : "Render this shot's clip from its still")}>
+ {generatingVideo ? <Activity size={14} className="animate-spin" /> : <Video size={14} />}
+ {generatingVideo ? 'Rendering…' : (scene.videoHistoryId ? 'Render again' : 'Render')}
+ </button>
+ {onPlacePoolItem && (
+ <button type="button" onClick={() => setSwapKind('video')} disabled={takeBusy || shotLock?.clip === 'locked'} className={SECONDARY_BUTTON}
+ title={shotLock?.clip === 'locked' ? 'Video locked. Unlock the video to change it.' : "Pick a clip made for this video that no shot uses: this shot's other takes, other shots', or the floor"}>
+ <Shuffle size={14} /> Swap from unused
+ </button>
+ )}
+ {scene.videoHistoryId && canContinueShot && (
+ <button
+ onClick={() => onContinueVideo(scene)}
+ disabled={settingsSaving || !!generatingVideo}
+ className={SECONDARY_BUTTON}
+ title="Native-extend this clip from its final latent frames and attach the longer result to this scene"
+ >
+ <Video size={14} /> Continue shot
+ </button>
+ )}
+ {onImportClipTake && (
+ <button type="button" onClick={() => onImportClipTake(scene)} disabled={takeBusy} className={SECONDARY_BUTTON}
+ title="Pick an existing clip from the gallery (e.g. made in an external tool) as a take">
+ <Clapperboard size={14} /> Import clip take
+ </button>
)}
</div>
+ {/* Why Render is off, on the card itself: a tooltip never shows on a phone. */}
+ {videoRefusal && videoRefusal !== performanceBlocked && !generatingVideo && layer === 'footage' && (
+ <div className="flex flex-wrap items-center gap-2 text-[11px] text-port-warning" data-testid="render-refusal">
+ <span>{videoRefusal}</span>
+ {shotLock && shotLock.still !== 'locked' && lockBlocked && <ShotLockButton scene={scene} />}
+ </div>
+ )}
+ <SceneTakeStrip scene={scene} kind="video" busy={takeBusy}
+ onSelect={(take) => onSelectTake?.(scene, take)}
+ onReview={(take, review) => onReviewTake?.(scene, take, review)}
+ onOpenPreview={onOpenPreview} />
+ </section>
+ </div>
)}
- <ShotActionInspector contract={scene.direction?.actionContract} scene={scene} />
- <PlateComparison scene={scene} frames={false} />
+ {/* What this shot's render covers and costs, and what blocks it, stays in view. */}
+ <SceneTimingPlan timing={timing} sceneId={scene.sceneId} lipSyncBackend={renderLane} onSplit={onSplit} onMergeNext={onMergeNext} />
+ {/* Everything set once and rarely revisited: timing, shot mode, layer, camera. */}
+ <details className="group/settings rounded border border-port-border">
+ <summary className="flex min-h-[44px] cursor-pointer items-center gap-2 px-2 text-xs marker:content-none sm:min-h-[32px] [&::-webkit-details-marker]:hidden">
+ <ChevronRight size={12} aria-hidden="true" className="shrink-0 transition-transform group-open/settings:rotate-90" />
+ <span className="shrink-0 font-medium">Shot settings</span>
+ <span className="min-w-0 truncate text-port-text-muted">· {settingsSummary}</span>
+ </summary>
+ <div className="space-y-2 p-2 pt-0">
<div className="flex flex-wrap gap-2 items-center text-xs">
{SCENE_TIME_FIELDS.map(([labelText, key]) => {
const toValue = (v) => (v === '' ? null : Number(v));
return (
<label key={key} className="flex items-center gap-1">{labelText}
- <input type="number" min="0" step="0.1" value={scene[key] ?? ''} className="w-16 bg-port-bg border border-port-border rounded px-1 py-1 min-h-[44px] sm:min-h-0"
+ <input type="number" min="0" step="0.1" value={scene[key] ?? ''} className="w-20 bg-port-bg border border-port-border rounded px-1 py-1 min-h-[44px] sm:min-h-0"
onChange={(e) => onEditLocal(scene.sceneId, { [key]: toValue(e.target.value) })}
onBlur={(e) => onSave(scene.sceneId, { [key]: toValue(e.target.value) })} />
</label>
@@ -293,45 +551,28 @@ export default function SceneCard({
<input type="checkbox" checked={loops} disabled={performance} onChange={(e) => applyPatch({ loop: e.target.checked })} />
Loop clip
</label>
+ </div>
+ <div className="flex flex-wrap gap-2 items-center text-xs">
+ <label htmlFor={fieldId('layer')}>Layer</label>
+ <select id={fieldId('layer')} value={layer} onChange={(e) => applyPatch({ visualLayer: e.target.value })}
+ className="bg-port-bg border border-port-border rounded px-1 py-1 min-h-[44px] sm:min-h-0">
+ {MUSIC_VIDEO_VISUAL_LAYERS.map((value) => <option key={value} value={value}>{LAYER_LABELS[value]}</option>)}
+ </select>
{/* A performance is sung footage — only the footage layer offers it. */}
{layer === 'footage' && (
<>
<label htmlFor={shotModeId} className="flex items-center gap-1">Shot</label>
- <select id={shotModeId} value={performance ? (scene.performanceStyle === 'music' ? 'music' : 'performance') : 'cutaway'}
+ <select id={shotModeId} value={shotModeValue}
onChange={(e) => applyPatch(e.target.value === 'cutaway' ? { shotMode: 'cutaway' }
: e.target.value === 'music' ? { shotMode: 'performance', performanceStyle: 'music' }
// Clear the style only when one is stored, so a plain lip-sync switch stays one field.
: { shotMode: 'performance', ...(scene.performanceStyle ? { performanceStyle: null } : {}) })}
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. Lip-sync: a singer's mouth follows the song. Music-driven: the song slice drives the whole frame's motion (a drummer on the beat). Both need a source-audio provider.">
- <option value="cutaway">Cutaway</option>
- <option value="performance">Performance (lip-sync)</option>
- <option value="music">Performance (music-driven)</option>
+ {Object.entries(SHOT_MODE_LABELS).map(([value, text]) => <option key={value} value={value}>{text}</option>)}
</select>
</>
)}
- </div>
- {/* A music-driven shot follows the whole mix, not one voice. */}
- {performance && scene.performanceStyle !== 'music' && (
- <div className="flex flex-wrap items-center gap-2 text-xs">
- <label htmlFor={fieldId('speaker')}>Speaker / singer</label>
- <input id={fieldId('speaker')} value={scene.performanceSpeaker || ''} maxLength={120}
- onChange={(e) => { setSpeakerDirty(true); onEditLocal(scene.sceneId, { performanceSpeaker: e.target.value }); }}
- onBlur={(e) => {
- setSpeakerSaving(true);
- Promise.resolve(onSave(scene.sceneId, { performanceSpeaker: e.target.value || null }))
- .then((saved) => setSpeakerDirty(saved === false), () => setSpeakerDirty(true))
- .finally(() => setSpeakerSaving(false));
- }}
- className="bg-port-bg border border-port-border rounded px-2 py-1" placeholder="Intended singer" />
- </div>
- )}
- <div className="flex flex-wrap gap-2 items-center text-xs">
- <label htmlFor={fieldId('layer')}>Layer</label>
- <select id={fieldId('layer')} value={layer} onChange={(e) => applyPatch({ visualLayer: e.target.value })}
- className="bg-port-bg border border-port-border rounded px-1 py-1 min-h-[44px] sm:min-h-0">
- {MUSIC_VIDEO_VISUAL_LAYERS.map((value) => <option key={value} value={value}>{LAYER_LABELS[value]}</option>)}
- </select>
{layer === 'still' && (
<>
<label htmlFor={fieldId('move')}>Move</label>
@@ -376,194 +617,55 @@ export default function SceneCard({
</>
)}
</div>
- {layer !== 'card' && <SceneCameraControls scene={scene} fieldId={fieldId} onEditLocal={onEditLocal} onSave={onSave} />}
{layer !== 'footage' && !layered && (
<p className="text-[11px] text-port-text-muted">
{LAYER_LABELS[layer]} sections render in composed or document mode — a plain render plays this scene&apos;s footage.
</p>
)}
- {layer !== 'footage' && layered && !sceneHasAuthoredSpan(scene) && (
- <p role="alert" className="text-[11px] text-port-warning">
- Set a start and end — a {{ card: 'title card', code: 'code-drawn shot' }[layer] || 'still'} runs for exactly its span.
- </p>
- )}
- <SceneTimingPlan timing={timing} sceneId={scene.sceneId} lipSyncBackend={renderLane} onSplit={onSplit} onMergeNext={onMergeNext} />
- {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 {clipSec.toFixed(1)}s — the render won&apos;t repeat it.
- Trim the shot, continue or regenerate a longer clip, or loop it on purpose.
- </span>
- <button type="button" onClick={() => applyPatch({ endSec: Math.round((scene.startSec + clipSec) * 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>
- <button type="button" onClick={() => applyPatch({ 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>
+ {layer !== 'card' && <SceneCameraControls scene={scene} fieldId={fieldId} onEditLocal={onEditLocal} onSave={onSave} />}
+ </div>
+ </details>
+ {/* A music-driven shot follows the whole mix, not one voice; a lip-sync needs its singer before it renders. */}
+ {performance && scene.performanceStyle !== 'music' && (
+ <div className="flex flex-wrap items-center gap-2 text-xs">
+ <label htmlFor={fieldId('speaker')}>Speaker / singer</label>
+ <input id={fieldId('speaker')} value={scene.performanceSpeaker || ''} maxLength={120}
+ onChange={(e) => { setSpeakerDirty(true); onEditLocal(scene.sceneId, { performanceSpeaker: e.target.value }); }}
+ onBlur={(e) => {
+ setSpeakerSaving(true);
+ Promise.resolve(onSave(scene.sceneId, { performanceSpeaker: e.target.value || null }))
+ .then((saved) => setSpeakerDirty(saved === false), () => setSpeakerDirty(true))
+ .finally(() => setSpeakerSaving(false));
+ }}
+ className="bg-port-bg border border-port-border rounded px-2 py-1" placeholder="Intended singer" />
</div>
)}
- {codeShot ? (
- <p className="text-xs text-port-text-muted" data-testid="code-shot-note">
- The composition draws this shot, so it needs no frame or clip.
- {!documentComposition && ' A composed render shows it as a black frame under the typography; render from a composition document to draw it.'}
- </p>
- ) : (<>
- {/* Reference frame — the still image that seeds this shot (Phase 1b) */}
- <div className="flex flex-col gap-2 sm:flex-row sm:items-start">
- <textarea
- aria-label="Reference frame prompt"
- value={scene.framePrompt || ''} rows={2}
- onChange={(e) => onEditLocal(scene.sceneId, { framePrompt: e.target.value })}
- onBlur={(e) => onSave(scene.sceneId, { framePrompt: e.target.value || null })}
- placeholder="Reference frame prompt — the still that seeds this shot (defaults to the shot prompt)"
- className="flex-1 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm"
- />
- <div className="flex items-center gap-2">
- {scene.referenceImageId && (
- <button
- type="button"
- onClick={() => onOpenPreview?.(`image:${scene.referenceImageId}`)}
- aria-label={`View scene ${index + 1} reference frame full size`}
- title={`View scene ${index + 1} reference frame full size`}
- className="shrink-0 rounded border border-port-border overflow-hidden focus:outline-none focus:ring-2 focus:ring-port-accent"
- >
- <img
- src={`/data/images/${scene.referenceImageId}`}
- alt=""
- className="w-32 aspect-video object-cover block"
- />
- </button>
- )}
- <div className="flex flex-col gap-1">
- <button onClick={() => onGenerateFrame(scene)} disabled={!!generatingFrame}
- 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={scene.referenceImageId
- ? 'Render another candidate frame — your selected frame stays until you pick a new one'
- : 'Generate a still reference frame for this scene'}>
- {generatingFrame ? <Activity size={14} className="animate-spin" /> : <ImageIcon size={14} />}
- {generatingFrame ? 'Generating frame…' : (scene.referenceImageId ? 'New frame take' : 'Generate frame')}
- </button>
- {onImportTake && (
- <button type="button" onClick={() => onImportTake(scene)} disabled={takeBusy}
- className="flex items-center gap-1 bg-port-bg border border-port-border hover:bg-port-border/40 disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0 whitespace-nowrap"
- title="Add a frame from the gallery or an upload (e.g. made in an external tool) as a take">
- <ImagePlus size={14} /> Import take
- </button>
- )}
- {onContinueFromPrevious && layer === 'footage' && index > 0 && (
- <>
- <button type="button" onClick={() => onContinueFromPrevious(scene, { keepStillAsEnd: keepStillAsEnd && Boolean(scene.referenceImageId) })}
- disabled={takeBusy || !previousHasClip}
- className="flex items-center gap-1 bg-port-bg border border-port-border hover:bg-port-border/40 disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0 whitespace-nowrap"
- title={previousHasClip ? 'Start this shot from the last frame the previous shot shows in the cut' : 'The previous shot needs a clip first'}>
- <SkipForward size={14} /> From previous shot
- </button>
- {scene.referenceImageId && (
- <label htmlFor={`mv-scene-${scene.sceneId}-keep-still-end`} className="flex items-center gap-1 text-[11px] text-port-text-muted min-h-[44px] sm:min-h-0">
- <input id={`mv-scene-${scene.sceneId}-keep-still-end`} type="checkbox" checked={keepStillAsEnd}
- onChange={(e) => setKeepStillAsEnd(e.target.checked)} />
- Keep this frame as the end frame
- </label>
- )}
- </>
+ {(scene.visualIntent || scene.direction || scene.direction?.actionContract) && (
+ <details className="group/direction rounded border border-port-border">
+ <summary className="flex min-h-[44px] cursor-pointer items-center gap-2 px-2 text-xs marker:content-none sm:min-h-[32px] [&::-webkit-details-marker]:hidden">
+ <ChevronRight size={12} aria-hidden="true" className="shrink-0 transition-transform group-open/direction:rotate-90" />
+ <span className="shrink-0 font-medium">Direction</span>
+ {scene.visualIntent && <span className="min-w-0 truncate text-port-text-muted">· {scene.visualIntent}</span>}
+ </summary>
+ <div className="space-y-2 p-2 pt-0 text-[11px] text-port-text-muted">
+ {scene.visualIntent && <p className="break-words">Intent: {scene.visualIntent}</p>}
+ {/* Applied treatment direction (#8980) — appended to both generated prompts. */}
+ {scene.direction && (
+ <p className="break-words" title={scene.direction.frameClause}>
+ Direction: {scene.direction.mode}{scene.direction.medium ? ` · planned ${MUSIC_VIDEO_MEDIUM_LABELS[scene.direction.medium] || scene.direction.medium}${scene.direction.mediumPinned ? ' (pinned)' : ''}` : ''}{scene.direction.focalSubject ? ` · ${scene.direction.focalSubject}` : ''}
+ {scene.direction.typographyRole !== 'none' ? ` · ${scene.direction.typographyRole} text, ${scene.direction.negativeSpace} region kept clear` : ' · no text'}
+ </p>
)}
+ <ShotActionInspector contract={scene.direction?.actionContract} scene={scene} />
+ <PlateComparison scene={scene} frames={false} />
</div>
- </div>
- </div>
- <SceneTakeStrip scene={scene} kind="image" busy={takeBusy}
- onSelect={(take) => onSelectTake?.(scene, take)}
- onReview={(take, review) => onReviewTake?.(scene, take, review)}
- onOpenPreview={onOpenPreview} />
- {/* Style-break end frame (#11173) — what a fal clip ends on */}
- {onGenerateEndFrame && layer === 'footage' && (
- <SceneEndFrame scene={scene} index={index} generating={!!generatingEndFrame} onGenerate={onGenerateEndFrame}
- onEditLocal={onEditLocal} onSave={onSave} onOpenPreview={onOpenPreview} takeBusy={takeBusy}
- onSelectTake={onSelectTake} onReviewTake={onReviewTake} videoSettings={falVideoSettings} />
+ </details>
)}
- {/* Render: the motion prompt, where this shot renders and what it costs, then its clip (Phase 1). */}
- <section aria-label="Render" className="space-y-2 rounded border border-port-border p-2">
- <h4 className="text-xs font-medium">Render</h4>
- {layer === 'footage' && promptField}
- <div className="flex flex-wrap items-center gap-2">
- <SceneRenderTarget id={fieldId('render-on')} value={renderPick} onChange={setRenderPick} performance={performance}
- saved={falVideoSettings || {}} disabled={!!generatingVideo} />
- {renderCost && <span className="text-[11px] text-port-text-muted">{renderCost}</span>}
- </div>
- <div className="flex items-center gap-2 flex-wrap">
- {scene.videoHistoryId && performance && (
- <PerformanceEvidence key={scene.videoHistoryId} clipSrc={clipSrc} instruction={instruction}
- temporal={performanceReview?.shot} excerptStartSec={performanceReview?.excerptStartSec || 0}
- repair={repairPlan} repairBusy={repairBusy || settingsSaving || generatingVideo || takeBusy}
- onRepair={onRepairPerformance ? () => onRepairPerformance(scene.sceneId, {
- excerptId: performanceReview.excerptId, sourceAssetId: repairPlan.sourceAssetId, boundarySec: repairPlan.boundarySec,
- }) : null} />
- )}
- {scene.videoHistoryId && !performance && (
- <div className="relative w-40 shrink-0">
- <video
- ref={clipPlayerRef}
- src={clipSrc}
- className="w-full aspect-video object-cover rounded border border-port-border bg-black"
- muted
- playsInline
- preload="metadata"
- controls
- onLoadedMetadata={(e) => {
- const sec = e.currentTarget.duration;
- if (Number.isFinite(sec) && sec > 0) setClipMeta({ id: scene.videoHistoryId, sec });
- }}
- />
- {/* Corner expand — do not put the open handler on <video> itself;
- that would fight native play/pause controls. Shape matches
- ScenePreview's open-in-new-tab overlay. Pause first so the
- lightbox's unmuted autoplay doesn't double-play the audio. */}
- <button
- type="button"
- onClick={() => {
- clipPlayerRef.current?.pause();
- onOpenPreview?.(`video:${scene.videoHistoryId}`);
- }}
- aria-label={`View scene ${index + 1} clip full size`}
- title={`View scene ${index + 1} clip full size`}
- className="always-dark absolute top-1 right-1 min-h-[44px] min-w-[44px] sm:min-h-0 sm:min-w-0 p-1 flex items-center justify-center rounded bg-black/50 text-white hover:bg-black/80 focus:outline-none focus:ring-2 focus:ring-port-accent"
- >
- <Maximize2 className="w-3 h-3" />
- </button>
- </div>
- )}
- <button onClick={generateVideo}
- disabled={!!videoRefusal}
- 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={videoRefusal
- || (performance ? `${capability.style === 'music' ? "Animate this scene's frame to the song" : "Lip-sync this scene's frame to the song"} via ${capability.label} — ${performanceCost}`
- : "Render this shot's clip from its still")}>
- {generatingVideo ? <Activity size={14} className="animate-spin" /> : <Video size={14} />}
- {generatingVideo ? 'Rendering…' : (scene.videoHistoryId ? 'Render again' : 'Render')}
- </button>
- {scene.videoHistoryId && canContinueShot && (
- <button
- onClick={() => onContinueVideo(scene)}
- disabled={settingsSaving || !!generatingVideo}
- className="flex items-center gap-1 bg-port-bg border border-port-border hover:bg-port-border/40 disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0 whitespace-nowrap"
- title="Native-extend this clip from its final latent frames and attach the longer result to this scene"
- >
- <Video size={14} /> Continue shot
- </button>
- )}
- {onImportClipTake && (
- <button type="button" onClick={() => onImportClipTake(scene)} disabled={takeBusy}
- className="flex items-center gap-1 bg-port-bg border border-port-border hover:bg-port-border/40 disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0 whitespace-nowrap"
- title="Pick an existing clip from the gallery (e.g. made in an external tool) as a take">
- <Clapperboard size={14} /> Import clip take
- </button>
- )}
- </div>
- <SceneTakeStrip scene={scene} kind="video" busy={takeBusy}
- onSelect={(take) => onSelectTake?.(scene, take)}
- onReview={(take, review) => onReviewTake?.(scene, take, review)}
- onOpenPreview={onOpenPreview} />
- </section>
- </>)}
</div>
+ {swapKind && (
+ <SceneTakePicker open onClose={() => setSwapKind(null)} projectId={projectId} scene={scene} kind={swapKind}
+ shotNumbers={shotNumbers} busy={takeBusy} onPlace={(pick) => onPlacePoolItem?.(scene, pick)} />
+ )}
</details>
{failure && (
<div className="mt-1 flex items-start gap-2 rounded border border-port-error/40 bg-port-error/10 px-2 py-1 text-xs text-port-error">
diff --git a/client/src/components/musicVideo/SceneCard.test.jsx b/client/src/components/musicVideo/SceneCard.test.jsx
index 394017aa9b..7151b25b7d 100644
--- a/client/src/components/musicVideo/SceneCard.test.jsx
+++ b/client/src/components/musicVideo/SceneCard.test.jsx
@@ -1,6 +1,6 @@
import { useState } from 'react';
import { describe, expect, it, vi } from 'vitest';
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
vi.mock('../../hooks/useVideoFileSrc.js', () => ({ useVideoFileSrc: () => ({}) }));
import SceneCard from './SceneCard.jsx';
import { GROK_VIDEO_DURATIONS } from '../../lib/grokVideoClip.js';
@@ -210,11 +210,14 @@ describe('move buttons (#10785)', () => {
const onMove = vi.fn();
const props = { scene, index: 1, isLast: false, onMove, onEditLocal: () => {}, onSave: () => {} };
const { rerender } = render(<SceneCard {...props} />);
- expect(screen.getByRole('button', { name: /Move earlier/ }).disabled).toBe(false);
- expect(screen.getByRole('button', { name: /Move later/ }).disabled).toBe(false);
+ fireEvent.click(screen.getByRole('button', { name: 'Shot actions' }));
+ expect(screen.getByRole('menuitem', { name: /Move earlier/ }).disabled).toBe(false);
+ fireEvent.click(screen.getByRole('menuitem', { name: /Move later/ }));
+ expect(onMove).toHaveBeenCalledWith(1, 1);
rerender(<SceneCard {...props} documentComposition />);
- expect(screen.getByRole('button', { name: /Move earlier/ }).disabled).toBe(true);
- expect(screen.getByRole('button', { name: /Move later/ }).disabled).toBe(true);
+ fireEvent.click(screen.getByRole('button', { name: 'Shot actions' }));
+ expect(screen.getByRole('menuitem', { name: /Move earlier/ }).disabled).toBe(true);
+ expect(screen.getByRole('menuitem', { name: /Move later/ }).disabled).toBe(true);
expect(screen.getByText(/comes from the composition document/)).toBeTruthy();
});
});
@@ -332,6 +335,10 @@ describe('Render follows the shot locks', () => {
);
const { rerender } = render(card('open', 'open'));
expect(screen.getByRole('button', { name: 'Render again' })).toHaveProperty('title', 'Lock the still first');
+ // On a phone there is no tooltip: the reason and the lock it needs sit under Render.
+ const refusal = screen.getByTestId('render-refusal');
+ expect(refusal.textContent).toContain('Lock the still first');
+ expect(refusal.querySelector('button')).toBeTruthy();
rerender(card('locked', 'locked'));
expect(screen.getByRole('button', { name: 'Render again' }).disabled).toBe(true);
expect(screen.getByRole('button', { name: 'Render again' }).title).toMatch(/^Video locked/);
@@ -340,3 +347,24 @@ describe('Render follows the shot locks', () => {
expect(onGenerateVideo).toHaveBeenCalledWith(scene);
});
});
+
+describe('start and end frames', () => {
+ // Uniquely catches the end frame hiding behind a collapsed row, losing its own actions, or the Render section not saying which renderer ends on it.
+ it('shows the start and end frames as a pair, works on the tapped one, and says which renderer ends on the end frame', () => {
+ const scene = { sceneId: 's1', prompt: 'She looks into the lens', referenceImageId: 'start.png', endImageId: 'end.png', startSec: 0, endSec: 4,
+ takes: [{ takeId: 't1', kind: 'image', assetId: 'start.png', status: 'selected' }, { takeId: 't2', kind: 'endImage', assetId: 'end.png', status: 'selected' }] };
+ render(<SceneCard scene={scene} index={0} expanded onEditLocal={() => {}} onSave={() => {}} onGenerateEndFrame={() => {}} onPlacePoolItem={() => {}}
+ falVideoSettings={{ backend: 'local' }} />);
+ const pair = screen.getByRole('group', { name: 'Start and end frames' });
+ expect(within(pair).getByRole('button', { name: 'Start frame' }).getAttribute('aria-pressed')).toBe('true');
+ expect(screen.queryByLabelText('End frame prompt')).toBeNull();
+ fireEvent.click(within(pair).getByRole('button', { name: 'End frame' }));
+ expect(screen.getByLabelText('End frame prompt')).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'Clear scene 1 end frame' })).toBeTruthy();
+ expect(screen.getByTestId('end-frame-plan').textContent).toMatch(/ignores it/);
+ const pick = screen.getByLabelText('Render on');
+ expect(within(pick).getByRole('option', { name: /Kling v3 Pro.*ends on end frame/ })).toBeTruthy();
+ fireEvent.change(pick, { target: { value: 'fal:fal-ai/kling-video/v3/pro/image-to-video' } });
+ expect(screen.getByTestId('end-frame-plan').textContent).toBe('The clip ends on the end frame.');
+ });
+});
diff --git a/client/src/components/musicVideo/SceneEndFrame.jsx b/client/src/components/musicVideo/SceneEndFrame.jsx
index 3709326e2c..c4d67f7146 100644
--- a/client/src/components/musicVideo/SceneEndFrame.jsx
+++ b/client/src/components/musicVideo/SceneEndFrame.jsx
@@ -1,78 +1,75 @@
-import { Activity, Wand2, X } from 'lucide-react';
+import { Activity, Shuffle, Wand2, X } from 'lucide-react';
import SceneTakeStrip from './SceneTakeStrip.jsx';
import { sceneEndFramePlan } from '../../../../server/lib/musicVideoEndFrame.js';
+import { falSceneTake } from '../../lib/musicVideoShotTiming.js';
+
+const BUTTON = 'flex items-center gap-1 bg-port-bg border border-port-border hover:bg-port-border/40 disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0 whitespace-nowrap';
+
+/**
+ * Whether a clip rendered with `settings` (the project's saved renderer, or a
+ * scene card's Render on pick merged over it) ends on the scene's end frame:
+ * the same model the clip request is built with (useMusicVideoSceneMedia
+ * generateSceneVideo), so a saved end-frame upgrade model counts.
+ */
+export function sceneEndFramePlanFor(scene, settings = {}) {
+ const mode = settings.generationMode === 'suppliedAudio' || (settings.backend === 'local' && settings.generationMode === 'audioReactive') ? 'a2v' : 'image';
+ const falModelId = settings.backend === 'fal' ? falSceneTake({ scene, videoSettings: settings }).modelId : null;
+ return sceneEndFramePlan(scene, { backend: settings.backend || null, falModelId, mode });
+}
/**
- * A scene's optional style-break end frame (#11173): a still the clip moves
- * into from its photographic start frame, such as a pencil-sketch rotoscope or
- * a magazine-cutout collage. The director describes it, renders it from the
- * selected start frame, and picks among its takes like any frame. A fal clip on
- * a model that takes an end frame ends on it; the note says when the current
- * renderer will ignore it.
+ * A shot's end frame (#11173): the still its clip moves into from the start
+ * frame, such as her head thrown back for a possession beat, or a pencil-sketch
+ * rotoscope of the same frame. The director describes it and renders it from
+ * the start frame, swaps one in from the unused stills, and picks among its
+ * takes like any frame. Only renderers that take an end frame use it; the
+ * Render section says whether the current pick does.
*/
export default function SceneEndFrame({
scene, index, generating = false, onGenerate, onEditLocal, onSave, onOpenPreview,
- takeBusy = false, onSelectTake, onReviewTake, videoSettings = null,
+ takeBusy = false, onSelectTake, onReviewTake, onSwap = null, disabled = false,
}) {
- const settings = videoSettings || {};
- // Same mode the clip request is built with (useMusicVideoSceneMedia generateSceneVideo).
- const mode = settings.generationMode === 'suppliedAudio' || (settings.backend === 'local' && settings.generationMode === 'audioReactive') ? 'a2v' : 'image';
- const plan = sceneEndFramePlan(scene, { backend: settings.backend || null, falModelId: settings.falModelId || null, mode });
const promptId = `mv-scene-${scene.sceneId}-end-frame-prompt`;
+ const clear = () => { onEditLocal(scene.sceneId, { endImageId: null }); onSave(scene.sceneId, { endImageId: null }); };
return (
- <details className="rounded border border-port-border bg-port-bg/40 px-2 py-1.5" open={Boolean(scene.endImageId || scene.endFramePrompt)}>
- <summary className="cursor-pointer text-xs text-port-text-muted min-h-[44px] sm:min-h-0 flex items-center">
- End frame (style break){scene.endImageId ? ' · set' : ''}
- </summary>
- <div className="mt-2 space-y-2">
- <div className="flex flex-col gap-2 sm:flex-row sm:items-start">
- <div className="flex-1 min-w-0">
- <label htmlFor={promptId} className="sr-only">End frame prompt</label>
- <textarea
- id={promptId}
- value={scene.endFramePrompt || ''} rows={2}
- onChange={(e) => onEditLocal(scene.sceneId, { endFramePrompt: e.target.value })}
- onBlur={(e) => onSave(scene.sceneId, { endFramePrompt: e.target.value || null })}
- placeholder="What the last frame becomes, e.g. the same frame as a pencil-sketch rotoscope"
- className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm"
- />
- </div>
- <div className="flex items-center gap-2">
- {scene.endImageId && (
- <div className="relative shrink-0">
- <button type="button" onClick={() => onOpenPreview?.(`image:${scene.endImageId}`)}
- aria-label={`View scene ${index + 1} end frame full size`}
- className="block rounded border border-port-border overflow-hidden focus:outline-none focus:ring-2 focus:ring-port-accent">
- <img src={`/data/images/${encodeURIComponent(scene.endImageId)}`} alt="" className="w-32 aspect-video object-cover block" />
- </button>
- <button type="button" onClick={() => { onEditLocal(scene.sceneId, { endImageId: null }); onSave(scene.sceneId, { endImageId: null }); }}
- aria-label={`Clear scene ${index + 1} end frame`} title="Clear the end frame (its takes stay)"
- className="always-dark absolute top-1 right-1 min-h-[44px] min-w-[44px] sm:min-h-0 sm:min-w-0 p-1 flex items-center justify-center rounded bg-black/50 text-white hover:bg-black/80">
- <X className="w-3 h-3" />
- </button>
- </div>
- )}
- <button type="button" onClick={() => onGenerate?.(scene)}
- disabled={generating || !scene.referenceImageId || !scene.endFramePrompt?.trim()}
- title={!scene.referenceImageId ? 'Generate a reference frame first'
- : !scene.endFramePrompt?.trim() ? 'Describe the end frame first'
- : 'Render the end frame from this scene\'s selected start frame'}
- 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">
- {generating ? <Activity size={14} className="animate-spin" /> : <Wand2 size={14} />}
- {generating ? 'Generating end frame…' : (scene.endImageId ? 'New end frame take' : 'Generate end frame')}
- </button>
- </div>
- </div>
+ <div className="space-y-2">
+ <label htmlFor={promptId} className="block text-[11px] text-port-text-muted">End frame prompt</label>
+ <textarea
+ id={promptId}
+ value={scene.endFramePrompt || ''} rows={2}
+ onChange={(e) => onEditLocal(scene.sceneId, { endFramePrompt: e.target.value })}
+ onBlur={(e) => onSave(scene.sceneId, { endFramePrompt: e.target.value || null })}
+ placeholder="Where the shot ends, e.g. her head thrown back, eyes white, lit from below"
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm"
+ />
+ <div className="flex flex-wrap gap-2">
+ <button type="button" onClick={() => onGenerate?.(scene)}
+ disabled={disabled || generating || !scene.referenceImageId || !scene.endFramePrompt?.trim()}
+ title={!scene.referenceImageId ? 'Generate a start frame first'
+ : !scene.endFramePrompt?.trim() ? 'Describe the end frame first'
+ : "Render the end frame from this shot's start frame"}
+ 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">
+ {generating ? <Activity size={14} className="animate-spin" /> : <Wand2 size={14} />}
+ {generating ? 'Generating end frame…' : (scene.endImageId ? 'New end frame take' : 'Generate end frame')}
+ </button>
+ {onSwap && (
+ <button type="button" onClick={onSwap} disabled={disabled || takeBusy} className={BUTTON}
+ title="Use a still made for this video that no shot uses as the end frame">
+ <Shuffle size={14} /> Swap from unused
+ </button>
+ )}
{scene.endImageId && (
- <p className={`text-[11px] ${plan.used ? 'text-port-text-muted' : 'text-port-warning'}`}>
- {plan.used ? 'The clip ends on this frame.' : plan.reason}
- </p>
+ <button type="button" onClick={clear} disabled={disabled} className={BUTTON}
+ aria-label={`Clear scene ${index + 1} end frame`} title="The clip ends where the model takes it; the end frame's takes stay">
+ <X size={14} /> No end frame
+ </button>
)}
- <SceneTakeStrip scene={scene} kind="endImage" busy={takeBusy}
- onSelect={(take) => onSelectTake?.(scene, take)}
- onReview={(take, review) => onReviewTake?.(scene, take, review)}
- onOpenPreview={onOpenPreview} />
</div>
- </details>
+ <p className="text-[11px] text-port-text-muted">The clip ends here on a fal.ai model marked &quot;ends on end frame&quot; under Render on.</p>
+ <SceneTakeStrip scene={scene} kind="endImage" busy={takeBusy}
+ onSelect={(take) => onSelectTake?.(scene, take)}
+ onReview={(take, review) => onReviewTake?.(scene, take, review)}
+ onOpenPreview={onOpenPreview} />
+ </div>
);
}
diff --git a/client/src/components/musicVideo/SceneRenderTarget.jsx b/client/src/components/musicVideo/SceneRenderTarget.jsx
index 180b04afa7..0c42bc9087 100644
--- a/client/src/components/musicVideo/SceneRenderTarget.jsx
+++ b/client/src/components/musicVideo/SceneRenderTarget.jsx
@@ -1,4 +1,10 @@
-import { FAL_DEFAULT_IMAGE_VIDEO_MODEL, FAL_IMAGE_VIDEO_MODELS, describeFalVideoRate, getFalVideoModel } from '../../lib/falVideoModels.js';
+import {
+ FAL_DEFAULT_IMAGE_VIDEO_MODEL, FAL_IMAGE_VIDEO_MODELS, coerceFalVideoSeconds, describeFalVideoRate, falVideoResolutions, getFalVideoModel,
+} from '../../lib/falVideoModels.js';
+import { GROK_VIDEO_DURATIONS } from '../../lib/grokVideoClip.js';
+import { grokCoverage } from '../../lib/musicVideoShotTiming.js';
+import { isAudioToVideoRuntime, isLtx2FamilyRuntime } from '../../lib/runnerFamilies';
+import { frameOptionsForModel } from '../../lib/videoGenParams.js';
/**
* Where one shot's clip renders, picked on its card: the project's saved
@@ -7,51 +13,185 @@ import { FAL_DEFAULT_IMAGE_VIDEO_MODEL, FAL_IMAGE_VIDEO_MODELS, describeFalVideo
* shot renders on fal's source-audio route, so fal is one choice there, and
* Grok (no audio) renders cutaways only.
* The pick is a value string: '' (saved), 'local', 'grok', 'fal' or 'fal:<modelId>'.
+ *
+ * A picked lane shows its own options, from the same definitions the Video Gen
+ * form and the project's render settings read: the local model and clip length
+ * (frame counts), Grok's clip lengths, and a fal model's lengths and
+ * resolutions. Each length defaults to the shortest one that covers the shot.
+ * `options` holds only what the director changed: `{ modelId, numFrames,
+ * grokDuration, falDuration, falResolution }`.
*/
const BACKEND_LABELS = { local: 'Local LTX', grok: 'Grok', fal: 'fal.ai' };
+// The local render's frame rate when the request names none (generateVideo's default).
+const LOCAL_FPS = 24;
+const SELECT = 'min-w-0 max-w-full bg-port-bg border border-port-border rounded px-1 py-1 text-xs min-h-[44px] sm:min-h-0 disabled:opacity-50';
function savedLabel(saved) {
if (saved.backend === 'fal') return `fal.ai · ${getFalVideoModel(saved.falModelId || FAL_DEFAULT_IMAGE_VIDEO_MODEL)?.label || 'video'}`;
return BACKEND_LABELS[saved.backend] || 'install default';
}
-export function renderTargetOptions({ performance, saved }) {
+export function renderTargetOptions({ performance, saved, endFrame = false }) {
return [
{ value: '', label: `Project setting · ${savedLabel(saved)}` },
- { value: 'local', label: performance ? 'Local LTX-2.5 lip-sync (free)' : 'Local LTX' },
+ { value: 'local', label: performance ? 'Local LTX lip-sync (free)' : 'Local LTX (free)' },
{ value: 'grok', label: performance ? 'Grok (cutaways only)' : 'Grok', disabled: performance },
...(performance
? [{ value: 'fal', label: 'fal.ai (song-driven)' }]
: FAL_IMAGE_VIDEO_MODELS.map((model) => {
const rate = describeFalVideoRate(model.id);
- return { value: `fal:${model.id}`, label: `fal.ai · ${model.label}${rate ? ` · ${rate}` : ''}` };
+ return { value: `fal:${model.id}`, label: `fal.ai · ${model.label}${rate ? ` · ${rate}` : ''}${endFrame && model.endImage ? ' · ends on end frame' : ''}` };
})),
];
}
-/** The settings overrides a pick makes for this render, or null for the project's saved renderer. */
-export function renderTargetOverrides(value, saved) {
+const isLtx25 = (model) => /^ltx25/.test(model?.runtime || '');
+
+/** Local models a shot can render on: any image-to-video model, or for lip-sync only the LTX audio-to-video ones. */
+export const localModelChoices = (models, performance) => (performance
+ ? models.filter((model) => isLtx2FamilyRuntime(model.runtime) && isAudioToVideoRuntime(model.runtime))
+ : models);
+
+/**
+ * The local model a shot renders on unless the director picks another: the
+ * project's pinned local model, else LTX-2.5, else this install's default.
+ * Never an empty "install default", so the picker always names the model.
+ */
+export function defaultLocalModelId({ models = [], saved = {}, defaultModel = '', performance = false }) {
+ const choices = localModelChoices(models, performance);
+ const has = (id) => !!id && choices.some((model) => model.id === id);
+ if (has(saved.modelId)) return saved.modelId;
+ return choices.find(isLtx25)?.id || (has(defaultModel) ? defaultModel : choices[0]?.id || '');
+}
+
+const shotSpan = (scene) => (typeof scene?.startSec === 'number' && typeof scene?.endSec === 'number' && scene.endSec > scene.startSec
+ ? scene.endSec - scene.startSec : null);
+
+/** The shortest frame count of `model` that covers the shot, else its longest; null for an untimed shot. */
+export function coveringFrames(model, spanSec) {
+ if (!(spanSec > 0)) return null;
+ const frames = frameOptionsForModel(model);
+ return frames.find((count) => count / LOCAL_FPS >= spanSec - 1e-6) ?? frames[frames.length - 1];
+}
+
+const falLengths = (model) => {
+ const rule = model?.duration;
+ if (rule?.kind === 'enum') return rule.values;
+ if (rule?.kind === 'range') return Array.from({ length: rule.max - rule.min + 1 }, (_, i) => rule.min + i);
+ return [];
+};
+
+/**
+ * The settings overrides a pick and its options make for this render, or null
+ * for the project's saved renderer. `context` carries what fills an unpicked
+ * option: the installed local models, this install's default, the shot.
+ */
+export function renderTargetOverrides(value, saved, options = {}, context = {}) {
if (!value) return null;
- if (!value.startsWith('fal')) return { backend: value };
+ const spanSec = shotSpan(context.scene);
+ if (value === 'local') {
+ const modelId = options.modelId || defaultLocalModelId({ ...context, saved });
+ const model = (context.models || []).find((m) => m.id === modelId);
+ const numFrames = context.performance ? null : options.numFrames || (model ? coveringFrames(model, spanSec) : null);
+ return { backend: 'local', ...(modelId ? { modelId } : {}), ...(numFrames ? { numFrames } : {}) };
+ }
+ if (value === 'grok') {
+ return { backend: 'grok', ...(options.grokDuration || spanSec != null ? { grokDuration: options.grokDuration || grokCoverage(spanSec).requestSec } : {}) };
+ }
const falModelId = value.slice(4) || null;
if (!falModelId) return { backend: 'fal' };
// Each model has its own resolutions, so the saved one only carries over to the saved model.
const sameModel = falModelId === (saved.falModelId || FAL_DEFAULT_IMAGE_VIDEO_MODEL);
// A picked model is the one this render uses, end frame or not.
- return { backend: 'fal', falModelId, falEndFrameModelId: falModelId, ...(sameModel ? {} : { falResolution: null, falDuration: null }) };
+ return {
+ backend: 'fal', falModelId, falEndFrameModelId: falModelId,
+ ...(sameModel ? {} : { falResolution: null, falDuration: null }),
+ ...(options.falDuration ? { falDuration: options.falDuration } : {}),
+ ...(options.falResolution ? { falResolution: options.falResolution } : {}),
+ };
+}
+
+const formatSec = (sec) => `${Math.round(sec * 10) / 10}s`;
+
+function OptionSelect({ id, label, value, onChange, disabled, children }) {
+ return (
+ <span className="flex min-w-0 items-center gap-1">
+ <label htmlFor={id} className="text-xs text-port-text-muted">{label}</label>
+ <select id={id} value={value} onChange={(e) => onChange(e.target.value)} disabled={disabled} className={SELECT}>{children}</select>
+ </span>
+ );
}
-export default function SceneRenderTarget({ id, value, onChange, performance, saved, disabled = false }) {
+export default function SceneRenderTarget({
+ id, value, onChange, options = {}, onOptionsChange, performance, saved, scene = null, models = [], defaultModel = '', disabled = false,
+}) {
+ const set = (patch) => onOptionsChange?.({ ...options, ...patch });
+ const spanSec = shotSpan(scene);
+ const overrides = renderTargetOverrides(value, saved, options, { models, defaultModel, performance, scene });
+ const localChoices = localModelChoices(models, performance);
+ const localModel = value === 'local' ? models.find((model) => model.id === overrides.modelId) : null;
+ const falModel = value.startsWith('fal:') ? getFalVideoModel(overrides.falModelId) : null;
+ const coversLabel = (sec) => (spanSec != null ? `${formatSec(sec)} · covers shot` : `${formatSec(sec)} · default`);
return (
<>
- <label htmlFor={id} className="text-xs">Render on</label>
- <select id={id} value={value} onChange={(e) => onChange(e.target.value)} disabled={disabled}
- title="Where this shot's clip renders. Only this shot; the project setting stays as it is."
- className="min-w-0 max-w-full flex-1 basis-48 bg-port-bg border border-port-border rounded px-1 py-1 text-xs min-h-[44px] sm:min-h-0 sm:flex-none disabled:opacity-50">
- {renderTargetOptions({ performance, saved }).map((option) => (
- <option key={option.value} value={option.value} disabled={option.disabled}>{option.label}</option>
- ))}
- </select>
+ <span className="flex min-w-0 flex-1 basis-48 items-center gap-1 sm:flex-none">
+ <label htmlFor={id} className="text-xs">Render on</label>
+ <select id={id} value={value} onChange={(e) => { onChange(e.target.value); onOptionsChange?.({}); }} disabled={disabled}
+ title="Where this shot's clip renders. Only this shot; the project setting stays as it is."
+ className={`${SELECT} flex-1 sm:flex-none`}>
+ {renderTargetOptions({ performance, saved, endFrame: Boolean(scene?.endImageId) }).map((option) => (
+ <option key={option.value} value={option.value} disabled={option.disabled}>{option.label}</option>
+ ))}
+ </select>
+ </span>
+ {value === 'local' && (
+ <>
+ <OptionSelect id={`${id}-model`} label="Model" value={overrides.modelId || ''} disabled={disabled || localChoices.length === 0}
+ onChange={(modelId) => set({ modelId, numFrames: null })}>
+ {localChoices.length === 0 && <option value="">{performance ? 'No lip-sync model installed' : 'No local model installed'}</option>}
+ {localChoices.map((model) => <option key={model.id} value={model.id}>{model.name || model.id}</option>)}
+ </OptionSelect>
+ {localModel && !performance && (
+ <OptionSelect id={`${id}-length`} label="Length" value={overrides.numFrames || ''} disabled={disabled}
+ onChange={(frames) => set({ numFrames: Number(frames) || null })}>
+ {frameOptionsForModel(localModel).map((frames) => (
+ <option key={frames} value={frames}>
+ {frames === coveringFrames(localModel, spanSec) ? coversLabel(frames / LOCAL_FPS) : formatSec(frames / LOCAL_FPS)}
+ </option>
+ ))}
+ </OptionSelect>
+ )}
+ </>
+ )}
+ {value === 'grok' && (
+ <OptionSelect id={`${id}-length`} label="Length" value={overrides.grokDuration || ''} disabled={disabled}
+ onChange={(sec) => set({ grokDuration: Number(sec) || null })}>
+ {overrides.grokDuration == null && <option value="">Default</option>}
+ {GROK_VIDEO_DURATIONS.map((sec) => (
+ <option key={sec} value={sec}>{spanSec != null && sec === grokCoverage(spanSec).requestSec ? coversLabel(sec) : formatSec(sec)}</option>
+ ))}
+ </OptionSelect>
+ )}
+ {falModel && !performance && (
+ <>
+ {falLengths(falModel).length > 0 && (
+ <OptionSelect id={`${id}-length`} label="Length" value={options.falDuration || ''} disabled={disabled}
+ onChange={(sec) => set({ falDuration: Number(sec) || null })}>
+ <option value="">{coversLabel(coerceFalVideoSeconds(falModel, spanSec))}</option>
+ {falLengths(falModel).map((sec) => <option key={sec} value={sec}>{formatSec(sec)}</option>)}
+ </OptionSelect>
+ )}
+ {falVideoResolutions(falModel).length > 1 && (
+ <OptionSelect id={`${id}-resolution`} label="Size" value={options.falResolution || ''} disabled={disabled}
+ onChange={(falResolution) => set({ falResolution: falResolution || null })}>
+ <option value="">{`${falModel.resolution.default} · default`}</option>
+ {falVideoResolutions(falModel).filter((res) => res !== falModel.resolution.default).map((res) => (
+ <option key={res} value={res}>{`${res} · ${describeFalVideoRate(falModel.id, res)}`}</option>
+ ))}
+ </OptionSelect>
+ )}
+ </>
+ )}
</>
);
}
diff --git a/client/src/components/musicVideo/SceneTakePicker.jsx b/client/src/components/musicVideo/SceneTakePicker.jsx
new file mode 100644
index 0000000000..d813e7bc68
--- /dev/null
+++ b/client/src/components/musicVideo/SceneTakePicker.jsx
@@ -0,0 +1,143 @@
+import { useEffect, useState } from 'react';
+import { X, Search, Film, Activity } from 'lucide-react';
+import Modal from '../ui/Modal.jsx';
+import TabPills from '../ui/TabPills.jsx';
+import { getMusicVideoMediaPool } from '../../services/apiMusicVideo.js';
+import { takeThumbUrl, takeClipUrl } from '../../lib/musicVideoTakes.js';
+import { formatCount } from '../../utils/formatters.js';
+
+const PAGE = 60;
+const SLOT_NOUN = { image: 'still', video: 'clip', endImage: 'end frame' };
+// An end frame is picked from the same unused stills as a start frame.
+const POOL_KIND = { image: 'image', video: 'video', endImage: 'image' };
+
+/** Which tab a pool item belongs on for this shot: its own takes, another shot's, or the floor. */
+export const poolGroup = (item, sceneId) => (!item.sceneId ? 'floor' : item.sceneId === sceneId ? 'shot' : 'others');
+
+/** Items of one kind matching a search over their prompt, or a shot number ("12" or "#12"). */
+export function filterPool(items, { kind, query, shotNumbers }) {
+ const needle = query.trim().toLowerCase().replace(/^#/, '');
+ return items.filter((item) => item.kind === kind && (!needle
+ || String(item.prompt || '').toLowerCase().includes(needle)
+ || (item.sceneId && String(shotNumbers.get(item.sceneId) ?? '') === needle)));
+}
+
+/**
+ * "Swap from unused": every still (or clip) generated for this video that no
+ * shot uses now, as a searchable contact sheet in three tabs: this shot's
+ * other takes, other shots' unused takes, and the floor (takes a cut shot, a
+ * re-plan or a merge left behind). Tap one to see it full size, then use it,
+ * or use it with its partner: a still's rendered clip, or a clip's still.
+ * `kind: 'endImage'` picks a still for the shot's end frame, on its own.
+ * `onPlace({ kind, assetId, withAssetId? })` puts it on the shot.
+ */
+export default function SceneTakePicker({ open, onClose, projectId, scene, kind, shotNumbers = new Map(), onPlace, busy = false }) {
+ const [pool, setPool] = useState(null);
+ const [error, setError] = useState(null);
+ const [group, setGroup] = useState('shot');
+ const [query, setQuery] = useState('');
+ const [shown, setShown] = useState(PAGE);
+ const [picked, setPicked] = useState(null);
+
+ useEffect(() => {
+ if (!open) return undefined;
+ let active = true;
+ setPool(null); setError(null); setPicked(null); setQuery(''); setShown(PAGE);
+ getMusicVideoMediaPool(projectId, { silent: true })
+ .then((res) => {
+ if (!active) return;
+ const items = res.items || [];
+ setPool(items);
+ // Open on the first tab that has anything in it.
+ const groups = new Set(items.filter((item) => item.kind === POOL_KIND[kind]).map((item) => poolGroup(item, scene.sceneId)));
+ setGroup(['shot', 'others', 'floor'].find((g) => groups.has(g)) || 'shot');
+ })
+ .catch((err) => { if (active) setError(err?.message || 'Could not load the unused takes'); });
+ return () => { active = false; };
+ }, [open, projectId, scene.sceneId, kind]);
+
+ const ofKind = pool ? filterPool(pool, { kind: POOL_KIND[kind], query, shotNumbers }) : [];
+ const counts = { shot: 0, others: 0, floor: 0 };
+ for (const item of ofKind) counts[poolGroup(item, scene.sceneId)] += 1;
+ const activeGroup = group;
+ const items = ofKind.filter((item) => poolGroup(item, scene.sceneId) === activeGroup);
+ const noun = SLOT_NOUN[kind];
+ const itemNoun = SLOT_NOUN[POOL_KIND[kind]];
+ const shotName = shotNumbers.get(scene.sceneId) ? `Shot ${shotNumbers.get(scene.sceneId)}` : 'this shot';
+ const partner = picked && (kind === 'image' ? picked.clipIds?.[0] : kind === 'video' ? picked.sourceImageId : null) || null;
+ // Stays open when the shot refuses the pick (onPlace resolves false), so another can be tried.
+ const place = (withAssetId) => Promise.resolve(onPlace?.({ kind, assetId: picked.assetId, ...(withAssetId ? { withAssetId } : {}) }))
+ .then((placed) => { if (placed !== false) onClose?.(); });
+
+ return (
+ <Modal open={open} onClose={onClose} size="2xl" align="top" usePortal ariaLabel={`Swap ${noun} for ${shotName}`}
+ panelClassName="bg-port-card border border-port-border rounded-lg p-3 space-y-2">
+ <div className="flex items-center gap-2">
+ <h3 className="min-w-0 flex-1 truncate text-sm font-medium">Swap {noun} · {shotName}</h3>
+ <button type="button" onClick={onClose} aria-label="Close" className="inline-flex min-h-[44px] min-w-[44px] items-center justify-center rounded sm:min-h-0 sm:min-w-0 sm:p-1">
+ <X size={16} />
+ </button>
+ </div>
+ <TabPills activeTab={activeGroup} onChange={(id) => { setGroup(id); setShown(PAGE); setPicked(null); }}
+ tabs={[{ id: 'shot', label: 'This shot', count: counts.shot }, { id: 'others', label: 'Other shots', count: counts.others }, { id: 'floor', label: 'Floor', count: counts.floor }]} />
+ <label htmlFor={`mv-pool-search-${scene.sceneId}`} className="flex items-center gap-2 rounded border border-port-border bg-port-bg px-2">
+ <Search size={14} aria-hidden="true" className="shrink-0 text-port-text-muted" />
+ <span className="sr-only">Search prompts or shot number</span>
+ <input id={`mv-pool-search-${scene.sceneId}`} type="search" value={query} onChange={(e) => { setQuery(e.target.value); setShown(PAGE); }}
+ placeholder="Search prompts or shot #" className="min-h-[44px] min-w-0 flex-1 bg-transparent text-sm outline-none sm:min-h-[32px]" />
+ </label>
+ {picked && (
+ <div className="space-y-2 rounded border border-port-border p-2">
+ {kind === 'video'
+ ? <video key={picked.assetId} src={takeClipUrl(picked)} poster={takeThumbUrl(picked)} controls autoPlay muted loop playsInline className="w-full aspect-video rounded bg-black object-contain" />
+ : <img src={takeThumbUrl(picked)} alt="" className="w-full aspect-video rounded bg-black object-contain" />}
+ {picked.prompt && <p className="line-clamp-2 text-[11px] text-port-text-muted">{picked.prompt}</p>}
+ <div className="flex flex-wrap gap-2">
+ <button type="button" disabled={busy} onClick={() => place(null)}
+ className="inline-flex min-h-[44px] items-center gap-1 rounded bg-port-accent px-3 text-xs font-medium text-white disabled:opacity-50 sm:min-h-[32px]">
+ {busy && <Activity size={14} className="animate-spin" />}Use {noun}
+ </button>
+ {partner && (
+ <button type="button" disabled={busy} onClick={() => place(partner)}
+ className="inline-flex min-h-[44px] items-center gap-1 rounded border border-port-border px-3 text-xs disabled:opacity-50 sm:min-h-[32px]">
+ Use {noun} + its {kind === 'image' ? 'clip' : 'still'}
+ </button>
+ )}
+ </div>
+ </div>
+ )}
+ {error && <p role="alert" className="text-xs text-port-error">{error}</p>}
+ {!pool && !error && <p className="flex items-center gap-2 text-xs text-port-text-muted"><Activity size={14} className="animate-spin" />Gathering every {itemNoun} made for this video…</p>}
+ {pool && items.length === 0 && (
+ <p className="text-xs text-port-text-muted">{query ? `No unused ${itemNoun}s match.` : `No unused ${itemNoun}s here.`}</p>
+ )}
+ <ul className="grid grid-cols-3 gap-2 sm:grid-cols-4 lg:grid-cols-6" aria-label={`Unused ${itemNoun}s`}>
+ {items.slice(0, shown).map((item) => {
+ const number = item.sceneId ? shotNumbers.get(item.sceneId) : null;
+ const selected = picked?.assetId === item.assetId;
+ return (
+ <li key={item.assetId}>
+ <button type="button" onClick={() => setPicked(item)} aria-pressed={selected}
+ aria-label={`${itemNoun}${number ? ` from shot ${number}` : ''}${item.prompt ? `: ${item.prompt.slice(0, 80)}` : ''}`}
+ className={`relative block w-full overflow-hidden rounded border ${selected ? 'border-port-accent ring-2 ring-port-accent' : 'border-port-border'} ${item.takeStatus === 'rejected' ? 'opacity-60' : ''}`}>
+ <img src={takeThumbUrl(item)} alt="" loading="lazy" className="block aspect-video w-full bg-black object-cover" />
+ {number && <span className="port-media-overlay-strong absolute left-1 top-1 rounded px-1 text-[10px] leading-tight">#{number}</span>}
+ {(kind === 'video' || item.clipIds?.length > 0) && (
+ <span className="port-media-overlay-strong absolute bottom-1 right-1 inline-flex items-center gap-0.5 rounded px-1 text-[10px] leading-tight">
+ <Film size={10} aria-hidden="true" />{kind === 'video' ? 'clip' : 'has clip'}
+ </span>
+ )}
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ {items.length > shown && (
+ <button type="button" onClick={() => setShown((n) => n + PAGE)}
+ className="w-full min-h-[44px] rounded border border-port-border text-xs sm:min-h-[32px]">
+ Show more ({formatCount(items.length - shown)} left)
+ </button>
+ )}
+ </Modal>
+ );
+}
diff --git a/client/src/components/musicVideo/SceneTakePicker.test.jsx b/client/src/components/musicVideo/SceneTakePicker.test.jsx
new file mode 100644
index 0000000000..de3b80e85f
--- /dev/null
+++ b/client/src/components/musicVideo/SceneTakePicker.test.jsx
@@ -0,0 +1,34 @@
+import { describe, expect, it, vi } from 'vitest';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+
+const pool = [
+ { kind: 'image', assetId: 'mine.png', sceneId: 's8', prompt: 'Film strip held to the lamp', clipIds: [] },
+ { kind: 'image', assetId: 'other.png', sceneId: 's12', prompt: 'Splicer close-up', clipIds: ['clip-12'] },
+ { kind: 'image', assetId: 'floor.png', sceneId: null, prompt: 'Reel on the floor', clipIds: [] },
+ { kind: 'video', assetId: 'clip-12', sceneId: 's12', sourceImageId: 'other.png' },
+];
+vi.mock('../../services/apiMusicVideo.js', () => ({ getMusicVideoMediaPool: vi.fn(async () => ({ items: pool })) }));
+const { default: SceneTakePicker } = await import('./SceneTakePicker.jsx');
+
+describe('Swap from unused', () => {
+ // Uniquely catches the picker offering the wrong kind or group, a shot-number search missing, or the partner clip dropped.
+ it('groups unused stills by where they came from, finds a shot by number, and uses a still with its clip', async () => {
+ const onPlace = vi.fn(async () => {});
+ const onClose = vi.fn();
+ render(<SceneTakePicker open projectId="mv-1" scene={{ sceneId: 's8' }} kind="image" onClose={onClose} onPlace={onPlace}
+ shotNumbers={new Map([['s8', 8], ['s12', 12]])} />);
+ expect(await screen.findByRole('tab', { name: /This shot/ })).toBeTruthy();
+ await waitFor(() => expect(screen.getAllByRole('listitem')).toHaveLength(1));
+
+ fireEvent.click(screen.getByRole('tab', { name: /Other shots/ }));
+ fireEvent.change(screen.getByLabelText('Search prompts or shot number'), { target: { value: '#12' } });
+ fireEvent.click(screen.getByRole('button', { name: /still from shot 12/ }));
+ fireEvent.click(screen.getByRole('button', { name: 'Use still + its clip' }));
+ expect(onPlace).toHaveBeenCalledWith({ kind: 'image', assetId: 'other.png', withAssetId: 'clip-12' });
+ await waitFor(() => expect(onClose).toHaveBeenCalled());
+
+ fireEvent.click(screen.getByRole('tab', { name: /Floor/ }));
+ fireEvent.change(screen.getByLabelText('Search prompts or shot number'), { target: { value: 'reel' } });
+ expect(screen.getAllByRole('listitem')).toHaveLength(1);
+ });
+});
diff --git a/client/src/components/musicVideo/stages/BoardStage.jsx b/client/src/components/musicVideo/stages/BoardStage.jsx
index cebdf5905c..d0425e0622 100644
--- a/client/src/components/musicVideo/stages/BoardStage.jsx
+++ b/client/src/components/musicVideo/stages/BoardStage.jsx
@@ -200,6 +200,8 @@ export default function BoardStage({ board }) {
failedScenes={sceneMedia.failedScenes}
songReview={attentionCtx.songReview}
falVideoSettings={videoSettings.settings}
+ videoModels={videoSettings.models}
+ defaultVideoModel={videoSettings.defaultModel}
canContinueShot={board.canContinueShot}
onMove={board.moveScene}
onDelete={board.onDeleteScene}
@@ -225,6 +227,9 @@ export default function BoardStage({ board }) {
previousHasClip={Boolean(previousShot(project, scene.sceneId)?.videoHistoryId)}
onImportTake={(target) => board.setPickerTarget({ type: 'take', sceneId: target.sceneId })}
onImportClipTake={(target) => board.setPickerTarget({ type: 'clip', sceneId: target.sceneId })}
+ onPlacePoolItem={takes.placePoolItem}
+ projectId={project.id}
+ shotNumbers={numbers}
layered={layered}
documentComposition={project.composition?.mode === 'document'}
/>
diff --git a/client/src/hooks/useMusicVideoSceneMedia.js b/client/src/hooks/useMusicVideoSceneMedia.js
index 200c8c1475..1ade044f77 100644
--- a/client/src/hooks/useMusicVideoSceneMedia.js
+++ b/client/src/hooks/useMusicVideoSceneMedia.js
@@ -384,7 +384,8 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applyS
...(settings.backend === 'grok'
// 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 }
+ // A scene card's Length pick wins.
+ ? { grokDuration: target?.grokDuration || (spanSec != null ? grokCoverage(spanSec).requestSec : settings.grokDuration) }
// fal.ai (#8968) — image-to-video only (see VideoRenderSettings). The
// request is exactly the take the scene card prices (falSceneTake):
// a cutaway names its model, the length covering the shot (or the
@@ -394,7 +395,8 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applyS
: falFields
? falFields
: settings.backend === 'local'
- ? { modelId: settings.modelId || undefined, disableAudio: true }
+ // A scene card's pick names its model and length; else the saved model at the model's default length.
+ ? { modelId: settings.modelId || undefined, ...(target?.numFrames ? { numFrames: target.numFrames } : {}), disableAudio: true }
// A named model is local-only machinery at the server boundary and
// would force the resolver off a Grok install default. Keep the
// shared pin saved, but omit it until this peer chooses Local.
diff --git a/client/src/hooks/useMusicVideoTakes.js b/client/src/hooks/useMusicVideoTakes.js
index 03b783a4d1..5d525d0396 100644
--- a/client/src/hooks/useMusicVideoTakes.js
+++ b/client/src/hooks/useMusicVideoTakes.js
@@ -3,6 +3,7 @@ import toast from '../components/ui/Toast';
import {
addMusicVideoSceneTake,
selectMusicVideoSceneTake,
+ placeMusicVideoPoolItem,
continueMusicVideoSceneFromPrevious,
reviewMusicVideoSceneTake,
getMusicVideoHandoff,
@@ -56,11 +57,12 @@ export default function useMusicVideoTakes({ project, applyScenePatch }) {
});
// Serialize take mutations; a failure toasts and leaves the chain usable.
+ // Resolves true when the change landed, false when it was refused.
const runTakeOp = (work, failMessage) => {
const projectId = project.id;
const run = chainRef.current.then(() => work(projectId));
- chainRef.current = run.then((scene) => { if (scene) applyScene(projectId, scene); })
- .catch((err) => toast.error(err?.message || failMessage));
+ chainRef.current = run.then((scene) => { if (scene) applyScene(projectId, scene); return true; })
+ .catch((err) => { toast.error(err?.message || failMessage); return false; });
return chainRef.current;
};
@@ -69,6 +71,12 @@ export default function useMusicVideoTakes({ project, applyScenePatch }) {
'Failed to select take',
);
+ // An unused still or clip from the project's pool becomes this shot's selection (with its partner, when picked).
+ const placePoolItem = (scene, pick) => runTakeOp(
+ (projectId) => placeMusicVideoPoolItem(projectId, scene.sceneId, pick, { silent: true }).then((res) => res.scene),
+ 'Failed to use that take',
+ );
+
// Continuing shot: the previous shot's last on-screen frame becomes this
// scene's start frame; `keepStillAsEnd` keeps the current one as its end frame.
const continueFromPrevious = (scene, { keepStillAsEnd = false } = {}) => runTakeOp(
@@ -154,5 +162,5 @@ export default function useMusicVideoTakes({ project, applyScenePatch }) {
if (failures.length) toast.error(failures.slice(0, 3).join(' · '));
};
- return { busy, selectTake, reviewTake, continueFromPrevious, importTake, importClipTake, exportHandoff, exportHandoffBundle, importHandoffFiles };
+ return { busy, selectTake, placePoolItem, reviewTake, continueFromPrevious, importTake, importClipTake, exportHandoff, exportHandoffBundle, importHandoffFiles };
}
diff --git a/client/src/lib/falVideoModels.js b/client/src/lib/falVideoModels.js
index ed8abb70b8..def3d7e0e3 100644
--- a/client/src/lib/falVideoModels.js
+++ b/client/src/lib/falVideoModels.js
@@ -12,6 +12,7 @@ export {
FAL_DEFAULT_TEXT_VIDEO_MODEL,
FAL_IMAGE_VIDEO_MODELS,
FAL_VIDEO_MODELS,
+ coerceFalVideoSeconds,
describeFalVideoRate,
estimateFalVideoCostUsd,
falImageVideoQuotes,
diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsx
index f5a24e4866..b605fc539a 100644
--- a/client/src/pages/MusicVideo.test.jsx
+++ b/client/src/pages/MusicVideo.test.jsx
@@ -1248,6 +1248,27 @@ describe('MusicVideo project video renderer', () => {
expect(updateMusicVideoProject.mock.calls.some(([, patch]) => patch?.videoSettings)).toBe(false);
});
+ // Uniquely catches "Local LTX" falling through to the install's default model, and a picked length being dropped.
+ it('renders a Local LTX pick on the model and length its card shows, LTX-2.5 before the install default', async () => {
+ getVideoGenStatus.mockResolvedValueOnce({ connected: true, defaultModel: 'ltx23_distilled_q4', falEnabled: true,
+ models: [{ id: 'ltx23_distilled_q4', name: 'LTX-2.3 Distilled Q4', runtime: 'mlx_video' }, { id: 'ltx25_mlx_q8', name: 'LTX-2.5 Q8', runtime: 'ltx25' }] });
+ generateVideo.mockResolvedValue({ jobId: 'local-pick-job' });
+ await openProject({ ...PROJECT_NO_CLIP, videoSettings: { backend: 'fal' }, scenes: [{ ...PROJECT_NO_CLIP.scenes[0], startSec: 0, endSec: 3 }] }, 'produce');
+ const render = within(await screen.findByRole('region', { name: 'Render' }));
+ fireEvent.change(render.getByLabelText('Render on'), { target: { value: 'local' } });
+ expect(render.getByLabelText('Model').value).toBe('ltx25_mlx_q8');
+ // A 3s shot: the shortest LTX length that covers it (73 frames at 24 fps).
+ const length = render.getByLabelText('Length');
+ expect(length.value).toBe('73');
+ expect(length.selectedOptions[0].textContent).toBe('3s · covers shot');
+ fireEvent.change(length, { target: { value: '121' } });
+ fireEvent.click(await findEnabledByRole('button', { name: /^Render$/ }));
+ await waitFor(() => expect(generateVideo).toHaveBeenCalledWith(expect.objectContaining({
+ backend: 'local', modelId: 'ltx25_mlx_q8', numFrames: 121, mode: 'image',
+ })));
+ expect(updateMusicVideoProject.mock.calls.some(([, patch]) => patch?.videoSettings)).toBe(false);
+ });
+
it('renders a cutaway on the picked fal.ai model at the shot-covering length, sending exactly the take it prices', async () => {
getVideoGenStatus.mockResolvedValueOnce({ connected: true, defaultModel: '', falEnabled: true, models: [] });
generateVideo.mockResolvedValue({ jobId: 'fal-h3-job' });
diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.js
index 64a9d7e6f8..5a50111f24 100644
--- a/client/src/services/apiMusicVideo.js
+++ b/client/src/services/apiMusicVideo.js
@@ -170,6 +170,12 @@ export const addMusicVideoSceneTake = (id, sceneId, body, options = {}) => reque
});
export const selectMusicVideoSceneTake = (id, sceneId, takeId, options = {}) =>
request(`${takesPath(id, sceneId)}/${encodeURIComponent(takeId)}/select`, { method: 'POST', ...options });
+// The project's unused stills and clips (the shot card's "Swap from unused") → { collectionId, items }.
+export const getMusicVideoMediaPool = (id, options = {}) => request(`/music-video/${encodeURIComponent(id)}/media-pool`, options);
+// Put a pool still or clip on a shot as its selection; `withAssetId` brings its partner → { scene }.
+export const placeMusicVideoPoolItem = (id, sceneId, body, options = {}) => request(`${takesPath(id, sceneId)}/use`, {
+ method: 'POST', body: JSON.stringify(body), ...options,
+});
// Start a shot from the previous shot's last on-screen frame → { scene, frame }.
export const continueMusicVideoSceneFromPrevious = (id, sceneId, body = {}, options = {}) =>
request(`/music-video/${encodeURIComponent(id)}/scenes/${encodeURIComponent(sceneId)}/continue-from-previous`, {
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index 7359b565b8..b6f0f72bc0 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -318,6 +318,24 @@ export const musicVideoTakeInputSchema = z.object({
if (!parsed.success) ctx.addIssue({ code: 'custom', path: ['assetId'], message: parsed.error.issues[0].message });
});
+// Put an unused still or clip from the project's pool on a shot; `withAssetId` is its partner (a still's clip, a clip's still).
+// `endImage` puts a still on the shot's end frame; only a start still pairs with a clip.
+export const musicVideoPoolUseSchema = z.object({
+ kind: z.enum(['image', 'video', 'endImage']),
+ assetId: z.string().min(1).max(256),
+ withAssetId: z.string().min(1).max(256).optional(),
+}).strict().superRefine((input, ctx) => {
+ if (input.kind === 'endImage' && input.withAssetId !== undefined) {
+ ctx.addIssue({ code: 'custom', path: ['withAssetId'], message: 'An end frame is placed on its own' });
+ }
+ const [still, clip] = input.kind === 'video' ? [input.withAssetId, input.assetId] : [input.assetId, input.withAssetId];
+ for (const [value, schema, path] of [[still, galleryImageName, input.kind === 'video' ? 'withAssetId' : 'assetId'], [clip, videoHistoryIdSchema, input.kind === 'video' ? 'assetId' : 'withAssetId']]) {
+ if (value === undefined) continue;
+ const parsed = schema.safeParse(value);
+ if (!parsed.success) ctx.addIssue({ code: 'custom', path: [path], message: parsed.error.issues[0].message });
+ }
+});
+
// Review a take: reject/restore it and/or leave a note for regeneration.
export const musicVideoTakeReviewSchema = z.object({
status: z.enum(MUSIC_VIDEO_TAKE_STATUSES).optional(),
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.js
index 73d7a06075..d51d5e4d92 100644
--- a/server/routes/musicVideo.js
+++ b/server/routes/musicVideo.js
@@ -12,7 +12,7 @@ import { existsSync } from 'fs';
import { unlink } from 'fs/promises';
import { pipeline } from 'stream/promises';
import { Router } from 'express';
-import { musicVideoSongStyleSunoSchema, musicVideoProjectListQuerySchema, musicVideoFinishedOutsideSchema, musicVideoProductionDraftSchema, musicVideoProductionApprovalSchema, musicVideoShotLockSchema, musicVideoProductionProofSchema, musicVideoProductionImportSchema, musicVideoContinueShotSchema, musicVideoProductionFeedbackSchema, musicVideoProductionFeedbackResolutionSchema, musicVideoProductionReviseSchema, musicVideoProductionRevertSchema } from '../lib/musicVideoValidation.js';
+import { musicVideoSongStyleSunoSchema, musicVideoProjectListQuerySchema, musicVideoFinishedOutsideSchema, musicVideoProductionDraftSchema, musicVideoProductionApprovalSchema, musicVideoShotLockSchema, musicVideoProductionProofSchema, musicVideoProductionImportSchema, musicVideoContinueShotSchema, musicVideoPoolUseSchema, musicVideoProductionFeedbackSchema, musicVideoProductionFeedbackResolutionSchema, musicVideoProductionReviseSchema, musicVideoProductionRevertSchema } from '../lib/musicVideoValidation.js';
import { productionReadiness } from '../services/musicVideo/productionReview.js';
import { finishedOutsideBlocker } from '../lib/musicVideoFinishedOutside.js';
import { getProductionReview, saveProductionDraft, prepareProductionReview, approveProductionReview, lockProductionShots, renderProductionProof, requireProductionReviewer, importProductionPlanning, bindProductionShot, addProductionFeedback, closeProductionFeedback, reviseProductionFromFeedback, revertProductionInput } from '../services/musicVideo/productionReviewService.js';
@@ -115,6 +115,7 @@ import {
appendSceneTakes,
appendTakesAcrossScenes,
selectSceneTake,
+ placeMediaPoolItem,
reviewSceneTake,
refreshSongStyleFromSuno,
} from '../services/musicVideo/projects.js';
@@ -1535,6 +1536,25 @@ router.post('/:id/scenes/:sceneId/continue-from-previous', asyncHandler(async (r
res.json(await continueFromPreviousShot(req.params.id, req.params.sceneId, { keepStillAsEnd }));
}));
+// Every still and clip generated for this video that no shot uses now (the shot card's "Swap from unused").
+router.get('/:id/media-pool', asyncHandler(async (req, res) => {
+ const project = await getProject(req.params.id);
+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ const { getMusicVideoMediaPool } = await import('../services/musicVideo/mediaPool.js');
+ res.json(await getMusicVideoMediaPool(project));
+}));
+
+router.post('/:id/scenes/:sceneId/takes/use', asyncHandler(async (req, res) => {
+ const { kind, assetId, withAssetId } = validateRequest(musicVideoPoolUseSchema, req.body);
+ const otherKind = kind === 'video' ? 'image' : 'video';
+ for (const [assetKind, id] of [[kind, assetId], [otherKind, withAssetId]]) {
+ if (id && !(await takeAssetExists(assetKind, id))) {
+ throw new ServerError(`${assetKind === 'video' ? 'Video' : 'Image'} not found in this install's media library`, { status: 400, code: 'TAKE_ASSET_NOT_FOUND' });
+ }
+ }
+ res.json({ scene: await placeMediaPoolItem(req.params.id, req.params.sceneId, { kind, assetId, withAssetId }) });
+}));
+
router.post('/:id/scenes/:sceneId/takes/:takeId/select', asyncHandler(async (req, res) => {
res.json(await selectSceneTake(req.params.id, req.params.sceneId, req.params.takeId));
}));
diff --git a/server/routes/musicVideoTakes.test.js b/server/routes/musicVideoTakes.test.js
index 9ee7da4e41..16e3d84c22 100644
--- a/server/routes/musicVideoTakes.test.js
+++ b/server/routes/musicVideoTakes.test.js
@@ -223,3 +223,56 @@ describe('external-asset handoff', () => {
expect(imported.body.imported.map((i) => i.sceneId)).toEqual(['intro']);
});
});
+
+describe('swapping a shot from unused takes', () => {
+ // Uniquely catches a cut shot's takes vanishing from the picker, a clip losing its still, and a used take offered as unused.
+ it('lists every unused still and clip, keeps a cut shot\'s takes on the floor, and puts a still with its clip on a shot', async () => {
+ for (const name of ['a-1.png', 'a-2.png', 'b-1.png', 'b-2.png']) seedImage(name);
+ seedVideoHistory([{ id: 'clip-b2', prompt: 'waves in slow motion' }, { id: 'clip-a1' }]);
+ await addTake(sceneA.sceneId, { kind: 'image', assetId: 'a-1.png', source: 'generated' });
+ await addTake(sceneA.sceneId, { kind: 'image', assetId: 'a-2.png', source: 'generated' });
+ await addTake(sceneA.sceneId, { kind: 'video', assetId: 'clip-a1', source: 'generated', sourceImageId: 'a-1.png' });
+ await addTake(sceneB.sceneId, { kind: 'image', assetId: 'b-1.png', source: 'generated' });
+ await addTake(sceneB.sceneId, { kind: 'image', assetId: 'b-2.png', source: 'generated' });
+ await addTake(sceneB.sceneId, { kind: 'video', assetId: 'clip-b2', source: 'generated', sourceImageId: 'b-2.png' });
+ const pool = async () => (await request(app).get(`${base()}/media-pool`)).body.items;
+
+ // Selected stills and clips are in use; the rest are offered, each naming the shot that holds it.
+ expect((await pool()).map((item) => [item.kind, item.assetId, item.sceneId]).sort()).toEqual([
+ ['image', 'a-2.png', sceneA.sceneId], ['image', 'b-2.png', sceneB.sceneId], ['video', 'clip-b2', sceneB.sceneId],
+ ]);
+
+ // Cutting shot B leaves its takes on the floor, the clip still paired with the still it was rendered from.
+ await request(app).delete(`${base()}/scenes/${sceneB.sceneId}`);
+ const floor = await pool();
+ expect(floor.filter((item) => !item.sceneId).map((item) => item.assetId).sort()).toEqual(['b-1.png', 'b-2.png', 'clip-b2']);
+ expect(floor.find((item) => item.assetId === 'b-2.png').clipIds).toEqual(['clip-b2']);
+ const { getCollection, musicVideoCollectionId } = await import('../services/mediaCollections.js');
+ expect((await getCollection(musicVideoCollectionId(project.id))).items).toHaveLength(6);
+
+ const used = await request(app).post(`${base()}/scenes/${sceneA.sceneId}/takes/use`).send({ kind: 'image', assetId: 'b-2.png', withAssetId: 'clip-b2' });
+ expect(used.status).toBe(200);
+ expect(used.body.scene).toMatchObject({ referenceImageId: 'b-2.png', videoHistoryId: 'clip-b2' });
+ expect(used.body.scene.takes.find((take) => take.assetId === 'clip-b2')).toMatchObject({ source: 'reused', sourceImageId: 'b-2.png' });
+ expect((await pool()).map((item) => item.assetId).sort()).toEqual(['a-1.png', 'a-2.png', 'b-1.png', 'clip-a1']);
+
+ // Any unused still can become the shot's end frame, and leaves the pool.
+ const end = await request(app).post(`${base()}/scenes/${sceneA.sceneId}/takes/use`).send({ kind: 'endImage', assetId: 'b-1.png' });
+ expect(end.status).toBe(200);
+ expect(end.body.scene).toMatchObject({ referenceImageId: 'b-2.png', endImageId: 'b-1.png' });
+ expect((await pool()).map((item) => item.assetId).sort()).toEqual(['a-1.png', 'a-2.png', 'clip-a1']);
+
+ expect((await request(app).post(`${base()}/scenes/${sceneA.sceneId}/takes/use`).send({ kind: 'image', assetId: 'missing.png' })).status).toBe(400);
+ expect((await request(app).post(`${base()}/scenes/${sceneA.sceneId}/takes/use`).send({ kind: 'endImage', assetId: 'a-1.png', withAssetId: 'clip-a1' })).status).toBe(400);
+
+ // A shot whose video is locked takes nothing new until it is unlocked.
+ const { setShotLocks } = await import('../services/musicVideo/productionReview.js');
+ await projects.mutateProjectRecord(project.id, (current) => ({ project: setShotLocks(
+ setShotLocks(current, { sceneIds: [sceneA.sceneId], locked: true, stage: 'still' }),
+ { sceneIds: [sceneA.sceneId], locked: true, stage: 'video' },
+ ) }));
+ const refused = await request(app).post(`${base()}/scenes/${sceneA.sceneId}/takes/use`).send({ kind: 'image', assetId: 'a-1.png' });
+ expect(refused.status).toBe(409);
+ expect((await reload()).scenes.find((scene) => scene.sceneId === sceneA.sceneId).referenceImageId).toBe('b-2.png');
+ });
+});
diff --git a/server/services/mediaCollections.js b/server/services/mediaCollections.js
index 6f25c437d1..42dda66637 100644
--- a/server/services/mediaCollections.js
+++ b/server/services/mediaCollections.js
@@ -612,6 +612,42 @@ export async function findOrCreateSeriesCollection({ seriesId, seriesName, descr
return result;
}
+// A music video's own collection (one per project): every still and clip
+// generated for it, kept findable after a shot drops them. The id is derived
+// from the project id, so the same project converges on one collection on
+// every peer and no owner stamp is needed.
+const MUSIC_VIDEO_ID_MAX = 100;
+export const musicVideoCollectionId = (projectId) => `mvc-${String(projectId).slice(0, MUSIC_VIDEO_ID_MAX)}`;
+export const musicVideoCollectionNameFor = (projectName) =>
+ `Music video: ${typeof projectName === 'string' && projectName.trim() ? projectName.trim() : 'Untitled'}`.slice(0, NAME_MAX_LENGTH);
+
+export async function findOrCreateMusicVideoCollection({ projectId, projectName }) {
+ if (!projectId || typeof projectId !== 'string') throw codedError('projectId is required', ERR_VALIDATION);
+ const id = musicVideoCollectionId(projectId);
+ assertCollectionId(id);
+ let createdId = null;
+ const result = await store().queueRecordWrite(id, async () => {
+ const current = await store().loadOne(id);
+ if (current && !current.deleted) return current;
+ const now = new Date().toISOString();
+ const next = {
+ id,
+ name: musicVideoCollectionNameFor(projectName),
+ description: 'Every still and clip generated for this music video.',
+ coverKey: null,
+ source: 'auto',
+ items: [],
+ createdAt: now,
+ updatedAt: now,
+ };
+ createdId = id;
+ await store().saveOneNow(id, next);
+ return next;
+ });
+ if (createdId) announceNewCollection(createdId);
+ return result;
+}
+
// Both cascade families below — unlink (clear the owner link) and rename
// (cascade the owner's display name) — share the same shape: scan all records
// by their owner stamp, then per-match queue a load→re-check→save. The
diff --git a/server/services/musicVideo/mediaPool.js b/server/services/musicVideo/mediaPool.js
new file mode 100644
index 0000000000..964f14c7bc
--- /dev/null
+++ b/server/services/musicVideo/mediaPool.js
@@ -0,0 +1,153 @@
+/**
+ * A music video's media pool: every still and clip generated for the project,
+ * kept in the project's own media collection (`mvc-<projectId>`) so nothing a
+ * shot drops is lost, and listed for the shot card's "Swap from unused" picker.
+ *
+ * Filing happens when a take lands (projects.js appendSceneTakes), when a
+ * change drops takes from the board (a cut shot, a merge, a re-plan, a pruned
+ * take), and on every pool read, which also backfills whatever the project
+ * already holds. A clip's still is kept on its video history entry
+ * (`musicVideo.sourceImageId`), so a clip on the floor still pairs with its
+ * still after the shot that held both is gone.
+ */
+
+import { TAKE_SLOT } from './takes.js';
+
+const KIND_OF_SLOT = { image: 'image', endImage: 'image', video: 'video' };
+
+/** The still a video take was rendered from, when it recorded one. */
+function takeSourceImageId(take) {
+ if (take?.sourceImageId) return take.sourceImageId;
+ return take?.dependencies?.references?.find((ref) => ref?.role === 'plate')?.assetId || null;
+}
+
+/** Every asset the project's shots hold as a take or a selection: `{ kind, ref, sceneId, take }`. */
+export function projectTakeAssets(project) {
+ const assets = [];
+ for (const scene of project?.scenes || []) {
+ const seen = new Set();
+ for (const take of Array.isArray(scene.takes) ? scene.takes : []) {
+ const kind = KIND_OF_SLOT[take?.kind];
+ if (!kind || typeof take.assetId !== 'string' || !take.assetId) continue;
+ seen.add(`${kind}:${take.assetId}`);
+ assets.push({ kind, ref: take.assetId, sceneId: scene.sceneId, take });
+ }
+ for (const [slot, field] of Object.entries(TAKE_SLOT)) {
+ const ref = scene[field];
+ const kind = KIND_OF_SLOT[slot];
+ if (typeof ref === 'string' && ref && !seen.has(`${kind}:${ref}`)) {
+ seen.add(`${kind}:${ref}`);
+ assets.push({ kind, ref, sceneId: scene.sceneId, take: null });
+ }
+ }
+ }
+ return assets;
+}
+
+/** Assets held by `before` that `after` no longer holds anywhere on its board. */
+export function droppedTakeAssets(before, after) {
+ const kept = new Set(projectTakeAssets(after).map((asset) => `${asset.kind}:${asset.ref}`));
+ return projectTakeAssets(before).filter((asset) => !kept.has(`${asset.kind}:${asset.ref}`));
+}
+
+const usedKeys = (project) => new Set((project?.scenes || []).flatMap((scene) => Object.entries(TAKE_SLOT)
+ .map(([slot, field]) => (scene[field] ? `${KIND_OF_SLOT[slot]}:${scene[field]}` : null)).filter(Boolean)));
+
+/**
+ * The pool the picker shows: every asset in the collection or on the board that
+ * no shot uses now (not selected in any shot's still, clip or end frame slot).
+ * Each item names the shot whose takes hold it (null on the floor), the take's
+ * prompt and status, a clip's still, and the clips rendered from a still.
+ * `history` maps a video id to its history entry. Newest first.
+ */
+function buildMediaPool(project, collectionItems = [], history = new Map()) {
+ const used = usedKeys(project);
+ const byKey = new Map();
+ const add = (kind, ref, fields) => {
+ const key = `${kind}:${ref}`;
+ const current = byKey.get(key);
+ // A take's details win over a bare collection row; the first shot holding it names it.
+ if (!current) byKey.set(key, { kind, assetId: ref, sceneId: null, takeStatus: null, prompt: null, sourceImageId: null, addedAt: null, ...fields });
+ else if (!current.sceneId && fields.sceneId) byKey.set(key, { ...current, ...fields, addedAt: current.addedAt || fields.addedAt });
+ };
+ for (const { kind, ref, sceneId, take } of projectTakeAssets(project)) {
+ add(kind, ref, { sceneId, takeStatus: take?.status || null, prompt: take?.prompt || null,
+ sourceImageId: kind === 'video' ? takeSourceImageId(take) : null, addedAt: take?.createdAt || null });
+ }
+ for (const item of collectionItems) {
+ if (item?.kind !== 'image' && item?.kind !== 'video') continue;
+ const entry = item.kind === 'video' ? history.get(item.ref) : null;
+ add(item.kind, item.ref, { sourceImageId: entry?.musicVideo?.sourceImageId || null, prompt: entry?.prompt || null, addedAt: item.addedAt || null });
+ }
+ const items = [...byKey.values()];
+ const clipsByStill = new Map();
+ for (const item of items) {
+ if (item.kind !== 'video' || !item.sourceImageId) continue;
+ clipsByStill.set(item.sourceImageId, [...(clipsByStill.get(item.sourceImageId) || []), item.assetId]);
+ }
+ return items
+ .filter((item) => !used.has(`${item.kind}:${item.assetId}`))
+ .map((item) => (item.kind === 'image' ? { ...item, clipIds: clipsByStill.get(item.assetId) || [] } : item))
+ .sort((a, b) => String(b.addedAt || '').localeCompare(String(a.addedAt || '')));
+}
+
+/**
+ * File assets into the project's collection, and record each clip's shot and
+ * still on its video history entry. Best-effort bookkeeping: a failure is
+ * logged, never thrown into the render or edit that triggered it.
+ */
+export async function fileMusicVideoMedia(project, assets) {
+ if (!project?.id || !assets?.length) return;
+ try {
+ const { findOrCreateMusicVideoCollection, bulkUpdateCollectionItems } = await import('../mediaCollections.js');
+ const collection = await findOrCreateMusicVideoCollection({ projectId: project.id, projectName: project.name });
+ const present = new Set(collection.items.map((item) => `${item.kind}:${item.ref}`));
+ const add = [];
+ for (const { kind, ref } of assets) {
+ const key = `${kind}:${ref}`;
+ if (present.has(key) || ref.includes(':') || ref.includes('/')) continue;
+ present.add(key);
+ add.push({ kind, ref });
+ }
+ if (add.length) await bulkUpdateCollectionItems(collection.id, { add });
+ const clips = new Map(assets.filter((asset) => asset.kind === 'video')
+ .map((asset) => [asset.ref, { projectId: project.id, sceneId: asset.sceneId || null, sourceImageId: takeSourceImageId(asset.take) }]));
+ if (clips.size) await stampClipProvenance(clips);
+ } catch (err) {
+ console.error(`❌ music-video media pool: filing for ${project.id} failed: ${err.message}`);
+ }
+}
+
+async function stampClipProvenance(clips) {
+ const { mutateVideoHistory, HISTORY_UNCHANGED } = await import('../videoGen/history.js');
+ await mutateVideoHistory((history) => {
+ let changed = false;
+ for (const entry of history) {
+ const tag = entry && clips.get(entry.id);
+ if (!tag || entry.musicVideo?.projectId === tag.projectId) continue;
+ entry.musicVideo = tag;
+ changed = true;
+ }
+ return changed ? history : HISTORY_UNCHANGED;
+ });
+}
+
+/**
+ * The unused stills and clips for a project's picker, backfilling its
+ * collection first. An asset no longer in the media library (deleted from the
+ * gallery or history) is left out rather than shown as a broken tile.
+ */
+export async function getMusicVideoMediaPool(project) {
+ await fileMusicVideoMedia(project, projectTakeAssets(project));
+ const [{ getCollection, musicVideoCollectionId }, { loadHistory }, { resolveGalleryImage }] = await Promise.all([
+ import('../mediaCollections.js'), import('../videoGen/history.js'), import('../../lib/pathSafety.js'),
+ ]);
+ const collection = await getCollection(musicVideoCollectionId(project.id)).catch(() => null);
+ const history = new Map((await loadHistory()).filter((entry) => entry?.id).map((entry) => [entry.id, entry]));
+ const items = buildMediaPool(project, collection?.items || [], history)
+ .filter((item) => (item.kind === 'video' ? history.has(item.assetId) : Boolean(resolveGalleryImage(item.assetId))))
+ // A partner that is gone is not offered, so "Use … + its still|clip" always works.
+ .map((item) => (item.clipIds ? { ...item, clipIds: item.clipIds.filter((id) => history.has(id)) }
+ : item.sourceImageId && !resolveGalleryImage(item.sourceImageId) ? { ...item, sourceImageId: null } : item));
+ return { collectionId: collection?.id || null, items };
+}
diff --git a/server/services/musicVideo/projects.js b/server/services/musicVideo/projects.js
index 4fa193f7be..d711bd5997 100644
--- a/server/services/musicVideo/projects.js
+++ b/server/services/musicVideo/projects.js
@@ -23,6 +23,7 @@ import { assertMusicVideoMediaSelections } from '../../lib/musicVideoMediaPolicy
*/
import { setSceneLastFailure } from './takes.js';
+import { droppedTakeAssets, fileMusicVideoMedia } from './mediaPool.js';
import { presentMusicVideoDependencies, retainMusicVideoDependencies } from '../../lib/musicVideoDependencies.js';
import { createRecordStoreBackendSelector } from '../../lib/pgFileFacade.js';
import { emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers } from '../sharing/recordEvents.js';
@@ -317,13 +318,21 @@ export async function appendSceneTakes(id, sceneId, inputs) {
if (inputs.some(input => input.source === 'generated')) {
const { appendSceneTakes: append } = await import('./takes.js');
const outcome = await mutateProjectRecord(id, current => append(current, sceneId, inputs), { source: 'generation-completion' });
+ await fileAppendedTakes(outcome.project, outcome.appended.map(take => ({ sceneId, take })));
return { scene: outcome.project.scenes.find(scene => scene.sceneId === sceneId), appended: outcome.appended };
}
const result = await (await selectBackend()).appendSceneTakes(id, sceneId, inputs);
emitRecordUpdated('musicVideoProject', id);
+ await fileAppendedTakes(await getProject(id), result.appended.map(take => ({ sceneId, take })));
return result;
}
+// Every take that lands also lands in the project's own collection (mediaPool.js).
+function fileAppendedTakes(project, placed) {
+ return fileMusicVideoMedia(project, placed.filter(({ take }) => take?.assetId)
+ .map(({ sceneId, take }) => ({ kind: take.kind === 'video' ? 'video' : 'image', ref: take.assetId, sceneId, take })));
+}
+
/**
* Persist (or clear, with `failure` null) a scene's last generation failure —
* `{ lane: 'image'|'video', error, at }` (#10154). Returns the updated scene.
@@ -337,6 +346,7 @@ export async function recordSceneFailure(id, sceneId, failure) {
export async function appendTakesAcrossScenes(id, items) {
const result = await (await selectBackend()).appendTakesAcrossScenes(id, items);
emitRecordUpdated('musicVideoProject', id);
+ await fileAppendedTakes(result.project, result.appended.filter(Boolean));
return result;
}
@@ -350,6 +360,39 @@ export async function selectSceneTake(id, sceneId, takeId) {
return scene;
}
+/**
+ * Put an unused still or clip from the project's pool on a shot (the shot
+ * card's "Swap from unused"): it becomes a take of the shot and its selection.
+ * `withAssetId` brings its partner too: a still's clip, or a clip's still.
+ * `kind: 'endImage'` puts a still on the shot's end frame instead.
+ * The take keeps the prompt and provider of the take it came from. A shot
+ * whose video is locked refuses, as it does any other new selection.
+ * Returns the updated scene.
+ */
+export async function placeMediaPoolItem(id, sceneId, { kind, assetId, withAssetId = null }) {
+ const [{ appendSceneTakes: append, selectSceneTake: select }, { assertClipUnlocked }, { projectTakeAssets }] = await Promise.all([
+ import('./takes.js'), import('./productionReview.js'), import('./mediaPool.js'),
+ ]);
+ const { scene } = await mutateProjectRecord(id, (current) => {
+ assertClipUnlocked(current, sceneId);
+ const origin = new Map(projectTakeAssets(current).filter(asset => asset.take).map(asset => [`${asset.kind}:${asset.ref}`, asset.take]));
+ const still = kind === 'video' ? withAssetId : assetId;
+ const clip = kind === 'video' ? assetId : withAssetId;
+ const input = (takeKind, ref) => {
+ const from = origin.get(`${takeKind === 'video' ? 'video' : 'image'}:${ref}`);
+ return { kind: takeKind, assetId: ref, source: 'reused', provider: from?.provider || null, prompt: from?.prompt || null,
+ ...(takeKind === 'video' && still ? { sourceImageId: still } : {}) };
+ };
+ const inputs = kind === 'endImage'
+ ? [input('endImage', assetId)]
+ : [...(still ? [input('image', still)] : []), ...(clip ? [input('video', clip)] : [])];
+ let outcome = append(current, sceneId, inputs);
+ for (const take of outcome.appended) outcome = { ...select(outcome.project, sceneId, take.takeId), appended: outcome.appended };
+ return outcome;
+ });
+ return scene;
+}
+
/** Reject/restore a take and/or set its note. Returns the updated scene. */
export async function reviewSceneTake(id, sceneId, takeId, review) {
const [{ reviewSceneTake: reviewTake }, { assertClipUnlocked }] = await Promise.all([import('./takes.js'), import('./productionReview.js')]);
@@ -369,6 +412,7 @@ export async function reviewSceneTake(id, sceneId, takeId, review) {
*/
export async function mutateProjectRecord(id, transform, { source = null } = {}) {
const { preserveAutomatedShotLocks } = source ? await import('./productionReview.js') : {};
+ let dropped = null;
const outcome = await (await selectBackend()).mutateProjectRecord(id, (current) => {
const outcome = transform(current);
if (source) {
@@ -382,9 +426,12 @@ export async function mutateProjectRecord(id, transform, { source = null } = {})
if ('replaced' in outcome) outcome.replaced = 0;
}
}
+ dropped = { project: current, assets: droppedTakeAssets(current, outcome.project) };
return { ...outcome, project: retainMusicVideoDependencies(current, outcome.project) };
});
emitRecordUpdated('musicVideoProject', id);
+ // A cut shot, a merge or a re-plan drops takes from the board: they stay findable in the project's collection.
+ if (dropped?.assets.length) await fileMusicVideoMedia(dropped.project, dropped.assets);
return outcome;
}