Skip to content

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

Add an optional cutting room floor scene after the song (#11356)

[._.]/3258029de97a
diff --git a/client/src/components/musicVideo/StatsOutro.test.jsx b/client/src/components/musicVideo/StatsOutro.test.jsx
new file mode 100644
index 0000000000..f9e55b7973
--- /dev/null
+++ b/client/src/components/musicVideo/StatsOutro.test.jsx
@@ -0,0 +1,74 @@
+import { describe, expect, it, vi } from 'vitest';
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
+
+const { getMusicVideoOutroStats } = vi.hoisted(() => ({
+ getMusicVideoOutroStats: vi.fn(async () => ({ stats: { stills: { made: 3, kept: 1 }, clips: { made: 2, kept: 1 }, rejected: 1, shots: 1, floorImages: [] } })),
+}));
+vi.mock('../../services/apiMusicVideo.js', async (importOriginal) => ({ ...(await importOriginal()), getMusicVideoOutroStats }));
+
+const { default: StoryboardAnimatic } = await import('./StoryboardAnimatic.jsx');
+const { default: StatsOutroPanel } = await import('./StatsOutroPanel.jsx');
+
+const scenes = [{ sceneId: 'a', label: 'Opening', startSec: 0 }];
+
+// A 2D context that records the text it is asked to draw (happy-dom's canvas draws nothing).
+function stubCanvas() {
+ const texts = [];
+ const ctx = new Proxy({}, {
+ get: (target, key) => {
+ if (key in target) return target[key];
+ if (key === 'fillText') return (text) => texts.push(text);
+ if (key === 'measureText') return (text) => ({ width: String(text).length * 10 });
+ if (key === 'createRadialGradient') return () => ({ addColorStop() {} });
+ return () => {};
+ },
+ set: (target, key, value) => { target[key] = value; return true; },
+ });
+ const spy = vi.spyOn(window.HTMLCanvasElement.prototype, 'getContext').mockReturnValue(ctx);
+ return { texts, restore: () => spy.mockRestore() };
+}
+
+describe('cutting room floor ending', () => {
+ // Uniquely catches the ending never reaching the player: it must follow the song and leave when the song plays again.
+ it('plays after the song ends, from Ending, and leaves when the song plays', async () => {
+ const play = vi.spyOn(window.HTMLMediaElement.prototype, 'play').mockImplementation(() => Promise.resolve());
+ const canvas = stubCanvas();
+ // The scene's own clock holds at its first frame.
+ const raf = vi.spyOn(window, 'requestAnimationFrame').mockImplementation(() => 1);
+ const project = { id: 'p', scenes, statsOutro: { enabled: true, durationSec: 6 } };
+ render(<StoryboardAnimatic project={project} audioUrl="/song.mp3" />);
+ expect(screen.queryByTestId('animatic-stats-outro')).toBeNull();
+ const audio = screen.getByLabelText('Song for the storyboard animatic');
+ act(() => { audio.dispatchEvent(new Event('ended')); });
+ expect(screen.getByTestId('animatic-stats-outro')).toBeTruthy();
+ await waitFor(() => expect(getMusicVideoOutroStats).toHaveBeenCalledWith('p', { silent: true }));
+ expect(canvas.texts).toContain('THE CUTTING ROOM FLOOR');
+ fireEvent.play(audio);
+ expect(screen.queryByTestId('animatic-stats-outro')).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: /Ending/ }));
+ await act(async () => {});
+ expect(screen.getByTestId('animatic-stats-outro')).toBeTruthy();
+ canvas.restore();
+ raf.mockRestore();
+ play.mockRestore();
+ });
+
+ it('offers no ending while it is off', () => {
+ render(<StoryboardAnimatic project={{ id: 'p', scenes, statsOutro: { enabled: false, durationSec: 6 } }} audioUrl="/song.mp3" />);
+ expect(screen.queryByRole('button', { name: /Ending/ })).toBeNull();
+ const audio = screen.getByLabelText('Song for the storyboard animatic');
+ act(() => { audio.dispatchEvent(new Event('ended')); });
+ expect(screen.queryByTestId('animatic-stats-outro')).toBeNull();
+ });
+
+ it('turns on with its default length and saves a new length', () => {
+ const onSave = vi.fn(async () => {});
+ const onEditLocal = vi.fn();
+ const { rerender } = render(<StatsOutroPanel project={{ id: 'p', statsOutro: null }} onEditLocal={onEditLocal} onSave={onSave} />);
+ fireEvent.click(screen.getByLabelText('Off'));
+ expect(onSave).toHaveBeenLastCalledWith({ statsOutro: { enabled: true, durationSec: 8 } });
+ rerender(<StatsOutroPanel project={{ id: 'p', statsOutro: { enabled: true, durationSec: 8 } }} onEditLocal={onEditLocal} onSave={onSave} />);
+ fireEvent.change(screen.getByLabelText('Length'), { target: { value: '12' } });
+ expect(onSave).toHaveBeenLastCalledWith({ statsOutro: { enabled: true, durationSec: 12 } });
+ });
+});
diff --git a/client/src/components/musicVideo/StatsOutroCanvas.jsx b/client/src/components/musicVideo/StatsOutroCanvas.jsx
new file mode 100644
index 0000000000..4d050f24a9
--- /dev/null
+++ b/client/src/components/musicVideo/StatsOutroCanvas.jsx
@@ -0,0 +1,78 @@
+import { useEffect, useRef, useState } from 'react';
+import { STATS_OUTRO_FONTS, drawStatsOutro } from '../../../../server/lib/musicVideoStatsOutro.js';
+
+// The canvas the animatic paints at; CSS scales it to the figure. The final render paints at the cut's own size.
+const WIDTH = 1280;
+const HEIGHT = 720;
+
+let facesAdded = false;
+// The outro's faces (the same bundled files the render page declares), registered once per page.
+function addOutroFaces() {
+ if (facesAdded || typeof FontFace !== 'function' || !document.fonts?.add) return;
+ facesAdded = true;
+ for (const { family, file } of Object.values(STATS_OUTRO_FONTS)) {
+ document.fonts.add(new FontFace(family, `url(/fonts/title-card/${file})`, { weight: '100 900' }));
+ }
+}
+
+// A gallery PNG has a small WebP beside it; the floor never needs the full still.
+const floorSrc = (imageId) => (/\.png$/i.test(imageId)
+ ? `/data/image-thumbnails/${encodeURIComponent(imageId.replace(/\.png$/i, '.webp'))}`
+ : `/data/images/${encodeURIComponent(imageId)}`);
+
+/**
+ * The cutting room floor outro (lib/musicVideoStatsOutro.js) at scene time
+ * `t`, painted by the same function the final render captures. `stats` is the
+ * server's tally (null while it loads: the floor and plate draw, the numbers
+ * read zero until it lands).
+ */
+export default function StatsOutroCanvas({ stats, t, durationSec }) {
+ const canvasRef = useRef(null);
+ const [images, setImages] = useState([]);
+ const [fontsReady, setFontsReady] = useState(0);
+ const floor = stats?.floorImages;
+
+ useEffect(() => {
+ addOutroFaces();
+ let active = true;
+ document.fonts?.load?.(`800 40px "${STATS_OUTRO_FONTS.head.family}"`)
+ .then(() => document.fonts.load(`500 40px "${STATS_OUTRO_FONTS.body.family}"`))
+ .then(() => { if (active) setFontsReady((n) => n + 1); })
+ .catch(() => {});
+ return () => { active = false; };
+ }, []);
+
+ useEffect(() => {
+ let active = true;
+ const loaded = (floor || []).map(() => null);
+ setImages(loaded);
+ (floor || []).forEach((imageId, i) => {
+ const img = new Image();
+ img.onload = () => {
+ if (!active) return;
+ loaded[i] = img;
+ setImages([...loaded]);
+ };
+ img.src = floorSrc(imageId);
+ });
+ return () => { active = false; };
+ }, [floor]);
+
+ useEffect(() => {
+ const ctx = canvasRef.current?.getContext?.('2d');
+ if (!ctx) return;
+ drawStatsOutro(ctx, { width: WIDTH, height: HEIGHT, t, durationSec, stats, images });
+ }, [t, durationSec, stats, images, fontsReady]);
+
+ return (
+ <canvas
+ ref={canvasRef}
+ width={WIDTH}
+ height={HEIGHT}
+ role="img"
+ aria-label="The cutting room floor: what was made, kept and left out of this video"
+ className="pointer-events-none absolute inset-0 h-full w-full"
+ data-testid="animatic-stats-outro"
+ />
+ );
+}
diff --git a/client/src/components/musicVideo/StatsOutroPanel.jsx b/client/src/components/musicVideo/StatsOutroPanel.jsx
new file mode 100644
index 0000000000..9378931649
--- /dev/null
+++ b/client/src/components/musicVideo/StatsOutroPanel.jsx
@@ -0,0 +1,50 @@
+import { Scissors } from 'lucide-react';
+import { STATS_OUTRO_DEFAULTS, normalizeStatsOutro } from '../../../../server/lib/musicVideoStatsOutro.js';
+
+// Lengths offered for the scene, in seconds (inside STATS_OUTRO_LIMITS).
+const LENGTHS = [4, 6, 8, 10, 12, 15, 20];
+
+/**
+ * The cutting room floor ending (lib/musicVideoStatsOutro.js): an optional
+ * scene after the song tallying what was made, kept and turned down. Off by
+ * default; on, it plays in the storyboard animatic when the song ends (or from
+ * its Ending button) and is added after the song in the final render.
+ */
+export default function StatsOutroPanel({ project, onEditLocal, onSave }) {
+ const outro = normalizeStatsOutro(project.statsOutro);
+ const on = !!outro?.enabled;
+ const commit = (patch) => {
+ const next = normalizeStatsOutro({ ...(outro || STATS_OUTRO_DEFAULTS), ...patch });
+ onEditLocal({ statsOutro: next });
+ return onSave({ statsOutro: next });
+ };
+ const lengths = LENGTHS.includes(outro?.durationSec) || !outro ? LENGTHS : [...LENGTHS, outro.durationSec].sort((a, b) => a - b);
+ return (
+ <section aria-label="Cutting room floor ending" className="space-y-2 rounded-lg border border-port-border bg-port-card p-2">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <h3 className="inline-flex items-center gap-1.5 text-sm font-medium">
+ <Scissors size={14} className="text-port-accent" aria-hidden="true" /> Cutting room floor ending
+ <span className="text-xs font-normal text-port-text-muted">Optional</span>
+ </h3>
+ <label htmlFor="mv-stats-outro-on" className="inline-flex min-h-[44px] items-center gap-2 text-xs text-port-text-muted sm:min-h-0">
+ {on ? `On · ${outro.durationSec}s after the song` : 'Off'}
+ <input id="mv-stats-outro-on" type="checkbox" checked={on} onChange={(e) => commit({ enabled: e.target.checked })} className="h-4 w-4" />
+ </label>
+ </div>
+ {on && (
+ <div className="flex flex-wrap items-end gap-x-4 gap-y-2">
+ <div>
+ <label htmlFor="mv-stats-outro-length" className="mb-0.5 block text-xs text-port-text-muted">Length</label>
+ <select id="mv-stats-outro-length" value={outro.durationSec} onChange={(e) => commit({ durationSec: Number(e.target.value) })}
+ className="min-h-[44px] rounded border border-port-border bg-port-bg px-2 py-1 text-sm sm:min-h-0">
+ {lengths.map((sec) => <option key={sec} value={sec}>{sec}s</option>)}
+ </select>
+ </div>
+ <p className="min-w-0 flex-1 basis-48 text-xs text-port-text-muted">
+ Stills and clips made against the ones in the cut, takes rejected, transitions, effects, camera moves and lip-syncs, over the unused stills. Ending plays it in the player.
+ </p>
+ </div>
+ )}
+ </section>
+ );
+}
diff --git a/client/src/components/musicVideo/StoryboardAnimatic.jsx b/client/src/components/musicVideo/StoryboardAnimatic.jsx
index 69005af85d..459a4374d9 100644
--- a/client/src/components/musicVideo/StoryboardAnimatic.jsx
+++ b/client/src/components/musicVideo/StoryboardAnimatic.jsx
@@ -2,13 +2,15 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import FilmLookFrame from '../media/FilmLookFrame.jsx';
import { safeReadStorage, safeWriteStorage } from '../../lib/safeStorage.js';
import { isFilmLookNeutral } from '../../lib/filmLook.js';
-import { Captions, Film } from 'lucide-react';
+import { Captions, Film, Scissors } from 'lucide-react';
import { formatDurationSec } from '../../utils/formatters.js';
-import { getMusicVideoLyricOverlayPreview } from '../../services/apiMusicVideo.js';
+import { getMusicVideoLyricOverlayPreview, getMusicVideoOutroStats } from '../../services/apiMusicVideo.js';
import { playthroughVersion } from './CompositionPreviewPlayer.jsx';
import { useVideoFileSrc } from '../../hooks/useVideoFileSrc.js';
import { selectedPerformanceInstruction } from '../../lib/musicVideoShotTiming.js';
import { normalizeTitleCard } from '../../../../server/lib/musicVideoTitleCard.js';
+import { statsOutroSeconds } from '../../../../server/lib/musicVideoStatsOutro.js';
+import StatsOutroCanvas from './StatsOutroCanvas.jsx';
import ShotStepper from './ShotStepper.jsx';
import FrameStepper, { captureMediaFrame } from './FrameStepper.jsx';
import { sceneFrameFit } from './SceneFrameFit.jsx';
@@ -237,6 +239,53 @@ function ShotClip({ scene, audioRef, time, current }) {
);
}
+/**
+ * The cutting room floor outro after the song (lib/musicVideoStatsOutro.js):
+ * when the song ends it plays for its own length on a clock of its own, and
+ * Ending plays it straight away. Playing or seeking the song leaves it. The
+ * tally is fetched each time it starts, so it counts the latest choices.
+ * Returns `{ seconds, t, active, start, stop }` (`t` null while it is off screen).
+ */
+function useStatsOutro({ project, audioRef }) {
+ const seconds = statsOutroSeconds(project.statsOutro);
+ const [t, setT] = useState(null);
+ const [stats, setStats] = useState(null);
+ const run = useRef({ handle: 0, startedAt: 0, generation: 0 });
+ const stop = useCallback(() => {
+ cancelAnimationFrame(run.current.handle);
+ run.current.generation += 1;
+ setT(null);
+ }, []);
+ const start = useCallback(() => {
+ if (!(seconds > 0)) return;
+ cancelAnimationFrame(run.current.handle);
+ const generation = ++run.current.generation;
+ run.current.startedAt = performance.now();
+ setT(0);
+ getMusicVideoOutroStats(project.id, { silent: true })
+ .then((next) => { if (run.current.generation === generation) setStats(next?.stats || null); })
+ .catch(() => {});
+ const tick = () => {
+ if (run.current.generation !== generation) return;
+ const elapsed = (performance.now() - run.current.startedAt) / 1000;
+ // It holds on its last (black) frame once it has run its length.
+ setT(Math.min(elapsed, seconds));
+ if (elapsed < seconds) run.current.handle = requestAnimationFrame(tick);
+ };
+ run.current.handle = requestAnimationFrame(tick);
+ }, [seconds, project.id]);
+ // A different video, or the outro turned off, leaves it.
+ useEffect(() => { stop(); setStats(null); }, [project.id, seconds, stop]);
+ useEffect(() => () => cancelAnimationFrame(run.current.handle), []);
+ useEffect(() => {
+ const audio = audioRef.current;
+ if (!audio || !(seconds > 0)) return undefined;
+ audio.addEventListener('ended', start);
+ return () => audio.removeEventListener('ended', start);
+ }, [audioRef, seconds, start]);
+ return { seconds, t, stats, active: t != null, start, stop };
+}
+
/**
* Something to watch before anything is rendered: the master song under the
* storyboard, showing each shot's selected video clip (muted, in step with the
@@ -261,6 +310,8 @@ export default function StoryboardAnimatic({ project, audioUrl, seekRequest, col
const scenes = project.scenes || [];
const lyricsAvailable = hasTimedLyrics(project);
const { overlay, failed } = useLyricOverlay({ project, enabled: lyricsAvailable && lyricsOn, audioRef, time });
+ const outro = useStatsOutro({ project, audioRef });
+ const songEndSec = Number(project.audioAnalysis?.durationSec) || 0;
useEffect(() => {
if (!seekRequest || applied.current === seekRequest.n || !audioRef.current) return;
applied.current = seekRequest.n;
@@ -306,7 +357,8 @@ export default function StoryboardAnimatic({ project, audioUrl, seekRequest, col
<div className={`space-y-2 ${collapsed ? 'max-xl:hidden' : ''}`}>
<figure ref={figureRef} aria-label="Storyboard animatic" className="relative aspect-video w-full overflow-hidden rounded border border-port-border bg-black">
{/* The project's film look, as the final render applies it over the whole picture, lyrics included. */}
- <FilmLookFrame look={lookOn ? project.filmLook : null} frame={Math.round(time * ANIMATIC_FPS)} playing={playing} className="h-full w-full">
+ <FilmLookFrame look={lookOn ? project.filmLook : null} frame={Math.round((outro.active ? songEndSec + outro.t : time) * ANIMATIC_FPS)}
+ playing={playing || (outro.active && outro.t < outro.seconds)} className="h-full w-full">
{shot?.referenceImageId && shotEffect ? (
<ImageEffectStill key={shot.sceneId} src={`/data/images/${shot.referenceImageId}`} effect={shotEffect}
endSrc={shot.endImageId ? `/data/images/${shot.endImageId}` : null}
@@ -328,6 +380,7 @@ export default function StoryboardAnimatic({ project, audioUrl, seekRequest, col
<TransitionGlitch scenes={scenes} figureRef={figureRef} audioRef={audioRef} time={time} layered={layered}
endSec={Number(project.audioAnalysis?.durationSec) || null} fps={ANIMATIC_FPS} />
{overlay}
+ {outro.active && <StatsOutroCanvas stats={outro.stats} t={outro.t} durationSec={outro.seconds} />}
</FilmLookFrame>
</figure>
<div className="flex min-w-0 flex-wrap items-center gap-2">
@@ -345,6 +398,21 @@ export default function StoryboardAnimatic({ project, audioUrl, seekRequest, col
)}
{lyricsOn && failed && <p className="text-port-error">The lyrics could not be drawn over the animatic.</p>}
</div>
+ {outro.seconds > 0 && (
+ <button
+ type="button"
+ onClick={() => {
+ if (outro.active) { outro.stop(); return; }
+ audioRef.current?.pause?.();
+ outro.start();
+ }}
+ aria-pressed={outro.active}
+ title={`The cutting room floor scene that plays for ${outro.seconds}s after the song`}
+ className={`flex min-h-[44px] shrink-0 items-center gap-1 rounded border px-2 text-xs sm:min-h-0 sm:py-1 ${outro.active ? 'border-port-accent text-port-accent' : 'border-port-border text-port-text-muted'}`}
+ >
+ <Scissors size={14} aria-hidden="true" /> Ending
+ </button>
+ )}
{lookAvailable && (
<button
type="button"
@@ -385,8 +453,8 @@ export default function StoryboardAnimatic({ project, audioUrl, seekRequest, col
preload="metadata"
aria-label="Song for the storyboard animatic"
onTimeUpdate={(e) => setTime(e.currentTarget.currentTime)}
- onSeeked={(e) => setTime(e.currentTarget.currentTime)}
- onPlay={() => setPlaying(true)}
+ onSeeked={(e) => { outro.stop(); setTime(e.currentTarget.currentTime); }}
+ onPlay={() => { outro.stop(); setPlaying(true); }}
onPause={() => setPlaying(false)}
onEnded={() => setPlaying(false)}
className="w-full"
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index e2ca68d9de..0271d0b834 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -73,6 +73,7 @@ import ProjectSettingsDrawer, { SETTINGS_TAB_IDS } from '../components/musicVide
import MusicVideoProjectCard from '../components/musicVideo/MusicVideoProjectCard.jsx';
import PreviewDock from '../components/musicVideo/PreviewDock.jsx';
import TitleCardPanel from '../components/musicVideo/TitleCardPanel.jsx';
+import StatsOutroPanel from '../components/musicVideo/StatsOutroPanel.jsx';
import NeedsAttentionBanner from '../components/musicVideo/NeedsAttentionBanner.jsx';
import SetupStage from '../components/musicVideo/stages/SetupStage.jsx';
import StageChecklist from '../components/musicVideo/StageChecklist.jsx';
@@ -1200,6 +1201,7 @@ export default function MusicVideo() {
{dock}
<TitleCardPanel project={selected} onEditLocal={editProjectLocal} onSave={saveProjectFields}
onPreview={(startSec) => seekToScene({ startSec }, { play: true })} />
+ <StatsOutroPanel project={selected} onEditLocal={editProjectLocal} onSave={saveProjectFields} />
</div>
));
const board = selected ? {
diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.js
index 6ee56dd32c..dfd4679974 100644
--- a/client/src/services/apiMusicVideo.js
+++ b/client/src/services/apiMusicVideo.js
@@ -173,6 +173,8 @@ export const selectMusicVideoSceneTake = (id, sceneId, takeId, options = {}) =>
request(`${takesPath(id, sceneId)}/${encodeURIComponent(takeId)}/select`, { method: 'POST', ...options });
// The project's unused stills and clips (the shot card's "Swap from unused") → { collectionId, items }.
export const getMusicVideoMediaPool = (id, options = {}) => request(`/music-video/${encodeURIComponent(id)}/media-pool`, options);
+/** The cutting room floor outro's tally for a video: `{ stats }`. */
+export const getMusicVideoOutroStats = (id, options = {}) => request(`/music-video/${encodeURIComponent(id)}/stats-outro`, options);
// Asset manager: mark unused pool items ★ 'ingredient' / ✕ 'bad' (null clears) → { assetMarks }.
export const markMusicVideoPoolAssets = (id, items, mark, options = {}) => request(`/music-video/${encodeURIComponent(id)}/media-pool/marks`, {
method: 'PATCH', body: JSON.stringify({ items, mark }), ...options,
diff --git a/server/lib/README.md b/server/lib/README.md
index 7d7cb0e0cd..49cda9bb9e 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -865,6 +865,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `musicVideoGrade.js` | Opt-in Music Video grade presets, bounded normalization, and shared song-timed RGB curves with deterministic grain for composed and document encodes. |
| `filmLook.js` | The film look: `FILM_LOOK_CONTROLS` (sliders, colors, toggles with their photography terms and prompt words), `FILM_LOOK_PRESETS`, `normalizeFilmLook`, `isFilmLookNeutral`, `describeFilmLook` (the look as prompt vocabulary), `filmLookFilterMarkup` (the one SVG filter the live preview, the document render and gallery bakes apply, frame-seeded), `filmLookMotionLayers` (the same look as CSS filter functions plus blended overlays a playing video can afford) and `filmLookRuntimeSource` (the page script that applies and re-seeds it per seek). Browser-safe. |
| `filmLookValidation.js` | `filmLookSchema` / `filmLookBakeSchema`: the Zod shape of a film look, derived from `FILM_LOOK_CONTROLS`. |
+| `musicVideoStatsOutro.js` | The cutting room floor outro: an optional scene after the song tallying the director's choices. `normalizeStatsOutro`, `statsOutroSeconds`, `musicVideoOutroStats` (the counts from the project's takes, selections, marks and media collection), `drawStatsOutro` (the one canvas painter the animatic and the final render share) and `statsOutroPageSource` (the render page's script). Browser-safe. |
| `musicVideoTitleCard.js` | The MTV-style opening title card (song, artist, year over the opener): `normalizeTitleCard`, `titleCardVisible`, `titleCardPrefill` (a new card's text and a window ending before the first sung line), and `titleCardRuntimeSource` (the page script the live preview and the document render install to draw it per seek, with its fade and title-safe layout). Browser-safe. |
| `musicVideoDependencies.js` | Versioned take/evidence provenance, dependency comparisons and bounded selective-repair previews. |
| `musicVideoEndFrame.js` | Style-break end frames (#11173): `sceneEndFramePlan(scene, { backend, falModelId })` says whether a clip sends the scene's end frame (only fal models with an end image, never a performance shot) and why not; `sceneEndFrameRequestFields` turns it into `lastImageFile`. Shared by the board and production. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 075cdf3108..5fd0a0d252 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -840,6 +840,7 @@ export * from './musicVideoActionContract.js';
export * from './musicVideoGrade.js';
export * from './filmLook.js';
export * from './filmLookValidation.js';
+export * from './musicVideoStatsOutro.js';
export * from './musicVideoTitleCard.js';
export * from './musicVideoDependencies.js';
export * from './musicVideoEndFrame.js';
diff --git a/server/lib/musicVideoStatsOutro.js b/server/lib/musicVideoStatsOutro.js
new file mode 100644
index 0000000000..ded9dc981d
--- /dev/null
+++ b/server/lib/musicVideoStatsOutro.js
@@ -0,0 +1,349 @@
+/**
+ * Music Video — the cutting room floor outro: an optional closing scene that
+ * plays after the song ends and tallies the human choices behind the video
+ * (stills and clips made against the ones in the cut, takes rejected,
+ * transitions, image effects, camera moves, lip-sync shots), over a floor of
+ * the stills that did not make it. One record on the project
+ * (`project.statsOutro`, null = off) turns it on and sets how long it runs;
+ * it adds that time after the song and never shortens it.
+ *
+ * Every count comes from what the project records (`musicVideoOutroStats`):
+ * its shots' takes and selections, its media collection and its asset marks.
+ * Media deleted from the library drops out of the counts with it.
+ *
+ * `drawStatsOutro` is the one painter for the storyboard animatic (a canvas
+ * over the picture) and the final render (a page captured frame by frame and
+ * appended to the cut), so both show the same frames. Every frame is a pure
+ * function of the scene's own time. Browser-safe, no imports.
+ */
+
+export const STATS_OUTRO_LIMITS = Object.freeze({ durationMin: 4, durationMax: 20 });
+export const STATS_OUTRO_DEFAULTS = Object.freeze({ enabled: false, durationSec: 8 });
+/** How many unused stills lie on the floor behind the tally. */
+export const STATS_OUTRO_FLOOR_MAX = 14;
+/** The fonts the scene draws in (bundled OFL faces, registered by each page). */
+export const STATS_OUTRO_FONTS = Object.freeze({
+ head: Object.freeze({ family: 'MV Archivo', file: 'archivo-variable.woff2' }),
+ body: Object.freeze({ family: 'MV Mono', file: 'ibm-plex-mono-500.woff2' }),
+});
+
+/** A stored outro from any input (null for none). */
+export function normalizeStatsOutro(input) {
+ if (!input || typeof input !== 'object' || Array.isArray(input)) return null;
+ const { durationMin, durationMax } = STATS_OUTRO_LIMITS;
+ const raw = typeof input.durationSec === 'number' && Number.isFinite(input.durationSec) ? input.durationSec : STATS_OUTRO_DEFAULTS.durationSec;
+ return {
+ enabled: typeof input.enabled === 'boolean' ? input.enabled : STATS_OUTRO_DEFAULTS.enabled,
+ durationSec: Math.round(Math.min(durationMax, Math.max(durationMin, raw)) * 10) / 10,
+ };
+}
+
+/** The seconds the outro adds after the song (0 when it is off). */
+export function statsOutroSeconds(input) {
+ const outro = normalizeStatsOutro(input);
+ return outro?.enabled ? outro.durationSec : 0;
+}
+
+const SLOT_KINDS = Object.freeze({ referenceImageId: 'image', endImageId: 'image', videoHistoryId: 'video' });
+const TAKE_KINDS = Object.freeze({ image: 'image', endImage: 'image', video: 'video' });
+
+/**
+ * The tally from what the project records. `collectionItems` are the rows of
+ * the video's media collection (`{ kind, ref }`): every still and clip made
+ * for it, including ones no shot holds any more. Returns
+ * `{ stills: { made, kept }, clips: { made, kept }, rejected, shots, lipSyncs,
+ * transitions, imageEffects, cameraMoves, floorImages }` — `kept` is what a
+ * shot uses now, `rejected` the takes rejected or marked ✕ bad, and
+ * `floorImages` up to STATS_OUTRO_FLOOR_MAX unused stills (rejected first) to
+ * lay on the floor. Pure.
+ */
+export function musicVideoOutroStats(project, { collectionItems = [] } = {}) {
+ const scenes = Array.isArray(project?.scenes) ? project.scenes : [];
+ const made = new Set();
+ const used = new Set();
+ const rejected = new Set();
+ const marks = project?.assetMarks && typeof project.assetMarks === 'object' ? project.assetMarks : {};
+ const note = (kind, ref) => (kind && typeof ref === 'string' && ref ? `${kind}:${ref}` : null);
+ for (const item of Array.isArray(collectionItems) ? collectionItems : []) {
+ const key = item?.kind === 'image' || item?.kind === 'video' ? note(item.kind, item.ref) : null;
+ if (key) made.add(key);
+ }
+ let lipSyncs = 0;
+ let transitions = 0;
+ let imageEffects = 0;
+ let cameraMoves = 0;
+ for (const scene of scenes) {
+ for (const take of Array.isArray(scene?.takes) ? scene.takes : []) {
+ const key = note(TAKE_KINDS[take?.kind], take?.assetId);
+ if (!key) continue;
+ made.add(key);
+ if (take.status === 'rejected') rejected.add(key);
+ }
+ for (const [field, kind] of Object.entries(SLOT_KINDS)) {
+ const key = note(kind, scene?.[field]);
+ if (key) { made.add(key); used.add(key); }
+ }
+ if (scene?.shotMode === 'performance') lipSyncs += 1;
+ if (scene?.transitionIn) transitions += 1;
+ if (scene?.transitionOut) transitions += 1;
+ if (scene?.imageEffect) imageEffects += 1;
+ if (scene?.camera?.move) cameraMoves += 1;
+ }
+ for (const [key, mark] of Object.entries(marks)) {
+ if (mark === 'bad' && made.has(key)) rejected.add(key);
+ }
+ // A take put back on a shot is no longer a rejection.
+ for (const key of used) rejected.delete(key);
+ const count = (keys, kind) => [...keys].filter((key) => key.startsWith(`${kind}:`)).length;
+ const unusedStills = [...made].filter((key) => key.startsWith('image:') && !used.has(key)).sort();
+ const floorPick = [...unusedStills.filter((key) => rejected.has(key)), ...unusedStills.filter((key) => !rejected.has(key))];
+ // Spread over the whole pile rather than its first few, so the floor shows the project's range.
+ const step = floorPick.length > STATS_OUTRO_FLOOR_MAX ? floorPick.length / STATS_OUTRO_FLOOR_MAX : 1;
+ const floorImages = [];
+ for (let i = 0; i < Math.min(STATS_OUTRO_FLOOR_MAX, floorPick.length); i++) floorImages.push(floorPick[Math.floor(i * step)].slice('image:'.length));
+ return {
+ stills: { made: count(made, 'image'), kept: count(used, 'image') },
+ clips: { made: count(made, 'video'), kept: count(used, 'video') },
+ rejected: rejected.size,
+ shots: scenes.length,
+ lipSyncs,
+ transitions,
+ imageEffects,
+ cameraMoves,
+ floorImages,
+ };
+}
+
+/* The functions below are inlined into the render page by toString()
+ * (statsOutroPageSource), so each must stay self-contained: no references to
+ * module scope, only to each other by name. */
+
+/**
+ * The tally's lines, in order: `{ label, value, accent? }`. Stills and clips
+ * always show; a choice the director never made (no transitions, say) is left
+ * out rather than shown as a zero. The last line is what was left on the floor.
+ */
+function statsOutroRows(stats) {
+ const n = (v) => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? Math.round(v) : 0);
+ const s = stats || {};
+ const stills = s.stills || {};
+ const clips = s.clips || {};
+ const rows = [
+ { label: 'Stills made', value: n(stills.made) },
+ { label: 'Clips made', value: n(clips.made) },
+ { label: 'Takes rejected', value: n(s.rejected), optional: true },
+ { label: 'Transitions placed', value: n(s.transitions), optional: true },
+ { label: 'Image effects', value: n(s.imageEffects), optional: true },
+ { label: 'Camera moves', value: n(s.cameraMoves), optional: true },
+ { label: 'Lip-sync shots', value: n(s.lipSyncs), optional: true },
+ { label: 'Shots in the cut', value: n(s.shots) },
+ ].filter((row) => !row.optional || row.value > 0).map(({ label, value }) => ({ label, value }));
+ const floor = Math.max(0, n(stills.made) - n(stills.kept)) + Math.max(0, n(clips.made) - n(clips.kept));
+ rows.push({ label: 'Left on the floor', value: floor, accent: true });
+ return rows;
+}
+
+/**
+ * Paint the outro at scene time `t` (0 = the song's last frame) on a
+ * width × height 2D context. `images[i]` is the loaded still for
+ * `stats.floorImages[i]` (null while loading, or when none). Everything sits
+ * inside the title-safe area and shrinks to fit, at any aspect.
+ */
+function drawStatsOutro(ctx, { width, height, t, durationSec, stats, images = [], fonts = {} }) {
+ const head = fonts.head || '"MV Archivo", "Arial Black", Impact, sans-serif';
+ const body = fonts.body || '"MV Mono", Menlo, Consolas, "Courier New", monospace';
+ const clamp = (v) => (v < 0 ? 0 : v > 1 ? 1 : v);
+ const ease = (p) => 1 - Math.pow(1 - clamp(p), 3);
+ const D = Math.max(1, Number(durationSec) || 8);
+ const unit = Math.min(width, height);
+ // Deterministic scatter: the same print lands in the same place on every frame and every page.
+ const hash = (i, salt) => {
+ const x = Math.sin((i + 1) * 12.9898 + salt * 78.233) * 43758.5453;
+ return x - Math.floor(x);
+ };
+ ctx.save();
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
+ ctx.globalAlpha = 1;
+ // The floor: a dark, warm edit-bay floor lit from above.
+ const floorGrad = ctx.createRadialGradient(width / 2, height * 0.42, unit * 0.1, width / 2, height / 2, Math.max(width, height) * 0.75);
+ floorGrad.addColorStop(0, '#2a2420');
+ floorGrad.addColorStop(1, '#0b0908');
+ ctx.fillStyle = floorGrad;
+ ctx.fillRect(0, 0, width, height);
+
+ // Prints and film offcuts dropped on the floor, landing one after another.
+ const prints = Math.max(8, (stats && Array.isArray(stats.floorImages) ? stats.floorImages.length : 0));
+ for (let i = 0; i < prints; i++) {
+ const land = ease((t - 0.1 - i * 0.07) / 0.5);
+ if (land <= 0) continue;
+ const size = unit * (0.2 + hash(i, 1) * 0.1);
+ const w = size * 1.25;
+ const h = size;
+ const x = (((i * 0.618034) + hash(i, 2) * 0.2) % 1) * (width + w) - w / 2;
+ const y = (((i * 0.381966) + hash(i, 3) * 0.3) % 1) * (height + h) - h / 2 + (1 - land) * -unit * 0.05;
+ const drift = t * unit * 0.004 * (0.5 + hash(i, 4));
+ const angle = (hash(i, 5) - 0.5) * 0.7;
+ ctx.save();
+ ctx.translate(x + drift, y);
+ ctx.rotate(angle);
+ ctx.scale(1 + (1 - land) * 0.12, 1 + (1 - land) * 0.12);
+ ctx.globalAlpha = land * 0.85;
+ const img = images[i] || null;
+ const iw = img ? img.naturalWidth || img.width : 0;
+ const ih = img ? img.naturalHeight || img.height : 0;
+ if (iw > 0 && ih > 0) {
+ // A print: a cream border around the still, cropped to fill.
+ const border = size * 0.05;
+ ctx.fillStyle = '#e9e1cf';
+ ctx.fillRect(-w / 2 - border, -h / 2 - border, w + border * 2, h + border * 2.6);
+ const scale = Math.max(w / iw, h / ih);
+ const sw = w / scale;
+ const sh = h / scale;
+ ctx.drawImage(img, (iw - sw) / 2, (ih - sh) / 2, sw, sh, -w / 2, -h / 2, w, h);
+ } else {
+ // A strip of film: dark frame, sprocket holes along both edges.
+ ctx.fillStyle = '#1b1715';
+ ctx.fillRect(-w / 2, -h / 2, w, h);
+ ctx.fillStyle = '#3a312b';
+ const hole = h * 0.07;
+ for (let k = 0; k < 6; k++) {
+ const hx = -w / 2 + (k + 0.5) * (w / 6) - hole / 2;
+ ctx.fillRect(hx, -h / 2 + hole * 0.6, hole, hole * 0.8);
+ ctx.fillRect(hx, h / 2 - hole * 1.4, hole, hole * 0.8);
+ }
+ ctx.fillStyle = '#2b2420';
+ ctx.fillRect(-w / 2 + w * 0.06, -h / 2 + hole * 2, w * 0.88, h - hole * 4);
+ }
+ ctx.restore();
+ }
+ // The prints sit in shadow, under the tally.
+ ctx.fillStyle = 'rgba(8, 6, 5, 0.5)';
+ ctx.fillRect(0, 0, width, height);
+
+ // The tally: an edit log on a dark plate, inside the title-safe area.
+ const rows = statsOutroRows(stats);
+ const insetX = width * 0.1;
+ const insetY = height * 0.1;
+ const safeW = width - insetX * 2;
+ const safeH = height - insetY * 2;
+ const panelW = height > width ? safeW : Math.min(safeW, Math.max(safeW * 0.62, unit * 1.1));
+ const measure = (text, font) => { ctx.font = font; return ctx.measureText(text).width; };
+ const fmt = (v) => String(Math.round(v)).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
+ const pad = 0.9; // plate padding, in row heights
+ const lineH = 1.5;
+ const headScale = 1.45;
+ // Fit the block's height first, then its widest line.
+ // Plate: padding, heading, a gap, the rows, a foot, padding (in units of the row size).
+ const blockUnits = pad + headScale + 0.6 + rows.length * lineH + 0.5 + pad;
+ let px = safeH / blockUnits;
+ const rowFont = (size, weight = 500) => `${weight} ${Math.floor(size * 100) / 100}px ${body}`;
+ const headFont = (size) => `800 ${Math.floor(size * 100) / 100}px ${head}`;
+ const headText = 'THE CUTTING ROOM FLOOR';
+ const widest = (size) => Math.max(
+ measure(headText, headFont(size * headScale)) + size * pad * 2,
+ ...rows.map((row) => measure(row.label.toUpperCase(), rowFont(size)) + measure(fmt(Math.max(row.value, 1000)), rowFont(size, 600)) + size * (2 + pad * 2)),
+ );
+ const wide = widest(px);
+ if (wide > panelW) px *= panelW / wide;
+ const plateW = Math.min(panelW, widest(px));
+ const plateH = px * blockUnits;
+ const left = (width - plateW) / 2;
+ const top = (height - plateH) / 2;
+ const plateIn = ease((t - 0.25) / 0.6);
+ ctx.globalAlpha = plateIn;
+ ctx.fillStyle = 'rgba(14, 11, 9, 0.86)';
+ ctx.fillRect(left, top, plateW, plateH);
+ ctx.strokeStyle = 'rgba(243, 196, 107, 0.55)';
+ ctx.lineWidth = Math.max(1, px * 0.06);
+ ctx.strokeRect(left + px * 0.25, top + px * 0.25, plateW - px * 0.5, plateH - px * 0.5);
+ ctx.textBaseline = 'alphabetic';
+ ctx.textAlign = 'center';
+ ctx.font = headFont(px * headScale);
+ ctx.fillStyle = '#f3ead7';
+ const headY = top + px * pad + px * headScale;
+ ctx.fillText(headText, width / 2, headY);
+ // A rule under the heading.
+ ctx.fillStyle = 'rgba(243, 196, 107, 0.7)';
+ ctx.fillRect(left + px * pad, headY + px * 0.45, plateW - px * pad * 2, Math.max(1, px * 0.06));
+ // Rows arrive one by one in the first half of the scene, each counting up to its number.
+ const firstRow = 0.9;
+ const stagger = Math.min(0.4, Math.max(0.12, (D * 0.5 - firstRow) / Math.max(1, rows.length)));
+ rows.forEach((row, i) => {
+ const start = firstRow + i * stagger;
+ const show = ease((t - start) / 0.35);
+ if (show <= 0) return;
+ const counted = row.value * ease((t - start) / 0.9);
+ const y = headY + px * 0.6 + px * lineH * (i + 1) + (1 - show) * px * 0.4;
+ ctx.globalAlpha = plateIn * show;
+ if (row.accent) {
+ ctx.fillStyle = 'rgba(255, 122, 61, 0.14)';
+ ctx.fillRect(left + px * pad * 0.6, y - px * 1.1, plateW - px * pad * 1.2, px * 1.5);
+ }
+ ctx.font = rowFont(px, row.accent ? 600 : 500);
+ ctx.textAlign = 'left';
+ ctx.fillStyle = row.accent ? '#ff8a4c' : '#e8c27a';
+ ctx.fillText(row.label.toUpperCase(), left + px * pad, y);
+ ctx.font = rowFont(px, 600);
+ ctx.textAlign = 'right';
+ ctx.fillStyle = row.accent ? '#ffb27a' : '#f3ead7';
+ ctx.fillText(fmt(counted), left + plateW - px * pad, y);
+ });
+
+ // CRT scanlines over the whole frame, faint.
+ ctx.globalAlpha = 0.12;
+ ctx.fillStyle = '#000';
+ const gap = Math.max(2, Math.round(height / 270));
+ for (let y = 0; y < height; y += gap * 2) ctx.fillRect(0, y, width, gap);
+ // In from black, out to black.
+ const dark = Math.max(1 - clamp(t / 0.6), clamp((t - (D - 0.8)) / 0.8));
+ if (dark > 0) {
+ ctx.globalAlpha = dark;
+ ctx.fillStyle = '#000';
+ ctx.fillRect(0, 0, width, height);
+ }
+ ctx.restore();
+}
+
+export { statsOutroRows, drawStatsOutro };
+
+/**
+ * The render page's script: draws the outro full-frame on a canvas and
+ * exposes `globalThis.portosComposition` (`seek(t)` on the outro's own time)
+ * for the shared composition encoder. `imageSrcs[i]` is the page-relative file
+ * for `stats.floorImages[i]`; the faces are declared by the page's
+ * @font-face rules. Every seek waits for the stills and faces to load.
+ */
+export function statsOutroPageSource({ stats, imageSrcs = [], width, height, fps, durationSec }) {
+ const json = (value) => JSON.stringify(value).replace(/</g, '\\u003c');
+ return `(() => {
+ ${statsOutroRows.toString()}
+ ${drawStatsOutro.toString()}
+ const STATS = ${json(stats)};
+ const SRCS = ${json(imageSrcs)};
+ const WIDTH = ${Number(width)}, HEIGHT = ${Number(height)}, FPS = ${Number(fps)}, DURATION = ${Number(durationSec)};
+ const canvas = document.getElementById('outro');
+ canvas.width = WIDTH;
+ canvas.height = HEIGHT;
+ const ctx = canvas.getContext('2d');
+ const images = SRCS.map(() => null);
+ const loaded = Promise.all(SRCS.map((src, i) => new Promise((resolve) => {
+ const img = new Image();
+ img.onload = () => { images[i] = img; resolve(); };
+ img.onerror = () => resolve();
+ img.src = src;
+ })));
+ const faces = document.fonts && document.fonts.load
+ ? Promise.all(['800 40px "MV Archivo"', '500 40px "MV Mono"', '600 40px "MV Mono"'].map((font) => document.fonts.load(font).catch(() => null)))
+ : Promise.resolve();
+ globalThis.portosComposition = {
+ durationSec: DURATION, fps: FPS, width: WIDTH, height: HEIGHT,
+ async seek(t) {
+ await loaded;
+ await faces;
+ drawStatsOutro(ctx, { width: WIDTH, height: HEIGHT, t, durationSec: DURATION, stats: STATS, images });
+ await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
+ },
+ };
+})();
+`;
+}
diff --git a/server/lib/musicVideoStatsOutro.test.js b/server/lib/musicVideoStatsOutro.test.js
new file mode 100644
index 0000000000..68b7ecf5d0
--- /dev/null
+++ b/server/lib/musicVideoStatsOutro.test.js
@@ -0,0 +1,60 @@
+import { describe, expect, it } from 'vitest';
+import { STATS_OUTRO_FLOOR_MAX, musicVideoOutroStats, normalizeStatsOutro, statsOutroRows, statsOutroSeconds } from './musicVideoStatsOutro.js';
+
+describe('cutting room floor outro', () => {
+ it('is off unless turned on, and its length stays inside its limits', () => {
+ expect(normalizeStatsOutro(null)).toBeNull();
+ expect(statsOutroSeconds(null)).toBe(0);
+ expect(statsOutroSeconds({ durationSec: 10 })).toBe(0);
+ expect(normalizeStatsOutro({ enabled: true })).toEqual({ enabled: true, durationSec: 8 });
+ expect(statsOutroSeconds({ enabled: true, durationSec: 99 })).toBe(20);
+ expect(statsOutroSeconds({ enabled: true, durationSec: 1 })).toBe(4);
+ });
+
+ // The tally is the feature: every count must come from what the project records, each asset counted once.
+ it('counts what was made, kept and turned down from the shots, the collection and the marks', () => {
+ const project = {
+ assetMarks: { 'image:bad.png': 'bad', 'image:kept.png': 'bad', 'image:never-made.png': 'bad' },
+ scenes: [
+ {
+ sceneId: 's1', referenceImageId: 'kept.png', videoHistoryId: 'clip-kept', endImageId: 'end.png',
+ transitionIn: 'vhs-glitch', transitionOut: 'channel-change', camera: { move: 'push-in' }, shotMode: 'performance',
+ takes: [
+ { kind: 'image', assetId: 'kept.png', status: 'candidate' },
+ { kind: 'image', assetId: 'rejected.png', status: 'rejected' },
+ { kind: 'video', assetId: 'clip-kept', status: 'candidate' },
+ { kind: 'video', assetId: 'clip-rejected', status: 'rejected' },
+ { kind: 'endImage', assetId: 'end.png', status: 'candidate' },
+ ],
+ },
+ // Restored onto another shot after being rejected here: in the cut, so not a rejection.
+ { sceneId: 's2', referenceImageId: 'rejected.png', imageEffect: 'flash-develop', takes: [] },
+ ],
+ };
+ const collectionItems = [
+ { kind: 'image', ref: 'kept.png' }, { kind: 'image', ref: 'floor.png' }, { kind: 'image', ref: 'bad.png' },
+ { kind: 'video', ref: 'clip-floor' }, { kind: 'video', ref: 'clip-kept' }, { kind: 'audio', ref: 'ignored.mp3' },
+ ];
+ const stats = musicVideoOutroStats(project, { collectionItems });
+ expect(stats).toEqual({
+ stills: { made: 5, kept: 3 }, // kept, rejected (now on s2), end, floor, bad
+ clips: { made: 3, kept: 1 },
+ rejected: 2, // clip-rejected, and bad.png by its mark; kept.png is in the cut and never-made.png was never made
+ shots: 2, lipSyncs: 1, transitions: 2, imageEffects: 1, cameraMoves: 1,
+ floorImages: ['bad.png', 'floor.png'],
+ });
+ const rows = statsOutroRows(stats);
+ expect(rows.at(-1)).toEqual({ label: 'Left on the floor', value: 4, accent: true });
+ expect(rows.map((row) => row.label)).toEqual(['Stills made', 'Clips made', 'Takes rejected', 'Transitions placed', 'Image effects',
+ 'Camera moves', 'Lip-sync shots', 'Shots in the cut', 'Left on the floor']);
+ });
+
+ it('leaves out the choices never made and spreads the floor over the whole pile', () => {
+ const collectionItems = Array.from({ length: 40 }, (_, i) => ({ kind: 'image', ref: `still-${String(i).padStart(2, '0')}.png` }));
+ const stats = musicVideoOutroStats({ scenes: [{ sceneId: 's' }] }, { collectionItems });
+ expect(stats.floorImages).toHaveLength(STATS_OUTRO_FLOOR_MAX);
+ expect(stats.floorImages[0]).toBe('still-00.png');
+ expect(stats.floorImages.at(-1) > 'still-35.png').toBe(true);
+ expect(statsOutroRows(stats).map((row) => row.label)).toEqual(['Stills made', 'Clips made', 'Shots in the cut', 'Left on the floor']);
+ });
+});
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index 083cc95aa1..bdd5bda072 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -2,6 +2,7 @@ import { MUSIC_VIDEO_MEDIA_MODES } from './musicVideoMediaPolicy.js';
import { MUSIC_VIDEO_GRADE_PRESETS, MUSIC_VIDEO_GRADE_MAX_GRAIN } from './musicVideoGrade.js';
import { filmLookSchema } from './filmLookValidation.js';
import { TITLE_CARD_FONTS, TITLE_CARD_LIMITS, TITLE_CARD_POSITIONS, TITLE_CARD_STYLES } from './musicVideoTitleCard.js';
+import { STATS_OUTRO_LIMITS } from './musicVideoStatsOutro.js';
import { COVER_DESIGN_OPTIONS } from './musicVideoCoverOverlay.js';
import { DISTROKID_REMEMBERED_OPTIONS } from './distrokidGenres.js';
import { CROSS_LINK_EDIT_TARGETS } from './musicVideoCrossLinks.js';
@@ -1278,6 +1279,13 @@ export const musicVideoCastAndSetsDirectionEditSchema = z.object({
}).strict()).max(8).optional(),
}).strict();
+// The cutting room floor outro (lib/musicVideoStatsOutro.js): an optional scene
+// after the song tallying the director's choices; null on the project = off.
+export const musicVideoStatsOutroSchema = z.object({
+ enabled: z.boolean().optional(),
+ durationSec: z.number().min(STATS_OUTRO_LIMITS.durationMin).max(STATS_OUTRO_LIMITS.durationMax).optional(),
+}).strict();
+
// The opening title card (lib/musicVideoTitleCard.js): song title, artist, year
// in a corner over the opener. Every field is optional (the normalizer fills
// defaults); null on the project = none.
@@ -1331,6 +1339,8 @@ export const musicVideoProjectCreateSchema = z.object({
filmLook: filmLookSchema.nullable().optional(),
// The opening title card (lib/musicVideoTitleCard.js); null = none.
titleCard: musicVideoTitleCardSchema.nullable().optional(),
+ // The cutting room floor outro after the song (lib/musicVideoStatsOutro.js); null = off.
+ statsOutro: musicVideoStatsOutroSchema.nullable().optional(),
}).strict();
export const musicVideoProjectUpdateSchema = z.object({
@@ -1359,6 +1369,8 @@ export const musicVideoProjectUpdateSchema = z.object({
filmLook: filmLookSchema.nullable().optional(),
// The opening title card (lib/musicVideoTitleCard.js); null = none.
titleCard: musicVideoTitleCardSchema.nullable().optional(),
+ // The cutting room floor outro after the song (lib/musicVideoStatsOutro.js); null = off.
+ statsOutro: musicVideoStatsOutroSchema.nullable().optional(),
}).strict();
// Mark a project finished outside PortOS (or clear the marker). The server
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.js
index bc64807c47..ca6f210681 100644
--- a/server/routes/musicVideo.js
+++ b/server/routes/musicVideo.js
@@ -1545,6 +1545,14 @@ router.get('/:id/media-pool', asyncHandler(async (req, res) => {
res.json(await getMusicVideoMediaPool(project));
}));
+// The cutting room floor outro's tally: what was made, kept and turned down for this video.
+router.get('/:id/stats-outro', asyncHandler(async (req, res) => {
+ const project = await getProject(req.params.id);
+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ const { getMusicVideoOutroStats } = await import('../services/musicVideo/statsOutro.js');
+ res.json({ stats: await getMusicVideoOutroStats(project) });
+}));
+
// The asset manager: mark unused stills and clips ★ ingredient / ✕ bad, or delete them from the library.
router.patch('/:id/media-pool/marks', asyncHandler(async (req, res) => {
const { items, mark } = validateRequest(musicVideoPoolMarkSchema, req.body);
diff --git a/server/services/backup.js b/server/services/backup.js
index 6a6d0129c4..e817486231 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -251,6 +251,8 @@ export const DEFAULT_EXCLUDES = [
{ path: '/code-animation-workspaces/', reason: 'In-flight sandboxed Code Animation worker workspaces — removed when each run ends', overridable: false },
{ path: '/code-animation-exports/', reason: 'Code Animation frame-exact export staging — the stored HTML plus render shim, staged once per export', overridable: true },
{ path: '/music-video-compositions/', reason: 'In-flight music-video typography overlay scratch — removed when its render ends and swept at boot', overridable: false },
+ { path: '/music-video-film-look/', reason: 'In-flight music-video film look pass (a staged link to the finished render) — removed when the pass ends', overridable: false },
+ { path: '/music-video-stats-outro/', reason: 'In-flight music-video outro page (fonts and floor stills) — removed when its render ends and swept at boot', overridable: false },
{ path: '/music-video-song-renders/', reason: 'In-flight music-video composition renders (a staged copy of the document plus scene media) — removed when the render ends and swept at boot', overridable: false },
{ path: '/launch-videos/*/*/proofs/', reason: 'Launch-video critique-loop contact sheets — re-rendered from the run composition', overridable: true },
{ path: '/cache/', reason: 'Remote-API metadata and licensed reading caches — regenerable on demand, and stale on restore anyway', overridable: false },
diff --git a/server/services/dataManager.js b/server/services/dataManager.js
index 4c6775bf84..55c8de7051 100644
--- a/server/services/dataManager.js
+++ b/server/services/dataManager.js
@@ -91,6 +91,8 @@ export const CATEGORIES = {
// here: a purge would strand those references (delete the artifact instead).
'music-video': { label: 'Music Video Development Files', description: 'Versioned development artifacts (check-in sheets, animatics, treatments) and composition documents referenced by Music Video projects', archivable: true, deletable: false },
'music-video-compositions': { label: 'Music Video Overlay Scratch', description: 'Typography overlay frames for an in-flight composed music-video render — removed when the render ends and swept at boot', archivable: false, deletable: false },
+ 'music-video-film-look': { label: 'Music Video Film Look Scratch', description: 'A staged link to a finished render for its film look pass — removed when the pass ends', archivable: false, deletable: false },
+ 'music-video-stats-outro': { label: 'Music Video Outro Scratch', description: 'The cutting room floor outro page (fonts and floor stills) for an in-flight music-video render — removed when the render ends and swept at boot', archivable: false, deletable: false },
'music-video-song-renders': { label: 'Music Video Composition Render Scratch', description: 'A staged copy of a composition document plus its scene media for an in-flight music-video render — removed when the render ends and swept at boot', archivable: false, deletable: false },
'code-animation-workspaces': { label: 'Code Animation Contained Workers', description: 'Per-run staged input, output and scratch for a sandboxed Code Animation worker — removed when the run ends and swept on the next run', archivable: false, deletable: false },
'code-animations': { label: 'Code Animations', description: 'Generated animation HTML retained with its job history — the only copy of provider-generated work', archivable: true, deletable: false },
diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.js
index dbeb75454b..c27f483d10 100644
--- a/server/services/musicVideo/projectsLogic.js
+++ b/server/services/musicVideo/projectsLogic.js
@@ -39,6 +39,7 @@ import { normalizeComposition, invalidateCompositionTiming, withStoredCompositio
import { normalizeSoundBed } from './soundBed.js';
import { normalizeFilmLook } from '../../lib/filmLook.js';
import { normalizeTitleCard } from '../../lib/musicVideoTitleCard.js';
+import { normalizeStatsOutro } from '../../lib/musicVideoStatsOutro.js';
import { remapTreatmentForClone, scenesFingerprint } from './treatment.js';
import { carryStoryboardApproval } from './productionReview.js';
import { normalizeMusicVideoAutomation } from '../../lib/musicVideoAutomation.js';
@@ -172,6 +173,8 @@ export function buildProjectRecord(input, { id, now }) {
filmLook: input.filmLook ? normalizeFilmLook(input.filmLook) : null,
// The opening title card (song, artist, year over the opener); null = none.
titleCard: normalizeTitleCard(input.titleCard),
+ // The cutting room floor outro after the song; null = off.
+ statsOutro: normalizeStatsOutro(input.statsOutro),
// #8980 — optional pre-production treatment (brief, arc, shot direction,
// proof checklist); null until the director starts one. See treatment.js.
treatment: null,
@@ -379,6 +382,8 @@ export function applyProjectPatch(project, patch) {
...('filmLook' in patch ? { filmLook: normalizeFilmLook(patch.filmLook) } : {}),
// The title card is replaced whole (one bounded record); null clears it.
...('titleCard' in patch ? { titleCard: normalizeTitleCard(patch.titleCard) } : {}),
+ // The outro after the song is replaced whole; null turns it off.
+ ...('statsOutro' in patch ? { statsOutro: normalizeStatsOutro(patch.statsOutro) } : {}),
};
// #8988: a bed is mixed UNDER the song — the song itself can't be its bed.
const masterTrackId = 'trackId' in patch ? patch.trackId : project.trackId;
diff --git a/server/services/musicVideo/render.eidoverse.test.js b/server/services/musicVideo/render.eidoverse.test.js
index 98ef6aef5e..368504fa9f 100644
--- a/server/services/musicVideo/render.eidoverse.test.js
+++ b/server/services/musicVideo/render.eidoverse.test.js
@@ -8,6 +8,7 @@ vi.mock('./productionReview.js', async load => ({ ...await load(), assertProduct
vi.mock('../../lib/ffmpeg.js', async load => ({ ...await load(), generateThumbnail: vi.fn(async () => 'thumb.jpg') }));
vi.mock('../instanceIdentity.js', () => ({ ensureInstanceId: vi.fn(async () => 'test-instance') }));
vi.mock('../videoGen/local.js', () => ({ loadHistory: vi.fn(async () => []), mutateVideoHistory: vi.fn(async () => {}) }));
+vi.mock('./statsOutro.js', () => ({ appendStatsOutro: vi.fn(async () => 0), sweepStatsOutroScratch: vi.fn(async () => {}) }));
vi.mock('./codeRender.js', async load => ({ ...await load(), writeCodeProofSheet: vi.fn(async () => null) }));
vi.mock('./eidoverseRender.js', async load => ({
...await load(),
@@ -23,6 +24,7 @@ const { renderMusicVideo } = await import('./render.js');
const { startExcerptRender } = await import('./excerptRender.js');
const { encodeEidoverseComposition } = await import('./eidoverseRender.js');
const { mutateVideoHistory } = await import('../videoGen/local.js');
+const { appendStatsOutro } = await import('./statsOutro.js');
const { musicVideoEvents } = await import('./events.js');
afterAll(cleanupTempDataRoots);
async function create(scene = { inlineScript: 'example source' }) {
@@ -40,6 +42,8 @@ it('routes both the final film and song-window proof through Eidoverse without r
expect((await projects.getProject(id)).renderHistoryId).toBe(jobId);
expect(mutateVideoHistory).toHaveBeenCalled();
expect(encodeEidoverseComposition.mock.calls.at(-1)[0]).toMatchObject({ audioPath: join(PATHS.music, 'song.wav'), project: { composition: { mode: 'eidoverse' } } });
+ // Eidoverse never grades the song, so its outro page must not grade the ending either.
+ expect(appendStatsOutro.mock.calls.at(-1)[0]).toMatchObject({ withFilmLook: false });
const excerptRendered = once(musicVideoEvents, 'excerpt-render');
const { excerptId } = await startExcerptRender(id, { startSec: 2, endSec: 5 });
expect((await excerptRendered)[0]).toMatchObject({ projectId: id, excerptId, status: 'complete' });
diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.js
index 7f27aac5ac..9ea9fb3aae 100644
--- a/server/services/musicVideo/render.js
+++ b/server/services/musicVideo/render.js
@@ -48,6 +48,8 @@ import { encodeCodeComposition, prepareCodeRender, writeCodeProofSheet } from '.
import { documentRenderInitScripts, encodeDocumentComposition, prepareDocumentRender, sweepDocumentScratch } from './documentRender.js';
import { renderTypographyOverlays, removeCompositionScratch, sweepCompositionScratch } from './compositionRender.js';
import { applyFilmLookFinish, filmLookFinishNeeded } from './filmLookFinish.js';
+import { appendStatsOutro, sweepStatsOutroScratch } from './statsOutro.js';
+import { statsOutroSeconds } from '../../lib/musicVideoStatsOutro.js';
import { selectedPerformanceInstruction } from '../../lib/musicVideoShotTiming.js';
import { captureMusicVideoEvidence, musicVideoTakeChanges } from '../../lib/musicVideoDependencies.js';
import { assertCurrentPerformanceTakes, withDraftPerformanceFallbacks } from './performanceShot.js';
@@ -729,6 +731,8 @@ const SEEKED_RENDERERS = Object.freeze({
code: {
label: 'code',
modelId: 'music-video-code',
+ // Draws the film look in its page, so the outro page draws it too.
+ filmLookInPage: true,
prepare: async (project) => prepareCodeRender(project),
encode: async ({ plan, project, projectId, jobId, audioPath, outputPath, signal, onProgress }) => {
await encodeCodeComposition({
@@ -741,6 +745,7 @@ const SEEKED_RENDERERS = Object.freeze({
document: {
label: 'composition document',
modelId: 'music-video-document',
+ filmLookInPage: true,
soundBed: true,
// A document draws the scenes' selected takes, so it runs the same
// performance-take gate as a footage render (#9266).
@@ -803,10 +808,13 @@ async function renderSeekedMode(projectId, project, handOff, renderer, options =
Promise.resolve().then(async () => {
await assertCurrentRenderApproval(projectId, project, options);
if (signal.aborted) throw Object.assign(new Error('Render cancelled'), { code: 'CANCELED' });
- return renderer.encode({
+ const encoded = await renderer.encode({
plan, project, projectId, jobId, audioPath, soundBed, outputPath, signal,
onProgress: (fraction) => broadcastSse(job, { type: 'progress', progress: fraction }),
});
+ // The cutting room floor outro (when on) joins after the song.
+ const outroSec = await appendStatsOutro({ project, path: outputPath, jobId, signal, withFilmLook: !!renderer.filmLookInPage });
+ return outroSec > 0 ? { ...encoded, durationSec: encoded.durationSec + outroSec } : encoded;
}).then(async (encoded) => {
job.overlayAbort = null;
job.status = 'complete';
@@ -970,6 +978,8 @@ async function renderAdmittedMusicVideo(projectId, options, permit) {
// look after ffmpeg (filmLookFinish.js); the pass takes the second half of
// whatever the encode's share of the bar is.
const finishing = filmLookFinishNeeded(project);
+ // Seconds the outro scene adds after the song (0 when it is off).
+ const outroSec = statsOutroSeconds(project.statsOutro);
// A composed render first captures its overlay (progress 0–50%), then
// encodes (50–100%); a plain render encodes across the whole bar.
const startEncode = (encodeArgs, progressBase = 0) => {
@@ -1038,6 +1048,19 @@ async function renderAdmittedMusicVideo(projectId, options, permit) {
await settleFailure(canceled, canceled ? 'Render cancelled' : signal ? `Killed by signal ${signal}` : `ffmpeg exit ${code}`);
return;
}
+ // The cutting room floor outro (when on) joins after the song, before
+ // the film look so the look grades it with the rest of the film.
+ if (outroSec > 0) {
+ job.overlayAbort = new AbortController();
+ const { signal: outroSignal } = job.overlayAbort;
+ try {
+ await appendStatsOutro({ project, path: outputPath, jobId, signal: outroSignal });
+ } catch (err) {
+ await settleFailure(outroSignal.aborted, outroSignal.aborted ? 'Render cancelled' : `Outro scene failed: ${err.message}`);
+ return;
+ }
+ job.overlayAbort = null;
+ }
// The cut is encoded; a film look re-encodes it in place through the
// look before it is published. A cancel here aborts the pass.
if (finishing) {
@@ -1077,7 +1100,7 @@ async function renderAdmittedMusicVideo(projectId, options, permit) {
seed: 0,
width: canonW,
height: canonH,
- numFrames: Math.round(totalDuration * (fps || 24)),
+ numFrames: Math.round((totalDuration + outroSec) * (fps || 24)),
fps: fps || 24,
filename,
thumbnail: poster,
@@ -1164,6 +1187,10 @@ export async function recoverStuckMusicVideoRenders() {
await sweepDocumentScratch().catch((err) => {
console.warn(`⚠️ Music Video recovery: could not remove stale composition-document scratch: ${err.message}`);
});
+ // Nor the outro scene's staged page.
+ await sweepStatsOutroScratch().catch((err) => {
+ console.warn(`⚠️ Music Video recovery: could not remove stale outro scratch: ${err.message}`);
+ });
const instanceId = await ensureInstanceId();
const stuck = (await listProjects()).filter((p) => p?.status === 'rendering'
&& !projectRenders.has(p.id) && isLocalRenderMark(p.renderingOn, instanceId));
diff --git a/server/services/musicVideo/render.terminal.test.js b/server/services/musicVideo/render.terminal.test.js
index 42ea183557..9d91fd6457 100644
--- a/server/services/musicVideo/render.terminal.test.js
+++ b/server/services/musicVideo/render.terminal.test.js
@@ -69,6 +69,7 @@ vi.mock('../videoGen/local.js', () => ({
mutateVideoHistory: vi.fn(async (fn) => fn([])),
}));
vi.mock('../tracks/index.js', () => ({ getTrack: vi.fn() }));
+vi.mock('./statsOutro.js', () => ({ appendStatsOutro: vi.fn(async () => 0), sweepStatsOutroScratch: vi.fn(async () => {}) }));
vi.mock('./compositionRender.js', () => ({
renderTypographyOverlays: h.renderTypographyOverlays,
removeCompositionScratch: vi.fn(async () => {}),
diff --git a/server/services/musicVideo/statsOutro.js b/server/services/musicVideo/statsOutro.js
new file mode 100644
index 0000000000..6daca84523
--- /dev/null
+++ b/server/services/musicVideo/statsOutro.js
@@ -0,0 +1,139 @@
+/**
+ * Music Video — the cutting room floor outro (lib/musicVideoStatsOutro.js):
+ * the tally read from the project's records, and the final-render pass that
+ * appends the scene after the song.
+ *
+ * The pass captures the outro page (the same painter the animatic draws with)
+ * through the shared composition encoder, then joins it to the finished cut
+ * with silence under it. In a footage render it runs before the film look pass,
+ * so the look grades the outro with the rest of the film; a seeked render draws
+ * its look in the page, so there the outro page draws it too (`withFilmLook`).
+ */
+
+import { copyFile, link, mkdir, rename, rm, writeFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { PATHS } from '../../lib/paths.js';
+import { ServerError } from '../../lib/errorHandler.js';
+import { filmLookRuntimeSource, isFilmLookNeutral, normalizeFilmLook } from '../../lib/filmLook.js';
+import { STATS_OUTRO_FONTS, musicVideoOutroStats, normalizeStatsOutro, statsOutroPageSource } from '../../lib/musicVideoStatsOutro.js';
+
+export const STATS_OUTRO_SCRATCH_DIR = 'music-video-stats-outro';
+
+/** Boot sweep: no render survives a restart, so every staged outro page is stale. */
+export const sweepStatsOutroScratch = async () => rm(join(PATHS.data, STATS_OUTRO_SCRATCH_DIR), { recursive: true, force: true });
+
+const FONT_DIR = new URL('./documentTemplates/shared/fonts/', import.meta.url);
+
+/**
+ * The tally for `project`: its shots' takes and selections plus every still
+ * and clip in its media collection and every clip stamped with it in the
+ * video history. Read-only.
+ */
+export async function getMusicVideoOutroStats(project) {
+ const [{ getCollection, musicVideoCollectionId }, { loadHistory }] = await Promise.all([
+ import('../mediaCollections.js'), import('../videoGen/history.js'),
+ ]);
+ const collection = await getCollection(musicVideoCollectionId(project.id)).catch(() => null);
+ const stamped = (await loadHistory().catch(() => []))
+ .filter((entry) => entry?.id && entry.musicVideo?.projectId === project.id)
+ .map((entry) => ({ kind: 'video', ref: entry.id }));
+ return musicVideoOutroStats(project, { collectionItems: [...(collection?.items || []), ...stamped] });
+}
+
+/** The outro page: a full-frame canvas, its faces, and the script that draws it per seek. Pure. */
+function statsOutroPage({ stats, imageSrcs, width, height, fps, durationSec }) {
+ const face = ({ family, file }, weight) => `@font-face { font-family: "${family}"; src: url(fonts/${file}) format("woff2"); font-weight: ${weight}; }`;
+ return `<!doctype html><html><head><meta charset="utf-8"><title>Cutting room floor</title>
+<style>${face(STATS_OUTRO_FONTS.head, '100 900')}
+${face(STATS_OUTRO_FONTS.body, '100 900')}
+html,body{margin:0;width:${width}px;height:${height}px;overflow:hidden;background:#000}canvas{display:block;width:${width}px;height:${height}px}</style>
+</head><body><canvas id="outro"></canvas><script src="app.js"></script></body></html>\n`;
+}
+
+/**
+ * Append the project's outro to the finished render at `path`, in place.
+ * Resolves the seconds it added (0 when the outro is off; the file is then
+ * untouched). Rejects on failure or when `signal` aborts, leaving `path` as
+ * it was.
+ */
+export async function appendStatsOutro({ project, path, jobId, signal, onProgress, withFilmLook = false }) {
+ const outro = normalizeStatsOutro(project?.statsOutro);
+ if (!outro?.enabled) return 0;
+ if (typeof jobId !== 'string' || !/^[A-Za-z0-9_-]+$/.test(jobId)) throw new Error('Invalid outro job id');
+ const { findFfmpeg, runFfmpegProcess, probeVideoGeometry } = await import('../../lib/ffmpeg.js');
+ const { openComposition } = await import('../htmlComposition/browser.js');
+ const { encodeComposition } = await import('../htmlComposition/encode.js');
+ const { ensureImageThumbnail } = await import('../../lib/imageThumbnail.js');
+ const ffmpeg = await findFfmpeg();
+ if (!ffmpeg) throw new ServerError('ffmpeg not found on PATH', { status: 500, code: 'FFMPEG_MISSING' });
+ const geometry = await probeVideoGeometry(path);
+ if (!geometry) throw new ServerError('The rendered video could not be measured for its outro', { status: 500, code: 'STATS_OUTRO_PROBE' });
+ const { width, height, fps } = geometry;
+ const durationSec = outro.durationSec;
+ const stats = await getMusicVideoOutroStats(project);
+ const directory = `${STATS_OUTRO_SCRATCH_DIR}/${jobId}`;
+ const scratch = join(PATHS.data, directory);
+ const clip = `${path}.outro.mp4`;
+ const joined = `${path}.outro-joined.mp4`;
+ let page;
+ try {
+ await rm(scratch, { recursive: true, force: true });
+ await mkdir(join(scratch, 'media'), { recursive: true });
+ await mkdir(join(scratch, 'fonts'), { recursive: true });
+ for (const { file } of Object.values(STATS_OUTRO_FONTS)) await copyFile(fileURLToPath(new URL(file, FONT_DIR)), join(scratch, 'fonts', file));
+ // The floor's stills ride as their small gallery thumbnails; one that is gone leaves a film offcut in its place.
+ const imageSrcs = [];
+ for (const [i, imageId] of stats.floorImages.entries()) {
+ // A gallery PNG has a small WebP beside it; any other still rides as itself, as the animatic shows it.
+ const png = /\.png$/i.test(imageId);
+ const thumb = imageId.replace(/\.png$/i, '.webp');
+ const ok = png ? await ensureImageThumbnail(thumb).catch(() => false) : /^[^/\\]+\.(jpe?g|webp)$/i.test(imageId);
+ const source = !ok ? null : png ? join(PATHS.imageThumbnails, thumb) : join(PATHS.images, imageId);
+ const name = `floor-${i}${png ? '.webp' : imageId.slice(imageId.lastIndexOf('.')).toLowerCase()}`;
+ const target = join(scratch, 'media', name);
+ const staged = source && await link(source, target).then(() => true, () => copyFile(source, target).then(() => true, () => false));
+ imageSrcs.push(staged ? `media/${name}` : '');
+ }
+ await writeFile(join(scratch, 'index.html'), statsOutroPage({ stats, imageSrcs, width, height, fps, durationSec }));
+ await writeFile(join(scratch, 'app.js'), statsOutroPageSource({ stats, imageSrcs, width, height, fps, durationSec }));
+ signal?.throwIfAborted();
+ // A render whose film look is drawn in its page (the seeked modes) has no later
+ // pass to grade the outro, so the outro page draws the look itself.
+ const look = withFilmLook ? normalizeFilmLook(project?.filmLook) : null;
+ const initScripts = look && !isFilmLookNeutral(look) ? [filmLookRuntimeSource(look)] : [];
+ page = await openComposition(directory, { signal, ownedBrowser: true, initScripts });
+ await encodeComposition(page, { width, height, fps, durationSec }, clip, {
+ signal, onProgress: (fraction) => onProgress?.(fraction * 0.6),
+ });
+ page.check();
+ await page.close({ verify: true });
+ page = null;
+ signal?.throwIfAborted();
+ // Join the cut and the outro, with silence under the outro. Both pictures
+ // are brought to the cut's frame, rate and pixel format first.
+ const norm = `scale=${width}:${height},setsar=1,fps=${fps},format=yuv420p`;
+ const audio = 'aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo';
+ const join2 = await runFfmpegProcess({
+ bin: ffmpeg, signal,
+ args: ['-hide_banner', '-loglevel', 'error', '-i', path, '-i', clip,
+ '-f', 'lavfi', '-t', String(durationSec), '-i', 'anullsrc=r=48000:cl=stereo',
+ '-filter_complex', `[0:v]${norm}[a0];[1:v]${norm}[b0];[0:a]${audio}[a1];[2:a]${audio}[b1];[a0][a1][b0][b1]concat=n=2:v=1:a=1[v][a]`,
+ '-map', '[v]', '-map', '[a]', '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '18', '-pix_fmt', 'yuv420p',
+ '-c:a', 'aac', '-b:a', '192k', '-movflags', '+faststart', '-y', joined],
+ });
+ if (!join2.ok) {
+ signal?.throwIfAborted();
+ throw new ServerError(`Outro join failed: ${join2.reason}`, { status: 500, code: 'STATS_OUTRO_JOIN' });
+ }
+ await rename(joined, path);
+ onProgress?.(1);
+ console.log(`🎞️ Music-video outro [${jobId.slice(0, 8)}]: ${durationSec}s cutting room floor after the song`);
+ return durationSec;
+ } finally {
+ if (page) await page.close().catch(() => {});
+ await rm(scratch, { recursive: true, force: true }).catch(() => {});
+ await rm(clip, { force: true }).catch(() => {});
+ await rm(joined, { force: true }).catch(() => {});
+ }
+}
diff --git a/server/services/musicVideo/statsOutro.test.js b/server/services/musicVideo/statsOutro.test.js
new file mode 100644
index 0000000000..5d71e1a17b
--- /dev/null
+++ b/server/services/musicVideo/statsOutro.test.js
@@ -0,0 +1,112 @@
+/**
+ * The cutting room floor outro pass over a finished render, with the
+ * composition browser, the shared encoder and ffmpeg stubbed at their
+ * boundaries: what the pass stages and asks of them, that the render grows by
+ * the outro only once the pass succeeds, and that nothing is left behind.
+ */
+
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { existsSync } from 'node:fs';
+import { mkdir, readFile, writeFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';
+
+vi.mock('../../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), {
+ dataRoot: () => lazyTempDataRoot('portos-mv-stats-outro-'),
+}));
+const { seen } = vi.hoisted(() => ({ seen: { opened: [], contract: null, ffmpeg: [], encodeFail: null } }));
+vi.mock('../../lib/ffmpeg.js', () => ({
+ findFfmpeg: async () => 'ffmpeg',
+ probeVideoGeometry: async () => ({ width: 1920, height: 1080, fps: 24, numFrames: 480, durationSec: 20 }),
+ runFfmpegProcess: async ({ args }) => {
+ const { writeFile: write } = await import('node:fs/promises');
+ seen.ffmpeg.push(args);
+ await write(args.at(-1), 'render-with-outro');
+ return { ok: true };
+ },
+}));
+vi.mock('../../lib/imageThumbnail.js', () => ({ ensureImageThumbnail: async () => false }));
+vi.mock('../mediaCollections.js', () => ({
+ musicVideoCollectionId: (id) => `mvc-${id}`,
+ getCollection: async () => ({ items: [{ kind: 'image', ref: 'floor.png' }, { kind: 'image', ref: 'photo.jpg' }, { kind: 'video', ref: 'clip-floor' }] }),
+}));
+vi.mock('../videoGen/history.js', () => ({ loadHistory: async () => [{ id: 'clip-stamped', musicVideo: { projectId: 'mv-1' } }] }));
+vi.mock('../htmlComposition/browser.js', () => ({
+ openComposition: async (directory, options) => {
+ const { readFile: read, readdir } = await import('node:fs/promises');
+ const { join: joinPath } = await import('node:path');
+ const { PATHS: paths } = await import('../../lib/paths.js');
+ const dir = joinPath(paths.data, directory);
+ seen.opened.push({ directory, options, index: await read(joinPath(dir, 'index.html'), 'utf8'), app: await read(joinPath(dir, 'app.js'), 'utf8'), fonts: await readdir(joinPath(dir, 'fonts')), media: await readdir(joinPath(dir, 'media')) });
+ return { check() {}, async close() {} };
+ },
+}));
+vi.mock('../htmlComposition/encode.js', () => ({
+ encodeComposition: async (_page, contract, outputPath) => {
+ const { writeFile: write } = await import('node:fs/promises');
+ seen.contract = contract;
+ if (seen.encodeFail) throw seen.encodeFail;
+ await write(outputPath, 'outro-clip');
+ },
+}));
+
+const { PATHS } = await import('../../lib/paths.js');
+const { STATS_OUTRO_SCRATCH_DIR, appendStatsOutro } = await import('./statsOutro.js');
+
+const project = { id: 'mv-1', statsOutro: { enabled: true, durationSec: 6 }, scenes: [{ sceneId: 's', referenceImageId: 'kept.png' }] };
+let path;
+beforeEach(async () => {
+ seen.opened.length = 0;
+ seen.ffmpeg.length = 0;
+ seen.contract = null;
+ seen.encodeFail = null;
+ await mkdir(PATHS.videos, { recursive: true });
+ path = join(PATHS.videos, 'music-video-example.mp4');
+ await writeFile(path, 'render');
+ await mkdir(PATHS.images, { recursive: true });
+ await writeFile(join(PATHS.images, 'photo.jpg'), 'jpeg');
+});
+afterAll(() => cleanupTempDataRoots());
+
+describe('cutting room floor outro pass', () => {
+ it('leaves a render alone, without a browser, while the outro is off', async () => {
+ expect(await appendStatsOutro({ project: { ...project, statsOutro: { enabled: false } }, path, jobId: 'job-off' })).toBe(0);
+ expect(await appendStatsOutro({ project: { ...project, statsOutro: null }, path, jobId: 'job-none' })).toBe(0);
+ expect(seen.opened).toEqual([]);
+ expect(await readFile(path, 'utf8')).toBe('render');
+ });
+
+ it('draws the tally at the render\'s own size and joins it after the song with silence under it', async () => {
+ expect(await appendStatsOutro({ project, path, jobId: 'job-on' })).toBe(6);
+ const [opened] = seen.opened;
+ expect(opened.directory).toBe(`${STATS_OUTRO_SCRATCH_DIR}/job-on`);
+ expect(opened.options).toMatchObject({ ownedBrowser: true, initScripts: [] });
+ // A JPEG still rides as itself (as the animatic shows it); a PNG with no thumbnail is a film offcut.
+ expect(opened.media).toEqual(['floor-1.jpg']);
+ expect(opened.fonts.sort()).toEqual(['archivo-variable.woff2', 'ibm-plex-mono-500.woff2']);
+ expect(opened.index).toContain('<canvas id="outro">');
+ // The counts the page draws are the project's: its shot, its collection and the clip stamped with it.
+ expect(opened.app).toContain('"stills":{"made":3,"kept":1},"clips":{"made":2,"kept":0}');
+ expect(seen.contract).toEqual({ width: 1920, height: 1080, fps: 24, durationSec: 6 });
+ const [join2] = seen.ffmpeg;
+ expect(join2).toEqual(expect.arrayContaining(['-i', path, '-i', `${path}.outro.mp4`, 'anullsrc=r=48000:cl=stereo']));
+ expect(join2[join2.indexOf('-filter_complex') + 1]).toContain('concat=n=2:v=1:a=1');
+ expect(await readFile(path, 'utf8')).toBe('render-with-outro');
+ expect(existsSync(join(PATHS.data, STATS_OUTRO_SCRATCH_DIR, 'job-on'))).toBe(false);
+ expect(existsSync(`${path}.outro.mp4`)).toBe(false);
+ });
+
+ it('draws the film look in the outro page for a render that has no later look pass', async () => {
+ await appendStatsOutro({ project: { ...project, filmLook: { preset: 'super8', grain: 0.5 } }, path, jobId: 'job-look', withFilmLook: true });
+ expect(seen.opened[0].options.initScripts).toHaveLength(1);
+ expect(seen.opened[0].options.initScripts[0]).toContain('__portosFilmLook');
+ });
+
+ it('keeps the render as it was when the capture fails, and cleans up', async () => {
+ seen.encodeFail = new Error('browser died');
+ await expect(appendStatsOutro({ project, path, jobId: 'job-fail' })).rejects.toThrow('browser died');
+ expect(await readFile(path, 'utf8')).toBe('render');
+ expect(seen.ffmpeg).toEqual([]);
+ expect(existsSync(join(PATHS.data, STATS_OUTRO_SCRATCH_DIR, 'job-fail'))).toBe(false);
+ });
+});