Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Click to Ad: the end card animates in five styles

Adarsh25c7c41f85a9
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 6ab85aeb..065c01c5 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -145,7 +145,7 @@ Every adapter implements `isConfigured`, `prepareFile`, `submit` and `poll`, and
- **Round 5 part 1 (fixes-5): reachability shared with Ollama.** The busy-vs-down rules above moved to `src/server/providers/reach.ts` (`hostPort`, `takesConnection`, `ask`, `checkReach`, `sharedCheck`, `reachSync`), which Ollama's check now uses too (see LLM provider). `REACH` is exported from there, and one map of running checks (`globalThis.__fuobeReachChecks`) replaces `__fuobeComfyProbe`; `probeComfy` and `probeComfySync` keep their behaviour (`tests/comfy-reach.test.ts`).
- **Round 5 part 2: soundtrack splits and asked sizes.** On `separate-soundtrack-dbs`, `prepareWorkflow()` binds `separationModel` to the model asked for, else the host's pick (`dbsModelFor` in `src/lib/av/split.ts`: DBS-TIGER on a CUDA device, DBS-BSRNN on a CPU, the other one when the pick isn't on disk). The device comes from `/system_stats` (`comfyDevice`, kept a minute) and the models on disk from `GET /models/dbs`, which ComfyUI-DBS registers (`comfyDbsModels`, read fresh at submit; callers that arrive while either request is on its way share it); a model that isn't there is refused in words, never sent. `channels` is mono or each channel (`dbsChannelsFor`), and a source with more than 2 channels (the header's count, else `params.extra.sourceChannels`) is split in mono with a mono Music & effects (`dbsSurroundBed`), because ComfyUI saves at most 2 channels. A canvas the request names (`params.extra.width` / `height`: a layout's, Soul's exact sizes) is fitted to the graph's grid and maximum side with its shape kept (`fitCanvas` in `src/lib/comfy.ts`), as the cloud's `sizeValue` fits it, so both engines render one size. Upload headers carry the channel count (`MediaInfo.channels`: WAV, FLAC, MP3 and an MP4 / MOV's first sound track in `src/lib/media-probe.ts`; WebM / Matroska in `src/server/webm-probe.ts`). The manifest's outputs gain the stems `music` and `effects` and the role `report` (a node's own account of the run).
- **llm** — text steps in this process (below).
-- **local** — results made in the browser (Color grading's PNG / WebM, Ads Studio composites; `/api/generations/local` records them).
+- **local** — results made in the browser (Color grading's PNG / WebM, Ads Studio composites, Kinetic Motion clips; `/api/generations/local` records them, an account's Kinetic Motion clip as its own run).
- **mock** — demo outputs for every operation (SVG art, bundled sample clips, a tone, layers with meta, cue lists, two stems, a GLB with a turntable from `scripts/gen-demo-3d.mjs`), so the product works with zero setup. Round-4 operations answer too: a scene-3d job gets the GLB plus a grey depth PNG on the open engine and a Spectral-coloured depth PNG on the cloud, and an EXR job a sample clip with a zip that holds only a README. An extract-frames job returns as many frames as `max_frames` asks (4 without a count), so a per-frame Mixed Media demo fans out like the real one. Splat and rig jobs get the demo GLB too (`meta.format` `glb`), so a demo run never shows the splat card. Since round 4 part 5 a `video-swap` on Character Swap Studio's segment graph also returns a `master`, so a demo continuation runs like a real one. Since round 5 part 1 a `face-mosaic` job returns a demo picture with no masks. Since round 5 part 2 a `separate-audio` job on `separate-soundtrack-dbs` returns four stems (voice, music, effects and background, voice first). A request with `demo: true` (a skill's free dry run) goes to this provider whatever Settings → Demo mode says (see Pipelines).
## Structured outputs
@@ -386,7 +386,7 @@ Each studio keeps its data and pure planner in `src/lib/`, its server module in
| **Mixed Media** (`/mixed-media`) | `catalog/mixed-media.ts`: 33 presets with settings, frames = floor(s × fps), open render (one job, on `oss-mixed-media` until round 5 part 1), cloud Fast plan (trim → restyle → original sound), preview plan. Round 4 part 2: the cloud Per frame plan (`planMixedFrames`, the cloud default until round 5 part 1): cut → `extract-frames` (every Nth frame of the clip, `frameSampling`; up to 500 a call) → one Nano Banana 2 or Seedream 5.0 Flash edit per frame (`frameEditParams`: a fixed seed on Nano Banana 2, while Seedream 5.0 Flash takes none; `planMixedFrames` gives each frame the one styled before it as a second picture, in lanes of 12 that start from the approved preview) → `images-to-video` in clips of up to 200 frames → `join-clips` at up to 2048 px (`frameJoinSize`; 4K frames are then drawn at 2K, `frameResolution`) → the cut's own sound; the limits are `FRAME_LIMITS`. Since round 5 part 1 (O9) the default on both engines is Fuobe Mixed Media (`MIXED_ORIGINAL`, `MIXED_FRAME_MODELS`: the Original first, then Nano Banana 2 and Seedream 5.0 Flash in the cloud), drawn frame by frame with no lanes (`originalFrameRequest`, `originalFrameParams`, `originalFrameSize`); `MIXED_MODES` adds Smooth on both engines (`planMixedSmooth`), and Fast stays cloud only (see Fuobe Originals) | `mixed-media.ts`: estimate (adds `mode`, `perFrameUsd`, the sampled `fps`, `providers`, `modelId`), render, preview; `cloudMode` takes `mode` or reads it from the model (a model of the other mode is a 422); since round 5 part 1 `mode: "smooth"`, `source.width` / `height` for the frame size, the look LoRAs a run can reach (civitai key, LoRA folder) with notes, and Smooth's 17-frame / 5 fps refusal before anything is paid for; `retryMixed` redoes only failed or canceled steps and what follows them (`createPipeline` `existing`, `unfilledRequest`) and cancels the old waiting ones; `framesProgress` names the frame that failed; no table (History is the feed: features `mixed-media`, `mixed-media-step`, `mixed-media-frame-step`, `mixed-media-preview`) | `/api/mixed-media[/preview \| /estimate \| /retry \| /progress?id=]` | `components/mixed-media/*` (the Restyle switch, Per frame or Fast, since round 5 part 1 also Smooth, and the price per frame) |
| **Image studios** (Color signature, Moodboards, Photodump, Fashion Factory, Character Sheet) | `catalog/palettes.ts` (`applySignature`, `SignatureRecord` in `request.signature`; since round 4 part 3 a Soul model locks the palette by default on the open engine, and curated moodboards are Fuobe Soul looks: see Fuobe Originals), `catalog/packs.ts` (photo-run planners with `PlanCaps`; since round 4 part 5 `PlanCaps` is only `has(id, engine)`, the packs and templates come from `studio-packs.generated.ts`, and `castSheetModel` makes Character Sheet's Soul Cast sheet on Fuobe Soul's cloud half in Cinema's casting look (Nano Banana Pro when that half is switched off; the Soul Cast sheet graph on the GPU); since round 4 part 4 Photodump and Fashion run a character with a Soul ID on Fuobe Soul with its trained LoRA on both engines, `PHOTODUMP_SOUL` and `soulIdOf`, else Nano Banana Pro, Seedream 5.0 Pro or Qwen-Image-Edit from the photos; since round 5 part 1 the cloud's default without a Soul ID is hosted Qwen-Image-Edit 2511, `PHOTO_EDIT`, and Fashion Factory's outfit is Fuobe Try-On with its photoset on Qwen edit, `FASHION_MODELS`, `fashionModel`, Nano Banana Pro and FASHN staying as cloud choices; Character Sheet's "From a description" draws on Fuobe Soul in the casting look). Since round 4 part 4 a moodboard trained as a style LoRA is a Fuobe look (`OWN_LOOK`, `own-style`: its LoRA, no look words) on Fuobe Soul and the Z-Image family on either engine (`palettes.ts`) | `palettes.ts` (seeded 50 palettes, lock chains; the lock keeps a Soul look's `presetStrength` and the `engine`), `moodboards.ts` (status derived from the cover job, Recraft style id, style LoRA; since round 4 part 4 `moodboardTrainingTargets` and `trainMoodboard`: a style element from up to 80 of the board's images, trained on the GPU or with fal's Z-Image style trainer), `photodump.ts` (runs as one `createPipeline` batch; `retryPhoto`, since round 4 part 5 through `currentRequest`, its chained step too; the character sheets, `sheetRequest`, which since round 5 part 1 draw the casting look on Fuobe Soul, or on the Soul Cast sheet graph with that look's words and LoRAs) | `/api/palettes[/id \| /lock]`, `/api/moodboards[/id[/retry \| /train]]` (since round 4 part 4 `GET …/train` lists the style targets with price, blocker and demo flag, and `POST` takes an optional `target`), `/api/photodump[/packs[/id] \| /character \| /fashion \| /retry]` (since round 5 part 1 `/fashion` takes an optional `modelId` for the photoset) | `components/{palettes,moodboards,photodump,fashion}/*`; k-means in `palettes/extract.worker.ts`; the chips load through `useSignature` in the composer; the curated sets are built in (`CURATED_SETS` in `moodboards/logic.ts`, drawn covers, nothing fetched from Higgsfield) and a curated card opens `/image?model=fuobe-soul&moodboard=curated:<id>`; since round 4 part 5 the empty Image studio's "Make your own Soul look" cards (`moodboards/soul-preset-cards.tsx`) show for Fuobe Soul and Soul HD, where they showed for Soul 2.0 |
| **AI Influencer builder** (`/influencer`; round 4 part 2) | `src/lib/influencer.ts`: the tiers (Average, Bold, Extreme, and six creature types with species and body colour), what each tier shows, pick rules and the two clashes (`togglePick`, `conflictFor`, `setTier`), seeded Shuffle with the researched weights and per-category locks (`shuffleInfluencer`), the prompt compiler (`compileSheetPrompt`, `compileCastPrompt`, `compileDressPrompt`), `faceOfRun` and `planInfluencer` per engine; the option data is generated (`catalog/influencer-options.generated.ts`) | `influencer.ts`: prices with Photodump's helpers (`planCaps`, `previewRun`, `runEngine`) and makes one job or a two-step `createPipeline`. Cloud: one sheet on Nano Banana Pro (16:9, 2K; the default until round 5 part 1) or Seedream 5.0 Pro, with the photo and clothing as references. Open: the Soul Cast sheet (`oss-zimage-soul-cast`); with a face, a reference or clothing, Qwen-Image-Edit 2511 (`oss-qwen-edit`) then takes the sheet as image 1, the photo and clothing after it (3 images at most), and the sheet becomes a helper step (`influencer-step`). No Higgsfield route. `retryPhoto` (`photodump.ts`) runs both steps again when the sheet failed, and re-chains a pass that never launched. Since round 5 part 1 (O10) the cloud default is Fuobe Soul: a 16:9 1080p sheet in the Realistic look (`INFLUENCER_LOOK`, `v1-realistic`), then hosted Qwen-Image-Edit 2511 adds the face, reference or clothing with no size sent, so the sheet keeps its shape; Nano Banana Pro and Seedream 5.0 Pro stay as choices and are the fallback, with a note, when Fuobe Soul or hosted Qwen edit is switched off. On the GPU the Soul Cast sheet carries that look's words and LoRAs | `POST /api/influencer` (`?preview=1` prices it; since round 5 part 1 also `POST /api/influencer/estimate`, the same price at the path the evaluation harness uses); retries through `POST /api/photodump/retry` | `components/influencer/*` (`influencer-builder.tsx`, `option-panel.tsx`); Save as character reuses `SaveCharacter` from `fashion/character-sheet.tsx` and reads the face from the run itself (`faceOfRun`); linked from Character Sheet, and from the AI Influencer app through `StudioConfig.related` |
-| **Marketing** (Marketing Studio, Click to Ad, Ads Studio, Ad Multiplier) | `catalog/marketing.ts`: 84 templates, 11 formats, 9 hooks, 14 settings, 10 ad styles, angles, word budgets, `formatModels` (since round 4 part 5 without Marketing Studio Image; since round 5 part 1 Fuobe Marketing Image first for every image format on both engines and the only one on the GPU, `MARKETING_IMAGE_MODEL`, with `wordsOnTop` saying when the browser sets the words), Ads Studio's picture models (`AD_VISUAL_MODELS`, `adVisualModel`, round 5 part 1), `UGC_MODELS`, `OPEN_SOUND_JOIN`; since round 4 part 5 the Ad Multiplier's `MULTIPLIER_MODELS` (cloud: Kling O3 edit by default, Happy Horse video edit and Gemini Omni Flash), `MULTIPLIER_WINDOW` (Kling O3 and Happy Horse recreate at most 15 s) and `mentionsFor` binding `@ImageN` for Happy Horse as for Kling; since round 4 part 2 the Click to Ad logo end card (`END_CARD`, `END_CARD_MODELS`, `endCardSteps`: cloud [`overlay-image`: the logo on the brand colour →] `ken-burns` → a silent track (`merge-audio-video`) → `join-clips` after the ad; open `oss-append-endcard`, or `oss-still-to-clip` + `oss-join-sound1` for an ad ComfyUI didn't encode) | `brand.ts` (website scrape, research job, `kitForSite`), `marketing.ts` (`planMarketing`, `planClickToAd`, `planMultiplier` with `referenceFacts` → RunPlan → `createPipeline`; since round 4 part 5 it cuts a longer selection to the edit model's window with a note, prices the edit by the clip's length and keeps the reference's sound (`KEEP_SOUND`: Kling's `keep_audio`, Happy Horse's `audio_setting` "origin"); since round 4 part 4 the Ad Multiplier's open recreation runs `fuobe-genjutsu-motion` pinned to the open engine; `marketing_runs` keeps the input for Run again and the browser composite; `withEndCard` turns the ad's last step into a helper and adds the card, with `adEncoder`, `cardBackground` and `silentWav`; since round 5 part 1 `onPlanEngine` pins every dual-engine step to the studio's engine in the estimate and the launch, `runsFor` makes a batch with words on top N one-picture runs, and a GPU Standalone shot of one photo is flagged `productShot`), `ads.ts` (batches, creatives, concepts, chat, proposals; since round 4 part 5 every ad is copy plus one visual composited in the browser: `BatchBody` has no `route` or `ratio`, the estimate no `route`, and an ad Higgsfield drew whole is `baked`, shown as it is and remade the Fuobe way on Retry; since round 5 part 1 `BatchBody` takes an optional `modelId` for the picture, and Retry reuses the batch's) | `/api/brands/**` (since round 4 part 5 `POST /api/brands/[id]/chat/confirm` takes `{messageId, engine}`), `/api/products/**`, `/api/marketing/**` (Click to Ad and its estimate take `endCard`; since round 5 part 1 `POST /api/marketing/runs/[id]/compose` serves cloud Fuobe Marketing Image runs too), `/api/ads/**` | `components/{marketing,ads,brand}/*` (since round 5 part 1 Ads Studio's cloud-only "Pictures by" select in `ads/new-ads.tsx`); ad layout math (`ads/layout.ts`) → canvas render with Google fonts (`ads/render.ts`) → stored zip (`ads/zip.ts`); @mention helpers (`ads/mention.ts`); the 9:16 end card drawn in the browser (`marketing/end-card.ts`) and uploaded once per look |
+| **Marketing** (Marketing Studio, Click to Ad, Ads Studio, Ad Multiplier) | `catalog/marketing.ts`: 84 templates, 11 formats, 9 hooks, 14 settings, 10 ad styles, angles, word budgets, `formatModels` (since round 4 part 5 without Marketing Studio Image; since round 5 part 1 Fuobe Marketing Image first for every image format on both engines and the only one on the GPU, `MARKETING_IMAGE_MODEL`, with `wordsOnTop` saying when the browser sets the words), Ads Studio's picture models (`AD_VISUAL_MODELS`, `adVisualModel`, round 5 part 1), `UGC_MODELS`, `OPEN_SOUND_JOIN`; since round 4 part 5 the Ad Multiplier's `MULTIPLIER_MODELS` (cloud: Kling O3 edit by default, Happy Horse video edit and Gemini Omni Flash), `MULTIPLIER_WINDOW` (Kling O3 and Happy Horse recreate at most 15 s) and `mentionsFor` binding `@ImageN` for Happy Horse as for Kling; since round 4 part 2 the Click to Ad logo end card (`END_CARD`, `END_CARD_MODELS`, `endCardSteps`: cloud [`overlay-image`: the logo on the brand colour →] `ken-burns` → a silent track (`merge-audio-video`) → `join-clips` after the ad; open `oss-append-endcard`, or `oss-still-to-clip` + `oss-join-sound1` for an ad ComfyUI didn't encode) | `brand.ts` (website scrape, research job, `kitForSite`), `marketing.ts` (`planMarketing`, `planClickToAd`, `planMultiplier` with `referenceFacts` → RunPlan → `createPipeline`; since round 4 part 5 it cuts a longer selection to the edit model's window with a note, prices the edit by the clip's length and keeps the reference's sound (`KEEP_SOUND`: Kling's `keep_audio`, Happy Horse's `audio_setting` "origin"); since round 4 part 4 the Ad Multiplier's open recreation runs `fuobe-genjutsu-motion` pinned to the open engine; `marketing_runs` keeps the input for Run again and the browser composite; `withEndCard` turns the ad's last step into a helper and adds the card, with `adEncoder`, `cardBackground` and `silentWav`; since round 5 part 1 `onPlanEngine` pins every dual-engine step to the studio's engine in the estimate and the launch, `runsFor` makes a batch with words on top N one-picture runs, and a GPU Standalone shot of one photo is flagged `productShot`), `ads.ts` (batches, creatives, concepts, chat, proposals; since round 4 part 5 every ad is copy plus one visual composited in the browser: `BatchBody` has no `route` or `ratio`, the estimate no `route`, and an ad Higgsfield drew whole is `baked`, shown as it is and remade the Fuobe way on Retry; since round 5 part 1 `BatchBody` takes an optional `modelId` for the picture, and Retry reuses the batch's) | `/api/brands/**` (since round 4 part 5 `POST /api/brands/[id]/chat/confirm` takes `{messageId, engine}`), `/api/products/**`, `/api/marketing/**` (Click to Ad and its estimate take `endCard`; since round 5 part 1 `POST /api/marketing/runs/[id]/compose` serves cloud Fuobe Marketing Image runs too), `/api/ads/**` | `components/{marketing,ads,brand}/*` (since round 5 part 1 Ads Studio's cloud-only "Pictures by" select in `ads/new-ads.tsx`); ad layout math (`ads/layout.ts`) → canvas render with Google fonts (`ads/render.ts`) → stored zip (`ads/zip.ts`); @mention helpers (`ads/mention.ts`); the 9:16 end card drawn in the browser (`marketing/end-card.ts`) and uploaded once per look; the animated end card (Kinetic Motion: five styles in `src/lib/motion/scenes/end-card/`, drawn and encoded in the browser by `src/components/motion/`, `marketing/end-card-motion.tsx`) sent as `endCard.clip`, which replaces the still and its push-in (cloud: its silent track, then `join-clips`; open: one `oss-join-sound1` with the ad first) |
| **Faceless Studio / Explainer** (`/faceless`, `/explainer`) | `catalog/faceless.ts`: genres, 22 styles (12 for Faceless), block planning, `buildEpisodeGraph` (steps keyed still / clip / join / narration / music / mix / words / captions), `planRerun`, `planRetry`, `estimateGraph`, `spokenTimes`, `sceneTiming`, `musicLength`, `styleRefLimit`. Round 4: Frame by frame is a Ken Burns move per scene, not a video model (`ENGINE_MODELS.kenBurns`: the cloud's `ken-burns` zooms only, the open `oss-ken-burns` pans and zooms and splits scenes over 10 s; the moves come from the scene's words, `sceneMoves` in `src/lib/av/ken-burns.ts`), joined with `framesJoin` (`oss-join-encoded` on the open engine); `musicPlan` adds a `music-loop` step when the film outlasts the music (open `oss-audio-loop` crossfades up to 600 s, the cloud's `join-audio` repeats whole plays); `staleSteps` / `bedFits` redo kept steps whose model, operation, clip length or music bed no longer fits; the open `upscale` is `oss-upscale-video-esrgan`. Since round 4 part 2 a channel's `settings.brief` (`BriefLook`, from Content Factory) adds look, camera and music words to the prompts, sets the scene length and the captions' words and position | `faceless.ts`: channels (avatar job), episodes, scripts written in the background by the llm provider (`askLlm`), `launch()` (stage one: stills, narration, word timings) and `advance()` (scenes cut to the spoken times, then clips, joins, music, mix, subtitles), `settle()`, `ensureFacelessRunner()` (2 s sweep, started at boot); a Motion change that reads as the scene's current camera move answers 422 (`sameCameraMove`); `readDocument()` for PDF and Word sources | `/api/faceless/**`, `/api/explainer[/link \| /document]` | `components/{faceless,explainer}/*` |
| **Content Factory** (`/content-factory`, `/content-factory/[id]`; round 4 part 2) | `catalog/content-factory.ts`: the style brief (`StyleBrief`: format, hook, pacing, shots, look, animation, voice, music, captions, topics; `parseBrief` reads an LLM's answer, `offlineBrief` makes one from the clip's shape, length and speech rate), 8 preset styles, 4 animation styles, lengths 30 s to 5 min, up to 10 episodes, the link guard (`referenceLink`: TikTok, Instagram, a direct clip or a web page; YouTube asks for an upload; `pageMedia` finds a page's og:video or `<video>`), episode titles (`parseSeries`, `offlineSeries`), prices (`seriesPrice`, `briefCostUsd`) and the Generate in Claude message (`claudePlan`, `claudeMessage`, `mcpCommand`) | `content-factory.ts`: a series is a `content_series` row whose episodes are ordinary Faceless episodes in a channel of its own (`createChannel` with the brief in its settings, then `createEpisode` per title; nothing is forked). Reading a reference: cloud = `extract-frames` (about a frame a second, JPEG) and Scribe v2 as generations, then `llmText` writes the brief from up to 20 frames (`fitFrames` keeps them within 15 MB) and the transcript; open = one `oss-reference-brief` job (Gemma 4 E4B, the first 30 s). A link is fetched through `fetchRemote`. The brief is written in this process when the series is next read (`seriesView`), and Generate / Next episode hold a one-process claim, so repeated clicks make one series | `/api/content-factory/series[/id[/generate \| /episodes \| /read]]`, `/api/content-factory/{estimate,claude}`; `POST /api/faceless/episodes` takes 30–300 s on a channel whose settings carry a brief | `components/content-factory/*` (`home.tsx`, `series-view.tsx`, `parts.tsx`, `hooks.ts`); the series page is a record page with a real 404 (`series` in `record-pages.ts` / `records.ts`) |
| **Image to 3D** (`/image-to-3d`; round 4 part 3: five modes and Rig & animate) | `lib/av/model3d.ts`: the modes (From an image, From several images, From text, Pick an object, Splat: `MODEL3D_MODES`), the models per mode and engine, the default first (`MODELS_3D`; From an image opens on Pixal3D, `oss-pixal3d` on `image-to-3d-pixal3d`, with TRELLIS.2 as the fallback; Pick an object has no open model, rigging is Meshy on fal only), the sides of a multi-view model (`VIEW_SIDES`: the front is needed; left and right are the object's own), `model3dBlocker`, `model3dRequest` (the sides go in `params.extra.views`), `viewerGlb` (the web GLB when there is one), `stillPromptFor3d`, what a card shows (`model3dView`, `splatFormatOf`, `stillOf`: the still a text-to-3D model was built from), `CLOUD_NOTICES` ("Built with DINOv3" for TripoSplat and TRELLIS.2 on fal too), 30 curated Meshy animations in 6 groups (`ANIMATION_PRESETS`; the dialog starts on Casual walk, and any id up to 696 can be typed) and `rigRequest` | ordinary generations; the open text route is `createStillTo3d` (see Pipelines); the extra formats and previews are stored (`persistArtifacts`). `src/server/model3d-finish.ts` finishes the first GLB of an open image-to-3D job in two steps, each a child process: `finishModel` before the job succeeds (`scripts/model3d/finish-glb.mjs` with glTF Transform, meshoptimizer and sharp: a roughness floor by material read from the metallic channel, the pivot at the bottom centre, meshopt geometry and WebP textures at 2048, in `meta.web`; the raw GLB stays the download), then `startTurntable` after it (`scripts/model3d/render-turntable.mjs`: `<model-viewer>` in headless Chromium on SwiftShader, CPU only, 96 frames at 24 fps on a studio backdrop, encoded by ffmpeg, plus a poster), one at a time at below-normal priority; `meta.finish.turntable` is queued, rendering (with progress), done, skipped (no Chromium or ffmpeg: the page records one in the browser) or failed, and a restart picks up the queued ones. A failure keeps what was made | `POST /api/generations` (and `?preview=1` for the price line before a run); `?mode=` and `?model=` pick the mode and model (⌘K opens every 3D model and Meshy Rigging here) | `app/(studio)/image-to-3d/page.tsx` (an async server component: each open model's licence line, read from the manifest in a `"use cache"` function), `components/model3d/*`: `model3d-studio.tsx` (the mode radio group, the side slots, the price), `model-card.tsx` (cards play the turntable and never load a GLB; a splat shows its orbit video or cut-out and a .spz / .ply download, since Fuobe doesn't draw splats; a rigged model plays its animation), `model-viewer.ts` (the viewer's setup: the same-origin meshopt decoder `public/vendor/meshopt_decoder.js`), `turntable.ts` and `webm.ts` (the browser's own turntable when the server can't: 96 frames at 24 fps through WebCodecs), `rig-dialog.tsx`, `hooks.ts`. The Library viewer (`ModelViewer` in `result-media.tsx`) never loads model-viewer for a splat |
@@ -402,6 +402,10 @@ Each studio keeps its data and pure planner in `src/lib/`, its server module in
| **Storyboard** (`/storyboard`; Popcorn looks and prices since round 5 part 1, O13) | `catalog/storyboard.ts` (above: `planStoryboard`, `STORYBOARD_MODELS`, `STORYBOARD_PARTNERS`, the look and the 21:9 crop); `src/lib/storyboard-board.ts` (`filmReady`: "Make the film" waits until the browser has graded and cropped a look board's frames, or gave up, `finishGaveUp` in `soul-finish.ts`) | `storyboard.ts`: `StoryboardBodySchema` (shared by the run and its estimate: `look`, `lookStrength`, `partner`), `estimateStoryboard` (each frame priced on its own model, which Assist's `create_storyboard` now uses too), the film's shape from `frame.crop`; `pollOne` writes the look's finish meta on every frame (see Structured outputs) | `POST /api/storyboards` (`look`, `lookStrength`, `partner: "nano-banana-pro"`), `POST /api/storyboards/estimate` (`{costUsd, demo, frames, models}`) | `storyboard-view.tsx`: the Look chip with a "No look" state (`look-chip.tsx`'s `none`), the price and frame count next to Generate (disabled while the estimate errs), and in the cloud a "Frames made on" choice of Fuobe or Nano Banana Pro. A 4-frame cloud board is priced under $0.20 in the tests (Nano Banana Pro: about $0.60) |
| **Assist** (`/assist`, `/assist/skills`, `/assist/memory`, `/assist/projects/[id]`, since round 4 part 4 `/assist/scheduled`) | `lib/assist.ts`: SKILL.md parsing (`parseSkillMd`, `toSkillMd`; since round 4 the Agent Skills frontmatter, with Fuobe's own fields under `metadata`, and the old layout still read), slash helpers, modes, `planRunnable`, `ASSIST_SUGGESTIONS`; `lib/assist-studios.ts` (a studio call's words → a Shorts preset, a Faceless style, a dub language); since round 4 part 4 `lib/assist-schedule.ts` (rules, time zones, the cap) and `lib/assist-connectors.ts` (URL checks and masking); since round 5 part 1 `lib/recipe.ts` and `lib/recipe-builder.ts` (see Skills that run by themselves) and `memoryCardLine` (a "Remember this?" card says "Saves to memory for future chats" while it asks, "Saved…" once approved, "Not saved to memory" after Not now; before, it said "Saved" while it still asked) | `server/skills.ts` (built-ins from `skills/` or `FUOBE_SKILLS_DIR`, user skills and toggles in SQLite, `.md` / `.zip` / `.skill` import via `assist/unzip.ts`; since round 5 part 1 `skillRecipe`, `setSkillFile`, `skillFiles` for the .zip download, `verified` stripped from an imported recipe, and "draft" a reserved name), since round 5 part 1 `recipes.ts`, `recipe-builder.ts` and `recipe-routes.ts`, `assist/projects.ts` (sources fetched safely; PDFs read by `assist/pdf.ts` with unpdf), `assist/docx.ts` (Word text, used by the Explainer), `assist/memory.ts`, `assist/context.ts`, `assist/studio-tools.ts`, `assist/studio-routes.ts` (the studio tools' adapters, below); since round 4 part 4 `assist/schedules.ts` and `assist/connectors.ts` (see Assist agent) | `/api/assist/**`; since round 4 part 4 `/api/assist/schedules[/scheduleId[/run]]` and `/api/assist/connectors[/connectorId]`; since round 5 part 1 `/api/assist/skills/[name]/{recipe,estimate,run,verify}`, `…/download?format=zip` and `/api/assist/skills/draft[/check \| /name \| /save]` | `components/assist/*`, `assist-view.tsx` (since round 5 part 1 `run-skill-dialog.tsx`, the "Runs by itself" chip and checks in `skills-view.tsx`, and `plan-jobs.tsx`, the approval card's job list shared with the Run form), `components/skills/*` (the skill builder); "Open in <Studio>" cards for studio jobs; since round 4 part 4 `schedule-dialog.tsx` (from a chat's Schedule button), `scheduled-view.tsx` (the Scheduled page and each project's Scheduled tab), `connectors-settings.tsx` (Settings → Assist · connectors) and connector tool calls in the transcript |
+## Kinetic Motion (`src/lib/motion/`, `src/components/motion/`)
+
+Motion graphics drawn by code, in the brand's own fonts and colours, with the words exactly as typed. A **scene** is a pure function of a **recipe** (JSON: scene, seed, size, fps, length, the typed fields, the brand, the person's own files, control values, export settings) and an absolute time: `scene.plan(input)` lays the text out once (`layout.ts`: balanced lines, never cut, never re-cased, never split mid-word; a field that doesn't fit is reported as `overflow` and blocks the render) and builds a timeline of cues (`tween.ts`, on the named curves in `ease.ts`: Bézier, closed-form springs), and `plan.evaluate(t)` gives a display list (`display.ts`: groups with transforms, clips, masks and blends; rects, ellipses, paths with stroke trim, text runs, images) in design units (1080 on the short side, `sizes.ts`). Randomness is a hash of the seed and a key (`random.ts`); there is no clock, DOM or `Math.random` in `src/lib/motion`, so any frame can be seeked in any order (`tests/motion-scenes.test.ts`). `camera2d.ts` is a 2.5D camera with parallax by depth. The browser half: `draw.ts` (`drawDisplayList`, the only code that draws a list, and SVG logo outlines read with the browser's SVG engine), `fonts.ts` (an export waits for the brand font or stops), `player.tsx` (the live preview: absolute time on animation frames, pauses off screen or in a hidden tab, rest frame for reduced motion, a smaller backing store on slow devices), `render.ts` (`renderClip`: frame i at i / fps, motion blur from shutter samples never across a cut, as many per frame as its fastest edge needs (`listTravel` in `display.ts`: one for a frame that barely moves, up to 48), WebCodecs H.264 MP4 from the canvas itself, else VP8 WebM, else the recorder) and `save.ts` (`saveMotionResult`: `POST /api/uploads`, then `POST /api/generations/local` with model `local-motion`, op `motion` and the recipe in `params.extra.motion`; nothing is downloaded from the page). Phase 1 ships the end card's five styles (`scenes/end-card/`: Draw-on, Rise, Iris, Split, Glint), whose rest frame is the still card's own layout (`planEndCard` and `renderEndCard` use the same `endCardRest` and drawer). The rest layout sizes type from the frame's short side, keeps a tall card's bottom fifth clear, and sets the words and pill in the kit colour that reads best on the brand colour (`cardColours`). Each style opens a few frames into its motion (`lead`), is readable by about 0.9 s of a 2.5 s card (`settled`), then a slow push-in (`CAMERA_FROM`, the `drift` curve) comes home on the last frame (`rest`, the poster); `signature` is the frame the style chooser shows. A saved clip carries its poster in `output.meta.poster`. Click to Ad joins the rendered card after the ad: in the cloud with its silent track and `merge-videos`, on the open engine with `oss-join-sound1`, which re-encodes the ad at 25 fps (the still card's `oss-append-endcard` copies the ad's picture instead); the open path has not yet been run end to end on a GPU.
+
## ComfyUI workflow library (`workflows/comfyui/`, `scripts/comfy/`)
`manifest.json` lists 158 workflows, 153 of them `validated: true` (the five H3 graphs of round 4 parts 4 and 5 are `validated: false`, below), each with its **bindings** (canonical key → node id + input), outputs (with `stem` and `role`), defaults, limits, required model files with download URLs and sizes, custom node packs, VRAM, licence, notes, `autoDownloads`, and since round 3 `expand` (`captions` or `timeline`: the provider rewrites the graph per request) and `worker: "isolated"`. Round 4 adds `expand: "videos"` / `"audios"` (joins, one loader per clip), model files marked `optional` (FILM beside RIFE; the Workflows page leaves them out of the missing count), and output roles `scene`, `depth`, `mask`, `cutout`, `matte`, `preview`, `frames`, `frame`, `lines`, `splat` and `brief` (the graphs with `frame`, `lines` and `brief` got their models in round 4 part 2, for Layers' OCR and Content Factory, and the `splat` graph in round 4 part 3, for Image to 3D; round 4 part 5 adds `master`, Character Swap Studio's lossless take, and round 5 part 2 `report`, a node's own account of the run, with the stems `music` and `effects`). The pipeline in `scripts/comfy/` exports the official templates through the real ComfyUI frontend (`app.graphToPrompt()`), applies documented transforms (`library.spec.mjs`, `lib/graph.mjs`), builds hand-written API graphs from `hand-built/*.json`, and validates every graph with `POST /prompt` against a live ComfyUI using zero-byte placeholder models.
diff --git a/docs/public-signup.md b/docs/public-signup.md
index ce41e779..e8cb6076 100644
--- a/docs/public-signup.md
+++ b/docs/public-signup.md
@@ -84,6 +84,20 @@ An account is signed in, but it sees the owner's studio as a guest does:
back at once. The live-updates stream isn't sent to accounts: their studios poll instead.
- **Its own uploads are its own.** Only the account that uploaded a file can use it in a run, and
no other account can open it. See [Uploads](#uploads).
+- **Results made in the browser (Kinetic Motion) are its own runs too.** A motion clip rendered in
+ the page (an animated end card, a text template) is saved with an upload and
+ `POST /api/generations/local` (`op: "motion"`, model `local-motion`). It needs the same own GPU or
+ own key as any upload, and counts as the account's own runs and files: the clip and every file it
+ names (its pictures, and the recipe's logo, product and pictures) must be the account's own (403
+ otherwise), a clip is never made from a video (400), the stored file must be the MP4 or WebM it
+ claims to be (400), and it shares the account's hourly run budget (60 an hour with its other runs,
+ 429). The words drawn on the clip (the recipe's fields and brand name) and its title go through the
+ studio's checks when they are on, whatever the page sends as the prompt, and are what the run keeps
+ (a refusal answers 422; a result the checks want to see waits for them). It shows in the account's
+ own runs, never the owner's Library. Nothing
+ is downloaded straight from the page: the clip is downloaded from the saved result. A guest's
+ call answers 401 with the sign-up card. Colour grades and Relight blends stay the owner's
+ (403, `code: "library"`).
## Managing accounts
diff --git a/src/app/api/generations/local/route.ts b/src/app/api/generations/local/route.ts
index 0de5f7ef..0bed9afa 100644
--- a/src/app/api/generations/local/route.ts
+++ b/src/app/api/generations/local/route.ts
@@ -1,24 +1,154 @@
import { z } from "zod";
-import { recordLocalGeneration } from "@/server/generations";
-
-const Body = z.object({
- feature: z.string().min(1).max(80),
- modelId: z.string().min(1),
- op: z.enum(["grade", "relight"]),
- prompt: z.string().max(2000),
- title: z.string().max(200).optional(),
- inputs: z.object({ images: z.array(z.string()).max(1).optional(), video: z.string().optional() }),
- params: z.object({ extra: z.record(z.string(), z.unknown()).optional() }).optional(),
- output: z.object({ url: z.string().startsWith("/api/files/").max(500), kind: z.enum(["image", "video"]), contentType: z.string().optional() }),
-});
-
-/** Record a result rendered in the browser (a colour grade, a Relight blend) so it shows up in the library. */
+import { LIBRARY_MESSAGE } from "@/lib/guest-access";
+import { RECIPE_MAX_BYTES, RecipeSchema } from "@/lib/motion/recipe";
+import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, diskHasRoom } from "@/server/account-files";
+import { fileAccount } from "@/server/account-library";
+import { accountInputProblem } from "@/server/account-inputs";
+import { requestViewer } from "@/server/auth";
+import { getGeneration, recordLocalGeneration } from "@/server/generations";
+import { moderateRun } from "@/server/hosted-run";
+import { holdForCheck } from "@/server/output-checks";
+import { hit, unhit } from "@/server/rate";
+import { db } from "@/server/db";
+import { contentTypeFor, filesRel } from "@/server/storage";
+import { runAsTenant } from "@/server/tenant";
+
+const Body = z
+ .object({
+ feature: z.string().min(1).max(80),
+ modelId: z.string().min(1),
+ op: z.enum(["grade", "relight", "motion"]),
+ prompt: z.string().max(2000),
+ title: z.string().max(200).optional(),
+ inputs: z.object({ images: z.array(z.string().max(500)).max(4).optional(), video: z.string().max(500).optional() }),
+ params: z.object({ extra: z.record(z.string(), z.unknown()).optional() }).optional(),
+ output: z.object({
+ url: z.string().startsWith("/api/files/").max(500),
+ kind: z.enum(["image", "video"]),
+ contentType: z.string().optional(),
+ /** A clip's poster (its last frame), shown on its tile. */
+ meta: z.object({ poster: z.string().startsWith("/api/files/").max(500) }).strict().optional(),
+ }),
+ })
+ .superRefine((b, ctx) => {
+ // A grade or a Relight blend is made from one picture; a motion clip from its logo and product (up to 4).
+ if (b.op !== "motion" && (b.inputs.images?.length ?? 0) > 1) ctx.addIssue({ code: "custom", path: ["inputs", "images"], message: "One picture" });
+ if (b.op === "motion") {
+ const recipe = b.params?.extra?.motion;
+ if (!recipe || typeof recipe !== "object" || Array.isArray(recipe)) ctx.addIssue({ code: "custom", path: ["params", "extra", "motion"], message: "The recipe" });
+ else if (JSON.stringify(recipe).length > RECIPE_MAX_BYTES) ctx.addIssue({ code: "custom", path: ["params", "extra", "motion"], message: "The recipe is too big" });
+ else if (!RecipeSchema.safeParse(recipe).success) ctx.addIssue({ code: "custom", path: ["params", "extra", "motion"], message: "The recipe" });
+ if (b.output.kind !== "video" || !/^video\/(mp4|webm)$/.test(b.output.contentType ?? "")) ctx.addIssue({ code: "custom", path: ["output"], message: "An MP4 or WebM clip" });
+ // A clip is made from pictures (its logo, its product): never from a video.
+ if (b.inputs.video) ctx.addIssue({ code: "custom", path: ["inputs", "video"], message: "No video" });
+ }
+ });
+
+const NOT_FOUND = "We can't find that.";
+const refuse = (status: number, error: string, extra: Record<string, unknown> = {}) => Response.json({ error, ...extra }, { status, headers: { "Cache-Control": "no-store" } });
+
+/** The asset behind a stored file's address, for the output check. */
+function assetIdOf(url: string): string | undefined {
+ const rel = filesRel(url);
+ if (!rel) return undefined;
+ const native = rel.split("/").join(process.platform === "win32" ? "\\" : "/");
+ return (db().prepare("SELECT id FROM assets WHERE rel_path IN (?, ?) LIMIT 1").get(rel, native) as { id: string } | undefined)?.id;
+}
+
+/** The stored file's own type differs from what the result says it is (a picture is never recorded as a clip). */
+function typeProblem(rel: string, output: { kind: string; contentType?: string }, op: string): boolean {
+ const stored = contentTypeFor(rel);
+ if (!stored.startsWith(`${output.kind}/`)) return true;
+ if (output.contentType && output.contentType.split(";")[0].trim().toLowerCase() !== stored) return true;
+ return op === "motion" && !/^video\/(mp4|webm)$/.test(stored);
+}
+
+/** The files a motion recipe names: its logo when it is stored here, its product and its pictures. */
+function recipeFiles(extra: Record<string, unknown> | undefined): Record<string, string | string[]> {
+ const r = RecipeSchema.safeParse(extra?.motion);
+ if (!r.success) return {};
+ const out: Record<string, string | string[]> = {};
+ // A stored logo is checked as a file; the kit's own link is only kept (the server never fetches it for an account).
+ // (" /api/files/…" is no stored file's path: it is checked, and refused, as written.)
+ const logo = r.data.brand.logo;
+ if (logo?.includes("/api/files/")) out._logo = logo;
+ if (r.data.media?.product) out._product = r.data.media.product;
+ if (r.data.media?.images?.length) out._media = r.data.media.images;
+ return out;
+}
+
+/** The words a motion clip shows (its typed fields and the brand's name) and its title: what the studio's checks read. */
+function shownWords(extra: Record<string, unknown> | undefined, title: string | undefined): string {
+ const r = RecipeSchema.safeParse(extra?.motion);
+ const words = r.success ? [...Object.values(r.data.fields), r.data.brand.name] : [];
+ return [...new Set([...words, title ?? ""].map((w) => w.trim()).filter(Boolean))].join(" · ").slice(0, 2000);
+}
+
+/**
+ * Record a result rendered in the browser (a colour grade, a Relight blend, a Kinetic Motion clip) so it shows up in the
+ * library. The owner records their own files. An account (public sign-up) records Kinetic Motion clips only, each from
+ * files it uploaded itself: the result is its own run (its own list, never the owner's Library), counted with its runs,
+ * and through the studio's checks when they are on.
+ */
export async function POST(request: Request) {
+ const viewer = requestViewer(request);
+ if (viewer.kind === "guest") return refuse(401, "Create a free account to run this.");
const parsed = Body.safeParse(await request.json().catch(() => null));
- if (!parsed.success) return Response.json({ error: "Invalid result" }, { status: 400 });
+ if (!parsed.success) return refuse(400, "Invalid result");
+ const body = parsed.data;
+ const rel = filesRel(body.output.url);
+ if (rel === null) return refuse(403, NOT_FOUND);
+ if (typeProblem(rel, body.output, body.op)) return refuse(400, "Invalid result");
+ const poster = body.output.meta?.poster;
+ if (poster && (body.output.kind !== "video" || !contentTypeFor(filesRel(poster) ?? "").startsWith("image/"))) return refuse(400, "Invalid result");
+
+ if (viewer.kind === "owner") {
+ // The owner's own files only: never an account's file recorded as the owner's result.
+ const named = Object.values(recipeFiles(body.params?.extra)).flat();
+ const refs = [body.output.url, ...(poster ? [poster] : []), ...(body.inputs.images ?? []), ...(body.inputs.video ? [body.inputs.video] : []), ...named].filter((r) => r.startsWith("/api/files/"));
+ for (const ref of refs) {
+ const r = filesRel(ref);
+ if (r === null || typeof fileAccount(r) === "string") return refuse(403, NOT_FOUND);
+ }
+ try {
+ return Response.json(recordLocalGeneration(body), { status: 201 });
+ } catch (e) {
+ return refuse(422, (e as Error).message);
+ }
+ }
+
+ const account = viewer.account;
+ // Accounts have their own runs, not the owner's Library: only Kinetic Motion results, recorded as their runs.
+ if (body.op !== "motion") return refuse(403, LIBRARY_MESSAGE, { code: "library" });
+ if (fileAccount(rel) !== account.id) return refuse(403, NOT_FOUND);
+ // Every file the clip names is the account's own: its inputs, its poster, and the recipe's logo, product and pictures.
+ const problem = accountInputProblem({ inputs: body.inputs, params: { extra: { ...recipeFiles(body.params?.extra), ...(poster && { _poster: poster }) } } }, account.id);
+ if (problem) return refuse(problem.status === 404 ? 403 : problem.status, problem.status === 404 || problem.code === "input-not-yours" ? NOT_FOUND : problem.error, { code: problem.code });
+ if (!diskHasRoom()) return refuse(503, ACCOUNT_MESSAGES.diskLow);
+ // A saved clip is one of the account's runs: the same hourly budget.
+ const bucket = `run:${account.id}`;
+ const rate = hit(bucket, ACCOUNT_LIMITS.runsPerHour, 60 * 60_000);
+ if (!rate.ok) return Response.json({ error: ACCOUNT_MESSAGES.runRate }, { status: 429, headers: { "Retry-After": String(rate.retryAfterS), "Cache-Control": "no-store" } });
+ // The words drawn on the clip and its title (never the page's own summary of them) go through the studio's checks,
+ // and are what the run keeps.
+ const prompt = shownWords(body.params?.extra, body.title);
+ const place = account.gpu ? ("own-gpu" as const) : account.keys?.fal || account.keys?.replicate ? ("own-key" as const) : ("pool" as const);
+ const checked = await moderateRun(account, { feature: body.feature, modelId: body.modelId, op: body.op, prompt, inputs: body.inputs }, null, "own", { kind: "video", place });
+ if (!checked.ok) {
+ unhit(bucket);
+ return refuse(422, checked.refusal.body.error, { code: checked.refusal.body.code });
+ }
try {
- return Response.json(recordLocalGeneration(parsed.data), { status: 201 });
+ const g = runAsTenant({ kind: "account", id: account.id }, () => recordLocalGeneration({ ...body, prompt }));
+ if (checked.checkOutputs) {
+ // Held until the output check answers, as any account run's files are.
+ const assetId = assetIdOf(body.output.url);
+ holdForCheck(g.id, [{ ...body.output, ...(assetId && { assetId }) }]);
+ return Response.json(getGeneration(g.id) ?? g, { status: 201 });
+ }
+ return Response.json(g, { status: 201 });
} catch (e) {
- return Response.json({ error: (e as Error).message }, { status: 422 });
+ unhit(bucket);
+ return refuse(422, (e as Error).message);
}
}
diff --git a/src/components/cinema/video-encode.ts b/src/components/cinema/video-encode.ts
index 59f2a6ba..089d5482 100644
--- a/src/components/cinema/video-encode.ts
+++ b/src/components/cinema/video-encode.ts
@@ -15,7 +15,60 @@ export function pathVideoType(): string | null {
return ["video/mp4;codecs=avc1.42E01E", "video/mp4", "video/webm;codecs=vp9", "video/webm;codecs=vp8", "video/webm"].find((t) => MediaRecorder.isTypeSupported(t)) ?? null;
}
-const VP8 = (width: number, height: number, fps: number): VideoEncoderConfig => ({ codec: "vp8", width, height, bitrate: 8_000_000, framerate: fps });
+const VP8 = (width: number, height: number, fps: number, bitrate = 8_000_000): VideoEncoderConfig => ({ codec: "vp8", width, height, bitrate, framerate: fps });
+
+/**
+ * A frame to encode: RGBA pixels, or a canvas (or any image source) handed to the encoder as it is, which spares a
+ * copy of every frame (about 8 MB at 1080 × 1920).
+ */
+export type FrameSource = ImageData | CanvasImageSource;
+
+/** Options for a render: the bit rate (8 Mbps by default) and a way to stop it. */
+export interface EncodeOptions {
+ bitrate?: number;
+ signal?: AbortSignal;
+}
+
+const isPixels = (f: FrameSource): f is ImageData => typeof ImageData !== "undefined" && f instanceof ImageData;
+
+function videoFrame(src: FrameSource, width: number, height: number, timestamp: number, duration: number): VideoFrame {
+ if (isPixels(src)) return new VideoFrame(src.data, { format: "RGBA", codedWidth: width, codedHeight: height, timestamp, duration });
+ return new VideoFrame(src as CanvasImageSource, { timestamp, duration, alpha: "discard" });
+}
+
+/** Lets the page breathe between frames without a timer (timers slow to a crawl in a hidden tab; messages don't). */
+export function breathe(): Promise<void> {
+ if (typeof MessageChannel === "undefined") return new Promise((r) => setTimeout(r, 0));
+ return new Promise((resolve) => {
+ const ch = new MessageChannel();
+ ch.port1.onmessage = () => {
+ ch.port1.close();
+ resolve();
+ };
+ ch.port2.postMessage(null);
+ });
+}
+
+/** Waits until the encoder holds at most `max` frames (its dequeue event, else short polls). */
+async function drain(e: VideoEncoder, max: number): Promise<void> {
+ while (e.encodeQueueSize > max) {
+ await new Promise<void>((resolve) => {
+ let done = false;
+ const finish = () => {
+ if (done) return;
+ done = true;
+ e.removeEventListener?.("dequeue", finish);
+ resolve();
+ };
+ e.addEventListener?.("dequeue", finish);
+ setTimeout(finish, 20);
+ });
+ }
+}
+
+const stopIfAsked = (signal?: AbortSignal) => {
+ if (signal?.aborted) throw signal.reason instanceof Error ? signal.reason : new DOMException("The render was stopped", "AbortError");
+};
/** WebCodecs can encode VP8 at this size here. */
export async function vp8Supported(width: number, height: number, fps: number): Promise<boolean> {
@@ -31,7 +84,7 @@ export async function vp8Supported(width: number, height: number, fps: number):
* `count` frames of two streams (`draw(i)` gives frame i of each) encoded with WebCodecs and written as two WebM files:
* every frame kept, frame i at i / fps, a keyframe each second.
*/
-export async function encodeVp8(count: number, width: number, height: number, fps: number, outputs: number, draw: (i: number) => ImageData[]): Promise<Uint8Array[]> {
+export async function encodeVp8(count: number, width: number, height: number, fps: number, outputs: number, draw: (i: number) => FrameSource[] | Promise<FrameSource[]>, opts: EncodeOptions = {}): Promise<Uint8Array[]> {
const chunks: EncodedFrame[][] = Array.from({ length: outputs }, () => []);
let failure: unknown;
const encoders = chunks.map((_, k) => {
@@ -43,22 +96,23 @@ export async function encodeVp8(count: number, width: number, height: number, fp
},
error: (err) => (failure = err),
});
- e.configure(VP8(width, height, fps));
+ e.configure(VP8(width, height, fps, opts.bitrate));
return e;
});
try {
const step = 1e6 / fps;
for (let i = 0; i < count; i++) {
- const images = draw(i);
+ stopIfAsked(opts.signal);
+ const images = await draw(i);
images.forEach((img, k) => {
- const f = new VideoFrame(img.data, { format: "RGBA", codedWidth: width, codedHeight: height, timestamp: Math.round(i * step), duration: Math.round(step) });
+ const f = videoFrame(img, width, height, Math.round(i * step), Math.round(step));
encoders[k].encode(f, { keyFrame: i % Math.max(1, Math.round(fps)) === 0 });
f.close();
});
if (failure) throw failure;
// Let the encoders and the page breathe (the progress label repaints).
- while (encoders.some((e) => e.encodeQueueSize > 4)) await new Promise((r) => setTimeout(r, 5));
- if (i % 4 === 3) await new Promise((r) => setTimeout(r, 0));
+ for (const e of encoders) await drain(e, 4);
+ if (i % 4 === 3) await breathe();
}
await Promise.all(encoders.map((e) => e.flush()));
if (failure) throw failure;
@@ -105,21 +159,24 @@ export async function recordWithMediaRecorder(type: string, count: number, width
/** The H.264 profiles tried in order (baseline 3.1 holds 1280 × 720 at 30 fps; main and high 4.0 more). */
const AVC_CODECS = ["avc1.42001f", "avc1.4d0028", "avc1.640028"];
-const AVC = (codec: string, width: number, height: number, fps: number): VideoEncoderConfig => ({ codec, width, height, bitrate: 8_000_000, framerate: fps, avc: { format: "avc" } });
+const AVC = (codec: string, width: number, height: number, fps: number, bitrate = 8_000_000): VideoEncoderConfig => ({ codec, width, height, bitrate, framerate: fps, avc: { format: "avc" } });
/** The H.264 profile WebCodecs encodes at this size here, or null (Chromium without proprietary codecs, Firefox). */
-export async function avcCodec(width: number, height: number, fps: number): Promise<string | null> {
+export async function avcCodec(width: number, height: number, fps: number, bitrate?: number): Promise<string | null> {
if (typeof VideoEncoder === "undefined" || typeof VideoFrame === "undefined") return null;
for (const c of AVC_CODECS) {
try {
- if ((await VideoEncoder.isConfigSupported(AVC(c, width, height, fps))).supported) return c;
+ if ((await VideoEncoder.isConfigSupported(AVC(c, width, height, fps, bitrate))).supported) return c;
} catch {}
}
return null;
}
-/** `count` frames (`draw(i)` gives frame i) encoded with WebCodecs H.264 and written as one MP4: every frame kept. */
-export async function encodeMp4(codec: string, count: number, width: number, height: number, fps: number, draw: (i: number) => ImageData): Promise<Uint8Array> {
+/**
+ * `count` frames (`draw(i)` gives frame i: pixels, or a canvas handed over as it is) encoded with WebCodecs H.264 and
+ * written as one MP4: every frame kept.
+ */
+export async function encodeMp4(codec: string, count: number, width: number, height: number, fps: number, draw: (i: number) => FrameSource | Promise<FrameSource>, opts: EncodeOptions = {}): Promise<Uint8Array> {
const frames: EncodedFrame[] = [];
let avcC: Uint8Array | null = null;
let failure: unknown;
@@ -133,17 +190,18 @@ export async function encodeMp4(codec: string, count: number, width: number, hei
},
error: (err) => (failure = err),
});
- e.configure(AVC(codec, width, height, fps));
+ e.configure(AVC(codec, width, height, fps, opts.bitrate));
try {
const step = 1e6 / fps;
for (let i = 0; i < count; i++) {
- const img = draw(i);
- const f = new VideoFrame(img.data, { format: "RGBA", codedWidth: width, codedHeight: height, timestamp: Math.round(i * step), duration: Math.round(step) });
+ stopIfAsked(opts.signal);
+ const img = await draw(i);
+ const f = videoFrame(img, width, height, Math.round(i * step), Math.round(step));
e.encode(f, { keyFrame: i % Math.max(1, Math.round(fps)) === 0 });
f.close();
if (failure) throw failure;
- while (e.encodeQueueSize > 4) await new Promise((r) => setTimeout(r, 5));
- if (i % 4 === 3) await new Promise((r) => setTimeout(r, 0));
+ await drain(e, 4);
+ if (i % 4 === 3) await breathe();
}
await e.flush();
if (failure) throw failure;
diff --git a/src/components/marketing/click-to-ad.tsx b/src/components/marketing/click-to-ad.tsx
index 9de23ac8..ec15730c 100644
--- a/src/components/marketing/click-to-ad.tsx
+++ b/src/components/marketing/click-to-ad.tsx
@@ -20,7 +20,9 @@ import { formatCost } from "@/lib/format";
import { cn } from "@/lib/utils";
import { toastError } from "@/lib/refusals";
import { templateCover } from "@/lib/template-covers";
-import { endCardPng, renderEndCard, siteLabel, type EndCardInput } from "./end-card";
+import { recipeKey } from "@/lib/motion/recipe";
+import { endCardPng, siteLabel, type EndCardInput } from "./end-card";
+import { EndCardMotionPanel, renderRecipe, useEndCardMotion, type EndCardChoice } from "./end-card-motion";
import { addRuns, send, useBrand, useEstimate, useProductActions, useProducts, useReadingProduct, useUpdateBrand } from "./hooks";
import type { ModelInfo } from "./model-info";
import { AvatarSlot, VoiceControl } from "./pickers";
@@ -65,6 +67,9 @@ function KitProgress() {
);
}
+/** The end card shown before a product is picked: a sample kit to try the styles on, with the visitor's own words. */
+const SAMPLE_CARD = { brand: "Aurèle", product: "Le Sérum Nuit", colors: ["#0e3b2f", "#cfae6e"], fonts: { heading: "Cormorant Garamond", body: "Manrope" } } as const;
+
const styleScene = (presenter: boolean, dark?: boolean) => (presenter ? "selfie" : dark ? "noir" : "orbit");
/** One ad style: its real cover when it has one (a clip plays as the template cards' do), else its drawn preview. */
@@ -89,22 +94,6 @@ export function StyleTile({ style: s, selected, onPick }: { style: AdStyle; sele
);
}
-/** The end card as the ad will end on it, drawn small (the same drawing as the full-size PNG). */
-function EndCardPreview({ input, className }: { input: EndCardInput; className?: string }) {
- const ref = useRef<HTMLCanvasElement>(null);
- const key = JSON.stringify(input);
- useEffect(() => {
- // The logo and fonts load at their own pace: only the latest look is drawn.
- let live = true;
- if (ref.current) void renderEndCard(ref.current, JSON.parse(key) as EndCardInput, 0.3, () => live);
- return () => {
- live = false;
- };
- }, [key]);
- const words = [input.content.brand, input.content.product, input.content.cta].filter(Boolean).join(", ");
- return <canvas ref={ref} role="img" aria-label={`End card preview: ${words}`} className={cn("aspect-[9/16] rounded-lg border bg-muted", className)} />;
-}
-
/**
* The product kit's logo and colours, kept in the product's brand kit (made from the page when the link
* was read) so they stay after a reload and reach the video prompts. Edits save to that kit.
@@ -191,14 +180,26 @@ export function ClickToAd({ models }: { models: Record<string, ModelInfo> }) {
const [cta, setCta] = useState<string>(END_CARD.cta);
const logo = brand?.logo || brandBits?.logo || null;
const withEndCard = endCardOn ?? !!logo;
+ // Before a product is picked the card previews on a sample kit, with the words typed here.
+ const [sampleBrand, setSampleBrand] = useState<string>(SAMPLE_CARD.brand);
+ const [sampleProduct, setSampleProduct] = useState<string>(SAMPLE_CARD.product);
+ const kitColors = useMemo<string[]>(() => (product ? (brand?.colors ?? brandBits?.colors ?? []) : [...SAMPLE_CARD.colors]), [product, brand, brandBits]);
+ // The card's style: animated (Draw-on by default) or Still.
+ const [cardChoice, setCardChoice] = useState<EndCardChoice>("draw-on");
+ const [renderLine, setRenderLine] = useState<string | null>(null);
const card = useMemo<EndCardInput>(
- () => ({
- theme: themeFrom(brand ?? (brandBits ? { colors: brandBits.colors } : null)),
- content: { brand: brand?.name ?? "", product: name.trim() || product?.name || "", cta: cta.trim() || undefined, website: siteLabel(brand?.website ?? product?.url) },
- logo,
- }),
- [brand, brandBits, name, product, cta, logo],
+ () =>
+ product
+ ? {
+ theme: themeFrom(brand ?? (brandBits ? { colors: brandBits.colors } : null)),
+ content: { brand: brand?.name ?? "", product: name.trim() || product.name || "", cta: cta.trim() || undefined, website: siteLabel(brand?.website ?? product.url) },
+ logo,
+ colors: kitColors,
+ }
+ : { theme: themeFrom({ colors: [...SAMPLE_CARD.colors], fonts: SAMPLE_CARD.fonts }), content: { brand: sampleBrand, product: sampleProduct, cta: cta.trim() || undefined }, logo: null, colors: kitColors },
+ [brand, brandBits, name, product, cta, logo, kitColors, sampleBrand, sampleProduct],
);
+ const motion = useEndCardMotion(card, kitColors, engine, cardChoice);
// The drawn card is uploaded once per look (a second Generate with the same card reuses it).
const uploadedCard = useRef<{ key: string; url: string } | null>(null);
const cardUrl = async () => {
@@ -209,6 +210,26 @@ export function ClickToAd({ models }: { models: Record<string, ModelInfo> }) {
uploadedCard.current = { key, url };
return url;
};
+ // The animated card: rendered here at the ad's size and the join's frame rate, uploaded with its last frame (the run's
+ // poster), once per look and engine.
+ const uploadedClip = useRef<{ key: string; body: { image: string; clip: string; seconds: number; variant: string } } | null>(null);
+ const endCardBody = async () => {
+ if (!motion.animated) return { image: await cardUrl() };
+ const key = `${engine}:${recipeKey(motion.recipe)}`;
+ if (uploadedClip.current?.key === key) return uploadedClip.current.body;
+ setRenderLine("Rendering the end card");
+ try {
+ const out = await renderRecipe(motion.recipe, motion.inputs, { formats: engine === "open" ? ["mp4", "webm"] : ["mp4"], onProgress: (d, n) => setRenderLine(`Rendering ${d} of ${n}`) });
+ setRenderLine("Saving…");
+ const ext = out.type === "video/webm" ? "webm" : "mp4";
+ const [clip, poster] = await Promise.all([uploadFile(new File([out.blob], `end-card.${ext}`, { type: out.type })), uploadFile(new File([out.poster], "end-card.png", { type: "image/png" }))]);
+ const body = { image: poster.url, clip: clip.url, seconds: motion.recipe.duration, variant: cardChoice };
+ uploadedClip.current = { key, body };
+ return body;
+ } finally {
+ setRenderLine(null);
+ }
+ };
const choose = (p: Product, bits?: { logo?: string; colors: string[] }) => {
setProductId(p.id);
@@ -238,14 +259,22 @@ export function ClickToAd({ models }: { models: Record<string, ModelInfo> }) {
voice,
voiceSample: sample?.ref,
avatar: withPresenter ? avatar?.ref : undefined,
- // Priced with a stand-in; the card itself is drawn and uploaded when you generate.
- endCard: withEndCard ? { image: "/api/files/placeholder.png" } : undefined,
+ // Priced with a stand-in; the card itself is drawn (or rendered) and uploaded when you generate.
+ endCard: withEndCard ? { image: "/api/files/placeholder.png", ...(motion.animated && { clip: "/api/files/placeholder.mp4" }) } : undefined,
}
: null,
- [engine, productId, styleId, picked, withPresenter, script, mode, instructions, quality, voice, sample, avatar, withEndCard],
+ [engine, productId, styleId, picked, withPresenter, script, mode, instructions, quality, voice, sample, avatar, withEndCard, motion.animated],
);
const est = useEstimate<RunEstimate>("/api/marketing/click-to-ad/estimate", body);
- const blocker = !product ? "Select a product or enter a product URL" : !product.images.length ? `${product.name} has no images` : !desc.trim() ? "Add a description" : est.data?.blocker;
+ const blocker = !product
+ ? "Select a product or enter a product URL"
+ : !product.images.length
+ ? `${product.name} has no images`
+ : !desc.trim()
+ ? "Add a description"
+ : withEndCard && motion.overflow.length
+ ? motion.overflow[0]
+ : est.data?.blocker;
const cost = est.data && !est.data.blocker ? (visitor && (est.data.demo || est.data.costUsd === 0) ? "Not available here" : est.data.demo ? "Placeholder · free" : est.data.costUsd == null ? "" : `≈ ${formatCost(est.data.costUsd)}`) : "";
const writeScript = async () => {
@@ -266,7 +295,7 @@ export function ClickToAd({ models }: { models: Record<string, ModelInfo> }) {
if (blocker) return void toast(blocker, { id: "c2a-blocker" });
setBusy(true);
try {
- const endCard = withEndCard ? { image: await cardUrl() } : undefined;
+ const endCard = withEndCard ? await endCardBody() : undefined;
const r = await send<{ run: MarketingRun; script: string }>("/api/marketing/click-to-ad", "POST", { ...body, endCard });
addRuns(qc, "click-to-ad", [r.run]);
setScript(r.script);
@@ -313,6 +342,22 @@ export function ClickToAd({ models }: { models: Record<string, ModelInfo> }) {
</div>
</Step>
+ {!product && (
+ <section aria-labelledby="c2a-end-card-try" className="min-w-0 space-y-3 rounded-2xl border p-4 sm:p-5">
+ <div>
+ <h3 id="c2a-end-card-try" className="text-[15px] font-semibold">
+ Your ad ends on your brand
+ </h3>
+ <p className="mt-0.5 text-[13px] text-muted-foreground">An animated end card in your brand&apos;s colours and fonts, in five styles. Try one with your words.</p>
+ </div>
+ <div className="grid min-w-0 gap-2 sm:grid-cols-2">
+ <input value={sampleBrand} onChange={(e) => setSampleBrand(e.target.value.slice(0, 40))} className="h-11 w-full min-w-0 rounded-xl border bg-background px-3 text-[14px] outline-none focus-visible:ring-2 focus-visible:ring-ring" aria-label="Brand name on the end card" placeholder="Brand name" />
+ <input value={sampleProduct} onChange={(e) => setSampleProduct(e.target.value.slice(0, 60))} className="h-11 w-full min-w-0 rounded-xl border bg-background px-3 text-[14px] outline-none focus-visible:ring-2 focus-visible:ring-ring" aria-label="Product name on the end card" placeholder="Product name" />
+ </div>
+ <EndCardMotionPanel card={card} colors={kitColors} motion={motion} choice={cardChoice} onChoice={setCardChoice} cta={cta} onCta={setCta} />
+ </section>
+ )}
+
{product && (
<Step n={2} title="Your product kit" hint="Review the details we extracted — edit anything before generating your video." done={!!desc.trim() && picked.length > 0}>
<div className="grid min-w-0 gap-5 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
@@ -384,7 +429,7 @@ export function ClickToAd({ models }: { models: Record<string, ModelInfo> }) {
))}
</div>
<div className="mt-5 grid min-w-0 gap-4 md:grid-cols-2">
- <div className="space-y-3">
+ <div className="min-w-0 space-y-3">
<div>
<p className="mb-1.5 text-[12px] font-medium text-muted-foreground">Who&apos;s in it</p>
<div role="radiogroup" aria-label="Presenter" className="inline-flex rounded-full bg-muted p-0.5">
@@ -399,21 +444,18 @@ export function ClickToAd({ models }: { models: Record<string, ModelInfo> }) {
{withPresenter && <AvatarSlot value={avatar} onChange={setAvatar} />}
<VoiceControl engine={engine} models={models} voice={voice} sample={sample} onVoice={setVoice} onSample={setSample} />
</div>
- <div className="flex items-start gap-3 rounded-xl border p-3">
- <EndCardPreview input={card} className={cn("w-[72px] shrink-0 transition-opacity", !withEndCard && "opacity-40")} />
- <div className="min-w-0 flex-1 space-y-2">
- <div className="flex items-center justify-between gap-2">
- <label htmlFor="c2a-end-card" className="text-[13px] font-medium">
- End card
- </label>
- <Switch id="c2a-end-card" checked={withEndCard} onCheckedChange={setEndCardOn} />
- </div>
- <p className="text-[12px] text-muted-foreground">
- {withEndCard ? `The ad ends on your ${logo ? "logo" : "brand name"} for ${END_CARD.seconds} s, in your brand colours.` : "The ad ends on its last shot."}
- {!logo && " Add a logo in the product kit to show it."}
- </p>
- {withEndCard && <input value={cta} onChange={(e) => setCta(e.target.value.slice(0, 30))} className={inputCls} aria-label="Call to action on the end card" placeholder="Call to action, e.g. Shop now" />}
+ <div className="min-w-0 space-y-2 rounded-xl border p-3">
+ <div className="flex items-center justify-between gap-2">
+ <label htmlFor="c2a-end-card" className="text-[13px] font-medium">
+ End card
+ </label>
+ <Switch id="c2a-end-card" checked={withEndCard} onCheckedChange={setEndCardOn} />
</div>
+ <p className="text-[12px] text-muted-foreground">
+ {withEndCard ? `The ad ends on your ${logo ? "logo" : "brand name"} for ${END_CARD.seconds} s, in your brand colours and fonts.` : "The ad ends on its last shot."}
+ {!logo && " Add a logo in the product kit to show it."}
+ </p>
+ {withEndCard && <EndCardMotionPanel card={card} colors={kitColors} motion={motion} choice={cardChoice} onChoice={setCardChoice} cta={cta} onCta={setCta} rendering={renderLine} />}
</div>
<div>
<p className="mb-1.5 text-[12px] font-medium text-muted-foreground">Video quality</p>
diff --git a/src/components/marketing/end-card-motion.tsx b/src/components/marketing/end-card-motion.tsx
new file mode 100644
index 00000000..67bcf8e3
--- /dev/null
+++ b/src/components/marketing/end-card-motion.tsx
@@ -0,0 +1,163 @@
+"use client";
+
+import { Loader2, Save } from "lucide-react";
+import { useEffect, useMemo, useState } from "react";
+import { Button } from "@/components/ui/button";
+import { measureText } from "@/components/ads/render";
+import { fontsReady } from "@/components/motion/fonts";
+import { MotionPlayer, useMotionInputs, usePlan, useScene, type MotionInputs } from "@/components/motion/player";
+import { canMakeMp4, renderClip, type RenderResult } from "@/components/motion/render";
+import { phaseLine, useMotionSave } from "@/components/motion/save";
+import { VariantPicker, type VariantChoice } from "@/components/motion/variant-picker";
+import { END_CARD } from "@/lib/catalog/marketing";
+import type { Engine } from "@/lib/catalog/types";
+import { DEFAULT_EXPORT, type Recipe } from "@/lib/motion/recipe";
+import { loadScene } from "@/lib/motion/registry";
+import { END_CARD_VARIANT_NAMES, END_CARD_VARIANTS, type EndCardVariant } from "@/lib/motion/scenes/end-card/shared";
+import type { SizeSpec } from "@/lib/motion/sizes";
+import type { EndCardInput } from "./end-card";
+
+/**
+ * Click to Ad's end card in motion: five designed styles (and Still), each a live preview drawn by the same code that
+ * renders the clip, so what plays here is what the ad ends on.
+ */
+
+export type EndCardChoice = EndCardVariant | "still";
+
+export const END_CARD_CHOICES: VariantChoice[] = [
+ ...END_CARD_VARIANTS.map((v) => ({ id: v, label: END_CARD_VARIANT_NAMES[v], scene: `end-card/${v}` })),
+ { id: "still", label: "Still", scene: "end-card/draw-on", still: true },
+];
+
+const HEX = /^#[0-9a-f]{6}$/i;
+
+/** The card as a Kinetic Motion recipe (the words as typed, the kit's colours and fonts, its logo). */
+export function endCardRecipe(card: EndCardInput, colors: readonly string[], scene: string, o: { fps: 24 | 25 | 30; size: SizeSpec; seconds?: number }): Recipe {
+ return {
+ v: 1,
+ scene,
+ seed: 1,
+ size: o.size,
+ fps: o.fps,
+ duration: o.seconds ?? END_CARD.seconds,
+ fields: { brand: card.content.brand, product: card.content.product, ...(card.content.cta && { cta: card.content.cta }), ...(card.content.website && { website: card.content.website }) },
+ brand: { name: card.content.brand, colors: colors.filter((c) => HEX.test(c)).slice(0, 8), fonts: { heading: card.theme.heading, body: card.theme.body }, ...(card.logo && { logo: card.logo }) },
+ export: DEFAULT_EXPORT,
+ };
+}
+
+/** The frame rate the ad's join works at: 25 on the open engine (its join resamples to 25), 24 in the cloud. */
+export const cardFps = (engine: Engine): 24 | 25 => (engine === "open" ? 25 : 24);
+
+const OVERFLOW_WORDS: Record<string, string> = {
+ product: "Shorten the product name to fit the end card",
+ cta: "Shorten the call to action to fit the end card",
+ brand: "Shorten the brand name to fit the end card",
+ website: "Shorten the address to fit the end card",
+};
+
+export function useEndCardMotion(card: EndCardInput, colors: readonly string[], engine: Engine, choice: EndCardChoice) {
+ const fps = cardFps(engine);
+ const sceneId = choice === "still" ? "end-card/draw-on" : `end-card/${choice}`;
+ const recipe = useMemo(() => endCardRecipe(card, colors, sceneId, { fps, size: END_CARD.size }), [card, colors, sceneId, fps]);
+ const inputs = useMotionInputs(recipe);
+ const scene = useScene(sceneId);
+ const plan = usePlan(scene, recipe, inputs);
+ const [mp4, setMp4] = useState<boolean | null>(null);
+ useEffect(() => {
+ let live = true;
+ void canMakeMp4(END_CARD.size.w, END_CARD.size.h, 24)
+ .then((ok) => live && setMp4(ok))
+ .catch(() => live && setMp4(false));
+ return () => {
+ live = false;
+ };
+ }, []);
+ // The cloud's join takes MP4 only: without an H.264 encoder here the card stays a still.
+ const stillOnly = engine === "cloud" && mp4 === false;
+ const overflow = plan?.overflow.map((f) => OVERFLOW_WORDS[f]).filter(Boolean) ?? [];
+ return { recipe, inputs, plan, overflow, stillOnly, animated: choice !== "still" && !stillOnly, recipeFor: (scene: string) => endCardRecipe(card, colors, scene, { fps, size: END_CARD.size }) };
+}
+
+/** Renders a recipe's clip here, in the brand's own fonts (a font that didn't load stops it). */
+export async function renderRecipe(recipe: Recipe, inputs: MotionInputs, o: { formats: ("mp4" | "webm")[]; signal?: AbortSignal; onProgress?: (done: number, total: number) => void }): Promise<RenderResult> {
+ await fontsReady([recipe.brand.fonts.heading, recipe.brand.fonts.body], { strict: true, text: Object.values(recipe.fields).join(" ") });
+ const scene = await loadScene(recipe.scene);
+ return renderClip(scene, recipe, { sources: inputs.sources, logo: inputs.logo, measure: measureText, formats: o.formats, signal: o.signal, onProgress: (d, n) => o.onProgress?.(d, n) });
+}
+
+/** The words a saved end card is listed and searched by. */
+const wordsOf = (card: EndCardInput) => [card.content.brand, card.content.product, card.content.cta, card.content.website].filter((w) => w?.trim()).join(" · ");
+
+export function EndCardMotionPanel({
+ card,
+ colors,
+ motion,
+ choice,
+ onChoice,
+ cta,
+ onCta,
+ rendering,
+}: {
+ card: EndCardInput;
+ colors: readonly string[];
+ motion: ReturnType<typeof useEndCardMotion>;
+ choice: EndCardChoice;
+ onChoice: (c: EndCardChoice) => void;
+ cta: string;
+ onCta: (v: string) => void;
+ /** "Rendering 42 of 63" while Generate renders the card. */
+ rendering?: string | null;
+}) {
+ const saver = useMotionSave();
+ const line = phaseLine(saver.phase);
+ const words = [card.content.brand, card.content.product, card.content.cta].filter(Boolean).join(", ");
+ // Only an animated style is kept as a clip; the still card is part of the ad itself.
+ const variant = motion.animated && choice !== "still" ? choice : null;
+ const save = () => {
+ if (!variant) return;
+ // A logo sting to keep: full 1080 × 1920 at 30 fps.
+ const recipe = endCardRecipe(card, colors, `end-card/${variant}`, { fps: 30, size: "9:16" });
+ void saver.save({ recipe, feature: "kinetic-end-card", title: `${card.content.brand || card.content.product || "Brand"} end card · ${END_CARD_VARIANT_NAMES[variant]}`, prompt: wordsOf(card), images: card.logo ? [card.logo] : [] }, (signal, progress) =>
+ renderRecipe(recipe, motion.inputs, { formats: ["mp4", "webm"], signal, onProgress: progress }),
+ );
+ };
+ return (
+ <div className="min-w-0 space-y-3">
+ <VariantPicker choices={END_CARD_CHOICES} value={motion.stillOnly ? "still" : choice} onChange={(id) => onChoice(id as EndCardChoice)} recipeFor={motion.recipeFor} inputs={motion.inputs} label="End card style" />
+ {motion.stillOnly && <p className="text-[12px] text-muted-foreground">This browser makes the still end card.</p>}
+ <div className="grid min-w-0 gap-3 sm:grid-cols-[180px_minmax(0,1fr)]">
+ <div className="mx-auto w-full max-w-[200px] sm:max-w-none">
+ {motion.animated ? (
+ <MotionPlayer plan={motion.plan} sources={motion.inputs.sources} size={END_CARD.size} duration={motion.recipe.duration} fps={motion.recipe.fps} label={`End card preview: ${words}`} />
+ ) : (
+ <MotionPlayer plan={motion.plan} sources={motion.inputs.sources} size={END_CARD.size} duration={motion.recipe.duration} fps={motion.recipe.fps} label={`End card preview: ${words}`} controls={false} active={false} />
+ )}
+ </div>
+ <div className="min-w-0 space-y-2">
+ <input value={cta} onChange={(e) => onCta(e.target.value.slice(0, 30))} className="h-11 w-full min-w-0 rounded-xl border bg-background px-3 text-[14px] outline-none focus-visible:ring-2 focus-visible:ring-ring" aria-label="Call to action on the end card" placeholder="Call to action, e.g. Shop now" />
+ {motion.overflow.map((m) => (
+ <p key={m} className="text-[12px] text-destructive">
+ {m}
+ </p>
+ ))}
+ {rendering && (
+ <p role="status" className="flex items-center gap-1.5 text-[12px] text-muted-foreground">
+ <Loader2 className="size-3.5 animate-spin" /> {rendering}
+ </p>
+ )}
+ {variant && (
+ <Button variant="outline" className="h-11 w-full" onClick={save} disabled={!!line || motion.overflow.length > 0 || !motion.plan}>
+ {line ? <Loader2 className="animate-spin" /> : <Save />} {line ?? `Save ${END_CARD_VARIANT_NAMES[variant]} to ${saver.label.endsWith("runs") ? "your runs" : "Library"}`}
+ </Button>
+ )}
+ {line && (
+ <Button variant="ghost" className="h-11 w-full" onClick={saver.cancel}>
+ Stop
+ </Button>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/marketing/end-card.ts b/src/components/marketing/end-card.ts
index c8198f89..8e5854b6 100644
--- a/src/components/marketing/end-card.ts
+++ b/src/components/marketing/end-card.ts
@@ -1,21 +1,17 @@
import { END_CARD } from "@/lib/catalog/marketing";
-import { containIn, contrast, fitText, fontString, readableOn, textBox, type AdPlan, type AdTheme, type Measure, type Rect, type TextBox } from "../ads/layout";
-import { drawPlan, ensureFont, loadImage, measureText } from "../ads/render";
+import { endCardRest, restNodes, type EndCardContent, type TextBlock } from "@/lib/motion/scenes/end-card/shared";
+import { designSize } from "@/lib/motion/sizes";
+import type { AdPlan, AdTheme, Measure, TextBox } from "../ads/layout";
+import { ensureFont, loadImage, measureText } from "../ads/render";
+import { drawDisplayList } from "../motion/draw";
/**
- * Click to Ad's logo end card: the brand colour, the logo (or the brand's name), the product name and a
- * call-to-action pill, centred on a 9:16 card. Laid out here (pure, tested) and drawn with the Ads Studio
- * compositor's drawPlan, so the preview on the page and the PNG the ad ends on are the same picture.
+ * Click to Ad's logo end card: the brand colour, the logo (or the brand's name), the product name, a call-to-action
+ * pill and the address, centred on a 9:16 card in the kit's colours. Laid out by the animated end card's own rest
+ * layout and drawn by the same drawer, so the still card and every style's last frame are the same picture.
*/
-export interface EndCardContent {
- /** Shown when the kit has no logo. */
- brand: string;
- product: string;
- cta?: string;
- /** A small line at the bottom (the shop's address). */
- website?: string;
-}
+export type { EndCardContent } from "@/lib/motion/scenes/end-card/shared";
export interface EndCardLayoutInput {
theme: AdTheme;
@@ -24,6 +20,8 @@ export interface EndCardLayoutInput {
logo?: { w: number; h: number } | null;
measure: Measure;
size?: { w: number; h: number };
+ /** The kit's colours (the words and the pill take one that reads on the brand colour). */
+ colors?: readonly string[];
}
/** "yourshop.com" from "https://www.yourshop.com/products/x". */
@@ -36,56 +34,35 @@ export function siteLabel(url: string | undefined): string | undefined {
}
}
-/** Where everything goes on the card: one centred block (logo or name, product, CTA), the address at the foot. */
-export function planEndCard(p: EndCardLayoutInput): AdPlan {
- const { w: W, h: H } = p.size ?? END_CARD.size;
- const t = p.theme;
- const m = Math.round(W * 0.1);
- const inner = W - 2 * m;
- const ink = t.onAccent;
- const gap = H * 0.04;
- // Measure the block first, then centre it a little above the middle.
- const logoH = H * 0.15;
- const name = !p.logo && p.content.brand.trim() ? fitText(p.content.brand.trim().toUpperCase(), inner, 2, t.heading, 800, W * 0.1, W * 0.06, p.measure) : null;
- const head = fitText(p.content.product.trim() || " ", inner, 2, t.heading, 700, W * 0.068, W * 0.045, p.measure);
- const ctaSize = W * 0.045;
- const label = p.content.cta?.trim() ? fitText(p.content.cta.trim(), inner - ctaSize * 2.4, 1, t.body, 700, ctaSize, W * 0.03, p.measure) : null;
- const ctaH = label ? label.size * 2.3 : 0;
- const top = p.logo ? logoH : name ? name.lines.length * name.size * 1.05 : 0;
- const headH = head.lines.length * head.size * 1.12;
- const total = top + (top ? gap : 0) + headH + (label ? gap * 1.4 + ctaH : 0);
- let y = Math.max(m, (H - total) / 2 - H * 0.03);
-
- let logo: Rect | undefined;
- let brand: TextBox | undefined;
- if (p.logo) {
- logo = containIn(p.logo.w, p.logo.h, { x: m, y, w: inner, h: logoH }, "center");
- y += logoH + gap;
- } else if (name) {
- brand = textBox(name, W / 2, y, t.heading, 800, ink, "center", inner, 1.05);
- y += top + gap;
- }
- const headline = textBox(head, W / 2, y, t.heading, 700, ink, "center", inner);
- y += headH;
- let cta: AdPlan["cta"];
- if (label) {
- y += gap * 1.4;
- const tw = p.measure(label.lines[0], fontString(t.body, label.size, 700));
- const bw = Math.min(inner, tw + label.size * 2.4);
- const bx = (W - bw) / 2;
- // The pill is the text colour; its words the brand colour, or whatever reads on the pill.
- const onPill = contrast(t.accent, ink) >= 3 ? t.accent : readableOn(ink);
- cta = { x: bx, y, w: bw, h: ctaH, radius: ctaH / 2, color: ink, text: textBox(label, bx + bw / 2, y + (ctaH - label.size * 1.12) / 2, t.body, 700, onPill, "center", bw) };
- }
- const site = p.content.website?.trim() ? fitText(p.content.website.trim(), inner, 1, t.body, 500, W * 0.032, W * 0.024, p.measure) : null;
- const body = site ? textBox(site, W / 2, H - m - site.size * 1.12, t.body, 500, ink, "center", inner) : undefined;
- return { w: W, h: H, bg: t.accent, image: null, logo, brand, headline, body, cta };
+/**
+ * Where everything goes on the card: one centred block (logo or name, product, CTA), the address at the foot. The
+ * animated end cards end on this same layout (lib/motion/scenes/end-card/shared.ts endCardRest), so the still card,
+ * the poster and every style's last frame match. Words are set exactly as typed (no capitals added, nothing cut);
+ * `overflow` names a field too long to fit even at its smallest size.
+ */
+export function planEndCard(p: EndCardLayoutInput): AdPlan & { overflow: (keyof EndCardContent)[] } {
+ const size = p.size ?? END_CARD.size;
+ const r = endCardRest({ theme: p.theme, content: p.content, logo: p.logo ?? null, measure: p.measure, size, letters: false, colors: p.colors });
+ const box = (b: TextBlock, width = r.inner): TextBox => ({ lines: b.layout.lines.map((l) => l.text), x: b.cx, y: b.y, size: b.layout.size, lineHeight: b.layout.lineHeight, font: b.layout.font, color: b.color, align: "center", width });
+ return {
+ w: size.w,
+ h: size.h,
+ bg: p.theme.accent,
+ image: null,
+ logo: r.logo,
+ brand: r.brand && box(r.brand),
+ headline: box(r.headline),
+ body: r.site && box(r.site),
+ cta: r.cta && { x: r.cta.x, y: r.cta.y, w: r.cta.w, h: r.cta.h, radius: r.cta.r, color: r.cta.color, text: box(r.cta.label, r.cta.w) },
+ overflow: r.overflow,
+ };
}
export interface EndCardInput {
theme: AdTheme;
content: EndCardContent;
logo?: string | null;
+ colors?: readonly string[];
}
/**
@@ -98,11 +75,14 @@ export async function renderEndCard(canvas: HTMLCanvasElement, input: EndCardInp
const { w, h } = END_CARD.size;
canvas.width = Math.round(w * scale);
canvas.height = Math.round(h * scale);
- const ctx = canvas.getContext("2d");
+ const ctx = canvas.getContext("2d", { alpha: false });
if (!ctx) return;
- ctx.setTransform(scale, 0, 0, scale, 0, 0);
- const plan = planEndCard({ theme: input.theme, content: input.content, logo: logo ? { w: logo.naturalWidth || 400, h: logo.naturalHeight || 120 } : null, measure: measureText });
- drawPlan(ctx, plan, null, logo);
+ // Laid out in the animated card's design units (1080 on the short side) and scaled by the drawer, as its frames are.
+ const size = designSize(END_CARD.size);
+ const rest = endCardRest({ theme: input.theme, content: input.content, logo: logo ? { w: logo.naturalWidth || 400, h: logo.naturalHeight || 120 } : null, measure: measureText, size, colors: input.colors });
+ const images = new Map<string, CanvasImageSource>();
+ if (logo) images.set("logo", logo);
+ drawDisplayList(ctx, { w: size.w, h: size.h, background: input.theme.accent, nodes: restNodes(rest) }, { images });
}
/** The full-size card as a PNG, ready to upload. */
diff --git a/src/components/motion/draw.ts b/src/components/motion/draw.ts
new file mode 100644
index 00000000..109bf15e
--- /dev/null
+++ b/src/components/motion/draw.ts
@@ -0,0 +1,414 @@
+"use client";
+
+import { IDENTITY, multiply, type ClipShape, type DisplayList, type DisplayNode, type Gradient, type Matrix, type Paint, type Stroke } from "@/lib/motion/display";
+import type { LogoInfo, LogoPath } from "@/lib/motion/scene";
+
+/**
+ * The only code that turns a Kinetic Motion display list into canvas calls: the live preview, the export and the covers
+ * all draw through drawDisplayList, so they are the same picture at different pixel counts. Also reads an SVG logo's
+ * outlines (with the browser's own SVG engine) for the scenes that trace them.
+ */
+
+type Ctx = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;
+type AnyCanvas = HTMLCanvasElement | OffscreenCanvas;
+
+export interface Sources {
+ /** Pictures by key ("logo", "product"). */
+ images: Map<string, CanvasImageSource>;
+}
+
+const paths = new Map<string, Path2D>();
+const lengths = new Map<string, number>();
+
+function path2d(d: string): Path2D {
+ let p = paths.get(d);
+ if (!p) {
+ p = new Path2D(d);
+ if (paths.size > 2000) paths.clear();
+ paths.set(d, p);
+ }
+ return p;
+}
+
+/** A path's length in its own units, measured once by an SVG path element. */
+function pathLength(d: string): number {
+ let n = lengths.get(d);
+ if (n === undefined) {
+ n = 0;
+ if (typeof document !== "undefined") {
+ try {
+ const el = document.createElementNS("http://www.w3.org/2000/svg", "path");
+ el.setAttribute("d", d);
+ n = el.getTotalLength();
+ } catch {}
+ }
+ lengths.set(d, n);
+ }
+ return n;
+}
+
+let filterOk: boolean | null = null;
+/** Whether this browser's canvas takes a CSS filter (blur); where it can't, scenes keep their scale moves only. */
+function canFilter(ctx: Ctx): boolean {
+ if (filterOk === null) {
+ try {
+ const before = ctx.filter;
+ ctx.filter = "blur(1px)";
+ filterOk = ctx.filter === "blur(1px)";
+ ctx.filter = before;
+ } catch {
+ filterOk = false;
+ }
+ }
+ return filterOk;
+}
+
+function makeCanvas(w: number, h: number): AnyCanvas {
+ if (typeof OffscreenCanvas !== "undefined") return new OffscreenCanvas(w, h);
+ return Object.assign(document.createElement("canvas"), { width: w, height: h });
+}
+
+/** Scratch layers per target canvas (one per nesting depth), reused frame to frame. */
+const layers = new WeakMap<object, AnyCanvas[]>();
+function layerFor(target: AnyCanvas, depth: number): { canvas: AnyCanvas; ctx: Ctx } {
+ let list = layers.get(target);
+ if (!list) layers.set(target, (list = []));
+ let c = list[depth];
+ if (!c || c.width !== target.width || c.height !== target.height) c = list[depth] = makeCanvas(target.width, target.height);
+ return { canvas: c, ctx: c.getContext("2d") as Ctx };
+}
+
+function paintOf(ctx: Ctx, p: Paint): string | CanvasGradient {
+ if (typeof p === "string") return p;
+ const g: Gradient = p;
+ const grad = g.kind === "linear" ? ctx.createLinearGradient(g.x0, g.y0, g.x1, g.y1) : ctx.createRadialGradient(g.cx, g.cy, g.r0, g.cx, g.cy, Math.max(0.001, g.r1));
+ for (const s of g.stops) grad.addColorStop(Math.min(1, Math.max(0, s.at)), s.color);
+ return grad;
+}
+
+function roundRect(ctx: Ctx | Path2D, x: number, y: number, w: number, h: number, r: number) {
+ const rr = Math.max(0, Math.min(r, w / 2, h / 2));
+ ctx.moveTo(x + rr, y);
+ ctx.lineTo(x + w - rr, y);
+ ctx.arc(x + w - rr, y + rr, rr, -Math.PI / 2, 0);
+ ctx.lineTo(x + w, y + h - rr);
+ ctx.arc(x + w - rr, y + h - rr, rr, 0, Math.PI / 2);
+ ctx.lineTo(x + rr, y + h);
+ ctx.arc(x + rr, y + h - rr, rr, Math.PI / 2, Math.PI);
+ ctx.lineTo(x, y + rr);
+ ctx.arc(x + rr, y + rr, rr, Math.PI, Math.PI * 1.5);
+ ctx.closePath();
+}
+
+function clipTo(ctx: Ctx, c: ClipShape) {
+ ctx.beginPath();
+ if (c.type === "rect") {
+ if (c.r) roundRect(ctx, c.x, c.y, c.w, c.h, c.r);
+ else ctx.rect(c.x, c.y, c.w, c.h);
+ } else ctx.ellipse(c.cx, c.cy, Math.max(0, c.rx), Math.max(0, c.ry), 0, 0, Math.PI * 2);
+ ctx.clip();
+}
+
+const setMatrix = (ctx: Ctx, m: Matrix) => ctx.setTransform(m[0], m[1], m[2], m[3], m[4], m[5]);
+
+function stroke(ctx: Ctx, s: Stroke, length: number, draw: () => void) {
+ const trim = s.trim ?? 1;
+ if (trim <= 0) return;
+ ctx.strokeStyle = paintOf(ctx, s.paint);
+ ctx.lineWidth = s.width;
+ ctx.lineCap = s.cap ?? "butt";
+ ctx.lineJoin = s.join ?? "miter";
+ if (trim < 1 && length > 0) {
+ ctx.setLineDash([length * trim, length + s.width * 4]);
+ ctx.lineDashOffset = 0;
+ } else ctx.setLineDash([]);
+ draw();
+ ctx.setLineDash([]);
+}
+
+/** The device-pixel box of a design-unit box under a matrix (clamped to the canvas). */
+function deviceBox(m: Matrix, b: { x: number; y: number; w: number; h: number }, W: number, H: number) {
+ const pts = [
+ [b.x, b.y],
+ [b.x + b.w, b.y],
+ [b.x, b.y + b.h],
+ [b.x + b.w, b.y + b.h],
+ ].map(([x, y]) => [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]]);
+ const x0 = Math.max(0, Math.floor(Math.min(...pts.map((p) => p[0]))));
+ const y0 = Math.max(0, Math.floor(Math.min(...pts.map((p) => p[1]))));
+ const x1 = Math.min(W, Math.ceil(Math.max(...pts.map((p) => p[0]))));
+ const y1 = Math.min(H, Math.ceil(Math.max(...pts.map((p) => p[1]))));
+ return { x: x0, y: y0, w: Math.max(0, x1 - x0), h: Math.max(0, y1 - y0) };
+}
+
+function drawNode(ctx: Ctx, n: DisplayNode, m: Matrix, alpha: number, src: Sources, depth: number) {
+ if (alpha <= 0.001) return;
+ switch (n.type) {
+ case "group": {
+ const gm = n.transform ? multiply(m, n.transform) : m;
+ const a = alpha * (n.opacity ?? 1);
+ if (a <= 0.001) return;
+ const bounds = n.isolate ?? n.mask?.bounds;
+ if (bounds) {
+ const target = ctx.canvas as AnyCanvas;
+ const box = deviceBox(gm, bounds, target.width, target.height);
+ if (!box.w || !box.h) return;
+ const layer = layerFor(target, depth);
+ const l = layer.ctx;
+ l.save();
+ l.setTransform(1, 0, 0, 1, 0, 0);
+ l.globalAlpha = 1;
+ l.globalCompositeOperation = "source-over";
+ l.clearRect(box.x, box.y, box.w, box.h);
+ l.beginPath();
+ l.rect(box.x, box.y, box.w, box.h);
+ l.clip();
+ if (n.clip) {
+ setMatrix(l, gm);
+ clipTo(l, n.clip);
+ }
+ if (n.blur && canFilter(l)) l.filter = `blur(${n.blur * Math.sqrt(Math.abs(gm[0] * gm[3] - gm[1] * gm[2]))}px)`;
+ for (const c of n.children) drawNode(l, c, gm, 1, src, depth + 1);
+ l.filter = "none";
+ if (n.mask) {
+ setMatrix(l, gm);
+ l.globalCompositeOperation = "destination-in";
+ l.fillStyle = paintOf(l, n.mask);
+ l.fillRect(bounds.x, bounds.y, bounds.w, bounds.h);
+ }
+ l.restore();
+ ctx.save();
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
+ ctx.globalAlpha = a;
+ ctx.globalCompositeOperation = n.blend ?? "source-over";
+ ctx.drawImage(layer.canvas, box.x, box.y, box.w, box.h, box.x, box.y, box.w, box.h);
+ ctx.restore();
+ return;
+ }
+ ctx.save();
+ if (n.clip) {
+ setMatrix(ctx, gm);
+ clipTo(ctx, n.clip);
+ }
+ if (n.blend) ctx.globalCompositeOperation = n.blend;
+ if (n.blur && canFilter(ctx)) ctx.filter = `blur(${n.blur * Math.sqrt(Math.abs(gm[0] * gm[3] - gm[1] * gm[2]))}px)`;
+ for (const c of n.children) drawNode(ctx, c, gm, a, src, depth);
+ ctx.restore();
+ return;
+ }
+ case "rect": {
+ setMatrix(ctx, m);
+ ctx.globalAlpha = alpha * (n.opacity ?? 1);
+ if (n.fill) {
+ ctx.fillStyle = paintOf(ctx, n.fill);
+ if (n.r) {
+ ctx.beginPath();
+ roundRect(ctx, n.x, n.y, n.w, n.h, n.r);
+ ctx.fill();
+ } else ctx.fillRect(n.x, n.y, n.w, n.h);
+ }
+ if (n.stroke) {
+ const s = n.stroke;
+ const r = Math.min(n.r ?? 0, n.w / 2, n.h / 2);
+ stroke(ctx, s, s.length ?? 2 * (n.w + n.h) - 8 * r + 2 * Math.PI * r, () => {
+ ctx.beginPath();
+ roundRect(ctx, n.x, n.y, n.w, n.h, r);
+ ctx.stroke();
+ });
+ }
+ return;
+ }
+ case "ellipse": {
+ setMatrix(ctx, m);
+ ctx.globalAlpha = alpha * (n.opacity ?? 1);
+ ctx.beginPath();
+ ctx.ellipse(n.cx, n.cy, Math.max(0, n.rx), Math.max(0, n.ry), 0, 0, Math.PI * 2);
+ if (n.fill) {
+ ctx.fillStyle = paintOf(ctx, n.fill);
+ ctx.fill();
+ }
+ if (n.stroke) {
+ const h = ((n.rx - n.ry) / (n.rx + n.ry)) ** 2;
+ const len = Math.PI * (n.rx + n.ry) * (1 + (3 * h) / (10 + Math.sqrt(4 - 3 * h)));
+ stroke(ctx, n.stroke, n.stroke.length ?? len, () => ctx.stroke());
+ }
+ return;
+ }
+ case "path": {
+ setMatrix(ctx, n.transform ? multiply(m, n.transform) : m);
+ ctx.globalAlpha = alpha * (n.opacity ?? 1);
+ const p = path2d(n.d);
+ if (n.fill) {
+ ctx.fillStyle = paintOf(ctx, n.fill);
+ ctx.fill(p);
+ }
+ if (n.stroke) stroke(ctx, n.stroke, n.stroke.length ?? pathLength(n.d), () => ctx.stroke(p));
+ return;
+ }
+ case "text": {
+ const a = alpha * (n.opacity ?? 1);
+ ctx.textBaseline = "top";
+ ctx.textAlign = "left";
+ for (const r of n.runs) {
+ const ra = a * (r.opacity ?? 1);
+ if (ra <= 0.001) continue;
+ setMatrix(ctx, r.transform ? multiply(m, r.transform) : m);
+ ctx.globalAlpha = ra;
+ ctx.font = r.font;
+ ctx.direction = r.dir ?? "ltr";
+ ctx.fillStyle = paintOf(ctx, r.fill);
+ ctx.fillText(r.text, r.x, r.y);
+ }
+ ctx.direction = "ltr";
+ return;
+ }
+ case "image": {
+ const img = src.images.get(n.src);
+ if (!img) return;
+ setMatrix(ctx, m);
+ ctx.globalAlpha = alpha * (n.opacity ?? 1);
+ ctx.imageSmoothingEnabled = n.smoothing ?? true;
+ ctx.imageSmoothingQuality = "high";
+ ctx.drawImage(img, n.x, n.y, n.w, n.h);
+ return;
+ }
+ }
+}
+
+/**
+ * Draw a display list onto a canvas `pixelWidth / list.w` times its design size (the canvas is that size). Clears to
+ * the list's background first, so every frame stands alone.
+ */
+export function drawDisplayList(ctx: Ctx, list: DisplayList, sources: Sources): void {
+ const W = ctx.canvas.width;
+ const H = ctx.canvas.height;
+ const k = W / list.w;
+ ctx.save();
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
+ ctx.globalAlpha = 1;
+ ctx.globalCompositeOperation = "source-over";
+ ctx.filter = "none";
+ ctx.fillStyle = list.background;
+ ctx.fillRect(0, 0, W, H);
+ const base: Matrix = multiply([k, 0, 0, H / list.h, 0, 0], IDENTITY);
+ for (const n of list.nodes) drawNode(ctx, n, base, 1, sources, 0);
+ ctx.restore();
+}
+
+// ---------------------------------------------------------------------------
+// Logos
+
+const GEOMETRY = "path, rect, circle, ellipse, line, polyline, polygon";
+const SKIP = "defs, clipPath, mask, pattern, symbol, marker, title, desc, metadata";
+
+/** The SVG's own outlines, mapped to its viewBox: null when there is none to trace (an embedded picture only). */
+async function svgOutlines(url: string): Promise<{ paths: LogoPath[]; viewBox: { x: number; y: number; w: number; h: number } } | null> {
+ const res = await fetch(url);
+ if (!res.ok) return null;
+ const text = await res.text();
+ const doc = new DOMParser().parseFromString(text, "image/svg+xml");
+ const svg = doc.documentElement;
+ if (svg.nodeName.toLowerCase() !== "svg" || doc.querySelector("parsererror")) return null;
+ const vbAttr = svg.getAttribute("viewBox")?.trim().split(/[\s,]+/).map(Number);
+ const w = parseFloat(svg.getAttribute("width") ?? "") || vbAttr?.[2] || 0;
+ const h = parseFloat(svg.getAttribute("height") ?? "") || vbAttr?.[3] || 0;
+ const viewBox = vbAttr && vbAttr.length === 4 && vbAttr.every(Number.isFinite) ? { x: vbAttr[0], y: vbAttr[1], w: vbAttr[2], h: vbAttr[3] } : { x: 0, y: 0, w, h };
+ if (!(viewBox.w > 0 && viewBox.h > 0)) return null;
+ // Measured live (hidden), at 1 unit a pixel, so the browser resolves every transform and length itself.
+ const host = document.createElement("div");
+ host.setAttribute("aria-hidden", "true");
+ host.style.cssText = "position:fixed;left:-10000px;top:0;width:0;height:0;overflow:hidden;visibility:hidden;pointer-events:none";
+ const live = document.importNode(svg, true) as unknown as SVGSVGElement;
+ live.setAttribute("width", String(viewBox.w));
+ live.setAttribute("height", String(viewBox.h));
+ live.setAttribute("preserveAspectRatio", "none");
+ live.querySelectorAll("script, foreignObject").forEach((e) => e.remove());
+ host.appendChild(live);
+ document.body.appendChild(host);
+ try {
+ const root = live.getScreenCTM();
+ if (!root) return null;
+ const inv = root.inverse();
+ const out: LogoPath[] = [];
+ for (const el of live.querySelectorAll<SVGGeometryElement>(GEOMETRY)) {
+ if (el.closest(SKIP)) continue;
+ const d = pathData(el);
+ if (!d) continue;
+ const screen = el.getScreenCTM();
+ if (!screen) continue;
+ const rel = inv.multiply(screen);
+ let length = 0;
+ try {
+ length = el.getTotalLength();
+ } catch {}
+ if (!(length > 0)) continue;
+ out.push({ d, m: [rel.a, rel.b, rel.c, rel.d, rel.e + viewBox.x, rel.f + viewBox.y], length });
+ if (out.length > 120) return null;
+ }
+ return out.length ? { paths: out, viewBox } : null;
+ } finally {
+ host.remove();
+ }
+}
+
+/** A geometry element as path data. */
+function pathData(el: Element): string | null {
+ const n = (a: string) => parseFloat(el.getAttribute(a) ?? "0") || 0;
+ switch (el.nodeName.toLowerCase()) {
+ case "path":
+ return el.getAttribute("d");
+ case "rect": {
+ const [x, y, w, h] = [n("x"), n("y"), n("width"), n("height")];
+ const r = Math.min(n("rx") || n("ry"), w / 2, h / 2);
+ if (!(w > 0 && h > 0)) return null;
+ return r > 0
+ ? `M${x + r} ${y}H${x + w - r}A${r} ${r} 0 0 1 ${x + w} ${y + r}V${y + h - r}A${r} ${r} 0 0 1 ${x + w - r} ${y + h}H${x + r}A${r} ${r} 0 0 1 ${x} ${y + h - r}V${y + r}A${r} ${r} 0 0 1 ${x + r} ${y}Z`
+ : `M${x} ${y}H${x + w}V${y + h}H${x}Z`;
+ }
+ case "circle":
+ case "ellipse": {
+ const cx = n("cx");
+ const cy = n("cy");
+ const rx = el.nodeName.toLowerCase() === "circle" ? n("r") : n("rx");
+ const ry = el.nodeName.toLowerCase() === "circle" ? n("r") : n("ry");
+ if (!(rx > 0 && ry > 0)) return null;
+ return `M${cx - rx} ${cy}A${rx} ${ry} 0 1 0 ${cx + rx} ${cy}A${rx} ${ry} 0 1 0 ${cx - rx} ${cy}Z`;
+ }
+ case "line":
+ return `M${n("x1")} ${n("y1")}L${n("x2")} ${n("y2")}`;
+ case "polyline":
+ case "polygon": {
+ const pts = (el.getAttribute("points") ?? "").trim().split(/[\s,]+/).map(Number);
+ if (pts.length < 4) return null;
+ let d = `M${pts[0]} ${pts[1]}`;
+ for (let i = 2; i + 1 < pts.length; i += 2) d += `L${pts[i]} ${pts[i + 1]}`;
+ return el.nodeName.toLowerCase() === "polygon" ? `${d}Z` : d;
+ }
+ }
+ return null;
+}
+
+const isSvgUrl = (url: string) => /\.svg($|\?)/i.test(url) || url.startsWith("data:image/svg");
+
+const outlines = new Map<string, Promise<LogoInfo>>();
+
+/** What a scene needs to know of a loaded logo: its size, and for an SVG with outlines, those outlines (read once). */
+export function logoInfoFor(url: string, img: HTMLImageElement): Promise<LogoInfo> {
+ let p = outlines.get(url);
+ if (!p) {
+ p = readLogo(url, img);
+ outlines.set(url, p);
+ }
+ return p;
+}
+
+async function readLogo(url: string, img: HTMLImageElement): Promise<LogoInfo> {
+ if (isSvgUrl(url)) {
+ const lines = await svgOutlines(url).catch(() => null);
+ const w = img.naturalWidth || lines?.viewBox.w || 400;
+ const h = img.naturalHeight || lines?.viewBox.h || 120;
+ if (lines) return { w, h, kind: "svg", paths: lines.paths, viewBox: lines.viewBox };
+ return { w, h, kind: "raster" };
+ }
+ return { w: img.naturalWidth || 400, h: img.naturalHeight || 120, kind: "raster" };
+}
diff --git a/src/components/motion/fonts.ts b/src/components/motion/fonts.ts
new file mode 100644
index 00000000..9f11836f
--- /dev/null
+++ b/src/components/motion/fonts.ts
@@ -0,0 +1,31 @@
+"use client";
+
+import { ensureFont } from "@/components/ads/render";
+
+/**
+ * The brand's fonts, ready to draw with. The preview draws as soon as it can (a fallback face until the brand font
+ * arrives). An export waits for every weight it uses, with the very letters it sets (so accents and other scripts get
+ * their part of the font too), and stops if the font isn't there: a clip is never made in the wrong typeface.
+ */
+
+export const FONT_NOT_LOADED = "Your brand font didn't load. Check your connection and try again.";
+
+const WEIGHTS = [400, 500, 700, 800];
+const SYSTEM = /^(system-ui|arial|helvetica|georgia|times new roman|sans-serif|serif|verdana|tahoma|trebuchet ms|courier new)$/i;
+
+/** Loads `families` (Google Fonts, 400–800); with `strict`, throws FONT_NOT_LOADED unless each is really there. */
+export async function fontsReady(families: (string | undefined)[], opts: { strict?: boolean; text?: string } = {}): Promise<void> {
+ if (typeof document === "undefined") return;
+ const list = [...new Set(families.filter((f): f is string => !!f?.trim()).map((f) => f.trim()))];
+ await Promise.all(list.map((f) => ensureFont(f, opts.strict ? 8000 : 2500)));
+ const sample = opts.text?.trim() || "Aa";
+ await Promise.all(list.flatMap((f) => WEIGHTS.map((w) => document.fonts.load(`${w} 32px "${f}"`, sample).catch(() => []))));
+ if (!opts.strict) return;
+ for (const f of list) {
+ if (SYSTEM.test(f)) continue;
+ // A family with no face at all (its stylesheet didn't come) would "check" fine: look for a loaded face first.
+ const faces = [...document.fonts].filter((face) => face.family.replace(/["']/g, "") === f);
+ if (!faces.some((face) => face.status === "loaded")) throw new Error(FONT_NOT_LOADED);
+ if (!WEIGHTS.every((w) => document.fonts.check(`${w} 32px "${f}"`, sample))) throw new Error(FONT_NOT_LOADED);
+ }
+}
diff --git a/src/components/motion/player.tsx b/src/components/motion/player.tsx
new file mode 100644
index 00000000..5fe4aea0
--- /dev/null
+++ b/src/components/motion/player.tsx
@@ -0,0 +1,301 @@
+"use client";
+
+import { Pause, Play, Repeat } from "lucide-react";
+import { useEffect, useMemo, useRef, useState } from "react";
+import { loadImage, measureText } from "@/components/ads/render";
+import type { Recipe } from "@/lib/motion/recipe";
+import { loadScene } from "@/lib/motion/registry";
+import type { LogoInfo, Scene, ScenePlan } from "@/lib/motion/scene";
+import { previewSize, type SizeSpec } from "@/lib/motion/sizes";
+import { cn } from "@/lib/utils";
+import { drawDisplayList, logoInfoFor, type Sources } from "./draw";
+import { fontsReady } from "./fonts";
+
+/**
+ * The live preview: the same scene code as the export, drawn on every animation frame at an absolute time (a dropped
+ * frame skips ahead, it never slows the motion). It pauses when the tab is hidden or the player is off screen; with
+ * reduced motion it shows the rest frame and waits for Play. Its canvas keeps a small backing store (and drops it a step
+ * on a slow device), which never touches what an export makes.
+ */
+
+export interface MotionInputs {
+ ready: boolean;
+ sources: Sources;
+ logo: LogoInfo | null;
+ /** Bumps when the fonts or the logo arrive (the layout is measured again). */
+ version: number;
+}
+
+const EMPTY_SOURCES: Sources = { images: new Map() };
+
+/** The logo and fonts a recipe needs, loaded (the preview draws with a fallback font until its own arrives). */
+export function useMotionInputs(recipe: Recipe | null): MotionInputs {
+ const logoUrl = recipe?.brand.logo || null;
+ const heading = recipe?.brand.fonts.heading;
+ const body = recipe?.brand.fonts.body;
+ const text = recipe ? Object.values(recipe.fields).join(" ") : "";
+ const [state, setState] = useState<MotionInputs>({ ready: false, sources: EMPTY_SOURCES, logo: null, version: 0 });
+ useEffect(() => {
+ let live = true;
+ void (async () => {
+ const img = logoUrl ? await loadImage(logoUrl).catch(() => null) : null;
+ const logo = img && logoUrl ? await logoInfoFor(logoUrl, img).catch(() => null) : null;
+ await fontsReady([heading, body], { text }).catch(() => undefined);
+ if (!live) return;
+ const images = new Map<string, CanvasImageSource>();
+ if (img) images.set("logo", img);
+ setState((s) => ({ ready: true, sources: { images }, logo, version: s.version + 1 }));
+ })();
+ return () => {
+ live = false;
+ };
+ }, [logoUrl, heading, body, text]);
+ return state;
+}
+
+/** The scene for an id, once loaded. */
+export function useScene(id: string | null): Scene | null {
+ const [scene, setScene] = useState<{ id: string; scene: Scene } | null>(null);
+ useEffect(() => {
+ if (!id) return;
+ let live = true;
+ void loadScene(id).then((s) => live && setScene({ id, scene: s }));
+ return () => {
+ live = false;
+ };
+ }, [id]);
+ return scene && scene.id === id ? scene.scene : null;
+}
+
+/** A scene planned for a recipe (memoised on the recipe and the loaded inputs). */
+export function usePlan(scene: Scene | null, recipe: Recipe | null, inputs: MotionInputs): ScenePlan | null {
+ const key = recipe ? JSON.stringify(recipe) : "";
+ return useMemo(() => {
+ if (!scene || !recipe || !inputs.ready) return null;
+ return scene.plan({ recipe, measure: measureText, logo: inputs.logo });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [scene, key, inputs.version, inputs.ready]);
+}
+
+export function useReducedMotion(): boolean {
+ const [reduced, setReduced] = useState(false);
+ useEffect(() => {
+ const mq = window.matchMedia("(prefers-reduced-motion: reduce)");
+ const on = () => setReduced(mq.matches);
+ on();
+ mq.addEventListener("change", on);
+ return () => mq.removeEventListener("change", on);
+ }, []);
+ return reduced;
+}
+
+interface Stats {
+ frames: number[];
+}
+declare global {
+ interface Window {
+ /** Set by an end-to-end test to read the preview's frame times. */
+ __kineticStats?: Stats;
+ }
+}
+
+const fmt = (t: number) => `${t.toFixed(1)} s`;
+
+export interface MotionPlayerProps {
+ plan: ScenePlan | null;
+ sources: Sources;
+ size: SizeSpec;
+ duration: number;
+ fps: number;
+ /** What the picture shows, for screen readers. */
+ label: string;
+ /** Play, scrub and loop under the picture. */
+ controls?: boolean;
+ /** Small chips animate only while active (hovered or focused); others show their rest frame. */
+ active?: boolean;
+ /** The time shown while inactive (a chip's telling moment); the rest frame by default. */
+ poster?: number;
+ className?: string;
+}
+
+export function MotionPlayer({ plan, sources, size, duration, fps, label, controls = true, active = true, poster, className }: MotionPlayerProps) {
+ const canvasRef = useRef<HTMLCanvasElement>(null);
+ const reduced = useReducedMotion();
+ const [playing, setPlaying] = useState(true);
+ const [loop, setLoop] = useState(true);
+ const [time, setTime] = useState(0);
+ const [visible, setVisible] = useState(true);
+ const [pageShown, setPageShown] = useState(true);
+ const [askedPlay, setAskedPlay] = useState(false);
+ const clock = useRef({ start: 0, from: 0 });
+ const timeRef = useRef(0);
+ const quality = useRef({ scale: 1, steps: 0, slow: [] as number[], fastSince: 0 });
+
+ // Reduced motion: the rest frame until Play is pressed.
+ const moving = playing && active && visible && pageShown && (!reduced || askedPlay) && !!plan;
+
+ useEffect(() => {
+ const el = canvasRef.current;
+ if (!el) return;
+ const io = new IntersectionObserver(([e]) => setVisible(e.isIntersecting), { threshold: 0.01 });
+ io.observe(el);
+ const vis = () => setPageShown(!document.hidden);
+ document.addEventListener("visibilitychange", vis);
+ return () => {
+ io.disconnect();
+ document.removeEventListener("visibilitychange", vis);
+ };
+ }, []);
+
+ /** Draws `t` at the backing size the box and the quality allow. */
+ const draw = (t: number) => {
+ const c = canvasRef.current;
+ if (!c || !plan) return;
+ const max = previewSize(size);
+ const dpr = Math.min(2, typeof window === "undefined" ? 1 : window.devicePixelRatio || 1);
+ const cssW = c.clientWidth || max.w;
+ const w = Math.max(16, Math.round(Math.min(max.w, cssW * dpr) * quality.current.scale));
+ const h = Math.max(16, Math.round((w * plan.design.h) / plan.design.w));
+ if (c.width !== w || c.height !== h) {
+ c.width = w;
+ c.height = h;
+ }
+ const ctx = c.getContext("2d", { alpha: false });
+ if (ctx) drawDisplayList(ctx, plan.evaluate(t), sources);
+ };
+
+ // Still frames: the rest frame (not playing, reduced motion, a chip at rest) or the scrubbed time.
+ useEffect(() => {
+ if (moving || !plan) return;
+ const t = !active ? (poster ?? plan.rest) : reduced && !askedPlay ? plan.rest : timeRef.current;
+ draw(t);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [moving, plan, active, reduced, askedPlay, sources, time, poster]);
+
+ useEffect(() => {
+ if (!moving || !plan) return;
+ let raf = 0;
+ clock.current = { start: performance.now(), from: timeRef.current >= duration ? 0 : timeRef.current };
+ let lastLabel = 0;
+ const tick = (now: number) => {
+ let t = clock.current.from + (now - clock.current.start) / 1000;
+ if (t >= duration) {
+ if (loop) {
+ t %= duration;
+ clock.current = { start: now - t * 1000, from: 0 };
+ } else {
+ t = duration;
+ timeRef.current = t;
+ setTime(t);
+ setPlaying(false);
+ draw(plan.rest);
+ return;
+ }
+ }
+ timeRef.current = t;
+ const t0 = performance.now();
+ draw(t);
+ const spent = performance.now() - t0;
+ window.__kineticStats?.frames.push(spent);
+ // Auto quality: a slow second steps the backing store down (twice at most); three fast seconds step it back.
+ const q = quality.current;
+ q.slow.push(spent);
+ if (q.slow.length >= 60) {
+ const sorted = [...q.slow].sort((a, b) => a - b);
+ const median = sorted[sorted.length >> 1];
+ q.slow = [];
+ if (median > 24 && q.steps < 2) {
+ q.steps++;
+ q.scale *= 0.75;
+ q.fastSince = 0;
+ } else if (median < 12 && q.steps > 0) {
+ q.fastSince ||= now;
+ if (now - q.fastSince > 3000) {
+ q.steps--;
+ q.scale /= 0.75;
+ q.fastSince = 0;
+ }
+ } else q.fastSince = 0;
+ }
+ if (controls && now - lastLabel > 100) {
+ lastLabel = now;
+ setTime(t);
+ }
+ raf = requestAnimationFrame(tick);
+ };
+ raf = requestAnimationFrame(tick);
+ return () => cancelAnimationFrame(raf);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [moving, plan, duration, loop, sources]);
+
+ const frame = 1 / fps;
+ const seek = (t: number) => {
+ const v = Math.min(duration, Math.max(0, t));
+ timeRef.current = v;
+ clock.current = { start: performance.now(), from: v };
+ setTime(v);
+ if (!moving) draw(v);
+ };
+
+ return (
+ <div className={cn("min-w-0", className)}>
+ <canvas
+ ref={canvasRef}
+ role="img"
+ aria-label={label}
+ data-kinetic-player={controls ? "main" : "chip"}
+ className="block h-auto w-full max-w-full rounded-lg bg-muted"
+ style={{ aspectRatio: `${plan?.design.w ?? 9} / ${plan?.design.h ?? 16}` }}
+ />
+ {controls && (
+ <div className="mt-1.5 flex min-w-0 items-center gap-1">
+ <button
+ type="button"
+ onClick={() => {
+ if (moving) {
+ setPlaying(false);
+ return;
+ }
+ setAskedPlay(true);
+ setPlaying(true);
+ }}
+ aria-label={moving ? "Pause" : "Play"}
+ className="grid size-11 shrink-0 place-items-center rounded-full text-foreground outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ {moving ? <Pause className="size-4" /> : <Play className="size-4" />}
+ </button>
+ <input
+ type="range"
+ min={0}
+ max={duration}
+ step={frame}
+ value={Math.min(duration, time)}
+ aria-label="Time"
+ aria-valuetext={fmt(time)}
+ onChange={(e) => {
+ setPlaying(false);
+ seek(Number(e.target.value));
+ }}
+ onKeyDown={(e) => {
+ if (!e.shiftKey || (e.key !== "ArrowLeft" && e.key !== "ArrowRight")) return;
+ e.preventDefault();
+ setPlaying(false);
+ seek(timeRef.current + (e.key === "ArrowRight" ? 1 : -1));
+ }}
+ className="h-11 min-w-0 flex-1 cursor-pointer accent-[var(--brand,currentColor)]"
+ />
+ <span className="w-12 shrink-0 text-right font-mono text-[11px] tabular-nums text-muted-foreground">{fmt(time)}</span>
+ <button
+ type="button"
+ onClick={() => setLoop((v) => !v)}
+ aria-pressed={loop}
+ aria-label="Loop"
+ className={cn("grid size-11 shrink-0 place-items-center rounded-full outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring", loop ? "text-foreground" : "text-muted-foreground/60")}
+ >
+ <Repeat className="size-4" />
+ </button>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/motion/render.ts b/src/components/motion/render.ts
new file mode 100644
index 00000000..140c9ce8
--- /dev/null
+++ b/src/components/motion/render.ts
@@ -0,0 +1,186 @@
+"use client";
+
+import { avcCodec, encodeMp4, encodeVp8, pathVideoType, recordWithMediaRecorder, vp8Supported } from "@/components/cinema/video-encode";
+import { listTravel, type DisplayList } from "@/lib/motion/display";
+import type { Measure } from "@/lib/motion/layout";
+import type { Recipe } from "@/lib/motion/recipe";
+import type { LogoInfo, Scene, ScenePlan } from "@/lib/motion/scene";
+import { exportBitrate, exportSize } from "@/lib/motion/sizes";
+import { frameCount } from "@/lib/motion/time";
+import { drawDisplayList, type Sources } from "./draw";
+
+/**
+ * A Kinetic Motion clip rendered in the browser, frame-exact: frame i is the scene at t = i / fps, drawn at the export
+ * size with motion blur (several moments inside the shutter, blended; never across a cut, and a held frame is drawn
+ * once), then encoded with WebCodecs: H.264 into MP4, else VP8 into WebM where the caller allows it, else the real-time
+ * recorder where it allows that. The result is a file to save to Fuobe (save.ts), never a download.
+ */
+
+export type AnyCanvas = HTMLCanvasElement | OffscreenCanvas;
+type Ctx = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;
+
+export const SHORTEN_MESSAGE = "Shorten the words to fit, then render again.";
+export const NO_ENCODER_MESSAGE = "This browser can't make this video. Try Chrome or Edge.";
+
+export interface RenderOptions {
+ sources: Sources;
+ logo: LogoInfo | null;
+ measure: Measure;
+ signal?: AbortSignal;
+ /** After each frame: how many are done, of how many, and the frame just drawn. */
+ onProgress?: (done: number, total: number, frame: AnyCanvas) => void;
+ /** The containers allowed, best first (default MP4, then WebM). */
+ formats?: ("mp4" | "webm")[];
+ /** Allow the real-time recorder when WebCodecs can't (it may drop a frame). */
+ recorder?: boolean;
+}
+
+export interface RenderResult {
+ blob: Blob;
+ type: string;
+ frames: number;
+ /** A PNG of the frame everything rests on. */
+ poster: Blob;
+ width: number;
+ height: number;
+ encoder: "webcodecs" | "recorder";
+}
+
+function canvas(w: number, h: number): AnyCanvas {
+ if (typeof OffscreenCanvas !== "undefined") return new OffscreenCanvas(w, h);
+ return Object.assign(document.createElement("canvas"), { width: w, height: h });
+}
+
+const ctx2d = (c: AnyCanvas) => c.getContext("2d", { alpha: false }) as Ctx;
+
+export async function toPng(c: AnyCanvas): Promise<Blob> {
+ if ("convertToBlob" in c) return c.convertToBlob({ type: "image/png" });
+ return new Promise((resolve, reject) => (c as HTMLCanvasElement).toBlob((b) => (b ? resolve(b) : reject(new Error("Couldn't save the frame"))), "image/png"));
+}
+
+/** The moments blended into frame `t` (sub-frame times and weights), kept on t's side of every cut. */
+export function shutterSamples(t: number, fps: number, samples: number, shutter: number, duration: number, cuts: number[]): { t: number; w: number }[] {
+ if (samples <= 1 || shutter <= 0) return [{ t, w: 1 }];
+ const open = shutter / 360 / fps;
+ const out: { t: number; w: number }[] = [];
+ for (let j = 0; j < samples; j++) {
+ const u = j / (samples - 1);
+ let s = t + (u - 0.5) * open;
+ for (const c of cuts) {
+ if (t < c && s >= c) s = c - 1e-6;
+ if (t >= c && s < c) s = c;
+ }
+ s = Math.min(duration, Math.max(0, s));
+ out.push({ t: s, w: 1 - Math.abs(2 * u - 1) * 0.75 });
+ }
+ return out;
+}
+
+/** The most motion-blur samples a frame takes (a very fast edge). */
+export const MAX_BLUR_SAMPLES = 48;
+
+/**
+ * How many moments to blend into a frame whose fastest edge travels `travel` export pixels while the shutter is open:
+ * one for a frame that barely moves, else enough that neighbouring moments sit about 2.5 px apart (never fewer than
+ * the recipe asks for, never more than MAX_BLUR_SAMPLES), so a fast edge reads as a smooth smear, not steps.
+ */
+export function blurSamples(travel: number, base: number): number {
+ if (base <= 1 || travel < 1) return 1;
+ return Math.max(base, Math.min(MAX_BLUR_SAMPLES, Math.ceil(travel / 2.5) + 1));
+}
+
+/** Draws frame `t` of `plan` onto `target`, blending the shutter's moments through `scratch`. */
+export function drawFrame(plan: ScenePlan, t: number, target: AnyCanvas, scratch: AnyCanvas, sources: Sources, o: { fps: number; samples: number; shutter: number; duration: number }): void {
+ const tc = ctx2d(target);
+ const half = o.shutter / 360 / o.fps / 2;
+ if (o.samples <= 1 || (plan.still(t - half) && plan.still(t))) {
+ drawDisplayList(tc, plan.evaluate(t), sources);
+ return;
+ }
+ // As many moments as this frame's motion needs, measured across the open shutter.
+ const ends = shutterSamples(t, o.fps, 2, o.shutter, o.duration, plan.cuts);
+ const first = plan.evaluate(ends[0].t);
+ const travel = listTravel(first, plan.evaluate(ends[1].t)) * (target.width / first.w);
+ const samples = blurSamples(travel, o.samples);
+ if (samples <= 1) {
+ drawDisplayList(tc, plan.evaluate(t), sources);
+ return;
+ }
+ const sc = ctx2d(scratch);
+ let total = 0;
+ for (const s of shutterSamples(t, o.fps, samples, o.shutter, o.duration, plan.cuts)) {
+ const list: DisplayList = plan.evaluate(s.t);
+ total += s.w;
+ if (total === s.w) {
+ drawDisplayList(tc, list, sources);
+ continue;
+ }
+ drawDisplayList(sc, list, sources);
+ tc.save();
+ tc.setTransform(1, 0, 0, 1, 0, 0);
+ tc.globalCompositeOperation = "source-over";
+ tc.globalAlpha = s.w / total;
+ tc.drawImage(scratch, 0, 0);
+ tc.restore();
+ }
+}
+
+/** Renders the whole clip (see the file's comment). Throws SHORTEN_MESSAGE when a typed field doesn't fit. */
+export async function renderClip(scene: Scene, recipe: Recipe, o: RenderOptions): Promise<RenderResult> {
+ const plan = scene.plan({ recipe, measure: o.measure, logo: o.logo });
+ if (plan.overflow.length) throw new Error(SHORTEN_MESSAGE);
+ const { w, h } = exportSize(recipe.size);
+ // H.264 wants even sides.
+ const W = w - (w % 2);
+ const H = h - (h % 2);
+ const n = frameCount(recipe.duration, recipe.fps);
+ const bitrate = recipe.export.bitrate ?? exportBitrate(recipe.size, recipe.duration);
+ const target = canvas(W, H);
+ const scratch = canvas(W, H);
+ const opts = { fps: recipe.fps, samples: recipe.export.blurSamples, shutter: recipe.export.shutter, duration: recipe.duration };
+ const frame = (i: number) => {
+ drawFrame(plan, i / recipe.fps, target, scratch, o.sources, opts);
+ o.onProgress?.(i + 1, n, target);
+ return target;
+ };
+ const formats = o.formats ?? ["mp4", "webm"];
+ let blob: Blob | null = null;
+ let type = "";
+ let encoder: RenderResult["encoder"] = "webcodecs";
+ for (const f of formats) {
+ if (f === "mp4") {
+ const codec = await avcCodec(W, H, recipe.fps, bitrate);
+ if (!codec) continue;
+ const bytes = await encodeMp4(codec, n, W, H, recipe.fps, frame, { bitrate, signal: o.signal });
+ blob = new Blob([bytes as BlobPart], { type: "video/mp4" });
+ type = "video/mp4";
+ break;
+ }
+ if (f === "webm" && (await vp8Supported(W, H, recipe.fps))) {
+ const [bytes] = await encodeVp8(n, W, H, recipe.fps, 1, (i) => [frame(i)], { bitrate, signal: o.signal });
+ blob = new Blob([bytes as BlobPart], { type: "video/webm" });
+ type = "video/webm";
+ break;
+ }
+ }
+ if (!blob && o.recorder) {
+ const rec = pathVideoType();
+ if (rec) {
+ const [b] = await recordWithMediaRecorder(rec, n, W, H, recipe.fps, 1, (i) => {
+ const c = frame(i);
+ return [ctx2d(c).getImageData(0, 0, W, H)];
+ });
+ blob = b;
+ type = rec.split(";")[0];
+ encoder = "recorder";
+ }
+ }
+ if (!blob) throw new Error(NO_ENCODER_MESSAGE);
+ if (o.signal?.aborted) throw new DOMException("The render was stopped", "AbortError");
+ drawDisplayList(ctx2d(target), plan.evaluate(plan.rest), o.sources);
+ const poster = await toPng(target);
+ return { blob, type, frames: n, poster, width: W, height: H, encoder };
+}
+
+/** Whether this browser can encode an MP4 of this size (the cloud end card needs one). */
+export const canMakeMp4 = (w: number, h: number, fps: number) => avcCodec(w - (w % 2), h - (h % 2), fps).then((c) => !!c);
diff --git a/src/components/motion/save.ts b/src/components/motion/save.ts
new file mode 100644
index 00000000..a97d5f51
--- /dev/null
+++ b/src/components/motion/save.ts
@@ -0,0 +1,126 @@
+"use client";
+
+import { useQueryClient } from "@tanstack/react-query";
+import { useRouter } from "next/navigation";
+import { useCallback, useRef, useState } from "react";
+import { toast } from "sonner";
+import { uploadFile, useAskBeforeUpload, useIsAccount } from "@/lib/api";
+import type { Generation } from "@/lib/catalog/types";
+import { recipeKey, type Recipe } from "@/lib/motion/recipe";
+import { responseError, toastError } from "@/lib/refusals";
+
+/**
+ * Everything made here goes through Fuobe: a finished render is uploaded (POST /api/uploads, the same rule as any
+ * upload: the owner, or an account with its own GPU or key) and recorded as a Kinetic Motion result (POST
+ * /api/generations/local), which shows in the Library (the owner's) or the account's own runs at once. The person
+ * downloads it from there, never straight from the page.
+ */
+
+export const MOTION_MODEL = "local-motion";
+
+export interface MotionResult {
+ blob: Blob;
+ type: string;
+ /** Its last frame (a PNG): the saved clip's tile shows it. */
+ poster?: Blob;
+}
+
+export interface SaveMeta {
+ recipe: Recipe;
+ feature: string;
+ title: string;
+ /** The typed words, joined (what the Library shows and searches). */
+ prompt: string;
+ /** The person's own stored files the clip was made from (logo, product). */
+ images?: string[];
+}
+
+/** Uploads a rendered clip and records it as a result; returns the result. */
+export async function saveMotionResult(clip: MotionResult, meta: SaveMeta): Promise<Generation> {
+ const ext = clip.type === "video/webm" ? "webm" : "mp4";
+ const [asset, poster] = await Promise.all([
+ uploadFile(new File([clip.blob], `kinetic-motion.${ext}`, { type: clip.type })),
+ clip.poster ? uploadFile(new File([clip.poster], "kinetic-motion.png", { type: "image/png" })).catch(() => null) : null,
+ ]);
+ const images = (meta.images ?? []).filter((u) => u.startsWith("/api/files/")).slice(0, 4);
+ const res = await fetch("/api/generations/local", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ feature: meta.feature,
+ modelId: MOTION_MODEL,
+ op: "motion",
+ prompt: meta.prompt.slice(0, 2000),
+ title: meta.title.slice(0, 200),
+ inputs: images.length ? { images } : {},
+ params: { extra: { motion: meta.recipe } },
+ output: { url: asset.url, kind: "video", contentType: asset.contentType, ...(poster && { meta: { poster: poster.url } }) },
+ }),
+ });
+ const body = (await res.json().catch(() => ({}))) as Generation & { error?: string };
+ if (!res.ok) throw responseError(res, body.error ?? "Couldn't save it. Try again.");
+ return body;
+}
+
+export type SavePhase = { kind: "idle" } | { kind: "rendering"; done: number; total: number } | { kind: "saving" } | { kind: "saved"; id: string };
+
+/**
+ * Render-then-save for a page: asks first whoever couldn't save (a guest: "Create a free account"; an account with no
+ * GPU or key: "Connect your GPU"), before anything renders. A look saves once per visit; a failed save keeps the
+ * rendered clip, so Try again uploads without rendering again.
+ */
+export function useMotionSave() {
+ const qc = useQueryClient();
+ const ask = useAskBeforeUpload();
+ const router = useRouter();
+ const account = useIsAccount();
+ const [phase, setPhase] = useState<SavePhase>({ kind: "idle" });
+ const rendered = useRef<{ key: string; clip: MotionResult } | null>(null);
+ const saved = useRef(new Map<string, string>());
+ const abort = useRef<AbortController | null>(null);
+
+ const save = useCallback(
+ async (meta: SaveMeta, render: (signal: AbortSignal, progress: (done: number, total: number) => void) => Promise<MotionResult>): Promise<Generation | null> => {
+ if (ask()) return null;
+ const key = recipeKey(meta.recipe);
+ if (saved.current.has(key)) {
+ toast(account ? "Already saved to your runs" : "Already saved to your Library", { action: { label: "Open", onClick: () => router.push("/library") } });
+ return null;
+ }
+ const ctl = new AbortController();
+ abort.current = ctl;
+ try {
+ let clip = rendered.current?.key === key ? rendered.current.clip : null;
+ if (!clip) {
+ setPhase({ kind: "rendering", done: 0, total: 1 });
+ clip = await render(ctl.signal, (done, total) => setPhase({ kind: "rendering", done, total }));
+ rendered.current = { key, clip };
+ }
+ setPhase({ kind: "saving" });
+ const g = await saveMotionResult(clip, meta);
+ saved.current.set(key, g.id);
+ setPhase({ kind: "saved", id: g.id });
+ void qc.invalidateQueries({ queryKey: ["generations"] });
+ toast.success(account ? "Saved to your runs" : "Saved to your Library", { action: { label: "Open", onClick: () => router.push("/library") } });
+ return g;
+ } catch (e) {
+ setPhase({ kind: "idle" });
+ if ((e as Error).name !== "AbortError") toastError(e, "Couldn't save it. Try again.");
+ return null;
+ } finally {
+ if (abort.current === ctl) abort.current = null;
+ }
+ },
+ [ask, account, qc, router],
+ );
+
+ const cancel = useCallback(() => abort.current?.abort(), []);
+ return { save, cancel, phase, label: account ? "Save to your runs" : "Save to Library" };
+}
+
+/** "Rendering 42 of 75", "Saving…", or null. */
+export function phaseLine(p: SavePhase): string | null {
+ if (p.kind === "rendering") return `Rendering ${p.done} of ${p.total}`;
+ if (p.kind === "saving") return "Saving…";
+ return null;
+}
diff --git a/src/components/motion/variant-picker.tsx b/src/components/motion/variant-picker.tsx
new file mode 100644
index 00000000..add99651
--- /dev/null
+++ b/src/components/motion/variant-picker.tsx
@@ -0,0 +1,62 @@
+"use client";
+
+import { useState } from "react";
+import type { Recipe } from "@/lib/motion/recipe";
+import { cn } from "@/lib/utils";
+import { MotionPlayer, usePlan, useScene, type MotionInputs } from "./player";
+
+/**
+ * A grid of looks to choose from, each a small live preview of its own: the chip under the pointer or the focus plays,
+ * the others show the moment that sets their look apart (one moves at a time). "Still" keeps the card as a picture.
+ * Three to a row on a phone, all in one row from a small tablet up: every choice is in view, nothing scrolls.
+ */
+
+export interface VariantChoice {
+ id: string;
+ label: string;
+ /** The scene that plays on the chip (Still shows a scene's rest frame). */
+ scene: string;
+ still?: boolean;
+}
+
+function Chip({ choice, recipe, inputs, selected, active, onPick, onActive }: { choice: VariantChoice; recipe: Recipe; inputs: MotionInputs; selected: boolean; active: boolean; onPick: () => void; onActive: (on: boolean) => void }) {
+ const scene = useScene(choice.scene);
+ const plan = usePlan(scene, recipe, inputs);
+ return (
+ <button
+ type="button"
+ aria-pressed={selected}
+ onClick={onPick}
+ onMouseEnter={() => onActive(true)}
+ onMouseLeave={() => onActive(false)}
+ onFocus={() => onActive(true)}
+ onBlur={() => onActive(false)}
+ className={cn("flex min-h-11 min-w-0 flex-col items-center gap-1 rounded-xl p-1 text-center outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring", selected && "bg-brand-faint ring-2 ring-primary")}
+ >
+ <MotionPlayer
+ plan={plan}
+ sources={inputs.sources}
+ size={recipe.size}
+ duration={recipe.duration}
+ fps={recipe.fps}
+ label={`${choice.label} end card`}
+ controls={false}
+ active={active && !choice.still}
+ poster={choice.still ? undefined : plan?.signature}
+ className="w-full max-w-[76px]"
+ />
+ <span className="block w-full truncate text-[11px] font-medium leading-4">{choice.label}</span>
+ </button>
+ );
+}
+
+export function VariantPicker({ choices, value, onChange, recipeFor, inputs, label }: { choices: VariantChoice[]; value: string; onChange: (id: string) => void; recipeFor: (scene: string) => Recipe; inputs: MotionInputs; label: string }) {
+ const [active, setActive] = useState<string | null>(null);
+ return (
+ <div role="group" aria-label={label} className="grid min-w-0 grid-cols-3 gap-1.5 py-1 sm:grid-cols-6">
+ {choices.map((c) => (
+ <Chip key={c.id} choice={c} recipe={recipeFor(c.scene)} inputs={inputs} selected={value === c.id} active={active === c.id} onPick={() => onChange(c.id)} onActive={(on) => setActive((a) => (on ? c.id : a === c.id ? null : a))} />
+ ))}
+ </div>
+ );
+}
diff --git a/src/lib/catalog/marketing.ts b/src/lib/catalog/marketing.ts
index 55c83bfa..b2d5748b 100644
--- a/src/lib/catalog/marketing.ts
+++ b/src/lib/catalog/marketing.ts
@@ -587,7 +587,8 @@ export const CLICK_TO_AD = { aspect: "9:16", maxSeconds: 12, shots: 3 } as const
/**
* The card is drawn in the browser (brand colour, logo, product name, CTA; components/marketing/end-card.ts)
* at the ad's 9:16 size, then held for 2–3 s: a gentle push-in on the cloud (fal image-to-video, zoom 1 → 1.05),
- * a still on the open engine. Without a drawn card the cloud puts the logo on the brand colour itself.
+ * a still on the open engine. Without a drawn card the cloud puts the logo on the brand colour itself. An animated
+ * card (Kinetic Motion's end-card styles, rendered in the browser) arrives as a clip and is joined as it is.
*/
export const END_CARD = { seconds: 2.5, minSeconds: 2, maxSeconds: 3, zoomTo: 1.05, fps: 24, size: { w: 720, h: 1280 }, cta: "Shop now" } as const;
@@ -610,6 +611,11 @@ export interface EndCardInput {
ad: string;
/** The card the page drew (/api/files/…). */
card?: string;
+ /**
+ * The animated card the page rendered (/api/files/… MP4, or WebM on the open engine): used as it is, in place of
+ * the still and its push-in.
+ */
+ clip?: string;
/** Cloud, no drawn card: the brand-colour background and the logo overlay-image puts on it. */
background?: string;
logo?: string;
@@ -634,15 +640,33 @@ export interface EndCardInput {
* The steps that make the end card and put it after the ad, and the key of the finished video. Cloud:
* [overlay-image: the logo on the brand colour →] ken-burns (zoom 1 → 1.05) → a silent sound track under it
* (merge-audio-video) → merge-videos after the ad. Open: video-append-endcard (the ad's sound kept, padded with
- * silence under the card), or still-to-clip + oss-join-sound1 for a clip the open engine didn't make.
+ * silence under the card), or still-to-clip + oss-join-sound1 for a clip the open engine didn't make. An animated card
+ * (a clip rendered in the page) goes through oss-join-sound1 with the ad, which re-encodes the ad at 25 fps.
*/
export function endCardSteps(o: EndCardInput): { steps: EndCardStep[]; final: string } {
const seconds = Math.max(END_CARD.minSeconds, Math.min(END_CARD.maxSeconds, o.seconds ?? END_CARD.seconds));
const result = { feature: o.feature, title: o.title, batchTitle: o.title };
const helper = { feature: `${o.feature}-step` };
if (o.engine === "open") {
- if (!o.card) throw new Error("The open engine needs the end card drawn on the page — turn End card off, or make the ad from Click to Ad");
const M = END_CARD_MODELS.open;
+ // The animated card: joined after the ad (put first by the chain), keeping the ad's sound with silence under the card.
+ // Unlike the still card's append (which copies the ad's picture), this join re-encodes the ad too, at 25 fps and the
+ // run's resolution: a small generation loss on the ad itself. Not yet run end to end on a GPU (unit-tested plan only).
+ if (o.clip) {
+ return {
+ final: "endcard",
+ steps: [
+ {
+ key: "endcard",
+ label: "Adding the end card",
+ request: { ...result, modelId: M.join, op: "concat", prompt: o.title, inputs: { videos: [o.clip] }, params: { aspectRatio: o.aspectRatio, ...(o.resolution && { resolution: o.resolution }) } },
+ after: [o.ad],
+ chain: [{ slot: "videos", position: "first" }],
+ },
+ ],
+ };
+ }
+ if (!o.card) throw new Error("The open engine needs the end card drawn on the page — turn End card off, or make the ad from Click to Ad");
if ((o.adEncodedBy ?? "comfyui") === "comfyui") {
return {
final: "endcard",
@@ -674,6 +698,18 @@ export function endCardSteps(o: EndCardInput): { steps: EndCardStep[]; final: st
const M = END_CARD_MODELS.cloud;
if (!o.silence) throw new Error("The end card needs its silent sound track");
const steps: EndCardStep[] = [];
+ if (o.clip) {
+ // The animated card is the clip: it only needs its silent track (it can start at once, beside the ad), then the join.
+ steps.push({ key: "endcardSound", label: "End card sound", request: { ...helper, modelId: M.sound, op: "mux", inputs: { video: o.clip, audio: o.silence } } });
+ steps.push({
+ key: "endcard",
+ label: "Adding the end card",
+ request: { ...result, modelId: M.join, op: "concat", prompt: o.title, params: { aspectRatio: o.aspectRatio } },
+ after: [o.ad, "endcardSound"],
+ chain: [{ slot: "videos" }, { slot: "videos" }],
+ });
+ return { steps, final: "endcard" };
+ }
if (!o.card) {
if (!o.background || !o.logo) throw new Error("Add a logo to the brand kit for the end card, or turn End card off");
steps.push({ key: "endcardArt", label: "End card", request: { ...helper, modelId: M.art, op: "overlay", inputs: { images: [o.background, o.logo] }, params: { position: { x: 0.5, y: 0.45 }, scale: 1 } } });
@@ -1121,6 +1157,9 @@ export interface MarketingRunMeta {
input?: Record<string, unknown>;
/** Click to Ad: the logo end card it ends on (the card the page drew; null: the kit's logo on its colour). */
endCard?: string | null;
+ /** Click to Ad: the animated end card it ends on, and its style (none: the still card). */
+ endCardClip?: string | null;
+ endCardVariant?: string | null;
}
export interface MarketingRun {
diff --git a/src/lib/catalog/models.ts b/src/lib/catalog/models.ts
index 4d647514..0ecdc1d1 100644
--- a/src/lib/catalog/models.ts
+++ b/src/lib/catalog/models.ts
@@ -2689,6 +2689,20 @@ const local: ModelDef[] = [
options: {},
hidden: true,
},
+ // Kinetic Motion: motion graphics (an animated end card, text templates) drawn by code in the brand's fonts and
+ // colours, rendered and encoded in the browser, then saved like any result.
+ {
+ id: "local-motion",
+ name: "Kinetic Motion",
+ vendor: "Fuobe",
+ family: "local",
+ engine: "open",
+ kind: "video",
+ tagline: "Motion graphics drawn in your browser in your brand fonts",
+ routes: [{ op: "motion", provider: "local", endpoint: "canvas" }],
+ options: {},
+ hidden: true,
+ },
// Marketing joins that keep the voice (UGC presenter, Click to Ad, Ad Multiplier): oss-join-clips drops every
// soundtrack and plays all frames at one rate, so a 25 fps presenter joined to 16 fps Wan clips came out silent
// and slowed down. These resample every clip to 25 fps and keep one clip's own sound.
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index c1d95959..9de06de7 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -40,6 +40,7 @@ export type Operation =
| "extend" // video → the same clip, continued
| "grade" // colour grade, rendered in the browser
| "relight" // the Relight tool's blend of a photo and its relit picture, rendered in the browser
+ | "motion" // motion graphics, rendered in the browser
| "reframe" // video → same video at a new aspect ratio (AI-filled edges)
| "finalize" // draft video → full-quality render of the same take
| "dialogue" // several speakers → one audio track
@@ -126,6 +127,7 @@ export const OPERATION_LABELS: Record<Operation, string> = {
extend: "Extend video",
grade: "Color grade",
relight: "Relight",
+ motion: "Motion graphics",
reframe: "Reframe",
finalize: "Final render",
dialogue: "Dialogue",
@@ -207,6 +209,7 @@ export const OPERATION_OUTPUT: Record<Operation, MediaKind> = {
extend: "video",
grade: "image",
relight: "image",
+ motion: "video",
reframe: "video",
finalize: "video",
dialogue: "audio",
diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.ts
index 46118e22..712043b0 100644
--- a/src/lib/guest-access.ts
+++ b/src/lib/guest-access.ts
@@ -123,7 +123,6 @@ const LIBRARY_CHANGES: [methods: string, path: RegExp][] = [
["PATCH DELETE", /^\/api\/folders\/[^/]+$/],
["PATCH DELETE", /^\/api\/generations\/[^/]+$/],
// (POST /api/generations/bulk goes to the route, which takes an account's likes, pins and reviews of its own runs only.)
- ["POST", /^\/api\/generations\/local$/],
["POST", /^\/api\/generations\/[^/]+\/(cancel|finish)$/],
["DELETE", /^\/api\/generations\/trash$/],
["DELETE", /^\/api\/assets\/[^/]+$/],
@@ -190,7 +189,8 @@ const GPU_READS = new Set(["/api/gpu/readiness", "/api/gpu/badges", "/api/gpu/pl
/**
* A change an account may send: signing out, its own GPU and its check, its own fal.ai and Replicate keys, price checks
* (reads go by guestRead, as a guest's), an upload (the route checks it: src/app/api/uploads, which the proxy's matcher
- * leaves out) and a look at its own clip's header (the route reads only its own files).
+ * leaves out), a look at its own clip's header (the route reads only its own files), and a result it made in its
+ * browser (POST /api/generations/local: the route takes its own Kinetic Motion clips only).
*/
export function accountMayChange(method: string, pathname: string, search: string): boolean {
if (method === "POST" && pathname === "/api/auth/logout") return true;
@@ -206,6 +206,9 @@ export function accountMayChange(method: string, pathname: string, search: strin
if (method === "POST" && (pathname === "/api/reports" || pathname === "/api/billing/interest")) return true;
// Like, pin or review many of its own runs at once (the route checks each is its own, and refuses the rest).
if (method === "POST" && pathname === "/api/generations/bulk") return true;
+ // A Kinetic Motion clip it rendered in its browser and uploaded, recorded as its own run (the route checks the files
+ // are its own, its run rate and the studio's checks; a grade or a Relight blend stays the owner's there).
+ if (method === "POST" && pathname === "/api/generations/local") return true;
return isPriceCheck(method, pathname, search);
}
diff --git a/src/lib/motion/camera2d.ts b/src/lib/motion/camera2d.ts
new file mode 100644
index 00000000..a8e14f7b
--- /dev/null
+++ b/src/lib/motion/camera2d.ts
@@ -0,0 +1,87 @@
+/**
+ * The 2.5D camera (pure): pan, zoom and roll over flat layers, with parallax by depth. A layer at depth z (0: the focus
+ * plane; more: farther away) moves and scales by focal / (focal + z), so near layers slide past far ones. Moves come
+ * from keys or a preset; a shake is seeded noise, for impacts only. Every layer keeps covering the frame (4 % overscan).
+ */
+
+import { about, multiply, translate, type Matrix } from "./display";
+import { noise1 } from "./random";
+import { sample, type Key } from "./tween";
+import { local } from "./time";
+import { curve, type CurveName } from "./ease";
+
+export interface Camera {
+ /** Pan, in design units. */
+ x: number;
+ y: number;
+ zoom: number;
+ /** Radians. */
+ roll: number;
+ focal: number;
+}
+
+export const REST_CAMERA: Camera = { x: 0, y: 0, zoom: 1, roll: 0, focal: 1000 };
+
+export type CameraPreset = "still" | "push-in" | "drift" | "rise" | "orbit-2d";
+
+export interface CameraMove {
+ preset?: CameraPreset;
+ /** Or keys per channel. */
+ keys?: Partial<Record<"x" | "y" | "zoom" | "roll", Key[]>>;
+ /** The window the preset plays in (seconds). */
+ from?: number;
+ to?: number;
+ curve?: CurveName;
+ /** Zoom at the start of the window, for push-in (default 1 → 1.06). */
+ zoomFrom?: number;
+ zoomTo?: number;
+ shake?: { amplitude: number; frequency: number; from: number; to: number; seed: number };
+}
+
+/** The camera at `t` for a frame `w` units wide. */
+export function cameraAt(move: CameraMove, t: number, w: number): Camera {
+ const cam = { ...REST_CAMERA };
+ const p = move.from !== undefined && move.to !== undefined ? curve(move.curve ?? "move")(local(t, move.from, move.to)) : 0;
+ switch (move.preset) {
+ case "push-in":
+ cam.zoom = (move.zoomFrom ?? 1) + ((move.zoomTo ?? 1.06) - (move.zoomFrom ?? 1)) * p;
+ break;
+ case "drift":
+ cam.x = (p - 0.5) * 0.02 * w;
+ break;
+ case "rise":
+ cam.y = (0.5 - p) * 0.02 * w;
+ break;
+ case "orbit-2d":
+ cam.roll = (p - 0.5) * 0.02;
+ cam.x = (p - 0.5) * 0.015 * w;
+ break;
+ }
+ if (move.keys) {
+ for (const k of ["x", "y", "zoom", "roll"] as const) {
+ const keys = move.keys[k];
+ if (keys?.length) cam[k] = sample(keys, t);
+ }
+ }
+ const s = move.shake;
+ if (s && t >= s.from && t < s.to) {
+ const fade = 1 - local(t, s.from, s.to);
+ cam.x += noise1(s.seed, "shake-x", t * s.frequency) * s.amplitude * fade;
+ cam.y += noise1(s.seed, "shake-y", t * s.frequency) * s.amplitude * fade;
+ }
+ return cam;
+}
+
+/**
+ * The transform a layer at depth `z` gets under `cam`, in a frame w × h. Zooms about the centre, then pans; the scale
+ * never drops below the overscan that keeps a full-frame layer covering the frame while it moves.
+ */
+export function layerMatrix(cam: Camera, z: number, w: number, h: number, coverFrame = false): Matrix {
+ const depth = cam.focal / (cam.focal + z);
+ let scale = 1 + (cam.zoom - 1) * depth;
+ if (coverFrame) {
+ const need = 1 + (2 * Math.max(Math.abs(cam.x * depth) / w, Math.abs(cam.y * depth) / h)) + Math.abs(cam.roll) * 0.6;
+ scale = Math.max(scale, Math.min(1.04, need));
+ }
+ return multiply(translate(-cam.x * depth, -cam.y * depth), about(w / 2, h / 2, scale, cam.roll * depth));
+}
diff --git a/src/lib/motion/display.ts b/src/lib/motion/display.ts
new file mode 100644
index 00000000..1c0c0e7e
--- /dev/null
+++ b/src/lib/motion/display.ts
@@ -0,0 +1,279 @@
+/**
+ * The display list (pure data): what a scene draws at one instant, with every number already resolved for that time.
+ * Scenes build it; src/components/motion/draw.ts is the only code that turns it into canvas calls, for the preview, the
+ * export and the covers alike. Coordinates are design units (1080 on the frame's short side); the drawer scales.
+ */
+
+/** A 2D affine matrix [a, b, c, d, e, f] (canvas setTransform order). */
+export type Matrix = [number, number, number, number, number, number];
+
+export const IDENTITY: Matrix = [1, 0, 0, 1, 0, 0];
+
+export const multiply = (m: Matrix, n: Matrix): Matrix => [
+ m[0] * n[0] + m[2] * n[1],
+ m[1] * n[0] + m[3] * n[1],
+ m[0] * n[2] + m[2] * n[3],
+ m[1] * n[2] + m[3] * n[3],
+ m[0] * n[4] + m[2] * n[5] + m[4],
+ m[1] * n[4] + m[3] * n[5] + m[5],
+];
+
+export const translate = (x: number, y: number): Matrix => [1, 0, 0, 1, x, y];
+
+/** Scale `s` (and rotate `rot` radians) about the point (cx, cy). */
+export function about(cx: number, cy: number, s: number, rot = 0, sy = s): Matrix {
+ const c = Math.cos(rot);
+ const n = Math.sin(rot);
+ const m: Matrix = [s * c, s * n, -sy * n, sy * c, 0, 0];
+ m[4] = cx - (m[0] * cx + m[2] * cy);
+ m[5] = cy - (m[1] * cx + m[3] * cy);
+ return m;
+}
+
+export const isIdentity = (m?: Matrix) => !m || (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1 && m[4] === 0 && m[5] === 0);
+
+export interface GradientStop {
+ at: number;
+ color: string;
+}
+export type Gradient =
+ | { kind: "linear"; x0: number; y0: number; x1: number; y1: number; stops: GradientStop[] }
+ | { kind: "radial"; cx: number; cy: number; r0: number; r1: number; stops: GradientStop[] };
+export type Paint = string | Gradient;
+
+export interface Stroke {
+ paint: Paint;
+ width: number;
+ /** How much of the outline is drawn, from its start (0–1). */
+ trim?: number;
+ /** The outline's length, when the scene knows it (else the drawer measures the path). */
+ length?: number;
+ cap?: CanvasLineCap;
+ join?: CanvasLineJoin;
+}
+
+export type Blend = "source-over" | "multiply" | "screen" | "overlay" | "lighter" | "source-atop";
+
+export type ClipShape = { type: "rect"; x: number; y: number; w: number; h: number; r?: number } | { type: "ellipse"; cx: number; cy: number; rx: number; ry: number };
+
+export interface GroupNode {
+ type: "group";
+ id?: string;
+ transform?: Matrix;
+ opacity?: number;
+ blend?: Blend;
+ clip?: ClipShape;
+ /** A gaussian blur in design units on everything inside (skipped where the canvas can't filter). */
+ blur?: number;
+ /**
+ * Drawn on a layer of its own (the bounds given), then put down as one: needed when a child blends with its
+ * siblings only ("source-atop" glints that must stay on the logo).
+ */
+ isolate?: { x: number; y: number; w: number; h: number };
+ /** A soft wipe: only what lies where the gradient is opaque shows (drawn on its own layer). */
+ mask?: Gradient & { bounds: { x: number; y: number; w: number; h: number } };
+ children: DisplayNode[];
+}
+
+export interface RectNode {
+ type: "rect";
+ id?: string;
+ x: number;
+ y: number;
+ w: number;
+ h: number;
+ r?: number;
+ fill?: Paint;
+ stroke?: Stroke;
+ opacity?: number;
+}
+
+export interface EllipseNode {
+ type: "ellipse";
+ id?: string;
+ cx: number;
+ cy: number;
+ rx: number;
+ ry: number;
+ fill?: Paint;
+ stroke?: Stroke;
+ opacity?: number;
+}
+
+export interface PathNode {
+ type: "path";
+ id?: string;
+ /** SVG path data. */
+ d: string;
+ transform?: Matrix;
+ fill?: Paint;
+ stroke?: Stroke;
+ opacity?: number;
+}
+
+/** One drawn piece of a typed field: a line, a word or a letter, placed. */
+export interface TextRun {
+ text: string;
+ /** The typed whitespace before it (not drawn; spelling checks join gap + text). */
+ gap: string;
+ font: string;
+ /** Left edge and top of the glyph box (textBaseline "top"). */
+ x: number;
+ y: number;
+ fill: Paint;
+ dir?: "ltr" | "rtl";
+ opacity?: number;
+ transform?: Matrix;
+}
+
+export interface TextNode {
+ type: "text";
+ /** The field it sets ("headline", "cta"…). */
+ field: string;
+ runs: TextRun[];
+ opacity?: number;
+}
+
+export interface ImageNode {
+ type: "image";
+ id?: string;
+ /** The source's key in the drawer's sources (the logo, the product). */
+ src: string;
+ x: number;
+ y: number;
+ w: number;
+ h: number;
+ opacity?: number;
+ smoothing?: boolean;
+}
+
+export type DisplayNode = GroupNode | RectNode | EllipseNode | PathNode | TextNode | ImageNode;
+
+export interface DisplayList {
+ /** Design size. */
+ w: number;
+ h: number;
+ background: string;
+ nodes: DisplayNode[];
+}
+
+export const group = (children: DisplayNode[], o: Omit<GroupNode, "type" | "children"> = {}): GroupNode => ({ type: "group", ...o, children });
+
+/** Every text node in a list, in drawing order (tests read the fields from it). */
+export function textNodes(nodes: readonly DisplayNode[]): TextNode[] {
+ const out: TextNode[] = [];
+ for (const n of nodes) {
+ if (n.type === "text") out.push(n);
+ else if (n.type === "group") out.push(...textNodes(n.children));
+ }
+ return out;
+}
+
+/** The pill outline as path data starting at the top centre, clockwise, and its length (for a stroke that draws on). */
+export function roundRectPath(x: number, y: number, w: number, h: number, r: number): { d: string; length: number } {
+ const rr = Math.max(0, Math.min(r, w / 2, h / 2));
+ const cx = x + w / 2;
+ const d = [
+ `M${cx} ${y}`,
+ `H${x + w - rr}`,
+ `A${rr} ${rr} 0 0 1 ${x + w} ${y + rr}`,
+ `V${y + h - rr}`,
+ `A${rr} ${rr} 0 0 1 ${x + w - rr} ${y + h}`,
+ `H${x + rr}`,
+ `A${rr} ${rr} 0 0 1 ${x} ${y + h - rr}`,
+ `V${y + rr}`,
+ `A${rr} ${rr} 0 0 1 ${x + rr} ${y}`,
+ "Z",
+ ].join(" ");
+ return { d, length: 2 * (w - 2 * rr) + 2 * (h - 2 * rr) + 2 * Math.PI * rr };
+}
+
+/** A colour with its alpha multiplied (hex #rrggbb or #rgb in, rgba() out). */
+export function withAlpha(hex: string, a: number): string {
+ const h = hex.replace("#", "");
+ const full = h.length === 3 ? [...h].map((c) => c + c).join("") : h.slice(0, 6).padEnd(6, "0");
+ const [r, g, b] = [0, 2, 4].map((i) => parseInt(full.slice(i, i + 2), 16));
+ return `rgba(${r},${g},${b},${Math.max(0, Math.min(1, a))})`;
+}
+
+/** Two hex colours mixed (p = 0: a, 1: b), as hex. */
+export function mixHex(a: string, b: string, p: number): string {
+ const rgb = (hex: string) => {
+ const h = hex.replace("#", "");
+ const full = h.length === 3 ? [...h].map((c) => c + c).join("") : h.slice(0, 6).padEnd(6, "0");
+ return [0, 2, 4].map((i) => parseInt(full.slice(i, i + 2), 16));
+ };
+ const x = rgb(a);
+ const y = rgb(b);
+ return `#${x.map((v, i) => Math.round(v + (y[i] - v) * p).toString(16).padStart(2, "0")).join("")}`;
+}
+
+// ---------------------------------------------------------------------------
+// Motion between two moments
+
+const d = (a: number | undefined, b: number | undefined) => Math.abs((a ?? 0) - (b ?? 0));
+
+/** How far a matrix change moves the frame's corners (design units). */
+function matrixTravel(m: Matrix | undefined, n: Matrix | undefined, w: number, h: number): number {
+ if (!m && !n) return 0;
+ const a = m ?? IDENTITY;
+ const b = n ?? IDENTITY;
+ let out = 0;
+ for (const [x, y] of [
+ [0, 0],
+ [w, 0],
+ [0, h],
+ [w, h],
+ ]) {
+ out = Math.max(out, Math.hypot((a[0] - b[0]) * x + (a[2] - b[2]) * y + (a[4] - b[4]), (a[1] - b[1]) * x + (a[3] - b[3]) * y + (a[5] - b[5])));
+ }
+ return out;
+}
+
+function paintTravel(p: Paint | undefined, q: Paint | undefined): number {
+ if (!p || !q || typeof p === "string" || typeof q === "string" || p.kind !== q.kind) return 0;
+ if (p.kind === "linear" && q.kind === "linear") return Math.max(d(p.x0, q.x0), d(p.y0, q.y0), d(p.x1, q.x1), d(p.y1, q.y1));
+ if (p.kind === "radial" && q.kind === "radial") return Math.max(d(p.cx, q.cx), d(p.cy, q.cy), d(p.r0, q.r0), d(p.r1, q.r1));
+ return 0;
+}
+
+const boxTravel = (a: { x: number; y: number; w: number; h: number }, b: { x: number; y: number; w: number; h: number }) => Math.max(d(a.x, b.x), d(a.y, b.y), d(a.x + a.w, b.x + b.w), d(a.y + a.h, b.y + b.h));
+
+function strokeTravel(a: Stroke | undefined, b: Stroke | undefined): number {
+ if (!a || !b) return 0;
+ return d(a.trim ?? 1, b.trim ?? 1) * (a.length ?? 0) + d(a.width, b.width);
+}
+
+function nodesTravel(a: readonly DisplayNode[], b: readonly DisplayNode[], w: number, h: number): number {
+ let out = 0;
+ const n = Math.min(a.length, b.length);
+ for (let i = 0; i < n; i++) {
+ const x = a[i];
+ const y = b[i];
+ if (x.type !== y.type) continue;
+ let t = 0;
+ if (x.type === "group" && y.type === "group") {
+ t = matrixTravel(x.transform, y.transform, w, h) + nodesTravel(x.children, y.children, w, h);
+ if (x.clip && y.clip && x.clip.type === "rect" && y.clip.type === "rect") t = Math.max(t, boxTravel(x.clip, y.clip));
+ if (x.mask && y.mask) t = Math.max(t, paintTravel(x.mask, y.mask));
+ } else if (x.type === "rect" && y.type === "rect") t = Math.max(boxTravel(x, y), paintTravel(x.fill, y.fill), strokeTravel(x.stroke, y.stroke));
+ else if (x.type === "ellipse" && y.type === "ellipse") t = Math.max(d(x.cx, y.cx) + d(x.rx, y.rx), d(x.cy, y.cy) + d(x.ry, y.ry), paintTravel(x.fill, y.fill));
+ else if (x.type === "image" && y.type === "image") t = boxTravel(x, y);
+ else if (x.type === "path" && y.type === "path") t = Math.max(x.d === y.d ? matrixTravel(x.transform, y.transform, w, h) : 0, strokeTravel(x.stroke, y.stroke));
+ else if (x.type === "text" && y.type === "text") {
+ const m = Math.min(x.runs.length, y.runs.length);
+ for (let k = 0; k < m; k++) t = Math.max(t, d(x.runs[k].x, y.runs[k].x), d(x.runs[k].y, y.runs[k].y), matrixTravel(x.runs[k].transform, y.runs[k].transform, w, h));
+ }
+ out = Math.max(out, t);
+ }
+ return out;
+}
+
+/**
+ * The farthest anything moves between two moments of one scene (design units): edges, centres, radii, gradient
+ * stops, stroke ends. Pieces that appear or vanish in between don't count (they need no blur). The export picks its
+ * motion-blur samples from it, so a fast edge gets enough of them to look smooth and a held frame gets one.
+ */
+export function listTravel(a: DisplayList, b: DisplayList): number {
+ return nodesTravel(a.nodes, b.nodes, a.w, a.h);
+}
diff --git a/src/lib/motion/ease.ts b/src/lib/motion/ease.ts
new file mode 100644
index 00000000..09f05d3d
--- /dev/null
+++ b/src/lib/motion/ease.ts
@@ -0,0 +1,180 @@
+/**
+ * Kinetic Motion's easing library (pure). Every curve maps progress 0..1 to 0..1 with f(0) = 0 and f(1) = 1, so a
+ * scene can put any of them on any window. Springs are closed-form (no integration, no state): a spring's curve is its
+ * motion over its own settle time, so a spring placed on a shorter window simply plays faster.
+ *
+ * Scenes name only the curves in CURVES, so every template shares one motion language.
+ */
+
+export type Ease = (p: number) => number;
+
+const clamp01 = (p: number) => (p <= 0 ? 0 : p >= 1 ? 1 : p);
+/** Pins the ends: f(0) = 0 and f(1) = 1 exactly, whatever float error the formula has. */
+const pinned =
+ (f: Ease): Ease =>
+ (p) => {
+ if (!(p > 0)) return 0;
+ if (p >= 1) return 1;
+ return f(p);
+ };
+
+export const linear: Ease = (p) => clamp01(p);
+
+const outOf = (f: Ease): Ease => (p) => 1 - f(1 - p);
+const inOutOf = (f: Ease): Ease => (p) => (p < 0.5 ? f(2 * p) / 2 : 1 - f(2 - 2 * p) / 2);
+const family = (f: Ease) => ({ in: pinned(f), out: pinned(outOf(f)), inOut: pinned(inOutOf(f)) });
+
+export const quad = family((p) => p * p);
+export const cubic = family((p) => p * p * p);
+export const quart = family((p) => p ** 4);
+export const quint = family((p) => p ** 5);
+export const sine = family((p) => 1 - Math.cos((p * Math.PI) / 2));
+export const expo = family((p) => (p === 0 ? 0 : 2 ** (10 * p - 10)));
+export const circ = family((p) => 1 - Math.sqrt(Math.max(0, 1 - p * p)));
+
+/** Pulls back before it goes (in), overshoots and returns (out); `overshoot` 1.70158 is the classic 10 %. */
+export const back = (overshoot = 1.70158) => family((p) => p * p * ((overshoot + 1) * p - overshoot));
+
+/** A plucked string: `amplitude` ≥ 1, `period` in progress units. */
+export const elastic = (amplitude = 1, period = 0.3) => {
+ const a = Math.max(1, amplitude);
+ const s = (period / (2 * Math.PI)) * Math.asin(1 / a);
+ return family((p) => (p === 0 || p === 1 ? p : -(a * 2 ** (10 * (p - 1)) * Math.sin(((p - 1 - s) * 2 * Math.PI) / period))));
+};
+
+const bounceOut: Ease = (p) => {
+ const n = 7.5625;
+ const d = 2.75;
+ if (p < 1 / d) return n * p * p;
+ if (p < 2 / d) return n * (p -= 1.5 / d) * p + 0.75;
+ if (p < 2.5 / d) return n * (p -= 2.25 / d) * p + 0.9375;
+ return n * (p -= 2.625 / d) * p + 0.984375;
+};
+export const bounce = family((p) => 1 - bounceOut(1 - p));
+
+/**
+ * A CSS cubic-bezier(x1, y1, x2, y2): x is solved for by Newton steps, with bisection where the slope is too flat, to
+ * 1e-7, so the curve matches a browser's within 1e-6.
+ */
+export function bezier(x1: number, y1: number, x2: number, y2: number): Ease {
+ const cx = 3 * x1;
+ const bx = 3 * (x2 - x1) - cx;
+ const ax = 1 - cx - bx;
+ const cy = 3 * y1;
+ const by = 3 * (y2 - y1) - cy;
+ const ay = 1 - cy - by;
+ const sx = (u: number) => ((ax * u + bx) * u + cx) * u;
+ const sy = (u: number) => ((ay * u + by) * u + cy) * u;
+ const dx = (u: number) => (3 * ax * u + 2 * bx) * u + cx;
+ const solve = (x: number): number => {
+ let u = x;
+ for (let i = 0; i < 8; i++) {
+ const err = sx(u) - x;
+ if (Math.abs(err) < 1e-7) return u;
+ const d = dx(u);
+ if (Math.abs(d) < 1e-6) break;
+ u -= err / d;
+ }
+ let lo = 0;
+ let hi = 1;
+ u = x;
+ for (let i = 0; i < 60; i++) {
+ const v = sx(u);
+ if (Math.abs(v - x) < 1e-7) return u;
+ if (v < x) lo = u;
+ else hi = u;
+ u = (lo + hi) / 2;
+ }
+ return u;
+ };
+ return pinned((p) => sy(solve(p)));
+}
+
+export interface SpringOptions {
+ stiffness: number;
+ damping: number;
+ mass?: number;
+ /** Starting speed, in progress units a second (0: from rest). */
+ velocity?: number;
+}
+
+/** The spring's position (0 at rest at the start, 1 at its target) `t` seconds in: the closed-form damped oscillator. */
+export function springAt(o: SpringOptions, t: number): number {
+ const m = o.mass ?? 1;
+ const w0 = Math.sqrt(o.stiffness / m);
+ const zeta = o.damping / (2 * Math.sqrt(o.stiffness * m));
+ const x0 = -1;
+ const v0 = o.velocity ?? 0;
+ let x: number;
+ if (zeta < 1) {
+ const wd = w0 * Math.sqrt(1 - zeta * zeta);
+ x = Math.exp(-zeta * w0 * t) * (x0 * Math.cos(wd * t) + ((v0 + zeta * w0 * x0) / wd) * Math.sin(wd * t));
+ } else if (zeta === 1) {
+ x = Math.exp(-w0 * t) * (x0 + (v0 + w0 * x0) * t);
+ } else {
+ const r = Math.sqrt(zeta * zeta - 1);
+ const r1 = -w0 * (zeta - r);
+ const r2 = -w0 * (zeta + r);
+ const c2 = (v0 - r1 * x0) / (r2 - r1);
+ const c1 = x0 - c2;
+ x = c1 * Math.exp(r1 * t) + c2 * Math.exp(r2 * t);
+ }
+ return 1 + x;
+}
+
+const settleCache = new Map<string, number>();
+
+/** When the spring stays within 0.1 % of its target for good (seconds; searched on a 1 ms grid up to 10 s). */
+export function springDuration(o: SpringOptions): number {
+ const key = `${o.stiffness}|${o.damping}|${o.mass ?? 1}|${o.velocity ?? 0}`;
+ const hit = settleCache.get(key);
+ if (hit !== undefined) return hit;
+ let last = 0;
+ for (let ms = 0; ms <= 10_000; ms++) if (Math.abs(springAt(o, ms / 1000) - 1) > 0.001) last = ms;
+ const d = (last + 1) / 1000;
+ settleCache.set(key, d);
+ return d;
+}
+
+/** A spring as a curve over its own settle time (it reaches 1 exactly at p = 1). */
+export function spring(o: SpringOptions): Ease {
+ const d = springDuration(o);
+ return pinned((p) => springAt(o, p * d));
+}
+
+/** `n` equal jumps (the last one at p = 1). */
+export const steps =
+ (n: number): Ease =>
+ (p) =>
+ p >= 1 ? 1 : p <= 0 ? 0 : Math.floor(p * n) / n;
+
+/** Stays at the start until the end. */
+export const hold: Ease = (p) => (p >= 1 ? 1 : 0);
+
+export const SPRINGS = {
+ pop: { stiffness: 420, damping: 26 },
+ settle: { stiffness: 180, damping: 20 },
+} as const satisfies Record<string, SpringOptions>;
+
+/**
+ * Fuobe's named curves: the only ones scenes use by name. enter: a soft expo-out for arrivals; glide: a gentler
+ * cubic-out for headlines and wide moves (the motion stays visible through its window); exit: leaving; move: an in-place
+ * move; pop: a button or badge, about 7 % past its size and back; settle: logos and large type; snap: small, UI-like
+ * moves; draw: strokes; drift: a slow camera that comes to rest on the last frame.
+ */
+export const CURVES = {
+ enter: bezier(0.16, 1, 0.3, 1),
+ glide: bezier(0.33, 1, 0.68, 1),
+ drift: sine.out,
+ exit: bezier(0.7, 0, 0.84, 0),
+ move: bezier(0.65, 0, 0.35, 1),
+ pop: spring(SPRINGS.pop),
+ settle: spring(SPRINGS.settle),
+ snap: bezier(0.2, 0, 0, 1),
+ draw: bezier(0.45, 0, 0.2, 1),
+ linear,
+} satisfies Record<string, Ease>;
+
+export type CurveName = keyof typeof CURVES;
+
+export const curve = (name: CurveName): Ease => CURVES[name];
diff --git a/src/lib/motion/layout.ts b/src/lib/motion/layout.ts
new file mode 100644
index 00000000..f0bd65e2
--- /dev/null
+++ b/src/lib/motion/layout.ts
@@ -0,0 +1,308 @@
+/**
+ * Text set exactly as typed (pure). The words a person types are drawn as they typed them: no case change, no "…", no
+ * hyphen, no word split across lines. Only leading and trailing whitespace is trimmed; a line break they typed is a
+ * forced break and runs of spaces are kept. Text shrinks to its smallest size; if it still doesn't fit, the layout says
+ * so (`overflow`) and the page asks for shorter words instead of cutting them.
+ *
+ * Lines are balanced: at the largest size that fits, among the breaks with the fewest lines, the one whose lines are
+ * closest in width (no lone short word on the last line). The layout also gives each line's words and letters (grapheme
+ * clusters: an emoji family or an accented letter stays whole) with their boxes, so a scene can move them one by one
+ * and still land exactly on this layout at rest.
+ *
+ * Every drawn piece carries `gap`, the whitespace before it in the typed text (not drawn): joining gap + text over every
+ * piece in order gives back the typed text, which tests/motion-spelling.test.ts checks for every scene.
+ */
+
+import { fontString, type Measure } from "@/components/ads/layout";
+
+export type { Measure };
+
+export interface Piece {
+ text: string;
+ /** The typed whitespace before this piece (a line's first piece: the break's whitespace). */
+ gap: string;
+ /** From the line's left edge. */
+ x: number;
+ w: number;
+}
+
+export interface LineLayout {
+ text: string;
+ /** The whitespace consumed by the break before this line ("" for the first). */
+ gap: string;
+ width: number;
+ words: Piece[];
+ /** Letters, or null for a script whose letters join (Arabic, Devanagari, Thai…): those move by word. */
+ graphemes: Piece[] | null;
+}
+
+export interface TextLayout {
+ /** The typed text, trimmed. */
+ text: string;
+ overflow: boolean;
+ size: number;
+ /** Line pitch (size × the spec's factor). */
+ lineHeight: number;
+ font: string;
+ family: string;
+ weight: number;
+ dir: "ltr" | "rtl";
+ lines: LineLayout[];
+ /** The widest line. */
+ width: number;
+ /** lines × lineHeight. */
+ height: number;
+}
+
+export interface TextSpec {
+ text: string;
+ family: string;
+ weight: number;
+ /** The box's width. */
+ width: number;
+ maxLines: number;
+ /** Largest and smallest size; the size steps down by `step` (6 %) between them. */
+ max: number;
+ min: number;
+ lineHeight?: number;
+ step?: number;
+ /** Letter boxes too (each costs a measurement per letter). */
+ letters?: boolean;
+}
+
+/** Scripts written without spaces between words: they may break between the words Intl.Segmenter finds. */
+const NO_SPACES = /[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}\p{Script=Thai}\p{Script=Lao}\p{Script=Myanmar}\p{Script=Khmer}]/u;
+/** Scripts whose letters join or reorder: never drawn letter by letter. */
+const COMPLEX = /[\p{Script=Hebrew}\p{Script=Arabic}\p{Script=Syriac}\p{Script=Thaana}\p{Script=Nko}\p{Script=Devanagari}\p{Script=Bengali}\p{Script=Gurmukhi}\p{Script=Gujarati}\p{Script=Oriya}\p{Script=Tamil}\p{Script=Telugu}\p{Script=Kannada}\p{Script=Malayalam}\p{Script=Sinhala}\p{Script=Thai}\p{Script=Lao}\p{Script=Tibetan}\p{Script=Myanmar}\p{Script=Khmer}\p{Script=Mongolian}]/u;
+const RTL_CHAR = /[\p{Script=Hebrew}\p{Script=Arabic}\p{Script=Syriac}\p{Script=Thaana}\p{Script=Nko}]/u;
+const LTR_CHAR = /[\p{Script=Latin}\p{Script=Greek}\p{Script=Cyrillic}\p{Script=Armenian}\p{Script=Georgian}]/u;
+/** Letter pairs a font may join into one glyph (fi, fl, ff…): a line holding one moves by word, never letter by letter. */
+const LIGATURE = /f[fijlbhkt]/;
+/** A typed line break (a new line, or a line or paragraph separator). */
+const BREAK = /[\r\n\p{Zl}\p{Zp}]/u;
+
+/** Left-to-right or right-to-left, by the first letter that says. */
+export function directionOf(text: string): "ltr" | "rtl" {
+ for (const ch of text) {
+ if (RTL_CHAR.test(ch)) return "rtl";
+ if (LTR_CHAR.test(ch)) return "ltr";
+ }
+ return "ltr";
+}
+
+const segmenters = new Map<string, Intl.Segmenter | null>();
+function segmenter(granularity: "word" | "grapheme"): Intl.Segmenter | null {
+ if (!segmenters.has(granularity)) segmenters.set(granularity, typeof Intl !== "undefined" && "Segmenter" in Intl ? new Intl.Segmenter(undefined, { granularity }) : null);
+ return segmenters.get(granularity)!;
+}
+
+/** Grapheme clusters (a ZWJ emoji, a letter and its accents, a flag stay one), with their offsets. */
+export function graphemes(text: string): { text: string; index: number }[] {
+ const seg = segmenter("grapheme");
+ if (seg) return [...seg.segment(text)].map((s) => ({ text: s.segment, index: s.index }));
+ const out: { text: string; index: number }[] = [];
+ let i = 0;
+ for (const ch of text) {
+ out.push({ text: ch, index: i });
+ i += ch.length;
+ }
+ return out;
+}
+
+/** A place a line may break: the atom from `start` to `end`, after the whitespace from `gapStart`. */
+interface Atom {
+ gapStart: number;
+ start: number;
+ end: number;
+ /** The whitespace before it holds a typed line break. */
+ forced: boolean;
+}
+
+function atomsOf(text: string): Atom[] {
+ const atoms: Atom[] = [];
+ const re = /(\s*)(\S+)/gy;
+ let m: RegExpExecArray | null;
+ while ((m = re.exec(text))) {
+ const gapStart = m.index;
+ const start = gapStart + m[1].length;
+ const word = m[2];
+ const forced = BREAK.test(m[1]);
+ const seg = NO_SPACES.test(word) ? segmenter("word") : null;
+ if (!seg) {
+ atoms.push({ gapStart, start, end: start + word.length, forced });
+ continue;
+ }
+ // A run with no spaces may break between its words (Japanese, Chinese, Thai); punctuation stays with the word before.
+ let first = true;
+ for (const s of seg.segment(word)) {
+ const a = start + s.index;
+ const prev = atoms[atoms.length - 1];
+ if (!first && prev && !(s as Intl.SegmentData & { isWordLike?: boolean }).isWordLike) {
+ prev.end = a + s.segment.length;
+ continue;
+ }
+ atoms.push({ gapStart: first ? gapStart : a, start: a, end: a + s.segment.length, forced: first && forced });
+ first = false;
+ }
+ }
+ return atoms;
+}
+
+type Width = (i: number, j: number) => number;
+
+/** Fewest lines that hold the atoms a..b (inclusive) at this width, or Infinity when one atom is wider than the box. */
+function greedyCount(a: number, b: number, width: number, w: Width): number {
+ let lines = 1;
+ let from = a;
+ for (let j = a; j <= b; j++) {
+ if (w(j, j) > width) return Infinity;
+ if (w(from, j) > width) {
+ lines++;
+ from = j;
+ }
+ }
+ return lines;
+}
+
+/** The break of atoms a..b into exactly `n` lines whose widths are closest to each other (least squares). */
+function balancedBreaks(a: number, b: number, n: number, width: number, w: Width): number[] {
+ if (n <= 1) return [a];
+ const avg = w(a, b) / n;
+ const count = b - a + 1;
+ // cost[l][j]: the best l + 1 lines ending at atom a + j; from[l][j]: where the last of them starts.
+ const cost = Array.from({ length: n }, () => new Float64Array(count).fill(Infinity));
+ const from = Array.from({ length: n }, () => new Int32Array(count).fill(-1));
+ for (let j = 0; j < count; j++) {
+ const lw = w(a, a + j);
+ if (lw <= width) cost[0][j] = (lw - avg) ** 2;
+ }
+ for (let l = 1; l < n; l++) {
+ for (let j = l; j < count; j++) {
+ for (let i = l; i <= j; i++) {
+ const prev = cost[l - 1][i - 1];
+ if (prev === Infinity) continue;
+ const lw = w(a + i, a + j);
+ if (lw > width) continue;
+ const c = prev + (lw - avg) ** 2;
+ if (c < cost[l][j]) {
+ cost[l][j] = c;
+ from[l][j] = i;
+ }
+ }
+ }
+ }
+ const starts: number[] = [];
+ let j = count - 1;
+ for (let l = n - 1; l > 0; l--) {
+ const i = from[l][j];
+ if (i < 0) return greedyStarts(a, b, width, w);
+ starts.unshift(a + i);
+ j = i - 1;
+ }
+ starts.unshift(a);
+ return starts;
+}
+
+function greedyStarts(a: number, b: number, width: number, w: Width): number[] {
+ const starts = [a];
+ let from = a;
+ for (let j = a + 1; j <= b; j++) {
+ if (w(from, j) > width) {
+ starts.push(j);
+ from = j;
+ }
+ }
+ return starts;
+}
+
+/** Paragraphs (typed line breaks) as atom ranges. */
+function paragraphs(atoms: Atom[]): [number, number][] {
+ const out: [number, number][] = [];
+ let start = 0;
+ for (let i = 1; i < atoms.length; i++) {
+ if (atoms[i].forced) {
+ out.push([start, i - 1]);
+ start = i;
+ }
+ }
+ if (atoms.length) out.push([start, atoms.length - 1]);
+ return out;
+}
+
+/** Lay out `spec.text` (see the file's comment). */
+export function layoutText(spec: TextSpec, measure: Measure): TextLayout {
+ const text = spec.text.trim();
+ const lh = spec.lineHeight ?? 1.12;
+ const dir = directionOf(text);
+ const complex = COMPLEX.test(text);
+ const atoms = atomsOf(text);
+ const paras = paragraphs(atoms);
+ const empty = (size: number): TextLayout => ({ text, overflow: false, size, lineHeight: size * lh, font: fontString(spec.family, size, spec.weight), family: spec.family, weight: spec.weight, dir, lines: [], width: 0, height: 0 });
+ if (!atoms.length) return empty(spec.max);
+
+ const attempt = (size: number, last: boolean): TextLayout | null => {
+ const font = fontString(spec.family, size, spec.weight);
+ const memo = new Map<number, number>();
+ const w: Width = (i, j) => {
+ const key = i * 4096 + j;
+ let v = memo.get(key);
+ if (v === undefined) {
+ v = measure(text.slice(atoms[i].start, atoms[j].end), font);
+ memo.set(key, v);
+ }
+ return v;
+ };
+ const counts = paras.map(([a, b]) => greedyCount(a, b, spec.width, w));
+ const total = counts.reduce((s, c) => s + c, 0);
+ const fits = total <= spec.maxLines && Number.isFinite(total);
+ if (!fits && !last) return null;
+ // Too long even at the smallest size: every line still laid out (nothing cut), and flagged.
+ const starts = paras.flatMap(([a, b], k) => (fits ? balancedBreaks(a, b, counts[k], spec.width, w) : greedyStarts(a, b, spec.width, w)));
+ const lines: LineLayout[] = starts.map((s, k) => {
+ const e = (k + 1 < starts.length ? starts[k + 1] : atoms.length) - 1;
+ const lineStart = atoms[s].start;
+ const lineText = text.slice(lineStart, atoms[e].end);
+ const width = w(s, e);
+ const at = (offset: number) => (offset <= 0 ? 0 : measure(lineText.slice(0, offset), font));
+ // A piece starts where the line up to its end ends, less the piece's own advance: the kerning before it is kept, so
+ // a piece drawn on its own lands exactly where the whole line draws it.
+ const left = (from: number, to: number, w: number) => (dir === "rtl" ? width - at(to) : Math.max(0, at(to) - w));
+ const words: Piece[] = [];
+ for (let i = s; i <= e; i++) {
+ const from = atoms[i].start - lineStart;
+ const to = atoms[i].end - lineStart;
+ const word = text.slice(atoms[i].start, atoms[i].end);
+ const w = from === 0 && to === lineText.length ? width : measure(word, font);
+ words.push({ text: word, gap: text.slice(atoms[i].gapStart, atoms[i].start), x: left(from, to, w), w });
+ }
+ let letters: Piece[] | null = null;
+ if (spec.letters && !complex && !LIGATURE.test(lineText)) {
+ letters = [];
+ let gap = atoms[s].gapStart < lineStart ? text.slice(atoms[s].gapStart, lineStart) : "";
+ for (const g of graphemes(lineText)) {
+ if (/^\s+$/.test(g.text)) {
+ gap += g.text;
+ continue;
+ }
+ const w = measure(g.text, font);
+ letters.push({ text: g.text, gap, x: left(g.index, g.index + g.text.length, w), w });
+ gap = "";
+ }
+ }
+ return { text: lineText, gap: text.slice(atoms[s].gapStart, lineStart), width, words, graphemes: letters };
+ });
+ return { text, overflow: !fits, size, lineHeight: size * lh, font, family: spec.family, weight: spec.weight, dir, lines, width: Math.max(...lines.map((l) => l.width)), height: lines.length * size * lh };
+ };
+
+ let size = spec.max;
+ const step = spec.step ?? 0.94;
+ for (;;) {
+ const last = size <= spec.min;
+ const got = attempt(size, last);
+ if (got) return got;
+ size = Math.max(spec.min, size * step);
+ }
+}
+
+/** The typed text back from a layout's lines (gap + text), for checks. */
+export const spelled = (pieces: readonly { gap?: string; text: string }[]): string => pieces.map((p) => (p.gap ?? "") + p.text).join("");
diff --git a/src/lib/motion/random.ts b/src/lib/motion/random.ts
new file mode 100644
index 00000000..97af17f8
--- /dev/null
+++ b/src/lib/motion/random.ts
@@ -0,0 +1,43 @@
+/**
+ * Seeded randomness for scenes (pure). A value is a hash of the seed and a stable key ("particle", 7), not the next
+ * number from a stream: particle 7's value is the same however many particles came before it, and whatever order a
+ * frame asks in. Scenes never call Math.random.
+ */
+
+/** A 32-bit integer mix (an avalanche: every input bit changes about half the output bits). */
+function mix32(h: number): number {
+ h = Math.imul(h ^ (h >>> 16), 0x7feb352d);
+ h = Math.imul(h ^ (h >>> 15), 0x846ca68b);
+ return (h ^ (h >>> 16)) >>> 0;
+}
+
+function absorb(h: number, key: string | number): number {
+ if (typeof key === "number") {
+ // Integers as themselves; a fraction by its bits.
+ const lo = Number.isInteger(key) ? key | 0 : Math.round(key * 1e6) | 0;
+ const hi = Number.isInteger(key) ? Math.floor(key / 2 ** 32) | 0 : 0x5bd1e995;
+ return mix32((mix32(h ^ lo) + 0x9e3779b9) ^ hi);
+ }
+ for (let i = 0; i < key.length; i++) h = Math.imul(h ^ key.charCodeAt(i), 0x01000193);
+ return mix32(h ^ key.length);
+}
+
+/** A number in [0, 1) for this seed and key. */
+export function rng(seed: number, ...keys: (string | number)[]): number {
+ let h = mix32((seed | 0) ^ 0x2545f491);
+ for (const k of keys) h = absorb(h, k);
+ return mix32(h) / 4294967296;
+}
+
+/** A number in [lo, hi) for this seed and key. */
+export const rngRange = (lo: number, hi: number, seed: number, ...keys: (string | number)[]): number => lo + (hi - lo) * rng(seed, ...keys);
+
+/** Smooth seeded noise in [-1, 1] along t (value noise with a smoothstep between whole steps): a camera shake's wobble. */
+export function noise1(seed: number, key: string, t: number): number {
+ const i = Math.floor(t);
+ const f = t - i;
+ const s = f * f * (3 - 2 * f);
+ const a = rng(seed, key, i) * 2 - 1;
+ const b = rng(seed, key, i + 1) * 2 - 1;
+ return a + (b - a) * s;
+}
diff --git a/src/lib/motion/recipe.ts b/src/lib/motion/recipe.ts
new file mode 100644
index 00000000..afa6c840
--- /dev/null
+++ b/src/lib/motion/recipe.ts
@@ -0,0 +1,75 @@
+/**
+ * A recipe: everything a Kinetic Motion clip is made from, as JSON (pure). The scene, the seed, the size and rate, the
+ * typed words, the brand, the person's own files, the scene's control values and the export settings. It is saved
+ * with the result (params.extra.motion), so the same clip can be made again.
+ */
+
+import { z } from "zod";
+import { rng } from "./random";
+
+/** A recipe is at most this big as JSON. */
+export const RECIPE_MAX_BYTES = 64 * 1024;
+
+const Hex = z.string().regex(/^#[0-9a-fA-F]{6}$/);
+const File = z.string().startsWith("/api/files/").max(500);
+
+export const RecipeSchema = z.object({
+ v: z.literal(1),
+ scene: z.string().regex(/^[a-z0-9-]+\/[a-z0-9-]+$/).max(80),
+ seed: z.number().int().min(0).max(2 ** 31 - 1),
+ size: z.union([z.enum(["9:16", "1:1", "16:9", "4:5"]), z.object({ w: z.number().int().min(64).max(4096), h: z.number().int().min(64).max(4096) })]),
+ fps: z.union([z.literal(24), z.literal(25), z.literal(30)]),
+ duration: z.number().min(0.5).max(60),
+ /** The typed words, by field (headline, sub, cta, website, badge…), exactly as typed. */
+ fields: z.record(z.string().max(40), z.string().max(600)),
+ brand: z.object({
+ name: z.string().max(120),
+ colors: z.array(Hex).max(8),
+ fonts: z.object({ heading: z.string().max(80).optional(), body: z.string().max(80).optional() }),
+ /** The logo's address (a stored file, or the kit's own link). */
+ logo: z.string().max(500).optional(),
+ }),
+ media: z.object({ product: File.optional(), images: z.array(File).max(4).optional() }).optional(),
+ controls: z.record(z.string().max(40), z.union([z.string().max(80), z.number(), z.boolean()])).optional(),
+ export: z.object({
+ format: z.enum(["mp4", "webm"]),
+ bitrate: z.number().int().min(500_000).max(40_000_000).optional(),
+ blurSamples: z.number().int().min(1).max(32),
+ shutter: z.number().min(0).max(360),
+ /** How it was encoded: frame-exact WebCodecs, or the real-time recorder (may drop a frame). */
+ encoder: z.enum(["webcodecs", "recorder"]).optional(),
+ }),
+});
+
+export type Recipe = z.infer<typeof RecipeSchema>;
+
+export const DEFAULT_EXPORT: Recipe["export"] = { format: "mp4", blurSamples: 8, shutter: 180 };
+
+/** A recipe checked and held to its scene's length limits; throws on a bad one. */
+export function normalizeRecipe(input: unknown, limits?: { min: number; max: number }): Recipe {
+ const r = RecipeSchema.parse(input);
+ if (JSON.stringify(r).length > RECIPE_MAX_BYTES) throw new Error("This recipe is too big");
+ const duration = limits ? Math.min(limits.max, Math.max(limits.min, r.duration)) : r.duration;
+ return { ...r, duration };
+}
+
+/** JSON with keys in a fixed order, so equal recipes write the same text. */
+export function stableJson(v: unknown): string {
+ if (Array.isArray(v)) return `[${v.map(stableJson).join(",")}]`;
+ if (v && typeof v === "object") {
+ return `{${Object.keys(v)
+ .filter((k) => (v as Record<string, unknown>)[k] !== undefined)
+ .sort()
+ .map((k) => `${JSON.stringify(k)}:${stableJson((v as Record<string, unknown>)[k])}`)
+ .join(",")}}`;
+ }
+ return JSON.stringify(v);
+}
+
+/** A short key for one look (equal recipes, equal keys): the page saves a look once per visit by it. */
+export function recipeKey(r: Recipe | Record<string, unknown>): string {
+ const text = stableJson(r);
+ const a = rng(0x51f15e, text);
+ const b = rng(0x2c1b3c6d, text);
+ return `${Math.floor(a * 2 ** 32).toString(16).padStart(8, "0")}${Math.floor(b * 2 ** 32).toString(16).padStart(8, "0")}`;
+}
diff --git a/src/lib/motion/registry.ts b/src/lib/motion/registry.ts
new file mode 100644
index 00000000..a38ec784
--- /dev/null
+++ b/src/lib/motion/registry.ts
@@ -0,0 +1,30 @@
+/**
+ * Every Kinetic Motion scene by id, loaded only when a page plays or renders it.
+ */
+
+import type { Scene } from "./scene";
+
+const LOADERS: Record<string, () => Promise<{ default: Scene }>> = {
+ "end-card/draw-on": () => import("./scenes/end-card/draw-on"),
+ "end-card/rise": () => import("./scenes/end-card/rise"),
+ "end-card/iris": () => import("./scenes/end-card/iris"),
+ "end-card/split": () => import("./scenes/end-card/split"),
+ "end-card/glint": () => import("./scenes/end-card/glint"),
+};
+
+export const SCENE_IDS = Object.keys(LOADERS);
+
+export const hasScene = (id: string): boolean => Object.hasOwn(LOADERS, id);
+
+const loaded = new Map<string, Promise<Scene>>();
+
+/** The scene with this id (rejects for an unknown one). */
+export function loadScene(id: string): Promise<Scene> {
+ if (!hasScene(id)) return Promise.reject(new Error(`No scene "${id}"`));
+ let p = loaded.get(id);
+ if (!p) {
+ p = LOADERS[id]().then((m) => m.default);
+ loaded.set(id, p);
+ }
+ return p;
+}
diff --git a/src/lib/motion/scene.ts b/src/lib/motion/scene.ts
new file mode 100644
index 00000000..3975a5c8
--- /dev/null
+++ b/src/lib/motion/scene.ts
@@ -0,0 +1,67 @@
+/**
+ * The scene contract (pure). A scene turns a recipe into a plan once (its text laid out, its timeline built), and the
+ * plan gives the display list at any absolute time. Nothing in a scene reads a clock, the DOM or Math.random: the same
+ * recipe and time always give the same picture, in any order of seeks.
+ */
+
+import type { DisplayList, Matrix } from "./display";
+import type { Measure } from "./layout";
+import type { Recipe } from "./recipe";
+import type { SizeSpec } from "./sizes";
+import type { MotionEvent, Timeline } from "./tween";
+
+/** An SVG logo's outlines, read from the file before the scene runs (the drawer's DOM does it). */
+export interface LogoPath {
+ d: string;
+ /** From the path's own units to the SVG's viewBox units. */
+ m: Matrix;
+ /** Its length in its own units. */
+ length: number;
+}
+
+export interface LogoInfo {
+ /** Its natural size. */
+ w: number;
+ h: number;
+ kind: "svg" | "raster";
+ /** Outlines a stroke can trace (SVG logos with at least one). */
+ paths?: LogoPath[];
+ viewBox?: { x: number; y: number; w: number; h: number };
+}
+
+/** What a scene is given besides the recipe: sizes known before it runs, never elements. */
+export interface SceneInput {
+ recipe: Recipe;
+ measure: Measure;
+ logo: LogoInfo | null;
+ images?: Record<string, { w: number; h: number }>;
+}
+
+export interface ScenePlan {
+ /** Design units. */
+ design: { w: number; h: number };
+ timeline: Timeline;
+ /** The last frame's time: everything is set and the camera is home. The frame there is the poster. */
+ rest: number;
+ /** Every element is in place by then (only a slow camera move may follow). */
+ settled: number;
+ /** A moment that shows what sets this scene apart (a chooser's still picture of it); the rest frame when absent. */
+ signature?: number;
+ /** Times where the picture cuts (motion blur never mixes across one). */
+ cuts: number[];
+ /** Typed fields that don't fit even at their smallest size: the page asks for shorter words, and nothing renders. */
+ overflow: string[];
+ evaluate(t: number): DisplayList;
+ /** Nothing moves at `t` (a held frame needs no motion blur samples). */
+ still(t: number): boolean;
+}
+
+export interface Scene {
+ id: string;
+ name: string;
+ durations: { min: number; max: number; default: number };
+ sizes: SizeSpec[];
+ plan(input: SceneInput): ScenePlan;
+}
+
+export const events = (plan: ScenePlan): MotionEvent[] => plan.timeline.events;
diff --git a/src/lib/motion/scenes/end-card/draw-on.ts b/src/lib/motion/scenes/end-card/draw-on.ts
new file mode 100644
index 00000000..7d44fc58
--- /dev/null
+++ b/src/lib/motion/scenes/end-card/draw-on.ts
@@ -0,0 +1,99 @@
+/**
+ * Draw-on (the default end card): editorial and premium. The logo's outlines trace on in the words' colour and the
+ * logo fills in under them (a raster logo wipes on with a soft edge and settles; no logo: the brand's name sets letter
+ * by letter). The product's name rises line by line out of its own line boxes, the call-to-action pill pops with its
+ * label, the address fades up, and the whole card drifts in on a slow push.
+ */
+
+import { about, group, translate, type DisplayNode } from "../../display";
+import { linearProgress, progress, type Cue } from "../../tween";
+import { endCardScene, letterRuns, lineLeft, lineRun, lineRuns, logoImage, logoPaths, pillRect, wipe } from "./shared";
+
+export default endCardScene("draw-on", ({ rest, input }) => {
+ const { logo, brand, headline, cta, site } = rest;
+ const svg = logo && input.logo?.kind === "svg" && input.logo.paths?.length ? logoPaths(input.logo, logo).sort((a, b) => b.length * b.scale - a.length * a.scale) : null;
+ const traceGroups = svg ? Math.min(svg.length, 5) : 0;
+ const cues: Cue[] = [];
+ if (svg) {
+ for (let g = 0; g < traceGroups; g++) cues.push({ id: `logo.trace.${g}`, kind: "draw", at: g * 0.06, dur: 0.45, curve: "draw", stagger: { group: "logo.trace", unit: "words", index: g, each: 0.06 } });
+ cues.push({ id: "logo.fill", kind: "fade", at: 0.35, dur: 0.3, curve: "enter" });
+ } else if (logo) {
+ cues.push({ id: "logo.wipe", kind: "draw", at: 0, dur: 0.6, curve: "glide" }, { id: "logo.settle", kind: "enter", at: 0, dur: 0.6, curve: "settle" });
+ } else if (brand) {
+ // Letters 30 ms apart; a long name moves in at most 12 beats.
+ const n = brand.layout.lines.reduce((s, l) => s + (l.graphemes ?? l.words).length, 0);
+ const slots = Math.min(n, 12);
+ for (let s = 0; s < slots; s++) cues.push({ id: `brand.beat.${s}`, kind: "enter", at: s * 0.03, dur: 0.4, curve: "glide", stagger: { group: "brand", unit: "letters", index: s, each: 0.03 } });
+ }
+ const lines = headline.layout.lines.length;
+ for (let i = 0; i < lines; i++) cues.push({ id: `headline.line.${i}`, kind: "enter", at: 0.2 + i * 0.09, dur: 0.5, curve: "glide", stagger: { group: "headline", unit: "elements", index: i, each: 0.09 } });
+ if (cta) cues.push({ id: "cta.pill", kind: "pop", at: 0.45, dur: 0.45, curve: "pop" });
+ if (site) cues.push({ id: "site", kind: "enter", at: 0.55, dur: 0.35, curve: "glide" });
+ const beats = brand ? Math.min(12, brand.layout.lines.reduce((s, l) => s + (l.graphemes ?? l.words).length, 0)) : 0;
+ const S = Math.min(rest.w, rest.h);
+
+ return {
+ cues,
+ lead: 0.1,
+ signature: 0.2,
+ frame(t, tl) {
+ const P = (id: string) => progress(tl, id, t);
+ const nodes: DisplayNode[] = [];
+ if (logo && svg) {
+ const fill = P("logo.fill");
+ if (fill > 0) nodes.push(logoImage(logo, fill));
+ if (fill < 1) {
+ const width = logo.h * 0.012;
+ svg.forEach((p, i) => {
+ const trim = P(`logo.trace.${Math.floor((i * traceGroups) / svg.length)}`);
+ if (trim <= 0) return;
+ nodes.push({ type: "path", d: p.d, transform: p.m, stroke: { paint: rest.ink, width: width / p.scale, trim, length: p.length, cap: "round", join: "round" }, opacity: 1 - fill });
+ });
+ }
+ } else if (logo) {
+ const s = 1.04 - 0.04 * P("logo.settle");
+ nodes.push(group([wipe([logoImage(logo)], logo, P("logo.wipe"), logo.w * 0.08)], { transform: about(logo.x + logo.w / 2, logo.y + logo.h / 2, s) }));
+ } else if (brand) {
+ const em = brand.layout.size;
+ // Once every letter is home, the name is drawn as whole lines (the letters sit exactly there).
+ if (P(`brand.beat.${beats - 1}`) >= 1) nodes.push(lineRuns(brand));
+ else
+ nodes.push(
+ letterRuns(brand, (k, n) => {
+ const p = P(`brand.beat.${Math.floor((k * Math.min(n, 12)) / n)}`);
+ return { opacity: p, dy: (1 - p) * 0.25 * em };
+ }),
+ );
+ }
+ // Each line rises out of its own line box.
+ for (let i = 0; i < lines; i++) {
+ const p = P(`headline.line.${i}`);
+ if (p <= 0) continue;
+ const L = headline.layout;
+ const lh = L.lineHeight;
+ const top = headline.y + i * lh;
+ const x = lineLeft(headline, i);
+ if (p >= 1) nodes.push(lineRun(headline, i));
+ else nodes.push(group([lineRun(headline, i, { dy: (1 - p) * lh })], { clip: { type: "rect", x: x - L.size * 0.2, y: top - L.size * 0.08, w: L.lines[i].width + L.size * 0.4, h: lh + L.size * 0.16 } }));
+ }
+ if (cta) {
+ const pop = P("cta.pill");
+ const lin = linearProgress(tl, "cta.pill", t);
+ // Solid within a frame or two; the label rides with the pill from its first frames and is in by 40 % of the pop.
+ const appear = Math.min(1, lin * 8);
+ if (appear > 0) {
+ const s = 0.6 + 0.4 * pop;
+ const label = Math.min(1, Math.max(0, (lin - 0.08) / 0.3));
+ const children: DisplayNode[] = [pillRect(cta)];
+ if (label > 0) children.push({ ...lineRuns(cta.label), ...(label < 1 && { opacity: label }) });
+ nodes.push(group(children, { transform: about(cta.x + cta.w / 2, cta.y + cta.h / 2, s), ...(appear < 1 && { opacity: appear }) }));
+ }
+ }
+ if (site) {
+ const p = P("site");
+ if (p > 0) nodes.push(group([lineRuns(site)], { transform: translate(0, (1 - p) * S * 0.018), ...(p < 1 && { opacity: p }) }));
+ }
+ return { nodes };
+ },
+ };
+});
diff --git a/src/lib/motion/scenes/end-card/glint.ts b/src/lib/motion/scenes/end-card/glint.ts
new file mode 100644
index 00000000..c3465372
--- /dev/null
+++ b/src/lib/motion/scenes/end-card/glint.ts
@@ -0,0 +1,117 @@
+/**
+ * Glint: luxury. The brand colour blooms out from the centre of a deep ground as a wide feathered circle (already
+ * glowing on the first frame); the mark fades up and settles and a wide band of
+ * light passes slowly across it (on the mark only), the product's name settles its tracking as it appears, and the
+ * call-to-action pill draws its outline, then fills with a quick wipe that brings its label.
+ */
+
+import { luminance } from "@/components/ads/layout";
+import { group, mixHex, roundRectPath, withAlpha, type DisplayNode } from "../../display";
+import { linearProgress, progress, type Cue } from "../../tween";
+import { blockCentre, deepGround, endCardScene, entering, letterRuns, lineRuns, markBox, markNodes, pillRect, wipe } from "./shared";
+
+const ANGLE = (20 * Math.PI) / 180;
+
+export default endCardScene("glint", ({ rest }) => {
+ const { headline, cta, site } = rest;
+ const mark = markBox(rest);
+ const cues: Cue[] = [{ id: "bloom", kind: "move", at: 0, dur: 0.55, curve: "glide" }];
+ if (mark) cues.push({ id: "mark", kind: "enter", at: 0.1, dur: 0.5, curve: "settle" }, { id: "glint", kind: "move", at: 0.45, dur: 0.7, curve: "move" });
+ if (headline.layout.lines.length) cues.push({ id: "headline", kind: "enter", at: 0.25, dur: 0.5, curve: "glide" });
+ if (cta) cues.push({ id: "cta.outline", kind: "draw", at: 0.42, dur: 0.22, curve: "draw" }, { id: "cta.fill", kind: "move", at: 0.58, dur: 0.3, curve: "snap" });
+ if (site) cues.push({ id: "site", kind: "fade", at: 0.55, dur: 0.35, curve: "enter" });
+ const ground = deepGround(rest.theme);
+ const S = Math.min(rest.w, rest.h);
+ // The light: on a light mark a warm white; on a dark brand name a lifted tint of its own colour. A logo on a light
+ // ground (its colours unknown, most likely dark) gets no band.
+ const lightMark = rest.logo ? luminance(rest.theme.accent) < 0.3 : luminance(rest.ink) > 0.3;
+ const sheen = lightMark ? "#fff4dc" : rest.logo ? null : mixHex(rest.ink, "#ffffff", 0.45);
+ const sheenAlpha = 0.75;
+
+ return {
+ cues,
+ lead: 0.06,
+ signature: 0.12,
+ background: ground,
+ frame(t, tl) {
+ const P = (id: string) => progress(tl, id, t);
+ const under: DisplayNode[] = [];
+ const bloom = P("bloom");
+ if (bloom > 0) {
+ // A feathered circle of the brand colour, grown until it covers the frame.
+ const cx = rest.w / 2;
+ const cy = rest.h * 0.45;
+ const far = Math.hypot(Math.max(cx, rest.w - cx), Math.max(cy, rest.h - cy));
+ const r = far * (0.2 + 1.5 * bloom);
+ const a = rest.theme.accent;
+ under.push({
+ type: "rect",
+ id: "bloom",
+ x: 0,
+ y: 0,
+ w: rest.w,
+ h: rest.h,
+ fill: { kind: "radial", cx, cy, r0: 0, r1: r, stops: [{ at: 0, color: a }, { at: 0.62, color: a }, { at: 0.82, color: withAlpha(a, 0.5) }, { at: 1, color: withAlpha(a, 0) }] },
+ });
+ }
+ const nodes: DisplayNode[] = [];
+ if (mark) {
+ const p = P("mark");
+ const seen = Math.min(1, linearProgress(tl, "mark", t) * 2);
+ if (seen > 0) {
+ const children: DisplayNode[] = [...markNodes(rest)];
+ const g = linearProgress(tl, "glint", t);
+ if (sheen && g > 0 && g < 1) {
+ // A wide band of light at 20°, crossing the mark once, drawn on the mark's own pixels only.
+ const dx = Math.cos(ANGLE);
+ const dy = Math.sin(ANGLE);
+ const reach = mark.w * 0.5 + mark.h * 0.5;
+ const band = Math.hypot(mark.w, mark.h) * 0.3;
+ const along = -(reach + band) + 2 * (reach + band) * P("glint");
+ const gx = mark.x + mark.w / 2 + dx * along;
+ const gy = mark.y + mark.h / 2 + dy * along;
+ children.push(
+ group(
+ [
+ {
+ type: "rect",
+ id: "glint",
+ x: mark.x,
+ y: mark.y,
+ w: mark.w,
+ h: mark.h,
+ fill: { kind: "linear", x0: gx - dx * band, y0: gy - dy * band, x1: gx + dx * band, y1: gy + dy * band, stops: [{ at: 0, color: withAlpha(sheen, 0) }, { at: 0.5, color: withAlpha(sheen, sheenAlpha) }, { at: 1, color: withAlpha(sheen, 0) }] },
+ },
+ ],
+ { blend: "source-atop" },
+ ),
+ );
+ }
+ const node = entering(children, { cx: mark.x + mark.w / 2, cy: mark.y + mark.h / 2, dy: (1 - p) * S * 0.05, scale: 0.97 + 0.03 * p, opacity: seen });
+ if (node.type === "group" && children.length > 1) node.isolate = { x: mark.x - 4, y: mark.y - 4, w: mark.w + 8, h: mark.h + 8 };
+ nodes.push(node);
+ }
+ }
+ if (headline.layout.lines.length) {
+ const p = P("headline");
+ if (p >= 1) nodes.push(lineRuns(headline));
+ else if (p > 0) nodes.push({ ...letterRuns(headline, () => ({}), (1 - p) * 0.06 * headline.layout.size), opacity: p });
+ }
+ if (cta) {
+ const outline = P("cta.outline");
+ const fill = P("cta.fill");
+ if (fill > 0) nodes.push(wipe([pillRect(cta), lineRuns(cta.label)], cta, fill, cta.h * 0.5));
+ if (outline > 0 && fill < 1) {
+ const width = S * 0.004;
+ const path = roundRectPath(cta.x + width / 2, cta.y + width / 2, cta.w - width, cta.h - width, cta.r - width / 2);
+ nodes.push({ type: "path", d: path.d, stroke: { paint: cta.color, width, trim: outline, length: path.length, cap: "round" } });
+ }
+ }
+ if (site) {
+ const p = P("site");
+ if (p > 0) nodes.push(entering([lineRuns(site)], { ...blockCentre(site), opacity: p }));
+ }
+ return { under, nodes };
+ },
+ };
+});
diff --git a/src/lib/motion/scenes/end-card/iris.ts b/src/lib/motion/scenes/end-card/iris.ts
new file mode 100644
index 00000000..5a5f7365
--- /dev/null
+++ b/src/lib/motion/scenes/end-card/iris.ts
@@ -0,0 +1,74 @@
+/**
+ * Iris: cinematic. A circle of the brand colour opens from the centre over the kit's second colour (already open a
+ * quarter on the first frame, with a fine rim in the words' colour on a deep ground); the mark comes into focus as it
+ * settles to size, the product's name tightens its letter-spacing as it appears, the address fades in and the
+ * call-to-action pill pops last.
+ */
+
+import { about, group, withAlpha, type DisplayNode } from "../../display";
+import { linearProgress, progress, type Cue } from "../../tween";
+import { blockCentre, deepGround, endCardScene, entering, letterRuns, lineRuns, markBox, markNodes, openingGround, pillRect } from "./shared";
+
+export default endCardScene("iris", ({ rest, second }) => {
+ const { headline, cta, site } = rest;
+ const mark = markBox(rest);
+ const cues: Cue[] = [{ id: "iris", kind: "move", at: 0, dur: 0.65, curve: "glide" }];
+ if (mark) cues.push({ id: "mark", kind: "enter", at: 0.15, dur: 0.5, curve: "settle" });
+ if (headline.layout.lines.length) cues.push({ id: "headline", kind: "enter", at: 0.3, dur: 0.5, curve: "glide" });
+ if (site) cues.push({ id: "site", kind: "fade", at: 0.5, dur: 0.35, curve: "enter" });
+ if (cta) cues.push({ id: "cta", kind: "pop", at: 0.5, dur: 0.4, curve: "pop" });
+ const ground = openingGround(rest.theme, second);
+ // On a deep ground a fine rim in the words' colour draws the circle's edge.
+ const rim = ground === deepGround(rest.theme) && ground !== second ? rest.ink : null;
+ const S = Math.min(rest.w, rest.h);
+
+ return {
+ cues,
+ lead: 0.06,
+ signature: 0.14,
+ background: ground,
+ frame(t, tl) {
+ const P = (id: string) => progress(tl, id, t);
+ const under: DisplayNode[] = [];
+ const R = Math.hypot(rest.w / 2, rest.h / 2) + 4;
+ const open = P("iris");
+ const r = open * R;
+ if (r > 0.5) {
+ // A soft edge a few units wide.
+ const edge = Math.max(0, (r - 3) / r);
+ under.push({
+ type: "ellipse",
+ id: "iris",
+ cx: rest.w / 2,
+ cy: rest.h / 2,
+ rx: r,
+ ry: r,
+ fill: { kind: "radial", cx: rest.w / 2, cy: rest.h / 2, r0: 0, r1: r, stops: [{ at: 0, color: rest.theme.accent }, { at: edge, color: rest.theme.accent }, { at: 1, color: withAlpha(rest.theme.accent, 0) }] },
+ ...(rim && open < 1 && { stroke: { paint: withAlpha(rim, 0.9 * (1 - open * open)), width: S * 0.006 } }),
+ });
+ }
+ const nodes: DisplayNode[] = [];
+ if (mark) {
+ const p = P("mark");
+ const seen = Math.min(1, linearProgress(tl, "mark", t) * 2.5);
+ if (seen > 0) nodes.push(entering(markNodes(rest), { cx: mark.x + mark.w / 2, cy: mark.y + mark.h / 2, scale: 0.9 + 0.1 * p, opacity: seen, blur: (1 - Math.min(1, p)) * 9 }));
+ }
+ if (headline.layout.lines.length) {
+ const p = P("headline");
+ // Letter by letter while the spacing tightens; whole lines once it is home (the letters sit exactly there).
+ if (p >= 1) nodes.push(lineRuns(headline));
+ else if (p > 0) nodes.push({ ...letterRuns(headline, () => ({}), (1 - p) * 0.12 * headline.layout.size), opacity: p });
+ }
+ if (site) {
+ const p = P("site");
+ if (p > 0) nodes.push(entering([lineRuns(site)], { ...blockCentre(site), opacity: p }));
+ }
+ if (cta) {
+ const p = P("cta");
+ const seen = Math.min(1, linearProgress(tl, "cta", t) * 6);
+ if (seen > 0) nodes.push(group([pillRect(cta), lineRuns(cta.label)], { transform: about(cta.x + cta.w / 2, cta.y + cta.h / 2, 0.7 + 0.3 * p), ...(seen < 1 && { opacity: seen }) }));
+ }
+ return { under, nodes };
+ },
+ };
+});
diff --git a/src/lib/motion/scenes/end-card/rise.ts b/src/lib/motion/scenes/end-card/rise.ts
new file mode 100644
index 00000000..61699b61
--- /dev/null
+++ b/src/lib/motion/scenes/end-card/rise.ts
@@ -0,0 +1,48 @@
+/**
+ * Rise: bold and fast. The brand colour sweeps up from the bottom as a panel over the kit's second colour (already on
+ * its way on the first frame), then the mark, the product's name and the call to action rise into place one after
+ * another, the pill with a short pop, and the card drifts in on a slow push.
+ */
+
+import { about, group, multiply, translate, type DisplayNode } from "../../display";
+import { progress, type Cue } from "../../tween";
+import { blockCentre, endCardScene, entering, lineRuns, markBox, markNodes, pillRect } from "./shared";
+
+export default endCardScene("rise", ({ rest, second }) => {
+ const { headline, cta, site } = rest;
+ const mark = markBox(rest);
+ const items = [mark && "mark", headline.layout.lines.length && "headline", cta && "cta"].filter(Boolean) as string[];
+ const cues: Cue[] = [{ id: "panel", kind: "move", at: 0, dur: 0.45, curve: "snap" }];
+ items.forEach((id, i) => cues.push({ id, kind: "enter", at: 0.18 + i * 0.11, dur: 0.5, curve: "glide", stagger: { group: "blocks", unit: "elements", index: i, each: 0.11 } }));
+ if (cta) cues.push({ id: "cta.pop", kind: "pop", at: 0.18 + (items.length - 1) * 0.11, dur: 0.5, curve: "pop" });
+ if (site) cues.push({ id: "site", kind: "enter", at: 0.5, dur: 0.35, curve: "glide" });
+ const S = Math.min(rest.w, rest.h);
+
+ return {
+ cues,
+ // The panel is about a quarter of the way up on the first frame.
+ lead: 0.055,
+ signature: 0.075,
+ background: second,
+ frame(t, tl) {
+ const P = (id: string) => progress(tl, id, t);
+ const lift = S * 0.1;
+ const panel = P("panel");
+ const under: DisplayNode[] = panel > 0 ? [{ type: "rect", id: "panel", x: 0, y: rest.h * (1 - panel), w: rest.w, h: rest.h * panel + 1, fill: rest.theme.accent }] : [];
+ const nodes: DisplayNode[] = [];
+ const rise = (id: string, children: DisplayNode[], c: { cx: number; cy: number }) => {
+ const p = P(id);
+ if (p > 0) nodes.push(entering(children, { ...c, dy: (1 - p) * lift, opacity: Math.min(1, p * 1.6) }));
+ };
+ if (mark) rise("mark", markNodes(rest), { cx: mark.x + mark.w / 2, cy: mark.y + mark.h / 2 });
+ if (headline.layout.lines.length) rise("headline", [lineRuns(headline)], blockCentre(headline));
+ if (cta) {
+ const s = 0.9 + 0.1 * P("cta.pop");
+ const p = P("cta");
+ if (p > 0) nodes.push(group([pillRect(cta), lineRuns(cta.label)], { transform: multiply(translate(0, (1 - p) * lift), about(cta.x + cta.w / 2, cta.y + cta.h / 2, s)), ...(p < 1 / 1.6 && { opacity: p * 1.6 }) }));
+ }
+ if (site) rise("site", [lineRuns(site)], blockCentre(site));
+ return { under, nodes };
+ },
+ };
+});
diff --git a/src/lib/motion/scenes/end-card/shared.ts b/src/lib/motion/scenes/end-card/shared.ts
new file mode 100644
index 00000000..ef485135
--- /dev/null
+++ b/src/lib/motion/scenes/end-card/shared.ts
@@ -0,0 +1,395 @@
+/**
+ * The logo end card, shared by its five animated styles (pure). The card at rest is one centred stack on the brand
+ * colour: the logo (or the brand's name), the product's name, the call-to-action pill and the shop's address under it,
+ * in the kit's own colours. That rest layout is also the still card's (components/marketing/end-card.ts), so the
+ * poster, the still and the last frame of every style are the same picture. Each style is a timeline of cues written
+ * for a 2.5 s card (readable by about 0.9 s) and scaled to the card's length, and a frame function that moves the rest
+ * layout's pieces. Through the hold a slow push-in keeps the card alive and comes to rest on the last frame.
+ */
+
+import { contrast, luminance, readableOn, themeFrom, type AdTheme } from "@/components/ads/layout";
+import { about, group, mixHex, multiply, translate, type DisplayList, type DisplayNode, type Matrix, type TextNode, type TextRun } from "../../display";
+import { curve } from "../../ease";
+import { layoutText, type Measure, type TextLayout } from "../../layout";
+import type { Recipe } from "../../recipe";
+import type { LogoInfo, Scene, SceneInput, ScenePlan } from "../../scene";
+import { designSize } from "../../sizes";
+import { frameCount } from "../../time";
+import { timeline, scaleCues, type Cue, type Timeline } from "../../tween";
+
+export const END_CARD_VARIANTS = ["draw-on", "rise", "iris", "split", "glint"] as const;
+export type EndCardVariant = (typeof END_CARD_VARIANTS)[number];
+
+export const END_CARD_VARIANT_NAMES: Record<EndCardVariant, string> = { "draw-on": "Draw-on", rise: "Rise", iris: "Iris", split: "Split", glint: "Glint" };
+
+/** The card's lengths (seconds), as Click to Ad's end card allows. */
+export const END_CARD_DURATIONS = { min: 2, max: 3, default: 2.5 } as const;
+
+export interface EndCardContent {
+ /** Shown when there is no logo. */
+ brand: string;
+ product: string;
+ cta?: string;
+ website?: string;
+}
+
+export interface TextBlock {
+ field: string;
+ layout: TextLayout;
+ /** The block's centre line and the top of its first line. */
+ cx: number;
+ y: number;
+ color: string;
+}
+
+export interface EndCardRest {
+ w: number;
+ h: number;
+ /** The side margin and the width text may take. */
+ margin: number;
+ inner: number;
+ theme: AdTheme;
+ /** The words' colour on the brand colour (a kit colour that reads on it, else white or near-black). */
+ ink: string;
+ logo?: { x: number; y: number; w: number; h: number };
+ brand?: TextBlock;
+ headline: TextBlock;
+ cta?: { x: number; y: number; w: number; h: number; r: number; color: string; label: TextBlock };
+ site?: TextBlock;
+ /** Fields that don't fit at their smallest size (or a stack too tall for the frame). */
+ overflow: (keyof EndCardContent)[];
+}
+
+const HEX = /^#[0-9a-f]{6}$/i;
+
+/**
+ * The card's colours from the kit: the words and the pill in the kit colour that reads best on the brand colour (at
+ * least 4.5:1), the pill's label in the brand colour; white or near-black only when no kit colour reads.
+ */
+export function cardColours(theme: AdTheme, colors: readonly string[]): { ink: string; pill: string; label: string } {
+ const accent = theme.accent.toLowerCase();
+ const best = colors
+ .filter((c) => HEX.test(c) && c.toLowerCase() !== accent)
+ .map((c) => ({ c, k: contrast(c, theme.accent) }))
+ .sort((a, b) => b.k - a.k)[0];
+ const ink = best && best.k >= 4.5 ? best.c : theme.onAccent;
+ return { ink, pill: ink, label: contrast(theme.accent, ink) >= 3 ? theme.accent : readableOn(ink) };
+}
+
+/**
+ * Where everything goes on the card (the still card's own layout): one centred stack (logo or name, product, CTA,
+ * address) a little above the middle. Type, the pill and the margins follow the frame's short side, so a wide card
+ * sets the same sizes as a tall one; a tall card keeps its foot clear (where phone apps put their buttons and
+ * captions). Text is set as typed (layoutText); a stack too tall for the frame is reported, never squeezed.
+ */
+export function endCardRest(p: { theme: AdTheme; content: EndCardContent; logo: { w: number; h: number } | null; measure: Measure; size: { w: number; h: number }; letters?: boolean; colors?: readonly string[] }): EndCardRest {
+ const { w: W, h: H } = p.size;
+ const t = p.theme;
+ const S = Math.min(W, H);
+ // The vertical unit: the height, up to a 9:16 card's.
+ const V = Math.min(H, (S * 16) / 9);
+ const m = Math.round(S * 0.1);
+ const inner = Math.min(W - 2 * m, Math.round(S * 1.1));
+ const { ink, pill, label: labelColour } = cardColours(t, p.colors ?? []);
+ const gap = V * 0.04;
+ const logoH = V * 0.15;
+ const letters = p.letters ?? true;
+ const brandText = p.content.brand.trim();
+ const name = !p.logo && brandText ? layoutText({ text: brandText, family: t.heading, weight: 800, width: inner, maxLines: 2, max: S * 0.1, min: S * 0.06, lineHeight: 1.05, letters }, p.measure) : null;
+ const head = layoutText({ text: p.content.product, family: t.heading, weight: 700, width: inner, maxLines: 2, max: S * 0.068, min: S * 0.045, letters }, p.measure);
+ const ctaSize = S * 0.045;
+ const ctaText = p.content.cta?.trim();
+ const label = ctaText ? layoutText({ text: ctaText, family: t.body, weight: 700, width: inner - ctaSize * 2.4, maxLines: 1, max: ctaSize, min: S * 0.03 }, p.measure) : null;
+ const siteText = p.content.website?.trim();
+ const site = siteText ? layoutText({ text: siteText, family: t.body, weight: 500, width: inner, maxLines: 1, max: S * 0.032, min: S * 0.024 }, p.measure) : null;
+ const ctaH = label ? label.size * 2.3 : 0;
+ const top = p.logo ? logoH : name ? name.lines.length * name.size * 1.05 : 0;
+ const headH = head.lines.length * head.size * 1.12;
+ const siteH = site ? site.size * 1.12 : 0;
+ const siteGap = gap * 0.9;
+ const above = top + (top ? gap : 0) + headH + (label ? gap * 1.4 + ctaH : 0);
+ const total = above + (site ? (above ? siteGap : 0) + siteH : 0);
+ let y = (H - total) / 2 - V * 0.03;
+ // A tall card keeps its bottom fifth clear.
+ if (H / W > 1.5) y = Math.min(y, H * 0.8 - total);
+ const fits = y >= m - 0.5 && y + total <= H - m + 0.5;
+ y = Math.max(m, y);
+
+ let logo: EndCardRest["logo"];
+ let brand: TextBlock | undefined;
+ if (p.logo) {
+ // Contained in the logo's band, centred.
+ const s = Math.min(inner / p.logo.w, logoH / p.logo.h);
+ const fw = p.logo.w * s;
+ const fh = p.logo.h * s;
+ logo = { x: (W - fw) / 2, y: y + (logoH - fh) / 2, w: fw, h: fh };
+ y += logoH + gap;
+ } else if (name) {
+ brand = { field: "brand", layout: name, cx: W / 2, y, color: ink };
+ y += top + gap;
+ }
+ const headline: TextBlock = { field: "product", layout: head, cx: W / 2, y, color: ink };
+ y += headH;
+ let cta: EndCardRest["cta"];
+ if (label) {
+ y += gap * 1.4;
+ const bw = Math.min(inner, label.width + label.size * 2.4);
+ const bx = (W - bw) / 2;
+ cta = { x: bx, y, w: bw, h: ctaH, r: ctaH / 2, color: pill, label: { field: "cta", layout: label, cx: bx + bw / 2, y: y + (ctaH - label.size * 1.12) / 2, color: labelColour } };
+ y += ctaH;
+ }
+ const siteBlock: TextBlock | undefined = site ? { field: "website", layout: site, cx: W / 2, y: y + (above ? siteGap : 0), color: ink } : undefined;
+ const overflow: (keyof EndCardContent)[] = [];
+ if (name?.overflow) overflow.push("brand");
+ if (head.overflow) overflow.push("product");
+ if (label?.overflow) overflow.push("cta");
+ if (site?.overflow) overflow.push("website");
+ // Every field fits but the stack doesn't: the field that takes two lines is the one to shorten.
+ if (!fits && !overflow.length) overflow.push(name && name.lines.length > 1 && head.lines.length < 2 ? "brand" : "product");
+ return { w: W, h: H, margin: m, inner, theme: t, ink, logo, brand, headline, cta, site: siteBlock, overflow };
+}
+
+// ---------------------------------------------------------------------------
+// Text runs
+
+/** Where line `i` of a block is drawn: its left edge and the top of its glyphs (as the still card's drawText). */
+export const lineLeft = (b: TextBlock, i: number) => b.cx - b.layout.lines[i].width / 2;
+export const glyphTop = (b: TextBlock, i: number) => b.y + i * b.layout.lineHeight + (b.layout.lineHeight - b.layout.size) / 2;
+
+export interface RunStyle {
+ dx?: number;
+ dy?: number;
+ opacity?: number;
+ scale?: number;
+}
+
+function styled(run: TextRun, s: RunStyle | undefined, w: number, size: number): TextRun {
+ if (!s) return run;
+ const out = { ...run, x: run.x + (s.dx ?? 0), y: run.y + (s.dy ?? 0) };
+ if (s.opacity !== undefined && s.opacity < 1) out.opacity = Math.max(0, s.opacity);
+ if (s.scale !== undefined && s.scale !== 1) out.transform = about(out.x + w / 2, out.y + size / 2, s.scale);
+ return out;
+}
+
+/** The block line by line. */
+export function lineRuns(b: TextBlock, each?: (line: number) => RunStyle): TextNode {
+ const L = b.layout;
+ return {
+ type: "text",
+ field: b.field,
+ runs: L.lines.map((l, i) => styled({ text: l.text, gap: l.gap, font: L.font, x: lineLeft(b, i), y: glyphTop(b, i), fill: b.color, ...(L.dir === "rtl" && { dir: "rtl" as const }) }, each?.(i), l.width, L.size)),
+ };
+}
+
+/** One line of a block on its own. */
+export function lineRun(b: TextBlock, i: number, style?: RunStyle): TextNode {
+ const L = b.layout;
+ const l = L.lines[i];
+ return { type: "text", field: b.field, runs: [styled({ text: l.text, gap: l.gap, font: L.font, x: lineLeft(b, i), y: glyphTop(b, i), fill: b.color, ...(L.dir === "rtl" && { dir: "rtl" as const }) }, style, l.width, L.size)] };
+}
+
+/** The block word by word; `each` gets the word's line, its index in the block and the block's word count. */
+export function wordRuns(b: TextBlock, each: (line: number, word: number, count: number) => RunStyle): TextNode {
+ const L = b.layout;
+ const count = L.lines.reduce((n, l) => n + l.words.length, 0);
+ let k = 0;
+ const runs: TextRun[] = [];
+ L.lines.forEach((l, i) => {
+ const left = lineLeft(b, i);
+ const top = glyphTop(b, i);
+ for (const w of l.words) runs.push(styled({ text: w.text, gap: w.gap, font: L.font, x: left + w.x, y: top, fill: b.color, ...(L.dir === "rtl" && { dir: "rtl" as const }) }, each(i, k++, count), w.w, L.size));
+ });
+ return { type: "text", field: b.field, runs };
+}
+
+/**
+ * The block letter by letter (grapheme clusters), with `spacing` extra units between letters (kept centred). A line
+ * whose letters join (a joining script, or a pair a font ligates) goes word by word instead, with the spacing between
+ * words. At spacing 0 every piece sits exactly where the whole line draws it (layout.ts keeps the kerning).
+ */
+export function letterRuns(b: TextBlock, each: (letter: number, count: number) => RunStyle, spacing = 0): TextNode {
+ const L = b.layout;
+ const pieces = L.lines.map((l) => l.graphemes ?? l.words);
+ const count = pieces.reduce((n, p) => n + p.length, 0);
+ let k = 0;
+ const runs: TextRun[] = [];
+ L.lines.forEach((l, i) => {
+ const ps = pieces[i];
+ const left = lineLeft(b, i) - ((ps.length - 1) * spacing) / 2;
+ const top = glyphTop(b, i);
+ ps.forEach((p, j) => {
+ runs.push(styled({ text: p.text, gap: p.gap, font: L.font, x: left + p.x + j * spacing, y: top, fill: b.color, ...(L.dir === "rtl" && { dir: "rtl" as const }) }, each(k++, count), p.w, L.size));
+ });
+ });
+ return { type: "text", field: b.field, runs };
+}
+
+// ---------------------------------------------------------------------------
+// The rest frame
+
+/** The logo as drawn at rest. */
+export const logoImage = (r: NonNullable<EndCardRest["logo"]>, opacity = 1): DisplayNode => ({ type: "image", id: "logo", src: "logo", x: r.x, y: r.y, w: r.w, h: r.h, ...(opacity < 1 && { opacity }) });
+
+export const pillRect = (c: NonNullable<EndCardRest["cta"]>): DisplayNode => ({ type: "rect", id: "cta.pill", x: c.x, y: c.y, w: c.w, h: c.h, r: c.r, fill: c.color });
+
+/** The card at rest: what the still card draws, in the same order. */
+export function restNodes(r: EndCardRest): DisplayNode[] {
+ const nodes: DisplayNode[] = [];
+ if (r.logo) nodes.push(logoImage(r.logo));
+ if (r.brand) nodes.push(lineRuns(r.brand));
+ if (r.headline.layout.lines.length) nodes.push(lineRuns(r.headline));
+ if (r.cta) nodes.push(pillRect(r.cta), lineRuns(r.cta.label));
+ if (r.site) nodes.push(lineRuns(r.site));
+ return nodes;
+}
+
+/** The mark at the top of the block: the logo, else the brand's name, else nothing. */
+export const markNodes = (r: EndCardRest): DisplayNode[] => (r.logo ? [logoImage(r.logo)] : r.brand ? [lineRuns(r.brand)] : []);
+
+/** The mark's box (null: no mark). */
+export function markBox(r: EndCardRest): { x: number; y: number; w: number; h: number } | null {
+ if (r.logo) return r.logo;
+ if (r.brand) return { x: r.brand.cx - r.brand.layout.width / 2, y: r.brand.y, w: r.brand.layout.width, h: r.brand.layout.height };
+ return null;
+}
+
+/** A second brand colour for panels and grounds: the kit's next colour that differs enough, else a deeper accent. */
+export function secondColour(colors: readonly string[], accent: string): string {
+ const other = colors.find((c) => HEX.test(c) && c.toLowerCase() !== accent.toLowerCase() && contrast(c, accent) >= 1.25);
+ return other ?? mixHex(accent, "#000000", 0.32);
+}
+
+/**
+ * A deep ground under the brand colour (Glint blooms from it): the kit's ink when it stands apart from the accent, else
+ * the accent taken down towards black.
+ */
+export function deepGround(theme: AdTheme): string {
+ return contrast(theme.ink, theme.accent) >= 1.8 ? theme.ink : mixHex(theme.accent, "#000000", 0.62);
+}
+
+/** A ground a style opens on: the kit's second colour when it stands apart from the brand colour, else the deep ground. */
+export function openingGround(theme: AdTheme, second: string): string {
+ return contrast(second, theme.accent) >= 1.8 ? second : deepGround(theme);
+}
+
+/** A colour's own deeper (or, for a very dark one, lighter) shade: the second of a two-tone pair. */
+export const shadeOf = (c: string) => (luminance(c) < 0.05 ? mixHex(c, "#ffffff", 0.14) : mixHex(c, "#000000", 0.22));
+
+/** The logo's outlines placed in its rest box: each path's matrix from its own units to design units. */
+export function logoPaths(logo: LogoInfo, box: NonNullable<EndCardRest["logo"]>): { d: string; m: Matrix; length: number; scale: number }[] {
+ const vb = logo.viewBox ?? { x: 0, y: 0, w: logo.w, h: logo.h };
+ const s = Math.min(box.w / vb.w, box.h / vb.h);
+ const place: Matrix = [s, 0, 0, s, box.x + (box.w - vb.w * s) / 2 - vb.x * s, box.y + (box.h - vb.h * s) / 2 - vb.y * s];
+ return (logo.paths ?? []).map((p) => {
+ const m = multiply(place, p.m);
+ return { d: p.d, m, length: p.length, scale: Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2])) || 1 };
+ });
+}
+
+// ---------------------------------------------------------------------------
+// The scene
+
+/** The card's content and theme from a recipe (fields brand, product, cta, website; the brand's colours and fonts). */
+export function endCardFrom(recipe: Recipe): { theme: AdTheme; content: EndCardContent } {
+ const f = recipe.fields;
+ return {
+ theme: themeFrom({ colors: recipe.brand.colors, fonts: recipe.brand.fonts }),
+ content: { brand: f.brand ?? recipe.brand.name ?? "", product: f.product ?? "", cta: f.cta || undefined, website: f.website || undefined },
+ };
+}
+
+/** How much a 2.5 s card's timing is stretched for this length (2 s: × 0.67, 3 s: × 1.33). */
+export const timeScale = (duration: number) => Math.max(2 / 3, Math.min(4 / 3, (duration - 1) / 1.5));
+
+/** A style's picture at one time: grounds under the camera, the card's pieces in it, covers over it. */
+export interface StyleFrame {
+ under?: DisplayNode[];
+ nodes: DisplayNode[];
+ over?: DisplayNode[];
+}
+
+export interface StyleBuild {
+ cues: Cue[];
+ /**
+ * How far (seconds, on a 2.5 s card) the card is already into its motion on its first frame: the cut from the ad
+ * lands on movement, never on an empty frame.
+ */
+ lead?: number;
+ /** A time (seconds, on a 2.5 s card, before the lead) whose frame shows what sets this style apart. */
+ signature?: number;
+ /** The ground under everything while it moves (the brand colour by default). */
+ background?: string;
+ frame(t: number, tl: Timeline): StyleFrame;
+}
+
+export interface StyleContext {
+ rest: EndCardRest;
+ input: SceneInput;
+ /** The second brand colour. */
+ second: string;
+}
+
+/** The push-in: the card's pieces start at this scale and reach 1 on the last frame. */
+export const CAMERA_FROM = 0.97;
+
+/** One end-card style as a scene: the rest layout, its cues scaled to the card's length, and its frames. */
+export function endCardScene(variant: EndCardVariant, build: (c: StyleContext) => StyleBuild): Scene {
+ return {
+ id: `end-card/${variant}`,
+ name: END_CARD_VARIANT_NAMES[variant],
+ durations: END_CARD_DURATIONS,
+ sizes: [{ w: 720, h: 1280 }, "9:16", "4:5", "1:1", "16:9"],
+ plan(input: SceneInput): ScenePlan {
+ const design = designSize(input.recipe.size);
+ const { theme, content } = endCardFrom(input.recipe);
+ const rest = endCardRest({ theme, content, logo: input.logo ? { w: input.logo.w, h: input.logo.h } : null, measure: input.measure, size: design, colors: input.recipe.brand.colors });
+ const style = build({ rest, input, second: secondColour(input.recipe.brand.colors, theme.accent) });
+ const k = timeScale(input.recipe.duration);
+ const lead = (style.lead ?? 0) * k;
+ const tl = timeline(scaleCues(style.cues, k).map((e) => ({ ...e, start: Math.round((e.start - lead) * 1e6) / 1e6 })));
+ // The last frame: the poster, the still card, and where the camera comes home.
+ const last = (frameCount(input.recipe.duration, input.recipe.fps) - 1) / input.recipe.fps;
+ const settled = Math.min(last, tl.rest);
+ const still: DisplayList = { w: design.w, h: design.h, background: theme.accent, nodes: restNodes(rest) };
+ const drift = curve("drift");
+ const camera = (t: number, nodes: DisplayNode[]): DisplayNode[] => {
+ const z = CAMERA_FROM + (1 - CAMERA_FROM) * drift(last > 0 ? t / last : 1);
+ return z >= 1 ? nodes : [group(nodes, { id: "camera", transform: about(design.w / 2, design.h / 2, z) })];
+ };
+ return {
+ design,
+ timeline: tl,
+ rest: last,
+ settled,
+ ...(style.signature !== undefined && { signature: Math.min(last, Math.max(0, style.signature * k - lead)) }),
+ cuts: [],
+ overflow: rest.overflow,
+ evaluate: (t) => {
+ if (t >= last) return still;
+ if (t >= settled) return { ...still, nodes: camera(t, still.nodes) };
+ const f = style.frame(t, tl);
+ return { w: design.w, h: design.h, background: style.background ?? theme.accent, nodes: [...(f.under ?? []), ...camera(t, f.nodes), ...(f.over ?? [])] };
+ },
+ still: (t) => t >= last,
+ };
+ },
+ };
+}
+
+/** A group moved by `dy`, scaled about (cx, cy) and faded: the common entrance of a block. */
+export function entering(children: DisplayNode[], o: { cx: number; cy: number; dy?: number; scale?: number; opacity?: number; blur?: number }): DisplayNode {
+ const m = multiply(translate(0, o.dy ?? 0), about(o.cx, o.cy, o.scale ?? 1));
+ return group(children, { transform: m, ...(o.opacity !== undefined && o.opacity < 1 && { opacity: Math.max(0, o.opacity) }), ...(o.blur && o.blur > 0.05 && { blur: o.blur }) });
+}
+
+/** A block's middle (for scaling about it). */
+export const blockCentre = (b: TextBlock) => ({ cx: b.cx, cy: b.y + b.layout.height / 2 });
+
+/** A soft-edged reveal of `children` left to right: `p` 0 shows nothing, 1 everything (the edge is `feather` wide). */
+export function wipe(children: DisplayNode[], box: { x: number; y: number; w: number; h: number }, p: number, feather: number): DisplayNode {
+ if (p >= 1) return group(children);
+ const edge = box.x - feather + (box.w + 2 * feather) * p;
+ return group(children, {
+ mask: { kind: "linear", x0: edge - feather, y0: 0, x1: edge, y1: 0, stops: [{ at: 0, color: "rgba(0,0,0,1)" }, { at: 1, color: "rgba(0,0,0,0)" }], bounds: { x: box.x - feather, y: box.y - feather, w: box.w + 2 * feather, h: box.h + 2 * feather } },
+ });
+}
diff --git a/src/lib/motion/scenes/end-card/split.ts b/src/lib/motion/scenes/end-card/split.ts
new file mode 100644
index 00000000..3b92e4f1
--- /dev/null
+++ b/src/lib/motion/scenes/end-card/split.ts
@@ -0,0 +1,79 @@
+/**
+ * Split: graphic. Two half panels in a clean two-tone of the kit's second colour part to the sides and reveal the
+ * card; the mark grows into place at the seam between them, the product's name cascades in word by word, then a line
+ * draws under the call to action and the pill grows up from it, its round ends kept, with its label.
+ */
+
+import { group, type DisplayNode } from "../../display";
+import { linearProgress, progress, type Cue } from "../../tween";
+import { endCardScene, entering, lineRuns, markBox, markNodes, shadeOf, wordRuns } from "./shared";
+
+export default endCardScene("split", ({ rest, second }) => {
+ const { headline, cta, site } = rest;
+ const mark = markBox(rest);
+ const words = headline.layout.lines.reduce((n, l) => n + l.words.length, 0);
+ const slots = Math.min(words, 8);
+ const cues: Cue[] = [{ id: "panels", kind: "move", at: 0, dur: 0.55, curve: "move" }];
+ if (mark) cues.push({ id: "mark", kind: "enter", at: 0.15, dur: 0.5, curve: "settle" });
+ for (let s = 0; s < slots; s++) cues.push({ id: `headline.word.${s}`, kind: "enter", at: 0.28 + s * 0.065, dur: 0.45, curve: "glide", stagger: { group: "headline", unit: "words", index: s, each: 0.065 } });
+ if (cta) cues.push({ id: "cta.line", kind: "draw", at: 0.48, dur: 0.2, curve: "draw" }, { id: "cta.fill", kind: "move", at: 0.6, dur: 0.3, curve: "snap" });
+ if (site) cues.push({ id: "site", kind: "fade", at: 0.55, dur: 0.35, curve: "enter" });
+ const left = second;
+ const right = shadeOf(second);
+ const S = Math.min(rest.w, rest.h);
+
+ return {
+ cues,
+ lead: 0.05,
+ signature: 0.3,
+ frame(t, tl) {
+ const P = (id: string) => progress(tl, id, t);
+ const nodes: DisplayNode[] = [];
+ if (mark) {
+ const p = P("mark");
+ const seen = Math.min(1, linearProgress(tl, "mark", t) * 2);
+ if (seen > 0) nodes.push(entering(markNodes(rest), { cx: mark.x + mark.w / 2, cy: mark.y + mark.h / 2, scale: 1.08 - 0.08 * p, opacity: seen }));
+ }
+ if (words) {
+ const em = headline.layout.size;
+ if (P(`headline.word.${slots - 1}`) >= 1) nodes.push(lineRuns(headline));
+ else
+ nodes.push(
+ wordRuns(headline, (_l, k, n) => {
+ const p = P(`headline.word.${Math.floor((k * slots) / n)}`);
+ return { opacity: Math.min(1, p * 1.3), dy: (1 - p) * 0.4 * em };
+ }),
+ );
+ }
+ if (cta) {
+ const line = P("cta.line");
+ const fill = P("cta.fill");
+ const base = cta.y + cta.h;
+ if (fill > 0) {
+ // The pill grows up from its baseline as a pill (round ends kept); its label is revealed with it.
+ const h = Math.max(1, cta.h * fill);
+ const shape = { x: cta.x, y: base - h, w: cta.w, h, r: Math.min(cta.r, h / 2) };
+ const label = Math.min(1, Math.max(0, (linearProgress(tl, "cta.fill", t) - 0.35) / 0.4));
+ nodes.push({ type: "rect", id: "cta.pill", ...shape, fill: cta.color });
+ if (label > 0) nodes.push(group([lineRuns(cta.label)], { clip: { type: "rect", ...shape }, ...(label < 1 && { opacity: label }) }));
+ }
+ if (line > 0 && fill < 1) {
+ const width = S * 0.004;
+ nodes.push({ type: "path", d: `M${cta.x + cta.r * 0.6} ${base - width / 2} H${cta.x + cta.w - cta.r * 0.6}`, stroke: { paint: cta.color, width, trim: line, length: cta.w - cta.r * 1.2, cap: "round" }, opacity: 1 - fill });
+ }
+ }
+ if (site) {
+ const p = P("site");
+ if (p > 0) nodes.push({ ...lineRuns(site), ...(p < 1 && { opacity: p }) });
+ }
+ // The panels part on top: they cover the card until they go.
+ const open = P("panels");
+ const over: DisplayNode[] = [];
+ if (open < 1) {
+ over.push({ type: "rect", id: "panel.left", x: -open * rest.w * 0.5, y: 0, w: rest.w * 0.5 + (1 - open), h: rest.h, fill: left });
+ over.push({ type: "rect", id: "panel.right", x: rest.w * 0.5 + open * rest.w * 0.5, y: 0, w: rest.w * 0.5, h: rest.h, fill: right });
+ }
+ return { nodes, over };
+ },
+ };
+});
diff --git a/src/lib/motion/sizes.ts b/src/lib/motion/sizes.ts
new file mode 100644
index 00000000..ad4e4edd
--- /dev/null
+++ b/src/lib/motion/sizes.ts
@@ -0,0 +1,51 @@
+/**
+ * Frame sizes and rates (pure). A scene lays out in design units, 1080 on the frame's short side, so its text wraps the
+ * same way in the preview, the export and a cover; the drawer scales design units to pixels. The preview's canvas keeps
+ * a smaller backing store (`preview`), which never changes the export.
+ */
+
+export type SizePreset = "9:16" | "1:1" | "16:9" | "4:5";
+export type SizeSpec = SizePreset | { w: number; h: number };
+
+export const SIZE_PRESETS: Record<SizePreset, { w: number; h: number; preview: { w: number; h: number } }> = {
+ "9:16": { w: 1080, h: 1920, preview: { w: 540, h: 960 } },
+ "1:1": { w: 1080, h: 1080, preview: { w: 720, h: 720 } },
+ "16:9": { w: 1920, h: 1080, preview: { w: 960, h: 540 } },
+ "4:5": { w: 1080, h: 1350, preview: { w: 576, h: 720 } },
+};
+
+/** The fps a clip may be made at (60 comes with the editor). */
+export const FPS_CHOICES = [24, 25, 30] as const;
+export const DEFAULT_FPS = 30;
+
+/** The pixels an export has. */
+export function exportSize(size: SizeSpec): { w: number; h: number } {
+ if (typeof size === "string") return { w: SIZE_PRESETS[size].w, h: SIZE_PRESETS[size].h };
+ return { w: Math.round(size.w), h: Math.round(size.h) };
+}
+
+/** The design units a scene lays out in: the export's shape with 1080 on its short side. */
+export function designSize(size: SizeSpec): { w: number; h: number } {
+ const { w, h } = exportSize(size);
+ const k = 1080 / Math.min(w, h);
+ return { w: Math.round(w * k), h: Math.round(h * k) };
+}
+
+/** The most backing pixels a preview canvas gets (before the device pixel ratio cap). */
+export function previewSize(size: SizeSpec): { w: number; h: number } {
+ if (typeof size === "string") return SIZE_PRESETS[size].preview;
+ const { w, h } = exportSize(size);
+ const k = Math.min(1, 720 / Math.max(w, h));
+ return { w: Math.round(w * k), h: Math.round(h * k) };
+}
+
+/** "9:16" for a preset, "720x1280" for a custom size. */
+export const sizeLabel = (size: SizeSpec): string => (typeof size === "string" ? size : `${Math.round(size.w)}x${Math.round(size.h)}`);
+
+/** Bits a second for an export: 10 Mbps at 1080p and up, 6 Mbps below, capped so the clip stays well under 95 MB. */
+export function exportBitrate(size: SizeSpec, duration: number): number {
+ const { w, h } = exportSize(size);
+ const base = Math.min(w, h) >= 1080 ? 10_000_000 : 6_000_000;
+ const cap = Math.floor((0.6 * 95 * 1024 * 1024 * 8) / Math.max(1, duration));
+ return Math.min(base, cap);
+}
diff --git a/src/lib/motion/time.ts b/src/lib/motion/time.ts
new file mode 100644
index 00000000..3053547e
--- /dev/null
+++ b/src/lib/motion/time.ts
@@ -0,0 +1,28 @@
+/**
+ * Kinetic Motion's clock (pure). A scene is sampled at an absolute time t in seconds, never stepped: frame i of a clip
+ * at `fps` is t = i / fps, so a preview that drops a frame skips ahead and an export that seeks anywhere gets the same
+ * picture. Every helper here is a plain function of its arguments.
+ */
+
+/** The frames of a clip `duration` seconds long at `fps`: round(duration × fps), at least 1 (2.5 s at 25 fps is 63). */
+export const frameCount = (duration: number, fps: number): number => Math.max(1, Math.round(duration * fps));
+
+/** When frame `i` is shown. */
+export const frameTime = (i: number, fps: number): number => i / fps;
+
+/** The frame `t` falls in, as its own time (a time exactly on a frame stays on it, despite float error). */
+export const quantize = (t: number, fps: number): number => Math.floor(t * fps + 1e-6) / fps;
+
+export const clamp = (v: number, lo = 0, hi = 1): number => (v < lo ? lo : v > hi ? hi : v);
+
+/** `t` kept inside a clip of `duration` seconds. */
+export const clampTime = (t: number, duration: number): number => clamp(t, 0, duration);
+
+/** Whether `t` is inside the window [a, b). */
+export const inWindow = (t: number, [a, b]: readonly [number, number]): boolean => t >= a && t < b;
+
+/** How far `t` is through the window [a, b], from 0 (before it) to 1 (after it). */
+export const local = (t: number, a: number, b: number): number => (b <= a ? (t >= b ? 1 : 0) : clamp((t - a) / (b - a)));
+
+/** a → b by p (not clamped). */
+export const mix = (a: number, b: number, p: number): number => a + (b - a) * p;
diff --git a/src/lib/motion/tween.ts b/src/lib/motion/tween.ts
new file mode 100644
index 00000000..81933445
--- /dev/null
+++ b/src/lib/motion/tween.ts
@@ -0,0 +1,131 @@
+/**
+ * Keys, tracks and timelines (pure). A track is a list of keys { t, v, ease } sampled at an absolute time; a timeline
+ * is a scene's list of timed events (what moves, when, for how long, on which curve), built once per recipe and then
+ * read at any t. The same events drive the timing checks in the tests and, later, the sound made from motion.
+ */
+
+import { curve, type CurveName } from "./ease";
+import { local, mix } from "./time";
+
+export interface Key {
+ t: number;
+ v: number;
+ /** The curve into this key from the one before it (default "move"). */
+ ease?: CurveName;
+}
+
+/** A track's value at `t`: the first key's before it, the last key's after it, eased in between. */
+export function sample(keys: readonly Key[], t: number): number {
+ if (!keys.length) return 0;
+ if (t <= keys[0].t) return keys[0].v;
+ const last = keys[keys.length - 1];
+ if (t >= last.t) return last.v;
+ for (let i = 1; i < keys.length; i++) {
+ const b = keys[i];
+ if (t <= b.t) {
+ const a = keys[i - 1];
+ return mix(a.v, b.v, curve(b.ease ?? "move")(local(t, a.t, b.t)));
+ }
+ }
+ return last.v;
+}
+
+/** When item `i` of `n` starts: `each` seconds apart, squeezed so the last starts at most `total` after the first. */
+export function stagger(i: number, n: number, each: number, total = Infinity): number {
+ if (n <= 1) return 0;
+ return i * Math.min(each, total / (n - 1));
+}
+
+/** What a timing rule calls a moving thing (tests/motion-timing.test.ts checks each kind's limits). */
+export type EventKind = "enter" | "pop" | "fade" | "draw" | "move" | "camera" | "exit";
+
+/** How a group of events is spaced: words (40–80 ms), elements (80–140 ms) or letters (20–50 ms). */
+export type StaggerUnit = "letters" | "words" | "elements";
+
+export interface MotionEvent {
+ /** Stable name ("headline.line.1", "cta.pill"). */
+ id: string;
+ kind: EventKind;
+ start: number;
+ dur: number;
+ curve: CurveName;
+ /** Events in one staggered group share it, with how they are spaced. */
+ group?: string;
+ unit?: StaggerUnit;
+}
+
+export interface Timeline {
+ events: MotionEvent[];
+ byId: Map<string, MotionEvent>;
+ /** Every element is set by then. */
+ rest: number;
+}
+
+export function timeline(events: MotionEvent[]): Timeline {
+ const byId = new Map(events.map((e) => [e.id, e]));
+ return { events, byId, rest: events.reduce((m, e) => Math.max(m, e.start + e.dur), 0) };
+}
+
+/** An event's eased progress at `t` (0 before it, 1 after it; an unknown id is done). */
+export function progress(tl: Timeline, id: string, t: number): number {
+ const e = tl.byId.get(id);
+ if (!e) return 1;
+ return curve(e.curve)(local(t, e.start, e.start + e.dur));
+}
+
+/** An event's plain (linear) progress at `t`. */
+export function linearProgress(tl: Timeline, id: string, t: number): number {
+ const e = tl.byId.get(id);
+ if (!e) return 1;
+ return local(t, e.start, e.start + e.dur);
+}
+
+/** Limits per kind, in seconds: an entrance 350–700 ms, nothing that moves under 200 ms. */
+export const DURATION_LIMITS: Record<EventKind, [number, number]> = {
+ enter: [0.35, 0.7],
+ pop: [0.35, 0.7],
+ fade: [0.2, 1.5],
+ draw: [0.2, 1.5],
+ move: [0.2, 3],
+ camera: [0.2, 30],
+ exit: [0.2, 0.7],
+};
+
+export const STAGGER_LIMITS: Record<StaggerUnit, [number, number]> = {
+ letters: [0.02, 0.05],
+ words: [0.04, 0.08],
+ elements: [0.08, 0.14],
+};
+
+const clampTo = (v: number, [lo, hi]: [number, number]) => Math.min(hi, Math.max(lo, v));
+
+/**
+ * A timeline written for a 2.5 s card (everything set by 1.3 s), scaled by `k` for a shorter or longer one: starts and
+ * spacing scale, durations scale within their kind's limits, staggers within their unit's.
+ */
+export interface Cue {
+ id: string;
+ kind: EventKind;
+ /** Seconds at k = 1. */
+ at: number;
+ dur: number;
+ curve: CurveName;
+ /** A staggered group: this is item `index` of `count`, `each` seconds apart (at k = 1). */
+ stagger?: { group: string; unit: StaggerUnit; index: number; each: number };
+}
+
+export function scaleCues(cues: Cue[], k: number): MotionEvent[] {
+ return cues.map((c) => {
+ const each = c.stagger ? clampTo(c.stagger.each * k, STAGGER_LIMITS[c.stagger.unit]) : 0;
+ const base = c.stagger ? c.at - c.stagger.index * c.stagger.each : c.at;
+ const start = base * k + (c.stagger ? c.stagger.index * each : 0);
+ return {
+ id: c.id,
+ kind: c.kind,
+ start: Math.round(start * 1e6) / 1e6,
+ dur: Math.round(clampTo(c.dur * k, DURATION_LIMITS[c.kind]) * 1e6) / 1e6,
+ curve: c.curve,
+ ...(c.stagger && { group: c.stagger.group, unit: c.stagger.unit }),
+ };
+ });
+}
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 747104e4..0a99ee9d 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -2634,13 +2634,15 @@ export function recordLocalGeneration(input: {
title?: string;
inputs: GenerationRequest["inputs"];
params?: GenerationRequest["params"];
- output: { url: string; kind: OutputFile["kind"]; contentType?: string };
+ output: { url: string; kind: OutputFile["kind"]; contentType?: string; meta?: { poster: string } };
}): Generation {
const model = getModel(input.modelId);
// A browser tool's own result: the model's local route for this very step (a grade is not recorded as a Relight blend).
if (!model || !model.routes.some((r) => r.provider === "local" && r.op === input.op)) throw new Error("Not a browser tool");
const now = Date.now();
- const req: GenerationRequest = { feature: input.feature, modelId: input.modelId, op: input.op, prompt: input.prompt, ...(input.title && { title: input.title }), inputs: input.inputs, params: input.params };
+ // Inside an account's work (the route's runAsTenant) the result is the account's own, as its runs are (stampTenant).
+ const account = tenantAccount();
+ const req: GenerationRequest = { feature: input.feature, modelId: input.modelId, op: input.op, prompt: input.prompt, ...(input.title && { title: input.title }), inputs: input.inputs, params: input.params, ...(account && { account }) };
const row: Row = {
id: nanoid(12),
batch_id: null,
diff --git a/src/server/hosted-run.ts b/src/server/hosted-run.ts
index 4b52b95b..75aef48f 100644
--- a/src/server/hosted-run.ts
+++ b/src/server/hosted-run.ts
@@ -18,6 +18,7 @@ import {
type Policy,
type Quote,
type RefuseCode,
+ type RunFacts,
} from "./billing";
import { outputKind, previewGeneration } from "./generations";
import { HOSTED_WORDS, inputCounts, poolAllows, poolReady, queueFacts, runFacts, runOnPool } from "./hosted";
@@ -138,16 +139,23 @@ async function inputFacts(accountId: string, req: GenerationRequest): Promise<{
* The moderation service's check of an account's run (no service: allowed, nothing to stamp). A refusal costs nothing:
* it comes before any hold.
*/
-export async function moderateRun(account: Account, req: GenerationRequest, planned: Planned | null, place: "pool" | "own"): Promise<{ ok: true; checkOutputs: boolean } | { ok: false; refusal: Refusal }> {
+export async function moderateRun(
+ account: Account,
+ req: GenerationRequest,
+ planned: Planned | null,
+ place: "pool" | "own",
+ /** A result made in the browser (no plan): what it is and where the account works. */
+ browser?: { kind: RunFacts["kind"]; place: RunFacts["place"] },
+): Promise<{ ok: true; checkOutputs: boolean } | { ok: false; refusal: Refusal }> {
if (!moderationConfigured()) return { ok: true, checkOutputs: false };
- const kind = planned ? outputKind(planned.op, planned.model) : "image";
+ const kind = planned ? outputKind(planned.op, planned.model) : (browser?.kind ?? "image");
const run = planned
? { ...runFacts(req, planned, kind), place: place === "pool" ? ("pool" as const) : planned.route.provider === "comfyui" ? ("own-gpu" as const) : ("own-key" as const) }
: null;
const a = await checkRun({
requestId: nanoid(16),
account: { id: account.id },
- run: run ?? { ...runFacts(req, { model: { id: req.modelId, kind: "image", engine: "open" }, op: req.op ?? "", jobs: 1, outputs: 1, providerId: "", costUsd: null, loras: { applied: [] } }, "image"), place: "own-gpu" },
+ run: run ?? { ...runFacts(req, { model: { id: req.modelId, kind, engine: "open" }, op: req.op ?? "", jobs: 1, outputs: 1, providerId: browser ? "local" : "", costUsd: null, loras: { applied: [] } }, kind), place: browser?.place ?? "own-gpu" },
prompt: req.prompt ?? "",
negative: req.negativePrompt ?? null,
inputs: await inputFacts(account.id, req),
diff --git a/src/server/marketing.ts b/src/server/marketing.ts
index 904f68af..c519c3ae 100644
--- a/src/server/marketing.ts
+++ b/src/server/marketing.ts
@@ -49,6 +49,7 @@ import {
import { dualEngine } from "@/lib/catalog/engines";
import { routesFor } from "@/lib/catalog/plan";
import { themeFrom } from "@/components/ads/layout";
+import { END_CARD_VARIANTS } from "@/lib/motion/scenes/end-card/shared";
import type { ChainSlot, Engine, GenerationRequest, ModelDef, Operation } from "@/lib/catalog/types";
import { getBrand, getProduct } from "./brand";
import { createPipeline, type PipelineStep } from "./chains";
@@ -119,8 +120,16 @@ export const ClickToAdBody = z.object({
/**
* End on the brand: a logo card after the ad, held 2–3 s. `image` is the card the page drew (brand colour,
* logo, product name, CTA); without it the cloud puts the kit's logo on its main colour (the open engine needs it).
+ * `clip`: the card animated in the page (Kinetic Motion), joined as it is; `variant` names its style (a note only).
*/
- endCard: z.object({ image: FILE.optional(), seconds: z.number().min(END_CARD.minSeconds).max(END_CARD.maxSeconds).optional() }).optional(),
+ endCard: z
+ .object({
+ image: FILE.optional(),
+ clip: FILE.optional(),
+ seconds: z.number().min(END_CARD.minSeconds).max(END_CARD.maxSeconds).optional(),
+ variant: z.enum(END_CARD_VARIANTS).optional(),
+ })
+ .optional(),
});
export type ClickToAdInput = z.infer<typeof ClickToAdBody>;
@@ -785,6 +794,7 @@ function withEndCard(plan: RunPlan, input: ClickToAdInput, ctx: { brand?: BrandK
ad,
adEncodedBy: plan.engine === "open" ? adEncoder(plan.steps.find((s) => s.key === ad)) : undefined,
card: input.endCard.image,
+ clip: input.endCard.clip,
background: ctx.background,
logo: rasterLogo(ctx.brand),
silence: ctx.silence,
@@ -801,8 +811,10 @@ function withEndCard(plan: RunPlan, input: ClickToAdInput, ctx: { brand?: BrandK
return { ...s, request };
});
const seconds = Math.max(END_CARD.minSeconds, Math.min(END_CARD.maxSeconds, input.endCard.seconds ?? END_CARD.seconds));
- const notes = [...plan.notes, `Ends on your logo card for ${seconds} s${input.endCard.image ? "" : " (the kit's logo on its main colour)"}`];
- return { ...plan, steps: [...steps, ...card.steps], finals: [card.final], meta: { ...plan.meta, endCard: input.endCard.image ?? null }, notes };
+ const animated = !!input.endCard.clip;
+ const notes = [...plan.notes, `Ends on your ${animated ? "animated " : ""}logo card for ${seconds} s${input.endCard.image || animated ? "" : " (the kit's logo on its main colour)"}`];
+ const meta = { ...plan.meta, endCard: input.endCard.image ?? null, ...(animated && { endCardClip: input.endCard.clip, endCardVariant: input.endCard.variant ?? null }) };
+ return { ...plan, steps: [...steps, ...card.steps], finals: [card.final], meta, notes };
}
export function planClickToAd(input: ClickToAdInput, ctx: { product: Product; brand?: BrandKit | null; script: string; background?: string; silence?: string }): RunPlan {
@@ -1285,7 +1297,7 @@ export async function runClickToAd(input: ClickToAdInput): Promise<{ run: Market
const script = input.script?.trim() ? fitScript(input.script, seconds) : (await clickToAdScript(input)).script;
// Checked first with stand-ins, so a plan that can't run writes no file.
const cloudCard = !!input.endCard && input.engine === "cloud";
- const fallback = cloudCard && !input.endCard?.image;
+ const fallback = cloudCard && !input.endCard?.image && !input.endCard?.clip;
if (cloudCard) planClickToAd(input, { product: ctx.product, brand: ctx.brand, script, background: "/api/files/placeholder.png", silence: "/api/files/placeholder.wav" });
const plan = planClickToAd(input, {
product: ctx.product,
diff --git a/tests/click-to-ad-endcard.test.ts b/tests/click-to-ad-endcard.test.ts
new file mode 100644
index 00000000..189cc072
--- /dev/null
+++ b/tests/click-to-ad-endcard.test.ts
@@ -0,0 +1,108 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import type { Product } from "@/lib/catalog/marketing";
+
+// Click to Ad's animated end card: the rendered clip replaces the still and its push-in, the joins stay. Cloud: the
+// clip gets its silent track (mux) and merge-videos joins it after the ad. Open: one join that keeps the ad's sound,
+// with the ad put first by the chain. Still: exactly the steps it had before.
+
+vi.setConfig({ testTimeout: 60_000 });
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-c2a-motion-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+process.env.OLLAMA_URL = "http://127.0.0.1:9";
+
+const { setSetting } = await import("@/server/settings");
+const mk = await import("@/server/marketing");
+const { withChainInputs } = await import("@/server/generations");
+const { saveFile } = await import("@/server/storage");
+const { endCardSteps } = await import("@/lib/catalog/marketing");
+
+beforeAll(() => setSetting("demoMode", "auto"));
+afterAll(() => {
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+
+const PNG = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.alloc(400, 7)]);
+const upload = (name = "p.png") => saveFile({ data: PNG, contentType: "image/png", name, source: "upload" }).url;
+const product = (): Product => ({ id: "p1", brandId: null, name: "Barrier Cream", sellingPoints: ["Calms red skin overnight"], images: [upload()], createdAt: 0, updatedAt: 0 });
+const SCRIPT = "Okay so this cream fixed my skin in a week and I am not even joking about it at all honestly.";
+const base = { ad: "captions", feature: "click-to-ad", title: "Clean Minimal · Barrier Cream", aspectRatio: "9:16", resolution: "480p" };
+
+describe("the end card's steps with a rendered clip", () => {
+ it("cloud: no overlay or push-in; the clip gets its silent track at once, then merge-videos after the ad", () => {
+ const { steps, final } = endCardSteps({ ...base, engine: "cloud", card: "/api/files/poster.png", clip: "/api/files/card.mp4", silence: "/api/files/silence.wav" });
+ expect(final).toBe("endcard");
+ expect(steps.map((s) => s.key)).toEqual(["endcardSound", "endcard"]);
+ expect(steps.some((s) => s.request.modelId === "ken-burns" || s.request.modelId === "overlay-image")).toBe(false);
+ expect(steps[0]).toEqual({ key: "endcardSound", label: "End card sound", request: { feature: "click-to-ad-step", modelId: "merge-audio-video", op: "mux", inputs: { video: "/api/files/card.mp4", audio: "/api/files/silence.wav" } } });
+ expect(steps[0].after).toBeUndefined();
+ expect(steps[1]).toMatchObject({ after: ["captions", "endcardSound"], chain: [{ slot: "videos" }, { slot: "videos" }], request: { feature: "click-to-ad", title: base.title, modelId: "join-clips", op: "concat" } });
+ expect(() => endCardSteps({ ...base, engine: "cloud", clip: "/api/files/card.mp4" })).toThrow(/silent sound track/);
+ });
+
+ it("open: one oss-join-sound1 step with the clip, the ad put first by the chain", () => {
+ for (const adEncodedBy of ["comfyui", "other"] as const) {
+ const { steps } = endCardSteps({ ...base, engine: "open", clip: "/api/files/card.webm", adEncodedBy });
+ expect(steps).toHaveLength(1);
+ expect(steps[0]).toMatchObject({
+ key: "endcard",
+ after: ["captions"],
+ chain: [{ slot: "videos", position: "first" }],
+ request: { feature: "click-to-ad", title: base.title, modelId: "oss-join-sound1", op: "concat", inputs: { videos: ["/api/files/card.webm"] }, params: { aspectRatio: "9:16", resolution: "480p" } },
+ });
+ const joined = withChainInputs({ ...steps[0].request, chain: steps[0].chain }, ["/api/files/ad.mp4"]);
+ expect(joined.inputs?.videos).toEqual(["/api/files/ad.mp4", "/api/files/card.webm"]);
+ }
+ });
+
+ it("still: the steps are exactly what they were", () => {
+ for (const o of [
+ { ...base, engine: "cloud" as const, card: "/api/files/card.png", silence: "/api/files/s.wav" },
+ { ...base, engine: "open" as const, card: "/api/files/card.png" },
+ { ...base, engine: "open" as const, card: "/api/files/card.png", adEncodedBy: "other" as const },
+ ]) {
+ expect(JSON.stringify(endCardSteps({ ...o, clip: undefined }))).toBe(JSON.stringify(endCardSteps(o)));
+ expect(endCardSteps(o).steps.some((s) => JSON.stringify(s).includes(".mp4"))).toBe(false);
+ }
+ });
+});
+
+describe("Click to Ad with the animated card", () => {
+ it("takes the clip and its style in the request, and refuses an unknown style or a link", () => {
+ const ok = mk.ClickToAdBody.safeParse({ engine: "cloud", productId: "p1", styleId: "clean-minimal", endCard: { image: "/api/files/a.png", clip: "/api/files/a.mp4", seconds: 2.5, variant: "iris" } });
+ expect(ok.success).toBe(true);
+ expect(mk.ClickToAdBody.safeParse({ engine: "cloud", productId: "p1", styleId: "x", endCard: { clip: "/api/files/a.mp4", variant: "spin" } }).success).toBe(false);
+ expect(mk.ClickToAdBody.safeParse({ engine: "cloud", productId: "p1", styleId: "x", endCard: { clip: "https://elsewhere.example/a.mp4" } }).success).toBe(false);
+ });
+
+ it("plans both engines with the clip, notes the animated card and keeps it in the run", () => {
+ const clip = saveFile({ data: Buffer.from("ftyp"), contentType: "video/mp4", name: "card.mp4", source: "upload" }).url;
+ const poster = upload("poster.png");
+ const cloud = mk.planClickToAd({ engine: "cloud", productId: "p1", styleId: "clean-minimal", endCard: { image: poster, clip, variant: "draw-on" } }, { product: product(), script: SCRIPT, silence: "/api/files/silence.wav" });
+ expect(cloud.steps.slice(-2).map((s) => s.key)).toEqual(["endcardSound", "endcard"]);
+ expect(cloud.meta).toMatchObject({ endCard: poster, endCardClip: clip, endCardVariant: "draw-on" });
+ expect(cloud.notes).toContain("Ends on your animated logo card for 2.5 s");
+ const open = mk.planClickToAd({ engine: "open", productId: "p1", styleId: "clean-minimal", voiceSample: upload("v.png"), endCard: { image: poster, clip, seconds: 3, variant: "split" } }, { product: product(), script: SCRIPT });
+ expect(open.steps.at(-1)).toMatchObject({ key: "endcard", request: { modelId: "oss-join-sound1", inputs: { videos: [clip] } }, chain: [{ slot: "videos", position: "first" }] });
+ expect(open.notes).toContain("Ends on your animated logo card for 3 s");
+ });
+
+ it("prices both paths (the estimate uses stand-in files)", () => {
+ // The estimate reads the product from the studio's own list: one saved there.
+ const db = mk as unknown as { estimatePlan: typeof mk.estimatePlan };
+ const cloud = mk.planClickToAd({ engine: "cloud", productId: "p1", styleId: "clean-minimal", endCard: { image: "/api/files/placeholder.png", clip: "/api/files/placeholder.mp4" } }, { product: product(), script: SCRIPT, silence: "/api/files/placeholder.wav" });
+ const cEst = db.estimatePlan(cloud);
+ expect(cEst.steps.map((s) => s.key).slice(-2)).toEqual(["endcardSound", "endcard"]);
+ expect(cEst.blocker).toBeFalsy();
+ const open = mk.planClickToAd({ engine: "open", productId: "p1", styleId: "clean-minimal", voiceSample: upload("v.png"), endCard: { image: "/api/files/placeholder.png", clip: "/api/files/placeholder.mp4" } }, { product: product(), script: SCRIPT });
+ const oEst = db.estimatePlan(open);
+ expect(oEst.steps.at(-1)!.key).toBe("endcard");
+ expect(oEst.blocker).toBeFalsy();
+ });
+});
diff --git a/tests/e2e/kinetic-endcard.mjs b/tests/e2e/kinetic-endcard.mjs
new file mode 100644
index 00000000..d1381f0b
--- /dev/null
+++ b/tests/e2e/kinetic-endcard.mjs
@@ -0,0 +1,360 @@
+// Click to Ad's animated end card, end to end (Kinetic Motion phase 1). Starts `next dev` on 3540 with a throwaway
+// data folder, the owner's password, public sign-up on, Demo mode on (stand-in results, no GPU, no paid call) and a
+// stand-in fal.ai on 3541 for an account's own key. Uses the system Chrome (WebCodecs H.264). Everything it starts is
+// stopped at the end.
+//
+// node tests/e2e/kinetic-endcard.mjs [evidence folder]
+//
+// KINETIC_PORT moves the app (and the stand-in to the next port).
+//
+// Checks. Owner: the preview animates (pixels differ between 0.2 s and 1.0 s, equal at 2.0 s and 2.4 s); Iris renders
+// to an MP4 whose frame count is round(seconds × fps); Generate sends the clip and the run joins it after the ad; "Save
+// the end card" makes a Library result whose file is the uploaded clip. Account with a stand-in key: uploads its clip,
+// records it, sees it in its own runs and downloads it; the owner's Library doesn't list it. Account with neither: the
+// upload is refused (connect-gpu). Guest: the page's note, and the record route answers 401. Reduced motion: the rest
+// frame and no autoplay. Phone 390 × 844: no sideways scroll, 44 px chips and scrub bar. Frame times on desktop and on
+// a 4× throttled phone. Evidence: MP4s of the five styles, contact sheets, screenshots, timings.
+import { spawn, execSync } from "node:child_process";
+import crypto from "node:crypto";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import sharp from "sharp";
+import { DESKTOP, launch, PHONE, root } from "./_browser.mjs";
+import { startFakeFal } from "../helpers/fake-cloud.ts";
+
+const PORT = Number(process.env.KINETIC_PORT ?? 3540);
+const APP = `http://127.0.0.1:${PORT}`;
+const out = path.resolve(process.argv[2] ?? fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-kinetic-")));
+fs.mkdirSync(out, { recursive: true });
+const data = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-kinetic-data-"));
+const logFile = path.join(out, "server.log");
+const PASSWORD = "owner password for kinetic";
+const ACCT_FAL = "acct-kinetic-key:acct-kinetic-secret";
+
+const failures = [];
+const notes = [];
+const check = (ok, what) => {
+ console.log(`${ok ? "ok " : "FAIL"} ${what}`);
+ if (!ok) failures.push(what);
+};
+const note = (s) => {
+ console.log(`note ${s}`);
+ notes.push(s);
+};
+const wait = (ms) => new Promise((r) => setTimeout(r, ms));
+
+const fal = await startFakeFal(PORT + 1);
+fal.keys[ACCT_FAL] = "good";
+
+const log = fs.openSync(logFile, "w");
+const server = spawn(process.execPath, [path.join(root, "node_modules/next/dist/bin/next"), "dev", "-p", String(PORT), "-H", "127.0.0.1"], {
+ cwd: root,
+ env: {
+ ...process.env,
+ NODE_ENV: "development",
+ FUOBE_DATA_DIR: data,
+ FUOBE_PASSWORD: PASSWORD,
+ FUOBE_PUBLIC_SIGNUP: "1",
+ FUOBE_DEMO_MODE: "on",
+ FUOBE_DEV_FAL_URL: fal.url,
+ COMFYUI_URL: "http://127.0.0.1:9",
+ OLLAMA_URL: "http://127.0.0.1:9",
+ LMSTUDIO_URL: "http://127.0.0.1:9",
+ UNSLOTH_URL: "http://127.0.0.1:9",
+ FUOBE_ACCOUNT_DISK_FREE_GB: "0",
+ },
+ stdio: ["ignore", log, log],
+});
+
+async function stopAll() {
+ try {
+ if (process.platform === "win32") execSync(`taskkill /pid ${server.pid} /T /F`, { stdio: "ignore" });
+ else server.kill("SIGTERM");
+ } catch {}
+ await fal.close();
+}
+
+const api = async (route, { method = "GET", body, cookie, raw, type } = {}) => {
+ const headers = { Origin: APP, ...(cookie && { cookie }) };
+ if (raw) Object.assign(headers, { "Content-Type": type, "X-File-Name": encodeURIComponent(`file.${type.split("/")[1]}`) });
+ else headers["Content-Type"] = "application/json";
+ const res = await fetch(APP + route, { method, headers, ...(raw ? { body: raw } : body !== undefined && { body: JSON.stringify(body) }) });
+ const buf = Buffer.from(await res.arrayBuffer());
+ let json = null;
+ try {
+ json = JSON.parse(buf.toString("utf8"));
+ } catch {}
+ return { status: res.status, json, buf, headers: res.headers };
+};
+const cookieOf = (res) => /fuobe_session=[^;]+/.exec(res.headers.get("set-cookie") ?? "")?.[0];
+const sha = (b) => crypto.createHash("sha256").update(b).digest("hex");
+
+/** The MP4's sample count, from its stsz box. */
+function mp4Frames(buf) {
+ const i = buf.indexOf(Buffer.from("stsz"));
+ return i < 0 ? -1 : buf.readUInt32BE(i + 12);
+}
+
+/** The scrub bar to `t`, then the main canvas's pixels. */
+async function frameAt(page, t) {
+ await page.evaluate((v) => {
+ const el = document.querySelector('input[type=range][aria-label="Time"]');
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value").set.call(el, String(v));
+ el.dispatchEvent(new Event("input", { bubbles: true }));
+ }, t);
+ await page.waitForTimeout(150);
+ return page.evaluate(() => document.querySelector('canvas[data-kinetic-player="main"]').toDataURL("image/png"));
+}
+
+const MONOGRAM =
+ "data:image/svg+xml," +
+ encodeURIComponent(
+ "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 120 120'><circle cx='60' cy='60' r='54' fill='none' stroke='#efe2c4' stroke-width='4'/><path d='M34 84V38l26 30 26-30v46' fill='none' stroke='#efe2c4' stroke-width='7' stroke-linejoin='round' stroke-linecap='round'/></svg>",
+ );
+
+const timings = {};
+let browser;
+try {
+ for (let i = 0; i < 300; i++) {
+ try {
+ const r = await fetch(`${APP}/login`);
+ if (r.status < 500) break;
+ } catch {}
+ await wait(1000);
+ }
+ const owner = cookieOf(await api("/api/auth/login", { method: "POST", body: { password: PASSWORD } }));
+ check(!!owner, "owner signs in");
+
+ // A fictional premium brand: a product photo, a monogram (SVG, traced by Draw-on) and its colours and fonts.
+ const photo = await sharp({ create: { width: 900, height: 1200, channels: 3, background: "#d9c7a8" } })
+ .composite([{ input: Buffer.from("<svg xmlns='http://www.w3.org/2000/svg' width='900' height='1200'><defs><radialGradient id='g' cx='50%' cy='45%' r='55%'><stop offset='0' stop-color='#fff6e6'/><stop offset='1' stop-color='#b89a72'/></radialGradient></defs><rect width='900' height='1200' fill='url(#g)'/><rect x='330' y='360' width='240' height='480' rx='40' fill='#6b1d2a'/><rect x='370' y='300' width='160' height='80' rx='16' fill='#2a1a14'/></svg>") }])
+ .png()
+ .toBuffer();
+ const up = await api("/api/uploads", { method: "POST", cookie: owner, raw: photo, type: "image/png" });
+ check(up.status === 201, `owner uploads a product photo (${up.status})`);
+ const brand = await api("/api/brands", { method: "POST", cookie: owner, body: { description: "Maison Ardent makes quiet, exceptional skincare.", name: "Maison Ardent", colors: ["#6b1d2a", "#e9d8b4"] } });
+ check(brand.status === 201, `owner makes a brand kit (${brand.status})`);
+ // Kit logos are stored files (a picture): the monogram drawn at 480 px with a clear ground.
+ const logoPng = await sharp(Buffer.from(decodeURIComponent(MONOGRAM.slice("data:image/svg+xml,".length))), { density: 384 }).resize(480, 480).png().toBuffer();
+ const logoUp = await api("/api/uploads", { method: "POST", cookie: owner, raw: logoPng, type: "image/png" });
+ check(logoUp.status === 201, `owner uploads the logo (${logoUp.status})`);
+ const kit = await api(`/api/brands/${brand.json.id}`, { method: "PATCH", cookie: owner, body: { logo: logoUp.json.url, colors: ["#6b1d2a", "#e9d8b4"], fonts: { heading: "Playfair Display", body: "Inter" } } });
+ check(kit.status === 200, `the kit gets its logo, colours and fonts (${kit.status})`);
+ const prod = await api("/api/products", { method: "POST", cookie: owner, body: { name: "Barrier Cream", brandId: brand.json.id, description: "A rich overnight cream that calms dry, reactive skin.", url: "https://maisonardent.com/products/barrier-cream", images: [up.json.url] } });
+ check(prod.status === 201, `owner adds the product (${prod.status})`);
+
+ browser = await launch({ channel: "chrome" });
+ const [cname, cvalue] = owner.split("=");
+ const ownerContext = async (opts) => {
+ const ctx = await browser.newContext({ ...opts, baseURL: APP });
+ await ctx.addCookies([{ name: cname, value: cvalue, url: APP }]);
+ return ctx;
+ };
+ const openCard = async (page) => {
+ page.on('pageerror', (e) => console.log('pageerror', e.message));
+ page.on('console', (m) => m.type() === 'error' && console.log('console', m.text().slice(0, 300)));
+ await page.goto("/marketing/click-to-ad", { waitUntil: "load", timeout: 240_000 });
+ await page.getByRole("button", { name: /Barrier Cream/ }).first().click({ timeout: 120_000 });
+ await page.locator('canvas[data-kinetic-player="main"]').waitFor({ timeout: 60_000 }).catch(async (e) => {
+ await page.screenshot({ path: path.join(out, 'crash.png'), fullPage: true });
+ throw e;
+ });
+ await page.waitForTimeout(1500);
+ };
+
+ // ---- Owner, desktop
+ const desk = await ownerContext({ ...DESKTOP });
+ await desk.addInitScript(() => (window.__kineticStats = { frames: [] }));
+ const page = await desk.newPage();
+ const uploads = [];
+ page.on("response", (r) => {
+ if (r.url().endsWith("/api/uploads") && r.request().method() === "POST") uploads.push({ type: r.request().headers()["content-type"], answer: r.json().catch(() => null) });
+ });
+ await openCard(page);
+ await page.locator('canvas[data-kinetic-player="main"]').scrollIntoViewIfNeeded();
+ // Frame times while it plays (draw cost per frame).
+ await page.evaluate(() => (window.__kineticStats.frames = []));
+ await page.waitForTimeout(5000);
+ const desktopFrames = await page.evaluate(() => window.__kineticStats.frames.slice());
+ const p95 = (xs) => [...xs].sort((a, b) => a - b)[Math.floor(xs.length * 0.95)] ?? NaN;
+ timings.previewDesktop = { frames: desktopFrames.length, p95ms: +p95(desktopFrames).toFixed(2), medianMs: +[...desktopFrames].sort((a, b) => a - b)[desktopFrames.length >> 1]?.toFixed(2) };
+ check(desktopFrames.length > 100 && p95(desktopFrames) <= 20, `desktop preview draws fast (${desktopFrames.length} frames in 5 s, p95 ${timings.previewDesktop.p95ms} ms)`);
+
+ const a = await frameAt(page, 0.2);
+ const b = await frameAt(page, 1.0);
+ const c = await frameAt(page, 2.5);
+ await frameAt(page, 0.3);
+ const d = await frameAt(page, 2.5);
+ check(a !== b, "the preview animates (0.2 s and 1.0 s differ)");
+ check(c === d, "the last frame is the same picture whenever it is sought");
+ const panel = page.locator('canvas[data-kinetic-player="main"]');
+ for (const t of [0.15, 0.4, 0.7, 1.0, 1.6]) {
+ await frameAt(page, t);
+ await panel.screenshot({ path: path.join(out, `preview-draw-on-${String(t).replace(".", "_")}s.png`) });
+ }
+ await page.getByText("End card", { exact: true }).first().scrollIntoViewIfNeeded();
+ await page.screenshot({ path: path.join(out, "click-to-ad-endcard-1440.png"), fullPage: false });
+
+ // Iris: render, upload, Generate.
+ await page.getByRole("button", { name: /^Iris/ }).first().click();
+ await page.waitForTimeout(800);
+ uploads.length = 0;
+ const started = Date.now();
+ const runReq = page.waitForRequest((r) => r.url().endsWith("/api/marketing/click-to-ad") && r.method() === "POST", { timeout: 120_000 });
+ await page.getByRole("button", { name: /Generate video/ }).click();
+ const req = await runReq;
+ timings.irisCardMs = Date.now() - started;
+ const sent = JSON.parse(req.postData());
+ check(/\.mp4$/.test(sent.endCard?.clip ?? "") && sent.endCard?.variant === "iris" && /\.png$/.test(sent.endCard?.image ?? ""), `Generate sends the rendered Iris clip and its poster (${JSON.stringify(sent.endCard)})`);
+ check(timings.irisCardMs <= 4000, `the 2.5 s card renders and uploads in ${timings.irisCardMs} ms (budget 4 s before upload)`);
+ const fps = sent.engine === "open" ? 25 : 24;
+ const clip = await api(sent.endCard.clip, { cookie: owner });
+ const frames = mp4Frames(clip.buf);
+ check(frames === Math.round(sent.endCard.seconds * fps), `the clip has round(${sent.endCard.seconds} × ${fps}) = ${frames} frames`);
+ fs.writeFileSync(path.join(out, `click-to-ad-card-iris-720x1280-${fps}fps.mp4`), clip.buf);
+ await page.waitForTimeout(3000);
+ const gens = await api("/api/generations?limit=200&steps=1", { cookie: owner });
+ const items = gens.json?.items ?? [];
+ const usesClip = items.filter((g) => JSON.stringify(g.request?.inputs ?? {}).includes(sent.endCard.clip));
+ const joinStep = items.find((g) => g.request?.modelId === (sent.engine === "open" ? "oss-join-sound1" : "join-clips"));
+ check(usesClip.length > 0 && usesClip.some((g) => ["merge-audio-video", "oss-join-sound1"].includes(g.request?.modelId)), `the run takes the clip in its ${sent.engine === "open" ? "join" : "silent-track mux"} step`);
+ check(!!joinStep, `the run ends on the join after the ad (${joinStep?.request?.modelId})`);
+ note(`Click to Ad ran on the ${sent.engine} engine; card ${fps} fps.`);
+
+ // Save the end card (each style) to the Library: 1080 × 1920 at 30 fps.
+ const styles = ["draw-on", "rise", "iris", "split", "glint"];
+ timings.saveMs = {};
+ for (const s of styles) {
+ await page.getByRole("button", { name: new RegExp(`^${s === "draw-on" ? "Draw-on" : s[0].toUpperCase() + s.slice(1)}`) }).first().click();
+ await page.waitForTimeout(500);
+ uploads.length = 0;
+ const t0 = Date.now();
+ const recorded = page.waitForResponse((r) => r.url().endsWith("/api/generations/local") && r.request().method() === "POST", { timeout: 120_000 });
+ await page.getByRole("button", { name: /^Save .+ to Library$/ }).click();
+ check((await recorded).status() === 201, `${s}: the result is recorded`);
+ await page.getByText("Saved to your Library").first().waitFor({ timeout: 30_000 });
+ timings.saveMs[s] = Date.now() - t0;
+ const lib = await api("/api/generations?limit=50", { cookie: owner });
+ const g = (lib.json?.items ?? []).find((x) => x.modelId === "local-motion" && x.request?.params?.extra?.motion?.scene === `end-card/${s}`);
+ check(!!g && g.feature === "kinetic-end-card" && g.status === "succeeded", `"Save the end card" (${s}) makes a Library result`);
+ if (!g) continue;
+ const file = await api(g.outputs[0].url, { cookie: owner });
+ const sentClip = await uploads.find((u) => /video\//.test(u.type ?? ""))?.answer;
+ check(!!sentClip && sentClip.url === g.outputs[0].url && sentClip.size === file.buf.length, `the Library's file is the uploaded ${s} clip (${file.buf.length} bytes)`);
+ check(mp4Frames(file.buf) === 75, `${s}: 75 frames (2.5 s at 30 fps)`);
+ const poster = g.outputs[0].meta?.poster ?? "";
+ check(poster.startsWith("/api/files/") && poster.endsWith(".png"), `${s}: its tile shows the clip's last frame (${g.outputs[0].meta?.poster})`);
+ fs.writeFileSync(path.join(out, `end-card-${s}-1080x1920-30fps.mp4`), file.buf);
+ await page.waitForTimeout(400);
+ }
+ await page.goto("/library", { waitUntil: "load", timeout: 120_000 });
+ await page.waitForTimeout(2500);
+ await page.screenshot({ path: path.join(out, "library-1440.png") });
+
+ // ---- Reduced motion: the rest frame, no autoplay.
+ const calm = await ownerContext({ ...DESKTOP, reducedMotion: "reduce" });
+ const cp = await calm.newPage();
+ await openCard(cp);
+ const r1 = await cp.evaluate(() => document.querySelector('canvas[data-kinetic-player="main"]').toDataURL());
+ await cp.waitForTimeout(700);
+ const r2 = await cp.evaluate(() => document.querySelector('canvas[data-kinetic-player="main"]').toDataURL());
+ check(r1 === r2, "reduced motion: the preview holds the rest frame (no autoplay)");
+ check(await cp.getByRole("button", { name: "Play" }).first().isVisible(), "reduced motion: Play is offered");
+ await calm.close();
+
+ // ---- Phone 390 × 844 (DPR 3), throttled 4×.
+ const phone = await ownerContext({ ...PHONE, deviceScaleFactor: 3 });
+ await phone.addInitScript(() => (window.__kineticStats = { frames: [] }));
+ const pp = await phone.newPage();
+ await openCard(pp);
+ await pp.locator('canvas[data-kinetic-player="main"]').scrollIntoViewIfNeeded();
+ const overflow = await pp.evaluate(() => document.scrollingElement.scrollWidth - window.innerWidth);
+ check(overflow <= 0, `phone: no sideways scroll (${overflow} px)`);
+ const rightEdge = await pp.evaluate(() => Math.max(...[...document.querySelectorAll('[aria-label="Call to action on the end card"], [aria-label="End card style"], canvas[data-kinetic-player="main"]')].map((e) => e.getBoundingClientRect().right)) - window.innerWidth);
+ check(rightEdge <= 0, `phone: the end card panel stays inside the screen (${Math.round(rightEdge)} px past the edge)`);
+ const chipH = await pp.$$eval('[role=group][aria-label="End card style"] button', (els) => els.map((e) => e.getBoundingClientRect().height));
+ check(chipH.length === 6 && chipH.every((h) => h >= 44), `phone: the six style chips are at least 44 px (${chipH.map(Math.round).join(", ")})`);
+ const scrubH = await pp.$eval('input[type=range][aria-label="Time"]', (e) => e.getBoundingClientRect().height);
+ check(scrubH >= 44, `phone: the scrub bar is at least 44 px (${scrubH})`);
+ await frameAt(pp, 0.6);
+ await pp.screenshot({ path: path.join(out, "click-to-ad-endcard-390-mid.png") });
+ await frameAt(pp, 2.2);
+ await pp.screenshot({ path: path.join(out, "click-to-ad-endcard-390.png") });
+ await pp.getByRole("button", { name: "Play" }).first().click();
+ const cdp = await phone.newCDPSession(pp);
+ await cdp.send("Emulation.setCPUThrottlingRate", { rate: 4 });
+ await pp.evaluate(() => (window.__kineticStats.frames = []));
+ await pp.waitForTimeout(5000);
+ const phoneFrames = await pp.evaluate(() => window.__kineticStats.frames.slice());
+ timings.previewPhone4x = { frames: phoneFrames.length, p95ms: +p95(phoneFrames).toFixed(2) };
+ check(phoneFrames.length > 60 && p95(phoneFrames) <= 33, `throttled phone preview: ${phoneFrames.length} frames in 5 s, p95 draw ${timings.previewPhone4x.p95ms} ms`);
+ await cdp.send("Emulation.setCPUThrottlingRate", { rate: 1 });
+ await phone.close();
+
+ // ---- An account with a stand-in fal.ai key: its own clip, saved through Fuobe, in its own runs.
+ const acct = cookieOf(await api("/api/auth/signup", { method: "POST", body: { email: "[email protected]", password: "account password" } }));
+ check(!!acct, "an account signs up");
+ const key = await api("/api/account/keys/fal", { method: "PUT", cookie: acct, body: { key: ACCT_FAL } });
+ check(key.status === 200, `the account adds its own key (${key.status})`);
+ const mine = fs.readFileSync(path.join(out, "end-card-draw-on-1080x1920-30fps.mp4"));
+ const aUp = await api("/api/uploads", { method: "POST", cookie: acct, raw: mine, type: "video/mp4" });
+ check(aUp.status === 201, `the account uploads its rendered clip (${aUp.status})`);
+ const recipe = { v: 1, scene: "end-card/draw-on", seed: 1, size: "9:16", fps: 30, duration: 2.5, fields: { brand: "Sora Skin", product: "Daily Veil SPF 50" }, brand: { name: "Sora Skin", colors: ["#c8643c", "#f2e6d8"], fonts: { heading: "Fraunces", body: "Manrope" } }, export: { format: "mp4", blurSamples: 8, shutter: 180 } };
+ const rec = await api("/api/generations/local", { method: "POST", cookie: acct, body: { feature: "kinetic-end-card", modelId: "local-motion", op: "motion", prompt: "Sora Skin · Daily Veil SPF 50", title: "Sora Skin end card", inputs: {}, params: { extra: { motion: recipe } }, output: { url: aUp.json?.url, kind: "video", contentType: "video/mp4" } } });
+ check(rec.status === 201 && rec.json?.status === "succeeded", `the account records its clip (${rec.status})`);
+ const theirs = await api("/api/generations?limit=50", { cookie: acct });
+ check((theirs.json?.items ?? []).some((g) => g.id === rec.json?.id), "it shows in the account's own runs");
+ const dl = await api(aUp.json?.url, { cookie: acct });
+ check(dl.status === 200 && sha(dl.buf) === sha(mine), "the account downloads its clip from Fuobe");
+ const ownerList = await api("/api/generations?limit=200", { cookie: owner });
+ check(!(ownerList.json?.items ?? []).some((g) => g.id === rec.json?.id), "the owner's Library doesn't list the account's result");
+ const stolen = await api("/api/generations/local", { method: "POST", cookie: acct, body: { feature: "kinetic-end-card", modelId: "local-motion", op: "motion", prompt: "x", inputs: {}, params: { extra: { motion: recipe } }, output: { url: sent.endCard.clip, kind: "video", contentType: "video/mp4" } } });
+ check(stolen.status === 403, `the account can't record the owner's clip (${stolen.status})`);
+
+ // ---- An account with neither a GPU nor a key: the upload asks it to connect one.
+ const bare = cookieOf(await api("/api/auth/signup", { method: "POST", body: { email: "[email protected]", password: "account password" } }));
+ const refused = await api("/api/uploads", { method: "POST", cookie: bare, raw: mine, type: "video/mp4" });
+ check(refused.status === 403 && refused.json?.code === "connect-gpu", `an account with no GPU or key can't upload (${refused.status} ${refused.json?.code})`);
+
+ // ---- Guest (phone and desktop): the page's note, the end card previews live on a sample kit with their words, and
+ // saving it opens the sign-up card. The record route asks to sign up.
+ for (const [name, viewport] of [["390", PHONE], ["1440", DESKTOP]]) {
+ const guest = await browser.newContext({ ...viewport, baseURL: APP });
+ const gp = await guest.newPage();
+ await gp.goto("/marketing/click-to-ad", { waitUntil: "load", timeout: 120_000 });
+ await gp.waitForTimeout(1500);
+ check(await gp.getByText("Click to Ad isn't available here.").first().isVisible(), `guest ${name}: the page says Click to Ad isn't available here`);
+ const main = gp.locator('canvas[data-kinetic-player="main"]');
+ await main.waitFor({ timeout: 60_000 });
+ await main.scrollIntoViewIfNeeded();
+ await gp.getByRole("textbox", { name: "Product name on the end card" }).fill("The Night Serum");
+ await gp.waitForTimeout(1200);
+ const g1 = await gp.evaluate(() => document.querySelector('canvas[data-kinetic-player="main"]').toDataURL());
+ await gp.waitForTimeout(400);
+ const g2 = await gp.evaluate(() => document.querySelector('canvas[data-kinetic-player="main"]').toDataURL());
+ check(g1 !== g2, `guest ${name}: the end card preview plays`);
+ const gOverflow = await gp.evaluate(() => document.scrollingElement.scrollWidth - window.innerWidth);
+ check(gOverflow <= 0, `guest ${name}: no sideways scroll (${gOverflow} px)`);
+ await gp.screenshot({ path: path.join(out, `click-to-ad-guest-${name}.png`) });
+ await gp.getByRole("button", { name: /^Save Draw-on to Library$/ }).click();
+ const card = gp.getByText(/Create a free account/).first();
+ check(await card.waitFor({ timeout: 10_000 }).then(() => true, () => false), `guest ${name}: saving the end card asks to create a free account`);
+ await gp.screenshot({ path: path.join(out, `click-to-ad-guest-${name}-save.png`) });
+ await guest.close();
+ }
+ const gRec = await api("/api/generations/local", { method: "POST", body: { feature: "x", modelId: "local-motion", op: "motion", prompt: "x", inputs: {}, output: { url: "/api/files/x.mp4", kind: "video", contentType: "video/mp4" } } });
+ check(gRec.status === 401, `guest: recording a result answers 401 (${gRec.status})`);
+ await desk.close();
+} catch (e) {
+ failures.push(`crashed: ${e?.stack ?? e}`);
+ console.error(e);
+} finally {
+ await browser?.close().catch(() => {});
+ await stopAll();
+}
+
+fs.writeFileSync(path.join(out, "e2e-result.json"), JSON.stringify({ failures, notes, timings }, null, 2));
+console.log(JSON.stringify({ timings }, null, 2));
+console.log(failures.length ? `\n${failures.length} failed` : "\nall passed");
+process.exit(failures.length ? 1 : 0);
diff --git a/tests/end-card-layout.test.ts b/tests/end-card-layout.test.ts
new file mode 100644
index 00000000..4746ac7a
--- /dev/null
+++ b/tests/end-card-layout.test.ts
@@ -0,0 +1,91 @@
+import { describe, expect, it } from "vitest";
+import { contrast, themeFrom } from "@/components/ads/layout";
+import { planEndCard } from "@/components/marketing/end-card";
+import { cardColours, endCardRest, type EndCardRest } from "@/lib/motion/scenes/end-card/shared";
+import { designSize, type SizeSpec } from "@/lib/motion/sizes";
+import { measure } from "./helpers/motion";
+
+// The end card's rest layout at every size (end-card-layout): sizes from the short side, the whole stack inside the
+// frame, the address under the pill (never under it on screen), a tall card's foot clear, and the kit's own colours.
+
+const theme = themeFrom({ colors: ["#0e3b2f", "#cfae6e"], fonts: { heading: "Cormorant Garamond", body: "Manrope" } });
+const content = { brand: "Aurèle", product: "Crème Absolue Régénérante Intense", cta: "Discover the ritual", website: "aurele-paris.com" };
+
+const rest = (size: SizeSpec, logo: { w: number; h: number } | null = { w: 1400, h: 360 }) => endCardRest({ theme, content, logo, measure, size: designSize(size), colors: ["#0e3b2f", "#cfae6e"] });
+
+/** The stack's boxes, top to bottom. */
+function boxes(r: EndCardRest) {
+ const out: { name: string; top: number; bottom: number; left: number; right: number }[] = [];
+ if (r.logo) out.push({ name: "logo", top: r.logo.y, bottom: r.logo.y + r.logo.h, left: r.logo.x, right: r.logo.x + r.logo.w });
+ if (r.brand) out.push({ name: "brand", top: r.brand.y, bottom: r.brand.y + r.brand.layout.height, left: r.brand.cx - r.brand.layout.width / 2, right: r.brand.cx + r.brand.layout.width / 2 });
+ const h = r.headline;
+ out.push({ name: "headline", top: h.y, bottom: h.y + h.layout.height, left: h.cx - h.layout.width / 2, right: h.cx + h.layout.width / 2 });
+ if (r.cta) out.push({ name: "pill", top: r.cta.y, bottom: r.cta.y + r.cta.h, left: r.cta.x, right: r.cta.x + r.cta.w });
+ if (r.site) out.push({ name: "site", top: r.site.y, bottom: r.site.y + r.site.layout.height, left: r.site.cx - r.site.layout.width / 2, right: r.site.cx + r.site.layout.width / 2 });
+ return out;
+}
+
+describe("the end card's layout (end-card-layout)", () => {
+ for (const size of ["9:16", "16:9", "1:1", "4:5"] as const) {
+ for (const logo of [{ w: 1400, h: 360 }, null]) {
+ it(`keeps a two-line headline's stack inside a ${size} frame, in order, nothing overlapping (${logo ? "logo" : "name"})`, () => {
+ const r = rest(size, logo);
+ expect(r.overflow).toEqual([]);
+ expect(r.headline.layout.lines.length).toBe(2);
+ const b = boxes(r);
+ for (const x of b) {
+ expect(x.top, `${size} ${x.name}`).toBeGreaterThanOrEqual(r.margin - 0.5);
+ expect(x.bottom, `${size} ${x.name}`).toBeLessThanOrEqual(r.h - r.margin + 0.5);
+ expect(x.left, `${size} ${x.name}`).toBeGreaterThanOrEqual(r.margin - 0.5);
+ expect(x.right, `${size} ${x.name}`).toBeLessThanOrEqual(r.w - r.margin + 0.5);
+ }
+ for (let i = 1; i < b.length; i++) expect(b[i].top, `${size} ${b[i].name} under ${b[i - 1].name}`).toBeGreaterThan(b[i - 1].bottom);
+ // The address sits just under the pill, not at the frame's foot.
+ const pill = b.find((x) => x.name === "pill")!;
+ const site = b.find((x) => x.name === "site")!;
+ expect(site.top - pill.bottom).toBeLessThan(r.h * 0.06);
+ });
+ }
+ }
+
+ it("sizes type and the pill from the short side: a wide card sets what a tall one does", () => {
+ const tall = rest("9:16");
+ const wide = rest("16:9");
+ expect(wide.headline.layout.size).toBeCloseTo(tall.headline.layout.size, 6);
+ expect(wide.cta!.h).toBeCloseTo(tall.cta!.h, 6);
+ // A 16:9 headline and pill are no taller than a third of the frame together.
+ expect(wide.headline.layout.height + wide.cta!.h).toBeLessThan(wide.h / 3);
+ });
+
+ it("keeps a tall card's bottom fifth clear (where phone apps put their buttons and captions)", () => {
+ for (const logo of [{ w: 1400, h: 360 }, { w: 400, h: 400 }, null]) {
+ const r = rest("9:16", logo);
+ const last = boxes(r).at(-1)!;
+ expect(last.bottom).toBeLessThanOrEqual(r.h * 0.8 + 0.5);
+ }
+ });
+
+ it("dresses the words and the pill in the kit's own colours when one reads on the brand colour", () => {
+ // Emerald and gold: gold words and pill, the label in emerald.
+ expect(cardColours(theme, ["#0e3b2f", "#cfae6e"])).toEqual({ ink: "#cfae6e", pill: "#cfae6e", label: "#0e3b2f" });
+ // Ivory and navy: navy words on ivory, the label in ivory.
+ const light = themeFrom({ colors: ["#f3ede2", "#1c2b4a"] });
+ expect(light.accent).toBe("#f3ede2");
+ expect(cardColours(light, ["#f3ede2", "#1c2b4a"])).toEqual({ ink: "#1c2b4a", pill: "#1c2b4a", label: "#f3ede2" });
+ // No kit colour reads (a pale yellow beside the accent): white or near-black, whichever reads.
+ const one = themeFrom({ colors: ["#c1121f", "#e05a5a"] });
+ const c = cardColours(one, ["#c1121f", "#e05a5a"]);
+ expect(c.ink).toBe(one.onAccent);
+ expect(contrast(c.ink, one.accent)).toBeGreaterThanOrEqual(3);
+ });
+
+ it("gives the still card the same colours and places as the animated rest frame", () => {
+ const size = designSize("9:16");
+ const still = planEndCard({ theme, content, logo: null, measure, size, colors: ["#0e3b2f", "#cfae6e"] });
+ const r = rest("9:16", null);
+ expect(still.headline.color).toBe(r.headline.color);
+ expect(still.cta!.color).toBe("#cfae6e");
+ expect(still.cta!.text.color).toBe("#0e3b2f");
+ expect(still.headline.y).toBeCloseTo(r.headline.y, 6);
+ });
+});
diff --git a/tests/generations-local-motion.test.ts b/tests/generations-local-motion.test.ts
new file mode 100644
index 00000000..c166cc68
--- /dev/null
+++ b/tests/generations-local-motion.test.ts
@@ -0,0 +1,246 @@
+import fs from "node:fs";
+import http from "node:http";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+import { NextRequest } from "next/server";
+
+// Kinetic Motion results through Fuobe (POST /api/generations/local): the owner records its own clip; an account
+// records only its own clip, made from its own files, as its own run (its list, never the owner's Library), within its
+// run rate and through the studio's checks; a guest is told to sign up; the proxy lets an account through to the route.
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+vi.setConfig({ testTimeout: 30_000 });
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-local-motion-"));
+process.env.FUOBE_DATA_DIR = dir;
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_MODERATION_URL;
+const auth = await import("@/server/auth");
+const { proxy } = await import("@/proxy");
+const access = await import("@/lib/guest-access");
+const { POST } = await import("@/app/api/generations/local/route");
+const { saveFile } = await import("@/server/storage");
+const { generationAccount, fileRecord } = await import("@/server/account-library");
+const { listGenerations, getGeneration } = await import("@/server/generations");
+const { hit } = await import("@/server/rate");
+const { RECIPE_MAX_BYTES } = await import("@/lib/motion/recipe");
+const { recipe } = await import("./helpers/motion");
+
+let moderation: http.Server | null = null;
+let answer: Record<string, unknown> = { allowed: true };
+/** What the studio's checks were last asked about. */
+let asked: { prompt?: string; run?: { kind?: string; place?: string } } = {};
+beforeAll(async () => {
+ auth.setPassword("install password");
+ moderation = http.createServer((req, res) => {
+ let body = "";
+ req.on("data", (c) => (body += c));
+ req.on("end", () => {
+ try {
+ asked = JSON.parse(body);
+ } catch {}
+ res.setHeader("content-type", "application/json");
+ res.end(JSON.stringify(answer));
+ });
+ });
+ await new Promise<void>((r) => moderation!.listen(0, "127.0.0.1", () => r()));
+});
+afterEach(() => {
+ delete process.env.FUOBE_PUBLIC_SIGNUP;
+ delete process.env.FUOBE_MODERATION_URL;
+ answer = { allowed: true };
+});
+afterAll(() => {
+ moderation?.close();
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+
+const MP4 = Buffer.concat([Buffer.from([0, 0, 0, 0x18]), Buffer.from("ftypisom"), Buffer.alloc(200, 1)]);
+const ownerFile = (type = "video/mp4", name = "k.mp4") => saveFile({ data: MP4, contentType: type, name, source: "upload" }).url;
+const accountFile = (id: string, type = "video/mp4", name = "k.mp4") => saveFile({ data: MP4, contentType: type, name, source: "upload", accountId: id }).url;
+
+const body = (output: string, over: Record<string, unknown> = {}) => ({
+ feature: "kinetic-end-card",
+ modelId: "local-motion",
+ op: "motion",
+ prompt: "Maison Ardent · Barrier Cream · Shop now",
+ title: "Maison Ardent end card · Draw-on",
+ inputs: {},
+ params: { extra: { motion: recipe("end-card/draw-on") } },
+ output: { url: output, kind: "video", contentType: "video/mp4" },
+ ...over,
+});
+
+const call = (b: unknown, cookie?: string) =>
+ POST(new Request("http://localhost:3000/api/generations/local", { method: "POST", headers: { "content-type": "application/json", host: "localhost:3000", ...(cookie && { cookie: `${auth.SESSION_COOKIE}=${cookie}` }) }, body: JSON.stringify(b) }));
+
+const owner = () => auth.createSession().value;
+let n = 0;
+function newAccount(): { id: string; cookie: string } {
+ const a = auth.createAccount(`motion-${n++}@example.com`, "long enough");
+ return { id: a.id, cookie: auth.createSession(a.id).value };
+}
+
+describe("the owner", () => {
+ it("records a Kinetic Motion clip with its recipe, in the Library", async () => {
+ const url = ownerFile();
+ const r = await call(body(url), owner());
+ expect(r.status).toBe(201);
+ const g = await r.json();
+ expect(g).toMatchObject({ modelId: "local-motion", op: "motion", status: "succeeded", kind: "video", feature: "kinetic-end-card" });
+ expect(generationAccount(g.id)).toBeNull();
+ expect(getGeneration(g.id)!.request.params?.extra?.motion).toMatchObject({ scene: "end-card/draw-on" });
+ });
+
+ it("refuses a recipe that is too big or not a recipe, and an output that isn't a clip under /api/files/", async () => {
+ const url = ownerFile();
+ const huge = { ...recipe("end-card/draw-on"), controls: Object.fromEntries(Array.from({ length: 900 }, (_, i) => [`k${i}`, "y".repeat(78)])) };
+ expect(JSON.stringify(huge).length).toBeGreaterThan(RECIPE_MAX_BYTES);
+ expect((await call(body(url, { params: { extra: { motion: huge } } }), owner())).status).toBe(400);
+ expect((await call(body(url, { params: { extra: { motion: { scene: "x" } } } }), owner())).status).toBe(400);
+ expect((await call(body(url, { params: {} }), owner())).status).toBe(400);
+ expect((await call(body(url, { output: { url, kind: "image", contentType: "image/png" } }), owner())).status).toBe(400);
+ expect((await call(body(url, { output: { url: "https://elsewhere.example/a.mp4", kind: "video", contentType: "video/mp4" } }), owner())).status).toBe(400);
+ expect((await call(body(url, { inputs: { images: ["/api/files/a.png", "/api/files/b.png", "/api/files/c.png", "/api/files/d.png", "/api/files/e.png"] } }), owner())).status).toBe(400);
+ });
+
+ it("refuses a picture recorded as a clip: the stored file's type is what counts", async () => {
+ const png = ownerFile("image/png", "p.png");
+ expect((await call(body(png), owner())).status).toBe(400);
+ const webm = ownerFile("video/webm", "k.webm");
+ expect((await call(body(webm), owner())).status).toBe(400);
+ expect((await call(body(webm, { output: { url: webm, kind: "video", contentType: "video/webm" } }), owner())).status).toBe(201);
+ });
+
+ it("never records an account's file as the owner's", async () => {
+ const a = newAccount();
+ expect((await call(body(accountFile(a.id)), owner())).status).toBe(403);
+ });
+
+ it("still takes a grade with one picture, and refuses two", async () => {
+ const out = ownerFile("image/png", "g.png");
+ const grade = { feature: "grade", modelId: "local-color-grade", op: "grade", prompt: "Warm", inputs: { images: [ownerFile("image/png", "s.png")] }, output: { url: out, kind: "image" } };
+ expect((await call(grade, owner())).status).toBe(201);
+ expect((await call({ ...grade, inputs: { images: [out, out] } }, owner())).status).toBe(400);
+ });
+});
+
+describe("an account", () => {
+ it("records its own clip as its own run: in its list, not the owner's", async () => {
+ process.env.FUOBE_PUBLIC_SIGNUP = "1";
+ const a = newAccount();
+ const logo = accountFile(a.id, "image/png", "logo.png");
+ const r = await call(body(accountFile(a.id), { inputs: { images: [logo] } }), a.cookie);
+ expect(r.status).toBe(201);
+ const g = await r.json();
+ expect(generationAccount(g.id)).toBe(a.id);
+ expect(listGenerations({ account: a.id }).map((x) => x.id)).toContain(g.id);
+ // Not in the owner's own list.
+ expect(listGenerations().map((x) => x.id)).not.toContain(g.id);
+ });
+
+ it("can't record the owner's file or another account's, or name someone else's input", async () => {
+ process.env.FUOBE_PUBLIC_SIGNUP = "1";
+ const a = newAccount();
+ const b = newAccount();
+ expect((await call(body(ownerFile()), a.cookie)).status).toBe(403);
+ expect((await call(body(accountFile(b.id)), a.cookie)).status).toBe(403);
+ const r = await call(body(accountFile(a.id), { inputs: { images: [accountFile(b.id, "image/png", "logo.png")] } }), a.cookie);
+ expect(r.status).toBe(403);
+ expect((await r.json()).error).toMatch(/can't find/);
+ });
+
+ it("can't name someone else's file anywhere in the clip: a video input, the recipe's product, pictures or logo", async () => {
+ process.env.FUOBE_PUBLIC_SIGNUP = "1";
+ const a = newAccount();
+ const theirs = ownerFile("image/png", "o.png");
+ // A clip is made from pictures, never from a video.
+ expect((await call(body(accountFile(a.id), { inputs: { video: ownerFile() } }), a.cookie)).status).toBe(400);
+ expect((await call(body(accountFile(a.id), { inputs: { video: accountFile(a.id) } }), a.cookie)).status).toBe(400);
+ for (const over of [{ media: { product: theirs } }, { media: { images: [theirs] } }, { brand: { ...recipe("end-card/draw-on").brand, logo: theirs } }]) {
+ const r = await call(body(accountFile(a.id), { params: { extra: { motion: recipe("end-card/draw-on", over) } } }), a.cookie);
+ expect(r.status).toBe(403);
+ expect((await r.json()).error).toMatch(/can't find/);
+ }
+ // Its own files there are fine.
+ const mine = accountFile(a.id, "image/png", "p.png");
+ expect((await call(body(accountFile(a.id), { params: { extra: { motion: recipe("end-card/draw-on", { media: { product: mine }, brand: { ...recipe("end-card/draw-on").brand, logo: mine } }) } } }), a.cookie)).status).toBe(201);
+ });
+
+ it("can't record a picture as a clip", async () => {
+ process.env.FUOBE_PUBLIC_SIGNUP = "1";
+ const a = newAccount();
+ expect((await call(body(accountFile(a.id, "image/png", "p.png")), a.cookie)).status).toBe(400);
+ });
+
+ it("records Kinetic Motion only: a grade stays the owner's library", async () => {
+ process.env.FUOBE_PUBLIC_SIGNUP = "1";
+ const a = newAccount();
+ const r = await call({ feature: "grade", modelId: "local-color-grade", op: "grade", prompt: "x", inputs: {}, output: { url: accountFile(a.id, "image/png", "g.png"), kind: "image" } }, a.cookie);
+ expect(r.status).toBe(403);
+ expect((await r.json()).code).toBe("library");
+ });
+
+ it("is held to its run rate", async () => {
+ process.env.FUOBE_PUBLIC_SIGNUP = "1";
+ const a = newAccount();
+ // Its saves and its runs share one hourly budget.
+ for (let i = 0; i < 60; i++) hit(`run:${a.id}`, 60, 60 * 60_000);
+ const r = await call(body(accountFile(a.id)), a.cookie);
+ expect(r.status).toBe(429);
+ expect(r.headers.get("retry-after")).toBeTruthy();
+ });
+
+ it("goes through the studio's checks: a refusal answers 422 with its words, a held output waits for its check", async () => {
+ process.env.FUOBE_PUBLIC_SIGNUP = "1";
+ const addr = moderation!.address() as { port: number };
+ process.env.FUOBE_MODERATION_URL = `http://127.0.0.1:${addr.port}`;
+ const a = newAccount();
+ answer = { allowed: false, code: "blocked", text: "This can't be made here." };
+ const refused = await call(body(accountFile(a.id)), a.cookie);
+ expect(refused.status).toBe(422);
+ expect(await refused.json()).toMatchObject({ error: "This can't be made here.", code: "blocked" });
+ answer = { allowed: true, checkOutputs: true };
+ const url = accountFile(a.id);
+ const held = await call(body(url), a.cookie);
+ expect(held.status).toBe(201);
+ const g = await held.json();
+ expect(g.status).toBe("running");
+ expect(fileRecord(url.replace("/api/files/", ""))?.held).toBe(true);
+ });
+
+ it("checks the words drawn on the clip and its title, not the page's summary, and keeps them as the run's words", async () => {
+ process.env.FUOBE_PUBLIC_SIGNUP = "1";
+ const addr = moderation!.address() as { port: number };
+ process.env.FUOBE_MODERATION_URL = `http://127.0.0.1:${addr.port}`;
+ const a = newAccount();
+ answer = { allowed: true };
+ const fields = { brand: "Halden & Rowe", product: "The Overcoat", cta: "Shop the coat" };
+ const r = await call(body(accountFile(a.id), { prompt: "", title: "Winter end card", params: { extra: { motion: recipe("end-card/rise", { fields }) } } }), a.cookie);
+ expect(r.status).toBe(201);
+ for (const w of [...Object.values(fields), "Maison Ardent", "Winter end card"]) expect(asked.prompt).toContain(w);
+ expect(asked.run).toMatchObject({ kind: "video", place: "pool" });
+ const g = await r.json();
+ expect(getGeneration(g.id)!.prompt).toBe(asked.prompt);
+ });
+});
+
+describe("guests and the proxy", () => {
+ const req = (cookie?: string) =>
+ new NextRequest("http://localhost:3000/api/generations/local", { method: "POST", headers: { "content-type": "application/json", ...(cookie && { cookie: `${auth.SESSION_COOKIE}=${cookie}` }) }, body: "{}" });
+
+ it("lets an account's call through to the route, and gives a guest the sign-up card", async () => {
+ process.env.FUOBE_PUBLIC_SIGNUP = "1";
+ expect(access.accountMayChange("POST", "/api/generations/local", "")).toBe(true);
+ expect(access.isLibraryChange("POST", "/api/generations/local")).toBe(false);
+ const a = newAccount();
+ expect(proxy(req(a.cookie)).headers.get("x-middleware-next")).toBe("1");
+ const guest = proxy(req());
+ expect(guest.status).toBe(401);
+ expect(guest.headers.get(access.GUEST_HEADER)).toBe("1");
+ expect((await call(body(ownerFile()))).status).toBe(401);
+ });
+});
diff --git a/tests/helpers/motion.ts b/tests/helpers/motion.ts
new file mode 100644
index 00000000..b5d997e1
--- /dev/null
+++ b/tests/helpers/motion.ts
@@ -0,0 +1,47 @@
+import type { DisplayList, DisplayNode } from "@/lib/motion/display";
+import type { Recipe } from "@/lib/motion/recipe";
+import type { LogoInfo, SceneInput } from "@/lib/motion/scene";
+
+/** A stand-in for canvas text metrics: half the font size per UTF-16 unit (so every glyph has a width). */
+export const measure = (text: string, font: string) => text.length * Number(/(\d+)px/.exec(font)![1]) * 0.5;
+
+export const RASTER_LOGO: LogoInfo = { w: 800, h: 200, kind: "raster" };
+export const SVG_LOGO: LogoInfo = {
+ w: 200,
+ h: 100,
+ kind: "svg",
+ viewBox: { x: 0, y: 0, w: 200, h: 100 },
+ paths: [
+ { d: "M10 10H90V90H10Z", m: [1, 0, 0, 1, 0, 0], length: 320 },
+ { d: "M110 50A40 40 0 1 0 190 50A40 40 0 1 0 110 50Z", m: [1, 0, 0, 1, 0, 0], length: 251 },
+ { d: "M0 95H200", m: [1, 0, 0, 1, 0, 0], length: 200 },
+ ],
+};
+
+export function recipe(scene: string, over: Partial<Recipe> = {}): Recipe {
+ return {
+ v: 1,
+ scene,
+ seed: 7,
+ size: { w: 720, h: 1280 },
+ fps: 24,
+ duration: 2.5,
+ fields: { brand: "Maison Ardent", product: "Barrier Cream", cta: "Shop now", website: "maisonardent.com" },
+ brand: { name: "Maison Ardent", colors: ["#6b1d2a", "#e9d8b4"], fonts: { heading: "Playfair Display", body: "Inter" } },
+ export: { format: "mp4", blurSamples: 8, shutter: 180 },
+ ...over,
+ };
+}
+
+export const input = (r: Recipe, logo: LogoInfo | null = RASTER_LOGO): SceneInput => ({ recipe: r, measure, logo });
+
+/** Every node in a list, depth first. */
+export function walk(nodes: readonly DisplayNode[], out: DisplayNode[] = []): DisplayNode[] {
+ for (const n of nodes) {
+ out.push(n);
+ if (n.type === "group") walk(n.children, out);
+ }
+ return out;
+}
+
+export const allNodes = (l: DisplayList) => walk(l.nodes);
diff --git a/tests/marketing-endcard.test.ts b/tests/marketing-endcard.test.ts
index 7fb16cee..70a713ab 100644
--- a/tests/marketing-endcard.test.ts
+++ b/tests/marketing-endcard.test.ts
@@ -30,7 +30,12 @@ const { planEndCard, siteLabel } = await import("@/components/marketing/end-card
const { themeFrom } = await import("@/components/ads/layout");
beforeAll(() => setSetting("demoMode", "auto"));
-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+afterAll(() => {
+ // The database stays open until the worker exits (Windows won't delete it before).
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
const PNG = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.alloc(400, 7)]);
const upload = (name = "p.png") => saveFile({ data: PNG, contentType: "image/png", name, source: "upload" }).url;
@@ -254,10 +259,10 @@ describe("the end card the page draws", () => {
for (const r of [logo!, cta!, { x: 0, y: body!.y, h: body!.lineHeight }]) inside(r);
});
- it("writes the brand's name when there is no logo, and leaves out a CTA nobody wrote", () => {
+ it("writes the brand's name as typed when there is no logo, and leaves out a CTA nobody wrote", () => {
const plan = planEndCard({ theme, content: { brand: "Dermaco", product: "A very long product name that keeps going and going for a while" }, logo: null, measure });
expect(plan.logo).toBeUndefined();
- expect(plan.brand!.lines).toEqual(["DERMACO"]);
+ expect(plan.brand!.lines).toEqual(["Dermaco"]);
expect(plan.cta).toBeUndefined();
expect(plan.headline.lines.length).toBeLessThanOrEqual(2);
for (const l of plan.headline.lines) expect(measure(l, plan.headline.font)).toBeLessThanOrEqual(720 - 144 + 1);
diff --git a/tests/motion-continuity.test.ts b/tests/motion-continuity.test.ts
new file mode 100644
index 00000000..0263a9be
--- /dev/null
+++ b/tests/motion-continuity.test.ts
@@ -0,0 +1,88 @@
+import { describe, expect, it } from "vitest";
+import { IDENTITY, multiply, type DisplayList, type DisplayNode, type Matrix } from "@/lib/motion/display";
+import { graphemes } from "@/lib/motion/layout";
+import { loadScene, SCENE_IDS } from "@/lib/motion/registry";
+import type { Scene } from "@/lib/motion/scene";
+import type { SizeSpec } from "@/lib/motion/sizes";
+import { input, measure, RASTER_LOGO, recipe, SVG_LOGO } from "./helpers/motion";
+
+// No jumps (motion-continuity): wherever a style changes how it draws a piece (letters to whole lines, a moving group
+// to the settled card, the settled card to the last frame), every letter, the logo and the pill stay where they were
+// within 1 unit. Checked for every style, size and kind of mark, across every frame and every event's edges.
+
+const scenes: Scene[] = await Promise.all(SCENE_IDS.map(loadScene));
+const SIZES: SizeSpec[] = ["9:16", "1:1", "16:9", "4:5"];
+
+const apply = (m: Matrix, x: number, y: number): [number, number] => [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]];
+
+/** Every placed piece by a stable key: each typed letter (by its place in its field), the logo, the pill. */
+function pieces(list: DisplayList): Map<string, [number, number]> {
+ const out = new Map<string, [number, number]>();
+ const count = new Map<string, number>();
+ const walk = (nodes: readonly DisplayNode[], m: Matrix) => {
+ for (const n of nodes) {
+ if (n.type === "group") walk(n.children, n.transform ? multiply(m, n.transform) : m);
+ else if (n.type === "image") out.set(`image:${n.src}`, apply(m, n.x, n.y));
+ else if (n.type === "rect" && n.id === "cta.pill") out.set("pill", apply(m, n.x + n.w / 2, n.y + n.h / 2));
+ else if (n.type === "text") {
+ for (const run of n.runs) {
+ const rm = run.transform ? multiply(m, run.transform) : m;
+ for (const g of graphemes(run.text)) {
+ if (/^\s+$/.test(g.text)) continue;
+ const font = run.font;
+ const x = run.x + measure(run.text.slice(0, g.index + g.text.length), font) - measure(g.text, font);
+ const k = count.get(n.field) ?? 0;
+ count.set(n.field, k + 1);
+ out.set(`${n.field}:${k}`, apply(rm, x, run.y));
+ }
+ }
+ }
+ }
+ };
+ walk(list.nodes, IDENTITY);
+ return out;
+}
+
+function jump(a: DisplayList, b: DisplayList): { key: string; d: number } {
+ const pa = pieces(a);
+ const pb = pieces(b);
+ let worst = { key: "", d: 0 };
+ for (const [key, p] of pa) {
+ const q = pb.get(key);
+ if (!q) continue;
+ const d = Math.hypot(p[0] - q[0], p[1] - q[1]);
+ if (d > worst.d) worst = { key, d };
+ }
+ return worst;
+}
+
+describe("no jumps (motion-continuity)", () => {
+ it("never moves a letter, the logo or the pill by more than 1 unit in an instant", () => {
+ const fields = [
+ { brand: "Halden & Rowe", product: "The Overcoat, in Loden Wool", cta: "Shop the collection", website: "haldenrowe.com" },
+ { brand: "Aurèle", product: "Le Sérum Nuit", cta: "Discover the ritual", website: "aurele.com" },
+ ];
+ for (const scene of scenes) {
+ for (const size of SIZES) {
+ for (const logo of [RASTER_LOGO, SVG_LOGO, null]) {
+ for (const f of fields) {
+ const r = recipe(scene.id, { size, fps: 25, fields: f });
+ const plan = scene.plan(input(r, logo));
+ const edges = plan.timeline.events.flatMap((e) => [e.start, e.start + e.dur]);
+ const times = [...Array.from({ length: Math.round(r.duration * r.fps) }, (_, i) => i / r.fps), ...edges, plan.settled, plan.rest].filter((t) => t >= 0 && t <= r.duration);
+ for (const t of times) {
+ for (const [a, b] of [
+ [t - 1e-5, t],
+ [t, t + 1e-5],
+ ]) {
+ if (a < 0) continue;
+ const j = jump(plan.evaluate(a), plan.evaluate(b));
+ expect(j.d, `${scene.id} ${size} ${logo?.kind ?? "no logo"} "${f.brand}" ${j.key} at ${a.toFixed(5)}→${b.toFixed(5)}`).toBeLessThanOrEqual(1);
+ }
+ }
+ }
+ }
+ }
+ }
+ });
+});
diff --git a/tests/motion-core.test.ts b/tests/motion-core.test.ts
new file mode 100644
index 00000000..6b90d6f8
--- /dev/null
+++ b/tests/motion-core.test.ts
@@ -0,0 +1,223 @@
+import { describe, expect, it } from "vitest";
+import { bezier, CURVES, back, bounce, circ, cubic, elastic, expo, linear, quad, quart, quint, sine, spring, springAt, springDuration, SPRINGS, steps } from "@/lib/motion/ease";
+import { noise1, rng } from "@/lib/motion/random";
+import { clamp, frameCount, frameTime, local, quantize } from "@/lib/motion/time";
+import { sample, scaleCues, stagger } from "@/lib/motion/tween";
+import { designSize, exportBitrate, exportSize, previewSize } from "@/lib/motion/sizes";
+import { normalizeRecipe, recipeKey, RECIPE_MAX_BYTES } from "@/lib/motion/recipe";
+import { about, multiply, roundRectPath } from "@/lib/motion/display";
+import { cameraAt, layerMatrix, REST_CAMERA } from "@/lib/motion/camera2d";
+import { recipe } from "./helpers/motion";
+
+// Kinetic Motion's pure core: the frame clock, the easing library, seeded randomness, keys, sizes and recipes.
+
+describe("the frame clock (motion-time)", () => {
+ it("counts frames as round(duration × fps)", () => {
+ expect(frameCount(2.5, 24)).toBe(60);
+ expect(frameCount(2.5, 25)).toBe(63);
+ expect(frameCount(5, 30)).toBe(150);
+ expect(frameCount(0, 30)).toBe(1);
+ expect(frameTime(30, 30)).toBe(1);
+ });
+
+ it("quantises to the frame a time falls in, stable on frame boundaries", () => {
+ for (const fps of [24, 25, 30]) {
+ for (let i = 0; i < 200; i++) {
+ const t = frameTime(i, fps);
+ expect(quantize(t, fps)).toBeCloseTo(t, 12);
+ expect(quantize(quantize(t, fps), fps)).toBe(quantize(t, fps));
+ expect(quantize(t + 0.5 / fps, fps)).toBeCloseTo(t, 12);
+ }
+ }
+ });
+
+ it("clamps local progress to 0..1", () => {
+ expect(local(-1, 0, 1)).toBe(0);
+ expect(local(0.25, 0, 1)).toBe(0.25);
+ expect(local(9, 0, 1)).toBe(1);
+ expect(local(1, 1, 1)).toBe(1);
+ expect(local(0.5, 1, 1)).toBe(0);
+ expect(clamp(2)).toBe(1);
+ });
+});
+
+describe("the easing library (motion-ease)", () => {
+ const families = { quad, cubic, quart, quint, sine, expo, circ, back: back(), elastic: elastic(), bounce };
+ const all: [string, (p: number) => number][] = [
+ ["linear", linear],
+ ...Object.entries(families).flatMap(([n, f]) => [[`${n}.in`, f.in], [`${n}.out`, f.out], [`${n}.inOut`, f.inOut]] as [string, (p: number) => number][]),
+ ...Object.entries(CURVES),
+ ["steps(4)", steps(4)],
+ ];
+
+ it("every curve starts at 0, ends at 1 and never gives NaN", () => {
+ for (const [name, f] of all) {
+ expect(f(0), name).toBe(0);
+ expect(f(1), name).toBe(1);
+ for (let i = 0; i <= 1000; i++) expect(Number.isFinite(f(i / 1000)), `${name} at ${i}`).toBe(true);
+ expect(f(-1), name).toBe(0);
+ expect(f(2), name).toBe(1);
+ }
+ });
+
+ it("bezier matches CSS's named timing functions", () => {
+ // Reference values from the CSS cubic-bezier definition, solved independently by bisection at high precision.
+ const ref = (x1: number, y1: number, x2: number, y2: number, x: number) => {
+ const bx = (u: number) => 3 * x1 * u * (1 - u) ** 2 + 3 * x2 * u * u * (1 - u) + u ** 3;
+ const by = (u: number) => 3 * y1 * u * (1 - u) ** 2 + 3 * y2 * u * u * (1 - u) + u ** 3;
+ let lo = 0;
+ let hi = 1;
+ for (let i = 0; i < 100; i++) {
+ const mid = (lo + hi) / 2;
+ if (bx(mid) < x) lo = mid;
+ else hi = mid;
+ }
+ return by((lo + hi) / 2);
+ };
+ const named: [number, number, number, number][] = [
+ [0.25, 0.1, 0.25, 1],
+ [0.42, 0, 1, 1],
+ [0, 0, 0.58, 1],
+ [0.42, 0, 0.58, 1],
+ [0.16, 1, 0.3, 1],
+ [0.7, 0, 0.84, 0],
+ [0.65, 0, 0.35, 1],
+ ];
+ for (const c of named) {
+ const f = bezier(...c);
+ for (let i = 1; i < 50; i++) expect(Math.abs(f(i / 50) - ref(...c, i / 50)), `${c} at ${i / 50}`).toBeLessThan(1e-4);
+ }
+ // ease at 0.5 (a value browsers agree on).
+ expect(bezier(0.25, 0.1, 0.25, 1)(0.5)).toBeCloseTo(0.8024, 3);
+ });
+
+ it("springs settle within their own settle time, and pop overshoots about 6 %", () => {
+ for (const o of Object.values(SPRINGS)) {
+ const d = springDuration(o);
+ expect(d).toBeGreaterThan(0.2);
+ expect(d).toBeLessThan(1);
+ for (let t = d; t < d + 2; t += 0.01) expect(Math.abs(springAt(o, t) - 1)).toBeLessThanOrEqual(0.001);
+ }
+ let peak = 0;
+ for (let i = 0; i <= 1000; i++) peak = Math.max(peak, CURVES.pop(i / 1000));
+ expect(peak - 1).toBeGreaterThan(0.04);
+ expect(peak - 1).toBeLessThan(0.08);
+ // Critically and over-damped springs never overshoot.
+ for (const o of [{ stiffness: 100, damping: 20 }, { stiffness: 100, damping: 60 }]) {
+ const f = spring(o);
+ for (let i = 0; i <= 200; i++) expect(f(i / 200)).toBeLessThanOrEqual(1 + 1e-9);
+ }
+ });
+});
+
+describe("seeded randomness (motion-random)", () => {
+ it("gives the same value for the same seed and key, in [0, 1)", () => {
+ for (let i = 0; i < 500; i++) {
+ const v = rng(42, "particle", i);
+ expect(v).toBe(rng(42, "particle", i));
+ expect(v).toBeGreaterThanOrEqual(0);
+ expect(v).toBeLessThan(1);
+ }
+ expect(rng(42, "particle", 1)).not.toBe(rng(43, "particle", 1));
+ expect(rng(42, "particle", 1)).not.toBe(rng(42, "particle", 2));
+ expect(rng(42, "a", "b")).not.toBe(rng(42, "ab"));
+ });
+
+ it("is order-free: asking in another order gives the same values", () => {
+ const keys = Array.from({ length: 300 }, (_, i) => i);
+ const forward = new Map(keys.map((k) => [k, rng(9, "p", k)]));
+ const shuffled = [...keys].sort((a, b) => rng(1, "shuffle", a) - rng(1, "shuffle", b));
+ for (const k of shuffled) expect(rng(9, "p", k)).toBe(forward.get(k));
+ // Spread: no bucket of ten is empty or crowded.
+ const buckets = new Array(10).fill(0);
+ for (let i = 0; i < 5000; i++) buckets[Math.floor(rng(3, i) * 10)]++;
+ for (const b of buckets) expect(b).toBeGreaterThan(400);
+ expect(Math.abs(noise1(1, "x", 2.5))).toBeLessThanOrEqual(1);
+ });
+});
+
+describe("keys, tracks and staggers", () => {
+ it("samples a track before, between and after its keys", () => {
+ const keys = [
+ { t: 0, v: 0 },
+ { t: 1, v: 10, ease: "linear" as const },
+ { t: 2, v: 0 },
+ ];
+ expect(sample(keys, -1)).toBe(0);
+ expect(sample(keys, 0.5)).toBe(5);
+ expect(sample(keys, 3)).toBe(0);
+ expect(stagger(3, 10, 0.06)).toBeCloseTo(0.18);
+ expect(stagger(9, 10, 0.1, 0.45)).toBeCloseTo(0.45);
+ });
+
+ it("scales a card's cues within each kind's limits", () => {
+ const cues = [
+ { id: "a", kind: "enter" as const, at: 0.3, dur: 0.55, curve: "enter" as const },
+ { id: "w1", kind: "enter" as const, at: 0.5, dur: 0.45, curve: "enter" as const, stagger: { group: "w", unit: "words" as const, index: 1, each: 0.065 } },
+ ];
+ const short = scaleCues(cues, 2 / 3);
+ expect(short[0].dur).toBeCloseTo(0.367, 3);
+ expect(short[0].start).toBeCloseTo(0.2, 6);
+ // The stagger keeps at least 40 ms between words.
+ expect(short[1].start - (0.5 - 0.065) * (2 / 3)).toBeCloseTo(0.0433, 3);
+ const long = scaleCues(cues, 4 / 3);
+ expect(long[0].dur).toBe(0.7);
+ });
+});
+
+describe("sizes and recipes", () => {
+ it("lays out in design units with 1080 on the short side", () => {
+ expect(designSize({ w: 720, h: 1280 })).toEqual({ w: 1080, h: 1920 });
+ expect(designSize("16:9")).toEqual({ w: 1920, h: 1080 });
+ expect(exportSize("9:16")).toEqual({ w: 1080, h: 1920 });
+ expect(previewSize("9:16")).toEqual({ w: 540, h: 960 });
+ expect(previewSize({ w: 720, h: 1280 })).toEqual({ w: 405, h: 720 });
+ });
+
+ it("keeps a long clip's bit rate under the account's clip limit", () => {
+ expect(exportBitrate("9:16", 5)).toBe(10_000_000);
+ expect(exportBitrate({ w: 720, h: 1280 }, 2.5)).toBe(6_000_000);
+ expect((exportBitrate("9:16", 60) * 60) / 8).toBeLessThanOrEqual(0.6 * 95 * 1024 * 1024);
+ });
+
+ it("checks a recipe, holds it to the scene's lengths, and keys equal looks alike", () => {
+ const r = recipe("end-card/draw-on");
+ expect(normalizeRecipe({ ...r, duration: 9 }, { min: 2, max: 3 }).duration).toBe(3);
+ expect(() => normalizeRecipe({ ...r, scene: "../x" })).toThrow();
+ expect(() => normalizeRecipe({ ...r, brand: { ...r.brand, colors: ["red"] } })).toThrow();
+ expect(() => normalizeRecipe({ ...r, fields: { headline: "x".repeat(601) } })).toThrow();
+ const big = { ...r, controls: Object.fromEntries(Array.from({ length: 900 }, (_, i) => [`k${i}`, "y".repeat(78)])) };
+ expect(JSON.stringify(big).length).toBeGreaterThan(RECIPE_MAX_BYTES);
+ expect(() => normalizeRecipe(big)).toThrow(/too big/);
+ expect(recipeKey(r)).toBe(recipeKey(JSON.parse(JSON.stringify({ ...r, fields: { website: r.fields.website, cta: r.fields.cta, product: r.fields.product, brand: r.fields.brand } }))));
+ expect(recipeKey(r)).not.toBe(recipeKey({ ...r, seed: 8 }));
+ expect(recipeKey(r)).toMatch(/^[0-9a-f]{16}$/);
+ });
+});
+
+describe("matrices and the 2.5D camera", () => {
+ it("scales about a point and composes", () => {
+ const m = about(10, 20, 2);
+ expect(m[0] * 10 + m[2] * 20 + m[4]).toBeCloseTo(10);
+ expect(m[1] * 10 + m[3] * 20 + m[5]).toBeCloseTo(20);
+ const n = multiply(about(0, 0, 2), [1, 0, 0, 1, 5, 0]);
+ expect(n[4]).toBe(10);
+ const pill = roundRectPath(0, 0, 200, 60, 30);
+ expect(pill.length).toBeCloseTo(2 * 140 + Math.PI * 60, 6);
+ expect(pill.d.startsWith("M100 0")).toBe(true);
+ });
+
+ it("moves near layers more than far ones and keeps a full-frame layer covering", () => {
+ const cam = cameraAt({ preset: "drift", from: 0, to: 2 }, 0, 1080);
+ expect(cam.x).toBeCloseTo(-0.01 * 1080);
+ const near = layerMatrix(cam, -200, 1080, 1920);
+ const far = layerMatrix(cam, 800, 1080, 1920);
+ expect(Math.abs(near[4] - 540 * (1 - near[0]))).toBeGreaterThan(Math.abs(far[4] - 540 * (1 - far[0])));
+ const cover = layerMatrix(cam, 0, 1080, 1920, true);
+ expect(cover[0]).toBeGreaterThan(1);
+ expect(cameraAt({}, 1, 1080)).toEqual(REST_CAMERA);
+ const shake = cameraAt({ shake: { amplitude: 10, frequency: 12, from: 0, to: 1, seed: 3 } }, 0.3, 1080);
+ expect(shake).toEqual(cameraAt({ shake: { amplitude: 10, frequency: 12, from: 0, to: 1, seed: 3 } }, 0.3, 1080));
+ expect(Math.abs(shake.x)).toBeLessThanOrEqual(10);
+ });
+});
diff --git a/tests/motion-layout.test.ts b/tests/motion-layout.test.ts
new file mode 100644
index 00000000..9f0d7d47
--- /dev/null
+++ b/tests/motion-layout.test.ts
@@ -0,0 +1,94 @@
+import { describe, expect, it } from "vitest";
+import { directionOf, graphemes, layoutText, spelled, type TextSpec } from "@/lib/motion/layout";
+import { measure } from "./helpers/motion";
+
+// Text set exactly as typed: balanced breaks, no truncation, no case change, words never split, any script.
+
+const cp = (...c: number[]) => String.fromCodePoint(...c);
+const FAMILY = cp(0x1f469, 0x200d, 0x1f469, 0x200d, 0x1f467);
+const spec = (text: string, over: Partial<TextSpec> = {}): TextSpec => ({ text, family: "Inter", weight: 700, width: 600, maxLines: 2, max: 60, min: 40, letters: true, ...over });
+
+describe("text layout (motion-layout)", () => {
+ it("balances lines: no lone short word on the last line", () => {
+ // Greedy wrapping would put "now." alone on line 2.
+ const l = layoutText(spec("Invoices that chase themselves now.", { width: 1000, max: 60, min: 60 }), measure);
+ expect(l.overflow).toBe(false);
+ expect(l.lines.length).toBe(2);
+ const [a, b] = l.lines.map((x) => x.width);
+ expect(Math.abs(a - b)).toBeLessThanOrEqual(150);
+ expect(l.lines.map((x) => x.text)).toEqual(["Invoices that chase", "themselves now."]);
+ });
+
+ it("uses the largest size that fits before adding lines", () => {
+ const one = layoutText(spec("Quietly exceptional.", { width: 700 }), measure);
+ expect(one.lines.length).toBe(1);
+ expect(one.size).toBe(60);
+ const shrunk = layoutText(spec("Quietly exceptional cream for evenings.", { width: 700, maxLines: 1 }), measure);
+ expect(shrunk.size).toBeLessThan(60);
+ expect(shrunk.size).toBeGreaterThanOrEqual(40 * 0.99);
+ });
+
+ it("flags overflow instead of cutting: never an ellipsis, never a broken word", () => {
+ const text = "An extraordinarily long product name that will never fit in two short lines at all";
+ const l = layoutText(spec(text, { width: 300 }), measure);
+ expect(l.overflow).toBe(true);
+ expect(l.size).toBe(40);
+ expect(l.lines.map((x) => x.text).join(" ")).toBe(text);
+ for (const line of l.lines) expect(line.text).not.toMatch(/…|\.\.\./);
+ const word = layoutText(spec("Supercalifragilisticexpialidocious", { width: 300 }), measure);
+ expect(word.overflow).toBe(true);
+ expect(word.lines.map((x) => x.text)).toEqual(["Supercalifragilisticexpialidocious"]);
+ });
+
+ it("never changes case, keeps typed line breaks and runs of spaces", () => {
+ const l = layoutText(spec("iPhone stays\nexactly SO", { width: 2000, maxLines: 3 }), measure);
+ expect(l.lines.map((x) => x.text)).toEqual(["iPhone stays", "exactly SO"]);
+ expect(l.lines[1].gap).toBe("\n");
+ expect(spelled(l.lines)).toBe("iPhone stays\nexactly SO");
+ expect(spelled(l.lines.flatMap((x) => x.words))).toBe("iPhone stays\nexactly SO");
+ expect(spelled(l.lines.flatMap((x) => x.graphemes ?? []))).toBe("iPhone stays\nexactly SO");
+ });
+
+ it("trims only the ends", () => {
+ const l = layoutText(spec(" two spaces "), measure);
+ expect(l.text).toBe("two spaces");
+ expect(spelled(l.lines)).toBe("two spaces");
+ });
+
+ it("round-trips emoji, accents, CJK and right-to-left text, and keeps grapheme clusters whole", () => {
+ for (const text of [`${FAMILY} family`, `É${cp(0x301)}cole ${cp(0xfb01)}ne`, "日本語のテキストを正確に", "العربية الجميلة", "iPhone® 15 — 20 % off!"]) {
+ const l = layoutText(spec(text, { width: 300, maxLines: 4 }), measure);
+ expect(spelled(l.lines), text).toBe(text);
+ expect(spelled(l.lines.flatMap((x) => x.words)), text).toBe(text);
+ const letters = l.lines.flatMap((x) => x.graphemes ?? x.words);
+ expect(spelled(letters), text).toBe(text);
+ }
+ const fam = layoutText(spec(`${FAMILY} family`), measure);
+ expect(fam.lines[0].graphemes![0].text).toBe(FAMILY);
+ expect(graphemes(FAMILY)).toHaveLength(1);
+ // Arabic joins its letters: drawn by word, right to left.
+ const ar = layoutText(spec("العربية الجميلة"), measure);
+ expect(ar.dir).toBe("rtl");
+ expect(ar.lines[0].graphemes).toBeNull();
+ expect(ar.lines[0].words[0].x).toBeGreaterThan(ar.lines[0].words[1].x);
+ expect(directionOf("Hello")).toBe("ltr");
+ // CJK may break between its words.
+ const ja = layoutText(spec("日本語のテキストを正確に表示します", { width: 260, maxLines: 4, max: 40, min: 30 }), measure);
+ expect(ja.lines.length).toBeGreaterThan(1);
+ expect(ja.lines.map((x) => x.text).join("")).toBe("日本語のテキストを正確に表示します");
+ });
+
+ it("places letters and words where the whole line puts them", () => {
+ const l = layoutText(spec("Shop now"), measure);
+ const line = l.lines[0];
+ expect(line.words[1].x).toBeCloseTo(measure("Shop ", l.font));
+ const last = line.graphemes!.at(-1)!;
+ expect(last.x + last.w).toBeCloseTo(line.width);
+ });
+
+ it("handles empty text", () => {
+ const l = layoutText(spec(" "), measure);
+ expect(l.lines).toEqual([]);
+ expect(l.overflow).toBe(false);
+ });
+});
diff --git a/tests/motion-no-direct-download.test.ts b/tests/motion-no-direct-download.test.ts
new file mode 100644
index 00000000..1c648b6c
--- /dev/null
+++ b/tests/motion-no-direct-download.test.ts
@@ -0,0 +1,41 @@
+import fs from "node:fs";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+
+// Everything made with Kinetic Motion goes through Fuobe: saved as a result, downloaded from the Library. No motion
+// code hands the person a file straight from the page.
+
+const ROOT = process.cwd();
+const files = (dir: string): string[] =>
+ fs.existsSync(dir) ? fs.readdirSync(dir, { withFileTypes: true }).flatMap((d) => (d.isDirectory() ? files(path.join(dir, d.name)) : /\.(ts|tsx)$/.test(d.name) ? [path.join(dir, d.name)] : [])) : [];
+
+describe("no direct download of a motion render", () => {
+ const sources = [...files(path.join(ROOT, "src/components/motion")), ...files(path.join(ROOT, "src/lib/motion")), path.join(ROOT, "src/components/marketing/end-card-motion.tsx")];
+
+ it("finds the motion code", () => {
+ expect(sources.length).toBeGreaterThan(15);
+ });
+
+ it("never imports downloadBlob or makes a download link", () => {
+ for (const f of sources) {
+ const src = fs.readFileSync(f, "utf8");
+ expect(src, f).not.toMatch(/downloadBlob/);
+ expect(src, f).not.toMatch(/\.download\s*=|download=|setAttribute\(\s*["']download/);
+ expect(src, f).not.toMatch(/URL\.createObjectURL/);
+ }
+ });
+
+ it("saves through an upload and a recorded result", () => {
+ const save = fs.readFileSync(path.join(ROOT, "src/components/motion/save.ts"), "utf8");
+ expect(save).toContain("uploadFile(");
+ expect(save).toContain('"/api/generations/local"');
+ expect(save).toContain('op: "motion"');
+ });
+
+ it("is written up in the public sign-up rules and the architecture notes", () => {
+ const doc = fs.readFileSync(path.join(ROOT, "docs/public-signup.md"), "utf8");
+ expect(doc).toMatch(/Kinetic Motion/);
+ expect(doc).toContain("POST /api/generations/local");
+ expect(fs.readFileSync(path.join(ROOT, "docs/ARCHITECTURE.md"), "utf8")).toMatch(/Kinetic Motion/);
+ });
+});
diff --git a/tests/motion-scenes.test.ts b/tests/motion-scenes.test.ts
new file mode 100644
index 00000000..5f31300a
--- /dev/null
+++ b/tests/motion-scenes.test.ts
@@ -0,0 +1,244 @@
+import fs from "node:fs";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+import { themeFrom } from "@/components/ads/layout";
+import { planEndCard } from "@/components/marketing/end-card";
+import { textNodes, type TextRun } from "@/lib/motion/display";
+import { loadScene, SCENE_IDS } from "@/lib/motion/registry";
+import { spelled } from "@/lib/motion/layout";
+import type { Scene } from "@/lib/motion/scene";
+import { END_CARD_VARIANTS, endCardFrom } from "@/lib/motion/scenes/end-card/shared";
+import { designSize, type SizeSpec } from "@/lib/motion/sizes";
+import { DURATION_LIMITS, STAGGER_LIMITS } from "@/lib/motion/tween";
+import { input, measure, RASTER_LOGO, recipe, SVG_LOGO, allNodes } from "./helpers/motion";
+
+// Every registered scene: determinism under any order of seeks, exact spelling, the timing rules, and (for the end
+// card) a rest frame that is the still card's own layout.
+
+const scenes: Scene[] = await Promise.all(SCENE_IDS.map(loadScene));
+const SIZES: SizeSpec[] = [{ w: 720, h: 1280 }, "9:16", "1:1", "16:9", "4:5"];
+const cp = (...c: number[]) => String.fromCodePoint(...c);
+
+describe("the registry", () => {
+ it("has the five end-card styles", () => {
+ expect(SCENE_IDS.sort()).toEqual(END_CARD_VARIANTS.map((v) => `end-card/${v}`).sort());
+ for (const s of scenes) expect(s.durations).toEqual({ min: 2, max: 3, default: 2.5 });
+ });
+});
+
+describe("determinism (motion-determinism)", () => {
+ it("gives the same display list at a time whatever was asked before, for every scene and size", () => {
+ for (const scene of scenes) {
+ for (const size of SIZES) {
+ for (const logo of [RASTER_LOGO, SVG_LOGO, null]) {
+ const r = recipe(scene.id, { size });
+ const a = scene.plan(input(r, logo));
+ const b = scene.plan(input(r, logo));
+ const times = Array.from({ length: 40 }, (_, i) => (i / 39) * r.duration);
+ const forward = times.map((t) => JSON.stringify(a.evaluate(t)));
+ // Backward, then 200 shuffled seeks on a second plan.
+ for (let i = times.length - 1; i >= 0; i--) expect(JSON.stringify(a.evaluate(times[i]))).toBe(forward[i]);
+ for (let k = 0; k < 200; k++) {
+ const i = (k * 37 + 11) % times.length;
+ expect(JSON.stringify(b.evaluate(times[i])), `${scene.id} ${JSON.stringify(size)} t=${times[i]}`).toBe(forward[i]);
+ }
+ expect(a.design).toEqual(designSize(size));
+ }
+ }
+ }
+ });
+
+ it("never reads a clock, Math.random or the page in the pure core", () => {
+ const root = path.join(process.cwd(), "src/lib/motion");
+ const files = (dir: string): string[] => fs.readdirSync(dir, { withFileTypes: true }).flatMap((d) => (d.isDirectory() ? files(path.join(dir, d.name)) : [path.join(dir, d.name)]));
+ for (const f of files(root)) {
+ const src = fs.readFileSync(f, "utf8").replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm, "");
+ expect(src, f).not.toMatch(/Math\.random|Date\.now|new Date|performance\.|requestAnimationFrame|document\.|window\.|"use client"/);
+ }
+ });
+});
+
+describe("spelling (motion-spelling)", () => {
+ const hostile = ["iPhone® 15 — 20 % off!", `ÉCOLE ${cp(0xfb01)} ligature`, `${cp(0x1f469, 0x200d, 0x1f469, 0x200d, 0x1f467)} family`, "العربية", " two spaces ", "Q", "Barrier Cream for very dry skin"];
+ const fieldsOf = (runs: TextRun[]) => spelled(runs);
+
+ it("sets every field exactly as typed at rest, and never draws a letter that wasn't typed", () => {
+ for (const scene of scenes) {
+ for (const text of hostile) {
+ for (const field of ["product", "cta", "brand", "website"] as const) {
+ const r = recipe(scene.id, { fields: { ...recipe(scene.id).fields, [field]: text } });
+ // The brand's name shows only without a logo.
+ const plan = scene.plan(input(r, field === "brand" ? null : RASTER_LOGO));
+ if (plan.overflow.length) continue;
+ const rest = textNodes(plan.evaluate(plan.rest).nodes);
+ const node = rest.find((n) => n.field === field);
+ expect(node, `${scene.id} ${field}`).toBeDefined();
+ expect(fieldsOf(node!.runs), `${scene.id} ${field} "${text}"`).toBe(text.trim());
+ for (let i = 0; i <= 30; i++) {
+ const t = (i / 30) * r.duration;
+ for (const n of textNodes(plan.evaluate(t).nodes)) {
+ const typed = r.fields[n.field] ?? "";
+ for (const run of n.runs) expect(typed.includes(run.text), `${scene.id} t=${t} "${run.text}" not in "${typed}"`).toBe(true);
+ }
+ }
+ }
+ }
+ }
+ });
+
+ it("never upper-cases the brand's name (the still card doesn't either)", () => {
+ const theme = themeFrom({ colors: ["#6b1d2a"] });
+ const still = planEndCard({ theme, content: { brand: "maison ardent", product: "Cream" }, logo: null, measure });
+ expect(still.brand!.lines).toEqual(["maison ardent"]);
+ for (const scene of scenes) {
+ const plan = scene.plan(input(recipe(scene.id, { fields: { brand: "maison ardent", product: "Cream" } }), null));
+ expect(spelled(textNodes(plan.evaluate(plan.rest).nodes).find((n) => n.field === "brand")!.runs)).toBe("maison ardent");
+ }
+ });
+
+ it("names a field that doesn't fit instead of cutting it", () => {
+ const long = "An extraordinarily long product name that keeps going well past what two lines can hold on any card";
+ for (const scene of scenes) expect(scene.plan(input(recipe(scene.id, { fields: { brand: "B", product: long } }))).overflow).toEqual(["product"]);
+ });
+});
+
+describe("timing (motion-timing)", () => {
+ it("keeps every entrance 350–700 ms, nothing under 200 ms, staggers in range, settled with a 1 s hold", () => {
+ for (const scene of scenes) {
+ for (const duration of [2, 2.5, 3]) {
+ for (const logo of [RASTER_LOGO, SVG_LOGO, null]) {
+ const r = recipe(scene.id, { duration });
+ const plan = scene.plan(input(r, logo));
+ const events = plan.timeline.events;
+ expect(events.length).toBeGreaterThan(2);
+ for (const e of events) {
+ const [lo, hi] = DURATION_LIMITS[e.kind];
+ expect(e.dur, `${scene.id} ${e.id} ${duration}s`).toBeGreaterThanOrEqual(lo - 1e-9);
+ expect(e.dur, `${scene.id} ${e.id} ${duration}s`).toBeLessThanOrEqual(hi + 1e-9);
+ expect(e.start + e.dur).toBeLessThanOrEqual(plan.settled + 1e-9);
+ // A style may already be a few frames into its motion on its first frame (never more than 0.15 s).
+ expect(e.start).toBeGreaterThanOrEqual(-0.15);
+ }
+ const groups = new Map<string, number[]>();
+ for (const e of events) if (e.group) groups.set(e.group, [...(groups.get(e.group) ?? []), e.start]);
+ for (const [g, starts] of groups) {
+ const unit = events.find((e) => e.group === g)!.unit!;
+ const [lo, hi] = STAGGER_LIMITS[unit];
+ for (let i = 1; i < starts.length; i++) {
+ const gap = starts[i] - starts[i - 1];
+ expect(gap, `${scene.id} ${g}`).toBeGreaterThanOrEqual(lo - 1e-6);
+ expect(gap, `${scene.id} ${g}`).toBeLessThanOrEqual(hi + 1e-6);
+ }
+ }
+ expect(duration - plan.settled, `${scene.id} ${duration}s hold`).toBeGreaterThanOrEqual(1);
+ // The last frame is the rest frame; through the hold only the camera moves, coming home on the last frame.
+ expect(plan.rest).toBeCloseTo((Math.round(duration * r.fps) - 1) / r.fps, 9);
+ const still = plan.evaluate(plan.rest);
+ for (const t of [plan.settled + 0.01, (plan.settled + plan.rest) / 2, plan.rest - 1 / r.fps]) {
+ const held = plan.evaluate(t);
+ expect(held.nodes).toHaveLength(1);
+ const cam = held.nodes[0];
+ expect(cam.type === "group" && cam.id === "camera" && JSON.stringify(cam.children)).toBe(JSON.stringify(still.nodes));
+ }
+ expect(JSON.stringify(plan.evaluate(duration))).toBe(JSON.stringify(still));
+ expect(plan.still(plan.rest)).toBe(true);
+ expect(plan.still(plan.settled)).toBe(false);
+ }
+ }
+ }
+ });
+
+ it("opens on a ground that stands apart from the brand colour, even for a dark kit", () => {
+ for (const colors of [["#6b1d2a", "#e9d8b4"], ["#1e3a8a"], ["#f5d90a", "#141414"]]) {
+ for (const id of ["end-card/iris", "end-card/glint"]) {
+ const plan = scenes.find((s) => s.id === id)!.plan(input(recipe(id, { brand: { name: "x", colors, fonts: {} } })));
+ expect(plan.evaluate(0.02).background.toLowerCase(), `${id} ${colors}`).not.toBe(endCardFrom(recipe(id, { brand: { name: "x", colors, fonts: {} } })).theme.accent.toLowerCase());
+ }
+ }
+ });
+
+ it("moves something between the start and rest (in-between frames differ)", () => {
+ for (const scene of scenes) {
+ const plan = scene.plan(input(recipe(scene.id)));
+ const frames = [0.1, 0.4, 0.8].map((t) => JSON.stringify(plan.evaluate(t * plan.settled)));
+ expect(new Set(frames).size, scene.id).toBe(3);
+ }
+ });
+
+ it("is readable by 0.95 s of a 2.5 s card: every piece in place but a passing light", () => {
+ for (const scene of scenes) {
+ for (const logo of [RASTER_LOGO, SVG_LOGO, null]) {
+ const plan = scene.plan(input(recipe(scene.id), logo));
+ for (const e of plan.timeline.events) if (e.id !== "glint") expect(e.start + e.dur, `${scene.id} ${e.id}`).toBeLessThanOrEqual(0.95 + 1e-9);
+ }
+ }
+ });
+
+ it("cuts in on movement: the first frame already shows the style under way", () => {
+ for (const scene of scenes) {
+ const plan = scene.plan(input(recipe(scene.id, { size: "9:16" })));
+ const first = plan.evaluate(0);
+ expect(allNodes(first).length, scene.id).toBeGreaterThan(0);
+ // Some event is already part-way on the first frame.
+ expect(plan.timeline.events.some((e) => e.start < 0), scene.id).toBe(true);
+ if (scene.id === "end-card/rise") {
+ const panel = allNodes(first).find((n) => n.type === "rect" && n.id === "panel");
+ expect(panel && panel.type === "rect" && panel.y <= first.h * 0.85).toBe(true);
+ }
+ if (scene.id === "end-card/iris") {
+ const iris = allNodes(first).find((n) => n.type === "ellipse" && n.id === "iris");
+ expect(iris && iris.type === "ellipse" && iris.rx >= Math.hypot(first.w, first.h) * 0.08).toBe(true);
+ }
+ }
+ });
+
+ it("gives each style a telling moment for the chooser, inside the card", () => {
+ for (const scene of scenes) {
+ const plan = scene.plan(input(recipe(scene.id)));
+ expect(plan.signature, scene.id).toBeDefined();
+ expect(plan.signature!).toBeGreaterThan(0);
+ expect(plan.signature!).toBeLessThan(plan.settled);
+ }
+ });
+});
+
+describe("the rest frame is the still card (motion-rest-frame)", () => {
+ it("puts the logo, the words and the pill where planEndCard does, within half a unit", () => {
+ for (const scene of scenes) {
+ for (const logo of [RASTER_LOGO, null]) {
+ const r = recipe(scene.id);
+ const plan = scene.plan(input(r, logo));
+ const { theme, content } = endCardFrom(r);
+ const still = planEndCard({ theme, content, logo, measure, size: plan.design });
+ const rest = plan.evaluate(plan.rest);
+ expect(rest.background).toBe(still.bg);
+ const nodes = allNodes(rest);
+ if (logo) {
+ const img = nodes.find((n) => n.type === "image")!;
+ expect(img.type === "image" && [img.x, img.y, img.w, img.h].map((v, i) => Math.abs(v - [still.logo!.x, still.logo!.y, still.logo!.w, still.logo!.h][i]) <= 0.5).every(Boolean), scene.id).toBe(true);
+ }
+ const pill = nodes.find((n) => n.type === "rect" && n.id === "cta.pill");
+ expect(pill && pill.type === "rect" && Math.abs(pill.x - still.cta!.x) <= 0.5 && Math.abs(pill.y - still.cta!.y) <= 0.5 && Math.abs(pill.w - still.cta!.w) <= 0.5).toBe(true);
+ const texts = textNodes(rest.nodes);
+ const boxes = { product: still.headline, cta: still.cta!.text, website: still.body!, brand: still.brand };
+ for (const [field, box] of Object.entries(boxes)) {
+ if (!box) continue;
+ const runs = texts.find((n) => n.field === field)!.runs;
+ expect(runs.map((x) => x.text)).toEqual(box.lines);
+ runs.forEach((run, i) => {
+ const top = box.y + i * box.lineHeight + (box.lineHeight - box.size) / 2;
+ expect(Math.abs(run.y - top), `${scene.id} ${field}`).toBeLessThanOrEqual(0.5);
+ expect(Math.abs(run.x + measure(run.text, run.font) / 2 - box.x), `${scene.id} ${field}`).toBeLessThanOrEqual(0.5);
+ expect(run.font).toBe(box.font);
+ });
+ }
+ }
+ }
+ });
+
+ it("reads on the brand colour: words in the readable ink, the pill's label in contrast", () => {
+ const r = recipe("end-card/draw-on", { brand: { name: "x", colors: ["#f5d90a"], fonts: {} } });
+ const { theme } = endCardFrom(r);
+ expect(theme.onAccent).toBe("#141414");
+ });
+});
diff --git a/tests/relight.test.ts b/tests/relight.test.ts
index b7ecfc6a..476c65f9 100644
--- a/tests/relight.test.ts
+++ b/tests/relight.test.ts
@@ -725,9 +725,9 @@ describe("where Relight lives", () => {
expect(acts[i + 1].id).toBe("live-edit");
});
- it("the local result route takes a Relight blend and nothing else new", () => {
+ it("the local result route takes a Relight blend (and Kinetic Motion clips)", () => {
const route = fs.readFileSync(path.join(ROOT, "src/app/api/generations/local/route.ts"), "utf8");
- expect(route).toContain('op: z.enum(["grade", "relight"])');
+ expect(route).toContain('op: z.enum(["grade", "relight", "motion"])');
});
});