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

let Code Animation study a reference video and attach references to vision-capable CLI providers

[._.]/ Adam Eivy4664b2c2352f
diff --git a/client/src/pages/CodeAnimation.jsx b/client/src/pages/CodeAnimation.jsx
index d7485f4ad2..4d4f673895 100644
--- a/client/src/pages/CodeAnimation.jsx
+++ b/client/src/pages/CodeAnimation.jsx
@@ -1,11 +1,12 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { AlertTriangle, CheckCircle2, Clock3, Copy, FileCode2, Globe, ImagePlus, LoaderCircle, Music2, PenLine, Sparkles, Wand2, X } from 'lucide-react';
+import { AlertTriangle, CheckCircle2, Clock3, Copy, FileCode2, Film, Globe, ImagePlus, LoaderCircle, Music2, PenLine, Sparkles, Wand2, X } from 'lucide-react';
import { Link, useLocation, useNavigate, useParams, useSearchParams } from 'react-router';
import PageHeader from '../components/PageHeader';
import ProviderModelSelector from '../components/ProviderModelSelector';
import AlbumTrackPicker from '../components/music/AlbumTrackPicker';
import CodeAnimationPreview from '../components/codeAnimation/CodeAnimationPreview';
import FilmStylePicker from '../components/codeAnimation/FilmStylePicker';
+import GalleryVideoPicker from '../components/videoGen/GalleryVideoPicker';
import ProductionProjects from '../components/codeAnimation/ProductionProjects';
import UniverseMoodBoardPicker, { BOARD_FOLLOW_UNIVERSE, BOARD_NONE, useStyleSourceLists } from '../components/media/UniverseMoodBoardPicker';
import InfiniteScrollFooter from '../components/ui/InfiniteScrollFooter';
@@ -46,6 +47,7 @@ const DEFAULT_DRAFT = {
moodBoardChoice: BOARD_FOLLOW_UNIVERSE,
includeMoodBoardImages: true,
referenceImages: [],
+ referenceVideo: null,
audio: null,
soundtrack: 'none',
format: { durationSeconds: 20, aspectRatio: '16:9', resolution: '1080p', fps: 30 },
@@ -146,6 +148,9 @@ function toBrief(draft) {
universeId: draft.universeId || null,
includeMoodBoardImages: draft.includeMoodBoardImages,
referenceImages: draft.referenceImages.map(({ filename, label, note }) => ({ filename, label, note })),
+ referenceVideo: draft.referenceVideo
+ ? { filename: draft.referenceVideo.filename, label: draft.referenceVideo.label, note: draft.referenceVideo.note }
+ : null,
audio: draft.audio
? draft.audio.source === 'track'
? {
@@ -209,6 +214,7 @@ function draftFromJob(job) {
...image,
url: `/api/uploads/${encodeURIComponent(image.filename)}`,
})),
+ referenceVideo: isRecord(input.referenceVideo) ? { ...input.referenceVideo, previewUrl: null } : null,
audio: input.audio
? input.audio.source === 'track'
? {
@@ -282,6 +288,7 @@ function FastCodeAnimation() {
const [trackPickerOpen, setTrackPickerOpen] = useState(false);
const [draft, setDraft] = useState(loadDraft);
const [uploading, setUploading] = useState(false);
+ const [videoPickerOpen, setVideoPickerOpen] = useState(false);
const [building, setBuilding] = useState(false);
const [writingBrief, setWritingBrief] = useState(false);
// The last built prompt, tagged with the brief it was built from.
@@ -346,7 +353,10 @@ function FastCodeAnimation() {
const briefKey = useMemo(() => JSON.stringify(brief), [brief]);
const promptStale = !!built && built.briefKey !== briefKey;
const limits = options?.limits;
- const maxRefs = limits?.referenceImagesMax ?? 8;
+ // A reference video is studied as a contact sheet plus keyframes, which
+ // occupy reference-image slots.
+ const maxRefs = (limits?.referenceImagesMax ?? 8) - (draft.referenceVideo ? limits?.referenceVideoImageSlots ?? 3 : 0);
+ const videoRoom = (limits?.referenceImagesMax ?? 8) - draft.referenceImages.length >= (limits?.referenceVideoImageSlots ?? 3);
const audioAccept = (options?.audioExtensions || ['mp3', 'wav', 'ogg', 'm4a']).map((ext) => `.${ext}`).join(',');
const generating = job?.id === jobId && job.status === 'running';
const canBuild = draft.concept.trim().length > 0 && !building && !uploading;
@@ -726,6 +736,24 @@ function FastCodeAnimation() {
</ul>
)}
</div>
+ <div>
+ <span className={labelClass}>Reference video <span className="text-gray-600">(optional; the quality bar — its pacing, camera and finish, never its content)</span></span>
+ {draft.referenceVideo ? (
+ <div className="flex items-center gap-2">
+ {draft.referenceVideo.previewUrl
+ ? <img src={draft.referenceVideo.previewUrl} alt="" className="h-12 w-20 shrink-0 rounded object-cover" />
+ : <Film className="h-5 w-5 shrink-0 text-gray-500" aria-hidden="true" />}
+ <input aria-label={`Note for ${draft.referenceVideo.label}`} value={draft.referenceVideo.note} maxLength={limits?.referenceNoteMax} onChange={(event) => update({ referenceVideo: { ...draft.referenceVideo, note: event.target.value } })} placeholder={`${draft.referenceVideo.label}: what to match (cut rhythm, depth of field, grade…)`} className={`${inputClass} min-w-0`} />
+ <button type="button" aria-label="Remove reference video" onClick={() => update({ referenceVideo: null })} className="shrink-0 text-gray-500 hover:text-port-error"><X className="h-4 w-4" /></button>
+ </div>
+ ) : (
+ <button type="button" onClick={() => setVideoPickerOpen(true)} disabled={!videoRoom} title={videoRoom ? undefined : `A reference video needs ${limits?.referenceVideoImageSlots ?? 3} free reference slots`} className="inline-flex items-center gap-1.5 rounded border border-port-border px-2.5 py-1.5 text-xs text-gray-200 hover:border-port-accent disabled:opacity-50">
+ <Film className="h-3.5 w-3.5" aria-hidden="true" /> Pick or upload a video…
+ </button>
+ )}
+ <GalleryVideoPicker open={videoPickerOpen} onClose={() => setVideoPickerOpen(false)} allowUpload uploadToGallery
+ onSelect={(item) => update({ referenceVideo: { filename: item.filename, label: item.prompt && item.prompt !== '(no prompt)' ? item.prompt.slice(0, 120) : item.filename, note: '', previewUrl: item.previewUrl } })} />
+ </div>
<div>
<label htmlFor="ca-audio" className={`${labelClass} flex items-center gap-1`}><Music2 className="h-3 w-3" /> Audio track <span className="text-gray-600">(optional; the animation syncs to it)</span></label>
{draft.audio ? (
diff --git a/client/src/pages/CodeAnimation.test.jsx b/client/src/pages/CodeAnimation.test.jsx
index 42423573c7..5c894e239b 100644
--- a/client/src/pages/CodeAnimation.test.jsx
+++ b/client/src/pages/CodeAnimation.test.jsx
@@ -31,6 +31,11 @@ vi.mock('../services/api', () => ({
uploadFile: vi.fn(),
uploadGalleryVideo: vi.fn(),
}));
+vi.mock('../components/videoGen/GalleryVideoPicker', () => ({
+ default: ({ open, onSelect, onClose }) => (open ? (
+ <button type="button" onClick={() => { onSelect({ filename: 'take.mp4', prompt: '(no prompt)', previewUrl: '/data/video-thumbnails/take.jpg' }); onClose(); }}>Choose example video</button>
+ ) : null),
+}));
vi.mock('../hooks/useProviderModels', () => ({
default: () => ({
providers: [{ id: 'api-1', name: 'Example API', type: 'api', enabled: true }],
@@ -280,6 +285,22 @@ describe('Code Animation page', () => {
expect(screen.getByText(/brief changed since this prompt was built/i)).toBeInTheDocument();
});
+ it('sends a picked Media History reference video with its note and reserves its image slots', async () => {
+ const user = userEvent.setup();
+ await renderPage();
+ expect(screen.getByText('Reference images (0/8)')).toBeInTheDocument();
+ await user.click(screen.getByRole('button', { name: /pick or upload a video/i }));
+ await user.click(screen.getByRole('button', { name: 'Choose example video' }));
+ expect(screen.getByText('Reference images (0/5)')).toBeInTheDocument();
+ await user.type(screen.getByLabelText('Note for take.mp4'), 'cut rhythm');
+ await user.type(screen.getByLabelText(/what happens/i), 'A lantern drifts over a harbor');
+ await user.click(screen.getByRole('button', { name: /build prompt/i }));
+ await waitFor(() => expect(buildCodeAnimationPrompt).toHaveBeenCalledTimes(1));
+ expect(buildCodeAnimationPrompt.mock.calls[0][0].referenceVideo).toEqual({ filename: 'take.mp4', label: 'take.mp4', note: 'cut rhythm' });
+ await user.click(screen.getByRole('button', { name: 'Remove reference video' }));
+ expect(screen.getByText('Reference images (0/8)')).toBeInTheDocument();
+ });
+
it('writes the brief from the universe and drops it into the form', async () => {
const user = userEvent.setup();
generateCodeAnimationBrief.mockResolvedValue({
diff --git a/server/routes/codeAnimation.js b/server/routes/codeAnimation.js
index 0093185a33..4698dd5dc9 100644
--- a/server/routes/codeAnimation.js
+++ b/server/routes/codeAnimation.js
@@ -116,6 +116,12 @@ const briefSchema = z.object({
label: z.string().trim().max(200).default(''),
note: z.string().trim().max(L.referenceNoteMax).default(''),
})).max(L.referenceImagesMax).default([]),
+ // A Media History video (data/videos basename) studied as the quality bar.
+ referenceVideo: z.object({
+ filename: uploadFilenameSchema,
+ label: z.string().trim().max(200).default(''),
+ note: z.string().trim().max(L.referenceNoteMax).default(''),
+ }).strict().nullable().optional(),
audio: audioSchema,
}).strict();
diff --git a/server/routes/codeAnimation.test.js b/server/routes/codeAnimation.test.js
index f6d7c25e3c..568a0e4013 100644
--- a/server/routes/codeAnimation.test.js
+++ b/server/routes/codeAnimation.test.js
@@ -1,6 +1,7 @@
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import express from 'express';
-import { mkdirSync, writeFileSync } from 'fs';
+import { existsSync, mkdirSync, writeFileSync } from 'fs';
+import { execFileSync, spawnSync } from 'child_process';
import { join } from 'path';
import { request } from '../lib/testHelper.js';
import { errorMiddleware, ServerError } from '../lib/errorHandler.js';
@@ -50,6 +51,7 @@ vi.mock('../services/promptRunner.js', () => ({
runPromptThroughProvider: vi.fn(),
resolveProviderAndModel: vi.fn(),
assertProvider: vi.fn(),
+ assertVisionRunUsedImages: vi.fn(),
}));
vi.mock('../services/mediaJobQueue/index.js', () => ({
enqueueJob: vi.fn(async () => ({ jobId: 'media-export', position: 1, status: 'queued' })),
@@ -625,6 +627,18 @@ describe('POST /api/code-animation/generate', () => {
expect(call.prompt).toContain('attached to this request');
});
+ it('attaches the references for a vision-capable CLI provider instead of only naming their paths', async () => {
+ getProviderById.mockResolvedValue({ id: 'cli-claude', type: 'cli', command: 'claude', enabled: true });
+ runPromptThroughProvider.mockResolvedValue({ text: '```html\n<!DOCTYPE html><html></html>\n```', provider: { id: 'cli-claude', type: 'cli', command: 'claude' } });
+ const app = makeApp();
+ const res = await request(app).post('/api/code-animation/generate').send({ ...brief, providerId: 'cli-claude' });
+ expect(res.status).toBe(202);
+ await pollUntilSettled(app, res.body.id);
+ const call = runPromptThroughProvider.mock.calls[0][0];
+ expect(call.screenshots).toEqual([join(PATHS.imageRefs, 'style-ref.png'), join(PATHS.images, 'pin.png'), join(PATHS.imageRefs, 'sheet.png')]);
+ expect(call.prompt).toContain(join(PATHS.images, 'pin.png'));
+ });
+
it('fails the job when the response holds no HTML document', async () => {
getProviderById.mockResolvedValue({ id: 'cli-1', type: 'cli', enabled: true });
runPromptThroughProvider.mockResolvedValue({ text: 'I wrote the file to disk.', provider: { id: 'cli-1' } });
@@ -655,3 +669,43 @@ describe('POST /api/code-animation/generate', () => {
expect((await request(makeApp()).get('/api/code-animation/generate/nope')).status).toBe(404);
});
});
+
+// A real (tiny) Media History video through real ffmpeg: a red second then a
+// blue second, so the measured rhythm has exactly one cut at 1s.
+const hasFfmpeg = spawnSync('ffmpeg', ['-version']).status === 0;
+describe.skipIf(!hasFfmpeg)('reference video', () => {
+ beforeAll(() => {
+ mkdirSync(PATHS.videos, { recursive: true });
+ execFileSync('ffmpeg', ['-v', 'error', '-y', '-f', 'lavfi', '-i', 'color=red:s=320x180:d=1:r=24', '-f', 'lavfi', '-i', 'color=blue:s=320x180:d=1:r=24',
+ '-filter_complex', '[0][1]concat=n=2:v=1', '-pix_fmt', 'yuv420p', join(PATHS.videos, 'reference-take.mp4')]);
+ });
+
+ it('samples a Media History video into stills and a measured cut rhythm for the prompt', async () => {
+ const app = makeApp();
+ const res = await request(app).post('/api/code-animation/prompt')
+ .send({ ...brief, referenceVideo: { filename: 'reference-take.mp4', label: 'Kakigori short', note: 'the finish' } });
+ expect(res.status).toBe(200);
+ expect(res.body.prompt).toContain('REFERENCE VIDEO — "Kakigori short"');
+ expect(res.body.prompt).toContain('2 shots in 2.0s');
+ expect(res.body.prompt).toContain('cuts at 1.0s');
+ expect(res.body.prompt).toContain('What to take from it: the finish');
+ const fromVideo = res.body.attachments.filter((item) => item.origin === 'reference-video');
+ expect(fromVideo).toHaveLength(3);
+ for (const item of fromVideo) expect(existsSync(join(PATHS.videoThumbnails, decodeURIComponent(item.url.split('/').pop())))).toBe(true);
+ // The stills take the first reference slots; the brief still fits 8 in all.
+ expect(res.body.attachments[0].origin).toBe('reference-video');
+ expect(res.body.attachments.length).toBeLessThanOrEqual(8);
+ });
+
+ it('refuses an unknown video and a brief whose images leave no room for its stills', async () => {
+ const app = makeApp();
+ const missing = await request(app).post('/api/code-animation/prompt').send({ ...brief, referenceVideo: { filename: 'nope.mp4' } });
+ expect(missing.status).toBe(400);
+ expect(missing.body.code).toBe('REFERENCE_NOT_FOUND');
+ const crowded = await request(app).post('/api/code-animation/prompt').send({ ...brief,
+ referenceImages: Array.from({ length: 6 }, () => ({ filename: 'abc12345-hero.png' })),
+ referenceVideo: { filename: 'reference-take.mp4' } });
+ expect(crowded.status).toBe(400);
+ expect(crowded.body.code).toBe('REFERENCE_LIMIT');
+ });
+});
diff --git a/server/services/codeAnimation/index.js b/server/services/codeAnimation/index.js
index a4e6a50375..9c68e4af62 100644
--- a/server/services/codeAnimation/index.js
+++ b/server/services/codeAnimation/index.js
@@ -14,6 +14,8 @@
import { randomUUID } from 'crypto';
import { ServerError } from '../../lib/errorHandler.js';
+import { isVisionCapableCliProvider } from '../../lib/localModelHeuristics.js';
+import { isVisionCapableCodexTuiProvider } from '../../lib/codex.js';
import { emitCodeAnimationChanged } from '../socket.js';
import { PATHS } from '../../lib/paths.js';
import { makePathResolver } from '../../lib/pathSafety.js';
@@ -216,22 +218,31 @@ async function resolveAudio(audio) {
*/
export async function buildCodeAnimationRequest(input, { delivery = 'copy' } = {}) {
const uploads = resolveUploadedImages(input.referenceImages || []);
+ const videoSlots = CODE_ANIMATION_LIMITS.referenceVideoImageSlots;
+ if (input.referenceVideo && uploads.length + videoSlots > CODE_ANIMATION_LIMITS.referenceImagesMax) {
+ throw new ServerError(`A reference video uses ${videoSlots} of the ${CODE_ANIMATION_LIMITS.referenceImagesMax} reference slots; remove some reference images`, { status: 400, code: 'REFERENCE_LIMIT' });
+ }
+ // ffmpeg sampling is imported only when a brief actually carries a video.
+ const referenceVideo = input.referenceVideo
+ ? await (await import('./referenceVideo.js')).resolveReferenceVideo(input.referenceVideo)
+ : null;
+ const videoImages = referenceVideo?.images || [];
const audio = await resolveAudio(input.audio);
const universe = await resolveUniverse(input.universeId, {
- imageSlots: Math.max(0, CODE_ANIMATION_LIMITS.referenceImagesMax - uploads.length),
+ imageSlots: Math.max(0, CODE_ANIMATION_LIMITS.referenceImagesMax - videoImages.length - uploads.length),
});
// The universe is the art direction, so its linked mood board is the default:
// an ABSENT moodBoardId follows the universe, an explicit null means none.
const moodBoardId = input.moodBoardId === undefined ? universe?.moodBoardId : input.moodBoardId;
- // Reference-image slots go to the user's own uploads first, then the
- // universe's style images, then the board's pins.
+ // Reference-image slots go to the reference video's stills first, then the
+ // user's own uploads, then the universe's style images, then the board's pins.
const universeImages = universe?.images || [];
const { board, images: boardImages } = await resolveMoodBoard(moodBoardId, {
imageSlots: input.includeMoodBoardImages === false
? 0
- : Math.max(0, CODE_ANIMATION_LIMITS.referenceImagesMax - uploads.length - universeImages.length),
+ : Math.max(0, CODE_ANIMATION_LIMITS.referenceImagesMax - videoImages.length - uploads.length - universeImages.length),
});
- const referenceImages = [...uploads, ...universeImages, ...boardImages];
+ const referenceImages = [...videoImages, ...uploads, ...universeImages, ...boardImages];
const promptInput = {
title: input.title,
concept: input.concept,
@@ -247,6 +258,7 @@ export async function buildCodeAnimationRequest(input, { delivery = 'copy' } = {
universe,
moodBoard: board,
referenceImages,
+ referenceVideo,
};
const prompt = buildCodeAnimationPrompt({ ...promptInput, delivery });
return {
@@ -396,8 +408,11 @@ export async function pageCodeAnimationJobs({ limit = JOB_PAGE_SIZE, cursor } =
};
}
+const canAttachImages = (provider) => provider.type === 'api'
+ || isVisionCapableCliProvider(provider) || isVisionCapableCodexTuiProvider(provider);
+
async function runGeneration({ provider, model, effort, prompt, referencePaths }) {
- const { runPromptThroughProvider } = await import('../promptRunner.js');
+ const { runPromptThroughProvider, assertVisionRunUsedImages } = await import('../promptRunner.js');
const result = await runPromptThroughProvider({
provider,
model: model || undefined,
@@ -407,9 +422,12 @@ async function runGeneration({ provider, model, effort, prompt, referencePaths }
// Start authoring in runtime data. This does not restrict CLI/TUI host tools;
// operator authorization is separate from the later render containment.
cwd: PATHS.data,
- screenshots: provider.type === 'api' ? referencePaths : [],
+ // Every provider that can read images gets them as attachments; a
+ // non-vision CLI keeps only the on-disk paths written into the prompt.
+ screenshots: canAttachImages(provider) ? referencePaths : [],
timeout: Math.max(provider.timeout || 0, 15 * 60 * 1000),
});
+ if (referencePaths.length && canAttachImages(provider)) assertVisionRunUsedImages(result, provider);
const html = extractAnimationHtml(result.text);
if (!html) throw new Error('The model response did not contain an HTML document');
return { html, provider: result.provider?.id || provider.id, model: result.model || null, runId: result.runId || null };
diff --git a/server/services/codeAnimation/prompt.js b/server/services/codeAnimation/prompt.js
index 2fce746c6a..528b30052d 100644
--- a/server/services/codeAnimation/prompt.js
+++ b/server/services/codeAnimation/prompt.js
@@ -73,6 +73,8 @@ export const CODE_ANIMATION_LIMITS = Object.freeze({
textMax: 4_000,
styleNotesMax: 2_000,
referenceImagesMax: 8,
+ // A reference video becomes a contact sheet plus two keyframes.
+ referenceVideoImageSlots: 3,
referenceNoteMax: 300,
audioNotesMax: 1_500,
});
@@ -137,12 +139,26 @@ function referenceImagesSection(images, delivery) {
const rows = images.map((image, index) => {
const where = delivery === 'cli' && image.path ? ` (${image.path})` : '';
const note = isNonBlankStr(image.note) ? ` — ${trimTo(image.note, CODE_ANIMATION_LIMITS.referenceNoteMax)}` : '';
- const origin = { 'mood-board': ' [from the mood board]', universe: ' [universe style image]' }[image.origin] || '';
+ const origin = { 'mood-board': ' [from the mood board]', universe: ' [universe style image]', 'reference-video': ' [from the reference video]' }[image.origin] || '';
return `${index + 1}. ${image.label}${origin}${where}${note}`;
});
return `${intro}\n${rows.join('\n')}\nUse them for palette, composition, silhouettes, texture, and lighting. Do NOT embed, fetch, or base64 them — recreate what matters procedurally in code.`;
}
+// A model cannot watch the video: it gets the sampled stills (listed with the
+// reference images) plus the measured cut rhythm, and is told what to take.
+function referenceVideoSection(video) {
+ if (!video) return '';
+ const { durationSec, cuts = [] } = video;
+ const shots = cuts.length + 1;
+ const rhythm = cuts.length
+ ? `${shots} shots in ${durationSec.toFixed(1)}s (average ${(durationSec / shots).toFixed(1)}s per shot); cuts at ${cuts.map((t) => `${t.toFixed(1)}s`).join(', ')}.`
+ : `One continuous ${durationSec.toFixed(1)}s shot with no detected cuts.`;
+ const note = isNonBlankStr(video.note) ? `\nWhat to take from it: ${trimTo(video.note, CODE_ANIMATION_LIMITS.referenceNoteMax)}` : '';
+ return `REFERENCE VIDEO — "${video.label}": the quality bar to match. Its contact sheet and two keyframes are among the reference images below. Measured rhythm: ${rhythm}${note}
+Study and match its craft, not its content: shot rhythm and coverage (wides, close-ups, inserts), camera moves and focus pulls, lighting and time of day, how it renders surfaces, and its finish (depth of field, bloom on light sources, colour grade, grain). Scale its cut rhythm to this piece's duration. Reproduce that fidelity with your own original subject, characters and story — never copy its characters, logos, text or shots.`;
+}
+
function audioSection({ audio, soundtrack, durationSeconds }) {
if (audio) {
const lines = [
@@ -267,6 +283,7 @@ export function buildCodeAnimationPrompt({
universe = null,
moodBoard = null,
referenceImages = [],
+ referenceVideo = null,
delivery = 'copy',
}) {
const { width, height } = resolveFrameSize(format.aspectRatio, format.resolution);
@@ -282,6 +299,8 @@ export function buildCodeAnimationPrompt({
sections.push(`ART DIRECTION:\n${artDirectionSection({ universe, styleNotes, styleGrammarId, hasMoodBoard: !!moodBoard })}`);
const boardText = moodBoardSection(moodBoard);
if (boardText) sections.push(boardText);
+ const videoText = referenceVideoSection(referenceVideo);
+ if (videoText) sections.push(videoText);
const imagesText = referenceImagesSection(referenceImages, delivery);
if (imagesText) sections.push(imagesText);
sections.push(`SOUND:\n${audioSection({ audio, soundtrack, durationSeconds })}`);
diff --git a/server/services/codeAnimation/referenceVideo.js b/server/services/codeAnimation/referenceVideo.js
new file mode 100644
index 0000000000..f2238b83e4
--- /dev/null
+++ b/server/services/codeAnimation/referenceVideo.js
@@ -0,0 +1,94 @@
+/**
+ * Turn a Media History video into what a coding model can actually study: a
+ * phone-sized contact sheet of the whole clip, two full-size keyframes, and the
+ * measured shot-cut times. A code model cannot watch a video, so the cut rhythm
+ * is handed over as numbers and the look as stills. Derived files are cached by
+ * the source file's identity, so re-previewing a prompt never re-runs ffmpeg.
+ */
+import { createHash } from 'crypto';
+import { readFile, stat, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { ServerError } from '../../lib/errorHandler.js';
+import { ensureDir } from '../../lib/fileCore.js';
+import { findFfmpeg, probeVideoDuration, runFfmpegProcess } from '../../lib/ffmpeg.js';
+import { PATHS } from '../../lib/paths.js';
+import { makePathResolver } from '../../lib/pathSafety.js';
+import { trimTo } from '../../lib/textUtils.js';
+
+const VIDEO_EXTENSIONS = ['mp4', 'webm', 'mov', 'm4v'];
+const resolveGalleryVideo = makePathResolver(() => PATHS.videos, { extensions: VIDEO_EXTENSIONS });
+
+// ffmpeg scene score above which a frame change counts as a cut.
+const CUT_THRESHOLD = 0.3;
+const MAX_CUTS = 120;
+
+const thumbUrl = (name) => `/data/video-thumbnails/${encodeURIComponent(name)}`;
+
+/** Parse `pts_time:` stamps from ffmpeg's showinfo log into rounded seconds. */
+export function parseCutTimes(stderr) {
+ const times = [];
+ for (const match of String(stderr || '').matchAll(/pts_time:([0-9.]+)/g)) {
+ const t = Math.round(Number(match[1]) * 100) / 100;
+ if (Number.isFinite(t) && t > 0 && (!times.length || t - times.at(-1) >= 0.2)) times.push(t);
+ }
+ return times.slice(0, MAX_CUTS);
+}
+
+async function detectCuts(ffmpeg, videoPath) {
+ const result = await runFfmpegProcess({
+ bin: ffmpeg,
+ args: ['-hide_banner', '-i', videoPath, '-an', '-vf', `scale=320:-2,select='gt(scene,${CUT_THRESHOLD})',showinfo`, '-f', 'null', '-'],
+ returnStderr: true,
+ stderrTailBytes: 400000,
+ });
+ return result.ok ? parseCutTimes(result.stderr) : [];
+}
+
+async function extractKeyframe(ffmpeg, videoPath, atSec, outputPath) {
+ const result = await runFfmpegProcess({
+ bin: ffmpeg,
+ args: ['-hide_banner', '-loglevel', 'error', '-ss', atSec.toFixed(2), '-i', videoPath, '-frames:v', '1', '-vf', 'scale=1280:-2', '-q:v', '3', '-y', outputPath],
+ });
+ if (!result.ok) throw new Error(`Reference keyframe failed: ${result.reason}`);
+}
+
+/**
+ * Resolve and sample a brief's reference video.
+ * @returns {Promise<{label, note, durationSec, cuts, images: Array<{label, origin, note, path, url}>}>}
+ */
+export async function resolveReferenceVideo(ref) {
+ const path = resolveGalleryVideo(ref.filename);
+ if (!path) throw new ServerError(`Reference video not found: ${ref.filename}`, { status: 400, code: 'REFERENCE_NOT_FOUND' });
+ const ffmpeg = await findFfmpeg();
+ if (!ffmpeg) throw new ServerError('ffmpeg is required to study a reference video', { status: 503, code: 'FFMPEG_UNAVAILABLE' });
+ const info = await stat(path);
+ const key = createHash('sha256').update(`${path}\0${info.size}\0${info.mtimeMs}`).digest('hex').slice(0, 16);
+ const names = { sheet: `refvideo-${key}-sheet.png`, early: `refvideo-${key}-k1.jpg`, late: `refvideo-${key}-k2.jpg`, meta: `refvideo-${key}.json` };
+ const at = (name) => join(PATHS.videoThumbnails, name);
+ await ensureDir(PATHS.videoThumbnails);
+ let meta = await readFile(at(names.meta), 'utf8').then(JSON.parse).catch(() => null);
+ if (!meta) {
+ const durationSec = await probeVideoDuration(path);
+ if (!durationSec) throw new ServerError('Could not read the reference video', { status: 400, code: 'REFERENCE_UNREADABLE' });
+ const { encodeReferenceContactSheet } = await import('../htmlComposition/encode.js');
+ // ~48 tiles across the whole clip, never finer than every half second.
+ const { times } = await encodeReferenceContactSheet(path, at(names.sheet), { everySec: Math.max(0.5, durationSec / 48) });
+ await extractKeyframe(ffmpeg, path, durationSec * 0.3, at(names.early));
+ await extractKeyframe(ffmpeg, path, durationSec * 0.7, at(names.late));
+ meta = { durationSec, cuts: await detectCuts(ffmpeg, path), sheetEverySec: times.length > 1 ? times[1] - times[0] : durationSec };
+ await writeFile(at(names.meta), JSON.stringify(meta));
+ }
+ const label = trimTo(ref.label, 120) || ref.filename;
+ const image = (name, what) => ({ label: `${label} — ${what}`, origin: 'reference-video', note: '', path: at(name), url: thumbUrl(name) });
+ return {
+ label,
+ note: ref.note || '',
+ durationSec: meta.durationSec,
+ cuts: meta.cuts,
+ images: [
+ image(names.sheet, `contact sheet, one tile every ${meta.sheetEverySec.toFixed(1)}s, read left to right`),
+ image(names.early, `frame at ${(meta.durationSec * 0.3).toFixed(1)}s`),
+ image(names.late, `frame at ${(meta.durationSec * 0.7).toFixed(1)}s`),
+ ],
+ };
+}