Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
Add a tunable film look for music-video previews, renders and gallery stills
Claudeeff60b6992ca
diff --git a/client/src/components/media/FilmLookControls.jsx b/client/src/components/media/FilmLookControls.jsxnew file mode 100644index 0000000000..739798e625--- /dev/null+++ b/client/src/components/media/FilmLookControls.jsx@@ -0,0 +1,141 @@+import { useId, useState } from 'react';+import { Copy, RotateCcw } from 'lucide-react';+import {+ FILM_LOOK_CONTROLS, FILM_LOOK_GROUPS, FILM_LOOK_PRESETS, describeFilmLook, filmLookPreset, normalizeFilmLook,+} from '../../lib/filmLook.js';+import { copyToClipboard } from '../../lib/clipboard';++const groupControls = (groupId) => FILM_LOOK_CONTROLS.filter((control) => control.group === groupId);+// Modifiers and tints ride under the effect they shape: they show once that effect is on.+const dependsOn = {+ halationColor: 'halation', castColor: 'cast', shadowColor: 'splitTone', highlightColor: 'splitTone',+ grainSize: 'grain', grainColor: 'grain', leakColor: 'leak',+};+const shown = (control, look) => !dependsOn[control.id] || Math.abs(look[dependsOn[control.id]]) > 0;+const percent = (control, value) => (control.min < 0 ? `${value > 0 ? '+' : ''}${Math.round(value * 100)}` : `${Math.round(value * 100)}%`);++function Slider({ control, value, onChange, onCommit, id }) {+ return (+ <div className="space-y-0.5">+ <div className="flex items-baseline justify-between gap-2 text-xs">+ <label htmlFor={id} className="min-w-0 truncate">+ <span className="text-port-text">{control.label}</span>{' '}+ <span className="ml-1.5 text-port-text-muted">{control.term}</span>+ </label>+ <span className="tabular-nums text-port-text-muted">{percent(control, value)}</span>+ </div>+ <input id={id} type="range" min={control.min} max={control.max} step={control.step} value={value} title={control.hint}+ onChange={(event) => onChange(Number(event.target.value))}+ onPointerUp={onCommit} onKeyUp={onCommit} onBlur={onCommit}+ className="block h-6 w-full accent-port-accent" />+ </div>+ );+}++/**+ * The film look's controls: preset chips, then every slider, color and toggle+ * grouped the way a colorist thinks (focus & glow, color, texture, frame).+ * Each row names the effect in photography terms, and the "In a prompt" box+ * rewrites the current settings as the words that ask an image or video model+ * for the same qualities, so tuning a look also teaches the vocabulary.+ *+ * `onChange(look)` fires on every slider move (for a live preview);+ * `onCommit(look)` fires when a control is released (to save). Both receive the+ * whole normalized look. Controlled: `look` is the current value (null = clean).+ */+export default function FilmLookControls({ look: given, onChange, onCommit, compact = false }) {+ const look = normalizeFilmLook(given) || filmLookPreset('none');+ const base = useId();+ const [openGroups, setOpenGroups] = useState(() => new Set(compact ? [] : FILM_LOOK_GROUPS.map((group) => group.id)));+ const set = (patch, { commit = true } = {}) => {+ const next = normalizeFilmLook({ ...look, ...patch, preset: 'custom' });+ onChange?.(next);+ if (commit) onCommit?.(next);+ };+ const live = (patch) => set(patch, { commit: false });+ const commit = () => onCommit?.(look);+ const applyPreset = (id) => { const next = filmLookPreset(id); onChange?.(next); onCommit?.(next); };+ const words = describeFilmLook(look);+ const toggleGroup = (id) => setOpenGroups((current) => {+ const next = new Set(current);+ if (next.has(id)) next.delete(id); else next.add(id);+ return next;+ });+ return (+ <div className="space-y-3 text-xs">+ <div>+ <div className="mb-1 flex items-center justify-between gap-2">+ <span className="text-port-text-muted">Presets</span>+ <button type="button" onClick={() => applyPreset('none')} className="inline-flex min-h-[44px] items-center gap-1 px-1 text-port-accent sm:min-h-0" aria-label="Reset to a clean look">+ <RotateCcw size={12} aria-hidden="true" /> Reset+ </button>+ </div>+ <div className="flex flex-wrap gap-1.5" role="group" aria-label="Film look presets">+ {FILM_LOOK_PRESETS.filter((preset) => preset.id !== 'none').map((preset) => (+ <button key={preset.id} type="button" onClick={() => applyPreset(preset.id)} title={preset.summary} aria-pressed={look.preset === preset.id}+ className={`min-h-[44px] rounded-full border px-3 py-1 sm:min-h-0 ${look.preset === preset.id ? 'border-port-accent bg-port-accent/20 text-port-accent' : 'border-port-border bg-port-bg text-port-text-muted hover:text-port-text'}`}>+ {preset.label}+ </button>+ ))}+ </div>+ {look.preset !== 'none' && <p className="mt-1 text-port-text-muted">{FILM_LOOK_PRESETS.find((preset) => preset.id === look.preset)?.summary || 'A custom look. Save it to keep it on this project.'}</p>}+ </div>++ {FILM_LOOK_GROUPS.map((group) => {+ const controls = groupControls(group.id).filter((control) => shown(control, look));+ const open = openGroups.has(group.id);+ const active = controls.filter((control) => !control.type && control.id in look && Math.abs(look[control.id]) > 0 && !dependsOn[control.id]).length;+ return (+ <section key={group.id} aria-label={group.label} className="rounded border border-port-border">+ <button type="button" onClick={() => toggleGroup(group.id)} aria-expanded={open}+ className="flex min-h-[44px] w-full items-center justify-between gap-2 px-2 py-1 text-left">+ <span className="font-medium text-port-text">{group.label}</span>+ <span className="text-port-text-muted">{active ? `${active} on` : 'off'} {open ? '▴' : '▾'}</span>+ </button>+ {open && (+ <div className="grid grid-cols-1 gap-x-4 gap-y-2 px-2 pb-2 sm:grid-cols-2">+ {controls.map((control) => {+ const id = `${base}-${control.id}`;+ if (control.type === 'color') {+ return (+ <div key={control.id} className="flex items-center justify-between gap-2">+ <label htmlFor={id} className="min-w-0 truncate" title={control.hint}>+ <span className="text-port-text">{control.label}</span>{' '}+ <span className="ml-1.5 text-port-text-muted">{control.term}</span>+ </label>+ <input id={id} type="color" value={look[control.id]} onChange={(event) => set({ [control.id]: event.target.value })}+ className="h-8 w-12 shrink-0 rounded border border-port-border bg-port-bg" />+ </div>+ );+ }+ if (control.type === 'toggle') {+ return (+ <label key={control.id} htmlFor={id} title={control.hint} className="flex min-h-[44px] items-center gap-2 sm:min-h-0">+ <input id={id} type="checkbox" checked={!!look[control.id]} onChange={(event) => set({ [control.id]: event.target.checked })} className="accent-port-accent" />+ <span className="text-port-text">{control.label}</span>{' '}+ <span className="text-port-text-muted">{control.term}</span>+ </label>+ );+ }+ return <Slider key={control.id} id={id} control={control} value={look[control.id]} onChange={(value) => live({ [control.id]: value })} onCommit={commit} />;+ })}+ </div>+ )}+ </section>+ );+ })}++ <div className="rounded border border-port-border bg-port-bg/60 p-2">+ <div className="mb-1 flex items-center justify-between gap-2">+ <span className="text-port-text-muted">In a prompt</span>+ {words && (+ <button type="button" onClick={() => copyToClipboard(words, 'Look words copied')} className="inline-flex min-h-[44px] items-center gap-1 px-1 text-port-accent sm:min-h-0" aria-label="Copy the look as prompt words">+ <Copy size={12} aria-hidden="true" /> Copy+ </button>+ )}+ </div>+ <p className="text-port-text" data-testid="film-look-words">{words || 'Move a control and the words an image or video model understands for it appear here.'}</p>+ </div>+ </div>+ );+}diff --git a/client/src/components/media/FilmLookControls.test.jsx b/client/src/components/media/FilmLookControls.test.jsxnew file mode 100644index 0000000000..6a71269f3e--- /dev/null+++ b/client/src/components/media/FilmLookControls.test.jsx@@ -0,0 +1,37 @@+import { describe, expect, it, vi } from 'vitest';+import { fireEvent, render, screen } from '@testing-library/react';+import FilmLookControls from './FilmLookControls.jsx';+import { filmLookPreset } from '../../lib/filmLook.js';++describe('FilmLookControls', () => {+ it('applies a preset as a whole saved look, names each control in photography terms and writes the look as prompt words', () => {+ const onChange = vi.fn();+ const onCommit = vi.fn();+ render(<FilmLookControls look={null} onChange={onChange} onCommit={onCommit} />);+ expect(screen.getByTestId('film-look-words')).toHaveTextContent(/Move a control/);++ fireEvent.click(screen.getByRole('button', { name: 'Polaroid' }));+ const polaroid = filmLookPreset('polaroid');+ expect(onChange).toHaveBeenLastCalledWith(polaroid);+ expect(onCommit).toHaveBeenLastCalledWith(polaroid);+ });++ it('streams slider moves without saving, saves on release, and reveals a tint only once its effect is on', () => {+ const onChange = vi.fn();+ const onCommit = vi.fn();+ const { rerender } = render(<FilmLookControls look={filmLookPreset('none')} onChange={onChange} onCommit={onCommit} />);+ expect(screen.queryByLabelText(/Halation color/)).toBeNull();++ const halation = screen.getByLabelText(/^Halation halation · highlight bloom$/);+ fireEvent.change(halation, { target: { value: '0.7' } });+ expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ halation: 0.7, preset: 'custom' }));+ expect(onCommit).not.toHaveBeenCalled();++ const live = onChange.mock.calls.at(-1)[0];+ rerender(<FilmLookControls look={live} onChange={onChange} onCommit={onCommit} />);+ fireEvent.pointerUp(screen.getByLabelText(/^Halation halation · highlight bloom$/));+ expect(onCommit).toHaveBeenCalledWith(expect.objectContaining({ halation: 0.7 }));+ expect(screen.getByLabelText(/Halation color/)).toBeInTheDocument();+ expect(screen.getByTestId('film-look-words')).toHaveTextContent(/halation/);+ });+});diff --git a/client/src/components/media/FilmLookEditor.jsx b/client/src/components/media/FilmLookEditor.jsxnew file mode 100644index 0000000000..2e30fd54ea--- /dev/null+++ b/client/src/components/media/FilmLookEditor.jsx@@ -0,0 +1,87 @@+import { useEffect, useState } from 'react';+import { Aperture, Save, X } from 'lucide-react';+import Modal from '../ui/Modal';+import toast from '../ui/Toast';+import FilmLookControls from './FilmLookControls.jsx';+import FilmLookPreview from './FilmLookPreview.jsx';+import { applyImageFilmLook } from '../../services/apiImageVideo';+import { filmLookPreset, isFilmLookNeutral, normalizeFilmLook } from '../../lib/filmLook.js';++/**+ * Tune a film look on one gallery image and keep it: "Save filtered copy"+ * bakes the look into a new image beside the untouched original (the server+ * renders the same filter at full size), and, inside a music video project,+ * "Use on project" makes it the project's finishing look for the live preview+ * and the final render.+ *+ * `projectLook` — optional `{ look, onSave(look), name }` from the hosting+ * project: the editor starts from that look and can write back to it.+ */+export default function FilmLookEditor({ item, open, onClose, onComplete, projectLook = null }) {+ const start = () => normalizeFilmLook(projectLook?.look) || normalizeFilmLook(item?.filmLook) || filmLookPreset('none');+ const [look, setLook] = useState(start);+ const [saving, setSaving] = useState(false);+ const [savingProject, setSavingProject] = useState(false);+ // A different image (or a reopen) starts over from the project's look, never from the last session's sliders.+ useEffect(() => { if (open) setLook(start()); }, [open, item?.key]); // eslint-disable-line react-hooks/exhaustive-deps+ if (!item) return null;+ const neutral = isFilmLookNeutral(look);+ const saveCopy = async () => {+ if (saving || neutral) return;+ setSaving(true);+ const variant = await applyImageFilmLook(item.filename, look, { silent: true }).catch((err) => {+ toast.error(err?.message || 'Could not save the filtered copy');+ return null;+ });+ setSaving(false);+ if (!variant) return;+ toast.success(`Saved ${variant.filename}`);+ await onComplete?.(variant);+ onClose();+ };+ const saveProject = async () => {+ if (!projectLook?.onSave || savingProject) return;+ setSavingProject(true);+ await Promise.resolve(projectLook.onSave(neutral ? null : look))+ .then(() => toast.success(neutral ? 'Project look cleared' : `Look saved to ${projectLook.name || 'the project'}`))+ .catch((err) => toast.error(err?.message || 'Could not save the project look'))+ .finally(() => setSavingProject(false));+ };+ return (+ <Modal open={open} onClose={onClose} size="3xl" zIndexClassName="z-[70]" backdropClassName="bg-black/85" ariaLabelledBy="film-look-title"+ panelClassName="overflow-hidden bg-port-card border border-port-border rounded-xl shadow-2xl flex flex-col">+ <header className="flex items-center justify-between gap-3 border-b border-port-border px-3 py-2">+ <div className="flex min-w-0 items-center gap-2">+ <Aperture className="h-4 w-4 shrink-0 text-port-accent" aria-hidden="true" />+ <h2 id="film-look-title" className="truncate text-sm font-semibold text-port-text">Film look</h2>+ </div>+ <button type="button" onClick={onClose} aria-label="Close" className="flex min-h-[44px] min-w-[44px] items-center justify-center rounded p-1.5 text-port-text-muted hover:text-port-text">+ <X className="h-4 w-4" />+ </button>+ </header>+ <div className="flex min-h-0 flex-1 flex-col md:flex-row">+ <div className="flex max-h-[42dvh] shrink-0 items-center justify-center bg-black md:max-h-none md:flex-1">+ <FilmLookPreview src={item.downloadUrl || item.previewUrl} alt={item.prompt} look={look} className="flex max-h-[42dvh] items-center justify-center md:max-h-[80dvh]" />+ </div>+ <div className="flex min-h-0 w-full flex-col border-t border-port-border md:w-96 md:border-l md:border-t-0">+ <div className="min-h-0 flex-1 overflow-y-auto p-3">+ <FilmLookControls look={look} onChange={setLook} />+ </div>+ <div className="flex flex-wrap gap-2 border-t border-port-border p-2">+ <button type="button" onClick={saveCopy} disabled={saving || neutral} title={neutral ? 'Move a control first' : 'Render this look into a new image; the original stays as it is'}+ className="inline-flex min-h-[44px] flex-1 items-center justify-center gap-1.5 rounded bg-port-accent px-3 text-xs text-white disabled:opacity-50">+ <Save className="h-3.5 w-3.5" aria-hidden="true" /> {saving ? 'Saving…' : 'Save filtered copy'}+ </button>+ {projectLook?.onSave && (+ <button type="button" onClick={saveProject} disabled={savingProject}+ title="Make this the project's finishing look: the live preview and the final render are viewed through it"+ className="inline-flex min-h-[44px] flex-1 items-center justify-center gap-1.5 rounded border border-port-accent px-3 text-xs text-port-accent disabled:opacity-50">+ {savingProject ? 'Saving…' : neutral ? 'Clear project look' : 'Use on project'}+ </button>+ )}+ </div>+ </div>+ </div>+ </Modal>+ );+}diff --git a/client/src/components/media/FilmLookPreview.jsx b/client/src/components/media/FilmLookPreview.jsxnew file mode 100644index 0000000000..b43463a9ed--- /dev/null+++ b/client/src/components/media/FilmLookPreview.jsx@@ -0,0 +1,44 @@+import { useEffect, useRef, useState } from 'react';+import { filmLookFilterMarkup, isFilmLookNeutral, normalizeFilmLook } from '../../lib/filmLook.js';++/**+ * An image seen through a film look, live: the same SVG filter the render and+ * the gallery bake use, sized to the image as displayed so every radius reads+ * as it will at full size. Press and hold (or press space) on the picture to+ * see the original underneath. `frame` re-seeds the grain and drift.+ */+export default function FilmLookPreview({ src, alt = '', look, frame = 0, className = '' }) {+ const imgRef = useRef(null);+ const [size, setSize] = useState({ width: 0, height: 0 });+ const [showOriginal, setShowOriginal] = useState(false);+ const filterId = useRef(`portos-film-look-${Math.random().toString(36).slice(2, 9)}`).current;+ useEffect(() => {+ const img = imgRef.current;+ if (!img) return undefined;+ const measure = () => setSize({ width: Math.round(img.clientWidth), height: Math.round(img.clientHeight) });+ measure();+ if (typeof ResizeObserver === 'undefined') return undefined;+ const observer = new ResizeObserver(measure);+ observer.observe(img);+ return () => observer.disconnect();+ }, [src]);+ const settings = normalizeFilmLook(look);+ const built = settings && !isFilmLookNeutral(settings) && size.width > 0+ ? filmLookFilterMarkup(settings, { frame, width: size.width, height: size.height, id: filterId })+ : null;+ const filtered = built?.active && !showOriginal;+ return (+ <div className={`relative select-none ${className}`}+ onPointerDown={() => setShowOriginal(true)} onPointerUp={() => setShowOriginal(false)} onPointerCancel={() => setShowOriginal(false)} onPointerLeave={() => setShowOriginal(false)}+ onKeyDown={(event) => { if (event.key === ' ') { event.preventDefault(); setShowOriginal(true); } }}+ onKeyUp={(event) => { if (event.key === ' ') setShowOriginal(false); }}+ role="img" aria-label={`${alt || 'Image'} with the film look applied. Hold to compare with the original.`} tabIndex={0}>+ {built && <div aria-hidden="true" dangerouslySetInnerHTML={{ __html: built.svg }} />}+ <img ref={imgRef} src={src} alt="" draggable={false} onLoad={() => imgRef.current && setSize({ width: Math.round(imgRef.current.clientWidth), height: Math.round(imgRef.current.clientHeight) })}+ className="block max-h-full max-w-full object-contain" style={{ filter: filtered ? built.css : 'none' }} data-testid="film-look-image" />+ {built?.active && (+ <span className="port-media-overlay pointer-events-none absolute bottom-2 left-2 rounded px-1.5 py-0.5 text-[10px]">{showOriginal ? 'Original' : 'Hold to compare'}</span>+ )}+ </div>+ );+}diff --git a/client/src/components/media/MediaLightbox.jsx b/client/src/components/media/MediaLightbox.jsxindex d94644ec29..107f6f48c4 100644--- a/client/src/components/media/MediaLightbox.jsx+++ b/client/src/components/media/MediaLightbox.jsx@@ -2,12 +2,13 @@ import { useEffect, useRef, useState } from 'react';import { createPortal } from 'react-dom';import {X, Copy, Sparkles, Film, Image as ImageIcon, Download, Eraser, Wand2,- ChevronLeft, ChevronRight, Maximize2, Minimize2, Star, Box, ScanEye,+ ChevronLeft, ChevronRight, Maximize2, Minimize2, Star, Box, ScanEye, Aperture,} from 'lucide-react';import PromptRefineModal from './PromptRefineModal';import { PromptFromMediaModal } from './PromptFromMedia';import AddToCollectionMenu from './AddToCollectionMenu';import PinToMoodBoardMenu from './PinToMoodBoardMenu';+import FilmLookEditor from './FilmLookEditor.jsx';import MediaImage from '../MediaImage';import { useScrollLock } from '../../hooks/useScrollLock';import { useSwipeNav } from '../../hooks/useSwipeNav';@@ -75,6 +76,11 @@ function describeCleanedLineage(item) {if (item.watermarkRemoved && item.cleanedFrom) {return `Watermark removed from ${item.cleanedFrom}`;}+ // A film-look bake (lib/filmLook.js) names the image it was rendered from.+ if (item.filmLookFrom) {+ const preset = item.filmLook?.preset;+ return `Film look${preset && preset !== 'custom' ? ` (${preset})` : ''} from ${item.filmLookFrom}`;+ }if (item.cleanedFrom) {return `${item.cleanLevel ? `Cleaned (${item.cleanLevel}) ` : 'Cleaned '}from ${item.cleanedFrom}`;}@@ -93,6 +99,12 @@ function describeImageExecution(item) {// onClean(item) — optional. Returning a rejected promise keeps the lightbox// open (e.g. on error) so the user can retry.//+// Film look (lib/filmLook.js) is offered on every gallery image: the editor+// bakes a filtered copy and reports it through `onFilmLookComplete(variant)`+// (the host splices it in like a clean). `filmLookProject` — optional+// `{ look, onSave, name }` — lets the editor read and write the hosting music+// video project's finishing look.+//// variantGroup — optional `{ active, group: [{ label, item }, ...] }` shape// from `computeImageVariantGroup` (in `./variants.js`). When present, the// SettingsPane renders a segmented control to swap between the original@@ -122,10 +134,13 @@ export default function MediaLightbox({onPosterChange,variantGroup = null,onSelectVariant,+ onFilmLookComplete,+ filmLookProject = null,}) {const [fullScreen, setFullScreen] = useState(false);const [refineOpen, setRefineOpen] = useState(false);const [promptFromOpen, setPromptFromOpen] = useState(false);+ const [filmLookOpen, setFilmLookOpen] = useState(false);useScrollLock(!!item);// Read callbacks + frequently-changing values from refs so the keydown// listener and the note-save debounce don't tear down on every parent@@ -169,6 +184,7 @@ export default function MediaLightbox({if (e.key === 'Escape') {if (refineOpen) { setRefineOpen(false); return; }if (promptFromOpen) { setPromptFromOpen(false); return; }+ if (filmLookOpen) { setFilmLookOpen(false); return; }if (fullScreen) { setFullScreen(false); return; }cb.onClose();return;@@ -198,10 +214,10 @@ export default function MediaLightbox({};window.addEventListener('keydown', onKey);return () => window.removeEventListener('keydown', onKey);- }, [item, hasPrevious, hasNext, fullScreen, refineOpen, promptFromOpen]);+ }, [item, hasPrevious, hasNext, fullScreen, refineOpen, promptFromOpen, filmLookOpen]);// Reset refine modal when the previewed item changes.- useEffect(() => { setRefineOpen(false); setPromptFromOpen(false); }, [item?.key]);+ useEffect(() => { setRefineOpen(false); setPromptFromOpen(false); setFilmLookOpen(false); }, [item?.key]);const { onTouchStart, onTouchEnd, onTouchCancel } = useSwipeNav({ onPrevious, onNext, hasPrevious, hasNext });@@ -279,6 +295,7 @@ export default function MediaLightbox({['Seed', item.seed ?? (isCodex ? 'n/a (gpt-image-2)' : null)],['Codex session', item.codexSessionId],['Cleaned', cleanedLabel],+ ['Look words', item.filmLookWords],['Execution', executionLabel],['Frames', item.numFrames],['FPS', item.fps],@@ -465,10 +482,14 @@ export default function MediaLightbox({getPlayhead={() => videoRef.current?.currentTime ?? 0}variantGroup={variantGroup}onSelectVariant={onSelectVariant}+ onFilmLook={!isVideo && item.filename ? () => setFilmLookOpen(true) : undefined}/>)}</div><PromptRefineModal item={item} open={refineOpen} onClose={() => setRefineOpen(false)} />+ {!isVideo && item.filename && (+ <FilmLookEditor item={item} open={filmLookOpen} onClose={() => setFilmLookOpen(false)} onComplete={onFilmLookComplete} projectLook={filmLookProject} />+ )}<PromptFromMediaModal item={item} open={promptFromOpen} onClose={() => setPromptFromOpen(false)} onResult={onPromptAnalysis} /></div>,document.body@@ -505,7 +526,7 @@ function SettingsPane({onClose, onRemix, onSendToImage, onSendToVideo, onSendTo3d, onContinue, onClean, onRegenerate, onRemoveWatermark, regenAvailable, regenBounds,copy, onRefine, onPromptFrom,annotation, onAnnotationChange, onPromptChange, onPosterChange, getPlayhead,- variantGroup, onSelectVariant,+ variantGroup, onSelectVariant, onFilmLook,}) {const asideClasses = 'md:w-80 lg:w-96 shrink-0 flex flex-col border-t md:border-t-0 md:border-l border-port-border min-h-0 max-h-dvh-cap [--dvh-cap:40vh] [--dvh-cap-dynamic:40dvh] md:[--dvh-cap:92vh] md:[--dvh-cap-dynamic:92dvh] [--dvh-inset:2rem]';const [posterSaving, setPosterSaving] = useState(false);@@ -863,6 +884,17 @@ function SettingsPane({<Box className="w-3.5 h-3.5" /> Send to 3D</button>)}+ {onFilmLook && (+ <button+ type="button"+ onClick={onFilmLook}+ title="Tune an analog film look on this image — soft focus, halation, grain, fade, vignette, light leaks — and save the result as a new copy. The original is kept."+ aria-label="Film look"+ className="flex-1 min-h-[44px] min-w-[80px] flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs bg-port-accent/80 text-white hover:opacity-90 rounded"+ >+ <Aperture className="w-3.5 h-3.5" /> Film look+ </button>+ )}{!isVideo && onClean && (<buttontype="button"diff --git a/client/src/components/media/MediaLightbox.test.jsx b/client/src/components/media/MediaLightbox.test.jsxindex 72d2096d30..fa7a746160 100644--- a/client/src/components/media/MediaLightbox.test.jsx+++ b/client/src/components/media/MediaLightbox.test.jsx@@ -10,6 +10,9 @@ vi.mock('./AddToCollectionMenu', () => ({ default: () => null }));vi.mock('./PromptRefineModal', () => ({default: ({ open }) => open ? <div data-testid="refine-modal" /> : null,}));+vi.mock('./FilmLookEditor.jsx', () => ({+ default: ({ open }) => open ? <div data-testid="film-look-editor" /> : null,+}));vi.mock('./PromptFromMedia', () => ({default: () => null,PromptFromMediaModal: ({ open }) => open ? <div data-testid="prompt-from-modal" /> : null,@@ -214,6 +217,20 @@ describe('MediaLightbox Escape cascade', () => {expect(screen.getByRole('dialog')).toBeTruthy();});+ it('opens the film look editor from the image actions and closes it without closing the lightbox', () => {+ const onClose = vi.fn();+ render(<MediaLightbox item={imageItem} onClose={onClose} />);++ fireEvent.click(screen.getByRole('button', { name: 'Film look' }));+ const editor = screen.getByTestId('film-look-editor');++ fireEvent.keyDown(editor, { key: 'Escape' });++ expect(onClose).not.toHaveBeenCalled();+ expect(screen.queryByTestId('film-look-editor')).toBeNull();+ expect(screen.getByRole('dialog')).toBeTruthy();+ });+it('closes the lightbox when Escape is pressed with nothing else open', () => {const onClose = vi.fn();render(<MediaLightbox item={imageItem} onClose={onClose} />);diff --git a/client/src/components/media/normalize.js b/client/src/components/media/normalize.jsindex 12ea0eacb7..033c74e2cb 100644--- a/client/src/components/media/normalize.js+++ b/client/src/components/media/normalize.js@@ -105,6 +105,13 @@ export function normalizeImage(i) {// `cleanedFrom` sibling "Watermark removed" rather than "Cleaned", so it// MUST survive normalization (same contract as `regenerated` above).watermarkRemoved: i.watermarkRemoved === true,+ // Film-look lineage — stamped by /api/image-gen/:filename/film-look on the+ // baked copy: the source it was rendered from, the look recipe (so the+ // editor can reopen it) and the look as prompt words. Labels the+ // `cleanedFrom` sibling "Film look" rather than "Cleaned".+ filmLookFrom: i.filmLookFrom || null,+ filmLook: i.filmLook && typeof i.filmLook === 'object' ? i.filmLook : null,+ filmLookWords: i.filmLookWords || null,provenance: i.provenance || null,// A compact gallery row (#8292) holds only a prompt preview; see// mediaDetail.js for the hydration every prompt consumer goes through.diff --git a/client/src/components/media/variants.js b/client/src/components/media/variants.jsindex c23e88ecea..05902f1a5d 100644--- a/client/src/components/media/variants.js+++ b/client/src/components/media/variants.js@@ -59,6 +59,11 @@ export function computeImageVariantGroup(item, items) {group.push({ label: 'Watermark removed', item: c });continue;}+ // A film-look bake (lib/filmLook.js) is a finishing pass, not a clean.+ if (c.filmLookFrom) {+ group.push({ label: 'Film look', item: c });+ continue;+ }const levelTag = c.cleanLevel ? ` (${c.cleanLevel})` : '';group.push({ label: `Cleaned${levelTag}`, item: c });}diff --git a/client/src/components/musicVideo/CompositionPanel.jsx b/client/src/components/musicVideo/CompositionPanel.jsxindex c2f15dc658..9acf231f6f 100644--- a/client/src/components/musicVideo/CompositionPanel.jsx+++ b/client/src/components/musicVideo/CompositionPanel.jsx@@ -1,5 +1,6 @@import { RenderFailure } from './RenderStatusPanel.jsx';import GradePanel from './GradePanel.jsx';+import FilmLookPanel from './FilmLookPanel.jsx';import TypographyPanel from './TypographyPanel.jsx';import EidoverseVideoPanel from './EidoverseVideoPanel.jsx';import CodeVideoPanel from './CodeVideoPanel.jsx';@@ -34,6 +35,7 @@ export default function CompositionPanel({ board }) {</p>)}<GradePanel project={project} onSave={board.saveCompositionGrade} />+ <FilmLookPanel project={project} onEditLocal={board.editProjectLocal} onSave={board.saveProjectFields} />{mode !== 'eidoverse' && <TypographyPanel project={project} onEditLocal={board.editProjectLocal} onSave={board.saveProjectFields} />}{mode === 'eidoverse' && <EidoverseVideoPanel key={project.id} project={project} onProject={board.replaceProject} productionReadiness={board.productionReadiness} />}{mode === 'code' && (diff --git a/client/src/components/musicVideo/CompositionPreviewPlayer.jsx b/client/src/components/musicVideo/CompositionPreviewPlayer.jsxindex bdb26ad691..0e5b861c53 100644--- a/client/src/components/musicVideo/CompositionPreviewPlayer.jsx+++ b/client/src/components/musicVideo/CompositionPreviewPlayer.jsx@@ -82,6 +82,15 @@ export default function CompositionPreviewPlayer({ project, audioUrl, seekRequesconst blobCache = useRef(new Map());const seekState = useRef({ inFlight: false, pending: null, ready: false });const appliedSeek = useRef(null);+ // The project's finishing film look (lib/filmLook.js) is posted into the+ // page, never baked into it: a slider move reaches the picture without a+ // rebuild, and the page re-seeds it for every frame it draws.+ const filmLook = lyrics ? null : (project.filmLook ?? null);+ const filmLookRef = useRef(filmLook);+ useEffect(() => {+ filmLookRef.current = filmLook;+ if (seekState.current.ready) iframeRef.current?.contentWindow?.postMessage({ type: 'portos-mv:film-look', look: filmLook }, '*');+ }, [filmLook]);// The document's own version (its folder + save time), not the project's// `updatedAt`: an unrelated save must not reload a playing preview.@@ -142,6 +151,8 @@ export default function CompositionPreviewPlayer({ project, audioUrl, seekReques// The manifest only: each file is fetched when the document first asks for it, so the first// frame waits on the media near the playhead rather than on every take in the project.event.source.postMessage({ type: 'portos-mv:manifest', keys: [...byKey.keys()] }, '*');+ // The page starts from the look saved when it was built; the board may have moved the sliders since.+ event.source.postMessage({ type: 'portos-mv:film-look', look: filmLookRef.current }, '*');showStatus();state.ready = true;postSeek(t);diff --git a/client/src/components/musicVideo/CompositionPreviewPlayer.test.jsx b/client/src/components/musicVideo/CompositionPreviewPlayer.test.jsxindex bc8c9e26cb..438ceee7df 100644--- a/client/src/components/musicVideo/CompositionPreviewPlayer.test.jsx+++ b/client/src/components/musicVideo/CompositionPreviewPlayer.test.jsx@@ -91,6 +91,31 @@ describe('CompositionPreviewPlayer', () => {expect(fetched()).toEqual(['/preview/a', '/preview/b', '/preview/c', '/preview/b', '/preview/c']);});+ it('hands the project film look to the loaded document and again when it changes, without rebuilding the preview', async () => {+ const look = { version: 1, preset: 'custom', grain: 0.4 };+ const { rerender } = render(<CompositionPreviewPlayer project={{ ...project, filmLook: look }} audioUrl={null} />);+ const frame = await screen.findByTitle('Composition document preview');+ const post = vi.spyOn(frame.contentWindow, 'postMessage');+ const send = (data) => act(async () => { window.dispatchEvent(new MessageEvent('message', { source: frame.contentWindow, data })); });+ await waitFor(async () => {+ await send({ type: 'portos-mv:loaded' });+ expect(post).toHaveBeenCalledWith({ type: 'portos-mv:film-look', look }, '*');+ expect(post).toHaveBeenCalledWith(expect.objectContaining({ type: 'portos-mv:manifest' }), '*');+ });+ // The look lands before the first seek so the document's first frame is already filtered.+ const seekAt = post.mock.calls.findIndex(([data]) => data.type === 'portos-mv:seek');+ const lookAt = post.mock.calls.findIndex(([data]) => data.type === 'portos-mv:film-look');+ expect(seekAt).toBeGreaterThan(-1);+ expect(lookAt).toBeLessThan(seekAt);++ const next = { ...look, grain: 0.9 };+ rerender(<CompositionPreviewPlayer project={{ ...project, filmLook: next }} audioUrl={null} />);+ await waitFor(() => expect(post).toHaveBeenCalledWith({ type: 'portos-mv:film-look', look: next }, '*'));+ rerender(<CompositionPreviewPlayer project={{ ...project, filmLook: null }} audioUrl={null} />);+ await waitFor(() => expect(post).toHaveBeenCalledWith({ type: 'portos-mv:film-look', look: null }, '*'));+ expect(api.getMusicVideoCompositionPreview).toHaveBeenCalledTimes(1);+ });+it('keeps the loaded preview through an unrelated project save and rebuilds when the document version changes', async () => {const { rerender } = render(<CompositionPreviewPlayer project={project} audioUrl={null} />);const frame = await screen.findByTitle('Composition document preview');diff --git a/client/src/components/musicVideo/FilmLookPanel.jsx b/client/src/components/musicVideo/FilmLookPanel.jsxnew file mode 100644index 0000000000..d1247e3800--- /dev/null+++ b/client/src/components/musicVideo/FilmLookPanel.jsx@@ -0,0 +1,29 @@+import { Aperture } from 'lucide-react';+import FilmLookControls from '../media/FilmLookControls.jsx';+import { isFilmLookNeutral } from '../../lib/filmLook.js';++/**+ * The project's finishing film look: the filter the composition live preview+ * and the final render are viewed through (lib/filmLook.js). Every slider move+ * reaches the docked preview at once (`onEditLocal`); releasing a control saves+ * (`onSave`). Source footage and generated images stay unchanged; to bake the+ * look into a still, open the image and use Film look there.+ */+export default function FilmLookPanel({ project, onEditLocal, onSave }) {+ const documentMode = project.composition?.mode === 'document';+ const on = !isFilmLookNeutral(project.filmLook);+ return (+ <section aria-label="Film look" className="space-y-2 border-t border-port-border pt-3">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <h3 className="inline-flex items-center gap-1.5 text-sm font-medium"><Aperture size={14} className="text-port-accent" aria-hidden="true" /> Film look</h3>+ <span className="text-xs text-port-text-muted">{on ? 'Live in the preview · applied to the final render' : 'Off'}</span>+ </div>+ {!documentMode && (+ <p className="text-xs text-port-text-muted" role="status">The film look is applied by the composition-document render style; this project's render style ignores it. It still works on any image through Film look in the image viewer.</p>+ )}+ <FilmLookControls look={project.filmLook} compact+ onChange={(look) => onEditLocal({ filmLook: look })}+ onCommit={(look) => onSave({ filmLook: isFilmLookNeutral(look) ? null : look })} />+ </section>+ );+}diff --git a/client/src/hooks/useMediaPreviewActions.js b/client/src/hooks/useMediaPreviewActions.jsindex 12e23e9c19..345bd8f7ca 100644--- a/client/src/hooks/useMediaPreviewActions.js+++ b/client/src/hooks/useMediaPreviewActions.js@@ -237,5 +237,12 @@ export default function useMediaPreviewActions({ onCleanComplete = null } = {})return variant;}, [onCleanComplete]);- return { handleRemix, handleSendToImage, handleSendToVideo, handleSendTo3d, handleContinue, handleClean, handleRemoveWatermark };+ // Film look: the lightbox's editor bakes the copy itself (FilmLookEditor) and+ // hands the variant here, so it lands in the consumer's local state the way a+ // clean does.+ const handleFilmLookComplete = useCallback(async (variant) => {+ if (onCleanComplete && variant) await onCleanComplete(variant);+ }, [onCleanComplete]);++ return { handleRemix, handleSendToImage, handleSendToVideo, handleSendTo3d, handleContinue, handleClean, handleRemoveWatermark, handleFilmLookComplete };}diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex d8dd6da62f..9b689f9b4e 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -313,4 +313,5 @@ grep -i "what you want to do" client/src/lib/README.md| `navPresentation.js` | Sidebar icon presentation and section ordering, separate from the Layout React refresh boundary. || `musicVideoGrade.js` | Shared Music Video grade preset and grain bounds for the composition controls. |+| `filmLook.js` | Shared film look controls, presets, normalizer, prompt vocabulary and the SVG filter markup the editor previews with (server `lib/filmLook.js`). || `musicVideoNarrativeEvents.js` | Named narrative event kinds, absolute onset/word/frame resolution and deterministic silence/reactive state for composition documents. |diff --git a/client/src/lib/filmLook.js b/client/src/lib/filmLook.jsnew file mode 100644index 0000000000..6dcbe9cd97--- /dev/null+++ b/client/src/lib/filmLook.js@@ -0,0 +1,14 @@+export {+ FILM_LOOK_VERSION,+ FILM_LOOK_GROUPS,+ FILM_LOOK_CONTROLS,+ FILM_LOOK_CONTROL_IDS,+ FILM_LOOK_PRESETS,+ FILM_LOOK_PRESET_IDS,+ filmLookPreset,+ normalizeFilmLook,+ isFilmLookNeutral,+ describeFilmLook,+ filmLookControl,+ filmLookFilterMarkup,+} from '../../../server/lib/filmLook.js';diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 9a5ecd0de2..6e0352a306 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -273,4 +273,5 @@ export * from './styleSourceChoice.js';export * from './trackProvenance.js';export * from './musicVideoGrade.js';+export * from './filmLook.js';export * from './musicVideoNarrativeEvents.js';diff --git a/client/src/pages/MediaHistory.jsx b/client/src/pages/MediaHistory.jsxindex d47baffd0a..c034d8b33e 100644--- a/client/src/pages/MediaHistory.jsx+++ b/client/src/pages/MediaHistory.jsx@@ -115,7 +115,7 @@ export default function MediaHistory() {setItems((prev) => [normalized, ...prev.filter((x) => x.key !== normalized.key)]);refresh();}, [setItems, refresh]);- const { handleRemix, handleSendToImage, handleSendToVideo, handleSendTo3d, handleContinue, handleClean, handleRemoveWatermark } = useMediaPreviewActions({+ const { handleRemix, handleSendToImage, handleSendToVideo, handleSendTo3d, handleContinue, handleClean, handleRemoveWatermark, handleFilmLookComplete } = useMediaPreviewActions({onCleanComplete: handleCleanComplete,});@@ -273,6 +273,7 @@ export default function MediaHistory() {onContinue={handleContinue}onClean={(item) => handleClean(item?.raw)}onRemoveWatermark={(item) => handleRemoveWatermark(item?.raw)}+ onFilmLookComplete={handleFilmLookComplete}/><VideoUpscaleDrawerdiff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex f20a5bf6b7..191892b4bc 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -779,6 +779,12 @@ export default function MusicVideo() {// older snapshot of the list overwrite a newer one.const timedTextSaveChain = useRef(Promise.resolve());const editProjectLocal = (patch) => patchProject(selected.id, patch);+ // The finishing film look, saved whole from the image viewer's editor ("Use on project").+ const saveFilmLook = (filmLook) => {+ const projectId = selected.id;+ return updateMusicVideoProject(projectId, { filmLook }, { silent: true })+ .then((saved) => patchProject(projectId, { filmLook: saved.filmLook ?? null }));+ };const saveProjectFields = (patch, { applyComposition = false } = {}) => {const projectId = selected.id;setCompositionSavePending((count) => count + 1);@@ -1274,7 +1280,8 @@ export default function MusicVideo() {<div id={MUSIC_VIDEO_PAGE_ID} className="flex h-full flex-col max-md:overflow-auto"><MidiInstallModal {...midi.installGate} /><MidiGatedModal {...midi.gatedGate} />- <MediaPreview preview={preview} setPreview={setPreview} items={previewItems} />+ <MediaPreview preview={preview} setPreview={setPreview} items={previewItems}+ filmLookProject={selected ? { look: selected.filmLook, name: selected.name, onSave: saveFilmLook } : null} />{pickerTarget && pickerTarget.type !== 'clip' && (<GalleryImagePickeropendiff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.jsindex 29585e42dc..b1b8e50c7f 100644--- a/client/src/services/apiImageVideo.js+++ b/client/src/services/apiImageVideo.js@@ -72,6 +72,12 @@ export const updateImagePrompt = (filename, prompt, options = {}) => request(`/i// the variant toggle without hydrating that whole list. Returns `{ items }`.export const listImageVariants = (filename, options = {}) =>request(`/image-gen/${encodeURIComponent(filename)}/variants`, { silent: true, ...options });+// Bake a film look (lib/filmLook.js) into a new copy of a gallery image; resolves the variant record.+export const applyImageFilmLook = (filename, look, options = {}) => request(`/image-gen/${encodeURIComponent(filename)}/film-look`, {+ method: 'POST',+ body: JSON.stringify({ look }),+ ...options,+});export const cleanGalleryImage = (filename, options = {}) => request(`/image-gen/${encodeURIComponent(filename)}/clean`, {method: 'POST',body: JSON.stringify({}),diff --git a/docs/HTML_COMPOSITIONS.md b/docs/HTML_COMPOSITIONS.mdindex c4729a5ac9..eb9cb6c16a 100644--- a/docs/HTML_COMPOSITIONS.md+++ b/docs/HTML_COMPOSITIONS.md@@ -281,6 +281,45 @@ Saving the selection gates rendering until the server has accepted it.See the [synthetic visual validation and remaining acceptance](validation/9302-music-video-grade.md).+## Music-video film look++A finishing filter for the analog, imperfect feel image and video models rarely+give on their own: soft focus, halation, color bleed, grain, fade, a color cast,+split toning, vignette, light leaks, gate weave and flicker. One definition in+`server/lib/filmLook.js` (`FILM_LOOK_CONTROLS`, `FILM_LOOK_PRESETS`,+`filmLookFilterMarkup`) serves three surfaces, so what is tuned on a still is+what the preview shows and what the render bakes:++- **Compose → Film look** stores the look on the project (`project.filmLook`,+ validated by `filmLookValidation.js`, normalized by `normalizeFilmLook`).+ Every slider move reaches the docked live preview at once; releasing a+ control saves. `null` is the bypass.+- **The image viewer (Film look)** on any gallery image, Cast & sets plate or+ mood-board still previews the same filter in the browser and **Save filtered+ copy** bakes it server-side (`POST /api/image-gen/:filename/film-look`,+ `services/imageGen/filmLookBake.js`) into a new image beside the untouched+ original, grouped with it like a cleaned copy. Inside a music video project+ the editor also offers **Use on project**.+- **The final render** installs the same runtime in every worker browser+ (`documentRenderInitScripts` → `openComposition({ initScripts })`), so the+ split render (#10365) and the overlay text probe see the filtered page.++The filter is an SVG `<filter>` applied to the document root (or to the+`<img>` for a still). Radii and offsets scale with the filtered element's+width, so a 390px phone preview, the 1920-wide render and a 4K still read+alike. Every time-varying effect (grain seed, gate weave, flicker, light-leak+drift) is a pure function of the song frame, so the four render workers agree+and a still is one bake. `filmLookRuntimeSource()` inlines the markup function+by `toString()` into sandboxed pages, which is why `filmLookFilterMarkup` must+stay self-contained; the runtime wraps `portosComposition.seek()` to advance+the frame before the page paints. A neutral look emits no filter at all.++Each control names its effect in photography terms, and the **In a prompt**+box rewrites the current settings as the words that ask a model for the same+qualities (`describeFilmLook`), so tuning a look also teaches the vocabulary+for the next generation prompt. The look works on composition-document+projects; the composed render style keeps its own render grade above.+## Music-video composition documentsA Music Video project can own its whole edit as a composition document: setdiff --git a/server/lib/README.md b/server/lib/README.mdindex 5483406bea..a5294dbea4 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -855,6 +855,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `musicVideoActionContract.js` | Versioned shot intent shape/timing validation and clip-relative frame/motion prompt compilation, shared by treatment and the board. || `sheetPointers.js` | Browser-safe persisted character-sheet layout: `LEGACY_SHEET_VARIANT_ID`, `readSheetPointer`, `listSheetPointers`, identity-preserving `applySheetPointerToCharacter`, and default-variant browser adapter `applySheetPointer`. || `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) 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`. || `musicVideoDependencies.js` | Versioned take/evidence provenance, dependency comparisons and bounded selective-repair previews. || `musicVideoCrossLinks.js` | Cross-links between a release's posts: each post's public link, the `Label: url` lines a new draft adds, which links a posted record carries (`links`, or what its draft always linked), and `crossLinkBackfill(kit)` listing the links each editable post (YouTube, Suno, X, Stacker News) still lacks. Shared by the publish payloads and the Publish stage. || `musicVideoExcerptRange.js` | `excerptRangeFits(startSec, endSec, totalSec, fps)`: whether a code/document excerpt window fits a frame-quantized render, allowing the end up to one frame past it (scene ends follow the analysed song length; the caller clamps). The start must fall inside the render; an unknown fps allows no slack. |diff --git a/server/lib/filmLook.js b/server/lib/filmLook.jsnew file mode 100644index 0000000000..cff2b5dc02--- /dev/null+++ b/server/lib/filmLook.js@@ -0,0 +1,433 @@+/**+ * Film look — the finishing filter a music video (or a single still) is viewed+ * through: soft focus, halation, color bleed, grain, fade, vignette, light+ * leaks, gate weave and the rest of the analog toolbox, as a stack of tunable+ * controls with named presets.+ *+ * ONE implementation serves every surface: an SVG filter (`filmLookFilterMarkup`)+ * that the composition live preview, the final render's browser and the gallery+ * still editor all apply with `filter: url(#…)`. Every effect that varies over+ * time (grain, weave, flicker, leak drift) is a pure function of the song FRAME,+ * never of RNG state or wall time, so an excerpt, a re-render, the live preview+ * and the four worker browsers of a split render all draw the same frame.+ *+ * `filmLookFilterMarkup` and `filmLookRuntimeSource` are inlined into sandboxed+ * pages by `toString()`, so they must stay self-contained: no references to+ * module scope, no imports. `FILM_LOOK_CONTROLS` is the single table the UI, the+ * Zod schema (`filmLookValidation.js`) and the normalizer are built from.+ */++export const FILM_LOOK_VERSION = 1;++export const FILM_LOOK_GROUPS = Object.freeze([+ { id: 'focus', label: 'Focus & glow' },+ { id: 'color', label: 'Color' },+ { id: 'texture', label: 'Texture' },+ { id: 'frame', label: 'Frame & motion' },+]);++// Each control: a slider (`min`/`max`/`step`, `def` default), a color, or a+// toggle. `term` is the cinematography / photography word for it and `words`+// turns a value into prompt language, so the panel teaches the vocabulary a+// user needs to ask an image or video model for the same quality directly.+export const FILM_LOOK_CONTROLS = Object.freeze([+ { id: 'defocus', group: 'focus', label: 'Soft focus', term: 'defocus · missed focus', min: 0, max: 1, step: 0.01, def: 0,+ hint: 'How far the whole picture sits from sharp. Lenses, not post, call this missed focus.',+ words: (v) => (v > 0.6 ? 'heavily out of focus, dreamy missed focus' : v > 0.3 ? 'soft focus, slightly out of focus' : 'gently softened focus') },+ { id: 'diffusion', group: 'focus', label: 'Diffusion', term: 'Pro-Mist · glow filter', min: 0, max: 1, step: 0.01, def: 0,+ hint: 'A glass diffusion filter: light spreads into a soft glow while edges stay readable.',+ words: (v) => (v > 0.5 ? 'heavy diffusion filter glow, blooming soft light' : 'subtle Pro-Mist diffusion, soft glowing light') },+ { id: 'halation', group: 'focus', label: 'Halation', term: 'halation · highlight bloom', min: 0, max: 1, step: 0.01, def: 0,+ hint: 'Film lets bright light bounce back through the emulsion: warm halos around lamps, signs and skin highlights.',+ words: (v) => (v > 0.5 ? 'strong red-orange halation around highlights, blooming neon' : 'soft halation around light sources') },+ { id: 'halationColor', group: 'focus', label: 'Halation color', term: 'halation tint', type: 'color', def: '#ff5a1f',+ hint: 'Film halation is red-orange (the anti-halation layer passes red). Change it for a stylized glow.' },+ { id: 'chroma', group: 'focus', label: 'Color fringing', term: 'chromatic aberration', min: 0, max: 1, step: 0.01, def: 0,+ hint: 'A cheap lens focuses red and blue at different points: colored fringes at edges, strongest off-center.',+ words: () => 'chromatic aberration, color fringing at edges, cheap lens' },+ { id: 'bleed', group: 'focus', label: 'Color bleed', term: 'chroma smear · VHS bleed', min: 0, max: 1, step: 0.01, def: 0,+ hint: 'Tape and broadcast carry color at lower resolution than brightness, so colors smear sideways past their edges.',+ words: (v) => (v > 0.5 ? 'heavy VHS color bleed, smeared chroma' : 'slight analog color bleed') },++ { id: 'exposure', group: 'color', label: 'Exposure', term: 'exposure · stops', min: -1, max: 1, step: 0.01, def: 0,+ hint: 'Overall brightness, about one stop either way.',+ words: (v) => (v > 0 ? 'overexposed, bright' : 'underexposed, dim') },+ { id: 'contrast', group: 'color', label: 'Contrast', term: 'contrast · tonal range', min: -1, max: 1, step: 0.01, def: 0,+ hint: 'Negative flattens the picture toward a faded print; positive deepens blacks and pushes whites.',+ words: (v) => (v > 0 ? 'high contrast, punchy' : 'low contrast, flat, muted tonal range') },+ { id: 'fade', group: 'color', label: 'Fade', term: 'lifted blacks · faded print', min: 0, max: 1, step: 0.01, def: 0,+ hint: 'Raises the blacks to a milky gray and holds back the whites, the way an old print or an expired stock looks.',+ words: (v) => (v > 0.5 ? 'faded print, washed-out lifted blacks, matte' : 'slightly faded, lifted blacks') },+ { id: 'saturation', group: 'color', label: 'Saturation', term: 'saturation · chroma', min: -1, max: 1, step: 0.01, def: 0,+ hint: 'Negative drains color toward monochrome; positive pushes it toward slide film.',+ words: (v) => (v > 0.3 ? 'richly saturated colors, slide film' : v > 0 ? 'slightly boosted color' : v < -0.6 ? 'nearly monochrome, desaturated' : 'muted desaturated colors') },+ { id: 'warmth', group: 'color', label: 'Warmth', term: 'color temperature · white balance', min: -1, max: 1, step: 0.01, def: 0,+ hint: 'Blue to amber. Tungsten light under daylight balance reads warm; the reverse reads cold.',+ words: (v) => (v > 0 ? 'warm amber tungsten color temperature' : 'cool blue color temperature') },+ { id: 'tint', group: 'color', label: 'Tint', term: 'green–magenta tint', min: -1, max: 1, step: 0.01, def: 0,+ hint: 'The other white-balance axis. Green reads as fluorescent tubes or expired film; magenta as a faded Polaroid.',+ words: (v) => (v > 0 ? 'magenta tint' : 'green tint, fluorescent cast') },+ { id: 'cast', group: 'color', label: 'Color cast', term: 'color cast · wash', min: 0, max: 1, step: 0.01, def: 0,+ hint: 'A single color laid over everything, like shooting through a tinted window or under a sodium lamp.',+ words: () => 'overall color cast' },+ { id: 'castColor', group: 'color', label: 'Cast color', term: 'cast hue', type: 'color', def: '#b9c04a',+ hint: 'Yellow-green is the classic expired-film and fluorescent cast.' },+ { id: 'splitTone', group: 'color', label: 'Split tone', term: 'split toning · shadows/highlights', min: 0, max: 1, step: 0.01, def: 0,+ hint: 'Tints shadows one color and highlights another. Teal shadows with orange highlights is the cinema cliché for a reason.',+ words: () => 'split-toned, colored shadows and highlights' },+ { id: 'shadowColor', group: 'color', label: 'Shadow tone', term: 'shadow tint', type: 'color', def: '#1f4a46', hint: 'The color the darkest areas lean toward.' },+ { id: 'highlightColor', group: 'color', label: 'Highlight tone', term: 'highlight tint', type: 'color', def: '#ffb067', hint: 'The color the brightest areas lean toward.' },++ { id: 'grain', group: 'texture', label: 'Grain', term: 'film grain · ISO noise', min: 0, max: 1, step: 0.01, def: 0,+ hint: 'The texture of fast film or a pushed stock. Strongest in the midtones, almost absent in pure black and white.',+ words: (v) => (v > 0.6 ? 'heavy film grain, high ISO, pushed film stock' : v > 0.3 ? 'visible film grain' : 'fine film grain') },+ { id: 'grainSize', group: 'texture', label: 'Grain size', term: 'grain structure · gauge', min: 0, max: 1, step: 0.01, def: 0.35, modifier: 'grain',+ hint: 'Fine grain reads as 35mm; coarse grain reads as Super 8 or a blown-up print.',+ words: (v) => (v > 0.6 ? 'coarse Super 8 grain' : v > 0.3 ? '16mm grain' : 'fine 35mm grain') },+ { id: 'grainColor', group: 'texture', label: 'Color grain', term: 'chroma noise', type: 'toggle', def: false,+ hint: 'Monochrome grain is film. Colored speckle is a sensor at high ISO or a Polaroid emulsion.' },+ { id: 'tapeNoise', group: 'texture', label: 'Tape noise', term: 'tape bands · tracking noise', min: 0, max: 1, step: 0.01, def: 0,+ hint: 'Faint horizontal bands of brightness noise, the texture of a worn videotape.',+ words: () => 'VHS tape noise, horizontal tracking bands' },++ { id: 'vignette', group: 'frame', label: 'Vignette', term: 'vignette · lens falloff', min: 0, max: 1, step: 0.01, def: 0,+ hint: 'The corners darken, as a wide-open vintage lens or a lens hood does.',+ words: (v) => (v > 0.5 ? 'heavy vignette, dark corners' : 'soft vignette') },+ { id: 'leak', group: 'frame', label: 'Light leak', term: 'light leak · fogging', min: 0, max: 1, step: 0.01, def: 0,+ hint: 'Light sneaking into the camera body fogs one side of the frame; on video it drifts slowly.',+ words: () => 'light leak, fogged edge of frame' },+ { id: 'leakColor', group: 'frame', label: 'Leak color', term: 'leak hue', type: 'color', def: '#ff7a2a', hint: 'Real leaks are orange-red, from light through the film base.' },+ { id: 'weave', group: 'frame', label: 'Gate weave', term: 'gate weave · frame jitter', min: 0, max: 1, step: 0.01, def: 0,+ hint: 'The frame drifts a few pixels as film shuffles through the projector gate. Stills ignore it.',+ words: () => 'projected film gate weave, slight frame jitter' },+ { id: 'flicker', group: 'frame', label: 'Flicker', term: 'projector flicker · exposure flicker', min: 0, max: 1, step: 0.01, def: 0,+ hint: 'Frame-to-frame brightness wobble of a projector or a hand-cranked camera. Stills ignore it.',+ words: () => 'flickering projector exposure' },+]);++export const FILM_LOOK_CONTROL_IDS = Object.freeze(FILM_LOOK_CONTROLS.map((control) => control.id));+const CONTROL_BY_ID = new Map(FILM_LOOK_CONTROLS.map((control) => [control.id, control]));++// Named starting points. Each lists only what differs from the defaults; the+// first non-neutral one is the look Adam's 1980s reference reads as.+export const FILM_LOOK_PRESETS = Object.freeze([+ { id: 'none', label: 'Clean', summary: 'No finishing; the picture as rendered.', values: {} },+ { id: 'neon-rain', label: 'Neon rain 80s', summary: 'Yellow-green cast, red-orange halation, missed focus, heavy grain, crushed shadows, faded contrast.',+ values: { defocus: 0.3, diffusion: 0.25, halation: 0.8, chroma: 0.25, bleed: 0.35, contrast: -0.2, fade: 0.3, saturation: 0.15, warmth: 0.2, tint: -0.15, cast: 0.2, castColor: '#b9c04a', splitTone: 0.35, shadowColor: '#163a2e', highlightColor: '#ffa060', grain: 0.6, grainSize: 0.45, vignette: 0.35 } },+ { id: 'polaroid', label: 'Polaroid', summary: 'Soft, warm, faded instant film with a milky lift and fine color speckle.',+ values: { defocus: 0.2, diffusion: 0.3, halation: 0.2, contrast: -0.3, fade: 0.45, saturation: -0.15, warmth: 0.3, tint: 0.15, cast: 0.15, castColor: '#e8c48a', grain: 0.3, grainSize: 0.3, grainColor: true, vignette: 0.45 } },+ { id: 'vhs', label: 'VHS', summary: 'Smeared color, soft detail, tape bands and a slow drifting leak.',+ values: { defocus: 0.35, bleed: 0.8, chroma: 0.4, contrast: -0.1, saturation: 0.1, grain: 0.25, grainSize: 0.2, grainColor: true, tapeNoise: 0.5, vignette: 0.15, weave: 0.2, flicker: 0.15 } },+ { id: 'super8', label: 'Super 8', summary: 'Coarse grain, warm faded color, gate weave and projector flicker.',+ values: { defocus: 0.15, halation: 0.35, contrast: -0.1, fade: 0.25, saturation: 0.1, warmth: 0.35, grain: 0.75, grainSize: 0.7, vignette: 0.5, leak: 0.2, weave: 0.6, flicker: 0.4 } },+ { id: '16mm', label: '16mm', summary: 'Documentary film: visible grain, honest color, a gentle vignette.',+ values: { halation: 0.25, contrast: 0.05, fade: 0.1, saturation: -0.05, grain: 0.45, grainSize: 0.4, vignette: 0.25, weave: 0.15 } },+ { id: 'soft-analog', label: 'Soft analog', summary: 'A light hand: a little diffusion, fine grain, a touch of warmth.',+ values: { defocus: 0.1, diffusion: 0.2, halation: 0.15, fade: 0.1, warmth: 0.1, grain: 0.25, grainSize: 0.3, vignette: 0.15 } },+ { id: 'teal-orange', label: 'Teal & orange', summary: 'Modern cinema grade: teal shadows, orange skin, clean and contrasty.',+ values: { contrast: 0.15, saturation: 0.1, splitTone: 0.6, shadowColor: '#0f5a63', highlightColor: '#ff9a4a', grain: 0.12, grainSize: 0.2, vignette: 0.2 } },+ { id: 'newsprint', label: 'Monochrome', summary: 'Black and white with grain and a fade, like pushed Tri-X.',+ values: { contrast: 0.2, fade: 0.15, saturation: -1, grain: 0.55, grainSize: 0.45, vignette: 0.3 } },+]);++export const FILM_LOOK_PRESET_IDS = Object.freeze(FILM_LOOK_PRESETS.map((preset) => preset.id));++const HEX = /^#[0-9a-f]{6}$/i;+const clampNumber = (value, control) => Math.min(control.max, Math.max(control.min, Math.round(value / control.step) * control.step));++/** The look a preset id names, with every control filled in. */+export function filmLookPreset(id) {+ const preset = FILM_LOOK_PRESETS.find((entry) => entry.id === id) || FILM_LOOK_PRESETS[0];+ return normalizeFilmLook({ preset: preset.id, ...preset.values });+}++/**+ * A complete, bounded look from any input: unknown keys dropped, numbers+ * clamped to their control's range, colors as `#rrggbb`, toggles as booleans.+ * Returns null for a non-object (a project without a look).+ */+export function normalizeFilmLook(input) {+ if (!input || typeof input !== 'object' || Array.isArray(input)) return null;+ const look = { version: FILM_LOOK_VERSION, preset: FILM_LOOK_PRESET_IDS.includes(input.preset) ? input.preset : 'custom' };+ for (const control of FILM_LOOK_CONTROLS) {+ const value = input[control.id];+ if (control.type === 'color') look[control.id] = typeof value === 'string' && HEX.test(value) ? value.toLowerCase() : control.def;+ else if (control.type === 'toggle') look[control.id] = typeof value === 'boolean' ? value : control.def;+ else look[control.id] = Number.isFinite(value) ? Number(clampNumber(value, control).toFixed(4)) : control.def;+ }+ return look;+}++/** True when the look changes nothing (every effect at zero), so a render can skip it. */+export function isFilmLookNeutral(look) {+ const settings = normalizeFilmLook(look);+ if (!settings) return true;+ // Colors and toggles only shape an effect; a modifier (grain size) only matters while its effect is on.+ return FILM_LOOK_CONTROLS.every((control) => control.type || control.modifier || settings[control.id] === 0);+}++/**+ * The look in prompt language: the vocabulary a user pastes into an image or+ * video prompt to ask for the same qualities at generation time. Lists only the+ * effects that are on, strongest first.+ */+export function describeFilmLook(look) {+ const settings = normalizeFilmLook(look);+ if (!settings) return '';+ const phrases = FILM_LOOK_CONTROLS+ .filter((control) => !control.type && control.words && Math.abs(settings[control.id]) >= 0.08+ && (!control.modifier || Math.abs(settings[control.modifier]) >= 0.08))+ .sort((a, b) => Math.abs(settings[b.id]) - Math.abs(settings[a.id]))+ .map((control) => control.words(settings[control.id]));+ if (settings.grainColor && settings.grain >= 0.08) phrases.splice(1, 0, 'colored noise speckle');+ // The strongest eight read as direction; a longer list reads as noise.+ return [...new Set(phrases)].slice(0, 8).join(', ');+}++/** The control record for an id (label, term, hint, range). */+export const filmLookControl = (id) => CONTROL_BY_ID.get(id) || null;++/**+ * The SVG `<filter>` for a look at one frame, in a `<svg>` element sized to+ * nothing, plus the CSS filter reference that applies it. `width`/`height` are+ * the CSS pixel size of the element being filtered: every radius and offset is a+ * fraction of them, so the same look reads the same on a phone preview, the+ * 1920-wide render and a 4K still.+ *+ * SELF-CONTAINED by contract (inlined into sandboxed pages via toString()).+ * `look` is a normalized look; missing values read as their neutral.+ */+export function filmLookFilterMarkup(look, { frame = 0, width = 1920, height = 1080, id = 'portos-film-look' } = {}) {+ const v = (key, neutral = 0) => (look && Number.isFinite(look[key]) ? look[key] : neutral);+ const hex = (key, fallback) => (look && typeof look[key] === 'string' && /^#[0-9a-f]{6}$/i.test(look[key]) ? look[key] : fallback);+ const rgb = (color) => [1, 3, 5].map((i) => parseInt(color.slice(i, i + 2), 16) / 255);+ const n = (value) => Number(value.toFixed(4));+ const w = Math.max(1, width);+ const h = Math.max(1, height);+ const f = Math.max(0, Math.floor(frame));+ // Integer hash → [0, 1): the same frame hashes the same in every browser.+ const hash = (seed) => {+ let x = Math.imul(seed + 0x9e3779b9, 0x85ebca6b) >>> 0;+ x ^= x >>> 13; x = Math.imul(x, 0xc2b2ae35) >>> 0; x ^= x >>> 16;+ return (x >>> 0) / 4294967296;+ };+ const LUMA = '0.2126 0.7152 0.0722';+ const lumaRgb = `${LUMA} 0 0 ${LUMA} 0 0 ${LUMA} 0 0 0 0 0 1 0`;+ const parts = [];+ let cur = 'SourceGraphic';+ let step = 0;+ const next = () => `s${step++}`;+ const emit = (markup, name = next()) => { parts.push(markup.replace('result=""', `result="${name}"`)); cur = name; return name; };++ // Opaque base: letterbox and transparent areas blend as black, so every+ // arithmetic step below works on alpha 1 and the edges stay clean.+ emit('<feFlood flood-color="#000" result=""/>', 'bg');+ emit(`<feComposite in="SourceGraphic" in2="bg" operator="over" result=""/>`);++ const weave = v('weave');+ if (weave > 0) {+ const dx = weave * 0.004 * w * (Math.sin(f * 0.37) + 0.6 * Math.sin(f * 1.13)) / 1.6;+ const dy = weave * 0.004 * h * (Math.cos(f * 0.29) + 0.6 * Math.sin(f * 0.91)) / 1.6;+ emit(`<feOffset in="${cur}" dx="${n(dx)}" dy="${n(dy)}" result=""/>`);+ }+ const defocus = v('defocus');+ if (defocus > 0) emit(`<feGaussianBlur in="${cur}" stdDeviation="${n(Math.pow(defocus, 1.5) * 0.014 * w)}" edgeMode="duplicate" result=""/>`);++ const bleed = v('bleed');+ if (bleed > 0) {+ const pic = cur;+ const blurred = emit(`<feGaussianBlur in="${pic}" stdDeviation="${n(bleed * 0.02 * w)} 0" edgeMode="duplicate" result=""/>`);+ const lumaPic = emit(`<feColorMatrix in="${pic}" type="matrix" values="${lumaRgb}" result=""/>`);+ const lumaBlur = emit(`<feColorMatrix in="${blurred}" type="matrix" values="${lumaRgb}" result=""/>`);+ // Blurred color, original brightness: d = 0.5 + (blur − lumaBlur)/2, then lumaPic + 2d − 1.+ const d = emit(`<feComposite in="${blurred}" in2="${lumaBlur}" operator="arithmetic" k1="0" k2="0.5" k3="-0.5" k4="0.5" result=""/>`);+ emit(`<feComposite in="${lumaPic}" in2="${d}" operator="arithmetic" k1="0" k2="1" k3="2" k4="-1" result=""/>`);+ }+ const chroma = v('chroma');+ if (chroma > 0) {+ const pic = cur;+ const shift = n(chroma * 0.004 * w);+ const r = emit(`<feColorMatrix in="${pic}" type="matrix" values="1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0" result=""/>`);+ const rs = emit(`<feOffset in="${r}" dx="${shift}" dy="0" result=""/>`);+ const g = emit(`<feColorMatrix in="${pic}" type="matrix" values="0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0" result=""/>`);+ const b = emit(`<feColorMatrix in="${pic}" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0" result=""/>`);+ const bs = emit(`<feOffset in="${b}" dx="-${shift}" dy="0" result=""/>`);+ const rg = emit(`<feComposite in="${rs}" in2="${g}" operator="arithmetic" k1="0" k2="1" k3="1" k4="0" result=""/>`);+ emit(`<feComposite in="${rg}" in2="${bs}" operator="arithmetic" k1="0" k2="1" k3="1" k4="0" result=""/>`);+ }+ const diffusion = v('diffusion');+ if (diffusion > 0) {+ const pic = cur;+ const glow = emit(`<feGaussianBlur in="${pic}" stdDeviation="${n((0.01 + 0.02 * diffusion) * w)}" edgeMode="duplicate" result=""/>`);+ emit(`<feComposite in="${pic}" in2="${glow}" operator="arithmetic" k1="0" k2="${n(1 - 0.25 * diffusion)}" k3="${n(0.55 * diffusion)}" k4="0" result=""/>`);+ }+ const halation = v('halation');+ if (halation > 0) {+ const pic = cur;+ const [hr, hg, hb] = rgb(hex('halationColor', '#ff5a1f'));+ const luma = emit(`<feColorMatrix in="${pic}" type="matrix" values="${lumaRgb}" result=""/>`);+ const bright = emit(`<feComponentTransfer in="${luma}" result=""><feFuncR type="linear" slope="2.5" intercept="-1.5"/><feFuncG type="linear" slope="2.5" intercept="-1.5"/><feFuncB type="linear" slope="2.5" intercept="-1.5"/></feComponentTransfer>`);+ const spread = emit(`<feGaussianBlur in="${bright}" stdDeviation="${n((0.008 + 0.03 * halation) * w)}" edgeMode="duplicate" result=""/>`);+ const tinted = emit(`<feColorMatrix in="${spread}" type="matrix" values="${n(hr)} 0 0 0 0 0 ${n(hg)} 0 0 0 0 0 ${n(hb)} 0 0 0 0 0 1 0" result=""/>`);+ emit(`<feComposite in="${pic}" in2="${tinted}" operator="arithmetic" k1="0" k2="1" k3="${n(1.3 * halation)}" k4="0" result=""/>`);+ }++ // Tone: exposure, contrast, fade, flicker, warmth and tint fold into one+ // linear transfer per channel (v' = slope·v + intercept).+ const exposure = v('exposure');+ const contrast = v('contrast');+ const fade = v('fade');+ const flicker = v('flicker');+ const warmth = v('warmth');+ const tint = v('tint');+ if (exposure || contrast || fade || flicker || warmth || tint) {+ const e = Math.pow(2, exposure) * (1 + flicker * 0.12 * (hash(f) * 2 - 1));+ const c = 1 + contrast * 0.8;+ const s = 1 - 0.28 * fade;+ const slope = e * c * s;+ const intercept = s * ((1 - c) / 2) + 0.2 * fade;+ const channel = { r: (1 + 0.18 * warmth) * (1 + 0.07 * tint), g: 1 - 0.15 * tint, b: (1 - 0.18 * warmth) * (1 + 0.07 * tint) };+ const fn = (name, scale) => `<feFunc${name} type="linear" slope="${n(slope * scale)}" intercept="${n(intercept * scale)}"/>`;+ emit(`<feComponentTransfer in="${cur}" result="">${fn('R', channel.r)}${fn('G', channel.g)}${fn('B', channel.b)}</feComponentTransfer>`);+ }+ const saturation = v('saturation');+ if (saturation) emit(`<feColorMatrix in="${cur}" type="saturate" values="${n(Math.max(0, 1 + saturation))}" result=""/>`);+ const cast = v('cast');+ if (cast > 0) {+ const pic = cur;+ const flood = emit(`<feFlood flood-color="${hex('castColor', '#b9c04a')}" result=""/>`);+ const blended = emit(`<feBlend in="${flood}" in2="${pic}" mode="soft-light" result=""/>`);+ emit(`<feComposite in="${pic}" in2="${blended}" operator="arithmetic" k1="0" k2="${n(1 - cast)}" k3="${n(cast)}" k4="0" result=""/>`);+ }+ const split = v('splitTone');+ if (split > 0) {+ const pic = cur;+ const hiMask = emit(`<feColorMatrix in="${pic}" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ${LUMA} 0 0" result=""/>`);+ const loMask = emit(`<feColorMatrix in="${pic}" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -0.2126 -0.7152 -0.0722 0 1" result=""/>`);+ const hiFlood = emit(`<feFlood flood-color="${hex('highlightColor', '#ffb067')}" result=""/>`);+ const loFlood = emit(`<feFlood flood-color="${hex('shadowColor', '#1f4a46')}" result=""/>`);+ const hi = emit(`<feComposite in="${hiFlood}" in2="${hiMask}" operator="in" result=""/>`);+ const lo = emit(`<feComposite in="${loFlood}" in2="${loMask}" operator="in" result=""/>`);+ const withHi = emit(`<feBlend in="${hi}" in2="${pic}" mode="soft-light" result=""/>`);+ const withLo = emit(`<feBlend in="${lo}" in2="${withHi}" mode="soft-light" result=""/>`);+ emit(`<feComposite in="${pic}" in2="${withLo}" operator="arithmetic" k1="0" k2="${n(1 - split)}" k3="${n(split)}" k4="0" result=""/>`);+ }++ const grain = v('grain');+ if (grain > 0) {+ const pic = cur;+ const size = v('grainSize', 0.35);+ // Grain features scale with the frame: the same look is as fine on a 4K still as in a phone preview.+ const base = Math.min(1.5, (0.95 - 0.7 * size) * (1920 / w));+ const noise = emit(`<feTurbulence type="fractalNoise" baseFrequency="${n(base)}" numOctaves="2" seed="${(f % 9973) + 1}" stitchTiles="noStitch" result=""/>`);+ const mono = look && look.grainColor === true+ ? emit(`<feColorMatrix in="${noise}" type="matrix" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 1" result=""/>`)+ : emit(`<feColorMatrix in="${noise}" type="matrix" values="1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 1" result=""/>`);+ const blended = emit(`<feBlend in="${mono}" in2="${pic}" mode="overlay" result=""/>`);+ emit(`<feComposite in="${pic}" in2="${blended}" operator="arithmetic" k1="0" k2="${n(1 - grain)}" k3="${n(grain)}" k4="0" result=""/>`);+ }+ const tape = v('tapeNoise');+ if (tape > 0) {+ const pic = cur;+ const bands = emit(`<feTurbulence type="fractalNoise" baseFrequency="${n(0.0015 * (1920 / w))} ${n(0.45 * (1080 / h))}" numOctaves="1" seed="${((f * 7) % 9973) + 1}" result=""/>`);+ const mono = emit(`<feColorMatrix in="${bands}" type="matrix" values="1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 1" result=""/>`);+ const blended = emit(`<feBlend in="${mono}" in2="${pic}" mode="soft-light" result=""/>`);+ emit(`<feComposite in="${pic}" in2="${blended}" operator="arithmetic" k1="0" k2="${n(1 - 0.8 * tape)}" k3="${n(0.8 * tape)}" k4="0" result=""/>`);+ }+ const vignette = v('vignette');+ if (vignette > 0) {+ const pic = cur;+ const inset = 0.08 + 0.1 * vignette;+ const lit = emit(`<feFlood flood-color="#fff" x="${n(w * inset)}" y="${n(h * inset)}" width="${n(w * (1 - 2 * inset))}" height="${n(h * (1 - 2 * inset))}" result=""/>`);+ // A primitive's region defaults to its input's, which would clip the blur to the lit rectangle; spread over the whole frame.+ const soft = emit(`<feGaussianBlur in="${lit}" stdDeviation="${n((0.06 + 0.06 * vignette) * w)}" x="0" y="0" width="${n(w)}" height="${n(h)}" result=""/>`);+ emit(`<feComposite in="${pic}" in2="${soft}" operator="arithmetic" k1="${n(vignette)}" k2="${n(1 - vignette)}" k3="0" k4="0" result=""/>`);+ }+ const leak = v('leak');+ if (leak > 0) {+ const pic = cur;+ const drift = 0.62 + 0.18 * Math.sin(f * 0.011) + 0.05 * Math.sin(f * 0.047);+ const breathe = 0.75 + 0.25 * Math.sin(f * 0.023 + 1);+ const glow = emit(`<feFlood flood-color="${hex('leakColor', '#ff7a2a')}" x="${n(w * drift)}" y="${n(-h * 0.2)}" width="${n(w * 0.3)}" height="${n(h * 1.4)}" result=""/>`);+ const soft = emit(`<feGaussianBlur in="${glow}" stdDeviation="${n(0.09 * w)}" x="0" y="0" width="${n(w)}" height="${n(h)}" result=""/>`);+ const faded = emit(`<feComponentTransfer in="${soft}" result=""><feFuncA type="linear" slope="${n(leak * breathe)}" intercept="0"/></feComponentTransfer>`);+ emit(`<feBlend in="${faded}" in2="${pic}" mode="screen" result=""/>`);+ }++ const filter = `<filter id="${id}" x="0" y="0" width="100%" height="100%" color-interpolation-filters="sRGB" primitiveUnits="userSpaceOnUse">${parts.join('')}</filter>`;+ return {+ svg: `<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0" style="position:absolute;width:0;height:0;overflow:hidden" aria-hidden="true" focusable="false"><defs>${filter}</defs></svg>`,+ filter,+ css: `url(#${id})`,+ active: parts.length > 2,+ };+}++/**+ * A browser script that applies a look to the page it runs in, re-seeding it+ * for every song frame: installed in the composition live preview and in the+ * final render's browser (`Page.addScriptToEvaluateOnNewDocument`) before the+ * document's own scripts. It exposes `window.__portosFilmLook`:+ *+ * apply(look) put a (normalized) look on the page, or null to clear it+ * frame(n) redraw the filter for song frame n (grain, weave, flicker, leak)+ * look the look currently applied+ *+ * `globalThis.portosComposition` is intercepted when the document assigns it so+ * its `seek(t)` sets the frame BEFORE the document paints; the document's own+ * paint wait then covers the filter, and a seek stays one paint. The filter sits+ * on the root element, so it covers every layer the document draws.+ */+export function filmLookRuntimeSource(look = null) {+ return `(() => {+ const markup = ${filmLookFilterMarkup.toString()};+ const ID = 'portos-film-look';+ let look = ${JSON.stringify(normalizeFilmLook(look))};+ let frame = 0;+ let fps = 24;+ let host = null;+ const draw = () => {+ const root = document.documentElement;+ if (!root) return;+ const built = look ? markup(look, { frame, width: root.clientWidth || innerWidth || 1920, height: root.clientHeight || innerHeight || 1080, id: ID }) : null;+ if (!built || !built.active) {+ if (host) { host.remove(); host = null; }+ root.style.filter = '';+ return;+ }+ if (!host) {+ host = document.createElementNS('http://www.w3.org/2000/svg', 'svg');+ host.setAttribute('width', '0'); host.setAttribute('height', '0'); host.setAttribute('aria-hidden', 'true');+ host.style.cssText = 'position:absolute;width:0;height:0;overflow:hidden;pointer-events:none';+ host.dataset.portosFilmLook = '1';+ (document.body || root).appendChild(host);+ } else if (!host.isConnected) (document.body || root).appendChild(host);+ host.innerHTML = '<defs>' + built.filter + '</defs>';+ if (root.style.filter !== built.css) root.style.filter = built.css;+ };+ const api = {+ apply(next) { look = next && typeof next === 'object' ? next : null; draw(); },+ frame(n) { const next = Math.max(0, Math.floor(Number(n) || 0)); if (next !== frame || !host) { frame = next; if (look) draw(); } },+ get look() { return look; },+ };+ Object.defineProperty(window, '__portosFilmLook', { value: api, configurable: false, writable: false });+ // Wrap the document's seek so the filter is re-seeded for the frame before the document paints it.+ let composition;+ const wrap = (c) => {+ if (!c || typeof c !== 'object' || typeof c.seek !== 'function' || c.__portosFilmLookWrapped) return c;+ const seek = c.seek;+ const wrapped = function(t, ...rest) {+ fps = Number(c.fps) > 0 ? Number(c.fps) : fps;+ api.frame(Math.round((Number(t) || 0) * fps));+ return seek.call(this, t, ...rest);+ };+ try { Object.defineProperty(c, 'seek', { value: wrapped, configurable: true, writable: true }); Object.defineProperty(c, '__portosFilmLookWrapped', { value: true }); }+ catch { return Object.assign(Object.create(c), { seek: wrapped, __portosFilmLookWrapped: true }); }+ return c;+ };+ Object.defineProperty(globalThis, 'portosComposition', { configurable: true, enumerable: true,+ get() { return composition; }, set(value) { composition = wrap(value); } });+ if (document.readyState === 'loading') addEventListener('DOMContentLoaded', draw, { once: true }); else draw();+ addEventListener('resize', () => { if (look) draw(); });+})();`;+}diff --git a/server/lib/filmLook.test.js b/server/lib/filmLook.test.jsnew file mode 100644index 0000000000..9a9b5d0466--- /dev/null+++ b/server/lib/filmLook.test.js@@ -0,0 +1,97 @@+import { describe, expect, it } from 'vitest';+import {+ FILM_LOOK_CONTROLS, FILM_LOOK_PRESETS, describeFilmLook, filmLookFilterMarkup, filmLookPreset, filmLookRuntimeSource,+ isFilmLookNeutral, normalizeFilmLook,+} from './filmLook.js';+import { filmLookSchema } from './filmLookValidation.js';++describe('film look settings', () => {+ it('normalizes any input to one bounded record and tells a neutral look from an active one', () => {+ expect(normalizeFilmLook(null)).toBeNull();+ expect(normalizeFilmLook('vhs')).toBeNull();+ const look = normalizeFilmLook({ preset: 'nope', grain: 4, exposure: -9, halationColor: 'red', grainColor: 'yes', bogus: 1, defocus: 0.123456 });+ expect(look).toMatchObject({ version: 1, preset: 'custom', grain: 1, exposure: -1, halationColor: '#ff5a1f', grainColor: false, defocus: 0.12 });+ expect(look).not.toHaveProperty('bogus');+ expect(Object.keys(look).sort()).toEqual(['preset', 'version', ...FILM_LOOK_CONTROLS.map((c) => c.id)].sort());+ expect(isFilmLookNeutral(null)).toBe(true);+ expect(isFilmLookNeutral(filmLookPreset('none'))).toBe(true);+ // Grain size alone shapes nothing; a tint alone shapes nothing.+ expect(isFilmLookNeutral({ grainSize: 0.9, castColor: '#00ff00' })).toBe(true);+ expect(isFilmLookNeutral({ grain: 0.1 })).toBe(false);+ });++ it('every preset is a valid, complete look the schema accepts, and the first real one reads as the 80s reference', () => {+ for (const preset of FILM_LOOK_PRESETS) {+ const look = filmLookPreset(preset.id);+ expect(look.preset).toBe(preset.id);+ expect(filmLookSchema.safeParse(look).success, preset.id).toBe(true);+ expect(isFilmLookNeutral(look)).toBe(preset.id === 'none');+ }+ const words = describeFilmLook(filmLookPreset('neon-rain'));+ expect(words).toMatch(/halation/);+ expect(words).toMatch(/grain/);+ expect(describeFilmLook(filmLookPreset('none'))).toBe('');+ // Prompt words follow the slider, and a modifier's words only appear with its effect.+ expect(describeFilmLook({ saturation: -1 })).toMatch(/monochrome/);+ expect(describeFilmLook({ grainSize: 1 })).toBe('');+ });++ it('refuses unknown keys and out-of-range values at the schema', () => {+ expect(filmLookSchema.safeParse({ grain: 0.5, sharpen: 1 }).success).toBe(false);+ expect(filmLookSchema.safeParse({ grain: 1.5 }).success).toBe(false);+ expect(filmLookSchema.safeParse({ castColor: 'green' }).success).toBe(false);+ expect(filmLookSchema.safeParse({ preset: 'polaroid', grain: 0.5, grainColor: true }).success).toBe(true);+ });+});++describe('film look filter markup', () => {+ it('is self-contained, inactive for a neutral look, and a pure function of the frame', () => {+ // The preview and render pages receive this function by toString(): a module-scope reference would throw here.+ const standalone = new Function(`return (${filmLookFilterMarkup.toString()});`)();+ expect(standalone(filmLookPreset('vhs'), { frame: 3 }).filter).toBe(filmLookFilterMarkup(filmLookPreset('vhs'), { frame: 3 }).filter);++ expect(filmLookFilterMarkup(filmLookPreset('none'), { frame: 1 }).active).toBe(false);+ expect(filmLookFilterMarkup(null).active).toBe(false);++ const look = filmLookPreset('super8');+ const a = filmLookFilterMarkup(look, { frame: 10, width: 1920, height: 1080 });+ const again = filmLookFilterMarkup(look, { frame: 10, width: 1920, height: 1080 });+ const b = filmLookFilterMarkup(look, { frame: 11, width: 1920, height: 1080 });+ expect(a.active).toBe(true);+ expect(a.filter).toBe(again.filter);+ expect(a.filter).not.toBe(b.filter);+ expect(a.css).toBe('url(#portos-film-look)');+ expect(a.svg).toContain(`id="portos-film-look"`);+ // Time-free looks draw the same filter at every frame, so a still is one bake.+ const still = normalizeFilmLook({ defocus: 0.5, fade: 0.5, vignette: 0.5 });+ expect(filmLookFilterMarkup(still, { frame: 0 }).filter).toBe(filmLookFilterMarkup(still, { frame: 500 }).filter);+ });++ it('scales radii with the filtered element so a phone preview, the render and a 4K still read alike', () => {+ const look = normalizeFilmLook({ defocus: 0.5 });+ const phone = /stdDeviation="([\d.]+)"/.exec(filmLookFilterMarkup(look, { width: 390, height: 219 }).filter)[1];+ const render = /stdDeviation="([\d.]+)"/.exec(filmLookFilterMarkup(look, { width: 1920, height: 1080 }).filter)[1];+ expect(Number(render) / Number(phone)).toBeCloseTo(1920 / 390, 1);+ });++ it('only emits the primitives a control turns on', () => {+ const grainOnly = filmLookFilterMarkup(normalizeFilmLook({ grain: 0.4 }), {}).filter;+ expect(grainOnly).toContain('feTurbulence');+ expect(grainOnly).not.toContain('feGaussianBlur');+ const glowOnly = filmLookFilterMarkup(normalizeFilmLook({ halation: 0.4, halationColor: '#00ff00' }), {}).filter;+ expect(glowOnly).toContain('feGaussianBlur');+ expect(glowOnly).not.toContain('feTurbulence');+ expect(glowOnly).toContain('0 1 0 0 0'); // the halation tint row for pure green+ });+});++describe('film look runtime', () => {+ it('carries the markup, the starting look and the composition seek hook into a page', () => {+ const source = filmLookRuntimeSource({ grain: 0.3, preset: 'custom' });+ expect(source).toContain('function filmLookFilterMarkup');+ expect(source).toContain('"grain":0.3');+ expect(source).toContain("'portosComposition'");+ expect(source).toContain('__portosFilmLook');+ expect(filmLookRuntimeSource(null)).toContain('let look = null;');+ });+});diff --git a/server/lib/filmLookValidation.js b/server/lib/filmLookValidation.jsnew file mode 100644index 0000000000..f1c8a944d3--- /dev/null+++ b/server/lib/filmLookValidation.js@@ -0,0 +1,26 @@+import { z } from 'zod';+import { FILM_LOOK_CONTROLS, FILM_LOOK_PRESET_IDS, FILM_LOOK_VERSION } from './filmLook.js';++/**+ * The film-look record a project stores and a gallery bake receives, derived+ * from the one control table so a new control is validated the moment it is+ * declared. Every field is optional (the normalizer fills defaults); unknown+ * keys are refused so a typo never silently becomes "no effect".+ */+const controlShape = {};+for (const control of FILM_LOOK_CONTROLS) {+ if (control.type === 'color') controlShape[control.id] = z.string().regex(/^#[0-9a-f]{6}$/i, `${control.id} is #rrggbb`).optional();+ else if (control.type === 'toggle') controlShape[control.id] = z.boolean().optional();+ else controlShape[control.id] = z.number().min(control.min).max(control.max).optional();+}++export const filmLookSchema = z.object({+ version: z.literal(FILM_LOOK_VERSION).optional(),+ preset: z.enum([...FILM_LOOK_PRESET_IDS, 'custom']).optional(),+ ...controlShape,+}).strict();++/** Body of `POST /api/image-gen/:filename/film-look`: the look to bake into a new copy. */+export const filmLookBakeSchema = z.object({+ look: filmLookSchema,+}).strict();diff --git a/server/lib/index.js b/server/lib/index.jsindex 5125cdce14..c7daf7ac01 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -833,6 +833,8 @@ export * from './imageLimits.js';export * from './musicVideoActionContract.js';export * from './musicVideoGrade.js';+export * from './filmLook.js';+export * from './filmLookValidation.js';export * from './musicVideoDependencies.js';export * from './musicVideoCrossLinks.js';export * from './musicVideoExcerptRange.js';diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex a5efa09d44..7e8bd5471f 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -1,5 +1,6 @@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 { COVER_DESIGN_OPTIONS } from './musicVideoCoverOverlay.js';import { DISTROKID_REMEMBERED_OPTIONS } from './distrokidGenres.js';import { CROSS_LINK_EDIT_TARGETS } from './musicVideoCrossLinks.js';@@ -1221,6 +1222,8 @@ export const musicVideoProjectCreateSchema = z.object({pacing: musicVideoPacingSchema.nullable().optional(),composition: musicVideoCompositionSchema.nullable().optional(),soundBed: musicVideoSoundBedSchema.nullable().optional(),+ // The finishing film look (lib/filmLook.js); null = none.+ filmLook: filmLookSchema.nullable().optional(),}).strict();export const musicVideoProjectUpdateSchema = z.object({@@ -1245,6 +1248,8 @@ export const musicVideoProjectUpdateSchema = z.object({pacing: musicVideoPacingSchema.nullable().optional(),composition: musicVideoCompositionSchema.nullable().optional(),soundBed: musicVideoSoundBedSchema.nullable().optional(),+ // The finishing film look (lib/filmLook.js); null = none.+ filmLook: filmLookSchema.nullable().optional(),}).strict();// Mark a project finished outside PortOS (or clear the marker). The serverdiff --git a/server/routes/imageGen.filmLook.test.js b/server/routes/imageGen.filmLook.test.jsnew file mode 100644index 0000000000..a6ae798f83--- /dev/null+++ b/server/routes/imageGen.filmLook.test.js@@ -0,0 +1,123 @@+import { describe, it, expect, beforeEach, beforeAll, afterAll, vi } from 'vitest';+import express from 'express';+import sharp from 'sharp';+import { mkdtemp, rm, writeFile, readFile } from 'fs/promises';+import { existsSync } from 'fs';+import { join } from 'path';+import { tmpdir } from 'os';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++// Sandbox PATHS.images and PATHS.data (the bake stages its page under data) the+// way imageGen.clean.test.js does, so the endpoint reads and writes real files+// without touching data/.+let sandbox;++vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ return {+ ...actual,+ get PATHS() {+ return { ...actual.PATHS, images: join(sandbox, 'images'), data: sandbox };+ },+ };+});++// The composition browser is a fake page: the test asserts what the bake asks+// of it (the staged page, the viewport it sizes, one screenshot) and hands back+// a PNG as the "rendered" frame.+const browser = vi.hoisted(() => ({ opened: [], commands: [], screenshot: null, closed: 0 }));+vi.mock('../services/htmlComposition/browser.js', () => ({+ openComposition: vi.fn(async (directory, options) => {+ const { readFile: read } = await import('fs/promises');+ const { join: j } = await import('path');+ browser.opened.push({ directory, options, page: await read(j(sandbox, directory, 'index.html'), 'utf8') });+ return {+ evaluate: vi.fn(async () => true),+ send: vi.fn(async (method, params) => {+ browser.commands.push({ method, params });+ return method === 'Page.captureScreenshot' ? { data: browser.screenshot.toString('base64') } : {};+ }),+ check: () => {},+ close: vi.fn(async () => { browser.closed += 1; }),+ };+ }),+}));++vi.mock('../services/imageGen/index.js', async () => {+ const actual = await vi.importActual('../services/imageGen/index.js');+ return { ...actual, checkConnection: vi.fn(), generateImage: vi.fn(), generateAvatar: vi.fn(), attachSseClient: vi.fn(() => false), cancel: vi.fn(() => false) };+});+vi.mock('../services/settings.js', () => ({+ getSettings: vi.fn(async () => ({ imageGen: { mode: 'external' } })),+ settingsEvents: { on: () => {}, emit: () => {} },+}));+vi.mock('../services/mediaJobQueue/index.js', () => ({ enqueueJob: vi.fn(), attachSseClient: vi.fn(() => false), cancelJob: vi.fn(), listJobs: vi.fn(() => []) }));+const { listCollectionsMock, addItemMock } = vi.hoisted(() => ({ listCollectionsMock: vi.fn(async () => []), addItemMock: vi.fn(async () => ({})) }));+vi.mock('../services/mediaCollections.js', () => ({ listCollections: listCollectionsMock, addItem: addItemMock, ERR_DUPLICATE: 'DUPLICATE' }));++let imageGenRoutes;+const png = (r, g, b) => sharp({ create: { width: 64, height: 48, channels: 3, background: { r, g, b } } }).png().toBuffer();++beforeAll(async () => {+ sandbox = await mkdtemp(join(tmpdir(), 'portos-film-look-'));+ await (await import('fs/promises')).mkdir(join(sandbox, 'images'), { recursive: true });+ ({ default: imageGenRoutes } = await import('./imageGen.js'));+});+afterAll(async () => { await rm(sandbox, { recursive: true, force: true }); });++describe('POST /api/image-gen/:filename/film-look', () => {+ let app;+ beforeEach(async () => {+ app = express();+ app.use(express.json());+ app.use('/api/image-gen', imageGenRoutes);+ app.use(errorMiddleware);+ browser.opened.length = 0;+ browser.commands.length = 0;+ browser.closed = 0;+ browser.screenshot = await png(200, 120, 60);+ await writeFile(join(sandbox, 'images', 'still-1.png'), await png(30, 40, 50));+ await writeFile(join(sandbox, 'images', 'still-1.metadata.json'), JSON.stringify({ prompt: 'a rainy window', seed: 3, modelId: 'example-model', regenerated: true, regenStrength: 0.4 }));+ });++ it('renders the look in the composition browser at the image size and saves it as a variant beside the original', async () => {+ const look = { preset: 'neon-rain', grain: 0.6, halation: 0.8 };+ const res = await request(app).post('/api/image-gen/still-1.png/film-look').send({ look });+ expect(res.status).toBe(200);+ expect(res.body.filename).toMatch(/^still-1_look-neon-rain-[0-9a-f]{8}\.png$/);+ expect(res.body).toMatchObject({ cleanedFrom: 'still-1.png', filmLookFrom: 'still-1.png', prompt: 'a rainy window', modelId: 'example-model', width: 64, height: 48 });+ expect(res.body.filmLook).toMatchObject({ preset: 'neon-rain', grain: 0.6, halation: 0.8, version: 1 });+ expect(res.body.filmLookWords).toMatch(/halation/);+ // The regen lineage would mislabel the copy (the lightbox reads it first), so it does not carry over.+ expect(res.body.regenerated).toBeUndefined();+ expect(res.body.regenStrength).toBeUndefined();++ // What the browser was asked: the staged one-image page with the filter on the image, sized to it, one capture, then closed.+ expect(browser.opened).toHaveLength(1);+ expect(browser.opened[0].directory).toMatch(/^film-look-bakes\//);+ expect(browser.opened[0].options).toMatchObject({ ownedBrowser: true });+ expect(browser.opened[0].page).toContain('<img src="source.png"');+ expect(browser.opened[0].page).toContain('filter:url(#portos-film-look)');+ expect(browser.opened[0].page).toContain('feTurbulence');+ expect(browser.commands.map((c) => c.method)).toEqual(['Emulation.setDeviceMetricsOverride', 'Page.captureScreenshot']);+ expect(browser.commands[0].params).toMatchObject({ width: 64, height: 48 });+ expect(browser.closed).toBe(1);++ // The copy is the captured frame; the original and the staging folder are as they were.+ const saved = await readFile(join(sandbox, 'images', res.body.filename));+ expect(saved.equals(browser.screenshot)).toBe(true);+ expect((await readFile(join(sandbox, 'images', 'still-1.png'))).equals(await png(30, 40, 50))).toBe(true);+ expect(existsSync(join(sandbox, browser.opened[0].directory))).toBe(false);+ const sidecar = JSON.parse(await readFile(join(sandbox, 'images', res.body.filename.replace(/\.png$/, '.metadata.json')), 'utf8'));+ expect(sidecar).toMatchObject({ filmLookFrom: 'still-1.png', cleanedFrom: 'still-1.png' });+ });++ it('refuses a look that changes nothing, an unknown control, and a missing image without opening a browser', async () => {+ expect((await request(app).post('/api/image-gen/still-1.png/film-look').send({ look: { preset: 'none' } })).status).toBe(422);+ expect((await request(app).post('/api/image-gen/still-1.png/film-look').send({ look: { grain: 0.5, sharpen: 1 } })).status).toBe(400);+ expect((await request(app).post('/api/image-gen/still-1.png/film-look').send({})).status).toBe(400);+ expect((await request(app).post('/api/image-gen/missing.png/film-look').send({ look: { grain: 0.5 } })).status).toBe(404);+ expect(browser.opened).toHaveLength(0);+ });+});diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex a894f45d22..c9e275a732 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -29,6 +29,8 @@ import { startHfDownloadStream } from '../services/hfDownloadStream.js';import { PATHS, ensureDir, resolveGalleryImage, unlinkGuarded, copyFileGuarded } from '../lib/fileUtils.js';import { prepareGenerateParams, resolveLocalImageModel, selectLocalImageModelFromSettings } from '../services/imageGen/prepareParams.js';import { applyImageClean, applyWatermarkRemoval, applyLightRegenVariant } from '../services/imageGen/variants.js';+import { applyFilmLookBake } from '../services/imageGen/filmLookBake.js';+import { filmLookBakeSchema } from '../lib/filmLookValidation.js';import { join, basename } from 'node:path';import { STYLE_PRESETS } from '../lib/writersRoomStylePresets.js';import {@@ -351,6 +353,19 @@ const regenerateSchema = z.object({annotated: z.boolean().optional(),});+// Film look (lib/filmLook.js) baked into a new copy of a gallery still — the+// same SVG filter the music-video preview and final render apply, rendered in+// the composition browser at the image's own size. Synchronous like Clean:+// writes a `_look-<preset>-<id>.png` variant + sidecar beside the untouched+// source, files it into the source's collections, and returns it.+router.post('/:filename/film-look', asyncHandler(async (req, res) => {+ const filename = req.params.filename;+ local.assertGalleryFilename(filename);+ const { look } = validateRequest(filmLookBakeSchema, req.body ?? {});+ const { metadata: sourceMeta } = await local.readImageSidecar(filename);+ res.json(await applyFilmLookBake({ filename, sourceMeta, look }));+}));+// Visible-watermark removal — erases the Gemini / Nano-Banana bottom-right ✦.// Body is optional: with no fields the corner box is auto-sized to the// sparkle's typical footprint. `size` overrides the square side; `region`diff --git a/server/routes/musicVideoCompositionDocument.test.js b/server/routes/musicVideoCompositionDocument.test.jsindex 1c97d2db54..54b3b404b0 100644--- a/server/routes/musicVideoCompositionDocument.test.js+++ b/server/routes/musicVideoCompositionDocument.test.js@@ -161,6 +161,19 @@ describe('music-video composition documents', () => {expect(invalidRevision.status).toBe(400);});+ it('persists a normalized film look through the project route, refuses an unknown control, and clears it with null', async () => {+ const saved = await request(app).patch(`/api/music-video/${project.id}`).send({ filmLook: { preset: 'polaroid', grain: 0.5, exposure: 0.123 } });+ expect(saved.status).toBe(200);+ expect(saved.body.filmLook).toMatchObject({ version: 1, preset: 'polaroid', grain: 0.5, exposure: 0.12, defocus: expect.any(Number) });+ expect((await request(app).patch(`/api/music-video/${project.id}`).send({ filmLook: { exposure: 3 } })).status).toBe(400);+ expect((await projects.getProject(project.id)).filmLook).toEqual(saved.body.filmLook);+ expect((await request(app).patch(`/api/music-video/${project.id}`).send({ filmLook: { grain: 0.5, sharpen: 1 } })).status).toBe(400);+ const cleared = await request(app).patch(`/api/music-video/${project.id}`).send({ filmLook: null });+ expect(cleared.status).toBe(200);+ expect(cleared.body.filmLook).toBeNull();+ expect((await projects.getProject(project.id)).filmLook).toBeNull();+ });+it('imports a zip (one top folder), switches the render style, lists, exports, previews and serves its files inert', async () => {const zip = createZip(Object.entries(FILES).map(([name, data]) => ({ name: `my-video/${name}`, data })), { compress: true });const created = await uploadZip(project.id, zip, 'my-video.zip');@@ -188,6 +201,7 @@ describe('music-video composition documents', () => {// Self-contained: no network, the stylesheet/script/asset inlined, PORTOS_MV injected, portos-mv.js dropped.expect(preview.body.html).toContain("default-src 'none'");expect(preview.body.html).toContain('window.PORTOS_MV = ');+ expect(preview.body.html).toContain('__portosFilmLook');expect(preview.body.html).toContain(FILES['app.js']);expect(preview.body.html).toContain('url("data:image/png;base64,');expect(preview.body.html).not.toContain('src="portos-mv.js"');diff --git a/server/services/imageGen/filmLookBake.js b/server/services/imageGen/filmLookBake.jsnew file mode 100644index 0000000000..5fdc146036--- /dev/null+++ b/server/services/imageGen/filmLookBake.js@@ -0,0 +1,113 @@+/**+ * Film-look bake — a gallery still viewed through a film look, saved as a new+ * copy beside the original (the original is never changed).+ *+ * The bake renders the SAME SVG filter the live preview and the final render+ * use (lib/filmLook.js), in the sandboxed composition browser: a one-file page+ * sized to the image, the image filtered on its root, one screenshot. So what+ * the editor shows on a phone is what lands in the gallery, at the image's own+ * resolution.+ *+ * The copy is a variant of its source (`cleanedFrom` = the group root, like a+ * clean or a watermark removal), so the lightbox offers an Original / Film look+ * toggle and the copy files into every collection the source is in.+ */++import { copyFile, mkdir, readFile, rm, writeFile } from 'fs/promises';+import { extname, join } from 'node:path';+import { randomUUID } from 'crypto';+import { ServerError } from '../../lib/errorHandler.js';+import { PATHS } from '../../lib/fileUtils.js';+import { describeFilmLook, filmLookFilterMarkup, isFilmLookNeutral, normalizeFilmLook } from '../../lib/filmLook.js';+import { persistVariant } from './variants.js';++export const FILM_LOOK_SCRATCH_DIR = 'film-look-bakes';+// The composition browser screenshots the whole viewport in one frame; past+// this a 4K-plus still would stall it rather than finish.+export const FILM_LOOK_BAKE_MAX_SIDE = 4096;+const SOURCE_EXT = new Set(['.png', '.jpg', '.jpeg', '.webp']);++/** The one-image page a bake screenshots: the image at its own size, the look on it, frame 0. Pure. */+function filmLookBakePage(look, { width, height, src }) {+ const built = filmLookFilterMarkup(normalizeFilmLook(look), { frame: 0, width, height });+ return `<!doctype html><html><head><meta charset="utf-8"><title>Film look</title>+<style>html,body{margin:0;width:${width}px;height:${height}px;overflow:hidden;background:#000}img{display:block;width:${width}px;height:${height}px;filter:${built.active ? built.css : 'none'}}</style>+</head><body>${built.svg}<img src="${src}" alt=""></body></html>\n`;+}++/**+ * Bake `look` into a new copy of gallery image `filename`; resolves the+ * gallery-compatible record of the copy (persistVariant's shape).+ */+export async function applyFilmLookBake({ filename, sourceMeta, look: input, signal }) {+ const look = normalizeFilmLook(input);+ if (!look || isFilmLookNeutral(look)) throw new ServerError('The film look has no effect; move a control before saving a copy', { status: 422, code: 'FILM_LOOK_NEUTRAL' });+ const ext = extname(filename).toLowerCase();+ if (!SOURCE_EXT.has(ext)) throw new ServerError('Only PNG, JPEG and WebP images take a film look', { status: 422, code: 'FILM_LOOK_SOURCE_TYPE' });+ const sourcePath = join(PATHS.images, filename);+ const buffer = await readFile(sourcePath).catch((err) => {+ if (err.code === 'ENOENT') throw new ServerError('Image not found', { status: 404, code: 'NOT_FOUND' });+ throw err;+ });+ const { default: sharp } = await import('sharp');+ const meta = await sharp(buffer).metadata().catch(() => null);+ const width = meta?.width;+ const height = meta?.height;+ if (!(width > 0 && height > 0)) throw new ServerError('Invalid or corrupt image', { status: 400, code: 'INVALID_IMAGE' });+ if (Math.max(width, height) > FILM_LOOK_BAKE_MAX_SIDE) {+ throw new ServerError(`The image is larger than ${FILM_LOOK_BAKE_MAX_SIDE}px on a side; downscale it before applying a film look`, { status: 422, code: 'FILM_LOOK_TOO_LARGE' });+ }++ const { openComposition } = await import('../htmlComposition/browser.js');+ const id = randomUUID();+ const scratch = join(PATHS.data, FILM_LOOK_SCRATCH_DIR, id);+ let page;+ let png;+ try {+ await mkdir(scratch, { recursive: true });+ const src = `source${ext}`;+ await copyFile(sourcePath, join(scratch, src));+ await writeFile(join(scratch, 'index.html'), filmLookBakePage(look, { width, height, src }));+ page = await openComposition(`${FILM_LOOK_SCRATCH_DIR}/${id}`, { signal, ownedBrowser: true });+ await page.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false });+ // The resize relays out the page; the screenshot waits for the paint after it.+ await page.evaluate('new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))');+ page.check();+ ({ data: png } = await page.send('Page.captureScreenshot', { format: 'png', fromSurface: true, captureBeyondViewport: false }));+ page.check();+ await page.close({ verify: true });+ page = null;+ } finally {+ if (page) await page.close().catch(() => {});+ await rm(scratch, { recursive: true, force: true }).catch(() => {});+ }+ const data = Buffer.from(png, 'base64');++ const base = filename.slice(0, -ext.length);+ const outFilename = `${base}_look-${look.preset}-${id.slice(0, 8)}.png`;+ // Anchor the copy at the group root so a look on a cleaned copy still toggles against the original.+ const groupRoot = typeof sourceMeta.cleanedFrom === 'string' && sourceMeta.cleanedFrom ? sourceMeta.cleanedFrom : filename;+ const createdAt = new Date().toISOString();+ // Drop the fields that would mislabel the copy (the lightbox reads them before the film-look lineage) and the+ // identity fields listGallery would otherwise spread over the copy's own.+ const {+ hidden: _hidden, filename: _srcFilename, id: _srcId,+ regenerated: _regenerated, regenStrength: _regenStrength, regenSteps: _regenSteps, regenModelId: _regenModelId,+ regenPixelDeltaPct: _regenPixelDeltaPct, regenPsnr: _regenPsnr, regenMethod: _regenMethod,+ watermarkRemoved: _watermarkRemoved, watermarkRegion: _watermarkRegion, cleanLevel: _cleanLevel, c2paStripped: _c2paStripped,+ ...sourceMetaForVariant+ } = sourceMeta;+ const lineage = { createdAt, cleanedFrom: groupRoot, filmLookFrom: filename, filmLook: look, filmLookWords: describeFilmLook(look) };+ return persistVariant({+ sourceFilename: filename,+ outFilename,+ data,+ variantMeta: { ...sourceMetaForVariant, ...lineage },+ width,+ height,+ sizeBefore: buffer.length,+ sizeAfter: data.length,+ logLine: `🎞️ Film look ${look.preset} ${filename} → ${outFilename} (${width}×${height})`,+ extraFields: lineage,+ });+}diff --git a/server/services/musicVideo/documentPreview.js b/server/services/musicVideo/documentPreview.jsindex b0d215d832..6dd7493bc8 100644--- a/server/services/musicVideo/documentPreview.js+++ b/server/services/musicVideo/documentPreview.js@@ -1,5 +1,6 @@import { PREVIEW_DOCUMENT_BASE, inlineDocumentModule, previewDocumentPath } from './documentModules.js';import { musicVideoMediaMode } from '../../lib/musicVideoMediaPolicy.js';+import { filmLookRuntimeSource } from '../../lib/filmLook.js';/*** Music Video — the in-app live preview of a composition document.*@@ -186,6 +187,9 @@ const BOOTSTRAP = `(() => {const entry = map.get(key) || null;for (const callback of callbacks) callback(entry);sweep();+ } else if (message.type === 'portos-mv:film-look') {+ // The finishing look, live from the panel's sliders: applied to the page root, re-seeded per seek.+ if (globalThis.__portosFilmLook) globalThis.__portosFilmLook.apply(message.look && typeof message.look === 'object' ? message.look : null);} else if (message.type === 'portos-mv:seek') {const t = Number(message.t) || 0;seeking = seeking.then(() => globalThis.portosComposition?.seek(t)).then(@@ -280,7 +284,8 @@ export async function buildDocumentPreview(project, { draft = false, files: give}const mode = musicVideoMediaMode(project);const csp = PREVIEW_CSP.replace('img-src data: blob:', mode === 'code-only' ? "img-src 'none'" : 'img-src data: blob:').replace('media-src data: blob:', mode !== 'code-images-video' ? "media-src 'none'" : 'media-src data: blob:');- const head = `<meta http-equiv="Content-Security-Policy" content="${csp}"><script>${BOOTSTRAP}</script><script>window.PORTOS_MV = ${scriptJson(data)};window.PORTOS_MV_EVENT_STATE = ${narrativeFrameState.toString()};</script>`;+ // The film look runtime always ships (the panel posts live changes); the project's saved look is its start.+ const head = `<meta http-equiv="Content-Security-Policy" content="${csp}"><script>${BOOTSTRAP}</script><script>${filmLookRuntimeSource(project.filmLook)}</script><script>window.PORTOS_MV = ${scriptJson(data)};window.PORTOS_MV_EVENT_STATE = ${narrativeFrameState.toString()};</script>`;const at = html.match(/<head[^>]*>/i);html = at ? `${html.slice(0, at.index + at[0].length)}${head}${html.slice(at.index + at[0].length)}` : `${head}${html}`;diff --git a/server/services/musicVideo/documentRender.js b/server/services/musicVideo/documentRender.jsindex ade4b19587..6ab3932745 100644--- a/server/services/musicVideo/documentRender.js+++ b/server/services/musicVideo/documentRender.js@@ -1,5 +1,6 @@import { assertMusicVideoMediaSelections, musicVideoMediaMode } from '../../lib/musicVideoMediaPolicy.js';import { musicVideoGradeFilter } from '../../lib/musicVideoGrade.js';+import { filmLookRuntimeSource, isFilmLookNeutral } from '../../lib/filmLook.js';/*** Music Video — render a project's composition document over the song.*@@ -58,6 +59,16 @@ const safeSegment = (id) => String(id || 'scene').replace(/[^A-Za-z0-9_-]+/g, '-/** The project's aspect ratio (brief), defaulting to 16:9 (lib/musicVideoAspect.js). */export const documentAspect = musicVideoAspect;+/**+ * The browser init scripts a document render opens its page with: the film+ * look runtime (lib/filmLook.js) when the project has a non-neutral look, so+ * every captured frame, probe sample and worker browser draws the same+ * finishing filter the live preview shows. Pure.+ */+export function documentRenderInitScripts(project) {+ return isFilmLookNeutral(project?.filmLook) ? [] : [filmLookRuntimeSource(project.filmLook)];+}+const aspectOf = (width, height) => {const r = width / height;if (Math.abs(r - 16 / 9) < 0.01) return '16:9';@@ -339,7 +350,8 @@ export async function encodeDocumentComposition({prepare: (dir) => stageDocumentData(dir, data, media),});signal?.throwIfAborted();- const openPage = (pageSignal) => openComposition(staged.directory, { signal: pageSignal, streamMedia: true, mediaMode: musicVideoMediaMode(project), ownedBrowser: true });+ const openPage = (pageSignal) => openComposition(staged.directory, { signal: pageSignal, streamMedia: true, mediaMode: musicVideoMediaMode(project), ownedBrowser: true,+ initScripts: documentRenderInitScripts(project) });page = await openPage(signal);const metadata = await page.evaluate(`(() => {const c = globalThis.portosComposition;@@ -476,7 +488,7 @@ export async function probeDocumentText({ project, jobId, signal, sampleTimes, o});signal?.throwIfAborted();page = await openComposition(staged.directory, { signal, streamMedia: true, mediaMode: musicVideoMediaMode(project), ownedBrowser: true,- initScripts: [OVERLAY_TEXT_PROBE_SCRIPT] });+ initScripts: [...documentRenderInitScripts(project), OVERLAY_TEXT_PROBE_SCRIPT] });const metadata = await page.evaluate(`(() => {const c = globalThis.portosComposition;if (!c || typeof c.seek !== 'function') throw new Error('portosComposition.seek is required');diff --git a/server/services/musicVideo/documentRender.test.js b/server/services/musicVideo/documentRender.test.jsindex e287bc2014..57a7fd2c6f 100644--- a/server/services/musicVideo/documentRender.test.js+++ b/server/services/musicVideo/documentRender.test.js@@ -28,7 +28,7 @@ vi.mock('../../lib/ffmpeg.js', async (importOriginal) => ({}));// Capture the frozen job folder the page would open, then stop the render.vi.mock('../htmlComposition/browser.js', () => ({- openComposition: async (directory) => {+ openComposition: async (directory, options) => {const { readFile: read, readdir: list } = await import('node:fs/promises');const { join: joinPath } = await import('node:path');const { PATHS: paths } = await import('../../lib/paths.js');@@ -37,7 +37,7 @@ vi.mock('../htmlComposition/browser.js', () => ({for (const name of await list(joinPath(dir, 'media'))) media[name] = await read(joinPath(dir, 'media', name), 'utf8');const window = {};new Function('window', await read(joinPath(dir, 'portos-mv.js'), 'utf8'))(window);- browser.seen = { directory, data: window.PORTOS_MV, media, song: JSON.parse(await read(joinPath(dir, 'song.json'), 'utf8')) };+ browser.seen = { directory, data: window.PORTOS_MV, media, song: JSON.parse(await read(joinPath(dir, 'song.json'), 'utf8')), initScripts: options?.initScripts ?? [] };return {async evaluate(expression) {if (expression.includes('reviewFootage')) { browser.sampleTimes.push(Number(/c.seek\(([^,]+)/.exec(expression)[1])); return browser.visibility; }@@ -169,3 +169,16 @@ it('carries measured footage samples and explicit missing hooks from the stagedexpect(browser.sampleTimes.every(at => at >= 1 && at < 10)).toBe(true);expect(await scratchEntries()).toEqual([]);});++// Uniquely catches the render page opening without the film look the live preview showed.+it('installs the project film look in the render page before the document runs, and nothing when the look is neutral', async () => {+ const { project, plan } = await fixture();+ await expect(encode(project, plan, 'job-plain')).rejects.toThrow('stop after staging');+ expect(browser.seen.initScripts).toEqual([]);+ const graded = { ...project, filmLook: { preset: 'super8', grain: 0.6, halation: 0.4 } };+ await expect(encode(graded, plan, 'job-look')).rejects.toThrow('stop after staging');+ expect(browser.seen.initScripts).toHaveLength(1);+ expect(browser.seen.initScripts[0]).toContain('__portosFilmLook');+ expect(browser.seen.initScripts[0]).toContain('"grain":0.6');+ expect(await scratchEntries()).toEqual([]);+});diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.jsindex f60ca01ac4..5f0ed0ef95 100644--- a/server/services/musicVideo/projectsLogic.js+++ b/server/services/musicVideo/projectsLogic.js@@ -37,6 +37,7 @@ import { normalizeLyricMarkers } from './lyricMarkers.js';import { ensureSceneTakes, TAKE_SLOT } from './takes.js';import { normalizeComposition, invalidateCompositionTiming, withStoredCompositionDocument } from './composition.js';import { normalizeSoundBed } from './soundBed.js';+import { normalizeFilmLook } from '../../lib/filmLook.js';import { remapTreatmentForClone, scenesFingerprint } from './treatment.js';import { normalizeMusicVideoAutomation } from '../../lib/musicVideoAutomation.js';@@ -159,6 +160,8 @@ export function buildProjectRecord(input, { id, now }) {composition: input.composition || input.mediaMode ? withStoredCompositionDocument(normalizeComposition(input.composition || { mode: 'document' }), null) : null,// #8988 — optional sound-design bed mixed under the song.soundBed: input.soundBed ? normalizeSoundBed(input.soundBed) : null,+ // The finishing film look every preview, render and baked still is viewed through; null = none.+ filmLook: input.filmLook ? normalizeFilmLook(input.filmLook) : null,// #8980 — optional pre-production treatment (brief, arc, shot direction,// proof checklist); null until the director starts one. See treatment.js.treatment: null,@@ -356,6 +359,8 @@ export function applyProjectPatch(project, patch) {...('composition' in patch ? { composition: withStoredCompositionDocument(normalizeComposition(patch.composition), project.composition) } : {}),// #8988 — an explicitly chosen sound-design bed; null clears it....('soundBed' in patch ? { soundBed: normalizeSoundBed(patch.soundBed) } : {}),+ // The film look is replaced whole (one bounded record); null clears it.+ ...('filmLook' in patch ? { filmLook: normalizeFilmLook(patch.filmLook) } : {}),};// #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;