Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-10589]): shared camera-movement vocabulary for music-video planning (#10597)
atomanticagent907afda86741
diff --git a/client/src/components/musicVideo/ProductionReviewPanel.jsx b/client/src/components/musicVideo/ProductionReviewPanel.jsxindex 9d99e21f3f..ac3e1005d6 100644--- a/client/src/components/musicVideo/ProductionReviewPanel.jsx+++ b/client/src/components/musicVideo/ProductionReviewPanel.jsx@@ -239,6 +239,11 @@ export default function ProductionReviewPanel({ project, review, onOpenArtifact,</div>{approvalHelp(key) && <p id={fieldId(`${key}-approval-help`)} role="status" className="mt-1 text-sm text-port-warning">{approvalHelp(key)}</p>}{listedProblems(key).length > 0 && <ul className="mt-1 list-disc pl-5 text-xs text-port-text-muted">{listedProblems(key).map(problem => <li key={problem}>{problem}</li>)}</ul>}+ {/* Camera variety (#10589) is advice, never a blocker on approval. */}+ {key === 'storyboard' && ready?.storyboard.camera?.notes?.length > 0 && <div role="note" aria-label="Camera variety notes" className="mt-2 text-xs text-port-text-muted">+ <p>Camera notes (they don't block approval):</p>+ <ul className="list-disc pl-5">{ready.storyboard.camera.notes.map(note => <li key={note}>{note}</li>)}</ul>+ </div>}{key === 'proof' ? proofContent : <ProductionReviewContext stage={key} project={project} onOpenArtifact={onOpenArtifact} onArtReady={available => setVisibleArt(available ? artIdentity : null)} onSeek={onSeek} />}{openRequests(key).length > 0 && <div role="group" aria-label={`${label} change requests`} className="mt-2 space-y-2 rounded border border-port-warning p-2"><p className="text-sm">Resolve these change requests to approve.</p>diff --git a/client/src/components/musicVideo/ProductionReviewPanel.test.jsx b/client/src/components/musicVideo/ProductionReviewPanel.test.jsxindex c0532b09c8..3dddc123af 100644--- a/client/src/components/musicVideo/ProductionReviewPanel.test.jsx+++ b/client/src/components/musicVideo/ProductionReviewPanel.test.jsx@@ -393,3 +393,22 @@ describe('Per-stage approval sections (#10151)', () => {expect(screen.queryByText('About production approvals')).toBeNull();});});++describe('storyboard camera notes (#10589)', () => {+ it('lists camera-variety notes under the storyboard without blocking approval', () => {+ const review = reviewFixture();+ const note = 'Chorus at 0:45 has no snap move: land a whip-pan, crash-zoom, dutch-roll, crash-zoom-out on its first downbeat.';+ review.readiness.storyboard = { approved: false, problems: [], camera: { staticRuns: [], snaplessChoruses: [{ label: 'Chorus', startSec: 45 }], notes: [note] } };+ render(<ProductionReviewPanel project={project} review={review} onOpenArtifact={vi.fn()} stage="storyboard" />);+ const notes = screen.getByRole('note', { name: 'Camera variety notes' });+ expect(within(notes).getByText(note)).toBeTruthy();+ expect(screen.getByRole('button', { name: 'Approve lyric-timed storyboard' }).disabled).toBe(false);+ });++ it('shows nothing when the camera plan is varied', () => {+ const review = reviewFixture();+ review.readiness.storyboard = { approved: false, problems: [], camera: { staticRuns: [], snaplessChoruses: [], notes: [] } };+ render(<ProductionReviewPanel project={project} review={review} onOpenArtifact={vi.fn()} stage="storyboard" />);+ expect(screen.queryByRole('note', { name: 'Camera variety notes' })).toBeNull();+ });+});diff --git a/client/src/components/musicVideo/SceneCameraControls.jsx b/client/src/components/musicVideo/SceneCameraControls.jsxnew file mode 100644index 0000000000..ac10856ce7--- /dev/null+++ b/client/src/components/musicVideo/SceneCameraControls.jsx@@ -0,0 +1,60 @@+import { CAMERA_FAMILIES, CAMERA_MOVEMENTS, CAMERA_SPEEDS, getCameraMovement } from '../../../../server/lib/cameraMovements.js';++const FIELD = 'bg-port-bg border border-port-border rounded px-1 py-1 min-h-[44px] sm:min-h-0';+const BY_FAMILY = CAMERA_FAMILIES.map((family) => [family, CAMERA_MOVEMENTS.filter((move) => move.family === family)])+ .filter(([, moves]) => moves.length);++/**+ * A shot's planned camera move (#10589): one of the shared catalog moves, its+ * speed, whether it lands on the downbeat, and why a still camera holds. The+ * i2v prompt carries it as the four-part camera block and a composed still+ * plays it through the layered camera rig.+ */+export default function SceneCameraControls({ scene, fieldId, onEditLocal, onSave }) {+ const camera = scene.camera && getCameraMovement(scene.camera.move) ? scene.camera : null;+ const move = camera ? getCameraMovement(camera.move) : null;+ const save = (next) => {+ const value = next?.move ? Object.fromEntries(Object.entries(next).filter(([, v]) => v !== '' && v !== undefined && v !== false)) : null;+ onEditLocal(scene.sceneId, { camera: value });+ onSave(scene.sceneId, { camera: value });+ };+ return (+ <div className="flex flex-wrap gap-2 items-center text-xs">+ <label htmlFor={fieldId('camera')}>Camera</label>+ <select id={fieldId('camera')} value={camera?.move || ''} className={FIELD}+ title="The planned camera move. Video prompts describe it as movement, speed, framing and end; composed stills play it."+ onChange={(e) => save(e.target.value ? { ...camera, move: e.target.value, ...(getCameraMovement(e.target.value).still ? {} : { reason: undefined }) } : null)}>+ <option value="">None</option>+ {BY_FAMILY.map(([family, moves]) => (+ <optgroup key={family} label={family}>+ {moves.map((m) => <option key={m.value} value={m.value}>{m.label}</option>)}+ </optgroup>+ ))}+ </select>+ {move && (+ <>+ <label htmlFor={fieldId('camera-speed')}>Speed</label>+ <select id={fieldId('camera-speed')} value={camera.speed || ''} className={FIELD}+ onChange={(e) => save({ ...camera, speed: e.target.value || undefined })}>+ <option value="">Default ({move.speed})</option>+ {CAMERA_SPEEDS.map((speed) => <option key={speed} value={speed}>{speed}</option>)}+ </select>+ <label className="flex items-center gap-1">+ <input type="checkbox" checked={camera.onBeat === true} onChange={(e) => save({ ...camera, onBeat: e.target.checked })} />+ On beat+ </label>+ {move.still && (+ <>+ <label htmlFor={fieldId('camera-reason')}>Why it holds</label>+ <input id={fieldId('camera-reason')} type="text" maxLength={300} value={camera.reason || ''}+ placeholder="The reason for a static camera"+ onChange={(e) => onEditLocal(scene.sceneId, { camera: { ...camera, reason: e.target.value } })}+ onBlur={(e) => save({ ...camera, reason: e.target.value.trim() || undefined })}+ className={`min-w-0 flex-1 basis-40 ${FIELD}`} />+ </>+ )}+ </>+ )}+ </div>+ );+}diff --git a/client/src/components/musicVideo/SceneCard.jsx b/client/src/components/musicVideo/SceneCard.jsxindex 94f330ce25..0d3c731432 100644--- a/client/src/components/musicVideo/SceneCard.jsx+++ b/client/src/components/musicVideo/SceneCard.jsx@@ -1,5 +1,6 @@import PlateComparison from './PlateComparison.jsx';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, Scissors } from 'lucide-react';@@ -290,7 +291,8 @@ export default function SceneCard({<><label htmlFor={fieldId('move')}>Move</label><select id={fieldId('move')} value={scene.stillMove || 'hold'} onChange={(e) => applyPatch({ stillMove: e.target.value })}- className="bg-port-bg border border-port-border rounded px-1 py-1 min-h-[44px] sm:min-h-0">+ disabled={!!scene.camera?.move} title={scene.camera?.move ? 'The planned camera move drives this still.' : undefined}+ className="bg-port-bg border border-port-border rounded px-1 py-1 min-h-[44px] sm:min-h-0 disabled:opacity-50">{STILL_MOVE_LABELS.map(([value, text]) => <option key={value} value={value}>{text}</option>)}</select></>@@ -329,6 +331,7 @@ 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's footage.diff --git a/client/src/components/musicVideo/SceneCard.test.jsx b/client/src/components/musicVideo/SceneCard.test.jsxindex dbc0446d71..7be9054382 100644--- a/client/src/components/musicVideo/SceneCard.test.jsx+++ b/client/src/components/musicVideo/SceneCard.test.jsx@@ -72,6 +72,43 @@ describe('persisted render failure chip (#10154)', () => {});});+describe('planned camera move (#10589)', () => {+ function Harness({ initial, onSave }) {+ const [scene, setScene] = useState(initial);+ return <SceneCard scene={scene} index={0} layered onEditLocal={(_id, patch) => setScene((current) => ({ ...current, ...patch }))} onSave={onSave} />;+ }++ it('picks a catalog move, its speed and beat, and clears it', () => {+ const onSave = vi.fn();+ render(<Harness initial={{ sceneId: 's1', visualLayer: 'still', startSec: 0, endSec: 5, takes: [] }} onSave={onSave} />);+ const select = screen.getByLabelText('Camera');+ expect(select.value).toBe('');+ expect(screen.getByLabelText('Move').disabled).toBe(false);+ fireEvent.change(select, { target: { value: 'whip-pan' } });+ expect(onSave).toHaveBeenLastCalledWith('s1', { camera: { move: 'whip-pan' } });+ expect(screen.getByLabelText('Move').disabled).toBe(true);+ fireEvent.change(screen.getByLabelText('Speed'), { target: { value: 'fast' } });+ fireEvent.click(screen.getByLabelText('On beat'));+ expect(onSave).toHaveBeenLastCalledWith('s1', { camera: { move: 'whip-pan', speed: 'fast', onBeat: true } });+ fireEvent.change(select, { target: { value: '' } });+ expect(onSave).toHaveBeenLastCalledWith('s1', { camera: null });+ });++ it('asks why a static camera holds, and offers no camera on a title card', () => {+ const onSave = vi.fn();+ const { unmount } = render(<Harness initial={{ sceneId: 's1', startSec: 0, endSec: 5, takes: [], camera: { move: 'slow-dolly-in' } }} onSave={onSave} />);+ expect(screen.queryByLabelText('Why it holds')).toBeNull();+ fireEvent.change(screen.getByLabelText('Camera'), { target: { value: 'locked-off' } });+ const reason = screen.getByLabelText('Why it holds');+ fireEvent.change(reason, { target: { value: ' the dancer fills the frame ' } });+ fireEvent.blur(reason);+ expect(onSave).toHaveBeenLastCalledWith('s1', { camera: { move: 'locked-off', reason: 'the dancer fills the frame' } });+ unmount();+ render(<SceneCard scene={{ sceneId: 's2', visualLayer: 'card', startSec: 0, endSec: 5, takes: [] }} index={0} layered onEditLocal={() => {}} onSave={() => {}} />);+ expect(screen.queryByLabelText('Camera')).toBeNull();+ });+});+describe('lyric type per shot (#10583)', () => {it('lets a composition-document shot pick its lyric zone and style, and clears back to the defaults', () => {const onSave = vi.fn();diff --git a/client/src/hooks/useMusicVideoSceneMedia.js b/client/src/hooks/useMusicVideoSceneMedia.jsindex 15efbe1d5a..b976d0ef63 100644--- a/client/src/hooks/useMusicVideoSceneMedia.js+++ b/client/src/hooks/useMusicVideoSceneMedia.js@@ -1,4 +1,5 @@import { shotActionContractProblem, shotActionPrompt } from '../../../server/lib/musicVideoActionContract.js';+import { shotCameraPrompt } from '../../../server/lib/cameraMovements.js';import { musicVideoConditioningReferences, MUSIC_VIDEO_MAX_CONDITIONING_REFERENCES } from '../../../server/lib/musicVideoConditioning.js';import { musicVideoCreativeContext } from '../../../server/lib/musicVideoCreativeContext.js';import { useEffect, useRef } from 'react';@@ -175,9 +176,10 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applyS[[(scene.framePrompt?.trim() || scene.prompt?.trim() || ''), style, direction, scene.direction?.frameClause?.trim()].filter(Boolean).join(', '), shotActionPrompt(project, scene, { frame: true })].filter(Boolean).join('\n');// The i2v prompt for a scene's clip: its shot prompt (or the frame prompt as a// fallback) suffixed the same way. The reference frame already fixes the- // look; this prompt guides the motion.+ // look; this prompt guides the motion. A planned camera move (#10589) follows+ // as the four-part camera block, same as handoff.js sceneShotPrompt.const buildShotPrompt = (scene) =>- [[(scene.prompt?.trim() || scene.framePrompt?.trim() || ''), style, motionDirection, scene.direction?.motionClause?.trim(), MOTION_CONTINUITY_CLAUSE].filter(Boolean).join(', '), shotActionPrompt(project, scene)].filter(Boolean).join('\n');+ [[(scene.prompt?.trim() || scene.framePrompt?.trim() || ''), style, motionDirection, scene.direction?.motionClause?.trim(), MOTION_CONTINUITY_CLAUSE].filter(Boolean).join(', '), shotCameraPrompt(scene.camera), shotActionPrompt(project, scene)].filter(Boolean).join('\n');/*** Render a still reference frame for one scene from its frame prompt. Thediff --git a/server/lib/README.md b/server/lib/README.mdindex 5a9e23297f..ea07703c77 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -47,7 +47,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `imageRuntimeRemedies.js` | Local image-runtime vocabulary, a dependency-free leaf beside `imageGenCapabilities.js`: `IMAGE_RUNTIME_READINESS` (ready/unavailable/unknown), `IMAGE_RUNTIME` + `IMAGE_RUNTIME_LABELS` (the shared torch venv vs. the configurable mflux interpreter), `IMAGE_RUNTIME_REMEDY` (the one action that fixes each unavailable state), and `IMAGE_RUNTIME_UNAVAILABLE_CODE`. `services/imageGen/localRuntime.js` builds the diagnosis from these, `services/imageGen/local.js` tags its pre-flight render refusal with the same remedy, and `client/src/lib/imageGenModes.js` re-exports them so no component hand-copies a remedy kind. || `renderModeLadder.js` | `resolveRenderPins` and `resolveRenderTargetPins` share backend-scoped model candidate inheritance across browser and server. Image-gen mode resolution ladder (#6815), a dependency-free leaf beside `generationModes.js`/`renderTargets.js` so the client imports it directly instead of hand-copying it: `isModeUsable(settings, mode)` (queueable + enabled gate, no per-provider spec lookup), `pickUsableMode(settings, candidates)` (first usable candidate, falling through disabled pins to the cloud-then-local tail), `renderTargetDefaults(settings, target)` (the normalized `settings.renderDefaults[target]` pin), and `imageModeCandidates(settings, target, record)` (the shared `[recordPin, targetPin, installDefault]` candidate order, declared once so a UI's own "what will Auto resolve to" display can't drift from the resolver). `services/imageGen/cloudProviderConfig.js` re-exports the first three for its existing callers. || `fableLoomLimits.js` | FableLoom record caps (`LOOM_LIMITS`) — the single source of truth shared by the route schemas and the record sanitizer. A leaf module, below both. |-| `fableLoomCameraMovements.js` | Shared FableLoom camera-movement registry for generated cut direction and the manual scene editor selector. |+| `cameraMovements.js` | Shared camera-movement vocabulary (#10589): `CAMERA_MOVEMENTS` (stable ids with `family`, `energy`, `snap`/`still` flags, start/end framing and the four-part movement/speed/framing/end prose), `normalizeCameraMovement`/`cameraMovementId`/`cameraMovementFromText`, `shotCameraPrompt(camera)` (the four-part i2v camera block for a structured shot camera) and `cameraMovementCatalogForPrompt`. Used by FableLoom, Music Video planning/review and the layered template's `cameraRig.js`. |+| `fableLoomCameraMovements.js` | FableLoom names for the shared `cameraMovements.js` catalog (generated cut direction and the manual scene editor selector); persisted ids are unchanged. || `fableLoomPlayback.js` | FableLoom node playback modes (`cut` auto-advances; `decision` loops while awaiting input), with the backward-compatible default. || `fableLoomParticipation.js` | FableLoom audience roles (helper vs protagonist), per-scene connection availability, prompt contracts, and backward-compatible defaults. || `fableLoomFormats.js` | FableLoom scene formats (`LOOM_FORMATS`, `asLoomFormat`, `sceneFormatContract`, …) — how a loom writes scene text, read by validation, the sanitizer, and every generative stage. |diff --git a/server/lib/cameraMovements.js b/server/lib/cameraMovements.jsnew file mode 100644index 0000000000..4c3f2d098f--- /dev/null+++ b/server/lib/cameraMovements.js@@ -0,0 +1,428 @@+/**+ * Shared camera-movement vocabulary (#10589) — FableLoom's cut direction, the+ * Music Video storyboard's structured `camera` field, the four-part i2v camera+ * block, and the layered document template's camera rig all key off these ids.+ *+ * `value` ids are stable persisted identifiers (FableLoom scene nodes and Music+ * Video scenes store them); labels and prose may improve without a migration.+ *+ * Each move carries:+ * - `family` — the kind of motion (push-pull, rotate, lateral, …). Planning+ * rules key off it ("at most two consecutive shots per family").+ * - `energy` — calm / medium / high: which song energy the move suits.+ * - `snap` — a hit-point move that lands a downbeat or hook word.+ * - `still` — the camera body does not travel (a static frame on screen).+ * - `movement` / `speed` / `framing` / `end` — the four parts of a camera+ * prompt, kept apart from the scene description.+ * - `startFraming` / `endFraming` — shot size at the first and last frame,+ * one of CAMERA_FRAMINGS; the rig's unit test holds every path+ * to them.+ * - `prompt` — the one-line direction FableLoom's prompts and editor show.+ */++import { escapeRegExp } from './textUtils.js';++export const CAMERA_FAMILIES = Object.freeze([+ 'static', 'push-pull', 'rotate', 'lateral', 'vertical', 'orbit', 'tracking', 'lens', 'roll', 'scale', 'time',+]);+export const CAMERA_ENERGIES = Object.freeze(['calm', 'medium', 'high']);+export const CAMERA_SPEEDS = Object.freeze(['slow', 'moderate', 'fast', 'snap']);+export const CAMERA_FRAMINGS = Object.freeze(['extreme-wide', 'wide', 'medium', 'close', 'extreme-close']);++const SPEED_TEXT = Object.freeze({+ slow: 'slow and steady for the whole shot',+ moderate: 'moderate, even pace',+ fast: 'fast and committed, easing into the end position',+ snap: 'a near-instant snap, then hold',+});+const FRAMING_TEXT = Object.freeze({+ 'extreme-wide': 'an extreme wide shot',+ wide: 'a wide shot',+ medium: 'a medium shot',+ close: 'a close-up',+ 'extreme-close': 'an extreme close-up',+});++// [value, label, family, energy, speed, startFraming, endFraming, movement, framing, end, prompt, flags]+const ROWS = [+ ['locked-off', 'Locked-off / static', 'static', 'calm', 'slow', 'medium', 'medium',+ 'The camera stays completely still on a tripod; only the subject and the world move.',+ 'Subject placed with deliberate negative space.',+ 'Same frame as it began.',+ 'Locked-off tripod shot; the camera remains completely still.', { still: true }],+ ['slow-dolly-in', 'Slow dolly in', 'push-pull', 'calm', 'slow', 'medium', 'close',+ 'The camera body travels straight toward the subject on a smooth track.',+ 'Subject centered, eye level.',+ 'Settles closer, with the subject filling more of the frame.',+ 'Camera slowly moves forward toward the subject.'],+ ['slow-dolly-out', 'Slow dolly out', 'push-pull', 'calm', 'slow', 'medium', 'wide',+ 'The camera body backs straight away from the subject on a smooth track.',+ 'Subject centered, eye level.',+ 'Opens up to show the surroundings around the subject.',+ 'Camera slowly moves backward away from the subject.'],+ ['fast-dolly-in', 'Fast dolly in', 'push-pull', 'high', 'fast', 'wide', 'close',+ 'The camera charges toward the subject along a straight line.',+ 'Subject small in the frame, centered.',+ 'Arrives tight on the subject with urgency.',+ 'Camera rapidly pushes toward the subject with urgent motion.'],+ ['dolly-zoom', 'Dolly zoom / vertigo', 'lens', 'medium', 'moderate', 'medium', 'medium',+ 'The camera dollies forward while the lens widens, so the subject keeps its size while the background stretches away.',+ 'Subject centered against a deep background.',+ 'Subject the same size, background warped and distant.',+ 'Camera dollies while zooming in the opposite direction, warping background scale.'],+ ['zoom-in', 'Optical zoom in', 'lens', 'calm', 'moderate', 'medium', 'close',+ 'The camera stays put while the lens narrows onto the subject.',+ 'Subject centered, flat perspective.',+ 'Magnified on the subject with compressed depth.',+ 'Stationary camera smoothly magnifies the subject with the lens.'],+ ['zoom-out', 'Optical zoom out', 'lens', 'calm', 'moderate', 'medium', 'wide',+ 'The camera stays put while the lens widens away from the subject.',+ 'Subject centered.',+ 'Wide view with the subject small inside the setting.',+ 'Stationary camera smoothly widens the field of view with the lens.'],+ ['crash-zoom', 'Crash zoom', 'lens', 'high', 'snap', 'medium', 'extreme-close',+ 'The lens punches in on a key detail in a fraction of a second.',+ 'Detail already near the center of frame.',+ 'Slams to a tight detail and holds there.',+ 'A sudden snap zoom punches into the key detail.', { snap: true }],+ ['macro-zoom', 'Extreme macro zoom', 'scale', 'medium', 'moderate', 'medium', 'extreme-close',+ 'The camera closes in past normal focus distance into a macro world on the subject.',+ 'Subject centered with a chosen detail at the center.',+ 'Lands in extreme macro texture of that detail.',+ 'The view transitions from the subject into an extreme macro detail.'],+ ['pan-left', 'Pan left', 'rotate', 'calm', 'moderate', 'medium', 'medium',+ 'The camera pivots horizontally to the left from a fixed position.',+ 'Subject on the right third.',+ 'Comes to rest on what lay to the left.',+ 'Camera pivots horizontally to the left from a fixed position.'],+ ['pan-right', 'Pan right', 'rotate', 'calm', 'moderate', 'medium', 'medium',+ 'The camera pivots horizontally to the right from a fixed position.',+ 'Subject on the left third.',+ 'Comes to rest on what lay to the right.',+ 'Camera pivots horizontally to the right from a fixed position.'],+ ['whip-pan', 'Whip pan', 'rotate', 'high', 'snap', 'medium', 'medium',+ 'The camera whips sideways so fast the frame smears into motion blur.',+ 'Subject sharp before the whip.',+ 'Snaps onto a new subject and holds it sharp.',+ 'Camera whips sideways with strong directional motion blur.', { snap: true }],+ ['tilt-up', 'Tilt up', 'rotate', 'calm', 'moderate', 'medium', 'medium',+ 'The camera pivots upward from a fixed position.',+ 'Lower part of the subject or the ground in frame.',+ 'Rests on what rises above.',+ 'Camera pivots vertically upward from a fixed position.'],+ ['tilt-down', 'Tilt down', 'rotate', 'calm', 'moderate', 'medium', 'medium',+ 'The camera pivots downward from a fixed position.',+ 'Sky or the top of the subject in frame.',+ 'Rests on what lies below.',+ 'Camera pivots vertically downward from a fixed position.'],+ ['truck-left', 'Truck left', 'lateral', 'calm', 'moderate', 'medium', 'medium',+ 'The camera body slides sideways to the left, parallel to the subject.',+ 'Subject in profile or square to the lens.',+ 'Same distance, the background has shifted past.',+ 'Camera travels laterally to the left on a parallel track.'],+ ['truck-right', 'Truck right', 'lateral', 'calm', 'moderate', 'medium', 'medium',+ 'The camera body slides sideways to the right, parallel to the subject.',+ 'Subject in profile or square to the lens.',+ 'Same distance, the background has shifted past.',+ 'Camera travels laterally to the right on a parallel track.'],+ ['pedestal-up', 'Pedestal up', 'vertical', 'calm', 'slow', 'medium', 'medium',+ 'The camera body rises straight up without changing its angle.',+ 'Subject at eye level.',+ 'Higher vantage, same angle and distance.',+ 'Camera rises vertically while keeping its angle and distance.'],+ ['pedestal-down', 'Pedestal down', 'vertical', 'calm', 'slow', 'medium', 'medium',+ 'The camera body lowers straight down without changing its angle.',+ 'Subject at eye level.',+ 'Lower vantage, same angle and distance.',+ 'Camera lowers vertically while keeping its angle and distance.'],+ ['crane-up', 'Crane up / high reveal', 'vertical', 'medium', 'slow', 'medium', 'wide',+ 'The camera lifts up and back on a crane arm while keeping the subject in view.',+ 'Subject at eye level.',+ 'High angle looking down on the subject and its surroundings.',+ 'Camera cranes upward into a high-angle reveal.'],+ ['crane-down', 'Crane down / landing', 'vertical', 'medium', 'slow', 'wide', 'medium',+ 'The camera descends on a crane arm from high above toward the subject.',+ 'High angle overview of the setting.',+ 'Lands near eye level with the subject.',+ 'Camera cranes down and settles near the subject.'],+ ['orbit-180', 'Orbit 180°', 'orbit', 'medium', 'moderate', 'medium', 'medium',+ 'The camera circles halfway around the subject, keeping it centered.',+ 'Subject centered, facing the lens.',+ 'Sees the subject from the opposite side.',+ 'Camera makes a half-circle around the subject.'],+ ['orbit-360', 'Orbit 360°', 'orbit', 'high', 'fast', 'medium', 'medium',+ 'The camera makes a full circle around the subject, keeping it centered.',+ 'Subject centered.',+ 'Returns to the starting angle after a full revolution.',+ 'Camera makes one complete circle around the subject.'],+ ['cinematic-arc', 'Slow cinematic arc', 'orbit', 'calm', 'slow', 'medium', 'medium',+ 'The camera drifts along a shallow curve around the subject.',+ 'Subject slightly off center.',+ 'A gently changed angle on the same subject.',+ 'Camera follows a slow, wide curved path around the subject.'],+ ['reveal-from-behind', 'Reveal from behind', 'lateral', 'medium', 'moderate', 'medium', 'medium',+ 'The camera slides out from behind a foreground object to uncover the scene.',+ 'Frame mostly blocked by a close foreground shape.',+ 'The subject fully revealed and clear.',+ 'Camera slides from behind a foreground object to reveal the scene.'],+ ['fly-through', 'Fly-through', 'push-pull', 'high', 'fast', 'wide', 'medium',+ 'The camera flies forward through an opening and keeps going into the space beyond.',+ 'An opening (window, gap, doorway) ahead.',+ 'Inside the new space, closer to its subject.',+ 'Camera passes through an opening and continues into the scene.'],+ ['following-shot', 'Following tracking shot', 'tracking', 'medium', 'moderate', 'medium', 'medium',+ 'The camera follows behind the moving subject at its pace.',+ 'Subject seen from behind, centered.',+ 'Still trailing the subject at the same distance.',+ 'Camera follows behind the moving subject at matching speed.'],+ ['leading-shot', 'Leading tracking shot', 'tracking', 'medium', 'moderate', 'medium', 'medium',+ 'The camera moves backward ahead of the subject as it advances.',+ 'Subject facing the lens, centered.',+ 'Still leading the subject at the same distance.',+ 'Camera moves backward ahead of the subject at matching speed.'],+ ['side-tracking', 'Side tracking shot', 'tracking', 'medium', 'moderate', 'medium', 'medium',+ 'The camera travels alongside the moving subject.',+ 'Subject in profile.',+ 'Still level with the subject, the background streaming past.',+ 'Camera travels parallel beside the moving subject.'],+ ['steadicam-follow', 'Steadicam follow', 'tracking', 'medium', 'moderate', 'medium', 'medium',+ 'A stabilized camera glides with the subject through the space.',+ 'Subject a few steps ahead.',+ 'Still with the subject deeper in the space.',+ 'Stabilized camera glides with the subject through the environment.'],+ ['handheld', 'Handheld documentary', 'tracking', 'medium', 'moderate', 'medium', 'medium',+ 'The camera is held by hand: small drifts, corrections and breathing.',+ 'Subject loosely centered.',+ 'Near where it began, reframed by hand.',+ 'Natural handheld drift and restrained shake create documentary immediacy.'],+ ['pov-walk', 'POV walk', 'tracking', 'medium', 'moderate', 'medium', 'medium',+ 'The camera is the character\'s eyes, walking forward with a light head bob.',+ 'Eye-level view down the path ahead.',+ 'Further along the path.',+ 'First-person camera advances with subtle human head-bob.'],+ ['worm-eye-track', "Worm's-eye tracking", 'tracking', 'medium', 'moderate', 'medium', 'medium',+ 'The camera skims along the ground looking up while it tracks forward.',+ 'Ground-level, subject looming above.',+ 'Still low, further along.',+ 'Ground-level camera tracks forward while looking up.'],+ ['drone-flyover', 'Drone flyover', 'tracking', 'medium', 'moderate', 'extreme-wide', 'extreme-wide',+ 'An aerial camera flies forward high over the landscape.',+ 'Landscape seen from high above.',+ 'Further across the landscape at the same altitude.',+ 'High aerial camera flies forward over the environment.'],+ ['drone-reveal', 'Drone rise and reveal', 'vertical', 'medium', 'slow', 'wide', 'extreme-wide',+ 'An aerial camera climbs and tips down to unveil the wider scene.',+ 'Low view of the near setting.',+ 'High above, the whole scene laid out below.',+ 'Aerial camera rises and tilts down to unveil the larger scene.'],+ ['drone-orbit', 'Large-scale drone orbit', 'orbit', 'medium', 'slow', 'extreme-wide', 'extreme-wide',+ 'An aerial camera sweeps a broad circle around a landmark.',+ 'Landmark at the center of a vast view.',+ 'Same landmark from a new compass angle.',+ 'Aerial camera sweeps in a broad circle around the landscape.'],+ ['drone-dive', 'FPV drone dive', 'vertical', 'high', 'fast', 'extreme-wide', 'medium',+ 'A first-person drone drops steeply down toward the subject.',+ 'High above the subject.',+ 'Pulls out of the dive near the subject.',+ 'Fast first-person aerial camera dives down a vertical structure.'],+ ['top-down-twist', "Top-down / God's-eye twist", 'roll', 'calm', 'slow', 'medium', 'medium',+ 'The camera looks straight down and slowly rotates around its lens axis.',+ 'Overhead view, subject centered.',+ 'Same overhead view, rotated a quarter turn.',+ 'Camera looks straight down while slowly rotating.'],+ ['dutch-roll', 'Dutch roll', 'roll', 'high', 'snap', 'medium', 'medium',+ 'The camera rolls on its lens axis into a tilted, uneasy horizon.',+ 'Level horizon, subject centered.',+ 'Holds on a canted Dutch angle.',+ 'Camera rolls on its lens axis into a disorienting Dutch angle.', { snap: true }],+ ['barrel-roll', 'Barrel roll', 'roll', 'high', 'fast', 'medium', 'medium',+ 'The camera turns a full revolution on its lens axis while drifting forward.',+ 'Subject centered.',+ 'Level again, slightly closer.',+ 'Camera rotates a full turn on its lens axis while moving forward.'],+ ['rack-focus', 'Rack focus', 'lens', 'calm', 'moderate', 'medium', 'medium',+ 'The camera holds position while focus shifts between foreground and background.',+ 'Two subjects at different depths.',+ 'The second subject sharp, the first soft.',+ 'Focus shifts decisively between foreground and background subjects; camera position stays fixed.'],+ ['focus-reveal', 'Reveal from blur', 'lens', 'calm', 'slow', 'medium', 'medium',+ 'The camera holds position while the image resolves from total blur to sharp focus.',+ 'Fully defocused frame.',+ 'Crisp, fully resolved image.',+ 'The shot begins fully defocused and gradually resolves to sharp focus.'],+ ['ots-drift', 'Over-the-shoulder drift', 'lateral', 'calm', 'slow', 'medium', 'medium',+ 'The camera sits behind one shoulder and drifts a little sideways.',+ 'Foreground shoulder soft on one side, subject beyond.',+ 'Same over-the-shoulder view, slightly shifted.',+ 'Camera holds an over-the-shoulder composition with a subtle lateral drift.'],+ ['push-past', 'Push past foreground', 'push-pull', 'medium', 'moderate', 'wide', 'medium',+ 'The camera pushes forward past a close foreground element to uncover the subject.',+ 'A foreground element close to the lens.',+ 'Past the foreground, closer on the subject.',+ 'Camera pushes past a close foreground element to uncover the subject.'],+ ['slider-parallax', 'Slider parallax', 'lateral', 'calm', 'slow', 'medium', 'medium',+ 'A short sideways slider move while staying aimed at the subject, so layers separate.',+ 'Foreground, subject and background layers.',+ 'Same subject, the layers shifted against each other.',+ 'A short lateral slider move creates controlled foreground-background parallax.'],+ ['body-mount', 'Body-mounted / SnorriCam', 'tracking', 'high', 'moderate', 'close', 'close',+ 'The camera is rigged to the subject, so they stay fixed while the world swings around them.',+ 'Subject\'s face or torso, rigidly centered.',+ 'Subject unchanged in frame, the world moved behind them.',+ 'Camera stays rigidly mounted to the moving subject while the world swings behind them.'],+ ['bullet-time', 'Bullet-time orbit', 'time', 'high', 'moderate', 'medium', 'medium',+ 'Time nearly stops while the camera moves around the frozen moment.',+ 'Subject mid-action.',+ 'A new angle on the same frozen instant.',+ 'Action nearly freezes while the camera moves around the moment.'],+ ['hyperlapse', 'Moving hyperlapse', 'time', 'medium', 'moderate', 'medium', 'medium',+ 'The camera travels forward through accelerated time.',+ 'A path or street ahead.',+ 'Much further along, time compressed around the route.',+ 'Camera advances through accelerated time with compressed environmental motion.'],+ // #10589 — scale and time moves for cosmic-scale music videos.+ ['infinite-zoom', 'Infinite zoom', 'scale', 'high', 'moderate', 'medium', 'extreme-close',+ 'The camera dives straight into the center of frame, the subject giving way to a smaller world nested inside it.',+ 'The entry point locked at the exact center.',+ 'Deep inside the nested world, still dead center, ready to loop.',+ 'Center-locked dive that keeps zooming into a nested world inside the subject.'],+ ['powers-of-ten', 'Powers-of-ten zoom out', 'scale', 'medium', 'slow', 'close', 'extreme-wide',+ 'The camera pulls straight back from overhead in steady multiples, each step showing ten times more.',+ 'Overhead view of the origin point, centered.',+ 'Vast scale — city, planet or beyond — with the origin still at the center.',+ 'Overhead pull-back by steady powers of ten with the origin locked at the center.'],+ ['locked-time-lapse', 'Locked time-lapse', 'time', 'calm', 'slow', 'medium', 'medium',+ 'The camera stays locked off while hours pass in seconds.',+ 'A composed view with something that changes over time (sky, crowd, light).',+ 'Same frame, much later.',+ 'Locked-off tripod time-lapse; light and motion race while the frame stays fixed.', { still: true }],+ ['tilt-shift-miniature', 'Tilt-shift miniature', 'lens', 'calm', 'slow', 'wide', 'wide',+ 'A high-angle camera drifts slowly while a narrow band of focus makes the world look like a model.',+ 'High angle over a busy scene, sharp band across the middle.',+ 'Same toy-like view, drifted slightly.',+ 'High-angle tilt-shift view with a narrow focus band that makes the scene look miniature.'],+ ['crash-zoom-out', 'Crash zoom out', 'lens', 'high', 'snap', 'extreme-close', 'wide',+ 'The lens snaps backward from a tight detail to the whole scene in an instant.',+ 'Tight on a detail.',+ 'Holds on the wide view that contains it.',+ 'A sudden snap zoom out from a tight detail to reveal the whole scene.', { snap: true }],+ ['chase-tracking', 'Chase / vehicle tracking', 'tracking', 'high', 'fast', 'medium', 'medium',+ 'The camera races alongside or behind a fast-moving subject or vehicle, swaying with the road.',+ 'Subject or vehicle centered, speed streaking past.',+ 'Still matched to the subject at speed.',+ 'Camera rides with a fast-moving subject or vehicle, matching its speed with road sway.'],+];++export const CAMERA_MOVEMENTS = Object.freeze(ROWS.map(([+ value, label, family, energy, speed, startFraming, endFraming, movement, framing, end, prompt, flags = {},+]) => Object.freeze({+ value, label, family, energy, speed, startFraming, endFraming, movement, framing, end, prompt,+ snap: flags.snap === true, still: flags.still === true,+})));++export const CAMERA_MOVEMENT_VALUES = Object.freeze(CAMERA_MOVEMENTS.map(({ value }) => value));+export const SNAP_CAMERA_MOVEMENTS = Object.freeze(CAMERA_MOVEMENTS.filter((move) => move.snap).map(({ value }) => value));++const BY_VALUE = new Map(CAMERA_MOVEMENTS.map((move) => [move.value, move]));++/** The catalog entry for a stable id, or null. */+export const getCameraMovement = (id) => (typeof id === 'string' && BY_VALUE.get(id)) || null;++/**+ * Canonicalize an id or label (case-insensitive) to its stable id; anything+ * else is returned trimmed so free-text direction survives (FableLoom stores+ * custom directions verbatim).+ */+export const normalizeCameraMovement = (raw) => {+ if (typeof raw !== 'string') return '';+ const candidate = raw.trim();+ const normalized = candidate.toLowerCase();+ const match = CAMERA_MOVEMENTS.find(({ value, label }) => (+ value.toLowerCase() === normalized || label.toLowerCase() === normalized+ ));+ return match?.value || candidate;+};++/** A catalog id for `raw`, or '' when it names no catalog move. */+export const cameraMovementId = (raw) => {+ const id = normalizeCameraMovement(raw);+ return BY_VALUE.has(id) ? id : '';+};++// Longest first so "slow dolly in" wins over "dolly zoom"-style partial overlaps.+const TEXT_MATCHERS = CAMERA_MOVEMENTS+ .flatMap((move) => [move.value, move.value.replace(/-/g, ' '), move.label.split(' / ')[0]]+ .map((needle) => ({ needle: needle.toLowerCase(), value: move.value })))+ .sort((a, b) => b.needle.length - a.needle.length)+ .map(({ needle, value }) => ({ value, pattern: new RegExp(`(?:^|[^a-z])${escapeRegExp(needle)}(?:$|[^a-z])`) }));+const STATIC_TEXT = /\b(?:static|lock(?:ed)?[- ]?off|tripod)\b/;++/**+ * Best-effort catalog id named somewhere inside free-text camera direction+ * (a storyboard's "Locked-off camera", "slow dolly in on the hands"), or ''.+ * Used only to report on prose; it never rewrites what a director typed.+ */+export const cameraMovementFromText = (text) => {+ if (typeof text !== 'string' || !text.trim()) return '';+ const exact = cameraMovementId(text);+ if (exact) return exact;+ const lower = text.toLowerCase();+ const hit = TEXT_MATCHERS.find(({ pattern }) => pattern.test(lower));+ if (hit) return hit.value;+ return STATIC_TEXT.test(lower) ? 'locked-off' : '';+};++/**+ * Compose the four-part camera prompt (Movement / Speed / Framing / End) for a+ * catalog move, kept separate from the scene description so an i2v model reads+ * the camera as its own instruction. `overrides` may set `speed` (a+ * CAMERA_SPEEDS value), `endFraming` (a CAMERA_FRAMINGS value), `onBeat`+ * (land the move on the downbeat) and `reason` (why a still camera is right).+ * Returns '' for an id outside the catalog. Callers go through shotCameraPrompt.+ */+function cameraMovementPrompt(id, overrides = {}) {+ const move = getCameraMovement(id);+ if (!move) return '';+ const speed = CAMERA_SPEEDS.includes(overrides.speed) ? overrides.speed : move.speed;+ const endFraming = CAMERA_FRAMINGS.includes(overrides.endFraming) ? overrides.endFraming : move.endFraming;+ const reason = typeof overrides.reason === 'string' && overrides.reason.trim() ? ` Reason: ${overrides.reason.trim()}` : '';+ const capital = (s) => s.charAt(0).toUpperCase() + s.slice(1);+ return [+ `Camera movement: ${move.label} — ${move.movement}${reason}`,+ `Speed: ${capital(SPEED_TEXT[speed])}${overrides.onBeat ? '; land the move exactly on the downbeat' : ''}.`,+ `Framing: Opens on ${FRAMING_TEXT[move.startFraming]}. ${move.framing}`,+ `End: ${move.end} Ends on ${FRAMING_TEXT[endFraming]}.`,+ ].join('\n');+}++/** The four-part camera prompt for a structured shot camera (`{ move, speed, endFraming, onBeat, reason }`), or ''. */+export const shotCameraPrompt = (camera) => (camera && typeof camera === 'object'+ ? cameraMovementPrompt(camera.move, camera) : '');++/** One line per move for an LLM prompt: id (label) [family, energy, snap]: direction. */+export const cameraMovementCatalogForPrompt = ({ detail = false } = {}) => CAMERA_MOVEMENTS+ .map((move) => (detail+ ? `- ${move.value} (${move.label}) [${move.family}, ${move.energy}${move.snap ? ', snap' : ''}${move.still ? ', static' : ''}]: ${move.movement}`+ : `- ${move.value} (${move.label}): ${move.prompt}`))+ .join('\n');++/** A short human label for a structured shot camera ("Whip pan, snap, on the downbeat"), or ''. */+export function shotCameraLabel(camera) {+ const move = getCameraMovement(camera?.move);+ if (!move) return '';+ return [move.label, CAMERA_SPEEDS.includes(camera.speed) && camera.speed !== move.speed ? camera.speed : '',+ camera.onBeat ? 'on the downbeat' : '', camera.reason?.trim() ? `because ${camera.reason.trim()}` : '']+ .filter(Boolean).join(', ');+}++const PUSH_FAMILIES = new Set(['push-pull', 'lens', 'scale']);+/**+ * The closest of the composed (ffmpeg) render's three still moves — hold, push+ * or pan — for a structured shot camera, or null when it names no catalog move.+ * The layered document plays the full move through its camera rig instead.+ */+export function stillMoveForCamera(camera) {+ const move = getCameraMovement(camera?.move);+ if (!move) return null;+ return move.still ? 'hold' : PUSH_FAMILIES.has(move.family) ? 'push' : 'pan';+}diff --git a/server/lib/cameraMovements.test.js b/server/lib/cameraMovements.test.jsnew file mode 100644index 0000000000..d69f927b79--- /dev/null+++ b/server/lib/cameraMovements.test.js@@ -0,0 +1,104 @@+import { describe, it, expect } from 'vitest';+import {+ CAMERA_ENERGIES, CAMERA_FAMILIES, CAMERA_FRAMINGS, CAMERA_MOVEMENTS, CAMERA_MOVEMENT_VALUES, CAMERA_SPEEDS, SNAP_CAMERA_MOVEMENTS,+ cameraMovementCatalogForPrompt, cameraMovementFromText, cameraMovementId, getCameraMovement,+ normalizeCameraMovement, shotCameraLabel, shotCameraPrompt, stillMoveForCamera,+} from './cameraMovements.js';+import { FABLELOOM_CAMERA_MOVEMENTS, normalizeFableLoomCameraMovement } from './fableLoomCameraMovements.js';++describe('camera movement catalog', () => {+ it('has unique ids and complete structured fields on every move', () => {+ expect(new Set(CAMERA_MOVEMENT_VALUES).size).toBe(CAMERA_MOVEMENTS.length);+ for (const move of CAMERA_MOVEMENTS) {+ expect(CAMERA_FAMILIES).toContain(move.family);+ expect(CAMERA_ENERGIES).toContain(move.energy);+ expect(CAMERA_SPEEDS).toContain(move.speed);+ expect(CAMERA_FRAMINGS).toContain(move.startFraming);+ expect(CAMERA_FRAMINGS).toContain(move.endFraming);+ for (const key of ['label', 'movement', 'framing', 'end', 'prompt']) expect(move[key].trim().length).toBeGreaterThan(0);+ expect(Object.isFrozen(move)).toBe(true);+ }+ });++ it('adds the scale and time moves', () => {+ for (const id of ['infinite-zoom', 'powers-of-ten', 'locked-time-lapse', 'tilt-shift-miniature', 'crash-zoom-out', 'chase-tracking']) {+ expect(getCameraMovement(id)).toBeTruthy();+ }+ expect(getCameraMovement('powers-of-ten').family).toBe('scale');+ expect(getCameraMovement('locked-time-lapse')).toMatchObject({ family: 'time', still: true });+ });++ it('marks the snap moves used on hit points', () => {+ expect([...SNAP_CAMERA_MOVEMENTS].sort()).toEqual(['crash-zoom', 'crash-zoom-out', 'dutch-roll', 'whip-pan']);+ });++ it('is the catalog FableLoom re-exports, so its stored ids still normalize unchanged', () => {+ expect(FABLELOOM_CAMERA_MOVEMENTS).toBe(CAMERA_MOVEMENTS);+ expect(normalizeFableLoomCameraMovement('Slow Dolly In')).toBe('slow-dolly-in');+ expect(normalizeFableLoomCameraMovement('my own custom move')).toBe('my own custom move');+ expect(normalizeCameraMovement('ORBIT-360')).toBe('orbit-360');+ });+});++describe('lookups', () => {+ it('resolves catalog ids only', () => {+ expect(cameraMovementId('Whip Pan')).toBe('whip-pan');+ expect(cameraMovementId('not a move')).toBe('');+ expect(getCameraMovement('nope')).toBeNull();+ expect(getCameraMovement(undefined)).toBeNull();+ });++ it('finds a move named inside free-text direction', () => {+ expect(cameraMovementFromText('Slow dolly in on the hands')).toBe('slow-dolly-in');+ expect(cameraMovementFromText('whip pan to the drummer')).toBe('whip-pan');+ expect(cameraMovementFromText('Static tripod frame')).toBe('locked-off');+ expect(cameraMovementFromText('something vague')).toBe('');+ expect(cameraMovementFromText('')).toBe('');+ });+});++describe('shotCameraPrompt', () => {+ it('composes the four-part Movement / Speed / Framing / End block', () => {+ const lines = shotCameraPrompt({ move: 'crash-zoom', onBeat: true }).split('\n');+ expect(lines).toHaveLength(4);+ expect(lines[0]).toMatch(/^Camera movement: /);+ expect(lines[1]).toMatch(/^Speed: .*land the move exactly on the downbeat\.$/);+ expect(lines[2]).toMatch(/^Framing: Opens on /);+ expect(lines[3]).toMatch(/^End: .*Ends on /);+ });++ it('applies speed, end framing and reason overrides and ignores invalid ones', () => {+ const base = shotCameraPrompt({ move: 'locked-off' });+ expect(shotCameraPrompt({ move: 'locked-off', reason: 'the dancer fills the frame' })).toContain('Reason: the dancer fills the frame');+ expect(shotCameraPrompt({ move: 'locked-off', speed: 'warp', endFraming: 'huge' })).toBe(base);+ expect(shotCameraPrompt({ move: 'slow-dolly-in', endFraming: 'extreme-close' })).not.toBe(shotCameraPrompt({ move: 'slow-dolly-in' }));+ });++ it('is empty for no camera or a move outside the catalog', () => {+ expect(shotCameraPrompt(null)).toBe('');+ expect(shotCameraPrompt({ move: 'teleport' })).toBe('');+ });+});++describe('labels, prompt catalog and composed still moves', () => {+ it('labels a shot camera for the storyboard', () => {+ expect(shotCameraLabel({ move: 'whip-pan', onBeat: true })).toBe('Whip pan, on the downbeat');+ expect(shotCameraLabel({ move: 'locked-off', reason: 'the dancer fills the frame' })).toBe('Locked-off / static, because the dancer fills the frame');+ expect(shotCameraLabel({ move: 'teleport' })).toBe('');+ });++ it('lists every move in the prompt catalog', () => {+ const lines = cameraMovementCatalogForPrompt({ detail: true }).split('\n');+ expect(lines).toHaveLength(CAMERA_MOVEMENTS.length);+ expect(lines.find((line) => line.startsWith('- whip-pan '))).toContain('[rotate, high, snap]');+ expect(cameraMovementCatalogForPrompt().split('\n')).toHaveLength(CAMERA_MOVEMENTS.length);+ });++ it('maps a camera to the nearest composed still move', () => {+ expect(stillMoveForCamera({ move: 'locked-off' })).toBe('hold');+ expect(stillMoveForCamera({ move: 'slow-dolly-in' })).toBe('push');+ expect(stillMoveForCamera({ move: 'truck-left' })).toBe('pan');+ expect(stillMoveForCamera({ move: 'teleport' })).toBeNull();+ expect(stillMoveForCamera(undefined)).toBeNull();+ });+});diff --git a/server/lib/fableLoomCameraMovements.js b/server/lib/fableLoomCameraMovements.jsindex ae4793e816..1395724b7f 100644--- a/server/lib/fableLoomCameraMovements.js+++ b/server/lib/fableLoomCameraMovements.js@@ -1,73 +1,17 @@/**- * Camera-direction vocabulary shared by FableLoom's AI prompts and editor.- * Values are stable persisted ids; labels and prompt text may improve without- * migrating existing scene nodes.+ * Camera-direction vocabulary for FableLoom's AI prompts and editor. The+ * catalog itself lives in the shared `cameraMovements.js` (#10589), which Music+ * Video planning also uses; these names stay so existing imports and persisted+ * scene-node ids keep working unchanged.*/+import {+ CAMERA_MOVEMENTS,+ CAMERA_MOVEMENT_VALUES,+ cameraMovementCatalogForPrompt,+ normalizeCameraMovement,+} from './cameraMovements.js';-export const FABLELOOM_CAMERA_MOVEMENTS = Object.freeze([- { value: 'locked-off', label: 'Locked-off / static', prompt: 'Locked-off tripod shot; the camera remains completely still.' },- { value: 'slow-dolly-in', label: 'Slow dolly in', prompt: 'Camera slowly moves forward toward the subject.' },- { value: 'slow-dolly-out', label: 'Slow dolly out', prompt: 'Camera slowly moves backward away from the subject.' },- { value: 'fast-dolly-in', label: 'Fast dolly in', prompt: 'Camera rapidly pushes toward the subject with urgent motion.' },- { value: 'dolly-zoom', label: 'Dolly zoom / vertigo', prompt: 'Camera dollies while zooming in the opposite direction, warping background scale.' },- { value: 'zoom-in', label: 'Optical zoom in', prompt: 'Stationary camera smoothly magnifies the subject with the lens.' },- { value: 'zoom-out', label: 'Optical zoom out', prompt: 'Stationary camera smoothly widens the field of view with the lens.' },- { value: 'crash-zoom', label: 'Crash zoom', prompt: 'A sudden snap zoom punches into the key detail.' },- { value: 'macro-zoom', label: 'Extreme macro zoom', prompt: 'The view transitions from the subject into an extreme macro detail.' },- { value: 'pan-left', label: 'Pan left', prompt: 'Camera pivots horizontally to the left from a fixed position.' },- { value: 'pan-right', label: 'Pan right', prompt: 'Camera pivots horizontally to the right from a fixed position.' },- { value: 'whip-pan', label: 'Whip pan', prompt: 'Camera whips sideways with strong directional motion blur.' },- { value: 'tilt-up', label: 'Tilt up', prompt: 'Camera pivots vertically upward from a fixed position.' },- { value: 'tilt-down', label: 'Tilt down', prompt: 'Camera pivots vertically downward from a fixed position.' },- { value: 'truck-left', label: 'Truck left', prompt: 'Camera travels laterally to the left on a parallel track.' },- { value: 'truck-right', label: 'Truck right', prompt: 'Camera travels laterally to the right on a parallel track.' },- { value: 'pedestal-up', label: 'Pedestal up', prompt: 'Camera rises vertically while keeping its angle and distance.' },- { value: 'pedestal-down', label: 'Pedestal down', prompt: 'Camera lowers vertically while keeping its angle and distance.' },- { value: 'crane-up', label: 'Crane up / high reveal', prompt: 'Camera cranes upward into a high-angle reveal.' },- { value: 'crane-down', label: 'Crane down / landing', prompt: 'Camera cranes down and settles near the subject.' },- { value: 'orbit-180', label: 'Orbit 180°', prompt: 'Camera makes a half-circle around the subject.' },- { value: 'orbit-360', label: 'Orbit 360°', prompt: 'Camera makes one complete circle around the subject.' },- { value: 'cinematic-arc', label: 'Slow cinematic arc', prompt: 'Camera follows a slow, wide curved path around the subject.' },- { value: 'reveal-from-behind', label: 'Reveal from behind', prompt: 'Camera slides from behind a foreground object to reveal the scene.' },- { value: 'fly-through', label: 'Fly-through', prompt: 'Camera passes through an opening and continues into the scene.' },- { value: 'following-shot', label: 'Following tracking shot', prompt: 'Camera follows behind the moving subject at matching speed.' },- { value: 'leading-shot', label: 'Leading tracking shot', prompt: 'Camera moves backward ahead of the subject at matching speed.' },- { value: 'side-tracking', label: 'Side tracking shot', prompt: 'Camera travels parallel beside the moving subject.' },- { value: 'steadicam-follow', label: 'Steadicam follow', prompt: 'Stabilized camera glides with the subject through the environment.' },- { value: 'handheld', label: 'Handheld documentary', prompt: 'Natural handheld drift and restrained shake create documentary immediacy.' },- { value: 'pov-walk', label: 'POV walk', prompt: 'First-person camera advances with subtle human head-bob.' },- { value: 'worm-eye-track', label: "Worm's-eye tracking", prompt: 'Ground-level camera tracks forward while looking up.' },- { value: 'drone-flyover', label: 'Drone flyover', prompt: 'High aerial camera flies forward over the environment.' },- { value: 'drone-reveal', label: 'Drone rise and reveal', prompt: 'Aerial camera rises and tilts down to unveil the larger scene.' },- { value: 'drone-orbit', label: 'Large-scale drone orbit', prompt: 'Aerial camera sweeps in a broad circle around the landscape.' },- { value: 'drone-dive', label: 'FPV drone dive', prompt: 'Fast first-person aerial camera dives down a vertical structure.' },- { value: 'top-down-twist', label: "Top-down / God's-eye twist", prompt: 'Camera looks straight down while slowly rotating.' },- { value: 'dutch-roll', label: 'Dutch roll', prompt: 'Camera rolls on its lens axis into a disorienting Dutch angle.' },- { value: 'barrel-roll', label: 'Barrel roll', prompt: 'Camera rotates a full turn on its lens axis while moving forward.' },- { value: 'rack-focus', label: 'Rack focus', prompt: 'Focus shifts decisively between foreground and background subjects; camera position stays fixed.' },- { value: 'focus-reveal', label: 'Reveal from blur', prompt: 'The shot begins fully defocused and gradually resolves to sharp focus.' },- { value: 'ots-drift', label: 'Over-the-shoulder drift', prompt: 'Camera holds an over-the-shoulder composition with a subtle lateral drift.' },- { value: 'push-past', label: 'Push past foreground', prompt: 'Camera pushes past a close foreground element to uncover the subject.' },- { value: 'slider-parallax', label: 'Slider parallax', prompt: 'A short lateral slider move creates controlled foreground-background parallax.' },- { value: 'body-mount', label: 'Body-mounted / SnorriCam', prompt: 'Camera stays rigidly mounted to the moving subject while the world swings behind them.' },- { value: 'bullet-time', label: 'Bullet-time orbit', prompt: 'Action nearly freezes while the camera moves around the moment.' },- { value: 'hyperlapse', label: 'Moving hyperlapse', prompt: 'Camera advances through accelerated time with compressed environmental motion.' },-]);--export const FABLELOOM_CAMERA_MOVEMENT_VALUES = Object.freeze(- FABLELOOM_CAMERA_MOVEMENTS.map(({ value }) => value),-);--export const normalizeFableLoomCameraMovement = (raw) => {- if (typeof raw !== 'string') return '';- const candidate = raw.trim();- const normalized = candidate.toLowerCase();- const match = FABLELOOM_CAMERA_MOVEMENTS.find(({ value, label }) => (- value.toLowerCase() === normalized || label.toLowerCase() === normalized- ));- return match?.value || candidate;-};--export const fableLoomCameraMovementCatalogForPrompt = () => FABLELOOM_CAMERA_MOVEMENTS- .map(({ value, label, prompt }) => `- ${value} (${label}): ${prompt}`)- .join('\n');+export const FABLELOOM_CAMERA_MOVEMENTS = CAMERA_MOVEMENTS;+export const FABLELOOM_CAMERA_MOVEMENT_VALUES = CAMERA_MOVEMENT_VALUES;+export const normalizeFableLoomCameraMovement = normalizeCameraMovement;+export const fableLoomCameraMovementCatalogForPrompt = () => cameraMovementCatalogForPrompt();diff --git a/server/lib/index.js b/server/lib/index.jsindex 817b413a6c..2eb260353b 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -117,6 +117,7 @@ export * from './creativeLatitude.js';export * as editorial from './editorial/index.js';export * from './familySettingsMap.js';export * from './fableLoomGraph.js';+export * from './cameraMovements.js';export * from './fableLoomCameraMovements.js';export * from './fableLoomPlayback.js';export * from './fableLoomParticipation.js';diff --git a/server/lib/musicVideoDependencies.js b/server/lib/musicVideoDependencies.jsindex 2b21c8b2db..b8ed5f78a5 100644--- a/server/lib/musicVideoDependencies.js+++ b/server/lib/musicVideoDependencies.js@@ -12,7 +12,9 @@ const assetRef = (scene, role, assetId = scene?.[slots[role]]) => ({});const layerRef = (scene) => ({ role: 'layer', sceneId: scene.sceneId, assetId: scene.sceneId,revision: checksum(Object.fromEntries(['startSec', 'endSec', 'visualLayer', 'stillMove', 'cardText', 'cardColor', 'shotMode', 'performanceSpeaker', 'loop']- .map((key) => [key, scene[key] ?? null]).concat([['actionContract', scene.direction?.actionContract || null]]))) });+ .map((key) => [key, scene[key] ?? null]).concat([['actionContract', scene.direction?.actionContract || null]])+ // #10589: only a planned camera joins the revision, so pre-camera evidence stays current.+ .concat(scene.camera ? [['camera', scene.camera]] : []))) });const snapshot = (references) => ({ version: MUSIC_VIDEO_DEPENDENCY_VERSION, references });/** Capture the actual submitted plate, including optional crop/mask provenance. */diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex d78ee0970e..67a03829cf 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -45,6 +45,7 @@ import { shotActionContractProblem } from './musicVideoActionContract.js';import { NARRATIVE_EVENT_KINDS } from './musicVideoNarrativeEvents.js';import { MUSIC_VIDEO_MEDIA } from './musicVideoMediumPlan.js';import { MUSIC_VIDEO_LYRIC_ROLES, MUSIC_VIDEO_STILL_MOVES, MUSIC_VIDEO_TEXT_ZONES, MUSIC_VIDEO_VISUAL_LAYERS } from './musicVideoLayers.js';+import { CAMERA_FRAMINGS, CAMERA_MOVEMENT_VALUES, CAMERA_SPEEDS } from './cameraMovements.js';import { MUSIC_VIDEO_SHOT_MODES, SOURCE_AUDIO_LIPSYNC } from './musicVideoShotTiming.js';import {MUSIC_VIDEO_AUTOMATION_BUDGET_MAX_USD,@@ -514,9 +515,22 @@ export const musicVideoDocumentTemplateSchema = z.object({template: z.enum(MUSIC_VIDEO_DOCUMENT_TEMPLATES).optional(),}).strict();+// #10589: a shot's structured camera move — a shared camera-movement id+// (lib/cameraMovements.js) with optional speed, end framing, downbeat landing+// and, for a still camera, the reason it holds. Feeds the i2v camera block and+// the layered template's camera rig. `null` clears it.+export const musicVideoSceneCameraSchema = z.object({+ move: z.enum(CAMERA_MOVEMENT_VALUES),+ speed: z.enum(CAMERA_SPEEDS).optional(),+ endFraming: z.enum(CAMERA_FRAMINGS).optional(),+ onBeat: z.boolean().optional(),+ reason: z.string().trim().max(300).optional(),+}).strict();+// Per-scene visual layer (#8985) — footage, a moved still, or a title card;// see musicVideoLayers.js. Only a composed render honors a non-footage layer.const sceneLayerFields = {+ camera: musicVideoSceneCameraSchema.nullable().optional(),visualLayer: z.enum(MUSIC_VIDEO_VISUAL_LAYERS).optional(),stillMove: z.enum(MUSIC_VIDEO_STILL_MOVES).optional(),cardText: z.string().max(500).nullable().optional(),diff --git a/server/lib/musicVideoValidation.test.js b/server/lib/musicVideoValidation.test.jsindex c8771ee074..3015cb7e59 100644--- a/server/lib/musicVideoValidation.test.js+++ b/server/lib/musicVideoValidation.test.js@@ -1,5 +1,5 @@import { describe, it, expect } from 'vitest';-import { musicVideoPublishPrepareSchema } from './musicVideoValidation.js';+import { musicVideoPublishPrepareSchema, musicVideoSceneCreateSchema, musicVideoSceneUpdateSchema } from './musicVideoValidation.js';describe('musicVideoPublishPrepareSchema (DistroKid release answers)', () => {const parse = (body) => musicVideoPublishPrepareSchema.safeParse(body);@@ -15,3 +15,19 @@ describe('musicVideoPublishPrepareSchema (DistroKid release answers)', () => {expect(parse({ stores: ['spotify'] }).success).toBe(false);});});++describe('scene camera (#10589)', () => {+ it('accepts a catalog camera on create and update, and clears it with null', () => {+ const camera = { move: 'whip-pan', speed: 'snap', endFraming: 'medium', onBeat: true };+ expect(musicVideoSceneCreateSchema.safeParse({ label: 'Hook', camera }).data?.camera).toEqual(camera);+ expect(musicVideoSceneUpdateSchema.safeParse({ camera }).success).toBe(true);+ expect(musicVideoSceneUpdateSchema.safeParse({ camera: null }).data).toEqual({ camera: null });+ expect(musicVideoSceneUpdateSchema.safeParse({ camera: { move: 'locked-off', reason: 'the dancer fills the frame' } }).success).toBe(true);+ });++ it('refuses an unknown move, speed or framing and extra keys', () => {+ for (const camera of [{ move: 'teleport' }, { move: 'whip-pan', speed: 'warp' }, { move: 'whip-pan', endFraming: 'huge' }, { move: 'whip-pan', lens: '35mm' }, { speed: 'snap' }]) {+ expect(musicVideoSceneUpdateSchema.safeParse({ camera }).success).toBe(false);+ }+ });+});diff --git a/server/services/musicVideo/compositionDocument.js b/server/services/musicVideo/compositionDocument.jsindex 5d50aaeb2e..71e70178de 100644--- a/server/services/musicVideo/compositionDocument.js+++ b/server/services/musicVideo/compositionDocument.js@@ -367,6 +367,9 @@ const UPGRADABLE_LAYERED_ENGINES = new Set(['e2267a068c92a3c7dee49db5f3e57caff1ac11aee1312c0d82e28352850aad3b','23842766a818fd9820d79ff229eab538cc0edf391992756cbfd14434d525c019','5f69f39cfbdbf0531c23250d01773447529a5254271b0b77f40d029d02bb0e1f',+ // #10583's engine (shared lyricType.js), before cameraRig.js (#10589); an upgraded+ // copy without the rig script keeps a slow push.+ '02ca75c17c58eec1bb37463fdd187a133d8c10499bb2b6556c793af8d63b93e8',]);const engineDigest = bytes => createHash('sha256').update(bytes.toString('utf8').replace(/\r\n?/g, '\n')).digest('hex');diff --git a/server/services/musicVideo/documentRender.js b/server/services/musicVideo/documentRender.jsindex 5869b0ddff..6d45d84679 100644--- a/server/services/musicVideo/documentRender.js+++ b/server/services/musicVideo/documentRender.js@@ -174,6 +174,8 @@ export function buildDocumentData(project, { media = new Map(), frame, clock, soshotMode: scene.shotMode === 'performance' ? 'performance' : 'cutaway',visualLayer: documentSceneVisualLayer(project, scene, { generated }),stillMove: typeof scene.stillMove === 'string' ? scene.stillMove : null,+ // #10589: the planned camera move the template's camera rig follows (only when planned).+ ...(typeof scene.camera?.move === 'string' ? { camera: structuredClone(scene.camera) } : {}),cardText: typeof scene.cardText === 'string' ? scene.cardText : null,cardColor: typeof scene.cardColor === 'string' ? scene.cardColor : null,textZone: MUSIC_VIDEO_TEXT_ZONES.includes(scene.textZone) ? scene.textZone : null,diff --git a/server/services/musicVideo/documentTemplates/layered/cameraRig.js b/server/services/musicVideo/documentTemplates/layered/cameraRig.jsnew file mode 100644index 0000000000..86adb64f97--- /dev/null+++ b/server/services/musicVideo/documentTemplates/layered/cameraRig.js@@ -0,0 +1,265 @@+/* Camera rig for PortOS music-video documents (#10589).+ *+ * One deterministic camera path per shared camera-movement id (the same ids+ * the storyboard's `camera.move` and the i2v camera prompt use — see+ * server/lib/cameraMovements.js), so code-drawn shots and generated shots+ * share one vocabulary.+ *+ * PORTOS_CAMERA_RIG.sample(id, t, options) -> {+ * position: [x, y, z], target: [x, y, z], up: [x, y, z],+ * fov (degrees, vertical), roll (radians around the view axis),+ * blur (0 sharp .. 1 fully soft), focusShift (0 near .. 1 far),+ * timeScale (how fast the world's own clock runs), framing, subjectFraction }+ *+ * `t` is normalized shot time (0 = first frame, 1 = last). Options:+ * speed 'slow' | 'moderate' | 'fast' | 'snap' (default: the move's own)+ * beat normalized time of the beat the move should hit (0..1)+ * onBeat true: the move arrives at `beat`; a snap move always centers on it+ * amount 0..1, how much of the path to travel (1 = the full move)+ *+ * The subject sits at the origin, one unit tall. Units are arbitrary; a three.js+ * world can scale them. `applyToCamera(camera, sample)` drives a+ * THREE.PerspectiveCamera; `flatView(id, t, options)` turns the same path into a+ * 2D cover transform ({ zoom, x, y, rotation }) for a flat still or video+ * frame — the layered engine draws its stills and footage through it, and the+ * GENTLE table below holds the engine's subtle moves as entries of the same rig.+ *+ * Pure math, no DOM and no three.js import: the same file loads as a plain+ * <script> (window.PORTOS_CAMERA_RIG) and under a test harness.+ */+(() => {+ 'use strict';++ const BASE_FOV = 50;+ // Camera-to-subject distance that frames a one-unit subject at BASE_FOV.+ const DIST = { 'extreme-wide': 14, wide: 5.5, medium: 2.5, close: 1.3, 'extreme-close': 0.6 };+ // Subject height as a fraction of frame height → framing (upper bounds).+ const FRAMING_BOUNDS = [['extreme-wide', 0.12], ['wide', 0.3], ['medium', 0.6], ['close', 1.2], ['extreme-close', Infinity]];++ const clamp = (v, a = 0, b = 1) => Math.max(a, Math.min(b, v));+ const lerp = (a, b, k) => a + (b - a) * k;+ const geo = (a, b, k) => a * Math.pow(b / a, k);+ const seg = (t, a, b) => (b > a ? clamp((t - a) / (b - a)) : (t >= b ? 1 : 0));+ const rad = (deg) => (deg * Math.PI) / 180;+ const easeInOut = (k) => (k < 0.5 ? 4 * k * k * k : 1 - Math.pow(-2 * k + 2, 3) / 2);+ const easeOut = (k) => 1 - Math.pow(1 - k, 3);+ const smooth = (k) => k * k * (3 - 2 * k);+ const sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];+ const add = (a, b) => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];+ const scale = (a, s) => [a[0] * s, a[1] * s, a[2] * s];+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];+ const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];+ const length = (a) => Math.hypot(a[0], a[1], a[2]);+ const normalize = (a) => { const l = length(a) || 1; return [a[0] / l, a[1] / l, a[2] / l]; };+ // Deterministic, smooth "hand" noise: a few incommensurate sines.+ const wobble = (t, seed) => Math.sin(t * 7.3 + seed) * 0.5 + Math.sin(t * 13.7 + seed * 2.1) * 0.3 + Math.sin(t * 23.1 + seed * 3.7) * 0.2;++ const ORIGIN = [0, 0, 0];+ // Camera on a sphere around `target`: yaw turns right, pitch looks down from above.+ const around = (target, dist, yawDeg, pitchDeg) => add(target, [+ dist * Math.sin(rad(yawDeg)) * Math.cos(rad(pitchDeg)), dist * Math.sin(rad(pitchDeg)), dist * Math.cos(rad(yawDeg)) * Math.cos(rad(pitchDeg)),+ ]);+ // Target in front of a fixed `position`: yaw turns right, pitch tilts up.+ const aim = (position, dist, yawDeg, pitchDeg) => add(position, [+ dist * Math.sin(rad(yawDeg)) * Math.cos(rad(pitchDeg)), dist * Math.sin(rad(pitchDeg)), -dist * Math.cos(rad(yawDeg)) * Math.cos(rad(pitchDeg)),+ ]);+ const fractionAt = (dist, fov) => 1 / (2 * dist * Math.tan(rad(fov) / 2));+ // The fov that keeps a subject at `fraction` of frame height from `dist`.+ const fovFor = (fraction, dist) => (2 * Math.atan(1 / (2 * dist * fraction)) * 180) / Math.PI;+ const pose = (position, target = ORIGIN, extra = {}) => ({ position, target, ...extra });++ const M = DIST.medium; const C = DIST.close; const W = DIST.wide; const XW = DIST['extreme-wide'];+ const MEDIUM_FRACTION = fractionAt(M, BASE_FOV);++ // id -> (k, t) => partial state. k is the eased move progress (0..1), t the+ // raw shot time for continuous texture (hand shake, head bob).+ const PATHS = {+ 'locked-off': () => pose([0, 0, M]),+ 'slow-dolly-in': (k) => pose([0, 0, lerp(M, C, k)]),+ 'slow-dolly-out': (k) => pose([0, 0, lerp(M, W, k)]),+ 'fast-dolly-in': (k) => pose([0, 0, lerp(W, C, k)]),+ 'dolly-zoom': (k) => { const d = lerp(M, 1.4, k); return pose([0, 0, d], ORIGIN, { fov: fovFor(MEDIUM_FRACTION, d) }); },+ 'zoom-in': (k) => pose([0, 0, M], ORIGIN, { fov: lerp(BASE_FOV, 26, k) }),+ 'zoom-out': (k) => pose([0, 0, M], ORIGIN, { fov: lerp(BASE_FOV, 80, k) }),+ 'crash-zoom': (k) => pose([0, 0, M], ORIGIN, { fov: lerp(BASE_FOV, 15, k) }),+ 'macro-zoom': (k) => pose([0, 0, geo(M, 0.5, k)], ORIGIN, { fov: lerp(BASE_FOV, 35, k) }),+ 'pan-left': (k) => pose([0, 0, M], aim([0, 0, M], M, lerp(0, -35, k), 0)),+ 'pan-right': (k) => pose([0, 0, M], aim([0, 0, M], M, lerp(0, 35, k), 0)),+ 'whip-pan': (k) => pose([0, 0, M], aim([0, 0, M], M, lerp(0, 90, k), 0), { blur: 0.8 * Math.sin(Math.PI * k) }),+ 'tilt-up': (k) => pose([0, 0, M], aim([0, 0, M], M, 0, lerp(0, 25, k))),+ 'tilt-down': (k) => pose([0, 0, M], aim([0, 0, M], M, 0, lerp(0, -25, k))),+ 'truck-left': (k) => pose([lerp(0, -1.5, k), 0, M], [lerp(0, -1.5, k), 0, 0]),+ 'truck-right': (k) => pose([lerp(0, 1.5, k), 0, M], [lerp(0, 1.5, k), 0, 0]),+ 'pedestal-up': (k) => pose([0, lerp(0, 1.2, k), M], [0, lerp(0, 1.2, k), 0]),+ 'pedestal-down': (k) => pose([0, lerp(0, -1.2, k), M], [0, lerp(0, -1.2, k), 0]),+ 'crane-up': (k) => pose(around(ORIGIN, lerp(M, 6, k), 0, lerp(0, 50, k))),+ 'crane-down': (k) => pose(around(ORIGIN, lerp(6, M, k), 0, lerp(50, 5, k))),+ 'orbit-180': (k) => pose(around(ORIGIN, M, lerp(0, 180, k), 5)),+ 'orbit-360': (k) => pose(around(ORIGIN, M, lerp(0, 360, k), 5)),+ 'cinematic-arc': (k) => pose(around(ORIGIN, 3, lerp(-30, 30, k), 6)),+ 'reveal-from-behind': (k) => pose([lerp(-1.4, 0, k), 0, M]),+ 'fly-through': (k) => pose([0, 0, lerp(7, 2.2, k)]),+ 'following-shot': (k, t) => { const s = lerp(0, -4, k); return pose([0, 0.3 + 0.03 * Math.sin(t * 18), s + M], [0, 0, s]); },+ 'leading-shot': (k, t) => { const s = lerp(0, 4, k); return pose([0, 0.2 + 0.03 * Math.sin(t * 18), s + M], [0, 0, s]); },+ 'side-tracking': (k) => { const s = lerp(0, 4, k); return pose([s, 0, M], [s, 0, 0]); },+ 'steadicam-follow': (k) => { const s = lerp(0, -3, k); return pose([0.15 * Math.sin(2 * Math.PI * k), 0.25, s + M], [0, 0, s]); },+ handheld: (_k, t) => pose([0.04 * wobble(t, 1), 0.03 * wobble(t, 2), M], [0.03 * wobble(t, 3), 0.02 * wobble(t, 4), 0], { roll: 0.015 * wobble(t, 5) }),+ 'pov-walk': (k, t) => { const s = lerp(0, -3, k); return pose([0.02 * Math.sin(t * 9), 0.04 * Math.abs(Math.sin(t * 18)), s + M], [0, 0, s]); },+ 'worm-eye-track': (k) => { const s = lerp(0, -3, k); return pose([0, -0.9, s + 2.3], [0, 0.2, s]); },+ 'drone-flyover': (k) => { const s = lerp(0, -10, k); return pose([0, 8, s + 11], [0, 0, s]); },+ 'drone-reveal': (k) => pose([0, lerp(1, 9, k), lerp(5.4, 11, k)]),+ 'drone-orbit': (k) => pose(around(ORIGIN, XW, lerp(0, 120, k), 35)),+ 'drone-dive': (k) => pose([0, lerp(13.5, 1.5, k), lerp(3.5, 2, k)]),+ 'top-down-twist': (k) => pose([0, 3, 0.001], ORIGIN, { roll: lerp(0, Math.PI / 2, k) }),+ 'dutch-roll': (k) => pose([0, 0, M], ORIGIN, { roll: lerp(0, rad(25), k) }),+ 'barrel-roll': (k) => pose([0, 0, lerp(3, 2, k)], ORIGIN, { roll: lerp(0, 2 * Math.PI, k) }),+ 'rack-focus': (k) => pose([0, 0, M], ORIGIN, { focusShift: k }),+ 'focus-reveal': (k) => pose([0, 0, M], ORIGIN, { blur: 1 - k }),+ 'ots-drift': (k) => pose([0.55 + lerp(0, 0.25, k), 0.15, M]),+ 'push-past': (k) => pose([0, 0, lerp(4, 2, k)]),+ 'slider-parallax': (k) => pose([lerp(-0.35, 0.35, k), 0, M]),+ 'body-mount': (k, t) => { const s = lerp(0, 3, k); return pose([s, 0.05 * Math.sin(t * 11), C], [s, 0.05 * Math.sin(t * 11), 0], { roll: 0.06 * Math.sin(t * 6) }); },+ 'bullet-time': (k) => pose(around(ORIGIN, M, lerp(-60, 60, k), 5), ORIGIN, { timeScale: 0.05 }),+ hyperlapse: (k) => { const s = lerp(0, -12, k); return pose([0, 0.2, s + M], [0, 0, s], { timeScale: 12 }); },+ 'infinite-zoom': (k) => { const d = geo(M, 0.8, k); return pose([0, 0, d], ORIGIN, { fov: fovFor(geo(MEDIUM_FRACTION, 9, k), d) }); },+ 'powers-of-ten': (k) => { const d = geo(C, 60, k); return pose([0, d, 0.02 * d]); },+ 'locked-time-lapse': () => pose([0, 0, M], ORIGIN, { timeScale: 60 }),+ 'tilt-shift-miniature': (k) => { const s = lerp(0, 0.8, k); return pose(around([s, 0, 0], 7, 0, 45), [s, 0, 0], { fov: 35, blur: 0.6, timeScale: 4 }); },+ 'crash-zoom-out': (k) => pose([0, 0, M], ORIGIN, { fov: lerp(15, 80, k) }),+ 'chase-tracking': (k, t) => { const s = lerp(0, -20, k); return pose([0.9 + 0.12 * Math.sin(t * 5), 0.35, s + 2.3], [0, 0, s], { roll: 0.03 * Math.sin(t * 7) }); },+ };++ // The catalog's default speed per move (server/lib/cameraMovements.js);+ // decides the ease when the caller passes none.+ const SNAP = new Set(['whip-pan', 'crash-zoom', 'dutch-roll', 'crash-zoom-out']);+ const FAST = new Set(['fast-dolly-in', 'orbit-360', 'fly-through', 'drone-dive', 'barrel-roll', 'chase-tracking']);+ const defaultSpeed = (id) => (SNAP.has(id) ? 'snap' : FAST.has(id) ? 'fast' : 'moderate');+ const SNAP_HALF_WINDOW = 0.06;++ /** Eased progress of a move at normalized shot time t. */+ function progress(id, t, options = {}) {+ const time = clamp(Number.isFinite(t) ? t : 0);+ const speed = options.speed || defaultSpeed(id);+ const beat = Number.isFinite(options.beat) ? clamp(options.beat) : null;+ const amount = Number.isFinite(options.amount) ? clamp(options.amount) : 1;+ let k;+ if (speed === 'snap') {+ const center = clamp(beat ?? 0.12, SNAP_HALF_WINDOW, 1 - SNAP_HALF_WINDOW);+ k = smooth(seg(time, center - SNAP_HALF_WINDOW, center + SNAP_HALF_WINDOW));+ } else if (beat != null && options.onBeat) {+ k = easeInOut(seg(time, 0, Math.max(beat, 0.05)));+ } else if (speed === 'fast') {+ k = easeOut(seg(time, 0, 0.7));+ } else {+ k = easeInOut(time);+ }+ return k * amount;+ }++ const framingOf = (fraction) => FRAMING_BOUNDS.find(([, bound]) => fraction < bound)[0];+ const upFor = (position, target) => (Math.abs(normalize(sub(target, position))[1]) > 0.98 ? [0, 0, -1] : [0, 1, 0]);++ function stateAt(id, k, t) {+ const path = PATHS[id];+ if (!path) return null;+ const partial = path(k, t);+ const state = {+ position: partial.position, target: partial.target,+ fov: partial.fov ?? BASE_FOV, roll: partial.roll ?? 0, blur: partial.blur ?? 0,+ focusShift: partial.focusShift ?? 0, timeScale: partial.timeScale ?? 1,+ };+ state.up = upFor(state.position, state.target);+ state.subjectFraction = fractionAt(length(sub(state.target, state.position)), state.fov);+ state.framing = framingOf(state.subjectFraction);+ return state;+ }++ /** The camera state of move `id` at normalized shot time `t`, or null for an unknown id. */+ function sample(id, t, options = {}) {+ if (!PATHS[id]) return null;+ return stateAt(id, progress(id, t, options), clamp(Number.isFinite(t) ? t : 0));+ }++ /** Drive a THREE.PerspectiveCamera (duck-typed) from a sample. */+ function applyToCamera(camera, state) {+ if (!camera || !state) return camera;+ camera.up.set(state.up[0], state.up[1], state.up[2]);+ camera.position.set(state.position[0], state.position[1], state.position[2]);+ camera.lookAt(state.target[0], state.target[1], state.target[2]);+ if (state.roll) camera.rotateZ(state.roll);+ if (camera.fov !== state.fov) { camera.fov = state.fov; camera.updateProjectionMatrix?.(); }+ return camera;+ }++ /**+ * The move as a 2D cover transform for a flat frame: `zoom` (relative to the+ * first frame), `x`/`y` offsets of the image center (frame widths/heights,+ * screen y down), and `rotation` (radians). The flat frame is the plane+ * through the first frame's target, facing the first frame's camera.+ */+ const FLAT_MAX_OFFSET = 0.15;+ const FLAT_ZOOM = [0.4, 6];+ function flatView(id, t, options = {}) {+ const rest = stateAt(id, 0, 0);+ const sampled = sample(id, t, options);+ if (!rest || !sampled) return null;+ const aspect = Number.isFinite(options.aspect) && options.aspect > 0 ? options.aspect : 16 / 9;+ const n0 = normalize(sub(rest.target, rest.position));+ const right0 = normalize(cross(n0, rest.up));+ const up0 = cross(right0, n0);+ // A camera travelling down the lens axis WITH its subject (follow, lead,+ // hyperlapse) keeps the subject's size and place: drop that shared travel+ // before projecting onto the flat frame.+ const travel = sub(sampled.target, rest.target);+ const lag = length(sub(sub(sampled.position, rest.position), travel));+ const together = length(travel) > 1e-6 && lag < 0.25 * length(travel) && Math.abs(dot(normalize(travel), n0)) > 0.85;+ const now = together ? { ...sampled, position: sub(sampled.position, travel), target: rest.target } : sampled;+ const dir = normalize(sub(now.target, now.position));+ const facing = dot(dir, n0);+ let hit = now.target;+ let dist = length(sub(now.target, now.position));+ if (facing > 0.2) {+ const along = dot(sub(rest.target, now.position), n0) / facing;+ if (along > 1e-3) { hit = add(now.position, scale(dir, along)); dist = along; }+ }+ const h = dist * Math.tan(rad(now.fov) / 2);+ const h0 = length(sub(rest.target, rest.position)) * Math.tan(rad(rest.fov) / 2);+ const offset = sub(hit, rest.target);+ let x = -dot(offset, right0) / (2 * h * aspect);+ const y = dot(offset, up0) / (2 * h);+ // A camera circling a fixed target reads as a sideways drift on a flat frame.+ if (length(sub(now.target, rest.target)) < 0.05) {+ const azimuth = (p) => Math.atan2(dot(sub(p, rest.target), right0), -dot(sub(p, rest.target), n0));+ x -= (Math.sin(azimuth(now.position) - azimuth(rest.position)) * 0.12) / aspect;+ }+ return {+ zoom: clamp(h0 / h, FLAT_ZOOM[0], FLAT_ZOOM[1]),+ x: clamp(x, -FLAT_MAX_OFFSET, FLAT_MAX_OFFSET), y: clamp(y, -FLAT_MAX_OFFSET, FLAT_MAX_OFFSET),+ rotation: now.roll, blur: now.blur, timeScale: now.timeScale,+ };+ }++ // The layered engine's subtle moves, as entries of this rig: `amount` of the+ // named path, drawn over a `base` cover scale.+ const GENTLE = Object.freeze({+ footage: Object.freeze({ move: 'slow-dolly-in', amount: 0.08, base: 1.02 }),+ hold: Object.freeze({ move: 'locked-off', amount: 1, base: 1.035 }),+ push: Object.freeze({ move: 'slow-dolly-in', amount: 0.15, base: 1.04 }),+ pull: Object.freeze({ move: 'slow-dolly-out', amount: 0.03, base: 1.13 }),+ 'drift-left': Object.freeze({ move: 'truck-left', amount: 0.12, base: 1.09 }),+ 'drift-right': Object.freeze({ move: 'truck-right', amount: 0.12, base: 1.09 }),+ rise: Object.freeze({ move: 'pedestal-up', amount: 0.1, base: 1.08 }),+ });+ // Unassigned stills cycle through these; a 'pan' still alternates the drifts.+ const GENTLE_CYCLE = Object.freeze(['push', 'pull', 'drift-left', 'drift-right', 'rise']);+ // How much of a director-chosen move a flat still travels (a photo has edges).+ const STILL_AMOUNT = 0.35;++ globalThis.PORTOS_CAMERA_RIG = Object.freeze({+ version: 1,+ ids: Object.freeze(Object.keys(PATHS)),+ has: (id) => Object.prototype.hasOwnProperty.call(PATHS, id),+ sample, progress, flatView, applyToCamera, framingOf, defaultSpeed,+ GENTLE, GENTLE_CYCLE, STILL_AMOUNT,+ });+})();diff --git a/server/services/musicVideo/documentTemplates/layered/cameraRig.test.js b/server/services/musicVideo/documentTemplates/layered/cameraRig.test.jsnew file mode 100644index 0000000000..2bc32697c4--- /dev/null+++ b/server/services/musicVideo/documentTemplates/layered/cameraRig.test.js@@ -0,0 +1,132 @@+import { readFileSync } from 'node:fs';+import vm from 'node:vm';+import { describe, expect, it } from 'vitest';+import { CAMERA_MOVEMENTS, CAMERA_MOVEMENT_VALUES } from '../../../../lib/cameraMovements.js';++// cameraRig.js is a classic browser script; load it the way a document does.+const rigSource = readFileSync(new URL('./cameraRig.js', import.meta.url), 'utf8');+const loadRig = () => {+ const context = {};+ context.globalThis = context;+ vm.createContext(context);+ vm.runInContext(rigSource, context);+ return context.PORTOS_CAMERA_RIG;+};+const rig = loadRig();+const finite = (s) => [...s.position, ...s.target, ...s.up, s.fov, s.roll, s.blur, s.focusShift, s.timeScale, s.subjectFraction].every(Number.isFinite);++describe('camera rig paths', () => {+ it('has exactly one path per shared catalog id', () => {+ expect([...rig.ids].sort()).toEqual([...CAMERA_MOVEMENT_VALUES].sort());+ expect(rig.has('whip-pan')).toBe(true);+ expect(rig.has('teleport')).toBe(false);+ });++ it.each(CAMERA_MOVEMENTS.map((move) => [move.value, move]))('%s is finite at t = 0, 0.5, 1 and frames like the catalog', (id, move) => {+ for (const t of [0, 0.5, 1]) expect(finite(rig.sample(id, t))).toBe(true);+ expect(rig.sample(id, 0).framing).toBe(move.startFraming);+ expect(rig.sample(id, 1).framing).toBe(move.endFraming);+ for (const t of [0, 0.5, 1]) {+ const view = rig.flatView(id, t);+ expect([view.zoom, view.x, view.y, view.rotation, view.blur, view.timeScale].every(Number.isFinite)).toBe(true);+ }+ });++ it('agrees with the catalog on which moves are snap and fast', () => {+ for (const move of CAMERA_MOVEMENTS) {+ expect(rig.defaultSpeed(move.value) === 'snap').toBe(move.speed === 'snap');+ expect(rig.defaultSpeed(move.value) === 'fast').toBe(move.speed === 'fast');+ }+ });++ it('is deterministic', () => {+ expect(JSON.stringify(loadRig().sample('handheld', 0.37))).toBe(JSON.stringify(rig.sample('handheld', 0.37)));+ });++ it('lands a snap move on the beat and an on-beat move by the beat', () => {+ expect(rig.progress('whip-pan', 0.3, { beat: 0.5 })).toBe(0);+ expect(rig.progress('whip-pan', 0.7, { beat: 0.5 })).toBe(1);+ expect(rig.progress('whip-pan', 0.5, { beat: 0.5 })).toBeCloseTo(0.5, 5);+ expect(rig.progress('slow-dolly-in', 0.4, { beat: 0.4, onBeat: true })).toBe(1);+ expect(rig.progress('slow-dolly-in', 0.5, { amount: 0.5 })).toBeCloseTo(0.25, 5);+ });++ it('drives a three.js-shaped camera', () => {+ const vec = () => ({ set(x, y, z) { Object.assign(this, { x, y, z }); } });+ const camera = { position: vec(), up: vec(), fov: 0, rotation: { z: 0 }, lookAt(x, y, z) { this.looked = [x, y, z]; }, rotateZ(r) { this.rolled = r; }, updateProjectionMatrix() { this.updated = true; } };+ const state = rig.sample('dutch-roll', 1);+ rig.applyToCamera(camera, state);+ expect([camera.position.x, camera.position.y, camera.position.z]).toEqual(state.position);+ expect(camera.fov).toBe(state.fov);+ expect(camera.looked).toEqual(state.target);+ expect(camera.rolled).toBe(state.roll);+ expect(camera.updated).toBe(true);+ });++ it('keeps the gentle engine moves as rig entries', () => {+ for (const key of ['footage', 'hold', 'push', 'pull', 'drift-left', 'drift-right', 'rise', ...rig.GENTLE_CYCLE]) {+ expect(rig.has(rig.GENTLE[key].move)).toBe(true);+ }+ });+});++// The engine's cover transform, evaluated on its own like engine.overlay.test.js.+const engine = readFileSync(new URL('./engine.js', import.meta.url), 'utf8');+const cameraBlock = engine.slice(engine.indexOf(' const RIG = globalThis.PORTOS_CAMERA_RIG'), engine.indexOf(' // ---------- media'));+const W = 1920; const H = 1080;+const clamp = (v, a = 0, b = 1) => Math.max(a, Math.min(b, v));+const lerp = (a, b, k) => a + (b - a) * k;+const seg = (t, a, b) => (b > a ? clamp((t - a) / (b - a)) : (t >= b ? 1 : 0));+const easeInOut = (k) => (k < 0.5 ? 4 * k * k * k : 1 - Math.pow(-2 * k + 2, 3) / 2);+const engineCamera = (portosRig) => new Function('W', 'H', 'downs', 'beats', 'globalThis', 'lerp', 'easeInOut', 'seg',+ `${cameraBlock}\nreturn { cameraView, cameraSample, moveFor };`)(W, H, [2, 6], [1, 2, 3, 4, 5, 6], { PORTOS_CAMERA_RIG: portosRig }, lerp, easeInOut, seg);++// Every canvas corner must land inside the rotated, scaled, offset frame (a same-aspect source is the tightest case).+function coversCanvas(view) {+ const dw = W * view.scale; const dh = H * view.scale;+ const cx = W / 2 + view.x * W; const cy = H / 2 + view.y * H;+ const cos = Math.cos(-view.rotation); const sin = Math.sin(-view.rotation);+ return [[0, 0], [W, 0], [0, H], [W, H]].every(([px, py]) => {+ const dx = px - cx; const dy = py - cy;+ return Math.abs(dx * cos - dy * sin) <= dw / 2 + 1e-6 && Math.abs(dx * sin + dy * cos) <= dh / 2 + 1e-6;+ });+}++describe('layered engine camera', () => {+ const { cameraView, cameraSample, moveFor } = engineCamera(rig);+ const still = (extra = {}) => ({ index: 0, startSec: 0, endSec: 8, media: { kind: 'image' }, ...extra });++ it.each(CAMERA_MOVEMENT_VALUES)('a still planned as %s never shows a frame edge', (move) => {+ for (let k = 0; k <= 1.0001; k += 0.05) expect(coversCanvas(cameraView(still({ camera: { move } }), k))).toBe(true);+ });++ it('keeps the gentle defaults edge-free too', () => {+ for (const stillMove of ['hold', 'push', 'pan', undefined]) {+ for (let index = 0; index < 5; index++) {+ for (let k = 0; k <= 1.0001; k += 0.1) expect(coversCanvas(cameraView(still({ stillMove, index }), k))).toBe(true);+ }+ }+ for (let k = 0; k <= 1.0001; k += 0.1) expect(coversCanvas(cameraView(still({ media: { kind: 'video' }, camera: { move: 'whip-pan' } }), k))).toBe(true);+ });++ it('plays a still\'s planned move over its still Move, and lets footage keep its own camera', () => {+ expect(moveFor(still({ camera: { move: 'orbit-180', speed: 'fast' }, stillMove: 'hold' }))).toMatchObject({ move: 'orbit-180', speed: 'fast' });+ expect(moveFor(still({ stillMove: 'hold' }))).toBe(rig.GENTLE.hold);+ expect(moveFor(still({ media: { kind: 'video' }, camera: { move: 'whip-pan' } }))).toBe(rig.GENTLE.footage);+ expect(moveFor(still({ camera: { move: 'teleport' }, stillMove: 'push' }))).toBe(rig.GENTLE.push);+ });++ it('hands authored code the rig sample for a planned move', () => {+ const sample = cameraSample(still({ camera: { move: 'crash-zoom', onBeat: true } }), 4);+ expect(sample.move).toBe('crash-zoom');+ expect(finite(sample)).toBe(true);+ expect(cameraSample(still(), 4)).toBeNull();+ });++ it('falls back to a slow push when the document has no rig script', () => {+ const fallback = engineCamera(undefined);+ expect(fallback.cameraView(still({ camera: { move: 'whip-pan' } }), 0)).toEqual({ scale: 1.04, x: 0, y: 0, rotation: 0 });+ expect(fallback.cameraView(still(), 1).scale).toBeCloseTo(1.1, 6);+ expect(fallback.cameraSample(still({ camera: { move: 'whip-pan' } }), 1)).toBeNull();+ });+});diff --git a/server/services/musicVideo/documentTemplates/layered/engine.js b/server/services/musicVideo/documentTemplates/layered/engine.jsindex b2f7ed73f2..37a3f92685 100644--- a/server/services/musicVideo/documentTemplates/layered/engine.js+++ b/server/services/musicVideo/documentTemplates/layered/engine.js@@ -1,10 +1,11 @@/* Layered music-video composition — the PortOS starting template.** Every frame is a pure function of song time t: portosComposition.seek(t)- * draws the scene under t (its selected take, with a gentle camera move and a- * beat punch-in), film grain and a vignette, an optional HUD, and the words- * (kinetic lyric type from the shared lyricType.js: sung lines, and hook- * slams for text cues flagged "hero").+ * draws the scene under t (its selected take, moved by cameraRig.js — the+ * scene's planned camera move or a gentle default — with a beat punch-in),+ * film grain and a vignette, an optional HUD, and the words (kinetic lyric+ * type from the shared lyricType.js: sung lines, and hook slams for text cues+ * flagged "hero").** Data: window.PORTOS_MV, written by PortOS as portos-mv.js at render time —* { project, render, song, lyrics, lyricMarkers, scenes, textCues, composition }.@@ -87,20 +88,49 @@const scene = r >= 0 ? SCENES[r] : null;return scene && t < scene.endSec ? scene : null;}- // Gentle camera moves (scale, offsets in frame fractions), picked per scene.- const MOVES = [- { s0: 1.04, s1: 1.12, x0: 0, x1: 0, y0: 0, y1: 0 },- { s0: 1.13, s1: 1.05, x0: 0, x1: 0, y0: 0, y1: 0 },- { s0: 1.09, s1: 1.09, x0: 0.022, x1: -0.022, y0: 0, y1: 0 },- { s0: 1.09, s1: 1.09, x0: -0.022, x1: 0.022, y0: 0, y1: 0 },- { s0: 1.05, s1: 1.11, x0: 0, x1: 0, y0: 0.018, y1: -0.01 },- ];+ // Camera moves come from cameraRig.js (globalThis.PORTOS_CAMERA_RIG, #10589):+ // one deterministic path per shared camera-movement id, plus the gentle+ // defaults in RIG.GENTLE. A scene's planned `camera.move` drives its still;+ // generated footage already carries its own camera move, so it only breathes.+ // A document whose index.html predates the rig falls back to a slow push.+ const RIG = globalThis.PORTOS_CAMERA_RIG || null;function moveFor(scene) {- if (scene.media?.kind === 'video') return { s0: 1.02, s1: 1.06, x0: 0, x1: 0, y0: 0, y1: 0 };- if (scene.stillMove === 'hold') return { s0: 1.03, s1: 1.04, x0: 0, x1: 0, y0: 0, y1: 0 };- if (scene.stillMove === 'push') return MOVES[0];- if (scene.stillMove === 'pan') return MOVES[2 + (scene.index % 2)];- return MOVES[scene.index % MOVES.length];+ if (scene.media?.kind === 'video') return RIG.GENTLE.footage;+ const camera = scene.camera;+ if (camera?.move && RIG.has(camera.move)) {+ return { move: camera.move, amount: RIG.STILL_AMOUNT, base: 1.04, speed: camera.speed, onBeat: camera.onBeat === true };+ }+ if (scene.stillMove === 'hold') return RIG.GENTLE.hold;+ if (scene.stillMove === 'push') return RIG.GENTLE.push;+ if (scene.stillMove === 'pan') return RIG.GENTLE[scene.index % 2 ? 'drift-right' : 'drift-left'];+ return RIG.GENTLE[RIG.GENTLE_CYCLE[scene.index % RIG.GENTLE_CYCLE.length]];+ }+ // The scene's first downbeat (else beat) as normalized shot time, for snap/on-beat moves.+ function beatIn(scene) {+ const span = scene.endSec - scene.startSec;+ const hit = downs.find((b) => b >= scene.startSec && b < scene.endSec) ?? beats.find((b) => b >= scene.startSec && b < scene.endSec);+ return hit == null || !(span > 0) ? null : (hit - scene.startSec) / span;+ }+ // The cover transform for scene time k (0..1): scale over the cover fit,+ // offsets in frame fractions, rotation in radians. Never shows a frame edge.+ function cameraView(scene, k) {+ if (!RIG) return { scale: lerp(1.04, 1.1, easeInOut(k)), x: 0, y: 0, rotation: 0 };+ const move = moveFor(scene);+ const options = { amount: move.amount, speed: move.speed, onBeat: move.onBeat, beat: beatIn(scene), aspect: W / H };+ const view = RIG.flatView(move.move, k, options);+ const lowest = Math.min(1, RIG.flatView(move.move, 0, options).zoom, RIG.flatView(move.move, 1, options).zoom);+ // The smallest scale whose rotated, offset frame still holds every canvas corner.+ const c = Math.abs(Math.cos(view.rotation)); const s = Math.abs(Math.sin(view.rotation));+ const sx = 1 + 2 * Math.abs(view.x); const sy = 1 + 2 * Math.abs(view.y);+ const cover = Math.max(sx * c + sy * s * (H / W), sy * c + sx * s * (W / H));+ return { scale: Math.max((move.base * view.zoom) / lowest, cover), x: view.x, y: view.y, rotation: view.rotation };+ }+ // The rig's camera state for a code-drawn shot with a planned move (authored code may follow it).+ function cameraSample(scene, t) {+ const id = scene?.camera?.move;+ if (!RIG || !id || !RIG.has(id)) return null;+ const k = seg(t, scene.startSec, scene.endSec);+ return { move: id, ...RIG.sample(id, k, { speed: scene.camera.speed, onBeat: scene.camera.onBeat === true, beat: beatIn(scene) }) };}// ---------- media (lazy, a few decoders at a time) ----------@@ -198,16 +228,17 @@}// ---------- drawing helpers ----------- function drawCover(src, k, move, extraScale = 1) {+ function drawCover(src, view, extraScale = 1) {const sw = src.videoWidth || src.naturalWidth || src.width;const sh = src.videoHeight || src.naturalHeight || src.height;if (!sw || !sh) return;- const s = lerp(move.s0, move.s1, easeInOut(k)) * extraScale;- const base = Math.max(W / sw, H / sh) * s;+ const base = Math.max(W / sw, H / sh) * view.scale * extraScale;const dw = sw * base; const dh = sh * base;- const ox = lerp(move.x0, move.x1, easeInOut(k)) * W;- const oy = lerp(move.y0, move.y1, easeInOut(k)) * H;- ctx.drawImage(src, (W - dw) / 2 + ox, (H - dh) / 2 + oy, dw, dh);+ if (!view.rotation) { ctx.drawImage(src, (W - dw) / 2 + view.x * W, (H - dh) / 2 + view.y * H, dw, dh); return; }+ ctx.save();+ ctx.translate(W / 2 + view.x * W, H / 2 + view.y * H); ctx.rotate(view.rotation);+ ctx.drawImage(src, -dw / 2, -dh / 2, dw, dh);+ ctx.restore();}const grainTiles = [];function buildGrain() {@@ -479,7 +510,7 @@else if (source) {const energetic = isHighEnergy(t) || scene.shotMode === 'performance';const punch = 1 + 0.018 * pulse(t, energetic ? beats : downs, 8) * state.reactiveGain;- drawCover(source, seg(t, scene.startSec, scene.endSec), moveFor(scene), punch);+ drawCover(source, cameraView(scene, seg(t, scene.startSec, scene.endSec)), punch);}if (isHighEnergy(t)) glitch(t, pulse(t, downs, 8) * state.reactiveGain);}@@ -494,7 +525,7 @@t, localT: t - authored.section.startSec, frame: frameOf(t), width: W, height: H,song: GENERATED.song, palette: GENERATED.palette, section: authored.section,safe: { x: W * inset, y: H * inset, w: W * (1 - 2 * inset), h: H * (1 - 2 * inset) },- karaoke: [], mediaKind: scene?.media?.kind || null, visualLayer: scene?.visualLayer || null,+ karaoke: [], mediaKind: scene?.media?.kind || null, visualLayer: scene?.visualLayer || null, camera: cameraSample(scene, t),events: state.activeEvents, reactiveGain: state.reactiveGain, hold: state.hold,});} finally { ctx.restore(); }diff --git a/server/services/musicVideo/documentTemplates/layered/index.html b/server/services/musicVideo/documentTemplates/layered/index.htmlindex 4801805187..289ce11bd8 100644--- a/server/services/musicVideo/documentTemplates/layered/index.html+++ b/server/services/musicVideo/documentTemplates/layered/index.html@@ -21,6 +21,7 @@ html, body { margin: 0; height: 100%; background: #000; overflow: hidden; }<canvas id="stage"></canvas><!-- PortOS writes portos-mv.js (window.PORTOS_MV) and media/ next to this page at render time. --><script src="portos-mv.js"></script><!-- portos-allow-hidden-content: the render-time data file -->+<script src="cameraRig.js"></script><!-- portos-allow-hidden-content: the reviewed camera-move paths the engine reads --><script type="module" src="lyricType.js"></script><!-- portos-allow-hidden-content: the shared PortOS lyric-type module --><script src="engine.js"></script><!-- portos-allow-hidden-content: the reviewed template engine beside this page --></body>diff --git a/server/services/musicVideo/handoff.js b/server/services/musicVideo/handoff.jsindex 972c94ad29..490b42c2e0 100644--- a/server/services/musicVideo/handoff.js+++ b/server/services/musicVideo/handoff.js@@ -1,4 +1,5 @@import { shotActionPrompt } from '../../lib/musicVideoActionContract.js';+import { shotCameraPrompt } from '../../lib/cameraMovements.js';import { musicVideoCreativeContext } from '../../lib/musicVideoCreativeContext.js';import { MOTION_CONTINUITY_CLAUSE } from '../../lib/musicVideoMotion.js';/**@@ -101,8 +102,12 @@ function composePrompt(primary, fallback, project, clause, { motion = false } =/** A scene's composed reference-frame prompt (also the server-owned production run's, #9066). */export const sceneFramePrompt = (project, scene) => [composePrompt(scene.framePrompt, scene.prompt, project, scene.direction?.frameClause), shotActionPrompt(project, scene, { frame: true })].filter(Boolean).join('\n');-/** A scene's composed shot (motion) prompt. */-export const sceneShotPrompt = (project, scene, options = {}) => [composePrompt(scene.prompt, scene.framePrompt, project, scene.direction?.motionClause, { motion: true }), shotActionPrompt(project, scene, options)].filter(Boolean).join('\n');+/**+ * A scene's composed shot (motion) prompt. A planned shot (#10589) carries its+ * camera as the four-part Movement / Speed / Framing / End block, kept apart+ * from the scene description so the i2v model reads it as its own instruction.+ */+export const sceneShotPrompt = (project, scene, options = {}) => [composePrompt(scene.prompt, scene.framePrompt, project, scene.direction?.motionClause, { motion: true }), shotCameraPrompt(scene.camera), shotActionPrompt(project, scene, options)].filter(Boolean).join('\n');/** Build the export manifest for a project. */export function buildHandoffManifest(project, { now = new Date().toISOString() } = {}) {diff --git a/server/services/musicVideo/handoff.test.js b/server/services/musicVideo/handoff.test.jsindex 0d5721eb59..3f3d972a75 100644--- a/server/services/musicVideo/handoff.test.js+++ b/server/services/musicVideo/handoff.test.js@@ -132,3 +132,19 @@ describe('buildHandoffManifest typography (#8992)', () => {expect(manifest.scenes[0].framePrompt).not.toContain('hold the reference frame');expect(manifest.scenes[0].shotPrompt).toContain('Universe style: Ink silhouettes');});++describe('sceneShotPrompt camera block (#10589)', () => {+ it('appends the four-part camera block for a planned shot, and nothing otherwise', async () => {+ const { sceneShotPrompt } = await import('./handoff.js');+ const { shotCameraPrompt } = await import('../../lib/cameraMovements.js');+ const project = { concept: { prompt: 'Example concept', style: 'ink' } };+ const scene = { sceneId: 's1', prompt: 'a courier leaps between rooftops' };+ const plain = sceneShotPrompt(project, scene);+ const planned = sceneShotPrompt(project, { ...scene, camera: { move: 'crash-zoom', onBeat: true } });+ const block = shotCameraPrompt({ move: 'crash-zoom', onBeat: true });+ expect(plain).not.toContain('Camera movement:');+ expect(planned).toContain(`\n${block}`);+ expect(planned.startsWith(plain.split('\n')[0])).toBe(true);+ expect(sceneShotPrompt(project, { ...scene, camera: { move: 'teleport' } })).toBe(plain);+ });+});diff --git a/server/services/musicVideo/planner.js b/server/services/musicVideo/planner.jsindex a10c07b595..2996aa160c 100644--- a/server/services/musicVideo/planner.js+++ b/server/services/musicVideo/planner.js@@ -45,6 +45,8 @@ import { effortArg, recordLlmRoute, resolveMusicVideoLlm } from './llmRoute.js';import { directShots, planShots, resolveClipCapacitySec, validSections } from './shotPlan.js';import { getProject, addProjectScenes, mutateProjectRecord } from './projects.js';import { productionFeedbackContext } from './productionReview.js';+import { parseShotCamera, planShotCameras, shotCameraPromptSection } from './shotCamera.js';+import { getCameraMovement } from '../../lib/cameraMovements.js';const SCENE_LABEL_MAX = 120;const SCENE_TEXT_MAX = 2000;@@ -168,6 +170,8 @@ export function buildScenePlanPrompt(project, shots) {if (s.shotMode === 'performance') parts.push(PERFORMANCE_FRAME);if (s.current?.framePrompt) parts.push(`current frame: ${quote(s.current.framePrompt, PROMPT_GUIDANCE_MAX)}`);if (s.current?.prompt) parts.push(`current motion: ${quote(s.current.prompt, PROMPT_GUIDANCE_MAX)}`);+ const currentMove = getCameraMovement(s.current?.camera?.move);+ if (currentMove) parts.push(`current camera: ${currentMove.value}${s.current.camera.speed ? ` (${s.current.camera.speed})` : ''}`);return parts.join('; ');}).join('\n');const revising = shots.some((s) => s.current);@@ -187,15 +191,18 @@ ${shotLines}For EACH shot above, propose a timed composition for its assigned medium (code-authored worlds, selected stills or footage):- "framePrompt": the opening reference still — subject, setting, lighting, composition. Keep it concrete and visual.-- "prompt": the motion for that shot — camera move, subject motion, mood — building on the frame. Higher-energy sections read more kinetic; calmer sections more static/lingering.+- "prompt": the motion for that shot — subject action, staging and mood — building on the frame. Higher-energy sections read more kinetic; calmer sections more lingering.+- "camera": the shot's camera move from the vocabulary below, with its speed, end framing, whether it lands on the downbeat, and (for a static camera) the reason.- Shots in the same section are one edited sequence: keep subject and setting continuous, but vary framing (wide / medium / close), angle, or action from shot to shot so consecutive shots cut rather than repeat.- The OPENING HOOK shot must grab attention immediately.- In each motion prompt, name absolute start/end times and the supplied musical anchors for subject action, prop transformation, camera framing/movement and any permitted graphic typography. Follow the saved energy target; this proposal still needs human review. Repeated choruses must develop the action, scale or staging instead of replaying the same pose. Include anticipation, payoff and recovery; motivated holds and long takes are valid. Do not replace choreography with continuous camera drift, geometry presence, subtitles alone or an arbitrary fast-cut quota.${revising ? '- These shots already exist. Revise each one\'s current frame and motion to address the unresolved review feedback, keeping what the feedback does not ask to change.\n' : ''}- If an energy target or required audio timing is absent, identify it as a director decision to review rather than inventing analysis or claiming the plan is approved.${hasLyrics ? '- Let the lyric lines inform the imagery and emotion of their shot (interpret, do not illustrate word-for-word). Never render the lyrics as on-screen text in footage; assigned card layers use their explicit card text.\n' : ''}${hasDelivery ? '- Follow the delivery directions: spoken or whispered lines play as intimate close-ups; shouts land as hard-hitting cuts or impacts; a silence or stop is a held, frozen or cut-to-black beat.\n' : ''}- Keep the assigned layer and shot mode: performance uses source-audio lip-sync and a frontal medium close-up with the mouth visible; cutaways show narrative action without lip-sync; cards are graphic beats.\n- Honor any director intent given for a shot. Instrumental shots carry no singing or lip-sync.+${shotCameraPromptSection()}+Respond with ONLY a JSON array, one object per shot, in shot-index order (replace every <…> with real content; do NOT output the literal angle-bracket text), no other text:-[{ "index": 0, "framePrompt": "<the opening reference still, ready to render>", "prompt": "<the shot's motion, ready to render>" }]`;+[{ "index": 0, "framePrompt": "<the opening reference still, ready to render>", "prompt": "<the shot's motion, ready to render>", "camera": { "move": "<camera move id>", "speed": "<slow|moderate|fast|snap>", "endFraming": "<extreme-wide|wide|medium|close|extreme-close>", "onBeat": false, "reason": "<why the camera holds, only for a static move>" } }]`;}// A CLI-style provider can echo its input (including this prompt's own JSON@@ -219,7 +226,11 @@ function isUsableScenePlanArray(parsed) {});}-/** Parse the LLM's scene-prompt response into a `Map<index, {framePrompt, prompt}>`. */+/**+ * Parse the LLM's scene-prompt response into a `Map<index, {framePrompt, prompt, camera}>`.+ * `camera` is validated against the catalog (shotCamera.js parseShotCamera) and+ * is null when absent or unusable; the planner's family rules apply later.+ */function parseScenePlanResponse(text, count) {const { value: parsed } = extractJson(text, { blockType: 'array', shapePredicate: isUsableScenePlanArray });if (!Array.isArray(parsed)) return null;@@ -231,8 +242,9 @@ function parseScenePlanResponse(text, count) {let prompt = typeof entry?.prompt === 'string' ? entry.prompt.trim().slice(0, SCENE_TEXT_MAX) : '';if (isPlaceholderText(framePrompt)) framePrompt = '';if (isPlaceholderText(prompt)) prompt = '';- if (!framePrompt && !prompt) continue;- byIndex.set(idx, { framePrompt, prompt });+ const camera = parseShotCamera(entry?.camera);+ if (!framePrompt && !prompt && !camera) continue;+ byIndex.set(idx, { framePrompt, prompt, camera });}return byIndex.size > 0 ? byIndex : null;}@@ -328,6 +340,7 @@ export async function planProject(id, { seedPrompts = true, providerId, model, elet promptsSeeded = false;let promptsSkippedReason = seedPrompts ? null : 'not-requested';let llmRoute = null;+ let proposedCameras = new Map();if (seedPrompts) {const guidance = [project.automation?.guidance?.trim(), directive?.trim()].filter(Boolean).join('\n');const planning = directive?.trim() ? { ...project, automation: { ...project.automation, guidance } } : project;@@ -337,6 +350,7 @@ export async function planProject(id, { seedPrompts = true, providerId, model, epromptsSeeded = true;for (const [idx, fields] of seeded) {if (!sceneInputs[idx]) continue;+ if (fields.camera) proposedCameras.set(idx, fields.camera);if (shots[idx].visualLayer === 'code') continue;if (shots[idx].visualLayer) Object.assign(sceneInputs[idx], directedPrompts(shots[idx], fields));else {@@ -348,6 +362,11 @@ export async function planProject(id, { seedPrompts = true, providerId, model, epromptsSkippedReason = reason;}}+ // Every non-card shot gets a catalog camera move (#10589): the model's pick when+ // it passes the family/performance rules, otherwise a deterministic one.+ planShotCameras(shots, proposedCameras).forEach((camera, idx) => {+ if (camera && sceneInputs[idx]) sceneInputs[idx].camera = camera;+ });// `addProjectScenes` returns the project it just persisted (read fresh// under the same lock/transaction that wrote it, not a re-derived@@ -410,7 +429,8 @@ function feedbackSceneIds(scenes, feedback) {* span, takes and selected media; the caller persists the returned fields.* A shot whose span still matches the deterministic plan keeps its assigned* set, look and layer direction. Throws when no usable proposal comes back.- * @returns {Promise<Map<string, { framePrompt?: string, prompt?: string }>>} revised fields by sceneId+ * A valid revised camera move (catalog id; a still move with its reason) is kept.+ * @returns {Promise<Map<string, { framePrompt?: string, prompt?: string, camera?: object }>>} revised fields by sceneId*/export async function proposeShotRevisions(project, feedback, { providerId, model, effort } = {}) {const scenes = (project.scenes || []).filter((scene) => Number.isFinite(scene.startSec) && scene.endSec > scene.startSec);@@ -424,15 +444,17 @@ export async function proposeShotRevisions(project, feedback, { providerId, modeconst base = match || { sectionLabel: scene.sectionLabel || scene.label, sectionIndex: scene.sectionIndex ?? index,shotIndex: 0, shotCount: 1, startSec: scene.startSec, endSec: scene.endSec };return { ...base, lyricText: scene.lyricText ?? base.lyricText, visualIntent: scene.visualIntent ?? base.visualIntent,- sceneId: scene.sceneId, current: { framePrompt: scene.framePrompt, prompt: scene.prompt } };+ sceneId: scene.sceneId, current: { framePrompt: scene.framePrompt, prompt: scene.prompt, camera: scene.camera } };});const { seeded, reason } = await tryProposeScenePrompts(project, shots, { providerId, model, effort });if (!seeded) throw new ServerError(`No revised shots came back (${reason}). Edit the shots by hand or retry.`, { status: 422, code: 'SHOT_REVISION_FAILED' });const updates = new Map();for (const [index, fields] of seeded) {const shot = shots[index];- updates.set(shot.sceneId, shot.visualLayer ? directedPrompts(shot, fields) : {- ...(fields.framePrompt ? { framePrompt: fields.framePrompt } : {}), ...(fields.prompt ? { prompt: fields.prompt } : {}),+ const camera = fields.camera && shot.visualLayer !== 'card' ? { camera: fields.camera } : {};+ const prose = fields.framePrompt || fields.prompt;+ updates.set(shot.sceneId, shot.visualLayer && prose ? { ...directedPrompts(shot, fields), ...camera } : {+ ...(fields.framePrompt ? { framePrompt: fields.framePrompt } : {}), ...(fields.prompt ? { prompt: fields.prompt } : {}), ...camera,});}return updates;diff --git a/server/services/musicVideo/planner.test.js b/server/services/musicVideo/planner.test.jsindex a2c076c02b..d25f3d293b 100644--- a/server/services/musicVideo/planner.test.js+++ b/server/services/musicVideo/planner.test.js@@ -773,3 +773,59 @@ describe('review feedback in shot planning', () => {expect(prompt).toContain('"Drop"');});});++describe('shot camera planning (#10589)', () => {+ const freshProjectResult = () => ({ project: makeProject(), scenes: [{ sceneId: 's1' }] });+ const llm = (entries) => {+ resolveProviderAndModel.mockResolvedValue({ provider: { id: 'p1', type: 'api' }, selectedModel: 'gpt' });+ runPromptThroughProvider.mockResolvedValue({ text: JSON.stringify(entries) });+ };++ it('puts the camera vocabulary and variety rules in the plan prompt and asks for a camera per shot', () => {+ const { shots } = planShots(SECTIONS, { beats: BEATS, downbeats: DOWNBEATS });+ const prompt = buildScenePlanPrompt(makeProject(), shots);+ expect(prompt).toContain('CAMERA VOCABULARY');+ expect(prompt).toContain('- whip-pan (Whip pan) [rotate, high, snap]');+ expect(prompt).toContain('- powers-of-ten');+ expect(prompt).toContain('At most 2 consecutive shots may use moves from the same family');+ expect(prompt).toContain('must give its "reason"');+ expect(prompt).toContain('"camera": { "move": "<camera move id>"');+ });++ it('keeps valid model cameras, drops unknown ids and reasonless lock-offs, and fills every shot', async () => {+ getProject.mockResolvedValue(makeProject());+ addProjectScenes.mockResolvedValue(freshProjectResult());+ llm([+ { index: 0, framePrompt: 'neon alley', prompt: 'a courier waits', camera: { move: 'pedestal-up', speed: 'slow', endFraming: 'wide', onBeat: false } },+ { index: 1, framePrompt: 'rooftop', prompt: 'the courier leaps', camera: { move: 'teleport-cam', speed: 'fast' } },+ { index: 2, framePrompt: 'dawn street', prompt: 'the courier walks away', camera: { move: 'locked-off' } },+ ]);+ await planProject('mv-1');+ const inputs = addProjectScenes.mock.calls[0][1];+ expect(inputs[0].camera).toEqual({ move: 'pedestal-up', speed: 'slow', endFraming: 'wide' });+ for (const input of inputs) expect(typeof input.camera?.move).toBe('string');+ expect(inputs.slice(1).some((input) => input.camera.move === 'teleport-cam' || input.camera.move === 'locked-off')).toBe(false);+ });++ it('plans catalog cameras without a provider, snapping the drop and never running one family three times', async () => {+ getProject.mockResolvedValue(makeProject());+ addProjectScenes.mockResolvedValue(freshProjectResult());+ await planProject('mv-1', { seedPrompts: false });+ const inputs = addProjectScenes.mock.calls[0][1];+ const { getCameraMovement } = await import('../../lib/cameraMovements.js');+ const families = inputs.map((input) => getCameraMovement(input.camera.move).family);+ for (let i = 2; i < families.length; i++) expect(families[i] === families[i - 1] && families[i] === families[i - 2]).toBe(false);+ const drop = inputs.find((input) => input.sectionLabel === 'Drop');+ expect(getCameraMovement(drop.camera.move).snap).toBe(true);+ expect(drop.camera.onBeat).toBe(true);+ });++ it('shows the current camera when revising and returns a valid revised camera', async () => {+ const scenes = [{ sceneId: 'scene-drop', label: 'Drop', startSec: 10, endSec: 18, framePrompt: 'rooftop', prompt: 'figure walks', camera: { move: 'truck-left' } }];+ const requests = [{ id: 'fb', stage: 'storyboard', target: 'Drop', text: 'Hit the drop harder', decision: 'request-changes', basis: 'b' }];+ llm([{ index: 0, framePrompt: 'rooftop', prompt: 'figure leaps', camera: { move: 'crash zoom', speed: 'snap', onBeat: true } }]);+ const updates = await proposeShotRevisions(makeProject({ scenes, productionReview: { feedback: requests } }), requests);+ expect(runPromptThroughProvider.mock.calls[0][0].prompt).toContain('current camera: truck-left');+ expect(updates.get('scene-drop').camera).toEqual({ move: 'crash-zoom', speed: 'snap', onBeat: true });+ });+});diff --git a/server/services/musicVideo/productionReview.js b/server/services/musicVideo/productionReview.jsindex 5167a4cfec..17b183cc3b 100644--- a/server/services/musicVideo/productionReview.js+++ b/server/services/musicVideo/productionReview.js@@ -5,6 +5,8 @@ import { ServerError } from '../../lib/errorHandler.js';import { musicVideoAllowsMedia } from '../../lib/musicVideoMediaPolicy.js';import { isNonBlankStr as text } from '../../lib/textUtils.js';+import { cameraMovementFromText, getCameraMovement } from '../../lib/cameraMovements.js';+import { cameraVarietyReport } from './shotCamera.js';const artifact = (project, id) => (project.devArtifacts || []).find(a => a.id === id && !a.deleted);const artifactBasis = a => a ? { id: a.id, version: a.version, file: a.file } : null;const source = p => {@@ -74,8 +76,9 @@ export function productionReviewBasis(project) {timingStatus: draft.timingStatus, timingNotes: draft.timingNotes, storyboard: draft.storyboard,storyboardSource: draft.storyboardSource || 'board', documentStoryboard: project.productionReview?.documentStoryboard,document: draft.storyboardSource === 'document' ? project.composition?.document : null,- scenes: (project.scenes || []).map(({ sceneId, startSec, endSec, lyricText, visualIntent, prompt, framePrompt }) =>- ({ sceneId, startSec, endSec, lyricText, visualIntent, prompt, framePrompt })), treatment: project.treatment });+ // A planned camera (#10589) joins the hash only when set, so older approvals stay current.+ scenes: (project.scenes || []).map(({ sceneId, startSec, endSec, lyricText, visualIntent, prompt, framePrompt, camera }) =>+ ({ sceneId, startSec, endSec, lyricText, visualIntent, prompt, framePrompt, ...(camera ? { camera } : {}) })), treatment: project.treatment });const window = project.productionReview?.proof;const proof = hash({ storyboard, composition: project.composition,window: window && { startSec: window.startSec, endSec: window.endSec },@@ -103,6 +106,7 @@ function productionApprovalInputs(project) {scenes[`scene ${n} timing`] = h([s.startSec, s.endSec]);scenes[`scene ${n} lyrics`] = h(s.lyricText);scenes[`scene ${n} prompt`] = h([s.visualIntent, s.prompt, s.framePrompt]);+ if (s.camera) scenes[`scene ${n} camera`] = h(s.camera);}const storyboard = { ...art, song: h([source(project).trackId, source(project).uploadedAudioFilename, source(project).duration, source(project).beats, source(project).sections]),lyrics: h([source(project).lyrics, source(project).markers, source(project).phrases]), 'lyric timing': h([draft.lyricsMode, draft.timingStatus, draft.timingNotes]),@@ -269,6 +273,7 @@ export function productionReadiness(project) {|| shot?.lyricCueIds?.some(id => !cues.some(c => c.id === id))) boardProblems.push(`Review lyric anchors for ${scene.label || 'each shot'}.`);}const storyboardApproved = !boardProblems.length && review.approvals?.storyboard?.basis === basis.storyboard;+ const camera = storyboardCameraReport(scenes, documentShots ? null : draft.storyboard);const proof = review.proof;const excerpt = (project.excerpts || []).find(e => e.id === proof?.excerptId);const proofProblems = unresolved('proof').map(f => `Resolve proof feedback for ${f.target}: ${f.text}`);@@ -279,13 +284,28 @@ export function productionReadiness(project) {const proofApproved = !proofProblems.length && hasProofEvidence(review.approvals?.proof?.proofReview) && review.approvals?.proof?.basis === hash({ basis: basis.proof, excerptId: excerpt.id, filename: excerpt.filename });return { basis, inputs, alignment: { basis: alignmentBasis, status: draft.lyricsMode === 'instrumental' ? 'instrumental': draft.timingStatus !== 'verified' ? 'provisional' : review.alignmentBasis === alignmentBasis ? 'verified' : 'stale' }, documentShotImport: { documentDirectory: project.composition?.document?.directory || null, audioBasis: alignmentBasis }, art: { approved: artApproved, problems: [...new Set(artProblems)], stale: artApproved ? null : staleApproval(project, 'art', basis.art, inputs) },- storyboard: { approved: storyboardApproved, problems: [...new Set(boardProblems)], stale: storyboardApproved ? null : staleApproval(project, 'storyboard', basis.storyboard, inputs) },+ storyboard: { approved: storyboardApproved, problems: [...new Set(boardProblems)], camera, stale: storyboardApproved ? null : staleApproval(project, 'storyboard', basis.storyboard, inputs) },proof: { approved: proofApproved, problems: proofProblems, excerptId: excerpt?.id || null, stale: proofApproved ? null : staleApproval(project, 'proof', basis.proof, inputs) },castAndSets: castAndSetsApproval(project),// The animated proof is optional review evidence: the approved storyboard is what the final render needs.readyForProduction: storyboardApproved };}+/**+ * Non-blocking camera-variety notes for the storyboard (#10589). A Board+ * scene's planned `camera.move` wins; otherwise the draft shot's free-text+ * camera is matched against the catalog (document shots use their own text).+ */+function storyboardCameraReport(scenes, draftShots) {+ const shots = scenes.filter(s => Number.isFinite(s.startSec)).sort((a, b) => a.startSec - b.startSec).map((scene) => {+ const shot = draftShots ? draftShots.find(s => s.sceneId === scene.sceneId) : scene;+ const planned = getCameraMovement(scene.camera?.move)?.value;+ return { label: scene.label || scene.sceneId, move: planned || cameraMovementFromText(typeof shot?.camera === 'string' ? shot.camera : ''),+ sectionKey: scene.sectionIndex ?? scene.sectionLabel ?? null, sectionLabel: scene.sectionLabel || '', startSec: scene.startSec };+ });+ return cameraVarietyReport(shots);+}+const refuseRevert = (message, code) => new ServerError(message, { status: 409, code });function restoreScenePrompt(project, value) {diff --git a/server/services/musicVideo/productionReview.stale.test.js b/server/services/musicVideo/productionReview.stale.test.jsindex a576022154..a7dc83bbc7 100644--- a/server/services/musicVideo/productionReview.stale.test.js+++ b/server/services/musicVideo/productionReview.stale.test.js@@ -68,3 +68,36 @@ describe('reverting a Cast & Sets approval (#10241)', () => {expect(() => revertApprovedInput(legacy, { stage: 'castAndSets', field: 'concept' })).toThrow(/not kept/);});});++describe('storyboard camera (#10589)', () => {+ const scenes = [+ { sceneId: 's1', label: 'Verse 1', sectionLabel: 'Verse', sectionIndex: 0, startSec: 0, endSec: 4, prompt: 'a', camera: { move: 'locked-off', reason: 'the singer holds still' } },+ { sceneId: 's2', label: 'Verse 2', sectionLabel: 'Verse', sectionIndex: 0, startSec: 4, endSec: 8, prompt: 'b', camera: { move: 'locked-time-lapse', reason: 'clouds race' } },+ { sceneId: 's3', label: 'Verse 3', sectionLabel: 'Verse', sectionIndex: 0, startSec: 8, endSec: 12, prompt: 'c' },+ { sceneId: 's4', label: 'Chorus 1', sectionLabel: 'Chorus', sectionIndex: 1, startSec: 12, endSec: 16, prompt: 'd', camera: { move: 'truck-left' } },+ ];+ const project = { id: 'p1', scenes, productionReview: { draft: { storyboard: [{ sceneId: 's3', camera: 'Static tripod frame on the hands' }] } } };++ it('flags a static run (reading free-text draft cameras) and a chorus with no snap, without blocking', () => {+ const { storyboard } = productionReadiness(project);+ expect(storyboard.camera.staticRuns).toEqual([['Verse 1', 'Verse 2', 'Verse 3']]);+ expect(storyboard.camera.snaplessChoruses).toEqual([{ label: 'Chorus', startSec: 12 }]);+ expect(storyboard.camera.notes).toHaveLength(2);+ expect(storyboard.problems.some((problem) => /static|snap/i.test(problem))).toBe(false);+ });++ it('clears the chorus note once the chorus snaps', () => {+ const snapped = { ...project, scenes: scenes.map((s) => (s.sceneId === 's4' ? { ...s, camera: { move: 'whip-pan', onBeat: true } } : s)) };+ expect(productionReadiness(snapped).storyboard.camera.snaplessChoruses).toEqual([]);+ });++ it('labels a camera edit and leaves the basis of camera-less boards unchanged', () => {+ const plain = { id: 'p1', scenes: scenes.map(({ camera, ...s }) => s), productionReview: { draft: {} } };+ const before = productionReadiness(plain);+ const withCamera = productionReadiness({ ...plain, scenes: plain.scenes.map((s, i) => (i === 3 ? { ...s, camera: { move: 'whip-pan' } } : s)) });+ expect(Object.keys(withCamera.inputs.storyboard).filter((k) => withCamera.inputs.storyboard[k] !== before.inputs.storyboard[k])).toEqual(['scene 4 camera']);+ expect(withCamera.basis.storyboard).not.toBe(before.basis.storyboard);+ const undefinedCamera = productionReadiness({ ...plain, scenes: plain.scenes.map((s) => ({ ...s, camera: undefined })) });+ expect(undefinedCamera.basis.storyboard).toBe(before.basis.storyboard);+ });+});diff --git a/server/services/musicVideo/productionReviewService.js b/server/services/musicVideo/productionReviewService.jsindex c189f713f4..7d0df9b6a6 100644--- a/server/services/musicVideo/productionReviewService.js+++ b/server/services/musicVideo/productionReviewService.js@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto';import { ServerError } from '../../lib/errorHandler.js';import { getProject, mutateProjectRecord } from './projects.js';import { musicVideoEvents } from './events.js';+import { shotCameraLabel } from '../../lib/cameraMovements.js';import { productionReadiness, seedArtDraft, productionReviewBasis, productionAlignmentBasis, documentStoryboardBasis, approveProductionStage, assertProductionApproval, recordProductionFeedback, resolveProductionFeedback, revertApprovedInput } from './productionReview.js';const reviewProcessId = randomUUID();@@ -232,7 +233,7 @@ export async function prepareProductionReview(id, options = {}) {sceneId: scene.sceneId,lyricCueIds: (current.lyricCues || []).filter(c => c.startSec < scene.endSec && c.endSec > scene.startSec).map(c => c.id),action: scene.visualIntent || scene.prompt || '', staging: scene.framePrompt || '',- camera: scene.direction?.camera || world.camera || '', transition: world.transitions || '',+ camera: shotCameraLabel(scene.camera) || scene.direction?.camera || world.camera || '', transition: world.transitions || '',}))];return { project: { ...current, productionReview: { ...current.productionReview, draft: { ...latest, storyboard } } } };});@@ -329,7 +330,8 @@ export async function reviseProductionFromFeedback(id, { stage, ...route }) {const draft = current.productionReview?.draft;const storyboard = draft?.storyboard?.map(shot => {const fields = updates.get(shot.sceneId);- return fields ? { ...shot, ...(fields.prompt ? { action: fields.prompt } : {}), ...(fields.framePrompt ? { staging: fields.framePrompt } : {}) } : shot;+ return fields ? { ...shot, ...(fields.prompt ? { action: fields.prompt } : {}), ...(fields.framePrompt ? { staging: fields.framePrompt } : {}),+ ...(fields.camera ? { camera: shotCameraLabel(fields.camera) } : {}) } : shot;});return { project: { ...current, scenes, updatedAt: new Date().toISOString(),...(storyboard ? { productionReview: { ...current.productionReview, draft: { ...draft, storyboard } } } : {}) } };diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.jsindex 8b803804ae..a560ba0daa 100644--- a/server/services/musicVideo/projectsLogic.js+++ b/server/services/musicVideo/projectsLogic.js@@ -480,6 +480,8 @@ function buildScene(input, { order }) {// #8985: what a composed render shows for this span (render.js#sceneLayer).visualLayer: input.visualLayer ?? 'footage',stillMove: input.stillMove ?? 'hold',+ // #10589: the planned camera move (absent on hand-added and pre-#10589 shots).+ ...(input.camera ? { camera: input.camera } : {}),cardText: input.cardText ?? null,...(input.codeOverlay ? { codeOverlay: true } : {}),cardColor: input.cardColor ?? null,@@ -699,6 +701,7 @@ export function splitScene(project, sceneId, { backend = null } = {}) {visualLayer: scene.visualLayer ?? 'footage',shotMode: scene.shotMode ?? 'cutaway',performanceSpeaker: scene.performanceSpeaker ?? null,+ ...(scene.camera ? { camera: scene.camera } : {}),...timing,}),}, { order: 0 });diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.jsindex 2df6b79ceb..7d7ac63e20 100644--- a/server/services/musicVideo/render.js+++ b/server/services/musicVideo/render.js@@ -54,6 +54,7 @@ import { AUDIO_NORM, buildAudioBedMix } from '../videoTimeline/audioBedMix.js';import { musicVideoEvents } from './events.js';import { projectSoundBed } from './soundBed.js';import { intercutClips } from './intercut.js';+import { stillMoveForCamera } from '../../lib/cameraMovements.js';// Per-project render mutex (keyed by projectId so two projects can render in// parallel; same-project re-entry returns 409 with the live jobId for re-attach).@@ -253,7 +254,8 @@ export async function resolveSceneClips(project, { layered = false } = {}) {}const imagePath = scene.referenceImageId ? safeUnder(PATHS.images, scene.referenceImageId) : null;if (!imagePath || !existsSync(imagePath)) { missingStills.push(scene.sceneId); continue; }- clips.push({ ...section, imagePath, move: scene.stillMove || 'hold' });+ // A planned camera move (#10589) picks the nearest composed still move.+ clips.push({ ...section, imagePath, move: stillMoveForCamera(scene.camera) || scene.stillMove || 'hold' });continue;}const entry = historyMap.get(scene.videoHistoryId);diff --git a/server/services/musicVideo/shotCamera.js b/server/services/musicVideo/shotCamera.jsnew file mode 100644index 0000000000..a25b53e6c2--- /dev/null+++ b/server/services/musicVideo/shotCamera.js@@ -0,0 +1,156 @@+/**+ * Music Video — each planned shot's structured camera move (#10589).+ *+ * The planner asks the model for `camera: { move, speed, endFraming, onBeat,+ * reason }` per shot, drawn from the shared camera-movement catalog+ * (lib/cameraMovements.js). This module validates that answer against the+ * catalog and the planning rules, and fills every gap deterministically, so a+ * plan made without a provider (or with a partial answer) still varies its+ * camera instead of locking off:+ *+ * - at most MAX_FAMILY_RUN consecutive shots from the same move family;+ * - hit points (a chorus/hook/drop's first shot, the opening hook) snap on+ * the downbeat when the planner picks;+ * - a still camera (lock-off, locked time-lapse) must give its reason;+ * - performance shots keep their frontal lip-sync framing, so they never take+ * a snap, orbit, roll or other high-energy move.+ *+ * Title cards are graphic beats with no camera. Pure; the planner persists the+ * result on the Board scenes as `scene.camera`.+ */++import {+ CAMERA_FRAMINGS, CAMERA_SPEEDS, SNAP_CAMERA_MOVEMENTS, cameraMovementCatalogForPrompt, cameraMovementId, getCameraMovement,+} from '../../lib/cameraMovements.js';++export const MAX_FAMILY_RUN = 2;+const HIT_SECTION = /chorus|hook|drop/i;+const REASON_MAX = 300;++// Deterministic picks per energy tier; the snap pool serves hit points.+const POOLS = Object.freeze({+ calm: ['slow-dolly-in', 'cinematic-arc', 'pedestal-up', 'slider-parallax', 'slow-dolly-out', 'tilt-up', 'focus-reveal', 'pan-right'],+ medium: ['truck-right', 'orbit-180', 'crane-up', 'steadicam-follow', 'push-past', 'pan-left', 'side-tracking', 'zoom-in'],+ high: ['fast-dolly-in', 'whip-pan', 'drone-dive', 'barrel-roll', 'chase-tracking', 'orbit-360', 'handheld', 'crash-zoom'],+});+const SNAP_POOL = SNAP_CAMERA_MOVEMENTS;+const PERFORMANCE_POOL = ['slow-dolly-in', 'slider-parallax', 'pedestal-up', 'handheld', 'zoom-in', 'ots-drift'];+const PERFORMANCE_FAMILIES = new Set(['static', 'push-pull', 'lateral', 'vertical', 'lens', 'tracking']);++const familyOf = (camera) => getCameraMovement(camera?.move)?.family || null;++/** calm / medium / high for a shot's normalized section energy (a chorus with no analysis reads high). */+function shotEnergyTier(shot) {+ const energy = shot?.sectionEnergy;+ if (typeof energy !== 'number' || !Number.isFinite(energy)) return HIT_SECTION.test(shot?.sectionLabel || '') ? 'high' : 'medium';+ return energy >= 0.67 ? 'high' : energy >= 0.34 ? 'medium' : 'calm';+}++/** A hit point: the opening hook, or the first shot of a chorus / hook / drop section. */+export const isHitShot = (shot) => shot?.hook === true || (shot?.shotIndex === 0 && HIT_SECTION.test(shot?.sectionLabel || ''));++const performanceSafe = (move) => PERFORMANCE_FAMILIES.has(move.family) && move.energy !== 'high' && !move.snap;++/**+ * Validate a model-proposed camera against the catalog. Accepts an object or a+ * bare id/label. Returns the normalized `{ move, speed?, endFraming?, onBeat?,+ * reason? }`, or null for an unknown move or a still camera with no reason.+ */+export function parseShotCamera(raw) {+ const value = typeof raw === 'string' ? { move: raw } : raw;+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;+ const move = cameraMovementId(typeof value.move === 'string' ? value.move : '');+ if (!move) return null;+ const reason = typeof value.reason === 'string' && !/^\s*<.+>\s*$/.test(value.reason) ? value.reason.trim().slice(0, REASON_MAX) : '';+ if (getCameraMovement(move).still && !reason) return null;+ return {+ move,+ ...(CAMERA_SPEEDS.includes(value.speed) ? { speed: value.speed } : {}),+ ...(CAMERA_FRAMINGS.includes(value.endFraming) ? { endFraming: value.endFraming } : {}),+ ...(value.onBeat === true ? { onBeat: true } : {}),+ ...(reason ? { reason } : {}),+ };+}++function pick(shot, index, blockedFamily, previousMove) {+ const performance = shot.shotMode === 'performance';+ const hit = !performance && isHitShot(shot);+ const pool = performance ? PERFORMANCE_POOL : hit ? SNAP_POOL : POOLS[shotEnergyTier(shot)];+ for (let step = 0; step < pool.length; step++) {+ const move = pool[(index + step) % pool.length];+ if (move === previousMove || getCameraMovement(move).family === blockedFamily) continue;+ return hit ? { move, speed: 'snap', onBeat: true } : { move };+ }+ // Every candidate collided (a one-family pool); any calm move outside the blocked family.+ return { move: POOLS.calm.find((move) => getCameraMovement(move).family !== blockedFamily) };+}++/**+ * One camera per shot, in shot order (null for title cards). `proposed` maps a+ * shot index to the model's raw camera answer; a valid answer is kept unless it+ * would make a third consecutive shot from one family or break a performance+ * shot's framing, in which case the deterministic pick replaces it.+ */+export function planShotCameras(shots, proposed = new Map()) {+ const cameras = [];+ for (const [index, shot] of shots.entries()) {+ if (shot.visualLayer === 'card') { cameras.push(null); continue; }+ const [a, b] = cameras.slice(-MAX_FAMILY_RUN).map(familyOf);+ const blockedFamily = cameras.length >= MAX_FAMILY_RUN && a && a === b ? a : null;+ let camera = parseShotCamera(proposed.get(index));+ if (camera && familyOf(camera) === blockedFamily) camera = null;+ if (camera && shot.shotMode === 'performance' && !performanceSafe(getCameraMovement(camera.move))) camera = null;+ cameras.push(camera || pick(shot, index, blockedFamily, cameras.at(-1)?.move));+ }+ return cameras;+}++/** The camera vocabulary and rules the shot-planning prompt carries. */+export function shotCameraPromptSection() {+ return `CAMERA VOCABULARY — give every shot a "camera" whose "move" is one of these ids (id (label) [family, energy]: what the camera does):+${cameraMovementCatalogForPrompt({ detail: true })}+Camera rules:+- At most ${MAX_FAMILY_RUN} consecutive shots may use moves from the same family.+- High-energy shots (energy 0.67 or more) use high-energy moves; calm shots use calm or medium ones.+- Hit points — a chorus's first downbeat, the OPENING HOOK, a hook word — take a snap move (${SNAP_POOL.join(', ')}) with "onBeat": true.+- A static camera (${['locked-off', 'locked-time-lapse'].join(', ')}) must give its "reason".+- Performance shots keep the frontal medium close-up: calm or medium push, lateral, vertical, lens or tracking moves only — no snap, orbit or roll.+- "speed" is one of ${CAMERA_SPEEDS.join(', ')}; "endFraming" is one of ${CAMERA_FRAMINGS.join(', ')}.+- Describe the camera only in "camera"; the motion "prompt" covers subject action, staging and mood.`;+}++const clock = (sec) => Number.isFinite(sec) ? `${Math.floor(sec / 60)}:${String(Math.floor(sec % 60)).padStart(2, '0')}` : null;+const STATIC_RUN = 3;++/**+ * The production review's camera-variety notes (#10589), never blocking.+ * `shots` are the storyboard shots in timeline order as `{ label, move,+ * sectionKey, sectionLabel, startSec }`, where `move` is a catalog id or null+ * (unknown). Flags runs of STATIC_RUN+ still shots and chorus / hook / drop+ * sections whose shots carry no snap move.+ */+export function cameraVarietyReport(shots) {+ const staticRuns = [];+ let run = [];+ const flush = () => { if (run.length >= STATIC_RUN) staticRuns.push(run.map((s) => s.label)); run = []; };+ for (const shot of shots) {+ if (getCameraMovement(shot.move)?.still) run.push(shot);+ else flush();+ }+ flush();+ // Consecutive shots of one chorus/hook/drop section form one hit section.+ const sections = [];+ for (const [index, shot] of shots.entries()) {+ if (!HIT_SECTION.test(shot.sectionLabel || '')) continue;+ const last = sections.at(-1);+ if (last && last.key === shot.sectionKey && last.endIndex === index - 1) { last.shots.push(shot); last.endIndex = index; }+ else sections.push({ key: shot.sectionKey, label: shot.sectionLabel, startSec: shot.startSec, shots: [shot], endIndex: index });+ }+ const snaplessChoruses = sections.filter((s) => !s.shots.some((shot) => getCameraMovement(shot.move)?.snap))+ .map((s) => ({ label: s.label, startSec: Number.isFinite(s.startSec) ? s.startSec : null }));+ const notes = [+ ...staticRuns.map((labels) => `${labels.length} static shots in a row (${labels[0]} – ${labels.at(-1)}): give one of them a move, or make sure each hold is motivated.`),+ ...snaplessChoruses.map((c) => `${c.label}${clock(c.startSec) ? ` at ${clock(c.startSec)}` : ''} has no snap move: land a ${SNAP_POOL.join(', ')} on its first downbeat.`),+ ];+ return { staticRuns, snaplessChoruses, notes };+}diff --git a/server/services/musicVideo/shotCamera.test.js b/server/services/musicVideo/shotCamera.test.jsnew file mode 100644index 0000000000..9895d86c85--- /dev/null+++ b/server/services/musicVideo/shotCamera.test.js@@ -0,0 +1,117 @@+import { describe, it, expect } from 'vitest';+import { getCameraMovement } from '../../lib/cameraMovements.js';+import { cameraVarietyReport, isHitShot, parseShotCamera, planShotCameras, shotCameraPromptSection } from './shotCamera.js';++const shot = (overrides = {}) => ({ sectionLabel: 'Verse', sectionIndex: 0, shotIndex: 1, shotCount: 4, sectionEnergy: 0.5, ...overrides });+const family = (camera) => getCameraMovement(camera.move).family;++describe('parseShotCamera', () => {+ it('normalizes a catalog id or label and keeps only valid fields', () => {+ expect(parseShotCamera({ move: 'Whip Pan', speed: 'snap', endFraming: 'medium', onBeat: true, extra: 1 }))+ .toEqual({ move: 'whip-pan', speed: 'snap', endFraming: 'medium', onBeat: true });+ expect(parseShotCamera('slow-dolly-in')).toEqual({ move: 'slow-dolly-in' });+ expect(parseShotCamera({ move: 'slow-dolly-in', speed: 'warp', endFraming: 'huge', onBeat: 'yes' })).toEqual({ move: 'slow-dolly-in' });+ });++ it('rejects unknown moves, placeholders and a still camera without its reason', () => {+ expect(parseShotCamera({ move: 'teleport' })).toBeNull();+ expect(parseShotCamera({ move: '<camera move id>' })).toBeNull();+ expect(parseShotCamera({ move: 'locked-off' })).toBeNull();+ expect(parseShotCamera({ move: 'locked-off', reason: '<why the camera holds, only for a static move>' })).toBeNull();+ expect(parseShotCamera({ move: 'locked-off', reason: ' the dancer fills the frame ' })).toEqual({ move: 'locked-off', reason: 'the dancer fills the frame' });+ expect(parseShotCamera(null)).toBeNull();+ expect(parseShotCamera(['whip-pan'])).toBeNull();+ });+});++describe('shot energy and hit points', () => {+ it('picks from the energy tier, reading an unanalyzed chorus as high', () => {+ const firstPick = (overrides) => planShotCameras([shot(overrides)])[0].move;+ expect(firstPick({ sectionEnergy: 0.1 })).toBe('slow-dolly-in');+ expect(firstPick({ sectionEnergy: 0.5 })).toBe('truck-right');+ expect(firstPick({ sectionEnergy: 0.9 })).toBe('fast-dolly-in');+ expect(firstPick({ sectionEnergy: undefined, sectionLabel: 'Verse' })).toBe('truck-right');+ expect(firstPick({ sectionEnergy: undefined, sectionLabel: 'Chorus 2' })).toBe('fast-dolly-in');+ });++ it('treats the opening hook and a chorus/drop first shot as hits', () => {+ expect(isHitShot(shot({ hook: true }))).toBe(true);+ expect(isHitShot(shot({ sectionLabel: 'Chorus', shotIndex: 0 }))).toBe(true);+ expect(isHitShot(shot({ sectionLabel: 'Chorus', shotIndex: 1 }))).toBe(false);+ expect(isHitShot(shot())).toBe(false);+ });+});++describe('planShotCameras', () => {+ it('gives every non-card shot a catalog move and cards none', () => {+ const cameras = planShotCameras([shot(), shot({ visualLayer: 'card' }), shot({ sectionEnergy: 0.9 })]);+ expect(cameras[1]).toBeNull();+ expect(getCameraMovement(cameras[0].move)).toBeTruthy();+ expect(getCameraMovement(cameras[2].move).energy === 'calm').toBe(false);+ });++ it('snaps on the downbeat at hit points', () => {+ const [camera] = planShotCameras([shot({ sectionLabel: 'Chorus', shotIndex: 0, sectionEnergy: 0.9 })]);+ expect(getCameraMovement(camera.move).snap).toBe(true);+ expect(camera).toMatchObject({ speed: 'snap', onBeat: true });+ });++ it('replaces a model pick that would run one family three times', () => {+ const shots = [shot(), shot(), shot()];+ const proposed = new Map([[0, { move: 'slow-dolly-in' }], [1, { move: 'fast-dolly-in' }], [2, { move: 'push-past' }]]);+ const cameras = planShotCameras(shots, proposed);+ expect(cameras[0].move).toBe('slow-dolly-in');+ expect(cameras[1].move).toBe('fast-dolly-in');+ expect(family(cameras[2])).not.toBe('push-pull');+ });++ it('never runs one family three times over a long deterministic plan', () => {+ const shots = Array.from({ length: 40 }, (_, i) => shot({ sectionEnergy: [0.1, 0.5, 0.9][i % 3], shotIndex: i % 4, sectionLabel: i % 8 < 4 ? 'Verse' : 'Chorus' }));+ const families = planShotCameras(shots).map(family);+ for (let i = 2; i < families.length; i++) expect(families[i] === families[i - 1] && families[i] === families[i - 2]).toBe(false);+ });++ it('keeps performance shots on frontal-safe moves', () => {+ const proposed = new Map([[0, { move: 'orbit-360' }], [1, { move: 'slider-parallax' }]]);+ const cameras = planShotCameras([shot({ shotMode: 'performance', hook: true }), shot({ shotMode: 'performance' })], proposed);+ for (const camera of cameras) {+ const move = getCameraMovement(camera.move);+ expect(move.snap || move.energy === 'high' || ['orbit', 'roll', 'rotate'].includes(move.family)).toBe(false);+ }+ expect(cameras[1].move).toBe('slider-parallax');+ });+});++describe('shotCameraPromptSection', () => {+ it('lists every catalog move with the variety rules', () => {+ const text = shotCameraPromptSection();+ expect(text).toContain('- locked-time-lapse (');+ expect(text).toContain('- crash-zoom-out (');+ expect(text).toMatch(/Hit points .* snap move/);+ });+});++describe('cameraVarietyReport', () => {+ const row = (label, move, sectionLabel = 'Verse', sectionKey = 0, startSec = 0) => ({ label, move, sectionLabel, sectionKey, startSec });++ it('flags three or more static shots in a row', () => {+ const report = cameraVarietyReport([row('A', 'locked-off'), row('B', 'locked-time-lapse'), row('C', 'locked-off'), row('D', 'slow-dolly-in'), row('E', 'locked-off'), row('F', 'locked-off')]);+ expect(report.staticRuns).toEqual([['A', 'B', 'C']]);+ expect(report.notes[0]).toMatch(/^3 static shots in a row \(A – C\)/);+ });++ it('flags a chorus with no snap move and passes one that has it', () => {+ const report = cameraVarietyReport([+ row('V', 'slow-dolly-in'),+ row('C1', 'truck-left', 'Chorus', 1, 45), row('C2', 'orbit-180', 'Chorus', 1, 50),+ row('B', 'pan-left', 'Bridge', 2, 60),+ row('C3', 'whip-pan', 'Chorus', 3, 75), row('C4', '', 'Chorus', 3, 80),+ ]);+ expect(report.snaplessChoruses).toEqual([{ label: 'Chorus', startSec: 45 }]);+ expect(report.notes).toEqual([expect.stringContaining('Chorus at 0:45 has no snap move')]);+ });++ it('reports nothing for a varied storyboard', () => {+ expect(cameraVarietyReport([row('A', 'locked-off'), row('B', 'whip-pan', 'Chorus', 1)]).notes).toEqual([]);+ });+});