diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 67f49766cd..475063de78 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "hyperframes",
"description": "HyperFrames by HeyGen. Write HTML, render video. Compositions, GSAP and runtime adapter animations, captions, voiceovers, audio-reactive visuals, and website capture for HyperFrames.",
- "version": "0.8.214",
+ "version": "0.8.224",
"author": {
"name": "HeyGen",
"email": "hyperframes@heygen.com",
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 48d6c24d98..59ec50454a 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "hyperframes",
"description": "Write HTML, render video. Compositions, Tailwind v4 styles, GSAP and runtime adapter animations, captions, voiceovers, audio-reactive visuals, and website capture for HyperFrames.",
- "version": "0.8.214",
+ "version": "0.8.224",
"author": {
"name": "HeyGen",
"email": "hyperframes@heygen.com",
diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.json
index 7eb1a0b006..cdae5cc122 100644
--- a/.cursor-plugin/plugin.json
+++ b/.cursor-plugin/plugin.json
@@ -3,7 +3,7 @@
"name": "hyperframes",
"displayName": "HyperFrames by HeyGen",
"description": "Write HTML, render video. Compositions, Tailwind v4 styles, GSAP and runtime adapter animations, captions, voiceovers, audio-reactive visuals, and website capture for HyperFrames.",
- "version": "0.8.214",
+ "version": "0.8.224",
"author": {
"name": "HeyGen",
"email": "hyperframes@heygen.com"
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 0cb4fadc6e..f5d8186490 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -238,6 +238,7 @@ jobs:
- "packages/cli/src/{background-removal,registry,telemetry}/**"
- "packages/cli/src/capture/{captureCompositionFrame,captureTimeout,navigateForCapture,readBoundedResponse}.ts"
- "packages/cli/src/media-use/lib/config-lock.mjs"
+ - "packages/cli/src/auth/{config,errors,paths,telemetryIdentity}.ts"
- "packages/cli/scripts/**"
- "packages/core/stubs/**"
- "packages/engine/src/**"
@@ -310,7 +311,7 @@ jobs:
name: Build
needs: changes
# A skipped required check passes, so a broken change detection must fail it instead.
- if: ${{ !cancelled() && (needs.changes.result != 'success' || needs.changes.outputs.code == 'true' || needs.changes.outputs.cli_bundle == 'true' || needs.changes.outputs.edit_accuracy == 'true' || needs.changes.outputs.release_only == 'true') }}
+ if: ${{ !cancelled() && (needs.changes.result != 'success' || needs.changes.outputs.code == 'true' || needs.changes.outputs.cli_bundle == 'true' || needs.changes.outputs.release_only == 'true') }}
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
@@ -343,9 +344,26 @@ jobs:
if-no-files-found: error
retention-days: 7
- run: bun run check:cli-lazy-deps
- - name: Share the built CLI with the edit accuracy shards
- if: needs.changes.outputs.edit_accuracy == 'true'
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+
+ # The shards need only the built CLI; building it apart keeps them from waiting on Build's packing checks.
+ edit-accuracy-cli:
+ name: "Studio: edit accuracy CLI build"
+ needs: changes
+ if: needs.changes.outputs.edit_accuracy == 'true'
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ with:
+ lfs: true
+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
+ - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
+ with:
+ node-version: 22
+ - uses: ./.github/actions/prepare-ffmpeg-bin
+ - run: bash scripts/ci/install-workspace-dependencies.sh
+ - run: bun run build
+ - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: edit-accuracy-cli
path: packages/cli/dist
@@ -1178,11 +1196,11 @@ jobs:
if-no-files-found: error
# Manual editing accuracy in the built Studio, gated against the base branch's baseline.json. A pull request
- # runs the `pr` slice in 5 shards; the merge queue runs the full grid in 20, so nothing reaches main unmeasured.
+ # runs the `pr` slice in 15 shards; the merge queue runs the full grid in 30, so nothing reaches main unmeasured.
# The gate job below repeats both shard counts.
studio-edit-accuracy:
name: "Studio: edit accuracy (${{ matrix.shard }}/${{ strategy.job-total }})"
- needs: [changes, build]
+ needs: [changes, edit-accuracy-cli]
if: needs.changes.outputs.edit_accuracy == 'true'
runs-on: ubuntu-latest
# Healthy shards take 6-9 min; 25 leaves a cancelled shard's fresh re-run inside the queue's 60 min check wait.
@@ -1190,7 +1208,7 @@ jobs:
strategy:
fail-fast: false
matrix:
- shard: ${{ fromJSON(github.event_name == 'merge_group' && '[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]' || '[1, 2, 3, 4, 5]') }}
+ shard: ${{ fromJSON(github.event_name == 'merge_group' && '[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]' || '[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]') }}
env:
EDIT_ACCURACY_GRID: ${{ github.event_name == 'merge_group' && 'full' || 'pr' }}
steps:
@@ -1254,7 +1272,7 @@ jobs:
# Each marked shard runs once more on a fresh runner and replaces its evidence before the gate reads it.
studio-edit-accuracy-retry:
name: "Studio: edit accuracy retry (${{ matrix.shard }})"
- needs: [changes, build, studio-edit-accuracy-retry-plan]
+ needs: [changes, edit-accuracy-cli, studio-edit-accuracy-retry-plan]
if: ${{ !cancelled() && needs.studio-edit-accuracy-retry-plan.outputs.shards != '[]' && needs.studio-edit-accuracy-retry-plan.outputs.shards != '' }}
runs-on: ubuntu-latest
timeout-minutes: 25
@@ -1264,7 +1282,7 @@ jobs:
shard: ${{ fromJSON(needs.studio-edit-accuracy-retry-plan.outputs.shards) }}
env:
EDIT_ACCURACY_GRID: ${{ github.event_name == 'merge_group' && 'full' || 'pr' }}
- SHARDS: ${{ github.event_name == 'merge_group' && 20 || 5 }}
+ SHARDS: ${{ github.event_name == 'merge_group' && 30 || 15 }}
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
@@ -1320,7 +1338,7 @@ jobs:
id: gate
# Smoothness and newly passing cases are reported, not gated; a case fails only if it fails 2 of its 3 runs.
env:
- SHARDS: ${{ github.event_name == 'merge_group' && 20 || 5 }}
+ SHARDS: ${{ github.event_name == 'merge_group' && 30 || 15 }}
run: |
set +e
mapfile -t RESULTS < <(find /tmp/edit-accuracy-shards -name results.json | sort)
diff --git a/.github/workflows/fast-video-validation.yml b/.github/workflows/fast-video-validation.yml
index f1ada4bd15..6c80db3fd9 100644
--- a/.github/workflows/fast-video-validation.yml
+++ b/.github/workflows/fast-video-validation.yml
@@ -46,8 +46,8 @@ jobs:
file: Dockerfile.test
load: true
tags: hyperframes-producer:test
+ # regression.yml owns this cache's writes.
cache-from: type=gha,scope=regression-test-image
- cache-to: type=gha,mode=max,scope=regression-test-image
- name: Validate fast-capture video (drawElement + BeginFrame)
run: |
diff --git a/.github/workflows/regression.yml b/.github/workflows/regression.yml
index 8aef6a4589..80ae838280 100644
--- a/.github/workflows/regression.yml
+++ b/.github/workflows/regression.yml
@@ -156,10 +156,9 @@ jobs:
load: true
tags: hyperframes-producer:test
cache-from: type=gha,scope=regression-test-image
- # PR matrices can fan out across many stacked branches at once. Let
- # them consume the shared cache, but keep a single writer on main so
- # concurrent exports cannot exhaust the Actions cache service.
- cache-to: ${{ github.event_name == 'push' && 'type=gha,mode=max,scope=regression-test-image' || '' }}
+ # One writer: the first shard of a main push. Every shard rebuilds the same layers with
+ # different digests, so each export added ~1.3 GB and evicted the rest of the 10 GB cache.
+ cache-to: ${{ github.event_name == 'push' && strategy.job-index == 0 && 'type=gha,mode=max,scope=regression-test-image' || '' }}
- name: "Run regression shard: ${{ matrix.shard }} (${{ matrix.mode }})"
run: |
diff --git a/.github/workflows/windows-render.yml b/.github/workflows/windows-render.yml
index bde7e5e584..4036f4836e 100644
--- a/.github/workflows/windows-render.yml
+++ b/.github/workflows/windows-render.yml
@@ -437,8 +437,17 @@ jobs:
studio_shard: 2/2
- lane: core
packages: --filter @hyperframes/core --filter @hyperframes/player --filter @hyperframes/shader-transitions
- - lane: engine-cli
+ # Engine and CLI ran one after the other in a single lane (about 5 + 11 min), 16 min of a 16 min deadline;
+ # each half runs the same two packages with Vitest's --shard, so the lanes end together.
+ - lane: engine-cli-1
packages: --filter @hyperframes/engine --filter @hyperframes/cli
+ test_shard: 1/2
+ process_tests: true
+ - lane: engine-cli-2
+ packages: --filter @hyperframes/engine --filter @hyperframes/cli
+ test_shard: 2/2
+ process_tests: true
+ once_checks: true
runtime_contract: true
steps:
@@ -451,8 +460,8 @@ jobs:
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
ref: ${{ inputs.ref || github.sha }}
- # Only the engine-cli lane reads an LFS file (engine's ffprobe test parses a producer HDR PNG).
- lfs: ${{ matrix.lane == 'engine-cli' }}
+ # Only the engine-cli lanes read an LFS file (engine's ffprobe test parses a producer HDR PNG).
+ lfs: ${{ matrix.process_tests == true }}
# -----------------------------------------------------------------
# Install FFmpeg so vitest suites that gate on `HAS_FFMPEG`
@@ -500,7 +509,7 @@ jobs:
bun run --cwd packages/core build
- name: Prepare browser for process tests
- if: matrix.lane == 'engine-cli'
+ if: matrix.process_tests
shell: pwsh
run: node --import tsx packages/cli/scripts/prepare-process-test-browser.mjs
@@ -518,25 +527,25 @@ jobs:
# Each package starts its own Vitest pool. Bound every pool so concurrent
# package scripts cannot oversubscribe the hosted Windows runner.
# timeout-minutes did not fire on a hung run, so the script enforces the 16 minutes itself.
- run: ./scripts/ci/run-with-deadline.ps1 -Minutes 16 -Command 'bun run ${{ matrix.packages }} test -- --maxWorkers=2 --reporter=verbose'
+ run: ./scripts/ci/run-with-deadline.ps1 -Minutes 16 -Command 'bun run ${{ matrix.packages }} test -- --maxWorkers=2 --reporter=verbose ${{ matrix.test_shard && format('--shard={0}', matrix.test_shard) || '' }}'
- name: Verify waveform cache writes on Windows
- if: matrix.lane == 'engine-cli'
+ if: matrix.once_checks
shell: pwsh
run: bun run --cwd packages/studio-server test -- src/helpers/waveform.test.ts src/helpers/waveform.file-race.test.ts --maxWorkers=2
- name: Verify producer lint entry reads on Windows
- if: matrix.lane == 'engine-cli'
+ if: matrix.once_checks
shell: pwsh
run: bunx vitest run packages/producer/src/services/hyperframeLint.file-race.test.ts --maxWorkers=2
- name: Verify Windows frame staging
- if: matrix.lane == 'engine-cli'
+ if: matrix.once_checks
shell: pwsh
run: bunx vitest run packages/producer/src/services/windowsFrameStaging.test.ts --maxWorkers=2
- name: Verify catalog file operations on Windows
- if: matrix.lane == 'engine-cli'
+ if: matrix.once_checks
shell: pwsh
run: bunx vitest run scripts/catalog/catalog-payload-assets.file-race.test.ts scripts/catalog/catalog-payload-assets.cache-race.test.ts --maxWorkers=2
diff --git a/.prettierignore b/.prettierignore
index ef105989a1..cea6e5f904 100644
--- a/.prettierignore
+++ b/.prettierignore
@@ -56,3 +56,4 @@ skills/media-use/SKILL.md
skills/figma/SKILL.md
skills/slideshow/SKILL.md
skills/remotion-to-hyperframes/SKILL.md
+skills/reverse-any-video/SKILL.md
diff --git a/ADOPTERS.md b/ADOPTERS.md
index fc90f652d4..5151720505 100644
--- a/ADOPTERS.md
+++ b/ADOPTERS.md
@@ -28,3 +28,5 @@ If you'd rather not be listed publicly, that's fine — drop a note in [our Disc
| [Mini Course Generator](https://minicoursegenerator.com) | [@eren-commits](https://github.com/eren-commits) | Uses HyperFrames for AI-composed videos in its course creation workflow. |
| [PandaStudio](https://www.writepanda.ai) | [@kamskans](https://github.com/kamskans) | Renders motion graphics, animated captions, and overlays for MP4 exports in its desktop video editor. |
| [Skyflo](https://skyflo.ai) | [@KaranJagtiani](https://github.com/KaranJagtiani) | Renders Skyflo's product launch films, authored end to end by AI agents from script to soundtrack selection. |
+| [OpenAI](https://openai.com) | [Brent Schooley](https://x.com/chefbrent) | Edits OpenAI developer videos in the cloud with HyperFrames, driven by an agent review-and-revise loop. |
+| [Nate Herk](https://www.youtube.com/@nateherk) | [@nateherkai](https://github.com/nateherkai) | Edits YouTube videos, reels, and Shorts with Claude Code or Codex through the HyperFrames-based Herk Edit Kit. |
diff --git a/README.md b/README.md
index ffe9f4c2c4..e76e22f63c 100644
--- a/README.md
+++ b/README.md
@@ -30,6 +30,13 @@
+
+ Download the desktop app:
+ macOS ·
+ Windows ·
+ Linux (.deb)
+
+
HyperFrames is an open-source framework for turning HTML, CSS, media, and seekable animations into deterministic MP4 videos. Use it locally with the CLI, from AI coding agents with skills, or as the rendering core behind hosted authoring workflows.
Using Claude Code, Codex, Cursor, or another coding agent? Run `npx hyperframes skills update` once, then ask your agent to make a video.
diff --git a/docs/catalog/blocks/ai-answer-rank.mdx b/docs/catalog/blocks/ai-answer-rank.mdx
index 45df066d4b..b70984226a 100644
--- a/docs/catalog/blocks/ai-answer-rank.mdx
+++ b/docs/catalog/blocks/ai-answer-rank.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
AI Answer Rank
+
Is your brand in the AI answer? A question types into a chat card, the assistant answers with a ranked list of three picks, then re-ranks: the promoted brand slides into its slot, the picks below step down, and the brand row lands with the one accent highlight and a check. For answer-engine and AI-visibility marketing
+
+
-
+
+
+
## Add it to your video
@@ -656,6 +662,4 @@ Created by Tugra Avci.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/ai-chat-reveal.mdx b/docs/catalog/blocks/ai-chat-reveal.mdx
index a22e742255..bc37064db6 100644
--- a/docs/catalog/blocks/ai-chat-reveal.mdx
+++ b/docs/catalog/blocks/ai-chat-reveal.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
AI Chat Reveal
+
A question is typed on a rising keyboard, sent, and answered by an AI that streams its reply word by word on a measured token rhythm - thinking dot, uneven bursts, bulleted list - before the app cuts to a branded closing card
+
+
-
+
+
+
## Add it to your video
@@ -1118,6 +1124,4 @@ Created by Miao Yang.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/app-showcase.mdx b/docs/catalog/blocks/app-showcase.mdx
index ff26089a28..0f1b3cc1a6 100644
--- a/docs/catalog/blocks/app-showcase.mdx
+++ b/docs/catalog/blocks/app-showcase.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
App Showcase
+
Fitness app product showcase with three floating smartphone screens
+
+
-
+
+
+
## Add it to your video
@@ -1013,6 +1019,4 @@ Tagged `showcase` `app` `3d`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/apple-money-count.mdx b/docs/catalog/blocks/apple-money-count.mdx
index 2808be72da..5dbc2b07b1 100644
--- a/docs/catalog/blocks/apple-money-count.mdx
+++ b/docs/catalog/blocks/apple-money-count.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Apple Money Count
+
Apple-style finance counter that counts from $0 to $10,000, flashes green, and bursts money icons with sound.
+
+
-
+
+
+
## Add it to your video
@@ -396,6 +402,4 @@ Created by [Stronkter](https://x.com/Stronkter).
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/aurora.mdx b/docs/catalog/blocks/aurora.mdx
index cd3d6048e9..875c684dec 100644
--- a/docs/catalog/blocks/aurora.mdx
+++ b/docs/catalog/blocks/aurora.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Aurora
+
Green and violet aurora curtains ripple across a night sky. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `background` `light` `aurora` `sky`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/bar-chart-race.mdx b/docs/catalog/blocks/bar-chart-race.mdx
index a543c80e80..110036ba96 100644
--- a/docs/catalog/blocks/bar-chart-race.mdx
+++ b/docs/catalog/blocks/bar-chart-race.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Bar Chart Race
+
Ranked bars grow and overtake each other as a time series advances, with the axis rescaling as values climb and the accent handing over to whoever leads
+
+
-
+
+
+
## Add it to your video
@@ -708,6 +714,4 @@ Tagged `data` `chart` `statistics` `ranking`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/beat-freeze-cut.mdx b/docs/catalog/blocks/beat-freeze-cut.mdx
index 8bc2aa4f43..fa4392a1f7 100644
--- a/docs/catalog/blocks/beat-freeze-cut.mdx
+++ b/docs/catalog/blocks/beat-freeze-cut.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Beat Freeze Cut
+
A beat-driven speed ramp, freeze-frame hit, and hard-cut sequence for music-led promos and montages.
+
+
-
+
+
+
## Add it to your video
@@ -952,6 +958,4 @@ Tagged `transition` `music` `beat-driven` `freeze-frame`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/blob.mdx b/docs/catalog/blocks/blob.mdx
index a920033885..e50535dee5 100644
--- a/docs/catalog/blocks/blob.mdx
+++ b/docs/catalog/blocks/blob.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Blob
+
A soft coral and pink blob with a warm highlight slowly changes shape on black. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `background` `abstract` `organic` `gradient`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/blue-sweater-intro-video.mdx b/docs/catalog/blocks/blue-sweater-intro-video.mdx
index db8f4bdde9..ae4d818c1c 100644
--- a/docs/catalog/blocks/blue-sweater-intro-video.mdx
+++ b/docs/catalog/blocks/blue-sweater-intro-video.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Blue Sweater Intro Video
+
Warm AI creator intro sequence that resolves into an X follow card for @_blue_sweater_.
+
+
-
+
+
+
## Add it to your video
@@ -1591,6 +1597,4 @@ Created by [Joe Sai](https://x.com/_blue_sweater_).
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/camcorder-hud.mdx b/docs/catalog/blocks/camcorder-hud.mdx
index c323350a74..84f6c8d0e7 100644
--- a/docs/catalog/blocks/camcorder-hud.mdx
+++ b/docs/catalog/blocks/camcorder-hud.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Camcorder HUD
+
Responsive REC, battery, editable date placeholder, and timeline-driven counter overlay for creator-camera and camcorder treatments
+
+
-
+
+
+
## Add it to your video
@@ -229,6 +235,4 @@ Tagged `camcorder` `camera` `recording` `hud` `overlay` `creator` `media-treatme
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/camera-dolly-zoom.mdx b/docs/catalog/blocks/camera-dolly-zoom.mdx
index 6252af4dae..49e8825251 100644
--- a/docs/catalog/blocks/camera-dolly-zoom.mdx
+++ b/docs/catalog/blocks/camera-dolly-zoom.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Dolly Zoom (Vertigo Shot)
+
Camera tracks toward or away from the subject while the field of view changes the opposite way, so the subject holds its frame size while the background collapses behind it or rushes in. Focal length is solved from dolly distance every frame against d * tan(FOV/2) = const, not keyframed beside it. Requires depth: the subject sits on the z = 0 plane and the content behind it must be layered or genuinely 3D (translateZ at two or more distinct depths) -- a flat element gains nothing from this move.
+
+
-
+
+
+
## Add it to your video
@@ -443,6 +449,4 @@ Tagged `camera` `depth` `3d` `cinematic`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/canopy-part-title.mdx b/docs/catalog/blocks/canopy-part-title.mdx
index a5525250ca..0c81d0b21f 100644
--- a/docs/catalog/blocks/canopy-part-title.mdx
+++ b/docs/catalog/blocks/canopy-part-title.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Canopy Part Title
+
Leaves sweep through the frame and part to reveal the headline.
+
+
-
+
+
+
## Add it to your video
@@ -1455,6 +1461,4 @@ Tagged `3d-motion` `title-card` `leaves` `organic` `depth-of-field` `two-headlin
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/carousel-circle-1.mdx b/docs/catalog/blocks/carousel-circle-1.mdx
index 5bc85e5cd0..834822902a 100644
--- a/docs/catalog/blocks/carousel-circle-1.mdx
+++ b/docs/catalog/blocks/carousel-circle-1.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Circle Carousel 1
+
Image cards ride a circle with a size gradient by depth angle, sweeping in fast-slow-fast swings (Circle style 1); 12 image slots.
+
+
-
+
+
+
## Add it to your video
@@ -1103,6 +1109,4 @@ Created by Jake Moran.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/carousel-circle-2.mdx b/docs/catalog/blocks/carousel-circle-2.mdx
index 880666df71..aeed4d2495 100644
--- a/docs/catalog/blocks/carousel-circle-2.mdx
+++ b/docs/catalog/blocks/carousel-circle-2.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Circle Carousel 2
+
Image cards ride a circle with a size gradient by depth angle, sweeping in fast-slow-fast swings (Circle style 2); 12 image slots.
+
+
-
+
+
+
## Add it to your video
@@ -1103,6 +1109,4 @@ Created by Jake Moran.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/carousel-circle-3.mdx b/docs/catalog/blocks/carousel-circle-3.mdx
index 5cc711ca67..0633c5fe28 100644
--- a/docs/catalog/blocks/carousel-circle-3.mdx
+++ b/docs/catalog/blocks/carousel-circle-3.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Circle Carousel 3
+
Image cards ride a circle with a size gradient by depth angle, sweeping in fast-slow-fast swings (Circle style 3); 12 image slots.
+
+
-
+
+
+
## Add it to your video
@@ -1103,6 +1109,4 @@ Created by Jake Moran.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/carousel-circle-4.mdx b/docs/catalog/blocks/carousel-circle-4.mdx
index 7a481b477b..7569cf147f 100644
--- a/docs/catalog/blocks/carousel-circle-4.mdx
+++ b/docs/catalog/blocks/carousel-circle-4.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Circle Carousel 4
+
Image cards ride a circle with a size gradient by depth angle, sweeping in fast-slow-fast swings (Circle style 4); 12 image slots.
+
+
-
+
+
+
## Add it to your video
@@ -1103,6 +1109,4 @@ Created by Jake Moran.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/carousel-circle-5.mdx b/docs/catalog/blocks/carousel-circle-5.mdx
index fc6f32ed3b..adcc236105 100644
--- a/docs/catalog/blocks/carousel-circle-5.mdx
+++ b/docs/catalog/blocks/carousel-circle-5.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Circle Carousel 5
+
Image cards ride a circle with a size gradient by depth angle, sweeping in fast-slow-fast swings (Circle style 5); 12 image slots.
+
+
-
+
+
+
## Add it to your video
@@ -1103,6 +1109,4 @@ Created by Jake Moran.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/carousel-orbit-1.mdx b/docs/catalog/blocks/carousel-orbit-1.mdx
index ff348514d2..4b305de207 100644
--- a/docs/catalog/blocks/carousel-orbit-1.mdx
+++ b/docs/catalog/blocks/carousel-orbit-1.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Orbit Carousel 1
+
Image cards on a spinning 3D Fibonacci sphere, billboarded to the camera, sized by camera distance (Orbit style 1); 24 image slots.
+
+
-
+
+
+
## Add it to your video
@@ -1137,6 +1143,4 @@ Created by Jake Moran.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/carousel-orbit-2.mdx b/docs/catalog/blocks/carousel-orbit-2.mdx
index 7d6ce79492..7cf2b45720 100644
--- a/docs/catalog/blocks/carousel-orbit-2.mdx
+++ b/docs/catalog/blocks/carousel-orbit-2.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Orbit Carousel 2
+
Image cards on a spinning 3D Fibonacci sphere, billboarded to the camera, sized by camera distance (Orbit style 2); 24 image slots.
+
+
-
+
+
+
## Add it to your video
@@ -1137,6 +1143,4 @@ Created by Jake Moran.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/carousel-orbit-3.mdx b/docs/catalog/blocks/carousel-orbit-3.mdx
index 57d67e898d..4b51f647bd 100644
--- a/docs/catalog/blocks/carousel-orbit-3.mdx
+++ b/docs/catalog/blocks/carousel-orbit-3.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Orbit Carousel 3
+
Image cards on a spinning 3D Fibonacci sphere, billboarded to the camera, sized by camera distance (Orbit style 3); 24 image slots.
+
+
-
+
+
+
## Add it to your video
@@ -1137,6 +1143,4 @@ Created by Jake Moran.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/carousel-orbit-4.mdx b/docs/catalog/blocks/carousel-orbit-4.mdx
index 0272c757d9..0f22bb1d5a 100644
--- a/docs/catalog/blocks/carousel-orbit-4.mdx
+++ b/docs/catalog/blocks/carousel-orbit-4.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Orbit Carousel 4
+
Image cards on a spinning 3D Fibonacci sphere, billboarded to the camera, sized by camera distance (Orbit style 4); 24 image slots.
+
+
-
+
+
+
## Add it to your video
@@ -1153,6 +1159,4 @@ Created by Jake Moran.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/carousel-orbit-5.mdx b/docs/catalog/blocks/carousel-orbit-5.mdx
index ec2caf2a97..92ae72a6c2 100644
--- a/docs/catalog/blocks/carousel-orbit-5.mdx
+++ b/docs/catalog/blocks/carousel-orbit-5.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Orbit Carousel 5
+
Image cards on a spinning 3D Fibonacci sphere, billboarded to the camera, sized by camera distance (Orbit style 5); 24 image slots.
+
+
-
+
+
+
## Add it to your video
@@ -1137,6 +1143,4 @@ Created by Jake Moran.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/carousel-path-1.mdx b/docs/catalog/blocks/carousel-path-1.mdx
index a290e45323..0ffdac8c67 100644
--- a/docs/catalog/blocks/carousel-path-1.mdx
+++ b/docs/catalog/blocks/carousel-path-1.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Path Carousel 1
+
Image cards ride an open bezier path (arc, V, diagonal, wave, S-curve) with depth scaling and tangent rotation (Path style 1); 24 image slots.
+
+
-
+
+
+
## Add it to your video
@@ -1159,6 +1165,4 @@ Created by Jake Moran.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/carousel-path-2.mdx b/docs/catalog/blocks/carousel-path-2.mdx
index 03f7e03ddf..d379c00d74 100644
--- a/docs/catalog/blocks/carousel-path-2.mdx
+++ b/docs/catalog/blocks/carousel-path-2.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Path Carousel 2
+
Image cards ride an open bezier path (arc, V, diagonal, wave, S-curve) with depth scaling and tangent rotation (Path style 2); 12 image slots.
+
+
-
+
+
+
## Add it to your video
@@ -1104,6 +1110,4 @@ Created by Jake Moran.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/carousel-path-3.mdx b/docs/catalog/blocks/carousel-path-3.mdx
index ac740c7045..3bf195fc77 100644
--- a/docs/catalog/blocks/carousel-path-3.mdx
+++ b/docs/catalog/blocks/carousel-path-3.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Path Carousel 3
+
Image cards ride an open bezier path (arc, V, diagonal, wave, S-curve) with depth scaling and tangent rotation (Path style 3); 12 image slots.
+
+
-
+
+
+
## Add it to your video
@@ -1118,6 +1124,4 @@ Created by Jake Moran.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/carousel-path-4.mdx b/docs/catalog/blocks/carousel-path-4.mdx
index 3a7cdddab7..06520f9f59 100644
--- a/docs/catalog/blocks/carousel-path-4.mdx
+++ b/docs/catalog/blocks/carousel-path-4.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Path Carousel 4
+
Image cards ride an open bezier path (arc, V, diagonal, wave, S-curve) with depth scaling and tangent rotation (Path style 4); 24 image slots.
+
+
-
+
+
+
## Add it to your video
@@ -1159,6 +1165,4 @@ Created by Jake Moran.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/carousel-path-5.mdx b/docs/catalog/blocks/carousel-path-5.mdx
index a6a6495ba9..b8c79b0de2 100644
--- a/docs/catalog/blocks/carousel-path-5.mdx
+++ b/docs/catalog/blocks/carousel-path-5.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Path Carousel 5
+
Image cards ride an open bezier path (arc, V, diagonal, wave, S-curve) with depth scaling and tangent rotation (Path style 5); 24 image slots.
+
+
-
+
+
+
## Add it to your video
@@ -1158,6 +1164,4 @@ Created by Jake Moran.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/carousel-text-circle-1.mdx b/docs/catalog/blocks/carousel-text-circle-1.mdx
index 86d6991cf8..c4cc010945 100644
--- a/docs/catalog/blocks/carousel-text-circle-1.mdx
+++ b/docs/catalog/blocks/carousel-text-circle-1.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Text + Circle Carousel 1
+
A headline mask-reveals word by word while a circle carousel converges from off-frame and threads the line, collapses to centre, hard-cuts to a second line that arrives at 1.4× (Circle style 1).
+
+
-
+
+
+
## Add it to your video
@@ -1146,6 +1152,4 @@ Created by Jake Moran.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/carousel-text-circle-2.mdx b/docs/catalog/blocks/carousel-text-circle-2.mdx
index 5cdaed98da..fdc8b1044a 100644
--- a/docs/catalog/blocks/carousel-text-circle-2.mdx
+++ b/docs/catalog/blocks/carousel-text-circle-2.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Text + Circle Carousel 2
+
A headline mask-reveals word by word while a circle carousel converges from off-frame and threads the line, collapses to centre, hard-cuts to a second line that arrives at 1.4× (Circle style 2).
+
+
-
+
+
+
## Add it to your video
@@ -1146,6 +1152,4 @@ Created by Jake Moran.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/carousel-text-circle-3.mdx b/docs/catalog/blocks/carousel-text-circle-3.mdx
index c8ef56a65a..e4f2b92694 100644
--- a/docs/catalog/blocks/carousel-text-circle-3.mdx
+++ b/docs/catalog/blocks/carousel-text-circle-3.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Text + Circle Carousel 3
+
A headline mask-reveals word by word while a circle carousel converges from off-frame and threads the line, collapses to centre, hard-cuts to a second line that arrives at 1.4× (Circle style 3).
+
+
-
+
+
+
## Add it to your video
@@ -1146,6 +1152,4 @@ Created by Jake Moran.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/carousel-text-circle-4.mdx b/docs/catalog/blocks/carousel-text-circle-4.mdx
index 79e48232a4..0ac75d90cb 100644
--- a/docs/catalog/blocks/carousel-text-circle-4.mdx
+++ b/docs/catalog/blocks/carousel-text-circle-4.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Text + Circle Carousel 4
+
A headline mask-reveals word by word while a circle carousel converges from off-frame and threads the line, collapses to centre, hard-cuts to a second line that arrives at 1.4× (Circle style 4).
+
+
-
+
+
+
## Add it to your video
@@ -1146,6 +1152,4 @@ Created by Jake Moran.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/carousel-text-circle-5.mdx b/docs/catalog/blocks/carousel-text-circle-5.mdx
index 57137a3c76..20be4b1e29 100644
--- a/docs/catalog/blocks/carousel-text-circle-5.mdx
+++ b/docs/catalog/blocks/carousel-text-circle-5.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Text + Circle Carousel 5
+
A headline mask-reveals word by word while a circle carousel converges from off-frame and threads the line, collapses to centre, hard-cuts to a second line that arrives at 1.4× (Circle style 5).
+
+
-
+
+
+
## Add it to your video
@@ -1146,6 +1152,4 @@ Created by Jake Moran.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/carousel-vision-1.mdx b/docs/catalog/blocks/carousel-vision-1.mdx
index 2728969554..3501aa3e90 100644
--- a/docs/catalog/blocks/carousel-vision-1.mdx
+++ b/docs/catalog/blocks/carousel-vision-1.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Vision Carousel 1
+
A ring of large image cards tilted into a row under a 3D camera, each card turning toward the centre (Vision style 1); 12 image slots.
+
+
-
+
+
+
## Add it to your video
@@ -1107,6 +1113,4 @@ Created by Jake Moran.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/carousel-vision-2.mdx b/docs/catalog/blocks/carousel-vision-2.mdx
index 1711c76a18..83a6cb56a9 100644
--- a/docs/catalog/blocks/carousel-vision-2.mdx
+++ b/docs/catalog/blocks/carousel-vision-2.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Vision Carousel 2
+
A ring of large image cards tilted into a row under a 3D camera, each card turning toward the centre (Vision style 2); 12 image slots.
+
+
-
+
+
+
## Add it to your video
@@ -1107,6 +1113,4 @@ Created by Jake Moran.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/carousel-vision-3.mdx b/docs/catalog/blocks/carousel-vision-3.mdx
index 688ccc2156..71ff46120d 100644
--- a/docs/catalog/blocks/carousel-vision-3.mdx
+++ b/docs/catalog/blocks/carousel-vision-3.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Vision Carousel 3
+
A ring of large image cards tilted into a row under a 3D camera, each card turning toward the centre (Vision style 3); 12 image slots.
+
+
-
+
+
+
## Add it to your video
@@ -1107,6 +1113,4 @@ Created by Jake Moran.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/carousel-vision-4.mdx b/docs/catalog/blocks/carousel-vision-4.mdx
index 8b434d0645..3bc354bdda 100644
--- a/docs/catalog/blocks/carousel-vision-4.mdx
+++ b/docs/catalog/blocks/carousel-vision-4.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Vision Carousel 4
+
A ring of large image cards tilted into a row under a 3D camera, each card turning toward the centre (Vision style 4); 12 image slots.
+
+
-
+
+
+
## Add it to your video
@@ -1114,6 +1120,4 @@ Created by Jake Moran.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/carousel-vision-5.mdx b/docs/catalog/blocks/carousel-vision-5.mdx
index 0332386e34..90f605fd79 100644
--- a/docs/catalog/blocks/carousel-vision-5.mdx
+++ b/docs/catalog/blocks/carousel-vision-5.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Vision Carousel 5
+
A ring of large image cards tilted into a row under a 3D camera, each card turning toward the centre (Vision style 5); 12 image slots.
+
+
-
+
+
+
## Add it to your video
@@ -1107,6 +1113,4 @@ Created by Jake Moran.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/chatgpt-exchange.mdx b/docs/catalog/blocks/chatgpt-exchange.mdx
index 5b3c6e1103..bc89a8f0e7 100644
--- a/docs/catalog/blocks/chatgpt-exchange.mdx
+++ b/docs/catalog/blocks/chatgpt-exchange.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
ChatGPT Exchange
+
A portrait ChatGPT-style exchange types and sends a prompt, streams an answer, assembles a comparison table, and scrolls back through the result
+
+
-
+
+
+
## Add it to your video
@@ -1512,6 +1518,4 @@ Created by Jake Moran.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/chromatic-radial-split.mdx b/docs/catalog/blocks/chromatic-radial-split.mdx
index 1aaa6003a3..e8b26a57f5 100644
--- a/docs/catalog/blocks/chromatic-radial-split.mdx
+++ b/docs/catalog/blocks/chromatic-radial-split.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Chromatic Radial Split
+
Shader transition with chromatic aberration radial split
+
+
-
+
+
+
## Add it to your video
@@ -432,6 +438,4 @@ Tagged `transition` `shader`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/chrome-orb.mdx b/docs/catalog/blocks/chrome-orb.mdx
index b0a3f8d850..92c9923bd8 100644
--- a/docs/catalog/blocks/chrome-orb.mdx
+++ b/docs/catalog/blocks/chrome-orb.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Chrome Orb
+
A mirror-chrome orb reflects a bright studio light, on black. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `object` `chrome` `metal` `material`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/cinemagraph.mdx b/docs/catalog/blocks/cinemagraph.mdx
index 1235ae25e9..8e7e218db0 100644
--- a/docs/catalog/blocks/cinemagraph.mdx
+++ b/docs/catalog/blocks/cinemagraph.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Cinemagraph
+
A still photograph with one living region: the frame is frozen while a single feathered window keeps moving - here, steam rising over a cup - drawn from the seek time alone with a period that divides the duration, so the render loops seamlessly. Swap the placeholder scene for a freeze-frame still masked over a looping video to cinemagraph real footage.
+
+
-
+
+
+
## Add it to your video
@@ -364,6 +370,4 @@ Tagged `effect` `cinemagraph` `photo` `loop` `freeze-frame`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/cinematic-zoom.mdx b/docs/catalog/blocks/cinematic-zoom.mdx
index cf2632487b..a0c821fc0f 100644
--- a/docs/catalog/blocks/cinematic-zoom.mdx
+++ b/docs/catalog/blocks/cinematic-zoom.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Cinematic Zoom
+
Shader transition with dramatic zoom blur
+
+
-
+
+
+
## Add it to your video
@@ -432,6 +438,4 @@ Tagged `transition` `shader`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/claude-exchange.mdx b/docs/catalog/blocks/claude-exchange.mdx
index 9aab648e01..9ad875a208 100644
--- a/docs/catalog/blocks/claude-exchange.mdx
+++ b/docs/catalog/blocks/claude-exchange.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Claude Exchange
+
A portrait Claude-style exchange types a prompt, works through search and reasoning steps, then streams a detailed answer with citations and actions
+
+
-
+
+
+
## Add it to your video
@@ -1711,6 +1717,4 @@ Created by Jake Moran.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/code-3d-extrude.mdx b/docs/catalog/blocks/code-3d-extrude.mdx
index a646b64fa8..d424843e5a 100644
--- a/docs/catalog/blocks/code-3d-extrude.mdx
+++ b/docs/catalog/blocks/code-3d-extrude.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Code 3D Extrude
+
Syntax-highlighted code on a lit, beveled 3D slab that rotates through real space and settles to a readable rest — true WebGL depth and lighting, not a 2D transform.
+
+
-
+
+
+
## Add it to your video
@@ -682,6 +688,4 @@ Tagged `code` `code-animation` `3d` `webgl` `developer`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/code-diff.mdx b/docs/catalog/blocks/code-diff.mdx
index 4c48ced036..ea8eb7baad 100644
--- a/docs/catalog/blocks/code-diff.mdx
+++ b/docs/catalog/blocks/code-diff.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Code Diff
+
An edit shown as a colored diff — removed lines collapse in red, added lines expand in green.
+
+
-
+
+
+
## Add it to your video
@@ -882,6 +888,4 @@ Tagged `code` `code-animation` `diff` `developer`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/code-highlight.mdx b/docs/catalog/blocks/code-highlight.mdx
index 7a9cffde1a..661c10831b 100644
--- a/docs/catalog/blocks/code-highlight.mdx
+++ b/docs/catalog/blocks/code-highlight.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Code Highlight Sweep
+
A highlight band sweeps across a target line while the surrounding context dims — draws the eye to one line.
+
+
-
+
+
+
## Add it to your video
@@ -811,6 +817,4 @@ Tagged `code` `code-animation` `highlight` `developer`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/code-morph.mdx b/docs/catalog/blocks/code-morph.mdx
index a187d7ff04..0eeaf31dd6 100644
--- a/docs/catalog/blocks/code-morph.mdx
+++ b/docs/catalog/blocks/code-morph.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Code Morph
+
One snippet transforms into another — tokens glide between positions, leavers fade out, enterers fade in. Shiki Magic Move re-driven as a paused GSAP timeline.
+
+
-
+
+
+
## Add it to your video
@@ -1282,6 +1288,4 @@ Tagged `code` `code-animation` `morph` `refactor` `developer`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/code-particle-assemble.mdx b/docs/catalog/blocks/code-particle-assemble.mdx
index bf1d5edee5..480e61548e 100644
--- a/docs/catalog/blocks/code-particle-assemble.mdx
+++ b/docs/catalog/blocks/code-particle-assemble.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Code Particle Assemble
+
Thousands of GPU points scatter through space and fly to the exact glyph pixels of the code, resolving into readable syntax-highlighted text — a particle system, not a token tween.
+
+
-
+
+
+
## Add it to your video
@@ -548,6 +554,4 @@ Tagged `code` `code-animation` `particles` `gpu` `webgl` `developer`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/code-scroll.mdx b/docs/catalog/blocks/code-scroll.mdx
index 957d60159d..5d3ece58c4 100644
--- a/docs/catalog/blocks/code-scroll.mdx
+++ b/docs/catalog/blocks/code-scroll.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Code Scroll To Line
+
The camera scrolls a long file to bring a target line to center and spotlights it — for walking through real modules.
+
+
-
+
+
+
## Add it to your video
@@ -1626,6 +1632,4 @@ Tagged `code` `code-animation` `scroll` `developer`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/code-shader-dissolve.mdx b/docs/catalog/blocks/code-shader-dissolve.mdx
index 1e66d944f4..2bdc8fbc93 100644
--- a/docs/catalog/blocks/code-shader-dissolve.mdx
+++ b/docs/catalog/blocks/code-shader-dissolve.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Code Shader Dissolve
+
The code compiles into existence: a GPU fragment shader resolves it out of seeded noise with a chromatic dissolve front and edge glow, then holds crisp.
+
+
-
+
+
+
## Add it to your video
@@ -604,6 +610,4 @@ Tagged `code` `code-animation` `shader` `webgl` `developer`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/code-slice-hero.mdx b/docs/catalog/blocks/code-slice-hero.mdx
index ab40012892..92248d4824 100644
--- a/docs/catalog/blocks/code-slice-hero.mdx
+++ b/docs/catalog/blocks/code-slice-hero.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Code Slice Hero
+
A tiled headline surface flips cell by cell under a sweeping depth field to reveal the rear headline.
+
+
-
+
+
+
## Add it to your video
@@ -596,6 +602,4 @@ Tagged `3d-motion` `transition` `typography` `tiles` `flip` `webgl2` `shadows` `
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/code-snippet-apple-terminal-pro.mdx b/docs/catalog/blocks/code-snippet-apple-terminal-pro.mdx
index 1137d6d8a6..4a0f933030 100644
--- a/docs/catalog/blocks/code-snippet-apple-terminal-pro.mdx
+++ b/docs/catalog/blocks/code-snippet-apple-terminal-pro.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Code Snippet - Apple Terminal Pro
+
Apple Terminal Pro profile: black background with grey text and lime green cursor, per-character typing animation of a shell session.
+
+
-
+
+
+
## Add it to your video
@@ -313,6 +319,4 @@ Tagged `code` `developer` `showcase` `terminal` `apple` `apple-terminal`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/code-snippet-dark-2026.mdx b/docs/catalog/blocks/code-snippet-dark-2026.mdx
index 7a693eca8f..218b36ace9 100644
--- a/docs/catalog/blocks/code-snippet-dark-2026.mdx
+++ b/docs/catalog/blocks/code-snippet-dark-2026.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Code Snippet - Dark 2026
+
VS Code workbench with per-character typing animation in the Dark 2026 theme. Full editor chrome with activity bar, sidebar, tabs, terminal, and status bar.
+
+
-
+
+
+
## Add it to your video
@@ -1157,6 +1163,4 @@ Tagged `code` `developer` `showcase` `vscode`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/code-snippet-dark-modern.mdx b/docs/catalog/blocks/code-snippet-dark-modern.mdx
index f8a2c1aa2d..088aef0a50 100644
--- a/docs/catalog/blocks/code-snippet-dark-modern.mdx
+++ b/docs/catalog/blocks/code-snippet-dark-modern.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Code Snippet - Dark Modern
+
VS Code workbench with per-character typing animation in the Dark Modern theme. Full editor chrome with activity bar, sidebar, tabs, terminal, and status bar.
+
+
-
+
+
+
## Add it to your video
@@ -1153,6 +1159,4 @@ Tagged `code` `developer` `showcase` `vscode`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/code-typing.mdx b/docs/catalog/blocks/code-typing.mdx
index d77cb7854a..10e8253489 100644
--- a/docs/catalog/blocks/code-typing.mdx
+++ b/docs/catalog/blocks/code-typing.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Code Typing
+
Token-streamed typing reveal with a caret that tracks the frontier — deterministic, no CSS animation.
+
+
-
+
+
+
## Add it to your video
@@ -829,6 +835,4 @@ Tagged `code` `code-animation` `typing` `developer`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/color-wheel.mdx b/docs/catalog/blocks/color-wheel.mdx
index 497aef72d0..8179222f29 100644
--- a/docs/catalog/blocks/color-wheel.mdx
+++ b/docs/catalog/blocks/color-wheel.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Color Wheel
+
A wide gradient slides slowly through the colours of the rainbow. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `background` `gradient` `rainbow` `color`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/cosmic-orb.mdx b/docs/catalog/blocks/cosmic-orb.mdx
index 4a88c63bdb..1a9198e305 100644
--- a/docs/catalog/blocks/cosmic-orb.mdx
+++ b/docs/catalog/blocks/cosmic-orb.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Cosmic Orb
+
An iridescent soap-bubble planet: a slowly spinning sphere of nebula bands, dust lanes and twinkling stars wrapped in a refracting glass limb with chromatic aberration at the edge.
+
+
-
+
+
+
## Add it to your video
@@ -539,6 +545,4 @@ Tagged `webgl` `shader` `background` `showcase` `3d`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/cross-warp-morph.mdx b/docs/catalog/blocks/cross-warp-morph.mdx
index 824e4790a3..420657c0b2 100644
--- a/docs/catalog/blocks/cross-warp-morph.mdx
+++ b/docs/catalog/blocks/cross-warp-morph.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Cross Warp Morph
+
Shader transition with cross-warped morphing
+
+
-
+
+
+
## Add it to your video
@@ -443,6 +449,4 @@ Tagged `transition` `shader`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/cuboid-carousel.mdx b/docs/catalog/blocks/cuboid-carousel.mdx
index 25004ad476..79dd8661b0 100644
--- a/docs/catalog/blocks/cuboid-carousel.mdx
+++ b/docs/catalog/blocks/cuboid-carousel.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Cuboid Carousel
+
A chain of bevelled cuboids rides a travelling wave as a content carousel.
+
+
-
+
+
+
## Add it to your video
@@ -942,6 +948,4 @@ Tagged `3d-motion` `carousel` `cards` `travelling-wave` `pbr` `shadows` `room-en
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/data-chart.mdx b/docs/catalog/blocks/data-chart.mdx
index afdb89fa02..ec5d0b2ac2 100644
--- a/docs/catalog/blocks/data-chart.mdx
+++ b/docs/catalog/blocks/data-chart.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Data Chart
+
Animated bar + line chart with staggered reveal, NYT-style typography, and value labels
+
+
-
+
+
+
## Add it to your video
@@ -530,6 +536,4 @@ Tagged `data` `chart` `statistics`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/domain-warp-dissolve.mdx b/docs/catalog/blocks/domain-warp-dissolve.mdx
index ddb96b955b..4803139c20 100644
--- a/docs/catalog/blocks/domain-warp-dissolve.mdx
+++ b/docs/catalog/blocks/domain-warp-dissolve.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Domain Warp Dissolve
+
Shader transition with fractal noise domain warping
+
+
-
+
+
+
## Add it to your video
@@ -446,6 +452,4 @@ Tagged `transition` `shader`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/editorial-flash-overlay.mdx b/docs/catalog/blocks/editorial-flash-overlay.mdx
index 569eb6f293..1c00c4af05 100644
--- a/docs/catalog/blocks/editorial-flash-overlay.mdx
+++ b/docs/catalog/blocks/editorial-flash-overlay.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Editorial Flash Overlay
+
Finite neutral-warm light layers for a seek-safe camera-flash cut or social reveal
+
+
-
+
+
+
## Add it to your video
@@ -195,6 +201,4 @@ Tagged `flash` `editorial` `social` `light` `transition` `overlay` `media-treatm
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/exploded-stack.mdx b/docs/catalog/blocks/exploded-stack.mdx
index 0f3b50418f..cc963a9b6c 100644
--- a/docs/catalog/blocks/exploded-stack.mdx
+++ b/docs/catalog/blocks/exploded-stack.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Exploded Stack
+
Isometric layer plates explode apart with a label beside each layer, hold, then collapse back into one stack. Built for architecture and system diagrams.
+
+
-
+
+
+
## Add it to your video
@@ -475,6 +481,4 @@ Tagged `3d-object` `three-js` `webgl` `isometric` `exploded-view` `layers` `diag
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/extruded-logo.mdx b/docs/catalog/blocks/extruded-logo.mdx
index 9fa760c7c1..d13d3ef0b0 100644
--- a/docs/catalog/blocks/extruded-logo.mdx
+++ b/docs/catalog/blocks/extruded-logo.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Extruded Logo
+
Beveled 3D letters flip up one by one, the word swings so light runs across the bevels, then settles for a readable hold. Chrome, gold or matte.
+
+
-
+
+
+
## Add it to your video
@@ -397,6 +403,4 @@ Tagged `3d-object` `three-js` `webgl` `logo` `text` `extruded` `title-card`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/falling-lines.mdx b/docs/catalog/blocks/falling-lines.mdx
index b278c92874..ef54edaa99 100644
--- a/docs/catalog/blocks/falling-lines.mdx
+++ b/docs/catalog/blocks/falling-lines.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Falling Lines
+
White lines fall down the frame at varied speeds, each fading into a trail. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `background` `texture` `lines` `rain` `monochrom
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/flash-through-white.mdx b/docs/catalog/blocks/flash-through-white.mdx
index a9ab5ba181..ee2b606799 100644
--- a/docs/catalog/blocks/flash-through-white.mdx
+++ b/docs/catalog/blocks/flash-through-white.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Flash Through White
+
Shader transition with white flash crossfade
+
+
-
+
+
+
## Add it to your video
@@ -432,6 +438,4 @@ Tagged `transition` `shader`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/flowchart-vertical.mdx b/docs/catalog/blocks/flowchart-vertical.mdx
index a995393acc..c911bc7eb7 100644
--- a/docs/catalog/blocks/flowchart-vertical.mdx
+++ b/docs/catalog/blocks/flowchart-vertical.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Flowchart Vertical
+
Portrait animated decision tree with SVG connectors, sticky-note nodes, cursor interaction, and typing correction
+
+
-
+
+
+
## Add it to your video
@@ -525,6 +531,4 @@ Tagged `diagram` `flowchart` `interactive` `portrait`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/flowchart.mdx b/docs/catalog/blocks/flowchart.mdx
index 764c6629c8..030a50f190 100644
--- a/docs/catalog/blocks/flowchart.mdx
+++ b/docs/catalog/blocks/flowchart.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Flowchart
+
Animated decision tree with SVG connectors, sticky-note nodes, cursor interaction, and typing correction
+
+
-
+
+
+
## Add it to your video
@@ -525,6 +531,4 @@ Tagged `diagram` `flowchart` `interactive`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/flowing-gradient.mdx b/docs/catalog/blocks/flowing-gradient.mdx
index d8ec3c2633..8f85d60c20 100644
--- a/docs/catalog/blocks/flowing-gradient.mdx
+++ b/docs/catalog/blocks/flowing-gradient.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Flowing Gradient
+
Bands of orange and violet flow across the frame in a smooth gradient. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `background` `gradient` `color` `flow`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/fractal-noise.mdx b/docs/catalog/blocks/fractal-noise.mdx
index c6e05adf49..841feddfec 100644
--- a/docs/catalog/blocks/fractal-noise.mdx
+++ b/docs/catalog/blocks/fractal-noise.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Fractal Noise
+
Soft grey fractal noise drifts across the frame like slow clouds. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `background` `noise` `texture` `clouds`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/freeze-frame-dressing.mdx b/docs/catalog/blocks/freeze-frame-dressing.mdx
index 75c9c85fd2..a597660c2c 100644
--- a/docs/catalog/blocks/freeze-frame-dressing.mdx
+++ b/docs/catalog/blocks/freeze-frame-dressing.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Freeze-Frame Dressing
+
Timeline-driven paper, tape, and flash dressing for a freeze-frame or background-removed subject
+
+
-
+
+
+
## Add it to your video
@@ -186,6 +192,4 @@ Tagged `freeze-frame` `cutout` `scrapbook` `paper` `social` `overlay` `media-tre
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/frost-sequence-camera-orbit.mdx b/docs/catalog/blocks/frost-sequence-camera-orbit.mdx
index ae4fe58871..8ba6222148 100644
--- a/docs/catalog/blocks/frost-sequence-camera-orbit.mdx
+++ b/docs/catalog/blocks/frost-sequence-camera-orbit.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Frost Sequence Camera Orbit
+
An orbiting camera follows an ice logo as it breaks apart, reforms into two text moments, and fades.
+
+
-
+
+
+
## Add it to your video
@@ -3390,6 +3396,4 @@ Tagged `3d-motion` `ice` `frost` `camera-orbit` `logo` `particles` `webgpu` `two
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/frost.mdx b/docs/catalog/blocks/frost.mdx
index c5c9abaa5b..1e317b4ea3 100644
--- a/docs/catalog/blocks/frost.mdx
+++ b/docs/catalog/blocks/frost.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Frost
+
A frozen blue orb with frost creeping in from its edge, on black. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `orb` `ice` `frost` `material`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/gabor-noise.mdx b/docs/catalog/blocks/gabor-noise.mdx
index c7ec56ef99..e56e8b6219 100644
--- a/docs/catalog/blocks/gabor-noise.mdx
+++ b/docs/catalog/blocks/gabor-noise.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Gabor Noise
+
Grey streaky noise drifts across the frame like a moving fingerprint. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `background` `texture` `noise` `monochrome`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/gallery-tunnel.mdx b/docs/catalog/blocks/gallery-tunnel.mdx
index c1194581d7..9247011cc8 100644
--- a/docs/catalog/blocks/gallery-tunnel.mdx
+++ b/docs/catalog/blocks/gallery-tunnel.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Gallery Tunnel
+
An infinite corridor of panels: a square tunnel receding to a vanishing point, its floor, ceiling and walls tiled with saturated colour slabs and caller-supplied images that swell toward camera and exit past you, the far end dissolving into fog.
+
+
-
+
+
+
## Add it to your video
@@ -564,6 +570,4 @@ Tagged `webgl` `3d` `background` `showcase` `depth` `loop`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/glass-hero.mdx b/docs/catalog/blocks/glass-hero.mdx
index e3830efc57..d9fedb2bfb 100644
--- a/docs/catalog/blocks/glass-hero.mdx
+++ b/docs/catalog/blocks/glass-hero.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Glass Hero
+
A solid glass object rises in front of a giant headline and keeps turning, so the type bends and splits into colour through it.
+
+
-
+
+
+
## Add it to your video
@@ -347,6 +353,4 @@ Tagged `3d-object` `three-js` `webgl` `glass` `refraction` `hero` `title-card`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/glass-shard-title.mdx b/docs/catalog/blocks/glass-shard-title.mdx
index 0a5c66513f..763a356e94 100644
--- a/docs/catalog/blocks/glass-shard-title.mdx
+++ b/docs/catalog/blocks/glass-shard-title.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Glass Shard Title
+
Glass shards fly in through fog and tile themselves into the headline.
+
+
-
+
+
+
## Add it to your video
@@ -422,6 +428,4 @@ Tagged `3d-motion` `title-card` `glass` `voronoi` `shards` `fog` `hdr`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/glitch.mdx b/docs/catalog/blocks/glitch.mdx
index dfb19e795f..6e60f96402 100644
--- a/docs/catalog/blocks/glitch.mdx
+++ b/docs/catalog/blocks/glitch.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Glitch
+
Shader transition with digital glitch artifacts
+
+
-
+
+
+
## Add it to your video
@@ -432,6 +438,4 @@ Tagged `transition` `shader`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/godrays.mdx b/docs/catalog/blocks/godrays.mdx
index 76077e143f..9a3350970b 100644
--- a/docs/catalog/blocks/godrays.mdx
+++ b/docs/catalog/blocks/godrays.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Godrays
+
Rays of light fan out from a corner and drift across a deep blue field. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `background` `light` `rays`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/goo.mdx b/docs/catalog/blocks/goo.mdx
index fc6feafcfa..efd9d484dd 100644
--- a/docs/catalog/blocks/goo.mdx
+++ b/docs/catalog/blocks/goo.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Goo
+
A glossy green liquid ball whose surface bulges and ripples like wet goo, centred on black. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `liquid` `3d` `organic` `orb`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/gooey-split.mdx b/docs/catalog/blocks/gooey-split.mdx
index 118a533ef0..9016ac0c92 100644
--- a/docs/catalog/blocks/gooey-split.mdx
+++ b/docs/catalog/blocks/gooey-split.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Gooey Split
+
A dot splits into a three-dot menu with a gooey metaball neck, spins into a swirl mark under directional shutter motion blur, then breaks back into three dots and merges into one. The goo is an SVG blur-and-threshold filter on the dots; the blur integrates each part along its real trajectory, so the smear follows the direction and speed of the spin.
+
+
-
+
+
+
## Add it to your video
@@ -1019,6 +1025,4 @@ Tagged `effect` `gooey` `metaball` `motion-blur` `morph` `logo` `icon`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/gravitational-lens.mdx b/docs/catalog/blocks/gravitational-lens.mdx
index 3cc6c8bf82..cce120882a 100644
--- a/docs/catalog/blocks/gravitational-lens.mdx
+++ b/docs/catalog/blocks/gravitational-lens.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Gravitational Lens
+
Shader transition with gravitational lensing distortion
+
+
-
+
+
+
## Add it to your video
@@ -431,6 +437,4 @@ Tagged `transition` `shader`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/halftone-field.mdx b/docs/catalog/blocks/halftone-field.mdx
index 5892456654..f18880a273 100644
--- a/docs/catalog/blocks/halftone-field.mdx
+++ b/docs/catalog/blocks/halftone-field.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Halftone Field
+
A full-bleed halftone light field: a grid of dots whose size and colour track a slow flowing simplex-noise field, so broad bands of light sweep across a mostly-black frame like a giant LED wall showing a plasma. Built to run under type.
+
+
-
+
+
+
## Add it to your video
@@ -490,6 +496,4 @@ Tagged `webgl` `shader` `background` `texture` `halftone`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/heatmap.mdx b/docs/catalog/blocks/heatmap.mdx
index 7657a3ad1b..b49949e52e 100644
--- a/docs/catalog/blocks/heatmap.mdx
+++ b/docs/catalog/blocks/heatmap.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Heatmap
+
Thermal colours flow through a glowing orb, on black. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `object` `heat` `thermal` `glow`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/heygen-avatar-promo-card.mdx b/docs/catalog/blocks/heygen-avatar-promo-card.mdx
index f3e5b53977..8fa53d0320 100644
--- a/docs/catalog/blocks/heygen-avatar-promo-card.mdx
+++ b/docs/catalog/blocks/heygen-avatar-promo-card.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
HeyGen Avatar Promo Card
+
A portrait HeyGen offer card pairs a moving avatar mosaic with bold promotional typography and a branded callout
+
+
-
+
+
+
## Add it to your video
@@ -494,6 +500,4 @@ Created by HeyGen.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/hologram.mdx b/docs/catalog/blocks/hologram.mdx
index b3b264e2de..e86eb770f6 100644
--- a/docs/catalog/blocks/hologram.mdx
+++ b/docs/catalog/blocks/hologram.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Hologram
+
A pale blue holographic orb with scan rings and flicker, on black. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `object` `hologram` `sci-fi` `blue`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/holographic.mdx b/docs/catalog/blocks/holographic.mdx
index 80c61bcb19..12be105a82 100644
--- a/docs/catalog/blocks/holographic.mdx
+++ b/docs/catalog/blocks/holographic.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Holographic
+
An iridescent foil orb with a shifting rainbow sheen, centred on black. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `holographic` `iridescent` `rainbow` `orb`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/hw-frame.mdx b/docs/catalog/blocks/hw-frame.mdx
index 65b70940d4..2ab4e72211 100644
--- a/docs/catalog/blocks/hw-frame.mdx
+++ b/docs/catalog/blocks/hw-frame.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Sketched Frame
+
Media in a hand-drawn border with corner doodles and a handwritten caption; the unit tilts slightly and boils (images inside the block; keep live footage in the host)
+
+
-
+
+
+
## Add it to your video
@@ -368,6 +374,4 @@ Tagged `handwritten` `frame` `media`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/hw-path-text.mdx b/docs/catalog/blocks/hw-path-text.mdx
index 50aa8d40dd..9910451a1b 100644
--- a/docs/catalog/blocks/hw-path-text.mdx
+++ b/docs/catalog/blocks/hw-path-text.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Text Along a Path
+
Handwriting flowing along any SVG path with a per-character reveal; the path is the only geometry input
+
+
-
+
+
+
## Add it to your video
@@ -260,6 +266,4 @@ Tagged `handwritten` `typography` `path` `overlay`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/hw-pipeline.mdx b/docs/catalog/blocks/hw-pipeline.mdx
index d5c86da13f..1e5d216f7e 100644
--- a/docs/catalog/blocks/hw-pipeline.mdx
+++ b/docs/catalog/blocks/hw-pipeline.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Hand-Drawn Flowchart
+
Wobbled boxes with handwritten labels joined by curved connectors, drawing on in sequence from a node list
+
+
-
+
+
+
## Add it to your video
@@ -383,6 +389,4 @@ Tagged `handwritten` `diagram` `data-viz` `overlay`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/hw-scribble-transition.mdx b/docs/catalog/blocks/hw-scribble-transition.mdx
index 6c1659d4ed..539bee1f08 100644
--- a/docs/catalog/blocks/hw-scribble-transition.mdx
+++ b/docs/catalog/blocks/hw-scribble-transition.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Scribble Transition
+
Overlay transition: scribble bands accumulate to cover the frame with a solid backstop, the host cuts beneath, and the scribble clears
+
+
-
+
+
+
## Add it to your video
@@ -218,6 +224,4 @@ Tagged `handwritten` `transition` `wipe`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/hw-text-cloud.mdx b/docs/catalog/blocks/hw-text-cloud.mdx
index 36b51d3e78..3e993b4fb5 100644
--- a/docs/catalog/blocks/hw-text-cloud.mdx
+++ b/docs/catalog/blocks/hw-text-cloud.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Speech Bubble
+
Hand-drawn speech bubble with a positionable tail: outline draws on, paper fill fades in, handwritten text types per character; boils
+
+
-
+
+
+
## Add it to your video
@@ -352,6 +358,4 @@ Tagged `handwritten` `speech-bubble` `overlay`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/hw-title.mdx b/docs/catalog/blocks/hw-title.mdx
index 0bd29528ab..890619f0ad 100644
--- a/docs/catalog/blocks/hw-title.mdx
+++ b/docs/catalog/blocks/hw-title.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Handwritten Title
+
Handwritten display text with a scalar-driven word-by-word highlight sweep and a seeded squiggle underline sized to the text; boils
+
+
-
+
+
+
## Add it to your video
@@ -323,6 +329,4 @@ Tagged `handwritten` `typography` `title-card` `overlay`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/hw-write-title.mdx b/docs/catalog/blocks/hw-write-title.mdx
index 84a62429c5..8414caa9cb 100644
--- a/docs/catalog/blocks/hw-write-title.mdx
+++ b/docs/catalog/blocks/hw-write-title.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Handwritten Write-On Title
+
True glyph write-on: filled Caveat letterforms revealed by baked per-glyph centerline strokes traced in real stroke order with a curvature-adaptive pen-velocity ease (fast on straights, slow into curves, inter-stroke pen lifts); optional squiggle underline; boils
+
+
-
+
+
+
## Add it to your video
@@ -566,6 +572,4 @@ Tagged `handwritten` `typography` `title-card` `write-on` `overlay`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/instagram-follow.mdx b/docs/catalog/blocks/instagram-follow.mdx
index 555aef1a5d..1f73e20a81 100644
--- a/docs/catalog/blocks/instagram-follow.mdx
+++ b/docs/catalog/blocks/instagram-follow.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Instagram Follow
+
Animated Instagram follow overlay with profile card and follow button
+
+
-
+
+
+
## Add it to your video
@@ -354,6 +360,4 @@ Tagged `social` `overlay` `instagram`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/ios26-liquid-glass.mdx b/docs/catalog/blocks/ios26-liquid-glass.mdx
index c6c4bf17c8..c7f34f439c 100644
--- a/docs/catalog/blocks/ios26-liquid-glass.mdx
+++ b/docs/catalog/blocks/ios26-liquid-glass.mdx
@@ -7,11 +7,15 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
iOS 26 Liquid Glass Home Screen
+
3D iPhone with a normal iOS 26 home screen, liquid glass app icons, shader wallpaper, dock, and fluid glass notifications that drop from the status area onto a GLTF device model.
+
+
-
+
+
+
Live preview needs the `chrome://flags/#canvas-draw-element` flag switched on.
@@ -1415,6 +1421,4 @@ Tagged `liquid-glass-html-in-canvas` `webgpu` `3d` `iphone` `ios26` `notificatio
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/lens-flare.mdx b/docs/catalog/blocks/lens-flare.mdx
index 66536b5c9c..6a94f29461 100644
--- a/docs/catalog/blocks/lens-flare.mdx
+++ b/docs/catalog/blocks/lens-flare.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Lens Flare
+
A camera lens flare: a bright star burst and a faint rainbow halo that slowly shimmer on black. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `background` `light` `flare` `glow`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/light-edge.mdx b/docs/catalog/blocks/light-edge.mdx
index 8afb9783be..d55150dff7 100644
--- a/docs/catalog/blocks/light-edge.mdx
+++ b/docs/catalog/blocks/light-edge.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Light Edge
+
Purple and cyan light races around the edge of an orb on black. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `object` `light` `glow` `neon` `edge`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/light-leak.mdx b/docs/catalog/blocks/light-leak.mdx
index 6fc3c0a662..dfa431e78e 100644
--- a/docs/catalog/blocks/light-leak.mdx
+++ b/docs/catalog/blocks/light-leak.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Light Leak
+
Shader transition with cinematic light leak overlay
+
+
-
+
+
+
## Add it to your video
@@ -431,6 +437,4 @@ Tagged `transition` `shader`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/liquid-glass-notification.mdx b/docs/catalog/blocks/liquid-glass-notification.mdx
index 7555771caa..8711afa7f4 100644
--- a/docs/catalog/blocks/liquid-glass-notification.mdx
+++ b/docs/catalog/blocks/liquid-glass-notification.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Liquid Glass Notification
+
Frosted glass notification cards floating over an aurora shader background
+
+
-
+
+
+
Live preview needs the `chrome://flags/#canvas-draw-element` flag switched on.
@@ -560,6 +566,4 @@ Tagged `html-in-canvas` `liquid-glass-html-in-canvas` `webgpu`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/liquid-glass-widgets.mdx b/docs/catalog/blocks/liquid-glass-widgets.mdx
index eafafa8df8..6ccf949fbe 100644
--- a/docs/catalog/blocks/liquid-glass-widgets.mdx
+++ b/docs/catalog/blocks/liquid-glass-widgets.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Liquid Glass Widgets
+
Frosted glass stat cards, showcase panel and pill chips over an aurora shader background
+
+
-
+
+
+
Live preview needs the `chrome://flags/#canvas-draw-element` flag switched on.
@@ -838,6 +844,4 @@ Tagged `html-in-canvas` `liquid-glass-html-in-canvas` `webgpu`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/liquid-metal.mdx b/docs/catalog/blocks/liquid-metal.mdx
index 6dbb2b52b5..f4ca8ab973 100644
--- a/docs/catalog/blocks/liquid-metal.mdx
+++ b/docs/catalog/blocks/liquid-metal.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Liquid Metal
+
A chrome sphere ripples and flows like molten metal on black. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `object` `metal` `chrome` `liquid` `sphere`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/logo-outro.mdx b/docs/catalog/blocks/logo-outro.mdx
index c618c161ee..40753fc268 100644
--- a/docs/catalog/blocks/logo-outro.mdx
+++ b/docs/catalog/blocks/logo-outro.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Logo Outro
+
Cinematic logo reveal with piece-by-piece assembly, glow bloom, tagline fade-in, and URL pill
+
+
-
+
+
+
## Add it to your video
@@ -299,6 +305,4 @@ Tagged `branding` `outro` `logo`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/lottie-character-walk.mdx b/docs/catalog/blocks/lottie-character-walk.mdx
index 9fcfa0af1d..ce8e20ae7d 100644
--- a/docs/catalog/blocks/lottie-character-walk.mdx
+++ b/docs/catalog/blocks/lottie-character-walk.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Lottie Character Walk
+
A jointed flat character walks in on planted feet, stops and points at a card; the body acting is a Lottie file and the stage is GSAP.
+
+
-
+
+
+
## Add it to your video
@@ -229,6 +235,4 @@ Tagged `character` `character-animation` `mascot` `walk-cycle` `gesture` `pointi
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/lower-third-bild.mdx b/docs/catalog/blocks/lower-third-bild.mdx
index 76fb419398..aac599f1c9 100644
--- a/docs/catalog/blocks/lower-third-bild.mdx
+++ b/docs/catalog/blocks/lower-third-bild.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Lower Third — BILD Style
+
News-style lower third with tight-fit text boxes: white headline bar with red drop-shadow, red sub-line with white drop-shadow.
+
+
-
+
+
+
## Add it to your video
@@ -238,6 +244,4 @@ Tagged `broadcast` `lower-third` `news` `overlay`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/lt-accent-underline.mdx b/docs/catalog/blocks/lt-accent-underline.mdx
index 9de431ba53..a8b3c357a0 100644
--- a/docs/catalog/blocks/lt-accent-underline.mdx
+++ b/docs/catalog/blocks/lt-accent-underline.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Lower Third — Accent Underline
+
Cardless lower third for footage overlay: name rises, an accent rule draws left-to-right, role fades in; text-shadowed for legibility
+
+
-
+
+
+
## Add it to your video
@@ -172,6 +178,4 @@ Tagged `lower-third` `overlay` `podcast` `interview` `minimal`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/lt-bold-block.mdx b/docs/catalog/blocks/lt-bold-block.mdx
index 4d40b76e09..9759affa4e 100644
--- a/docs/catalog/blocks/lt-bold-block.mdx
+++ b/docs/catalog/blocks/lt-bold-block.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Lower Third — Bold Block
+
High-energy podcast lower third: solid dark block wipes in, uppercase name slams up, accent tag pops
+
+
-
+
+
+
## Add it to your video
@@ -174,6 +180,4 @@ Tagged `lower-third` `overlay` `podcast` `interview` `bold`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/lt-clean-bar.mdx b/docs/catalog/blocks/lt-clean-bar.mdx
index 195607529a..c35e6a8900 100644
--- a/docs/catalog/blocks/lt-clean-bar.mdx
+++ b/docs/catalog/blocks/lt-clean-bar.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Lower Third — Clean Bar
+
Minimal white-card lower third for podcasts/interviews: accent tab, name + role, clip-wipe entrance
+
+
-
+
+
+
## Add it to your video
@@ -177,6 +183,4 @@ Tagged `lower-third` `overlay` `podcast` `interview`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/lt-color-block.mdx b/docs/catalog/blocks/lt-color-block.mdx
index 5fccfae884..606306e901 100644
--- a/docs/catalog/blocks/lt-color-block.mdx
+++ b/docs/catalog/blocks/lt-color-block.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Lower Third — Color Block
+
High-energy lower third: bold accent-color block slides in with overshoot, condensed name + mono role
+
+
-
+
+
+
## Add it to your video
@@ -166,6 +172,4 @@ Tagged `lower-third` `overlay` `podcast` `interview` `bold`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/lt-dark-card.mdx b/docs/catalog/blocks/lt-dark-card.mdx
index 13f5c709ec..9ee6202640 100644
--- a/docs/catalog/blocks/lt-dark-card.mdx
+++ b/docs/catalog/blocks/lt-dark-card.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Lower Third — Dark Card
+
Charcoal card lower third for bright footage: name, drawn accent underline, role; slide-up entrance
+
+
-
+
+
+
## Add it to your video
@@ -176,6 +182,4 @@ Tagged `lower-third` `overlay` `podcast` `interview` `dark`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/lt-kicker-name.mdx b/docs/catalog/blocks/lt-kicker-name.mdx
index e80ecdc987..b44affb012 100644
--- a/docs/catalog/blocks/lt-kicker-name.mdx
+++ b/docs/catalog/blocks/lt-kicker-name.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Lower Third — Kicker Name
+
Cardless lower third with an accent eyebrow/kicker tag, heavy name, and a drawn baseline; for footage
+
+
-
+
+
+
## Add it to your video
@@ -179,6 +185,4 @@ Tagged `lower-third` `overlay` `podcast` `interview` `bold`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/lt-mask-reveal.mdx b/docs/catalog/blocks/lt-mask-reveal.mdx
index 8b471660b2..d76732bebd 100644
--- a/docs/catalog/blocks/lt-mask-reveal.mdx
+++ b/docs/catalog/blocks/lt-mask-reveal.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Lower Third — Mask Reveal
+
Cardless lower third: an accent sweep crosses and clip-path-reveals a heavy name, role fades up; for footage
+
+
-
+
+
+
## Add it to your video
@@ -185,6 +191,4 @@ Tagged `lower-third` `overlay` `podcast` `interview` `bold`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/lt-neon-border.mdx b/docs/catalog/blocks/lt-neon-border.mdx
index b979762c51..ea949db5ef 100644
--- a/docs/catalog/blocks/lt-neon-border.mdx
+++ b/docs/catalog/blocks/lt-neon-border.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Neon Border
+
Two arcs of light travel the edge of a rounded panel and snap corner to corner, trailing a soft three-layer bloom. A lower third for a name and role.
+
+
-
+
+
+
## Add it to your video
@@ -498,6 +504,4 @@ Tagged `lower-third` `glow` `loop` `video-primitive`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/lt-side-rule.mdx b/docs/catalog/blocks/lt-side-rule.mdx
index bd6373d7e8..6b7fc47baa 100644
--- a/docs/catalog/blocks/lt-side-rule.mdx
+++ b/docs/catalog/blocks/lt-side-rule.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Lower Third — Side Rule
+
Cardless lower third with a vertical accent bar; condensed display name + mono role, text-shadowed for footage
+
+
-
+
+
+
## Add it to your video
@@ -179,6 +185,4 @@ Tagged `lower-third` `overlay` `podcast` `interview` `minimal`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/lt-soft-pill.mdx b/docs/catalog/blocks/lt-soft-pill.mdx
index dac57b8e6b..fbfd9977e5 100644
--- a/docs/catalog/blocks/lt-soft-pill.mdx
+++ b/docs/catalog/blocks/lt-soft-pill.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Lower Third — Soft Pill
+
Rounded white pill lower third for podcasts/interviews: status dot, name + role, scale-pop entrance
+
+
-
+
+
+
## Add it to your video
@@ -184,6 +190,4 @@ Tagged `lower-third` `overlay` `podcast` `interview` `minimal`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/lt-stack-bars.mdx b/docs/catalog/blocks/lt-stack-bars.mdx
index d8825d7cde..156ac8c476 100644
--- a/docs/catalog/blocks/lt-stack-bars.mdx
+++ b/docs/catalog/blocks/lt-stack-bars.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Lower Third — Stack Bars
+
Two stacked bars: a dark name bar wipes from the left, an accent role bar wipes from the right
+
+
-
+
+
+
## Add it to your video
@@ -174,6 +180,4 @@ Tagged `lower-third` `overlay` `podcast` `interview` `bold`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/macos-notification.mdx b/docs/catalog/blocks/macos-notification.mdx
index b177f78994..4ae731ff05 100644
--- a/docs/catalog/blocks/macos-notification.mdx
+++ b/docs/catalog/blocks/macos-notification.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
macOS Notification
+
Animated macOS-style notification banner with app icon and message
+
+
-
+
+
+
## Add it to your video
@@ -267,6 +273,4 @@ Tagged `social` `overlay` `notification`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/macos-tahoe-liquid-glass.mdx b/docs/catalog/blocks/macos-tahoe-liquid-glass.mdx
index 08a5d4c926..10b2537ac8 100644
--- a/docs/catalog/blocks/macos-tahoe-liquid-glass.mdx
+++ b/docs/catalog/blocks/macos-tahoe-liquid-glass.mdx
@@ -7,11 +7,15 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
macOS Tahoe Liquid Glass Desktop
+
3D MacBook with a macOS Tahoe-style desktop, glass menu bar, Finder window, dock, and cinematic device camera move.
+
+
-
+
+
+
Live preview needs the `chrome://flags/#canvas-draw-element` flag switched on.
@@ -1534,6 +1540,4 @@ Tagged `html-in-canvas` `3d` `macos` `tahoe` `gltf`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/marble.mdx b/docs/catalog/blocks/marble.mdx
index 660d40793d..c771d3869e 100644
--- a/docs/catalog/blocks/marble.mdx
+++ b/docs/catalog/blocks/marble.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Marble
+
Ink-dark veins wind through white in a marbled pattern that slowly shifts. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `background` `marble` `texture`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/mesh-gradient.mdx b/docs/catalog/blocks/mesh-gradient.mdx
index f2f4549407..074bf93c5b 100644
--- a/docs/catalog/blocks/mesh-gradient.mdx
+++ b/docs/catalog/blocks/mesh-gradient.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Mesh Gradient
+
Soft coral, orange and violet fields blend and drift in a mesh gradient. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `background` `gradient` `color`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/message-thread-reveal.mdx b/docs/catalog/blocks/message-thread-reveal.mdx
index 8879350735..442d3d9748 100644
--- a/docs/catalog/blocks/message-thread-reveal.mdx
+++ b/docs/catalog/blocks/message-thread-reveal.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Message Thread Reveal
+
A full text conversation plays out on a phone - bubbles popping in, typing indicators, a shared link card, emoji, delivered receipts - with the whole thread scrolling up beat by beat until a closing card lands. The complete chat ad-template, measured message by message
+
+
-
+
+
+
## Add it to your video
@@ -1731,6 +1737,4 @@ Created by Miao Yang.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/mk-background.mdx b/docs/catalog/blocks/mk-background.mdx
index 7da511a215..4a2f08833c 100644
--- a/docs/catalog/blocks/mk-background.mdx
+++ b/docs/catalog/blocks/mk-background.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Minimal Gradient Background
+
Procedural soft-blob gradient backdrop in a minimalist presentation style: two radial blobs drifting over a base color, with an animatable rounded-card bar mask and optional frosted-glass mode
+
+
-
+
+
+
## Add it to your video
@@ -301,6 +307,4 @@ Tagged `background` `gradient` `minimal` `professional` `presentation`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/mk-callout-highlight.mdx b/docs/catalog/blocks/mk-callout-highlight.mdx
index 4684f0ed88..da43f200f1 100644
--- a/docs/catalog/blocks/mk-callout-highlight.mdx
+++ b/docs/catalog/blocks/mk-callout-highlight.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Word-Sweep Highlight
+
A sentence whose word-by-word emphasis is driven by a single scalar — tween it to sync the highlight with a voiceover
+
+
-
+
+
+
## Add it to your video
@@ -222,6 +228,4 @@ Tagged `typography` `karaoke` `captions` `minimal`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/mk-clone-wall-transition.mdx b/docs/catalog/blocks/mk-clone-wall-transition.mdx
index 393904eb86..a8067f5209 100644
--- a/docs/catalog/blocks/mk-clone-wall-transition.mdx
+++ b/docs/catalog/blocks/mk-clone-wall-transition.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Text Clone Wall Transition
+
Overlay transition: a tiled word wall covers the frame, inverts via difference blending, and clears — hard-cut the content beneath while covered
+
+
-
+
+
+
## Add it to your video
@@ -291,6 +297,4 @@ Tagged `transition` `typography` `wipe`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/mk-line-graph.mdx b/docs/catalog/blocks/mk-line-graph.mdx
index 992ebf5f52..7b0edafa00 100644
--- a/docs/catalog/blocks/mk-line-graph.mdx
+++ b/docs/catalog/blocks/mk-line-graph.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Minimal Line Graph
+
One or two SVG series draw on with dots popping and value labels riding the draw front; dim baseline axis, x-labels, color-dot legend
+
+
-
+
+
+
## Add it to your video
@@ -358,6 +364,4 @@ Tagged `data-viz` `chart` `graph` `minimal`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/mk-placeholder-grid.mdx b/docs/catalog/blocks/mk-placeholder-grid.mdx
index 493a881d9c..122823d2c0 100644
--- a/docs/catalog/blocks/mk-placeholder-grid.mdx
+++ b/docs/catalog/blocks/mk-placeholder-grid.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Rounded Media Grid
+
N-up rounded-corner media grid (2-up, 3-up, 4-up, 3x2, hero plus two): per-cell inside-scale framing, staggered box-in entrance, slow settle
+
+
-
+
+
+
## Add it to your video
@@ -299,6 +305,4 @@ Tagged `placeholder` `media` `grid` `minimal`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/mk-progress-stat.mdx b/docs/catalog/blocks/mk-progress-stat.mdx
index c6ebb9ec98..b0ff8e6b2f 100644
--- a/docs/catalog/blocks/mk-progress-stat.mdx
+++ b/docs/catalog/blocks/mk-progress-stat.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Count-Up Stat Card
+
Big-numeral statistic with count-up, label, thin progress track filling to value/max, and caption; light and dark schemes
+
+
-
+
+
+
## Add it to your video
@@ -251,6 +257,4 @@ Tagged `data-viz` `stat` `minimal`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/mk-specs-list.mdx b/docs/catalog/blocks/mk-specs-list.mdx
index 324d9b7579..3725f3a815 100644
--- a/docs/catalog/blocks/mk-specs-list.mdx
+++ b/docs/catalog/blocks/mk-specs-list.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Specs Checklist
+
Left-aligned specs/traits checklist over footage or a board: rows slide in staggered with an accent underline sweep; light and dark schemes
+
+
-
+
+
+
## Add it to your video
@@ -288,6 +294,4 @@ Tagged `data-viz` `list` `minimal` `professional`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/nebula.mdx b/docs/catalog/blocks/nebula.mdx
index 241af46271..29b7a42aff 100644
--- a/docs/catalog/blocks/nebula.mdx
+++ b/docs/catalog/blocks/nebula.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Nebula
+
A small world of pink and blue gas swirls inside a sphere on black. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `object` `space` `nebula` `sphere`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/news-ticker.mdx b/docs/catalog/blocks/news-ticker.mdx
index 648bf5df21..329c14d5cd 100644
--- a/docs/catalog/blocks/news-ticker.mdx
+++ b/docs/catalog/blocks/news-ticker.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
News Ticker
+
Premium broadcast-style lower-third ticker with live label, headline ribbon, and scrolling news crawl.
+
+
-
+
+
+
## Add it to your video
@@ -474,6 +480,4 @@ Tagged `lower-third` `overlay` `news` `ticker`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/north-korea-locked-down.mdx b/docs/catalog/blocks/north-korea-locked-down.mdx
index 91d2f84d9b..80aec0f3a4 100644
--- a/docs/catalog/blocks/north-korea-locked-down.mdx
+++ b/docs/catalog/blocks/north-korea-locked-down.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
North Korea Locked Down
+
Realistic map zoom into North Korea with a red scribble circle, locked-down pop-up label, and reddish editorial wash.
+
+
-
+
+
+
## Add it to your video
@@ -381,6 +387,4 @@ use 📷HyperFrames by HeyGen and Image Gen if you need it for assets or like p
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/notes-reveal.mdx b/docs/catalog/blocks/notes-reveal.mdx
index 74d2ba3658..07fd55f3f1 100644
--- a/docs/catalog/blocks/notes-reveal.mdx
+++ b/docs/catalog/blocks/notes-reveal.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Notes Reveal
+
A personal note is typed character by character in a notes app - caret riding every letter, the page scrolling up on measured settle curves as each line lands - then cuts to a hand-lettered paper card with a marker headline and a ticked checklist
+
+
-
+
+
+
## Add it to your video
@@ -1768,6 +1774,4 @@ Created by Miao Yang.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/notification-cascade.mdx b/docs/catalog/blocks/notification-cascade.mdx
index 6af4763f17..6ae87119c5 100644
--- a/docs/catalog/blocks/notification-cascade.mdx
+++ b/docs/catalog/blocks/notification-cascade.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Notification Cascade
+
Phone notifications land one after another and stack up the screen, each banner pushing the pile down as it arrives, before the whole stack lifts away into a closing card
+
+
-
+
+
+
## Add it to your video
@@ -617,6 +623,4 @@ Created by Miao Yang.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/nyc-paris-flight.mdx b/docs/catalog/blocks/nyc-paris-flight.mdx
index 90be719613..c6e6e372bd 100644
--- a/docs/catalog/blocks/nyc-paris-flight.mdx
+++ b/docs/catalog/blocks/nyc-paris-flight.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
NYC Paris Flight
+
Apple-style realistic map animation with a plane flying from New York to Paris, marker circle, landing pop, and sound effects.
+
+
-
+
+
+
## Add it to your video
@@ -601,6 +607,4 @@ Created by [Stronkter](https://x.com/Stronkter).
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/obsidian.mdx b/docs/catalog/blocks/obsidian.mdx
index 930b02221e..a8a328bb1c 100644
--- a/docs/catalog/blocks/obsidian.mdx
+++ b/docs/catalog/blocks/obsidian.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Obsidian
+
A dark glass orb catches pink and cyan iridescent light on black. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `object` `glass` `iridescent` `dark`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/orbit-card.mdx b/docs/catalog/blocks/orbit-card.mdx
index 607a5116cd..c069111fc6 100644
--- a/docs/catalog/blocks/orbit-card.mdx
+++ b/docs/catalog/blocks/orbit-card.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Orbit Card
+
A single feature card orbits a dot sphere on approved Blender camera motion.
+
+
-
+
+
+
## Add it to your video
@@ -175,6 +181,4 @@ Tagged `3d-motion` `cards` `feature-reveal` `dots` `orbit` `blender-motion` `sph
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/organic-light-leak-overlay.mdx b/docs/catalog/blocks/organic-light-leak-overlay.mdx
index 1ca512bded..43501a1ab7 100644
--- a/docs/catalog/blocks/organic-light-leak-overlay.mdx
+++ b/docs/catalog/blocks/organic-light-leak-overlay.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Organic Light Leak Overlay
+
Finite CSS light-leak overlay for memory beats and motivated transitions
+
+
-
+
+
+
## Add it to your video
@@ -191,6 +197,4 @@ Tagged `light-leak` `film` `memory` `transition` `overlay` `media-treatment-over
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/oscilloscope-trace.mdx b/docs/catalog/blocks/oscilloscope-trace.mdx
index 870dd83899..999a6d6226 100644
--- a/docs/catalog/blocks/oscilloscope-trace.mdx
+++ b/docs/catalog/blocks/oscilloscope-trace.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Oscilloscope Trace
+
CRT oscilloscope beam sweeping a waveform across a 10x8 graticule, with closed-form phosphor persistence: the tail decays as exp(-age/tau) and brightens where the beam slows
+
+
-
+
+
+
## Add it to your video
@@ -610,6 +616,4 @@ Tagged `instrument` `data` `showcase` `retro`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/plasma.mdx b/docs/catalog/blocks/plasma.mdx
index c5345d0095..1afd785262 100644
--- a/docs/catalog/blocks/plasma.mdx
+++ b/docs/catalog/blocks/plasma.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Plasma
+
Deep violet plasma folds and churns across the whole frame. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `background` `texture` `plasma` `purple`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/plastic.mdx b/docs/catalog/blocks/plastic.mdx
index dcbc3e2199..f80e560c04 100644
--- a/docs/catalog/blocks/plastic.mdx
+++ b/docs/catalog/blocks/plastic.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Plastic
+
A glossy white plastic orb with soft studio reflections, on black. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `object` `plastic` `material` `white`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/prism.mdx b/docs/catalog/blocks/prism.mdx
index fe1dd30f18..fa20800ffd 100644
--- a/docs/catalog/blocks/prism.mdx
+++ b/docs/catalog/blocks/prism.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Prism
+
A white beam of light splits into a slowly turning rainbow. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `background` `light` `prism` `rainbow`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/product-turntable.mdx b/docs/catalog/blocks/product-turntable.mdx
index 4e4583f52c..49bcc83a0b 100644
--- a/docs/catalog/blocks/product-turntable.mdx
+++ b/docs/catalog/blocks/product-turntable.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Product Turntable
+
A product turns a full revolution on a studio plinth in a seamless loop. Drop in a GLB or glTF model, or keep the built-in drink can with your own label.
+
+
-
+
+
+
## Add it to your video
@@ -429,6 +435,4 @@ Tagged `3d-object` `three-js` `webgl` `product` `turntable` `glb` `loop`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/rack-focus.mdx b/docs/catalog/blocks/rack-focus.mdx
index d977f2506c..6c3a17fcbe 100644
--- a/docs/catalog/blocks/rack-focus.mdx
+++ b/docs/catalog/blocks/rack-focus.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Rack Focus
+
A focus pull with real aperture bokeh: the focal plane travels from a near subject to a far one, so one resolves as the other blows into hard-edged polygon discs that clip to a cat's eye toward the corners. A focus pull only reads against content at two clearly separated depths, so this block carries its own depth-layered night exterior and puts both subject depths on variables.
+
+
-
+
+
+
## Add it to your video
@@ -717,6 +723,4 @@ Tagged `webgl` `shader` `camera` `depth` `cinematic` `showcase`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/reddit-post.mdx b/docs/catalog/blocks/reddit-post.mdx
index c143b1f6b0..16bc68d2c8 100644
--- a/docs/catalog/blocks/reddit-post.mdx
+++ b/docs/catalog/blocks/reddit-post.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Reddit Post Card
+
Animated Reddit post card overlay with upvotes and comments
+
+
-
+
+
+
## Add it to your video
@@ -412,6 +418,4 @@ Tagged `social` `overlay` `reddit`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/ridged-burn.mdx b/docs/catalog/blocks/ridged-burn.mdx
index 5346bcf30f..c78104a82b 100644
--- a/docs/catalog/blocks/ridged-burn.mdx
+++ b/docs/catalog/blocks/ridged-burn.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Ridged Burn
+
Shader transition with ridged turbulence burn effect
+
+
-
+
+
+
## Add it to your video
@@ -443,6 +449,4 @@ Tagged `transition` `shader`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/ripple-waves.mdx b/docs/catalog/blocks/ripple-waves.mdx
index c2cf4a1c04..dda975bbad 100644
--- a/docs/catalog/blocks/ripple-waves.mdx
+++ b/docs/catalog/blocks/ripple-waves.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Ripple Waves
+
Shader transition with concentric ripple wave distortion
+
+
-
+
+
+
## Add it to your video
@@ -432,6 +438,4 @@ Tagged `transition` `shader`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/ripples.mdx b/docs/catalog/blocks/ripples.mdx
index 99b66e45f1..5d2ba815bc 100644
--- a/docs/catalog/blocks/ripples.mdx
+++ b/docs/catalog/blocks/ripples.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Ripples
+
Concentric rings ripple outward from the centre, white on black. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `background` `texture` `rings` `waves` `monochro
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/sdf-iris.mdx b/docs/catalog/blocks/sdf-iris.mdx
index 9b0770151e..543e7436fa 100644
--- a/docs/catalog/blocks/sdf-iris.mdx
+++ b/docs/catalog/blocks/sdf-iris.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
SDF Iris
+
Shader transition with signed distance field iris reveal
+
+
-
+
+
+
## Add it to your video
@@ -432,6 +438,4 @@ Tagged `transition` `shader`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/share-sheet-carousel.mdx b/docs/catalog/blocks/share-sheet-carousel.mdx
index a57fdfaa97..c709f88553 100644
--- a/docs/catalog/blocks/share-sheet-carousel.mdx
+++ b/docs/catalog/blocks/share-sheet-carousel.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Share-Sheet Carousel
+
A share sheet springs up from the bottom of the phone and cycles previews inside its card on a fast cut rhythm while the blurred ground swaps behind it, ending on an accept tap
+
+
-
+
+
+
## Add it to your video
@@ -490,6 +496,4 @@ Created by Miao Yang.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/sine-wave.mdx b/docs/catalog/blocks/sine-wave.mdx
index 8735b072be..d02a6b2726 100644
--- a/docs/catalog/blocks/sine-wave.mdx
+++ b/docs/catalog/blocks/sine-wave.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Sine Wave
+
A glowing white sine wave travels across a black frame. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `background` `wave` `line` `glow`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/slack-notification-ad.mdx b/docs/catalog/blocks/slack-notification-ad.mdx
index 3d8dc9355e..660786fd84 100644
--- a/docs/catalog/blocks/slack-notification-ad.mdx
+++ b/docs/catalog/blocks/slack-notification-ad.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Slack Notification Ad
+
A portrait lock screen fills with escalating Slack video requests before HeyGen delivers the payoff
+
+
-
+
+
+
## Add it to your video
@@ -778,6 +784,4 @@ Created by HeyGen.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/snow.mdx b/docs/catalog/blocks/snow.mdx
index b7439b3847..a084ccbaf6 100644
--- a/docs/catalog/blocks/snow.mdx
+++ b/docs/catalog/blocks/snow.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Snow
+
Seek-safe falling-snow overlay: sparse or dense flakes drift down with size, speed and opacity correlated per flake for depth, radial-masked so the frame center stays clear
+
+
-
+
+
+
## Add it to your video
@@ -291,6 +297,4 @@ Tagged `snow` `snowfall` `winter` `weather` `overlay` `ambient` `particles` `med
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/spain-map.mdx b/docs/catalog/blocks/spain-map.mdx
index a82ac40496..75dde392a9 100644
--- a/docs/catalog/blocks/spain-map.mdx
+++ b/docs/catalog/blocks/spain-map.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Spain Map
+
Animated Spain choropleth by autonomous community with staggered reveals and gradient legend — D3 conic conformal projection
+
+
-
+
+
+
## Add it to your video
@@ -459,6 +465,4 @@ Tagged `data` `map` `geography` `spain` `europe` `choropleth`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/spiral-galaxy.mdx b/docs/catalog/blocks/spiral-galaxy.mdx
index bdff90fd4a..c76e93db40 100644
--- a/docs/catalog/blocks/spiral-galaxy.mdx
+++ b/docs/catalog/blocks/spiral-galaxy.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Spiral Galaxy
+
A spiral galaxy seen from outside, turning with real differential rotation: inner stars orbit faster than outer ones, so the arms wind up over the shot instead of spinning rigidly. 20,000 additive GPU sprites, seeded once and solved directly from time, so any frame can be rendered on its own.
+
+
-
+
+
+
## Add it to your video
@@ -416,6 +422,4 @@ Tagged `hero` `space` `particles` `webgl` `background`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/spiral.mdx b/docs/catalog/blocks/spiral.mdx
index b7edc8e67c..3fc0ac06c3 100644
--- a/docs/catalog/blocks/spiral.mdx
+++ b/docs/catalog/blocks/spiral.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Spiral
+
A bold black and white spiral turns in the frame. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `background` `pattern` `spiral` `monochrome`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/split-flap-board.mdx b/docs/catalog/blocks/split-flap-board.mdx
index baea7a7624..d1d9df439c 100644
--- a/docs/catalog/blocks/split-flap-board.mdx
+++ b/docs/catalog/blocks/split-flap-board.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Split-Flap Board
+
Solari-style departure board: every cell walks its drum forward through the intervening characters of a fixed alphabet until it lands on its target, so the text resolves as a mechanical cascade instead of a fade.
+
+
-
+
+
+
## Add it to your video
@@ -436,6 +442,4 @@ Tagged `text` `kinetic` `mechanical` `split-flap` `solari` `departure-board` `re
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/spotify-card.mdx b/docs/catalog/blocks/spotify-card.mdx
index ed773bcd5d..8d287be253 100644
--- a/docs/catalog/blocks/spotify-card.mdx
+++ b/docs/catalog/blocks/spotify-card.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Spotify Now Playing
+
Animated Spotify now-playing card with album art and progress bar
+
+
-
+
+
+
## Add it to your video
@@ -365,6 +371,4 @@ Tagged `social` `overlay` `spotify`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/starfield.mdx b/docs/catalog/blocks/starfield.mdx
index e6daa8a4b9..778438b8e8 100644
--- a/docs/catalog/blocks/starfield.mdx
+++ b/docs/catalog/blocks/starfield.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Starfield
+
Seek-safe night-sky overlay: sparse or dense stars in three size tiers that twinkle and drift in two parallax layers, radial-masked to keep the frame center clear
+
+
-
+
+
+
## Add it to your video
@@ -275,6 +281,4 @@ Tagged `starfield` `night-sky` `stars` `twinkle` `sky` `weather` `overlay` `ambi
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/strands.mdx b/docs/catalog/blocks/strands.mdx
index b8619e95e8..8851bf9c62 100644
--- a/docs/catalog/blocks/strands.mdx
+++ b/docs/catalog/blocks/strands.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Strands
+
Thin ribbons of pink and blue light weave across a black field. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `background` `light` `lines` `ribbons`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/stripes.mdx b/docs/catalog/blocks/stripes.mdx
index ec9f0111bb..bc8e73bb44 100644
--- a/docs/catalog/blocks/stripes.mdx
+++ b/docs/catalog/blocks/stripes.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Stripes
+
Bold black and white diagonal stripes slide across the frame. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `background` `pattern` `stripes` `monochrome`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/sun-burst.mdx b/docs/catalog/blocks/sun-burst.mdx
index 5e1d6da332..41620b9c10 100644
--- a/docs/catalog/blocks/sun-burst.mdx
+++ b/docs/catalog/blocks/sun-burst.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Sun Burst
+
Cream and black rays fan out from the centre and slowly turn. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `background` `light` `rays` `radial`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/swirl-vortex.mdx b/docs/catalog/blocks/swirl-vortex.mdx
index 78707d0e26..4e37c40c23 100644
--- a/docs/catalog/blocks/swirl-vortex.mdx
+++ b/docs/catalog/blocks/swirl-vortex.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Swirl Vortex
+
Shader transition with swirling vortex distortion
+
+
-
+
+
+
## Add it to your video
@@ -442,6 +448,4 @@ Tagged `transition` `shader`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/swirl.mdx b/docs/catalog/blocks/swirl.mdx
index 235c35b456..20f3d91654 100644
--- a/docs/catalog/blocks/swirl.mdx
+++ b/docs/catalog/blocks/swirl.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Swirl
+
Orange and blue color fields swirl and flow into each other across the whole frame. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `background` `gradient` `flow` `abstract`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/thermal-distortion.mdx b/docs/catalog/blocks/thermal-distortion.mdx
index 74d74f8297..be6af9d166 100644
--- a/docs/catalog/blocks/thermal-distortion.mdx
+++ b/docs/catalog/blocks/thermal-distortion.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Thermal Distortion
+
Shader transition with heat haze thermal distortion
+
+
-
+
+
+
## Add it to your video
@@ -443,6 +449,4 @@ Tagged `transition` `shader`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/thin-film.mdx b/docs/catalog/blocks/thin-film.mdx
index bb428befae..763b474549 100644
--- a/docs/catalog/blocks/thin-film.mdx
+++ b/docs/catalog/blocks/thin-film.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Thin Film
+
An orb's rim shimmers with soap-bubble iridescence on black. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `object` `iridescent` `bubble` `rainbow`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/thread-message-stack.mdx b/docs/catalog/blocks/thread-message-stack.mdx
index 42bd47de70..7cb2d98072 100644
--- a/docs/catalog/blocks/thread-message-stack.mdx
+++ b/docs/catalog/blocks/thread-message-stack.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Thread Message Stack
+
A source-owned editable conversation stack with arbitrary incoming and outgoing messages
+
+
-
+
+
+
## Add it to your video
@@ -305,6 +311,4 @@ Tagged `social` `conversation` `messages`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/tiktok-follow.mdx b/docs/catalog/blocks/tiktok-follow.mdx
index 287d5fa6d7..e589ba131f 100644
--- a/docs/catalog/blocks/tiktok-follow.mdx
+++ b/docs/catalog/blocks/tiktok-follow.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
TikTok Follow
+
Animated TikTok follow overlay with profile card and follow button
+
+
-
+
+
+
## Add it to your video
@@ -329,6 +335,4 @@ Tagged `social` `overlay` `tiktok`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/transitions-3d.mdx b/docs/catalog/blocks/transitions-3d.mdx
index ea4e71f2bc..8f31ba419e 100644
--- a/docs/catalog/blocks/transitions-3d.mdx
+++ b/docs/catalog/blocks/transitions-3d.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
3D Transitions
+
Showcase of 3D perspective flip and rotate transitions
+
+
-
+
+
+
## Add it to your video
@@ -363,6 +369,4 @@ Tagged `transition` `showcase`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/transitions-blur.mdx b/docs/catalog/blocks/transitions-blur.mdx
index 5fdd80c779..f04286e790 100644
--- a/docs/catalog/blocks/transitions-blur.mdx
+++ b/docs/catalog/blocks/transitions-blur.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Blur Transitions
+
Showcase of blur-based transitions between scenes
+
+
-
+
+
+
## Add it to your video
@@ -453,6 +459,4 @@ Tagged `transition` `showcase`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/transitions-cover.mdx b/docs/catalog/blocks/transitions-cover.mdx
index 34bcb618a0..5dc1bcaaeb 100644
--- a/docs/catalog/blocks/transitions-cover.mdx
+++ b/docs/catalog/blocks/transitions-cover.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Cover Transitions
+
Showcase of cover/uncover slide transitions
+
+
-
+
+
+
## Add it to your video
@@ -437,6 +443,4 @@ Tagged `transition` `showcase`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/transitions-destruction.mdx b/docs/catalog/blocks/transitions-destruction.mdx
index a6837eb885..e130b0bca1 100644
--- a/docs/catalog/blocks/transitions-destruction.mdx
+++ b/docs/catalog/blocks/transitions-destruction.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Destruction Transitions
+
Showcase of destructive break-apart transitions
+
+
-
+
+
+
## Add it to your video
@@ -480,6 +486,4 @@ Tagged `transition` `showcase`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/transitions-dissolve.mdx b/docs/catalog/blocks/transitions-dissolve.mdx
index 5f042f1216..1458bda938 100644
--- a/docs/catalog/blocks/transitions-dissolve.mdx
+++ b/docs/catalog/blocks/transitions-dissolve.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Dissolve Transitions
+
Showcase of dissolve and fade transitions
+
+
-
+
+
+
## Add it to your video
@@ -457,6 +463,4 @@ Tagged `transition` `showcase` `crossfade`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/transitions-distortion.mdx b/docs/catalog/blocks/transitions-distortion.mdx
index cdf9d94b79..307b5f28ad 100644
--- a/docs/catalog/blocks/transitions-distortion.mdx
+++ b/docs/catalog/blocks/transitions-distortion.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Distortion Transitions
+
Showcase of warp and distortion transitions
+
+
-
+
+
+
## Add it to your video
@@ -451,6 +457,4 @@ Tagged `transition` `showcase`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/transitions-grid.mdx b/docs/catalog/blocks/transitions-grid.mdx
index 9ddf314047..3683940b34 100644
--- a/docs/catalog/blocks/transitions-grid.mdx
+++ b/docs/catalog/blocks/transitions-grid.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Grid Transitions
+
Showcase of grid-based tile transitions
+
+
-
+
+
+
## Add it to your video
@@ -371,6 +377,4 @@ Tagged `transition` `showcase`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/transitions-light.mdx b/docs/catalog/blocks/transitions-light.mdx
index e633498203..32082bef28 100644
--- a/docs/catalog/blocks/transitions-light.mdx
+++ b/docs/catalog/blocks/transitions-light.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Light Transitions
+
Showcase of light-based glow and flash transitions
+
+
-
+
+
+
## Add it to your video
@@ -457,6 +463,4 @@ Tagged `transition` `showcase`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/transitions-mechanical.mdx b/docs/catalog/blocks/transitions-mechanical.mdx
index 79ef4bee38..3ac6957cef 100644
--- a/docs/catalog/blocks/transitions-mechanical.mdx
+++ b/docs/catalog/blocks/transitions-mechanical.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Mechanical Transitions
+
Showcase of mechanical shutter and iris transitions
+
+
-
+
+
+
## Add it to your video
@@ -489,6 +495,4 @@ Tagged `transition` `showcase`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/transitions-other.mdx b/docs/catalog/blocks/transitions-other.mdx
index be7c8b4513..64943d4763 100644
--- a/docs/catalog/blocks/transitions-other.mdx
+++ b/docs/catalog/blocks/transitions-other.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Other Transitions
+
Showcase of miscellaneous creative transitions
+
+
-
+
+
+
## Add it to your video
@@ -461,6 +467,4 @@ Tagged `transition` `showcase`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/transitions-push.mdx b/docs/catalog/blocks/transitions-push.mdx
index 52fe978274..cf5537e93e 100644
--- a/docs/catalog/blocks/transitions-push.mdx
+++ b/docs/catalog/blocks/transitions-push.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Push Transitions
+
Showcase of push and slide transitions
+
+
-
+
+
+
## Add it to your video
@@ -449,6 +455,4 @@ Tagged `transition` `showcase`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/transitions-radial.mdx b/docs/catalog/blocks/transitions-radial.mdx
index 9e5f919d20..37ddb0e4ff 100644
--- a/docs/catalog/blocks/transitions-radial.mdx
+++ b/docs/catalog/blocks/transitions-radial.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Radial Transitions
+
Showcase of radial wipe and reveal transitions
+
+
-
+
+
+
## Add it to your video
@@ -421,6 +427,4 @@ Tagged `transition` `showcase`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/transitions-scale.mdx b/docs/catalog/blocks/transitions-scale.mdx
index 505cc75183..8394f90bc5 100644
--- a/docs/catalog/blocks/transitions-scale.mdx
+++ b/docs/catalog/blocks/transitions-scale.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Scale Transitions
+
Showcase of scale and zoom transitions
+
+
-
+
+
+
## Add it to your video
@@ -416,6 +422,4 @@ Tagged `transition` `showcase`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/ui-3d-reveal.mdx b/docs/catalog/blocks/ui-3d-reveal.mdx
index bd3d31a170..088b66c5a0 100644
--- a/docs/catalog/blocks/ui-3d-reveal.mdx
+++ b/docs/catalog/blocks/ui-3d-reveal.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
3D UI Reveal
+
Perspective 3D reveal animation for UI elements
+
+
-
+
+
+
## Add it to your video
@@ -2830,6 +2836,4 @@ Tagged `showcase` `3d` `reveal`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/us-map-bubble.mdx b/docs/catalog/blocks/us-map-bubble.mdx
index aa8337fbdf..dd8eec5d51 100644
--- a/docs/catalog/blocks/us-map-bubble.mdx
+++ b/docs/catalog/blocks/us-map-bubble.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
US Bubble Map
+
Animated US bubble map with proportional city markers, value callouts, and connection lines — composable with us-map
+
+
-
+
+
+
## Add it to your video
@@ -545,6 +551,4 @@ Tagged `data` `map` `geography` `usa` `bubble` `cities`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/us-map-flow.mdx b/docs/catalog/blocks/us-map-flow.mdx
index 7dbe74cd60..cc66a9c7fc 100644
--- a/docs/catalog/blocks/us-map-flow.mdx
+++ b/docs/catalog/blocks/us-map-flow.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
US Flow Map
+
Animated connection arcs between US cities over a base map — composable origin-destination flow visualization
+
+
-
+
+
+
## Add it to your video
@@ -495,6 +501,4 @@ Tagged `data` `map` `geography` `usa` `flow` `connections` `arcs`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/us-map-hex.mdx b/docs/catalog/blocks/us-map-hex.mdx
index b974ee8c06..a5231ec304 100644
--- a/docs/catalog/blocks/us-map-hex.mdx
+++ b/docs/catalog/blocks/us-map-hex.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
US Hex Grid Map
+
Animated hexagonal tile grid map — each state as an equal-weight hex with data fill and abbreviation label
+
+
-
+
+
+
## Add it to your video
@@ -625,6 +631,4 @@ Tagged `data` `map` `geography` `usa` `hexgrid` `tilegrid`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/us-map.mdx b/docs/catalog/blocks/us-map.mdx
index b78436b67e..55813f35fd 100644
--- a/docs/catalog/blocks/us-map.mdx
+++ b/docs/catalog/blocks/us-map.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
US Map
+
Animated US choropleth map with staggered state reveals, value labels, and gradient legend — pure inline SVG with GSAP
+
+
-
+
+
+
## Add it to your video
@@ -468,6 +474,4 @@ Tagged `data` `map` `geography` `usa` `choropleth`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/vfx-anamorphic-flare.mdx b/docs/catalog/blocks/vfx-anamorphic-flare.mdx
index 47f15ca81f..2753df964c 100644
--- a/docs/catalog/blocks/vfx-anamorphic-flare.mdx
+++ b/docs/catalog/blocks/vfx-anamorphic-flare.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Anamorphic Streak Flare
+
A drifting field of bright points, each one throwing the long horizontal blue-violet streak a real anamorphic cinema lens produces. Built from the measured filter constants: a 0.3 high-pass, 80 horizontal taps at quarter resolution, a samples/3 gain and a 0x7a8aff tint.
+
+
-
+
+
+
## Add it to your video
@@ -478,6 +484,4 @@ Tagged `vfx` `background` `showcase` `optical` `canvas`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/vfx-iphone-device.mdx b/docs/catalog/blocks/vfx-iphone-device.mdx
index 465a4a4a71..f2b6e6e01b 100644
--- a/docs/catalog/blocks/vfx-iphone-device.mdx
+++ b/docs/catalog/blocks/vfx-iphone-device.mdx
@@ -7,11 +7,15 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
iPhone & MacBook 3D Showcase
+
Real GLTF iPhone 15 Pro Max and MacBook Pro models with live HTML-in-Canvas screen content, morphing glass lens, product review camera choreography, and 360° turntable.
+
+
-
+
+
+
Live preview needs the `chrome://flags/#canvas-draw-element` flag switched on.
@@ -922,6 +928,4 @@ Tagged `html-in-canvas` `3d` `device` `iphone` `macbook` `gltf`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/vfx-liquid-background.mdx b/docs/catalog/blocks/vfx-liquid-background.mdx
index 8d25a00fd7..9878e2c527 100644
--- a/docs/catalog/blocks/vfx-liquid-background.mdx
+++ b/docs/catalog/blocks/vfx-liquid-background.mdx
@@ -7,11 +7,15 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Liquid Background
+
Organic liquid simulation with vertex displacement on a subdivided plane. HTML content floats above rippling fluid surface with real-time wave dynamics.
+
+
-
+
+
+
Live preview needs the `chrome://flags/#canvas-draw-element` flag switched on.
@@ -1324,6 +1330,4 @@ Tagged `html-in-canvas` `liquid` `webgl` `displacement` `background`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/vfx-liquid-glass.mdx b/docs/catalog/blocks/vfx-liquid-glass.mdx
index 7052924f4a..df01e582c7 100644
--- a/docs/catalog/blocks/vfx-liquid-glass.mdx
+++ b/docs/catalog/blocks/vfx-liquid-glass.mdx
@@ -7,11 +7,15 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Liquid Glass
+
VFX composition block
+
+
-
+
+
+
Live preview needs the `chrome://flags/#canvas-draw-element` flag switched on.
@@ -832,6 +838,4 @@ Tagged `html-in-canvas` `webgl`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/vfx-magnetic.mdx b/docs/catalog/blocks/vfx-magnetic.mdx
index fc757986b5..0d4d03f9d5 100644
--- a/docs/catalog/blocks/vfx-magnetic.mdx
+++ b/docs/catalog/blocks/vfx-magnetic.mdx
@@ -7,11 +7,15 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Magnetic
+
VFX composition block
+
+
-
+
+
+
Live preview needs the `chrome://flags/#canvas-draw-element` flag switched on.
@@ -544,6 +550,4 @@ Tagged `html-in-canvas` `webgl`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/vfx-portal.mdx b/docs/catalog/blocks/vfx-portal.mdx
index 07e5505bbf..32ad499d80 100644
--- a/docs/catalog/blocks/vfx-portal.mdx
+++ b/docs/catalog/blocks/vfx-portal.mdx
@@ -7,11 +7,15 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Portal
+
VFX composition block
+
+
-
+
+
+
Live preview needs the `chrome://flags/#canvas-draw-element` flag switched on.
@@ -943,6 +949,4 @@ Tagged `html-in-canvas` `webgl`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/vfx-shatter.mdx b/docs/catalog/blocks/vfx-shatter.mdx
index 6f0008d0cd..99b114ea46 100644
--- a/docs/catalog/blocks/vfx-shatter.mdx
+++ b/docs/catalog/blocks/vfx-shatter.mdx
@@ -7,11 +7,15 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Shatter
+
VFX composition block
+
+
-
+
+
+
Live preview needs the `chrome://flags/#canvas-draw-element` flag switched on.
@@ -1229,6 +1235,4 @@ Tagged `html-in-canvas` `webgl`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/vfx-text-cursor.mdx b/docs/catalog/blocks/vfx-text-cursor.mdx
index e676e2c758..ae2f970ee9 100644
--- a/docs/catalog/blocks/vfx-text-cursor.mdx
+++ b/docs/catalog/blocks/vfx-text-cursor.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
VFX Text Cursor
+
Dramatic text reveal with cursor glow, chromatic shadow rays, and directional lighting on a black stage. Canvas-based shader post-processing with spectral color edges.
+
+
-
+
+
+
Live preview needs the `chrome://flags/#canvas-draw-element` flag switched on.
@@ -927,6 +933,4 @@ Tagged `html-in-canvas` `text` `shader` `cursor` `chromatic`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/voronoi.mdx b/docs/catalog/blocks/voronoi.mdx
index 69c912797d..35e1257730 100644
--- a/docs/catalog/blocks/voronoi.mdx
+++ b/docs/catalog/blocks/voronoi.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Voronoi
+
Magenta cells with glowing blue centres shift and reshape across the frame. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `background` `pattern` `cells` `voronoi`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/vpn-youtube-spot.mdx b/docs/catalog/blocks/vpn-youtube-spot.mdx
index 3113540e96..ad2c569e77 100644
--- a/docs/catalog/blocks/vpn-youtube-spot.mdx
+++ b/docs/catalog/blocks/vpn-youtube-spot.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
VPN YouTube Spot
+
Snappy Apple-style YouTube insert showing a phone finding and installing a friendly VPN app with sound effects.
+
+
-
+
+
+
## Add it to your video
@@ -1063,6 +1069,4 @@ HyperFrames by HeyGen make me a 7s video with Apple-style bold font and styling:
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/water.mdx b/docs/catalog/blocks/water.mdx
index ec6da2f23f..c555f73f36 100644
--- a/docs/catalog/blocks/water.mdx
+++ b/docs/catalog/blocks/water.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Water
+
A sphere of wind-rippled water reflecting a blue sky, on black. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `orb` `water` `material` `blue`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/waveform.mdx b/docs/catalog/blocks/waveform.mdx
index 4df9ee5d7e..17fc1f68a9 100644
--- a/docs/catalog/blocks/waveform.mdx
+++ b/docs/catalog/blocks/waveform.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Waveform
+
Equalizer bars in a blue to pink gradient pulse across the middle of the frame, like an audio visualizer. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `audio` `music` `visualizer` `bars`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/week-in-merges.mdx b/docs/catalog/blocks/week-in-merges.mdx
index 57bbdad818..85e4f01899 100644
--- a/docs/catalog/blocks/week-in-merges.mdx
+++ b/docs/catalog/blocks/week-in-merges.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Week in Merges
+
Each author's avatar bounces across their row at a speed set by how many pull requests they merged
+
+
-
+
+
+
## Add it to your video
@@ -577,6 +583,4 @@ Tagged `data` `chart` `ranking` `leaderboard`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/weight-wave.mdx b/docs/catalog/blocks/weight-wave.mdx
index d26c200203..b9f6d29ae0 100644
--- a/docs/catalog/blocks/weight-wave.mdx
+++ b/docs/catalog/blocks/weight-wave.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Weight Wave
+
A crest of thickness travels along a headline: each character swells from light to black and leans forward as the wave passes, driven by the wght and slnt variable-font axes rather than by transforms.
+
+
-
+
+
+
## Add it to your video
@@ -393,6 +399,4 @@ Tagged `typography` `kinetic-type` `title` `variable-font` `text`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/whip-pan.mdx b/docs/catalog/blocks/whip-pan.mdx
index abab65987c..f0a0138520 100644
--- a/docs/catalog/blocks/whip-pan.mdx
+++ b/docs/catalog/blocks/whip-pan.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Whip Pan
+
Shader transition simulating a fast camera whip pan
+
+
-
+
+
+
## Add it to your video
@@ -432,6 +438,4 @@ Tagged `transition` `shader`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/wireframe-portal-title.mdx b/docs/catalog/blocks/wireframe-portal-title.mdx
index 7bdea1635d..3c5314302b 100644
--- a/docs/catalog/blocks/wireframe-portal-title.mdx
+++ b/docs/catalog/blocks/wireframe-portal-title.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Wireframe Portal Title
+
A wireframe portal bursts open, the title comes through, then its letters swap into a second phrase.
+
+
-
+
+
+
## Add it to your video
@@ -1670,6 +1676,4 @@ Tagged `3d-motion` `title-card` `wireframe` `portal` `burst` `typography` `post-
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/world-map.mdx b/docs/catalog/blocks/world-map.mdx
index 1547fc7685..59be7ddb97 100644
--- a/docs/catalog/blocks/world-map.mdx
+++ b/docs/catalog/blocks/world-map.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
World Map
+
Animated world choropleth with country-by-country reveal, tooltip labels, and rotating globe inset — D3 Natural Earth projection
+
+
-
+
+
+
## Add it to your video
@@ -501,6 +507,4 @@ Tagged `data` `map` `geography` `world` `choropleth`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/worley-noise.mdx b/docs/catalog/blocks/worley-noise.mdx
index b79195749d..a4763363b4 100644
--- a/docs/catalog/blocks/worley-noise.mdx
+++ b/docs/catalog/blocks/worley-noise.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Worley Noise
+
A field of drifting cells, light at their centres and dark at their edges. A WebGPU shader from the Shaders library (shaders.com, MIT).
+
+
-
+
+
+
## Add it to your video
@@ -99,6 +105,4 @@ Tagged `webgpu` `webgpu-shader` `background` `texture` `noise` `cells` `monochro
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/x-post.mdx b/docs/catalog/blocks/x-post.mdx
index 160d84651c..4ec0fa29da 100644
--- a/docs/catalog/blocks/x-post.mdx
+++ b/docs/catalog/blocks/x-post.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
X Post Card
+
Animated X/Twitter post card overlay with engagement metrics
+
+
-
+
+
+
## Add it to your video
@@ -508,6 +514,4 @@ Tagged `social` `overlay` `twitter`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/yt-comment-card.mdx b/docs/catalog/blocks/yt-comment-card.mdx
index 0d284b94d3..5202bafa35 100644
--- a/docs/catalog/blocks/yt-comment-card.mdx
+++ b/docs/catalog/blocks/yt-comment-card.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Comment Cards
+
Social comments typing on over footage: avatar pop, username and time, per-character typewriter, likes row; image avatars or initials chips
+
+
-
+
+
+
## Add it to your video
@@ -384,6 +390,4 @@ Tagged `social` `comments` `creator` `overlay`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/yt-lcd-background.mdx b/docs/catalog/blocks/yt-lcd-background.mdx
index 0833b367ca..90c956756a 100644
--- a/docs/catalog/blocks/yt-lcd-background.mdx
+++ b/docs/catalog/blocks/yt-lcd-background.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Scanline Board Background
+
Textured paper board: scanlines with slow drift, optional pixel grid, static grain, and display text with a blur-focus entrance and chromatic-fringe title
+
+
-
+
+
+
## Add it to your video
@@ -372,6 +378,4 @@ Tagged `background` `texture` `creator`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/yt-logo-intro.mdx b/docs/catalog/blocks/yt-logo-intro.mdx
index 470ed87519..bb84272716 100644
--- a/docs/catalog/blocks/yt-logo-intro.mdx
+++ b/docs/catalog/blocks/yt-logo-intro.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Logo Intro Sequence
+
Logo stamp pops on a lined board, a kicker line gives way to the title with an accent arrow chip; seeded line distortion
+
+
-
+
+
+
## Add it to your video
@@ -317,6 +323,4 @@ Tagged `logo` `intro` `creator`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/yt-lower-third.mdx b/docs/catalog/blocks/yt-lower-third.mdx
index 85c5a57f38..b9f2ae7b22 100644
--- a/docs/catalog/blocks/yt-lower-third.mdx
+++ b/docs/catalog/blocks/yt-lower-third.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
YouTube Lower Third
+
Animated YouTube subscribe lower third with avatar and channel info
+
+
-
+
+
+
## Add it to your video
@@ -308,6 +314,4 @@ Tagged `social` `overlay` `youtube`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/yt-prism-title.mdx b/docs/catalog/blocks/yt-prism-title.mdx
index 59822f62da..a85af2fb91 100644
--- a/docs/catalog/blocks/yt-prism-title.mdx
+++ b/docs/catalog/blocks/yt-prism-title.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Chromatic Fringe Title
+
Display title on a transparent root: blur-focus entrance, red/blue fringe that settles then breathes, perspective bow, slow scale drift
+
+
-
+
+
+
## Add it to your video
@@ -270,6 +276,4 @@ Tagged `typography` `title-card` `creator`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/blocks/yt-vertical-fill.mdx b/docs/catalog/blocks/yt-vertical-fill.mdx
index 6a7108593c..1d9e3579b9 100644
--- a/docs/catalog/blocks/yt-vertical-fill.mdx
+++ b/docs/catalog/blocks/yt-vertical-fill.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Vertical Media Filler
+
Portrait media filling a widescreen frame via blurred-scale, mirror, or copy side fills; grid texture and foreground contrast lift (images inside the block; keep live footage in the host)
+
+
-
+
+
+
## Add it to your video
@@ -294,6 +300,4 @@ Tagged `placeholder` `vertical` `media`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/agent-cursor.mdx b/docs/catalog/components/agent-cursor.mdx
index b5505c1729..62f603745d 100644
--- a/docs/catalog/components/agent-cursor.mdx
+++ b/docs/catalog/components/agent-cursor.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Agent Cursor
+
An AI agent operating a UI: a cursor with an accent name label that types out each step, clicks each target with a small ring, and ends on a check.
+
+
-
+
+
+
## Paste it into your composition
@@ -475,6 +481,4 @@ Tagged `cursor` `motion-primitive` `agent` `ai` `status` `click`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/animated-bar-chart.mdx b/docs/catalog/components/animated-bar-chart.mdx
index 3fec6629c0..86f4d5cb34 100644
--- a/docs/catalog/components/animated-bar-chart.mdx
+++ b/docs/catalog/components/animated-bar-chart.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Animated Bar Chart
+
A compact data card with deterministic bar growth and value callouts.
+
+
-
+
+
+
## Paste it into your composition
@@ -153,6 +159,4 @@ Tagged `data`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/arc-motion-path.mdx b/docs/catalog/components/arc-motion-path.mdx
index e336aed913..6c8021e9dc 100644
--- a/docs/catalog/components/arc-motion-path.mdx
+++ b/docs/catalog/components/arc-motion-path.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Arc Motion Path
+
A GSAP MotionPath primitive that flies a callout along a curved arc with autorotation.
+
+
-
+
+
+
## Paste it into your composition
@@ -154,6 +160,4 @@ Tagged `video-primitive` `motionpath` `gsap-plugin` `hyperframes-native`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/ascii-render-pass.mdx b/docs/catalog/components/ascii-render-pass.mdx
index 26d8cf7047..e6858d4e27 100644
--- a/docs/catalog/components/ascii-render-pass.mdx
+++ b/docs/catalog/components/ascii-render-pass.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
ASCII Render Pass
+
A slotted scene renders as live ASCII: a canvas samples the source's luminance grid (rasterized once at mount) and draws glyphs from a density ramp charset; resolution steps coarse to fine as the piece resolves, then holds legible-fine.
+
+
-
+
+
+
## Paste it into your composition
@@ -563,6 +569,4 @@ Tagged `motion-primitive` `experiment` `texture` `ascii` `quantize`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/ascii-trail-reveal.mdx b/docs/catalog/components/ascii-trail-reveal.mdx
index 518910a09d..f4bef04215 100644
--- a/docs/catalog/components/ascii-trail-reveal.mdx
+++ b/docs/catalog/components/ascii-trail-reveal.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
ASCII Trail Reveal
+
An authored S-curve sweeps through a deterministic ASCII grid, flipping cells away to reveal a labeled panel.
+
+
-
+
+
+
## Paste it into your composition
@@ -456,6 +462,4 @@ Tagged `motion-primitive` `intro` `reveal` `ascii` `trail` `grid`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/aurora-drift.mdx b/docs/catalog/components/aurora-drift.mdx
index a30346d622..105621e8c2 100644
--- a/docs/catalog/components/aurora-drift.mdx
+++ b/docs/catalog/components/aurora-drift.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Aurora Drift
+
Three soft accent-derived aurora fields drift in an exact ambient loop over a deep base and faint vignette.
+
+
-
+
+
+
## Paste it into your composition
@@ -310,6 +316,4 @@ Tagged `motion-primitive` `background` `aurora` `gradient` `ambient` `loopable`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/avatar-cloud.mdx b/docs/catalog/components/avatar-cloud.mdx
index 7aa09befae..47fd367a2d 100644
--- a/docs/catalog/components/avatar-cloud.mdx
+++ b/docs/catalog/components/avatar-cloud.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Avatar Cloud
+
Lettermark avatars populate a loose elliptical cloud while fine SVG links draw between the community and its central proof label.
+
+
-
+
+
+
## Paste it into your composition
@@ -546,6 +552,4 @@ Tagged `effects` `avatars` `community` `network` `social-proof` `prove`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/avatar-group-hover.mdx b/docs/catalog/components/avatar-group-hover.mdx
index 22fedeccf3..1b3f855d63 100644
--- a/docs/catalog/components/avatar-group-hover.mdx
+++ b/docs/catalog/components/avatar-group-hover.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Avatar Group Hover
+
A distance-falloff avatar group lift with bouncy hover return
+
+
-
+
+
+
## Paste it into your composition
@@ -176,6 +182,4 @@ Tagged `video-primitive` `transition-primitive` `transitions-dev-port` `avatar`
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/badge-pop.mdx b/docs/catalog/components/badge-pop.mdx
index 1ffa016734..7fc0276269 100644
--- a/docs/catalog/components/badge-pop.mdx
+++ b/docs/catalog/components/badge-pop.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Badge Pop
+
A transitions.dev-inspired notification badge pop with elastic scale and count reveal
+
+
-
+
+
+
## Paste it into your composition
@@ -225,6 +231,4 @@ Tagged `video-primitive` `transition-primitive` `transitions-dev-port` `badge` `
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/beat-accent.mdx b/docs/catalog/components/beat-accent.mdx
index e8e964e6bd..787deb1ff9 100644
--- a/docs/catalog/components/beat-accent.mdx
+++ b/docs/catalog/components/beat-accent.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Beat Accent
+
A single music-hit sting: impact flash, micro scale-pulse on the subject, immediate decay.
+
+
-
+
+
+
## Paste it into your composition
@@ -400,6 +406,4 @@ Tagged `motion-primitive` `effects` `burst` `sting` `emphasize` `impact`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/beat-pulse-background.mdx b/docs/catalog/components/beat-pulse-background.mdx
index 579424595c..d0ad6dd9ab 100644
--- a/docs/catalog/components/beat-pulse-background.mdx
+++ b/docs/catalog/components/beat-pulse-background.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Beat Pulse Background
+
An accent-derived backdrop pulses its glow intensity and saturation on a deterministic, supplied beat grid.
+
+
-
+
+
+
## Paste it into your composition
@@ -284,6 +290,4 @@ Tagged `motion-primitive` `background` `beat` `pulse` `rhythmic` `reactive`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/beat-timeline.mdx b/docs/catalog/components/beat-timeline.mdx
index a875b86802..0379c5cd26 100644
--- a/docs/catalog/components/beat-timeline.mdx
+++ b/docs/catalog/components/beat-timeline.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Beat Timeline
+
A paused master-timeline orchestration spine that pins titled beat rows to evenly spaced named labels. Each row enters on its label, holds with the sequence, then exits with the group.
+
+
-
+
+
+
## Paste it into your composition
@@ -364,6 +370,4 @@ Tagged `orchestration` `transitions` `sequencing` `bridge` `timeline`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/before-after-wipe.mdx b/docs/catalog/components/before-after-wipe.mdx
index b4c709b924..19ff7ed085 100644
--- a/docs/catalog/components/before-after-wipe.mdx
+++ b/docs/catalog/components/before-after-wipe.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Before After Wipe
+
Two full-bleed content slots compare before and after states as a persistent divider wipes the after layer over the before layer and rests at a configurable split. Callers fill the named before/after slot panels; token-styled defaults render when a slot is left empty.
+
+
-
+
+
+
## Paste it into your composition
@@ -557,6 +563,4 @@ Tagged `prop` `ui-props` `compare` `comparison` `split-screen` `holdable` `befor
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/blur-in.mdx b/docs/catalog/components/blur-in.mdx
index 4920f3410c..a342c225b3 100644
--- a/docs/catalog/components/blur-in.mdx
+++ b/docs/catalog/components/blur-in.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Blur In
+
An Operator Black word-level content reveal that resolves its own text from controlled blur
+
+
-
+
+
+
## Paste it into your composition
@@ -316,6 +322,4 @@ Tagged `video-primitive` `blur-in` `text-effect`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/blur-out-up.mdx b/docs/catalog/components/blur-out-up.mdx
index 05e1821a31..beaaa57f8e 100644
--- a/docs/catalog/components/blur-out-up.mdx
+++ b/docs/catalog/components/blur-out-up.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Blur Out Up
+
Words arrive clean and depart upward with increasing blur for airy exits.
+
+
-
+
+
+
## Paste it into your composition
@@ -188,6 +194,4 @@ Tagged `motion-primitive` `typography`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/bottom-up-letters.mdx b/docs/catalog/components/bottom-up-letters.mdx
index 9c552ab3b2..87e66058fa 100644
--- a/docs/catalog/components/bottom-up-letters.mdx
+++ b/docs/catalog/components/bottom-up-letters.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Bottom Up Letters
+
Splits text into letters and reveals each glyph from below with deterministic staggered timing
+
+
-
+
+
+
## Paste it into your composition
@@ -182,6 +188,4 @@ Tagged `motion-primitive` `text` `letters` `reveal`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/browser-device-stage.mdx b/docs/catalog/components/browser-device-stage.mdx
index f50c97e187..7d68ac2507 100644
--- a/docs/catalog/components/browser-device-stage.mdx
+++ b/docs/catalog/components/browser-device-stage.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Browser Device Stage
+
A generic app surface in token-native device chrome (browser, window, or phone). The screen is a slot for caller img/video/HTML with a token-styled skeleton default; one settle entrance, a readable hold, and an optional screen swap.
+
+
-
+
+
+
## Paste it into your composition
@@ -726,6 +732,4 @@ Tagged `stage` `product-demo` `device` `browser` `phone` `slot` `chrome`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/camera-rig-depth-stack.mdx b/docs/catalog/components/camera-rig-depth-stack.mdx
index 4855e0b4be..55f9a49d23 100644
--- a/docs/catalog/components/camera-rig-depth-stack.mdx
+++ b/docs/catalog/components/camera-rig-depth-stack.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Camera Rig Depth Stack
+
A 3D camera-rig-style card stack with depth, parallax, and focus shift.
+
+
-
+
+
+
## Paste it into your composition
@@ -118,6 +124,4 @@ Tagged `advanced-motion` `hyperframes-native`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/camera-scan-gate.mdx b/docs/catalog/components/camera-scan-gate.mdx
index 670d1d5895..35dc228a31 100644
--- a/docs/catalog/components/camera-scan-gate.mdx
+++ b/docs/catalog/components/camera-scan-gate.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Camera Scan Gate
+
A camera and QR recognition moment with a viewfinder sweep, bracket lock, confirmation pulse, and verified next beat.
+
+
-
+
+
+
## Paste it into your composition
@@ -598,6 +604,4 @@ Tagged `prop` `ui-props` `camera` `qr` `scan` `recognition` `interaction` `demon
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/camera-shake.mdx b/docs/catalog/components/camera-shake.mdx
index 30ebea095d..f28c67b652 100644
--- a/docs/catalog/components/camera-shake.mdx
+++ b/docs/catalog/components/camera-shake.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Camera Shake
+
Procedural handheld, telephoto and rig camera shake for any wrapper: nine measured profiles with per-lens projection, closed-form and seek-safe
+
+
-
+
+
+
## Paste it into your composition
@@ -886,6 +892,4 @@ Tagged `camera` `shake` `handheld` `effect` `cinematic`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/caption-blend-difference.mdx b/docs/catalog/components/caption-blend-difference.mdx
index c47f389941..9db2d84d53 100644
--- a/docs/catalog/components/caption-blend-difference.mdx
+++ b/docs/catalog/components/caption-blend-difference.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Blend Difference
+
Auto-inverting text using mix-blend-mode: difference — flips between white and black per-pixel against the background
+
+
-
+
+
+
## Paste it into your composition
@@ -138,6 +144,4 @@ Tagged `text` `text-effect` `effect` `blend-mode` `contrast` `inversion`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/caption-camera-follow.mdx b/docs/catalog/components/caption-camera-follow.mdx
index 7c2e1114cf..04889dce6d 100644
--- a/docs/catalog/components/caption-camera-follow.mdx
+++ b/docs/catalog/components/caption-camera-follow.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Camera Follow Captions
+
One sentence written across a world far larger than the frame. Each word is sized against everything already written, so the block grows geometrically and the camera pulls back at a steady rate to keep landing the new word at the same size. Old words stay lit and simply become small.
+
+
-
+
+
+
## Paste it into your composition
@@ -507,6 +513,4 @@ Tagged `captions` `caption-style` `camera` `typography` `motion-primitive` `port
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/caption-clip-wipe.mdx b/docs/catalog/components/caption-clip-wipe.mdx
index 39baf9cd46..38ecee1203 100644
--- a/docs/catalog/components/caption-clip-wipe.mdx
+++ b/docs/catalog/components/caption-clip-wipe.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Clip Wipe
+
Left-to-right clip-path wipe reveal per word
+
+
-
+
+
+
## Paste it into your composition
@@ -280,6 +286,4 @@ Tagged `captions` `caption-style` `wipe` `clip-path` `reveal`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/caption-editorial-emphasis.mdx b/docs/catalog/components/caption-editorial-emphasis.mdx
index ce7ae0e495..8af2049e57 100644
--- a/docs/catalog/components/caption-editorial-emphasis.mdx
+++ b/docs/catalog/components/caption-editorial-emphasis.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Editorial Emphasis
+
Dual-font system with dramatic size contrast for emphasis words
+
+
-
+
+
+
## Paste it into your composition
@@ -466,6 +472,4 @@ Tagged `captions` `caption-style` `editorial` `typography` `emphasis`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/caption-emoji-pop.mdx b/docs/catalog/components/caption-emoji-pop.mdx
index 8fa6d093b0..082fe3250d 100644
--- a/docs/catalog/components/caption-emoji-pop.mdx
+++ b/docs/catalog/components/caption-emoji-pop.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Emoji Pop
+
Emoji integration with stroked text and horizontal squeeze entrance
+
+
-
+
+
+
## Paste it into your composition
@@ -521,6 +527,4 @@ Tagged `captions` `caption-style` `emoji` `social`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/caption-glitch-rgb.mdx b/docs/catalog/components/caption-glitch-rgb.mdx
index 37d1db7ec2..7fbb07d703 100644
--- a/docs/catalog/components/caption-glitch-rgb.mdx
+++ b/docs/catalog/components/caption-glitch-rgb.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Glitch RGB
+
RGB chromatic aberration with CRT scanline overlay
+
+
-
+
+
+
## Paste it into your composition
@@ -383,6 +389,4 @@ Tagged `captions` `caption-style` `glitch` `cyber` `tech`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/caption-gradient-fill.mdx b/docs/catalog/components/caption-gradient-fill.mdx
index 62b34c6036..9c9ca43e75 100644
--- a/docs/catalog/components/caption-gradient-fill.mdx
+++ b/docs/catalog/components/caption-gradient-fill.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Gradient Fill
+
Gradient-clipped text with elastic bounce entrance
+
+
-
+
+
+
## Paste it into your composition
@@ -273,6 +279,4 @@ Tagged `captions` `caption-style` `gradient` `colorful`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/caption-highlight.mdx b/docs/catalog/components/caption-highlight.mdx
index 45448e89de..59f2bfbbe7 100644
--- a/docs/catalog/components/caption-highlight.mdx
+++ b/docs/catalog/components/caption-highlight.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Highlight
+
Red background sweep behind each active word, TikTok-style
+
+
-
+
+
+
## Paste it into your composition
@@ -315,6 +321,4 @@ Tagged `captions` `caption-style` `highlight` `social` `tiktok`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/caption-kinetic-slam.mdx b/docs/catalog/components/caption-kinetic-slam.mdx
index a1405142c1..91ba89b5aa 100644
--- a/docs/catalog/components/caption-kinetic-slam.mdx
+++ b/docs/catalog/components/caption-kinetic-slam.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Kinetic Slam
+
Full-screen single-word display with alternating entrance directions
+
+
-
+
+
+
## Paste it into your composition
@@ -248,6 +254,4 @@ Tagged `captions` `caption-style` `kinetic` `typography` `slam`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/caption-matrix-decode.mdx b/docs/catalog/components/caption-matrix-decode.mdx
index 5361f55010..43e46ff481 100644
--- a/docs/catalog/components/caption-matrix-decode.mdx
+++ b/docs/catalog/components/caption-matrix-decode.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Matrix Decode
+
Character scramble animation before text reveal
+
+
-
+
+
+
## Paste it into your composition
@@ -308,6 +314,4 @@ Tagged `captions` `caption-style` `matrix` `scramble` `decode`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/caption-neon-accent.mdx b/docs/catalog/components/caption-neon-accent.mdx
index 2e5fca0de9..b807e0cdb8 100644
--- a/docs/catalog/components/caption-neon-accent.mdx
+++ b/docs/catalog/components/caption-neon-accent.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Neon Accent
+
Multi-color neon glow accents with wiggle drift animation
+
+
-
+
+
+
## Paste it into your composition
@@ -568,6 +574,4 @@ Tagged `captions` `caption-style` `neon` `glow` `accent`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/caption-neon-glow.mdx b/docs/catalog/components/caption-neon-glow.mdx
index 3a4fe4d6a2..ef0d6a92f0 100644
--- a/docs/catalog/components/caption-neon-glow.mdx
+++ b/docs/catalog/components/caption-neon-glow.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Neon Glow
+
Cyan and magenta neon glow with keyword accent colors
+
+
-
+
+
+
## Paste it into your composition
@@ -270,6 +276,4 @@ Tagged `captions` `caption-style` `neon` `glow` `gaming`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/caption-parallax-layers.mdx b/docs/catalog/components/caption-parallax-layers.mdx
index 2d993c9283..6249bba456 100644
--- a/docs/catalog/components/caption-parallax-layers.mdx
+++ b/docs/catalog/components/caption-parallax-layers.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Parallax Layers
+
Behind-subject 3D text layering with vertical stretch effect
+
+
-
+
+
+
## Paste it into your composition
@@ -409,6 +415,4 @@ Tagged `captions` `caption-style` `parallax` `3d` `depth`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/caption-particle-burst.mdx b/docs/catalog/components/caption-particle-burst.mdx
index ad5566c145..0830976a7b 100644
--- a/docs/catalog/components/caption-particle-burst.mdx
+++ b/docs/catalog/components/caption-particle-burst.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Particle Burst
+
Keyword words trigger colored particle explosions
+
+
-
+
+
+
## Paste it into your composition
@@ -350,6 +356,4 @@ Tagged `captions` `caption-style` `particles` `burst` `effects`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/caption-pill-karaoke.mdx b/docs/catalog/components/caption-pill-karaoke.mdx
index eba1b2040e..612076c2f7 100644
--- a/docs/catalog/components/caption-pill-karaoke.mdx
+++ b/docs/catalog/components/caption-pill-karaoke.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Pill Karaoke
+
Pill-shaped container with per-word karaoke color highlight
+
+
-
+
+
+
## Paste it into your composition
@@ -436,6 +442,4 @@ Tagged `captions` `caption-style` `karaoke` `pill`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/caption-texture.mdx b/docs/catalog/components/caption-texture.mdx
index 8cbfd487d9..5240f09ca8 100644
--- a/docs/catalog/components/caption-texture.mdx
+++ b/docs/catalog/components/caption-texture.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Texture
+
Flowing texture mask over large uppercase text — ships with 6 textures (lava, marble, metal, wood, concrete, rock), configurable via the texture variable
+
+
-
+
+
+
## Paste it into your composition
@@ -284,6 +290,4 @@ Tagged `captions` `caption-style` `texture` `mask`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/caption-weight-shift.mdx b/docs/catalog/components/caption-weight-shift.mdx
index e84261c891..facec68b20 100644
--- a/docs/catalog/components/caption-weight-shift.mdx
+++ b/docs/catalog/components/caption-weight-shift.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Weight Shift
+
Elegant font-weight transition between caption lines
+
+
-
+
+
+
## Paste it into your composition
@@ -451,6 +457,4 @@ Tagged `captions` `caption-style` `minimal` `typography`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/card-resize.mdx b/docs/catalog/components/card-resize.mdx
index e8d26532be..51a6d39a82 100644
--- a/docs/catalog/components/card-resize.mdx
+++ b/docs/catalog/components/card-resize.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Card Resize
+
A transitions.dev-inspired card resize primitive that expands a compact card into a detail panel
+
+
-
+
+
+
## Paste it into your composition
@@ -253,6 +259,4 @@ Tagged `video-primitive` `transition-primitive` `transitions-dev-port` `card` `l
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/caret-swap.mdx b/docs/catalog/components/caret-swap.mdx
index e0fa5dba7c..838a4ce497 100644
--- a/docs/catalog/components/caret-swap.mdx
+++ b/docs/catalog/components/caret-swap.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Caret Swap
+
A gradient caret expands over one phrase, collapses to the left, then types its replacement with a blinking caret.
+
+
-
+
+
+
## Paste it into your composition
@@ -437,6 +443,4 @@ Created by [Remocn](https://github.com/Remocn/remocn).
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/char-slam-explode.mdx b/docs/catalog/components/char-slam-explode.mdx
index 6e41888684..72f3f554bb 100644
--- a/docs/catalog/components/char-slam-explode.mdx
+++ b/docs/catalog/components/char-slam-explode.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Char Slam Explode
+
Headline glyphs hold in a deterministic scatter, then reassemble with an overshooting slam and a three-frame landing shake.
+
+
-
+
+
+
## Paste it into your composition
@@ -414,6 +420,4 @@ Tagged `motion-primitive` `typography` `text-treatment` `scatter` `slam` `impact
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/chart-story.mdx b/docs/catalog/components/chart-story.mdx
index 0902148bfd..6269517fc9 100644
--- a/docs/catalog/components/chart-story.mdx
+++ b/docs/catalog/components/chart-story.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Chart Story
+
One chart builds from data in reading order and lands the exact supplied values: staggered bars, a left-to-right line with area fill, a sweeping donut, or filling progress bars, with an accented value callout on the emphasized datum.
+
+
-
+
+
+
## Paste it into your composition
@@ -819,6 +825,4 @@ Tagged `motion-primitive` `proof` `stats` `chart` `bars` `line` `donut` `progres
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/chat-message.mdx b/docs/catalog/components/chat-message.mdx
index 37adf97444..77cb032aea 100644
--- a/docs/catalog/components/chat-message.mdx
+++ b/docs/catalog/components/chat-message.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Chat Message
+
One message arrives on the measured entry - scale 0.75, 0.12s, growing from its sender's corner. The type is an enum switched like marker-highlight's style: a received or sent bubble with a real tail, a large emoji row, an image, or a link card with title and domain. The atom that chat-thread builds conversations from
+
+
-
+
+
+
## Paste it into your composition
@@ -385,6 +391,4 @@ Created by Miao Yang.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/chat-thread.mdx b/docs/catalog/components/chat-thread.mdx
index d5d526a970..4ea99f5f38 100644
--- a/docs/catalog/components/chat-thread.mdx
+++ b/docs/catalog/components/chat-thread.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Chat Thread
+
The measured conversation as one mountable scene at full fidelity: status bar, back badge, avatar and name pill, bubbles with real iMessage tails, a Delivered receipt, large emoji rows, a media placeholder, a link card, and typing dots holding the beat. Every message picks its type by prefix - recv:/sent: text, emoji: a large row, img media, card:Title~domain a link card - and heights are measured at mount so any thread fits
+
+
-
+
+
+
## Paste it into your composition
@@ -743,6 +749,4 @@ Created by Miao Yang.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/chromatic-aberration-wipe.mdx b/docs/catalog/components/chromatic-aberration-wipe.mdx
index a5b48439a0..d4c973aa3c 100644
--- a/docs/catalog/components/chromatic-aberration-wipe.mdx
+++ b/docs/catalog/components/chromatic-aberration-wipe.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Chromatic Aberration Wipe
+
A fast slide wipe with RGB channel split on peak frames.
+
+
-
+
+
+
## Paste it into your composition
@@ -242,6 +248,4 @@ Tagged `video-primitive` `transition-primitive`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/code-terminal-run.mdx b/docs/catalog/components/code-terminal-run.mdx
index 4cd885dcc5..18b69aeb6d 100644
--- a/docs/catalog/components/code-terminal-run.mdx
+++ b/docs/catalog/components/code-terminal-run.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Code Terminal Run
+
A token-chrome terminal panel runs one command: the prompt line types deterministically behind an integer-cycle caret, executes after a beat, and output lines print one per cue before a fresh prompt appears.
+
+
-
+
+
+
## Paste it into your composition
@@ -638,6 +644,4 @@ Tagged `motion-primitive` `product-demo` `terminal` `typing` `deterministic`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/colorama-wipe.mdx b/docs/catalog/components/colorama-wipe.mdx
index 3e3e14ef3c..583c626008 100644
--- a/docs/catalog/components/colorama-wipe.mdx
+++ b/docs/catalog/components/colorama-wipe.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Colorama Wipe
+
Headline reveal through a feathered, leaning wipe front that is blurred and colour-mapped as it passes, then settles to clean type and wipes off again — the After Effects masked-text + Compound Blur + Colorama 'shiny wipe' as a deterministic canvas effect on any text element
+
+
-
+
+
+
## Paste it into your composition
@@ -413,6 +419,4 @@ Tagged `text` `reveal` `wipe` `colorama` `gradient` `blur` `headline` `saas`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/comparison-split.mdx b/docs/catalog/components/comparison-split.mdx
index 891ee9483f..a9efdc2cd3 100644
--- a/docs/catalog/components/comparison-split.mdx
+++ b/docs/catalog/components/comparison-split.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Comparison Split
+
Two full-bleed panels compare before and after states as a persistent divider wipes the vivid after layer over the muted before layer and rests at a configurable split.
+
+
-
+
+
+
## Paste it into your composition
@@ -526,6 +532,4 @@ Tagged `prop` `ui-props` `compare` `holdable` `before-after` `wipe`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/confetti.mdx b/docs/catalog/components/confetti.mdx
index 4780527bc8..9005dc032b 100644
--- a/docs/catalog/components/confetti.mdx
+++ b/docs/catalog/components/confetti.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Confetti
+
A deterministic celebration burst with seeded particles and gravity.
+
+
-
+
+
+
## Paste it into your composition
@@ -182,6 +188,4 @@ Tagged `effect`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/conic-progress-ring.mdx b/docs/catalog/components/conic-progress-ring.mdx
index 6332c7c688..ad98661f0b 100644
--- a/docs/catalog/components/conic-progress-ring.mdx
+++ b/docs/catalog/components/conic-progress-ring.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Conic Progress Ring
+
A token-driven conic progress ring whose angular fill and center count settle together from one registered percentage.
+
+
-
+
+
+
## Paste it into your composition
@@ -311,6 +317,4 @@ Tagged `data` `progress` `ring` `conic-gradient` `prove` `demonstrate`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/constellation-hub.mdx b/docs/catalog/components/constellation-hub.mdx
index 23c3230fa8..98350bc440 100644
--- a/docs/catalog/components/constellation-hub.mdx
+++ b/docs/catalog/components/constellation-hub.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Constellation Hub
+
Feature nodes brighten in narration order as real-length SVG connectors draw outward from a fixed central hub, then settle into one lockup.
+
+
-
+
+
+
## Paste it into your composition
@@ -505,6 +511,4 @@ Tagged `motion-primitive` `feature-tour` `hub` `nodes` `connector` `reveal`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/count-up.mdx b/docs/catalog/components/count-up.mdx
index b2c4dd43fe..74b6a6896b 100644
--- a/docs/catalog/components/count-up.mdx
+++ b/docs/catalog/components/count-up.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Count Up
+
A token-native stat counter that eases between values, counting up or down, and lands with a restrained scale pulse.
+
+
-
+
+
+
## Paste it into your composition
@@ -377,6 +383,4 @@ Tagged `motion-primitive` `proof` `stats` `counter` `number` `countdown` `determ
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/cta-close.mdx b/docs/catalog/components/cta-close.mdx
index 243283cf8b..f95c2e64d4 100644
--- a/docs/catalog/components/cta-close.mdx
+++ b/docs/catalog/components/cta-close.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
CTA Close
+
A display-scale action line lands per word and fills the frame with air, one generous CTA capsule pops beneath it with a single overshoot, and the finished close holds completely still.
+
+
-
+
+
+
## Paste it into your composition
@@ -341,6 +347,4 @@ Tagged `motion-primitive` `ui-props` `cta` `end-card` `close` `ask`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/cta-lockup.mdx b/docs/catalog/components/cta-lockup.mdx
index 9be73fc01c..cae356793b 100644
--- a/docs/catalog/components/cta-lockup.mdx
+++ b/docs/catalog/components/cta-lockup.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
CTA Lockup
+
A canonical closing lockup that reveals an action line, pops in an accent CTA capsule, settles supporting microcopy, and holds with confidence.
+
+
-
+
+
+
## Paste it into your composition
@@ -335,6 +341,4 @@ Tagged `motion-primitive` `ui-props` `cta` `end-card` `lockup` `ask`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/cursor-annotate.mdx b/docs/catalog/components/cursor-annotate.mdx
index cde9728647..d0423639b0 100644
--- a/docs/catalog/components/cursor-annotate.mdx
+++ b/docs/catalog/components/cursor-annotate.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Annotate Cursor
+
A marker pen glides onto the frame and hand-draws a loose loop, an underline, or an arrow around a region, the ink laid exactly under its nib, then lifts and leaves.
+
+
-
+
+
+
## Paste it into your composition
@@ -573,6 +579,4 @@ Tagged `cursor` `motion-primitive` `pen` `annotation` `draw-on` `highlight`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/cursor-context-menu.mdx b/docs/catalog/components/cursor-context-menu.mdx
index cf50aafaa3..48b3a92335 100644
--- a/docs/catalog/components/cursor-context-menu.mdx
+++ b/docs/catalog/components/cursor-context-menu.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Context Menu Cursor
+
A cursor right-clicks a file, a context menu blooms from its tip, the hover highlight tracks the item under it, and the chosen action plays out: duplicate, rename, move to trash, or a confirmation toast.
+
+
-
+
+
+
## Paste it into your composition
@@ -638,6 +644,4 @@ Tagged `cursor` `motion-primitive` `menu` `right-click` `desktop` `files`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/cursor-drag-drop.mdx b/docs/catalog/components/cursor-drag-drop.mdx
index 556aa13fcf..b75363e6d8 100644
--- a/docs/catalog/components/cursor-drag-drop.mdx
+++ b/docs/catalog/components/cursor-drag-drop.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Drag and Drop Cursor
+
A cursor grabs a task card, lifts and tilts it into its motion, carries it in lockstep to an empty column, drops it with a small settle, and the list closes the gap behind it.
+
+
-
+
+
+
## Paste it into your composition
@@ -540,6 +546,4 @@ Tagged `cursor` `motion-primitive` `drag` `drop` `kanban` `product-demo`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/cursor-glyph-trail.mdx b/docs/catalog/components/cursor-glyph-trail.mdx
index 93ec39b17f..8cb160e7cb 100644
--- a/docs/catalog/components/cursor-glyph-trail.mdx
+++ b/docs/catalog/components/cursor-glyph-trail.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Cursor Glyph Trail
+
A tutorial cursor path: on a settings screen the arrow clicks through three steps, leaving a dotted trail spaced evenly by distance and a numbered marker at each click; each step's trail fades as the next move begins.
+
+
-
+
+
+
## Paste it into your composition
@@ -730,6 +736,4 @@ Tagged `cursor` `motion-primitive` `demonstrate` `trail` `tutorial` `steps` `det
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/cursor-marquee-select.mdx b/docs/catalog/components/cursor-marquee-select.mdx
index 4393a86696..30953ae08a 100644
--- a/docs/catalog/components/cursor-marquee-select.mdx
+++ b/docs/catalog/components/cursor-marquee-select.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Marquee Select Cursor
+
A cursor drags a selection rectangle across a photo grid; each tile rings and pops a check the frame the rectangle touches it, while a pill counts the selection up.
+
+
-
+
+
+
## Paste it into your composition
@@ -1127,6 +1133,4 @@ Tagged `cursor` `motion-primitive` `select` `marquee` `grid` `product-demo`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/cursor-text-select.mdx b/docs/catalog/components/cursor-text-select.mdx
index 4fd17c8af8..1f39643e5e 100644
--- a/docs/catalog/components/cursor-text-select.mdx
+++ b/docs/catalog/components/cursor-text-select.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Text Select Cursor
+
An arrow turns into an I-beam over a document, drags a selection across a phrase character by character, raises a format toolbar, turns back into an arrow and clicks Bold.
+
+
-
+
+
+
## Paste it into your composition
@@ -517,6 +523,4 @@ Tagged `cursor` `motion-primitive` `text` `selection` `editor` `toolbar`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/cursor-zoom-follow.mdx b/docs/catalog/components/cursor-zoom-follow.mdx
index 0f3013f60d..548d748c92 100644
--- a/docs/catalog/components/cursor-zoom-follow.mdx
+++ b/docs/catalog/components/cursor-zoom-follow.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Zoom Follow Cursor
+
Screen-recording auto-zoom: the camera pushes in toward each upcoming click, trails the cursor on a smooth spring, marks every click with a press and a ring, then eases back out to the full screen as the cursor leaves.
+
+
-
+
+
+
## Paste it into your composition
@@ -802,6 +808,4 @@ Tagged `cursor` `camera` `zoom` `screen-recording` `click` `product-demo`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/curtain-reveal.mdx b/docs/catalog/components/curtain-reveal.mdx
index 4ac3eb7525..261b4d6009 100644
--- a/docs/catalog/components/curtain-reveal.mdx
+++ b/docs/catalog/components/curtain-reveal.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Curtain Reveal
+
Two pleated stage curtains gather outward from center, the way real velvet bunches at the tieback, revealing the stage underneath. A static pelmet frames the top; a soft spotlight can bloom in as they part.
+
+
-
+
+
+
## Paste it into your composition
@@ -453,6 +459,4 @@ Tagged `curtain` `stage reveal` `transition` `motion-primitive`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/cut-the-curve.mdx b/docs/catalog/components/cut-the-curve.mdx
index fe27e590e3..360288b16d 100644
--- a/docs/catalog/components/cut-the-curve.mdx
+++ b/docs/catalog/components/cut-the-curve.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Cut the Curve
+
A velocity-matched directional hard cut: the outgoing subject accelerates with power4.in, swaps at peak velocity, and the incoming subject continues in the same direction with power4.out.
+
+
-
+
+
+
## Paste it into your composition
@@ -578,6 +584,4 @@ Tagged `transition` `directional-cut` `velocity-match` `whip` `bridge` `demonstr
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/dart-cursor.mdx b/docs/catalog/components/dart-cursor.mdx
index def70b1f0b..786e60229b 100644
--- a/docs/catalog/components/dart-cursor.mdx
+++ b/docs/catalog/components/dart-cursor.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Dart Cursor
+
A bold outlined arrowhead that dives in from camera depth, flies nose-first with motion blur along its path, squashes on two clicks, and whips out of frame.
+
+
-
+
+
+
## Paste it into your composition
@@ -438,6 +444,4 @@ Tagged `cursor` `motion-primitive` `pointer` `click` `motion-blur` `depth`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/decline-chart.mdx b/docs/catalog/components/decline-chart.mdx
index a228c96289..80e6a4b92d 100644
--- a/docs/catalog/components/decline-chart.mdx
+++ b/docs/catalog/components/decline-chart.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Decline Chart
+
A metric line draws downward as its value counts down and the ambient background darkens in lockstep.
+
+
-
+
+
+
## Paste it into your composition
@@ -352,6 +358,4 @@ Tagged `motion-primitive` `data` `chart` `decline` `metric` `problem`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/device-frame-stage.mdx b/docs/catalog/components/device-frame-stage.mdx
index d6620aba86..5fa5e9c5a9 100644
--- a/docs/catalog/components/device-frame-stage.mdx
+++ b/docs/catalog/components/device-frame-stage.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Device Frame Stage
+
A phone or tablet mockup staged as a physical scene prop with a screen slot for arbitrary reconstructed UI, rising onto the stage, settling, and holding an idle float
+
+
-
+
+
+
## Paste it into your composition
@@ -542,6 +548,4 @@ Tagged `prop` `device` `mobile` `tablet` `ui-props` `holdable`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/directional-wipe.mdx b/docs/catalog/components/directional-wipe.mdx
index dccffc77c8..c71a984d49 100644
--- a/docs/catalog/components/directional-wipe.mdx
+++ b/docs/catalog/components/directional-wipe.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Directional Wipe
+
A directional scene push that slides one panel over another.
+
+
-
+
+
+
## Paste it into your composition
@@ -222,6 +228,4 @@ Tagged `transition-primitive`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/drift-hold.mdx b/docs/catalog/components/drift-hold.mdx
index a81fc210e1..a7e1cb0f3a 100644
--- a/docs/catalog/components/drift-hold.mdx
+++ b/docs/catalog/components/drift-hold.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Drift Hold
+
A centered content card stays subtly alive through loop-exact rotation, scale breathing, and a slow light sweep.
+
+
-
+
+
+
## Paste it into your composition
@@ -267,6 +273,4 @@ Tagged `motion-primitive` `camera` `ambient` `drift` `hold` `loopable`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/dynamic-grid.mdx b/docs/catalog/components/dynamic-grid.mdx
index e377a16677..0cdc1d7c48 100644
--- a/docs/catalog/components/dynamic-grid.mdx
+++ b/docs/catalog/components/dynamic-grid.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Dynamic Grid
+
A responsive animated grid background driven by CSS variables for SaaS, code, and data scenes
+
+
-
+
+
+
## Paste it into your composition
@@ -181,6 +187,4 @@ Tagged `video-primitive` `motion-primitive` `background` `grid` `ui`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/echo-smear.mdx b/docs/catalog/components/echo-smear.mdx
index 3d4450f248..9a851dfc89 100644
--- a/docs/catalog/components/echo-smear.mdx
+++ b/docs/catalog/components/echo-smear.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Echo Smear
+
Distance-adaptive streak — records each element's real trajectory (position, rotation, scale, opacity), then trails time-offset copies behind it in proportion to its speed, combined by brightest pixel, so fast moves smear and slow ones stay sharp; spinning edges stay smooth
+
+
-
+
+
+
## Paste it into your composition
@@ -662,6 +668,4 @@ Tagged `effect` `smear` `echo` `motion-blur` `velocity` `after-effects` `animati
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/echo-trail.mdx b/docs/catalog/components/echo-trail.mdx
index 6a0c45be7e..289721175d 100644
--- a/docs/catalog/components/echo-trail.mdx
+++ b/docs/catalog/components/echo-trail.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Echo Trail
+
A moving element renders with N ghosted copies of itself at t minus i times delta, opacity stepped down per ghost; one traversal, echoes collapsing into the settled element at rest.
+
+
-
+
+
+
## Paste it into your composition
@@ -431,6 +437,4 @@ Tagged `motion-primitive` `demonstrate` `trail` `onion-skin` `ghosts` `determini
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/extended-keyframe.mdx b/docs/catalog/components/extended-keyframe.mdx
index 66fe85cb9c..068212506d 100644
--- a/docs/catalog/components/extended-keyframe.mdx
+++ b/docs/catalog/components/extended-keyframe.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Extended Keyframe
+
The never-fully-lands arrival: an element covers most of its move in the first fifth of the duration and creeps the rest to the last frame, exits along its arrival vector, and carries shutter motion blur — from any side or by scale, one call per element, plus the ease on its own for any tween
+
+
-
+
+
+
## Paste it into your composition
@@ -618,6 +624,4 @@ Tagged `motion` `ease` `arrival` `kinetic-type` `text` `motion-blur` `after-effe
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/facet-morph.mdx b/docs/catalog/components/facet-morph.mdx
index d9ebde357b..1372fffbb3 100644
--- a/docs/catalog/components/facet-morph.mdx
+++ b/docs/catalog/components/facet-morph.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Facet Morph
+
A faceted low-poly mass of 36 triangles continuously reshapes between three authored silhouettes (blob, mark, badge) with per-facet flat shading that recomputes as the vertices move. Light reads from the upper left; lit facets lift toward a pale accent-tinted tone while turned-away facets fall toward near-black. One calm continuous morph, then a settled hold.
+
+
-
+
+
+
## Paste it into your composition
@@ -628,6 +634,4 @@ Tagged `motion-primitive` `intro` `morph` `low-poly` `svg` `deterministic`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/fade-through.mdx b/docs/catalog/components/fade-through.mdx
index 1321f912f7..e3261fc9ed 100644
--- a/docs/catalog/components/fade-through.mdx
+++ b/docs/catalog/components/fade-through.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Fade Through
+
A calm transition primitive that fades one layer out, passes through a wash, and reveals the next layer
+
+
-
+
+
+
## Paste it into your composition
@@ -173,6 +179,4 @@ Tagged `motion-primitive` `transition` `fade` `crossfade` `scene`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/filmed-screen.mdx b/docs/catalog/components/filmed-screen.mdx
index bf306f4863..b343433d36 100644
--- a/docs/catalog/components/filmed-screen.mdx
+++ b/docs/catalog/components/filmed-screen.mdx
@@ -7,11 +7,15 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Filmed Screen
+
Your scene, filmed off a screen: perspective, depth of field that follows an element you name, LED sub-pixels and per-shot colour grades. Shots glide into each other, focus racks between elements, and the focused element stays sharp.
+
+
-
+
+
+
Live preview needs the `chrome://flags/#canvas-draw-element` flag switched on.
@@ -763,6 +769,4 @@ Tagged `filmed` `screen` `monitor` `led` `camera` `depth-of-field` `html-in-canv
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/focus-blur-resolve.mdx b/docs/catalog/components/focus-blur-resolve.mdx
index 81cf525821..9e500d1ca4 100644
--- a/docs/catalog/components/focus-blur-resolve.mdx
+++ b/docs/catalog/components/focus-blur-resolve.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Focus Blur Resolve
+
A premium focus pull from heavy blur to crisp text, then a soft blur-out exit.
+
+
-
+
+
+
## Paste it into your composition
@@ -168,6 +174,4 @@ Tagged `motion-primitive` `typography`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/focus-rack.mdx b/docs/catalog/components/focus-rack.mdx
index 48e9348979..149fe6112d 100644
--- a/docs/catalog/components/focus-rack.mdx
+++ b/docs/catalog/components/focus-rack.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Focus Rack
+
Focus shifts once between two cards at different apparent depths through synchronized blur, dimming, scale, and parallax.
+
+
-
+
+
+
## Paste it into your composition
@@ -406,6 +412,4 @@ Tagged `motion-primitive` `camera` `focus` `focus-rack` `depth` `parallax` `emph
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/focus-swap.mdx b/docs/catalog/components/focus-swap.mdx
index a2bc5bbcc4..bb0a513b85 100644
--- a/docs/catalog/components/focus-swap.mdx
+++ b/docs/catalog/components/focus-swap.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Focus Swap
+
Moves attention between two side-by-side cards as one recedes with scale, blur, and dimming while the other advances to full focus.
+
+
-
+
+
+
## Paste it into your composition
@@ -357,6 +363,4 @@ Tagged `effect` `ui-props` `focus` `blur` `attention` `demonstrate`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/gesture-tap.mdx b/docs/catalog/components/gesture-tap.mdx
index 9041a80b8a..053d4f238f 100644
--- a/docs/catalog/components/gesture-tap.mdx
+++ b/docs/catalog/components/gesture-tap.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Gesture Tap
+
A contact circle taps a mobile pill button, releases it into a new labeled accent state, and lifts away.
+
+
-
+
+
+
## Paste it into your composition
@@ -480,6 +486,4 @@ Tagged `motion-primitive` `gesture` `tap` `interaction` `ui-props`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/gloss-sweep.mdx b/docs/catalog/components/gloss-sweep.mdx
index 8ad809279e..b5a372dfb9 100644
--- a/docs/catalog/components/gloss-sweep.mdx
+++ b/docs/catalog/components/gloss-sweep.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Gloss Sweep
+
A card lands with a restrained slam, catches one diagonal specular gloss, and holds perfectly still.
+
+
-
+
+
+
## Paste it into your composition
@@ -289,6 +295,4 @@ Tagged `motion-primitive` `celebration` `gloss` `card` `badge` `payoff`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/grade-split-reveal.mdx b/docs/catalog/components/grade-split-reveal.mdx
index 31c451f78a..50dcf2a306 100644
--- a/docs/catalog/components/grade-split-reveal.mdx
+++ b/docs/catalog/components/grade-split-reveal.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Grade Split Reveal
+
The same picture twice, one flat and one finished, with a hard edge sweeping between them. It stops in the middle long enough to compare, then commits and the graded look takes the frame. Both looks are real HyperFrames color grading run through the WebGL shader, so the preview and the render match.
+
+
-
+
+
+
## Paste it into your composition
@@ -523,6 +529,4 @@ Tagged `color-grading` `media` `compare` `reveal` `motion-primitive` `grade`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/grain-field.mdx b/docs/catalog/components/grain-field.mdx
index 725f6fcf1b..6500a85d4f 100644
--- a/docs/catalog/components/grain-field.mdx
+++ b/docs/catalog/components/grain-field.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Grain Field
+
A clearly visible accent-tinted dot field drifts over a subtle luminance gradient in an exact ambient loop.
+
+
-
+
+
+
## Paste it into your composition
@@ -245,6 +251,4 @@ Tagged `motion-primitive` `background` `grain` `dots` `texture` `ambient` `loopa
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/grain-overlay.mdx b/docs/catalog/components/grain-overlay.mdx
index 16b3b4eb04..56442f897d 100644
--- a/docs/catalog/components/grain-overlay.mdx
+++ b/docs/catalog/components/grain-overlay.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Grain Overlay
+
Animated film grain texture overlay using CSS keyframes — adds warmth and analog character to any composition
+
+
-
+
+
+
## Paste it into your composition
@@ -130,6 +136,4 @@ Tagged `texture` `grain` `overlay` `film`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/grid-card-assemble.mdx b/docs/catalog/components/grid-card-assemble.mdx
index 2894ddca12..538558a78c 100644
--- a/docs/catalog/components/grid-card-assemble.mdx
+++ b/docs/catalog/components/grid-card-assemble.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Grid Card Assemble
+
N capability cards (thin-line icon that draws on, mono label, optional muted body) stagger-assemble into a grid or vertical list with a fade plus short slide into slot, then hold perfectly still.
+
+
-
+
+
+
## Paste it into your composition
@@ -547,6 +553,4 @@ Tagged `motion-primitive` `layout` `grid` `list` `stagger` `assemble` `feature-t
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/grid-pixelate-wipe.mdx b/docs/catalog/components/grid-pixelate-wipe.mdx
index cb5771a18f..f29c3e1f26 100644
--- a/docs/catalog/components/grid-pixelate-wipe.mdx
+++ b/docs/catalog/components/grid-pixelate-wipe.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Grid Pixelate Wipe
+
Transition effect where the screen dissolves into a grid of squares that fade out with staggered timing — use between scenes
+
+
-
+
+
+
## Paste it into your composition
@@ -135,6 +141,4 @@ Tagged `transition` `wipe` `grid` `pixelate`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/halftone-dissolve.mdx b/docs/catalog/components/halftone-dissolve.mdx
index b21934d978..b8f6811459 100644
--- a/docs/catalog/components/halftone-dissolve.mdx
+++ b/docs/catalog/components/halftone-dissolve.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Halftone Dissolve
+
Scene A dissolves into scene B through a growing halftone dot field: accent ink dots pop onto a fixed grid smallest-first, each opens into a window onto B, until the windows merge and B fully replaces A.
+
+
-
+
+
+
## Paste it into your composition
@@ -498,6 +504,4 @@ Tagged `motion-primitive` `transition` `texture` `halftone` `dissolve`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/headline-slam.mdx b/docs/catalog/components/headline-slam.mdx
index bea7f69415..7de9a63267 100644
--- a/docs/catalog/components/headline-slam.mdx
+++ b/docs/catalog/components/headline-slam.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Headline Slam
+
A heavyweight headline scales down into frame, lands with a deterministic three-frame shake, holds with subtle drift, and whips upward on exit.
+
+
-
+
+
+
## Paste it into your composition
@@ -314,6 +320,4 @@ Tagged `motion-primitive` `typography` `headline` `slam` `impact` `exit`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/hw-arrow.mdx b/docs/catalog/components/hw-arrow.mdx
index 99dcd2a6f3..97864abd84 100644
--- a/docs/catalog/components/hw-arrow.mdx
+++ b/docs/catalog/components/hw-arrow.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Hand-Drawn Arrow
+
Wobbled draw-on arrow with straight, gentle, and swoop curve poses, a four-way stroke texture matrix (plain/soft/sharp/spray), and a travel-aligned head-arrival stretch pulse with spring recovery; boils while on screen
+
+
-
+
+
+
## Paste it into your composition
@@ -725,6 +731,4 @@ Tagged `handwritten` `annotation` `arrow` `overlay`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/hw-boil.mdx b/docs/catalog/components/hw-boil.mdx
index 1fa2b3f820..d6ac880c3e 100644
--- a/docs/catalog/components/hw-boil.mdx
+++ b/docs/catalog/components/hw-boil.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Hand-Drawn Boil
+
Hand-drawn jitter that re-poses every N frames, as seek-safe helpers: pose derives from quantized timeline time through a seeded hash; includes the shared onUpdate dispatcher, a wobbled-ellipse path generator, the boil pose control (off/calm/lively over the family-locked frameDrop), a curvature-adaptive pen-velocity ease, and the completed stroke matrix (plain/soft/sharp/spray — spray is index-seeded deterministic dots, no turbulence) with texture-safe draw-on
+
+
-
+
+
+
## Paste it into your composition
@@ -558,6 +564,4 @@ Tagged `handwritten` `effect` `annotation`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/hw-box-label.mdx b/docs/catalog/components/hw-box-label.mdx
index d31bf6b9ac..bd24632555 100644
--- a/docs/catalog/components/hw-box-label.mdx
+++ b/docs/catalog/components/hw-box-label.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Hand-Drawn Box Label
+
Wobbled rounded rectangle draws on — across the authored stroke matrix (plain/soft/sharp/spray) — or drops in and lands with a volume-true contact squash and bouncy spring recovery, with a handwritten label above or centered; boils
+
+
-
+
+
+
## Paste it into your composition
@@ -605,6 +611,4 @@ Tagged `handwritten` `annotation` `overlay`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/hw-callout-circle.mdx b/docs/catalog/components/hw-callout-circle.mdx
index bf8b4ae27c..69319974ff 100644
--- a/docs/catalog/components/hw-callout-circle.mdx
+++ b/docs/catalog/components/hw-callout-circle.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Scribble Callout Circle
+
Wobbled ellipse draws around a target with optional scribble fill and curved connector; the handwritten label pops in WITH momentum and the drawn shapes absorb the arrival with a volume-preserving contact squash; outline and connector take the family stroke matrix (plain/soft/sharp/spray); boils
+
+
-
+
+
+
## Paste it into your composition
@@ -677,6 +683,4 @@ Tagged `handwritten` `annotation` `callout` `overlay`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/hw-underline.mdx b/docs/catalog/components/hw-underline.mdx
index 74468d97c3..ab964ec539 100644
--- a/docs/catalog/components/hw-underline.mdx
+++ b/docs/catalog/components/hw-underline.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Squiggle Marks
+
Hand-drawn squiggle underline, double-pass strikethrough, and bracket marks that draw on
+
+
-
+
+
+
## Paste it into your composition
@@ -311,6 +317,4 @@ Tagged `handwritten` `annotation` `text-treatment`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/icon-morph-beat.mdx b/docs/catalog/components/icon-morph-beat.mdx
index eb06e7c4da..4c78d6b23c 100644
--- a/docs/catalog/components/icon-morph-beat.mdx
+++ b/docs/catalog/components/icon-morph-beat.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Icon Morph Beat
+
An icon morphs between authored state silhouettes, shifts to an accent color, and marks completion with one restrained pulse.
+
+
-
+
+
+
## Paste it into your composition
@@ -333,6 +339,4 @@ Tagged `motion-primitive` `product-demo` `icon` `morph` `state-change` `completi
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/icon-swap.mdx b/docs/catalog/components/icon-swap.mdx
index 33dafb94e1..5b0b74077c 100644
--- a/docs/catalog/components/icon-swap.mdx
+++ b/docs/catalog/components/icon-swap.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Icon Swap
+
A scale-and-blur icon swap primitive for toolbar and action state changes
+
+
-
+
+
+
## Paste it into your composition
@@ -190,6 +196,4 @@ Tagged `video-primitive` `transition-primitive` `transitions-dev-port` `icon` `s
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/ink-bleed-reveal.mdx b/docs/catalog/components/ink-bleed-reveal.mdx
index f55df6d2ca..3e84da1a1d 100644
--- a/docs/catalog/components/ink-bleed-reveal.mdx
+++ b/docs/catalog/components/ink-bleed-reveal.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Ink Bleed Reveal
+
Liquid ink blooms through paper under a gooey blur-plus-threshold filter, merges, then contracts as a crisp slotted mark resolves beneath it, with static seeded paper grain riding the result.
+
+
-
+
+
+
## Paste it into your composition
@@ -523,6 +529,4 @@ Tagged `motion-primitive` `texture` `reveal` `gooey` `svg-filter` `deterministic
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/inline-highlight.mdx b/docs/catalog/components/inline-highlight.mdx
index 9c04dc333b..8d4a0800e5 100644
--- a/docs/catalog/components/inline-highlight.mdx
+++ b/docs/catalog/components/inline-highlight.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Inline Highlight
+
A clean marker-style inline highlight that animates behind text using a CSS scale variable
+
+
-
+
+
+
## Paste it into your composition
@@ -169,6 +175,4 @@ Tagged `motion-primitive` `text` `highlight` `caption`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/input-feedback.mdx b/docs/catalog/components/input-feedback.mdx
index 7bd8379bd5..1e3350afd2 100644
--- a/docs/catalog/components/input-feedback.mdx
+++ b/docs/catalog/components/input-feedback.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Input Feedback
+
A transitions.dev-inspired input feedback primitive with shake, clear affordance, and success state
+
+
-
+
+
+
## Paste it into your composition
@@ -232,6 +238,4 @@ Tagged `transition-primitive` `transitions-dev-port` `input` `feedback`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/iris-reveal.mdx b/docs/catalog/components/iris-reveal.mdx
index c69d6b4303..d687973ed2 100644
--- a/docs/catalog/components/iris-reveal.mdx
+++ b/docs/catalog/components/iris-reveal.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Iris Reveal
+
A circle clip-path opens from an authored origin revealing state B over state A in one confident pass, then holds on B. Classic register dims and desaturates the before state so the after state lands in full color; a thin accent rim rides the iris edge. Callers fill the named before/after slot panels; token-styled defaults render when a slot is left empty.
+
+
-
+
+
+
## Paste it into your composition
@@ -557,6 +563,4 @@ Tagged `transition` `iris` `circle-reveal` `clip-path` `bridge` `slots`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/keyframe-scrub-stack.mdx b/docs/catalog/components/keyframe-scrub-stack.mdx
index b171d22b03..a609e0cdb9 100644
--- a/docs/catalog/components/keyframe-scrub-stack.mdx
+++ b/docs/catalog/components/keyframe-scrub-stack.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Keyframe Scrub Stack
+
A keyframe-sequenced stack of cards with offset timing and easing presets.
+
+
-
+
+
+
## Paste it into your composition
@@ -139,6 +145,4 @@ Tagged `advanced-motion` `anime-inspired` `hyperframes-native`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/kinetic-center-build.mdx b/docs/catalog/components/kinetic-center-build.mdx
index 9f6174821f..0d3273fd03 100644
--- a/docs/catalog/components/kinetic-center-build.mdx
+++ b/docs/catalog/components/kinetic-center-build.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Kinetic Center Build
+
Words enter from the right and push the growing phrase left until the final line locks centered.
+
+
-
+
+
+
## Paste it into your composition
@@ -364,6 +370,4 @@ Created by [Remocn](https://github.com/Remocn/remocn).
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/kinetic-type-swap.mdx b/docs/catalog/components/kinetic-type-swap.mdx
index ff15b7d692..8c3a4ca719 100644
--- a/docs/catalog/components/kinetic-type-swap.mdx
+++ b/docs/catalog/components/kinetic-type-swap.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Kinetic Type Swap
+
A held sentence keeps its fixed text in place while one widest-word masked slot rolls through alternatives and settles on the final option.
+
+
-
+
+
+
## Paste it into your composition
@@ -452,6 +458,4 @@ Tagged `motion-primitive` `text-effects` `kinetic-type` `word-swap` `reveal`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/light-sweep-pass.mdx b/docs/catalog/components/light-sweep-pass.mdx
index d86a37368a..12b384f0d4 100644
--- a/docs/catalog/components/light-sweep-pass.mdx
+++ b/docs/catalog/components/light-sweep-pass.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Light Sweep Pass
+
A traveling key light re-shades a slotted scene: a soft diagonal gradient band crosses the frame once while every per-element highlight and shadow shifts in lockstep (all driven by one --light-x property), then the light settles into a resting key. Quiet, expensive-feeling; the scene itself never moves. Callers fill the named scene slot; a token hero-and-cards default renders when it is left empty.
+
+
-
+
+
+
## Paste it into your composition
@@ -555,6 +561,4 @@ Tagged `motion-primitive` `overlay` `light` `sweep` `slots` `deterministic`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/line-by-line-slide.mdx b/docs/catalog/components/line-by-line-slide.mdx
index 9821acdb85..568bbff9f0 100644
--- a/docs/catalog/components/line-by-line-slide.mdx
+++ b/docs/catalog/components/line-by-line-slide.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Line-by-Line Slide
+
Each line enters from the left with staggered slide and exits to the right.
+
+
-
+
+
+
## Paste it into your composition
@@ -183,6 +189,4 @@ Tagged `motion-primitive` `typography`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/line-swap.mdx b/docs/catalog/components/line-swap.mdx
index 5058a6fed5..3e4eba3c76 100644
--- a/docs/catalog/components/line-swap.mdx
+++ b/docs/catalog/components/line-swap.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Line Swap
+
A masked full-line beat replacement: line A holds center then exits up through an overflow-hidden mask as line B enters bottom-up on the same beat, with an optional accent underline drawing beneath one word of line B.
+
+
-
+
+
+
## Paste it into your composition
@@ -388,6 +394,4 @@ Tagged `motion-primitive` `text-effects` `swap` `beat` `deterministic`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/locked-nucleus-orbit.mdx b/docs/catalog/components/locked-nucleus-orbit.mdx
index ce74e07ed5..7052e31033 100644
--- a/docs/catalog/components/locked-nucleus-orbit.mdx
+++ b/docs/catalog/components/locked-nucleus-orbit.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Locked Nucleus Orbit
+
A fixed center nucleus anchors deterministic satellite orbits that settle into a composed lockup.
+
+
-
+
+
+
## Paste it into your composition
@@ -429,6 +435,4 @@ Tagged `motion-primitive` `intro` `reveal` `orbit` `lockup` `deterministic`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/logo-brand-close.mdx b/docs/catalog/components/logo-brand-close.mdx
index 0d99b17435..cef64104f5 100644
--- a/docs/catalog/components/logo-brand-close.mdx
+++ b/docs/catalog/components/logo-brand-close.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Logo Brand Close
+
A display-scale wordmark cascades letter by letter into a centered lockup, the accent brand period lands last, an optional tagline and wide-tracked mono URL settle beneath, and the finished identity holds dead still to the end of the film.
+
+
-
+
+
+
## Paste it into your composition
@@ -445,6 +451,4 @@ Tagged `motion-primitive` `typography` `brand` `logo` `end-card` `close`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/logo-sting.mdx b/docs/catalog/components/logo-sting.mdx
index ccf0a4b5dd..f266e5766f 100644
--- a/docs/catalog/components/logo-sting.mdx
+++ b/docs/catalog/components/logo-sting.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Logo Sting
+
A wordmark slams into its final scale, fires one accent ring and one white impact frame, then holds completely still.
+
+
-
+
+
+
## Paste it into your composition
@@ -255,6 +261,4 @@ Tagged `motion-primitive` `brand` `logo` `sting` `impact` `reveal`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/logo-wall.mdx b/docs/catalog/components/logo-wall.mdx
index d0925961f9..f7b6f5a514 100644
--- a/docs/catalog/components/logo-wall.mdx
+++ b/docs/catalog/components/logo-wall.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Logo Wall
+
A trusted-by wall of placeholder lettermark logos that fades and scales into place with a deterministic per-cell stagger.
+
+
-
+
+
+
## Paste it into your composition
@@ -375,6 +381,4 @@ Tagged `data` `logos` `social-proof` `stagger` `prove`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/magnetic-cursor.mdx b/docs/catalog/components/magnetic-cursor.mdx
index e7ec9866f6..0ce8c63c22 100644
--- a/docs/catalog/components/magnetic-cursor.mdx
+++ b/docs/catalog/components/magnetic-cursor.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Magnetic Cursor
+
A soft dot pointer glides across an editor toolbar, is pulled into each button and morphs into its rounded hover plate while the icon leans toward it, presses one, and leaves as a dot.
+
+
-
+
+
+
## Paste it into your composition
@@ -504,6 +510,4 @@ Tagged `cursor` `motion-primitive` `pointer` `hover` `morph` `toolbar`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/marker-checklist-card.mdx b/docs/catalog/components/marker-checklist-card.mdx
index aaeec5a10b..4d328fa062 100644
--- a/docs/catalog/components/marker-checklist-card.mdx
+++ b/docs/catalog/components/marker-checklist-card.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Marker Checklist Card
+
A hand-lettered paper card: marker headline with an underline and a drawn ellipse around one word, then three checklist rows whose checks draw themselves on - typewriter labels, marker values. The paper-and-marker sibling of mk-specs-list's clean professional rows
+
+
-
+
+
+
## Paste it into your composition
@@ -391,6 +397,4 @@ Created by Miao Yang.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/marker-highlight.mdx b/docs/catalog/components/marker-highlight.mdx
index 55a3489aa4..99633a5d72 100644
--- a/docs/catalog/components/marker-highlight.mdx
+++ b/docs/catalog/components/marker-highlight.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Marker Highlight
+
Display text settles in, then one hand-drawn marker stroke (highlight, circle, underline, or scribble) draws over the emphasized word on cue.
+
+
-
+
+
+
## Paste it into your composition
@@ -444,6 +450,4 @@ Tagged `motion-primitive` `typography` `emphasis` `marker` `deterministic`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/match-cut.mdx b/docs/catalog/components/match-cut.mdx
index a63458d065..1c2f9c89eb 100644
--- a/docs/catalog/components/match-cut.mdx
+++ b/docs/catalog/components/match-cut.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Match Cut
+
A circle accelerates into a hard single-frame scene swap, matches the incoming circle exactly, and continues into a smaller resting pose.
+
+
-
+
+
+
## Paste it into your composition
@@ -385,6 +391,4 @@ Tagged `motion-primitive` `transition` `match-cut` `hard-cut` `continuity`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/matrix-decode.mdx b/docs/catalog/components/matrix-decode.mdx
index b3325dea51..1e5f17a647 100644
--- a/docs/catalog/components/matrix-decode.mdx
+++ b/docs/catalog/components/matrix-decode.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Matrix Decode
+
Random scramble resolves left-to-right into the target text.
+
+
-
+
+
+
## Paste it into your composition
@@ -206,6 +212,4 @@ Tagged `motion-primitive` `typography`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/menu-morph.mdx b/docs/catalog/components/menu-morph.mdx
index 1911dcc9ce..32edc1db1d 100644
--- a/docs/catalog/components/menu-morph.mdx
+++ b/docs/catalog/components/menu-morph.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Menu Morph
+
A transitions.dev-inspired hamburger and plus-menu morph primitive for compact action menus
+
+
-
+
+
+
## Paste it into your composition
@@ -238,6 +244,4 @@ Tagged `video-primitive` `transition-primitive` `transitions-dev-port` `menu` `m
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/mesh-gradient-bg.mdx b/docs/catalog/components/mesh-gradient-bg.mdx
index 53b2c06581..93cff167f1 100644
--- a/docs/catalog/components/mesh-gradient-bg.mdx
+++ b/docs/catalog/components/mesh-gradient-bg.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Mesh Gradient Background
+
A render-safe mesh gradient using animated radial layers.
+
+
-
+
+
+
## Paste it into your composition
@@ -156,6 +162,4 @@ Tagged `effect`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/micro-transitions.mdx b/docs/catalog/components/micro-transitions.mdx
index e33af392d9..4131eed6d7 100644
--- a/docs/catalog/components/micro-transitions.mdx
+++ b/docs/catalog/components/micro-transitions.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Micro Transitions
+
A transitions.dev-inspired pack of badge, dropdown, modal, tabs, tooltip, and success-check micro transitions
+
+
-
+
+
+
## Paste it into your composition
@@ -342,6 +348,4 @@ Tagged `transition-primitive` `motion-primitive` `transitions-dev-port` `ui` `tr
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/mk-emphasis-type.mdx b/docs/catalog/components/mk-emphasis-type.mdx
index 29ca8a15d8..7e2479fa5c 100644
--- a/docs/catalog/components/mk-emphasis-type.mdx
+++ b/docs/catalog/components/mk-emphasis-type.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Background Emphasis Type
+
Oversized low-contrast background word drifting slowly behind the subject — typography as texture
+
+
-
+
+
+
## Paste it into your composition
@@ -151,6 +157,4 @@ Tagged `typography` `text-treatment` `minimal`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/mk-usage-arc.mdx b/docs/catalog/components/mk-usage-arc.mdx
index 721a8769f2..bea9c044d6 100644
--- a/docs/catalog/components/mk-usage-arc.mdx
+++ b/docs/catalog/components/mk-usage-arc.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Hairline Arc Gauge
+
Thin circular gauge that draws on while its percentage counts up; one helper call drives both
+
+
-
+
+
+
## Paste it into your composition
@@ -213,6 +219,4 @@ Tagged `data-viz` `gauge` `minimal`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/modal-morph.mdx b/docs/catalog/components/modal-morph.mdx
index 238fa0853b..7320dfc04a 100644
--- a/docs/catalog/components/modal-morph.mdx
+++ b/docs/catalog/components/modal-morph.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Modal Morph
+
A small card expands into a full panel, shared-element style: both layouts measured once at mount, the container morphs by transform only (never width/height tweens) while keyed children counter-scale and re-flow onto their own measured targets as pure functions of time.
+
+
-
+
+
+
## Paste it into your composition
@@ -600,6 +606,4 @@ Tagged `motion-primitive` `structure` `flip` `shared-element` `modal` `determini
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/morph-swap.mdx b/docs/catalog/components/morph-swap.mdx
index abaa84d8df..12fe2a8ef0 100644
--- a/docs/catalog/components/morph-swap.mdx
+++ b/docs/catalog/components/morph-swap.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Morph Swap
+
Two slotted siblings stacked at one shared center: A holds, then condenses or reshapes into B on a shared 50% 50% transform origin. Condense shrink-fades A exactly as B scales up; reshape morphs the silhouette on scaleX/scaleY, never width or height tweens. Token card defaults render when a slot is left empty.
+
+
-
+
+
+
## Paste it into your composition
@@ -464,6 +470,4 @@ Tagged `transition` `morph` `swap` `condense` `reshape` `holdable` `slots`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/morph-text.mdx b/docs/catalog/components/morph-text.mdx
index 1ee47ce464..34709f5a38 100644
--- a/docs/catalog/components/morph-text.mdx
+++ b/docs/catalog/components/morph-text.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Morph Text
+
Gooey text morph — cycles through an editable word list using SVG threshold + GSAP-driven blur for a fluid, satisfying transition effect
+
+
-
+
+
+
## Paste it into your composition
@@ -288,6 +294,4 @@ Tagged `text` `text-effect` `typography` `morph` `gooey` `kinetic` `animation`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/motion-blur.mdx b/docs/catalog/components/motion-blur.mdx
index bac52f5dc0..f0093a8b5f 100644
--- a/docs/catalog/components/motion-blur.mdx
+++ b/docs/catalog/components/motion-blur.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Motion Blur
+
After Effects-style motion blur — integrates each element over a shutter window (shutter angle, phase, samples per frame) by sampling the GSAP timeline at sub-frame times and averaging equal-weight additive copies of the element along its real trajectory, so translation, scale, rotation, 3D rotation and skew all drive the smear
+
+
-
+
+
+
## Usage
@@ -865,6 +871,4 @@ Tagged `effect` `motion-blur` `shutter` `after-effects` `velocity` `animation`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/multi-device-splay.mdx b/docs/catalog/components/multi-device-splay.mdx
index 493ff2feb2..dfa3f34753 100644
--- a/docs/catalog/components/multi-device-splay.mdx
+++ b/docs/catalog/components/multi-device-splay.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Multi Device Splay
+
Phone, tablet, and desktop product mockups fan from a centered stack into a proud splayed arrangement with a subtle idle float.
+
+
-
+
+
+
## Paste it into your composition
@@ -801,6 +807,4 @@ Tagged `motion-primitive` `device` `phone` `tablet` `desktop` `splay`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/multiplayer-cursors.mdx b/docs/catalog/components/multiplayer-cursors.mdx
index 97af5b12dd..be72221dc6 100644
--- a/docs/catalog/components/multiplayer-cursors.mdx
+++ b/docs/catalog/components/multiplayer-cursors.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Multiplayer Cursors
+
Labeled collaborator cursors with token-derived colors and soft glows drift from spread positions into a shared center zone, proving live multiplayer presence.
+
+
-
+
+
+
## Paste it into your composition
@@ -504,6 +510,4 @@ Tagged `cursor` `pointer` `multiplayer` `collaboration` `presence` `loop` `prove
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/native-notification-pop.mdx b/docs/catalog/components/native-notification-pop.mdx
index 8e13c599a1..e711b9673d 100644
--- a/docs/catalog/components/native-notification-pop.mdx
+++ b/docs/catalog/components/native-notification-pop.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Native Notification Pop
+
One system-faithful notification banner (iOS or macOS) drops in over any scene on an accurate interruptible spring: fast arrival, soft overshoot, settled mass, backdrop blur, app dot, title, one body line. Holds; tucks away only via exit.
+
+
-
+
+
+
## Paste it into your composition
@@ -536,6 +542,4 @@ Tagged `motion-primitive` `product-demo` `overlay` `notification` `spring`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/notes-typing.mdx b/docs/catalog/components/notes-typing.mdx
index df77f9db2d..38eb52601a 100644
--- a/docs/catalog/components/notes-typing.mdx
+++ b/docs/catalog/components/notes-typing.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Notes Typing
+
The notes-app confession as a mountable scene: a bold title, then body lines typed character by character on the measured human keystroke rhythm, the caret riding every landed character and jumping down at each paragraph. For a bare prompt line use typed-prompt; for an even mechanical reveal use typewriter
+
+
-
+
+
+
## Paste it into your composition
@@ -425,6 +431,4 @@ Created by Miao Yang.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/notification-pileup.mdx b/docs/catalog/components/notification-pileup.mdx
index 723dabc9ea..b7343f664b 100644
--- a/docs/catalog/components/notification-pileup.mdx
+++ b/docs/catalog/components/notification-pileup.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Notification Pileup
+
Mobile notification cards arrive faster and faster, each new alert pushing the existing stack downward into a dense, anxious tower.
+
+
-
+
+
+
## Paste it into your composition
@@ -539,6 +545,4 @@ Tagged `notification` `mobile` `ui-props` `overload` `pileup` `loop` `agitate`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/notification-stack.mdx b/docs/catalog/components/notification-stack.mdx
index 7ea0d276b4..f8d11c4a44 100644
--- a/docs/catalog/components/notification-stack.mdx
+++ b/docs/catalog/components/notification-stack.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Notification Stack
+
1 to 5 token notification cards slide-settle into a vertical stack on cues, newest on top; one card grows slightly and brightens as the focus while the rest dim by position.
+
+
-
+
+
+
## Paste it into your composition
@@ -466,6 +472,4 @@ Tagged `motion-primitive` `product-demo` `notification` `stack` `stagger`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/number-pop-in.mdx b/docs/catalog/components/number-pop-in.mdx
index 80f43fcbf3..d8f6f9e274 100644
--- a/docs/catalog/components/number-pop-in.mdx
+++ b/docs/catalog/components/number-pop-in.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Number Pop In
+
A transitions.dev-inspired digit pop-in with blur, lift, and staggered value reveal
+
+
-
+
+
+
## Paste it into your composition
@@ -198,6 +204,4 @@ Tagged `video-primitive` `transition-primitive` `transitions-dev-port` `number`
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/number-wheel.mdx b/docs/catalog/components/number-wheel.mdx
index 2c5d90ae2a..33cd394a1f 100644
--- a/docs/catalog/components/number-wheel.mdx
+++ b/docs/catalog/components/number-wheel.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Number Wheel
+
A rolling digit counter primitive for metrics, prices, counts, and scoreboards
+
+
-
+
+
+
## Paste it into your composition
@@ -199,6 +205,4 @@ Tagged `video-primitive` `motion-primitive` `number` `counter` `data`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/offset-path-traveler.mdx b/docs/catalog/components/offset-path-traveler.mdx
index 6cbf739759..175abbe9b9 100644
--- a/docs/catalog/components/offset-path-traveler.mdx
+++ b/docs/catalog/components/offset-path-traveler.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Offset Path Traveler
+
A slotted traveler follows an authored path with tangent rotation, curved entry, and curved exit.
+
+
-
+
+
+
## Paste it into your composition
@@ -363,6 +369,4 @@ Tagged `motion-primitive` `product-demo` `path` `traveler` `auto-rotate`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/onboarding-stepper-flow.mdx b/docs/catalog/components/onboarding-stepper-flow.mdx
index 95602e46d6..e3be56457a 100644
--- a/docs/catalog/components/onboarding-stepper-flow.mdx
+++ b/docs/catalog/components/onboarding-stepper-flow.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Onboarding Stepper Flow
+
A composed onboarding flow with milestone rail, active step card, and next-action button
+
+
-
+
+
+
## Paste it into your composition
@@ -147,6 +153,4 @@ Tagged `ui-flow` `onboarding` `stepper`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/ordered-dither-pass.mdx b/docs/catalog/components/ordered-dither-pass.mdx
index 71785f3970..fea315129b 100644
--- a/docs/catalog/components/ordered-dither-pass.mdx
+++ b/docs/catalog/components/ordered-dither-pass.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Ordered Dither Pass
+
Bayer-matrix ordered dithering quantizes a slotted scene (rasterized once at mount): the image emerges from pure 2-tone noise to clean, or dissolves the reverse. Stateless per frame, never error diffusion.
+
+
-
+
+
+
## Paste it into your composition
@@ -589,6 +595,4 @@ Tagged `motion-primitive` `experiment` `texture` `dither` `transition` `quantize
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/outline-draw.mdx b/docs/catalog/components/outline-draw.mdx
index 462f9de988..2ffa77162a 100644
--- a/docs/catalog/components/outline-draw.mdx
+++ b/docs/catalog/components/outline-draw.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Outline Draw
+
A rounded outline that proves a callout by drawing clockwise as a hollow conic-gradient border with a clean closure.
+
+
-
+
+
+
## Paste it into your composition
@@ -249,6 +255,4 @@ Tagged `motion-primitive` `effects` `outline` `border` `mask` `proof`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/oversized-cursor.mdx b/docs/catalog/components/oversized-cursor.mdx
index b5fe66ae19..77d0b3c399 100644
--- a/docs/catalog/components/oversized-cursor.mdx
+++ b/docs/catalog/components/oversized-cursor.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Oversized Cursor
+
The look-here pointer for a video: the macOS arrow at 3.5x its normal size lands its tip on one control, clicks it on, settles just below it so the result stays in view, then exits off-screen
+
+
-
+
+
+
## Paste it into your composition
@@ -466,6 +472,4 @@ Tagged `cursor` `motion-primitive` `actor` `pointer` `interaction`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/overwhelm-surround.mdx b/docs/catalog/components/overwhelm-surround.mdx
index efd4e5241e..57e5fb149a 100644
--- a/docs/catalog/components/overwhelm-surround.mdx
+++ b/docs/catalog/components/overwhelm-surround.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Overwhelm Surround
+
Tasks, tabs, pings, and notification bubbles accelerate inward around a calm central subject, turning overload into visible spatial pressure.
+
+
-
+
+
+
## Paste it into your composition
@@ -450,6 +456,4 @@ Tagged `effects` `agitate` `overwhelm` `pressure` `notifications`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/page-slide.mdx b/docs/catalog/components/page-slide.mdx
index bb6e48d928..d84948c29b 100644
--- a/docs/catalog/components/page-slide.mdx
+++ b/docs/catalog/components/page-slide.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Page Slide
+
A transitions.dev-inspired page slide primitive with outgoing and incoming panels
+
+
-
+
+
+
## Paste it into your composition
@@ -198,6 +204,4 @@ Tagged `video-primitive` `transition-primitive` `transitions-dev-port` `page` `s
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/pan-stations.mdx b/docs/catalog/components/pan-stations.mdx
index 30efb1acb0..44c971eda5 100644
--- a/docs/catalog/components/pan-stations.mdx
+++ b/docs/catalog/components/pan-stations.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Pan Stations
+
A lateral camera move across a continuous row of labeled feature stations, with a steady dwell at each stop before the next pan.
+
+
-
+
+
+
## Paste it into your composition
@@ -440,6 +446,4 @@ Tagged `camera` `pan` `stations` `features` `exhibit` `agitate` `cross-shelved`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/panel-reveal.mdx b/docs/catalog/components/panel-reveal.mdx
index 7cd31f5e4a..a8b2253053 100644
--- a/docs/catalog/components/panel-reveal.mdx
+++ b/docs/catalog/components/panel-reveal.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Panel Reveal
+
A panel reveal primitive with height expansion and content fade
+
+
-
+
+
+
## Paste it into your composition
@@ -211,6 +217,4 @@ Tagged `transition-primitive` `transitions-dev-port` `panel` `reveal`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/paper-collage-reveal.mdx b/docs/catalog/components/paper-collage-reveal.mdx
index 30ab9be3ec..8d5784d7ef 100644
--- a/docs/catalog/components/paper-collage-reveal.mdx
+++ b/docs/catalog/components/paper-collage-reveal.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Paper Collage Reveal
+
A scrapbook patchwork of torn paper scraps, each with its own texture and tilt, flutters away in a staggered scatter to reveal the content underneath.
+
+
-
+
+
+
## Paste it into your composition
@@ -517,6 +523,4 @@ Tagged `collage` `scrapbook` `torn paper` `reveal` `transition` `motion-primitiv
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/parallax-device-dive.mdx b/docs/catalog/components/parallax-device-dive.mdx
index 306b1a8aa5..29a2214430 100644
--- a/docs/catalog/components/parallax-device-dive.mdx
+++ b/docs/catalog/components/parallax-device-dive.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Parallax Device Dive
+
A canonical phone rises into view before the camera pushes through its screen and layered app UI expands to fill the frame.
+
+
-
+
+
+
## Paste it into your composition
@@ -526,6 +532,4 @@ Tagged `motion-primitive` `camera` `device` `phone` `parallax` `transition`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/parallax-unzoom.mdx b/docs/catalog/components/parallax-unzoom.mdx
index 373f46a93f..293976096f 100644
--- a/docs/catalog/components/parallax-unzoom.mdx
+++ b/docs/catalog/components/parallax-unzoom.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Parallax Unzoom
+
Reveal transition — focus card scales down from full frame as siblings parallax in to form a grid (reverse of parallax-zoom)
+
+
-
+
+
+
## Paste it into your composition
@@ -158,6 +164,4 @@ Tagged `transition` `reveal` `unzoom` `parallax` `grid` `hero`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/parallax-zoom.mdx b/docs/catalog/components/parallax-zoom.mdx
index bae5f2dec8..81b4791145 100644
--- a/docs/catalog/components/parallax-zoom.mdx
+++ b/docs/catalog/components/parallax-zoom.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Parallax Zoom
+
Center card scales up to fill the frame while siblings parallax outward — inspired by the eBay Playbook hero transition
+
+
-
+
+
+
## Paste it into your composition
@@ -154,6 +160,4 @@ Tagged `transition` `zoom` `parallax` `grid` `hero`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/particle-image-reveal.mdx b/docs/catalog/components/particle-image-reveal.mdx
index 38e0d596fc..012f5b133a 100644
--- a/docs/catalog/components/particle-image-reveal.mdx
+++ b/docs/catalog/components/particle-image-reveal.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Particle Image Reveal
+
A seeded deterministic particle field converges and settles while a slotted image reveals beneath it, the trail thinning until the image holds clean.
+
+
-
+
+
+
## Paste it into your composition
@@ -469,6 +475,4 @@ Tagged `motion-primitive` `intros-reveals` `particles` `reveal` `canvas` `determ
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/particle-text-dissolve.mdx b/docs/catalog/components/particle-text-dissolve.mdx
index 892d1ddd2d..6f1fd93544 100644
--- a/docs/catalog/components/particle-text-dissolve.mdx
+++ b/docs/catalog/components/particle-text-dissolve.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Particle Text Dissolve
+
Text assembles from a seeded particle cloud (or dissolves into it): per-particle targets sampled once from the rendered text bitmap at mount, table-driven particles, zero per-particle tweens, one onUpdate painter.
+
+
-
+
+
+
## Paste it into your composition
@@ -492,6 +498,4 @@ Tagged `motion-primitive` `text-effects` `particles` `canvas` `deterministic` `e
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/pendulum-swing.mdx b/docs/catalog/components/pendulum-swing.mdx
index 477cc719eb..915be0315b 100644
--- a/docs/catalog/components/pendulum-swing.mdx
+++ b/docs/catalog/components/pendulum-swing.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Pendulum Swing
+
Content hangs from a fixed pivot and swings into rest with gravity-damped oscillation, like a hanging sign settling on its hook.
+
+
-
+
+
+
## Paste it into your composition
@@ -208,6 +214,4 @@ Tagged `motion-primitive` `physics` `swing` `settle` `reveal`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/per-word-crossfade.mdx b/docs/catalog/components/per-word-crossfade.mdx
index 6830a20af6..61b7c6a9ff 100644
--- a/docs/catalog/components/per-word-crossfade.mdx
+++ b/docs/catalog/components/per-word-crossfade.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Per-Word Crossfade
+
Words gently fade into place with a short vertical drift for calm keynote rhythm.
+
+
-
+
+
+
## Paste it into your composition
@@ -193,6 +199,4 @@ Tagged `motion-primitive` `typography`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/per-word-rise.mdx b/docs/catalog/components/per-word-rise.mdx
index d45dff5d5d..bffd96a012 100644
--- a/docs/catalog/components/per-word-rise.mdx
+++ b/docs/catalog/components/per-word-rise.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Per Word Rise
+
Words or characters rise into place in a controlled blur-to-sharp cascade, settle softly on landing, and hold still until the cut (optional fade or up exit).
+
+
-
+
+
+
## Paste it into your composition
@@ -394,6 +400,4 @@ Tagged `motion-primitive` `text-effects` `typography` `stagger` `reveal`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/perspective-marquee.mdx b/docs/catalog/components/perspective-marquee.mdx
index 0d40800d31..5cc0a0d46e 100644
--- a/docs/catalog/components/perspective-marquee.mdx
+++ b/docs/catalog/components/perspective-marquee.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Perspective Marquee
+
A 3D tilted marquee with depth feel as items roll toward the horizon.
+
+
-
+
+
+
## Paste it into your composition
@@ -214,6 +220,4 @@ Tagged `motion-primitive` `typography`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/physical-exit.mdx b/docs/catalog/components/physical-exit.mdx
index c66a17b041..f1572ffc18 100644
--- a/docs/catalog/components/physical-exit.mdx
+++ b/docs/catalog/components/physical-exit.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Physical Exit
+
A card exits with physical momentum in toss, drop, or slide mode, carrying acceleration and rotation through the final offscreen pose without fading.
+
+
-
+
+
+
## Paste it into your composition
@@ -323,6 +329,4 @@ Tagged `motion-primitive` `exit` `momentum` `toss` `drop` `slide`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/press-ripple.mdx b/docs/catalog/components/press-ripple.mdx
index 1c38b2dd21..b23eb07a20 100644
--- a/docs/catalog/components/press-ripple.mdx
+++ b/docs/catalog/components/press-ripple.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Press Ripple
+
A cursor decel-arrives from off-stage, lands slightly off-center on a caller-positioned target, compresses with it in lockstep, releases with two small click rings while the label swaps to a check, then exits off-stage while the confirmed state holds.
+
+
-
+
+
+
## Paste it into your composition
@@ -515,6 +521,4 @@ Tagged `cursor` `motion-primitive` `product-demo` `press` `ripple` `payoff`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/pull-back-reveal.mdx b/docs/catalog/components/pull-back-reveal.mdx
index fcb54e2941..4895c84af4 100644
--- a/docs/catalog/components/pull-back-reveal.mdx
+++ b/docs/catalog/components/pull-back-reveal.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Pull Back Reveal
+
A tight stat detail holds, then one decelerating camera pull-back reveals the headline and supporting cards that recontextualize it.
+
+
-
+
+
+
## Paste it into your composition
@@ -412,6 +418,4 @@ Tagged `motion-primitive` `camera` `pull-back` `reveal` `recontextualize`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/pull-to-refresh.mdx b/docs/catalog/components/pull-to-refresh.mdx
index 09ffe24c3a..808b810a08 100644
--- a/docs/catalog/components/pull-to-refresh.mdx
+++ b/docs/catalog/components/pull-to-refresh.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Pull to Refresh
+
A mobile list pulls through nonlinear rubber-band resistance, arms at a threshold, commits to a bounded loading indicator, then snaps exactly back to rest.
+
+
-
+
+
+
## Paste it into your composition
@@ -754,6 +760,4 @@ Tagged `pointer` `pointers` `mobile` `gesture` `interaction` `refresh` `demonstr
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/push-in.mdx b/docs/catalog/components/push-in.mdx
index d0ef3cb996..cbe2d76590 100644
--- a/docs/catalog/components/push-in.mdx
+++ b/docs/catalog/components/push-in.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Push In
+
A centered headline gains focus through one slow, continuous camera push and a gentle fade out.
+
+
-
+
+
+
## Paste it into your composition
@@ -253,6 +259,4 @@ Tagged `motion-primitive` `camera` `push-in` `focus` `emphasize` `holdable`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/radial-surround.mdx b/docs/catalog/components/radial-surround.mdx
index e6466fe4b0..6edcee07b7 100644
--- a/docs/catalog/components/radial-surround.mdx
+++ b/docs/catalog/components/radial-surround.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Radial Surround
+
Labeled hairline chips assemble around a centered subject on an elliptical ring, then optionally converge inward with a subtle edge dim. The center never moves: surrounded, not zoomed.
+
+
-
+
+
+
## Paste it into your composition
@@ -511,6 +517,4 @@ Tagged `motion-primitive` `problem-setup` `radial` `ring` `surround` `converge`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/rgb-glitch-text.mdx b/docs/catalog/components/rgb-glitch-text.mdx
index 12ecc6f09d..df53f11aeb 100644
--- a/docs/catalog/components/rgb-glitch-text.mdx
+++ b/docs/catalog/components/rgb-glitch-text.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
RGB Glitch Text
+
RGB-offset text copies jitter briefly for a controlled glitch window.
+
+
-
+
+
+
## Paste it into your composition
@@ -187,6 +193,4 @@ Tagged `motion-primitive` `typography`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/rubber-band-bumper.mdx b/docs/catalog/components/rubber-band-bumper.mdx
index fea9636bc6..121d5af4ba 100644
--- a/docs/catalog/components/rubber-band-bumper.mdx
+++ b/docs/catalog/components/rubber-band-bumper.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Rubber Band Bumper
+
An outgoing panel pulls against increasing resistance, holds at tension, then snaps past an edge with overshoot as the incoming panel settles behind it.
+
+
-
+
+
+
## Paste it into your composition
@@ -406,6 +412,4 @@ Tagged `motion-primitive` `transition` `rubber-band` `resistance` `overshoot`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/scan-band.mdx b/docs/catalog/components/scan-band.mdx
index 89dd41fb78..f87c43878a 100644
--- a/docs/catalog/components/scan-band.mdx
+++ b/docs/catalog/components/scan-band.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Scan Band
+
A diagonal distortion band sweeps once across a clean wordmark, revealing clipped red and cyan offsets only inside the moving band.
+
+
-
+
+
+
## Paste it into your composition
@@ -291,6 +297,4 @@ Tagged `motion-primitive` `typography` `scan` `chromatic` `distortion` `wordmark
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/scramble-reveal.mdx b/docs/catalog/components/scramble-reveal.mdx
index 313c1e5c96..760355de77 100644
--- a/docs/catalog/components/scramble-reveal.mdx
+++ b/docs/catalog/components/scramble-reveal.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Scramble Reveal
+
A deterministic hacker-style text reveal that cycles fixed glyph rows and locks the target string from left to right.
+
+
-
+
+
+
## Paste it into your composition
@@ -366,6 +372,4 @@ Tagged `motion-primitive` `text-effects` `scramble` `reveal` `deterministic`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/screen-flow-carousel.mdx b/docs/catalog/components/screen-flow-carousel.mdx
index 5496f9d8cb..d3547e0330 100644
--- a/docs/catalog/components/screen-flow-carousel.mdx
+++ b/docs/catalog/components/screen-flow-carousel.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Screen Flow Carousel
+
Two to five app screens ride a horizontal rail: one primary at center, neighbors receded, advancing on cues with a velocity-matched throw and a smooth long-tail catch while a mono caption swaps with each advance. Screens are slots with token skeleton defaults.
+
+
-
+
+
+
## Paste it into your composition
@@ -654,6 +660,4 @@ Tagged `product-demo` `feature-tour` `carousel` `rail` `slot` `screens`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/scroll-camera-story.mdx b/docs/catalog/components/scroll-camera-story.mdx
index e912d64b96..81d2f21099 100644
--- a/docs/catalog/components/scroll-camera-story.mdx
+++ b/docs/catalog/components/scroll-camera-story.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Scroll Camera Story
+
A compressed forced-scroll cinematic pass: a tall scene of slotted sections travels past the camera top to bottom, depth layers parallax at different rates, each section rises as the camera reaches it, and the pass decelerates into a held final section.
+
+
-
+
+
+
## Paste it into your composition
@@ -883,6 +889,4 @@ Tagged `camera` `scroll` `parallax` `story` `sections` `slot` `servo`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/scroll-feed.mdx b/docs/catalog/components/scroll-feed.mdx
index e440f6f911..9618c74356 100644
--- a/docs/catalog/components/scroll-feed.mdx
+++ b/docs/catalog/components/scroll-feed.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Scroll Feed
+
A loop-friendly column of varied skeleton post cards scrolls upward with subtle motion trails and an agitated pace.
+
+
-
+
+
+
## Paste it into your composition
@@ -474,6 +480,4 @@ Tagged `motion-primitive` `effects` `scroll` `feed` `loop` `agitation`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/segmentation-flood.mdx b/docs/catalog/components/segmentation-flood.mdx
index 51be76f03c..a2e5c5e485 100644
--- a/docs/catalog/components/segmentation-flood.mdx
+++ b/docs/catalog/components/segmentation-flood.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Segmentation Flood
+
Machine-vision read of a slotted subject: translucent accent segmentation masks flood on in quantized scanline steps, each region gets a thin bracket and mono label chip, a deterministic 2-frame HUD flicker rides the pass, then the labeled read settles clean.
+
+
-
+
+
+
## Paste it into your composition
@@ -595,6 +601,4 @@ Tagged `motion-primitive` `product-demo` `ai` `hud` `canvas` `deterministic` `ex
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/separator.mdx b/docs/catalog/components/separator.mdx
index 23b63e4e1b..22ea461d59 100644
--- a/docs/catalog/components/separator.mdx
+++ b/docs/catalog/components/separator.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Separator
+
A one-pixel structural separator with horizontal and vertical variants plus a seek-safe progress reveal
+
+
-
+
+
+
## Paste it into your composition
@@ -315,6 +321,4 @@ Tagged `video-primitive` `separator` `layout`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/settings-toggle-flow.mdx b/docs/catalog/components/settings-toggle-flow.mdx
index f4e2ad697a..ea3a2e410c 100644
--- a/docs/catalog/components/settings-toggle-flow.mdx
+++ b/docs/catalog/components/settings-toggle-flow.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Settings Toggle Flow
+
A composed settings flow with preference rows, toggle switches, and active-state feedback
+
+
-
+
+
+
## Paste it into your composition
@@ -143,6 +149,4 @@ Tagged `ui-flow` `settings` `toggle`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/shared-axis-y.mdx b/docs/catalog/components/shared-axis-y.mdx
index 253505a5e9..62332644ea 100644
--- a/docs/catalog/components/shared-axis-y.mdx
+++ b/docs/catalog/components/shared-axis-y.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Shared Axis Y
+
Per-word vertical shared-axis transition for sharp editorial swaps.
+
+
-
+
+
+
## Paste it into your composition
@@ -175,6 +181,4 @@ Tagged `motion-primitive` `typography`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/shared-axis-z.mdx b/docs/catalog/components/shared-axis-z.mdx
index d0630bb615..485194ee3e 100644
--- a/docs/catalog/components/shared-axis-z.mdx
+++ b/docs/catalog/components/shared-axis-z.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Shared Axis Z
+
Scale-based shared-axis transition for focus shifts and context depth.
+
+
-
+
+
+
## Paste it into your composition
@@ -174,6 +180,4 @@ Tagged `motion-primitive` `typography`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/sheet-spring-up.mdx b/docs/catalog/components/sheet-spring-up.mdx
index e1c56095a7..1eab2c94b0 100644
--- a/docs/catalog/components/sheet-spring-up.mdx
+++ b/docs/catalog/components/sheet-spring-up.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Sheet Spring-Up
+
A bottom sheet rushes up from below the frame on a real spring sampled frame by frame from reference footage, overshooting its resting place and settling back without an approximated ease
+
+
-
+
+
+
## Paste it into your composition
@@ -322,6 +328,4 @@ Created by Miao Yang.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/shimmer-sweep.mdx b/docs/catalog/components/shimmer-sweep.mdx
index 35933b0a87..96edcc1170 100644
--- a/docs/catalog/components/shimmer-sweep.mdx
+++ b/docs/catalog/components/shimmer-sweep.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Shimmer Sweep
+
Animated light sweep across text or elements using a CSS gradient mask — ideal for AI accents and premium reveals
+
+
-
+
+
+
## Paste it into your composition
@@ -121,6 +127,4 @@ Tagged `text` `shimmer` `highlight` `effect`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/shutter-slam.mdx b/docs/catalog/components/shutter-slam.mdx
index e621cab4ac..f4ad18fe65 100644
--- a/docs/catalog/components/shutter-slam.mdx
+++ b/docs/catalog/components/shutter-slam.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Shutter Slam
+
One word thrown through six single-property beats under integrated shutter blur — two translate slams, a scale punch, then a full turn about each axis — on the measured easing of the After Effects export the shutter model was fitted to
+
+
-
+
+
+
## Paste it into your composition
@@ -923,6 +929,4 @@ Tagged `effect` `motion-blur` `shutter` `after-effects` `slam` `animation`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/signup-flow.mdx b/docs/catalog/components/signup-flow.mdx
index 81553b38d1..8d958fcd1e 100644
--- a/docs/catalog/components/signup-flow.mdx
+++ b/docs/catalog/components/signup-flow.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Signup Flow
+
A composed signup flow with social action, email field, password field, and submit button
+
+
-
+
+
+
## Paste it into your composition
@@ -135,6 +141,4 @@ Tagged `ui-flow` `signup` `form`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/skeleton-reveal.mdx b/docs/catalog/components/skeleton-reveal.mdx
index ec378bed9c..838731dc11 100644
--- a/docs/catalog/components/skeleton-reveal.mdx
+++ b/docs/catalog/components/skeleton-reveal.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Skeleton Reveal
+
A skeleton loader transition that pulses, then cross-fades into content
+
+
-
+
+
+
## Paste it into your composition
@@ -207,6 +213,4 @@ Tagged `video-primitive` `transition-primitive` `transitions-dev-port` `skeleton
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/slit-scan-reveal.mdx b/docs/catalog/components/slit-scan-reveal.mdx
index aaedd07733..2a94349af2 100644
--- a/docs/catalog/components/slit-scan-reveal.mdx
+++ b/docs/catalog/components/slit-scan-reveal.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Slit Scan Reveal
+
The frame's rows sample an authored subject at offset times: a canvas painter draws row slices of one pure position function evaluated at t minus offset(row), smearing arrival through time until the offsets collapse to zero and the mark holds coherent.
+
+
-
+
+
+
## Paste it into your composition
@@ -410,6 +416,4 @@ Tagged `motion-primitive` `time` `slit-scan` `canvas` `deterministic` `experimen
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/slot-machine-roll.mdx b/docs/catalog/components/slot-machine-roll.mdx
index 11aacc4ee9..b64341a963 100644
--- a/docs/catalog/components/slot-machine-roll.mdx
+++ b/docs/catalog/components/slot-machine-roll.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Slot Machine Roll
+
A vertical reel scrolls characters from one value to another.
+
+
-
+
+
+
## Paste it into your composition
@@ -214,6 +220,4 @@ Tagged `video-primitive` `motion-primitive` `typography`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/social-proof-card.mdx b/docs/catalog/components/social-proof-card.mdx
index ecc7137cc1..4cebeace3d 100644
--- a/docs/catalog/components/social-proof-card.mdx
+++ b/docs/catalog/components/social-proof-card.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Social Proof Card
+
The app-store close as one mountable scene: wordmark, five stars, a proof line, three feature icons and a CTA capsule build in a quiet stagger and hold - measured from reference ad footage. For an animated star sweep use star-rating-fill; for a quote card use testimonial-proof-card; for a bare lockup use cta-lockup
+
+
-
+
+
+
## Paste it into your composition
@@ -311,6 +317,4 @@ Created by Miao Yang.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/soft-blob-touch.mdx b/docs/catalog/components/soft-blob-touch.mdx
index ff6166a0a9..aabca86be4 100644
--- a/docs/catalog/components/soft-blob-touch.mdx
+++ b/docs/catalog/components/soft-blob-touch.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Soft Blob Touch
+
A granular soft blob idles with slow internal drift; a scripted touch dot decel-arrives, the blob deforms toward it with an attraction bulge, then recovers with a velocity-preserving spring. No hard edges anywhere.
+
+
-
+
+
+
## Paste it into your composition
@@ -594,6 +600,4 @@ Tagged `motion-primitive` `product-demo` `material` `blob` `touch` `grain`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/soft-blur-in.mdx b/docs/catalog/components/soft-blur-in.mdx
index 8637910135..485418ae41 100644
--- a/docs/catalog/components/soft-blur-in.mdx
+++ b/docs/catalog/components/soft-blur-in.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Soft Blur In
+
A soft opacity, blur, and lift reveal for headlines, captions, and product UI callouts
+
+
-
+
+
+
## Paste it into your composition
@@ -160,6 +166,4 @@ Tagged `motion-primitive` `text` `reveal` `blur`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/split-tilt-cards.mdx b/docs/catalog/components/split-tilt-cards.mdx
index 0c46f1940f..df112c9e15 100644
--- a/docs/catalog/components/split-tilt-cards.mdx
+++ b/docs/catalog/components/split-tilt-cards.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Split Tilt Cards
+
Two equal-weight cards arrive from opposite wings with mirrored rotateY book-open tilts under one shared perspective, pill badges spring-pop at each inner edge, and the pair holds with a barely-there phase-opposed idle float. Card bodies are content slots with token skeleton defaults.
+
+
-
+
+
+
## Paste it into your composition
@@ -650,6 +656,4 @@ Tagged `motion-primitive` `layout` `compare` `holdable` `book-open` `tilt` `slot
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/spotlight-card.mdx b/docs/catalog/components/spotlight-card.mdx
index 238c2f0d0e..cab4b71b15 100644
--- a/docs/catalog/components/spotlight-card.mdx
+++ b/docs/catalog/components/spotlight-card.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Spotlight Card
+
A card with a scripted cursor spotlight and lit border.
+
+
-
+
+
+
## Paste it into your composition
@@ -160,6 +166,4 @@ Tagged `effect`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/spring-pop.mdx b/docs/catalog/components/spring-pop.mdx
index aa759cb91b..79a35919f8 100644
--- a/docs/catalog/components/spring-pop.mdx
+++ b/docs/catalog/components/spring-pop.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Spring Pop
+
A badge pops in from a visible near-rest scale, overshoots full size once, and settles cleanly.
+
+
-
+
+
+
## Paste it into your composition
@@ -271,6 +277,4 @@ Tagged `motion-primitive` `effects` `spring` `overshoot` `pop` `reveal`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/spring-stack-shuffle.mdx b/docs/catalog/components/spring-stack-shuffle.mdx
index 10284fa80b..6a7e91295f 100644
--- a/docs/catalog/components/spring-stack-shuffle.mdx
+++ b/docs/catalog/components/spring-stack-shuffle.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Spring Stack Shuffle
+
A stack of 3 to 5 slotted cards reshuffles on cues: the back card throws over the top and lands at the front with real mass, the rest compress and resettle; cues that land mid-flight redirect the moving cards with velocity preserved.
+
+
-
+
+
+
## Paste it into your composition
@@ -684,6 +690,4 @@ Tagged `motion-primitive` `product-demo` `physics` `stack` `interruptible-spring
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/stagger-cascade.mdx b/docs/catalog/components/stagger-cascade.mdx
index 02ff437cf1..964396aae3 100644
--- a/docs/catalog/components/stagger-cascade.mdx
+++ b/docs/catalog/components/stagger-cascade.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Stagger Cascade
+
A responsive grid of tile cards that fades and travels into place with an evenly spaced per-item GSAP stagger. The ordered cascade is the only visual mechanic.
+
+
-
+
+
+
## Paste it into your composition
@@ -334,6 +340,4 @@ Tagged `effects` `grid` `stagger` `entrance` `exhibit`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/stagger-lattice.mdx b/docs/catalog/components/stagger-lattice.mdx
index 046b970ec1..7fa857de2b 100644
--- a/docs/catalog/components/stagger-lattice.mdx
+++ b/docs/catalog/components/stagger-lattice.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Stagger Lattice
+
A staggered grid reveal inspired by Anime.js v4 stagger utilities, implemented with GSAP for HyperFrames.
+
+
-
+
+
+
## Paste it into your composition
@@ -150,6 +156,4 @@ Tagged `advanced-motion` `anime-inspired` `hyperframes-native`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/staggered-fade-up.mdx b/docs/catalog/components/staggered-fade-up.mdx
index 77a3684473..1aad9d5392 100644
--- a/docs/catalog/components/staggered-fade-up.mdx
+++ b/docs/catalog/components/staggered-fade-up.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Staggered Fade Up
+
Words fade in and slide up one after another with configurable delay.
+
+
-
+
+
+
## Paste it into your composition
@@ -198,6 +204,4 @@ Tagged `video-primitive` `motion-primitive` `typography`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/star-rating-fill.mdx b/docs/catalog/components/star-rating-fill.mdx
index 9068eee140..893c9411e6 100644
--- a/docs/catalog/components/star-rating-fill.mdx
+++ b/docs/catalog/components/star-rating-fill.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Star Rating Fill
+
A token-driven star row whose colored layer sweeps to a rating, preserves the fractional final star, and can count the value in sync.
+
+
-
+
+
+
## Paste it into your composition
@@ -374,6 +380,4 @@ Tagged `data` `rating` `stars` `fractional` `fill` `prove`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/state-chip-rail.mdx b/docs/catalog/components/state-chip-rail.mdx
index dea39f8bd1..7f86d48def 100644
--- a/docs/catalog/components/state-chip-rail.mdx
+++ b/docs/catalog/components/state-chip-rail.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
State Chip Rail
+
A rail of mono status chips advances a seek-safe data-state snap machine on a cue schedule: active chip ink on surface, done chips dim, pending chips hollow, optional badges pop beside one state.
+
+
-
+
+
+
## Paste it into your composition
@@ -442,6 +448,4 @@ Tagged `motion-primitive` `product-demo` `state-machine` `status` `chips` `rail`
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/sticky-mock-swap.mdx b/docs/catalog/components/sticky-mock-swap.mdx
index f8292cd192..7e35f06896 100644
--- a/docs/catalog/components/sticky-mock-swap.mdx
+++ b/docs/catalog/components/sticky-mock-swap.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Sticky Mock Swap
+
A pinned product mock cross-fades through accent-tinted feature states while matching captions rise, hold, and exit beside it.
+
+
-
+
+
+
## Paste it into your composition
@@ -540,6 +546,4 @@ Tagged `motion-primitive` `product-demo` `sticky` `mock` `crossfade` `feature-to
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/stitched-text-draw.mdx b/docs/catalog/components/stitched-text-draw.mdx
index 7abac7de9b..ddd0e66d78 100644
--- a/docs/catalog/components/stitched-text-draw.mdx
+++ b/docs/catalog/components/stitched-text-draw.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Stitched Text Draw
+
Text drawn as thread stitches: a single-stroke display alphabet draws via attribute-driven dashoffset with stitch-tuned dash patterns, seeded angle jitter, needle-hole dots, a leading needle, and a thread-tail overshoot per letter.
+
+
-
+
+
+
## Paste it into your composition
@@ -942,6 +948,4 @@ Tagged `motion-primitive` `experiment` `type` `craft` `stitch` `deterministic`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/stop-motion-cadence.mdx b/docs/catalog/components/stop-motion-cadence.mdx
index d41060de92..4f196287a5 100644
--- a/docs/catalog/components/stop-motion-cadence.mdx
+++ b/docs/catalog/components/stop-motion-cadence.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Stop Motion Cadence
+
The stepped-time law as a demo primitive: one driver quantizes timeline time to floor(t * fps) / fps and feeds ALL motion; four token paper-cut shapes throw-and-land with squash on hits, 2-frame boil jitter seeded per step, and sparkle accents living exactly 2 to 3 frames.
+
+
-
+
+
+
## Paste it into your composition
@@ -544,6 +550,4 @@ Tagged `motion-primitive` `time-law` `stop-motion` `stepped` `boil` `determinist
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/store-badge-lockup.mdx b/docs/catalog/components/store-badge-lockup.mdx
index bc7919ee0b..bb7b1ce74f 100644
--- a/docs/catalog/components/store-badge-lockup.mdx
+++ b/docs/catalog/components/store-badge-lockup.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Store Badge Lockup
+
Settles a short headline above equal-size App Store and Google Play badges as a token-driven mobile end-card call to action.
+
+
-
+
+
+
## Paste it into your composition
@@ -381,6 +387,4 @@ Tagged `prop` `ui-props` `mobile` `store-badges` `cta` `ask`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/streaming-text.mdx b/docs/catalog/components/streaming-text.mdx
index cee9c9589c..d2105f7cca 100644
--- a/docs/catalog/components/streaming-text.mdx
+++ b/docs/catalog/components/streaming-text.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Streaming Text
+
Words arrive the way an AI answer streams - in uneven bursts on a measured token rhythm, each word landing grey and inking to full colour - rather than the even tick of a typewriter
+
+
-
+
+
+
## Paste it into your composition
@@ -333,6 +339,4 @@ Created by Miao Yang.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/strikethrough-replace.mdx b/docs/catalog/components/strikethrough-replace.mdx
index db271fa72f..96bd0750e1 100644
--- a/docs/catalog/components/strikethrough-replace.mdx
+++ b/docs/catalog/components/strikethrough-replace.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Strikethrough Replace
+
Draw a strike line across old text, then reveal the replacement.
+
+
-
+
+
+
## Paste it into your composition
@@ -191,6 +197,4 @@ Tagged `motion-primitive` `typography`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/success-check.mdx b/docs/catalog/components/success-check.mdx
index 3f921159d8..7eae9ac19a 100644
--- a/docs/catalog/components/success-check.mdx
+++ b/docs/catalog/components/success-check.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Success Check
+
A success check primitive with ring pop, path draw, and subtle rotate blur
+
+
-
+
+
+
## Paste it into your composition
@@ -213,6 +219,4 @@ Tagged `video-primitive` `transition-primitive` `transitions-dev-port` `success`
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/svg-line-draw-loader.mdx b/docs/catalog/components/svg-line-draw-loader.mdx
index 1794d78640..213c82fd32 100644
--- a/docs/catalog/components/svg-line-draw-loader.mdx
+++ b/docs/catalog/components/svg-line-draw-loader.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
SVG Line Draw Loader
+
An Anime.js-style path drawing loader implemented as a seekable GSAP stroke timeline.
+
+
-
+
+
+
## Paste it into your composition
@@ -130,6 +136,4 @@ Tagged `video-primitive` `advanced-motion` `anime-inspired` `hyperframes-native`
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/svg-mask-reveal.mdx b/docs/catalog/components/svg-mask-reveal.mdx
index c6bc3f4740..71bc39ebcf 100644
--- a/docs/catalog/components/svg-mask-reveal.mdx
+++ b/docs/catalog/components/svg-mask-reveal.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
SVG Mask Reveal
+
A soft token-colored sweep reveals media only through an editable SVG wordmark mask.
+
+
-
+
+
+
## Paste it into your composition
@@ -392,6 +398,4 @@ Tagged `effect` `svg` `mask` `wordmark` `reveal` `exhibit`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/svg-stroke-trace.mdx b/docs/catalog/components/svg-stroke-trace.mdx
index cb660169a8..1113318fe7 100644
--- a/docs/catalog/components/svg-stroke-trace.mdx
+++ b/docs/catalog/components/svg-stroke-trace.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
SVG Stroke Trace
+
An authored SVG path draws from its measured length, holds with subtle drift, and optionally fills when the path is closed.
+
+
-
+
+
+
## Paste it into your composition
@@ -306,6 +312,4 @@ Tagged `motion-primitive` `intro` `reveal` `svg` `stroke` `line-draw`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/swipe-rail.mdx b/docs/catalog/components/swipe-rail.mdx
index cc7660e3de..eeff120788 100644
--- a/docs/catalog/components/swipe-rail.mdx
+++ b/docs/catalog/components/swipe-rail.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Swipe Rail
+
A contact circle leads a horizontal card rail through a fast drag, momentum carry, and settled snap to the next card.
+
+
-
+
+
+
## Paste it into your composition
@@ -434,6 +440,4 @@ Tagged `motion-primitive` `interaction` `gesture` `swipe` `cards` `rail`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/tabs-slide-indicator.mdx b/docs/catalog/components/tabs-slide-indicator.mdx
index 4591229810..90cecee5db 100644
--- a/docs/catalog/components/tabs-slide-indicator.mdx
+++ b/docs/catalog/components/tabs-slide-indicator.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Tabs Slide Indicator
+
A pill indicator transition that slides between active tabs
+
+
-
+
+
+
## Paste it into your composition
@@ -247,6 +253,4 @@ Tagged `transition-primitive` `transitions-dev-port` `tabs` `indicator`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/telemetry-hud.mdx b/docs/catalog/components/telemetry-hud.mdx
index cc4531c810..7155cfc2fc 100644
--- a/docs/catalog/components/telemetry-hud.mdx
+++ b/docs/catalog/components/telemetry-hud.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Telemetry HUD
+
Quiet mono debug-HUD readouts frame a slotted subject: corner brackets draw on, label:value lines tick their values on cues, one readout emphasized in accent. The subject never moves; the HUD breathes zero.
+
+
-
+
+
+
## Paste it into your composition
@@ -631,6 +637,4 @@ Tagged `motion-primitive` `product-demo` `hud` `telemetry` `deterministic`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/terminal-simulator.mdx b/docs/catalog/components/terminal-simulator.mdx
index a74865ec82..ac680ddf04 100644
--- a/docs/catalog/components/terminal-simulator.mdx
+++ b/docs/catalog/components/terminal-simulator.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Terminal Simulator
+
A terminal window types commands and streams log output.
+
+
-
+
+
+
## Paste it into your composition
@@ -147,6 +153,4 @@ Tagged `code-animation`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/testimonial-card.mdx b/docs/catalog/components/testimonial-card.mdx
index 7ea00f73a9..f57871fd56 100644
--- a/docs/catalog/components/testimonial-card.mdx
+++ b/docs/catalog/components/testimonial-card.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Testimonial Card
+
Reveals a customer quote at reading pace, then settles its avatar, author name, and handle beneath as a clean proof beat.
+
+
-
+
+
+
## Paste it into your composition
@@ -406,6 +412,4 @@ Tagged `prop` `ui-props` `testimonial` `social-proof` `quote` `prove`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/testimonial-proof-card.mdx b/docs/catalog/components/testimonial-proof-card.mdx
index c8f99c0d00..4cb3c2edba 100644
--- a/docs/catalog/components/testimonial-proof-card.mdx
+++ b/docs/catalog/components/testimonial-proof-card.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Testimonial Proof Card
+
A quote card whose testimonial reveals per-line through a soft mask, with an avatar disc (initials default, image slot), mono name and role, an optional company text mark, and one emphasis substring underlined in accent ink after the quote lands.
+
+
-
+
+
+
## Paste it into your composition
@@ -575,6 +581,4 @@ Tagged `motion-primitive` `proof` `testimonial` `quote` `social-proof` `determin
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/text-match-cut.mdx b/docs/catalog/components/text-match-cut.mdx
index 6e265ad89c..ec48e037b4 100644
--- a/docs/catalog/components/text-match-cut.mdx
+++ b/docs/catalog/components/text-match-cut.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Text Match Cut
+
One line of text becomes another mid-move: both ride a single 85 % easy-ease curve and hard-swap at the speed peak, as scale, tracking, or a same-direction slide.
+
+
-
+
+
+
## Paste it into your composition
@@ -402,6 +408,4 @@ Tagged `motion-primitive` `transition` `typography` `match-cut` `hard-cut` `cont
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/text-shimmer.mdx b/docs/catalog/components/text-shimmer.mdx
index 6819223dfd..7513fb392b 100644
--- a/docs/catalog/components/text-shimmer.mdx
+++ b/docs/catalog/components/text-shimmer.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Text Shimmer
+
A static headline receives one clean specular gradient sweep through its glyphs, then returns to its ordinary text color.
+
+
-
+
+
+
## Paste it into your composition
@@ -254,6 +260,4 @@ Tagged `motion-primitive` `text-effects` `shimmer` `specular` `emphasis`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/text-stagger.mdx b/docs/catalog/components/text-stagger.mdx
index 732de4ac93..91b65a9fe0 100644
--- a/docs/catalog/components/text-stagger.mdx
+++ b/docs/catalog/components/text-stagger.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Text Stagger
+
A transitions.dev-inspired text stagger primitive with enter, shimmer, and exit-ready words
+
+
-
+
+
+
## Paste it into your composition
@@ -210,6 +216,4 @@ Tagged `video-primitive` `transition-primitive` `transitions-dev-port` `text` `s
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/text-state-swap.mdx b/docs/catalog/components/text-state-swap.mdx
index fc5d77d233..70b81edd37 100644
--- a/docs/catalog/components/text-state-swap.mdx
+++ b/docs/catalog/components/text-state-swap.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Text State Swap
+
A text state swap primitive with outgoing blur and incoming lift
+
+
-
+
+
+
## Paste it into your composition
@@ -191,6 +197,4 @@ Tagged `video-primitive` `transition-primitive` `transitions-dev-port` `text` `s
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/texture-mask-text.mdx b/docs/catalog/components/texture-mask-text.mdx
index 06e959aae9..698df252c2 100644
--- a/docs/catalog/components/texture-mask-text.mdx
+++ b/docs/catalog/components/texture-mask-text.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Texture Mask Text
+
CSS luminance masks that cut holes through letterforms - 66 pre-built texture masks from ambientCG PBR color maps
+
+
-
+
+
+
## Paste it into your composition
@@ -895,6 +901,4 @@ Tagged `text` `text-effect` `effect` `texture` `mask`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/three-orbiting-cards.mdx b/docs/catalog/components/three-orbiting-cards.mdx
index cc904b7f2d..8bd9c88b5d 100644
--- a/docs/catalog/components/three-orbiting-cards.mdx
+++ b/docs/catalog/components/three-orbiting-cards.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Three Orbiting Cards
+
A Three.js-powered orbit scene driven by a paused GSAP timeline for deterministic renders.
+
+
-
+
+
+
## Paste it into your composition
@@ -172,6 +178,4 @@ Tagged `video-primitive` `three-js` `webgl` `hyperframes-native`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/ticker-takeover.mdx b/docs/catalog/components/ticker-takeover.mdx
index 821e8dc2b0..13bde0052e 100644
--- a/docs/catalog/components/ticker-takeover.mdx
+++ b/docs/catalog/components/ticker-takeover.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Ticker Takeover
+
A mono ticker rolls through options, locks on a final word with an accent flash, and promotes it into a full-frame headline.
+
+
-
+
+
+
## Paste it into your composition
@@ -397,6 +403,4 @@ Tagged `motion-primitive` `typography` `ticker` `slot-machine` `headline` `revea
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/tilt-card.mdx b/docs/catalog/components/tilt-card.mdx
index 04ff09e6c6..3524436cf4 100644
--- a/docs/catalog/components/tilt-card.mdx
+++ b/docs/catalog/components/tilt-card.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Tilt Card
+
A transitions.dev-inspired tilt card primitive with depth layers and hover-style parallax
+
+
-
+
+
+
## Paste it into your composition
@@ -234,6 +240,4 @@ Tagged `video-primitive` `transition-primitive` `transitions-dev-port` `card` `t
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/titlecard-calm.mdx b/docs/catalog/components/titlecard-calm.mdx
index 3e31fed1d4..6808519c76 100644
--- a/docs/catalog/components/titlecard-calm.mdx
+++ b/docs/catalog/components/titlecard-calm.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Titlecard Calm
+
A restrained title card where a mono kicker and generous grotesque headline fade upward, drift almost imperceptibly, and exit cleanly.
+
+
-
+
+
+
## Paste it into your composition
@@ -263,6 +269,4 @@ Tagged `motion-primitive` `typography` `title-card` `calm` `orient`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/titlecard-lockup.mdx b/docs/catalog/components/titlecard-lockup.mdx
index 29656fcb22..3ad3d65644 100644
--- a/docs/catalog/components/titlecard-lockup.mdx
+++ b/docs/catalog/components/titlecard-lockup.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Titlecard Lockup
+
The calm breather titlecard: an optional mono kicker fades up, the wordmark settles dead-center with one restrained move, a hairline rule draws left to right, a mono label fades beneath, and the lockup holds truly still.
+
+
-
+
+
+
## Paste it into your composition
@@ -400,6 +406,4 @@ Tagged `motion-primitive` `typography` `title-card` `lockup` `breather` `orient`
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/toggle-flip.mdx b/docs/catalog/components/toggle-flip.mdx
index 7f6185b8f5..c3ea395552 100644
--- a/docs/catalog/components/toggle-flip.mdx
+++ b/docs/catalog/components/toggle-flip.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Toggle Flip
+
An oversized UI toggle switch that flips with real physicality: thumb overshoot, track color crossfade, and a soft press-compress before release. The reference prop of the ui-props family.
+
+
-
+
+
+
## Paste it into your composition
@@ -500,6 +506,4 @@ Tagged `prop` `ui-props` `toggle` `interaction` `reference-prop` `demonstrate`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/top-down-letters.mdx b/docs/catalog/components/top-down-letters.mdx
index 647a62d691..301ccb8812 100644
--- a/docs/catalog/components/top-down-letters.mdx
+++ b/docs/catalog/components/top-down-letters.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Top-Down Letters
+
Letters descend from above in a pronounced staircase with zero blur.
+
+
-
+
+
+
## Paste it into your composition
@@ -189,6 +195,4 @@ Tagged `video-primitive` `motion-primitive` `typography`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/torn-paper-rip.mdx b/docs/catalog/components/torn-paper-rip.mdx
index c0d4040216..59132328e4 100644
--- a/docs/catalog/components/torn-paper-rip.mdx
+++ b/docs/catalog/components/torn-paper-rip.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Torn Paper Rip
+
A fibrous paper tear runs across the frame: the torn sheet shows its white paper core along the edge and lifts away on a soft shadow, leaving the next scene standing.
+
+
-
+
+
+
## Paste it into your composition
@@ -488,6 +494,4 @@ Tagged `torn paper` `paper rip` `paper tear` `transition` `texture` `motion-prim
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/touch-indicator.mdx b/docs/catalog/components/touch-indicator.mdx
index 6a713848d1..6b3cdff29b 100644
--- a/docs/catalog/components/touch-indicator.mdx
+++ b/docs/catalog/components/touch-indicator.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Touch Indicator
+
A translucent contact-circle gesture actor for mobile UI scenes: it touches the glass on the frame the host target responds, then lifts. Tap or swipe, picked by variable.
+
+
-
+
+
+
## Paste it into your composition
@@ -327,6 +333,4 @@ Tagged `cursor` `motion-primitive` `mobile` `gesture` `touch` `pointer`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/tracing-beam.mdx b/docs/catalog/components/tracing-beam.mdx
index 2780b393eb..5d6be308fa 100644
--- a/docs/catalog/components/tracing-beam.mdx
+++ b/docs/catalog/components/tracing-beam.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Tracing Beam
+
A glowing dash follows one SVG path through three UI elements, lifting and brightening each element in sequence.
+
+
-
+
+
+
## Paste it into your composition
@@ -474,6 +480,4 @@ Tagged `motion-primitive` `product-demo` `attention` `beam` `path` `spotlight`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/tracking-in.mdx b/docs/catalog/components/tracking-in.mdx
index 96eda05185..eaa4974c8e 100644
--- a/docs/catalog/components/tracking-in.mdx
+++ b/docs/catalog/components/tracking-in.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Tracking In
+
A precise letter-spacing reveal for premium headings and interface labels
+
+
-
+
+
+
## Paste it into your composition
@@ -172,6 +178,4 @@ Tagged `motion-primitive` `text` `reveal` `typography`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/trust-strip.mdx b/docs/catalog/components/trust-strip.mdx
index f2313cb9c3..dcda99e918 100644
--- a/docs/catalog/components/trust-strip.mdx
+++ b/docs/catalog/components/trust-strip.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Trust Strip
+
A monochrome trust row of wide-tracked mono wordmarks that fade in with an opacity-only left-to-right stagger, then hold dead still.
+
+
-
+
+
+
## Paste it into your composition
@@ -304,6 +310,4 @@ Tagged `motion-primitive` `proof` `trust` `logo-strip` `wordmarks`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/type-match-cut.mdx b/docs/catalog/components/type-match-cut.mdx
index 6cd4f108bd..f95237792e 100644
--- a/docs/catalog/components/type-match-cut.mdx
+++ b/docs/catalog/components/type-match-cut.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Type Match Cut
+
A headline splits vertically around an incoming panel, which grows from the negative space and takes the frame as the words exit through opposite edges.
+
+
-
+
+
+
## Paste it into your composition
@@ -482,6 +488,4 @@ Tagged `motion-primitive` `transition` `typography` `match-cut` `continuity`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/typed-prompt.mdx b/docs/catalog/components/typed-prompt.mdx
index 867baf38fc..d8e4e52708 100644
--- a/docs/catalog/components/typed-prompt.mdx
+++ b/docs/catalog/components/typed-prompt.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Typed Prompt
+
A prompt line types itself in chunked human cadence behind a deterministic blinking caret, with optional backspace-and-retype correction of the final word.
+
+
"},{"id":"cadence","type":"enum","role":"timing","label":"Cadence","description":"Keystroke rhythm: uniform fixed steps or seeded human chunks.","default":"human","options":[{"value":"uniform","label":"Uniform"},{"value":"human","label":"Human"}]},{"id":"caret","type":"enum","role":"style","label":"Caret","description":"Blink runs integer sine cycles during typing then goes solid.","default":"blink","options":[{"value":"blink","label":"Blink"},{"value":"solid","label":"Solid"}]},{"id":"correction","type":"string","role":"content","label":"Correction","description":"Mistyped word typed in place of the final word, then backspaced and corrected. Empty disables.","default":""},{"id":"cues","type":"string","role":"timing","label":"Cues","description":"Comma-separated seconds relative to mount start; cue N anchors the start of word N. Empty uses the authored rhythm.","default":""},{"id":"accent","type":"enum","role":"style","label":"Accent","description":"Color of the prompt glyph and caret.","default":"green","options":[{"value":"green","label":"Green"},{"value":"blue","label":"Blue"},{"value":"violet","label":"Violet"}]},{"id":"exit","type":"enum","role":"timing","label":"Exit","description":"Outgoing transition. Frame roots own transitions; none holds the end frame.","default":"none","options":[{"value":"none","label":"None"},{"value":"fade","label":"Fade"},{"value":"up","label":"Up"}]}]}
meta={{"category":"Product Demo","badge":"Stable","codeLines":384}}
attribution={{"path":"registry/components/typed-prompt","tags":["motion-primitive","product-demo","typing","prompt","deterministic"]}}
@@ -419,7 +423,9 @@ That writes one file: `compositions/components/typed-prompt.html`.
-
+
+
+
## Paste it into your composition
@@ -465,6 +471,4 @@ Tagged `motion-primitive` `product-demo` `typing` `prompt` `deterministic`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/typewriter.mdx b/docs/catalog/components/typewriter.mdx
index 1bb34d6b6f..5bd20de163 100644
--- a/docs/catalog/components/typewriter.mdx
+++ b/docs/catalog/components/typewriter.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Typewriter
+
Character-by-character text reveal with a deterministic blinking cursor.
+
+
-
+
+
+
## Paste it into your composition
@@ -198,6 +204,4 @@ Tagged `video-primitive` `motion-primitive` `typography`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/typing-indicator.mdx b/docs/catalog/components/typing-indicator.mdx
index 9c9517bc24..e330ed7222 100644
--- a/docs/catalog/components/typing-indicator.mdx
+++ b/docs/catalog/components/typing-indicator.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Typing Indicator
+
The three-dot chat bubble that says someone is writing: it pops in at the thread's edge exactly as messaging apps do, holds while the reply is coming, and vanishes when the message lands
+
+
-
+
+
+
## Paste it into your composition
@@ -369,6 +375,4 @@ Created by Miao Yang.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/ui-focus-zoom.mdx b/docs/catalog/components/ui-focus-zoom.mdx
index 6a36531966..c9ce7c9ac2 100644
--- a/docs/catalog/components/ui-focus-zoom.mdx
+++ b/docs/catalog/components/ui-focus-zoom.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
UI Focus Zoom
+
A full app surface establishes with one settle, then the camera zooms and pans to an anchored region on its cue and holds the zoomed state, with an optional soft focus halo at the anchor. The surface is a slot with a token-styled skeleton default.
+
+
-
+
+
+
## Paste it into your composition
@@ -644,6 +650,4 @@ Tagged `camera` `product-demo` `zoom` `focus` `pan` `slot` `servo`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/variable-axis-type.mdx b/docs/catalog/components/variable-axis-type.mdx
index abaa28b9f1..224fcb6486 100644
--- a/docs/catalog/components/variable-axis-type.mdx
+++ b/docs/catalog/components/variable-axis-type.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Variable Axis Type
+
A locked one-line headline whose weight or width axis morphs into a decisive emphasis beat.
+
+
-
+
+
+
## Paste it into your composition
@@ -269,6 +275,4 @@ Tagged `typography` `variable-font` `kinetic-type` `axis` `emphasize`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/variable-font-flex.mdx b/docs/catalog/components/variable-font-flex.mdx
index a5649ab308..2e388232c6 100644
--- a/docs/catalog/components/variable-font-flex.mdx
+++ b/docs/catalog/components/variable-font-flex.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Variable Font Flex
+
A word lands while its variable-font weight and width axes flex from hairline-condensed to black-wide with per-character stagger; font-size eases inversely so the letterforms gain mass while the box holds.
+
+
-
+
+
+
## Paste it into your composition
@@ -382,6 +388,4 @@ Tagged `motion-primitive` `experiment` `type` `variable-font` `deterministic`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/vector-editor-rig.mdx b/docs/catalog/components/vector-editor-rig.mdx
index 5bf2624ea1..4d37dfd15b 100644
--- a/docs/catalog/components/vector-editor-rig.mdx
+++ b/docs/catalog/components/vector-editor-rig.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Vector Editor Rig
+
A dark design-tool app chrome with a live vector pen path, sequential anchor points, bezier handles, a selection frame, and theme-driven blue accents.
+
+
-
+
+
+
## Paste it into your composition
@@ -870,6 +876,4 @@ Tagged `prop` `ui-props` `demonstrate` `vector` `design-tool` `pen-tool` `bezier
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/velocity-throw-snap.mdx b/docs/catalog/components/velocity-throw-snap.mdx
index fac5512309..f0e5bb8352 100644
--- a/docs/catalog/components/velocity-throw-snap.mdx
+++ b/docs/catalog/components/velocity-throw-snap.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Velocity Throw Snap
+
A five-shot rail whips past on a fast decaying curve, then overshoots and snaps the selected hero shot exactly to center.
+
+
-
+
+
+
## Paste it into your composition
@@ -560,6 +566,4 @@ Tagged `motion-primitive` `feature-tour` `rail` `velocity` `throw` `snap` `physi
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/vignette.mdx b/docs/catalog/components/vignette.mdx
index d15ed5d18e..b5ce0fce22 100644
--- a/docs/catalog/components/vignette.mdx
+++ b/docs/catalog/components/vignette.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Vignette
+
Cinematic radial vignette overlay using a pure-CSS gradient — darkens the edges to pull focus toward the center
+
+
-
+
+
+
## Paste it into your composition
@@ -106,6 +112,4 @@ Tagged `vignette` `overlay` `cinematic` `effect`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/vox-annotate.mdx b/docs/catalog/components/vox-annotate.mdx
index 0fb4ecd340..9c236245a8 100644
--- a/docs/catalog/components/vox-annotate.mdx
+++ b/docs/catalog/components/vox-annotate.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Vox Annotate
+
The Vox-style annotate gesture: a keyword in a held sentence gets a hand-drawn marker while a thin connector draws up to a mono callout label, all as one choreographed beat on the cue.
+
+
-
+
+
+
## Paste it into your composition
@@ -557,6 +563,4 @@ Tagged `motion-primitive` `typography` `annotation` `marker` `deterministic`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/whip-pan-cut.mdx b/docs/catalog/components/whip-pan-cut.mdx
index b78b392e2c..94b9105004 100644
--- a/docs/catalog/components/whip-pan-cut.mdx
+++ b/docs/catalog/components/whip-pan-cut.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Whip Pan Cut
+
A full-frame whip pan: scene A whips off laterally with capped directional motion blur while scene B enters in the same direction at matched velocity, on a speed-ramp profile with a decelerating catch. Both scenes ride one strip, so seam velocity is exact by construction. Callers fill the named before/after slot panels; token-styled defaults render when a slot is left empty.
+
+
-
+
+
+
## Paste it into your composition
@@ -564,6 +570,4 @@ Tagged `transition` `whip-pan` `motion-blur` `velocity-match` `speed-ramp` `brid
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/whiteboard-ink.mdx b/docs/catalog/components/whiteboard-ink.mdx
index 96c7ef9b80..f41b1175d1 100644
--- a/docs/catalog/components/whiteboard-ink.mdx
+++ b/docs/catalog/components/whiteboard-ink.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Whiteboard Ink
+
A whiteboard sketch draws one measured stroke at a time while a pen nib follows the active tip. Preset sketches (bulb, flow, rocket) or your own multi-stroke SVG paths via the strokes slot; a path marked data-ink=accent rides the accent token.
+
+
-
+
+
+
## Paste it into your composition
@@ -618,6 +624,4 @@ Tagged `motion-primitive` `intro` `reveal` `svg` `whiteboard` `line-draw` `slot`
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/wordmark-tiles.mdx b/docs/catalog/components/wordmark-tiles.mdx
index d5a357a1c9..38ff14719a 100644
--- a/docs/catalog/components/wordmark-tiles.mdx
+++ b/docs/catalog/components/wordmark-tiles.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Wordmark Tiles
+
A wordmark resolves from deterministic color noise into correctly cropped glyph tiles through a spatially modulated GSAP wave.
+
+
-
+
+
+
## Paste it into your composition
@@ -436,6 +442,4 @@ Tagged `typography` `wordmark` `tiles` `raster` `reveal`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/x-follow-card.mdx b/docs/catalog/components/x-follow-card.mdx
index bf6e382da5..75d2593054 100644
--- a/docs/catalog/components/x-follow-card.mdx
+++ b/docs/catalog/components/x-follow-card.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
X Follow Card
+
A social follow card with avatar, handle, and follower motion.
+
+
-
+
+
+
## Paste it into your composition
@@ -144,6 +150,4 @@ Tagged `social-overlay`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/yt-camera-move.mdx b/docs/catalog/components/yt-camera-move.mdx
index 9c1c8750c5..100d99a1e6 100644
--- a/docs/catalog/components/yt-camera-move.mdx
+++ b/docs/catalog/components/yt-camera-move.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Camera Punch-In
+
Dynamic zoom, slide, and 3D tilt-pan helpers for any wrapper (video, include, card) with cubic-easing defaults and an edge-defocus pulse overlay
+
+
-
+
+
+
## Paste it into your composition
@@ -229,6 +235,4 @@ Tagged `camera` `zoom` `effect` `creator`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/yt-circle-pointer.mdx b/docs/catalog/components/yt-circle-pointer.mdx
index a562ba8860..d8f9bed38b 100644
--- a/docs/catalog/components/yt-circle-pointer.mdx
+++ b/docs/catalog/components/yt-circle-pointer.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Pointer Circle + Countdown
+
Draw-on annotation ellipse around a target plus a countdown chip that pulses each tick
+
+
-
+
+
+
## Paste it into your composition
@@ -222,6 +228,4 @@ Tagged `annotation` `countdown` `overlay`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/yt-feather-highlight.mdx b/docs/catalog/components/yt-feather-highlight.mdx
index 6fe157f07a..8ccebc29ec 100644
--- a/docs/catalog/components/yt-feather-highlight.mdx
+++ b/docs/catalog/components/yt-feather-highlight.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Feathered Spotlight
+
Dims the frame except a feathered ellipse; the hole's position and size are CSS variables, so helpers glide the spotlight between targets
+
+
-
+
+
+
## Paste it into your composition
@@ -199,6 +205,4 @@ Tagged `highlight` `spotlight` `effect` `overlay`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/yt-screen-warp.mdx b/docs/catalog/components/yt-screen-warp.mdx
index ca54586a40..480bf8b49c 100644
--- a/docs/catalog/components/yt-screen-warp.mdx
+++ b/docs/catalog/components/yt-screen-warp.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
On-Screen Display Effect
+
Grid, scanline, vignette, and sheen overlay plus a 3D-warp wrapper class that makes footage read as if playing on a physical display
+
+
-
+
+
+
## Paste it into your composition
@@ -177,6 +183,4 @@ Tagged `effect` `overlay` `texture`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/catalog/components/zoom-through-transition.mdx b/docs/catalog/components/zoom-through-transition.mdx
index 3d155ac633..32ceddabc0 100644
--- a/docs/catalog/components/zoom-through-transition.mdx
+++ b/docs/catalog/components/zoom-through-transition.mdx
@@ -7,12 +7,16 @@ mode: "frame"
import { CatalogDetail, CatalogSlot } from "/snippets/catalog-detail.jsx";
import { InstallCommand } from "/snippets/install-command.jsx";
+
+
Zoom Through Transition
+
A transition that zooms through a focal card into the next scene.
+
+
-
+
+
+
## Paste it into your composition
@@ -361,6 +367,4 @@ Tagged `transition-primitive`.
- [Add assets and Catalog items in the browser editor](/studio/assets-and-blocks)
- [Put blocks together into one video](/concepts/compositions)
-
-
-
+
diff --git a/docs/changelog.mdx b/docs/changelog.mdx
index adaa10b6c1..d640877474 100644
--- a/docs/changelog.mdx
+++ b/docs/changelog.mdx
@@ -8,6 +8,359 @@ Recent HyperFrames releases, including user-facing features, fixes, and migratio
{/* New release entries are prepended by `bun run changelog:draft --write`. */}
+
+Paid HyperFrames plans can render final cuts in the cloud at the composition's fps and high quality. Safari keeps audio smooth during playback, and Studio downloads exports larger than 2 GiB.
+
+## Features
+
+- **Skills:** Render final cuts in the cloud on a paid HyperFrames plan ([2b76e9a70](https://github.com/heygen-com/hyperframes/commit/2b76e9a70a749c445cd137946512b0dda8aa770f), [#6884](https://github.com/heygen-com/hyperframes/pull/6884)).
+
+## Fixes
+
+- **Skills:** Paid-plan cloud final keeps the composition fps and high quality ([6b0fd6d10](https://github.com/heygen-com/hyperframes/commit/6b0fd6d10992ebf5913dcc8418b7b8b58803f035), [#6886](https://github.com/heygen-com/hyperframes/pull/6886)).
+- **CLI:** Stopping remove-background on a Mac no longer aborts the process ([ea7d43c61](https://github.com/heygen-com/hyperframes/commit/ea7d43c616c4cd3bb77f27eaf9f3becd32e41744), [#6848](https://github.com/heygen-com/hyperframes/pull/6848)).
+- **Core:** A stuck seek in check or snapshot fails named before the protocol timeout ([1e5413f34](https://github.com/heygen-com/hyperframes/commit/1e5413f34ce489a1b35eaf46635a630a44cb5804), [#6596](https://github.com/heygen-com/hyperframes/pull/6596)).
+- **Core:** Style a sub-composition root written as #root[data-composition-id] ([5c92fb077](https://github.com/heygen-com/hyperframes/commit/5c92fb07761cd0667d22380c2c855b89766f8fa4), [#6843](https://github.com/heygen-com/hyperframes/pull/6843)).
+- **Studio Server:** Repeated splits stop stacking id CSS rules ([124a00f56](https://github.com/heygen-com/hyperframes/commit/124a00f563944a006dd9ac286ecb91043b0fa0b9), [#6874](https://github.com/heygen-com/hyperframes/pull/6874)).
+- **Producer:** Auto renders with color-graded media stay SDR instead of promoting to HDR ([60f711686](https://github.com/heygen-com/hyperframes/commit/60f711686ccae602caaed24faa3e225be6d96b12), [#6671](https://github.com/heygen-com/hyperframes/pull/6671)).
+- **Studio:** Preserve identity for stale metadata completions ([168429d51](https://github.com/heygen-com/hyperframes/commit/168429d514ccefdfc5658138fb58426cf0e66e01), [#6755](https://github.com/heygen-com/hyperframes/pull/6755)).
+- **Core:** Safari stops chopping audio by seeking it over and over during playback ([0c16afd94](https://github.com/heygen-com/hyperframes/commit/0c16afd949f2511ca17347eaa113640df0bac1e5), [#6854](https://github.com/heygen-com/hyperframes/pull/6854)).
+- **Studio Server:** Download exports larger than 2 GiB ([164d6c7a3](https://github.com/heygen-com/hyperframes/commit/164d6c7a36eba26e9126b364beab98437e2eeec7), [#6602](https://github.com/heygen-com/hyperframes/pull/6602)).
+
+## Docs & Examples
+
+- List OpenAI and Nate Herk as HyperFrames adopters ([a04b45a6d](https://github.com/heygen-com/hyperframes/commit/a04b45a6db0d1f724be9cf1985c3b13657195f0d), [#6876](https://github.com/heygen-com/hyperframes/pull/6876)).
+
+## Internal
+
+- **CLI:** Proxy failure wording without added comments or a try/catch ([4d6d38519](https://github.com/heygen-com/hyperframes/commit/4d6d38519d06b650a5d4f55c5cc7ba854c0993ad), [#6715](https://github.com/heygen-com/hyperframes/pull/6715)).
+- **Core:** Split the frozen-picture judgement so it stays under the complexity limit ([2bd8cd95c](https://github.com/heygen-com/hyperframes/commit/2bd8cd95cb43fba47de906530e043900bb283371), [#6870](https://github.com/heygen-com/hyperframes/pull/6870)).
+
+[View the full commit range](https://github.com/heygen-com/hyperframes/compare/v0.8.223...v0.8.224).
+
+
+
+Reverse any video now runs on the HyperFrames plan, with clearer credit wording. Preview voice no longer drops out while other tracks play, and Windows renders keep their telemetry.
+
+## Features
+
+- **Skills:** Re-land reverse any video on the HyperFrames plan, with clearer credit wording ([f2358315e](https://github.com/heygen-com/hyperframes/commit/f2358315e59731833334c5d881a7fb5543c22a97), [#6833](https://github.com/heygen-com/hyperframes/pull/6833)).
+- **Core:** Playback health reports how long a video on screen showed no moving picture ([359b6c8a3](https://github.com/heygen-com/hyperframes/commit/359b6c8a3877039068711915d94323f7e777f5e6), [#6856](https://github.com/heygen-com/hyperframes/pull/6856)).
+
+## Fixes
+
+- **Lint:** The podcast-lanes.html page Desktop writes is not a second root composition ([5169422a8](https://github.com/heygen-com/hyperframes/commit/5169422a8a424fadbb97424a95316a63343eb4f2), [#6809](https://github.com/heygen-com/hyperframes/pull/6809)).
+- **Player:** Preview voice no longer goes silent while other tracks play ([443ded426](https://github.com/heygen-com/hyperframes/commit/443ded42615f81fd5a4b97d34318676fb76957bd), [#6859](https://github.com/heygen-com/hyperframes/pull/6859)).
+- **History:** Reading a project's history no longer rewrites its record ([e342a9099](https://github.com/heygen-com/hyperframes/commit/e342a9099162b6a5d4ad89d9a986203c2b548091), [#6832](https://github.com/heygen-com/hyperframes/pull/6832)).
+- **Lint:** A timeline registered in a local script file counts as registered ([0708f6ca7](https://github.com/heygen-com/hyperframes/commit/0708f6ca7dc0718487a2d0a066853b87db92a1aa), [#6829](https://github.com/heygen-com/hyperframes/pull/6829)).
+- **CLI:** Say stdin was empty when a JSON flag reads - and nothing is piped ([ef9155fee](https://github.com/heygen-com/hyperframes/commit/ef9155fee13cf8a65282e1681ac2761edcb1fcc2), [#6852](https://github.com/heygen-com/hyperframes/pull/6852)).
+- **Core:** Same-time sets at 0 land in authored order on the first frame ([aafbd96b7](https://github.com/heygen-com/hyperframes/commit/aafbd96b77702f295c77de1430dfcb14302e4958), [#6851](https://github.com/heygen-com/hyperframes/pull/6851)).
+- **CLI:** Remove-background gathers each decoded frame in linear time ([80f9350da](https://github.com/heygen-com/hyperframes/commit/80f9350da21b54741d392c684511b6f93a00026c), [#6850](https://github.com/heygen-com/hyperframes/pull/6850)).
+- **CLI:** Exit-time telemetry no longer loses a render's events on Windows ([6aa9c78bd](https://github.com/heygen-com/hyperframes/commit/6aa9c78bd87d6215ad7c599e4caf44331b39a645), [#6847](https://github.com/heygen-com/hyperframes/pull/6847)).
+- **CLI:** Read BOM-prefixed JSON files for timeline plans, grades and motion specs ([16e2e4c6b](https://github.com/heygen-com/hyperframes/commit/16e2e4c6b5579a0ccefbfc7bd6991ec23a6f8c75), [#6845](https://github.com/heygen-com/hyperframes/pull/6845)).
+- **Producer:** HDR renders report their encoder wait in render telemetry ([3d942ee92](https://github.com/heygen-com/hyperframes/commit/3d942ee9210a166a53a6497b76aa323acc8e95bc), [#6841](https://github.com/heygen-com/hyperframes/pull/6841)).
+
+## Performance
+
+- **Studio:** A long timeline no longer lays itself out on every render while it settles ([9b0df610c](https://github.com/heygen-com/hyperframes/commit/9b0df610cca45bb1bc8bacec78059d3c4443ec09), [#6855](https://github.com/heygen-com/hyperframes/pull/6855)).
+
+## Catalog
+
+- One Docs menu and Catalog in the top bar ([4cee7be83](https://github.com/heygen-com/hyperframes/commit/4cee7be834c18b571da1cfcda6e3eaeca7689855), [#6860](https://github.com/heygen-com/hyperframes/pull/6860)).
+
+[View the full commit range](https://github.com/heygen-com/hyperframes/compare/v0.8.222...v0.8.223).
+
+
+
+Render takes --start and --end to make just one span of the film as its own MP4. Capture retries without WebGL when a page stops answering, so more exports finish. Lint warns when a font or image in a linked stylesheet points at the wrong folder.
+
+## Features
+
+- **Lint:** Warn when a url() in a linked stylesheet does not resolve beside it ([6cddd1a24](https://github.com/heygen-com/hyperframes/commit/6cddd1a24043ce852bcca3e4cf59378a02d400d1), [#6844](https://github.com/heygen-com/hyperframes/pull/6844)).
+- **Telemetry:** Render_complete splits capture time into seek, page, screenshot and encoder wait ([4da50e221](https://github.com/heygen-com/hyperframes/commit/4da50e221842f97dafebe5004225bd7e11443586), [#6839](https://github.com/heygen-com/hyperframes/pull/6839)).
+- **CLI:** Render --start and --end render only that span of the film as its own MP4 ([5a164fb36](https://github.com/heygen-com/hyperframes/commit/5a164fb3693d522ef163570bde82b10af47d2322), [#6834](https://github.com/heygen-com/hyperframes/pull/6834)).
+- **CLI:** Review notes name the command that reviews the cuts inside a sub-composition ([01783f375](https://github.com/heygen-com/hyperframes/commit/01783f3757be1cb45246e180b3891a376461375f), [#6820](https://github.com/heygen-com/hyperframes/pull/6820)).
+- **CLI:** Beats analyses an audio or video file given directly ([a37307126](https://github.com/heygen-com/hyperframes/commit/a3730712618c1b39520d760a85168178e5869ab0), [#6812](https://github.com/heygen-com/hyperframes/pull/6812)).
+
+## Fixes
+
+- **CLI:** History show --diff names a changed video or audio file instead of refusing ([4ba01be15](https://github.com/heygen-com/hyperframes/commit/4ba01be1519a27c6363d2afca088924de99a895d), [#6836](https://github.com/heygen-com/hyperframes/pull/6836)).
+- **CLI:** Point a brace-stripped JSON flag value at the file and stdin forms ([3ebf888fb](https://github.com/heygen-com/hyperframes/commit/3ebf888fb69bcf462c177d2042ed33b5d6501b1e), [#6838](https://github.com/heygen-com/hyperframes/pull/6838)).
+- **Producer:** Render telemetry names content gates instead of calling them disabled ([6a8c064fb](https://github.com/heygen-com/hyperframes/commit/6a8c064fb96e68e365b91063f511a3cd934794f7), [#6835](https://github.com/heygen-com/hyperframes/pull/6835)).
+- **CLI:** --variables-file and --variables \ read the file again ([6f2b07227](https://github.com/heygen-com/hyperframes/commit/6f2b072275b6107c253fd61edebe107cbd3c8275), [#6831](https://github.com/heygen-com/hyperframes/pull/6831)).
+- **Lint:** A font the project's root stylesheet declares counts for its sub-compositions ([bf4717893](https://github.com/heygen-com/hyperframes/commit/bf47178937d210c269ac8e737f5f5d7f24b74d82), [#6827](https://github.com/heygen-com/hyperframes/pull/6827)).
+- **CLI:** Capture retries without WebGL when the page stops answering under software GL ([ef2159fe8](https://github.com/heygen-com/hyperframes/commit/ef2159fe8c05d89dbdb75a7d38b7c6a67763ad67), [#6821](https://github.com/heygen-com/hyperframes/pull/6821)).
+- **Studio:** A split at a clip's edge leaves the file unchanged ([b20d0a62c](https://github.com/heygen-com/hyperframes/commit/b20d0a62ce1d1c573c3344b544851875bd2b157c), [#6826](https://github.com/heygen-com/hyperframes/pull/6826)).
+- **CLI:** Check and snapshot load GSAP from the bundled copy, not jsDelivr ([88d8e5b49](https://github.com/heygen-com/hyperframes/commit/88d8e5b490c268d60b6942b96a0c71deaefc40f9), [#6824](https://github.com/heygen-com/hyperframes/pull/6824)).
+- **CLI:** Check drops a request a network change cut when the file loads again ([44ee07a2d](https://github.com/heygen-com/hyperframes/commit/44ee07a2da79f58bd3147a61b3e544745390e7d9), [#6823](https://github.com/heygen-com/hyperframes/pull/6823)).
+- **Producer:** Report extract_video progress while ffmpeg extracts frames ([536209da0](https://github.com/heygen-com/hyperframes/commit/536209da07b48d77b300a7659ab07a38195d07c2), [#6822](https://github.com/heygen-com/hyperframes/pull/6822)).
+- **CLI:** Check no longer calls text occluded by a cover that a CSS mask paints through ([d4a866d61](https://github.com/heygen-com/hyperframes/commit/d4a866d612ed8bba2eed0b3594adc1dd805c14c0), [#6818](https://github.com/heygen-com/hyperframes/pull/6818)).
+- **CLI:** Render names the FFmpeg that has no libx264 and how to point at another ([315969cda](https://github.com/heygen-com/hyperframes/commit/315969cda01aeb6e3e8a9102249f7b6bca9eabbb), [#6819](https://github.com/heygen-com/hyperframes/pull/6819)).
+- **CLI:** Check sees an image swap even when the page cannot read the image's pixels ([054592c4d](https://github.com/heygen-com/hyperframes/commit/054592c4dea41d894824d29feacfd216850e1fb9), [#6817](https://github.com/heygen-com/hyperframes/pull/6817)).
+- **Producer:** A render that stalls before its first frame says which worker phase it was in ([2f8b8c47e](https://github.com/heygen-com/hyperframes/commit/2f8b8c47e02a7eae0644d644616b7d3f50618c5d), [#6814](https://github.com/heygen-com/hyperframes/pull/6814)).
+- **Engine:** A video clip starting between frames shows its media on the right frame ([10a4ed56c](https://github.com/heygen-com/hyperframes/commit/10a4ed56cb09159afec0dba3ea784e3162ee2e71), [#6759](https://github.com/heygen-com/hyperframes/pull/6759)).
+- **CLI:** The ignored-binary note names only the missing binary, and covers .hyperframes/bin ([71b668010](https://github.com/heygen-com/hyperframes/commit/71b668010f9bffb8f50b43c623679d4759c0a5ec), [#6807](https://github.com/heygen-com/hyperframes/pull/6807)).
+- **CLI:** Add says --dir is the project root when the folder is missing ([0bd1fd597](https://github.com/heygen-com/hyperframes/commit/0bd1fd59721a2660d07474e1628e18d6c1ced09f), [#6808](https://github.com/heygen-com/hyperframes/pull/6808)).
+- **Core:** The first cut after Play starts on time instead of running ahead ([07c714ce9](https://github.com/heygen-com/hyperframes/commit/07c714ce9b139500465b37174971e5f288b854a9), [#6794](https://github.com/heygen-com/hyperframes/pull/6794)).
+
+## Performance
+
+- **Studio Server:** Add createProjectSignatureAsync so project open stops blocking the loop ([bb2c8142f](https://github.com/heygen-com/hyperframes/commit/bb2c8142fd726c9f2bdb827d7b79b311341195af), [#6825](https://github.com/heygen-com/hyperframes/pull/6825)).
+- **Studio:** Films with thousands of timed clips stop re-reading every clip each frame ([d83f27674](https://github.com/heygen-com/hyperframes/commit/d83f2767436ef85260a42e6c548f9609f99b11ba), [#6805](https://github.com/heygen-com/hyperframes/pull/6805)).
+
+## Docs & Examples
+
+- **Quickstart:** Drop the stale 'if you are on Windows' line ([28181602f](https://github.com/heygen-com/hyperframes/commit/28181602fe2d9ffa38474a6e8155a89909a7b8aa), [#6803](https://github.com/heygen-com/hyperframes/pull/6803)).
+- **README:** Link the desktop app download for macOS, Windows and Linux ([b239d8dea](https://github.com/heygen-com/hyperframes/commit/b239d8dea93b4a25fe548d23e879dd0fc16df0ef), [#6790](https://github.com/heygen-com/hyperframes/pull/6790)).
+
+## Internal
+
+- **History:** The write-timing test no longer depends on how late its timers fire ([746ce956b](https://github.com/heygen-com/hyperframes/commit/746ce956b322128e93fc768bc1a6b20573a43eab), [#6837](https://github.com/heygen-com/hyperframes/pull/6837)).
+- **CLI:** Capture watchdog tests use a fake output folder outside the temp dir ([8142d6d59](https://github.com/heygen-com/hyperframes/commit/8142d6d59f84d83dd91dc15e34e92bd753e6b296), [#6828](https://github.com/heygen-com/hyperframes/pull/6828)).
+- **Engine:** The rotated-clip fixture builds on ffmpeg older than 6 ([279d40dcd](https://github.com/heygen-com/hyperframes/commit/279d40dcd75e3d074149b18dc5b297608dcf0540), [#6811](https://github.com/heygen-com/hyperframes/pull/6811)).
+- **Studio:** Run the merge queue edit accuracy grid in 30 shards ([b93c01c75](https://github.com/heygen-com/hyperframes/commit/b93c01c75a06f45d5eaca90bb22a56f4507581d0), [#6804](https://github.com/heygen-com/hyperframes/pull/6804)).
+
+## Other Changes
+
+
+[View the full commit range](https://github.com/heygen-com/hyperframes/compare/v0.8.221...v0.8.222).
+
+
+
+Snapshots of video projects take less time because each clip is read once for all the times you ask for. Preview now stops at once when you press Ctrl+C.
+
+## Fixes
+
+- **CLI:** Snapshot probes each video clip once for all the times it is asked for ([b3c47a36a](https://github.com/heygen-com/hyperframes/commit/b3c47a36a2bd8dff5bbf3753e3e6fe97d013c42b), [#6798](https://github.com/heygen-com/hyperframes/pull/6798)).
+- **CLI:** Preview stops at once on Ctrl+C after Studio was open ([3e795ece0](https://github.com/heygen-com/hyperframes/commit/3e795ece0fec8ef5331058566893f85a50605070), [#6782](https://github.com/heygen-com/hyperframes/pull/6782)).
+- **CLI:** Add takes several names in one call, and adopted audio is labelled voice or sfx ([7f7a4af7c](https://github.com/heygen-com/hyperframes/commit/7f7a4af7c48b736fb678d83047ab76af7ca7983a), [#6791](https://github.com/heygen-com/hyperframes/pull/6791)).
+- **CLI:** Check no longer flags a hidden scene child or a small animated sprite ([8c36f3254](https://github.com/heygen-com/hyperframes/commit/8c36f3254f0b98aa097f9b02d229d69596a592c2), [#6783](https://github.com/heygen-com/hyperframes/pull/6783)).
+- **Core:** Long cut-list edits play every cut without dropped or late frames ([9fd90d23c](https://github.com/heygen-com/hyperframes/commit/9fd90d23c4cc1208965c2179cd25a6d871246df9), [#6785](https://github.com/heygen-com/hyperframes/pull/6785)).
+- **CLI:** Hyperframes docs motion-blur shows the motion blur guide ([21eefcd00](https://github.com/heygen-com/hyperframes/commit/21eefcd006f895ee41641de65392b56c7b7e6c0a), [#6779](https://github.com/heygen-com/hyperframes/pull/6779)).
+
+## Docs & Examples
+
+- **Studio App:** Pending video edits have no cap of 10 ([f43bec76e](https://github.com/heygen-com/hyperframes/commit/f43bec76e7ceef13e65b930496f7e1f66779250b), [#6797](https://github.com/heygen-com/hyperframes/pull/6797)).
+
+## Catalog
+
+- **CLI:** A missing registry item names the closest ones, and a blocked browser says how to allow it ([47a1a9206](https://github.com/heygen-com/hyperframes/commit/47a1a92064cef4cf6602199ece1b32b8c16a22ae), [#6799](https://github.com/heygen-com/hyperframes/pull/6799)).
+- **Registry:** Caption components keep the last phrase until its last word ends ([32c01c99a](https://github.com/heygen-com/hyperframes/commit/32c01c99a1bbe12e329c4d5812995b07600a1a8a), [#6792](https://github.com/heygen-com/hyperframes/pull/6792)).
+
+## Internal
+
+- **Studio:** Edit accuracy screenshots are viewport-only and taken in the confirmation re-runs ([36cf990d9](https://github.com/heygen-com/hyperframes/commit/36cf990d99a6c585c2d28219823134b5743e5ee1), [#6795](https://github.com/heygen-com/hyperframes/pull/6795)).
+- **CLI:** A failed late-image snapshot reports why it failed ([27e16becb](https://github.com/heygen-com/hyperframes/commit/27e16becb1e9888a83df0b664a4fcdb932ce4c71), [#6793](https://github.com/heygen-com/hyperframes/pull/6793)).
+- **Studio:** Split edit accuracy into 15 PR shards packed by measured case time ([2a9dd0598](https://github.com/heygen-com/hyperframes/commit/2a9dd059830437403c755c49fd465b570b8c6d6b), [#6784](https://github.com/heygen-com/hyperframes/pull/6784)).
+
+[View the full commit range](https://github.com/heygen-com/hyperframes/compare/v0.8.220...v0.8.221).
+
+
+
+Playback no longer stalls at a cut while the next clip has not started, which removes a stutter at every cut. Text-to-speech also finds its voice package when your shell sets a PYTHONPATH.
+
+## Fixes
+
+- **Core:** The playhead keeps moving at a cut while the incoming take has not started ([471d60a8a](https://github.com/heygen-com/hyperframes/commit/471d60a8ac5f5a9824c5dde6c8d487bd0e436174), [#6768](https://github.com/heygen-com/hyperframes/pull/6768)).
+- **Core:** A still sub-composition's data-no-timeline on its template root skips the timeline wait ([c5a52037c](https://github.com/heygen-com/hyperframes/commit/c5a52037c92), [#6762](https://github.com/heygen-com/hyperframes/pull/6762)).
+- **CLI:** Check flags caption words hidden behind a cut-out and ignores a mostly transparent cover ([f523ee2fc](https://github.com/heygen-com/hyperframes/commit/f523ee2fcac), [#6770](https://github.com/heygen-com/hyperframes/pull/6770)).
+- **CLI:** Text-to-speech ignores a foreign PYTHONPATH when it looks for kokoro-onnx ([d1c059371](https://github.com/heygen-com/hyperframes/commit/d1c0593717d50fe4cd374775f8519df22b6ed517), [#6769](https://github.com/heygen-com/hyperframes/pull/6769)).
+
+[View the full commit range](https://github.com/heygen-com/hyperframes/compare/v0.8.219...v0.8.220).
+
+
+
+On Windows, check, snapshot and render no longer stop with an error about a locked Chrome log file. Render with no output path now saves into the project folder, and normalize-audio no longer makes a quiet clip quieter.
+
+## Fixes
+
+- **CLI:** A locked Chrome debug.log on Windows no longer fails check, snapshot or render ([6874cc289](https://github.com/heygen-com/hyperframes/commit/6874cc289012f31a0c9441d7fff12a277080c077), [#6771](https://github.com/heygen-com/hyperframes/pull/6771)).
+- **CLI:** Normalize-audio never cuts a clip that is quieter than the target ([9c01e2e12](https://github.com/heygen-com/hyperframes/commit/9c01e2e1213f89451b7f19c4883f60899aa8910d), [#6767](https://github.com/heygen-com/hyperframes/pull/6767)).
+- **CLI:** Render with no -o writes to the project's renders folder from any directory ([aa094f385](https://github.com/heygen-com/hyperframes/commit/aa094f385838cbaca4f85036a6cbe5905c88f2ee), [#6766](https://github.com/heygen-com/hyperframes/pull/6766)).
+
+[View the full commit range](https://github.com/heygen-com/hyperframes/compare/v0.8.218...v0.8.219).
+
+
+
+The CLI now signs in with its own HyperFrames account link, separate from the HeyGen CLI. Run `hyperframes auth login` once after upgrading, and cloud work then bills to your HyperFrames plan.
+
+## Features
+
+- **CLI:** The CLI signs in with its own HyperFrames OAuth client and keeps its login apart from the HeyGen CLI, so one tool's sign-in no longer overwrites the other's. Existing users sign in again once. A `HEYGEN_API_KEY` still works as before ([3e462f427](https://github.com/heygen-com/hyperframes/commit/3e462f427723e81352fea956b155848428cf1319), [#6687](https://github.com/heygen-com/hyperframes/pull/6687)).
+
+[View the full commit range](https://github.com/heygen-com/hyperframes/compare/v0.8.217...v0.8.218).
+
+
+
+The preview no longer hangs when a scene cannot close. Render errors name the kind of missing file, never its path, and a project .env only sets the CLI's own settings.
+
+## Features
+
+- **CLI:** A render that finds a file missing says which kind of file, never its path ([943849025](https://github.com/heygen-com/hyperframes/commit/943849025a4d44d740ef94414cc8f422dbad2a52), [#6742](https://github.com/heygen-com/hyperframes/pull/6742)).
+- **CLI:** A feedback report names why the last check failed ([eab6541f5](https://github.com/heygen-com/hyperframes/commit/eab6541f5ba017aa7b8bb53263a40105ace6168e), [#6717](https://github.com/heygen-com/hyperframes/pull/6717)).
+
+## Fixes
+
+- **CLI:** A project .env only sets the CLI's own settings ([838f8782c](https://github.com/heygen-com/hyperframes/commit/838f8782c4a96913d1627cd344be8431e7c44019), [#6565](https://github.com/heygen-com/hyperframes/pull/6565)).
+- **Core:** The preview's scene window settles when a scene can't unmount instead of hanging the page ([93f3d3dcb](https://github.com/heygen-com/hyperframes/commit/93f3d3dcbbcc1820b7827d2bd688d61eb334c693), [#6740](https://github.com/heygen-com/hyperframes/pull/6740)).
+- **CLI:** Allow-occlusion on the covering element silences text_occluded ([1a80b5407](https://github.com/heygen-com/hyperframes/commit/1a80b5407d6383be0922245389d93d94a3de86a0), [#6741](https://github.com/heygen-com/hyperframes/pull/6741)).
+- **Engine:** Long films show progress during the effect check and never wait minutes on it ([e1a8c7f17](https://github.com/heygen-com/hyperframes/commit/e1a8c7f1730149a81d5aa5863b963487a2e3955e), [#6697](https://github.com/heygen-com/hyperframes/pull/6697)).
+- **CLI:** A failed render's code comes only from the producer's list of safe codes ([0da46832e](https://github.com/heygen-com/hyperframes/commit/0da46832ef9ddaa0e4f6941b02f066ae7c0b53dc), [#6737](https://github.com/heygen-com/hyperframes/pull/6737)).
+- **Core:** Telemetry redaction covers folders with spaces in any script ([71f716a91](https://github.com/heygen-com/hyperframes/commit/71f716a91bc625e9243c5f25c194a114bb555668), [#6734](https://github.com/heygen-com/hyperframes/pull/6734)).
+- **CLI:** Snapshot says FFmpeg was stopped when it exits 255 with no output ([94203ad43](https://github.com/heygen-com/hyperframes/commit/94203ad431678f85e20a2de17852f7f9c5e1ba04), [#6718](https://github.com/heygen-com/hyperframes/pull/6718)).
+
+
+[View the full commit range](https://github.com/heygen-com/hyperframes/compare/v0.8.216...v0.8.217).
+
+
+
+This release carries every change from v0.8.215, which never reached npm. iPhone Safari keeps every take's sound, multi-worker renders land each frame in place, and encoding runs faster.
+
+## Features
+
+- **Telemetry:** Identify signed-in CLI users by their HyperFrames user id, and say signed-in usage is not anonymous ([1c3fcf4d2](https://github.com/heygen-com/hyperframes/commit/1c3fcf4d237d031107baa6a5646b5bb1ee82cc2a), [#6703](https://github.com/heygen-com/hyperframes/pull/6703)).
+- **Producer:** Report which element set the film length ([3ca1005a8](https://github.com/heygen-com/hyperframes/commit/3ca1005a81e76565a69d5874371c857321b66d59), [#6689](https://github.com/heygen-com/hyperframes/pull/6689)).
+
+## Fixes
+
+- **Player:** iPhone Safari keeps every take's sound after the first seconds of an edit ([48ba0e5b2](https://github.com/heygen-com/hyperframes/commit/48ba0e5b2bf91fc816adc0a7769d7344091aa5d7), [#6724](https://github.com/heygen-com/hyperframes/pull/6724)).
+- **AWS Lambda:** The release ffmpeg build falls back to verified mirrors when a source host is down ([f0665f718](https://github.com/heygen-com/hyperframes/commit/f0665f71813278b0e6999df68de691e51d52679d), [#6728](https://github.com/heygen-com/hyperframes/pull/6728)).
+- **CLI:** A failed render names its failure code for the Desktop app ([ba8ffffa0](https://github.com/heygen-com/hyperframes/commit/ba8ffffa0b5695d207cc89949e90e5902839fd67), [#6725](https://github.com/heygen-com/hyperframes/pull/6725)).
+- **CLI:** A snapshot still shows what playback shows, whatever other times are asked for ([cf1589242](https://github.com/heygen-com/hyperframes/commit/cf15892425245da96dc43d858a7478031533d2f1), [#6720](https://github.com/heygen-com/hyperframes/pull/6720)).
+- **CLI:** The lint summary points at hyperframes lint, not a flag only render takes ([98a28cc4b](https://github.com/heygen-com/hyperframes/commit/98a28cc4b2919f1c8418d2cb61bafc66ec9ccb31), [#6723](https://github.com/heygen-com/hyperframes/pull/6723)).
+- **Ci:** Skills sync steps past the five hidden ClawHub versions blocking it ([49e031230](https://github.com/heygen-com/hyperframes/commit/49e0312300d6c049b19eb8435930f980621a993f), [#6713](https://github.com/heygen-com/hyperframes/pull/6713)).
+- **CLI:** An unknown command like search says which command does that ([bb4deb801](https://github.com/heygen-com/hyperframes/commit/bb4deb8014a8457425c2e6e4a8619969514824ea), [#6710](https://github.com/heygen-com/hyperframes/pull/6710)).
+- **CLI:** Check says how many browser-playable copies are done while it makes them ([2f8c4b1da](https://github.com/heygen-com/hyperframes/commit/2f8c4b1dafaebc26f4dcfe6252312faf39ff9d89), [#6712](https://github.com/heygen-com/hyperframes/pull/6712)).
+- **Core:** A multi-worker or chunked render lands every frame where an in-order render does ([fa9acbd73](https://github.com/heygen-com/hyperframes/commit/fa9acbd7399b7cd5ca9940399d9066bb33d96973), [#6707](https://github.com/heygen-com/hyperframes/pull/6707)).
+- **CLI:** Check says a lint error is why the browser pass was skipped ([11312b359](https://github.com/heygen-com/hyperframes/commit/11312b359b18c07911615656b95f48c7d8d82fea), [#6709](https://github.com/heygen-com/hyperframes/pull/6709)).
+- **CLI:** Capture names the network's proxy when it refuses the connection to the site ([f0c5db6ea](https://github.com/heygen-com/hyperframes/commit/f0c5db6ea266a5a96907e66ef762e0f6dd85d623), [#6706](https://github.com/heygen-com/hyperframes/pull/6706)).
+- **CLI:** Check waits as long as the --timeout it was given before it counts as idle ([6c1765933](https://github.com/heygen-com/hyperframes/commit/6c17659337d50b578c5c54ae716308a13eb2c822), [#6705](https://github.com/heygen-com/hyperframes/pull/6705)).
+- **CLI:** Audio windows read beats off the whole clip; beats snap to the signal and mark silence ([4fa5f5451](https://github.com/heygen-com/hyperframes/commit/4fa5f54519150566b8ef706f60c05ff13c903423), [#6692](https://github.com/heygen-com/hyperframes/pull/6692)).
+- **Producer:** A BeginFrame capture that draws no first frame in 20 s switches to screenshot ([a5496b188](https://github.com/heygen-com/hyperframes/commit/a5496b1887950777b78ed5ac2bff3505961cb5fe), [#6701](https://github.com/heygen-com/hyperframes/pull/6701)).
+- **CLI:** Media-treatment --capability preset finds the presets area ([cfa653af4](https://github.com/heygen-com/hyperframes/commit/cfa653af4d0f95d751286fb25c8d38bdb56ef663), [#6700](https://github.com/heygen-com/hyperframes/pull/6700)).
+- **CLI:** A Windows render no longer prints taskkill's already-exited message ([ac449555f](https://github.com/heygen-com/hyperframes/commit/ac449555f4607ea65895628164cb2835afdd0ce5), [#6698](https://github.com/heygen-com/hyperframes/pull/6698)).
+- **CLI:** Snapshot reads https video in the Desktop app instead of failing at ffprobe ([0620067eb](https://github.com/heygen-com/hyperframes/commit/0620067eb096fee9b6748efb9421d852d540cbf6), [#6699](https://github.com/heygen-com/hyperframes/pull/6699)).
+- **CLI:** A stopped model download resumes on the next run instead of starting over ([81959201f](https://github.com/heygen-com/hyperframes/commit/81959201f0acb2e265e4d8c30daa89ffc1c9607d), [#6694](https://github.com/heygen-com/hyperframes/pull/6694)).
+- **CLI:** Media-treatment finds an area by the name its overview prints ([2c3d1e07f](https://github.com/heygen-com/hyperframes/commit/2c3d1e07fe63d4a2d67d63a3e29d4ad73e291d8e), [#6675](https://github.com/heygen-com/hyperframes/pull/6675)).
+- **Engine:** Downloads refuse hosts that resolve to private addresses ([9830059bd](https://github.com/heygen-com/hyperframes/commit/9830059bdb08adbab473d059d1b6db2230a5bb15), [#6571](https://github.com/heygen-com/hyperframes/pull/6571)).
+- **CLI:** Check no longer reports outline text as not painted ([9f65efb19](https://github.com/heygen-com/hyperframes/commit/9f65efb19c3f435ef58f6fc81c6909d2a3920f8a), [#6693](https://github.com/heygen-com/hyperframes/pull/6693)).
+- **CLI:** Beats --json answers with no track when the composition has no music ([ec10aae54](https://github.com/heygen-com/hyperframes/commit/ec10aae54fd3bcadaebb7e935a2b53d788fee074), [#6690](https://github.com/heygen-com/hyperframes/pull/6690)).
+- **Core:** Graded media honors object-position vertically instead of mirroring it ([aa4a71fe4](https://github.com/heygen-com/hyperframes/commit/aa4a71fe417401b5d8a69cff36f56319defd3ba7), [#6691](https://github.com/heygen-com/hyperframes/pull/6691)).
+- **Studio:** Audio keeps playing after a timeline move or trim in a static composition ([9aa6346a7](https://github.com/heygen-com/hyperframes/commit/9aa6346a779328f1c0963ec3d37b856ad164c969), [#6428](https://github.com/heygen-com/hyperframes/pull/6428)).
+- **Engine:** A render from an app that bundles the engine stamps the engine's version ([cdc86117c](https://github.com/heygen-com/hyperframes/commit/cdc86117c7ffa6bf087017035ea17149b98303da), [#6686](https://github.com/heygen-com/hyperframes/pull/6686)).
+- **Studio:** An undo or redo counts as a preview change from its key, not from its reload ([710314c15](https://github.com/heygen-com/hyperframes/commit/710314c15e11bb1f49cd83117f42b3cf2b2fc62e), [#6683](https://github.com/heygen-com/hyperframes/pull/6683)).
+- **Producer:** A capture that landed every frame is not failed for the work after its last frame ([067cbf7ac](https://github.com/heygen-com/hyperframes/commit/067cbf7acf55e54517650b5ade24cfa352806c04), [#6674](https://github.com/heygen-com/hyperframes/pull/6674)).
+- **CLI:** Check no longer treats a transparent canvas as covering the frame ([203a08dd7](https://github.com/heygen-com/hyperframes/commit/203a08dd7c1d4856e04e6a1288915a4b6f5fa2f6), [#6681](https://github.com/heygen-com/hyperframes/pull/6681)).
+- **Core:** Grade groups resolve per composition; freeze frames keep their lane ([c569760a7](https://github.com/heygen-com/hyperframes/commit/c569760a7a7c96df6540d53bbfe4670225ae140e), [#6685](https://github.com/heygen-com/hyperframes/pull/6685)).
+
+## Performance
+
+- **Engine:** Encode high quality with the x264 fast preset ([be05c8693](https://github.com/heygen-com/hyperframes/commit/be05c86932be215ec70621dc568af96415555fa0), [#6640](https://github.com/heygen-com/hyperframes/pull/6640)).
+- **Engine:** Size render workers from measured heap and the container's CPU quota ([cd003e201](https://github.com/heygen-com/hyperframes/commit/cd003e201051317234598bcf1c70cfed4770613f), [#6641](https://github.com/heygen-com/hyperframes/pull/6641)).
+- **Producer:** The audio true-peak check seeks to each segment instead of decoding up to it ([c2cde2fb6](https://github.com/heygen-com/hyperframes/commit/c2cde2fb624ba5a311615574dff822a41f61ea96), [#6672](https://github.com/heygen-com/hyperframes/pull/6672)).
+
+## Docs & Examples
+
+- **CLI:** Say which audio probes run once per file ([5d437d5ee](https://github.com/heygen-com/hyperframes/commit/5d437d5eecd65f05daa4ff451ebb85b71f88fdb9), [#6731](https://github.com/heygen-com/hyperframes/pull/6731)).
+- **CLI:** List check's audio findings with severity, trigger and fix ([fa97f9d4b](https://github.com/heygen-com/hyperframes/commit/fa97f9d4b7b4f401560dcc3e642267e953a2a89e), [#6730](https://github.com/heygen-com/hyperframes/pull/6730)).
+
+## Catalog
+
+- **Skills:** The registry skill says its commands are catalog and add ([1428f8768](https://github.com/heygen-com/hyperframes/commit/1428f876899557a4fe4448a6ac327ff503be53f5), [#6680](https://github.com/heygen-com/hyperframes/pull/6680)).
+
+## Internal
+
+- One regression shard writes the test image cache ([74f323473](https://github.com/heygen-com/hyperframes/commit/74f3234736ad87568831ed51c34a7e289dc668e6), [#6729](https://github.com/heygen-com/hyperframes/pull/6729)).
+- **CLI:** The publish abort test checks the summary hint is absent ([077de9bfe](https://github.com/heygen-com/hyperframes/commit/077de9bfe9f248c0807ba2c7f78d1514adf85bc6), [#6726](https://github.com/heygen-com/hyperframes/pull/6726)).
+
+[View the full commit range](https://github.com/heygen-com/hyperframes/compare/v0.8.214...v0.8.216).
+
+
+
+Multi-worker and chunked exports no longer twitch where the preview plays clean. Snapshot reads https video in the Desktop app, and a stopped model download resumes.
+
+## Features
+
+- **Telemetry:** Identify signed-in CLI users by their HyperFrames user id, and say signed-in usage is not anonymous ([1c3fcf4d2](https://github.com/heygen-com/hyperframes/commit/1c3fcf4d237d031107baa6a5646b5bb1ee82cc2a), [#6703](https://github.com/heygen-com/hyperframes/pull/6703)).
+- **Producer:** Report which element set the film length ([3ca1005a8](https://github.com/heygen-com/hyperframes/commit/3ca1005a81e76565a69d5874371c857321b66d59), [#6689](https://github.com/heygen-com/hyperframes/pull/6689)).
+
+## Fixes
+
+- **CLI:** An unknown command like search says which command does that ([bb4deb801](https://github.com/heygen-com/hyperframes/commit/bb4deb8014a8457425c2e6e4a8619969514824ea), [#6710](https://github.com/heygen-com/hyperframes/pull/6710)).
+- **CLI:** Check says how many browser-playable copies are done while it makes them ([2f8c4b1da](https://github.com/heygen-com/hyperframes/commit/2f8c4b1dafaebc26f4dcfe6252312faf39ff9d89), [#6712](https://github.com/heygen-com/hyperframes/pull/6712)).
+- **Core:** A multi-worker or chunked render lands every frame where an in-order render does ([fa9acbd73](https://github.com/heygen-com/hyperframes/commit/fa9acbd7399b7cd5ca9940399d9066bb33d96973), [#6707](https://github.com/heygen-com/hyperframes/pull/6707)).
+- **CLI:** Check says a lint error is why the browser pass was skipped ([11312b359](https://github.com/heygen-com/hyperframes/commit/11312b359b18c07911615656b95f48c7d8d82fea), [#6709](https://github.com/heygen-com/hyperframes/pull/6709)).
+- **CLI:** Capture names the network's proxy when it refuses the connection to the site ([f0c5db6ea](https://github.com/heygen-com/hyperframes/commit/f0c5db6ea266a5a96907e66ef762e0f6dd85d623), [#6706](https://github.com/heygen-com/hyperframes/pull/6706)).
+- **CLI:** Check waits as long as the --timeout it was given before it counts as idle ([6c1765933](https://github.com/heygen-com/hyperframes/commit/6c17659337d50b578c5c54ae716308a13eb2c822), [#6705](https://github.com/heygen-com/hyperframes/pull/6705)).
+- **CLI:** Audio windows read beats off the whole clip; beats snap to the signal and mark silence ([4fa5f5451](https://github.com/heygen-com/hyperframes/commit/4fa5f54519150566b8ef706f60c05ff13c903423), [#6692](https://github.com/heygen-com/hyperframes/pull/6692)).
+- **Producer:** A BeginFrame capture that draws no first frame in 20 s switches to screenshot ([a5496b188](https://github.com/heygen-com/hyperframes/commit/a5496b1887950777b78ed5ac2bff3505961cb5fe), [#6701](https://github.com/heygen-com/hyperframes/pull/6701)).
+- **CLI:** Media-treatment --capability preset finds the presets area ([cfa653af4](https://github.com/heygen-com/hyperframes/commit/cfa653af4d0f95d751286fb25c8d38bdb56ef663), [#6700](https://github.com/heygen-com/hyperframes/pull/6700)).
+- **CLI:** A Windows render no longer prints taskkill's already-exited message ([ac449555f](https://github.com/heygen-com/hyperframes/commit/ac449555f4607ea65895628164cb2835afdd0ce5), [#6698](https://github.com/heygen-com/hyperframes/pull/6698)).
+- **CLI:** Snapshot reads https video in the Desktop app instead of failing at ffprobe ([0620067eb](https://github.com/heygen-com/hyperframes/commit/0620067eb096fee9b6748efb9421d852d540cbf6), [#6699](https://github.com/heygen-com/hyperframes/pull/6699)).
+- **CLI:** A stopped model download resumes on the next run instead of starting over ([81959201f](https://github.com/heygen-com/hyperframes/commit/81959201f0acb2e265e4d8c30daa89ffc1c9607d), [#6694](https://github.com/heygen-com/hyperframes/pull/6694)).
+- **CLI:** Media-treatment finds an area by the name its overview prints ([2c3d1e07f](https://github.com/heygen-com/hyperframes/commit/2c3d1e07fe63d4a2d67d63a3e29d4ad73e291d8e), [#6675](https://github.com/heygen-com/hyperframes/pull/6675)).
+- **Engine:** Downloads refuse hosts that resolve to private addresses ([9830059bd](https://github.com/heygen-com/hyperframes/commit/9830059bdb08adbab473d059d1b6db2230a5bb15), [#6571](https://github.com/heygen-com/hyperframes/pull/6571)).
+- **CLI:** Check no longer reports outline text as not painted ([9f65efb19](https://github.com/heygen-com/hyperframes/commit/9f65efb19c3f435ef58f6fc81c6909d2a3920f8a), [#6693](https://github.com/heygen-com/hyperframes/pull/6693)).
+- **CLI:** Beats --json answers with no track when the composition has no music ([ec10aae54](https://github.com/heygen-com/hyperframes/commit/ec10aae54fd3bcadaebb7e935a2b53d788fee074), [#6690](https://github.com/heygen-com/hyperframes/pull/6690)).
+- **Core:** Graded media honors object-position vertically instead of mirroring it ([aa4a71fe4](https://github.com/heygen-com/hyperframes/commit/aa4a71fe417401b5d8a69cff36f56319defd3ba7), [#6691](https://github.com/heygen-com/hyperframes/pull/6691)).
+- **Studio:** Audio keeps playing after a timeline move or trim in a static composition ([9aa6346a7](https://github.com/heygen-com/hyperframes/commit/9aa6346a779328f1c0963ec3d37b856ad164c969), [#6428](https://github.com/heygen-com/hyperframes/pull/6428)).
+- **Engine:** A render from an app that bundles the engine stamps the engine's version ([cdc86117c](https://github.com/heygen-com/hyperframes/commit/cdc86117c7ffa6bf087017035ea17149b98303da), [#6686](https://github.com/heygen-com/hyperframes/pull/6686)).
+- **Studio:** An undo or redo counts as a preview change from its key, not from its reload ([710314c15](https://github.com/heygen-com/hyperframes/commit/710314c15e11bb1f49cd83117f42b3cf2b2fc62e), [#6683](https://github.com/heygen-com/hyperframes/pull/6683)).
+- **Producer:** A capture that landed every frame is not failed for the work after its last frame ([067cbf7ac](https://github.com/heygen-com/hyperframes/commit/067cbf7acf55e54517650b5ade24cfa352806c04), [#6674](https://github.com/heygen-com/hyperframes/pull/6674)).
+- **CLI:** Check no longer treats a transparent canvas as covering the frame ([203a08dd7](https://github.com/heygen-com/hyperframes/commit/203a08dd7c1d4856e04e6a1288915a4b6f5fa2f6), [#6681](https://github.com/heygen-com/hyperframes/pull/6681)).
+- **Core:** Grade groups resolve per composition; freeze frames keep their lane ([c569760a7](https://github.com/heygen-com/hyperframes/commit/c569760a7a7c96df6540d53bbfe4670225ae140e), [#6685](https://github.com/heygen-com/hyperframes/pull/6685)).
+
+## Performance
+
+- **Producer:** The audio true-peak check seeks to each segment instead of decoding up to it ([c2cde2fb6](https://github.com/heygen-com/hyperframes/commit/c2cde2fb624ba5a311615574dff822a41f61ea96), [#6672](https://github.com/heygen-com/hyperframes/pull/6672)).
+
+## Catalog
+
+- **Skills:** The registry skill says its commands are catalog and add ([1428f8768](https://github.com/heygen-com/hyperframes/commit/1428f876899557a4fe4448a6ac327ff503be53f5), [#6680](https://github.com/heygen-com/hyperframes/pull/6680)).
+
+[View the full commit range](https://github.com/heygen-com/hyperframes/compare/v0.8.214...v0.8.215).
+
+
img.nav-logo) {
margin-left: 16px;
}
@@ -1831,3 +1840,16 @@ pre.shiki {
.hf-remix-credit, .hf-remix-help { color: var(--hf-text-secondary); }
.hf-remix-credit a { color: inherit; }
.hf-remix-btn { background: var(--hf-heading); color: var(--hf-background); }
+
+/* Catalog item pages: the title, the standfirst and the Docs tab are written into the page itself
+ (scripts/generate-catalog-pages.ts), because Mintlify renders snippet components in the browser only and
+ search engines read the server HTML. CatalogDetail adds the player, tabs and tools around them. */
+.hf-ve-static-head { margin: 24px 0 28px; } /* the component's own my-4 (16px) + its header's 8px */
+.hf-ve-static-head h1 { margin: 0; font-size: 44px; line-height: 1.1; font-weight: 700; letter-spacing: -0.02em; color: var(--hf-text); }
+.hf-ve-static-head p { margin: 12px 0 0; font-size: 18px; line-height: 1.5; color: var(--hf-text-secondary); max-width: 70ch; }
+html.dark .hf-ve-static-head h1 { color: #f5f3f1; }
+html.dark .hf-ve-static-head p { color: #b8b6b4; }
+@media (max-width: 640px) { .hf-ve-static-head h1 { font-size: 32px; } }
+/* The Docs tab's text sits after the component and shows only while that tab is open, as the tab's own slot did. */
+[data-static-slot] { display: none; }
+body:has(.hf-ve-slots[data-tab="docs"]) [data-static-slot="docs"] { display: block; }
diff --git a/docs/docs.json b/docs/docs.json
index 5181593ef2..d89286f855 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -25,7 +25,7 @@
"logo": {
"light": "/logo/light.svg",
"dark": "/logo/dark.svg",
- "href": "https://hyperframes.heygen.com/introduction"
+ "href": "https://hyperframes.heygen.com/"
},
"favicon": "/favicon.svg",
"contextual": {
@@ -48,127 +48,291 @@
"navigation": {
"tabs": [
{
- "tab": "Make a video",
+ "tab": "Docs",
"icon": "book-open",
- "groups": [
+ "menu": [
{
- "group": "Start here",
- "pages": [
- "introduction",
- "quickstart",
- "examples",
- "faq"
- ]
- },
- {
- "group": "Make a video",
- "pages": [
- "workflows",
- "guides/product-launch-video",
- "guides/faceless-explainer",
- "guides/motion-graphics",
- "guides/captions-and-recuts",
- "guides/music-to-video",
- "prompting/data-and-maps",
- "guides/avatar-presenter",
- "guides/pr-to-video",
- "guides/slideshow",
- "guides/general-video"
- ]
- },
- {
- "group": "Use it with your agent",
- "pages": [
- "guides/with-claude-code",
- "guides/with-codex",
- "guides/with-cursor",
- "guides/mcp",
- "guides/free-agents",
- "guides/skills",
- "guides/plugins",
- "guides/design-tools"
- ]
- },
- {
- "group": "Compare",
- "pages": [
- "guides/hyperframes-vs-remotion",
- "prompting/remotion-migration"
- ]
- },
- {
- "group": "Tips for better videos",
- "pages": [
- "prompting/overview",
- "prompting/motion",
- "prompting/media-and-audio",
- "prompting/captions-catalog",
- "prompting/color-grading",
- "prompting/design-systems",
+ "item": "Make a video",
+ "icon": "book-open",
+ "description": "Guides by kind of video",
+ "groups": [
{
- "group": "More prompt topics",
+ "group": "Start here",
"pages": [
- "prompting/examples",
- "prompting/editing-existing-videos",
- "prompting/recreating-references",
- "prompting/capstone"
+ "introduction",
+ "quickstart",
+ "examples",
+ "faq"
+ ]
+ },
+ {
+ "group": "Make a video",
+ "pages": [
+ "workflows",
+ "guides/product-launch-video",
+ "guides/faceless-explainer",
+ "guides/motion-graphics",
+ "guides/captions-and-recuts",
+ "guides/music-to-video",
+ "prompting/data-and-maps",
+ "guides/avatar-presenter",
+ "guides/pr-to-video",
+ "guides/slideshow",
+ "guides/general-video"
+ ]
+ },
+ {
+ "group": "Use it with your agent",
+ "pages": [
+ "guides/with-claude-code",
+ "guides/with-codex",
+ "guides/with-cursor",
+ "guides/mcp",
+ "guides/free-agents",
+ "guides/skills",
+ "guides/plugins",
+ "guides/design-tools"
+ ]
+ },
+ {
+ "group": "Compare",
+ "pages": [
+ "guides/hyperframes-vs-remotion",
+ "prompting/remotion-migration"
+ ]
+ },
+ {
+ "group": "Tips for better videos",
+ "pages": [
+ "prompting/overview",
+ "prompting/motion",
+ "prompting/media-and-audio",
+ "prompting/captions-catalog",
+ "prompting/color-grading",
+ "prompting/design-systems",
+ {
+ "group": "More prompt topics",
+ "pages": [
+ "prompting/examples",
+ "prompting/editing-existing-videos",
+ "prompting/recreating-references",
+ "prompting/capstone"
+ ]
+ }
+ ]
+ },
+ {
+ "group": "Images, sound and footage",
+ "pages": [
+ "guides/media",
+ "guides/video-components",
+ "guides/voice-and-audio",
+ "guides/remove-background",
+ "guides/media-effects",
+ "guides/export-and-share"
+ ]
+ },
+ {
+ "group": "Browser editor",
+ "pages": [
+ "studio/index",
+ "studio/canvas",
+ "studio/timeline",
+ "studio/audio-effects",
+ "studio/assets-and-blocks",
+ "studio/export"
+ ]
+ },
+ {
+ "group": "Help and updates",
+ "pages": [
+ "help",
+ "thirty-days",
+ "product-updates",
+ "weekly-updates",
+ "changelog"
]
}
]
},
{
- "group": "Images, sound and footage",
- "pages": [
- "guides/media",
- "guides/video-components",
- "guides/voice-and-audio",
- "guides/remove-background",
- "guides/media-effects",
- "guides/export-and-share"
+ "item": "Studio app",
+ "icon": "laptop",
+ "description": "The desktop app",
+ "groups": [
+ {
+ "group": "Studio app",
+ "pages": [
+ "studio-app/index",
+ "studio-app/first-video",
+ "studio-app/existing-project",
+ "studio-app/reference-video",
+ "studio-app/brand-kits",
+ "studio-app/video-clips",
+ "studio-app/edit-with-the-agent",
+ "studio-app/workspace",
+ "studio-app/connect-your-agent",
+ "studio-app/export",
+ "studio-app/share"
+ ]
+ }
]
},
{
- "group": "Browser editor",
- "pages": [
- "studio/index",
- "studio/canvas",
- "studio/timeline",
- "studio/audio-effects",
- "studio/assets-and-blocks",
- "studio/export"
+ "item": "Developers",
+ "icon": "code",
+ "description": "CLI, SDK and reference",
+ "groups": [
+ {
+ "group": "Start here",
+ "pages": [
+ "developers/overview",
+ "developers/index",
+ "concepts/index"
+ ]
+ },
+ {
+ "group": "Command line",
+ "pages": [
+ "developers/cli",
+ "packages/cli",
+ "developers/catalog-search",
+ "developers/harness-tool-context",
+ "packages/lint"
+ ]
+ },
+ {
+ "group": "SDK guides",
+ "pages": [
+ "sdk/quickstart",
+ "sdk/guides/querying-and-editing",
+ "sdk/guides/timing-and-animation",
+ "sdk/guides/undo-redo-and-patches",
+ "sdk/guides/persistence",
+ "sdk/guides/embedded-override-mode",
+ "sdk/guides/canvas-integration",
+ "sdk/guides/editing-affordances"
+ ]
+ },
+ {
+ "group": "SDK reference",
+ "pages": [
+ "sdk/reference/open-composition",
+ "sdk/reference/composition",
+ "sdk/reference/edit-operations",
+ "sdk/reference/types",
+ "sdk/reference/adapters",
+ "sdk/reference/utilities"
+ ]
+ },
+ {
+ "group": "Composition, design & animation",
+ "pages": [
+ "concepts/compositions",
+ "concepts/variables",
+ "concepts/data-attributes",
+ "guides/gsap-animation",
+ "guides/frame-sources",
+ "guides/imported-film-html",
+ "concepts/frame-adapters",
+ "concepts/determinism",
+ "guides/html-in-canvas",
+ "guides/motion-blur",
+ "guides/vfx-chain",
+ "guides/figma"
+ ]
+ },
+ {
+ "group": "Composition reference",
+ "pages": [
+ "reference/html-schema",
+ "reference/color-grading",
+ "reference/audio-effects",
+ "reference/speed-ramps",
+ "reference/lint-rules"
+ ]
+ },
+ {
+ "group": "Rendering paths",
+ "pages": [
+ "guides/rendering",
+ "deploy/overview",
+ "deploy/cloud",
+ "guides/deploy"
+ ]
+ },
+ {
+ "group": "Cloud infrastructure",
+ "pages": [
+ "deploy/aws-lambda",
+ "deploy/gcp-cloud-run",
+ "deploy/templates-on-lambda",
+ "deploy/migrating-to-hyperframes-lambda",
+ "packages/aws-lambda",
+ "packages/gcp-cloud-run"
+ ]
+ },
+ {
+ "group": "Advanced rendering",
+ "pages": [
+ "guides/4k-rendering",
+ "guides/hdr",
+ "guides/performance"
+ ]
+ },
+ {
+ "group": "Packages",
+ "pages": [
+ "packages/core",
+ "packages/parsers",
+ "packages/studio-server",
+ "packages/sdk",
+ "packages/engine",
+ "packages/player",
+ "packages/producer",
+ "packages/shader-transitions",
+ "packages/studio"
+ ]
+ },
+ {
+ "group": "Agent setup",
+ "pages": [
+ "guides/authentication",
+ "guides/webmcp"
+ ]
+ },
+ {
+ "group": "Contributing & community",
+ "pages": [
+ "contributing",
+ "contributing/catalog",
+ "contributing/release-channels",
+ "contributing/agent-plugins",
+ "contributing/changelog-process",
+ "contributing/testing-local-changes",
+ "contributing/canary-rollouts",
+ "community/adopters"
+ ]
+ }
]
},
{
- "group": "Help and updates",
- "pages": [
- "help",
- "thirty-days",
- "product-updates",
- "weekly-updates",
- "changelog"
- ]
- }
- ]
- },
- {
- "tab": "Studio app",
- "icon": "laptop",
- "groups": [
+ "item": "Free lessons",
+ "icon": "graduation-cap",
+ "description": "A free video course",
+ "href": "https://hyperframes.heygen.com/lessons"
+ },
{
- "group": "Studio app",
- "pages": [
- "studio-app/index",
- "studio-app/first-video",
- "studio-app/existing-project",
- "studio-app/reference-video",
- "studio-app/brand-kits",
- "studio-app/video-clips",
- "studio-app/edit-with-the-agent",
- "studio-app/workspace",
- "studio-app/connect-your-agent",
- "studio-app/export",
- "studio-app/share"
- ]
+ "item": "Community",
+ "icon": "users",
+ "description": "Videos people made",
+ "href": "https://hyperframes.studio/?view=community"
+ },
+ {
+ "item": "App changelog",
+ "icon": "sparkles",
+ "description": "What's new in the app",
+ "href": "https://hyperframes.studio/changelog"
}
]
},
@@ -841,143 +1005,6 @@
]
}
]
- },
- {
- "tab": "Developers",
- "icon": "code",
- "groups": [
- {
- "group": "Start here",
- "pages": [
- "developers/overview",
- "developers/index",
- "concepts/index"
- ]
- },
- {
- "group": "Command line",
- "pages": [
- "developers/cli",
- "packages/cli",
- "developers/catalog-search",
- "developers/harness-tool-context",
- "packages/lint"
- ]
- },
- {
- "group": "SDK guides",
- "pages": [
- "sdk/quickstart",
- "sdk/guides/querying-and-editing",
- "sdk/guides/timing-and-animation",
- "sdk/guides/undo-redo-and-patches",
- "sdk/guides/persistence",
- "sdk/guides/embedded-override-mode",
- "sdk/guides/canvas-integration",
- "sdk/guides/editing-affordances"
- ]
- },
- {
- "group": "SDK reference",
- "pages": [
- "sdk/reference/open-composition",
- "sdk/reference/composition",
- "sdk/reference/edit-operations",
- "sdk/reference/types",
- "sdk/reference/adapters",
- "sdk/reference/utilities"
- ]
- },
- {
- "group": "Composition, design & animation",
- "pages": [
- "concepts/compositions",
- "concepts/variables",
- "concepts/data-attributes",
- "guides/gsap-animation",
- "guides/frame-sources",
- "guides/imported-film-html",
- "concepts/frame-adapters",
- "concepts/determinism",
- "guides/html-in-canvas",
- "guides/motion-blur",
- "guides/vfx-chain",
- "guides/figma"
- ]
- },
- {
- "group": "Composition reference",
- "pages": [
- "reference/html-schema",
- "reference/color-grading",
- "reference/audio-effects",
- "reference/speed-ramps",
- "reference/lint-rules"
- ]
- },
- {
- "group": "Rendering paths",
- "pages": [
- "guides/rendering",
- "deploy/overview",
- "deploy/cloud",
- "guides/deploy"
- ]
- },
- {
- "group": "Cloud infrastructure",
- "pages": [
- "deploy/aws-lambda",
- "deploy/gcp-cloud-run",
- "deploy/templates-on-lambda",
- "deploy/migrating-to-hyperframes-lambda",
- "packages/aws-lambda",
- "packages/gcp-cloud-run"
- ]
- },
- {
- "group": "Advanced rendering",
- "pages": [
- "guides/4k-rendering",
- "guides/hdr",
- "guides/performance"
- ]
- },
- {
- "group": "Packages",
- "pages": [
- "packages/core",
- "packages/parsers",
- "packages/studio-server",
- "packages/sdk",
- "packages/engine",
- "packages/player",
- "packages/producer",
- "packages/shader-transitions",
- "packages/studio"
- ]
- },
- {
- "group": "Agent setup",
- "pages": [
- "guides/authentication",
- "guides/webmcp"
- ]
- },
- {
- "group": "Contributing & community",
- "pages": [
- "contributing",
- "contributing/catalog",
- "contributing/release-channels",
- "contributing/agent-plugins",
- "contributing/changelog-process",
- "contributing/testing-local-changes",
- "contributing/canary-rollouts",
- "community/adopters"
- ]
- }
- ]
}
]
},
@@ -1043,10 +1070,6 @@
},
"navbar": {
"links": [
- {
- "label": "Lessons",
- "href": "https://hyperframes.heygen.com/lessons"
- },
{
"type": "github",
"href": "https://github.com/heygen-com/hyperframes"
@@ -1054,7 +1077,7 @@
],
"primary": {
"type": "button",
- "label": "Download Studio",
+ "label": "Download",
"href": "https://hyperframes.studio/studio/download?src=docs-navbar"
}
},
diff --git a/docs/guides/authentication.mdx b/docs/guides/authentication.mdx
index 3a7120eb18..6ed5831efa 100644
--- a/docs/guides/authentication.mdx
+++ b/docs/guides/authentication.mdx
@@ -37,7 +37,9 @@ Signing in is the same OAuth step as creating an account — new users land on t
-The credential lives in `~/.heygen/credentials` (mode `0600`) — no per-repo `.env` to manage. Browser OAuth is a `hyperframes auth login` feature. The separate [`heygen` CLI](https://github.com/heygen-com/heygen-cli) (its own install — there's no `npx heygen`) is API-key-only, so `heygen auth login` just stores a key you paste. Both read the same `~/.heygen/credentials`, so signing in with one carries to the other.
+HyperFrames uses its own public OAuth client and stores credentials in `~/.hyperframes/credentials` (mode `0600`). Sign in again after upgrading from the shared HeyGen login. The separate [`heygen` CLI](https://github.com/heygen-com/heygen-cli) keeps its own login in `~/.heygen`; HyperFrames does not move or delete it. An expired HyperFrames OAuth session requires refresh or sign-in and never selects a saved API key instead. An explicit API-key login or environment key selects API-key billing.
+
+`auth status` verifies identity. For a dedicated HyperFrames OAuth login it reports the billing product, but the HyperFrames balance is unavailable here: `/v3/users/me` returns generic HeyGen account billing fields. Those raw fields remain in JSON and are not presented as the HyperFrames balance. Host-injected or custom-client OAuth is reported as an unverified billing product.
No account is needed to try HyperFrames locally. With no credential, voice can
@@ -54,12 +56,11 @@ sound retrieval. It resolves first-match-wins:
2. `HEYGEN_ACCESS_TOKEN` — an OAuth token a host app injects
3. `HEYGEN_API_KEY` — environment variable
4. `HYPERFRAMES_API_KEY` — alias, for parity with other tools
-5. `~/.heygen/credentials` — written by `hyperframes auth login` (or `heygen auth login`)
+5. `~/.hyperframes/credentials` — written by `hyperframes auth login`
A nearby project `.env` can supply the keys, but never `HEYGEN_API_BASE`. Point at a different config directory
-with `HEYGEN_CONFIG_DIR`. The `hyperframes` CLI's own commands check the API keys before `HEYGEN_ACCESS_TOKEN`; see
-the [CLI reference](/packages/cli). `media-use resolve` searches through the separate `heygen` CLI, which resolves its
-own credential.
+with `HYPERFRAMES_CONFIG_DIR`. The `hyperframes` CLI's own commands check the API keys before `HEYGEN_ACCESS_TOKEN`; see
+the [CLI reference](/packages/cli). When `media-use` invokes the separate `heygen` executable, it supplies an isolated temporary credential containing the selected access token. That helper cannot refresh a HyperFrames grant or pick up another HeyGen login.
## Providers used by agent workflows
@@ -70,7 +71,7 @@ vision key is available.
| Capability | Provider order | Key(s) — first match wins | Local dependency |
|------------|----------------|---------------------------|------------------|
-| **Voice (TTS)** | HeyGen → ElevenLabs → Kokoro | `HEYGEN_API_KEY` → `HYPERFRAMES_API_KEY` → `~/.heygen` · then `ELEVENLABS_API_KEY` | Kokoro: `pip install kokoro-onnx soundfile` |
+| **Voice (TTS)** | HeyGen → ElevenLabs → Kokoro | `HEYGEN_API_KEY` → `HYPERFRAMES_API_KEY` → `~/.hyperframes` · then `ELEVENLABS_API_KEY` | Kokoro: `pip install kokoro-onnx soundfile` |
| **Music (BGM)** | HeyGen library → Lyria → MusicGen | HeyGen credential (above) · then `GEMINI_API_KEY` → `GOOGLE_API_KEY` | MusicGen: `pip install transformers torch soundfile numpy` |
| **Sound effects** | HeyGen library → bundled library | HeyGen credential (above) | bundled — no deps |
| **Capture descriptions** | OpenRouter → Gemini | `OPENROUTER_API_KEY` → `GEMINI_API_KEY` | None; optional for [website capture](/guides/product-launch-video) |
@@ -145,7 +146,9 @@ to a shared space with `--space`.
| `HEYGEN_ACCESS_TOKEN` | OAuth token a host app injects; never refreshed or saved. |
| `HEYGEN_API_BASE` | A host app's gateway for media workflows; never read from a project `.env`. |
| `HEYGEN_API_URL` | API base URL for `hyperframes` CLI commands (default `https://api.heygen.com`). |
-| `HEYGEN_CONFIG_DIR` | Credentials directory (default `~/.heygen`). |
+| `HYPERFRAMES_CONFIG_DIR` | HyperFrames credentials root (default `~/.hyperframes`). |
+| `HYPERFRAMES_ENV` | `prod` (default) or `dev`; switches OAuth and API defaults together. Dev credentials live under the root’s `dev/` directory. |
+| `HYPERFRAMES_OAUTH_CLIENT_ID` | Override the public client ID for a controlled OAuth environment. |
| `ELEVENLABS_API_KEY` | ElevenLabs TTS, used when no HeyGen credential is present. |
| `GEMINI_API_KEY` / `GOOGLE_API_KEY` | Explicit Gemini TTS selection and Lyria music generation; capture descriptions use `GEMINI_API_KEY`. |
| `GOOGLE_APPLICATION_CREDENTIALS` / `GCS_CREDS` | Gemini TTS service-account JSON file path / injected JSON. Used when neither API key is set. |
diff --git a/docs/guides/motion-blur.mdx b/docs/guides/motion-blur.mdx
index 0fe3c208ee..4289b18500 100644
--- a/docs/guides/motion-blur.mdx
+++ b/docs/guides/motion-blur.mdx
@@ -29,7 +29,7 @@ That is all. The same attribute drives the browser editor preview and `hyperfram
| `data-motion-blur` | none | `on` enables blur. `off` opts out, on the root or on any subtree. |
| `data-motion-blur-shutter` | `240` | Shutter angle in degrees, 0–720. Larger is a longer smear. |
| `data-motion-blur-samples` | at least 32 | A fixed number of samples per frame, 2–64. Left unset, each mover gets at least 32, and about one per 2 px of smear when that is more, so a fast move never shows steps. |
-| `data-motion-blur-events` | off | `on` runs timeline callbacks (`onUpdate` and similar) while blur looks for movers and at each sample. Needed when the motion is set from a callback, such as a `render(t)` function, which blur cannot otherwise see. |
+| `data-motion-blur-events` | off | `on` runs timeline callbacks (`onUpdate` and similar) while blur looks for movers, and at each sample when a callback changes an element's inline style or its box. Needed when the motion is set from a callback, such as a `render(t)` function, which blur cannot otherwise see. |
| `data-motion-blur-tier` | `auto` | `capture` or `filter` forces one of the two ways blur is drawn (below). |
## In the browser editor
diff --git a/docs/packages/cli.mdx b/docs/packages/cli.mdx
index f7f3a29405..ac0c7d34fd 100644
--- a/docs/packages/cli.mdx
+++ b/docs/packages/cli.mdx
@@ -28,11 +28,12 @@ npm install -g hyperframes
| Bring in source material | [`capture`](#capture), [`media-use`](#media-use), [`transcribe`](#transcribe), [`tts`](#tts), [`remove-background`](#remove-background), [`media-treatment`](#media-treatment), [`beats`](#beats), [`audio`](#audio), [`normalize-audio`](#normalize-audio), [`models`](#models) |
| Look at it, or share it | [`preview`](#preview), [`present`](#present-and-play), [`play`](#present-and-play), [`publish`](#publish), [`open`](#open-and-catch-up), [`catch-up`](#open-and-catch-up) |
| Find problems | [`lint`](#lint), [`check`](#check), [`snapshot`](#snapshot), [`keyframes`](#keyframes), [`compare`](#compare-and-grade-compare), [`grade-compare`](#compare-and-grade-compare) |
+| Rebuild a video | [`measure`](#measure), [`diff`](#diff) |
| Edit from the terminal | [`timeline`](#timeline), [`history`](#history) |
| Make a file | [`render`](#render), [`benchmark`](#benchmark) |
| Render somewhere else | [`cloud`](#hyperframes-cloud), [`lambda`](#hyperframes-lambda), [`cloudrun`](#hyperframes-cloudrun) |
| Fix your setup | [`doctor`](#doctor), [`browser`](#browser), [`upgrade`](#upgrade), [`docs`](#docs), [`info`](#info-and-compositions), [`compositions`](#info-and-compositions), [`clean`](#clean) |
-| Connect other tools | [`auth`](#hyperframes-auth), [`skills`](#skills), [`usage`](#usage), [`figma`](#figma-and-events), [`events`](#figma-and-events), [`telemetry`](#telemetry), [`feedback`](#feedback) |
+| Connect other tools | [`auth`](#hyperframes-auth), [`billing`](#billing), [`skills`](#skills), [`usage`](#usage), [`figma`](#figma-and-events), [`events`](#figma-and-events), [`telemetry`](#telemetry), [`feedback`](#feedback) |
`validate`, `inspect`, and `layout` still work but are
[deprecated](#deprecated-validate-inspect-and-layout). Use `check` instead.
@@ -85,6 +86,11 @@ machine-readable `code` and, when there is a next step, a `hint`:
Some commands add their own fields next to `error`, such as `findings` from
`lint` or `reason` and `fix` from a refused `timeline` edit.
+**The project `.env`.** The `.env` in the current directory sets only the CLI's own
+settings: `HEYGEN_API_KEY`, `HYPERFRAMES_API_KEY`, `ELEVENLABS_API_KEY`, `FIGMA_TOKEN`, and the
+vision keys, models, Vertex settings and timeout, and the telemetry opt-outs `HYPERFRAMES_NO_TELEMETRY` and `DO_NOT_TRACK`. A variable already in your environment wins. Any
+other key in the file is ignored, and one line on stderr names them.
+
**Flags, not prompts.** A missing required flag fails immediately with a usage
example rather than waiting for input. Two commands are interactive on a TTY:
`init` prompts for a project name and example unless you pass
@@ -682,19 +688,22 @@ and are copied to `~/.media/` so other projects can reuse them. Sound effects
under CC BY get their credit written to `.media/audio/sfx/CREDITS.md`.
**What needs an account, and what can cost money.** The HeyGen sources run
-through the separate `heygen` CLI, signed in with `heygen auth login --oauth`.
-Searching the music, image, and icon catalogs is free. Text to speech and avatar
-video draw on a free allowance when you are signed in with OAuth, then on your
-HeyGen billing, so an agent should ask before generating them. When a
+through the separate `heygen` executable using the login selected by
+`hyperframes auth login`. It receives a temporary access-token credential and
+cannot read the separate HeyGen login or refresh a HyperFrames grant.
+The server decides feature eligibility and charges. An explicit API-key credential
+uses API-key billing. When a
host app sets `HEYGEN_API_BASE` and `HEYGEN_API_KEY`, HeyGen calls go through that
host instead and are charged to its key. The `codex` image fallback uses your
ChatGPT subscription. Openverse, theSVG, GitHub, favicons, color grades, and the
local generators cost nothing. `doctor` exits 1 only when ffmpeg, ffprobe, or the
bundled sounds are missing; HeyGen problems are listed with a fix but do not fail it.
-`media-use` sends anonymous usage events — the media type, which source won, and
+`media-use` sends usage events — the media type, which source won, and
whether it reused a file, never your intent text or paths — and honors the same
-opt-outs as [`telemetry`](#telemetry).
+opt-outs as [`telemetry`](#telemetry). They are anonymous until you sign in to
+HeyGen; after that they are linked to your account, as described under
+[`telemetry`](#telemetry).
See [Voice, sound, and captions](/guides/voice-and-audio) and
[Color grading](/guides/media-effects#fix-and-grade-the-color) for the workflows around these assets, and
@@ -708,10 +717,11 @@ them.
```bash
npx hyperframes beats [dir]
npx hyperframes beats [dir] --json # { ok, file, count, bpm }
+npx hyperframes beats --json # { ok, file, count, bpm, beatTimes }
```
-`beats` takes the project folder, not a media file. For the beats of one audio
-or video file, run `npx hyperframes audio --only beats --json`.
+Given an audio or video file instead of a folder, `beats` analyses that file
+with the same tracker and prints the result; it writes nothing.
`beats` finds the music track — an `` element with
`data-timeline-role="music"`, or an id like `music`, `bgm`, or `soundtrack` —
@@ -1292,6 +1302,27 @@ last 3 s (a held end card) or time when an element marked `data-hold` is on
screen, and it stays quiet when `sweep_static` already reports the sweep or a
whole-composition `keepsMoving` assertion sets its own limit.
+#### Audio findings
+
+The `audio` section checks the clips the render mixes. It runs even when lint
+stops the browser pass, and remote sources are not fetched.
+
+| Code | Severity | Triggers when | Fix |
+| ------------------------------ | -------- | ------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------- |
+| `audio_source_unreadable` | error | The file cannot be read as audio, so the render's mix fails and the render stops. | Point `src` at a file with an audio track, or re-export it. |
+| `audio_source_rejected` | error | The file has no audio track, so render stops before it starts. | Point `src` at a file with audio, or remove `data-has-audio="true"` from a ``. |
+| `audio_starts_past_source_end` | warning | `data-media-start` is at or past the file's length, so the clip plays nothing. | Lower `data-media-start` below the file's length. |
+| `audio_clip_silent` | warning | The file is silent for the whole part the clip plays. | Check the file has sound there, or move `data-media-start` to where it does. |
+| `audio_none` | info | No clip plays audio and no unmuted `` has an audio track. | Nothing for a silent film; otherwise add the ``. |
+| `audio_check_unavailable` | info | The audio check itself failed, and the message says why, so the clips were not checked. | Re-run; if it repeats, run `hyperframes doctor`. |
+| `audio_src_not_found` | error | An `` names a file that is not in the project, so the render is silent. Reported by `lint`. | Add the file or fix the path. |
+
+Each media probe (the audio metadata render uses, and render's media-type rule)
+runs at most once per file; whether a `` has sound is probed on each use.
+The check runs alongside the browser pass, up to four files at a time. A clip
+longer than 3 s is first sampled at three 1-second spots and decoded in full
+only if all three are silent.
+
#### Mark intentional layout choices
When the audit is wrong because the layout is deliberate, say so in the HTML and
@@ -1474,6 +1505,59 @@ session, and it is where new work should go. Their flags are unchanged — run
`npx hyperframes inspect --help` if you are maintaining automation that still
calls them.
+## Rebuild an existing video
+
+These commands serve the `reverse-any-video` skill: measure a video, have HeyGen
+draft its timeline, then score your rebuild against it.
+
+### `measure`
+
+Measures a video file and prints JSON. Each measurement is a subcommand; run
+`npx hyperframes measure --help` for its flags.
+
+```bash
+npx hyperframes measure probe ref.mp4
+npx hyperframes measure cuts ref.mp4
+npx hyperframes measure frames ref.mp4 --events
+npx hyperframes measure face ref.mp4 --start 1 --end 2.5
+```
+
+| Subcommand | What it reports |
+| ------------ | --------------------------------------------------------------------------------------- |
+| `probe` | Displayed size, frame rate, duration, sound, and what to fix before rebuilding |
+| `cuts` | Hard cuts from the frame-to-frame difference, and the shots between them |
+| `events` | Cuts, flashes, appears, disappears and holds; `--map` adds the sound's hits |
+| `frames` | Frames as pictures: chosen moments, an overview sheet, a range, or strips around events |
+| `extract` | A still or a clip cut from the video, cropped to a region, as project media |
+| `curve` | Each move of one element: start, duration, overshoot and the closest GSAP ease |
+| `energy` | How much two clips move, and whether at the same moments |
+| `look` | Brightness, contrast, saturation and warmth, alone or against another video |
+| `face` | The face's size and position over a window |
+| `sync` | The lag between mouth motion and the voice |
+
+### `diff`
+
+Scores a render, or a project folder without rendering it, against the original
+video frame by frame: SSIM, the worst moments, missed and extra cuts, duration
+and the sound's offset. It exits non-zero when the scores fall under the bar.
+
+```bash
+npx hyperframes diff original.mp4 renders/final.mp4
+npx hyperframes diff original.mp4 . --at 0.5,2.4,3.1
+npx hyperframes diff original.mp4 renders/final.mp4 --segments segments.md --sbs
+```
+
+| Flag | Description |
+| ----------------------------------------- | -------------------------------------------------------------------- |
+| `--at` | Compare only these seconds |
+| `--range` | Compare every frame of `start,end` seconds |
+| `--segments` | A verdict per `## S01 · a–b s` segment of a file |
+| `--drawn` | Score one drawn element's box `x,y,w,h[,a-b]` by itself (repeatable) |
+| `--min-mean` / `--min-p05` / `--min-cell` | The SSIM bars to pass |
+| `--sbs` | Also write an original-beside-yours video |
+| `--out` | Folder for the sheet and log (default `.hyperframes/diff/`) |
+| `--json` | Print one JSON result |
+
## Edit from the command line
### `timeline`
@@ -1644,6 +1728,7 @@ Quality and file size:
| `--crf` | from `--quality`| Override MP4/WebM encoder CRF, 0–51. Lower is better quality. Not with `--video-bitrate`; rejected for MOV. |
| `--video-bitrate` | from `--quality`| Target MP4/WebM bitrate, e.g. `10M` or `5000k`. Not with `--crf`; rejected for MOV. |
| `--keyframe-interval` | encoder default | MP4 only. A keyframe at least every N seconds, e.g. `2`, so a player can seek or switch rendition at that spacing. |
+| `--start`, `--end` | whole film | Render only the seconds between them, as an MP4 that starts at 0 with that span's audio. MP4 at 24, 25, 30 or 60 fps, SDR only. |
| `--max-bitrate` | uncapped | MP4 only. Peak video bitrate cap, e.g. `8M`, held alongside the `--crf` or `--quality` target rather than replacing it. |
| `--buffer-size` | 2 × `--max-bitrate` | MP4 only. Buffer the cap is measured over, e.g. `16M`. Needs `--max-bitrate`. |
| `--vp9-cpu-used` | encoder default | libvpx-vp9 speed/quality trade-off for WebM, -8 to 8. Env: `PRODUCER_VP9_CPU_USED`. |
@@ -1672,7 +1757,7 @@ How it uses the machine, and when it gives up:
| `--batch-concurrency` / `--batch-fail-fast` | `1` / off | Batch rows at once, and whether the first failure stops the rest |
| `--debug` | off | Keep intermediates and write diagnostics under the Producer `.debug` directory |
| `--quiet` | off | Less output |
-| `--skill` | — | Record which authoring workflow started this render, in anonymous telemetry |
+| `--skill` | — | Record which authoring workflow started this render, in usage telemetry |
Low-memory detection reads **host** RAM, not cgroup or container limits, so
containerised callers — including `--docker` — should set
@@ -1962,12 +2047,13 @@ npx hyperframes docs [topic]
```
Topics: `data-attributes`, `examples`, `rendering`, `gsap`, `troubleshooting`,
-`compositions`. Run it bare to list them.
+`compositions`, `motion-blur`. Run it bare to list them.
### `feedback`
-Send feedback about how it went. It is anonymous unless the app that launched
-the CLI attaches your email (below).
+Send feedback about how it went. It rides the same usage telemetry, so it is
+anonymous until you sign in to HeyGen and linked to your account after that. An
+app that launches the CLI can also attach your email (below).
```bash
npx hyperframes feedback --rating 10
@@ -2021,10 +2107,16 @@ values are never collected, except short self-identifying names: `AGENT`,
the `//` tag an app that launches the CLI sets, sent as
`client` so reports from that app can be told apart.
-Nothing personally identifying is collected until you sign in. When you run
-`hyperframes auth login`, your HeyGen account email — or username, if the
-account has no email — is linked to your usage, and your prior anonymous usage
-is stitched to it. Nothing else personal, and only once you choose to sign in.
+Nothing personally identifying is collected until you sign in. **Signed-in usage
+is not anonymous.** When you run `hyperframes auth login`, your usage is linked
+to your HeyGen account from then on: it is keyed on an id derived from your
+HeyGen username (the same id the HyperFrames web app and Desktop use), and your
+account email and username are stored with it. While you are signed in, every
+event carries that id and your username. Anonymous usage from before the first
+sign-in is merged in, unless an older CLI version had already linked the install
+to your email; that earlier history stays on its own profile. `media-use` links the same way when it finds a
+signed-in HeyGen account. Nothing else personal is added, and the opt-outs below
+still turn all of it off.
Turn it all off with `HYPERFRAMES_NO_TELEMETRY=1` or the command above.
[Feedback collection](/help#share-feedback) explains the post-render prompt and the
@@ -2143,6 +2235,24 @@ goes only to that provider's own usage endpoint. The command sends no telemetry
and skips the update check. The numbers are a snapshot: they do not reserve
allowance or estimate what the next video will cost.
+### `billing`
+
+Opens the HyperFrames plans or credits page in the browser, then waits until the
+account shows the change, so an agent's run carries on by itself. The page is on
+the web app for `HYPERFRAMES_ENV`: hyperframes.studio, or dev.hyperframes.dev
+with `HYPERFRAMES_ENV=dev`.
+
+```bash
+npx hyperframes billing subscribe
+npx hyperframes billing top-up --needed 180
+```
+
+| Flag | Description |
+| ----------- | -------------------------------------------------------------------------- |
+| `--needed` | Credits the waiting step needs; `top-up` waits until the balance covers it |
+| `--tool` | The step that is waiting, shown on the page |
+| `--timeout` | Seconds to wait (default 600) |
+
### `figma` and `events`
`npx hyperframes figma` imports through the Figma REST API, with three
@@ -2150,21 +2260,22 @@ subcommands: `asset` (export an image or SVG), `tokens` (pull design tokens),
and `component` (import an editable component). Run it bare for usage. See
[Figma integration](/guides/figma) for setup and examples.
-`npx hyperframes events` lets an installed workflow skill emit an anonymous
-usage event (`--skill`, `--event`, `--outcome`). Nothing calls it by hand.
+`npx hyperframes events` lets an installed workflow skill emit a usage event
+(`--skill`, `--event`, `--outcome`). Like the rest of [`telemetry`](#telemetry),
+it is anonymous until you sign in. Nothing calls it by hand.
## hyperframes auth
-Sign in to HeyGen and manage credentials. They live in `~/.heygen/credentials`
-(mode `0600`) and are **shared with the `heygen` CLI** — sign in with one and
-the other picks up the session.
+Sign into your HeyGen account through the dedicated HyperFrames OAuth client.
+Credentials live in `~/.hyperframes/credentials` (mode `0600`), independently
+of the `heygen` CLI. A previous shared login requires a fresh HyperFrames sign-in.
First match wins:
1. `HEYGEN_API_KEY`
2. `HYPERFRAMES_API_KEY` (a HyperFrames alias for the same thing)
3. `HEYGEN_ACCESS_TOKEN` (an OAuth token a host app injects; never refreshed or saved)
-4. `~/.heygen/credentials`
+4. `~/.hyperframes/credentials`
### `auth login`
@@ -2224,7 +2335,9 @@ hyperframes auth logout --yes # no prompt
| `HYPERFRAMES_API_KEY` | Alias for `HEYGEN_API_KEY`. |
| `HEYGEN_ACCESS_TOKEN` | OAuth token from a host app; never refreshed. |
| `HEYGEN_API_URL` | API base URL (default `https://api.heygen.com`). |
-| `HEYGEN_CONFIG_DIR` | Credentials directory (default `~/.heygen`). |
+| `HYPERFRAMES_CONFIG_DIR` | Credentials root (default `~/.hyperframes`). |
+| `HYPERFRAMES_ENV` | `prod` (default) or `dev`; selects matching OAuth/API hosts and a separate dev credential directory. |
+| `HYPERFRAMES_OAUTH_CLIENT_ID` | Override the selected public OAuth client. |
For the keys other capabilities use — ElevenLabs and Gemini for voice and music
fallback, OpenRouter and Gemini for capture — and how the skills prioritize
diff --git a/docs/packages/core.mdx b/docs/packages/core.mdx
index 8a0a3f9527..ba654b10be 100644
--- a/docs/packages/core.mdx
+++ b/docs/packages/core.mdx
@@ -135,6 +135,9 @@ and `` elements. Eligible local candidates are inlined by default; with
when the entry file is in a subdirectory. Width and density descriptors are
preserved.
+Mounted scenes resolve their `srcset` candidates from the scene's own directory
+when the files exist there, with project-root paths as the fallback.
+
Local stylesheet `@import` rules keep each occurrence's media condition and
cascade position, even when several imports reference the same file. Circular
imports stop at a stylesheet already being expanded.
diff --git a/docs/packages/studio-server.mdx b/docs/packages/studio-server.mdx
index 1e19999ed7..5b1dac940b 100644
--- a/docs/packages/studio-server.mdx
+++ b/docs/packages/studio-server.mdx
@@ -66,6 +66,28 @@ the bundler inlines can be served with ids that a later save does not mint.
bundle: (dir, options) => bundleToSingleHtml(dir, { runtime: "inline", ...options }),
```
+## Source-file backups
+
+File saves and deletes preserve the previous bytes in `.hyperframes/backup/`
+before changing the source. A successful response includes `backupPath`,
+relative to the project directory. If the backup fails, the operation stops.
+
+Long project-relative paths use a SHA-256 backup key so the timestamped backup
+filename fits filesystem limits. Shorter paths keep their existing names.
+The server retains ten snapshots per file by default, including snapshots
+with the older backup names. The source path must still fit your filesystem's
+own limits.
+
+## Serving finished renders
+
+Studio streams finished render files from disk, including exports larger than
+2 GiB. This applies to the project's `/renders/file/*` route and each render
+job's `/view` and `/download` routes. A host mounting the API should forward
+the response body as a stream so it can deliver large exports without
+buffering the whole file in memory.
+
+`HEAD` requests return the same file metadata without opening a file stream.
+
## Where Studio loads GSAP from
Studio adds GSAP scripts to previews when a composition needs them: the GSAP
diff --git a/docs/quickstart.mdx b/docs/quickstart.mdx
index 73bdf93fdb..e66a8280de 100644
--- a/docs/quickstart.mdx
+++ b/docs/quickstart.mdx
@@ -6,8 +6,9 @@ description: "Make your first HyperFrames video in the free Studio app for Mac,
import { QuickstartContinuationGrid } from "/snippets/quickstart-continuation-grid.jsx";
import { DocsVideo } from "/snippets/docs-video.jsx";
-HyperFrames turns one sentence into a video you can keep editing. Start in the Studio app; if you are on Windows or
-already work with an AI agent in a terminal, use one of the other two ways. All three make the same kind of project.
+HyperFrames turns one sentence into a video you can keep editing. Start in the Studio app; if you already work with an
+AI agent in a terminal, or your computer can't run the app, use one of the other two ways. All three make the same
+kind of project.
` block valid JSON matching the SlideshowManifest schema.
+If supplied, `startTime` and `endTime` must be finite JSON numbers. Quoted numbers such as `"0"`, `null`, and overflowing values such as `1e400` are invalid.
### `slideshow_unresolved_ref`
@@ -907,6 +908,12 @@ Source: the project lint pass in `packages/lint/src/project.ts`, `packages/lint/
**Fix:** Add the missing mask file(s) to the project, or update the `mask-image` URL.
+### `missing_stylesheet_asset`
+
+**Warning.** A `url()` in a linked local stylesheet does not resolve beside that stylesheet. Browsers resolve `url()` from the stylesheet's own folder, so the font or image 404s and the render falls back silently. When the file exists in a parent folder, the fix hint names the working path.
+
+**Fix:** Change the `url()` to be relative to the stylesheet (for example `../assets/fonts/x.ttf` from `styles/main.css`), or add the file.
+
### `inaccessible_media_url`
**Error.** A remote media URL did not answer a `HEAD` request with a 2xx status (or the request failed or timed out), so the media cannot load. Reported only by the async `lintMediaUrls()` export of `@hyperframes/lint`; `hyperframes lint` and `hyperframes check` do not run it.
diff --git a/docs/snippets/catalog-detail.jsx b/docs/snippets/catalog-detail.jsx
index 38dc85fea5..02e476047c 100644
--- a/docs/snippets/catalog-detail.jsx
+++ b/docs/snippets/catalog-detail.jsx
@@ -68,7 +68,6 @@ export const CatalogDetail = ({
compositionSrc,
variables = [],
title,
- description,
meta = {},
about,
attribution,
@@ -585,10 +584,6 @@ export const CatalogDetail = ({
color 100ms ease;
}
-.hf-ve-head-title { margin: 8px 0 28px; }
-.hf-ve-head-title h1 { margin: 0; font-size: 44px; line-height: 1.1; font-weight: 700; letter-spacing: -0.02em; color: var(--ve-fg); }
-.hf-ve-head-title p { margin: 12px 0 0; font-size: 18px; line-height: 1.5; color: var(--ve-muted); max-width: 70ch; }
-@media (max-width: 640px) { .hf-ve-head-title h1 { font-size: 32px; } }
/* Item page anatomy: bar, stage beside Tune, tabs, tab body. */
.hf-ve-bar {
display: flex;
@@ -2085,13 +2080,6 @@ export const CatalogDetail = ({
-
-
- {title}
- {description && {description}
}
-
-
-
{installSlot && (
Install
diff --git a/docs/studio-app/edit-with-the-agent.mdx b/docs/studio-app/edit-with-the-agent.mdx
index 1994c9c493..2943783098 100644
--- a/docs/studio-app/edit-with-the-agent.mdx
+++ b/docs/studio-app/edit-with-the-agent.mdx
@@ -54,7 +54,7 @@ You can also draw across the timeline to talk about a stretch of the video, such
## Send several edits at once
-Picks, drawings, and comments do not run on their own. Each one becomes a row in **Pending video edits**, up to 10.
+Picks, drawings, and comments do not run on their own. Each one becomes a row in **Pending video edits**.
Check them, add a note for all of them, then send them as one request with the send button, for example
**Send 3 edits to Claude Code** (or **Queue 3 edits** while a run is working). Choose **Edit note** to change a row's words, or **Delete** to drop it.
diff --git a/gemini-extension.json b/gemini-extension.json
index 30ec22d618..992ba73f13 100644
--- a/gemini-extension.json
+++ b/gemini-extension.json
@@ -1,5 +1,5 @@
{
"name": "hyperframes",
- "version": "0.8.214",
+ "version": "0.8.224",
"description": "HyperFrames by HeyGen. Write HTML, render video. Compositions, GSAP and runtime adapter animations, captions, voiceovers, audio-reactive visuals, and website capture for HyperFrames."
}
diff --git a/packages/aws-lambda/image/build-ffmpeg.sh b/packages/aws-lambda/image/build-ffmpeg.sh
index fbbc222339..3ae94ea301 100755
--- a/packages/aws-lambda/image/build-ffmpeg.sh
+++ b/packages/aws-lambda/image/build-ffmpeg.sh
@@ -15,10 +15,7 @@ source /fetch.sh
license() { mkdir -p "$PREFIX/share/licenses/$1" && cp "${@:2}" "$PREFIX/share/licenses/$1/"; }
-read -r x264_commit x264_url < <(awk '$1 == "x264" { print $2, $3 }' /build/sources.txt)
-retry git clone -q "$x264_url" "$SRC/x264"
-git -C "$SRC/x264" checkout -q "$x264_commit"
-[ "$(git -C "$SRC/x264" rev-parse HEAD)" = "$x264_commit" ]
+fetch x264
(cd "$SRC/x264" && ./configure --prefix="$DEPS" --enable-static --enable-pic --disable-cli &&
make -j"$JOBS" && make install)
license x264 "$SRC/x264/COPYING"
diff --git a/packages/aws-lambda/image/fetch.sh b/packages/aws-lambda/image/fetch.sh
index e09d84c290..d2c6cd9a75 100644
--- a/packages/aws-lambda/image/fetch.sh
+++ b/packages/aws-lambda/image/fetch.sh
@@ -10,10 +10,20 @@ retry() {
return 1
}
+# Tries each URL on the source's line in order; only bytes matching its sha256 (git: its commit) are taken.
fetch() {
- local name=$1 sum url
- read -r sum url <<<"$(awk -v n="$name" '$1 == n { print $2, $3 }' "$SOURCES")"
- curl -fsSL --retry 5 --retry-all-errors --retry-delay 3 --connect-timeout 20 --max-time 600 -o "$SRC/$name" "$url"
- echo "$sum $SRC/$name" | sha256sum -c --quiet
- tar -xf "$SRC/$name" -C "$SRC"
+ local name=$1 sum urls url
+ read -r sum urls <<<"$(awk -v n="$name" '$1 == n { $1 = ""; print }' "$SOURCES")"
+ for url in $urls; do
+ if [[ $url == *.git ]]; then
+ retry git clone -q "$url" "$SRC/$name" && git -C "$SRC/$name" checkout -q "$sum" &&
+ [ "$(git -C "$SRC/$name" rev-parse HEAD)" = "$sum" ] && return 0
+ rm -rf "${SRC:?}/$name"
+ else
+ curl -fsSL --retry 5 --retry-all-errors --retry-delay 3 --connect-timeout 20 --max-time 600 -o "$SRC/$name" "$url" &&
+ echo "$sum $SRC/$name" | sha256sum -c --quiet && tar -xf "$SRC/$name" -C "$SRC" && return 0
+ fi
+ echo "fetch: $name not taken from $url" >&2
+ done
+ return 1
}
diff --git a/packages/aws-lambda/image/fetch.test.ts b/packages/aws-lambda/image/fetch.test.ts
index 5295b08fb7..6ee7d53d78 100644
--- a/packages/aws-lambda/image/fetch.test.ts
+++ b/packages/aws-lambda/image/fetch.test.ts
@@ -13,26 +13,35 @@ const tarGz = (() => {
return readFileSync(out);
})();
-async function fetchAfterResets(resets: number) {
+// Serves `body` after resetting the first `resets` connections.
+function serve(body: Buffer, resets = 0) {
let hits = 0;
const server = createServer((socket) => {
socket.once("data", () => {
if (++hits <= resets) return socket.resetAndDestroy();
socket.write(
- `HTTP/1.1 200 OK\r\nContent-Length: ${tarGz.length}\r\nConnection: close\r\n\r\n`,
+ `HTTP/1.1 200 OK\r\nContent-Length: ${body.length}\r\nConnection: close\r\n\r\n`,
);
- socket.end(tarGz);
+ socket.end(body);
});
}).listen(0, "127.0.0.1");
const { port } = server.address() as { port: number };
+ return {
+ url: `http://127.0.0.1:${port}/pkg.tar.gz`,
+ hits: () => hits,
+ close: () => server.close(),
+ };
+}
+
+async function fetchSource(line: string) {
const dir = mkdtempSync(join(tmpdir(), "fetch-run-"));
- const sum = createHash("sha256").update(tarGz).digest("hex");
- writeFileSync(
- join(dir, "sources.txt"),
- `pkg.tar.gz ${sum} http://127.0.0.1:${port}/pkg.tar.gz\n`,
- );
+ writeFileSync(join(dir, "sources.txt"), `${line}\n`);
const proc = Bun.spawn(
- ["bash", "-c", `set -euo pipefail; source ${import.meta.dir}/fetch.sh; fetch pkg.tar.gz`],
+ [
+ "bash",
+ "-c",
+ `set -euo pipefail; source ${import.meta.dir}/fetch.sh; fetch ${line.split(" ")[0]}`,
+ ],
{
env: { ...process.env, SRC: dir, SOURCES: join(dir, "sources.txt") },
stdout: "pipe",
@@ -40,13 +49,58 @@ async function fetchAfterResets(resets: number) {
},
);
const code = await proc.exited;
- server.close();
- return { code, hits, extracted: readFileSync(join(dir, "hello.txt"), "utf8") };
+ if (code !== 0) console.error(await new Response(proc.stderr).text());
+ return { code, dir };
+}
+
+const sum = createHash("sha256").update(tarGz).digest("hex");
+
+function gitRepo(file: string) {
+ const dir = mkdtempSync(join(tmpdir(), "fetch-git-"));
+ const git = (...args: string[]) =>
+ Bun.spawnSync(["git", "-c", "user.name=t", "-c", "user.email=t@t", "-C", dir, ...args])
+ .stdout.toString()
+ .trim();
+ git("init", "-q", "repo.git");
+ writeFileSync(join(dir, "repo.git", file), file);
+ git("-C", "repo.git", "add", ".");
+ git("-C", "repo.git", "commit", "-qm", file);
+ return { url: join(dir, "repo.git"), commit: git("-C", "repo.git", "rev-parse", "HEAD") };
}
describe("ffmpeg image fetch", () => {
it("retries a reset connection and still checks the sha256", async () => {
- const r = await fetchAfterResets(2);
- expect(r).toMatchObject({ code: 0, hits: 3, extracted: "hi" });
+ const host = serve(tarGz, 2);
+ const r = await fetchSource(`pkg.tar.gz ${sum} ${host.url}`);
+ host.close();
+ expect(r.code).toBe(0);
+ expect(host.hits()).toBe(3);
+ expect(readFileSync(join(r.dir, "hello.txt"), "utf8")).toBe("hi");
+ }, 30_000);
+
+ it("skips a mirror whose bytes do not match the sha256 for the next one", async () => {
+ const wrong = serve(Buffer.from("not the release"));
+ const right = serve(tarGz);
+ const r = await fetchSource(`pkg.tar.gz ${sum} ${wrong.url} ${right.url}`);
+ wrong.close();
+ right.close();
+ expect(r.code).toBe(0);
+ expect([wrong.hits(), right.hits()]).toEqual([1, 1]);
+ expect(readFileSync(join(r.dir, "hello.txt"), "utf8")).toBe("hi");
+ }, 30_000);
+
+ it("fails when no URL serves the pinned bytes", async () => {
+ const wrong = serve(Buffer.from("not the release"));
+ const r = await fetchSource(`pkg.tar.gz ${sum} ${wrong.url}`);
+ wrong.close();
+ expect(r.code).not.toBe(0);
+ }, 30_000);
+
+ it("takes a git source only at its pinned commit", async () => {
+ const stale = gitRepo("old.txt");
+ const pinned = gitRepo("pinned.txt");
+ const r = await fetchSource(`x264 ${pinned.commit} ${stale.url} ${pinned.url}`);
+ expect(r.code).toBe(0);
+ expect(readFileSync(join(r.dir, "x264", "pinned.txt"), "utf8")).toBe("pinned.txt");
}, 30_000);
});
diff --git a/packages/aws-lambda/image/sources.txt b/packages/aws-lambda/image/sources.txt
index 66e2683544..99d6141f01 100644
--- a/packages/aws-lambda/image/sources.txt
+++ b/packages/aws-lambda/image/sources.txt
@@ -1,8 +1,9 @@
-# name sha256 url (x264 has no stable tarballs: its line pins a git commit, r3191 as in the x86 ffmpeg-static)
-ffmpeg-7.0.2.tar.xz 8646515b638a3ad303e23af6a3587734447cb8fc0a0c064ecdb8e95c4fd8b389 https://ffmpeg.org/releases/ffmpeg-7.0.2.tar.xz
-x264 4613ac3c15fd75cebc4b9f65b7fb95e70a3acce1 https://code.videolan.org/videolan/x264.git
-x265_4.1.tar.gz a31699c6a89806b74b0151e5e6a7df65de4b49050482fe5ebf8a4379d7af8f29 https://bitbucket.org/multicoreware/x265_git/downloads/x265_4.1.tar.gz
+# name sha256 url [mirror url...]: fetch.sh tries them in order and takes only bytes matching the sha256
+# (x264 has no stable tarballs: its line pins a git commit, r3191 as in the x86 ffmpeg-static)
+ffmpeg-7.0.2.tar.xz 8646515b638a3ad303e23af6a3587734447cb8fc0a0c064ecdb8e95c4fd8b389 https://ffmpeg.org/releases/ffmpeg-7.0.2.tar.xz https://ftp.osuosl.org/pub/blfs/conglomeration/ffmpeg/ffmpeg-7.0.2.tar.xz http://downloads.yoctoproject.org/mirror/sources/ffmpeg-7.0.2.tar.xz
+x264 4613ac3c15fd75cebc4b9f65b7fb95e70a3acce1 https://code.videolan.org/videolan/x264.git https://github.com/mirror/x264.git
+x265_4.1.tar.gz a31699c6a89806b74b0151e5e6a7df65de4b49050482fe5ebf8a4379d7af8f29 https://bitbucket.org/multicoreware/x265_git/downloads/x265_4.1.tar.gz https://ftp.osuosl.org/pub/blfs/conglomeration/x265/x265_4.1.tar.gz http://downloads.yoctoproject.org/mirror/sources/x265_4.1.tar.gz
libvpx-1.15.0.tar.gz e935eded7d81631a538bfae703fd1e293aad1c7fd3407ba00440c95105d2011e https://github.com/webmproject/libvpx/archive/refs/tags/v1.15.0.tar.gz
-opus-1.5.2.tar.gz 65c1d2f78b9f2fb20082c38cbe47c951ad5839345876e46941612ee87f9a7ce1 https://downloads.xiph.org/releases/opus/opus-1.5.2.tar.gz
+opus-1.5.2.tar.gz 65c1d2f78b9f2fb20082c38cbe47c951ad5839345876e46941612ee87f9a7ce1 https://downloads.xiph.org/releases/opus/opus-1.5.2.tar.gz https://github.com/xiph/opus/releases/download/v1.5.2/opus-1.5.2.tar.gz https://ftp.osuosl.org/pub/blfs/conglomeration/opus/opus-1.5.2.tar.gz
zimg-3.0.5.tar.gz a9a0226bf85e0d83c41a8ebe4e3e690e1348682f6a2a7838f1b8cbff1b799bcf https://github.com/sekrit-twc/zimg/archive/refs/tags/release-3.0.5.tar.gz
dav1d-1.5.1.tar.xz 401813f1f89fa8fd4295805aa5284d9aed9bc7fc1fdbe554af4292f64cbabe21 https://downloads.videolan.org/pub/videolan/dav1d/1.5.1/dav1d-1.5.1.tar.xz
diff --git a/packages/aws-lambda/package.json b/packages/aws-lambda/package.json
index 4e265f3624..b9b0ba7981 100644
--- a/packages/aws-lambda/package.json
+++ b/packages/aws-lambda/package.json
@@ -1,6 +1,6 @@
{
"name": "@hyperframes/aws-lambda",
- "version": "0.8.214",
+ "version": "0.8.224",
"description": "AWS Lambda adapter for HyperFrames distributed rendering — handler, client-side SDK, and CDK construct.",
"repository": {
"type": "git",
diff --git a/packages/cli/package.json b/packages/cli/package.json
index c56fec9a8c..285afbdd22 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@hyperframes/cli",
- "version": "0.8.214",
+ "version": "0.8.224",
"description": "Make videos with code and AI agents: write HTML, render MP4. Open source.",
"keywords": [
"ai-agents",
diff --git a/packages/cli/scripts/test-home.mjs b/packages/cli/scripts/test-home.mjs
index 708c7ac013..07feafbfc6 100644
--- a/packages/cli/scripts/test-home.mjs
+++ b/packages/cli/scripts/test-home.mjs
@@ -18,6 +18,7 @@ for (const name of [
"CODEX_HOME",
"CLAUDE_CONFIG_DIR",
"HEYGEN_CONFIG_DIR",
+ "HYPERFRAMES_CONFIG_DIR",
"HYPERFRAMES_CATALOG_ARTIFACT_DIR",
"HYPERFRAMES_MEDIA_HOME",
"HF_HOME",
diff --git a/packages/cli/src/api/transcribe.ts b/packages/cli/src/api/transcribe.ts
index 7054668cd7..e07edafb2b 100644
--- a/packages/cli/src/api/transcribe.ts
+++ b/packages/cli/src/api/transcribe.ts
@@ -1,5 +1,6 @@
import { existsSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
import { basename, dirname, extname, join, resolve } from "node:path";
+import { transcribeWithHeygen } from "../heygen/transcribe.js";
import { normalizeErrorMessage } from "../utils/errorMessage.js";
import {
createRenderCancellationScope,
@@ -38,7 +39,7 @@ import {
// finishing even on the fastest hardware for the shortest clip.
export const MIN_TIMEOUT_MS = 5000;
-export type TranscribeEngine = "auto" | "parakeet" | "whisper";
+export type TranscribeEngine = "auto" | "parakeet" | "whisper" | "heygen";
export type CaptionFormat = "srt" | "vtt";
/** The program that does the work: Parakeet runs on sherpa-onnx or parakeet-mlx. */
export type TranscribeRunner = ParakeetRunner | "whisper";
@@ -69,8 +70,10 @@ export interface TranscribeOptions {
input: string;
/** Where transcript.json goes; caption scripts in this folder's .html files are patched. Default: the input's folder. */
dir?: string;
- /** Default "auto": Parakeet when installed and it covers `language`, else whisper. */
+ /** Default "auto": Parakeet when installed and it covers `language`, else whisper; "heygen" runs on HeyGen. */
engine?: TranscribeEngine;
+ /** HeyGen only: label each word with its speaker. */
+ speakers?: boolean;
/** Whisper model. Parakeet has its own fixed model. */
model?: string;
language?: string;
@@ -97,7 +100,7 @@ export interface TranscribeOptions {
export type TranscribeResult =
| {
kind: "transcribed";
- engine: "parakeet" | "whisper";
+ engine: "parakeet" | "whisper" | "heygen";
model: string;
detectedLanguage: string | null;
wordCount: number;
@@ -367,6 +370,71 @@ function failureMessage(err: unknown): string {
return stderr ? `${base}\n${stderr}` : base;
}
+interface EngineTranscript {
+ transcriptPath: string;
+ model: string;
+ detectedLanguage: string | null;
+ durationSeconds: number;
+ speechOnsetSeconds: number | null;
+}
+
+/** Every engine's words end the same way: normalized, patched into caption scripts, and as a sidecar if asked. */
+function finishTranscript(
+ result: EngineTranscript,
+ engine: "parakeet" | "whisper" | "heygen",
+ dir: string,
+ sidecar: CaptionSidecar | undefined,
+): TranscribeResult {
+ const { words } = loadTranscript(result.transcriptPath);
+
+ writeFileSync(result.transcriptPath, JSON.stringify(words, null, 2));
+ patchCaptionHtml(dir, words);
+ if (sidecar) {
+ try {
+ writeCaptionSidecar(words, sidecar, false);
+ } catch (err) {
+ throw new TranscribeError(
+ "caption_write_failed",
+ `Transcript saved to ${result.transcriptPath}, but the caption file ${sidecar.outPath} could not be written: ${normalizeErrorMessage(err)}`,
+ { cause: err, transcriptPath: result.transcriptPath },
+ );
+ }
+ }
+
+ return {
+ kind: "transcribed",
+ engine,
+ model: result.model,
+ detectedLanguage: result.detectedLanguage,
+ wordCount: words.length,
+ durationSeconds: result.durationSeconds,
+ speechOnsetSeconds: result.speechOnsetSeconds,
+ transcriptPath: result.transcriptPath,
+ ...(sidecar && { captions: { format: sidecar.to, outputPath: sidecar.outPath } }),
+ };
+}
+
+async function transcribeOnHeygen(
+ inputPath: string,
+ dir: string,
+ sidecar: CaptionSidecar | undefined,
+ options: TranscribeRequest,
+): Promise
{
+ try {
+ const result = await transcribeWithHeygen(inputPath, join(dir, TRANSCRIPT_FILE), {
+ diarize: options.speakers,
+ projectDir: dir,
+ onStatus: options.onStatus,
+ });
+ return finishTranscript(result, "heygen", dir, sidecar);
+ } catch (err) {
+ if (err instanceof TranscribeError) throw err;
+ const fix =
+ err instanceof Error && "fix" in err && typeof err.fix === "string" ? ` Fix: ${err.fix}` : "";
+ throw new TranscribeError("failed", `${normalizeErrorMessage(err)}.${fix}`, { cause: err });
+ }
+}
+
// fallow-ignore-next-line complexity
async function transcribeAudio(
inputPath: string,
@@ -375,10 +443,11 @@ async function transcribeAudio(
options: TranscribeRequest,
): Promise {
const engine = (options.engine ?? "auto").toLowerCase();
+ if (engine === "heygen") return transcribeOnHeygen(inputPath, dir, sidecar, options);
if (engine !== "auto" && engine !== "parakeet" && engine !== "whisper") {
throw new TranscribeError(
"invalid_option",
- `Unknown --engine: ${options.engine}. Use auto, parakeet, or whisper.`,
+ `Unknown --engine: ${options.engine}. Use auto, parakeet, whisper, or heygen.`,
);
}
const unsupported = sherpaUnsupportedReason();
@@ -488,33 +557,7 @@ async function transcribeAudio(
}
}
- const { words } = loadTranscript(result.transcriptPath);
-
- writeFileSync(result.transcriptPath, JSON.stringify(words, null, 2));
- patchCaptionHtml(dir, words);
- if (sidecar) {
- try {
- writeCaptionSidecar(words, sidecar, false);
- } catch (err) {
- throw new TranscribeError(
- "caption_write_failed",
- `Transcript saved to ${result.transcriptPath}, but the caption file ${sidecar.outPath} could not be written: ${normalizeErrorMessage(err)}`,
- { cause: err, transcriptPath: result.transcriptPath },
- );
- }
- }
-
- return {
- kind: "transcribed",
- engine: engineOf(runner),
- model: result.model,
- detectedLanguage: result.detectedLanguage,
- wordCount: words.length,
- durationSeconds: result.durationSeconds,
- speechOnsetSeconds: result.speechOnsetSeconds,
- transcriptPath: result.transcriptPath,
- ...(sidecar && { captions: { format: sidecar.to, outputPath: sidecar.outPath } }),
- };
+ return finishTranscript(result, engineOf(runner), dir, sidecar);
} catch (err) {
if (err instanceof TranscribeError) throw err;
if (err instanceof DecodeCancelled || cancellation?.signal.aborted) {
diff --git a/packages/cli/src/audio/analysis/analyze.test.ts b/packages/cli/src/audio/analysis/analyze.test.ts
index 3bb020c306..4d427edc8a 100644
--- a/packages/cli/src/audio/analysis/analyze.test.ts
+++ b/packages/cli/src/audio/analysis/analyze.test.ts
@@ -1,10 +1,12 @@
import { describe, expect, it } from "vitest";
import {
+ rhythm,
signalProvider,
+ silence,
type AudioAnalysisProvider,
type AudioSignal,
} from "@hyperframes/core/audio-analysis";
-import { analyzeSignal, envelopeHopMs } from "./analyze.js";
+import { analyzeSignal, envelopeHopMs, type MarkedBeats } from "./analyze.js";
const RATE = 8000;
const tone: AudioSignal = {
@@ -83,6 +85,158 @@ describe("analyzeSignal", () => {
});
});
+/** A 120 BPM click every half second from 0.25 s, with nothing at all from `restFrom` to `restTo`. */
+function clicks(seconds: number, restFrom = Infinity, restTo = Infinity): AudioSignal {
+ const samples = new Float32Array(seconds * RATE);
+ let state = 7;
+ for (let t = 0.25; t < seconds; t += 0.5) {
+ if (t >= restFrom && t < restTo) continue;
+ for (let i = 0; i < 0.05 * RATE; i++) {
+ state = (state * 1_103_515_245 + 12_345) % 2_147_483_648;
+ samples[Math.round(t * RATE) + i]! +=
+ 0.5 * ((state / 2_147_483_648) * 2 - 1) * Math.exp(-i / (0.01 * RATE));
+ }
+ }
+ return { sampleRate: RATE, channels: [samples] };
+}
+
+// xorshift32: the clicks' LCG repeats in a short cycle, which the tracker would hear as a pulse
+let hissState = 0x9e3779b9;
+function hiss(): number {
+ hissState ^= hissState << 13;
+ hissState ^= hissState >>> 17;
+ hissState ^= hissState << 5;
+ return (hissState >>> 0) / 2 ** 31 - 1;
+}
+
+/** 120 BPM: a kick on every beat, a hat between, a held bass note; `db` quieter from `quietFrom` on. */
+function groove(seconds: number, quietFrom: number, db: number): AudioSignal {
+ const x = new Float32Array(seconds * RATE);
+ for (let k = 0; k * 0.5 + 0.25 < seconds; k++) {
+ const at = Math.round((0.25 + k * 0.5) * RATE);
+ for (let i = 0; i < 0.2 * RATE && at + i < x.length; i++) {
+ const sweep = 50 + 100 * Math.exp(-i / (0.03 * RATE));
+ x[at + i]! += 0.6 * Math.sin((2 * Math.PI * sweep * i) / RATE) * Math.exp(-i / (0.06 * RATE));
+ }
+ const off = at + 0.25 * RATE;
+ for (let i = 0; i < 0.04 * RATE && off + i < x.length; i++)
+ x[off + i]! += 0.15 * hiss() * Math.exp(-i / (0.008 * RATE));
+ }
+ for (let i = 0; i < x.length; i++) {
+ x[i]! += 0.1 * Math.sin((2 * Math.PI * 55 * i) / RATE);
+ if (i >= quietFrom * RATE) x[i]! *= 10 ** (-db / 20);
+ }
+ return { sampleRate: RATE, channels: [x] };
+}
+
+const answering = (id: string, times: number[]): AudioAnalysisProvider => ({
+ id,
+ local: true,
+ capabilities: ["beats"],
+ analyze: async () => ({ times }),
+});
+
+describe("analyzeSignal beats, from any provider", () => {
+ it("moves a provider's beats onto the signal's own when one is within a quarter beat", async () => {
+ const signal = clicks(12);
+ const measured = rhythm(signal).beats.times;
+ // 30 ms late on every beat, plus one beat between two of the signal's
+ const late = answering(
+ "late",
+ [...measured.map((t) => t + 0.03), 6.5].sort((a, b) => a - b),
+ );
+ const analysis = await analyzeSignal(signal, { capabilities: ["beats", "bpm"] }, [
+ late,
+ signalProvider,
+ ]);
+ const beats = analysis.values.beats as MarkedBeats;
+ expect(analysis.provenance.beats).toBe("late");
+ expect(beats.times).toEqual([...measured, 6.5].sort((a, b) => a - b));
+ expect(beats.snap).toMatchObject({
+ reference: "signal beats",
+ snapped: measured.length,
+ medianShiftMs: 30,
+ });
+ expect(beats.snap?.unsnapped).toEqual([6.5]);
+ expect((analysis.values.bpm as { value: number }).value).toBeCloseTo(120, 0);
+ });
+
+ it("keeps the signal's own beats as measured", async () => {
+ const signal = clicks(12);
+ const analysis = await analyzeSignal(signal, { capabilities: ["beats"] }, [signalProvider]);
+ const beats = analysis.values.beats as MarkedBeats;
+ expect(beats.times).toEqual(rhythm(signal).beats.times);
+ expect(beats.snap).toBeUndefined();
+ });
+
+ it("marks every beat in digital silence as unheard, from any provider, and keeps it in the grid", async () => {
+ const signal = clicks(12, 4, 6);
+ const quiet = silence(signal);
+ const inQuiet = (t: number) => quiet.some((s) => t >= s.start && t < s.end);
+ const grid = Array.from({ length: 24 }, (_, k) => 0.25 + k * 0.5);
+ for (const provider of [answering("grid", grid), signalProvider]) {
+ const analysis = await analyzeSignal(signal, { capabilities: ["beats"], fileOffset: 1 }, [
+ provider,
+ ]);
+ const beats = analysis.values.beats as MarkedBeats;
+ expect(beats.unheard).toHaveLength(beats.times.length);
+ expect(beats.unheard).toEqual(beats.times.map((t) => inQuiet(t - 1)));
+ }
+ const grid24 = (
+ await analyzeSignal(signal, { capabilities: ["beats"] }, [answering("grid", grid)])
+ ).values.beats as MarkedBeats;
+ expect(grid24.times).toHaveLength(24);
+ // the four grid beats in the rest, each moved onto the signal's own grid there
+ const resting = grid24.times.filter((_, k) => grid24.unheard[k]);
+ expect(resting.map((t) => Math.round(t * 4) / 4)).toEqual([4.25, 4.75, 5.25, 5.75]);
+ });
+
+ it("marks beats unheard where noise plays with no pulse, though it is far from silence", async () => {
+ const signal = clicks(12, 4, 8);
+ const samples = signal.channels[0]!;
+ for (let i = 4 * RATE; i < 8 * RATE; i++) samples[i] = 0.05 * hiss();
+ expect(silence(signal).some((s) => s.start < 8 && s.end > 4)).toBe(false);
+ const grid = Array.from({ length: 24 }, (_, k) => 0.25 + k * 0.5);
+ const beats = (
+ await analyzeSignal(signal, { capabilities: ["beats"] }, [answering("grid", grid)])
+ ).values.beats as MarkedBeats;
+ const inHiss = beats.times.map((t) => t > 4.1 && t < 8);
+ expect(beats.unheard.filter((_, k) => inHiss[k]).every(Boolean)).toBe(true);
+ expect(beats.unheard.filter((_, k) => !inHiss[k] && beats.times[k]! < 11.5).some(Boolean)).toBe(
+ false,
+ );
+ });
+
+ it.each([30, 45])("keeps beats heard in a section %i dB under the loudest", async (db) => {
+ const signal = groove(24, 12, db);
+ const grid = Array.from({ length: 48 }, (_, k) => 0.25 + k * 0.5);
+ const beats = (
+ await analyzeSignal(signal, { capabilities: ["beats"] }, [answering("grid", grid)])
+ ).values.beats as MarkedBeats;
+ const quiet = beats.unheard.filter((_, k) => beats.times[k]! > 12.1 && beats.times[k]! < 23.5);
+ expect(quiet.length).toBeGreaterThan(18);
+ expect(quiet.some(Boolean)).toBe(false);
+ });
+
+ it("marks downbeats the same way, and moves them by the bar's own beat", async () => {
+ const signal = clicks(12, 4, 6);
+ const measured = rhythm(signal).beats.times;
+ const bars: AudioAnalysisProvider = {
+ id: "bars",
+ local: true,
+ capabilities: ["downbeats"],
+ analyze: async () => ({ times: [0.27, 2.27, 4.27, 6.27, 8.27, 10.27], meter: 4 }),
+ };
+ const downbeats = (await analyzeSignal(signal, { capabilities: ["downbeats"] }, [bars])).values
+ .downbeats as MarkedBeats;
+ expect(downbeats.snap?.toleranceMs).toBe(125);
+ expect(downbeats.unheard).toEqual([false, false, true, false, false, false]);
+ expect(
+ downbeats.times.filter((_, k) => !downbeats.unheard[k]).every((t) => measured.includes(t)),
+ ).toBe(true);
+ });
+});
+
describe("analyzeSignal quality", () => {
const service: AudioAnalysisProvider = {
id: "service",
diff --git a/packages/cli/src/audio/analysis/analyze.ts b/packages/cli/src/audio/analysis/analyze.ts
index 60bc0adf67..a8e8020053 100644
--- a/packages/cli/src/audio/analysis/analyze.ts
+++ b/packages/cli/src/audio/analysis/analyze.ts
@@ -1,7 +1,13 @@
import {
+ localBeatEvidence,
+ medianInterval,
+ rhythm,
runLadder,
signalDuration,
signalProvider,
+ silence,
+ snapper,
+ STEADY_BEAT_CONFIDENCE,
tempoOf,
type AnalysisQuality,
type AudioAnalysisProvider,
@@ -10,6 +16,7 @@ import {
type Beats,
type LadderResult,
type LadderStep,
+ type SnapReport,
} from "@hyperframes/core/audio-analysis";
import { apiProvider } from "./providers/api.js";
import { appleMuProvider, appleSoundProvider } from "./providers/apple.js";
@@ -121,11 +128,12 @@ export async function analyzeSignal(
let result = ladders.get(capability);
if (!result) {
const withContext = capability === "onsets" && framing.cut;
- result = runLadder(capability, withContext ? signal : framing.windowed, providers, {
+ const input = withContext ? signal : framing.windowed;
+ result = runLadder(capability, input, providers, {
quality,
provider: capability === "beats" ? beatProvider : request.provider?.[capability],
options: optionsFor(capability, request, analysis.analyzed),
- });
+ }).then((answer) => settled(capability, answer, input));
ladders.set(capability, result);
}
return result;
@@ -159,6 +167,67 @@ function serviceHint(
: [];
}
+export interface MarkedBeats {
+ times: number[];
+ /** True where nothing rhythmic sounds at the beat (silence, hiss, a held note): the grid runs on there. */
+ unheard: boolean[];
+ meter?: number | null;
+ snap?: SnapReport;
+}
+
+/** Under this a beat sits in digital silence, whatever the rest of the clip does. */
+const DIGITAL_SILENCE_DB = -80;
+/** A beat whose onset stands this far over its span is heard even where the span keeps no steady beat (narration). */
+const HEARD_LIFT = 1.5;
+
+const roundTime = (t: number) => Math.round(t * 1000) / 1000;
+
+/** Beats move onto the signal's own; unheard in digital silence, or with neither a steady beat around nor an onset. */
+function settled(
+ capability: AudioCapability,
+ result: LadderResult,
+ signal: AudioSignal,
+): LadderResult {
+ if (capability !== "beats" && capability !== "downbeats") return result;
+ const value = result.value as Omit | null;
+ if (!value?.times) return result;
+ const beat = beatOf(capability, value, signal);
+ const onSignal = result.provenance === "signal" ? value : snappedToSignal(value, signal, beat);
+ const quiet = silence(signal, { thresholdDb: DIGITAL_SILENCE_DB });
+ const evidence = localBeatEvidence(
+ signal,
+ onSignal.times,
+ capability === "downbeats" ? beat : undefined,
+ );
+ const unheard = onSignal.times.map(
+ (t, i) =>
+ quiet.some((span) => t >= span.start && t < span.end) ||
+ (evidence[i]!.confidence < STEADY_BEAT_CONFIDENCE && evidence[i]!.lift < HEARD_LIFT),
+ );
+ return { ...result, value: { ...onSignal, unheard } };
+}
+
+/** The beat is the answer's own beat interval, or its bar over its meter; the signal's when neither is known. */
+function beatOf(
+ capability: "beats" | "downbeats",
+ value: Omit,
+ signal: AudioSignal,
+): number {
+ const interval = medianInterval(value.times);
+ const own =
+ capability === "beats" ? interval : interval && value.meter ? interval / value.meter : null;
+ return own ?? medianInterval(rhythm(signal).beats.times) ?? 0;
+}
+
+function snappedToSignal(value: Omit, signal: AudioSignal, beat: number) {
+ const onBeat = snapper(rhythm(signal).beats.times, beat / 4, "signal beats");
+ return {
+ ...value,
+ times: value.times.map((t) => roundTime(onBeat.snap(t))),
+ snap: onBeat.report(),
+ };
+}
+
/** Tempo is read off the beats of whichever provider placed them, so the two never disagree. */
function tempoFromBeats(beats: LadderResult): LadderResult {
const times = (beats.value as Beats | null)?.times;
diff --git a/packages/cli/src/audio/analysis/providers/api.ts b/packages/cli/src/audio/analysis/providers/api.ts
index 5cc1ff7492..5f3207a111 100644
--- a/packages/cli/src/audio/analysis/providers/api.ts
+++ b/packages/cli/src/audio/analysis/providers/api.ts
@@ -213,29 +213,14 @@ function answerFor(signal: AudioSignal, capability: AudioApiCapability) {
return request(signal);
}
-/** The signal's own beats, which an answer's times move onto when one is within a quarter of the answer's beat. */
-function beatSnapper(signal: AudioSignal, beatSeconds: number | null): Snapper {
+/** The signal's own beats, which a section boundary moves onto when one is within a quarter beat. */
+function beatSnapper(signal: AudioSignal): Snapper {
const measured = rhythm(signal).beats.times;
- const period = beatSeconds ?? medianInterval(measured) ?? 0;
- return snapper(measured, period / 4, "signal beats");
-}
-
-function snappedBeats(signal: AudioSignal, body: AudioApiResponse) {
- const times = body.beats!.times;
- const onBeat = beatSnapper(signal, medianInterval(times));
- return { times: rounded(times.map(onBeat.snap)), snap: onBeat.report() };
-}
-
-function snappedDownbeats(signal: AudioSignal, body: AudioApiResponse) {
- const { times, meter = null } = body.downbeats!;
- const beat = body.beats ? medianInterval(body.beats.times) : null;
- const bar = medianInterval(times);
- const onBeat = beatSnapper(signal, beat ?? (bar && meter ? bar / meter : null));
- return { times: rounded(times.map(onBeat.snap)), meter, snap: onBeat.report() };
+ return snapper(measured, (medianInterval(measured) ?? 0) / 4, "signal beats");
}
function snappedSections(signal: AudioSignal, body: AudioApiResponse) {
- const onBeat = beatSnapper(signal, null);
+ const onBeat = beatSnapper(signal);
const end = (signal.channels[0]?.length ?? 0) / signal.sampleRate;
const move = (t: number) => (t <= 0 || t >= end ? t : onBeat.snap(t));
const spans = body.sections!.spans.map((s) => ({
@@ -246,13 +231,12 @@ function snappedSections(signal: AudioSignal, body: AudioApiResponse) {
return { spans, snap: onBeat.report() };
}
-/** The answer for one capability, its times moved onto what the signal measured. */
function measured(capability: AudioApiCapability, signal: AudioSignal, body: AudioApiResponse) {
const value =
capability === "beats"
- ? snappedBeats(signal, body)
+ ? { times: rounded(body.beats!.times) }
: capability === "downbeats"
- ? snappedDownbeats(signal, body)
+ ? { times: rounded(body.downbeats!.times), meter: body.downbeats!.meter ?? null }
: capability === "sections"
? snappedSections(signal, body)
: body.describe!;
diff --git a/packages/cli/src/audio/analysis/providers/localProviders.test.ts b/packages/cli/src/audio/analysis/providers/localProviders.test.ts
index e3341a2b22..ce9bf95260 100644
--- a/packages/cli/src/audio/analysis/providers/localProviders.test.ts
+++ b/packages/cli/src/audio/analysis/providers/localProviders.test.ts
@@ -75,7 +75,8 @@ describe.skipIf(process.platform === "win32")("beatThisProvider", () => {
downbeats: "beat-this",
bpm: "beat-this",
});
- expect(analysis.values.downbeats).toEqual({ times: [0.5, 2.5, 4.5], meter: 4 });
+ expect(analysis.values.downbeats).toMatchObject({ times: [0.5, 2.5, 4.5], meter: 4 });
+ expect((analysis.values.downbeats as { unheard: boolean[] }).unheard).toHaveLength(3);
expect(analysis.values.bpm).toMatchObject({ value: 120 });
});
diff --git a/packages/cli/src/audio/analysis/run.test.ts b/packages/cli/src/audio/analysis/run.test.ts
index 91a72210f9..61ed41774b 100644
--- a/packages/cli/src/audio/analysis/run.test.ts
+++ b/packages/cli/src/audio/analysis/run.test.ts
@@ -3,7 +3,8 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, describe, expect, it } from "vitest";
import { findFfBinary } from "@hyperframes/parsers/ff-binaries";
-import type { Moments, Onsets } from "@hyperframes/core/audio-analysis";
+import type { AudioCapability, Moments, Onsets } from "@hyperframes/core/audio-analysis";
+import type { MarkedBeats } from "./analyze.js";
import { formatReport } from "./format.js";
import { analyzeTargets, previewTarget } from "./run.js";
@@ -197,6 +198,90 @@ describe.skipIf(!ffmpeg)("analyzeTargets", () => {
expect(report.items[0]!.moments).toEqual(windowOnly.items[0]!.moments);
});
+ it("reads a window's beats, bars and tempo off the whole clip, so a short window still has them", async () => {
+ const path = wav("click-bed.wav", 16, (t) => hit(0)(t % 0.5));
+ const clip = { from: 0, seconds: 16 };
+ const at = (window: { from: number; seconds: number }, withClip: boolean) => ({
+ path,
+ file: "click-bed.wav",
+ ref: "#bed",
+ kind: "audio" as const,
+ placement: null,
+ window,
+ ...(withClip && { clip }),
+ });
+ const request = { capabilities: ["beats", "downbeats", "bpm"] as AudioCapability[] };
+ const [whole, windowed, alone] = await Promise.all([
+ analyzeTargets([at(clip, true)], request),
+ analyzeTargets([at({ from: 6, seconds: 3 }, true)], request),
+ analyzeTargets([at({ from: 6, seconds: 3 }, false)], request),
+ ]);
+ const beatsOf = (report: typeof whole) => report.items[0]!.beats as MarkedBeats;
+ const inWindow = (t: number) => t >= 6 && t < 9;
+ expect(beatsOf(alone).times).toEqual([]);
+ expect(beatsOf(windowed).times.length).toBeGreaterThanOrEqual(5);
+ expect(beatsOf(windowed).times).toEqual(beatsOf(whole).times.filter(inWindow));
+ expect(beatsOf(windowed).unheard).toEqual(beatsOf(windowed).times.map(() => false));
+ expect((windowed.items[0]!.downbeats as MarkedBeats).times).toEqual(
+ (whole.items[0]!.downbeats as MarkedBeats).times.filter(inWindow),
+ );
+ expect((windowed.items[0]!.bpm as { value: number }).value).toBeCloseTo(120, 0);
+ expect(windowed.items[0]!.window).toEqual({ from: 6, to: 9 });
+ });
+
+ it("answers no steady beat, and no tempo, for a window where only noise plays", async () => {
+ // noise() repeats in a short cycle, which reads as a pulse; hiss needs a generator that does not
+ let state = 0x9e3779b9;
+ const hiss = () => {
+ state ^= state << 13;
+ state ^= state >>> 17;
+ state ^= state << 5;
+ return (state >>> 0) / 2 ** 31 - 1;
+ };
+ const path = wav("hiss-gap.wav", 24, (t) =>
+ t >= 8 && t < 16 ? 0.05 * hiss() : hit(0)(t % 0.5),
+ );
+ const target = {
+ path,
+ file: "hiss-gap.wav",
+ ref: "#bed",
+ kind: "audio" as const,
+ placement: null,
+ // 6 s: long enough that the window's own reading is "no steady beat", not "too short"
+ window: { from: 9, seconds: 6 },
+ clip: { from: 0, seconds: 24 },
+ };
+ const [item] = (await analyzeTargets([target], { capabilities: ["beats", "downbeats", "bpm"] }))
+ .items;
+ expect(item!.beats).toMatchObject({ times: [], reason: "no steady beat" });
+ expect((item!.downbeats as MarkedBeats).times).toEqual([]);
+ expect(item!.bpm).toEqual({ value: null, curve: [] });
+ });
+
+ it("reads a section far quieter than the clip's loudest from the window itself, as before", async () => {
+ // loud clicks for 10 s, then the same clicks 40 dB under them: the clip's grid has no beats there
+ const quiet = 10 ** (-40 / 20);
+ const path = wav("quiet-section.wav", 30, (t) => (t < 10 ? 1 : quiet) * hit(0)(t % 0.5));
+ const at = (clip: { from: number; seconds: number } | null) => ({
+ path,
+ file: "quiet-section.wav",
+ ref: "#bed",
+ kind: "audio" as const,
+ placement: null,
+ window: { from: 14, seconds: 8 },
+ ...(clip && { clip }),
+ });
+ const request = { capabilities: ["beats", "bpm"] as AudioCapability[] };
+ const [withClip, alone] = await Promise.all([
+ analyzeTargets([at({ from: 0, seconds: 30 })], request),
+ analyzeTargets([at(null)], request),
+ ]);
+ const beats = withClip.items[0]!.beats as MarkedBeats;
+ expect(beats.times.length).toBeGreaterThanOrEqual(15);
+ expect(beats.times).toEqual((alone.items[0]!.beats as MarkedBeats).times);
+ expect((withClip.items[0]!.bpm as { value: number }).value).toBeCloseTo(120, 0);
+ });
+
it.each([
{ from: 1, seconds: 8, duration: 8 },
{ from: 11, seconds: 3, duration: 1 },
diff --git a/packages/cli/src/audio/analysis/run.ts b/packages/cli/src/audio/analysis/run.ts
index 176c00dd68..c329f39cfb 100644
--- a/packages/cli/src/audio/analysis/run.ts
+++ b/packages/cli/src/audio/analysis/run.ts
@@ -1,11 +1,14 @@
import { existsSync } from "node:fs";
import {
envelope,
+ tempoOf,
type AudioCapability,
type AudioSignal,
type LadderStep,
+ type Section,
+ type Tempo,
} from "@hyperframes/core/audio-analysis";
-import { analyzeSignal, type AnalyzeOptions } from "./analyze.js";
+import { analyzeSignal, type Analysis, type AnalyzeOptions, type MarkedBeats } from "./analyze.js";
import { decodeAudio, probeAudio, type AudioStreamInfo } from "./decode.js";
import type { AudioTarget, Placement } from "./targets.js";
import {
@@ -46,6 +49,8 @@ const round = (t: number) => Math.round(t * 1000) / 1000;
const EDGE_CONTEXT_SECONDS = 0.1;
const KIND_SAMPLE_RATE = 16_000;
const KIND_DECODE_BYTES = 256 * 1024 * 1024;
+const RHYTHM_SAMPLE_RATE = 22_050;
+const RHYTHM: readonly AudioCapability[] = ["beats", "downbeats", "bpm", "sections"];
/** A file the film does not play yet, placed where the caller would put it. */
export async function previewTarget(
@@ -158,11 +163,12 @@ async function clipKindSignal(
stream: AudioStreamInfo,
sampleRate: number,
windowSignal?: AudioSignal,
+ purpose = "kind",
): Promise {
if (windowSignal) return windowSignal;
const seconds = Math.min(target.clip!.seconds, Math.max(0, stream.duration - target.clip!.from));
if (seconds * sampleRate * stream.channels * 4 > KIND_DECODE_BYTES)
- throw new Error("whole clip exceeds the kind analysis decode limit");
+ throw new Error(`whole clip exceeds the ${purpose} analysis decode limit`);
return (await decodeAudio(target.path, target.clip!, stream, { sampleRate }))?.signal;
}
@@ -190,7 +196,145 @@ async function clipKind(
return analysis;
}
-/** Analyzes the window, except a kind the window would misjudge, which comes from the whole clip. */
+async function wholeClipKind(
+ target: AudioTarget,
+ signal: AudioSignal,
+ request: AnalyzeOptions,
+ stream: AudioStreamInfo,
+ cache?: KindCacheSource,
+): Promise {
+ try {
+ const kind = await clipKind(
+ target,
+ request,
+ stream,
+ cache,
+ coversPart(target) ? undefined : signal,
+ );
+ if (!kind) throw new Error("no audio stream");
+ return kind;
+ } catch (error) {
+ const kind = await analyzeSignal(signal, { ...request, capabilities: ["kind"] });
+ kind.warnings.push(
+ `kind uses only the selected range: could not analyze the whole clip (${firstLine(error)})`,
+ );
+ return kind;
+ }
+}
+
+const firstLine = (error: unknown) =>
+ error instanceof Error ? error.message.split("\n")[0] : String(error);
+
+const between = (from: number, to: number) => (t: number) => t >= from && t < to;
+
+function beatsBetween(value: MarkedBeats, from: number, to: number): MarkedBeats {
+ const keep = value.times.map(between(from, to));
+ return {
+ ...value,
+ times: value.times.filter((_, i) => keep[i]),
+ unheard: value.unheard.filter((_, i) => keep[i]),
+ };
+}
+
+/** A window keeps the clip's beats when at least two, and at least half, of them are heard there. */
+const PULSE_BEATS = 2;
+
+const heardTimes = (beats: MarkedBeats) => beats.times.filter((_, i) => !beats.unheard[i]);
+
+interface RhythmWindow {
+ from: number;
+ to: number;
+ beats: MarkedBeats | null;
+ pulse: boolean;
+}
+
+const CUTS: Partial unknown>> = {
+ beats: (_value, { beats, pulse }) =>
+ pulse ? beats : { times: [], unheard: [], confidence: 0, reason: "no steady beat" },
+ downbeats: (value, { from, to, pulse }) =>
+ pulse
+ ? beatsBetween(value as MarkedBeats, from, to)
+ : { times: [], unheard: [], meter: null, confidence: "low" },
+ bpm: (value, { from, to, beats, pulse }): Tempo =>
+ pulse && beats
+ ? {
+ value: tempoOf(heardTimes(beats)).value,
+ curve: (value as Tempo).curve.filter((point) => between(from, to)(point.t)),
+ }
+ : { value: null, curve: [] },
+ sections: (value, { from, to }) => {
+ const sections = value as { spans: Section[] };
+ return { ...sections, spans: sections.spans.filter((s) => s.end > from && s.start < to) };
+ },
+};
+
+const beatsIn = (values: Analysis["values"], from: number, to: number) =>
+ values.beats ? beatsBetween(values.beats as MarkedBeats, from, to) : null;
+
+const pulseIn = (beats: MarkedBeats | null) =>
+ !!beats && heardTimes(beats).length >= Math.max(PULSE_BEATS, beats.times.length / 2);
+
+function rhythmBetween(
+ values: Analysis["values"],
+ asked: readonly AudioCapability[],
+ from: number,
+ to: number,
+): Analysis["values"] {
+ const beats = beatsIn(values, from, to);
+ const window = { from, to, beats, pulse: pulseIn(beats) };
+ return Object.fromEntries(
+ asked.map((capability) => {
+ const value = values[capability];
+ return [capability, value == null ? value : (CUTS[capability]?.(value, window) ?? value)];
+ }),
+ );
+}
+
+/** Rhythm read off the whole clip and cut to the window: a window alone is too short to hear a beat, a bar or a section. */
+async function wholeClipRhythm(
+ target: AudioTarget,
+ signal: AudioSignal,
+ request: AnalyzeOptions,
+ stream: AudioStreamInfo,
+): Promise {
+ const asked = request.capabilities.filter((capability) => RHYTHM.includes(capability));
+ try {
+ const rate = Math.min(stream.sampleRate, RHYTHM_SAMPLE_RATE);
+ const clip = await clipKindSignal(target, stream, rate, undefined, "rhythm");
+ if (!clip) throw new Error("no audio stream");
+ const needsBeats = asked.some((c) => c === "bpm" || c === "downbeats");
+ const measure = needsBeats && !asked.includes("beats") ? [...asked, "beats" as const] : asked;
+ const whole = await analyzeSignal(clip, {
+ ...request,
+ capabilities: measure,
+ fileOffset: target.clip!.from,
+ context: undefined,
+ });
+ const from = request.fileOffset ?? 0;
+ const to = from + target.window!.seconds;
+ const cut = rhythmBetween(whole.values, asked, from, to);
+ const beatAnswers = asked.filter((capability) => capability !== "sections");
+ if (!beatAnswers.length || pulseIn(beatsIn(whole.values, from, to)))
+ return { ...whole, values: cut };
+ // No pulse on the clip's grid here can be a section far under the clip's loudest: the window reads it alone.
+ const own = await analyzeSignal(signal, { ...request, capabilities: beatAnswers });
+ return {
+ ...own,
+ values: { ...cut, ...own.values },
+ provenance: { ...whole.provenance, ...own.provenance },
+ ladder: { ...whole.ladder, ...own.ladder },
+ warnings: [...new Set([...whole.warnings, ...own.warnings])],
+ };
+ } catch (error) {
+ const rhythm = await analyzeSignal(signal, { ...request, capabilities: asked });
+ rhythm.warnings.push(
+ `beats, bars and sections use only the selected range: could not analyze the whole clip (${firstLine(error)})`,
+ );
+ return rhythm;
+ }
+}
+
+/** Analyzes the window, except a kind and a rhythm the window would misjudge, which come from the whole clip. */
async function analyzeWindow(
target: AudioTarget,
signal: AudioSignal,
@@ -199,28 +343,26 @@ async function analyzeWindow(
cache?: KindCacheSource,
) {
const kindApart = request.capabilities.includes("kind") && target.clip !== undefined;
- if (!kindApart) return analyzeSignal(signal, request);
- const analysis = await analyzeSignal(signal, {
- ...request,
- capabilities: request.capabilities.filter((capability) => capability !== "kind"),
- });
- let kind;
- try {
- kind = await clipKind(target, request, stream, cache, coversPart(target) ? undefined : signal);
- if (!kind) throw new Error("no audio stream");
- } catch (error) {
- kind = await analyzeSignal(signal, { ...request, capabilities: ["kind"] });
- const reason = error instanceof Error ? error.message.split("\n")[0] : String(error);
- kind.warnings.push(
- `kind uses only the selected range: could not analyze the whole clip (${reason})`,
- );
- }
+ const rhythmApart =
+ coversPart(target) && request.capabilities.some((capability) => RHYTHM.includes(capability));
+ if (!kindApart && !rhythmApart) return analyzeSignal(signal, request);
+ const apart = (capability: AudioCapability) =>
+ (kindApart && capability === "kind") || (rhythmApart && RHYTHM.includes(capability));
+ const parts = [
+ await analyzeSignal(signal, {
+ ...request,
+ capabilities: request.capabilities.filter((capability) => !apart(capability)),
+ }),
+ ...(kindApart ? [await wholeClipKind(target, signal, request, stream, cache)] : []),
+ ...(rhythmApart ? [await wholeClipRhythm(target, signal, request, stream)] : []),
+ ];
+ const [window] = parts;
return {
- ...analysis,
- values: { ...analysis.values, kind: kind.values.kind },
- provenance: { ...analysis.provenance, ...kind.provenance },
- ladder: { ...analysis.ladder, ...kind.ladder },
- warnings: [...new Set([...analysis.warnings, ...kind.warnings])],
+ ...window!,
+ values: Object.assign({}, ...parts.map((part) => part.values)),
+ provenance: Object.assign({}, ...parts.map((part) => part.provenance)),
+ ladder: Object.assign({}, ...parts.map((part) => part.ladder)),
+ warnings: [...new Set(parts.flatMap((part) => part.warnings))],
};
}
diff --git a/packages/cli/src/auth/_test-utils.ts b/packages/cli/src/auth/_test-utils.ts
index 4afd6cd224..bbaceb14e2 100644
--- a/packages/cli/src/auth/_test-utils.ts
+++ b/packages/cli/src/auth/_test-utils.ts
@@ -14,9 +14,16 @@ const ENV_KEYS = [
"HEYGEN_API_KEY",
"HEYGEN_ACCESS_TOKEN",
"HYPERFRAMES_API_KEY",
+ "HYPERFRAMES_CONFIG_DIR",
"HEYGEN_CONFIG_DIR",
+ "HEYGEN_API_BASE",
"HEYGEN_API_URL",
"HYPERFRAMES_OAUTH_CLIENT_ID",
+ "HYPERFRAMES_ENV",
+ "HYPERFRAMES_OAUTH_TOKEN_URL",
+ "HYPERFRAMES_OAUTH_AUTHORIZE_URL",
+ "HYPERFRAMES_OAUTH_REVOKE_URL",
+ "HYPERFRAMES_OAUTH_DEVICE_URL",
] as const;
type EnvKey = (typeof ENV_KEYS)[number];
@@ -30,7 +37,7 @@ export interface EnvFixture {
/**
* Take a snapshot of the auth-related env, clear them, make a tmp
- * `HEYGEN_CONFIG_DIR`, and return a `restore()` that undoes all of
+ * `HYPERFRAMES_CONFIG_DIR`, and return a `restore()` that undoes all of
* the above.
*/
export async function setupTempAuthEnv(prefix = "hf-auth-test-"): Promise {
@@ -40,7 +47,7 @@ export async function setupTempAuthEnv(prefix = "hf-auth-test-"): Promise => {
for (const k of ENV_KEYS) {
diff --git a/packages/cli/src/auth/browser.ts b/packages/cli/src/auth/browser.ts
index 12bc79985f..517a6d7f9e 100644
--- a/packages/cli/src/auth/browser.ts
+++ b/packages/cli/src/auth/browser.ts
@@ -1,9 +1,10 @@
/**
- * Open a URL in the user's default browser. Falls back to printing the
- * URL when no browser is openable (SSH session, CI, `BROWSER=none`,
- * or `open` rejects).
+ * Open a URL in the user's default browser. Falls back to printing the URL when no browser is openable
+ * (SSH session, CI, `BROWSER=none`, or `open` rejects). ponytail: `HF_BROWSER_LOG` is a test seam for
+ * scripted journeys: the URL goes to that file, and a harness plays the person in its own browser.
*/
+import { appendFileSync } from "node:fs";
import { c } from "../ui/colors.js";
import { normalizeErrorMessage } from "../utils/errorMessage.js";
@@ -13,6 +14,11 @@ export interface OpenBrowserResult {
}
export async function openBrowser(url: string): Promise {
+ const log = process.env["HF_BROWSER_LOG"];
+ if (log) {
+ appendFileSync(log, `${url}\n`);
+ return { opened: true };
+ }
if (process.env["BROWSER"] === "none" || process.env["HF_NO_BROWSER"] === "1") {
printManualInstructions(url);
return { opened: false };
diff --git a/packages/cli/src/auth/client.ts b/packages/cli/src/auth/client.ts
index 0bb3f92bb4..a485f1b278 100644
--- a/packages/cli/src/auth/client.ts
+++ b/packages/cli/src/auth/client.ts
@@ -19,8 +19,8 @@ import { ErrApi, ErrUnauthenticated, isAuthError } from "./errors.js";
import type { ResolvedCredential } from "./resolver.js";
import { scrubCredentials } from "./scrub.js";
import type { OAuthTokens } from "./store.js";
+import { oauthEnvironment } from "./config.js";
-const DEFAULT_BASE_URL = "https://api.heygen.com";
export const HEYGEN_CLI_SOURCE_HEADER = "X-HeyGen-Source";
export const HEYGEN_CLI_SOURCE = "cli";
// Tool-attribution header identifying this CLI as the request origin. Sent on
@@ -32,7 +32,9 @@ export const HEYGEN_CLIENT_SOURCE = "hyperframes";
export function apiBaseUrl(): string {
const override = process.env["HEYGEN_API_URL"];
- return override && override.length > 0 ? override.replace(/\/+$/, "") : DEFAULT_BASE_URL;
+ return override && override.length > 0
+ ? override.replace(/\/+$/, "")
+ : `https://api.${oauthEnvironment() === "dev" ? "dev." : ""}heygen.com`;
}
export type BillingType = "wallet" | "subscription" | "usage_based" | string;
diff --git a/packages/cli/src/auth/config.test.ts b/packages/cli/src/auth/config.test.ts
new file mode 100644
index 0000000000..9e50b53fa3
--- /dev/null
+++ b/packages/cli/src/auth/config.test.ts
@@ -0,0 +1,51 @@
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { setupTempAuthEnv } from "./_test-utils.js";
+import {
+ assertOAuthIdentity,
+ authorizeEndpoint,
+ deviceAuthorizationEndpoint,
+ oauthIdentity,
+ resolveClientId,
+ revokeEndpoint,
+ tokenEndpoint,
+} from "./config.js";
+import { apiBaseUrl } from "./client.js";
+
+describe("HyperFrames OAuth configuration", () => {
+ let fixture: Awaited>;
+ beforeEach(async () => {
+ fixture = await setupTempAuthEnv();
+ });
+ afterEach(async () => {
+ await fixture.restore();
+ });
+
+ it("uses the dedicated public production client", () => {
+ expect(resolveClientId()).toBe("Zg3LF4FCLoeJoGs2YqMtZ17g");
+ expect(authorizeEndpoint()).toBe("https://app.heygen.com/oauth/authorize");
+ expect(tokenEndpoint()).toBe("https://api2.heygen.com/v1/oauth/token");
+ expect(apiBaseUrl()).toBe("https://api.heygen.com");
+ });
+
+ it("switches every default host together for development", () => {
+ process.env["HYPERFRAMES_ENV"] = "dev";
+ expect(resolveClientId()).toBe("9QoaiwCZov9O0cAkC4OZbR4p");
+ expect(authorizeEndpoint()).toBe("https://api2.dev.heygen.com/v1/oauth/authorize");
+ expect(tokenEndpoint()).toBe("https://api2.dev.heygen.com/v1/oauth/token");
+ expect(revokeEndpoint()).toBe("https://api2.dev.heygen.com/v1/oauth/revoke");
+ expect(deviceAuthorizationEndpoint()).toBe(
+ "https://api2.dev.heygen.com/v1/oauth/device_authorization",
+ );
+ expect(apiBaseUrl()).toBe("https://api.dev.heygen.com");
+ });
+
+ it("rejects a session after either its client or token server changes", () => {
+ const identity = oauthIdentity();
+ expect(() => assertOAuthIdentity(identity)).not.toThrow();
+ process.env["HYPERFRAMES_OAUTH_CLIENT_ID"] = "another-client";
+ expect(() => assertOAuthIdentity(identity)).toThrow("different OAuth client or environment");
+ delete process.env["HYPERFRAMES_OAUTH_CLIENT_ID"];
+ process.env["HYPERFRAMES_OAUTH_TOKEN_URL"] = "https://other.example/token";
+ expect(() => assertOAuthIdentity(identity)).toThrow("different OAuth client or environment");
+ });
+});
diff --git a/packages/cli/src/auth/config.ts b/packages/cli/src/auth/config.ts
new file mode 100644
index 0000000000..28d2303caa
--- /dev/null
+++ b/packages/cli/src/auth/config.ts
@@ -0,0 +1,67 @@
+import { AuthError, ErrOAuthNotConfigured } from "./errors.js";
+
+const PROD_CLIENT_ID = "Zg3LF4FCLoeJoGs2YqMtZ17g";
+
+export function oauthEnvironment(): "prod" | "dev" {
+ const value = process.env["HYPERFRAMES_ENV"] || "prod";
+ if (value === "prod" || value === "dev") return value;
+ throw new AuthError("OAUTH_NOT_CONFIGURED", "HYPERFRAMES_ENV must be prod or dev");
+}
+
+export function defaultClientId(): string {
+ return oauthEnvironment() === "prod" ? PROD_CLIENT_ID : "9QoaiwCZov9O0cAkC4OZbR4p";
+}
+
+export function resolveClientId(): string {
+ const id = process.env["HYPERFRAMES_OAUTH_CLIENT_ID"] || defaultClientId();
+ if (!id) throw ErrOAuthNotConfigured();
+ return id;
+}
+
+export function tokenEndpoint(): string {
+ return (
+ process.env["HYPERFRAMES_OAUTH_TOKEN_URL"] ||
+ `https://api2.${oauthEnvironment() === "dev" ? "dev." : ""}heygen.com/v1/oauth/token`
+ );
+}
+
+export function authorizeEndpoint(): string {
+ return (
+ process.env["HYPERFRAMES_OAUTH_AUTHORIZE_URL"] ||
+ (oauthEnvironment() === "dev"
+ ? "https://api2.dev.heygen.com/v1/oauth/authorize"
+ : "https://app.heygen.com/oauth/authorize")
+ );
+}
+
+export function revokeEndpoint(): string {
+ return (
+ process.env["HYPERFRAMES_OAUTH_REVOKE_URL"] ||
+ `https://api2.${oauthEnvironment() === "dev" ? "dev." : ""}heygen.com/v1/oauth/revoke`
+ );
+}
+
+export function deviceAuthorizationEndpoint(): string {
+ return (
+ process.env["HYPERFRAMES_OAUTH_DEVICE_URL"] ||
+ `https://api2.${oauthEnvironment() === "dev" ? "dev." : ""}heygen.com/v1/oauth/device_authorization`
+ );
+}
+
+export function oauthIdentity(): { client_id: string; token_endpoint: string } {
+ return { client_id: resolveClientId(), token_endpoint: tokenEndpoint() };
+}
+
+export function assertOAuthIdentity(tokens: { client_id?: string; token_endpoint?: string }): void {
+ const identity = oauthIdentity();
+ if (
+ tokens.client_id !== identity.client_id ||
+ tokens.token_endpoint !== identity.token_endpoint
+ ) {
+ throw new AuthError(
+ "LOGIN_EXPIRED",
+ "This login belongs to a different OAuth client or environment",
+ "Run `hyperframes auth login` to sign into the selected HyperFrames environment.",
+ );
+ }
+}
diff --git a/packages/cli/src/auth/errors.ts b/packages/cli/src/auth/errors.ts
index bb307c9d3c..365afbc952 100644
--- a/packages/cli/src/auth/errors.ts
+++ b/packages/cli/src/auth/errors.ts
@@ -37,7 +37,7 @@ export const ErrInvalidStore = (detail: string) =>
new AuthError(
"INVALID_STORE",
`Credential file is unreadable: ${detail}`,
- "Delete ~/.heygen/credentials and run `hyperframes auth login` to re-create it.",
+ "Delete ~/.hyperframes/credentials and run `hyperframes auth login` to re-create it.",
);
export const ErrUnauthenticated = (detail?: string) =>
diff --git a/packages/cli/src/auth/loopback.ts b/packages/cli/src/auth/loopback.ts
index 5b14cb56cd..f554591577 100644
--- a/packages/cli/src/auth/loopback.ts
+++ b/packages/cli/src/auth/loopback.ts
@@ -45,7 +45,7 @@ export interface LoopbackHandle {
}
const CALLBACK_PATH = "/oauth/callback";
-const DEFAULT_TIMEOUT_MS = 120_000;
+const DEFAULT_TIMEOUT_MS = 300_000;
export async function startLoopback(opts: LoopbackOptions): Promise {
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
@@ -191,7 +191,7 @@ function respond(res: ServerResponse, status: number, body: string): void {
}
function successPage(): string {
- return `Signed in to HeyGen
+ return `Signed in to HyperFrames
You're signed in. You can close this tab and return to your terminal.
`;
}
diff --git a/packages/cli/src/auth/media-environment.test.ts b/packages/cli/src/auth/media-environment.test.ts
new file mode 100644
index 0000000000..581809c9c6
--- /dev/null
+++ b/packages/cli/src/auth/media-environment.test.ts
@@ -0,0 +1,107 @@
+import { promises as fs } from "node:fs";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { setupTempAuthEnv } from "./_test-utils.js";
+import { persistFreshOAuth } from "./oauth.js";
+import { withMediaAuthEnvironment } from "./media-environment.js";
+
+describe("media-use authentication", () => {
+ let fixture: Awaited>;
+ beforeEach(async () => {
+ fixture = await setupTempAuthEnv();
+ });
+ afterEach(async () => {
+ vi.unstubAllGlobals();
+ await fixture.restore();
+ });
+
+ it("passes a fresh access token through a private, temporary Go credential file", async () => {
+ await persistFreshOAuth({ access_token: "hf-access", refresh_token: "hf-refresh" });
+ let path = "";
+ await withMediaAuthEnvironment(async (env) => {
+ path = join(env.HEYGEN_CONFIG_DIR!, "credentials");
+ expect(env.HEYGEN_ACCESS_TOKEN).toBe("hf-access");
+ expect(env.HEYGEN_API_BASE).toBe("https://api.heygen.com");
+ expect(env.HEYGEN_API_KEY).toBeUndefined();
+ const copied = JSON.parse(await fs.readFile(path, "utf8"));
+ expect(copied.oauth.access_token).toBe("hf-access");
+ expect(copied.oauth.refresh_token).toBeUndefined();
+ if (process.platform !== "win32") {
+ expect((await fs.stat(path)).mode & 0o777).toBe(0o600);
+ expect((await fs.stat(env.HEYGEN_CONFIG_DIR!)).mode & 0o777).toBe(0o700);
+ }
+ });
+ await expect(fs.stat(path)).rejects.toMatchObject({ code: "ENOENT" });
+ expect(await fs.readFile(join(fixture.dir, "credentials"), "utf8")).toContain("hf-refresh");
+ });
+
+ it("refreshes a token before a helper could outlive it", async () => {
+ await persistFreshOAuth({
+ access_token: "near-expiry",
+ refresh_token: "hf-refresh",
+ expires_at: new Date(Date.now() + 5 * 60 * 1000).toISOString(),
+ });
+ const fetchMock = vi.fn(
+ async () =>
+ new Response(
+ JSON.stringify({ access_token: "refreshed", refresh_token: "rotated", expires_in: 3600 }),
+ { status: 200, headers: { "content-type": "application/json" } },
+ ),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ await withMediaAuthEnvironment(async (env) => {
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(env.HEYGEN_ACCESS_TOKEN).toBe("refreshed");
+ const copied = JSON.parse(
+ await fs.readFile(join(env.HEYGEN_CONFIG_DIR!, "credentials"), "utf8"),
+ );
+ expect(copied.oauth.access_token).toBe("refreshed");
+ expect(copied.oauth.refresh_token).toBeUndefined();
+ });
+ expect(await fs.readFile(join(fixture.dir, "credentials"), "utf8")).toContain("rotated");
+ });
+
+ it("refuses to send OAuth to a non-HeyGen media gateway", async () => {
+ await persistFreshOAuth({ access_token: "hf-access", refresh_token: "hf-refresh" });
+ process.env["HEYGEN_API_BASE"] = "https://gateway.example";
+ try {
+ await expect(withMediaAuthEnvironment(() => undefined)).rejects.toThrow(
+ "requires its own API credential",
+ );
+ } finally {
+ delete process.env["HEYGEN_API_BASE"];
+ }
+ });
+
+ it("isolates an anonymous operation from an existing HeyGen login", async () => {
+ process.env["HEYGEN_CONFIG_DIR"] = join(fixture.dir, "heygen");
+ await fs.mkdir(process.env["HEYGEN_CONFIG_DIR"]);
+ const legacyPath = join(process.env["HEYGEN_CONFIG_DIR"], "credentials");
+ await fs.writeFile(legacyPath, "hg_other_wallet");
+ await withMediaAuthEnvironment(async (env) => {
+ expect(env.HEYGEN_CONFIG_DIR).not.toBe(process.env["HEYGEN_CONFIG_DIR"]);
+ expect(await fs.readdir(env.HEYGEN_CONFIG_DIR!)).toEqual([]);
+ expect(env.HEYGEN_API_KEY).toBeUndefined();
+ });
+ expect(await fs.readFile(legacyPath, "utf8")).toBe("hg_other_wallet");
+ });
+
+ it("preserves an explicit host gateway and cleans up after a subprocess error", async () => {
+ process.env["HEYGEN_API_BASE"] = "https://gateway.example";
+ process.env["HEYGEN_API_KEY"] = "gateway-key";
+ let dir = "";
+ try {
+ await expect(
+ withMediaAuthEnvironment((env) => {
+ dir = env.HEYGEN_CONFIG_DIR!;
+ expect(env.HEYGEN_API_BASE).toBe("https://gateway.example");
+ expect(env.HEYGEN_API_KEY).toBe("gateway-key");
+ throw new Error("subprocess failed");
+ }),
+ ).rejects.toThrow("subprocess failed");
+ await expect(fs.stat(dir)).rejects.toMatchObject({ code: "ENOENT" });
+ } finally {
+ delete process.env["HEYGEN_API_BASE"];
+ }
+ });
+});
diff --git a/packages/cli/src/auth/media-environment.ts b/packages/cli/src/auth/media-environment.ts
new file mode 100644
index 0000000000..f4cb56e26d
--- /dev/null
+++ b/packages/cli/src/auth/media-environment.ts
@@ -0,0 +1,73 @@
+import { promises as fs } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { apiBaseUrl } from "./client.js";
+import { refreshTokens } from "./oauth.js";
+import { AuthError, isAuthError } from "./errors.js";
+import { resolveCredential, tryResolveCredential } from "./resolver.js";
+import { writeStore } from "./store.js";
+
+// Avatar helpers can poll for five minutes after submitting paid work.
+const MIN_HELPER_TOKEN_LIFETIME_MS = 10 * 60 * 1000;
+
+/** The Go CLI accepts OAuth through a credential file, but cannot refresh a HyperFrames grant. */
+export async function withMediaAuthEnvironment(run: (env: NodeJS.ProcessEnv) => T): Promise {
+ let credential;
+ try {
+ credential = await tryResolveCredential();
+ } catch (error) {
+ // An expired login must not stop anonymous/local providers or select another wallet.
+ if (!isAuthError(error) || error.code !== "LOGIN_EXPIRED") throw error;
+ }
+ const expiresDuringHelper =
+ credential?.type === "oauth" &&
+ credential.expires_at !== undefined &&
+ credential.expires_at.getTime() - Date.now() < MIN_HELPER_TOKEN_LIFETIME_MS;
+ if (
+ credential?.type === "oauth" &&
+ credential.refresh_token &&
+ (credential.refreshable || expiresDuringHelper)
+ ) {
+ await refreshTokens(credential.refresh_token);
+ credential = await resolveCredential();
+ }
+
+ const dir = await fs.mkdtemp(join(tmpdir(), "hyperframes-media-auth-"));
+ try {
+ await fs.chmod(dir, 0o700);
+ const env: NodeJS.ProcessEnv = { ...process.env, HEYGEN_CONFIG_DIR: dir };
+ env.HEYGEN_API_BASE ||= apiBaseUrl();
+ if (credential?.type === "oauth") {
+ const host = new URL(env.HEYGEN_API_BASE).hostname;
+ if (host !== "heygen.com" && !host.endsWith(".heygen.com")) {
+ throw new AuthError(
+ "OAUTH_NOT_CONFIGURED",
+ "A media gateway requires its own API credential",
+ );
+ }
+ delete env.HEYGEN_API_KEY;
+ delete env.HYPERFRAMES_API_KEY;
+ env.HEYGEN_ACCESS_TOKEN = credential.access_token;
+ await writeStore(
+ {
+ oauth: {
+ access_token: credential.access_token,
+ expires_at: credential.expires_at?.toISOString(),
+ token_type: "Bearer",
+ },
+ },
+ join(dir, "credentials"),
+ );
+ } else if (credential?.type === "api_key") {
+ env.HEYGEN_API_KEY = credential.key;
+ delete env.HEYGEN_ACCESS_TOKEN;
+ } else {
+ delete env.HEYGEN_ACCESS_TOKEN;
+ delete env.HEYGEN_API_KEY;
+ delete env.HYPERFRAMES_API_KEY;
+ }
+ return await run(env);
+ } finally {
+ await fs.rm(dir, { recursive: true, force: true });
+ }
+}
diff --git a/packages/cli/src/auth/oauth.test.ts b/packages/cli/src/auth/oauth.test.ts
index a391ef7f7d..d5d76a2740 100644
--- a/packages/cli/src/auth/oauth.test.ts
+++ b/packages/cli/src/auth/oauth.test.ts
@@ -1,3 +1,4 @@
+import { oauthIdentity } from "./config.js";
import { promises as fs } from "node:fs";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { setupTempAuthEnv } from "./_test-utils.js";
@@ -12,7 +13,7 @@ import {
startAuthorizationCodeFlow,
startDeviceAuthorizationFlow,
} from "./oauth.js";
-import { readStore, writeStore } from "./store.js";
+import { readStore, writeStore as writeUnboundStore, type Credentials } from "./store.js";
// Mock the interactive bits so startAuthorizationCodeFlow runs headless.
vi.mock("./loopback.js", () => ({
@@ -68,6 +69,13 @@ async function loginWithTokens(body: Record) {
return (await readStore()).credentials;
}
+async function writeStore(credentials: Credentials): Promise {
+ await writeUnboundStore({
+ ...credentials,
+ ...(credentials.oauth ? { oauth: { ...oauthIdentity(), ...credentials.oauth } } : {}),
+ });
+}
+
describe("auth/oauth", () => {
let fixture: Awaited>;
@@ -170,6 +178,26 @@ describe("auth/oauth", () => {
});
describe("refreshTokens", () => {
+ it.each([undefined, "foreign-client"])(
+ "does not send a refresh token with client binding %s",
+ async (client_id) => {
+ await writeUnboundStore({
+ oauth: {
+ access_token: "at",
+ refresh_token: "rt",
+ client_id,
+ token_endpoint: oauthIdentity().token_endpoint,
+ },
+ });
+ const fetchImpl = vi.fn();
+ await expect(refreshTokens("rt", { fetchImpl })).rejects.toMatchObject({
+ code: "LOGIN_EXPIRED",
+ });
+ expect(fetchImpl).not.toHaveBeenCalled();
+ expect((await readStore()).credentials.oauth?.refresh_token).toBe("rt");
+ },
+ );
+
it("posts grant_type=refresh_token and persists the response", async () => {
process.env["HEYGEN_API_URL"] = "https://api.test.example";
await writeStore({ oauth: { access_token: "old_at", refresh_token: "old_rt" } });
@@ -196,7 +224,7 @@ describe("auth/oauth", () => {
// Should have persisted.
const { credentials } = await readStore();
- expect(credentials.oauth?.access_token).toBe("new_at");
+ expect(credentials.oauth).toMatchObject({ ...oauthIdentity(), access_token: "new_at" });
});
it("preserves the prior refresh_token when the server omits it (no rotation)", async () => {
@@ -264,6 +292,7 @@ describe("auth/oauth", () => {
path,
JSON.stringify({
oauth: {
+ ...oauthIdentity(),
access_token: "old_at",
refresh_token: "keep_me_rt",
id_token: "future_id_token_value",
@@ -281,6 +310,7 @@ describe("auth/oauth", () => {
});
it("throws REFRESH_FAILED on 400/401", async () => {
+ await writeStore({ oauth: { access_token: "at", refresh_token: "bad_rt" } });
const fetchImpl = (async () =>
new Response("invalid_grant", {
status: 400,
@@ -291,6 +321,7 @@ describe("auth/oauth", () => {
});
it("throws API_ERROR on 5xx", async () => {
+ await writeStore({ oauth: { access_token: "at", refresh_token: "rt" } });
const fetchImpl = (async () =>
new Response("upstream", { status: 503 })) as unknown as typeof fetch;
await expect(refreshTokens("rt", { fetchImpl })).rejects.toSatisfy((err) => {
@@ -300,6 +331,20 @@ describe("auth/oauth", () => {
});
describe("revokeTokens", () => {
+ it("does not revoke another client's stored grant", async () => {
+ await writeUnboundStore({
+ oauth: {
+ access_token: "foreign-at",
+ refresh_token: "foreign-rt",
+ client_id: "another-client",
+ token_endpoint: oauthIdentity().token_endpoint,
+ },
+ });
+ const fetchImpl = vi.fn();
+ await revokeTokens("foreign-rt", { fetchImpl });
+ expect(fetchImpl).not.toHaveBeenCalled();
+ });
+
it("never throws on network failure (best-effort)", async () => {
const fetchImpl = (async () => {
throw new Error("connection refused");
@@ -348,6 +393,7 @@ describe("auth/oauth", () => {
describe("error scrubbing", () => {
it("refreshTokens does not leak token-shaped secrets from the error body", async () => {
+ await writeStore({ oauth: { access_token: "at", refresh_token: "rt_leak_secret" } });
const fetchImpl = (async () =>
new Response(
'{"error":"invalid_grant","echoed":"refresh_token=rt_leak_secret&code_verifier=cv_leak"}',
diff --git a/packages/cli/src/auth/oauth.ts b/packages/cli/src/auth/oauth.ts
index 4ef646beb8..d0cee324e4 100644
--- a/packages/cli/src/auth/oauth.ts
+++ b/packages/cli/src/auth/oauth.ts
@@ -38,7 +38,6 @@ import {
ErrApi,
ErrDeviceAuthFailed,
ErrLoginChanged,
- ErrOAuthNotConfigured,
ErrRefreshFailed,
isAuthError,
} from "./errors.js";
@@ -55,25 +54,23 @@ import {
type StoredUserInfo,
} from "./store.js";
import { c } from "../ui/colors.js";
+import {
+ assertOAuthIdentity,
+ authorizeEndpoint,
+ deviceAuthorizationEndpoint,
+ oauthIdentity,
+ resolveClientId,
+ revokeEndpoint,
+ tokenEndpoint,
+} from "./config.js";
+
+export { resolveClientId } from "./config.js";
const REVOKE_TIMEOUT_MS = 5_000;
const MIN_EXPIRES_IN_SECONDS = 30;
-/**
- * Default OAuth client_id baked at build time. Override with the
- * `HYPERFRAMES_OAUTH_CLIENT_ID` env var. Empty string means "not
- * configured" — `resolveClientId()` errors cleanly with a pointer
- * at `--api-key`.
- */
-const DEFAULT_CLIENT_ID = "q2A2QRSke2LrFTPJhoDbHtXh";
const DEFAULT_SCOPES = "openid profile email";
-// Endpoint defaults — see file-header comment for why these straddle two
-// hosts. Each is independently overridable.
-const DEFAULT_AUTHORIZE_URL = "https://app.heygen.com/oauth/authorize";
-const DEFAULT_TOKEN_URL = "https://api2.heygen.com/v1/oauth/token";
-const DEFAULT_REVOKE_URL = "https://api2.heygen.com/v1/oauth/revoke";
-const DEFAULT_DEVICE_AUTHORIZATION_URL = "https://api2.heygen.com/v1/oauth/device_authorization";
const DEVICE_CODE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
const MAX_DEVICE_FLOW_SECONDS = 30 * 60;
const MIN_DEVICE_POLL_SECONDS = 5;
@@ -81,19 +78,6 @@ const MAX_DEVICE_POLL_SECONDS = 60;
const MAX_DEVICE_RESPONSE_BYTES = 64 * 1024;
const DEVICE_REQUEST_TIMEOUT_MS = 15_000;
-function authorizeEndpoint(): string {
- return process.env["HYPERFRAMES_OAUTH_AUTHORIZE_URL"] || DEFAULT_AUTHORIZE_URL;
-}
-function tokenEndpoint(): string {
- return process.env["HYPERFRAMES_OAUTH_TOKEN_URL"] || DEFAULT_TOKEN_URL;
-}
-function revokeEndpoint(): string {
- return process.env["HYPERFRAMES_OAUTH_REVOKE_URL"] || DEFAULT_REVOKE_URL;
-}
-function deviceAuthorizationEndpoint(): string {
- return process.env["HYPERFRAMES_OAUTH_DEVICE_URL"] || DEFAULT_DEVICE_AUTHORIZATION_URL;
-}
-
export interface AuthorizeFlowOptions {
/** Override scopes (default `openid profile email`). */
scope?: string;
@@ -134,14 +118,6 @@ export interface DeviceAuthorizationFlowOptions {
onChallenge?: (challenge: DeviceAuthorizationChallenge) => void | Promise;
}
-/** Read the client_id, throwing `ErrOAuthNotConfigured` when unset. */
-export function resolveClientId(): string {
- const override = process.env["HYPERFRAMES_OAUTH_CLIENT_ID"];
- const id = override && override.length > 0 ? override : DEFAULT_CLIENT_ID;
- if (!id || id.length === 0) throw ErrOAuthNotConfigured();
- return id;
-}
-
/**
* For command-entry points: throw the standard `ErrOAuthNotConfigured`
* via `resolveClientId()`; on a real misconfig, print a friendly hint
@@ -214,7 +190,7 @@ export async function startAuthorizationCodeFlow(
* RFC 8628 attended device flow. This function deliberately returns an
* unpersisted token set: the command must verify `/v3/users/me` first and only
* then call `persistFreshOAuth`. That ordering prevents a token for the wrong
- * account/resource from ever becoming the active shared credential.
+ * account/resource from ever becoming the active HyperFrames credential.
*/
export async function startDeviceAuthorizationFlow(
opts: DeviceAuthorizationFlowOptions = {},
@@ -385,6 +361,9 @@ export async function refreshTokens(
refresh_token: string,
opts: RefreshOptions = {},
): Promise {
+ const { credentials } = await readStore();
+ if (credentials.oauth?.refresh_token !== refresh_token) throw ErrLoginChanged();
+ assertOAuthIdentity(credentials.oauth);
const clientId = resolveClientId();
const fetchImpl = opts.fetchImpl ?? fetch;
const body = new URLSearchParams({
@@ -432,6 +411,13 @@ export async function revokeTokens(token: string, opts: RevokeOptions = {}): Pro
let clientId: string;
try {
clientId = resolveClientId();
+ const { credentials } = await readStore();
+ if (
+ credentials.oauth &&
+ (credentials.oauth.access_token === token || credentials.oauth.refresh_token === token)
+ ) {
+ assertOAuthIdentity(credentials.oauth);
+ }
} catch {
// OAuth not configured — nothing to revoke server-side.
return;
@@ -488,7 +474,9 @@ function buildAuthorizeUrl(args: {
code_challenge: args.challenge,
code_challenge_method: "S256",
});
- return `${authorizeEndpoint()}?${params.toString()}`;
+ const urlWithEndpointQuery = new URL(authorizeEndpoint());
+ for (const [key, value] of params) urlWithEndpointQuery.searchParams.set(key, value);
+ return urlWithEndpointQuery.toString();
}
async function exchangeCodeForTokens(args: {
@@ -622,7 +610,9 @@ async function persistOAuth(tokens: OAuthTokens, opts: { refreshed?: string } =
throw ErrLoginChanged();
}
const oauth: OAuthTokens =
- opts.refreshed !== undefined ? { ...existing.oauth, ...tokens } : { ...tokens };
+ opts.refreshed !== undefined
+ ? { ...existing.oauth, ...tokens, ...oauthIdentity() }
+ : { ...tokens, ...oauthIdentity() };
// Start from the existing record so co-located data survives: the
// api_key, the friendly-display `user` block, AND any unknown/foreign
// keys another CLI wrote (carried on a hidden symbol slot by spread).
@@ -656,7 +646,7 @@ export async function persistVerifiedOAuthSession(
}
const next: Credentials = {
...credentials,
- oauth: { ...tokens },
+ oauth: { ...tokens, ...oauthIdentity() },
};
if (user.email || user.first_name || user.last_name || user.username) {
// Preserve only unknown/foreign user fields from the existing record.
diff --git a/packages/cli/src/auth/paths.test.ts b/packages/cli/src/auth/paths.test.ts
index ec78ef4556..785543c46f 100644
--- a/packages/cli/src/auth/paths.test.ts
+++ b/packages/cli/src/auth/paths.test.ts
@@ -1,32 +1,40 @@
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { homedir } from "node:os";
import { join } from "node:path";
import { CREDENTIAL_FILENAME, configDir, credentialPath } from "./paths.js";
describe("auth/paths", () => {
- const original = process.env["HEYGEN_CONFIG_DIR"];
+ const original = process.env["HYPERFRAMES_CONFIG_DIR"];
beforeEach(() => {
- delete process.env["HEYGEN_CONFIG_DIR"];
+ delete process.env["HYPERFRAMES_CONFIG_DIR"];
});
afterEach(() => {
- if (original !== undefined) process.env["HEYGEN_CONFIG_DIR"] = original;
- else delete process.env["HEYGEN_CONFIG_DIR"];
+ vi.unstubAllEnvs();
+ if (original !== undefined) process.env["HYPERFRAMES_CONFIG_DIR"] = original;
+ else delete process.env["HYPERFRAMES_CONFIG_DIR"];
});
- it("defaults to ~/.heygen", () => {
- expect(configDir()).toBe(join(homedir(), ".heygen"));
+ it("defaults to ~/.hyperframes", () => {
+ expect(configDir()).toBe(join(homedir(), ".hyperframes"));
});
- it("honors HEYGEN_CONFIG_DIR override", () => {
- process.env["HEYGEN_CONFIG_DIR"] = "/tmp/some-test-dir";
+ it("honors HYPERFRAMES_CONFIG_DIR override", () => {
+ process.env["HYPERFRAMES_CONFIG_DIR"] = "/tmp/some-test-dir";
expect(configDir()).toBe("/tmp/some-test-dir");
expect(credentialPath()).toBe(join("/tmp/some-test-dir", CREDENTIAL_FILENAME));
});
- it("treats empty HEYGEN_CONFIG_DIR as unset", () => {
- process.env["HEYGEN_CONFIG_DIR"] = "";
- expect(configDir()).toBe(join(homedir(), ".heygen"));
+ it("treats empty HYPERFRAMES_CONFIG_DIR as unset", () => {
+ process.env["HYPERFRAMES_CONFIG_DIR"] = "";
+ expect(configDir()).toBe(join(homedir(), ".hyperframes"));
+ });
+
+ it("ignores the HeyGen CLI directory and isolates the dev environment", () => {
+ vi.stubEnv("HEYGEN_CONFIG_DIR", "/tmp/heygen-other-account");
+ expect(configDir()).toBe(join(homedir(), ".hyperframes"));
+ vi.stubEnv("HYPERFRAMES_ENV", "dev");
+ expect(configDir()).toBe(join(homedir(), ".hyperframes", "dev"));
});
});
diff --git a/packages/cli/src/auth/paths.ts b/packages/cli/src/auth/paths.ts
index 3df82f4fc2..c909b24650 100644
--- a/packages/cli/src/auth/paths.ts
+++ b/packages/cli/src/auth/paths.ts
@@ -1,23 +1,19 @@
/**
- * Filesystem layout for the shared HeyGen credential store. Mirrors
- * `heygen-cli/internal/paths/paths.go` so both CLIs read the same file.
- * `HEYGEN_CONFIG_DIR` overrides the directory.
+ * HyperFrames credentials are isolated from the HeyGen CLI and between environments.
*/
import { homedir } from "node:os";
import { join } from "node:path";
+import { oauthEnvironment } from "./config.js";
/**
- * Filename for the credential store. Matches heygen-cli (no `.json`
- * suffix) so a `~/.heygen/credentials` written by either CLI is
- * readable by the other — see `heygen-cli/internal/auth/file_resolver.go`.
+ * Filename for the HyperFrames credential store (JSON, no extension).
*/
export const CREDENTIAL_FILENAME = "credentials";
export function configDir(): string {
- const override = process.env["HEYGEN_CONFIG_DIR"];
- if (override && override.length > 0) return override;
- return join(homedir(), ".heygen");
+ const root = process.env["HYPERFRAMES_CONFIG_DIR"] || join(homedir(), ".hyperframes");
+ return oauthEnvironment() === "dev" ? join(root, "dev") : root;
}
export function credentialPath(): string {
diff --git a/packages/cli/src/auth/resolver.test.ts b/packages/cli/src/auth/resolver.test.ts
index 6119879381..9450d74475 100644
--- a/packages/cli/src/auth/resolver.test.ts
+++ b/packages/cli/src/auth/resolver.test.ts
@@ -1,10 +1,18 @@
+import { oauthIdentity } from "./config.js";
import { promises as fs } from "node:fs";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { setupTempAuthEnv } from "./_test-utils.js";
import { isAuthError } from "./errors.js";
import { resolveCredential, tryResolveCredential } from "./resolver.js";
-import { writeStore } from "./store.js";
+import { writeStore as writeUnboundStore, type Credentials } from "./store.js";
+
+async function writeStore(credentials: Credentials): Promise {
+ await writeUnboundStore({
+ ...credentials,
+ ...(credentials.oauth ? { oauth: { ...oauthIdentity(), ...credentials.oauth } } : {}),
+ });
+}
describe("auth/resolver", () => {
let fixture: Awaited>;
@@ -102,15 +110,20 @@ describe("auth/resolver", () => {
if (r.type === "oauth") expect(r.refreshable).toBe(true);
});
- it("skips expired non-refreshable oauth and falls through to api_key", async () => {
+ it("refuses an expired OAuth login without switching to the stored API wallet", async () => {
const past = new Date(Date.now() - 60 * 60 * 1000).toISOString();
await writeStore({
api_key: "fallback",
oauth: { access_token: "stale-at", expires_at: past },
});
- const r = await resolveCredential();
- expect(r.type).toBe("api_key");
- if (r.type === "api_key") expect(r.key).toBe("fallback");
+ await expect(resolveCredential()).rejects.toMatchObject({ code: "LOGIN_EXPIRED" });
+ });
+
+ it("requires a new login for an unbound or foreign OAuth credential", async () => {
+ await writeUnboundStore({ api_key: "fallback", oauth: { access_token: "legacy" } });
+ await expect(resolveCredential()).rejects.toMatchObject({ code: "LOGIN_EXPIRED" });
+ await writeStore({ oauth: { access_token: "foreign", client_id: "shared-heygen-cli" } });
+ await expect(resolveCredential()).rejects.toMatchObject({ code: "LOGIN_EXPIRED" });
});
it("reports an expired login with no refresh token as expired, not as never signed in", async () => {
diff --git a/packages/cli/src/auth/resolver.ts b/packages/cli/src/auth/resolver.ts
index f2278ab730..f09559b28a 100644
--- a/packages/cli/src/auth/resolver.ts
+++ b/packages/cli/src/auth/resolver.ts
@@ -1,11 +1,11 @@
/**
- * Chain resolver for HeyGen credentials.
+ * Chain resolver for HyperFrames credentials.
*
* Priority — first non-empty wins:
* 1. `HEYGEN_API_KEY` env (matches heygen-cli)
* 2. `HYPERFRAMES_API_KEY` env (alias for parity with other tools)
* 3. `HEYGEN_ACCESS_TOKEN` env (host-managed OAuth)
- * 4. `~/.heygen/credentials` (JSON) — unexpired OAuth, else api_key
+ * 4. `~/.hyperframes/credentials` (JSON) — bound OAuth or an explicit API key
*
* Absent sources fall through. Broken files surface `ErrInvalidStore` immediately;
* silently falling back would mask user configuration errors.
@@ -13,11 +13,12 @@
* Expiry policy: an OAuth access_token whose `expires_at` is in the
* past (60s skew) is considered expired. If a `refresh_token` is also
* present, callers can still use it via `refreshable: true`. Otherwise
- * the api_key (if any) wins, else `ErrLoginExpired`, not `ErrNotConfigured`.
+ * session requires sign-in; a saved API key never replaces expired OAuth.
*/
import { isHeaderSafe, readStore } from "./store.js";
import { ErrInvalidStore, ErrLoginExpired, ErrNotConfigured, isAuthError } from "./errors.js";
+import { assertOAuthIdentity } from "./config.js";
type EnvSource = "env" | "env_alias" | "env_oauth";
type CredentialSource = EnvSource | "file_json" | "file_legacy";
@@ -79,12 +80,14 @@ export async function resolveCredential(opts: ResolveOptions = {}): Promise",
- * "scope": "openid profile",
- * "token_type": "Bearer"
- * },
- * "user": {
- * "email": "...",
- * "first_name": "...",
- * "last_name": "...",
- * "username": "..."
- * }
- * }
- *
- * Legacy: a single-line plaintext API key (the format heygen-cli has
- * written historically). If `JSON.parse` rejects the file, we treat the
- * trimmed contents as an API key; the next write upgrades to JSON.
- *
- * Writes go to a temp file + rename, 0600 mode, parent dir 0700.
- *
- * Cross-CLI forward compatibility: this file is SHARED with the Go
- * `heygen` CLI (and any future tool). Either CLI may write keys this
- * version doesn't model yet. To avoid one CLI silently clobbering the
- * other's data on round-trip, the reader stashes every unrecognized
- * top-level key (and every unrecognized key inside the `oauth` / `user`
- * sub-objects) into a hidden passthrough bag, and the writer re-emits
- * them verbatim. Known fields are still strictly validated; the
- * passthrough is purely additive and never feeds an HTTP header.
- *
- * The same contract binds the destructive paths (`clearOAuth`,
- * `clearUserInfo`, and the failed `auth login --api-key` rollback): when
- * removing a credential would leave the file with no known credential but
- * a surviving unknown/foreign top-level (or user-block) key, they write
- * the credential-less remnant rather than deleting the file — see
- * `hasPreservedUnknownData`. Deleting there would clobber exactly the
- * cross-CLI data this machinery exists to preserve.
+ * Atomic rename plus 0600 files/0700 directories protects credential writes.
+ * OAuth callers verify the client/environment binding before using stored grants.
+ * Unknown JSON fields survive round-trips so older versions preserve newer data;
+ * known fields are validated before they can enter an HTTP header.
*/
import { promises as fs } from "node:fs";
@@ -70,6 +34,8 @@ const KNOWN_OAUTH_KEYS = new Set([
"expires_at",
"scope",
"token_type",
+ "client_id",
+ "token_endpoint",
]);
/** Keys this CLI version models inside the `user` sub-object. */
const KNOWN_USER_KEYS = new Set(["email", "first_name", "last_name", "username"]);
@@ -81,6 +47,8 @@ export interface OAuthTokens {
expires_at?: string;
scope?: string;
token_type?: string;
+ client_id?: string;
+ token_endpoint?: string;
/** Unknown/future keys captured for cross-CLI round-trip. */
[UNKNOWN]?: Record;
}
@@ -284,6 +252,8 @@ function assignOptionalStrings(
}
const OAUTH_OPTIONAL: readonly [string, FieldPicker][] = [
+ ["client_id", "header_safe"],
+ ["token_endpoint", "non_empty"],
["refresh_token", "header_safe"],
["expires_at", "non_empty"],
["scope", "non_empty"],
@@ -433,6 +403,8 @@ function serializeOAuth(o: OAuthTokens): Record {
if (o.expires_at) oauth["expires_at"] = o.expires_at;
if (o.scope) oauth["scope"] = o.scope;
if (o.token_type) oauth["token_type"] = o.token_type;
+ if (o.client_id) oauth["client_id"] = o.client_id;
+ if (o.token_endpoint) oauth["token_endpoint"] = o.token_endpoint;
return oauth;
}
diff --git a/packages/cli/src/auth/telemetryIdentity.test.ts b/packages/cli/src/auth/telemetryIdentity.test.ts
new file mode 100644
index 0000000000..066cc0b0c9
--- /dev/null
+++ b/packages/cli/src/auth/telemetryIdentity.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it } from "vitest";
+import { heygenUserId, telemetryIdentity } from "./telemetryIdentity.js";
+
+describe("heygenUserId", () => {
+ // Vectors from the HyperFrames web app's toUUID (demo-next derive-user-id.ts),
+ // which keys its users table and PostHog persons. A mismatch splits one person
+ // across the CLI and the web app.
+ it("matches the web app's derived user id", () => {
+ expect(heygenUserId("alice")).toBe("2bd806c9-7f0e-50af-9a1f-c3328fa763a9");
+ expect(heygenUserId("21e28514b7994f46b907b74914a3ca6e")).toBe(
+ "9f3df3a5-89ae-5609-b80b-ce3b7d5f8c37",
+ );
+ });
+ it("passes a UUID through unhashed, like the web app", () => {
+ const id = "6f1c0d4e-2b3a-4c5d-8e9f-0a1b2c3d4e5f";
+ expect(heygenUserId(id)).toBe(id);
+ });
+
+ // media-use/lib/telemetry.test.mjs pins the same "alice" vector for its copy.
+});
+
+describe("telemetryIdentity", () => {
+ it("keys on the username and sets email and heygen_username", () => {
+ expect(telemetryIdentity({ username: "alice", email: " Alice@Example.com " })).toEqual({
+ distinctId: "2bd806c9-7f0e-50af-9a1f-c3328fa763a9",
+ traits: { email: "alice@example.com", heygen_username: "alice" },
+ });
+ });
+
+ it("keeps the username exactly as HeyGen returns it", () => {
+ expect(telemetryIdentity({ username: "Alice" })?.traits).toEqual({ heygen_username: "Alice" });
+ });
+
+ it("falls back to the lowercased email without a username", () => {
+ expect(telemetryIdentity({ email: "Alice@Example.com" })).toEqual({
+ distinctId: "alice@example.com",
+ traits: { email: "alice@example.com" },
+ });
+ });
+
+ it("returns nothing without an email or username", () => {
+ expect(telemetryIdentity({ username: " ", email: "" })).toBeUndefined();
+ });
+});
diff --git a/packages/cli/src/auth/telemetryIdentity.ts b/packages/cli/src/auth/telemetryIdentity.ts
new file mode 100644
index 0000000000..e196d4f4a8
--- /dev/null
+++ b/packages/cli/src/auth/telemetryIdentity.ts
@@ -0,0 +1,38 @@
+import { createHash } from "node:crypto";
+import type { UserInfo } from "./client.js";
+
+export interface TelemetryIdentity {
+ distinctId: string;
+ /** PostHog person properties. `heygen_username` joins one person across HeyGen's projects. */
+ traits: Record;
+}
+
+const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+/** The id the HyperFrames web app and Desktop key their users on: a UUID as is, else its sha256-derived UUID. */
+export function heygenUserId(username: string): string {
+ if (UUID_PATTERN.test(username)) return username;
+ const hash = createHash("sha256").update(username).digest();
+ hash[6] = (hash[6]! & 0x0f) | 0x50;
+ hash[8] = (hash[8]! & 0x3f) | 0x80;
+ const hex = hash.toString("hex");
+ return [
+ hex.slice(0, 8),
+ hex.slice(8, 12),
+ hex.slice(12, 16),
+ hex.slice(16, 20),
+ hex.slice(20, 32),
+ ].join("-");
+}
+
+/** Keyed on the username's user id; an account without one falls back to its lowercased email. */
+export function telemetryIdentity(user: UserInfo): TelemetryIdentity | undefined {
+ const email = user.email?.trim().toLowerCase() || undefined;
+ const username = user.username?.trim() ? user.username : undefined;
+ const traits: Record = {};
+ if (email) traits.email = email;
+ if (username) traits.heygen_username = username;
+ if (username) return { distinctId: heygenUserId(username), traits };
+ if (email) return { distinctId: email, traits };
+ return undefined;
+}
diff --git a/packages/cli/src/auth/user.ts b/packages/cli/src/auth/user.ts
index bb4146747a..f992a5f749 100644
--- a/packages/cli/src/auth/user.ts
+++ b/packages/cli/src/auth/user.ts
@@ -1,6 +1,6 @@
/**
* Persistence + display helpers for the friendly-display `user` block in
- * the shared `~/.heygen/credentials` file.
+ * the HyperFrames `~/.hyperframes/credentials` file.
*
* The `user` block is additive METADATA captured at login time from
* `GET /v3/users/me` — NOT a credential. It lets `auth status` (and the
diff --git a/packages/cli/src/background-removal/frameReader.test.ts b/packages/cli/src/background-removal/frameReader.test.ts
new file mode 100644
index 0000000000..6d5278f942
--- /dev/null
+++ b/packages/cli/src/background-removal/frameReader.test.ts
@@ -0,0 +1,101 @@
+import { PassThrough, Readable } from "node:stream";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { readFrames } from "./frameReader.js";
+
+const FRAME = 12;
+
+/** `count` frames whose every byte names the frame, so a mixed-up or shifted byte shows. */
+const frames = (count: number) =>
+ Array.from({ length: count }, (_, n) => Buffer.alloc(FRAME, n + 1));
+const stream = (chunks: Buffer[]) => Readable.from(chunks, { objectMode: false });
+const cut = (whole: Buffer, sizes: number[]) => {
+ const chunks: Buffer[] = [];
+ let at = 0;
+ for (const size of sizes) {
+ chunks.push(whole.subarray(at, at + size));
+ at += size;
+ }
+ if (at < whole.length) chunks.push(whole.subarray(at));
+ return chunks;
+};
+const read = async (source: NodeJS.ReadableStream) => {
+ const out: Buffer[] = [];
+ for await (const frame of readFrames(source, FRAME)) out.push(Buffer.from(frame));
+ return out;
+};
+
+afterEach(() => vi.restoreAllMocks());
+
+describe("readFrames", () => {
+ it("yields each frame in order whatever the chunks split or coalesce", async () => {
+ const sent = frames(6);
+ const whole = Buffer.concat(sent);
+ for (const sizes of [
+ [FRAME],
+ [1, 1, 1],
+ [5, 20, 3, 44],
+ [FRAME * 6],
+ [FRAME * 2 + 5, FRAME * 3 - 5],
+ [FRAME - 1, 1, FRAME + 1, FRAME - 1],
+ ]) {
+ expect(await read(stream(cut(whole, sizes)))).toEqual(sent);
+ }
+ });
+
+ it("drops a partial frame at the end of the stream, as a cut-off decoder leaves it", async () => {
+ const sent = frames(3);
+ const whole = Buffer.concat([...sent, Buffer.alloc(FRAME - 4, 9)]);
+ expect(await read(stream(cut(whole, [7, 19, 11])))).toEqual(sent);
+ });
+
+ it("yields nothing for an empty stream", async () => {
+ expect(await read(stream([]))).toEqual([]);
+ });
+
+ it("gives each frame its own memory, so a held frame survives the next one being read", async () => {
+ const whole = Buffer.concat(frames(3));
+ const held: Buffer[] = [];
+ for await (const frame of readFrames(stream(cut(whole, [5, 5, 5])), FRAME)) held.push(frame);
+ expect(held).toEqual(frames(3));
+ });
+
+ it("throws the stream's error to the reader", async () => {
+ const source = new PassThrough();
+ const reading = read(source);
+ source.write(Buffer.alloc(FRAME + 3, 1));
+ source.destroy(new Error("decoder pipe broke"));
+ await expect(reading).rejects.toThrow("decoder pipe broke");
+ });
+
+ it("stops reading, and releases the stream, when the reader leaves early", async () => {
+ const source = new PassThrough();
+ source.write(Buffer.concat(frames(4)));
+ for await (const frame of readFrames(source, FRAME)) {
+ expect(frame).toEqual(frames(1)[0]);
+ break;
+ }
+ expect(source.destroyed).toBe(true);
+ });
+
+ it("copies each byte once: a pipe's small chunks never re-copy what was already gathered", async () => {
+ const frameBytes = 64 * 1024 * 8;
+ const frame = Buffer.alloc(frameBytes, 7);
+ const chunks = cut(Buffer.concat([frame, frame, frame]), Array(24).fill(64 * 1024));
+ const concat = vi.spyOn(Buffer, "concat");
+ const copy = vi.spyOn(Buffer.prototype, "copy");
+
+ let count = 0;
+ for await (const got of readFrames(stream(chunks), frameBytes)) {
+ expect(got.length).toBe(frameBytes);
+ count++;
+ }
+
+ const concatenated = concat.mock.results.reduce(
+ (sum, r) => sum + (r.value as Buffer).length,
+ 0,
+ );
+ const copied = copy.mock.results.reduce((sum, r) => sum + (r.value as number), 0);
+ expect(count).toBe(3);
+ expect(concatenated + copied).toBeLessThanOrEqual(frameBytes * 3 * 1.01);
+ });
+});
diff --git a/packages/cli/src/background-removal/frameReader.ts b/packages/cli/src/background-removal/frameReader.ts
new file mode 100644
index 0000000000..d760a3fb7c
--- /dev/null
+++ b/packages/cli/src/background-removal/frameReader.ts
@@ -0,0 +1,24 @@
+/** Whole frames from a raw-video pipe: each chunk is copied once, into the frame it belongs to. */
+export async function* readFrames(
+ stream: NodeJS.ReadableStream,
+ frameBytes: number,
+): AsyncGenerator {
+ let frame: Buffer | undefined;
+ let filled = 0;
+ for await (const chunk of stream as AsyncIterable) {
+ let at = 0;
+ while (at < chunk.length) {
+ frame ??= Buffer.allocUnsafe(frameBytes);
+ const take = Math.min(frameBytes - filled, chunk.length - at);
+ chunk.copy(frame, filled, at, at + take);
+ filled += take;
+ at += take;
+ if (filled === frameBytes) {
+ const whole = frame;
+ frame = undefined;
+ filled = 0;
+ yield whole;
+ }
+ }
+ }
+}
diff --git a/packages/cli/src/background-removal/inference.stop.test.ts b/packages/cli/src/background-removal/inference.stop.test.ts
new file mode 100644
index 0000000000..b5cd8484d7
--- /dev/null
+++ b/packages/cli/src/background-removal/inference.stop.test.ts
@@ -0,0 +1,96 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const cleanups = vi.hoisted(() => new Set<() => Promise>());
+const native = vi.hoisted(() => ({
+ frames: [] as (() => void)[],
+ released: 0,
+ releasedDuringFrame: 0,
+ inFrame: false,
+}));
+
+vi.mock("../browser/launch.js", () => ({
+ registerBrowserSessionCleanup: (cleanup: () => Promise) => {
+ cleanups.add(cleanup);
+ return () => cleanups.delete(cleanup);
+ },
+}));
+vi.mock("./manager.js", () => ({
+ ensureModel: async () => "model.onnx",
+ selectProviders: () => ({ providers: ["coreml", "cpu"], label: "CoreML" }),
+}));
+vi.mock("./coremlTemp.js", () => ({
+ trackCoreMlTemp: () => ({ record: () => undefined, forget: () => undefined }),
+}));
+// A frame inside the native session ends when the test says so; releasing the session meanwhile is what aborts
+// the process on a Mac ("mutex lock failed").
+vi.mock("../utils/optionalPackages.js", () => {
+ const chain: Record = {};
+ for (const step of ["resize", "raw", "toColourspace"]) chain[step] = () => chain;
+ chain.toBuffer = async () => Buffer.alloc(320 * 320 * 3);
+ return {
+ loadSharp: async () => () => chain,
+ loadOptionalPackage: async () => ({
+ Tensor: class {},
+ InferenceSession: {
+ create: async () => ({
+ inputNames: ["in"],
+ outputNames: ["out"],
+ run: () =>
+ new Promise((resolve) => {
+ native.inFrame = true;
+ native.frames.push(() => {
+ native.inFrame = false;
+ resolve({ out: { data: new Float32Array(320 * 320) } });
+ });
+ }),
+ release: async () => {
+ native.released++;
+ if (native.inFrame) native.releasedDuringFrame++;
+ },
+ }),
+ },
+ }),
+ };
+});
+
+import { createSession } from "./inference.js";
+
+const frame = (session: Awaited>) =>
+ session.process(Buffer.alloc(48), 4, 4);
+const settle = () => new Promise((resolve) => setTimeout(resolve, 5));
+
+beforeEach(() => {
+ cleanups.clear();
+ Object.assign(native, { frames: [], released: 0, releasedDuringFrame: 0, inFrame: false });
+});
+
+describe("a stop signal while a frame is inside the session", () => {
+ it("releases the session only after that frame has ended", async () => {
+ const session = await createSession();
+ const running = frame(session);
+ await settle();
+ const [stop] = [...cleanups];
+
+ const stopped = stop!();
+ await settle();
+ expect(native.released).toBe(0);
+
+ native.frames.shift()!();
+ await running.catch(() => undefined);
+ await stopped;
+
+ expect(native.released).toBe(1);
+ expect(native.releasedDuringFrame).toBe(0);
+ });
+
+ it("starts no frame after the stop, and closing afterwards does not release a second time", async () => {
+ const session = await createSession();
+ const [stop] = [...cleanups];
+ await stop!();
+
+ await expect(frame(session)).rejects.toThrow(/stopped/i);
+ await session.close();
+
+ expect(native.released).toBe(1);
+ });
+});
diff --git a/packages/cli/src/background-removal/inference.ts b/packages/cli/src/background-removal/inference.ts
index 1f124c45fa..a1fd33bbdc 100644
--- a/packages/cli/src/background-removal/inference.ts
+++ b/packages/cli/src/background-removal/inference.ts
@@ -9,6 +9,7 @@ import type { InferenceSession, Tensor } from "onnxruntime-node";
import type sharpType from "sharp";
import { loadOptionalPackage, loadSharp } from "../utils/optionalPackages.js";
import { registerBrowserSessionCleanup } from "../browser/launch.js";
+import { drainToExit } from "../utils/commandResult.js";
import { trackCoreMlTemp } from "./coremlTemp.js";
import { ensureModel, selectProviders, type Device, type ModelId } from "./manager.js";
@@ -75,7 +76,23 @@ export async function createSession(options: CreateSessionOptions = {}): Promise
const coreMlTemp = choice.label === "CoreML" ? trackCoreMlTemp() : undefined;
// A signal stops the run through the CLI's shutdown, which releases the session so CoreML removes its temp files.
- const unregister = coreMlTemp && registerBrowserSessionCleanup(async () => session?.release());
+ // Releasing it while a frame is inside it aborts the process, so the stop waits for that frame and refuses the next.
+ if (coreMlTemp) drainToExit();
+ let stopped = false;
+ let inFlight: Promise | undefined;
+ let released = false;
+ const release = async () => {
+ if (released || !session) return;
+ released = true;
+ await session.release();
+ };
+ const unregister =
+ coreMlTemp &&
+ registerBrowserSessionCleanup(async () => {
+ stopped = true;
+ await inFlight;
+ await release();
+ });
let session: InferenceSession;
let providerUsed = choice.label;
try {
@@ -125,38 +142,45 @@ export async function createSession(options: CreateSessionOptions = {}): Promise
}
};
+ const convert = async (rgb: Buffer, width: number, height: number, withBackground: boolean) => {
+ const tensor = await preprocess(sharp, ort, rgb, width, height, inputData);
+ const outputs = await run(tensor);
+ const output = outputs[outputName];
+ if (!output) throw new Error(`Model did not return output '${outputName}'`);
+ const expectedBytes = width * height * 4;
+ if (!rgbaBuf || rgbaBuf.length !== expectedBytes) {
+ rgbaBuf = Buffer.allocUnsafe(expectedBytes);
+ }
+ if (withBackground) {
+ if (!rgbaBgBuf || rgbaBgBuf.length !== expectedBytes) {
+ rgbaBgBuf = Buffer.allocUnsafe(expectedBytes);
+ }
+ }
+ return await postprocess(
+ sharp,
+ output,
+ rgb,
+ width,
+ height,
+ maskBuf,
+ rgbaBuf,
+ withBackground ? rgbaBgBuf : null,
+ );
+ };
+
return {
get provider() {
return providerUsed;
},
async process(rgb, width, height, withBackground = false) {
- const tensor = await preprocess(sharp, ort, rgb, width, height, inputData);
- const outputs = await run(tensor);
- const output = outputs[outputName];
- if (!output) throw new Error(`Model did not return output '${outputName}'`);
- const expectedBytes = width * height * 4;
- if (!rgbaBuf || rgbaBuf.length !== expectedBytes) {
- rgbaBuf = Buffer.allocUnsafe(expectedBytes);
- }
- if (withBackground) {
- if (!rgbaBgBuf || rgbaBgBuf.length !== expectedBytes) {
- rgbaBgBuf = Buffer.allocUnsafe(expectedBytes);
- }
- }
- return await postprocess(
- sharp,
- output,
- rgb,
- width,
- height,
- maskBuf,
- rgbaBuf,
- withBackground ? rgbaBgBuf : null,
- );
+ if (stopped) throw new Error("Background removal was stopped.");
+ const frame = convert(rgb, width, height, withBackground);
+ inFlight = frame.catch(() => undefined);
+ return await frame;
},
async close() {
unregister?.();
- await session.release();
+ await release();
coreMlTemp?.forget();
},
};
diff --git a/packages/cli/src/background-removal/pipeline.ts b/packages/cli/src/background-removal/pipeline.ts
index 5b7f6a6b7c..905e4ef480 100644
--- a/packages/cli/src/background-removal/pipeline.ts
+++ b/packages/cli/src/background-removal/pipeline.ts
@@ -19,6 +19,7 @@ import { renameSync, rmSync } from "node:fs";
import { basename, dirname, extname, join } from "node:path";
import { findFFmpeg, findFFprobe, getFFmpegInstallHint } from "../browser/ffmpeg.js";
import { runCancellableProcess } from "../utils/cancellableProcess.js";
+import { readFrames } from "./frameReader.js";
import { createSession, type Session } from "./inference.js";
import { type Device, type ModelId } from "./manager.js";
import {
@@ -273,22 +274,6 @@ export function buildEncoderArgs(
return [...base, "-frames:v", "1", "-pix_fmt", "rgba", "-update", "1", outputPath];
}
-async function* readFrames(
- stream: NodeJS.ReadableStream,
- frameBytes: number,
-): AsyncGenerator {
- let buffered: Buffer = Buffer.alloc(0);
- for await (const chunk of stream) {
- buffered =
- buffered.length === 0 ? (chunk as Buffer) : Buffer.concat([buffered, chunk as Buffer]);
- while (buffered.length >= frameBytes) {
- // Copy because the next concat would clobber the underlying memory.
- yield Buffer.from(buffered.subarray(0, frameBytes));
- buffered = buffered.subarray(frameBytes);
- }
- }
-}
-
export interface RenderTargets {
format: OutputFormat;
inputKind: "video" | "image";
diff --git a/packages/cli/src/browser/ffmpeg.test.ts b/packages/cli/src/browser/ffmpeg.test.ts
index 99830a2a78..33b3d9bc1a 100644
--- a/packages/cli/src/browser/ffmpeg.test.ts
+++ b/packages/cli/src/browser/ffmpeg.test.ts
@@ -121,6 +121,10 @@ describe("resolveH264EncoderMode", () => {
).rejects.toThrow(H264EncoderUnavailableError);
expect(probeGpu).toHaveBeenCalledOnce();
+ await expect(
+ detectH264EncoderModeForRender("/custom/ffmpeg", true, signal, probeGpu),
+ ).rejects.toThrow("/custom/ffmpeg has no libx264");
+
mockRun.mockResolvedValue({ stdout: " V....D h264_nvenc H.264\n" } as never);
expect(await detectH264EncoderModeForRender("/custom/ffmpeg", true, signal)).toBe("gpu");
expect(gpuProbes.shared).toHaveBeenCalledOnce();
diff --git a/packages/cli/src/browser/ffmpeg.ts b/packages/cli/src/browser/ffmpeg.ts
index c7fa224998..088fc48a81 100644
--- a/packages/cli/src/browser/ffmpeg.ts
+++ b/packages/cli/src/browser/ffmpeg.ts
@@ -1,5 +1,5 @@
import { getCachedGpuEncoder } from "@hyperframes/engine";
-import { findFfBinary } from "@hyperframes/parsers/ff-binaries";
+import { findFfBinary, getSkippedX86Binary } from "@hyperframes/parsers/ff-binaries";
import { detectLinuxDistro, ffmpegInstallCommand } from "./linuxDeps.js";
import { runCancellableProcess } from "../utils/cancellableProcess.js";
@@ -8,8 +8,13 @@ export { FFMPEG_PATH_ENV, FFPROBE_PATH_ENV } from "@hyperframes/parsers/ff-binar
export type H264EncoderMode = "software" | "gpu";
export class H264EncoderUnavailableError extends Error {
- constructor(readonly hevcEncoderAvailable = false) {
- super("This FFmpeg build has no libx264 and no GPU H.264 encoder that works on this machine.");
+ constructor(
+ readonly hevcEncoderAvailable = false,
+ ffmpegPath?: string,
+ ) {
+ super(
+ `${ffmpegPath ?? "This FFmpeg build"} has no libx264 and no GPU H.264 encoder that works on this machine.`,
+ );
this.name = "H264EncoderUnavailableError";
}
}
@@ -25,11 +30,12 @@ export function resolveH264EncoderMode(
ffmpegEncodersOutput: string,
gpuRequested: boolean,
usableGpu: boolean,
+ ffmpegPath?: string,
): H264EncoderMode {
if (gpuRequested && usableGpu) return "gpu";
if (hasLibx264(ffmpegEncodersOutput)) return "software";
if (usableGpu) return "gpu";
- throw new H264EncoderUnavailableError(/\blibx265\b/.test(ffmpegEncodersOutput));
+ throw new H264EncoderUnavailableError(/\blibx265\b/.test(ffmpegEncodersOutput), ffmpegPath);
}
function hasLibx264(ffmpegEncodersOutput: string): boolean {
@@ -48,7 +54,7 @@ export async function detectH264EncoderModeForRender(
});
const needsGpu = gpuRequested || !hasLibx264(result.stdout);
const usableGpu = needsGpu && (await probeGpu()) !== null;
- return resolveH264EncoderMode(result.stdout, gpuRequested, usableGpu);
+ return resolveH264EncoderMode(result.stdout, gpuRequested, usableGpu, ffmpegPath);
}
// `configuredMustExist`: the CLI surfaces an install hint when a binary is
@@ -96,6 +102,15 @@ export function getFFmpegInstallCommand(): string | undefined {
}
export function getFFmpegInstallHint(): string {
+ const ignored = (["ffmpeg", "ffprobe"] as const)
+ .filter((name) => !findFfBinary(name, { configuredMustExist: true }))
+ .map(getSkippedX86Binary)
+ .filter((path) => path !== undefined);
+ const note = ignored.map((path) => ` (ignored ${path}: x86_64 only, it cannot run on this Mac)`);
+ return installHint() + note.join("");
+}
+
+function installHint(): string {
const command = getFFmpegInstallCommand();
// Guarding on `command`, not the platform alone: the function above is the
// sole owner of platform-to-command, so the day win32 stops returning one
diff --git a/packages/cli/src/browser/manager.test.ts b/packages/cli/src/browser/manager.test.ts
index 6556c96a1d..da953ea1c3 100644
--- a/packages/cli/src/browser/manager.test.ts
+++ b/packages/cli/src/browser/manager.test.ts
@@ -739,6 +739,43 @@ describe("findBrowser — cache resolution", () => {
}
});
+ it.each(["EBUSY", "EPERM"])(
+ "does not fail a run when Windows holds a leftover's debug.log (%s)",
+ async (code) => {
+ const home = useRealCacheHome();
+ const root = join(home, ".cache", "hyperframes");
+ const held = join(root, ".chrome-replaced-dead");
+ vi.doMock("node:fs", async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ rmSync: (path: string, options?: Parameters[1]) => {
+ if (!String(path).includes(".chrome-replaced-")) return actual.rmSync(path, options);
+ throw Object.assign(
+ new Error(`${code}: operation not permitted, unlink '${path}/debug.log'`),
+ { code },
+ );
+ },
+ };
+ });
+ installPuppeteerBrowsersMock({
+ installImpl: async ({ cacheDir, buildId }) =>
+ writeStagedInstall(cacheDir, buildId, "fresh"),
+ });
+ try {
+ const { ensureBrowser, sweepKilledInstalls, clearBrowser } = await import("./manager.js");
+ mkdirSync(held, { recursive: true });
+ await expect(sweepKilledInstalls()).resolves.toBeUndefined();
+ await expect(ensureBrowser({ force: true })).resolves.toMatchObject({ source: "download" });
+ await ensureBrowser({ force: true });
+ expect(existsSync(held)).toBe(true);
+ expect(() => clearBrowser()).toThrow(code);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ },
+ );
+
it("serializes concurrent force downloads so they never install at the same time", async () => {
const downloadedBinary = join(HF_CACHE, "chrome-headless-shell", "force-downloaded");
const paths = installFsMocks({
diff --git a/packages/cli/src/browser/manager.ts b/packages/cli/src/browser/manager.ts
index d96e89b944..831b18ebaf 100644
--- a/packages/cli/src/browser/manager.ts
+++ b/packages/cli/src/browser/manager.ts
@@ -907,7 +907,7 @@ function moveStagedInstallIntoCache(
if (replaced) renameSync(aside, target);
throw err;
}
- if (replaced) rmSync(aside, { recursive: true, force: true });
+ if (replaced) removeLeftover(aside);
return join(target, relative(staged.path, staged.executablePath));
}
@@ -918,7 +918,7 @@ const REPLACED_PREFIX = ".chrome-replaced-";
const isInstallLeftover = (name: string) =>
name.startsWith(STAGING_PREFIX) || name.startsWith(REPLACED_PREFIX);
-function removeInstallLeftovers(): boolean {
+function removeInstallLeftovers(tolerateLocked = true): boolean {
let names: string[];
try {
names = readdirSync(CACHE_ROOT_DIR);
@@ -927,11 +927,19 @@ function removeInstallLeftovers(): boolean {
throw err;
}
const leftovers = names.filter(isInstallLeftover);
- for (const name of leftovers)
- rmSync(join(CACHE_ROOT_DIR, name), { recursive: true, force: true });
+ for (const name of leftovers) removeLeftover(join(CACHE_ROOT_DIR, name), tolerateLocked);
return leftovers.length > 0;
}
+// A running Chrome keeps its debug.log open and Windows refuses to unlink it; the next sweep retries.
+function removeLeftover(path: string, tolerateLocked = true): void {
+ try {
+ rmSync(path, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
+ } catch (err) {
+ if (!tolerateLocked || (!isErrno(err, "EBUSY") && !isErrno(err, "EPERM"))) throw err;
+ }
+}
+
export async function sweepKilledInstalls(): Promise {
const names = existsSync(CACHE_ROOT_DIR) ? readdirSync(CACHE_ROOT_DIR) : [];
if (!names.some(isInstallLeftover)) return;
@@ -940,7 +948,7 @@ export async function sweepKilledInstalls(): Promise {
// Deletes the managed Chrome cache and interrupted-install leftovers; true when any of them existed.
export function clearBrowser(): boolean {
- const removedLeftovers = removeInstallLeftovers();
+ const removedLeftovers = removeInstallLeftovers(false);
if (!existsSync(CACHE_DIR)) return removedLeftovers;
rmSync(CACHE_DIR, { recursive: true, force: true });
return true;
diff --git a/packages/cli/src/capture/captureAttempt.ts b/packages/cli/src/capture/captureAttempt.ts
index 1386249685..3c728c9943 100644
--- a/packages/cli/src/capture/captureAttempt.ts
+++ b/packages/cli/src/capture/captureAttempt.ts
@@ -30,6 +30,7 @@ import type { CaptureWatchdog } from "./captureWatchdog.js";
import type { PartialCaptureState } from "./partialCapture.js";
import { runNavigationChecks } from "./navigationPhase.js";
+import { watchWebglStall } from "./webglStallWatch.js";
import { runCoreExtraction } from "./coreExtractionPhase.js";
import { runPostExtraction } from "./postExtractionPhase.js";
@@ -153,6 +154,7 @@ export async function captureWebsiteAttempt(
bodyChildCount: Number.POSITIVE_INFINITY,
};
let contentCheckTimedOut = false;
+ let stallWatch: { stop(): void } | undefined;
try {
// ═══════════════════════════════════════════════════════════════
@@ -171,6 +173,11 @@ export async function captureWebsiteAttempt(
// Set up hooks BEFORE navigation
await setupAnimationCapture(page1);
const { cdp, animations: cdpAnims } = await startCdpAnimationCapture(page1);
+ if (!disableWebgl)
+ stallWatch = watchWebglStall(cdp, () => {
+ state.webglStalled = true;
+ void captureBrowser.close();
+ });
// Hook WebGL to capture shader source code (GLSL)
// Captured shaders inform Claude Code about the site's visual effects
@@ -352,6 +359,7 @@ export async function captureWebsiteAttempt(
lastPhase,
};
} finally {
+ stallWatch?.stop();
watchdog.unregisterBrowser(captureBrowser);
await captureBrowser.close();
}
diff --git a/packages/cli/src/capture/captureCompositionFrame.browserFallback.test.ts b/packages/cli/src/capture/captureCompositionFrame.browserFallback.test.ts
index 8400a665d4..f2f93673c7 100644
--- a/packages/cli/src/capture/captureCompositionFrame.browserFallback.test.ts
+++ b/packages/cli/src/capture/captureCompositionFrame.browserFallback.test.ts
@@ -269,4 +269,13 @@ describe("openSettledCompositionPage when nothing may listen", () => {
expect(launched().args).toEqual(["--headless", HYPERFRAMES_BROWSER_MARKER_ARG]);
expect(opened.page.setRequestInterception).not.toHaveBeenCalled();
});
+
+ it("asks the page to replay skipped frames, so a still shows what playback shows", async () => {
+ const opened = fakeBrowser();
+ mocks.launch.mockResolvedValue(opened.browser);
+ await openSettledCompositionPage(HTML, "http://127.0.0.1:3000", OPTIONS);
+ expect(opened.page.evaluateOnNewDocument).toHaveBeenCalledWith(
+ "window.__HF_REPLAY_SKIPPED_FRAMES = true",
+ );
+ });
});
diff --git a/packages/cli/src/capture/captureCompositionFrame.test.ts b/packages/cli/src/capture/captureCompositionFrame.test.ts
index 69fa311aa8..9a21a76594 100644
--- a/packages/cli/src/capture/captureCompositionFrame.test.ts
+++ b/packages/cli/src/capture/captureCompositionFrame.test.ts
@@ -1,3 +1,4 @@
+import { SEEK_SETTLES_BEFORE_PROTOCOL_TIMEOUT_MS } from "./captureTimeout.js";
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
@@ -111,7 +112,10 @@ describe("seekCompositionTimeline", () => {
expect(waitForFunction).not.toHaveBeenCalled();
expect(evaluate).toHaveBeenCalledTimes(4);
expect(evaluate).toHaveBeenNthCalledWith(1, expect.any(Function), 1.25, false, false, false);
- expect(evaluate).toHaveBeenNthCalledWith(2, expect.any(Function), { videoFrames: true });
+ expect(evaluate).toHaveBeenNthCalledWith(2, expect.any(Function), {
+ videoFrames: true,
+ timeoutMs: SEEK_SETTLES_BEFORE_PROTOCOL_TIMEOUT_MS,
+ });
expect(evaluate.mock.calls[2]?.[0]).toContain("window.setTimeout(finish, 100)");
// Post-seek font settle: a seek can reveal glyphs whose unicode-range
// subsets only start loading after the next layout (CJK snapshot reports).
@@ -126,7 +130,10 @@ describe("seekCompositionTimeline", () => {
expect(evaluate).toHaveBeenNthCalledWith(1, expect.any(Function), 1.25, false, false, false);
await settleCompositionSeek(page);
- expect(evaluate).toHaveBeenNthCalledWith(2, expect.any(Function), { videoFrames: true });
+ expect(evaluate).toHaveBeenNthCalledWith(2, expect.any(Function), {
+ videoFrames: true,
+ timeoutMs: SEEK_SETTLES_BEFORE_PROTOCOL_TIMEOUT_MS,
+ });
expect(evaluate).toHaveBeenCalledTimes(4);
});
@@ -245,7 +252,10 @@ describe("seekCompositionTimeline", () => {
expect(evaluate).toHaveBeenCalledTimes(3);
expect(evaluate).toHaveBeenNthCalledWith(1, expect.any(Function), 4, true, false, false);
- expect(evaluate).toHaveBeenNthCalledWith(2, expect.any(Function), { videoFrames: true });
+ expect(evaluate).toHaveBeenNthCalledWith(2, expect.any(Function), {
+ videoFrames: true,
+ timeoutMs: SEEK_SETTLES_BEFORE_PROTOCOL_TIMEOUT_MS,
+ });
expect(evaluate).toHaveBeenNthCalledWith(3, expect.any(Function), { ms: 500, frames: 2 });
const frames: (() => void)[] = [];
@@ -543,8 +553,12 @@ describe("DENSE_GEOMETRY_SEEK_OPTIONS", () => {
return barrier.mock.calls;
};
- expect(await barrierCalls(DENSE_GEOMETRY_SEEK_OPTIONS)).toEqual([[{ videoFrames: false }]]);
- expect(await barrierCalls(AUDIT_SEEK_OPTIONS)).toEqual([[{ videoFrames: true }]]);
+ expect(await barrierCalls(DENSE_GEOMETRY_SEEK_OPTIONS)).toEqual([
+ [{ videoFrames: false, timeoutMs: SEEK_SETTLES_BEFORE_PROTOCOL_TIMEOUT_MS }],
+ ]);
+ expect(await barrierCalls(AUDIT_SEEK_OPTIONS)).toEqual([
+ [{ videoFrames: true, timeoutMs: SEEK_SETTLES_BEFORE_PROTOCOL_TIMEOUT_MS }],
+ ]);
});
it("is genuinely geometry-only — no post-seek settle waits at the 600-sample cap", () => {
diff --git a/packages/cli/src/capture/captureCompositionFrame.ts b/packages/cli/src/capture/captureCompositionFrame.ts
index 9110ab0a9d..35b1143df8 100644
--- a/packages/cli/src/capture/captureCompositionFrame.ts
+++ b/packages/cli/src/capture/captureCompositionFrame.ts
@@ -1,4 +1,5 @@
import { oneProcessOverPipe } from "@hyperframes/engine";
+import { SEEK_SETTLES_BEFORE_PROTOCOL_TIMEOUT_MS } from "./captureTimeout.js";
import {
rethrowAfterBrowserCleanup,
launchManagedBrowser,
@@ -72,7 +73,7 @@ export interface SeekCompositionTimelineOptions {
skipWebglDraws?: boolean;
}
-type SeekBarrierOptions = { videoFrames: boolean };
+type SeekBarrierOptions = { videoFrames: boolean; timeoutMs: number };
type FontWaitOptions = { ms: number; frames: number };
type CompositionPageFunction =
@@ -340,6 +341,7 @@ export async function openSettledCompositionPage(
await import("@hyperframes/engine");
await installMediaRenderIdBridge(page);
await page.evaluateOnNewDocument(forcePreservedDrawingBuffer);
+ await page.evaluateOnNewDocument("window.__HF_REPLAY_SKIPPED_FRAMES = true");
await page.setViewport(viewport);
if (answer) await answerPageInProcess(page, url, answer);
await options.beforeNavigate?.(page);
@@ -560,7 +562,10 @@ export async function settleCompositionSeek(
await Reflect.apply(waitForCompletion, window, [barrier]);
}
},
- { videoFrames: options.waitForVideoFrames !== false },
+ {
+ videoFrames: options.waitForVideoFrames !== false,
+ timeoutMs: SEEK_SETTLES_BEFORE_PROTOCOL_TIMEOUT_MS,
+ },
);
const animationFrameSettle = options.animationFrameSettle ?? "race";
diff --git a/packages/cli/src/capture/captureTimeout.ts b/packages/cli/src/capture/captureTimeout.ts
index 43682e7a29..41b3d5e67c 100644
--- a/packages/cli/src/capture/captureTimeout.ts
+++ b/packages/cli/src/capture/captureTimeout.ts
@@ -1,4 +1,6 @@
export const PUPPETEER_DEFAULT_PROTOCOL_TIMEOUT_MS = 180_000;
+export const SEEK_SETTLES_BEFORE_PROTOCOL_TIMEOUT_MS =
+ PUPPETEER_DEFAULT_PROTOCOL_TIMEOUT_MS - 10_000;
export class StageBudgetTimeoutError extends Error {
readonly budgetMs: number;
diff --git a/packages/cli/src/capture/index.ts b/packages/cli/src/capture/index.ts
index aafc33d1fc..2c8bd5e27e 100644
--- a/packages/cli/src/capture/index.ts
+++ b/packages/cli/src/capture/index.ts
@@ -53,11 +53,12 @@ async function captureTarget(
try {
return await settle(run(false));
} catch (err) {
- if (!(err instanceof NavigationDeadlineError) || watchdog.expired() || !err.webglObserved) {
- throw err;
- }
- onProgress?.("warn", "Navigation timed out; retrying once with WebGL disabled");
- state.warnings.push("Navigation timed out; retrying once with WebGL disabled");
+ const navigationStalled = err instanceof NavigationDeadlineError && err.webglObserved;
+ if (!(navigationStalled || state.webglStalled) || watchdog.expired()) throw err;
+ const why = navigationStalled ? "Navigation timed out" : "The page stopped answering";
+ state.webglStalled = false;
+ onProgress?.("warn", `${why}; retrying once with WebGL disabled`);
+ state.warnings.push(`${why}; retrying once with WebGL disabled`);
opts.onPhase?.({
schema: CAPTURE_PHASE_SCHEMA,
phase: "navigation",
diff --git a/packages/cli/src/capture/index.watchdog.test.ts b/packages/cli/src/capture/index.watchdog.test.ts
index 0619aa79ce..2ed698bdab 100644
--- a/packages/cli/src/capture/index.watchdog.test.ts
+++ b/packages/cli/src/capture/index.watchdog.test.ts
@@ -36,7 +36,7 @@ describe("capture navigation retry launch", () => {
it("retries a WebGL navigation deadline and carries the degradation warning into the result", async () => {
const options: CaptureOptions = {
url: "https://example.com",
- outputDir: "/tmp/hf-capture-test",
+ outputDir: "/nonexistent/hf-capture-test",
};
const partial = createPartialCaptureState(options);
const result: CaptureResult = {
@@ -85,7 +85,7 @@ describe("capture navigation retry launch", () => {
it("does not retry a navigation deadline without observed WebGL", async () => {
const options: CaptureOptions = {
url: "https://example.com",
- outputDir: "/tmp/hf-capture-test-no-webgl",
+ outputDir: "/nonexistent/hf-capture-test-no-webgl",
};
captureWebsiteAttemptMock.mockReset();
captureWebsiteAttemptMock.mockRejectedValueOnce(
@@ -96,6 +96,70 @@ describe("capture navigation retry launch", () => {
await expect(captureWebsite(options)).rejects.toThrow("capture navigation timed out");
expect(captureWebsiteAttemptMock).toHaveBeenCalledOnce();
});
+ const closedBrowser = () => new Error("Protocol error: Connection closed.");
+
+ it("retries once without WebGL when the page stopped answering", async () => {
+ const options: CaptureOptions = {
+ url: "https://example.com",
+ outputDir: "capture-test-stall-out",
+ };
+ const finished = {
+ ...(await import("./partialCapture.js")).createPartialCaptureState(options),
+ };
+ captureWebsiteAttemptMock.mockReset();
+ captureWebsiteAttemptMock
+ .mockImplementationOnce(async (_o, _p, _w, _wd, state: { webglStalled: boolean }) => {
+ state.webglStalled = true;
+ throw closedBrowser();
+ })
+ .mockResolvedValueOnce({
+ ok: true,
+ projectDir: options.outputDir,
+ url: options.url,
+ httpStatus: 200,
+ title: "",
+ extracted: finished.extracted,
+ screenshots: [],
+ tokens: finished.tokens,
+ assets: [],
+ dropped: finished.dropped,
+ warnings: [],
+ lastPhase: {
+ schema: CAPTURE_PHASE_SCHEMA,
+ phase: "complete",
+ status: "completed",
+ remainingMs: 1,
+ },
+ } satisfies CaptureResult);
+
+ const { captureWebsite } = await import("./index.js");
+ const actual = await captureWebsite(options);
+
+ expect(captureWebsiteAttemptMock).toHaveBeenNthCalledWith(
+ 2,
+ expect.anything(),
+ undefined,
+ true,
+ expect.anything(),
+ expect.anything(),
+ undefined,
+ );
+ expect(actual.warnings).toContain(
+ "The page stopped answering; retrying once with WebGL disabled",
+ );
+ });
+
+ it("does not retry a failed capture whose page never stalled", async () => {
+ captureWebsiteAttemptMock.mockReset();
+ captureWebsiteAttemptMock.mockRejectedValueOnce(closedBrowser());
+
+ const { captureWebsite } = await import("./index.js");
+ await expect(
+ captureWebsite({ url: "https://example.com", outputDir: "capture-test-stall-out-2" }),
+ ).rejects.toThrow("Connection closed");
+ expect(captureWebsiteAttemptMock).toHaveBeenCalledOnce();
+ });
+
it("a capture whose network step never answers ends at four minutes with its partial bundle", async () => {
vi.useFakeTimers();
try {
diff --git a/packages/cli/src/capture/navigateForCapture.gsap.browser.test.ts b/packages/cli/src/capture/navigateForCapture.gsap.browser.test.ts
new file mode 100644
index 0000000000..94432e2c24
--- /dev/null
+++ b/packages/cli/src/capture/navigateForCapture.gsap.browser.test.ts
@@ -0,0 +1,72 @@
+import { once } from "node:events";
+import { createServer } from "node:http";
+import type { AddressInfo } from "node:net";
+import puppeteer, { type Browser, type Page } from "puppeteer-core";
+import { afterAll, beforeAll, expect, it } from "vitest";
+import { gsapCdnDist } from "@hyperframes/core/gsap-cdn";
+import { ensureBrowser } from "../browser/manager.js";
+import { gotoWhenSent } from "./navigateForCapture.js";
+
+const PIXEL = Buffer.from(
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==",
+ "base64",
+);
+const PAGE = ` `;
+
+const server = createServer((req, res) => {
+ const pic = req.url === "/pic.png";
+ res.setHeader("Content-Type", pic ? "image/png" : "text/html");
+ res.end(pic ? PIXEL : PAGE);
+});
+let browser: Browser;
+
+beforeAll(async () => {
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const { executablePath } = await ensureBrowser();
+ browser = await puppeteer.launch({
+ executablePath,
+ headless: true,
+ args: ["--no-sandbox", "--proxy-server=http://127.0.0.1:9", "--proxy-bypass-list=127.0.0.1"],
+ });
+}, 60_000);
+
+afterAll(async () => {
+ const closed = once(server.close(), "close");
+ server.closeAllConnections();
+ await Promise.all([browser?.close(), closed]);
+});
+
+async function expectGsapAndPicture(page: Page): Promise {
+ await page.waitForFunction("document.getElementById('pic')?.complete", { timeout: 10_000 });
+ expect(await page.evaluate("typeof window.gsap")).toBe("object");
+ expect(await page.evaluate("document.getElementById('pic').naturalWidth")).toBe(1);
+}
+
+it("loads bundled GSAP and the page's own media while the CDN is unreachable", async () => {
+ const page = await browser.newPage();
+ await gotoWhenSent(page, `http://127.0.0.1:${(server.address() as AddressInfo).port}/`, 20_000);
+ await expectGsapAndPicture(page);
+ await page.close();
+});
+
+it("does the same on a page whose own requests puppeteer interception answers, as a snapshot runs it", async () => {
+ const origin = "http://in-process.invalid";
+ const page = await browser.newPage();
+ await page.setRequestInterception(true);
+ page.on("request", (request) => {
+ if (request.isInterceptResolutionHandled()) return;
+ const target = new URL(request.url());
+ if (target.origin !== origin) return void request.continue().catch(() => {});
+ const pic = target.pathname === "/pic.png";
+ void request
+ .respond({
+ status: 200,
+ contentType: pic ? "image/png" : "text/html",
+ body: pic ? PIXEL : PAGE,
+ })
+ .catch(() => {});
+ });
+ await gotoWhenSent(page, `${origin}/`, 20_000);
+ await expectGsapAndPicture(page);
+ await page.close();
+});
diff --git a/packages/cli/src/capture/navigateForCapture.test.ts b/packages/cli/src/capture/navigateForCapture.test.ts
index c9b6abf2c9..167defa0ab 100644
--- a/packages/cli/src/capture/navigateForCapture.test.ts
+++ b/packages/cli/src/capture/navigateForCapture.test.ts
@@ -1,8 +1,10 @@
+import { gsapCdnDist } from "@hyperframes/core/gsap-cdn";
import { EventEmitter } from "node:events";
import { afterEach, describe, expect, it, vi } from "vitest";
import { TimeoutError, type Page } from "puppeteer-core";
import {
gotoWhenSent,
+ explainProxyRefusal,
isNavigationTimeoutError,
navigateForCapture,
networkIdleAttemptTimeoutMs,
@@ -286,7 +288,7 @@ describe("waitForPageReady", () => {
/** A page whose goto keeps Puppeteer's contract: a non-zero timeout rejects the navigation. */
function fakeChromePage() {
const session = Object.assign(new EventEmitter(), {
- send: async () => undefined,
+ send: async (_method: string, _params?: Record) => undefined,
detach: vi.fn(async () => undefined),
});
let load: (response: unknown) => void = () => undefined;
@@ -325,6 +327,37 @@ describe("gotoWhenSent", () => {
vi.useRealTimers();
});
+ it("answers the page's request for jsDelivr GSAP from the bundled copy, and lets any other request go", async () => {
+ const chrome = fakeChromePage();
+ const sent: Array<[string, Record | undefined]> = [];
+ chrome.session.send = async (method: string, params?: Record) => {
+ sent.push([method, params]);
+ };
+ const opened = gotoWhenSent(chrome.page, "http://127.0.0.1:1/", 10_000);
+ await vi.waitFor(() => expect(sent.map(([method]) => method)).toContain("Fetch.enable"));
+ chrome.session.emit("Fetch.requestPaused", {
+ requestId: "gsap",
+ request: { url: `${gsapCdnDist()}gsap.min.js` },
+ });
+ chrome.session.emit("Fetch.requestPaused", {
+ requestId: "other",
+ request: { url: "https://cdn.example/lib.js" },
+ });
+ await vi.waitFor(() =>
+ expect(sent.map(([method]) => method)).toContain("Fetch.continueRequest"),
+ );
+ const fulfilled = sent.find(([method]) => method === "Fetch.fulfillRequest")?.[1];
+ expect(fulfilled).toMatchObject({ requestId: "gsap", responseCode: 200 });
+ expect(Buffer.from(String(fulfilled?.body), "base64").toString()).toContain("GreenSock");
+ expect(sent.find(([method]) => method === "Fetch.continueRequest")?.[1]).toEqual({
+ requestId: "other",
+ });
+ chrome.navigate();
+ chrome.send();
+ chrome.load({ status: () => 200 });
+ await opened;
+ });
+
it("gives the page its whole budget after a cold Chrome is slow to send the request", async () => {
vi.useFakeTimers();
const chrome = fakeChromePage();
@@ -465,3 +498,57 @@ describe("settleAcrossNavigation", () => {
expect(waitForNetworkIdle).not.toHaveBeenCalled();
});
});
+
+describe("a proxy that was in the way", () => {
+ const failWith = async (message: string, url = "https://shop.example.com/") => {
+ const goto = vi.fn().mockRejectedValue(new Error(message));
+ return (await navigateForCapture({ goto }, url, 120_000).then(
+ () => undefined,
+ (err: unknown) => err,
+ )) as Error;
+ };
+
+ it("that refused the tunnel to the site is named, with the code kept", async () => {
+ const failure = await failWith(
+ "net::ERR_TUNNEL_CONNECTION_FAILED at https://shop.example.com/x?q=1",
+ );
+ expect(failure.message).toBe(
+ "Your network's proxy refused the connection to shop.example.com. Ask whoever runs it to allow shop.example.com. (net::ERR_TUNNEL_CONNECTION_FAILED)",
+ );
+ expect((failure.cause as Error).message).toContain("/x?q=1");
+ });
+
+ it("that could not be reached itself is not asked to allow the site", async () => {
+ const failure = await failWith("net::ERR_PROXY_CONNECTION_FAILED at https://shop.example.com/");
+ expect(failure.message).toBe(
+ "Could not reach your network's proxy. Check the proxy address and that the proxy is running, or ask whoever runs it. (net::ERR_PROXY_CONNECTION_FAILED)",
+ );
+ expect(failure.message).not.toContain("allow");
+ });
+
+ it("names no raw address when the site's cannot be read", () => {
+ const failure = explainProxyRefusal(
+ new Error("net::ERR_TUNNEL_CONNECTION_FAILED"),
+ "not a url at all",
+ ) as Error;
+ expect(failure.message).toContain("connection to the site");
+ expect(failure.message).not.toContain("not a url");
+ });
+
+ it("is named after a networkidle2 timeout falls back too", async () => {
+ const goto = vi
+ .fn()
+ .mockRejectedValueOnce(new TimeoutError("Navigation timeout of 30000 ms exceeded"))
+ .mockRejectedValueOnce(new Error("net::ERR_TUNNEL_CONNECTION_FAILED at https://a.example/"));
+ await expect(navigateForCapture({ goto }, "https://a.example/", 120_000)).rejects.toThrow(
+ /proxy refused the connection to a\.example/,
+ );
+ });
+
+ it("leaves every other failure as it was", async () => {
+ const name = new Error("net::ERR_NAME_NOT_RESOLVED at https://nope.example/");
+ expect(explainProxyRefusal(name, "https://nope.example/")).toBe(name);
+ const goto = vi.fn().mockRejectedValue(name);
+ await expect(navigateForCapture({ goto }, "https://nope.example/", 120_000)).rejects.toBe(name);
+ });
+});
diff --git a/packages/cli/src/capture/navigateForCapture.ts b/packages/cli/src/capture/navigateForCapture.ts
index 4d61d10c4b..318be38e4b 100644
--- a/packages/cli/src/capture/navigateForCapture.ts
+++ b/packages/cli/src/capture/navigateForCapture.ts
@@ -1,4 +1,6 @@
import type { CDPSession, HTTPResponse, Page } from "puppeteer-core";
+import { gsapCdnDist } from "@hyperframes/core/gsap-cdn";
+import { bundledGsapFor } from "../server/gsapVendor.js";
import {
isDegradableEvaluateTimeoutError,
isNavigationTimeoutError,
@@ -9,6 +11,22 @@ export { isNavigationTimeoutError };
export const NETWORK_IDLE_ATTEMPT_MS = 30_000;
+const PROXY_FAILURES = {
+ "net::ERR_TUNNEL_CONNECTION_FAILED": (host: string) =>
+ `Your network's proxy refused the connection to ${host}. Ask whoever runs it to allow ${host}.`,
+ "net::ERR_PROXY_CONNECTION_FAILED": () =>
+ "Could not reach your network's proxy. Check the proxy address and that the proxy is running, or ask whoever runs it.",
+} as const;
+const PROXY_FAILURE = new RegExp(Object.keys(PROXY_FAILURES).join("|"));
+
+export function explainProxyRefusal(err: unknown, url: string): unknown {
+ const said = err instanceof Error ? err.message : String(err);
+ const code = PROXY_FAILURE.exec(said)?.[0] as keyof typeof PROXY_FAILURES | undefined;
+ if (!code) return err;
+ const host = URL.canParse(url) ? new URL(url).host : "the site";
+ return new Error(`${PROXY_FAILURES[code](host)} (${code})`, { cause: err });
+}
+
export type CaptureGotoWaitUntil = "networkidle2" | "domcontentloaded";
export interface CaptureGotoOptions {
@@ -50,15 +68,16 @@ export async function navigateForCapture(
};
} catch (err) {
if (!isNavigationTimeoutError(err) || networkIdleTimeoutMs >= totalTimeoutMs) {
- throw err;
+ throw explainProxyRefusal(err, url);
}
}
const fallbackTimeoutMs = totalTimeoutMs - networkIdleTimeoutMs;
- const response = await page.goto(url, {
- waitUntil: "domcontentloaded",
- timeout: fallbackTimeoutMs,
- });
+ const response = await page
+ .goto(url, { waitUntil: "domcontentloaded", timeout: fallbackTimeoutMs })
+ .catch((err: unknown) => {
+ throw explainProxyRefusal(err, url);
+ });
return {
response,
waitUntil: "domcontentloaded",
@@ -155,6 +174,28 @@ const SENT_OR_ANSWERED_WITHOUT_NETWORK = [
"Network.responseReceived",
] as const;
+async function serveBundledGsap(cdp: CDPSession): Promise {
+ cdp.on("Fetch.requestPaused", ({ requestId, request }) => {
+ const bundled = bundledGsapFor(request.url);
+ void (
+ bundled
+ ? cdp.send("Fetch.fulfillRequest", {
+ requestId,
+ responseCode: 200,
+ responseHeaders: [
+ { name: "Content-Type", value: bundled.contentType },
+ { name: "Access-Control-Allow-Origin", value: "*" },
+ ],
+ body: bundled.body.toString("base64"),
+ })
+ : cdp.send("Fetch.continueRequest", { requestId })
+ ).catch(() => undefined);
+ });
+ await cdp.send("Fetch.enable", {
+ patterns: [{ urlPattern: `${gsapCdnDist()}*`, requestStage: "Request" }],
+ });
+}
+
export async function gotoWhenSent(
page: Page,
url: string,
@@ -165,6 +206,7 @@ export async function gotoWhenSent(
const cdp = await page.createCDPSession();
try {
await cdp.send("Network.enable");
+ await serveBundledGsap(cdp);
const sent = documentRequestSent(cdp);
const unfinished = unfinishedPageLoadRequests(cdp);
const navigation = page.goto(url, { waitUntil: "domcontentloaded", timeout: 0 });
diff --git a/packages/cli/src/capture/partialCapture.ts b/packages/cli/src/capture/partialCapture.ts
index 0e98a5fb4a..b34c6fe4f3 100644
--- a/packages/cli/src/capture/partialCapture.ts
+++ b/packages/cli/src/capture/partialCapture.ts
@@ -27,6 +27,7 @@ export interface PartialCaptureState {
assets: CaptureResult["assets"];
dropped: CaptureResult["dropped"];
warnings: string[];
+ webglStalled: boolean;
}
export function createPartialCaptureState(opts: CaptureOptions): PartialCaptureState {
@@ -65,6 +66,7 @@ export function createPartialCaptureState(opts: CaptureOptions): PartialCaptureS
assets: [],
dropped: noDrops(),
warnings: [],
+ webglStalled: false,
};
}
diff --git a/packages/cli/src/capture/publicNetwork.test.ts b/packages/cli/src/capture/publicNetwork.test.ts
index c456e42e93..96beaa487a 100644
--- a/packages/cli/src/capture/publicNetwork.test.ts
+++ b/packages/cli/src/capture/publicNetwork.test.ts
@@ -47,6 +47,7 @@ describe("public address policy", () => {
"169.254.169.254",
"100.64.0.1",
"0.1.2.3",
+ "192.0.0.8",
"192.0.0.9",
"192.0.2.1",
"198.18.0.1",
@@ -58,6 +59,14 @@ describe("public address policy", () => {
"::ffff:8.8.8.8",
"8.8.8.999",
])("rejects %s", (ip) => expect(isPublicIPv4(ip)).toBe(false));
+ it.each(["192.0.66.108", "192.0.1.1", "192.0.3.1"])(
+ "accepts %s: only 192.0.0.0/24 and 192.0.2.0/24 are reserved",
+ (ip) => expect(isPublicIPv4(ip)).toBe(true),
+ );
+ it("resolves a host served from 192.0/16 public space (nasa.gov on WordPress VIP)", async () => {
+ mocks.resolve4.mockResolvedValue(["192.0.66.108"]);
+ await expect(resolvePublicAddress("www.nasa.gov")).resolves.toBe("192.0.66.108");
+ });
it("accepts public literals without DNS", async () => {
await expect(resolvePublicAddress("8.8.8.8")).resolves.toBe("8.8.8.8");
expect(mocks.resolve4).not.toHaveBeenCalled();
diff --git a/packages/cli/src/capture/publicNetwork.ts b/packages/cli/src/capture/publicNetwork.ts
index 2641db103b..8824e356e5 100644
--- a/packages/cli/src/capture/publicNetwork.ts
+++ b/packages/cli/src/capture/publicNetwork.ts
@@ -5,6 +5,7 @@ import { isIP, type Socket } from "node:net";
import { request as httpRequest, type IncomingMessage, type ClientRequest } from "node:http";
import { request as httpsRequest, type RequestOptions } from "node:https";
import { connect as tlsConnect } from "node:tls";
+import { isBlockedNetworkHost } from "@hyperframes/engine/network-policy";
import {
captureUpstreamProxy,
connectAuthority,
@@ -15,36 +16,9 @@ import {
const DNS_TIMEOUT_MS = 10_000;
const CARES_TIMEOUT_MS = 5_000;
-function ipv4Number(address: string): number {
- return address.split(".").reduce((value, octet) => value * 256 + Number(octet), 0);
-}
-
-// Conservatively exclude special-use networks, including all of 192.0/16.
-const NON_PUBLIC_IPV4: ReadonlyArray = [
- ["0.0.0.0", 8],
- ["10.0.0.0", 8],
- ["100.64.0.0", 10],
- ["127.0.0.0", 8],
- ["169.254.0.0", 16],
- ["172.16.0.0", 12],
- ["192.0.0.0", 16],
- ["192.88.99.0", 24],
- ["192.168.0.0", 16],
- ["198.18.0.0", 15],
- ["198.51.100.0", 24],
- ["203.0.113.0", 24],
- ["224.0.0.0", 3],
-];
-const NON_PUBLIC_RANGES = NON_PUBLIC_IPV4.map(([network, prefix]) => ({
- start: ipv4Number(network),
- end: ipv4Number(network) + 2 ** (32 - prefix),
-}));
-
-/** Conservative IPv4-only policy: special-use addresses fail closed. */
+/** IPv4-only (IPv6 fails closed), on the engine's special-use list so capture and downloads agree. */
export function isPublicIPv4(address: string): boolean {
- if (isIP(address) !== 4) return false;
- const value = ipv4Number(address);
- return !NON_PUBLIC_RANGES.some(({ start, end }) => value >= start && value < end);
+ return isIP(address) === 4 && !isBlockedNetworkHost(address);
}
export function assertPublicHostname(hostname: string): string {
diff --git a/packages/cli/src/capture/scaffolding.ts b/packages/cli/src/capture/scaffolding.ts
index f722459842..32786264ba 100644
--- a/packages/cli/src/capture/scaffolding.ts
+++ b/packages/cli/src/capture/scaffolding.ts
@@ -8,7 +8,7 @@
import { captureSiteName } from "./localPage.js";
import { existsSync, readFileSync } from "node:fs";
import { join, resolve } from "node:path";
-import { applyDotEnv, CAPTURE_ENV_KEYS } from "../utils/dotEnv.js";
+import { applyDotEnv, PROJECT_ENV_KEYS } from "../utils/dotEnv.js";
import { writeNewFileSync } from "../utils/writeNewFile.js";
import type { CatalogedAsset } from "./assetCataloger.js";
import type { CaptureResult, DesignTokens } from "./types.js";
@@ -24,7 +24,7 @@ export function loadEnvFile(startDir: string): void {
for (let i = 0; i < 5; i++) {
const envPath = resolve(dir, ".env");
try {
- applyDotEnv(readFileSync(envPath, "utf-8"), process.env, CAPTURE_ENV_KEYS);
+ applyDotEnv(readFileSync(envPath, "utf-8"), process.env, PROJECT_ENV_KEYS);
break;
} catch {
dir = resolve(dir, "..");
diff --git a/packages/cli/src/capture/webglStallWatch.test.ts b/packages/cli/src/capture/webglStallWatch.test.ts
new file mode 100644
index 0000000000..9bced3bbb0
--- /dev/null
+++ b/packages/cli/src/capture/webglStallWatch.test.ts
@@ -0,0 +1,48 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { CDPSession } from "puppeteer-core";
+import { watchWebglStall } from "./webglStallWatch.js";
+
+/** A page that answers `Runtime.evaluate` while `silent` is false. */
+function fakePage() {
+ const state = { silent: false };
+ const cdp = {
+ send: vi.fn(async (method: string) => {
+ if (method === "Runtime.evaluate" && state.silent) return new Promise(() => {});
+ return {};
+ }),
+ } as unknown as CDPSession;
+ return { cdp, state };
+}
+
+describe("watchWebglStall", () => {
+ afterEach(() => vi.useRealTimers());
+
+ it("calls onStall once when a page stops answering", async () => {
+ vi.useFakeTimers();
+ const page = fakePage();
+ const onStall = vi.fn();
+ watchWebglStall(page.cdp, onStall);
+ page.state.silent = true;
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(onStall).toHaveBeenCalledOnce();
+ });
+
+ it("leaves a page that keeps answering alone", async () => {
+ vi.useFakeTimers();
+ const onStall = vi.fn();
+ watchWebglStall(fakePage().cdp, onStall);
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(onStall).not.toHaveBeenCalled();
+ });
+
+ it("stops probing once stopped", async () => {
+ vi.useFakeTimers();
+ const page = fakePage();
+ const onStall = vi.fn();
+ const watch = watchWebglStall(page.cdp, onStall);
+ watch.stop();
+ page.state.silent = true;
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(onStall).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/cli/src/capture/webglStallWatch.ts b/packages/cli/src/capture/webglStallWatch.ts
new file mode 100644
index 0000000000..0552c1a04c
--- /dev/null
+++ b/packages/cli/src/capture/webglStallWatch.ts
@@ -0,0 +1,38 @@
+import type { CDPSession } from "puppeteer-core";
+
+const PROBE_EVERY_MS = 4_000;
+const PROBE_TIMEOUT_MS = 8_000;
+const MISSES = 2;
+
+/** Calls `onStall` once when two probes in a row get no answer from the page; an error still counts as an answer. */
+export function watchWebglStall(
+ cdp: CDPSession,
+ onStall: () => void,
+ timing = { everyMs: PROBE_EVERY_MS, timeoutMs: PROBE_TIMEOUT_MS },
+): { stop(): void } {
+ let timer: ReturnType | undefined;
+ let stopped = false;
+ let misses = 0;
+ const probe = async () => {
+ const answered = await Promise.race([
+ cdp.send("Runtime.evaluate", { expression: "1" }).then(
+ () => true,
+ () => true,
+ ),
+ new Promise((resolve) => setTimeout(() => resolve(false), timing.timeoutMs).unref()),
+ ]);
+ if (stopped) return;
+ misses = answered ? 0 : misses + 1;
+ if (misses >= MISSES) return onStall();
+ timer = setTimeout(probe, timing.everyMs);
+ timer.unref();
+ };
+ timer = setTimeout(probe, timing.everyMs);
+ timer.unref();
+ return {
+ stop() {
+ stopped = true;
+ clearTimeout(timer);
+ },
+ };
+}
diff --git a/packages/cli/src/cli.agentMode.test.ts b/packages/cli/src/cli.agentMode.test.ts
index 4624d3a8ab..e58b4536b1 100644
--- a/packages/cli/src/cli.agentMode.test.ts
+++ b/packages/cli/src/cli.agentMode.test.ts
@@ -286,6 +286,12 @@ describe("agent-mode contract", () => {
["cloud rendr", "Did you mean 'hyperframes cloud render'?"],
["help rendr", "Did you mean 'hyperframes render'?"],
["help cloud rendr", "Did you mean 'hyperframes cloud render'?"],
+ ["search crossfade", "Did you mean 'hyperframes catalog'?"],
+ ["install crossfade", "Did you mean 'hyperframes add'?"],
+ ["find crossfade", "Did you mean 'hyperframes catalog'?"],
+ ["list", "Did you mean 'hyperframes catalog'?"],
+ ["browse", "Did you mean 'hyperframes catalog'?"],
+ ["registry", "Did you mean 'hyperframes catalog'?"],
])(
"unknown command `%s` suggests the closest one, usage on stderr, exit 2",
async (args, hint) => {
diff --git a/packages/cli/src/cli.commands.test.ts b/packages/cli/src/cli.commands.test.ts
index f14bc1c5b0..2676bc1955 100644
--- a/packages/cli/src/cli.commands.test.ts
+++ b/packages/cli/src/cli.commands.test.ts
@@ -19,6 +19,7 @@ function commandLoaderBlock(): string {
// Vite cannot resolve a template-string import, so each listed top-level command is named here.
const LIST_COMMANDS: Record Promise<{ default: unknown }>> = {
+ add: () => import("./commands/add.js"),
audio: () => import("./commands/audio.js"),
catalog: () => import("./commands/catalog.js"),
compare: () => import("./commands/compare.js"),
diff --git a/packages/cli/src/cli.dotEnv.test.ts b/packages/cli/src/cli.dotEnv.test.ts
index ecccb09103..f4af3198ca 100644
--- a/packages/cli/src/cli.dotEnv.test.ts
+++ b/packages/cli/src/cli.dotEnv.test.ts
@@ -44,8 +44,8 @@ it.each(
[
["capture", false, undefined, "fixture-key", undefined],
["capture", true, undefined, undefined, undefined],
- ["init", false, process.execPath, "fixture-key", undefined],
- ["init", true, process.execPath, "fixture-key", undefined],
+ ["init", false, undefined, "fixture-key", undefined],
+ ["init", true, undefined, "fixture-key", undefined],
["capture", false, process.execPath, "fixture-key", process.execPath],
] as const
).flatMap((test) =>
@@ -84,6 +84,6 @@ it.each(
mockTelemetry();
process.argv = ["node", "cli.ts", ...prefix, command];
await import("./cli.js");
- expect(observed).toEqual([browser, command === "capture" ? undefined : "--no-warnings", key]);
+ expect(observed).toEqual([browser, undefined, key]);
},
);
diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts
index 0c114392f3..a2b784f690 100644
--- a/packages/cli/src/cli.ts
+++ b/packages/cli/src/cli.ts
@@ -65,22 +65,12 @@ if (rootVersionRequested) {
process.exit(0);
}
-// Capture treats CWD as project data too: its early loader must use the same
-// allowlist/opt-out as output ancestors, before browser selection can observe it.
-const { applyDotEnv, CAPTURE_ENV_KEYS } = await import("./utils/dotEnv.js");
+// The working directory is project data: load only the settings a project `.env` may supply,
+// before browser selection can observe the environment.
+const { loadProjectDotEnv } = await import("./utils/dotEnv.js");
const captureEnv = argv[commandWordIndex(argv)] === "capture";
if (!captureEnv || process.env.HYPERFRAMES_NO_CAPTURE_DOTENV !== "1") {
- try {
- const { readFileSync } = await import("node:fs");
- const envPath = resolve(process.cwd(), ".env");
- applyDotEnv(
- readFileSync(envPath, "utf-8"),
- process.env,
- captureEnv ? CAPTURE_ENV_KEYS : undefined,
- );
- } catch {
- /* .env not present — fine, env vars may be set another way */
- }
+ loadProjectDotEnv(process.cwd(), process.env, (line) => console.error(line));
}
// ── Lazy imports ────────────────────────────────────────────────────────────
@@ -98,7 +88,7 @@ import {
markCommandDelivered,
} from "./utils/render-success-state.js";
import { resolveCommandUsage, type ResolvedCommandUsage } from "./utils/commandUsageResolution.js";
-import { closestMatch } from "./utils/didYouMean.js";
+import { closestMatch, synonymMatch } from "./utils/didYouMean.js";
import { jsonErrorBody, watchOutput, writeJsonFailure } from "./utils/jsonError.js";
import { isDevMode } from "./utils/env.js";
import {
@@ -107,6 +97,7 @@ import {
CliUsageError,
USAGE_EXIT_CODE,
consumeCommandResult,
+ endProcess,
outputWritten,
registerRootExitCodeSanitizer,
registerRootExitRequester,
@@ -185,6 +176,9 @@ const commandLoaders = {
import("./commands/media-treatment.js").then((m) => m.mediaTreatmentCommand),
"grade-compare": () => import("./commands/grade-compare.js").then((m) => m.default),
compare: () => import("./commands/compare.js").then((m) => m.default),
+ diff: () => import("./commands/diff.js").then((m) => m.default),
+ measure: () => import("./commands/measure.js").then((m) => m.default),
+ billing: () => import("./commands/billing.js").then((m) => m.default),
capture: () => import("./commands/capture.js").then((m) => m.default),
lambda: () => import("./commands/lambda.js").then((m) => m.default),
cloudrun: () => import("./commands/cloudrun.js").then((m) => m.default),
@@ -380,7 +374,13 @@ registerRootExitRequester((exitCode) => {
presented: true,
}).finally(async () => {
await outputWritten();
- process.exit(exitCode);
+ endProcess(exitCode, {
+ exit: (code) => process.exit(code),
+ setExitCode: (code) => {
+ process.exitCode = code;
+ },
+ later: setTimeout,
+ });
});
});
@@ -542,7 +542,10 @@ async function unknownCommandError(requested: ResolvedCommandUsage): Promise {
});
});
-describe("add command run() — extra positional arguments", () => {
+describe("add command run() — several names", () => {
let dir: string;
- let errorSpy: ReturnType;
beforeEach(() => {
dir = tmp();
- errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ writeRegistryConfig(dir);
+ mockFetch();
});
afterEach(() => {
- errorSpy.mockRestore();
+ vi.restoreAllMocks();
vi.unstubAllGlobals();
rmSync(dir, { recursive: true, force: true });
});
@@ -545,22 +544,50 @@ describe("add command run() — extra positional arguments", () => {
await runCittyCommand(cmd, { rawArgs });
}
- it("rejects `add a --dir b c` through the CLI wrapper, before any registry call", async () => {
- const fetchSpy = vi.fn();
- vi.stubGlobal("fetch", fetchSpy);
+ it("installs every name in one call and reports them together", async () => {
+ const log = vi.spyOn(console, "log").mockImplementation(() => {});
- await expect(runWrapped(["a", "--dir", dir, "b", "c"])).rejects.toThrow(CliUsageError);
- expect(fetchSpy).not.toHaveBeenCalled();
- expect(errorSpy.mock.calls.flat().join(" ")).toContain(
- "Unexpected extra arguments for hyperframes add: b, c",
- );
- expect(errorSpy.mock.calls.flat().join(" ")).toContain("Run add once per item");
+ await runWrapped(["my-block", "--dir", dir, "deprecated-block", "--no-clipboard", "--json"]);
+
+ expect(JSON.parse(String(log.mock.calls[0]?.[0]))).toEqual({
+ ok: true,
+ installed: ["my-block", "deprecated-block"],
+ warnings: expect.any(Array),
+ errors: [],
+ });
+ expect(existsSync(join(dir, "compositions", "my-block.html"))).toBe(true);
+ expect(existsSync(join(dir, "compositions", "deprecated-block.html"))).toBe(true);
});
- it("does not fire on a normal single-item invocation", async () => {
- mockFetch();
- writeRegistryConfig(dir);
+ it("keeps the installs that worked when one name is unknown, and fails the call", async () => {
+ const log = vi.spyOn(console, "log").mockImplementation(() => {});
+ await expect(
+ runWrapped(["my-block", "no-such-block", "--dir", dir, "--no-clipboard", "--json"]),
+ ).rejects.toMatchObject({ result: { exitCode: 1 } });
+
+ const out = JSON.parse(String(log.mock.calls[0]?.[0]));
+ expect(out).toMatchObject({ ok: false, installed: ["my-block"] });
+ expect(out.errors).toEqual([{ name: "no-such-block", error: expect.any(String) }]);
+ expect(existsSync(join(dir, "compositions", "my-block.html"))).toBe(true);
+ });
+
+ it("says --dir is the project root when it does not exist", async () => {
+ const log = vi.spyOn(console, "log").mockImplementation(() => {});
+ const missing = join(dir, "compositions", "new-folder");
+
+ await expect(
+ runWrapped(["my-block", "--dir", missing, "--no-clipboard", "--json"]),
+ ).rejects.toMatchObject({ result: { exitCode: 1 } });
+
+ const out = JSON.parse(String(log.mock.calls[0]?.[0]));
+ expect(out.error.message).toContain(`Project folder not found: ${missing}`);
+ expect(out.error.message).toContain("--dir is the project root");
+ expect(out.error.message).toContain("hyperframes init");
+ expect(existsSync(missing)).toBe(false);
+ });
+
+ it("still installs a single name the way it did", async () => {
await expect(
runWrapped(["my-block", "--dir", dir, "--no-clipboard", "--json"]),
).resolves.toBeUndefined();
diff --git a/packages/cli/src/commands/add.ts b/packages/cli/src/commands/add.ts
index 84a698620e..a995239e67 100644
--- a/packages/cli/src/commands/add.ts
+++ b/packages/cli/src/commands/add.ts
@@ -148,19 +148,70 @@ export function buildSnippet(
return "";
}
+function installJson(results: RunAddResult[], errors: Array<{ name: string; error: string }>) {
+ return {
+ ok: errors.length === 0,
+ installed: results.map((r) => r.name),
+ warnings: results.flatMap((r) => r.warnings.map((w) => `${r.name}: ${w}`)),
+ errors,
+ };
+}
+
/** `add --json` output: successful installs and each item's warnings or failure. */
export function tagAddJson(
tag: string,
results: RunAddResult[],
errors: Array<{ name: string; error: string }> = [],
) {
- return {
- ok: errors.length === 0,
- tag,
- installed: results.map((r) => r.name),
- warnings: results.flatMap((r) => r.warnings.map((w) => `${r.name}: ${w}`)),
- errors,
- };
+ return { ...installJson(results, errors), tag };
+}
+
+export function severalAddJson(
+ results: RunAddResult[],
+ errors: Array<{ name: string; error: string }> = [],
+) {
+ return installJson(results, errors);
+}
+
+interface InstallContext {
+ projectDir: string;
+ force: boolean | undefined;
+ vars: string | undefined;
+ json: boolean;
+}
+
+type InstallOutcome = { result: RunAddResult } | { name: string; error: string };
+
+async function installOne(name: string, context: InstallContext): Promise {
+ try {
+ const result = await runAdd({
+ name,
+ projectDir: context.projectDir,
+ skipClipboard: true,
+ force: context.force,
+ vars: context.vars,
+ });
+ if (!context.json) {
+ for (const warning of result.warnings) console.log(` ${c.warn("Warning:")} ${warning}`);
+ console.log(` ${c.success("✓")} ${result.name}`);
+ }
+ return { result };
+ } catch (err) {
+ const reason = err instanceof Error ? err.message : String(err);
+ if (!context.json) console.log(` ${c.error("✗")} ${name} (skipped: ${reason})`);
+ return { name, error: reason };
+ }
+}
+
+async function installEach(names: readonly string[], context: InstallContext) {
+ const results: RunAddResult[] = [];
+ const errors: Array<{ name: string; error: string }> = [];
+ for (const name of names) {
+ const outcome = await installOne(name, context);
+ if ("result" in outcome) results.push(outcome.result);
+ else errors.push(outcome);
+ }
+ return { results, errors };
}
/** `--vars` is JSON, a file or `-`; a malformed one is an error, not a snippet that drops the values. */
@@ -458,7 +509,8 @@ export default defineCommand({
type: "positional",
description:
"Registry item name or tag. Single items install directly (e.g. shader-wipe). " +
- "If the name matches a tag instead, all blocks with that tag are installed (e.g. html-in-canvas, captions).",
+ "If the name matches a tag instead, all blocks with that tag are installed (e.g. html-in-canvas, captions). " +
+ "Give several names to install each of them in one call.",
required: true,
},
dir: {
@@ -500,8 +552,41 @@ export default defineCommand({
const json = args.json === true;
const skipClipboard = args.clipboard === false;
+ if (!existsSync(projectDir)) {
+ failCaught(
+ new Error(
+ `Project folder not found: ${projectDir}. --dir is the project root, not where the block lands (that is its compositions/ folder), and it must already exist. Create one with \`hyperframes init \`.`,
+ ),
+ json,
+ c.error,
+ );
+ }
+
const hasConfigBefore = existsSync(projectConfigPath(projectDir));
+ const names = Array.isArray(args._) && args._.length > 1 ? args._.map(String) : [args.name];
+ if (names.length > 1) {
+ if (!json) {
+ console.log("");
+ console.log(`${c.accent("◆")} Installing ${c.accent(String(names.length))} items`);
+ }
+ const { results, errors } = await installEach(names, {
+ projectDir,
+ force: args.force,
+ vars: args.vars,
+ json,
+ });
+ if (json) {
+ console.log(JSON.stringify(severalAddJson(results, errors)));
+ } else {
+ console.log("");
+ const summary = `Installed ${results.length}/${names.length} items`;
+ console.log(`${errors.length > 0 ? c.error("✗") : c.success("✓")} ${summary}`);
+ }
+ if (errors.length > 0) failCommand();
+ return;
+ }
+
// Try single item first. If it fails, check if the name matches a tag.
try {
const result = await runAdd({
@@ -586,28 +671,10 @@ export default defineCommand({
);
}
- const results: RunAddResult[] = [];
- const errors: Array<{ name: string; error: string }> = [];
- for (const item of items) {
- try {
- const result = await runAdd({
- name: item.name,
- projectDir,
- skipClipboard: true,
- force: args.force,
- vars: args.vars,
- });
- results.push(result);
- for (const warning of result.warnings) {
- if (!json) console.log(` ${c.warn("Warning:")} ${warning}`);
- }
- if (!json) console.log(` ${c.success("✓")} ${result.name}`);
- } catch (err) {
- const reason = err instanceof Error ? err.message : String(err);
- errors.push({ name: item.name, error: reason });
- if (!json) console.log(` ${c.error("✗")} ${item.name} (skipped: ${reason})`);
- }
- }
+ const { results, errors } = await installEach(
+ items.map((item) => item.name),
+ { projectDir, force: args.force, vars: args.vars, json },
+ );
if (json) {
console.log(JSON.stringify(tagAddJson(args.name, results, errors)));
diff --git a/packages/cli/src/commands/auth.ts b/packages/cli/src/commands/auth.ts
index 9424eb5184..272553a278 100644
--- a/packages/cli/src/commands/auth.ts
+++ b/packages/cli/src/commands/auth.ts
@@ -28,8 +28,8 @@ export const examples: Example[] = [
const HELP = `
${c.bold("hyperframes auth")} ${c.dim(" [args]")}
-Manage HeyGen credentials. Credentials live in
-${c.accent("~/.heygen/credentials")} and are shared with heygen-cli.
+Manage HyperFrames credentials. Credentials live in
+${c.accent("~/.hyperframes/credentials")}, independently of heygen-cli.
${c.bold("SUBCOMMANDS:")}
${c.accent("login")} ${c.dim("Sign in via browser, --device for SSH, or --api-key for a long-lived key.")}
@@ -42,7 +42,8 @@ ${c.bold("ENV VARS:")}
${c.accent("HYPERFRAMES_API_KEY")} Alias for HEYGEN_API_KEY.
${c.accent("HEYGEN_ACCESS_TOKEN")} OAuth token from a host app; used after the API keys, never refreshed or saved.
${c.accent("HEYGEN_API_URL")} Override the API base URL (default https://api.heygen.com).
- ${c.accent("HEYGEN_CONFIG_DIR")} Override the credentials directory (default ~/.heygen).
+ ${c.accent("HYPERFRAMES_ENV")} prod (default) or dev; selects OAuth, API and plans-page hosts together.
+ ${c.accent("HYPERFRAMES_CONFIG_DIR")} Override the credentials directory (default ~/.hyperframes).
${c.accent("HYPERFRAMES_OAUTH_CLIENT_ID")} Override the OAuth client_id (for dev/test).
${c.accent("HYPERFRAMES_OAUTH_DEVICE_URL")} Override the RFC 8628 device endpoint (for dev/test).
`;
diff --git a/packages/cli/src/commands/auth/login.test.ts b/packages/cli/src/commands/auth/login.test.ts
index 2944040a76..8a1d2e8104 100644
--- a/packages/cli/src/commands/auth/login.test.ts
+++ b/packages/cli/src/commands/auth/login.test.ts
@@ -5,6 +5,9 @@ import { readStore, writeStore } from "../../auth/store.js";
import { setupTempAuthEnv, type EnvFixture } from "../../auth/_test-utils.js";
import { CliRuntimeError } from "../../utils/commandResult.js";
+// heygenUserId("alice"): the sha256-derived UUID the web app and Desktop also use.
+const ALICE_USER_ID = "2bd806c9-7f0e-50af-9a1f-c3328fa763a9";
+
// Mock only AuthClient — keep the real store/resolver so the test
// exercises the actual on-disk rollback / persistence behavior.
// `verifyState` controls what `getCurrentUser` returns per test:
@@ -106,6 +109,8 @@ describe("auth login", () => {
"REMOTE_CONTAINERS",
"GITPOD_WORKSPACE_ID",
"container",
+ "CLAUDECODE",
+ "CLAUDE_CODE_ENTRYPOINT",
].map((key) => [key, process.env[key]]),
);
for (const key of Object.keys(runtimeEnv)) delete process.env[key];
@@ -127,6 +132,7 @@ describe("auth login", () => {
for (const token of Object.keys(usersByToken)) delete usersByToken[token];
for (const fn of Object.values(telemetry)) fn.mockClear();
for (const fn of Object.values(deviceAuth)) fn.mockClear();
+ for (const fn of Object.values(browserAuth)) fn.mockClear();
vi.spyOn(console, "log").mockImplementation(() => {});
vi.spyOn(console, "error").mockImplementation(() => {});
});
@@ -245,18 +251,23 @@ describe("auth login", () => {
expect(onDisk.future_credential).toEqual({ token: "owned_by_other_cli" });
});
- it("attributes a successful login to the account email", async () => {
- verifyState.user = { email: "alice@example.com", username: "alice" };
+ it("attributes a successful login to the username's HyperFrames user id", async () => {
+ verifyState.user = { email: "Alice@Example.com", username: "alice" };
await runLogin("hg_goodkey456");
- expect(telemetry.identifyUser).toHaveBeenCalledWith("alice@example.com");
- expect(telemetry.trackAuthLoginCompleted).toHaveBeenCalledWith("api_key", "alice@example.com");
+ expect(telemetry.identifyUser).toHaveBeenCalledWith(ALICE_USER_ID, {
+ email: "alice@example.com",
+ heygen_username: "alice",
+ });
+ expect(telemetry.trackAuthLoginCompleted).toHaveBeenCalledWith("api_key", ALICE_USER_ID);
});
- it("falls back to username when the account has no email", async () => {
- verifyState.user = { username: "alice" };
+ it("falls back to the email when the account has no username", async () => {
+ verifyState.user = { email: "alice@example.com" };
await runLogin("hg_goodkey456");
- expect(telemetry.identifyUser).toHaveBeenCalledWith("alice");
- expect(telemetry.trackAuthLoginCompleted).toHaveBeenCalledWith("api_key", "alice");
+ expect(telemetry.identifyUser).toHaveBeenCalledWith("alice@example.com", {
+ email: "alice@example.com",
+ });
+ expect(telemetry.trackAuthLoginCompleted).toHaveBeenCalledWith("api_key", "alice@example.com");
});
it("does not identify when the identity probe returns nothing", async () => {
@@ -309,6 +320,21 @@ describe("auth login", () => {
expect(deviceAuth.start).not.toHaveBeenCalled();
});
+ it("lets a coding agent on this machine open the browser sign-in without a terminal", async () => {
+ process.env["CLAUDECODE"] = "1";
+ Object.defineProperty(process.stdout, "isTTY", { configurable: true, value: undefined });
+ await runCommand({});
+ expect(browserAuth.start).toHaveBeenCalledOnce();
+ });
+
+ it("keeps a coding agent in CI off the browser sign-in", async () => {
+ process.env["CLAUDECODE"] = "1";
+ process.env["CI"] = "true";
+ Object.defineProperty(process.stdout, "isTTY", { configurable: true, value: undefined });
+ await expect(runCommand({})).rejects.toThrow(/Invalid command usage/);
+ expect(browserAuth.start).not.toHaveBeenCalled();
+ });
+
it("opens verification_uri_complete without asking the user to re-enter the code", async () => {
deviceChallenge.verificationUriComplete =
"https://app.heygen.com/oauth/device?user_code=ABCD-2345";
diff --git a/packages/cli/src/commands/auth/login.ts b/packages/cli/src/commands/auth/login.ts
index 89bed70997..68097c1179 100644
--- a/packages/cli/src/commands/auth/login.ts
+++ b/packages/cli/src/commands/auth/login.ts
@@ -1,12 +1,13 @@
import { failCommand, failUsage } from "../../utils/commandResult.js";
-import { envFlagEnabled, isAttendedTerminal } from "../../utils/attendedTerminal.js";
+import { envFlagEnabled, isAttendedTerminal, isCI } from "../../utils/attendedTerminal.js";
+import { isAgentDriven } from "../../telemetry/agent_runtime.js";
/**
* `hyperframes auth login` — sign in to HeyGen.
*
* Default: OAuth 2.0 + PKCE via a loopback callback. The CLI opens
* the user's browser, captures the authorization code on an
* ephemeral 127.0.0.1 port, exchanges it for tokens, and persists
- * them to `~/.heygen/credentials`.
+ * them to `~/.hyperframes/credentials`.
*
* `--api-key`: opts into the legacy long-lived API-key path.
*
@@ -47,6 +48,7 @@ import {
type StoredUserInfo,
type UserInfo,
} from "../../auth/index.js";
+import { telemetryIdentity } from "../../auth/telemetryIdentity.js";
import { c } from "../../ui/colors.js";
const STDIN_TIMEOUT_MS = 30_000;
@@ -113,10 +115,14 @@ function isRemoteOrHeadless(): boolean {
process.env["BROWSER"] === "none" ||
process.env["HF_NO_BROWSER"] === "1" ||
remoteEnvironment ||
- process.stdout.isTTY !== true,
+ (process.stdout.isTTY !== true && !agentShellOnThisMachine()),
);
}
+function agentShellOnThisMachine(): boolean {
+ return !isCI() && isAgentDriven();
+}
+
function assertAttendedDeviceFlow(): void {
if (!isAttendedTerminal()) {
console.error(
@@ -178,9 +184,9 @@ async function runDeviceLogin(): Promise {
failCommand();
}
- const id = identityKey(user);
- if (id) identifyUser(id);
- trackAuthLoginCompleted("device", id);
+ const who = telemetryIdentity(user);
+ if (who) identifyUser(who.distinctId, who.traits);
+ trackAuthLoginCompleted("device", who?.distinctId);
const identity = userDisplayName(toStoredUserInfo(user)) ?? "(unknown user)";
console.log(c.success(`✓ Signed in as ${identity}.`));
}
@@ -250,9 +256,9 @@ async function reportIdentity(credential: ReturnType):
// Attribute this install to the signed-in account (and stitch its prior
// anonymous usage) before recording completion, so the completed event
// carries the identity. Both no-op under the telemetry opt-out.
- const id = identityKey(user);
- if (id) identifyUser(id);
- trackAuthLoginCompleted("oauth", id);
+ const who = telemetryIdentity(user);
+ if (who) identifyUser(who.distinctId, who.traits);
+ trackAuthLoginCompleted("oauth", who?.distinctId);
const identity = userDisplayName(toStoredUserInfo(user)) ?? "(unknown user)";
console.log(c.success(`✓ Signed in as ${identity}.`));
} catch (err) {
@@ -269,20 +275,6 @@ async function reportIdentity(credential: ReturnType):
}
}
-/**
- * The stable key we associate this install with in telemetry after sign-in.
- * `/v3/users/me` exposes no opaque user_id, so we key on the HeyGen account
- * EMAIL — the canonical account identifier and the reliable join key back to
- * billing — falling back to username only when the account exposes no email.
- * (Username is NOT a privacy win — HeyGen usernames are frequently email-shaped
- * — it is purely a fallback so an emailless account is still attributable.)
- * The privacy notice (showTelemetryNotice) and docs/packages/cli.mdx disclose
- * both, so keep them in sync with whatever this returns.
- */
-function identityKey(user: UserInfo): string | undefined {
- return user.email ?? user.username;
-}
-
/** Project the API `/v3/users/me` view onto the on-disk identity block. */
function toStoredUserInfo(user: UserInfo): StoredUserInfo {
const out: StoredUserInfo = {};
@@ -369,9 +361,9 @@ async function runApiKeyLogin(inlineKey: string): Promise {
await rollback(previous);
failCommand();
}
- const id = identityKey(user);
- if (id) identifyUser(id);
- trackAuthLoginCompleted("api_key", id);
+ const who = telemetryIdentity(user);
+ if (who) identifyUser(who.distinctId, who.traits);
+ trackAuthLoginCompleted("api_key", who?.distinctId);
}
async function snapshotStore(): Promise {
diff --git a/packages/cli/src/commands/auth/logout.ts b/packages/cli/src/commands/auth/logout.ts
index 0c0b3d711c..45b6041edd 100644
--- a/packages/cli/src/commands/auth/logout.ts
+++ b/packages/cli/src/commands/auth/logout.ts
@@ -69,8 +69,8 @@ function warnIfEnvCredentialActive(): void {
async function ensureConfirmed(yes: boolean, keepApiKey: boolean): Promise {
if (yes) return true;
const prompt = keepApiKey
- ? `This will sign out of any active OAuth session on this machine (~/.heygen lives at ${configDir()}). Continue? [y/N] `
- : `This will sign out of HeyGen on this machine (~/.heygen lives at ${configDir()}). Continue? [y/N] `;
+ ? `This will sign out of any active OAuth session on this machine (~/.hyperframes lives at ${configDir()}). Continue? [y/N] `
+ : `This will sign out of HeyGen on this machine (~/.hyperframes lives at ${configDir()}). Continue? [y/N] `;
return confirmInteractive(prompt);
}
diff --git a/packages/cli/src/commands/auth/status-guidance.ts b/packages/cli/src/commands/auth/status-guidance.ts
index cb4269fe2a..866dc17212 100644
--- a/packages/cli/src/commands/auth/status-guidance.ts
+++ b/packages/cli/src/commands/auth/status-guidance.ts
@@ -12,6 +12,8 @@ import { c } from "../../ui/colors.js";
export interface UnconfiguredContext {
/** A human can act on guidance now — a TTY, or a coding agent driving the CLI. */
interactive: boolean;
+ /** A coding agent runs this; the person reads what it relays. */
+ agent?: boolean;
}
/** The local engine a workflow will fall back to, and whether it's ready. */
@@ -58,10 +60,8 @@ function offlineEngineLines(engines?: OfflineEngineLine[]): string[] {
/**
* Human guidance for an unconfigured machine — registration-first.
* Both paths use `npx hyperframes` (zero-install via npm): browser OAuth
- * (sign-in / sign-up) and `--api-key` both write `~/.heygen`. The separate
- * `heygen` CLI shares that file but needs its own install (no `npx heygen`),
- * so it's left to the docs — not dangled here as a command a fresh machine
- * can't run. Names the local fallback so "no key" never reads as a failure,
+ * (sign-in / sign-up) and `--api-key` both write the isolated HyperFrames store.
+ * Names the local fallback so "no key" never reads as a failure,
* and never steers users toward a per-repo `.env`. Mirrors the
* media-use skill's Preflight section.
*/
@@ -69,6 +69,11 @@ export function buildUnconfiguredLines(
ctx: UnconfiguredContext,
engines?: OfflineEngineLine[],
): string[] {
+ if (ctx.agent)
+ return [
+ c.warn("Not signed in to HeyGen."),
+ `Ask the person to run ${c.accent("! npx hyperframes auth login")} in this prompt, then wait until they say it is done.`,
+ ];
if (!ctx.interactive) {
return [
c.warn("Not signed in to HeyGen (non-interactive)."),
@@ -80,7 +85,7 @@ export function buildUnconfiguredLines(
return [
c.warn("Not signed in to HeyGen — voice & music will use local engines (free, offline)."),
"",
- "Sign in or sign up (browser OAuth, writes ~/.heygen — no per-repo .env):",
+ "Sign in or sign up (browser OAuth, writes ~/.hyperframes — no per-repo .env):",
` ${c.accent("npx hyperframes auth login")} ${c.dim("# browser sign-in / sign-up")}`,
"",
"Or paste an existing HeyGen API key (get one at app.heygen.com/settings/api):",
diff --git a/packages/cli/src/commands/auth/status-user.test.ts b/packages/cli/src/commands/auth/status-user.test.ts
index 5bce36e4a8..1fb6d3ddb0 100644
--- a/packages/cli/src/commands/auth/status-user.test.ts
+++ b/packages/cli/src/commands/auth/status-user.test.ts
@@ -1,6 +1,8 @@
+import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { writeStore } from "../../auth/store.js";
import { setupTempAuthEnv, type EnvFixture } from "../../auth/_test-utils.js";
+import { persistFreshOAuth } from "../../auth/oauth.js";
import { consumeCommandResult } from "../../utils/commandResult.js";
// Mock only AuthClient so the live /v3/users/me probe is controllable;
@@ -35,7 +37,7 @@ describe("auth status — persisted user block surface", () => {
let stdout: string[];
beforeEach(async () => {
- envFixture = await setupTempAuthEnv("hf-status-");
+ envFixture = await setupTempAuthEnv("hf-status-99-");
probeState.apiReject = false;
probeState.user = { email: "live@example.com" };
stdout = [];
@@ -49,6 +51,7 @@ describe("auth status — persisted user block surface", () => {
afterEach(async () => {
consumeCommandResult();
vi.restoreAllMocks();
+ vi.unstubAllGlobals();
await envFixture.restore();
});
@@ -75,6 +78,85 @@ describe("auth status — persisted user block surface", () => {
expect(stdout.join("\n")).not.toContain("stored@example.com");
});
+ async function configureBillingCredential(mode: string): Promise {
+ if (mode === "api_key") {
+ await writeStore({ api_key: "hg_x" });
+ return;
+ }
+ if (mode === "host") {
+ process.env["HEYGEN_ACCESS_TOKEN"] = "host-at";
+ return;
+ }
+ if (mode === "hyperframes_dev") process.env["HYPERFRAMES_ENV"] = "dev";
+ if (mode === "custom") process.env["HYPERFRAMES_OAUTH_CLIENT_ID"] = "custom-client";
+ await persistFreshOAuth({ access_token: "at", refresh_token: "rt" });
+ }
+
+ it.each([
+ ["hyperframes", "hyperframes"],
+ ["hyperframes_dev", "hyperframes"],
+ ["custom", "unknown"],
+ ["host", "unknown"],
+ ["api_key", "heygen"],
+ ])("keeps %s billing distinct from generic account balances", async (mode, product) => {
+ probeState.user = {
+ email: "live@example.com",
+ billing_type: "subscription",
+ wallet: { remaining_balance: 99 },
+ subscription: { plan: "HeyGen Pro" },
+ };
+ await configureBillingCredential(mode);
+ expect(await runStatus(true)).toBe(0);
+ const payload = lastJson();
+ expect(payload["billing_product"]).toBe(product);
+ expect(payload["user"]).toEqual(probeState.user);
+ if (mode !== "api_key") {
+ expect(payload["hyperframes_balance"]).toBeNull();
+ expect(payload["billing_notice"]).toContain("HeyGen account");
+ }
+ stdout = [];
+ expect(await runStatus(false)).toBe(0);
+ const text = stdout.join("\n");
+ if (mode === "hyperframes_dev") expect(text).toContain(join("dev", "credentials"));
+ if (mode === "api_key") {
+ expect(text).toContain("Wallet:");
+ expect(text).toMatch(/^Wallet:\s+99$/m);
+ } else {
+ expect(text).not.toMatch(/^Wallet:/m);
+ expect(text).not.toContain("HeyGen Pro");
+ expect(text).toContain(
+ mode.startsWith("hyperframes")
+ ? "HyperFrames balance unavailable"
+ : "OAuth product not verified",
+ );
+ }
+ });
+
+ it("gives no 'balance unavailable' notice when the HyperFrames plan is shown", async () => {
+ vi.stubGlobal(
+ "fetch",
+ async () =>
+ new Response(
+ JSON.stringify({
+ data: {
+ subscription: { plan_name: "pro", status: "active" },
+ usage: { remaining_units: 25000 },
+ },
+ }),
+ ),
+ );
+ await configureBillingCredential("hyperframes");
+ expect(await runStatus(true)).toBe(0);
+ const payload = lastJson();
+ expect(payload["hyperframes"]).toEqual({ plan: "pro", credits: 25000 });
+ expect(payload).not.toHaveProperty("billing_notice");
+ stdout = [];
+ expect(await runStatus(false)).toBe(0);
+ const text = stdout.join("\n");
+ expect(text).toContain("pro plan, 25,000 credits");
+ expect(text).not.toContain("balance unavailable");
+ });
+
it("surfaces the persisted user block (with resolved display_name) for a file credential", async () => {
await writeStore({
api_key: "hg_x",
diff --git a/packages/cli/src/commands/auth/status.test.ts b/packages/cli/src/commands/auth/status.test.ts
index 41b44ae936..343b985e9e 100644
--- a/packages/cli/src/commands/auth/status.test.ts
+++ b/packages/cli/src/commands/auth/status.test.ts
@@ -97,6 +97,15 @@ describe("buildUnconfiguredLines — offline engine readiness", () => {
});
});
+describe("buildUnconfiguredLines — a coding agent", () => {
+ const text = joined({ interactive: true, agent: true });
+
+ it("asks the person to sign in from the prompt, with no local or API-key detour", () => {
+ expect(text).toContain("! npx hyperframes auth login");
+ expect(text).not.toMatch(/local engines|api-key|Kokoro/i);
+ });
+});
+
describe("buildUnconfiguredJson", () => {
it("recommends auth login and reports the local fallback", () => {
for (const ctx of [INTERACTIVE, NON_INTERACTIVE]) {
diff --git a/packages/cli/src/commands/auth/status.ts b/packages/cli/src/commands/auth/status.ts
index 6b262877fe..0abfdc5b92 100644
--- a/packages/cli/src/commands/auth/status.ts
+++ b/packages/cli/src/commands/auth/status.ts
@@ -18,6 +18,7 @@ import { failCommand, setCommandExitCode } from "../../utils/commandResult.js";
import { defineCommand } from "../../utils/defineCommand.js";
import {
ENV_CREDENTIAL_VAR,
+ credentialPath,
AuthClient,
isAuthError,
loadUserInfo,
@@ -30,6 +31,7 @@ import {
} from "../../auth/index.js";
import { getSystemMeta } from "../../telemetry/system.js";
import { c } from "../../ui/colors.js";
+import { pageUrl, readPlan, type Plan } from "../../heygen/plan.js";
import { resolveMusic, resolveVoice } from "../../audio/providers.js";
import {
buildUnconfiguredJson,
@@ -38,6 +40,16 @@ import {
type UnconfiguredContext,
} from "./status-guidance.js";
import { jsonFailure } from "../../utils/jsonError.js";
+import { defaultClientId, resolveClientId } from "../../auth/config.js";
+
+type BillingProduct = "hyperframes" | "heygen" | "unknown";
+
+function billingProduct(credential: ResolvedCredential): BillingProduct {
+ if (credential.type === "api_key") return "heygen";
+ if (isFileSource(credential.source) && resolveClientId() === defaultClientId())
+ return "hyperframes";
+ return "unknown";
+}
interface VerifiedStatus {
credential: ResolvedCredential;
@@ -50,9 +62,11 @@ interface VerifiedStatus {
*/
persistedUser: StoredUserInfo | null;
apiError: string | null;
+ /** The HyperFrames plan and credits, when the server (or the mock) answers. */
+ plan?: Plan | null;
}
-/** True for credentials resolved from the shared file (not env). */
+/** True for credentials resolved from the HyperFrames store (not env). */
function isFileSource(source: ResolvedCredential["source"]): boolean {
return source === "file_json" || source === "file_legacy";
}
@@ -95,7 +109,10 @@ export default defineCommand({
*/
function detectUnconfiguredContext(): UnconfiguredContext {
const sys = getSystemMeta();
- return { interactive: !sys.is_ci && (sys.is_tty || sys.agent_runtime !== null) };
+ return {
+ interactive: !sys.is_ci && (sys.is_tty || sys.agent_runtime !== null),
+ agent: !sys.is_ci && sys.agent_runtime !== null,
+ };
}
/**
@@ -153,7 +170,7 @@ async function verify(credential: ResolvedCredential): Promise {
const persistedUser = await loadPersistedUser(credential);
try {
const user = await client.getCurrentUser(credential);
- return { credential, user, persistedUser, apiError: null };
+ return { credential, user, persistedUser, apiError: null, plan: await readPlan() };
} catch (err) {
if (!isAuthError(err)) throw err;
return {
@@ -182,18 +199,29 @@ async function loadPersistedUser(credential: ResolvedCredential): Promise = {
configured: true,
source: s.credential.source,
type: s.credential.type,
+ billing_product: product,
user: s.user,
// The friendly-display block persisted at login (file-sourced creds
// only). Strictly additive — the live `user` field above is
// unchanged. Lets callers read identity offline / on an API blip.
persisted_user: persistedUserJson(s.persistedUser),
api_error: s.apiError,
+ hyperframes: s.plan ?? null,
};
if (s.credential.type === "oauth") {
+ payload["hyperframes_balance"] = null;
+ // With the plan read, `hyperframes` above holds the plan and credits, so there is no notice to give.
+ if (product !== "hyperframes")
+ payload["billing_notice"] =
+ "OAuth billing product is not verified here; user billing fields describe the HeyGen account.";
+ else if (!s.plan)
+ payload["billing_notice"] =
+ "HyperFrames balance is unavailable here; user billing fields describe the HeyGen account.";
payload["expires_at"] = s.credential.expires_at?.toISOString() ?? null;
payload["refreshable"] = s.credential.refreshable;
payload["scope"] = s.credential.scope ?? null;
@@ -239,7 +267,17 @@ function collectStatusRows(s: VerifiedStatus): [string, string][] {
if (cached) rows.push(["Account:", `${cached} ${c.dim("(cached)")}`]);
return rows;
}
- if (s.user) rows.push(...identityRows(s.user));
+ if (s.user) rows.push(...identityRows(s.user, billingProduct(s.credential), !!s.plan));
+ const plan = s.plan;
+ if (plan) {
+ const tag = plan.mock ? ` ${c.dim("(mock)")}` : "";
+ rows.push([
+ "HyperFrames:",
+ plan.plan === "none"
+ ? `Free · Upgrade to Pro: ${pageUrl("plans")}${tag}`
+ : `${plan.plan} plan, ${plan.credits.toLocaleString("en-US")} credits${tag}`,
+ ]);
+ }
return rows;
}
@@ -256,20 +294,42 @@ function oauthRows(credential: Extract):
return rows;
}
-function identityRows(user: UserInfo): [string, string][] {
+/** `hasPlan`: the HyperFrames line below shows the plan and credits, so no "unavailable" balance above it. */
+function identityRows(
+ user: UserInfo,
+ product: BillingProduct,
+ hasPlan = false,
+): [string, string][] {
const identity = user.email ?? user.username ?? "(unknown user)";
- return [["Account:", identity], ...billingRows(user)];
+ const rows: [string, string][] = [["Account:", identity]];
+ if (product === "hyperframes")
+ return [
+ ...rows,
+ ["Billing:", "HyperFrames"],
+ ...(hasPlan
+ ? []
+ : [["Balance:", "HyperFrames balance unavailable here."] as [string, string]]),
+ ];
+ if (product === "unknown")
+ return [
+ ...rows,
+ [
+ "Billing:",
+ "OAuth product not verified; HeyGen account balances are not the active-payer balance.",
+ ],
+ ];
+ return [...rows, ...billingRows(user)];
}
-const SOURCE_LABELS: Record = {
+const SOURCE_LABELS = {
env: `env (${ENV_CREDENTIAL_VAR.env})`,
env_alias: `env (${ENV_CREDENTIAL_VAR.env_alias})`,
env_oauth: `env (${ENV_CREDENTIAL_VAR.env_oauth})`,
- file_legacy: "file (~/.heygen/credentials — legacy plaintext)",
- file_json: "file (~/.heygen/credentials)",
};
function describeSource(source: ResolvedCredential["source"]): string {
+ if (source === "file_legacy") return `file (${credentialPath()} — legacy plaintext)`;
+ if (source === "file_json") return `file (${credentialPath()})`;
return SOURCE_LABELS[source];
}
diff --git a/packages/cli/src/commands/batchRender.test.ts b/packages/cli/src/commands/batchRender.test.ts
index a76b3f5aed..72978a5a10 100644
--- a/packages/cli/src/commands/batchRender.test.ts
+++ b/packages/cli/src/commands/batchRender.test.ts
@@ -85,6 +85,27 @@ describe("resolveOutputTemplate", () => {
});
describe("prepareBatchRender", () => {
+ it.each(["utf8", "utf16le"] as const)("reads a %s batch file with a BOM", (encoding) => {
+ const batchPath = join(tmpDir, "rows.json");
+ writeFileSync(batchPath, '\uFEFF[{"name":"Café","title":"Hello\\uFEFFworld"}]', encoding);
+ const prepared = prepareBatchRender({
+ batchPath,
+ outputTemplate: join(tmpDir, "renders", "{name}.mp4"),
+ indexPath: writeIndex(),
+ strictVariables: false,
+ quiet: true,
+ json: false,
+ });
+
+ expect(prepared.rows).toEqual([
+ {
+ index: 0,
+ variables: { name: "Café", title: "Hello\uFEFFworld" },
+ outputPath: resolve(tmpDir, "renders", "Café.mp4"),
+ },
+ ]);
+ });
+
it("resolves output paths and the manifest path", () => {
const batchPath = writeJson("rows.json", '[{"name":"Alice"},{"name":"Bob"}]');
const outDir = join(tmpDir, "renders");
diff --git a/packages/cli/src/commands/batchRender.ts b/packages/cli/src/commands/batchRender.ts
index 2293c37ec2..6594c96a3f 100644
--- a/packages/cli/src/commands/batchRender.ts
+++ b/packages/cli/src/commands/batchRender.ts
@@ -1,5 +1,6 @@
import { failCommand } from "../utils/commandResult.js";
-import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { mkdirSync, writeFileSync } from "node:fs";
+import { readJsonFileText } from "../utils/jsonFlag.js";
import { dirname, join, resolve, sep } from "node:path";
import { c } from "../ui/colors.js";
import { errorBox } from "../ui/format.js";
@@ -241,7 +242,7 @@ function reportBatchVariableIssues(
export function prepareBatchRender(options: PrepareBatchRenderOptions): PreparedBatchRender {
const batchPath = resolve(options.batchPath);
- const read = options.readFile ?? ((path: string) => readFileSync(path, "utf8"));
+ const read = options.readFile ?? readJsonFileText;
let raw: string;
try {
raw = read(batchPath);
@@ -441,8 +442,6 @@ export async function runBatchRender(options: RunBatchRenderOptions): Promise {
expect(Math.abs(report.bpm - 120)).toBeLessThanOrEqual(1);
});
- it("points a media file argument to hyperframes audio instead of reading it as a project", async () => {
- const song = join(project("file-arg", 120), "assets", "song.wav");
- const { exitCode, out } = await runBeats(song);
- expect(exitCode).toBe(1);
- expect(out).toContain(`hyperframes audio ${JSON.stringify(song)} --only beats --json`);
+ it("analyses an audio file given directly and writes nothing", async () => {
+ const dir = project("file-arg", 120);
+ const song = join(dir, "assets", "song.wav");
+ const { exitCode, out } = await runBeats(song, true);
+ expect(exitCode).toBe(0);
+ const report = JSON.parse(out) as {
+ ok: boolean;
+ file: string;
+ bpm: number;
+ beatTimes: number[];
+ };
+ expect(report).toMatchObject({ ok: true, file: song });
+ expect(report.beatTimes.length).toBeGreaterThan(18);
+ expect(Math.abs(report.bpm - 120)).toBeLessThanOrEqual(1);
+ expect(existsSync(join(dir, "beats"))).toBe(false);
});
it("tells a composition file argument to pass its folder", async () => {
diff --git a/packages/cli/src/commands/beats.ts b/packages/cli/src/commands/beats.ts
index 5b81c9cb9a..459d8f5cea 100644
--- a/packages/cli/src/commands/beats.ts
+++ b/packages/cli/src/commands/beats.ts
@@ -21,7 +21,7 @@ import { c } from "../ui/colors.js";
export const examples: Example[] = [
["Generate the beat file for the current project", "hyperframes beats"],
["Generate for a specific directory", "hyperframes beats ./my-video"],
- ["Beats of a single audio file", "hyperframes audio music.mp3 --only beats --json"],
+ ["Beats of a single audio or video file", "hyperframes beats music.mp3 --json"],
];
function fail(message: string): never {
@@ -96,24 +96,54 @@ function report(file: string, result: MusicBeatAnalysis, json: boolean): void {
);
}
+async function analyzeFile(audioPath: string, json: boolean): Promise {
+ const result = await analyzeMusicFromSignal(await decode(audioPath));
+ if (result.beatTimes.length === 0) fail(`No beats detected in ${audioPath}.`);
+ if (json) {
+ console.log(
+ JSON.stringify(
+ {
+ ok: true,
+ file: audioPath,
+ count: result.beatTimes.length,
+ bpm: result.bpm,
+ beatTimes: result.beatTimes,
+ },
+ null,
+ 2,
+ ),
+ );
+ return;
+ }
+ console.log(
+ c.success(
+ `✓ ${result.beatTimes.length} beats in ${audioPath} (bpm ${result.bpm ?? "?"}, ${result.bpmConfidence})`,
+ ),
+ );
+}
+
export default defineCommand({
meta: {
name: "beats",
- description: "Detect beats in the music track and write beats/.json",
+ description:
+ "Detect beats in the project music track (writes beats/.json) or in one audio file",
},
args: {
- dir: { type: "positional", description: "Project directory", required: false },
+ dir: {
+ type: "positional",
+ description: "Project directory, or one audio or video file to analyse",
+ required: false,
+ },
json: { type: "boolean", description: "Output result as JSON", default: false },
},
async run({ args }) {
if (args.dir && existsSync(resolve(args.dir)) && statSync(resolve(args.dir)).isFile()) {
- const file = JSON.stringify(args.dir);
- fail(
- /\.html?$/i.test(args.dir)
- ? `${args.dir} is a file; beats takes the project folder: hyperframes beats ${JSON.stringify(dirname(args.dir))}`
- : `${args.dir} is a file; beats takes a project folder. ` +
- `For one audio or video file run: hyperframes audio ${file} --only beats --json`,
- );
+ if (/\.html?$/i.test(args.dir)) {
+ fail(
+ `${args.dir} is a file; beats takes the project folder: hyperframes beats ${JSON.stringify(dirname(args.dir))}`,
+ );
+ }
+ return await analyzeFile(resolve(args.dir), Boolean(args.json));
}
const project = resolveProject(args.dir);
const target = resolveMusicTarget(project);
diff --git a/packages/cli/src/commands/billing.ts b/packages/cli/src/commands/billing.ts
new file mode 100644
index 0000000000..1db3617109
--- /dev/null
+++ b/packages/cli/src/commands/billing.ts
@@ -0,0 +1,63 @@
+import { openBrowser } from "../auth/browser.js";
+import { pageUrl, readPlan, type Plan } from "../heygen/plan.js";
+import { c } from "../ui/colors.js";
+import { failCommand } from "../utils/commandResult.js";
+import { defineCommand } from "../utils/defineCommand.js";
+
+const describe = (p: Plan | null) =>
+ p && p.plan !== "none" ? `${p.plan} plan, ${p.credits.toLocaleString("en-US")} credits` : "Free";
+
+/** Opens the plans or credits page, then waits until the account shows the change, so the run continues on its own. */
+export default defineCommand({
+ meta: {
+ name: "billing",
+ description:
+ "Open the HyperFrames plans or credits page and wait until the person is done (subscribe | top-up)",
+ },
+ args: {
+ action: { type: "positional", description: "subscribe | top-up", required: true },
+ needed: {
+ type: "string",
+ description: "Credits the waiting step needs (top-up waits until the balance covers it)",
+ },
+ tool: { type: "string", description: "The step that is waiting, shown on the page" },
+ timeout: { type: "string", description: "Seconds to wait (default 600)" },
+ },
+ // fallow-ignore-next-line complexity
+ async run({ args }) {
+ const action = String(args.action);
+ if (action !== "subscribe" && action !== "top-up") {
+ console.error(c.error("Use `billing subscribe` or `billing top-up`."));
+ failCommand();
+ }
+ const needed = Number(args.needed) || undefined;
+ const before = await readPlan();
+ const done = (p: Plan | null) =>
+ action === "subscribe"
+ ? !!p && p.plan !== "none"
+ : !!p && p.plan !== "none" && p.credits >= (needed ?? (before?.credits ?? 0) + 1);
+ if (done(before) && (action === "subscribe" || needed)) {
+ console.log(c.success(`✓ Already covered: ${describe(before)}.`));
+ return;
+ }
+ const url = pageUrl(action === "subscribe" ? "plans" : "credits", { needed, tool: args.tool });
+ console.log(`${action === "subscribe" ? "Plans" : "Credits"} page: ${c.accent(url)}`);
+ await openBrowser(url);
+ console.log("Waiting for the person to finish there ...");
+ const deadline = Date.now() + (Number(args.timeout) || 600) * 1000;
+ while (Date.now() < deadline) {
+ await new Promise((r) => setTimeout(r, 2000));
+ const now = await readPlan();
+ if (done(now)) {
+ console.log(c.success(`✓ Done: ${describe(now)}. Carry on.`));
+ return;
+ }
+ }
+ console.error(
+ c.error(
+ `Still waiting on the ${action === "subscribe" ? "plans" : "credits"} page; run this again once it is done.`,
+ ),
+ );
+ failCommand();
+ },
+});
diff --git a/packages/cli/src/commands/check.test.ts b/packages/cli/src/commands/check.test.ts
index a53f1c67e6..2a22a6af94 100644
--- a/packages/cli/src/commands/check.test.ts
+++ b/packages/cli/src/commands/check.test.ts
@@ -12,6 +12,7 @@ vi.mock("../telemetry/events.js", () => ({
import { contrastRatio, parseColorRGBA } from "./contrast-bg.js";
import { createCheckCommand, parseCheckRange } from "./check.js";
+import { readConfig } from "../telemetry/config.js";
import { CheckDeadlineError, CheckStoppedError } from "../utils/checkDeadline.js";
import { trackCommandFailures } from "../utils/command-failure-tracking.js";
import type { CommandDef } from "citty";
@@ -1567,6 +1568,77 @@ describe("check pipeline", () => {
expect(report.contrast).toMatchObject({ ok: true, errorCount: 0, findings: [] });
});
+ it("says in plain words that a lint error is why the browser pass was skipped", async () => {
+ const lint = lintWith(
+ "error",
+ "root_missing_composition_id",
+ "Root needs data-composition-id.",
+ );
+ const { report } = await runScenario(fakeDriver(), {}, { lint });
+ const log = vi.spyOn(console, "log").mockImplementation(() => undefined);
+ const command = createCheckCommand({
+ resolveProject: () => PROJECT,
+ runPipeline: vi.fn(async () => report),
+ prepareMedia: vi.fn(async () => []),
+ withMeta: (value) => value,
+ });
+
+ await runViaCli(command, { rawArgs: [] });
+
+ const said = log.mock.calls.map((call) => String(call[0])).join("\n");
+ expect(said).toContain("Browser validation skipped because of the lint error above");
+ expect(said).not.toContain("Browser session never ran");
+ });
+
+ describe("remembers the newest check for hyperframes feedback", () => {
+ const run = (runPipeline: () => Promise) =>
+ runViaCli(
+ createCheckCommand({
+ resolveProject: () => PROJECT,
+ runPipeline: vi.fn(runPipeline),
+ prepareMedia: vi.fn(async () => []),
+ withMeta: (value) => value,
+ }),
+ { rawArgs: [] },
+ );
+
+ it("keeps the error codes of a failed check", async () => {
+ const lint = lintWith(
+ "error",
+ "root_missing_composition_id",
+ "Root needs data-composition-id.",
+ );
+ const { report } = await runScenario(fakeDriver(), {}, { lint });
+ await run(async () => report);
+
+ expect(readConfig().lastCheck).toMatchObject({
+ exitCode: 1,
+ codes: { root_missing_composition_id: 1 },
+ });
+ });
+
+ it("records a check that threw as a failure, not the check before it", async () => {
+ await run(async () => (await runScenario(fakeDriver(), {}, {})).report);
+ await run(async () => {
+ throw new Error("browser died");
+ });
+
+ expect(readConfig().lastCheck).toMatchObject({ exitCode: 1, codes: { runtime_error: 1 } });
+ });
+
+ it("leaves a check that never finished as unfinished, with when it started", async () => {
+ const { report } = await runScenario(fakeDriver(), {}, {});
+ await run(async () => report);
+ let finish!: (value: CheckReport) => void;
+ const running = run(() => new Promise((resolve) => (finish = resolve)));
+ await vi.waitFor(() => expect(readConfig().lastCheck?.exitCode).toBeUndefined());
+
+ expect(readConfig().lastCheck?.at).toMatch(/^\d{4}-\d\d-\d\dT/);
+ finish(report);
+ await running;
+ });
+ });
+
it("marks browserSkipped true when the linter itself crashes", async () => {
const { deps } = dependencies(fakeDriver());
deps.lintProject = vi.fn(async () => {
@@ -2267,6 +2339,42 @@ describe("check pipeline", () => {
}
});
+ it("a check given a long --timeout is not ended as idle after 120 s of waiting for its page", async () => {
+ vi.useFakeTimers();
+ try {
+ let aborted!: AbortSignal;
+ const driver = fakeDriver({
+ collectOverlapGrid: vi.fn(
+ () =>
+ new Promise((_, reject) =>
+ aborted.addEventListener("abort", () => reject(aborted.reason)),
+ ),
+ ),
+ });
+ const { deps } = dependencies(driver);
+ deps.runBrowserCheck = async (_project, options, motion, deadline) => {
+ aborted = deadline!.signal;
+ deadline!.start();
+ return runAuditGrid(driver, options, motion, undefined, deadline!.enter);
+ };
+ const pending = runCheckPipeline(
+ PROJECT,
+ { ...DEFAULT_CHECK_OPTIONS, timeout: 400_000 },
+ deps,
+ );
+ await vi.advanceTimersByTimeAsync(300_000);
+ expect(aborted.aborted).toBe(false);
+ await vi.advanceTimersByTimeAsync(110_000);
+ const report = await pending;
+ const failure = report.runtime.findings.find(
+ (finding) => finding.code === "check_runtime_failure",
+ );
+ expect(failure?.message).toContain("no progress for 410 s");
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it("a deadline keeps the layout findings the finished samples already made", async () => {
vi.useFakeTimers();
try {
@@ -2692,6 +2800,7 @@ describe("check pipeline", () => {
blockSelector: "#title",
sourceFile: "compositions/stat.html",
text: "Every team gets one shared calendar now",
+ blockText: "Every team gets one shared calendar now",
opacity: 1,
fontPx: 96,
rect: { left: 160, top: 380, width: 1600, height: 220 },
@@ -2733,6 +2842,20 @@ describe("check pipeline", () => {
expect(checkExitCode(strict.report)).toBe(0);
});
+ it("seeks each craft frame with WebGL draws on, so a redrawn canvas reads as moving", async () => {
+ const driver = craftDriver();
+ await runScenario(driver);
+ const painted = new Set(
+ vi
+ .mocked(driver.seekGeometry)
+ .mock.calls.flatMap(([time, seek]) => (seek?.draws ? [time] : [])),
+ );
+ const sampled = vi.mocked(driver.collectCraftFrame!).mock.calls.map(([time]) => time);
+
+ expect(sampled.length).toBeGreaterThan(0);
+ expect(sampled.every((time) => painted.has(time))).toBe(true);
+ });
+
it("re-measures a short line between dense samples before judging it", async () => {
const driver = craftDriver();
const { report } = await runScenario(driver);
diff --git a/packages/cli/src/commands/check.ts b/packages/cli/src/commands/check.ts
index 20cf1b98f9..ac2026b343 100644
--- a/packages/cli/src/commands/check.ts
+++ b/packages/cli/src/commands/check.ts
@@ -41,6 +41,8 @@ import { resolveLocalBrowserGpuMode } from "../browser/gpuPolicy.js";
import { preResolveHostileMediaProxies, type PreparedMediaFile } from "../utils/checkBrowser.js";
import { parseTimeoutMs } from "../utils/timeoutArg.js";
import { failureMessage, jsonFailure } from "../utils/jsonError.js";
+import { recordLastCheck } from "../telemetry/config.js";
+import { failureCodes } from "../utils/checkFailureCodes.js";
export const examples: Example[] = [
["Run the full verification gate", "hyperframes check"],
@@ -287,9 +289,15 @@ export function createCheckCommand(
await runPrepareMedia(dependencies, project, options, asJson);
return;
}
+ recordLastCheck({ at: new Date().toISOString(), codes: {} });
const report = await withProjectLock(project.dir, "check", () =>
dependencies.runPipeline(project, options),
);
+ recordLastCheck({
+ at: new Date().toISOString(),
+ exitCode: checkExitCode(report),
+ codes: failureCodes(report),
+ });
if (asJson) {
console.log(JSON.stringify(dependencies.withMeta(report), null, 2));
} else {
@@ -303,6 +311,11 @@ export function createCheckCommand(
}
setCommandExitCode(checkExitCode(report));
} catch (error) {
+ recordLastCheck({
+ at: new Date().toISOString(),
+ exitCode: 1,
+ codes: { [error instanceof CliUsageError ? error.code : "runtime_error"]: 1 },
+ });
reportCheckFailure(error, asJson, (value) => dependencies.withMeta(value));
} finally {
reported.done();
@@ -639,6 +652,13 @@ function nonNegativeNumber(value: unknown, fallback: number): number {
return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
}
+function browserSkippedLine(report: CheckReport): string {
+ const lintError = report.lint.findings.some((finding) => finding.severity === "error");
+ return lintError
+ ? "Browser validation skipped because of the lint error above: fix it and run check again. Layout, motion, and contrast were not checked, so this is not a clean pass."
+ : "Browser session never ran — layout, motion, and contrast below are empty placeholders, not a clean pass.";
+}
+
function printHumanReport(report: CheckReport): void {
if (report.scope) {
console.log(
@@ -649,9 +669,7 @@ function printHumanReport(report: CheckReport): void {
printSection("Lint", report.lint);
if (report.browserSkipped) {
console.log();
- console.log(
- ` ${c.warn("⚠")} Browser session never ran — layout, motion, and contrast below are empty placeholders, not a clean pass.`,
- );
+ console.log(` ${c.warn("⚠")} ${browserSkippedLine(report)}`);
}
printSection("Runtime", report.runtime);
printLayoutSection("Layout", report.layout);
diff --git a/packages/cli/src/commands/diff.ts b/packages/cli/src/commands/diff.ts
new file mode 100644
index 0000000000..ae672d371e
--- /dev/null
+++ b/packages/cli/src/commands/diff.ts
@@ -0,0 +1,256 @@
+import { basename, extname, join, resolve } from "node:path";
+import { defineCommand } from "../utils/defineCommand.js";
+import type { Example } from "./_examples.js";
+import { c } from "../ui/colors.js";
+import { failCommand, setCommandExitCode } from "../utils/commandResult.js";
+import { normalizeErrorMessage } from "../utils/errorMessage.js";
+import { withMeta } from "../utils/updateCheck.js";
+import {
+ DEFAULT_MIN_CELL,
+ DEFAULT_MIN_MEAN,
+ DEFAULT_MIN_P05,
+ diffVideos,
+ findLedger,
+ type DiffResult,
+} from "../measure/diff.js";
+import { Fix, formatJson, outDir, parseNumbers, parseRange } from "../measure/media.js";
+import { readSegments } from "../measure/segments.js";
+import { repeated } from "./media-use/generate.js";
+import { parseMask } from "../heygen/generate.js";
+
+export const examples: Example[] = [
+ [
+ "Score a render against the original, frame by frame",
+ "hyperframes diff original.mp4 renders/final.mp4",
+ ],
+ [
+ "Score one segment of a project without rendering it",
+ "hyperframes diff original.mp4 . --range 2.1,4.5",
+ ],
+ [
+ "Score chosen moments of a project without rendering it",
+ "hyperframes diff original.mp4 . --at 0.5,2.4,3.1",
+ ],
+ [
+ "Score one drawn element (a title's box) by itself at chosen moments of a project",
+ "hyperframes diff original.mp4 . --at 1,1.5,2 --drawn 120,670,485,115",
+ ],
+ [
+ "Judge each segment of the final render and write a side-by-side",
+ "hyperframes diff original.mp4 renders/final.mp4 --segments segments.md --sbs",
+ ],
+];
+
+function number(value: unknown, flag: string): number | undefined {
+ if (value === undefined) return undefined;
+ const [n] = parseNumbers(value, flag);
+ return n;
+}
+
+/** `x,y,w,h` or `x,y,w,h,a-b` in the original's pixels and seconds. */
+function parseDrawn(text: string): ReturnType {
+ try {
+ return parseMask(text);
+ } catch {
+ throw new Fix(`--drawn ${text} is not x,y,w,h[,a-b]`, "--drawn 120,670,485,115,0-2.77");
+ }
+}
+
+function personLine(p: NonNullable[number]["person"] & object): string {
+ const off = [
+ ...(p.framing ?? [])
+ .filter((f) => !f.pass)
+ .map(
+ (f) => `framing off ${f.window[0]}–${f.window[1]} s (shift ${f.shift}, size ×${f.scale})`,
+ ),
+ ...(p.text ?? []).filter((t) => t.carried).map((t) => `${t.clip} carries ${t.drawn}'s text`),
+ ...(p.sync ?? [])
+ .filter((x) => x.pass === false)
+ .map((x) => `lips ${x.lag_ms} ms off at ${x.window[0]} s`),
+ ];
+ const moved = p.energy ? `, motion ×${p.energy.mean_ratio} (reported)` : "";
+ return `person ${p.pass === null ? "—" : p.pass ? "✓" : "✗"}${off.length ? ` ${off.join("; ")}` : ""}${moved}`;
+}
+
+// fallow-ignore-next-line complexity
+function printHuman(r: DiffResult) {
+ const mark = r.pass ? c.success("✓ pass") : c.error("✗ fail");
+ console.log(
+ `${mark} SSIM mean ${r.ssim.mean}, p05 ${r.ssim.p05}, worst cell p05 ${r.ssim.cell_p05} over ${r.ssim.frames} frames (${r.window[0]}–${r.window[1]} s)`,
+ );
+ if (!r.missing_content.pass)
+ console.log(
+ ` missing content in ${Math.round(r.missing_content.share * 100)}% of frames: ${r.missing_content.spans.map(([a, b]) => `${a}–${b} s`).join(", ")}`,
+ );
+ if (r.missing_content.texture.share > 0)
+ console.log(
+ ` missing texture (reported, not failed) in ${Math.round(r.missing_content.texture.share * 100)}% of frames: ${r.missing_content.texture.spans.map(([a, b]) => `${a}–${b} s`).join(", ")}`,
+ );
+ for (const m of r.worst)
+ console.log(` worst ${m.t}s ssim ${m.ssim} cell ${m.cell.roi.join(",")} at ${m.cell.ssim}`);
+ if (r.whole_frame_reuse?.spans.length)
+ console.log(
+ ` whole frame of the original in ${Math.round(r.whole_frame_reuse.share * 100)}% of frames${r.whole_frame_reuse.pass ? "" : `, with its drawn things at ${r.whole_frame_reuse.drawn.map(([a, b]) => `${a}–${b} s`).join(", ")} (a copy)`}`,
+ );
+ if (r.cuts)
+ console.log(
+ ` cuts: ${r.cuts.reference.length} in the original${r.cuts.pass ? ", all matched" : `; missing ${r.cuts.missing.join(", ") || "none"}, extra ${r.cuts.extra.join(", ") || "none"}`}`,
+ );
+ if (r.duration)
+ console.log(
+ ` duration: original ${r.duration.reference} s, yours ${r.duration.yours} s${r.duration.pass ? "" : " (differ)"}`,
+ );
+ if (r.sound)
+ console.log(
+ ` sound: ${"offset_ms" in r.sound ? (r.sound.offset_ms === null ? (r.sound.note ?? "not aligned") : `${r.sound.offset_ms} ms off`) : `original ${r.sound.original ? "has" : "has no"} sound, yours ${r.sound.yours ? "has" : "has no"}`}${r.sound.pass ? "" : " (fails)"}`,
+ );
+ if (r.components)
+ console.log(
+ ` components: ${r.components.passed} of ${r.components.total} pass${r.components.mean === null ? "" : `, mean ${r.components.mean}`}`,
+ );
+ if (r.person) {
+ const g = r.person.gates;
+ const mark = (v: boolean | null, failed: string[]) =>
+ v === null ? "unmeasured" : v ? "ok" : `fails in ${failed.join(", ")}`;
+ console.log(
+ ` person: framing ${mark(g.framing, r.person.failed.framing)}, text in the clip ${mark(g.text, r.person.failed.text)}, lips ${mark(g.sync, r.person.failed.sync)}; reported: motion ×${r.person.energy ?? "?"}, ${r.person.shots_at_cuts.at_cuts} of ${r.person.shots_at_cuts.total} clips start at a cut${r.person.shots_at_cuts.cuts_without_shot.length ? `, no new clip at ${r.person.shots_at_cuts.cuts_without_shot.join(", ")} s` : ""}`,
+ );
+ }
+ console.log(` every frame: ${r.frames}`);
+ for (const s of r.segments ?? []) {
+ const state = s.pass === null ? c.dim("—") : s.pass ? c.success("✓") : c.error("✗");
+ const detail =
+ [
+ s.ssim && `ssim ${s.ssim.mean} / p05 ${s.ssim.p05} / cell ${s.ssim.cell_p05}`,
+ s.energy && `motion ×${s.energy.mean_ratio}, luma ×${s.look?.luma_ratio}`,
+ s.person && personLine(s.person),
+ ]
+ .filter(Boolean)
+ .join("; ") ||
+ (s.note ?? "");
+ const region = s.regenerated ? `; person in ${s.regenerated.roi.join(",")}` : "";
+ console.log(
+ ` ${state} ${s.id} ${s.window[0]}–${s.window[1]} s ${s.pixels}${s.regenerated ? " outside the region" : ""}: ${detail}${region}`,
+ );
+ }
+ for (const d of r.drawn ?? []) {
+ const state = d.pass === null ? c.dim("—") : d.pass ? c.success("✓") : c.error("✗");
+ const detail =
+ d.pass === null
+ ? "no ink found in the box (crop it tight around the letters)"
+ : `score ${d.score} / p05 ${d.p05}, off by ${d.offset!.join(",")} px${d.ink === undefined ? "" : `, ink ×${d.ink}`}`;
+ console.log(
+ ` ${state} ${d.id} ${d.box.join(",")} ${d.window[0]}–${d.window[1]} s: ${detail}`,
+ );
+ }
+ for (const w of r.warnings) console.log(` ${c.warn("⚠")} ${w}`);
+ if (r.sheet) console.log(` sheet ${r.sheet}`);
+ if (r.sbs) console.log(` side by side ${r.sbs}`);
+}
+
+export default defineCommand({
+ meta: {
+ name: "diff",
+ description:
+ "Score a render or a project against the original video frame by frame: SSIM, worst moments, cuts, segments",
+ },
+ args: {
+ reference: { type: "positional", description: "The original video", required: true },
+ yours: {
+ type: "positional",
+ description:
+ "A rendered video, or a project folder (captured at the original's frame times, no render)",
+ required: true,
+ },
+ at: { type: "string", description: "Compare only these seconds, e.g. 0.5,2.4" },
+ range: { type: "string", description: "Compare every frame of start,end seconds" },
+ segments: {
+ type: "string",
+ description:
+ "A file of `## S01 · a–b s` segments: a verdict per segment (Pixels: regenerated compares motion and look)",
+ },
+ ledger: {
+ type: "string",
+ description:
+ "The project's media ledger, to find whole-frame cuts of the original (default: .media/manifest.jsonl beside the project or REVERSE.md)",
+ },
+ project: {
+ type: "string",
+ description:
+ "The project folder, to find the ledger's generated clips and check them for the original's text (default: the folder holding .media)",
+ },
+ "min-mean": { type: "string", description: `Mean SSIM to pass (default ${DEFAULT_MIN_MEAN})` },
+ "min-p05": {
+ type: "string",
+ description: `5th-percentile SSIM to pass (default ${DEFAULT_MIN_P05})`,
+ },
+ "min-cell": {
+ type: "string",
+ description: `5th percentile of each frame's worst 4x4 cell to pass (default ${DEFAULT_MIN_CELL})`,
+ },
+ worst: { type: "string", description: "Worst moments to show (default 4)" },
+ sbs: {
+ type: "boolean",
+ description: "Also write an original | yours side-by-side video",
+ default: false,
+ },
+ out: {
+ type: "string",
+ description: "Folder for the sheet and log (default .hyperframes/diff/)",
+ },
+ timeout: {
+ type: "string",
+ description: "Render-ready timeout in ms for a project folder (default 5000)",
+ },
+ drawn: {
+ type: "string",
+ description:
+ "A drawn element's box x,y,w,h in the original's pixels, optionally its seconds a-b (repeatable): scored by itself whatever is behind it, with its offset and ink (yours over the original's: under 1 is lighter, thinner or smaller)",
+ },
+ json: { type: "boolean", description: "Print one JSON result", default: false },
+ },
+ // fallow-ignore-next-line complexity
+ async run({ args, rawArgs }) {
+ const json = args.json === true;
+ try {
+ if (args.at !== undefined && args.range !== undefined)
+ throw new Fix("--at and --range both given", "pass one of them");
+ const yours = resolve(String(args.yours));
+ const stem = basename(yours, extname(yours)) || "project";
+ const segmentsFile = args.segments === undefined ? undefined : resolve(String(args.segments));
+ const result = await diffVideos({
+ reference: resolve(String(args.reference)),
+ yours,
+ at: args.at === undefined ? undefined : parseNumbers(args.at, "--at"),
+ range: args.range === undefined ? undefined : parseRange(args.range),
+ segments: segmentsFile === undefined ? undefined : readSegments(segmentsFile),
+ ledger:
+ args.ledger === undefined
+ ? findLedger(yours, segmentsFile)
+ : resolve(String(args.ledger)),
+ project: args.project === undefined ? undefined : resolve(String(args.project)),
+ drawn: repeated(rawArgs, "--drawn").map(parseDrawn),
+ thresholds: {
+ mean: number(args["min-mean"], "--min-mean"),
+ p05: number(args["min-p05"], "--min-p05"),
+ cell: number(args["min-cell"], "--min-cell"),
+ },
+ worst: number(args.worst, "--worst"),
+ sbs: args.sbs === true,
+ outDir: outDir(args.out, join("diff", stem)),
+ timeoutMs: number(args.timeout, "--timeout"),
+ log: (message) => console.error(message),
+ });
+ if (json) console.log(formatJson(withMeta({ ok: true, ...result })));
+ else printHuman(result);
+ if (!result.pass) setCommandExitCode(1);
+ } catch (err) {
+ const fix = err instanceof Fix ? err.fix : undefined;
+ const message = normalizeErrorMessage(err);
+ if (json)
+ console.log(formatJson(withMeta({ ok: false, error: message, ...(fix ? { fix } : {}) })));
+ else console.error(`${c.error("✗")} ${message}${fix ? `\n Fix: ${fix}` : ""}`);
+ failCommand();
+ }
+ },
+});
diff --git a/packages/cli/src/commands/docs.test.ts b/packages/cli/src/commands/docs.test.ts
index 707584e0fe..09b873cdf4 100644
--- a/packages/cli/src/commands/docs.test.ts
+++ b/packages/cli/src/commands/docs.test.ts
@@ -48,3 +48,18 @@ describe("docs examples topic", () => {
}
});
});
+
+describe("docs topics", () => {
+ const source = readFileSync(
+ join(REPO_ROOT, "packages", "cli", "src", "commands", "docs.ts"),
+ "utf8",
+ );
+
+ it("has a file for every topic it lists, including motion-blur", () => {
+ const files = [...source.matchAll(/file: "([^"]+)"/g)].map((match) => match[1] ?? "");
+ expect(files).toContain("motion-blur.md");
+ for (const file of files) {
+ expect(readdirSync(join(REPO_ROOT, "packages", "cli", "src", "docs"))).toContain(file);
+ }
+ });
+});
diff --git a/packages/cli/src/commands/docs.ts b/packages/cli/src/commands/docs.ts
index a3c7566d4c..cd1042f21e 100644
--- a/packages/cli/src/commands/docs.ts
+++ b/packages/cli/src/commands/docs.ts
@@ -43,6 +43,10 @@ const TOPICS: Record = {
file: "compositions.md",
description: "Composition structure, nesting, and variables",
},
+ "motion-blur": {
+ file: "motion-blur.md",
+ description: "Shutter smear on fast movers: attributes, tiers, checks",
+ },
};
function docsDir(): string {
diff --git a/packages/cli/src/commands/events.ts b/packages/cli/src/commands/events.ts
index 37d68790f9..a381f7f043 100644
--- a/packages/cli/src/commands/events.ts
+++ b/packages/cli/src/commands/events.ts
@@ -23,7 +23,7 @@ export default defineCommand({
meta: {
name: "events",
description:
- "Emit an anonymous skill-usage telemetry event (skills report their own invocation/outcome). Honors DO_NOT_TRACK / telemetry opt-out.",
+ "Emit a skill-usage telemetry event (skills report their own invocation/outcome). Honors DO_NOT_TRACK / telemetry opt-out.",
},
args: {
skill: {
diff --git a/packages/cli/src/commands/feedback.telemetryJoinKeys.test.ts b/packages/cli/src/commands/feedback.telemetryJoinKeys.test.ts
index 069fb2310f..4a60962e61 100644
--- a/packages/cli/src/commands/feedback.telemetryJoinKeys.test.ts
+++ b/packages/cli/src/commands/feedback.telemetryJoinKeys.test.ts
@@ -22,6 +22,43 @@ describe("buildTelemetryJoinKeys", () => {
expect(keys).toBe("fid=f tid=t renders=render-a,render-b!");
});
+ it("names the last check's exit code and top error codes", () => {
+ const keys = buildTelemetryJoinKeys({
+ feedbackId: "f",
+ anonymousId: "t",
+ lastCheck: { at: "", exitCode: 1, codes: { text_overlap: 4, contrast_low: 1 } },
+ });
+ expect(keys).toBe("fid=f tid=t check=exit1:text_overlap*4,contrast_low*1");
+ });
+
+ it("says unfinished when the last check never reported an exit code", () => {
+ const keys = buildTelemetryJoinKeys({
+ feedbackId: "f",
+ anonymousId: "t",
+ lastCheck: { at: "", codes: {} },
+ });
+ expect(keys).toBe("fid=f tid=t check=unfinished");
+ });
+
+ it("says how many minutes ago the last check ran, so one from another project is spotted", () => {
+ const keys = buildTelemetryJoinKeys({
+ feedbackId: "f",
+ anonymousId: "t",
+ lastCheck: { at: "2026-10-29T10:00:00.000Z", exitCode: 1, codes: { text_overlap: 4 } },
+ now: Date.parse("2026-10-29T10:12:30.000Z"),
+ });
+ expect(keys).toBe("fid=f tid=t check=exit1:text_overlap*4 check_age=13m");
+ });
+
+ it("says only the exit code when the last check had no error codes", () => {
+ const keys = buildTelemetryJoinKeys({
+ feedbackId: "f",
+ anonymousId: "t",
+ lastCheck: { at: "", exitCode: 0, codes: {} },
+ });
+ expect(keys).toBe("fid=f tid=t check=exit0");
+ });
+
it("stays within the backend env cap for a full ring of uuid render ids", () => {
const uuid = "01234567-89ab-cdef-0123-456789abcdef";
const keys = buildTelemetryJoinKeys({
@@ -36,4 +73,20 @@ describe("buildTelemetryJoinKeys", () => {
// submitFeedback caps env at 500 chars; the doctor summary consumes ~100.
expect(keys.length).toBeLessThan(400);
});
+
+ it("still fits the env cap with a full ring and three long error codes", () => {
+ const uuid = "01234567-89ab-cdef-0123-456789abcdef";
+ const code = "x".repeat(60);
+ const keys = buildTelemetryJoinKeys({
+ feedbackId: uuid,
+ anonymousId: uuid,
+ recentRenders: Array.from({ length: 5 }, () => ({ id: uuid, at: "", ok: true })),
+ lastCheck: {
+ at: "",
+ exitCode: 1,
+ codes: { [code + "a"]: 9, [code + "b"]: 8, [code + "c"]: 7 },
+ },
+ });
+ expect(keys.length).toBeLessThan(500 - 100);
+ });
});
diff --git a/packages/cli/src/commands/feedback.ts b/packages/cli/src/commands/feedback.ts
index ac4f166000..cf29c43c6e 100644
--- a/packages/cli/src/commands/feedback.ts
+++ b/packages/cli/src/commands/feedback.ts
@@ -12,7 +12,7 @@ import {
} from "../telemetry/events.js";
import { shouldTrack } from "../telemetry/client.js";
import { getDoctorSummary } from "../telemetry/feedback.js";
-import { readConfig, type RecentRenderRecord } from "../telemetry/config.js";
+import { readConfig, type LastCheckRecord, type RecentRenderRecord } from "../telemetry/config.js";
import { publishProjectArchive } from "../utils/publishProject.js";
import { submitCatalogSearchMiss, submitFeedback } from "../utils/submitFeedback.js";
import { buildIssueUrl, HYPERFRAMES_REPO_URL } from "../utils/feedbackIssue.js";
@@ -57,11 +57,25 @@ export function buildTelemetryJoinKeys(input: {
feedbackId: string;
anonymousId: string;
recentRenders?: RecentRenderRecord[];
+ lastCheck?: LastCheckRecord;
+ now?: number;
}): string {
const parts = [`fid=${input.feedbackId}`, `tid=${input.anonymousId}`];
if (input.recentRenders?.length) {
parts.push(`renders=${input.recentRenders.map((r) => `${r.id}${r.ok ? "" : "!"}`).join(",")}`);
}
+ if (input.lastCheck) {
+ const codes = Object.entries(input.lastCheck.codes).map(
+ ([code, n]) => `${code.slice(0, 24)}*${n}`,
+ );
+ const result =
+ input.lastCheck.exitCode === undefined ? "unfinished" : `exit${input.lastCheck.exitCode}`;
+ parts.push(`check=${result}${codes.length ? `:${codes.join(",")}` : ""}`);
+ const minutes = Math.round(
+ ((input.now ?? Date.now()) - Date.parse(input.lastCheck.at)) / 60_000,
+ );
+ if (Number.isFinite(minutes) && minutes >= 0) parts.push(`check_age=${minutes}m`);
+ }
return parts.join(" ");
}
@@ -298,6 +312,7 @@ export default defineCommand({
feedbackId,
anonymousId: config.anonymousId,
recentRenders: config.recentRenders,
+ lastCheck: config.lastCheck,
});
const envWithJoinKeys = doctorSummary ? `${doctorSummary} ${joinKeys}` : joinKeys;
diff --git a/packages/cli/src/commands/grade-compare.test.ts b/packages/cli/src/commands/grade-compare.test.ts
index bb94c7b00e..6aa63a4d4f 100644
--- a/packages/cli/src/commands/grade-compare.test.ts
+++ b/packages/cli/src/commands/grade-compare.test.ts
@@ -57,6 +57,22 @@ describe("parseGradesFile", () => {
}
});
+ it("parses a grades file saved with a UTF-8 BOM", () => {
+ const dir = tempDir();
+ try {
+ const file = join(dir, "grades.json");
+ writeFileSync(
+ file,
+ `\uFEFF${JSON.stringify([{ label: "warm", grading: { preset: "warm-daylight" } }])}`,
+ );
+ expect(parseGradesFile(file)).toEqual([
+ { label: "warm", grading: { preset: "warm-daylight" } },
+ ]);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
it("errors clearly for missing or invalid grades files", () => {
const dir = tempDir();
try {
diff --git a/packages/cli/src/commands/grade-compare.ts b/packages/cli/src/commands/grade-compare.ts
index f67956f83f..258b7d67c8 100644
--- a/packages/cli/src/commands/grade-compare.ts
+++ b/packages/cli/src/commands/grade-compare.ts
@@ -7,6 +7,7 @@ import {
rmSync,
writeFileSync,
} from "node:fs";
+import { readJsonFileText } from "../utils/jsonFlag.js";
import { tmpdir } from "node:os";
import { basename, dirname, extname, join, resolve } from "node:path";
import {
@@ -214,7 +215,7 @@ export function parseGradesFile(filePath: string): GradeCompareCell[] {
let parsed: unknown;
try {
- parsed = JSON.parse(readFileSync(filePath, "utf-8"));
+ parsed = JSON.parse(readJsonFileText(filePath));
} catch (err) {
throw new Error(`Could not parse grades JSON: ${normalizeErrorMessage(err)}`);
}
diff --git a/packages/cli/src/commands/history.test.ts b/packages/cli/src/commands/history.test.ts
index ea9f0978a0..dbf116276c 100644
--- a/packages/cli/src/commands/history.test.ts
+++ b/packages/cli/src/commands/history.test.ts
@@ -263,6 +263,25 @@ describe.each(["direct", "preview"])("hyperframes history (%s)", (mode) => {
expect(diff).toMatch(/-A\n\\ No newline at end of file\n\+A2/);
});
+ it("--diff names a video it never keeps, one line, and still shows the page's change", async () => {
+ const { hf, json, write } = await setup();
+ await hf("begin", "--who", "claude", "--label", "Import clip");
+ write("clip.mp4", "video bytes the history only hashes");
+ write("index.html", "A2");
+ const { entry } = await json("end");
+
+ const shown = await hf("show", entry.id, "--diff");
+
+ expect(shown.code, shown.err).toBe(0);
+ expect(shown.out).toContain("Media clip.mp4 changed, not kept in history");
+ expect(shown.out).toMatch(/-A\n\\ No newline at end of file\n\+A2/);
+ const peeked = await hf("peek", entry.id, "clip.mp4");
+ expect([peeked.code, peeked.err]).toEqual([
+ 2,
+ "clip.mp4 is video or audio: the history keeps that it changed, not its bytes",
+ ]);
+ });
+
it.each([false, true])("shows a large text diff completely (json=%s)", async (json) => {
const { hf, turn } = await setup();
const before = `before-${"a".repeat(600_000)}-end-before\n`;
diff --git a/packages/cli/src/commands/history.ts b/packages/cli/src/commands/history.ts
index 806f5c8480..aecc626a6b 100644
--- a/packages/cli/src/commands/history.ts
+++ b/packages/cli/src/commands/history.ts
@@ -5,6 +5,7 @@ import {
HistoryBusyError,
HistoryIdError,
HistoryRefusedError,
+ isUncopiedMedia,
type HistoryEntry,
type HistoryListItem,
type HistoryResult,
@@ -196,6 +197,10 @@ function print(json: boolean, data: object, text: string): void {
async function textDiff(reader: Reader, entry: HistoryEntry): Promise {
const out: string[] = [];
for (const file of entry.files) {
+ if (isUncopiedMedia(file.path)) {
+ out.push(`Media ${file.path} changed, not kept in history`);
+ continue;
+ }
const sides = await Promise.all(
[file.before, file.after].map((hash) => (hash ? reader.blob(hash) : Buffer.alloc(0))),
);
@@ -451,6 +456,10 @@ export default defineCommand({
if (!args.path) return print(args.json, { files }, Object.keys(files).join("\n"));
const hash = files[args.path];
if (!hash) throw new Refusal(`${args.path} did not exist then`);
+ if (isUncopiedMedia(args.path))
+ throw new Refusal(
+ `${args.path} is video or audio: the history keeps that it changed, not its bytes`,
+ );
process.stdout.write(await reader.blob(hash));
}),
),
diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts
index 243d6466da..0b0ff7797b 100644
--- a/packages/cli/src/commands/init.ts
+++ b/packages/cli/src/commands/init.ts
@@ -790,7 +790,7 @@ export default defineCommand({
description:
"Owning authoring skill slug (e.g. hyperframes). Stamped into " +
"hyperframes.json so every render of this project is attributed to it on " +
- "anonymous telemetry, without re-passing --skill on each render. Ignored unless it is a slug.",
+ "usage telemetry, without re-passing --skill on each render. Ignored unless it is a slug.",
},
},
async run({ args }) {
diff --git a/packages/cli/src/commands/lambda/policies.test.ts b/packages/cli/src/commands/lambda/policies.test.ts
index 309e40c7be..8566efe259 100644
--- a/packages/cli/src/commands/lambda/policies.test.ts
+++ b/packages/cli/src/commands/lambda/policies.test.ts
@@ -85,6 +85,12 @@ describe("policies — validatePolicy", () => {
expect(result.granted).toEqual(allRequiredActions());
});
+ it("reads a policy saved with a UTF-8 BOM", () => {
+ const path = join(workdir, "bom-policy.json");
+ writeFileSync(path, `\uFEFF${JSON.stringify({ Version: "2012-10-17", Statement: [] })}`);
+ expect(validatePolicy(path).granted).toEqual([]);
+ });
+
it("reports specific missing actions", () => {
const path = writePolicy({
Version: "2012-10-17",
diff --git a/packages/cli/src/commands/lambda/policies.ts b/packages/cli/src/commands/lambda/policies.ts
index 89dc212098..b6599ddd11 100644
--- a/packages/cli/src/commands/lambda/policies.ts
+++ b/packages/cli/src/commands/lambda/policies.ts
@@ -21,7 +21,7 @@ import { CliUsageError, failUsage, setCommandExitCode } from "../../utils/comman
* checked-in policy still covers the CLI's needs with `policies validate`.
*/
-import { readFileSync } from "node:fs";
+import { readJsonFileText } from "../../utils/jsonFlag.js";
import { c } from "../../ui/colors.js";
import { failureMessage, jsonFailure } from "../../utils/jsonError.js";
@@ -334,7 +334,7 @@ export interface ValidateResult {
* not by our matcher. We end-anchor only.
*/
export function validatePolicy(policyPath: string): ValidateResult {
- const raw = readFileSync(policyPath, "utf-8");
+ const raw = readJsonFileText(policyPath);
const parsed = JSON.parse(raw) as { Statement?: unknown };
const statements: Array<{
Effect?: string;
diff --git a/packages/cli/src/commands/layout-audit.browser.js b/packages/cli/src/commands/layout-audit.browser.js
index e26425dbeb..7ab3687d6f 100644
--- a/packages/cli/src/commands/layout-audit.browser.js
+++ b/packages/cli/src/commands/layout-audit.browser.js
@@ -1303,10 +1303,25 @@
}
}
- function isOpaqueOccluder(element, x, y) {
+ // A mask changes painting, not hit-testing, and its alpha is not modelled: a masked layer is never proven opaque.
+ // A mask on an ancestor of both the layer and `covered` masks them alike, so the walk stops there.
+ function hasMaskImage(layer, covered) {
+ for (
+ let current = layer;
+ current && !current.contains(covered);
+ current = current.parentElement
+ ) {
+ const style = getComputedStyle(current);
+ if ((style.maskImage || style.webkitMaskImage || "none") !== "none") return true;
+ }
+ return false;
+ }
+
+ function isOpaqueOccluder(element, x, y, covered) {
const opacity = opacityChain(element);
if (opacity < OCCLUDING_ALPHA) return false;
if (IGNORE_TAGS.has(element.tagName)) return false;
+ if (hasMaskImage(element, covered)) return false;
if (element.tagName === "IMG") {
const alpha = imageAlphaAt(element, x, y);
if (alpha !== null) return alpha * opacity >= OCCLUDING_ALPHA;
@@ -1362,6 +1377,12 @@
return !!ctx && ctx === preserve3dContext(b);
}
+ // A covering element marked to cover text, or inside a marked wrapper that does not also hold the text.
+ function allowsOcclusionOf(hit, element) {
+ const allowed = authoredElement(hit).closest("[data-layout-allow-occlusion]");
+ return !!allowed && !allowed.contains(element);
+ }
+
// The opaque element painted over (x, y), or null when the topmost element
// there is related to the text, non-opaque, sharing a 3D context with it, or
// part of a transient crossfade overlap.
@@ -1377,12 +1398,12 @@
for (const hit of stack) {
if (!isForeignElement(element, hit)) return null;
// Pair-specific exemptions excuse this hit only; keep walking for deeper occluders.
- if (hasIgnoreFlag(hit)) continue;
+ if (hasIgnoreFlag(hit) || allowsOcclusionOf(hit, element)) continue;
if (sharedPreserve3d(element, hit)) continue;
if (isCrossSceneTransitionOverlap(element, hit)) continue;
const matte = seenMattes && matteFrameFor(hit);
if (matte && !seenMattes.has(matte)) seenMattes.set(matte, hit);
- if (isOpaqueOccluder(hit, x, y)) return hit;
+ if (isOpaqueOccluder(hit, x, y, element)) return hit;
}
return null;
}
@@ -1599,6 +1620,48 @@
return false;
}
+ const COMPOSITION_HOST = "[data-composition-src], [data-composition-id], [data-composition-file]";
+
+ // The global window [start, end) the element's own timed clip is on screen, or null when any timing
+ // up the chain is not a plain number. Each timed composition host moves its children's clock to its
+ // start minus its in-point, and an in-point host cuts them to its own slot (startResolver.ts).
+ function nonNegativeNumber(value) {
+ const number = value === null || value.trim() === "" ? NaN : Number(value);
+ return Number.isFinite(number) && number >= 0 ? number : null;
+ }
+
+ function clipLifetime(element) {
+ const own = element.closest("[data-start]");
+ if (!own) return null;
+ const start = Number(own.getAttribute("data-start"));
+ const duration = Number(own.getAttribute("data-duration"));
+ if (!Number.isFinite(start) || !(duration > 0)) return null;
+ const hosts = [];
+ for (let host = own.parentElement; host; host = host.parentElement) {
+ if (host.matches(COMPOSITION_HOST) && host.hasAttribute("data-start")) hosts.unshift(host);
+ }
+ let offset = 0;
+ let cutStart = -Infinity;
+ let cutEnd = Infinity;
+ for (const host of hosts) {
+ const hostStart = Number(host.getAttribute("data-start"));
+ if (!Number.isFinite(hostStart)) return null;
+ const inPoint =
+ nonNegativeNumber(host.getAttribute("data-playback-start")) ??
+ nonNegativeNumber(host.getAttribute("data-media-start")) ??
+ 0;
+ if (inPoint > 0) {
+ const hostEnd = Number(host.getAttribute("data-end"));
+ const hostDuration = Number(host.getAttribute("data-duration")) || hostEnd - hostStart;
+ cutStart = Math.max(cutStart, offset + hostStart);
+ if (hostDuration > 0) cutEnd = Math.min(cutEnd, offset + hostStart + hostDuration);
+ }
+ offset += hostStart - inPoint;
+ }
+ const from = Math.max(start + offset, cutStart);
+ return { start: from, end: Math.max(from, Math.min(start + duration + offset, cutEnd)) };
+ }
+
// text_occluded: atomic labels flag at any hit; prose needs coveredFraction >= proseCoverageFloor (default 0.15).
function occludedTextIssue(element, time, proseCoverageFloor, matteResults) {
if (hasAllowOcclusionFlag(element)) return null;
@@ -1702,8 +1765,10 @@
)
continue;
// Last: an opaque check reads a video's frame, which a backdrop under its content never needs.
+ const matte = matteFrameFor(cover);
+ if (matte && matteCoverage([rootRect], [matte]) < COVER_CANVAS_SHARE) continue;
const rect = toRect(cover.getBoundingClientRect());
- if (!isOpaqueOccluder(cover, rect.left + rect.width / 2, rect.top + rect.height / 2))
+ if (!isOpaqueOccluder(cover, rect.left + rect.width / 2, rect.top + rect.height / 2, root))
continue;
return {
code: "canvas_covered",
@@ -2544,7 +2609,11 @@
if (clipped) issues.push(clipped);
issues.push(...textOverflowIssues(element, root, rootRect, time, tolerance, clipped));
const occluded = occludedTextIssue(element, time, proseCoverageFloor, matteResults);
- if (occluded) issues.push(occluded);
+ if (occluded) {
+ const lifetime = clipLifetime(element);
+ if (lifetime) occluded.lifetime = lifetime;
+ issues.push(occluded);
+ }
const invisible = invisibleTextIssue(element, time);
if (invisible) issues.push(invisible);
}
@@ -2710,6 +2779,7 @@
...craftAnchor(element),
blockSelector: craftAnchor(block).selector,
text: textContentFor(element, true),
+ blockText: textContentFor(block, false),
opacity: round(opacityChain(element)),
fontPx: round(renderedFontPx(element, getComputedStyle(element))),
rect: { left: rect.left, top: rect.top, width: rect.width, height: rect.height },
diff --git a/packages/cli/src/commands/layout-audit.browser.test.ts b/packages/cli/src/commands/layout-audit.browser.test.ts
index 0f7f20a69e..d0099f0d4a 100644
--- a/packages/cli/src/commands/layout-audit.browser.test.ts
+++ b/packages/cli/src/commands/layout-audit.browser.test.ts
@@ -3262,6 +3262,55 @@ describe("layout-audit.browser occlusion", () => {
);
});
+ it("lets data-layout-allow-occlusion on the covering element silence text_occluded", () => {
+ const issues = (overlayAttrs?: string) =>
+ auditOcclusionScene({
+ overlayAttrs,
+ overlayStyle: { backgroundColor: "rgb(10, 10, 10)" },
+ topmostId: "overlay",
+ });
+
+ expect(issues().some((issue) => issue.code === "text_occluded")).toBe(true);
+ expect(
+ issues("data-layout-allow-occlusion").some((issue) => issue.code === "text_occluded"),
+ ).toBe(false);
+ });
+
+ it("honours the flag on a graded video whose topmost element is its canvas stand-in", () => {
+ document.body.innerHTML = `
+
+ `;
+ installOcclusionGeometry({
+ styleOverrides: { overlay: { backgroundColor: "rgb(10, 10, 10)" } },
+ headlineTextRect: rect({ left: 200, top: 500, width: 600, height: 80 }),
+ topmostId: "overlay",
+ });
+ installAuditScript();
+ expect(runAudit().some((issue) => issue.code === "text_occluded")).toBe(false);
+ });
+
+ it("still flags a cover inside a flagged wrapper that also holds the text", () => {
+ document.body.innerHTML = `
+
+ `;
+ installOcclusionGeometry({
+ styleOverrides: { overlay: { backgroundColor: "rgb(10, 10, 10)" } },
+ headlineTextRect: rect({ left: 200, top: 500, width: 600, height: 80 }),
+ topmostId: "overlay",
+ });
+ installAuditScript();
+ expect(runAudit().some((issue) => issue.code === "text_occluded")).toBe(true);
+ });
+
it("respects the data-layout-allow-occlusion opt-out", () => {
const issues = auditOcclusionScene({
headlineAttrs: "data-layout-allow-occlusion",
diff --git a/packages/cli/src/commands/layout-audit.chromium.test.ts b/packages/cli/src/commands/layout-audit.chromium.test.ts
index a670a030e1..29053d09c5 100644
--- a/packages/cli/src/commands/layout-audit.chromium.test.ts
+++ b/packages/cli/src/commands/layout-audit.chromium.test.ts
@@ -295,6 +295,20 @@ describe.runIf(executablePath)("layout audit in Chromium", () => {
expect(codes).toContain("text_not_painted");
});
+ it("does not call text occluded by a cover that a CSS mask paints through", async () => {
+ const cover = (style: string) =>
+ `
`;
+ const maskedAway = "mask-image:linear-gradient(transparent,transparent)";
+ const text = heading(300, "Seen through");
+ expect(await auditCodes(stage(text + cover("")))).toContain("text_occluded");
+ expect(await auditCodes(stage(text + cover(maskedAway)))).not.toContain("text_occluded");
+ const wrapped = `${cover("")}
`;
+ expect(await auditCodes(stage(text + wrapped))).not.toContain("text_occluded");
+ const fade = "mask-image:linear-gradient(black,black)";
+ const sharedMask = `${text}${cover("")}
`;
+ expect(await auditCodes(stage(sharedMask))).toContain("text_occluded");
+ });
+
it("reports text positioned outside the ancestor background", async () => {
const codes = await auditCodes(
gradientHeading('Gradient text '),
diff --git a/packages/cli/src/commands/layout-audit.video-alpha.browser.test.ts b/packages/cli/src/commands/layout-audit.video-alpha.browser.test.ts
index 16a601b76f..552319ac83 100644
--- a/packages/cli/src/commands/layout-audit.video-alpha.browser.test.ts
+++ b/packages/cli/src/commands/layout-audit.video-alpha.browser.test.ts
@@ -43,6 +43,10 @@ interface VideoScene {
/** Report each element's text as one line box, as Chromium does, rather than one per word. */
wholeLine?: boolean;
textAttrs?: string;
+ /** Size each text element to its first word's box instead of the whole frame. */
+ sizedText?: boolean;
+ /** Attributes on the timed wrapper around the text. */
+ lineAttrs?: string;
}
function domRect({ left, top, width, height }: Box): DOMRect {
@@ -88,7 +92,7 @@ function installVideoScene(scene: VideoScene): { getImageData: ReturnType
- ${spans}
+ ${spans}
`;
@@ -111,6 +115,18 @@ function installVideoScene(scene: VideoScene): { getImageData: ReturnType
{
const owner = node?.parentElement?.id ?? "";
const word = (node?.textContent ?? "").slice(start, end);
@@ -202,6 +218,8 @@ function runAudit(): AuditIssue[] {
const occlusionOf = (issues: AuditIssue[], id: string) =>
issues.find((issue) => issue.code === "text_occluded" && issue.selector === `#${id}`);
+const coverOf = (issues: AuditIssue[]) => issues.find((issue) => issue.code === "canvas_covered");
+
const SHIP = { ship: [{ word: "SHIP", left: 800, width: 200 }] };
const subjectLeftOf = (edge: number) => (x: number) => (x < edge ? 255 : 0);
@@ -213,6 +231,55 @@ describe("layout-audit.browser text behind a ", () => {
Reflect.deleteProperty(window, "__hyperframesLayoutAudit");
});
+ it("does not call a cutout that is mostly transparent a cover of the canvas", () => {
+ installVideoScene({
+ text: SHIP,
+ sizedText: true,
+ alphaAt: (x) => (x >= 640 && x < 1280 ? 255 : 0),
+ });
+ expect(coverOf(runAudit())).toBeUndefined();
+ });
+
+ it("still calls a fully opaque frame over buried content a cover of the canvas", () => {
+ installVideoScene({ text: SHIP, sizedText: true });
+ expect(coverOf(runAudit())).toMatchObject({ severity: "error", selector: "#clip" });
+ });
+
+ it("reports the word's own clip window, shifted only by composition hosts", () => {
+ installVideoScene({
+ text: SHIP,
+ textAttrs: 'data-start="2.4" data-duration="0.4"',
+ lineAttrs: 'data-start="2" data-duration="5"',
+ });
+ expect(occlusionOf(runAudit(), "ship")).toMatchObject({
+ lifetime: { start: 2.4, end: 2.8 },
+ });
+ });
+
+ it("shifts the window by an anonymous host and its in-point, and cuts it to the host slot", () => {
+ installVideoScene({
+ text: SHIP,
+ textAttrs: 'data-start="0.2" data-duration="1"',
+ lineAttrs:
+ 'data-composition-src="beat.html" data-start="2" data-media-start="0.5" data-duration="3"',
+ });
+ expect(occlusionOf(runAudit(), "ship")).toMatchObject({
+ lifetime: { start: 2, end: 2.7 },
+ });
+ });
+
+ it("reads an invalid playback-start as absent and cuts to a host that ends with data-end", () => {
+ installVideoScene({
+ text: SHIP,
+ textAttrs: 'data-start="0.2" data-duration="5"',
+ lineAttrs:
+ 'data-composition-src="beat.html" data-start="2" data-playback-start="-1" data-media-start="0.5" data-end="3"',
+ });
+ expect(occlusionOf(runAudit(), "ship")).toMatchObject({
+ lifetime: { start: 2, end: 3 },
+ });
+ });
+
it("keeps a fully opaque frame occluding like any raster", () => {
installVideoScene({ text: SHIP });
expect(occlusionOf(runAudit(), "ship")).toMatchObject({
diff --git a/packages/cli/src/commands/layout.ts b/packages/cli/src/commands/layout.ts
index 352290d144..fbfb63b2fc 100644
--- a/packages/cli/src/commands/layout.ts
+++ b/packages/cli/src/commands/layout.ts
@@ -544,7 +544,7 @@ export function createInspectCommand(commandName: "inspect" | "layout") {
);
}
const allIssues = collapseStatic
- ? collapseStaticLayoutIssues(result.rawIssues, result.samples.length)
+ ? collapseStaticLayoutIssues(result.rawIssues, result.samples.length, result.samples)
: result.rawIssues;
const limited = limitLayoutIssues(allIssues, maxIssues);
const summary = summarizeLayoutIssues(allIssues);
diff --git a/packages/cli/src/commands/measure.ts b/packages/cli/src/commands/measure.ts
new file mode 100644
index 0000000000..586c6a9284
--- /dev/null
+++ b/packages/cli/src/commands/measure.ts
@@ -0,0 +1,34 @@
+import { defineCommand } from "../utils/defineCommand.js";
+import type { Example } from "./_examples.js";
+
+export const examples: Example[] = [
+ [
+ "Size, frame rate and what to fix before rebuilding a video",
+ "hyperframes measure probe ref.mp4",
+ ],
+ [
+ "Everything that changes when, with the sound's hits",
+ "hyperframes measure events ref.mp4 --map",
+ ],
+ ["The frames around every event, as strips", "hyperframes measure frames ref.mp4 --events"],
+];
+
+export default defineCommand({
+ meta: {
+ name: "measure",
+ description:
+ "Measure a video file as JSON: clock, cuts, events, frames, crops, eases, motion energy, look, faces, lip sync",
+ },
+ subCommands: {
+ probe: () => import("./measure/probe.js").then((m) => m.default),
+ cuts: () => import("./measure/cuts.js").then((m) => m.default),
+ events: () => import("./measure/events.js").then((m) => m.default),
+ frames: () => import("./measure/frames.js").then((m) => m.default),
+ extract: () => import("./measure/extract.js").then((m) => m.default),
+ curve: () => import("./measure/curve.js").then((m) => m.default),
+ energy: () => import("./measure/energy.js").then((m) => m.default),
+ look: () => import("./measure/look.js").then((m) => m.default),
+ face: () => import("./measure/face.js").then((m) => m.default),
+ sync: () => import("./measure/sync.js").then((m) => m.default),
+ },
+});
diff --git a/packages/cli/src/commands/measure/curve.ts b/packages/cli/src/commands/measure/curve.ts
new file mode 100644
index 0000000000..b0aebf4d87
--- /dev/null
+++ b/packages/cli/src/commands/measure/curve.ts
@@ -0,0 +1,84 @@
+import { defineCommand } from "../../utils/defineCommand.js";
+import type { Example } from "../_examples.js";
+import {
+ compareWindowArgs,
+ jsonArg,
+ num,
+ roiArg,
+ runMeasure,
+ videoAndRoi,
+ videoArg,
+ window,
+} from "../../measure/command.js";
+import { compareCurves, curves, printable } from "../../measure/curve.js";
+import { Fix, parseRoi, probeVideo } from "../../measure/media.js";
+
+export const examples: Example[] = [
+ [
+ "The ease, duration and overshoot of one element's move",
+ "hyperframes measure curve original.mp4 --start 2.1 --end 3 --roi 240,280,600,540",
+ ],
+ [
+ "The same move in your render, paired with the original's",
+ "hyperframes measure curve original.mp4 --start 2.1 --end 3 --roi 240,280,600,540 --compare renders/final.mp4 --compare-start 2.1",
+ ],
+];
+
+/** "#rrggbb" as RGB. */
+function hex(text: string): number[] {
+ const m = /^#?([0-9a-f]{6})$/i.exec(text);
+ if (!m) throw new Fix(`--bg must be #rrggbb, got "${text}"`, "--bg #101820");
+ return [0, 2, 4].map((i) => parseInt(m[1]!.slice(i, i + 2), 16));
+}
+
+export default defineCommand({
+ meta: {
+ name: "curve",
+ description:
+ "Each move of one element on a flat background: start, duration, overshoot and the closest GSAP ease",
+ },
+ args: {
+ video: videoArg,
+ start: { type: "string", description: "Window start in seconds (default 0)" },
+ end: { type: "string", description: "Window end in seconds (default: the end)" },
+ roi: {
+ ...roiArg,
+ description: "Region holding the whole move, overshoot included, and nothing else that moves",
+ },
+ bg: { type: "string", description: "Background #rrggbb (default: the ROI border's median)" },
+ thr: {
+ type: "string",
+ description: "Pixel distance from the background that counts as the element (24)",
+ },
+ compare: {
+ type: "string",
+ description: "A second video (your render) to measure the same way",
+ },
+ ...compareWindowArgs,
+ json: jsonArg,
+ },
+ run: ({ args }) =>
+ runMeasure(() => {
+ const { info, roi } = videoAndRoi(args.video, args.roi);
+ const [start, end] = window(info, args.start, args.end);
+ const opts = { bg: args.bg ? hex(args.bg) : null, thr: num(args.thr, "--thr", 24) };
+ const ref = curves(info.path, start, end - start, roi, opts);
+ if (!args.compare) return { video: info.path, ...ref, moves: printable(ref.moves) };
+ const other = probeVideo(args.compare);
+ const yoursRoi = args["compare-roi"]
+ ? parseRoi(args["compare-roi"], other.width, other.height)
+ : roi;
+ const yours = curves(
+ other.path,
+ num(args["compare-start"], "--compare-start", start),
+ end - start,
+ yoursRoi,
+ opts,
+ );
+ return {
+ compare: compareCurves(ref, yours),
+ reference: printable(ref.moves),
+ yours: printable(yours.moves),
+ };
+ }),
+});
diff --git a/packages/cli/src/commands/measure/cuts.ts b/packages/cli/src/commands/measure/cuts.ts
new file mode 100644
index 0000000000..53ac6747f8
--- /dev/null
+++ b/packages/cli/src/commands/measure/cuts.ts
@@ -0,0 +1,52 @@
+import { defineCommand } from "../../utils/defineCommand.js";
+import type { Example } from "../_examples.js";
+import { jsonArg, runMeasure, videoArg, window } from "../../measure/command.js";
+import { findCuts, signatures } from "../../measure/cuts.js";
+import { probeVideo, round, videoClip } from "../../measure/media.js";
+
+export const examples: Example[] = [
+ ["Every hard cut and the shots between them", "hyperframes measure cuts ref.mp4"],
+ ["Cuts in the first 20 seconds", "hyperframes measure cuts ref.mp4 --start 0 --end 20"],
+];
+
+export default defineCommand({
+ meta: {
+ name: "cuts",
+ description:
+ "Hard cuts from the frame-to-frame difference (scene scores miss some), and the shots between them",
+ },
+ args: {
+ video: videoArg,
+ start: { type: "string", description: "First second to read (default 0)" },
+ end: { type: "string", description: "Last second to read (default: the end)" },
+ json: jsonArg,
+ },
+ async run({ args }) {
+ await runMeasure(() => {
+ const info = probeVideo(String(args.video));
+ const [start, end] = window(info, args.start, args.end);
+ const clip = videoClip(info.path, start, end - start, info);
+ const found = findCuts(signatures(clip.input, clip.filters).frames);
+ const f0 = Math.ceil(start * info.fps - 1e-6);
+ const cuts = found.map((c) => ({
+ t: round((f0 + c.frame) / info.fps, 3),
+ frame: f0 + c.frame,
+ ...(c.frames > 1 ? { frames: c.frames } : {}),
+ change: round(c.change, 1),
+ }));
+ const edges = [start, ...cuts.map((c) => c.t), end];
+ return {
+ video: info.path,
+ start,
+ end: round(end, 3),
+ fps: round(info.fps, 3),
+ cuts,
+ shots: edges.slice(1).map((e, i) => ({
+ start: round(edges[i]!, 3),
+ end: round(e, 3),
+ seconds: round(e - edges[i]!, 2),
+ })),
+ };
+ });
+ },
+});
diff --git a/packages/cli/src/commands/measure/energy.ts b/packages/cli/src/commands/measure/energy.ts
new file mode 100644
index 0000000000..681b1f10a7
--- /dev/null
+++ b/packages/cli/src/commands/measure/energy.ts
@@ -0,0 +1,66 @@
+import { defineCommand } from "../../utils/defineCommand.js";
+import type { Example } from "../_examples.js";
+import { jsonArg, num, runMeasure } from "../../measure/command.js";
+import { compareEnergy, energyCurve } from "../../measure/energy.js";
+import { Fix, parseRoi, probeVideo, round, videoClip, type Roi } from "../../measure/media.js";
+
+export const examples: Example[] = [
+ [
+ "Does a regenerated shot move as much as the original's, and when",
+ "hyperframes measure energy ref.mp4 renders/v1.mp4 --start 4 --seconds 5",
+ ],
+];
+
+export default defineCommand({
+ meta: {
+ name: "energy",
+ description:
+ "How much two clips move, and whether they move at the same moments, when their pixels differ",
+ },
+ args: {
+ reference: { type: "positional", description: "The original", required: true },
+ yours: { type: "positional", description: "The other video", required: true },
+ start: { type: "string", description: "Second the window starts in the original (default 0)" },
+ "yours-start": { type: "string", description: "Second it starts in yours (default: --start)" },
+ seconds: { type: "string", description: "Window length (default: the rest of the original)" },
+ roi: { type: "string", description: "Region of the original, x,y,w,h" },
+ "yours-roi": {
+ type: "string",
+ description: "Region of yours (default: --roi scaled by the widths)",
+ },
+ json: jsonArg,
+ },
+ async run({ args }) {
+ await runMeasure(() => {
+ const [a, b] = [probeVideo(String(args.reference)), probeVideo(String(args.yours))];
+ const start = num(args.start, "--start", 0);
+ const yoursStart = num(args["yours-start"], "--yours-start", start);
+ const seconds = num(args.seconds, "--seconds", a.duration - start);
+ if (seconds <= 0.5) throw new Fix("the window is under half a second", "--seconds 2 or more");
+ const roi = args.roi === undefined ? undefined : parseRoi(args.roi, a.width, a.height);
+ const k = b.width / a.width;
+ const scaled = (r: Roi): Roi => [
+ Math.round(r[0] * k),
+ Math.round(r[1] * k),
+ Math.max(2, Math.round(r[2] * k)),
+ Math.max(2, Math.round(r[3] * k)),
+ ];
+ const yoursRoi =
+ args["yours-roi"] !== undefined
+ ? parseRoi(args["yours-roi"], b.width, b.height)
+ : roi && scaled(roi);
+ const r = compareEnergy(
+ energyCurve(videoClip(a.path, start, seconds, a), roi),
+ energyCurve(videoClip(b.path, yoursStart, seconds, b), yoursRoi),
+ );
+ return {
+ reference: a.path,
+ yours: b.path,
+ window_s: round(seconds, 3),
+ ...r,
+ reading:
+ "mean_ratio is how much yours moves (0.8–1.25 is the same amount); r near 1 at a small lag_s is the same action at the same time",
+ };
+ });
+ },
+});
diff --git a/packages/cli/src/commands/measure/events.ts b/packages/cli/src/commands/measure/events.ts
new file mode 100644
index 0000000000..fe51df471d
--- /dev/null
+++ b/packages/cli/src/commands/measure/events.ts
@@ -0,0 +1,190 @@
+import { writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { defineCommand } from "../../utils/defineCommand.js";
+import type { Example } from "../_examples.js";
+import {
+ jsonArg,
+ num,
+ outArg,
+ roiArg,
+ runMeasure,
+ videoAndRoi,
+ videoArg,
+ window,
+} from "../../measure/command.js";
+import {
+ countEvents,
+ detectEvents,
+ drawStrip,
+ lookWindows,
+ type ScreenEvent,
+} from "../../measure/events.js";
+import { Fix, outDir, round, type VideoInfo } from "../../measure/media.js";
+
+export const examples: Example[] = [
+ [
+ "The film's event map: cuts, flashes, what appears where, holds, and the sound's hits, grouped into windows to look at",
+ "hyperframes measure events ref.mp4 --map",
+ ],
+ [
+ "When one region changes, frame by frame",
+ "hyperframes measure events ref.mp4 --roi 0,800,1080,300 --start 2 --end 6",
+ ],
+];
+
+/** "6x10" as columns and rows. */
+function parseGrid(text: unknown): { cols: number; rows: number } {
+ const m = /^(\d+)x(\d+)$/.exec(String(text));
+ if (!m || Number(m[1]) < 1 || Number(m[2]) < 1)
+ throw new Fix(`--grid must be COLSxROWS, got "${String(text)}"`, "--grid 6x10");
+ return { cols: Number(m[1]), rows: Number(m[2]) };
+}
+
+const isRecord = (v: unknown): v is Record =>
+ typeof v === "object" && v !== null && !Array.isArray(v);
+const numbers = (v: unknown): number[] =>
+ Array.isArray(v) ? v.filter((x): x is number => typeof x === "number") : [];
+
+interface Sound {
+ bpm: number | null;
+ beats: number[];
+ onsets: { t: number; strength: number }[];
+}
+
+/** The sound's onsets, beats and tempo, measured on this machine. */
+async function soundOf(info: VideoInfo, start: number, end: number): Promise {
+ if (!info.audio) return null;
+ const { analyzeTargets, previewTarget } = await import("../../audio/analysis/run.js");
+ const report = await analyzeTargets([await previewTarget(info.path, info.path, null)], {
+ capabilities: ["onsets", "beats", "bpm"],
+ quality: "local",
+ });
+ const item = report.items[0];
+ if (!item) return null;
+ const inside = (t: number) => t >= start && t <= end;
+ const onsets =
+ isRecord(item.onsets) && Array.isArray(item.onsets.events) ? item.onsets.events : [];
+ return {
+ bpm: isRecord(item.bpm) && typeof item.bpm.value === "number" ? round(item.bpm.value, 1) : null,
+ beats: numbers(isRecord(item.beats) ? item.beats.times : undefined).filter(inside),
+ onsets: onsets
+ .filter(isRecord)
+ .flatMap((e) =>
+ typeof e.t === "number" && typeof e.strength === "number" && inside(e.t)
+ ? [{ t: e.t, strength: e.strength }]
+ : [],
+ ),
+ };
+}
+
+const LIST_MAX = 64;
+
+export default defineCommand({
+ meta: {
+ name: "events",
+ description:
+ "When things change on screen: cuts, flashes, appears, disappears, changes and holds; --map adds the sound and the windows worth looking at",
+ },
+ args: {
+ video: videoArg,
+ map: {
+ type: "boolean",
+ description:
+ "The whole window on a 4x4 grid with the sound's onsets and beats, grouped into windows to look at",
+ default: false,
+ },
+ roi: roiArg,
+ grid: {
+ type: "string",
+ description: "Split the frame into COLSxROWS cells, e.g. 6x10 (default with --map: 4x4)",
+ },
+ start: { type: "string", description: "First second (default 0)" },
+ end: { type: "string", description: "Last second (default: the end)" },
+ thr: {
+ type: "string",
+ description: "Mean grey-level change of an appear or a cut (default 5)",
+ },
+ out: outArg,
+ json: jsonArg,
+ },
+ async run({ args }) {
+ // fallow-ignore-next-line complexity
+ await runMeasure(async () => {
+ const { info, roi } = videoAndRoi(args.video, args.roi);
+ const [start, end] = window(info, args.start, args.end);
+ const grid =
+ args.grid !== undefined
+ ? parseGrid(args.grid)
+ : args.map && args.roi === undefined
+ ? { cols: 4, rows: 4 }
+ : undefined;
+ const thr = num(args.thr, "--thr", 5);
+ const found = detectEvents({ info, start, end, roi, grid, thr });
+ if (found.frames < 3)
+ throw new Fix(`under 3 frames between ${start}s and ${end}s`, "widen --start/--end");
+ const dir = outDir(args.out, "measure/events");
+ const name = `events-${start}-${round(end, 2)}s`;
+ const strip = found.shown.length ? drawStrip(found, join(dir, `${name}.png`)) : null;
+ const holds = found.events.filter((e) => e.type === "hold");
+ const head = {
+ video: info.path,
+ ...(grid ? { grid: `${grid.cols}x${grid.rows}` } : { roi }),
+ start,
+ end: round(end, 3),
+ fps: round(info.fps, 3),
+ };
+ if (!args.map) {
+ const lengths = holds.map((e) => e.seconds ?? 0).sort((a, b) => a - b);
+ return {
+ ...head,
+ frames: found.frames,
+ thr,
+ counts: countEvents(found.events),
+ holds: {
+ longest_s: lengths.at(-1) ?? 0,
+ median_s: lengths[(lengths.length - 1) >> 1] ?? 0,
+ count: lengths.length,
+ },
+ strip,
+ strip_events: `${found.shown.length} of ${found.events.length - holds.length} (cuts and flashes, then the largest steps, then changes)`,
+ events: found.events,
+ };
+ }
+ const sound = await soundOf(info, start, end);
+ const cuts = found.events.filter((e) => e.type === "cut").map((e) => e.t);
+ const edges = [start, ...cuts, end];
+ const windows = lookWindows(found.events, info.fps, sound?.onsets.map((o) => o.t) ?? []);
+ const file = join(dir, `${name}-map.json`);
+ writeFileSync(
+ file,
+ JSON.stringify({ ...head, events: found.events, sound, windows }, null, 1),
+ );
+ const strong = sound?.onsets.filter((o) => o.strength >= 0.5).map((o) => round(o.t, 3)) ?? [];
+ const longHolds = holds
+ .filter((e: ScreenEvent) => (e.seconds ?? 0) >= 0.5)
+ .map((e) => ({ t: e.t, seconds: e.seconds }));
+ return {
+ ...head,
+ duration: round(end - start, 3),
+ counts: countEvents(found.events),
+ shots: edges.slice(1).map((e, i) => ({ start: round(edges[i]!, 3), end: round(e, 3) })),
+ holds: longHolds,
+ sound: sound
+ ? {
+ bpm: sound.bpm,
+ beats: sound.beats.length,
+ ...(sound.beats.length
+ ? { beat_times: sound.beats.slice(0, LIST_MAX).map((t) => round(t, 3)) }
+ : {}),
+ onsets: sound.onsets.length,
+ strong_onsets: strong.slice(0, LIST_MAX),
+ }
+ : "none",
+ windows,
+ strip,
+ file,
+ next: "look at each window's frames: npx hyperframes measure frames --events",
+ };
+ });
+ },
+});
diff --git a/packages/cli/src/commands/measure/extract.ts b/packages/cli/src/commands/measure/extract.ts
new file mode 100644
index 0000000000..28f1ba5b75
--- /dev/null
+++ b/packages/cli/src/commands/measure/extract.ts
@@ -0,0 +1,274 @@
+// Pixels from the original, as project media: a still at one moment or a clip over a window, cropped to a region,
+// frame-exact, recorded in the media ledger as cut from the original. A rebuild reuses footage, photos and people
+// this way instead of drawing or generating them.
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join, relative, resolve } from "node:path";
+import { defineCommand } from "../../utils/defineCommand.js";
+import type { Example } from "../_examples.js";
+import { jsonArg, num, roiArg, runMeasure, videoAndRoi, videoArg } from "../../measure/command.js";
+import { Fix, frameAt, round, runFfmpeg, type Roi, type VideoInfo } from "../../measure/media.js";
+
+export const examples: Example[] = [
+ [
+ "A photo from the original at 3.2 s, cropped to its box",
+ "hyperframes measure extract original.mp4 --at 3.2 --roi 120,340,840,620 --out assets/photo.png",
+ ],
+ [
+ "The original's whole soundtrack",
+ "hyperframes measure extract original.mp4 --out assets/sound.m4a",
+ ],
+ [
+ "The talking head from 4.0 s to 9.5 s with its sound",
+ "hyperframes measure extract original.mp4 --from 4 --to 9.5 --roi 0,0,1080,1350 --audio --out assets/presenter.mp4",
+ ],
+];
+
+/** H.264 needs even sizes: shrink an odd width or height by a pixel. */
+const even = ([x, y, w, h]: Roi): Roi => [x, y, w - (w % 2), h - (h % 2)];
+
+/** The nearest folder at or above `from` holding index.html: the project the file belongs to. */
+function projectOf(from: string): string | null {
+ for (let dir = resolve(from); ; dir = dirname(dir)) {
+ if (existsSync(join(dir, "index.html"))) return dir;
+ if (dirname(dir) === dir) return null;
+ }
+}
+
+async function record(
+ out: string,
+ type: "image" | "video" | "bgm",
+ provenance: Record,
+ duration?: number,
+) {
+ const project = projectOf(dirname(out));
+ if (!project) return null;
+ const { recordInPlace } = await import("../../media-use/lib/manifest.mjs");
+ const { regenerateIndex } = await import("../../media-use/lib/index-gen.mjs");
+ const rel = (p: string) => relative(project, p).split("\\").join("/");
+ const path = rel(out);
+ const from = String(provenance.from);
+ if (!rel(from).startsWith("..")) provenance = { ...provenance, from: rel(from) };
+ const entry = recordInPlace(project, {
+ type,
+ path,
+ source: "extracted",
+ description: `cut from the original ${String(provenance.window ?? provenance.at)}`,
+ ...(duration !== undefined ? { duration } : {}),
+ provenance,
+ });
+ regenerateIndex(project);
+ return entry.id;
+}
+
+const crop = (roi: Roi) => `crop=${roi[2]}:${roi[3]}:${roi[0]}:${roi[1]}`;
+
+/** The frame shown at `at` seconds, cropped, as a picture. */
+export async function cutStill(info: VideoInfo, at: number, roi: Roi, out: string) {
+ const k = frameAt(at, info.fps);
+ const t = k / info.fps;
+ const { extractVideoFrameToBuffer } = await import("../snapshot.js");
+ const png = await extractVideoFrameToBuffer(info.path, t);
+ if (!png)
+ throw new Fix(`no frame at ${round(t, 3)}s`, `pick a time before ${round(info.duration, 2)}s`);
+ const work = mkdtempSync(join(tmpdir(), "hf-extract-"));
+ try {
+ const full = join(work, "frame.png");
+ writeFileSync(full, png);
+ runFfmpeg(["-y", "-i", full, "-vf", crop(roi), "-frames:v", "1", out]);
+ } finally {
+ rmSync(work, { recursive: true, force: true });
+ }
+ return { at: round(t, 3), frame: k };
+}
+
+/** The frames shown from `from` to `to` seconds, cropped (to even sizes), as an H.264 clip. */
+export function cutClip(
+ info: VideoInfo,
+ from: number,
+ to: number,
+ asked: Roi,
+ out: string,
+ opts: { audio?: boolean; crf?: number } = {},
+) {
+ const k0 = frameAt(from, info.fps);
+ const k1 = Math.min(info.frames, Math.ceil(to * info.fps - 1e-6));
+ if (k1 <= k0) throw new Fix("--to is not after --from", "--from 4 --to 9.5");
+ const roi = even(asked);
+ const [a, n] = [k0 / info.fps, k1 - k0];
+ const sound = Boolean(opts.audio && info.audio);
+ // Frames picked by index, as diff and the event map count them: a seek keeps whichever frame is showing at the
+ // seek time, which at some rates is the one before k0.
+ runFfmpeg([
+ ...["-y", "-i", info.path],
+ ...[
+ "-vf",
+ `trim=start_frame=${k0}:end_frame=${k1},setpts=PTS-STARTPTS,${crop(roi)},format=yuv420p`,
+ ],
+ ...["-r", info.fpsText, "-c:v", "libx264", "-crf", String(opts.crf ?? 14), "-preset", "medium"],
+ ...(sound
+ ? [
+ "-af",
+ `atrim=start=${a}:end=${k1 / info.fps},asetpts=PTS-STARTPTS`,
+ "-c:a",
+ "aac",
+ "-b:a",
+ "192k",
+ ]
+ : ["-an"]),
+ ...["-movflags", "+faststart", out],
+ ]);
+ return {
+ window: [round(a, 3), round(k1 / info.fps, 3)],
+ frames: n,
+ duration: round(n / info.fps, 3),
+ roi,
+ audio: sound,
+ };
+}
+
+/** The sound from `from` to `to` seconds as an audio file, on the same clock as the picture. */
+export function cutSound(info: VideoInfo, from: number, to: number, out: string) {
+ if (!info.audio) throw new Fix(`${info.path} has no sound`, "leave out of the rebuild");
+ const [a, b] = [Math.max(0, from), Math.min(info.duration, to)];
+ if (b <= a) throw new Fix("--to is not after --from", "--from 0 --to 12");
+ const codec = /\.wav$/i.test(out)
+ ? ["-c:a", "pcm_s16le"]
+ : /\.mp3$/i.test(out)
+ ? ["-c:a", "libmp3lame", "-q:a", "2"]
+ : ["-c:a", "aac", "-b:a", "256k"];
+ runFfmpeg(["-y", "-ss", String(a), "-i", info.path, "-t", String(b - a), "-vn", ...codec, out]);
+ return { window: [round(a, 3), round(b, 3)], duration: round(b - a, 3) };
+}
+
+export default defineCommand({
+ meta: {
+ name: "extract",
+ description:
+ "Cut a still (--at) or a clip (--from/--to) out of a video, cropped to a region, as project media",
+ },
+ args: {
+ video: videoArg,
+ out: {
+ type: "string",
+ description: "The file to write: .png/.jpg for a still, .mp4 for a clip",
+ required: true,
+ },
+ at: { type: "string", description: "A still of the frame shown at this second" },
+ from: { type: "string", description: "A clip's first second" },
+ to: { type: "string", description: "A clip's end second" },
+ audio: {
+ type: "boolean",
+ description: "Keep the clip's sound (default: picture only)",
+ default: false,
+ },
+ crf: { type: "string", description: "Clip quality, lower is better (default 14)" },
+ roi: roiArg,
+ json: jsonArg,
+ },
+ async run({ args }) {
+ // fallow-ignore-next-line complexity
+ await runMeasure(async () => {
+ const { info, roi: asked } = videoAndRoi(args.video, args.roi);
+ const out = resolve(String(args.out));
+ mkdirSync(dirname(out), { recursive: true });
+ if (/\.(m4a|aac|mp3|wav)$/i.test(out)) {
+ const sound = cutSound(
+ info,
+ num(args.from, "--from", 0),
+ num(args.to, "--to", info.duration),
+ out,
+ );
+ const ledger = await record(
+ out,
+ "bgm",
+ { provider: "original", from: info.path, window: sound.window },
+ sound.duration,
+ );
+ return {
+ out,
+ kind: "sound",
+ ...sound,
+ ...(ledger ? { ledger } : {}),
+ place: {
+ "data-start": sound.window[0],
+ "data-duration": sound.duration,
+ note: "an with this src",
+ },
+ };
+ }
+ const isClip = args.from !== undefined || args.to !== undefined;
+ if (isClip === (args.at !== undefined))
+ throw new Fix(
+ "pass --at for a still, or --from and --to for a clip",
+ "--at 3.2, or --from 4 --to 9.5",
+ );
+ if (!isClip) {
+ if (!/\.(png|jpe?g|webp)$/i.test(out))
+ throw new Fix(`${out} is not a picture`, "--out assets/name.png");
+ const { at, frame: k } = await cutStill(info, num(args.at, "--at", 0), asked, out);
+ const ledger = await record(out, "image", {
+ provider: "original",
+ from: info.path,
+ at,
+ roi: asked,
+ });
+ return {
+ out,
+ kind: "image",
+ at,
+ frame: k,
+ roi: asked,
+ ...(ledger ? { ledger } : {}),
+ place: { left: asked[0], top: asked[1], width: asked[2], height: asked[3] },
+ };
+ }
+
+ if (!/\.(mp4|mov|webm)$/i.test(out))
+ throw new Fix(`${out} is not a video`, "--out assets/name.mp4");
+ const clip = cutClip(
+ info,
+ num(args.from, "--from", 0),
+ num(args.to, "--to", info.duration),
+ asked,
+ out,
+ {
+ audio: args.audio,
+ crf: num(args.crf, "--crf", 14),
+ },
+ );
+ const { window, duration, roi } = clip;
+ const askedEnd = num(args.to, "--to", info.duration);
+ const ledger = await record(
+ out,
+ "video",
+ { provider: "original", from: info.path, window, roi, audio: clip.audio },
+ duration,
+ );
+ return {
+ out,
+ kind: "clip",
+ window,
+ frames: clip.frames,
+ duration,
+ roi,
+ audio: clip.audio,
+ ...(askedEnd > info.duration + 0.5 / info.fps
+ ? {
+ note: `--to ${askedEnd} is past the end; the clip stops at ${round(info.duration, 3)} s`,
+ }
+ : {}),
+ ...(ledger ? { ledger } : {}),
+ place: {
+ "data-start": window[0],
+ "data-duration": duration,
+ left: roi[0],
+ top: roi[1],
+ width: roi[2],
+ height: roi[3],
+ note: "a clip at the original's time and box; muted unless it carries the film's sound",
+ },
+ };
+ });
+ },
+});
diff --git a/packages/cli/src/commands/measure/face.ts b/packages/cli/src/commands/measure/face.ts
new file mode 100644
index 0000000000..d1fd03f9e2
--- /dev/null
+++ b/packages/cli/src/commands/measure/face.ts
@@ -0,0 +1,108 @@
+import { defineCommand } from "../../utils/defineCommand.js";
+import type { Example } from "../_examples.js";
+import { jsonArg, num, runMeasure, videoArg, window } from "../../measure/command.js";
+import {
+ FIT_MIN_FACES,
+ againstStart,
+ faceBoxes,
+ faceFit,
+ faceSummary,
+} from "../../measure/face.js";
+import { Fix, probeVideo, round } from "../../measure/media.js";
+
+export const examples: Example[] = [
+ [
+ "How big and where the presenter's face is in a shot",
+ "hyperframes measure face ref.mp4 --start 4 --end 9.5",
+ ],
+ [
+ "The scale and x, y that put a generated clip's face on the original's face over 2-6 s",
+ "hyperframes measure face presenter.mp4 --against ref.mp4 --from 2 --to 6",
+ ],
+];
+
+export default defineCommand({
+ meta: {
+ name: "face",
+ description:
+ "How big the face is and where, over a window: its box per sampled frame and whether a generated presenter can keep the likeness at that size",
+ },
+ args: {
+ video: videoArg,
+ start: {
+ type: "string",
+ description:
+ "First second (default 0; with --against, 0 for a shot of its own and --from for a render as long as the original)",
+ },
+ end: {
+ type: "string",
+ description:
+ "Last second (default: the end; with --against, --start plus the length of --from/--to)",
+ },
+ samples: {
+ type: "string",
+ description: "Frames sampled, evenly, the last one included (default 8)",
+ },
+ cast: {
+ type: "boolean",
+ description:
+ "The person is one face in a crowd: grade the smallest face (and look for faces down to 20 px)",
+ default: false,
+ },
+ against: {
+ type: "string",
+ description:
+ "The original video: print the GSAP scale and x, y (canvas pixels) that put this clip's face on the original's over --from/--to",
+ },
+ from: { type: "string", description: "With --against: the original's first second" },
+ to: { type: "string", description: "With --against: the original's last second" },
+ json: jsonArg,
+ },
+ async run({ args }) {
+ await runMeasure(async () => {
+ const info = probeVideo(String(args.video));
+ const cast = args.cast === true;
+ const samples = Math.max(1, num(args.samples, "--samples", 8));
+ const opts = cast ? { minFace: 0 } : {};
+ if (args.against !== undefined) {
+ const ref = probeVideo(String(args.against));
+ const [a, b] = window(ref, args.from, args.to, ["--from", "--to"]);
+ const s = num(args.start, "--start", againstStart(info.duration, ref.duration, a));
+ const e = Math.min(info.duration, s + (b - a));
+ if (!(e > s))
+ throw new Fix(`--start ${s} is past this clip's end`, `--start 0 (or leave it out)`);
+ const [fo, fc] = [
+ await faceBoxes(ref, a, b, samples, opts),
+ await faceBoxes(info, s, e, samples, opts),
+ ];
+ const rel = (f: { t: number; boxes: number[][] }[], t0: number) =>
+ f.map((x) => ({ t: x.t - t0, boxes: x.boxes }));
+ const fit = faceFit(rel(fo, a), rel(fc, s), ref, info, cast);
+ return {
+ video: info.path,
+ against: ref.path,
+ window: [round(s, 3), round(e, 3)],
+ against_window: [a, b],
+ canvas: [ref.width, ref.height],
+ ...fit,
+ ...(fit.transform === null
+ ? {
+ note: `fewer than ${FIT_MIN_FACES} moments with a face in both: try a wider window or more --samples`,
+ }
+ : {}),
+ reading:
+ "gsap.set(clip, { scale, x, y }) on a clip element that fills the canvas (object-fit: cover) with the default transform origin (its centre); x, y and the faces' centre and height are in the canvas's (the original's) pixels, clip_face before the transform; residual is the median face-centre miss left after it, in face heights",
+ };
+ }
+ const [a, b] = window(info, args.start, args.end);
+ return {
+ video: info.path,
+ start: a,
+ end: b,
+ ...faceSummary(await faceBoxes(info, a, b, samples, opts), cast),
+ reading:
+ "face_height is the face's height over the frame's; boxes are x, y, w, h as shares of the frame",
+ };
+ });
+ },
+});
diff --git a/packages/cli/src/commands/measure/frames.ts b/packages/cli/src/commands/measure/frames.ts
new file mode 100644
index 0000000000..b95b35b8c2
--- /dev/null
+++ b/packages/cli/src/commands/measure/frames.ts
@@ -0,0 +1,338 @@
+import { mkdtempSync, readdirSync, renameSync, rmSync } from "node:fs";
+import { join } from "node:path";
+import { defineCommand } from "../../utils/defineCommand.js";
+import type { Example } from "../_examples.js";
+import {
+ jsonArg,
+ num,
+ outArg,
+ roiArg,
+ runMeasure,
+ videoAndRoi,
+ videoArg,
+ window,
+} from "../../measure/command.js";
+import { detectEvents, lookWindows } from "../../measure/events.js";
+import {
+ Fix,
+ frameAt,
+ outDir,
+ parseNumbers,
+ parseRange,
+ readClip,
+ round,
+ runFfmpeg,
+ videoClip,
+ type Frames,
+ type Roi,
+ type VideoInfo,
+} from "../../measure/media.js";
+
+export const examples: Example[] = [
+ ["An overview sheet, one frame a second", "hyperframes measure frames ref.mp4 --every 1"],
+ [
+ "The consecutive frames around every event, one strip per window",
+ "hyperframes measure frames ref.mp4 --events",
+ ],
+ [
+ "Every frame of a transition, at full size",
+ "hyperframes measure frames ref.mp4 --range 2.1,2.6 --width 0",
+ ],
+ [
+ "Two moments, cropped to read the text",
+ "hyperframes measure frames ref.mp4 --at 1.2,3.4 --roi 100,800,880,200",
+ ],
+];
+
+const TILE_W = 360;
+const SHEET_TILES = 24;
+const STRIP_MAX = 12;
+const WINDOWS_MAX = 60;
+
+/** Runs of consecutive indexes, for a short select expression. */
+function runsOf(ks: number[]): [number, number][] {
+ const out: [number, number][] = [];
+ for (const k of ks) {
+ const last = out.at(-1);
+ if (last && k === last[1] + 1) last[1] = k;
+ else out.push([k, k]);
+ }
+ return out;
+}
+
+/** The frames at these indexes (sorted, unique), in order, from one decode pass. */
+function framesAt(info: VideoInfo, ks: number[], roi: Roi, width: number): Frames {
+ const expr = runsOf(ks)
+ .map(([a, b]) => (a === b ? `eq(n\\,${a})` : `between(n\\,${a}\\,${b})`))
+ .join("+");
+ // Renumbered so the raw output is exactly the picked frames, no gap filled by a repeat.
+ const clip = {
+ ...videoClip(info.path, 0, undefined, info),
+ filters: [`select=${expr}`, `setpts=N/(${info.fpsText})/TB`],
+ };
+ const full = roi[0] === 0 && roi[1] === 0 && roi[2] === info.width && roi[3] === info.height;
+ return readClip(clip, { ...(full ? {} : { roi }), width: width || roi[2] });
+}
+
+/** Writes frames as numbered PNGs in one ffmpeg call; returns their paths in order. */
+function writeFrames(
+ f: Frames,
+ from: number,
+ count: number,
+ dir: string,
+ prefix: string,
+): string[] {
+ // Beside the output, so the move below stays on one filesystem (a container's /tmp often is not the project's).
+ const work = mkdtempSync(join(dir, ".frames-"));
+ try {
+ const raw = Buffer.concat(
+ f.frames
+ .slice(from, from + count)
+ .map((px) => Buffer.from(px.buffer, px.byteOffset, px.byteLength)),
+ );
+ runFfmpeg(
+ [
+ "-y",
+ "-f",
+ "rawvideo",
+ "-pix_fmt",
+ "rgb24",
+ "-s",
+ `${f.w}x${f.h}`,
+ "-i",
+ "-",
+ "-start_number",
+ "0",
+ join(work, "%04d.png"),
+ ],
+ raw,
+ );
+ return readdirSync(work)
+ .sort()
+ .map((name, i) => {
+ const to = join(dir, `${prefix}-${String(i).padStart(2, "0")}.png`);
+ renameSync(join(work, name), to);
+ return to;
+ });
+ } finally {
+ rmSync(work, { recursive: true, force: true });
+ }
+}
+
+async function sheet(
+ paths: string[],
+ labels: string[],
+ out: string,
+ width: number,
+): Promise {
+ const { createContactSheet } = await import("../../capture/contactSheet.js");
+ return createContactSheet(paths, out, {
+ cols: Math.min(6, paths.length),
+ maxImages: paths.length,
+ cellWidth: width,
+ labelMode: "custom",
+ labels,
+ });
+}
+
+/**
+ * Up to `max` of a window's frames: all when they fit, else the frame before, at and after each event's onset
+ * (uniform thinning turns a cut into a dissolve and drops one-frame flashes), the rest evenly spaced.
+ */
+function spread(
+ k0: number,
+ k1: number,
+ max: number,
+ onsets: number[] = [],
+): { ks: number[]; step: number } {
+ const n = k1 - k0 + 1;
+ if (n <= max) return { ks: Array.from({ length: n }, (_, i) => k0 + i), step: 1 };
+ const must = new Set(onsets.flatMap((k) => [k - 1, k, k + 1]).filter((k) => k >= k0 && k <= k1));
+ // At least half the strip stays evenly spaced, so what happens between the onsets is seen too.
+ const room = Math.max(Math.ceil(max / 2), max - must.size);
+ for (let i = 0; i < room; i++) must.add(k0 + Math.round((i * (n - 1)) / (room - 1)));
+ const ks = [...must].sort((a, b) => a - b);
+ return { ks, step: Math.ceil((n - 1) / Math.max(1, ks.length - 1)) };
+}
+
+const label = (k: number, fps: number) => `f${k} · ${round(k / fps, 3)}s`;
+
+export default defineCommand({
+ meta: {
+ name: "frames",
+ description:
+ "Frames of a video as pictures: chosen moments, an overview sheet, consecutive native frames of a range, or strips around every event",
+ },
+ args: {
+ video: videoArg,
+ at: { type: "string", description: "Seconds, e.g. 1.2,3.4: one picture each" },
+ every: {
+ type: "string",
+ description: "An overview: one frame every N seconds on sheets of 24",
+ },
+ range: {
+ type: "string",
+ description: "start,end seconds: consecutive native frames as one strip",
+ },
+ events: {
+ type: "boolean",
+ description: "One strip of consecutive frames per window from measure events --map",
+ default: false,
+ },
+ start: { type: "string", description: "With --events or --every: first second (default 0)" },
+ end: {
+ type: "string",
+ description: "With --events or --every: last second (default: the end)",
+ },
+ max: {
+ type: "string",
+ description: `Frames per strip (default ${STRIP_MAX}; longer ranges are evenly thinned)`,
+ },
+ width: {
+ type: "string",
+ description: `Picture width in pixels (default ${TILE_W}; 0 keeps the ROI's size)`,
+ },
+ roi: roiArg,
+ out: outArg,
+ json: jsonArg,
+ },
+ async run({ args }) {
+ // fallow-ignore-next-line complexity
+ await runMeasure(async () => {
+ const modes = [args.at, args.every, args.range, args.events || undefined].filter(
+ (v) => v !== undefined,
+ );
+ if (modes.length !== 1)
+ throw new Fix(
+ "pass exactly one of --at, --every, --range or --events",
+ "npx hyperframes measure frames ref.mp4 --every 1",
+ );
+ const { info, roi } = videoAndRoi(args.video, args.roi);
+ const dir = outDir(args.out, "measure/frames");
+ const width = num(args.width, "--width", TILE_W);
+ const max = num(args.max, "--max", STRIP_MAX);
+ const last = info.frames - 1;
+ const head = {
+ video: info.path,
+ fps: round(info.fps, 3),
+ ...(args.roi !== undefined ? { roi } : {}),
+ };
+
+ if (args.at !== undefined) {
+ const ks = [
+ ...new Set(
+ parseNumbers(args.at, "--at").map((t) => Math.min(last, frameAt(t, info.fps))),
+ ),
+ ].sort((a, b) => a - b);
+ const f = framesAt(info, ks, roi, num(args.width, "--width", 0));
+ const paths = writeFrames(f, 0, ks.length, dir, "at");
+ return {
+ ...head,
+ frames: ks.map((k, i) => ({ t: round(k / info.fps, 3), frame: k, path: paths[i] })),
+ };
+ }
+
+ if (args.every !== undefined) {
+ const step = num(args.every, "--every", 1);
+ const [a, b] = window(info, args.start, args.end);
+ const ks = [
+ ...new Set(
+ Array.from({ length: Math.floor((b - a) / step) + 1 }, (_, i) =>
+ Math.min(last, frameAt(a + i * step, info.fps)),
+ ),
+ ),
+ ];
+ const f = framesAt(info, ks, roi, width);
+ const sheets: string[] = [];
+ for (let s = 0; s < ks.length; s += SHEET_TILES) {
+ const part = ks.slice(s, s + SHEET_TILES);
+ const paths = writeFrames(f, s, part.length, dir, `every-${s / SHEET_TILES}`);
+ const out = await sheet(
+ paths,
+ part.map((k) => `${round(k / info.fps, 2)}s`),
+ join(dir, `every-${step}s-${s / SHEET_TILES + 1}.jpg`),
+ f.w,
+ );
+ for (const p of paths) rmSync(p, { force: true });
+ if (out) sheets.push(out);
+ }
+ return { ...head, every_s: step, frames: ks.length, sheets };
+ }
+
+ if (args.range !== undefined) {
+ const [a, b] = parseRange(args.range);
+ const k0 = frameAt(a, info.fps);
+ const k1 = Math.min(last, Math.max(k0, Math.ceil(b * info.fps - 1e-6) - 1));
+ const { ks, step } = spread(k0, k1, max);
+ const f = framesAt(info, ks, roi, width);
+ const paths = writeFrames(f, 0, ks.length, dir, "range");
+ const out = await sheet(
+ paths,
+ ks.map((k) => label(k, info.fps)),
+ join(dir, `range-${a}-${b}s.jpg`),
+ f.w,
+ );
+ for (const p of paths) rmSync(p, { force: true });
+ return { ...head, start: a, end: b, frames: ks.length, every_nth_frame: step, strip: out };
+ }
+
+ // --events: the windows the event map groups, each as a strip of its consecutive frames.
+ const [a, b] = window(info, args.start, args.end);
+ const found = detectEvents({
+ info,
+ start: a,
+ end: b,
+ roi: [0, 0, info.width, info.height],
+ grid: { cols: 4, rows: 4 },
+ });
+ const windows = lookWindows(found.events, info.fps).slice(0, WINDOWS_MAX);
+ const picks = windows.map((wnd) =>
+ spread(
+ frameAt(wnd.start, info.fps),
+ Math.min(last, frameAt(wnd.end, info.fps)),
+ max,
+ wnd.onset_frames,
+ ),
+ );
+ const all = [...new Set(picks.flatMap((p) => p.ks))].sort((x, y) => x - y);
+ if (!all.length)
+ return {
+ ...head,
+ windows: [],
+ note: "nothing changes on screen: one overview frame is enough (--every)",
+ };
+ const f = framesAt(info, all, roi, width);
+ const strips = [];
+ for (const [i, wnd] of windows.entries()) {
+ const { ks, step } = picks[i]!;
+ const from = all.indexOf(ks[0]!);
+ const paths = writeFrames(f, from, ks.length, dir, `w${i + 1}`);
+ const out = await sheet(
+ paths,
+ ks.map((k) => label(k, info.fps)),
+ join(dir, `window-${String(i + 1).padStart(2, "0")}-${wnd.start}s.jpg`),
+ f.w,
+ );
+ for (const p of paths) rmSync(p, { force: true });
+ strips.push({
+ start: wnd.start,
+ end: wnd.end,
+ what: wnd.what,
+ frames: ks.length,
+ ...(step > 1 ? { thinned: `onsets kept, about every ${step}th frame between` } : {}),
+ strip: out,
+ });
+ }
+ const total = lookWindows(found.events, info.fps).length;
+ return {
+ ...head,
+ windows: strips,
+ ...(total > WINDOWS_MAX
+ ? {
+ note: `${total} windows; the first ${WINDOWS_MAX} shown: use --start/--end for the rest`,
+ }
+ : {}),
+ };
+ });
+ },
+});
diff --git a/packages/cli/src/commands/measure/look.ts b/packages/cli/src/commands/measure/look.ts
new file mode 100644
index 0000000000..0a52a690d7
--- /dev/null
+++ b/packages/cli/src/commands/measure/look.ts
@@ -0,0 +1,114 @@
+import { defineCommand } from "../../utils/defineCommand.js";
+import type { Example } from "../_examples.js";
+import {
+ jsonArg,
+ num,
+ roiArg,
+ runMeasure,
+ videoAndRoi,
+ videoArg,
+ window,
+} from "../../measure/command.js";
+import { compareLook, look, sameLook } from "../../measure/look.js";
+import { Fix, parseRoi, probeVideo, readFrameAt, videoClip } from "../../measure/media.js";
+
+export const examples: Example[] = [
+ ["The grade of the first 5 seconds", "hyperframes measure look ref.mp4 --start 0 --end 5"],
+ [
+ "Does the rebuild's grade match the original's",
+ "hyperframes measure look ref.mp4 --compare renders/v1.mp4",
+ ],
+];
+
+export default defineCommand({
+ meta: {
+ name: "look",
+ description:
+ "Brightness, contrast, saturation, black-and-white share and warmth of a window, or compared with another video",
+ },
+ args: {
+ video: videoArg,
+ start: { type: "string", description: "First second (default 0)" },
+ end: { type: "string", description: "Last second (default: the end)" },
+ fps: { type: "string", description: "Frames sampled per second (default 2)" },
+ roi: roiArg,
+ at: { type: "string", description: "With --grid: the moment to read" },
+ grid: {
+ type: "string",
+ description: "With --at: the mean colour of each cell, COLSxROWS, e.g. 8x6",
+ },
+ compare: { type: "string", description: "Another video measured over the same window" },
+ "compare-start": {
+ type: "string",
+ description: "Second the window starts in it (default: --start)",
+ },
+ "compare-roi": { type: "string", description: "Region of it (default: the whole frame)" },
+ json: jsonArg,
+ },
+ async run({ args }) {
+ await runMeasure(() => {
+ const { info, roi } = videoAndRoi(args.video, args.roi);
+ if (args.grid !== undefined || args.at !== undefined) {
+ const m = /^(\d+)x(\d+)$/.exec(String(args.grid ?? ""));
+ if (!m || args.at === undefined)
+ throw new Fix("--grid and --at go together", "--at 2 --grid 8x6");
+ const [cols, rows] = [Number(m[1]), Number(m[2])];
+ const at = num(args.at, "--at", 0);
+ const { frames, w, h } = readFrameAt(info, at, { roi, width: Math.min(640, roi[2]) });
+ const px = frames[0];
+ if (!px) throw new Fix(`no frame at ${at}s`, "pick a time inside the video");
+ const hex = (v: number[]) =>
+ `#${v.map((c) => Math.round(c).toString(16).padStart(2, "0")).join("")}`;
+ const colors = Array.from({ length: rows }, (_, r) =>
+ Array.from({ length: cols }, (_, c) => {
+ const [x0, x1, y0, y1] = [
+ Math.floor((c * w) / cols),
+ Math.floor(((c + 1) * w) / cols),
+ Math.floor((r * h) / rows),
+ Math.floor(((r + 1) * h) / rows),
+ ];
+ const sum = [0, 0, 0];
+ for (let y = y0; y < y1; y++)
+ for (let x = x0; x < x1; x++)
+ for (let k = 0; k < 3; k++) sum[k]! += px[(y * w + x) * 3 + k]!;
+ const n = Math.max(1, (x1 - x0) * (y1 - y0));
+ return hex(sum.map((v) => v / n));
+ }),
+ );
+ return {
+ video: info.path,
+ at,
+ roi,
+ grid: `${cols}x${rows}`,
+ colors,
+ reading: "rows top to bottom, each cell's mean colour",
+ };
+ }
+ const [a, b] = window(info, args.start, args.end);
+ const fps = num(args.fps, "--fps", 2);
+ const ref = look(videoClip(info.path, a, b - a, info), fps, roi);
+ if (args.compare === undefined) return { video: info.path, start: a, end: b, ...ref };
+ const other = probeVideo(String(args.compare));
+ const otherRoi =
+ args["compare-roi"] === undefined
+ ? undefined
+ : parseRoi(args["compare-roi"], other.width, other.height);
+ const theirs = look(
+ videoClip(other.path, num(args["compare-start"], "--compare-start", a), b - a, other),
+ fps,
+ otherRoi,
+ );
+ const diff = compareLook(ref, theirs);
+ return {
+ video: info.path,
+ compare: other.path,
+ start: a,
+ end: b,
+ reference: ref,
+ other: theirs,
+ ...diff,
+ same_look: sameLook(diff),
+ };
+ });
+ },
+});
diff --git a/packages/cli/src/commands/measure/probe.ts b/packages/cli/src/commands/measure/probe.ts
new file mode 100644
index 0000000000..3b381fd6c3
--- /dev/null
+++ b/packages/cli/src/commands/measure/probe.ts
@@ -0,0 +1,129 @@
+import { defineCommand } from "../../utils/defineCommand.js";
+import type { Example } from "../_examples.js";
+import { jsonArg, runMeasure, videoArg } from "../../measure/command.js";
+import {
+ ffmpegBin,
+ Fix,
+ probeVideo,
+ round,
+ runFfmpeg,
+ type VideoInfo,
+} from "../../measure/media.js";
+import { execFileSync } from "node:child_process";
+import { mkdirSync } from "node:fs";
+import { dirname, resolve } from "node:path";
+
+export const examples: Example[] = [
+ [
+ "Size, frame rate, sound, and what to fix before rebuilding",
+ "hyperframes measure probe ref.mp4",
+ ],
+ [
+ "Make a constant-rate SDR working copy of a phone or HDR video",
+ "hyperframes measure probe ref.mp4 --normalize original.mp4",
+ ],
+];
+
+// Sections longer than this are analysed and checked one at a time.
+const SECTION_S = 60;
+const STANDARD = ["24000/1001", "24", "25", "30000/1001", "30", "50", "60000/1001", "60"];
+const rateOf = (text: string) => {
+ const [a, b] = text.split("/").map(Number);
+ return (a ?? 0) / (b || 1);
+};
+
+/** The standard frame rate closest to a variable-rate video's average. */
+const standardRate = (info: VideoInfo) =>
+ STANDARD.reduce((best, r) =>
+ Math.abs(rateOf(r) - info.avgFps) < Math.abs(rateOf(best) - info.avgFps) ? r : best,
+ );
+
+const hasFilter = (name: string) =>
+ new RegExp(`\\s${name}\\s`).test(
+ execFileSync(ffmpegBin(), ["-hide_banner", "-filters"], { windowsHide: true }).toString(),
+ );
+
+/** A constant-rate SDR H.264 copy: what the measuring tools, diff and the render all read the same way. */
+function normalize(info: VideoInfo, out: string): { path: string; fps: string } {
+ const fps = info.vfr ? standardRate(info) : info.fpsText;
+ const filters = [`fps=${fps}`];
+ if (info.hdr) {
+ if (!hasFilter("zscale"))
+ throw new Fix(
+ "this ffmpeg cannot tone-map HDR (no zscale filter)",
+ "install an ffmpeg built with libzimg, e.g. brew install ffmpeg",
+ );
+ filters.push(
+ "zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709,tonemap=hable:desat=0,zscale=t=bt709:m=bt709:r=tv",
+ );
+ }
+ mkdirSync(dirname(out), { recursive: true });
+ runFfmpeg([
+ ...["-y", "-i", info.path, "-vf", [...filters, "format=yuv420p"].join(",")],
+ ...["-c:v", "libx264", "-crf", "12", "-preset", "medium", "-c:a", "aac", "-b:a", "192k", out],
+ ]);
+ return { path: out, fps };
+}
+
+export default defineCommand({
+ meta: {
+ name: "probe",
+ description:
+ "Size (as displayed), frame rate, duration, sound, and what to fix before measuring or rebuilding",
+ },
+ args: {
+ video: videoArg,
+ normalize: {
+ type: "string",
+ description:
+ "Write a constant-frame-rate SDR copy here (for variable-rate or HDR videos); the original is left alone",
+ },
+ json: jsonArg,
+ },
+ async run({ args }) {
+ // fallow-ignore-next-line complexity
+ await runMeasure(() => {
+ const info = probeVideo(String(args.video));
+ const notes: string[] = [];
+ if (info.vfr)
+ notes.push(
+ "variable frame rate: frame times drift, so measure and rebuild a constant-rate copy (--normalize)",
+ );
+ if (info.hdr) notes.push("HDR: --normalize tone-maps an SDR copy; the render is SDR");
+ if (info.duration > SECTION_S)
+ notes.push(
+ `longer than ${SECTION_S} s: analyse and check it in sections of at most ${SECTION_S} s, split at cuts (measure cuts)`,
+ );
+ if (!info.audio) notes.push("no sound: the rebuild has no ");
+ const made = args.normalize ? normalize(info, resolve(String(args.normalize))) : undefined;
+ return {
+ video: info.path,
+ width: info.width,
+ height: info.height,
+ fps: round(info.fps, 3),
+ fps_text: info.fpsText,
+ duration: round(info.duration, 3),
+ frames: info.frames,
+ picture_duration: round(info.frames / info.fps, 3),
+ audio: info.audio,
+ vfr: info.vfr,
+ hdr: info.hdr,
+ codec: info.codec,
+ canvas: {
+ width: info.width,
+ height: info.height,
+ fps: made?.fps ?? info.fpsText,
+ duration: round(info.frames / info.fps, 3),
+ note: "data-width, data-height and data-duration (the picture's length) on the root composition; render with --fps at this rate",
+ },
+ ...(made ? { normalized: made.path } : {}),
+ notes,
+ ...((info.vfr || info.hdr) && !made
+ ? {
+ fix: `npx hyperframes measure probe ${String(args.video)} --normalize `,
+ }
+ : {}),
+ };
+ });
+ },
+});
diff --git a/packages/cli/src/commands/measure/sync.ts b/packages/cli/src/commands/measure/sync.ts
new file mode 100644
index 0000000000..6bf4e7f14c
--- /dev/null
+++ b/packages/cli/src/commands/measure/sync.ts
@@ -0,0 +1,53 @@
+import { defineCommand } from "../../utils/defineCommand.js";
+import type { Example } from "../_examples.js";
+import {
+ jsonArg,
+ num,
+ roiArg,
+ runMeasure,
+ videoAndRoi,
+ videoArg,
+ window,
+} from "../../measure/command.js";
+import { Fix } from "../../measure/media.js";
+import { avSync } from "../../measure/sync.js";
+
+export const examples: Example[] = [
+ [
+ "How far the presenter's mouth trails the voice",
+ "hyperframes measure sync renders/v1.mp4 --roi 470,620,140,90 --start 2 --end 8",
+ ],
+];
+
+export default defineCommand({
+ meta: {
+ name: "sync",
+ description:
+ "Picture against sound for a person speaking: the lag between mouth motion and the voice",
+ },
+ args: {
+ video: videoArg,
+ roi: { ...roiArg, description: "The mouth, x,y,w,h in the video's pixels", required: true },
+ start: { type: "string", description: "First second (default 0)" },
+ end: { type: "string", description: "Last second (default: the end)" },
+ "max-lag-ms": { type: "string", description: "Lags searched each way (default 400)" },
+ json: jsonArg,
+ },
+ async run({ args }) {
+ await runMeasure(() => {
+ if (args.roi === undefined)
+ throw new Fix("--roi is required", "--roi x,y,w,h round the mouth");
+ const { info, roi } = videoAndRoi(args.video, args.roi);
+ const [start, end] = window(info, args.start, args.end);
+ return {
+ video: info.path,
+ roi,
+ start,
+ end,
+ ...avSync(info, roi, start, end, num(args["max-lag-ms"], "--max-lag-ms", 400)),
+ reading:
+ "positive best_lag_ms means the picture is late; trust high confidence, repeat a medium one on another window without cuts",
+ };
+ });
+ },
+});
diff --git a/packages/cli/src/commands/media-use.ts b/packages/cli/src/commands/media-use.ts
index 121dcc3bb3..7feeeadcf0 100644
--- a/packages/cli/src/commands/media-use.ts
+++ b/packages/cli/src/commands/media-use.ts
@@ -4,6 +4,7 @@ import { fileURLToPath } from "node:url";
import { spawnSync } from "node:child_process";
import { existsSync } from "node:fs";
import { finishCommand } from "../utils/commandResult.js";
+import { withMediaAuthEnvironment } from "../auth/media-environment.js";
const MEDIA_USE_ARGS = {
type: { type: "string" },
@@ -68,18 +69,17 @@ export function mediaUseVerbFlags(verb: MediaUseVerb): string[] {
return verb === "resolve" ? [] : [`--${verb}`];
}
-type InvokeMediaUse = (verb: MediaUseVerb) => never;
+type InvokeMediaUse = (verb: MediaUseVerb) => never | Promise;
-function invokeEngine(verb: MediaUseVerb): never {
+async function invokeEngine(verb: MediaUseVerb): Promise {
const here = dirname(fileURLToPath(import.meta.url));
const passed = mediaUsePassthroughArgs(process.argv);
const flag = mediaUseVerbFlags(verb);
- const result = spawnSync(
- process.execPath,
- [resolveMediaUseEnginePath(here), ...flag, ...passed],
- {
+ const result = await withMediaAuthEnvironment((env) =>
+ spawnSync(process.execPath, [resolveMediaUseEnginePath(here), ...flag, ...passed], {
stdio: "inherit",
- },
+ env,
+ }),
);
if (result.error) throw result.error;
finishCommand(result.status ?? 1);
@@ -94,13 +94,17 @@ function subcommand(name: MediaUseVerb, invoke: InvokeMediaUse) {
}
export function createMediaUseCommand(invoke: InvokeMediaUse = invokeEngine) {
- const subCommands = Object.fromEntries(
- MEDIA_USE_VERBS.map((name) => [name, () => subcommand(name, invoke)]),
- );
+ const subCommands = {
+ ...Object.fromEntries(MEDIA_USE_VERBS.map((name) => [name, () => subcommand(name, invoke)])),
+ generate: () => import("./media-use/generate.js").then((m) => m.default),
+ };
return defineCommand({
meta: { name: "media-use", description: "Resolve and operate on project media" },
subCommands,
- run: () => console.log("Run `hyperframes media-use --help`"),
+ run: ({ args }) => {
+ if (!args._?.[0])
+ console.log("Run `hyperframes media-use --help`");
+ },
});
}
diff --git a/packages/cli/src/commands/media-use/generate.ts b/packages/cli/src/commands/media-use/generate.ts
new file mode 100644
index 0000000000..e5f4fd3fd0
--- /dev/null
+++ b/packages/cli/src/commands/media-use/generate.ts
@@ -0,0 +1,162 @@
+import { defineCommand } from "../../utils/defineCommand.js";
+import type { Example } from "../_examples.js";
+import { jsonArg, num, runMeasure } from "../../measure/command.js";
+import { Fix } from "../../measure/media.js";
+import {
+ GENERATE_TYPES,
+ checkRequest,
+ generate,
+ parseMask,
+ type GenerateRequest,
+ type GenerateType,
+} from "../../heygen/generate.js";
+import { checkLimit, creditsOf, priceOf } from "../../heygen/pricing.js";
+
+export const examples: Example[] = [
+ [
+ "Price a clean plate of a frame, then make it",
+ 'hyperframes media-use generate --type image --reference f120.png --prompt "the same shot with no text" --out assets/plate.png --plan',
+ ],
+ [
+ "A 6 s shot that starts from the original's first frame",
+ 'hyperframes media-use generate --type video --first-frame assets/s03-first.png --prompt "slow push in" --seconds 6 --out assets/s03.mp4',
+ ],
+ [
+ "The original's presenter re-shot clean, saying an 8 s stretch of the original voice",
+ 'hyperframes media-use generate --type video --reference assets/presenter-clean.png --audio assets/s02-voice.m4a --motion assets/s02-original.mp4 --mask 110,615,390,165 --prompt "the woman talks to camera, seated, soft daylight" --seconds 8 --aspect 9:16 --out assets/s02-presenter.mp4',
+ ],
+ [
+ "The person in a photo saying a script in a chosen voice",
+ 'hyperframes media-use generate --type avatar --photo assets/presenter.png --script "Hi, I am Ana" --voice --out assets/ana.mp4',
+ ],
+];
+
+const isType = (v: string): v is GenerateType => GENERATE_TYPES.some((t) => t === v);
+
+/** Every value of a flag given more than once (citty keeps only the last). */
+export function repeated(raw: string[], flag: string): string[] {
+ return raw.flatMap((a, i) =>
+ a === flag && raw[i + 1] !== undefined
+ ? [raw[i + 1]!]
+ : a.startsWith(`${flag}=`)
+ ? [a.slice(flag.length + 1)]
+ : [],
+ );
+}
+
+export default defineCommand({
+ meta: {
+ name: "generate",
+ description:
+ "Make new media on HeyGen: an image (edited from references), a video shot (from a first frame), a person speaking from a photo, a voice, or music. --plan prices it first",
+ },
+ args: {
+ type: {
+ type: "string",
+ description: `What to make: ${GENERATE_TYPES.join(", ")}`,
+ required: true,
+ },
+ out: {
+ type: "string",
+ description: "The project file to write, e.g. assets/plate.png",
+ required: true,
+ },
+ prompt: { type: "string", description: "What it shows or sounds like (image, video, music)" },
+ reference: {
+ type: "string",
+ description:
+ "image: comma-separated pictures to edit from or follow; video: the person to show speaking",
+ },
+ audio: {
+ type: "string",
+ description: "video: speech the referenced person says, lips in sync (5–15 s)",
+ },
+ motion: {
+ type: "string",
+ description: "video: a clip whose camera and body motion the shot follows (up to 15 s)",
+ },
+ mask: {
+ type: "string",
+ description:
+ "video: x,y,w,h[,a-b] of the --motion clip to blank before sending (its drawn text; a-b in the clip's seconds); repeat for more",
+ },
+ "first-frame": { type: "string", description: "video: the picture the shot starts from" },
+ photo: { type: "string", description: "avatar: the person's photo" },
+ script: { type: "string", description: "avatar, voice: the words spoken" },
+ voice: { type: "string", description: "avatar, voice: a HeyGen voice id" },
+ seconds: {
+ type: "string",
+ description: "video 5–15 (default 5); music: 30, 60, 120 or 180 (default 30)",
+ },
+ aspect: {
+ type: "string",
+ description: "Aspect ratio, e.g. 9:16 (image, video without a first frame, avatar)",
+ },
+ model: { type: "string", description: "image: nano-banana-2 (default) or gpt-image-2.5" },
+ bpm: { type: "string", description: "music: tempo, 60–180" },
+ vocals: {
+ type: "boolean",
+ description: "music: allow singing (default instrumental)",
+ default: false,
+ },
+ "max-credits": {
+ type: "string",
+ description:
+ "The person's credit limit, less what earlier calls used: make nothing when this call would cost more",
+ },
+ plan: {
+ type: "boolean",
+ description: "Print the price and what would be sent; make nothing",
+ default: false,
+ },
+ json: jsonArg,
+ },
+ async run({ args, rawArgs }) {
+ await runMeasure(async () => {
+ const type = String(args.type);
+ if (!isType(type))
+ throw new Fix(`unknown --type ${type}`, `--type ${GENERATE_TYPES.join("|")}`);
+ const request: GenerateRequest = {
+ type,
+ out: String(args.out),
+ prompt: args.prompt,
+ references: args.reference
+ ?.split(",")
+ .map((p) => p.trim())
+ .filter(Boolean),
+ firstFrame: args["first-frame"],
+ audio: args.audio,
+ motion: args.motion,
+ masks: repeated(rawArgs, "--mask").map(parseMask),
+ photo: args.photo,
+ script: args.script,
+ voice: args.voice,
+ seconds: num(args.seconds, "--seconds"),
+ aspect: args.aspect,
+ model: args.model,
+ bpm: num(args.bpm, "--bpm"),
+ instrumental: !args.vocals,
+ };
+ const price = priceOf(request);
+ const credits = creditsOf(price);
+ if (args.plan) {
+ checkRequest(request);
+ return {
+ plan: true,
+ type,
+ out: request.out,
+ price,
+ credits,
+ next: "run the same command without --plan to make it",
+ };
+ }
+ checkLimit(credits, num(args["max-credits"], "--max-credits"));
+ const made = await generate(
+ request,
+ (status) => console.error(`generate: ${status}…`),
+ credits ?? undefined,
+ );
+ return { ...made, price, credits };
+ });
+ },
+});
diff --git a/packages/cli/src/commands/motion-signature.browser.chromium.test.ts b/packages/cli/src/commands/motion-signature.browser.chromium.test.ts
index 40d1746453..54c8c4b9c0 100644
--- a/packages/cli/src/commands/motion-signature.browser.chromium.test.ts
+++ b/packages/cli/src/commands/motion-signature.browser.chromium.test.ts
@@ -568,6 +568,23 @@ describe.skipIf(!RUNS_CHROMIUM)("motion-signature.browser in Chromium", () => {
expect(after).toEqual(before);
});
+ it("sees a small sprite move across a large canvas", async () => {
+ await load(
+ composition(
+ "#c { width: 640px; height: 360px; }",
+ ' ',
+ ),
+ );
+ const draw = (x: number) =>
+ `{ const ctx = document.getElementById("c").getContext("2d"); ctx.clearRect(0, 0, 1080, 1920); ctx.fillStyle = "#fc8"; ctx.fillRect(${x}, 500, 24, 24); }`;
+ await mutate(draw(300));
+ const before = await sample();
+ await mutate(draw(308));
+ const after = await sample();
+
+ expect(after.liveness).not.toBe(before.liveness);
+ });
+
it("ignores a repaint of a canvas whose contents are skipped by content-visibility:hidden", async () => {
await load(
composition(
diff --git a/packages/cli/src/commands/motion-signature.browser.js b/packages/cli/src/commands/motion-signature.browser.js
index 29705291ac..9521ad8016 100644
--- a/packages/cli/src/commands/motion-signature.browser.js
+++ b/packages/cli/src/commands/motion-signature.browser.js
@@ -6,6 +6,8 @@
(function () {
const IGNORE_TAGS = new Set(["SCRIPT", "STYLE", "TEMPLATE", "NOSCRIPT", "META", "LINK"]);
const MEDIA_TAGS = new Set(["CANVAS", "VIDEO", "IMG"]);
+ const COARSE_MEDIA_SAMPLE_SIDE = 8;
+ const LIVENESS_MEDIA_SAMPLE_SIDE = 32;
const FNV_OFFSET_BASIS = 2166136261;
const FNV_PRIME = 16777619;
const LIVENESS_POSITION_BUCKET_PX = 2;
@@ -220,28 +222,35 @@
return before || after ? hashFields([before, after]) : "";
}
+ function unreadableMedia(element) {
+ return "x" + (element.currentSrc || element.getAttribute("src") || "");
+ }
+
// Pixel-only media motion (canvas repaint, playing video, same-size swap) is invisible to DOM channels,
- // so fold in an 8x8 downsample. Unreadable media hashes to a constant; iframe media is a separate document.
+ // so fold in a downsample: fine for liveness (a small sprite moving), coarse for the frozen-sweep guard,
+ // which a wall-clock repaint between seeks would fool. Unreadable media hashes to its source.
// fallow-ignore-next-line complexity
- function mediaPixelChannel(element) {
+ function mediaPixelChannel(element, ctx) {
if (!MEDIA_TAGS.has(element.tagName)) return "";
try {
const rect = element.getBoundingClientRect();
const sourceWidth = element.videoWidth || element.width || rect.width;
const sourceHeight = element.videoHeight || element.height || rect.height;
- if (!sourceWidth || !sourceHeight) return "x";
+ if (!sourceWidth || !sourceHeight) return unreadableMedia(element);
const off = document.createElement("canvas");
- off.width = 8;
- off.height = 8;
+ const side = ctx && ctx.quantize ? LIVENESS_MEDIA_SAMPLE_SIDE : COARSE_MEDIA_SAMPLE_SIDE;
+ off.width = side;
+ off.height = side;
const ctx2d = off.getContext("2d");
- if (!ctx2d) return "x";
- ctx2d.drawImage(element, 0, 0, 8, 8);
- const data = ctx2d.getImageData(0, 0, 8, 8).data;
+ if (!ctx2d) return unreadableMedia(element);
+ if (side === LIVENESS_MEDIA_SAMPLE_SIDE) ctx2d.imageSmoothingQuality = "high";
+ ctx2d.drawImage(element, 0, 0, side, side);
+ const data = ctx2d.getImageData(0, 0, side, side).data;
let hash = 0;
for (let i = 0; i < data.length; i++) hash = (hash * 31 + data[i]) >>> 0;
return String(hash);
} catch {
- return "x";
+ return unreadableMedia(element);
}
}
diff --git a/packages/cli/src/commands/motion-signature.browser.test.ts b/packages/cli/src/commands/motion-signature.browser.test.ts
index 264b5a72a7..b3e905d5e1 100644
--- a/packages/cli/src/commands/motion-signature.browser.test.ts
+++ b/packages/cli/src/commands/motion-signature.browser.test.ts
@@ -110,6 +110,18 @@ function mockMediaPixels(read: () => number): void {
} as unknown as CanvasRenderingContext2D);
}
+function mockUnreadableMedia(): void {
+ const getContextSpy = vi.spyOn(HTMLCanvasElement.prototype, "getContext") as unknown as {
+ mockReturnValue(value: CanvasRenderingContext2D): void;
+ };
+ getContextSpy.mockReturnValue({
+ drawImage() {},
+ getImageData() {
+ throw new DOMException("tainted canvas", "SecurityError");
+ },
+ } as unknown as CanvasRenderingContext2D);
+}
+
const ROOT = { left: 0, top: 0, width: 640, height: 360 };
const COUNTDOWN = { left: 280, top: 140, width: 80, height: 48 };
const ZERO_BOX = { left: 0, top: 0, width: 0, height: 0 };
@@ -158,6 +170,22 @@ describe("motion-signature.browser media and geometry channels", () => {
expect(collect()).not.toBe(before);
});
+ it("changes the sweep fingerprint when an img whose pixels cannot be read swaps its source", () => {
+ document.body.innerHTML = `
+
+
+
+ `;
+ installFixture({ rects: { root: ROOT, frame: ROOT } });
+ mockUnreadableMedia();
+
+ const collect = installScript();
+ const before = collect();
+ document.getElementById("frame")?.setAttribute("src", "https://cdn.example/b.png");
+
+ expect(collect()).not.toBe(before);
+ });
+
// Opacity-only reveals (code-typing scenes) must count as motion both mid-fade and when a glyph crosses
// the 0.2 visibility floor; otherwise `check` misfires sweep_static.
it("changes the sweep fingerprint when text reveals via opacity alone", () => {
diff --git a/packages/cli/src/commands/normalize-audio.ts b/packages/cli/src/commands/normalize-audio.ts
index 02bb1f024c..ed53398cee 100644
--- a/packages/cli/src/commands/normalize-audio.ts
+++ b/packages/cli/src/commands/normalize-audio.ts
@@ -2,6 +2,7 @@ import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { relative, resolve } from "node:path";
import {
absoluteLoudnessPlan,
+ absoluteOutcome,
audioNormalizationPlan,
audioTags,
DEFAULT_TARGET_LUFS,
@@ -169,7 +170,7 @@ async function plannedNormalization(
if (options.reference === undefined) {
const targetTag = byId(tags, options.target, "Target");
const plan = await measuredAbsolutePlan(projectDir, targetTag, parsedLufs(options.lufs));
- const withinTolerance = targetTag.volume > 0 && Math.abs(plan.changeDb) <= tolerance;
+ const withinTolerance = targetTag.volume > 0 && absoluteOutcome(plan, tolerance) === "matched";
return { targetTag, withinTolerance, plan: { mode: "absolute", ...plan } };
}
const { referenceTag, targetTag } = selectedTags(tags, options.reference, options.target);
@@ -189,7 +190,9 @@ async function normalizeAudio(options: NormalizeAudioOptions): Promise 0 && absoluteOutcome(plan, tolerance) === "held";
+ const wrote = options.write && !withinTolerance && !heldByLimit;
if (wrote) {
writeAtomically(
filePath,
@@ -228,6 +231,15 @@ function printHumanResult(result: NormalizeAudioResult): void {
return;
}
+ if (
+ result.mode === "absolute" &&
+ result.previousVolume > 0 &&
+ absoluteOutcome(result, result.tolerance) === "held"
+ ) {
+ console.log(c.dim("Cannot get closer to the target; the gain is unchanged."));
+ return;
+ }
+
console.log(
`Set #${result.targetId} data-volume ${result.previousVolume.toFixed(3)} → ${result.volume.toFixed(6)} ` +
`(${result.changeDb >= 0 ? "+" : ""}${result.changeDb.toFixed(1)} dB).`,
diff --git a/packages/cli/src/commands/preview.ts b/packages/cli/src/commands/preview.ts
index 62bedf8338..855c52369c 100644
--- a/packages/cli/src/commands/preview.ts
+++ b/packages/cli/src/commands/preview.ts
@@ -54,6 +54,7 @@ import { runRenderSetupWorker } from "../utils/cancellableProcess.js";
import { formatLintStartupMessage } from "../utils/lintFormat.js";
import {
activeServerOnPort,
+ closeServer,
findPortAndServe,
scanActiveServers,
killActiveServers,
@@ -1743,7 +1744,7 @@ export async function runEmbeddedMode(
.catch(() => {})
.finally(() => {
watcher.close();
- result.server.close(() => resolveRun());
+ void closeServer(result.server).then(resolveRun);
});
};
// `on`, not `once`: a repeat Ctrl+C/SIGTERM while shutdown is running must
diff --git a/packages/cli/src/commands/publish.test.ts b/packages/cli/src/commands/publish.test.ts
index 552c4272fa..b19f036db8 100644
--- a/packages/cli/src/commands/publish.test.ts
+++ b/packages/cli/src/commands/publish.test.ts
@@ -12,9 +12,20 @@ vi.mock("../utils/publishProject.js", async (importOriginal) => ({
import publishCommand, { examples, parseUpdateTarget } from "./publish.js";
import { ensureProjectId } from "../utils/projectLink.js";
-import { writeStore } from "../auth/store.js";
+import { writeStore as writeUnboundStore, type Credentials } from "../auth/store.js";
+import { oauthIdentity } from "../auth/config.js";
import { consumeCommandResult } from "../utils/commandResult.js";
+async function writeStore(credentials: Credentials, path?: string): Promise {
+ await writeUnboundStore(
+ {
+ ...credentials,
+ ...(credentials.oauth ? { oauth: { ...oauthIdentity(), ...credentials.oauth } } : {}),
+ },
+ path,
+ );
+}
+
const VISIBLE_INDEX = ``;
function mockPublished(result: Record): void {
@@ -106,7 +117,7 @@ describe("publish default-entry preflight", () => {
const output = await runEntryMismatch("compositions/brand/index.html");
expect(output).toContain("blank_root_with_standalone_composition");
- expect(output).not.toContain("run with --lint-verbose for full output");
+ expect(output).not.toContain("for full output");
});
});
@@ -193,7 +204,7 @@ describe("publish --update / --space ownership preflight", () => {
const project = mkdtempSync(join(tmpdir(), "hf-publish-owner-"));
const config = mkdtempSync(join(tmpdir(), "hf-publish-owner-config-"));
writeFileSync(join(project, "index.html"), VISIBLE_INDEX);
- vi.stubEnv("HEYGEN_CONFIG_DIR", config);
+ vi.stubEnv("HYPERFRAMES_CONFIG_DIR", config);
vi.stubEnv("HEYGEN_API_KEY", credentials.env ?? "");
vi.stubEnv("HYPERFRAMES_API_KEY", "");
if (credentials.stored) await writeStore(credentials.stored, join(config, "credentials"));
@@ -352,7 +363,7 @@ describe("publish --update / --space ownership preflight", () => {
expect(stored?.credentials.oauth).toMatchObject(loginB);
expect(stored?.credentials.user?.email).toBe("b@example.com");
- expect(fetchMock.mock.calls.map(([url]) => url)).toEqual(["https://auth.test/token"]);
+ expect(fetchMock).not.toHaveBeenCalled();
expect(exitCode).toBe(1);
expect(errors.join("\n")).toContain("Your login changed during publish. Run publish again.");
} finally {
diff --git a/packages/cli/src/commands/render.ts b/packages/cli/src/commands/render.ts
index 68d1a9b18d..94f9bfae39 100644
--- a/packages/cli/src/commands/render.ts
+++ b/packages/cli/src/commands/render.ts
@@ -4,7 +4,12 @@ import { failCommand, requestCliExit, scheduleCliExit } from "../utils/commandRe
import { defineCommand } from "../utils/defineCommand.js";
import type { Example } from "./_examples.js";
import { mkdtempSync, readdirSync, readFileSync, statSync, writeFileSync, rmSync } from "node:fs";
-import { createRenderPlan, resolveBrowserGpuForCli, type RenderFormat } from "./render/plan.js";
+import {
+ createRenderPlan,
+ resolveBrowserGpuForCli,
+ type RenderFormat,
+ type RenderRange,
+} from "./render/plan.js";
import { seedProjectAuthoringSkill } from "../utils/projectConfig.js";
import { deliveryFlagArgs } from "../utils/deliveryFlags.js";
import type { CatalogUsage } from "../utils/catalogUsage.js";
@@ -76,6 +81,7 @@ import {
} from "../ui/format.js";
import { warnIfWebmAlphaDropped } from "../utils/webmAlphaCheck.js";
import { renderFailureDiagnostic } from "../ui/renderDiagnostic.js";
+import { missingPathKind } from "../telemetry/missingPathKind.js";
import { renderProgress, renderMachineProgress } from "../ui/progress.js";
import {
trackRenderComplete,
@@ -121,6 +127,7 @@ import {
import { runEnvironmentChecks } from "../browser/preflight.js";
import {
detectH264EncoderModeForRender,
+ FFMPEG_PATH_ENV,
getFFmpegInstallHint,
H264EncoderUnavailableError,
type H264EncoderMode,
@@ -199,7 +206,7 @@ export default defineCommand({
type: "string",
description:
"Authoring skill that initiated this render (e.g. hyperframes). " +
- "Recorded on anonymous render telemetry for per-skill usage breakdowns; ignored unless it is a slug.",
+ "Recorded on render telemetry for per-skill usage breakdowns; ignored unless it is a slug.",
},
format: {
type: "string",
@@ -261,6 +268,16 @@ export default defineCommand({
description:
"Override MP4/WebM encoder CRF. Mutually exclusive with --video-bitrate; unsupported for MOV.",
},
+ start: {
+ type: "string",
+ description:
+ "Render from this second of the film (MP4). The clip starts at 0 and carries the audio of the span.",
+ },
+ end: {
+ type: "string",
+ description:
+ "Render up to this second of the film (default: the end). Needs MP4, a whole frame rate of 24, 25, 30 or 60, and SDR.",
+ },
"video-bitrate": {
type: "string",
description:
@@ -524,6 +541,7 @@ export interface RenderOptions {
vp9CpuUsed?: number;
videoBitrate?: string;
keyframeIntervalSeconds?: number;
+ range?: RenderRange;
proresProfile?: ProresProfile;
maxBitrate?: string;
bufferSize?: string;
@@ -859,6 +877,7 @@ async function renderDocker(
vp9CpuUsed: options.vp9CpuUsed,
videoBitrate: options.videoBitrate,
keyframeIntervalSeconds: options.keyframeIntervalSeconds,
+ range: options.range,
proresProfile: options.proresProfile,
maxBitrate: options.maxBitrate,
bufferSize: options.bufferSize,
@@ -1060,7 +1079,7 @@ async function executeLocalRender(
errorBox(
`${isHls ? "HLS" : "MP4"} H.264 encoder unavailable`,
error.message,
- `Install an FFmpeg build with libx264 support (${getFFmpegInstallHint()})` +
+ `Install an FFmpeg build with libx264 support (${getFFmpegInstallHint()}), or point ${FFMPEG_PATH_ENV} at one` +
(isHls
? "."
: ", or render WebM instead: hyperframes render --format webm --output output.webm"),
@@ -1158,8 +1177,24 @@ async function executeLocalRender(
resumeSegments: options.resumeSegments,
keepSegments: options.keepSegments,
strictness: options.bestEffort === false ? "strict" : "best-effort",
+ // plan() takes the film's own size; these only satisfy the request shape.
+ distributed: options.range ? { width: 1920, height: 1080 } : undefined,
},
});
+ if (options.range) {
+ return renderRange({
+ producer,
+ request,
+ range: options.range,
+ projectDir,
+ outputPath,
+ options,
+ logger,
+ startTime,
+ cpu,
+ signal: cancellation.signal,
+ });
+ }
const job = producer.createRenderJob(producer.renderConfigFromRequest(request, { logger }));
const onProgress = options.quiet
@@ -1259,6 +1294,54 @@ async function executeLocalRender(
};
}
+async function renderRange(input: {
+ producer: Awaited>;
+ request: ReturnType>["createRenderRequest"]>;
+ range: RenderRange;
+ projectDir: string;
+ outputPath: string;
+ options: RenderOptions;
+ logger: ProducerLogger;
+ startTime: number;
+ cpu: RenderCpuSampler;
+ signal: AbortSignal;
+}): Promise {
+ const { producer, options } = input;
+ let framesEncoded = 0;
+ try {
+ const config = producer.distributedConfigFromRequest(input.request, {
+ logger: input.logger,
+ abortSignal: input.signal,
+ });
+ ({ framesEncoded } = await producer.renderSpan(
+ input.projectDir,
+ config,
+ input.range,
+ input.outputPath,
+ ));
+ } catch (error: unknown) {
+ handleRenderError(error, options, input.startTime, input.cpu, false, "");
+ }
+ markRenderSucceeded();
+ const elapsed = Date.now() - input.startTime;
+ input.cpu.stop();
+ printRenderComplete({
+ outputPath: input.outputPath,
+ projectDir: input.projectDir,
+ desktopHint: wantsDesktopHint(options),
+ elapsedMs: elapsed,
+ quiet: options.quiet,
+ format: options.format,
+ });
+ if (options.exitAfterComplete) scheduleCliExit();
+ return {
+ renderTimeMs: elapsed,
+ durationMs: Math.round((framesEncoded / fpsToNumber(options.fps)) * 1000),
+ outcome: "completed",
+ warnings: [],
+ };
+}
+
function getMemorySnapshot() {
return {
peakMemoryMb: bytesToMb(process.memoryUsage.rss()),
@@ -1815,6 +1898,7 @@ function handleRenderError(
// the render_complete success path, since nothing failed to name.
errorName: error instanceof Error ? error.name : "unknown",
failedStageCode: normalizeStageCode(failedStage || "pipeline"),
+ missingPathKind: missingPathKind(error),
...renderJobObservabilityTelemetryPayload(job),
...getMemorySnapshot(),
...cpu.stop(),
@@ -1948,6 +2032,10 @@ function trackRenderMetrics(
speedRatio,
captureAvgMs: perf?.captureAvgMs,
captureP50Ms: perf?.captureP50Ms,
+ captureSeekAvgMs: perf?.captureSeekAvgMs,
+ captureBeforeCaptureAvgMs: perf?.captureBeforeCaptureAvgMs,
+ captureScreenshotAvgMs: perf?.captureScreenshotAvgMs,
+ encoderWaitAvgMs: perf?.encoderWaitAvgMs,
subTimelineWait: perf?.subTimelineWait,
videoCount: perf?.videoCount,
capturePeakMs: perf?.capturePeakMs,
diff --git a/packages/cli/src/commands/render/execute.ts b/packages/cli/src/commands/render/execute.ts
index 2e51075b55..d5b16af90e 100644
--- a/packages/cli/src/commands/render/execute.ts
+++ b/packages/cli/src/commands/render/execute.ts
@@ -162,6 +162,7 @@ export function renderOptionsFromPlan(
vp9CpuUsed: plan.vp9CpuUsed,
videoBitrate: plan.videoBitrate,
keyframeIntervalSeconds: plan.keyframeIntervalSeconds,
+ range: plan.range,
proresProfile: plan.proresProfile,
maxBitrate: plan.maxBitrate,
bufferSize: plan.bufferSize,
@@ -376,6 +377,7 @@ export function batchRowRenderOptions(
vp9CpuUsed: plan.vp9CpuUsed,
videoBitrate: plan.videoBitrate,
keyframeIntervalSeconds: plan.keyframeIntervalSeconds,
+ range: plan.range,
proresProfile: plan.proresProfile,
maxBitrate: plan.maxBitrate,
bufferSize: plan.bufferSize,
diff --git a/packages/cli/src/commands/render/plan.test.ts b/packages/cli/src/commands/render/plan.test.ts
index e73915fb1b..8fd104df7c 100644
--- a/packages/cli/src/commands/render/plan.test.ts
+++ b/packages/cli/src/commands/render/plan.test.ts
@@ -1,7 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
-import { basename, join, resolve } from "node:path";
+import { basename, dirname, join, parse, resolve } from "node:path";
import { CliUsageError } from "../../utils/commandResult.js";
import { createRenderPlan } from "./plan.js";
@@ -37,6 +37,18 @@ describe("createRenderPlan", () => {
expect(Object.isFrozen(plan.environment)).toBe(true);
});
+ it("reads variables from --variables-file and from a path given to --variables", async () => {
+ const { resolveVariablesArg } = await import("../../utils/variables.js");
+ const file = join(projectDir, "vars.json");
+ writeFileSync(file, '{"title":"Hello"}');
+ for (const args of [{ "variables-file": file }, { variables: file }]) {
+ const plan = createRenderPlan({ dir: projectDir, ...args });
+ expect(resolveVariablesArg(plan.variablesArg, plan.variablesFileArg)).toEqual({
+ title: "Hello",
+ });
+ }
+ });
+
// GIF's Netscape frame-delay field is stored in centiseconds, so fps above
// 30 rounds to visually-indistinguishable delay values. createRenderPlan
// clamps and flags it so both the CLI console warning (present.ts) and
@@ -196,10 +208,17 @@ describe("createRenderPlan", () => {
expect(plan.format).toBe("hls");
expect(plan.hlsSegmentSeconds).toBe(4);
// No extension: outputPath is the directory the playlists are written into.
- expect(plan.outputPath.startsWith(resolve("renders", plan.project.name))).toBe(true);
+ expect(plan.outputPath.startsWith(join(projectDir, "renders", plan.project.name))).toBe(true);
expect(basename(plan.outputPath)).not.toContain(".");
});
+ it("writes the default output under the project's renders folder whatever the cwd is", () => {
+ vi.spyOn(process, "cwd").mockReturnValue(parse(projectDir).root);
+ const plan = createRenderPlan({ dir: projectDir });
+
+ expect(dirname(plan.outputPath)).toBe(join(projectDir, "renders"));
+ });
+
it("carries an explicit --hls-segment-seconds and rejects a fractional one", () => {
expect(
createRenderPlan({ dir: projectDir, format: "hls", "hls-segment-seconds": "6" })
@@ -247,6 +266,30 @@ describe("createRenderPlan", () => {
}
});
+ it("carries --start and --end into the plan, and refuses what a range cannot render", () => {
+ expect(createRenderPlan({ dir: projectDir, start: "2.5", end: "6" }).range).toEqual({
+ startSeconds: 2.5,
+ endSeconds: 6,
+ });
+ expect(createRenderPlan({ dir: projectDir, end: "4" }).range).toEqual({
+ startSeconds: 0,
+ endSeconds: 4,
+ });
+ expect(createRenderPlan({ dir: projectDir }).range).toBeUndefined();
+ const refused: Array> = [
+ { start: "-1" },
+ { start: "abc" },
+ { start: "5", end: "5" },
+ { start: "1", format: "webm" },
+ { start: "1", fps: "29.97" },
+ { start: "1", fps: "50" },
+ { start: "1", hdr: true },
+ ];
+ for (const flags of refused) {
+ expect(() => createRenderPlan({ dir: projectDir, ...flags })).toThrow(CliUsageError);
+ }
+ });
+
it("rejects batch and single-render variables before execution", () => {
expect(() =>
createRenderPlan({ dir: projectDir, batch: "rows.json", variables: '{"name":"Ada"}' }),
diff --git a/packages/cli/src/commands/render/plan.ts b/packages/cli/src/commands/render/plan.ts
index 8c11cd4778..5247008e33 100644
--- a/packages/cli/src/commands/render/plan.ts
+++ b/packages/cli/src/commands/render/plan.ts
@@ -1,9 +1,11 @@
import { statSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import {
+ DISTRIBUTED_FPS,
formatRenderOutputTimestamp,
fpsToNumber,
isAspectAgnosticResolutionAlias,
+ isDistributedFps,
normalizeResolutionFlag,
parseFps,
type CanvasResolution,
@@ -84,6 +86,8 @@ export interface RenderCommandArgs {
hdr?: boolean;
sdr?: boolean;
crf?: string;
+ start?: string;
+ end?: string;
"video-bitrate"?: string;
"keyframe-interval"?: string;
"max-bitrate"?: string;
@@ -168,6 +172,7 @@ export interface RenderPlan {
vp9CpuUsed?: number;
videoBitrate?: string;
keyframeIntervalSeconds?: number;
+ range?: RenderRange;
proresProfile?: ProresProfile;
maxBitrate?: string;
bufferSize?: string;
@@ -207,6 +212,53 @@ function parseRenderFormat(input: string): RenderFormat | undefined {
return RENDER_FORMATS.find((format) => format === input);
}
+export interface RenderRange {
+ startSeconds: number;
+ endSeconds?: number;
+}
+
+function parseRenderRange(
+ args: Pick,
+ format: RenderFormat,
+ fps: Fps,
+ hdr: boolean | undefined,
+): RenderRange | undefined {
+ if (args.start === undefined && args.end === undefined) return undefined;
+ const seconds = (flag: string, raw: string): number => {
+ const parsed = raw.trim() === "" ? Number.NaN : Number(raw);
+ if (!Number.isFinite(parsed) || parsed < 0) {
+ errorBox(`Invalid ${flag}`, `Got "${raw}". Must be a number of seconds, 0 or more.`);
+ failUsage();
+ }
+ return parsed;
+ };
+ const startSeconds = args.start === undefined ? 0 : seconds("--start", args.start);
+ const endSeconds = args.end === undefined ? undefined : seconds("--end", args.end);
+ if (endSeconds !== undefined && endSeconds <= startSeconds) {
+ errorBox("Invalid range", `--end (${endSeconds}) must be after --start (${startSeconds}).`);
+ failUsage();
+ }
+ const limit = rangeLimit(format, fps, hdr);
+ if (limit) {
+ errorBox(
+ "A range renders what chunked renders can",
+ limit,
+ "Remove --start/--end to render the whole film.",
+ );
+ failUsage();
+ }
+ return { startSeconds, endSeconds };
+}
+
+function rangeLimit(format: RenderFormat, fps: Fps, hdr: boolean | undefined): string | undefined {
+ if (format !== "mp4") return `--start/--end render MP4 only, not ${format}.`;
+ if (fps.den !== 1 || !isDistributedFps(fps.num)) {
+ return `--start/--end need a whole frame rate in ${DISTRIBUTED_FPS.join(", ")}, not ${fps.num}/${fps.den}.`;
+ }
+ if (hdr) return "--start/--end render SDR only, not --hdr.";
+ return undefined;
+}
+
function positiveInteger(raw: string, title: string, message: string, min = 1): number {
const parsed = Number(raw);
if (!Number.isInteger(parsed) || parsed < min) {
@@ -457,7 +509,7 @@ export function createRenderPlan(args: RenderCommandArgs, now = new Date()): Ren
)
: 1;
- const rendersDir = resolve("renders");
+ const rendersDir = join(project.dir, "renders");
const ext = FORMAT_EXT[format];
const timestamp = formatRenderOutputTimestamp(now);
const batchOutputTemplate = args.output
@@ -545,6 +597,7 @@ export function createRenderPlan(args: RenderCommandArgs, now = new Date()): Ren
failUsage();
}
+ const range = parseRenderRange(args, format, fps, args.hdr);
const quiet = args.quiet ?? false;
const batchJson = args.json ?? false;
return Object.freeze({
@@ -592,6 +645,7 @@ export function createRenderPlan(args: RenderCommandArgs, now = new Date()): Ren
vp9CpuUsed,
videoBitrate,
...delivery,
+ range,
hdrMode: args.sdr ? "force-sdr" : args.hdr ? "force-hdr" : "auto",
pageSideCompositing: args["page-side-compositing"] !== false,
experimentalFastCapture: args["experimental-fast-capture"] === true,
diff --git a/packages/cli/src/commands/snapshot.lateImages.browser.test.ts b/packages/cli/src/commands/snapshot.lateImages.browser.test.ts
index 3f85548978..ad52605313 100644
--- a/packages/cli/src/commands/snapshot.lateImages.browser.test.ts
+++ b/packages/cli/src/commands/snapshot.lateImages.browser.test.ts
@@ -69,20 +69,28 @@ function writeProject(name: string, reveal: string): string {
async function snapshotAt(dir: string, time: string) {
const output = join(dir, "out");
const log = vi.spyOn(console, "log").mockImplementation(() => undefined);
- vi.spyOn(console, "error").mockImplementation(() => undefined);
- vi.spyOn(console, "warn").mockImplementation(() => undefined);
+ const said: string[] = [];
+ const keep = (...parts: unknown[]) => void said.push(parts.map(String).join(" "));
+ vi.spyOn(console, "error").mockImplementation(keep);
+ vi.spyOn(console, "warn").mockImplementation(keep);
try {
- await snapshotCommand.run?.({
- args: {
- dir,
- at: time,
- end: false,
- json: true,
- output,
- describe: "false",
- "browser-gpu": false,
- },
- } as never);
+ try {
+ await snapshotCommand.run?.({
+ args: {
+ dir,
+ at: time,
+ end: false,
+ json: true,
+ output,
+ describe: "false",
+ "browser-gpu": false,
+ },
+ } as never);
+ } catch (error) {
+ throw new Error(`snapshot failed: ${[...said, ...log.mock.calls.flat()].join(" | ")}`, {
+ cause: error,
+ });
+ }
const envelope = JSON.parse(String(log.mock.calls.at(-1)?.[0]));
return { envelope, output };
} finally {
diff --git a/packages/cli/src/commands/snapshot.test.ts b/packages/cli/src/commands/snapshot.test.ts
index 74e9f7f71b..177f14d4b4 100644
--- a/packages/cli/src/commands/snapshot.test.ts
+++ b/packages/cli/src/commands/snapshot.test.ts
@@ -18,9 +18,23 @@ const snapshotState = vi.hoisted(() => ({
closeServer: vi.fn(async () => undefined),
ffmpegTimesOut: false,
ffmpegFails: false,
+ ffmpegKilled: false,
noFfmpeg: false,
}));
+const spawned = vi.hoisted(() => ({ files: [] as string[] }));
+
+vi.mock("../utils/cancellableProcess.js", async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ runCancellableProcess: (...args: Parameters) => {
+ spawned.files.push(String(args[0]));
+ return actual.runCancellableProcess(...args);
+ },
+ };
+});
+
vi.mock("../browser/ffmpeg.js", async (importOriginal) => {
const actual = await importOriginal();
return {
@@ -39,13 +53,15 @@ vi.mock("../capture/captureCompositionFrame.js", async (importOriginal) => {
runFfmpegOnce: (...args: Parameters) =>
snapshotState.ffmpegTimesOut
? Promise.resolve({ code: null, timedOut: true, stderr: "" })
- : snapshotState.ffmpegFails
- ? Promise.resolve({
- code: 1,
- timedOut: false,
- stderr: "\nError while decoding stream #0:0\n",
- })
- : actual.runFfmpegOnce(...args),
+ : snapshotState.ffmpegKilled
+ ? Promise.resolve({ code: 255, timedOut: false, stderr: "" })
+ : snapshotState.ffmpegFails
+ ? Promise.resolve({
+ code: 1,
+ timedOut: false,
+ stderr: "\nError while decoding stream #0:0\n",
+ })
+ : actual.runFfmpegOnce(...args),
};
});
@@ -61,6 +77,7 @@ import snapshotCommand, {
decodeFramesInOnePass,
extractVideoFrameOrWarn,
probeContainingSourceFrameSeek,
+ createSourceProbeCache,
containingSourceFrameIndex,
computeSnapshotTimes,
formatSnapshotTimestamp,
@@ -705,6 +722,47 @@ describe("extractVideoFrameToBuffer", () => {
},
);
+ it.skipIf(noProbe)(
+ "probes a clip once for all the times asked of it, and plans each time as it would alone",
+ async () => {
+ const dir = mkdtempSync(join(tmpdir(), "hf-snapshot-probe-cache-"));
+ try {
+ const clip = join(dir, "clip.mp4");
+ execFileSync(ffmpeg!, [
+ ...["-hide_banner", "-loglevel", "error", "-f", "lavfi"],
+ ...["-i", "testsrc2=d=20:r=25:s=320x180", "-c:v", "libx264", "-g", "50"],
+ ...["-pix_fmt", "yuv420p", clip],
+ ]);
+ const times = Array.from({ length: 40 }, (_, i) => 0.4 + i * 0.47);
+ spawned.files.length = 0;
+ const alone = [];
+ for (const time of times)
+ alone.push(await probeContainingSourceFrameSeek(clip, time, false));
+ const spawnedAlone = spawned.files.length;
+
+ spawned.files.length = 0;
+ const cache = createSourceProbeCache();
+ const horizon = times.at(-1)!;
+ const cached = await Promise.all(
+ times.map((time) =>
+ probeContainingSourceFrameSeek(clip, time, false, { cache, horizon }),
+ ),
+ );
+ expect(cached).toEqual(alone);
+ const probes = spawned.files.filter((file) => file === ffprobe).length;
+ const landings = spawned.files.length - probes;
+ // One stream read and one packet read; a seek landing per keyframe (a keyframe every 2 s), not per time.
+ expect(probes).toBe(2);
+ expect(landings).toBeLessThanOrEqual(2 * Math.ceil(20 / 2));
+ expect(spawned.files.length * 3, "far fewer processes than a probe per time").toBeLessThan(
+ spawnedAlone,
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ },
+ );
+
it.skipIf(noProbe)(
"gives two times inside one source frame the same frame, without decoding on",
async () => {
@@ -757,6 +815,24 @@ describe("extractVideoFrameToBuffer", () => {
return clip;
};
+ it.skipIf(noProbe)(
+ "says FFmpeg was stopped, not that a frame is bad, when it exits 255 with no output",
+ async () => {
+ const dir = mkdtempSync(join(tmpdir(), "hf-snapshot-killed-"));
+ snapshotState.ffmpegKilled = true;
+ try {
+ const warnings: string[] = [];
+ expect(await extractVideoFrameOrWarn(warnings, oneSecondClip(dir), 0.5)).toBeNull();
+ expect(warnings).toEqual([
+ expect.stringContaining("FFmpeg was stopped before it finished"),
+ ]);
+ } finally {
+ snapshotState.ffmpegKilled = false;
+ rmSync(dir, { recursive: true, force: true });
+ }
+ },
+ );
+
it.skipIf(noProbe)(
"records the clip, time and FFmpeg's reason when the extract fails",
async () => {
diff --git a/packages/cli/src/commands/snapshot.ts b/packages/cli/src/commands/snapshot.ts
index ef32e7e3dc..097c9fbcf3 100644
--- a/packages/cli/src/commands/snapshot.ts
+++ b/packages/cli/src/commands/snapshot.ts
@@ -379,6 +379,12 @@ export function containingSourceFrameIndex(timestamps: readonly number[], time:
class FrameExtractError extends Error {}
const lastLine = (text: string) => text.trim().split("\n").at(-1) ?? "";
+
+const ffmpegFailure = (result: { stderr: string; code: number | null }) =>
+ lastLine(result.stderr) ||
+ (result.code === 255
+ ? "FFmpeg was stopped before it finished (exit code 255 with no error output means it was killed, such as by a time limit)"
+ : `exit code ${result.code}`);
const processStderr = (error: unknown) =>
error instanceof Error && "stderr" in error && typeof error.stderr === "string"
? error.stderr
@@ -395,11 +401,24 @@ export async function remoteVideoInput(url: string, download = downloadToTemp):
}
}
+export interface SourceProbeCache {
+ streams: Map | null>>;
+ packets: Map | null> }>;
+ landings: Map>;
+}
+
+export const createSourceProbeCache = (): SourceProbeCache => ({
+ streams: new Map(),
+ packets: new Map(),
+ landings: new Map(),
+});
+
/** Keyframe seek plus the decoded-time threshold that selects the frame containing `time`, or null. */
export async function probeContainingSourceFrameSeek(
videoPath: string,
time: number,
holdLastFrame: boolean,
+ { cache, horizon = time }: { cache?: SourceProbeCache; horizon?: number } = {},
): Promise<{ seek?: number; select?: number; decodesFrom?: number } | null> {
const ffprobe = findFFprobe();
// Without ffprobe, fall back to a plain seek: the first frame at or after `time`.
@@ -428,7 +447,10 @@ export async function probeContainingSourceFrameSeek(
);
}
};
- const data = await probe("%+#1", "stream=time_base,start_pts:format=start_time,duration");
+ const streamQuery = () => probe("%+#1", "stream=time_base,start_pts:format=start_time,duration");
+ const data = await (cache
+ ? (cache.streams.get(videoPath) ?? cache.streams.set(videoPath, streamQuery()).get(videoPath)!)
+ : streamQuery());
if (data === null || !Array.isArray(data.streams)) return null;
const stream: unknown = data.streams[0];
if (
@@ -458,7 +480,18 @@ export async function probeContainingSourceFrameSeek(
const startTicks =
Math.abs(startPts * timeBase - formatStart) <= 1e-6 ? startPts : formatStart / timeBase;
// An absolute end: edit-list preroll packets start before the video, so a relative window can stop short.
- const packetData = await probe(`%${startTicks * timeBase + time + 1}`, "packet=pts,dts,flags");
+ const packetEnd = Math.max(time, horizon) + 1;
+ const packetQuery = () => probe(`%${startTicks * timeBase + packetEnd}`, "packet=pts,dts,flags");
+ const kept = cache?.packets.get(videoPath);
+ const packetData = await (kept && kept.end >= packetEnd
+ ? kept.data
+ : cache
+ ? (() => {
+ const data = packetQuery();
+ cache.packets.set(videoPath, { end: packetEnd, data });
+ return data;
+ })()
+ : packetQuery());
if (packetData === null || !Array.isArray(packetData.packets)) return null;
const packets: { pts: number; dts: number; key: boolean }[] = [];
for (const packet of packetData.packets) {
@@ -481,7 +514,12 @@ export async function probeContainingSourceFrameSeek(
// seek lands; a seek to exactly that keyframe trims its leading frames, so it is `start_t`.
const ffmpeg = findFFmpeg();
const landing = async (seek: number) => {
- const raw = ffmpeg ? await probeSeekLanding(ffmpeg, videoPath, seek) : null;
+ const key = `${videoPath}\0${seek}`;
+ const asked =
+ cache?.landings.get(key) ??
+ (ffmpeg ? probeSeekLanding(ffmpeg, videoPath, seek) : Promise.resolve(null));
+ cache?.landings.set(key, asked);
+ const raw = await asked;
return raw === null ? null : raw - startTicks * timeBase;
};
const candidates = packets.filter(
@@ -639,9 +677,7 @@ export async function extractVideoFrameToBuffer(
);
}
if (result.code !== 0 || !existsSync(outPath)) {
- throw new FrameExtractError(
- `FFmpeg could not extract ${frameOf}: ${lastLine(result.stderr) || `exit code ${result.code}`}`,
- );
+ throw new FrameExtractError(`FFmpeg could not extract ${frameOf}: ${ffmpegFailure(result)}`);
}
return readFileSync(outPath);
} finally {
@@ -702,9 +738,7 @@ export async function decodeFramesInOnePass(
}
const written = (n: number) => join(tmp, `${n}.png`);
if (result.code !== 0 || !byTime.every((_, i) => existsSync(written(i + 1)))) {
- throw new FrameExtractError(
- `FFmpeg could not extract ${what}: ${lastLine(result.stderr) || `exit code ${result.code}`}`,
- );
+ throw new FrameExtractError(`FFmpeg could not extract ${what}: ${ffmpegFailure(result)}`);
}
const buffers: Buffer[] = [];
for (const [i, [, indexes]] of byTime.entries()) {
@@ -847,7 +881,7 @@ export function serveCapturePage(projectDir: string, html: string, proxy: boolea
* Render key frames from a composition as PNG screenshots.
* The agent can Read these to verify its output visually.
*/
-async function captureSnapshots(
+export async function captureSnapshots(
projectDir: string,
opts: {
frames?: number;
@@ -870,13 +904,17 @@ async function captureSnapshots(
review?: boolean;
/** Progress lines; `--json` sends them to stderr so stdout stays one envelope. */
log?: (message: string) => void;
+ record?: boolean;
},
): Promise {
const startedAt = performance.now();
const log = opts.log ?? ((message: string) => console.log(message));
const { bundleWithLocalizedFonts } = await import("../utils/bundleWithLocalizedFonts.js");
- const capture = await captureArtifactRevision(projectDir).catch(warnSnapshotsNotRecorded);
+ const capture =
+ opts.record === false
+ ? undefined
+ : await captureArtifactRevision(projectDir).catch(warnSnapshotsNotRecorded);
const invocation = randomUUID();
const artifacts: Array<{
id: string;
@@ -1099,8 +1137,13 @@ async function captureSnapshots(
console.warn(` ${c.warn("⚠")} No player API — seeks will be skipped`);
}
+ const sourceProbes = createSourceProbeCache();
const frameBank = createFrameBank({
- probe: probeContainingSourceFrameSeek,
+ probe: (path, time, holdLastFrame, horizon) =>
+ probeContainingSourceFrameSeek(path, time, holdLastFrame, {
+ cache: sourceProbes,
+ horizon,
+ }),
decode: async (path, frames) =>
decodeFramesInOnePass(
path,
@@ -1404,7 +1447,7 @@ async function captureSnapshots(
log,
)
: false;
- if (!recorded) {
+ if (!recorded && opts.record !== false) {
const paths = [...replaced, ...artifacts.map((artifact) => artifact.image)];
if (paths.length > 0) await forgetRecordedArtifacts(projectDir, paths).catch(() => undefined);
}
diff --git a/packages/cli/src/commands/snapshotFrameBank.ts b/packages/cli/src/commands/snapshotFrameBank.ts
index 45854d1405..608d210c0d 100644
--- a/packages/cli/src/commands/snapshotFrameBank.ts
+++ b/packages/cli/src/commands/snapshotFrameBank.ts
@@ -19,7 +19,12 @@ export interface PlannedFrame extends FrameWant {
}
interface FrameBankDeps {
- probe: (path: string, time: number, holdLastFrame: boolean) => Promise;
+ probe: (
+ path: string,
+ time: number,
+ holdLastFrame: boolean,
+ horizon: number,
+ ) => Promise;
/** One ffmpeg pass over `frames`, which share a displayed size; throws when the pass fails. */
decode: (path: string, frames: PlannedFrame[]) => Promise;
}
@@ -62,8 +67,9 @@ async function probeFrames(
wants: FrameWant[],
): Promise {
try {
+ const horizon = Math.max(...wants.map((want) => want.time));
const plans = await Promise.all(
- wants.map((want) => probe(path, want.time, want.holdLastFrame)),
+ wants.map((want) => probe(path, want.time, want.holdLastFrame, horizon)),
);
return plans.flatMap((plan, i) =>
plan?.seek !== undefined && plan.select !== undefined
diff --git a/packages/cli/src/commands/snapshotReview.test.ts b/packages/cli/src/commands/snapshotReview.test.ts
index 46793b29b5..99c3784e76 100644
--- a/packages/cli/src/commands/snapshotReview.test.ts
+++ b/packages/cli/src/commands/snapshotReview.test.ts
@@ -43,6 +43,34 @@ describe("resolveReviewTimeline", () => {
expect(timeline.scenes).toEqual([{ id: "number", start: 7.2, end: 13 }]);
});
+ it("names the --composition command for a host that holds several timed clips", () => {
+ const html = ``;
+ expect(resolveReviewTimeline(html, {}, 10).notes).toEqual([
+ "reel holds several timed clips; run --review --composition reel-comp to review its cuts.",
+ ]);
+ });
+
+ it("leaves out the note for hosts whose layers share one start and end", () => {
+ const html = `
+
+
+
+
+
`;
+ expect(resolveReviewTimeline(html, {}, 10).notes).toEqual([]);
+ });
+
it("times a host without data-duration from its registered timeline", () => {
const html = `
diff --git a/packages/cli/src/commands/snapshotReview.ts b/packages/cli/src/commands/snapshotReview.ts
index 8b1318fbeb..3b2fb35d48 100644
--- a/packages/cli/src/commands/snapshotReview.ts
+++ b/packages/cli/src/commands/snapshotReview.ts
@@ -94,17 +94,33 @@ export function resolveReviewTimeline(
return to > from ? [roundMs(from), roundMs(to)] : null;
};
const scenes: ReviewScene[] = [];
- const rows = topLevelElements(toDomNode(target as unknown as Element)).filter((node) => {
- const kind = trackKindOf(node).kind;
- return kind === "video" || kind === "graphics";
- });
- rows.forEach((node, index) => {
+ const notes: string[] = [];
+ const sceneRows = (root: ReturnType
) =>
+ topLevelElements(root).filter((node) => {
+ const kind = trackKindOf(node).kind;
+ return kind === "video" || kind === "graphics";
+ });
+ sceneRows(toDomNode(target as unknown as Element)).forEach((node, index) => {
const interval = span(node.el);
- if (interval)
- scenes.push({ id: sceneId(node.el, index), start: interval[0], end: interval[1] });
+ if (!interval) return;
+ const id = sceneId(node.el, index);
+ scenes.push({ id, start: interval[0], end: interval[1] });
+ const inner = node.el.getAttribute("data-composition-id");
+ const innerScenes = inner
+ ? sceneRows(node).flatMap((row, rowIndex) => {
+ const inside = span(row.el);
+ return inside
+ ? [{ id: sceneId(row.el, rowIndex), start: inside[0], end: inside[1] }]
+ : [];
+ })
+ : [];
+ if (inner && innerScenes.length >= 2 && seamTimes(innerScenes, interval).length > 0) {
+ notes.push(
+ `${id} holds several timed clips; run --review --composition ${inner} to review its cuts.`,
+ );
+ }
});
const beats: ReviewBeat[] = [];
- const notes: string[] = [];
for (const el of Array.from((target as unknown as Element).querySelectorAll("[data-beat]"))) {
const name = el.getAttribute("data-beat")?.trim() || sceneId(el, beats.length);
const timed = el.hasAttribute("data-start") || el.hasAttribute("data-composition-id");
diff --git a/packages/cli/src/commands/telemetry.ts b/packages/cli/src/commands/telemetry.ts
index 0a67d52044..0d90e0dc20 100644
--- a/packages/cli/src/commands/telemetry.ts
+++ b/packages/cli/src/commands/telemetry.ts
@@ -74,7 +74,7 @@ function runStatus(): void {
}
export default defineCommand({
- meta: { name: "telemetry", description: "Manage anonymous usage telemetry" },
+ meta: { name: "telemetry", description: "Manage usage telemetry" },
args: {
subcommand: {
type: "positional",
@@ -89,23 +89,24 @@ export default defineCommand({
console.log(`
${c.bold("hyperframes telemetry")} ${c.dim("")}
-Manage anonymous usage data collection.
+Manage usage data collection (anonymous until you sign in to HeyGen).
${c.bold("SUBCOMMANDS:")}
${c.accent("status")} ${c.dim("Show current telemetry status")}
- ${c.accent("enable")} ${c.dim("Enable anonymous telemetry")}
- ${c.accent("disable")} ${c.dim("Disable anonymous telemetry")}
+ ${c.accent("enable")} ${c.dim("Enable usage telemetry")}
+ ${c.accent("disable")} ${c.dim("Disable usage telemetry")}
${c.bold("WHAT WE COLLECT:")}
${c.dim("\u2022")} Command names (init, render, preview, etc.)
${c.dim("\u2022")} Render performance (duration, fps, quality)
${c.dim("\u2022")} Template choices
${c.dim("\u2022")} OS, architecture, Node.js version, CLI version
+ ${c.dim("\u2022")} Once you sign in to HeyGen: your account email and username
${c.bold("WHAT WE DON'T COLLECT:")}
${c.dim("\u2022")} File paths, project names, or video content
${c.dim("\u2022")} IP addresses (discarded by our analytics provider)
- ${c.dim("\u2022")} Any personally identifiable information
+ ${c.dim("\u2022")} Anything that identifies you before you sign in
${c.dim("You can also set")} ${c.accent("HYPERFRAMES_NO_TELEMETRY=1")} ${c.dim("or")} ${c.accent("DO_NOT_TRACK=1")} ${c.dim("to disable.")}
`);
diff --git a/packages/cli/src/commands/transcribe.ts b/packages/cli/src/commands/transcribe.ts
index 501dc4e439..1b690eeb1b 100644
--- a/packages/cli/src/commands/transcribe.ts
+++ b/packages/cli/src/commands/transcribe.ts
@@ -19,6 +19,10 @@ import { jsonFailure } from "../utils/jsonError.js";
export const examples: Example[] = [
["Transcribe an audio file", "hyperframes transcribe audio.mp3"],
["Transcribe a video file", "hyperframes transcribe video.mp4"],
+ [
+ "Transcribe on HeyGen, with speakers",
+ "hyperframes transcribe interview.mp4 --engine heygen --speakers",
+ ],
["Use a larger model for better accuracy", "hyperframes transcribe audio.mp3 --model medium.en"],
["Set language to filter non-target speech", "hyperframes transcribe audio.mp3 --language en"],
["Import an existing SRT file", "hyperframes transcribe subtitles.srt"],
@@ -52,9 +56,14 @@ export default defineCommand({
engine: {
type: "string",
description:
- "ASR engine: auto (Parakeet if installed and it covers --language, else whisper), parakeet, or whisper. Default: auto. Parakeet is more accurate and faster; install it with `hyperframes models install parakeet`.",
+ "ASR engine: auto (Parakeet if installed and it covers --language, else whisper), parakeet, whisper, or heygen (HeyGen's speech model; needs an API key, charged to API credits). Default: auto. Parakeet is more accurate and faster than whisper; install it with `hyperframes models install parakeet`.",
alias: "e",
},
+ speakers: {
+ type: "boolean",
+ description: "With --engine heygen: label each word with its speaker",
+ default: false,
+ },
model: {
type: "string",
description: `Whisper model (default: ${DEFAULT_MODEL}). Options: tiny.en, base.en, small.en, medium.en, small, medium, large-v3`,
@@ -119,6 +128,7 @@ export default defineCommand({
input: args.input,
dir: args.dir,
engine: args.engine,
+ speakers: args.speakers,
model: args.model,
language: args.language,
installRuntime: args["runtime-install"],
diff --git a/packages/cli/src/docs/motion-blur.md b/packages/cli/src/docs/motion-blur.md
new file mode 100644
index 0000000000..1eaccd4030
--- /dev/null
+++ b/packages/cli/src/docs/motion-blur.md
@@ -0,0 +1,28 @@
+# Motion Blur
+
+Fast-moving elements get a shutter smear along their path. It is opt-in: nothing blurs until the composition root has `data-motion-blur="on"`.
+
+## Turn it on
+
+- `data-motion-blur` — `on` enables blur; `off` opts out, on the root or on any subtree
+- `data-motion-blur-shutter` — shutter angle in degrees, 0-720 (default: 240)
+- `data-motion-blur-samples` — samples per frame, 2-64 (default: at least 32, sized to the smear)
+- `data-motion-blur-events` — `on` runs timeline callbacks while blur looks for movers; needed when motion is set from a `render(t)` callback
+- `data-motion-blur-tier` — `auto` (default), `capture` or `filter`
+
+The same attributes drive the browser editor preview and `hyperframes render`.
+
+## Two ways it is drawn
+
+- `capture` redraws each mover along its path, so turns and zooms smear truthfully. Needs a browser with HTML in Canvas.
+- `filter` puts an SVG filter on each mover. Works in any Chrome and costs little; turns and zooms are only softened.
+
+`auto` uses `filter` when every mover only translates and `capture` when anything turns or scales.
+
+## Check and render
+
+- `npx hyperframes check` reports `motion_blur_filter_fallback`, `motion_blur_no_movers` and `motion_blur_unverified`
+- `hyperframes render --page-motion-blur off` renders without the composition's blur
+- Blur is off for HDR, distributed, and sub-frame-blur renders
+
+Full guide: https://hyperframes.heygen.com/guides/motion-blur
diff --git a/packages/cli/src/help.ts b/packages/cli/src/help.ts
index 8949e249e9..a467cf66b2 100644
--- a/packages/cli/src/help.ts
+++ b/packages/cli/src/help.ts
@@ -59,6 +59,12 @@ const GROUPS: Group[] = [
"Render candidate color grades onto a reference frame as one labeled comparison PNG",
],
["compare", "Render composition variants into one labeled comparison sheet"],
+ ["diff", "Score a render or a project against the original video, frame by frame"],
+ [
+ "measure",
+ "Measure a video file: clock, cuts, events, frames, motion, crops, boxes, eases, look",
+ ],
+ ["billing", "Open the HyperFrames plans or credits page and wait until it is done"],
["info", "Print project metadata"],
["compositions", "List all compositions in a project"],
["timeline", "Print the project's tracks and clips"],
@@ -107,8 +113,8 @@ const GROUPS: Group[] = [
{
title: "Settings",
commands: [
- ["feedback", "Submit anonymous feedback about your experience"],
- ["telemetry", "Manage anonymous usage telemetry"],
+ ["feedback", "Submit feedback about your experience"],
+ ["telemetry", "Manage usage telemetry"],
],
},
];
diff --git a/packages/cli/src/heygen/generate.test.ts b/packages/cli/src/heygen/generate.test.ts
new file mode 100644
index 0000000000..b7735f020e
--- /dev/null
+++ b/packages/cli/src/heygen/generate.test.ts
@@ -0,0 +1,517 @@
+import { execFileSync } from "node:child_process";
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, afterEach, describe, expect, it, vi } from "vitest";
+import { findFFmpeg } from "../browser/ffmpeg.js";
+import { probeVideo } from "../measure/media.js";
+
+vi.mock("../cloud/auth.js", () => ({
+ resolveCloudAuthHeaders: async () => ({ "x-api-key": "k" }),
+ refreshIfNeeded: async (credential: T) => credential,
+ resolveCloudBaseUrl: () => "https://api.test",
+}));
+
+vi.stubEnv("HEYGEN_API_KEY", "k");
+
+const { checkRequest, generate, parseMask, structureRatio, urlOf } = await import("./generate.js");
+const { checkLimit, creditsOf, priceOf } = await import("./pricing.js");
+const ffmpeg = findFFmpeg();
+const project = mkdtempSync(join(tmpdir(), "hf-generate-test-"));
+writeFileSync(join(project, "index.html"), "");
+afterAll(() => rmSync(project, { recursive: true, force: true }));
+afterEach(() => vi.unstubAllGlobals());
+
+const json = (body: unknown) => new Response(JSON.stringify(body), { status: 200 });
+
+/** A 30 fps clip of these lavfi sources one after another: each new source is a cut. */
+function shots(name: string, sources: string[], size = "180x320"): string {
+ const path = join(project, name);
+ execFileSync(ffmpeg!, [
+ ...["-v", "error", "-y"],
+ ...sources.flatMap((src) => ["-f", "lavfi", "-i", `${src}:s=${size}:r=30`]),
+ ...["-filter_complex", `concat=n=${sources.length}:v=1`, "-pix_fmt", "yuv420p", path],
+ ]);
+ return path;
+}
+
+describe("generate", () => {
+ it("finds the file URL wherever the route keeps it", () => {
+ expect(
+ urlOf({ id: "a", status: "completed", images: [{ url: "https://x/i.png" }] }, [
+ "images.0.url",
+ ]),
+ ).toBe("https://x/i.png");
+ expect(
+ urlOf({ id: "a", status: "completed", video_url: "ftp://no" }, ["video_url"]),
+ ).toBeNull();
+ });
+
+ it.skipIf(!ffmpeg)("edits a picture from a reference, downloads it and records it", async () => {
+ const ref = join(project, "ref.png");
+ execFileSync(ffmpeg!, [
+ "-v",
+ "error",
+ "-y",
+ "-f",
+ "lavfi",
+ "-i",
+ "color=c=red:s=64x36",
+ "-frames:v",
+ "1",
+ ref,
+ ]);
+ const sent: { url: string; body?: Record }[] = [];
+ vi.stubGlobal("fetch", async (url: string, init?: RequestInit) => {
+ sent.push({ url, ...(init?.body ? { body: JSON.parse(String(init.body)) } : {}) });
+ if (url === "https://files.test/plate.png") return new Response(new Uint8Array([1, 2, 3]));
+ return json({
+ data: {
+ id: "img1",
+ status: "completed",
+ images: [{ url: "https://files.test/plate.png" }],
+ },
+ });
+ });
+ const r = await generate({
+ type: "image",
+ out: join(project, "assets/plate.png"),
+ prompt: "empty room",
+ references: [ref],
+ });
+ expect(sent[0]!.body).toMatchObject({
+ model: "nano-banana-2",
+ prompt: "empty room",
+ reference_images: [{ type: "base64", media_type: "image/jpeg" }],
+ });
+ expect(readFileSync(r.out)).toEqual(Buffer.from([1, 2, 3]));
+ const ledger = readFileSync(join(project, ".media/manifest.jsonl"), "utf8");
+ expect(ledger).toContain('"source":"generated"');
+ expect(ledger).toContain('"references":["ref.png"]');
+ });
+
+ it.skipIf(!ffmpeg)("re-shoots a person speaking a stretch of the original voice", async () => {
+ const [face, voice] = [join(project, "face.png"), join(project, "voice.m4a")];
+ execFileSync(ffmpeg!, [
+ "-v",
+ "error",
+ "-y",
+ "-f",
+ "lavfi",
+ "-i",
+ "color=c=gray:s=36x64",
+ "-frames:v",
+ "1",
+ face,
+ ]);
+ execFileSync(ffmpeg!, ["-v", "error", "-y", "-f", "lavfi", "-i", "sine=d=1", voice]);
+ const guide = join(project, "guide.mp4");
+ execFileSync(ffmpeg!, [
+ "-v",
+ "error",
+ "-y",
+ "-f",
+ "lavfi",
+ "-i",
+ "testsrc2=d=1:s=180x320",
+ guide,
+ ]);
+ const sent: Record[] = [];
+ vi.stubGlobal("fetch", async (url: string, init?: RequestInit) => {
+ if (init?.body) sent.push(JSON.parse(String(init.body)));
+ if (url === "https://files.test/s.mp4") return new Response(new Uint8Array([7]));
+ return json({
+ data: { id: "v2", status: "completed", video_url: "https://files.test/s.mp4" },
+ });
+ });
+ await generate({
+ type: "video",
+ out: join(project, "assets/presenter.mp4"),
+ prompt: "talks to camera",
+ references: [face],
+ audio: voice,
+ motion: guide,
+ seconds: 8,
+ aspect: "9:16",
+ });
+ expect(sent[0]).toMatchObject({
+ mode: "reference_to_video",
+ duration: 8,
+ aspect_ratio: "9:16",
+ reference_images: [{ media_type: "image/jpeg" }],
+ reference_audio: [{ media_type: "audio/mpeg" }],
+ reference_videos: [{ media_type: "video/mp4" }],
+ });
+ expect(readFileSync(join(project, ".media/manifest.jsonl"), "utf8")).toContain(
+ '"audio":"voice.m4a"',
+ );
+ await expect(
+ generate({ type: "video", out: "x.mp4", prompt: "p", audio: voice, firstFrame: face }),
+ ).rejects.toThrow(/--first-frame cannot be used/);
+ });
+
+ /** A static sine texture (smooth fills cannot copy it), with a white bar sliding through x 30..150 when `bar`. */
+ function textured(name: string, size: string, bar: boolean): string {
+ const path = join(project, name);
+ const slide = bar ? ",drawbox=x='30+t*40':y=100:w=20:h=30:color=white:t=fill" : "";
+ execFileSync(ffmpeg!, [
+ ...["-v", "error", "-y", "-f", "lavfi", "-i", `color=c=gray:s=${size}:r=30:d=3`],
+ ...[
+ "-vf",
+ `geq=lum='128+100*sin(X/3)*sin(Y/3)':cb=128:cr=128${slide}`,
+ "-pix_fmt",
+ "yuv420p",
+ path,
+ ],
+ ]);
+ return path;
+ }
+
+ const answers = (file: string) => {
+ const sent: Record[] = [];
+ vi.stubGlobal("fetch", async (url: string, init?: RequestInit) => {
+ if (init?.body) sent.push(JSON.parse(String(init.body)));
+ if (url === "https://files.test/r.mp4") return new Response(readFileSync(file));
+ return json({
+ data: { id: "r1", status: "completed", video_url: "https://files.test/r.mp4" },
+ });
+ });
+ return sent;
+ };
+
+ it.skipIf(!ffmpeg)(
+ "fills a masked box with the picture behind moving text, not a smear",
+ async () => {
+ const guide = textured("slide.mp4", "180x320", true);
+ const sent = answers(guide);
+ await generate({
+ type: "video",
+ out: join(project, "assets/slide-out.mp4"),
+ prompt: "p",
+ motion: guide,
+ masks: [parseMask("30,90,120,50")],
+ });
+ const [video] = sent[0]!.reference_videos as { data: string }[];
+ const sentClip = join(project, "slide-sent.mp4");
+ writeFileSync(sentClip, Buffer.from(video!.data, "base64"));
+ const box = (f: string) =>
+ execFileSync(ffmpeg!, [
+ ...["-v", "error", "-ss", "1.5", "-i", f, "-frames:v", "1"],
+ ...["-vf", "crop=120:50:30:90,format=gray", "-f", "rawvideo", "-"],
+ ]);
+ const [got, clean] = [box(sentClip), box(textured("slide-clean.mp4", "180x320", false))];
+ const diff = got.reduce((a, v, i) => a + Math.abs(v - clean[i]!), 0) / got.length;
+ expect(diff).toBeLessThan(12);
+ },
+ );
+
+ it("reads a box with more edges than its surroundings as structure", () => {
+ const flat = new Uint8Array(100 * 100).fill(100);
+ expect(structureRatio(flat, 100, [40, 40, 20, 20])).toEqual({ inside: 0, ring: 0 });
+ for (let y = 40; y < 60; y++)
+ for (let x = 40; x < 60; x++) flat[y * 100 + x] = (x + y) % 2 ? 255 : 0;
+ const { inside, ring } = structureRatio(flat, 100, [40, 40, 20, 20]);
+ expect(inside).toBeGreaterThan(100);
+ expect(inside).toBeGreaterThan(10 * ring);
+ });
+
+ it.skipIf(!ffmpeg)(
+ "says so when the result still shows structure inside a masked box",
+ async () => {
+ const guide = textured("flatguide.mp4", "180x320", false);
+ const busy = join(project, "busy.mp4");
+ execFileSync(ffmpeg!, [
+ ...["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=gray:s=180x320:r=30:d=1"],
+ ...[
+ "-vf",
+ "geq=lum='if(between(X,30,150)*between(Y,90,140),128+120*sin(X*2)*sin(Y*2),128)':cb=128:cr=128",
+ ],
+ ...["-pix_fmt", "yuv420p", busy],
+ ]);
+ answers(busy);
+ const flatMask = parseMask("30,90,120,50");
+ const r = await generate({
+ type: "video",
+ out: join(project, "assets/busy-out.mp4"),
+ prompt: "p",
+ motion: guide,
+ masks: [flatMask],
+ aspect: "9:16",
+ });
+ expect(r.notes?.join(" ")).toContain("mask 30,90,120,50 still shows structure");
+ },
+ );
+
+ it.skipIf(!ffmpeg)(
+ "crops a 1344x768 answer to the requested 16:9, never stretches it",
+ async () => {
+ answers(textured("wide.mp4", "1344x768", false));
+ const r = await generate({
+ type: "video",
+ out: join(project, "assets/wide-out.mp4"),
+ prompt: "p",
+ });
+ const { width, height } = probeVideo(r.out);
+ expect([width, height]).toEqual([1344, 756]);
+ expect(r.notes?.[0]).toBe(
+ "HeyGen returned 1344x768 for 16:9; cropped to 1344x756 (centre), not stretched",
+ );
+ },
+ );
+
+ it.skipIf(!ffmpeg)("blanks the motion clip's masked regions before sending it", async () => {
+ // A guide with white letters at 40,100 over a moving picture; the mask covers them for its first 0.5 s.
+ const guide = join(project, "titled.mp4");
+ execFileSync(ffmpeg!, [
+ ...["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=d=1:s=180x320", "-vf"],
+ "drawbox=x=40:y=100:w=100:h=10:color=white:t=fill,drawbox=x=40:y=120:w=100:h=10:color=white:t=fill",
+ guide,
+ ]);
+ const face = join(project, "face2.png");
+ execFileSync(ffmpeg!, [
+ ...["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=gray:s=36x64", "-frames:v", "1"],
+ face,
+ ]);
+ const sent: Record[] = [];
+ vi.stubGlobal("fetch", async (url: string, init?: RequestInit) => {
+ if (init?.body) sent.push(JSON.parse(String(init.body)));
+ if (url === "https://files.test/m.mp4") return new Response(new Uint8Array([7]));
+ return json({
+ data: { id: "v3", status: "completed", video_url: "https://files.test/m.mp4" },
+ });
+ });
+ await generate({
+ type: "video",
+ out: join(project, "assets/masked.mp4"),
+ prompt: "walks",
+ references: [face],
+ motion: guide,
+ masks: [parseMask("30,90,120,50,0-0.5")],
+ });
+ const [video] = sent[0]!.reference_videos as { data: string }[];
+ const sentClip = join(project, "sent.mp4");
+ writeFileSync(sentClip, Buffer.from(video!.data, "base64"));
+ // The letters are two white rows of bars: the largest step between neighbouring rows' brightness is their edge.
+ // Filled from around, no such step is left; after 0.5 s they are back.
+ const edge = (t: number) => {
+ const px = execFileSync(ffmpeg!, [
+ ...["-v", "error", "-ss", String(t), "-i", sentClip, "-frames:v", "1"],
+ ...["-vf", "crop=100:40:40:95,format=gray", "-f", "rawvideo", "-"],
+ ]);
+ const rows = Array.from({ length: 40 }, (_, y) => px.subarray(y * 100, y * 100 + 100));
+ const mean = rows.map((r) => r.reduce((a, v) => a + v, 0) / r.length);
+ return Math.max(...mean.slice(1).map((m, y) => Math.abs(m - mean[y]!)));
+ };
+ expect(edge(0.2)).toBeLessThan(30);
+ expect(edge(0.8)).toBeGreaterThan(60);
+ expect(readFileSync(join(project, ".media/manifest.jsonl"), "utf8")).toContain(
+ '"motion_masks":[[30,90,120,50,0,0.5]]',
+ );
+ expect(() => parseMask("30,90,120")).toThrow(/x,y,w,h/);
+ const { repeated } = await import("../commands/media-use/generate.js");
+ expect(
+ repeated(["--mask", "1,1,2,2", "--out", "a.mp4", "--mask=3,3,4,4,0-1"], "--mask"),
+ ).toEqual(["1,1,2,2", "3,3,4,4,0-1"]);
+ await expect(
+ generate({ type: "video", out: "x.mp4", prompt: "p", masks: [parseMask("1,1,2,2")] }),
+ ).rejects.toThrow(/--mask blanks regions of the --motion clip/);
+ });
+
+ it.skipIf(!ffmpeg)("refuses a guide with a cut inside before sending anything", async () => {
+ const guide = shots("two-shots.mp4", ["color=c=red:d=1", "testsrc2=d=1"]);
+ const face = join(project, "face3.png");
+ execFileSync(ffmpeg!, [
+ ...["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=gray:s=36x64", "-frames:v", "1"],
+ face,
+ ]);
+ const fetched = vi.fn();
+ vi.stubGlobal("fetch", fetched);
+ const request = {
+ type: "video" as const,
+ out: join(project, "assets/refused.mp4"),
+ prompt: "talks",
+ references: [face],
+ motion: guide,
+ };
+ await expect(generate(request)).rejects.toMatchObject({
+ message: `--motion ${guide} has a cut at 1.00 s`,
+ fix: "guide has a cut at 1.00 s: generate 0–1.00 s and 1.00–2.00 s as two shots, each with its own --motion clip",
+ });
+ expect(fetched).not.toHaveBeenCalled();
+ expect(existsSync(request.out)).toBe(false);
+ });
+
+ it.skipIf(!ffmpeg)("reports where HeyGen cut inside the returned shot", async () => {
+ // The guide's last frame is another picture: a cut within a frame of the end is no second shot, so it is sent.
+ const guide = shots("stray-frame.mp4", ["testsrc2=d=1", "color=c=blue:d=0.02"]);
+ const made = shots("heygen-cut.mp4", ["testsrc2=d=1", "color=c=red:d=1"]);
+ const clean = shots("heygen-clean.mp4", ["testsrc2=d=2"]);
+ const face = join(project, "face4.png");
+ execFileSync(ffmpeg!, [
+ ...["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=gray:s=36x64", "-frames:v", "1"],
+ face,
+ ]);
+ let file = made;
+ const sent: Record[] = [];
+ vi.stubGlobal("fetch", async (url: string, init?: RequestInit) => {
+ if (init?.body) sent.push(JSON.parse(String(init.body)));
+ if (url === "https://files.test/c.mp4") return new Response(readFileSync(file));
+ return json({
+ data: { id: `c${sent.length}`, status: "completed", video_url: "https://files.test/c.mp4" },
+ });
+ });
+ const request = { type: "video" as const, prompt: "walks", references: [face], motion: guide };
+ const cut = await generate({ ...request, out: join(project, "assets/cut.mp4") });
+ expect(sent).toHaveLength(1);
+ expect(cut.cuts_inside).toEqual([1]);
+ expect(readFileSync(join(project, ".media/manifest.jsonl"), "utf8")).toContain(
+ '"cuts_inside":[1]',
+ );
+ file = clean;
+ const one = await generate({ ...request, out: join(project, "assets/one.mp4"), seconds: 6 });
+ expect(one.cuts_inside).toEqual([]);
+ });
+
+ it.skipIf(!ffmpeg)(
+ "asks for 768p whatever the source's size, as 1080p bills about twice",
+ async () => {
+ const guide = shots("tall.mp4", ["testsrc2=d=1"], "1080x1920");
+ const sent: Record[] = [];
+ vi.stubGlobal("fetch", async (url: string, init?: RequestInit) => {
+ if (init?.body) sent.push(JSON.parse(String(init.body)));
+ if (url === "https://files.test/t.mp4") return new Response(new Uint8Array([7]));
+ return json({
+ data: { id: "t1", status: "completed", video_url: "https://files.test/t.mp4" },
+ });
+ });
+ const r = await generate({
+ type: "video",
+ out: join(project, "assets/tall.mp4"),
+ prompt: "walks",
+ motion: guide,
+ aspect: "9:16",
+ });
+ expect(sent[0]).toMatchObject({ resolution: "768p", aspect_ratio: "9:16" });
+ // An unreadable download is kept and its cuts reported as unknown.
+ expect(r.cuts_inside).toBeNull();
+ // A reference shot bills its seconds and the guide's at $0.05: 5 s and the 1 s guide.
+ expect(priceOf({ type: "video", out: "a.mp4", motion: guide }).usd).toBe(0.3);
+ },
+ );
+
+ it("waits for a queued shot and downloads it", async () => {
+ const answers = [
+ json({ data: { video_id: "v1", status: "pending" } }),
+ json({ data: { id: "v1", status: "processing" } }),
+ json({ data: { id: "v1", status: "completed", video_url: "https://files.test/v1.mp4" } }),
+ new Response(new Uint8Array([9])),
+ ];
+ const urls: string[] = [];
+ vi.stubGlobal("fetch", async (url: string) => {
+ urls.push(url);
+ return answers.shift()!;
+ });
+ vi.useFakeTimers({ toFake: ["setTimeout"] });
+ const pending = generate({
+ type: "video",
+ out: join(project, "assets/shot.mp4"),
+ prompt: "push in",
+ seconds: 6,
+ });
+ await vi.runAllTimersAsync();
+ const r = await pending;
+ vi.useRealTimers();
+ expect(urls.slice(0, 3)).toEqual([
+ "https://api.test/v3/models/videos",
+ "https://api.test/v3/models/videos/v1",
+ "https://api.test/v3/models/videos/v1",
+ ]);
+ expect(existsSync(r.out)).toBe(true);
+ expect(r.job).toBe("v1");
+ });
+
+ it("names its own price when HeyGen refuses for credits without saying how many", async () => {
+ vi.stubGlobal(
+ "fetch",
+ async () =>
+ new Response(JSON.stringify({ error: { code: "hf_usage_exhausted" } }), { status: 402 }),
+ );
+ const request = {
+ type: "image",
+ out: join(project, "assets/broke.png"),
+ prompt: "a desk",
+ } as const;
+ await expect(
+ generate(request, undefined, creditsOf(priceOf(request)) ?? undefined),
+ ).rejects.toThrow("this step needs about 67");
+ });
+
+ it("prices before making", () => {
+ expect(priceOf({ type: "video", out: "a.mp4", seconds: 6 }).usd).toBe(0.12);
+ expect(priceOf({ type: "music", out: "a.mp3" }).usd).toBe(0.09);
+ expect(
+ priceOf({
+ type: "image",
+ out: "a.png",
+ model: "gpt-image-2.5",
+ aspect: "1:1",
+ references: ["a", "b"],
+ }).usd,
+ ).toBe(0.07);
+ expect(priceOf({ type: "voice", out: "a.mp3" }).usd).toBeNull();
+ });
+
+ it("prices only a request the real call would accept", () => {
+ // --plan runs the same checks as the real call, so it never prices a request the call would refuse.
+ const [plate, voice] = [join(project, "plate.png"), join(project, "voice.m4a")];
+ writeFileSync(plate, "");
+ writeFileSync(voice, "");
+ const shot = { type: "video" as const, out: "a.mp4", references: [plate], audio: voice };
+ expect(() => checkRequest(shot)).toThrow("--prompt is required for this type");
+ expect(() =>
+ checkRequest({ ...shot, prompt: "x", audio: join(project, "missing.m4a") }),
+ ).toThrow("no file at");
+ expect(() => checkRequest({ ...shot, prompt: "she talks to the camera" })).not.toThrow();
+ expect(() => checkRequest({ ...shot, prompt: "x", firstFrame: "f.png" })).toThrow(
+ "--first-frame cannot be used",
+ );
+ expect(() => checkRequest({ ...shot, prompt: "x", out: "a.png" })).toThrow(
+ "--out a.png does not fit a video",
+ );
+ expect(() => checkRequest({ ...shot, prompt: "x", masks: [parseMask("1,1,2,2")] })).toThrow(
+ "--mask blanks regions of the --motion clip",
+ );
+ });
+
+ it("prices an avatar on the plan's avatar rows, not its API price", () => {
+ const script = Array.from({ length: 30 }, () => "word").join(" ");
+ const avatar = priceOf({ type: "avatar", out: "a.mp4", script });
+ expect(creditsOf(avatar)).toBe(200);
+ expect(avatar.list).toBeCloseTo(1.2167);
+ expect(() => checkLimit(creditsOf(avatar), 220)).not.toThrow();
+ });
+
+ it("charges a reference shot's pictures after the first two", () => {
+ const shot = (pictures: number) => ({
+ type: "video" as const,
+ out: "a.mp4",
+ seconds: 5,
+ references: Array.from({ length: pictures }, (_, i) => `${i}.png`),
+ });
+ const credits = [1, 2, 3, 9].map((n) => creditsOf(priceOf(shot(n))));
+ expect(credits).toEqual([167, 167, 180, 260]);
+ expect(priceOf(shot(9)).list).toBeCloseTo(0.39);
+ expect(() => checkLimit(credits[3]!, 250)).toThrow("about 260 credits, over --max-credits 250");
+ expect(() => checkLimit(credits[3]!, 260)).not.toThrow();
+ });
+
+ it("keeps a call under the person's credit limit, or refuses it before sending", () => {
+ const shot = creditsOf(priceOf({ type: "video", out: "a.mp4", seconds: 6 }));
+ expect(shot).toBe(72);
+ expect(creditsOf(priceOf({ type: "image", out: "a.png" }))).toBe(67);
+ expect(() => checkLimit(shot, 72)).not.toThrow();
+ expect(() => checkLimit(shot, 30)).toThrow("about 72 credits, over --max-credits 30");
+ expect(() => checkLimit(null, 30)).toThrow("cannot be priced ahead");
+ expect(() => checkLimit(null, undefined)).not.toThrow();
+ });
+});
diff --git a/packages/cli/src/heygen/generate.ts b/packages/cli/src/heygen/generate.ts
new file mode 100644
index 0000000000..e957982702
--- /dev/null
+++ b/packages/cli/src/heygen/generate.ts
@@ -0,0 +1,558 @@
+// New media on HeyGen for `media-use generate`: a still (optionally edited from a reference), a shot (optionally from
+// a first frame), a person speaking from one photo, a voice reading text, or music. Every call is priced first with
+// --plan, keyed for idempotency, downloaded into the project and recorded in the media ledger as generated.
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ renameSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, extname, join, relative, resolve } from "node:path";
+import { findCuts, signatures } from "../measure/cuts.js";
+import { Fix, probeVideo, round, runFfmpeg, videoClip } from "../measure/media.js";
+import { idempotencyKey, runJob, type Job } from "./v3.js";
+
+export type GenerateType = "image" | "video" | "avatar" | "voice" | "music";
+export const GENERATE_TYPES: readonly GenerateType[] = [
+ "image",
+ "video",
+ "avatar",
+ "voice",
+ "music",
+];
+
+export interface GenerateRequest {
+ type: GenerateType;
+ out: string;
+ prompt?: string;
+ /** image: pictures the result is edited from or styled after. video: the person or things to keep in the shot. */
+ references?: string[];
+ /** video: speech the person in the references says, lips in sync (a stretch of the original's voice). */
+ audio?: string;
+ /** video: a clip whose camera and body motion the shot follows (the original's same stretch, up to 15 s). */
+ motion?: string;
+ /** video: regions of the motion clip blanked before it is sent (its drawn text), so the shot does not copy them. */
+ masks?: Mask[];
+ /** video: the shot starts from this picture. */
+ firstFrame?: string;
+ /** avatar: the photo of the person who speaks. */
+ photo?: string;
+ /** avatar and voice: what is said. */
+ script?: string;
+ voice?: string;
+ seconds?: number;
+ aspect?: string;
+ model?: string;
+ instrumental?: boolean;
+ bpm?: number;
+}
+
+/** A region of the motion clip in its pixels, and optionally the seconds of the clip it covers. */
+export interface Mask {
+ box: [number, number, number, number];
+ window?: [number, number];
+}
+
+/** `x,y,w,h` or `x,y,w,h,a-b` (seconds of the motion clip). */
+export function parseMask(text: string): Mask {
+ const m =
+ /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?)\s*-\s*(\d+(?:\.\d+)?)\s*)?$/.exec(
+ text,
+ );
+ if (!m || Number(m[3]) <= 0 || Number(m[4]) <= 0)
+ throw new Fix(`--mask ${text} is not x,y,w,h[,a-b]`, "--mask 190,405,700,175,1.0-2.7");
+ const box: Mask["box"] = [Number(m[1]), Number(m[2]), Number(m[3]), Number(m[4])];
+ return m[5] ? { box, window: [Number(m[5]), Number(m[6])] } : { box };
+}
+
+/**
+ * Fills a box from the pixels around it (ffmpeg delogo): no letter survives, but the box is smeared. Delogo needs a
+ * pixel of picture on every side, so boxes are kept 1 px inside the frame.
+ */
+function delogoFilters(masks: Mask[], width: number, height: number): string {
+ return masks
+ .flatMap(({ box: [x, y, w, h], window }) => {
+ const [x0, y0] = [Math.max(1, x), Math.max(1, y)];
+ const [x1, y1] = [Math.min(width - 2, x + w), Math.min(height - 2, y + h)];
+ if (x1 - x0 < 1 || y1 - y0 < 1) return [];
+ const when = window ? `:enable='between(t,${window[0]},${window[1]})'` : "";
+ return [`delogo=x=${x0}:y=${y0}:w=${x1 - x0}:h=${y1 - y0}${when}`];
+ })
+ .join(",");
+}
+
+/** A box's temporal median over about a second either side: moving text becomes the picture behind it. */
+function maskFilters(masks: Mask[], fps: number): string {
+ const radius = Math.min(127, Math.max(2, Math.round(fps)));
+ const steps = masks.map(({ box: [x, y, w, h], window }, i) => {
+ const when = window ? `:enable='between(t,${window[0]},${window[1]})'` : "";
+ const [w2, h2] = [w - (w % 2), h - (h % 2)];
+ return `[v${i}]split[a${i}][b${i}];[b${i}]crop=${w2}:${h2}:${x}:${y},tmedian=radius=${radius}[m${i}];[a${i}][m${i}]overlay=${x}:${y}${when}[v${i + 1}]`;
+ });
+ return `[0:v]null[v0];${steps.join(";")}`;
+}
+
+/** Mean absolute pixel step inside a box and in a ring around it: the box holds more edges when inside > ring. */
+export function structureRatio(
+ gray: Uint8Array,
+ width: number,
+ box: [number, number, number, number],
+): { inside: number; ring: number } {
+ const height = gray.length / width;
+ const [x0, y0, x1, y1] = [box[0], box[1], box[0] + box[2], box[1] + box[3]];
+ const pad = Math.max(box[2], box[3]) >> 1;
+ const sum = [0, 0];
+ const n = [0, 0];
+ for (let y = Math.max(0, y0 - pad); y < Math.min(height - 1, y1 + pad); y++)
+ for (let x = Math.max(0, x0 - pad); x < Math.min(width - 1, x1 + pad); x++) {
+ const k = x >= x0 && x < x1 && y >= y0 && y < y1 ? 0 : 1;
+ const i = y * width + x;
+ sum[k]! += Math.abs(gray[i]! - gray[i + 1]!) + Math.abs(gray[i]! - gray[i + width]!);
+ n[k]!++;
+ }
+ return { inside: sum[0]! / (n[0] || 1), ring: sum[1]! / (n[1] || 1) };
+}
+
+interface Route {
+ path: string;
+ poll: (id: string) => string;
+ body: (r: GenerateRequest, media: Media) => Record;
+ /** Where the finished job keeps the file's URL. */
+ urls: string[];
+ ledger: "image" | "video" | "voice" | "bgm";
+ ext: string[];
+}
+
+type Media = (
+ path: string,
+ kind: "image" | "audio" | "video",
+) => { type: "base64"; media_type: string; data: string };
+
+const DEFAULTS = { image: "nano-banana-2", video: "heygen-video-1", music: "lyria-3-pro" } as const;
+const VIDEO_RESOLUTION = "768p";
+/** HeyGen follows at most this many seconds of a guide clip; the rest is not sent. */
+export const GUIDE_MAX_S = 15;
+const MUSIC_LENGTHS = [30, 60, 120, 180];
+
+const need = (value: T | undefined, flag: string, example: string): T => {
+ if (value === undefined || value === "")
+ throw new Fix(`${flag} is required for this type`, example);
+ return value;
+};
+
+const ROUTES: Record = {
+ image: {
+ path: "/v3/images",
+ poll: (id) => `/v3/images/${id}`,
+ body: (r, media) => ({
+ model: r.model ?? DEFAULTS.image,
+ prompt: need(r.prompt, "--prompt", '--prompt "the same room, empty, no text"'),
+ num_images: 1,
+ ...(r.aspect ? { aspect_ratio: r.aspect } : {}),
+ ...(r.references?.length
+ ? { reference_images: r.references.map((p) => media(p, "image")) }
+ : {}),
+ }),
+ urls: ["images.0.url", "image_url", "url"],
+ ledger: "image",
+ ext: [".png", ".jpg", ".jpeg", ".webp"],
+ },
+ video: {
+ path: "/v3/models/videos",
+ poll: (id) => `/v3/models/videos/${id}`,
+ // fallow-ignore-next-line complexity
+ body: (r, media) => {
+ // A person speaking given audio is a reference shot: the references show who, the audio drives the lips.
+ const spoken = !!r.audio || !!r.references?.length || !!r.motion;
+ if (spoken && r.firstFrame)
+ throw new Fix(
+ "--first-frame cannot be used with --reference, --audio or --motion",
+ "a speaking shot takes the person as --reference and the voice as --audio",
+ );
+ return {
+ model: r.model ?? DEFAULTS.video,
+ mode: spoken ? "reference_to_video" : r.firstFrame ? "image_to_video" : "text_to_video",
+ prompt: need(r.prompt, "--prompt", '--prompt "slow push in on the desk"'),
+ duration: Math.min(15, Math.max(5, Math.round(r.seconds ?? 5))),
+ // 1080p bills about twice 768p (2026-10-23, 5 s 9:16 jobs: text $0.10 vs $0.20, a reference picture $0.25
+ // vs $0.45, a 1 s guide clip $0.30 vs $0.55), so every shot stays at 768p whatever the source's size.
+ resolution: VIDEO_RESOLUTION,
+ ...(r.firstFrame ? { image: media(r.firstFrame, "image") } : {}),
+ ...(r.firstFrame ? {} : { aspect_ratio: r.aspect ?? "16:9" }),
+ ...(r.references?.length
+ ? { reference_images: r.references.map((p) => media(p, "image")) }
+ : {}),
+ ...(r.audio ? { reference_audio: [media(r.audio, "audio")] } : {}),
+ // One guide clip: HeyGen follows its camera and body motion, and takes the face from the references.
+ ...(r.motion ? { reference_videos: [media(r.motion, "video")] } : {}),
+ };
+ },
+ urls: ["video_url", "output.video_url", "url"],
+ ledger: "video",
+ ext: [".mp4", ".mov", ".webm"],
+ },
+ avatar: {
+ path: "/v3/videos",
+ poll: (id) => `/v3/videos/${id}`,
+ body: (r, media) => ({
+ type: "image",
+ image: media(need(r.photo, "--photo", "--photo assets/presenter.png"), "image"),
+ script: need(r.script, "--script", '--script "What they say"'),
+ voice_id: need(
+ r.voice,
+ "--voice",
+ "--voice (npx hyperframes media-use resolve --type voice lists voices)",
+ ),
+ ...(r.aspect ? { aspect_ratio: r.aspect } : {}),
+ output_format: "mp4",
+ }),
+ urls: ["video_url"],
+ ledger: "video",
+ ext: [".mp4"],
+ },
+ voice: {
+ path: "/v3/voices/speech",
+ poll: (id) => `/v3/voices/speech/${id}`,
+ body: (r) => ({
+ text: need(r.script, "--script", '--script "What the voice says"'),
+ voice_id: need(r.voice, "--voice", "--voice "),
+ }),
+ urls: ["audio_url"],
+ ledger: "voice",
+ ext: [".mp3", ".wav", ".m4a"],
+ },
+ music: {
+ path: "/v3/audio/music",
+ poll: (id) => `/v3/audio/music/${id}`,
+ body: (r) => ({
+ model: r.model ?? DEFAULTS.music,
+ prompt: need(r.prompt, "--prompt", '--prompt "warm lo-fi beat, soft keys"'),
+ duration_seconds: MUSIC_LENGTHS.find((s) => s >= (r.seconds ?? 30)) ?? 180,
+ instrumental: r.instrumental ?? true,
+ ...(r.bpm ? { bpm: Math.round(r.bpm) } : {}),
+ }),
+ urls: ["audio_url"],
+ ledger: "bgm",
+ ext: [".mp3"],
+ },
+};
+
+const isRecord = (v: unknown): v is Record =>
+ typeof v === "object" && v !== null && !Array.isArray(v);
+
+/** The first URL at any of these dotted paths of a job. */
+export function urlOf(job: Job, paths: string[]): string | null {
+ for (const p of paths) {
+ let v: unknown = job;
+ for (const key of p.split("."))
+ v = Array.isArray(v) ? v[Number(key)] : isRecord(v) ? v[key] : undefined;
+ if (typeof v === "string" && /^https?:\/\//.test(v)) return v;
+ }
+ return null;
+}
+
+function needFile(path: string): void {
+ if (!existsSync(path))
+ throw new Fix(`no file at ${path}`, "pass a picture or sound from the project");
+}
+
+/**
+ * A picture or a sound as the routes take it inline, pictures shrunk to 2048 px so the body stays small, a motion
+ * clip with its masks filled.
+ */
+function inline(work: string, masks: Mask[] = []): Media {
+ return (path, kind) => {
+ needFile(path);
+ const out = join(
+ work,
+ `in-${Math.random().toString(36).slice(2)}.${{ image: "jpg", audio: "mp3", video: "mp4" }[kind]}`,
+ );
+ if (kind === "image")
+ runFfmpeg([
+ "-y",
+ "-i",
+ path,
+ "-vf",
+ "scale='min(2048,iw)':'min(2048,ih)':force_original_aspect_ratio=decrease",
+ "-q:v",
+ "3",
+ "-frames:v",
+ "1",
+ out,
+ ]);
+ else if (kind === "audio")
+ runFfmpeg(["-y", "-i", path, "-vn", "-ac", "1", "-c:a", "libmp3lame", "-b:a", "128k", out]);
+ // A guide clip only needs its motion: 720 px on the long side, no sound, at most 15 s.
+ else {
+ const guide = masks.length ? fillMasks(path, masks, work) : path;
+ const scale = "scale='if(gt(iw,ih),min(720,iw),-2)':'if(gt(iw,ih),-2,min(720,ih))'";
+ runFfmpeg([
+ ...["-y", "-i", guide, "-t", "15", "-an", "-vf", scale],
+ ...["-c:v", "libx264", "-crf", "28", "-preset", "veryfast", "-pix_fmt", "yuv420p", out],
+ ]);
+ }
+ return {
+ type: "base64",
+ media_type: { image: "image/jpeg", audio: "audio/mpeg", video: "video/mp4" }[kind],
+ data: readFileSync(out).toString("base64"),
+ };
+ };
+}
+
+/**
+ * The seconds where a new shot starts in a video's first `seconds`, and the length read. A cut within a frame of
+ * either end leaves a stray frame, not a second shot, and does not count.
+ */
+function cutsInside(path: string, seconds?: number): { cuts: number[]; length: number } {
+ const info = probeVideo(path);
+ const clip = videoClip(info.path, 0, seconds, info);
+ const { frames } = signatures(clip.input, clip.filters);
+ const cuts = findCuts(frames)
+ .filter((c) => c.frame > 1 && c.frame < frames.length - 1)
+ .map((c) => round(c.frame / info.fps, 3));
+ return { cuts, length: round(frames.length / info.fps, 3) };
+}
+
+/** The masks whose box, in `clip`'s frames, holds more edges than the picture around it at some sampled time. */
+function structured(clip: string, guide: { width: number; height: number }, masks: Mask[]) {
+ const { width: w, height: h } = probeVideo(clip);
+ const gray = runFfmpeg(["-i", clip, "-vf", "fps=2", "-pix_fmt", "gray", "-f", "rawvideo", "-"]);
+ // The box as a fraction of the guide's frame, in the clip's pixels (its size and aspect may differ).
+ const [kx, ky] = [w / guide.width, h / guide.height];
+ return masks.flatMap((mask) => {
+ const [bx, by, bw, bh] = mask.box;
+ const box = [bx * kx, by * ky, bw * kx, bh * ky].map(Math.round) as Mask["box"];
+ let worst = 0;
+ for (let i = 0; (i + 1) * w * h <= gray.length; i++) {
+ if (mask.window && (i / 2 < mask.window[0] || i / 2 > mask.window[1])) continue;
+ const { inside, ring } = structureRatio(gray.subarray(i * w * h, (i + 1) * w * h), w, box);
+ if (inside > 6 && inside > 1.5 * ring) worst = Math.max(worst, inside / (ring || 1));
+ }
+ return worst ? [{ mask, worst }] : [];
+ });
+}
+
+/** A copy of the guide with each mask's box filled: the temporal median, and delogo's smear where text stays put. */
+function fillMasks(path: string, masks: Mask[], work: string): string {
+ const info = probeVideo(path);
+ const encode = (from: string, name: string, filter: string[]) => {
+ const out = join(work, name);
+ runFfmpeg([
+ ...["-y", "-i", from, "-an"],
+ ...filter,
+ ...["-crf", "14", "-pix_fmt", "yuv420p", out],
+ ]);
+ return out;
+ };
+ const median = encode(path, "median.mp4", [
+ ...["-t", "15", "-filter_complex", maskFilters(masks, info.fps)],
+ ...["-map", `[v${masks.length}]`],
+ ]);
+ const left = structured(median, info, masks).map((s) => s.mask);
+ if (!left.length) return median;
+ return encode(median, "delogo.mp4", ["-vf", delogoFilters(left, info.width, info.height)]);
+}
+
+/**
+ * HeyGen answers a 16:9 request at 1344x768 (1.75:1). The result is cropped, centred, to the requested ratio
+ * (1344x756) rather than stretched; returns a note on what was done, or nothing when it already fits.
+ */
+export function fitAspect(out: string, aspect: string): string | undefined {
+ const [aw, ah] = aspect.split(":").map(Number);
+ if (!aw || !ah) return;
+ const { width, height } = probeVideo(out);
+ const want = aw / ah;
+ if (Math.abs(width / height - want) / want < 0.002) return;
+ const even = (n: number) => n - (n % 2);
+ const [w, h] =
+ width / height > want ? [even(height * want), height] : [width, even(width / want)];
+ const fitted = `${out}.fit${extname(out)}`;
+ runFfmpeg([
+ ...[
+ "-y",
+ "-i",
+ out,
+ "-vf",
+ `crop=${w}:${h}`,
+ "-c:v",
+ "libx264",
+ "-crf",
+ "12",
+ "-preset",
+ "slow",
+ ],
+ ...["-pix_fmt", "yuv420p", "-c:a", "copy", fitted],
+ ]);
+ renameSync(fitted, out);
+ return `HeyGen returned ${width}x${height} for ${aspect}; cropped to ${w}x${h} (centre), not stretched`;
+}
+
+const COUNT = ["", "one", "two", "three", "four", "five", "six"];
+
+/**
+ * Refuses a --motion clip holding more than one shot before anything is sent: HeyGen follows the guide's cut into
+ * a cut of its own, so each shot is its own generation.
+ */
+function checkGuide(r: Pick): void {
+ if (!r.motion) return;
+ const { cuts, length } = cutsInside(r.motion, GUIDE_MAX_S);
+ if (!cuts.length) return;
+ const s = (t: number) => t.toFixed(2);
+ const and = (items: string[]) => `${items.slice(0, -1).join(", ")} and ${items.at(-1)}`;
+ const at =
+ cuts.length > 1 ? `cuts at ${and(cuts.map((t) => `${s(t)} s`))}` : `a cut at ${s(cuts[0]!)} s`;
+ const edges = [0, ...cuts, length];
+ const shots = edges.slice(1).map((e, i) => `${i ? s(edges[i]!) : "0"}–${s(e)} s`);
+ throw new Fix(
+ `--motion ${r.motion} has ${at}`,
+ `guide has ${at}: generate ${and(shots)} as ${COUNT[shots.length] ?? shots.length} shots, each with its own --motion clip`,
+ );
+}
+
+/** What the real call would refuse, checked without sending anything: `--plan` prices only a request that would run.
+ * The route's body runs with a stand-in for the media, so its required flags and conflicts are checked as sent. */
+export function checkRequest(r: GenerateRequest): void {
+ const route = ROUTES[r.type];
+ if (!route.ext.includes(extname(r.out).toLowerCase()))
+ throw new Fix(`--out ${r.out} does not fit a ${r.type}`, `--out assets/name${route.ext[0]}`);
+ if (r.masks?.length && !r.motion)
+ throw new Fix("--mask blanks regions of the --motion clip", "pass --motion with --mask");
+ route.body(r, (path) => {
+ needFile(path);
+ return { type: "base64", media_type: "", data: "" };
+ });
+ checkGuide(r);
+}
+
+/** The nearest folder at or above `from` holding index.html. */
+function projectOf(from: string): string | null {
+ for (let dir = resolve(from); ; dir = dirname(dir)) {
+ if (existsSync(join(dir, "index.html"))) return dir;
+ if (dirname(dir) === dir) return null;
+ }
+}
+
+export interface Generated {
+ out: string;
+ type: GenerateType;
+ job: string;
+ route: string;
+ ledger?: string;
+ /** video: seconds where HeyGen cut inside the returned shot; null when the file could not be read. */
+ cuts_inside?: number[] | null;
+ /** What was changed or looks wrong in the result: a crop to the requested aspect, text that may have come back. */
+ notes?: string[];
+}
+
+// fallow-ignore-next-line complexity
+export async function generate(
+ r: GenerateRequest,
+ onWait?: (status: string) => void,
+ credits?: number,
+): Promise {
+ checkRequest(r);
+ const route = ROUTES[r.type];
+ const out = resolve(r.out);
+ mkdirSync(dirname(out), { recursive: true });
+ const project = projectOf(dirname(out));
+ const work = mkdtempSync(join(tmpdir(), "hf-generate-"));
+ try {
+ const body = route.body(r, inline(work, r.masks));
+ const key = idempotencyKey(route.path, [JSON.stringify(body)]);
+ const job = await runJob(route.path, body, key, (id) => route.poll(encodeURIComponent(id)), {
+ log: {
+ projectDir: project ?? undefined,
+ what: `generate ${r.type} ${relative(project ?? ".", out)}`,
+ },
+ onWait: (j) => onWait?.(j.status),
+ timeoutMs: 30 * 60_000,
+ credits,
+ });
+ const url = urlOf(job, route.urls);
+ if (!url)
+ throw new Fix(
+ `HeyGen finished job ${job.id} without a file URL`,
+ "run the same command again; it re-reads the job",
+ );
+ const res = await fetch(url, { signal: AbortSignal.timeout(300_000) });
+ if (!res.ok)
+ throw new Fix(
+ `could not download the result (${res.status})`,
+ "run the same command again; it re-reads the job",
+ );
+ writeFileSync(out, Buffer.from(await res.arrayBuffer()));
+ // HeyGen sometimes cuts inside a shot on its own; the shot is paid for and kept, the cuts are reported.
+ let cuts: number[] | null | undefined;
+ if (r.type === "video")
+ try {
+ cuts = cutsInside(out).cuts;
+ } catch {
+ cuts = null;
+ }
+ const notes: string[] = [];
+ if (r.type === "video" && (r.aspect || !r.firstFrame))
+ try {
+ const note = fitAspect(out, r.aspect ?? "16:9");
+ if (note) notes.push(note);
+ } catch (e) {
+ notes.push(
+ `kept HeyGen's size, could not crop to ${r.aspect ?? "16:9"}: ${e instanceof Error ? e.message : e}`,
+ );
+ }
+ if (r.masks?.length && r.motion)
+ try {
+ for (const { mask, worst } of structured(out, probeVideo(r.motion), r.masks))
+ notes.push(
+ `mask ${mask.box.join(",")} still shows structure in the result (${worst.toFixed(1)}x its surroundings): the text may have come back, regenerate without the guide`,
+ );
+ } catch {
+ notes.push("could not check the masked boxes of the result");
+ }
+ let ledger: string | undefined;
+ if (project) {
+ const { recordInPlace } = await import("../media-use/lib/manifest.mjs");
+ const { regenerateIndex } = await import("../media-use/lib/index-gen.mjs");
+ const describe = (p?: string) =>
+ p ? relative(project, resolve(p)).split("\\").join("/") : undefined;
+ ledger = recordInPlace(project, {
+ type: route.ledger,
+ path: relative(project, out).split("\\").join("/"),
+ source: "generated",
+ description: r.prompt ?? r.script ?? r.type,
+ provenance: {
+ provider: "heygen",
+ route: route.path,
+ model: body.model ?? null,
+ job: job.id,
+ prompt: r.prompt ?? null,
+ ...(r.references?.length ? { references: r.references.map(describe) } : {}),
+ ...(r.firstFrame ? { first_frame: describe(r.firstFrame) } : {}),
+ ...(r.photo ? { photo: describe(r.photo) } : {}),
+ ...(r.audio ? { audio: describe(r.audio) } : {}),
+ ...(r.motion ? { motion: describe(r.motion) } : {}),
+ ...(r.masks?.length
+ ? { motion_masks: r.masks.map((m) => [...m.box, ...(m.window ?? [])]) }
+ : {}),
+ ...(r.voice ? { voice: r.voice } : {}),
+ ...(cuts !== undefined ? { cuts_inside: cuts } : {}),
+ },
+ }).id;
+ regenerateIndex(project);
+ }
+ return {
+ out,
+ type: r.type,
+ job: job.id,
+ route: route.path,
+ ...(ledger ? { ledger } : {}),
+ ...(cuts !== undefined ? { cuts_inside: cuts } : {}),
+ ...(notes.length ? { notes } : {}),
+ };
+ } finally {
+ rmSync(work, { recursive: true, force: true });
+ }
+}
diff --git a/packages/cli/src/heygen/plan.test.ts b/packages/cli/src/heygen/plan.test.ts
new file mode 100644
index 0000000000..52e7a80f26
--- /dev/null
+++ b/packages/cli/src/heygen/plan.test.ts
@@ -0,0 +1,56 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("../cloud/auth.js", () => ({
+ resolveCloudAuthHeaders: async () => ({ "x-api-key": "k" }),
+ resolveCloudBaseUrl: () => "https://api.dev.heygen.com",
+}));
+
+const { pageUrl, readPlan } = await import("./plan.js");
+
+const asked: string[] = [];
+const answer = (data: unknown) =>
+ vi.stubGlobal("fetch", async (url: string) => {
+ asked.push(url);
+ return new Response(JSON.stringify({ code: 100, data }));
+ });
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.unstubAllEnvs();
+});
+
+describe("readPlan", () => {
+ it("reads the plan the way the subscription route sends it", async () => {
+ answer({
+ subscription: { plan_name: "pro", status: "active" },
+ usage: { remaining_units: 25000 },
+ });
+ expect(await readPlan()).toEqual({ plan: "pro", credits: 25000 });
+ expect(asked.at(-1)).toBe("https://api2.dev.heygen.com/v1/payment/hyperframes/subscription");
+ answer({ subscription: null, usage: { remaining_units: 0 } });
+ expect(await readPlan()).toEqual({ plan: "none", credits: 0 });
+ answer({
+ subscription: { plan_name: "pro", status: "incomplete" },
+ usage: { remaining_units: 0 },
+ });
+ expect((await readPlan())?.plan).toBe("none");
+ });
+});
+
+describe("pageUrl", () => {
+ it("links the web app for HYPERFRAMES_ENV and tells the page the buyer came from the CLI", () => {
+ vi.stubEnv("HYPERFRAMES_PLANS_URL", "");
+ vi.stubEnv("HYPERFRAMES_CREDITS_URL", "");
+ vi.stubEnv("HYPERFRAMES_ENV", "prod");
+ expect(pageUrl("plans")).toBe("https://hyperframes.studio/pricing?from=cli");
+ expect(pageUrl("credits")).toBe("https://hyperframes.studio/pricing?from=cli");
+ expect(pageUrl("credits", { needed: 180, tool: "reverse" })).toBe(
+ "https://hyperframes.studio/pricing?from=cli&needed_credits=180&tool=reverse",
+ );
+ vi.stubEnv("HYPERFRAMES_ENV", "dev");
+ const dev = new URL(pageUrl("credits"));
+ expect(dev.host).not.toBe("hyperframes.studio");
+ expect(`${dev.pathname}${dev.search}`).toBe("/pricing?from=cli");
+ expect(new URL(pageUrl("plans")).host).toBe(dev.host);
+ });
+});
diff --git a/packages/cli/src/heygen/plan.ts b/packages/cli/src/heygen/plan.ts
new file mode 100644
index 0000000000..d42e95640d
--- /dev/null
+++ b/packages/cli/src/heygen/plan.ts
@@ -0,0 +1,65 @@
+// The HyperFrames plan and credits the signed-in account holds, and the web pages that change them.
+import { oauthEnvironment } from "../auth/config.js";
+import { resolveCloudAuthHeaders, resolveCloudBaseUrl } from "../cloud/auth.js";
+
+export interface Plan {
+ plan: string;
+ credits: number;
+ mock?: boolean;
+}
+
+const UNPAID = new Set(["incomplete", "incomplete_expired"]);
+
+const isRecord = (v: unknown): v is Record =>
+ typeof v === "object" && v !== null && !Array.isArray(v);
+
+// ponytail: HYPERFRAMES_MOCK_PLAN="pro:25000" | "none" stands in when the server will not answer the CLI client
+// (EF admits only the Desktop client today); drop it once the CLI client is registered.
+function mockPlan(): Plan | null {
+ const raw = process.env["HYPERFRAMES_MOCK_PLAN"]?.trim();
+ if (!raw) return null;
+ const [plan = "none", credits = "0"] = raw.split(":");
+ return { plan, credits: Number(credits) || 0, mock: true };
+}
+
+// Payment routes live on api2, beside the OAuth ones; the v3 generation routes stay on api.
+const billingBaseUrl = () => resolveCloudBaseUrl().replace("://api.", "://api2.");
+
+export async function readPlan(): Promise {
+ try {
+ const res = await fetch(`${billingBaseUrl()}/v1/payment/hyperframes/subscription`, {
+ headers: { ...(await resolveCloudAuthHeaders()), accept: "application/json" },
+ signal: AbortSignal.timeout(15_000),
+ });
+ const body: unknown = await res.json().catch(() => null);
+ const data = isRecord(body) && isRecord(body.data) ? body.data : body;
+ if (!res.ok || !isRecord(data)) return mockPlan();
+ const usage = isRecord(data.usage) ? data.usage : {};
+ // studio-contracts' BillingSubscription: `subscription` is null on Free; an unpaid placeholder still names a plan.
+ const sub = isRecord(data.subscription) ? data.subscription : null;
+ const paid = !!sub && !UNPAID.has(String(sub.status));
+ return {
+ plan: paid ? String(sub.plan_name ?? "paid") : "none",
+ credits: Number(usage.remaining_units ?? 0) || 0,
+ };
+ } catch {
+ return mockPlan();
+ }
+}
+
+const webBase = () =>
+ oauthEnvironment() === "dev" ? "https://dev.hyperframes.dev" : "https://hyperframes.studio";
+const plansUrl = () => process.env["HYPERFRAMES_PLANS_URL"] || `${webBase()}/pricing`;
+const creditsUrl = () => process.env["HYPERFRAMES_CREDITS_URL"] || `${webBase()}/pricing`;
+
+/** A plans or credits page link with what the web side reads: `from=cli`, the credits needed, the waiting step. */
+export function pageUrl(
+ kind: "plans" | "credits",
+ fields: { needed?: number; tool?: string; base?: string } = {},
+): string {
+ const url = new URL(fields.base ?? (kind === "plans" ? plansUrl() : creditsUrl()));
+ url.searchParams.set("from", "cli");
+ if (fields.needed) url.searchParams.set("needed_credits", String(fields.needed));
+ if (fields.tool) url.searchParams.set("tool", fields.tool);
+ return url.toString();
+}
diff --git a/packages/cli/src/heygen/pricing.ts b/packages/cli/src/heygen/pricing.ts
new file mode 100644
index 0000000000..c9132847e7
--- /dev/null
+++ b/packages/cli/src/heygen/pricing.ts
@@ -0,0 +1,122 @@
+// Prices before a paid call, from the HyperFrames app's creation pricing (hyperframes-internal
+// packages/desktop/shared/creationPricing.mjs, 2026-10-22). HeyGen charges in units of $1/60, rounded up; the label
+// rounds up to the cent. Routes HeyGen does not price ahead say so instead of guessing.
+import { Fix, probeVideo, round } from "../measure/media.js";
+import { GUIDE_MAX_S, type GenerateRequest } from "./generate.js";
+
+export interface Price {
+ usd: number | null;
+ /** The list price before HeyGen's unit rounding. */
+ list: number | null;
+ /** What a HyperFrames plan charges, before rounding up to a whole credit. */
+ credits: number | null;
+ basis: string;
+}
+
+const UNIT = 1 / 60;
+const charged = (usd: number) => Math.ceil(usd / UNIT - 1e-9) * UNIT;
+const cents = (usd: number) => Math.ceil(charged(usd) * 100 - 1e-9) / 100;
+const HF_CREDITS_PER_USD = 1000;
+const at = (list: number, basis: string, credits = list * HF_CREDITS_PER_USD): Price => ({
+ usd: cents(list),
+ list,
+ credits,
+ basis,
+});
+
+const GPT_IMAGE: Record = {
+ "1:1": 0.05268,
+ "16:9": 0.0396,
+ "9:16": 0.0396,
+ "4:3": 0.03612,
+ "3:4": 0.03612,
+};
+const NANO_IMAGE = 0.067;
+const VIDEO_768P_PER_S = 0.018;
+// A reference shot (pictures, voice or guide clip) bills more, and its guide clip's seconds bill too: measured
+// 2026-10-23 from the wallet, 5 s with a picture $0.25, 10 s $0.50, 5 s with a 1 s guide $0.30, with a 3 s guide $0.40.
+const VIDEO_REF_768P_PER_S = 0.05;
+// A reference shot's first two pictures are included; each one after them bills on its own line.
+const VIDEO_INCLUDED_IMAGES = 2;
+const VIDEO_EXTRA_IMAGE = 0.02;
+// The price book's HyperFrames rows (experiment-framework price_book rules.json, 2026-10-28).
+const HF_VIDEO_768P_PER_S = 12;
+const HF_VIDEO_REF_768P_PER_S = 100 / 3;
+const HF_VIDEO_EXTRA_IMAGE = 40 / 3;
+const HF_AVATAR_IV_PHOTO_PER_S = 800 / 60;
+const MUSIC_PER_TRACK = 0.08;
+const AVATAR_IV_PER_MIN = 4.83;
+const SCRIPT_WORDS_PER_S = 2;
+
+// fallow-ignore-next-line complexity
+export function priceOf(r: GenerateRequest): Price {
+ switch (r.type) {
+ case "image": {
+ const refs = r.references?.length ?? 0;
+ if ((r.model ?? "nano-banana-2") === "nano-banana-2")
+ return at(NANO_IMAGE, "nano-banana-2, $0.067 an image");
+ const each = GPT_IMAGE[r.aspect ?? "16:9"] ?? GPT_IMAGE["16:9"]!;
+ return at(
+ each + Math.max(0, refs - 1) * 0.0082,
+ `gpt-image-2.5 at ${r.aspect ?? "16:9"}, $0.0082 a reference after the first`,
+ );
+ }
+ case "video": {
+ const seconds = Math.min(15, Math.max(5, Math.round(r.seconds ?? 5)));
+ if (r.audio || r.references?.length || r.motion) {
+ const guide = r.motion ? Math.min(GUIDE_MAX_S, probeVideo(r.motion).pictureDuration) : 0;
+ const extra = Math.max(0, (r.references?.length ?? 0) - VIDEO_INCLUDED_IMAGES);
+ const billed = seconds + guide;
+ return at(
+ billed * VIDEO_REF_768P_PER_S + extra * VIDEO_EXTRA_IMAGE,
+ `heygen-video-1 reference shot at 768p, ${seconds} s${guide ? ` and the ${round(guide, 2)} s guide` : ""} at $0.05 a second${extra ? `, ${extra} extra pictures at $0.02` : ""}`,
+ billed * HF_VIDEO_REF_768P_PER_S + extra * HF_VIDEO_EXTRA_IMAGE,
+ );
+ }
+ return at(
+ seconds * VIDEO_768P_PER_S,
+ `heygen-video-1 at 768p, ${seconds} s at $0.018 a second`,
+ seconds * HF_VIDEO_768P_PER_S,
+ );
+ }
+ case "avatar": {
+ const words = (r.script ?? "").split(/\s+/).filter(Boolean).length;
+ const seconds = Math.max(1, Math.floor(words / SCRIPT_WORDS_PER_S));
+ return at(
+ Math.ceil(seconds * AVATAR_IV_PER_MIN) / 60,
+ `avatar video, about ${seconds} s from ${words} words at $4.83 a minute`,
+ seconds * HF_AVATAR_IV_PHOTO_PER_S,
+ );
+ }
+ case "music":
+ return at(MUSIC_PER_TRACK, "lyria-3-pro, $0.08 a track");
+ case "voice":
+ return {
+ usd: null,
+ list: null,
+ credits: null,
+ basis: "HeyGen does not price catalog speech ahead; it is charged per character",
+ };
+ }
+}
+
+// No HeyGen unit rounding here: a $0.067 image is charged 67 credits, measured on dev 2026-10-29. Still an estimate.
+export const creditsOf = (p: Price): number | null =>
+ p.credits === null ? null : Math.ceil(p.credits - 1e-9);
+
+/** Refuses, before anything is sent, a call that would not fit what is left of the person's credit limit. */
+export function checkLimit(credits: number | null, limit: number | undefined): void {
+ if (limit === undefined) return;
+ const fix =
+ "tell the person what their limit leaves out, then ask whether to raise it or make the video without this piece";
+ if (credits === null)
+ throw new Fix(
+ `this call cannot be priced ahead, so it cannot be kept under --max-credits ${limit}; nothing was made`,
+ fix,
+ );
+ if (credits > limit)
+ throw new Fix(
+ `this call is about ${credits} credits, over --max-credits ${limit}; nothing was made or charged`,
+ fix,
+ );
+}
diff --git a/packages/cli/src/heygen/transcribe.test.ts b/packages/cli/src/heygen/transcribe.test.ts
new file mode 100644
index 0000000000..1078db14e9
--- /dev/null
+++ b/packages/cli/src/heygen/transcribe.test.ts
@@ -0,0 +1,72 @@
+import { execFileSync } from "node:child_process";
+import { mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, afterEach, describe, expect, it, vi } from "vitest";
+import { findFFmpeg } from "../browser/ffmpeg.js";
+
+vi.mock("../cloud/auth.js", () => ({
+ resolveCloudAuthHeaders: async () => ({ "x-api-key": "k" }),
+ refreshIfNeeded: async (credential: T) => credential,
+ resolveCloudBaseUrl: () => "https://api.test",
+}));
+vi.stubEnv("HEYGEN_API_KEY", "k");
+
+const { transcribeWithHeygen, wordsOf } = await import("./transcribe.js");
+const ffmpeg = findFFmpeg();
+const dir = mkdtempSync(join(tmpdir(), "hf-heygen-asr-test-"));
+afterAll(() => rmSync(dir, { recursive: true, force: true }));
+afterEach(() => vi.unstubAllGlobals());
+
+const job = {
+ id: "t1",
+ status: "completed",
+ model: "scribe-v2",
+ language: "en",
+ duration_seconds: 1.5,
+ segments: [
+ {
+ speaker: "speaker_0",
+ start: 0.1,
+ end: 1.2,
+ words: [
+ { word: "Hello", start: 0.1, end: 0.5 },
+ { word: "there", start: 0.6, end: 1.2, speaker: "speaker_1" },
+ { word: " ", start: 1.2, end: 1.3 },
+ ],
+ },
+ ],
+};
+
+describe("HeyGen transcription", () => {
+ it("keeps each word's time and speaker, and drops blanks", () => {
+ expect(wordsOf(job)).toEqual([
+ { text: "Hello", start: 0.1, end: 0.5, speaker: "speaker_0" },
+ { text: "there", start: 0.6, end: 1.2, speaker: "speaker_1" },
+ ]);
+ });
+
+ it.skipIf(!ffmpeg)("sends the audio once and writes the transcript", async () => {
+ const audio = join(dir, "a.wav");
+ execFileSync(ffmpeg!, ["-v", "error", "-y", "-f", "lavfi", "-i", "sine=f=300:d=1.5", audio]);
+ const bodies: Record[] = [];
+ vi.stubGlobal("fetch", async (_url: string, init: RequestInit) => {
+ bodies.push(JSON.parse(String(init.body)));
+ return new Response(JSON.stringify({ data: job }), { status: 200 });
+ });
+ const out = join(dir, "transcript.json");
+ const r = await transcribeWithHeygen(audio, out, { diarize: true });
+ expect(bodies).toHaveLength(1);
+ expect(bodies[0]).toMatchObject({
+ model: "scribe-v2",
+ diarize: true,
+ audio: { type: "base64", media_type: "audio/mpeg" },
+ });
+ expect(r).toMatchObject({
+ detectedLanguage: "en",
+ durationSeconds: 1.5,
+ speechOnsetSeconds: 0.1,
+ });
+ expect(JSON.parse(readFileSync(out, "utf8"))).toHaveLength(2);
+ });
+});
diff --git a/packages/cli/src/heygen/transcribe.ts b/packages/cli/src/heygen/transcribe.ts
new file mode 100644
index 0000000000..b98be3f6ca
--- /dev/null
+++ b/packages/cli/src/heygen/transcribe.ts
@@ -0,0 +1,97 @@
+// Transcription on HeyGen (`transcribe --engine heygen`): word times from its speech model, with speakers when asked.
+// The route runs inside the POST and takes an API key; the Idempotency-Key makes a re-run free.
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { runFfmpeg } from "../measure/media.js";
+import { idempotencyKey, runJob } from "./v3.js";
+
+const ROUTE = "/v3/audio/transcriptions";
+const MODEL = "scribe-v2";
+
+export interface HeygenTranscript {
+ transcriptPath: string;
+ model: string;
+ detectedLanguage: string | null;
+ durationSeconds: number;
+ speechOnsetSeconds: number | null;
+}
+
+const isRecord = (v: unknown): v is Record =>
+ typeof v === "object" && v !== null && !Array.isArray(v);
+const list = (v: unknown) => (Array.isArray(v) ? v.filter(isRecord) : []);
+
+/** Words in the transcript file's own shape, `speaker` kept when the model labelled one. */
+export function wordsOf(job: Record) {
+ return list(job.segments).flatMap((segment) =>
+ list(segment.words).flatMap((w) => {
+ const text = String(w.word ?? w.text ?? "").trim();
+ if (!text || typeof w.start !== "number" || typeof w.end !== "number") return [];
+ const speaker = w.speaker ?? segment.speaker;
+ return [
+ {
+ text,
+ start: w.start,
+ end: w.end,
+ ...(speaker !== undefined ? { speaker: String(speaker) } : {}),
+ },
+ ];
+ }),
+ );
+}
+
+export async function transcribeWithHeygen(
+ inputPath: string,
+ transcriptPath: string,
+ opts: { diarize?: boolean; projectDir?: string; onStatus?: (message: string) => void } = {},
+): Promise {
+ const work = mkdtempSync(join(tmpdir(), "hf-heygen-asr-"));
+ try {
+ opts.onStatus?.("Preparing audio for HeyGen...");
+ const mp3 = join(work, "audio.mp3");
+ runFfmpeg([
+ "-y",
+ "-i",
+ inputPath,
+ "-vn",
+ "-ac",
+ "1",
+ "-ar",
+ "16000",
+ "-c:a",
+ "libmp3lame",
+ "-b:a",
+ "64k",
+ mp3,
+ ]);
+ const audio = readFileSync(mp3);
+ const diarize = opts.diarize === true;
+ opts.onStatus?.("Transcribing on HeyGen...");
+ const job = await runJob(
+ ROUTE,
+ {
+ model: MODEL,
+ audio: { type: "base64", media_type: "audio/mpeg", data: audio.toString("base64") },
+ diarize,
+ },
+ idempotencyKey(ROUTE, [audio, String(diarize)]),
+ (id) => `${ROUTE}/${encodeURIComponent(id)}`,
+ {
+ log: { projectDir: opts.projectDir, what: `transcribe ${inputPath}` },
+ timeoutMs: 10 * 60_000,
+ },
+ );
+ const words = wordsOf(job);
+ writeFileSync(transcriptPath, JSON.stringify(words, null, 2));
+ return {
+ transcriptPath,
+ model: typeof job.model === "string" ? job.model : MODEL,
+ detectedLanguage: typeof job.language === "string" ? job.language : null,
+ durationSeconds:
+ typeof job.duration_seconds === "number" ? job.duration_seconds : (words.at(-1)?.end ?? 0),
+ speechOnsetSeconds: words[0]?.start ?? null,
+ };
+ } finally {
+ rmSync(work, { recursive: true, force: true });
+ }
+}
diff --git a/packages/cli/src/heygen/v3.test.ts b/packages/cli/src/heygen/v3.test.ts
new file mode 100644
index 0000000000..c76972079c
--- /dev/null
+++ b/packages/cli/src/heygen/v3.test.ts
@@ -0,0 +1,298 @@
+import { mkdtempSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("../cloud/auth.js", () => ({
+ resolveCloudAuthHeaders: async () => ({ "x-api-key": "k" }),
+ refreshIfNeeded: async (credential: T) => credential,
+ resolveCloudBaseUrl: () => "https://api.test",
+}));
+
+const { idempotencyKey, runJob } = await import("./v3.js");
+
+const reply = (status: number, body: unknown) =>
+ new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
+
+beforeEach(() => {
+ vi.stubEnv("HYPERFRAMES_CONFIG_DIR", mkdtempSync(join(tmpdir(), "hf-v3-test-")));
+ vi.stubEnv("HEYGEN_API_KEY", "payer");
+});
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.unstubAllEnvs();
+});
+
+describe("runJob", () => {
+ it("sends the key, polls until the job ends and returns it", async () => {
+ const calls: { url: string; init: RequestInit }[] = [];
+ const answers = [
+ reply(200, { data: { id: "j1", status: "pending" } }),
+ reply(200, { data: { id: "j1", status: "processing" } }),
+ reply(200, { data: { id: "j1", status: "completed", output: { json: { ok: 1 } } } }),
+ ];
+ vi.stubGlobal("fetch", async (url: string, init: RequestInit) => {
+ calls.push({ url, init });
+ return answers.shift()!;
+ });
+ const job = await runJob("/v3/x", { a: 1 }, "hf-key", (id) => `/v3/x/${id}`, { intervalMs: 1 });
+ expect(job.output).toEqual({ json: { ok: 1 } });
+ expect(calls.map((c) => c.url)).toEqual([
+ "https://api.test/v3/x",
+ "https://api.test/v3/x/j1",
+ "https://api.test/v3/x/j1",
+ ]);
+ expect(new Headers(calls[0]!.init.headers).get("Idempotency-Key")).toBe("hf-key");
+ });
+
+ it("turns refusals into what to do next", async () => {
+ vi.stubGlobal("fetch", async () =>
+ reply(402, { error: { code: "insufficient_credit", message: "no" } }),
+ );
+ await expect(runJob("/v3/x", {}, "k", (id) => id)).rejects.toMatchObject({
+ fix: expect.stringContaining("top up"),
+ });
+ vi.stubGlobal("fetch", async () =>
+ reply(402, { error: { code: "hf_subscription_required", message: "no plan" } }),
+ );
+ await expect(runJob("/v3/x", {}, "k", (id) => id)).rejects.toMatchObject({
+ fix: "Subscribe: https://hyperframes.studio/pricing?from=cli",
+ });
+ vi.stubGlobal("fetch", async () =>
+ reply(402, { code: "hf_usage_exhausted", url: "https://pay.test/credits" }),
+ );
+ await expect(runJob("/v3/x", {}, "k", (id) => id)).rejects.toMatchObject({
+ fix: "Add credits: https://pay.test/credits",
+ });
+ vi.stubGlobal("fetch", async () => reply(401, { message: "bad" }));
+ await expect(runJob("/v3/x", {}, "k", (id) => id)).rejects.toMatchObject({
+ fix: "npx hyperframes auth login",
+ });
+ vi.stubGlobal("fetch", async () =>
+ reply(200, { data: { id: "j", status: "failed", failure_code: "content_policy_violation" } }),
+ );
+ await expect(runJob("/v3/x", {}, "k", (id) => id)).rejects.toMatchObject({
+ fix: expect.stringContaining("reword"),
+ });
+ });
+
+ it("names what an out-of-credits step needs, from the call's own price when HeyGen does not say", async () => {
+ vi.stubGlobal("fetch", async () => reply(402, { error: { code: "hf_usage_exhausted" } }));
+ await expect(runJob("/v3/x", {}, "k", (id) => id, { credits: 782 })).rejects.toMatchObject({
+ message: expect.stringContaining("this step needs about 782 in total"),
+ });
+ await expect(runJob("/v3/x", {}, "k", (id) => id, { credits: 782 })).rejects.toMatchObject({
+ message: expect.stringContaining("billing top-up --needed 782"),
+ fix: expect.stringContaining("needed_credits=782"),
+ });
+ vi.stubGlobal("fetch", async () =>
+ reply(402, { error: { code: "hf_usage_exhausted", needed_credits: 180, balance: 30 } }),
+ );
+ await expect(runJob("/v3/x", {}, "k", (id) => id, { credits: 782 })).rejects.toMatchObject({
+ message: expect.stringContaining("this step needs 180 in total, balance 30"),
+ });
+ vi.stubGlobal("fetch", async () => reply(402, { error: { code: "hf_usage_exhausted" } }));
+ await expect(runJob("/v3/x", {}, "k", (id) => id)).rejects.toMatchObject({
+ message: expect.stringContaining("this step needs more"),
+ });
+ });
+
+ it("sends a failed or refused job again as a new one, and picks a finished one up", async () => {
+ const keys: (string | null)[] = [];
+ const run = (key: string, answers: Response[]) => {
+ vi.stubGlobal("fetch", async (_url: string, init: RequestInit) => {
+ if (init.method === "POST") keys.push(new Headers(init.headers).get("Idempotency-Key"));
+ return answers.shift()!;
+ });
+ return runJob("/v3/x", {}, key, (id) => `/v3/x/${id}`, { intervalMs: 1 });
+ };
+ const failed = () => [
+ reply(200, { data: { id: "j", status: "pending" } }),
+ reply(200, { data: { id: "j", status: "failed", failure_code: "generation_failed" } }),
+ ];
+ const done = () => [reply(200, { data: { id: "j", status: "completed" } })];
+
+ await expect(run("hf-fails", failed())).rejects.toMatchObject({
+ fix: "fix the request it names, then run again",
+ });
+ await expect(run("hf-fails", failed())).rejects.toThrow("generation_failed");
+ await run("hf-fails", done());
+ await run("hf-fails", done());
+ expect(keys).toEqual(["hf-fails", "hf-fails-1", "hf-fails-2", "hf-fails-2"]);
+
+ keys.length = 0;
+ await run("hf-works", done());
+ await run("hf-works", done());
+ expect(keys).toEqual(["hf-works", "hf-works"]);
+
+ keys.length = 0;
+ await expect(
+ run("hf-broke", [reply(402, { error: { code: "hf_usage_exhausted" } })]),
+ ).rejects.toThrow("out of HyperFrames credits");
+ await run("hf-broke", done());
+ expect(keys).toEqual(["hf-broke", "hf-broke-1"]);
+ });
+
+ it.each([401, 403, 408, 409, 425, 429])(
+ "keeps the key after a %i, which says nothing about the job",
+ async (status) => {
+ const key = `hf-lost-${status}`;
+ const keys: (string | null)[] = [];
+ const answers = [
+ reply(status, { message: "no" }),
+ reply(200, { data: { id: "j", status: "completed" } }),
+ ];
+ vi.stubGlobal("fetch", async (_url: string, init: RequestInit) => {
+ keys.push(new Headers(init.headers).get("Idempotency-Key"));
+ return answers.shift()!;
+ });
+ await expect(runJob("/v3/x", {}, key, (id) => id)).rejects.toThrow();
+ await runJob("/v3/x", {}, key, (id) => id);
+ expect(keys).toEqual([key, key]);
+ },
+ );
+
+ it("does not let one account's failure move another account's key", async () => {
+ const keys: (string | null)[] = [];
+ const run = (answers: Response[]) => {
+ vi.stubGlobal("fetch", async (_url: string, init: RequestInit) => {
+ keys.push(new Headers(init.headers).get("Idempotency-Key"));
+ return answers.shift()!;
+ });
+ return runJob("/v3/x", {}, "hf-shared", (id) => id);
+ };
+ vi.stubEnv("HEYGEN_API_KEY", "payer-a");
+ await expect(run([reply(402, { code: "hf_usage_exhausted" })])).rejects.toThrow();
+ vi.stubEnv("HEYGEN_API_KEY", "payer-b");
+ await run([reply(200, { data: { id: "j", status: "completed" } })]);
+ expect(keys).toEqual(["hf-shared", "hf-shared"]);
+ });
+
+ describe("with a host's sign-in token", () => {
+ const signIn = (token: string) => {
+ vi.stubEnv("HEYGEN_API_KEY", "");
+ vi.stubEnv("HEYGEN_ACCESS_TOKEN", token);
+ };
+ const done = () => reply(200, { data: { id: "j", status: "completed" } });
+ const failed = () =>
+ reply(200, { data: { id: "j", status: "failed", failure_code: "generation_failed" } });
+ /** Answers `/v3/users/me` with `accounts`, and each job call with the next of `answers`. */
+ const server = (
+ accounts: Record Response)>,
+ answers: (Response | (() => Response))[],
+ ) => {
+ const keys: (string | null)[] = [];
+ vi.stubGlobal("fetch", async (url: string, init: RequestInit) => {
+ if (!url.endsWith("/v3/users/me")) {
+ if (init.method === "POST") keys.push(new Headers(init.headers).get("Idempotency-Key"));
+ const answer = answers.shift()!;
+ return typeof answer === "function" ? answer() : answer;
+ }
+ const token = new Headers(init.headers).get("authorization")?.replace("Bearer ", "");
+ const account = accounts[token!]!;
+ return typeof account === "function" ? account() : account.clone();
+ });
+ return keys;
+ };
+ const accounts = {
+ a: reply(200, { data: { username: "a", email: "same@test" } }),
+ b: reply(200, { data: { username: "b", email: "same@test" } }),
+ };
+
+ it.each([
+ ["no local user", null],
+ ["someone else's local user", { user: { email: "stale@test" } }],
+ ])("gives each account its own failures, with %s", async (_name, stored) => {
+ if (stored)
+ writeFileSync(
+ join(process.env["HYPERFRAMES_CONFIG_DIR"]!, "credentials"),
+ JSON.stringify(stored),
+ );
+ const keys = server(accounts, [
+ done(),
+ reply(402, { error: { code: "hf_usage_exhausted" } }),
+ done(),
+ ]);
+ signIn("a");
+ await runJob("/v3/x", {}, "hf-host", (id) => id);
+ signIn("b");
+ await expect(runJob("/v3/x", {}, "hf-host", (id) => id)).rejects.toThrow();
+ signIn("a");
+ await runJob("/v3/x", {}, "hf-host", (id) => id);
+ expect(keys).toEqual(["hf-host", "hf-host", "hf-host"]);
+ });
+
+ it("holds a failure to the account that sent the job, whoever signs in during it", async () => {
+ const keys = server(accounts, [
+ done(),
+ reply(200, { data: { id: "j", status: "pending" } }),
+ () => {
+ signIn("b");
+ return failed();
+ },
+ done(),
+ done(),
+ ]);
+ signIn("b");
+ await runJob("/v3/x", {}, "hf-switch", (id) => id);
+ signIn("a");
+ await expect(
+ runJob("/v3/x", {}, "hf-switch", (id) => id, { intervalMs: 1 }),
+ ).rejects.toThrow();
+ await runJob("/v3/x", {}, "hf-switch", (id) => id);
+ signIn("a");
+ await runJob("/v3/x", {}, "hf-switch", (id) => id);
+ expect(keys).toEqual(["hf-switch", "hf-switch", "hf-switch", "hf-switch-1"]);
+ });
+
+ it("sends the job with the credential it looked up", async () => {
+ const seen: (string | null)[] = [];
+ const me = accounts.a;
+ vi.stubGlobal("fetch", async (url: string, init: RequestInit) => {
+ if (url.endsWith("/v3/users/me")) {
+ signIn("b");
+ return me.clone();
+ }
+ seen.push(new Headers(init.headers).get("authorization"));
+ return done();
+ });
+ signIn("a");
+ await runJob("/v3/x", {}, "hf-window", (id) => id);
+ expect(seen).toEqual(["Bearer a"]);
+ });
+
+ it("records nothing when the account cannot be told", async () => {
+ const keys = server({ a: () => reply(503, {}) }, [
+ reply(402, { error: { code: "hf_usage_exhausted" } }),
+ done(),
+ ]);
+ signIn("a");
+ await expect(runJob("/v3/x", {}, "hf-unknown", (id) => id)).rejects.toThrow();
+ await runJob("/v3/x", {}, "hf-unknown", (id) => id);
+ expect(keys).toEqual(["hf-unknown", "hf-unknown"]);
+ });
+
+ it("sends a job that failed for this account as a new one", async () => {
+ const keys = server(accounts, [failed(), done()]);
+ signIn("a");
+ await expect(runJob("/v3/x", {}, "hf-own", (id) => id)).rejects.toThrow();
+ await runJob("/v3/x", {}, "hf-own", (id) => id);
+ expect(keys).toEqual(["hf-own", "hf-own-1"]);
+ });
+
+ it("keeps the key through a lost answer, then a new sign-in", async () => {
+ const keys = server(accounts, [reply(401, { message: "expired" }), done()]);
+ signIn("a");
+ await expect(runJob("/v3/x", {}, "hf-resigned", (id) => id)).rejects.toThrow();
+ await runJob("/v3/x", {}, "hf-resigned", (id) => id);
+ expect(keys).toEqual(["hf-resigned", "hf-resigned"]);
+ });
+ });
+
+ it("keys the same request the same way", () => {
+ expect(idempotencyKey("/v3/x", ["a", Buffer.from("b")])).toBe(
+ idempotencyKey("/v3/x", ["a", Buffer.from("b")]),
+ );
+ expect(idempotencyKey("/v3/x", ["a"])).not.toBe(idempotencyKey("/v3/y", ["a"]));
+ });
+});
diff --git a/packages/cli/src/heygen/v3.ts b/packages/cli/src/heygen/v3.ts
new file mode 100644
index 0000000000..4ec4c15366
--- /dev/null
+++ b/packages/cli/src/heygen/v3.ts
@@ -0,0 +1,254 @@
+// HeyGen's v3 job routes through the hyperframes credential chain (API key, host token or OAuth, refreshed). A paid
+// call carries an Idempotency-Key derived from what it asks for, so the same command again picks up the same job
+// rather than paying twice; a failed job is asked again. Every job is logged to .hyperframes/heygen-jobs.jsonl.
+import { createHash } from "node:crypto";
+import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+import { configDir } from "../auth/paths.js";
+import { AuthClient, buildAuthHeaders } from "../auth/client.js";
+import { resolveCredential } from "../auth/resolver.js";
+import { refreshIfNeeded, resolveCloudAuthHeaders, resolveCloudBaseUrl } from "../cloud/auth.js";
+import { Fix } from "../measure/media.js";
+import { pageUrl } from "./plan.js";
+
+export interface Job {
+ id: string;
+ status: string;
+ failure_code?: string;
+ failure_message?: string;
+ [field: string]: unknown;
+}
+
+const RUNNING = new Set(["pending", "processing", "queued", "running", "waiting", "in_progress"]);
+const isRecord = (v: unknown): v is Record =>
+ typeof v === "object" && v !== null && !Array.isArray(v);
+
+/** The same request always gets the same key: a re-run is a resume, never a second charge. */
+export function idempotencyKey(route: string, parts: readonly (string | Buffer)[]): string {
+ const h = createHash("sha256").update(route);
+ for (const p of parts) h.update(p).update("\0");
+ return `hf-${h.digest("hex").slice(0, 40)}`;
+}
+
+class Refused extends Fix {
+ status = 0;
+}
+
+/** Refusals that say nothing about the job: a lost answer may have started it, so a retry keeps its key. */
+const KEEPS_KEY = new Set([401, 403, 408, 409, 425, 429]);
+
+const failedKeysFile = () => join(configDir(), "heygen-failed-keys");
+
+const noSignIn = (): never => {
+ throw new Fix("no HeyGen sign-in on this machine", "npx hyperframes auth login");
+};
+
+interface Sender {
+ auth: Record;
+ /** Who failures belong to: this API and this account; null when the account cannot be told. */
+ scope: string | null;
+}
+
+/** Fixed when a job starts: a sign-in during it must not send the job or own its failure. */
+async function jobSender(): Promise {
+ const credential = await resolveCredential().then(refreshIfNeeded).catch(noSignIn);
+ const who =
+ credential.type === "api_key"
+ ? credential.key
+ : await new AuthClient().getCurrentUser(credential).then(
+ (user) => user.username ?? user.email,
+ () => undefined,
+ );
+ const scope = who
+ ? createHash("sha256").update(`${resolveCloudBaseUrl()}\0${who}`).digest("hex").slice(0, 16)
+ : null;
+ return { auth: buildAuthHeaders(credential), scope };
+}
+
+function failedKeys(scope: string): Set {
+ const file = failedKeysFile();
+ const lines = existsSync(file) ? readFileSync(file, "utf8").split("\n") : [];
+ return new Set(
+ lines.filter((l) => l.startsWith(`${scope} `)).map((l) => l.slice(scope.length + 1)),
+ );
+}
+
+function markFailed(key: string, scope: string | null): void {
+ if (!scope) return;
+ mkdirSync(configDir(), { recursive: true });
+ appendFileSync(failedKeysFile(), `${scope} ${key}\n`);
+}
+
+/** The key to send: `key` itself, or past every key whose job failed or was refused, so a retry is a new job. */
+function liveKey(key: string, scope: string | null): string {
+ const failed = scope ? failedKeys(scope) : new Set();
+ let sent = key;
+ for (let n = 1; failed.has(sent); n++) sent = `${key}-${n}`;
+ return sent;
+}
+
+/** A refused call says what to do: sign in, subscribe, add credits, or change the request. `estimate` is the
+ * caller's own price for the call (what `--plan` prints), named when HeyGen does not say what the step needs. */
+// fallow-ignore-next-line complexity
+function refusal(status: number, body: unknown, estimate?: number): Refused {
+ const err = isRecord(body) && isRecord(body.error) ? body.error : isRecord(body) ? body : {};
+ const code = String(err.code ?? err.failure_code ?? "");
+ const message = String(err.message ?? err.failure_message ?? "").slice(0, 300);
+ const url = typeof err.url === "string" ? err.url : undefined;
+ const given = Number(err.needed_credits) || undefined;
+ const needed = given ?? (estimate || undefined);
+ const needs = given ? `${given} in total` : needed ? `about ${needed} in total` : "more";
+ const balance = err.balance === undefined ? "" : `, balance ${String(err.balance)}`;
+ // The fix is the one line the agent relays as printed; the problem says how to wait for the person.
+ if (/hf_subscription_required/i.test(code))
+ return new Refused(
+ `this is a HyperFrames Pro feature; nothing was charged. Run \`npx hyperframes billing subscribe\`: it opens the page and waits`,
+ `Subscribe: ${url ?? pageUrl("plans", { needed })}`,
+ );
+ if (/hf_usage_exhausted/i.test(code))
+ return new Refused(
+ `out of HyperFrames credits (this step needs ${needs}${balance}); nothing was charged. Run \`npx hyperframes billing top-up${needed ? ` --needed ${needed}` : ""}\`: it opens the page and waits`,
+ `Add credits: ${url ?? pageUrl("credits", { needed })}`,
+ );
+ if (/api_key_required/i.test(code))
+ return new Refused(
+ "this HeyGen feature is not available with this sign-in yet; nothing was charged",
+ "continue without this step",
+ );
+ if (status === 401 || status === 403)
+ return new Refused(
+ `HeyGen refused the credential (${status}${message ? `: ${message}` : ""})`,
+ "npx hyperframes auth login",
+ );
+ if (status === 402 || /insufficient|credit|usage_exhausted|quota/i.test(code))
+ return new Refused(
+ `HeyGen says there is not enough credit (${code || status})`,
+ "top up at https://app.heygen.com, or sign in with npx hyperframes auth login to use the plan's allowance",
+ );
+ if (/content_policy/i.test(code))
+ return new Refused(
+ `HeyGen declined the content: ${message || code}`,
+ "reword the prompt once without the flagged part",
+ );
+ return new Refused(
+ `HeyGen ${status}${code ? ` ${code}` : ""}: ${message || "request refused"}`,
+ "fix the request it names, then run again",
+ );
+}
+
+// fallow-ignore-next-line complexity
+async function call(
+ method: "GET" | "POST",
+ route: string,
+ body?: unknown,
+ key?: string,
+ estimate?: number,
+ auth?: Record,
+): Promise {
+ const headers: Record = {
+ ...(auth ?? (await resolveCloudAuthHeaders().catch(noSignIn))),
+ accept: "application/json",
+ };
+ if (body !== undefined) headers["content-type"] = "application/json";
+ if (key) headers["Idempotency-Key"] = key;
+ let res: Response;
+ try {
+ res = await fetch(`${resolveCloudBaseUrl()}${route}`, {
+ method,
+ headers,
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
+ signal: AbortSignal.timeout(method === "POST" ? 180_000 : 30_000),
+ });
+ } catch (err) {
+ throw new Fix(
+ `no answer from HeyGen for ${route} (${err instanceof Error ? err.message : String(err)})`,
+ "run the same command again: it resumes the same job",
+ );
+ }
+ const value: unknown = await res.json().catch(() => null);
+ if (res.status >= 500 || value === null)
+ throw new Fix(
+ `HeyGen ${res.status} for ${route} with no readable answer`,
+ "run the same command again: it resumes the same job",
+ );
+ if (!res.ok) {
+ const refused = refusal(res.status, value, estimate);
+ refused.status = res.status;
+ throw refused;
+ }
+ const data = isRecord(value) && isRecord(value.data) ? value.data : value;
+ if (!isRecord(data))
+ throw new Fix(`HeyGen answered ${route} with no job`, "run the same command again");
+ const id = data.id ?? data.job_id ?? data.video_id ?? data.generation_id;
+ return {
+ ...data,
+ id: typeof id === "string" ? id : "",
+ status: String(data.status ?? (id ? "pending" : "completed")),
+ };
+}
+
+export interface JobLog {
+ /** The project whose .hyperframes/heygen-jobs.jsonl records the job; omitted, nothing is logged. */
+ projectDir?: string;
+ /** What the job is for, in a few words. */
+ what: string;
+}
+
+function log(entry: JobLog, record: Record) {
+ if (!entry.projectDir) return;
+ const dir = join(entry.projectDir, ".hyperframes");
+ mkdirSync(dir, { recursive: true });
+ appendFileSync(
+ join(dir, "heygen-jobs.jsonl"),
+ `${JSON.stringify({ at: new Date().toISOString(), what: entry.what, ...record })}\n`,
+ );
+}
+
+export interface RunOptions {
+ /** How long to wait for the job to finish before handing back its id. */
+ timeoutMs?: number;
+ intervalMs?: number;
+ onWait?: (job: Job) => void;
+ log?: JobLog;
+ /** What the call is priced at in credits, named in an out-of-credits refusal that does not say. */
+ credits?: number;
+}
+
+/** Starts a job (or picks up the one this key already started) and polls `pollRoute(id)` until it ends. */
+export async function runJob(
+ route: string,
+ body: unknown,
+ key: string,
+ pollRoute: (id: string) => string,
+ opts: RunOptions = {},
+): Promise {
+ const started = Date.now();
+ const { auth, scope } = await jobSender();
+ const sent = liveKey(key, scope);
+ let job: Job;
+ try {
+ job = await call("POST", route, body, sent, opts.credits, auth);
+ } catch (err) {
+ if (err instanceof Refused && !KEEPS_KEY.has(err.status)) markFailed(sent, scope);
+ throw err;
+ }
+ if (opts.log) log(opts.log, { route, id: job.id, key: sent, status: job.status });
+ while (RUNNING.has(job.status.toLowerCase())) {
+ if (Date.now() - started > (opts.timeoutMs ?? 15 * 60_000))
+ throw new Fix(
+ `HeyGen job ${job.id} is still ${job.status}`,
+ "run the same command again later: it picks up this job",
+ );
+ opts.onWait?.(job);
+ await new Promise((r) => setTimeout(r, opts.intervalMs ?? 5000));
+ job = await call("GET", pollRoute(job.id));
+ }
+ if (opts.log) log(opts.log, { route, id: job.id, key: sent, status: job.status });
+ if (!/^(completed|succeeded|success|done)$/i.test(job.status)) {
+ markFailed(sent, scope);
+ throw refusal(422, {
+ error: { code: job.failure_code ?? job.status, message: job.failure_message ?? "" },
+ });
+ }
+ return job;
+}
diff --git a/packages/cli/src/measure/command.ts b/packages/cli/src/measure/command.ts
new file mode 100644
index 0000000000..f953e78ca6
--- /dev/null
+++ b/packages/cli/src/measure/command.ts
@@ -0,0 +1,89 @@
+// What every `hyperframes measure ` shares: one JSON object on stdout (summaries, never per-frame arrays;
+// pictures as file paths), progress on stderr, and an error that says what to run instead.
+import { c } from "../ui/colors.js";
+import { failCommand } from "../utils/commandResult.js";
+import { normalizeErrorMessage } from "../utils/errorMessage.js";
+import { withMeta } from "../utils/updateCheck.js";
+import {
+ Fix,
+ formatJson,
+ parseNumbers,
+ parseRoi,
+ probeVideo,
+ type Roi,
+ type VideoInfo,
+} from "./media.js";
+
+export async function runMeasure(work: () => object | Promise): Promise {
+ try {
+ console.log(formatJson(withMeta({ ok: true, ...(await work()) })));
+ } catch (err) {
+ const fix = err instanceof Fix ? err.fix : undefined;
+ console.log(
+ formatJson(
+ withMeta({ ok: false, error: normalizeErrorMessage(err), ...(fix ? { fix } : {}) }),
+ ),
+ );
+ if (process.stdout.isTTY) console.error(`${c.error("✗")} ${normalizeErrorMessage(err)}`);
+ failCommand();
+ }
+}
+
+/** Arguments most ops take. */
+export const videoArg = {
+ type: "positional",
+ description: "The video file",
+ required: true,
+} as const;
+export const roiArg = {
+ type: "string",
+ description: "Region x,y,w,h in the video's pixels (default: whole frame)",
+} as const;
+export const outArg = {
+ type: "string",
+ description: "Folder for pictures (default .hyperframes/measure/)",
+} as const;
+export const jsonArg = {
+ type: "boolean",
+ description: "Accepted for symmetry; output is always JSON",
+ default: false,
+} as const;
+/** Where a second video (your render) is measured, when it is measured the same way. */
+export const compareWindowArgs = {
+ "compare-start": { type: "string", description: "Its window start (default: --start)" },
+ "compare-roi": { type: "string", description: "Its region (default: --roi)" },
+} as const;
+
+/** The video's probe and its ROI (whole frame by default). */
+export function videoAndRoi(video: unknown, roi: unknown): { info: VideoInfo; roi: Roi } {
+ const info = probeVideo(String(video));
+ return {
+ info,
+ roi:
+ roi === undefined ? [0, 0, info.width, info.height] : parseRoi(roi, info.width, info.height),
+ };
+}
+
+/** One number from a flag, or `fallback` when it is absent. */
+export function num(value: unknown, flag: string, fallback: number): number;
+export function num(value: unknown, flag: string): number | undefined;
+export function num(value: unknown, flag: string, fallback?: number): number | undefined {
+ return value === undefined ? fallback : parseNumbers(value, flag)[0];
+}
+
+/** start,end seconds from --start/--end (or --from/--to), clamped to the video. */
+export function window(
+ info: VideoInfo,
+ start: unknown,
+ end: unknown,
+ flags = ["--start", "--end"],
+) {
+ const a = num(start, flags[0]!, 0);
+ const b = Math.min(info.duration, num(end, flags[1]!, info.duration));
+ if (!(b > a))
+ throw new Fix(
+ `${flags[1]} ${b} is not after ${flags[0]} ${a}`,
+ `${flags[0]} 0 ${flags[1]} ${Math.min(6, info.duration)}`,
+ );
+ return [a, b] as const;
+}
diff --git a/packages/cli/src/measure/compare.test.ts b/packages/cli/src/measure/compare.test.ts
new file mode 100644
index 0000000000..3e6ba302ee
--- /dev/null
+++ b/packages/cli/src/measure/compare.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it } from "vitest";
+import { compareEnergy } from "./energy.js";
+import { compareLook, type Look } from "./look.js";
+
+const look = (over: Partial): Look => ({
+ frames: 4,
+ luma: 120,
+ contrast: 40,
+ saturation: 0.4,
+ bw_share: 0,
+ warmth: 0,
+ ...over,
+});
+
+describe("compareLook", () => {
+ it("finds nothing to compare in grayscale or black against itself", () => {
+ const grey = look({ saturation: 0, bw_share: 1 });
+ expect(compareLook(grey, grey).saturation_ratio).toBe(1);
+ expect(compareLook(grey, look({ saturation: 0.002 })).saturation_ratio).toBe(1);
+ const black = look({ luma: 0, contrast: 0, saturation: 0 });
+ expect(compareLook(black, black)).toMatchObject({ luma_ratio: 1, contrast_ratio: 1 });
+ });
+
+ it("still sees colour or light where the reference has none", () => {
+ expect(compareLook(look({ saturation: 0 }), look({})).saturation_ratio).toBeGreaterThan(100);
+ expect(compareLook(look({}), look({ saturation: 0 })).saturation_ratio).toBe(0);
+ expect(compareLook(look({ luma: 0 }), look({})).luma_ratio).toBeGreaterThan(100);
+ });
+});
+
+describe("compareEnergy", () => {
+ const still = Array.from({ length: 12 }, () => 0);
+ const moving = Array.from({ length: 12 }, (_, i) => 2 + (i % 3));
+
+ it("calls two still shots the same amount of movement", () => {
+ expect(compareEnergy(still, still)).toMatchObject({ mean_ratio: 1, peak_ratio: 1 });
+ expect(
+ compareEnergy(
+ still,
+ still.map(() => 0.02),
+ ),
+ ).toMatchObject({ mean_ratio: 1 });
+ });
+
+ it("still sees movement against a still reference, and the reverse", () => {
+ expect(compareEnergy(still, moving).mean_ratio).toBeGreaterThan(100);
+ expect(compareEnergy(moving, still).mean_ratio).toBe(0);
+ });
+});
diff --git a/packages/cli/src/measure/curve.test.ts b/packages/cli/src/measure/curve.test.ts
new file mode 100644
index 0000000000..fea547908a
--- /dev/null
+++ b/packages/cli/src/measure/curve.test.ts
@@ -0,0 +1,43 @@
+import { execFileSync } from "node:child_process";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, describe, expect, it } from "vitest";
+import { findFFmpeg, findFFprobe } from "../browser/ffmpeg.js";
+import { compareCurves, curves } from "./curve.js";
+
+const ffmpeg = findFFmpeg();
+const dir = mkdtempSync(join(tmpdir(), "hf-curve-test-"));
+afterAll(() => rmSync(dir, { recursive: true, force: true }));
+
+/** A white box sliding 0.5 s with back.out(1.7) from x=20 to x=220, starting at 0.3 s + `shift`. */
+function slide(name: string, shift: number): string {
+ const q = `min(max((t-0.3)/0.5,0),1)-1`;
+ const x = `20+200*(1+2.7*pow(${q},3)+1.7*pow(${q},2))`.replaceAll("t", `(t-${shift})`);
+ const out = join(dir, name);
+ execFileSync(ffmpeg!, [
+ ...["-nostdin", "-v", "error", "-y"],
+ ...["-f", "lavfi", "-i", "color=black:s=320x120:d=1.2:r=30"],
+ ...["-f", "lavfi", "-i", "color=white:s=40x40:d=1.2:r=30"],
+ ...["-filter_complex", `[0][1]overlay=x='${x}':y=40`],
+ ...["-pix_fmt", "yuv444p", "-c:v", "libx264", "-crf", "0", out],
+ ]);
+ return out;
+}
+
+describe.skipIf(!ffmpeg || !findFFprobe())("curves", () => {
+ it("reads a back.out slide's ease, length and overshoot, and pairs it with a later copy", () => {
+ const a = curves(slide("a.mp4", 0), 0, 1.2, [0, 0, 320, 120]);
+ const b = curves(slide("b.mp4", 0.1), 0, 1.2, [0, 0, 320, 120]);
+ expect(a.moves).toHaveLength(1);
+ const x = a.moves[0];
+ if (!x || x.pulse) throw new Error("expected one fitted move");
+ expect(x.prop).toBe("x");
+ expect(x.ease).toMatch(/^back\.out\(1\.[5-9]\)/);
+ expect(Math.abs(x.duration_s - 0.5)).toBeLessThanOrEqual(0.07);
+ expect(Math.abs(x.overshoot_pct - 10)).toBeLessThanOrEqual(3);
+ const c = compareCurves(a, b).find((m) => m.prop === "x")!;
+ expect(Math.abs(c.start_offset_s! - 0.1)).toBeLessThanOrEqual(0.04);
+ expect(c.curve_rmse!).toBeLessThan(0.05);
+ });
+});
diff --git a/packages/cli/src/measure/curve.ts b/packages/cli/src/measure/curve.ts
new file mode 100644
index 0000000000..b5448780a4
--- /dev/null
+++ b/packages/cli/src/measure/curve.ts
@@ -0,0 +1,303 @@
+// The ease of one graphic move as numbers, ported from the Studio's motion-curve.mjs: inside an ROI, the element's
+// box (centre, width, height) and its ink (mean difference from the background) on every frame, then for each
+// property that changes, when the move starts and settles, the overshoot past its end value and the closest GSAP
+// ease. Compared with a second window, a spring, a back-out or a slow expo is checked rather than eyeballed.
+import { Fix, probeVideo, readFrames, round, type Roi } from "./media.js";
+
+const W = 240;
+export type Prop = "x" | "y" | "w" | "h" | "ink";
+const PROPS: Prop[] = ["x", "y", "w", "h", "ink"];
+
+/** One frame of an element: its box centre and size (video pixels) and ink; x and y are null when it is absent. */
+interface Row {
+ t: number;
+ x: number | null;
+ y: number | null;
+ w: number;
+ h: number;
+ ink: number;
+}
+
+type Ease = [name: string, f: (u: number) => number];
+const pw = (k: number): Ease => [`power${k}.in`, (u) => u ** (k + 1)];
+const pwo = (k: number): Ease => [`power${k}.out`, (u) => 1 - (1 - u) ** (k + 1)];
+const pwio = (k: number): Ease => [
+ `power${k}.inOut`,
+ (u) => (u < 0.5 ? 2 ** k * u ** (k + 1) : 1 - (-2 * u + 2) ** (k + 1) / 2),
+];
+const back = (s: number): Ease => [
+ `back.out(${s.toFixed(1)})`,
+ (u) => 1 + (s + 1) * (u - 1) ** 3 + s * (u - 1) ** 2,
+];
+const elastic = (p: number): Ease => [
+ `elastic.out(1,${p})`,
+ (u) => (u <= 0 ? 0 : u >= 1 ? 1 : 2 ** (-10 * u) * Math.sin(((u - p / 4) * 2 * Math.PI) / p) + 1),
+];
+/** GSAP's named eases as functions of normalized time. */
+const EASES: Ease[] = [
+ ["none", (u) => u],
+ ...[1, 2, 3, 4].flatMap((k) => [pw(k), pwo(k), pwio(k)]),
+ ["sine.out", (u) => Math.sin((u * Math.PI) / 2)],
+ ["sine.inOut", (u) => -(Math.cos(Math.PI * u) - 1) / 2],
+ ["expo.out", (u) => (u >= 1 ? 1 : 1 - 2 ** (-10 * u))],
+ ["circ.out", (u) => Math.sqrt(1 - (u - 1) ** 2)],
+ ...Array.from({ length: 26 }, (_, i) => back(0.5 + i * 0.1)),
+ ...[0.2, 0.25, 0.3, 0.4, 0.5].map(elastic),
+];
+
+export interface FittedMove {
+ prop: Prop;
+ pulse?: undefined;
+ from: number;
+ to: number;
+ start_s: number;
+ duration_s: number;
+ frames: number;
+ overshoot_pct: number;
+ anticipation_pct: number;
+ ease: string;
+ rmse: number;
+ next: string[];
+ /** 21 samples of normalized progress, for comparing two moves' shapes. */
+ curve: number[];
+}
+
+/** A stretch that returns to where it began: its peak and length, no ease. */
+export interface PulseMove {
+ prop: Prop;
+ pulse: true;
+ from: number;
+ peak: number;
+ start_s: number;
+ duration_s: number;
+ frames: number;
+}
+
+export type Move = FittedMove | PulseMove;
+
+/** Box and ink per frame of `roi`, against a flat background (the ROI border's median on the first frame, or `bg`). */
+// fallow-ignore-next-line complexity
+function track(
+ path: string,
+ start: number,
+ seconds: number,
+ roi: Roi,
+ { bg = null, thr = 24 }: { bg?: number[] | null; thr?: number } = {},
+): { fps: number; bg: number[]; rows: Row[] } {
+ const fps = probeVideo(path).fps;
+ const width = Math.min(W, roi[2]);
+ const { frames: fs, h } = readFrames(path, { start, seconds, roi, width });
+ const first = fs[0];
+ if (!first)
+ throw new Fix(
+ `no frames between ${start}s and ${start + seconds}s`,
+ "pick a window inside the video",
+ );
+ const k = roi[2] / width;
+ let ref = bg;
+ if (!ref) {
+ const border: number[][] = [[], [], []];
+ for (let y = 0; y < h; y++)
+ for (let x = 0; x < width; x++)
+ if (x < 2 || y < 2 || x >= width - 2 || y >= h - 2)
+ for (let c = 0; c < 3; c++) border[c]!.push(first[(y * width + x) * 3 + c]!);
+ ref = border.map((v) => v.sort((a, b) => a - b)[v.length >> 1]!);
+ }
+ const [r0, g0, b0] = [ref[0]!, ref[1]!, ref[2]!];
+ const rows = fs.map((f, i): Row => {
+ const xs: number[] = [];
+ const ys: number[] = [];
+ let ink = 0;
+ for (let y = 0; y < h; y++)
+ for (let x = 0; x < width; x++) {
+ const j = (y * width + x) * 3;
+ const d = Math.max(
+ Math.abs(f[j]! - r0),
+ Math.abs(f[j + 1]! - g0),
+ Math.abs(f[j + 2]! - b0),
+ );
+ ink += d;
+ if (d > thr) {
+ xs.push(x);
+ ys.push(y);
+ }
+ }
+ const t = round(start + i / fps, 3);
+ if (xs.length < 4) return { t, x: null, y: null, w: 0, h: 0, ink: round(ink / (width * h), 2) };
+ xs.sort((a, b) => a - b);
+ ys.sort((a, b) => a - b);
+ const q = (v: number[], p: number) => v[Math.min(v.length - 1, Math.floor(v.length * p))]!;
+ const [x0, x1, y0, y1] = [q(xs, 0.01), q(xs, 0.99), q(ys, 0.01), q(ys, 0.99)];
+ return {
+ t,
+ x: round(roi[0] + ((x0 + x1 + 1) / 2) * k, 1),
+ y: round(roi[1] + ((y0 + y1 + 1) / 2) * k, 1),
+ w: round((x1 - x0 + 1) * k, 1),
+ h: round((y1 - y0 + 1) * k, 1),
+ ink: round(ink / (width * h), 2),
+ };
+ });
+ return { fps, bg: ref, rows };
+}
+
+/** Fit one stretch of values from its start value to its settled end value. */
+function fit(
+ rows: readonly Row[],
+ idx: number[],
+ v: number[],
+ prop: Prop,
+ fps: number,
+ a: number,
+ b: number,
+): FittedMove {
+ const [v0, v1] = [v[a]!, v[b]!];
+ const span = v1 - v0;
+ const p = v.slice(a, b + 1).map((x) => (x - v0) / span);
+ const u = p.map((_, i) => i / Math.max(1, p.length - 1));
+ const fits = EASES.map(([name, f]) => ({
+ name,
+ rmse: Math.sqrt(p.reduce((s, x, i) => s + (x - f(u[i]!)) ** 2, 0) / p.length),
+ })).sort((m, n) => m.rmse - n.rmse);
+ return {
+ prop,
+ from: round(v0, 1),
+ to: round(v1, 1),
+ start_s: rows[idx[a]!]!.t,
+ duration_s: round((idx[b]! - idx[a]!) / fps, 3),
+ frames: idx[b]! - idx[a]!,
+ overshoot_pct: round(Math.max(0, Math.max(...p) - 1) * 100, 1),
+ anticipation_pct: round(Math.max(0, -Math.min(...p)) * 100, 1),
+ ease: fits[0]!.name,
+ rmse: round(fits[0]!.rmse, 3),
+ next: fits.slice(1, 3).map((f) => `${f.name} ${round(f.rmse, 3)}`),
+ curve: Array.from({ length: 21 }, (_, i) =>
+ round(p[Math.round((i / 20) * (p.length - 1))]!, 3),
+ ),
+ };
+}
+
+/** Every move of one property: stretches of change separated by holds of 0.15 s or more (shorter stills are the
+ * turn at an overshoot's peak). A stretch that returns to where it began is a pulse (peak and length, no ease). */
+// fallow-ignore-next-line complexity
+function fitMoves(
+ rows: readonly Row[],
+ prop: Prop,
+ fps: number,
+ minChange: number,
+ quant: number,
+): Move[] {
+ const idx = rows.flatMap((r, i) => (r[prop] == null ? [] : [i]));
+ const v = idx.map((i) => rows[i]![prop] ?? 0);
+ const out: Move[] = [];
+ for (let i = 0; i < v.length - 1; ) {
+ if (Math.abs(v[i + 1]! - v[i]!) <= quant) {
+ i++;
+ continue;
+ }
+ const hold = Math.max(3, Math.round(0.15 * fps));
+ let [b, still] = [i + 1, 0];
+ for (let j = i + 1; j < v.length - 1 && still < hold; j++)
+ if (Math.abs(v[j + 1]! - v[j]!) <= quant) still++;
+ else [still, b] = [0, j + 1];
+ const span = v[b]! - v[i]!;
+ const peak = v
+ .slice(i, b + 1)
+ .reduce((m, x) => (Math.abs(x - v[i]!) > Math.abs(m - v[i]!) ? x : m), v[i]!);
+ // a creep of under 3% of the move before it really starts is compression noise, not the move
+ let a = i;
+ while (a < b - 2 && Math.abs(v[a + 1]! - v[a]!) < 0.03 * Math.abs(span)) a++;
+ if (Math.abs(span) >= minChange) out.push(fit(rows, idx, v, prop, fps, a, b));
+ else if (Math.abs(peak - v[i]!) >= minChange)
+ out.push({
+ prop,
+ pulse: true,
+ from: round(v[i]!, 1),
+ peak: round(peak, 1),
+ start_s: rows[idx[i]!]!.t,
+ duration_s: round((idx[b]! - idx[i]!) / fps, 3),
+ frames: idx[b]! - idx[i]!,
+ });
+ i = b;
+ }
+ return out;
+}
+
+export interface Curves {
+ start: number;
+ seconds: number;
+ roi: Roi;
+ fps: number;
+ bg: number[];
+ moves: Move[];
+}
+
+/** Every move of the element in `roi`, sorted by start. */
+export function curves(
+ path: string,
+ start: number,
+ seconds: number,
+ roi: Roi,
+ opts: { bg?: number[] | null; thr?: number } = {},
+): Curves {
+ const { fps, bg, rows } = track(path, start, seconds, roi, opts);
+ const minPx = 0.02 * Math.max(roi[2], roi[3]);
+ const step = roi[2] / Math.min(W, roi[2]);
+ const moves = PROPS.flatMap((k) =>
+ k === "ink" ? fitMoves(rows, k, fps, 2, 0.5) : fitMoves(rows, k, fps, minPx, step),
+ ).sort((m, n) => m.start_s - n.start_s);
+ return { start, seconds, roi, fps: round(fps, 2), bg, moves };
+}
+
+export interface MoveComparison {
+ prop: Prop;
+ at_s: number;
+ yours?: "no matching move";
+ start_offset_s?: number;
+ duration_frames?: string;
+ pulse?: true;
+ peak?: string;
+ ease?: string;
+ same_family?: boolean;
+ overshoot_pct?: string;
+ curve_rmse?: number;
+}
+
+/** Pair each reference move with your move of the same property that starts closest on the window's clock. */
+export function compareCurves(ref: Curves, yours: Curves): MoveComparison[] {
+ const family = (s: string) => s.replace(/\(.*\)/, "").replace(/\d/, "");
+ return ref.moves.map((m) => {
+ const rel = m.start_s - ref.start;
+ const d = yours.moves
+ .filter((x) => x.prop === m.prop && !!x.pulse === !!m.pulse)
+ .sort(
+ (x, y) => Math.abs(x.start_s - yours.start - rel) - Math.abs(y.start_s - yours.start - rel),
+ )[0];
+ const head = { prop: m.prop, at_s: round(rel, 2) };
+ if (!d) return { ...head, yours: "no matching move" };
+ const common = {
+ ...head,
+ start_offset_s: round(d.start_s - yours.start - rel, 3),
+ duration_frames: `${m.frames} → ${d.frames}`,
+ };
+ if (m.pulse || d.pulse)
+ return {
+ ...common,
+ pulse: true,
+ peak: `${m.pulse ? m.peak : m.to} → ${d.pulse ? d.peak : d.to}`,
+ };
+ return {
+ ...common,
+ ease: `${m.ease} → ${d.ease}`,
+ same_family: family(m.ease) === family(d.ease),
+ overshoot_pct: `${m.overshoot_pct} → ${d.overshoot_pct}`,
+ curve_rmse: round(
+ Math.sqrt(m.curve.reduce((s, x, i) => s + (x - d.curve[i]!) ** 2, 0) / m.curve.length),
+ 3,
+ ),
+ };
+ });
+}
+
+/** Moves as printed: the shape samples stay internal. */
+export const printable = (moves: Move[]) =>
+ moves.map((m) => (m.pulse ? m : { ...m, curve: undefined }));
diff --git a/packages/cli/src/measure/cuts.test.ts b/packages/cli/src/measure/cuts.test.ts
new file mode 100644
index 0000000000..87102d0185
--- /dev/null
+++ b/packages/cli/src/measure/cuts.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from "vitest";
+import { confirmsCut, cutsIn, findCuts, SIG_H, SIG_W } from "./cuts.js";
+
+/** Frame changes: `base` everywhere, with the given changes at their frames. */
+const changes = (n: number, base: number, at: Record) =>
+ Array.from({ length: n }, (_, i) => (i === 0 ? 0 : (at[i] ?? base)));
+
+describe("cutsIn", () => {
+ it("finds a hard cut and a two-frame whip as one cut", () => {
+ expect(cutsIn(changes(60, 1, { 20: 40, 40: 30, 41: 25 }))).toEqual([
+ { frame: 20, frames: 1, change: 40 },
+ { frame: 40, frames: 2, change: 30 },
+ ]);
+ });
+
+ it("finds a soft same-angle punch-in that nothing near it rivals", () => {
+ // dan 9.743 s: 11.3 grey levels against neighbours of about 1.
+ expect(cutsIn(changes(60, 1, { 30: 11.3 }))).toEqual([
+ { frame: 30, frames: 1, change: 11.3, soft: true },
+ ]);
+ });
+
+ it("leaves a smaller change among moving frames or a stepped animation alone", () => {
+ // Hands moving: neighbours up to 5, so 11 is not alone.
+ expect(cutsIn(changes(60, 1, { 25: 5, 30: 11 }))).toEqual([]);
+ // A 15 fps animation in a 30 fps file changes every other frame by about as much.
+ const stepped = Array.from({ length: 60 }, (_, i) => (i % 2 ? 0 : 10.5));
+ expect(cutsIn(stepped)).toEqual([]);
+ expect(cutsIn(changes(60, 1, { 30: 9 }))).toEqual([]);
+ });
+});
+
+describe("confirmsCut", () => {
+ it("matches a soft cut with a clear change within a frame on the other side", () => {
+ const cut = { frame: 30, frames: 1, change: 11.3, soft: true as const };
+ expect(confirmsCut(changes(60, 1, { 31: 7 }), cut)).toBe(true);
+ expect(confirmsCut(changes(60, 1, { 32: 7 }), cut)).toBe(false);
+ expect(confirmsCut(changes(60, 1, { 30: 4 }), cut)).toBe(false);
+ expect(confirmsCut(changes(60, 2, { 30: 7 }), cut)).toBe(false);
+ });
+});
+
+describe("findCuts", () => {
+ it("reads changes from grey frames", () => {
+ const frame = (v: number) => new Uint8Array(SIG_W * SIG_H).fill(v);
+ const frames = [
+ ...Array.from({ length: 20 }, () => frame(100)),
+ ...Array.from({ length: 20 }, () => frame(140)),
+ ];
+ expect(findCuts(frames)).toEqual([{ frame: 20, frames: 1, change: 40 }]);
+ });
+});
diff --git a/packages/cli/src/measure/cuts.ts b/packages/cli/src/measure/cuts.ts
new file mode 100644
index 0000000000..725f4bdcb4
--- /dev/null
+++ b/packages/cli/src/measure/cuts.ts
@@ -0,0 +1,83 @@
+// Cuts from the frame-to-frame difference, ported from the Studio's videoShots.mjs; ffmpeg's scene score misses some.
+// A punch-in at the same angle changes less than a cut, so a smaller change that stands alone is a soft cut.
+import { decode, meanAbsDiff, type Frames } from "./media.js";
+
+export const SIG_W = 64;
+export const SIG_H = 36;
+const CUT_LEVEL = 12;
+const CUT_RATIO = 4;
+const SOFT_LEVEL = 10;
+const SOFT_RATIO = 8;
+const SOFT_ALONE = 4;
+const CONFIRM_LEVEL = 6;
+const CONFIRM_SHARE = 0.5;
+const NEIGHBOURS = 12;
+
+export interface Cut {
+ frame: number;
+ /** A whip or a two-frame dissolve changes on consecutive frames: one cut this many frames long. */
+ frames: number;
+ /** Its largest change, in mean grey levels. */
+ change: number;
+ soft?: true;
+}
+
+/** Every frame of ffmpeg's `input` (after `filters`) as SIG_W x SIG_H grey levels. */
+export function signatures(input: string[], filters: string[] = []): Frames {
+ return decode(input, [...filters, `scale=${SIG_W}:${SIG_H}:flags=area`], SIG_W, SIG_H, true);
+}
+
+const median = (values: number[]) => {
+ const sorted = [...values].sort((x, y) => x - y);
+ return sorted[Math.floor(sorted.length / 2)] ?? 0;
+};
+
+export function frameChanges(frames: Uint8Array[]): number[] {
+ return frames.map((f, i) => (i ? meanAbsDiff(frames[i - 1]!, f) : 0));
+}
+
+const neighbours = (diffs: number[], i: number) =>
+ diffs.slice(Math.max(1, i - NEIGHBOURS), i).concat(diffs.slice(i + 1, i + NEIGHBOURS + 1));
+
+export function cutsIn(diffs: number[]): Cut[] {
+ const hits = diffs.flatMap((d, i): { frame: number; change: number; soft?: true }[] => {
+ if (i === 0) return [];
+ const around = neighbours(diffs, i);
+ const typical = Math.max(1, median(around));
+ if (d >= CUT_LEVEL && d >= CUT_RATIO * typical) return [{ frame: i, change: d }];
+ const alone = d >= SOFT_ALONE * Math.max(0, ...around);
+ return d >= SOFT_LEVEL && d >= SOFT_RATIO * typical && alone
+ ? [{ frame: i, change: d, soft: true }]
+ : [];
+ });
+ const out: Cut[] = [];
+ for (const { soft, ...h } of hits) {
+ const last = out.at(-1);
+ if (last && h.frame === last.frame + last.frames) {
+ last.frames++;
+ last.change = Math.max(last.change, h.change);
+ if (!soft) delete last.soft;
+ } else out.push({ ...h, frames: 1, ...(soft ? { soft } : {}) });
+ }
+ return out;
+}
+
+/** The frame indexes where a new shot starts, each with its change and length. */
+export function findCuts(frames: Uint8Array[]): Cut[] {
+ return cutsIn(frameChanges(frames));
+}
+
+/**
+ * Whether these changes show a clear change within a frame of `frame`, though maybe under a cut's thresholds: a
+ * soft cut found on the other side counts as matched by it, as a soft cut is a change near the line.
+ */
+export function confirmsCut(diffs: number[], cut: Cut): boolean {
+ return [cut.frame - 1, cut.frame, cut.frame + 1].some((i) => {
+ const d = diffs[i];
+ if (i < 1 || d === undefined) return false;
+ return (
+ d >= Math.max(CONFIRM_LEVEL, CONFIRM_SHARE * cut.change) &&
+ d >= CUT_RATIO * Math.max(1, median(neighbours(diffs, i)))
+ );
+ });
+}
diff --git a/packages/cli/src/measure/diff-people.test.ts b/packages/cli/src/measure/diff-people.test.ts
new file mode 100644
index 0000000000..557fb5b146
--- /dev/null
+++ b/packages/cli/src/measure/diff-people.test.ts
@@ -0,0 +1,257 @@
+import { execFileSync } from "node:child_process";
+import { mkdirSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+import { soundOffset } from "./diff.js";
+import {
+ clipFolder,
+ diffVerdicts,
+ ffmpeg,
+ loadOpenCvFirst,
+ noTools,
+ REF_ARGS,
+} from "./diff.test-helpers.js";
+import { probeVideo } from "./media.js";
+import { parseSegments } from "./segments.js";
+
+const { dir, clip } = clipFolder("hf-diff-person-test-");
+
+describe.skipIf(noTools)("diffVideos: copies, sound and re-shot people", () => {
+ loadOpenCvFirst();
+ const ref = noTools ? "" : clip("ref.mp4", REF_ARGS);
+
+ // The ledger cuts the original's whole frame for 0–3 s. Two comparisons per test, so none nears the per-test
+ // limit under the flake gate's contention.
+ const ledger = join(dir, "manifest.jsonl");
+ writeFileSync(
+ ledger,
+ JSON.stringify({
+ type: "video",
+ path: "assets/all.mp4",
+ provenance: { provider: "original", window: [0, 3], roi: [0, 0, 320, 180] },
+ }) + "\n",
+ );
+ const titled = '## S01 · 0–3 s · Title\nPixels: rebuilt\nCopy: "TITLE"\n';
+ const reuse = (yours: string, md: string, name: string) =>
+ diffVerdicts({
+ reference: ref,
+ yours,
+ segments: parseSegments(md),
+ ledger,
+ outDir: join(dir, name),
+ });
+
+ it("fails the original's whole frame played where copy is meant to be rebuilt", async () => {
+ const copy = await reuse(ref, titled, "copy");
+ expect(copy.whole_frame_reuse).toMatchObject({ spans: [[0, 3]], drawn: [[0, 3]], pass: false });
+ expect(copy.segments?.[0]?.pass).toBe(false);
+ expect(copy.pass).toBe(false);
+ // Footage reused with its burned-in title is a copy too (Miao, 2026-10-23: no whole-frame cut with drawn things).
+ const burned = await reuse(
+ ref,
+ '## S01 · 0–3 s · Title over footage\nPixels: reused\nCopy: "TITLE"\n',
+ "burned",
+ );
+ expect(burned.whole_frame_reuse).toMatchObject({ share: 1, drawn: [[0, 3]], pass: false });
+ });
+
+ it("passes footage with nothing drawn on it cut whole", async () => {
+ const footage = await reuse(ref, "## S01 · 0–3 s · Footage\nPixels: reused\n", "footage");
+ expect(footage.whole_frame_reuse).toMatchObject({ share: 1, drawn: [], pass: true });
+ expect(footage.pass).toBe(true);
+ });
+
+ it("does not count a cut that only fed a generation as reuse", async () => {
+ // A motion guide is not played: yours differs from it.
+ const flipped = clip("guided.mp4", [...["-i", ref, "-vf"], "hflip"]);
+ const guided = await reuse(flipped, titled, "guided");
+ expect(guided.whole_frame_reuse).toMatchObject({ spans: [], pass: true });
+ // A generated shot that starts from the original's first frame matches it for a few frames only: not reuse.
+ const started = clip("started.mp4", [
+ ...["-i", ref, "-filter_complex"],
+ "[0]split[a][b];[b]hflip[f];[a][f]overlay=enable='gte(t\\,0.2)'",
+ ]);
+ const start = await reuse(started, titled, "started");
+ expect(start.whole_frame_reuse).toMatchObject({ spans: [], pass: true });
+ });
+
+ it("finds a whole-frame still of the original shown in yours", async () => {
+ const ledger = join(dir, "stills.jsonl");
+ writeFileSync(
+ ledger,
+ [
+ { type: "image", provenance: { provider: "original", at: 1, roi: [0, 0, 320, 180] } },
+ { type: "image", provenance: { provider: "original", at: 2.5 } },
+ ]
+ .map((e) => JSON.stringify(e))
+ .join("\n"),
+ );
+ // Yours holds the original's frame at 1 s for the whole clip.
+ const held = clip("held.mp4", [
+ ...["-i", ref, "-vf"],
+ "select=eq(n\\,30),loop=loop=89:size=1,setpts=N/30/TB",
+ ]);
+ const r = await diffVerdicts({
+ reference: ref,
+ yours: held,
+ segments: parseSegments('## S01 · 0–3 s · Collage\nPixels: rebuilt\nCopy: "TITLE"\n'),
+ ledger,
+ outDir: join(dir, "held"),
+ });
+ expect(r.whole_frame_reuse).toMatchObject({ stills: [1], spans: [[0, 3]], pass: false });
+ });
+
+ it("reads sound that starts late as late, and the picture's length as the duration", async () => {
+ // Clicks at uneven times, with the sound running 0.4 s past the picture.
+ const clicks = "aevalsrc=sin(2*PI*660*t)*lt(mod(t*t*3\\,1)\\,0.08):s=48000:d=3.4";
+ const voiced = (name: string, delay: number) =>
+ clip(name, [
+ ...["-f", "lavfi", "-i", "testsrc2=d=3:r=30:s=320x180"],
+ ...["-itsoffset", String(delay), "-f", "lavfi", "-i", clicks],
+ ...["-map", "0:v", "-map", "1:a", "-c:a", "aac"],
+ ]);
+ const on = voiced("voiced.mp4", 0);
+ const same = await diffVerdicts({ reference: on, yours: on, outDir: join(dir, "voiced") });
+ expect(same.duration).toMatchObject({ reference: 3, pass: true });
+ expect(same.sound).toMatchObject({ offset_ms: 0, pass: true });
+ const late = await diffVerdicts({
+ reference: on,
+ yours: voiced("late.mp4", 0.2),
+ outDir: join(dir, "late"),
+ });
+ expect(late.sound).toMatchObject({ offset_ms: 200, pass: false });
+ });
+
+ it("places the sound by its decoded timestamps, not the start time the probe reports", () => {
+ // ffmpeg 5.1 drops an HE-AAC edit list's skip twice: the first sample it keeps is timestamped 0.1 s in while
+ // the probe still says the track starts at 0. Here a sound timestamped 0.25 s in, probed as starting at 0,
+ // against the same sound with 0.25 s of silence baked into its samples: in sync.
+ const clicks = "aevalsrc=sin(2*PI*660*t)*lt(mod(t*t*3\\,1)\\,0.08):s=48000:d=3";
+ const picture = ["-f", "lavfi", "-i", "testsrc2=d=3:r=30:s=320x180"];
+ const stamped = clip("stamped.mp4", [
+ ...picture,
+ ...["-itsoffset", "0.25", "-f", "lavfi", "-i", clicks],
+ ...["-map", "0:v", "-map", "1:a", "-c:a", "pcm_s16le", "-f", "mov"],
+ ]);
+ const baked = clip("baked.mp4", [
+ ...picture,
+ ...["-f", "lavfi", "-i", clicks, "-af", "adelay=250:all=1"],
+ ...["-map", "0:v", "-map", "1:a", "-c:a", "pcm_s16le", "-f", "mov"],
+ ]);
+ const probedAtZero = { ...probeVideo(stamped), audioStart: 0 };
+ expect(soundOffset(stamped, baked, probedAtZero, probeVideo(baked))).toMatchObject({
+ offset_ms: 0,
+ pass: true,
+ });
+ });
+
+ it("passes a re-shot person whose motion is off when the components are right", async () => {
+ // The bottom half (the person) frozen on its first frame: no motion at all. Pixels above match.
+ const frozen = clip("frozen.mp4", [
+ ...["-i", ref, "-filter_complex"],
+ "[0]split[a][b];[b]crop=320:90:0:90,trim=end_frame=1,tpad=stop=89:stop_mode=clone[f];[a][f]overlay=0:90",
+ ]);
+ const r = await diffVerdicts({
+ reference: ref,
+ yours: frozen,
+ segments: parseSegments(
+ "## S01 · 0–3 s · Board over a presenter\nPixels: rebuilt\nRegenerated: 0, 0.5, 1, 0.5\n",
+ ),
+ outDir: join(dir, "frozen"),
+ });
+ const [s] = r.segments!;
+ expect(s!.person?.energy?.mean_ratio).toBeLessThan(0.5);
+ expect(s!.person?.gates).toEqual({ framing: null, text: null, sync: null });
+ expect(s!.pass).toBe(true);
+ expect(r.components).toMatchObject({ passed: 1, total: 1 });
+ expect(r.person?.energy).toBeLessThan(0.5);
+ expect(r.pass).toBe(true);
+ });
+
+ // The original: a white label over a soft lower half (the person). Yours draws the label over a re-shot half.
+ const strokes = (x0: number) =>
+ [0, 14, 28].map((x) => `drawbox=x=${x0 + x}:y=110:w=6:h=24:color=white:t=fill`).join(",");
+ const label = strokes(120);
+ const soft = (delay: number) =>
+ `[0]split[a][b];[b]crop=320:90:0:90,gblur=sigma=10,hue=s=0.4,tpad=start=${delay}:start_mode=clone[f];[a][f]overlay=0:90:shortest=1`;
+ const carried = join(dir, "carried");
+ // The generated clips: one made from a guide with the label on it, one from a masked guide. Yours draws the
+ // label over each; over the first, 8 px off, the letters show doubled.
+ const carriedRef = (): string => {
+ const base = clip("carried-ref.mp4", [
+ ...["-i", ref, "-filter_complex"],
+ `${soft(0)},${label}`,
+ ]);
+ mkdirSync(join(carried, "assets"), { recursive: true });
+ clip("carried/assets/dirty.mp4", [...["-i", ref, "-filter_complex"], `${soft(5)},${label}`]);
+ clip("carried/assets/clean.mp4", [...["-i", ref, "-filter_complex"], soft(5)]);
+ execFileSync(ffmpeg!, [
+ ...["-hide_banner", "-loglevel", "error", "-y", "-i", ref, "-filter_complex"],
+ `${soft(0)},trim=end_frame=1`,
+ ...["-frames:v", "1", join(carried, "assets", "still.png")],
+ ]);
+ return base;
+ };
+ const carriedBase = noTools ? "" : carriedRef();
+ const judgeCarried = (path: string, x0: number) => {
+ const ledger = join(carried, `${path}.jsonl`);
+ writeFileSync(
+ ledger,
+ JSON.stringify({
+ type: "video",
+ path: `assets/${path}.mp4`,
+ provenance: { provider: "heygen", references: ["assets/still.png"], window: [0, 3] },
+ }) + "\n",
+ );
+ return diffVerdicts({
+ reference: carriedBase,
+ yours: clip(`carried-yours-${path}.mp4`, [
+ ...["-i", join(carried, "assets", `${path}.mp4`), "-vf"],
+ strokes(x0),
+ ]),
+ segments: parseSegments(
+ "## S01 · 0–3 s · Label over a presenter\nPixels: rebuilt\nRegenerated: 0, 90, 320, 90\nDrawn: 118, 108, 42, 28\n",
+ ),
+ ledger,
+ project: carried,
+ outDir: join(dir, `carried-${path}`),
+ });
+ };
+
+ it("fails a re-shot person whose generated clip carries the original's text", async () => {
+ const dirty = await judgeCarried("dirty", 128);
+ expect(dirty.segments?.[0]?.person?.text?.[0]).toMatchObject({
+ drawn: "S01.D1",
+ carried: true,
+ });
+ expect(dirty.segments?.[0]?.pass).toBe(false);
+ expect(dirty.person).toMatchObject({ gates: { text: false }, failed: { text: ["S01"] } });
+ expect(dirty.pass).toBe(false);
+ });
+
+ it("passes a re-shot person whose generated clip came from a masked guide", async () => {
+ const clean = await judgeCarried("clean", 120);
+ expect(clean.segments?.[0]?.drawn?.[0]?.pass).toBe(true);
+ expect(clean.segments?.[0]?.person?.gates.text).toBe(true);
+ expect(clean.segments?.[0]?.pass).toBe(true);
+ expect(clean.person?.shots_at_cuts).toMatchObject({
+ at_cuts: 1,
+ total: 1,
+ cuts_without_shot: [],
+ });
+ });
+
+ it("judges a regenerated segment by motion and look, not pixels", async () => {
+ const shifted = clip("shifted.mp4", [...["-i", ref, "-vf"], "hflip"]);
+ const segments = parseSegments("## S01 · 0–3 s · AI shot\nPixels: regenerated\n");
+ const r = await diffVerdicts({
+ reference: ref,
+ yours: shifted,
+ segments,
+ outDir: join(dir, "regen"),
+ });
+ expect(r.ssim.mean).toBeLessThan(0.9);
+ expect(r.segments?.[0]?.energy?.mean_ratio).toBeCloseTo(1, 1);
+ expect(r.segments?.[0]?.pass).toBe(true);
+ });
+});
diff --git a/packages/cli/src/measure/diff-segments.test.ts b/packages/cli/src/measure/diff-segments.test.ts
new file mode 100644
index 0000000000..db28dc44d1
--- /dev/null
+++ b/packages/cli/src/measure/diff-segments.test.ts
@@ -0,0 +1,132 @@
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+import {
+ clipFolder,
+ diffVerdicts,
+ loadOpenCvFirst,
+ noTools,
+ REF_ARGS,
+} from "./diff.test-helpers.js";
+import { parseSegments } from "./segments.js";
+
+const { dir, clip } = clipFolder("hf-diff-seg-test-");
+
+describe.skipIf(noTools)("diffVideos with segments", () => {
+ loadOpenCvFirst();
+ const ref = noTools ? "" : clip("ref.mp4", REF_ARGS);
+
+ it("judges a rebuilt segment's regenerated region by motion and look, the rest by SSIM", async () => {
+ // The bottom half mirrored, as a re-shot presenter differs in pixels but moves the same.
+ const mixed = clip("mixed.mp4", [
+ ...["-i", ref, "-filter_complex"],
+ "[0]split[a][b];[b]crop=320:90:0:90,hflip[f];[a][f]overlay=0:90",
+ ]);
+ const md = "## S01 · 0–3 s · Board over a presenter\nPixels: rebuilt\n";
+ const plain = await diffVerdicts({
+ reference: ref,
+ yours: mixed,
+ segments: parseSegments(md),
+ outDir: join(dir, "mixed-plain"),
+ });
+ expect(plain.segments?.[0]?.pass).toBe(false);
+ const r = await diffVerdicts({
+ reference: ref,
+ yours: mixed,
+ segments: parseSegments(`${md}Regenerated: 0, 0.5, 1, 0.5\n`),
+ outDir: join(dir, "mixed"),
+ });
+ const [s] = r.segments!;
+ expect(s!.ssim!.mean).toBeGreaterThan(0.99);
+ expect(s!.regenerated?.roi).toEqual([0, 90, 320, 90]);
+ expect(s!.person?.energy?.mean_ratio).toBeCloseTo(1, 1);
+ expect(s!.pass).toBe(true);
+ // A wrong box outside the region still fails the segment.
+ const boxed = clip("mixed-box.mp4", [
+ ...["-i", mixed, "-vf"],
+ "drawbox=x=20:y=10:w=60:h=40:color=red:t=fill",
+ ]);
+ const bad = await diffVerdicts({
+ reference: ref,
+ yours: boxed,
+ segments: parseSegments(`${md}Regenerated: 0, 0.5, 1, 0.5\n`),
+ outDir: join(dir, "mixed-box"),
+ });
+ expect(bad.segments?.[0]?.pass).toBe(false);
+ });
+
+ // A label (three white strokes) over a soft bottom half, a regenerated person (here 5 frames late); yours
+ // draws it 24 px off. Two tests of two comparisons each, so neither nears the per-test limit on a busy runner.
+ const strokes = (x0: number) =>
+ [0, 14, 28].map((x) => `drawbox=x=${x0 + x}:y=110:w=6:h=24:color=white:t=fill`).join(",");
+ const soft = (delay: number) =>
+ `[0]split[a][b];[b]crop=320:90:0:90,gblur=sigma=10,hue=s=0.4,tpad=start=${delay}:start_mode=clone[f];[a][f]overlay=0:90:shortest=1`;
+ const labelled = (name: string, delay: number, x0: number) =>
+ noTools ? "" : clip(name, [...["-i", ref, "-filter_complex"], `${soft(delay)},${strokes(x0)}`]);
+ const base = labelled("label-ref.mp4", 0, 120);
+ const right = labelled("label-right.mp4", 5, 120);
+ const off = labelled("label-off.mp4", 5, 144);
+ const md =
+ "## S01 · 0–3 s · Label over a presenter\nPixels: rebuilt\nRegenerated: 0, 90, 320, 90\n";
+ const judge = (yours: string, text: string, name: string) =>
+ diffVerdicts({
+ reference: base,
+ yours,
+ segments: parseSegments(text),
+ outDir: join(dir, name),
+ });
+
+ it("hides a drawn element in a regenerated region without a Drawn line, and flags a box over the whole frame", async () => {
+ expect((await judge(off, md, "drawn-hidden")).segments?.[0]?.pass).toBe(true);
+ const whole = await judge(right, md.replace("0, 90, 320, 90", "0, 0, 320, 180"), "drawn-whole");
+ expect(whole.warnings.some((w) => w.includes("covers the whole frame"))).toBe(true);
+ });
+
+ it("judges each drawn element inside a regenerated region by itself, not by what is behind it", async () => {
+ const drawn = `${md}Drawn: 118, 108, 42, 28\n`;
+ const good = (await judge(right, drawn, "drawn-right")).segments![0]!;
+ expect(good.pass).toBe(true);
+ expect(good.drawn?.[0]).toMatchObject({ id: "S01.D1", box: [118, 108, 42, 28], pass: true });
+ expect(good.scored).toContain("1 drawn elements, each scored by itself");
+ const bad = await judge(off, drawn, "drawn-off");
+ expect(bad.segments?.[0]?.pass).toBe(false);
+ expect(bad.segments?.[0]?.drawn?.[0]?.pass).toBe(false);
+ });
+
+ it("scores a drawn element by itself without segments, and its ink says when yours is thinner", async () => {
+ // The same three-stroke label over two different flat backdrops; yours draws it at half the stroke width.
+ const strokes = (w: number) =>
+ [0, 14, 28].map((x) => `drawbox=x=${120 + x}:y=110:w=${w}:h=24:color=white:t=fill`).join(",");
+ const backdrop = (colour: string) => [
+ "-f",
+ "lavfi",
+ "-i",
+ `color=c=${colour}:s=320x180:d=3:r=30`,
+ ];
+ const base = clip("solo-ref.mp4", [...backdrop("0x305070"), "-vf", strokes(6)]);
+ const right = clip("solo-right.mp4", [...backdrop("0x604030"), "-vf", strokes(6)]);
+ const thin = clip("solo-thin.mp4", [...backdrop("0x604030"), "-vf", strokes(3)]);
+ const box: [number, number, number, number] = [116, 106, 44, 32];
+ const good = await diffVerdicts({
+ reference: base,
+ yours: right,
+ at: [0.5, 1, 1.5, 2],
+ drawn: [{ box }, { box, window: [1, 3] }],
+ outDir: join(dir, "solo-right"),
+ });
+ expect(good.segments).toBeUndefined();
+ expect(good.drawn).toHaveLength(2);
+ expect(good.drawn?.[0]).toMatchObject({ id: "D1", box, window: [0, 3], frames: 4, pass: true });
+ expect(good.drawn?.[1]).toMatchObject({ id: "D2", window: [1, 3], frames: 3, pass: true });
+ const bad = await diffVerdicts({
+ reference: base,
+ yours: thin,
+ at: [0.5, 1, 1.5, 2],
+ drawn: [{ box }],
+ outDir: join(dir, "solo-thin"),
+ });
+ expect(good.drawn?.[0]).toMatchObject({ score: 1, offset: [0, 0], ink: 1 });
+ // Half-weight letters in the right place: the score barely drops, the ink says it.
+ expect(bad.drawn?.[0]?.score).toBeLessThan(0.9);
+ expect(bad.drawn?.[0]?.ink).toBe(0.5);
+ });
+});
diff --git a/packages/cli/src/measure/diff.test-helpers.ts b/packages/cli/src/measure/diff.test-helpers.ts
new file mode 100644
index 0000000000..02b3f040aa
--- /dev/null
+++ b/packages/cli/src/measure/diff.test-helpers.ts
@@ -0,0 +1,63 @@
+import { execFileSync } from "node:child_process";
+import { cpSync, existsSync, mkdtempSync, renameSync, rmSync } from "node:fs";
+import { tmpdir, userInfo } from "node:os";
+import { basename, join } from "node:path";
+import { afterAll, beforeAll } from "vitest";
+import { findFFmpeg, findFFprobe } from "../browser/ffmpeg.js";
+import { diffVideos, type DiffOptions } from "./diff.js";
+import { loadOpenCv, OPENCV_DIR } from "./opencv.js";
+
+export const ffmpeg = findFFmpeg();
+export const noTools = !ffmpeg || !findFFprobe();
+
+/** testsrc2, 3 s at 30 fps: the original most of diff's tests compare against. */
+export const REF_ARGS = ["-f", "lavfi", "-i", "testsrc2=d=3:r=30:s=320x180"];
+
+/** A temp folder for one test file's clips, removed after its tests, and a maker of lossless synthetic clips in it,
+ * so SSIM differences come from the picture, not the encoder. */
+export function clipFolder(prefix: string): {
+ dir: string;
+ clip: (name: string, args: string[]) => string;
+} {
+ const dir = mkdtempSync(join(tmpdir(), prefix));
+ afterAll(() => rmSync(dir, { recursive: true, force: true }));
+ const clip = (name: string, args: string[]): string => {
+ const out = join(dir, name);
+ execFileSync(ffmpeg!, [
+ ...["-hide_banner", "-loglevel", "error", "-y", ...args],
+ ...["-pix_fmt", "yuv420p", "-c:v", "libx264", "-crf", "0", out],
+ ]);
+ return out;
+ };
+ return { dir, clip };
+}
+
+/** diffVideos for a test that reads verdicts only: no worst-moment pictures, each of which costs seven ffmpeg runs. */
+export const diffVerdicts = (options: DiffOptions) => diffVideos({ worst: 0, ...options });
+
+/** opencv.js loaded before a block's tests, so none pays for its download inside the per-test limit. The files come
+ * from this machine's cache, else a temp copy kept between runs (each has its own home), else the network. */
+export function loadOpenCvFirst(): void {
+ beforeAll(async () => {
+ const shared = join(tmpdir(), `hf-test-opencv-${basename(OPENCV_DIR)}`);
+ const machine = join(
+ userInfo().homedir,
+ ".cache",
+ "hyperframes",
+ "opencv",
+ basename(OPENCV_DIR),
+ );
+ for (const from of [machine, shared])
+ if (!existsSync(join(OPENCV_DIR, "opencv.js")) && existsSync(join(from, "opencv.js")))
+ cpSync(from, OPENCV_DIR, { recursive: true });
+ await loadOpenCv();
+ if (existsSync(join(shared, "opencv.js"))) return;
+ const staged = `${shared}-${process.pid}`;
+ cpSync(OPENCV_DIR, staged, { recursive: true });
+ try {
+ renameSync(staged, shared);
+ } catch {
+ rmSync(staged, { recursive: true, force: true });
+ }
+ }, 90_000);
+}
diff --git a/packages/cli/src/measure/diff.test.ts b/packages/cli/src/measure/diff.test.ts
new file mode 100644
index 0000000000..ab30fb1e74
--- /dev/null
+++ b/packages/cli/src/measure/diff.test.ts
@@ -0,0 +1,346 @@
+import { existsSync } from "node:fs";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+import {
+ cellsOutside,
+ diffVideos,
+ longRuns,
+ pickedFrames,
+ regionRoi,
+ selectFilter,
+ wholeFrameCuts,
+} from "./diff.js";
+import {
+ clipFolder,
+ diffVerdicts,
+ loadOpenCvFirst,
+ noTools,
+ REF_ARGS,
+} from "./diff.test-helpers.js";
+import { carriedFrame, shotFraming, syncPass } from "./person.js";
+import { parseSegments } from "./segments.js";
+
+const { dir, clip } = clipFolder("hf-diff-test-");
+
+describe("parseSegments", () => {
+ it("reads headings and where each window's pixels come from", () => {
+ const md = [
+ "# Film — reverse",
+ "## S01 · 0.00–2.40 s · Title card",
+ "Pixels: rebuilt",
+ "## S02 · 2.40–5.00 s · Talking head",
+ "Pixels: reused",
+ "## S03 · 5.00–6.5 s · Product shot",
+ "Pixels: regenerated",
+ "## S04 · 6.5–8 s",
+ "## Unknowns",
+ ].join("\n");
+ expect(parseSegments(md)).toEqual([
+ { id: "S01", start: 0, end: 2.4, title: "Title card", pixels: "rebuilt" },
+ { id: "S02", start: 2.4, end: 5, title: "Talking head", pixels: "reused" },
+ { id: "S03", start: 5, end: 6.5, title: "Product shot", pixels: "regenerated" },
+ { id: "S04", start: 6.5, end: 8, title: "", pixels: "rebuilt" },
+ ]);
+ });
+
+ it("reads a regenerated region inside a rebuilt segment, in pixels or shares", () => {
+ const md = [
+ "## S01 · 0–2 s · Board under the presenter",
+ "Pixels: rebuilt",
+ "Regenerated: 0, 95, 720, 600 (the re-shot presenter)",
+ "## S02 · 2–4 s",
+ "Regenerated: 0 0.5 1 0.5",
+ "## S03 · 4–6 s",
+ "Pixels: regenerated",
+ "Regenerated: 0, 0, 10, 10",
+ ].join("\n");
+ const [a, b, c] = parseSegments(md);
+ expect(a!.regenerated).toEqual([0, 95, 720, 600]);
+ expect(b!.regenerated).toEqual([0, 0.5, 1, 0.5]);
+ expect(c!.regenerated).toBeUndefined();
+ });
+
+ it("reads drawn elements over a regenerated person, and whether a segment quotes copy", () => {
+ const md = [
+ "## S01 · 0–2 s · Title over the presenter",
+ "Pixels: rebuilt",
+ "Regenerated: 0, 0, 608, 1080",
+ 'Copy: "IS NO" / "LONGER"',
+ "Drawn: 110, 615, 390, 165 (the title)",
+ "Drawn: 40 40 120 120, logo 0.5–1.5 s",
+ "## S02 · 2–4 s",
+ "Copy: none, footage only",
+ ].join("\n");
+ const [a, b] = parseSegments(md);
+ expect(a!.drawn).toEqual([
+ { box: [110, 615, 390, 165] },
+ { box: [40, 40, 120, 120], window: [0.5, 1.5] },
+ ]);
+ expect(a!.copy).toBe(true);
+ expect(b!.drawn).toBeUndefined();
+ expect(b!.copy).toBeUndefined();
+ });
+});
+
+describe("whole-frame cuts", () => {
+ it("keeps the ledger's cuts and stills from the original that cover the whole frame", () => {
+ const ledger = [
+ {
+ type: "video",
+ provenance: { provider: "original", window: [0, 12.267], roi: [0, 0, 720, 1280] },
+ },
+ { type: "video", provenance: { provider: "original", window: [1, 2] } },
+ {
+ type: "video",
+ provenance: { provider: "original", window: [3, 4], roi: [0, 0, 720, 704] },
+ },
+ { type: "image", provenance: { provider: "original", at: 3, roi: [0, 0, 720, 1280] } },
+ { type: "image", provenance: { provider: "original", at: 5, roi: [60, 260, 480, 560] } },
+ { type: "video", provenance: { provider: "heygen", window: [0, 5] } },
+ ]
+ .map((e) => JSON.stringify(e))
+ .join("\n");
+ expect(wholeFrameCuts(`${ledger}\nnot json`, 720, 1280)).toEqual({
+ windows: [
+ [0, 12.267],
+ [1, 2],
+ ],
+ stills: [3],
+ });
+ });
+
+ it("drops runs of frames shorter than the minimum", () => {
+ const on = [true, true, false, true, true, true, true, true];
+ expect(longRuns(on, [0, 1, 2, 3, 4, 5, 9, 10], 3)).toEqual([
+ false,
+ false,
+ false,
+ true,
+ true,
+ true,
+ false,
+ false,
+ ]);
+ });
+});
+
+describe("regenerated regions", () => {
+ it("scales shares to pixels, clips to the frame and leaves the covered cells to the region", () => {
+ expect(regionRoi([0, 0.5, 1, 0.5], 320, 180)).toEqual([0, 90, 320, 90]);
+ expect(regionRoi([600, 1200, 400, 200], 720, 1280)).toEqual([600, 1200, 120, 80]);
+ // 80x44 cells: the bottom half covers rows 2 and 3 (row 2 from y 88, all but 2 px of it).
+ expect(cellsOutside([0, 90, 320, 90], 320, 180)).toEqual([0, 1, 2, 3, 4, 5, 6, 7]);
+ });
+});
+
+describe("person gates", () => {
+ const at = (t: number, ...boxes: number[][]) => ({ t, boxes });
+ const face = [0.4, 0.3, 0.2, 0.12];
+ const original = [0, 0.4, 0.8, 1.2].map((t) => at(t, face));
+
+ it("fails a shot's framing only when the face sits clearly off the original's", () => {
+ const moved = (dy: number, grow = 1) =>
+ [0, 0.4, 0.8, 1.2].map((t) => at(t, [0.4, 0.3 + dy, 0.2 * grow, 0.12 * grow]));
+ expect(shotFraming([0, 1.5], original, moved(0.01))).toMatchObject({ pass: true });
+ // Half a face height lower, or 40% bigger.
+ expect(shotFraming([0, 1.5], original, moved(0.06))).toMatchObject({ pass: false });
+ expect(shotFraming([0, 1.5], original, moved(0, 1.4))).toMatchObject({ pass: false });
+ // One stray moment off (a hand over the face, a photo) is not a framing.
+ const stray = original.map((m, i) => (i === 1 ? at(m.t, [0.4, 0.6, 0.2, 0.12]) : m));
+ expect(shotFraming([0, 1.5], original, stray)).toMatchObject({ pass: true });
+ // Another face in yours (a picture on the wall) does not stand in for the person.
+ const crowd = [0, 0.4, 0.8, 1.2].map((t) => at(t, [0.05, 0.05, 0.3, 0.2], face));
+ expect(shotFraming([0, 1.5], original, crowd)).toMatchObject({
+ shift: 0,
+ pass: true,
+ });
+ // Too few faces to judge.
+ expect(shotFraming([0, 0.5], original, original)).toBeUndefined();
+ });
+
+ it("judges lips only on a confident reading, inside +45 / −125 ms", () => {
+ expect(syncPass({ best_lag_ms: 30, confidence: "high" })).toBe(true);
+ expect(syncPass({ best_lag_ms: -120, confidence: "high" })).toBe(true);
+ expect(syncPass({ best_lag_ms: 80, confidence: "high" })).toBe(false);
+ expect(syncPass({ best_lag_ms: -200, confidence: "high" })).toBe(false);
+ expect(syncPass({ best_lag_ms: -300, confidence: "medium" })).toBeNull();
+ });
+
+ it("finds the original's letters in a generated clip, not the place they share", () => {
+ // A textured place (the same in the original, the clean still and the clip) and white letters over it.
+ const [w, h] = [60, 30];
+ const place = new Uint8Array(w * h * 3).map((_, i) => 60 + ((i * 37) % 50));
+ const lettered = (px: Uint8Array) => {
+ const out = new Uint8Array(px);
+ for (let y = 8; y < 22; y++)
+ for (const x0 of [10, 25, 40])
+ for (let x = x0; x < x0 + 4; x++) out.set([255, 255, 255], (y * w + x) * 3);
+ return out;
+ };
+ const original = lettered(place);
+ expect(carriedFrame(original, lettered(place), place, w, h, undefined)).toBeGreaterThan(0.9);
+ expect(carriedFrame(original, place, place, w, h, undefined)).toBeLessThan(0.1);
+ });
+});
+
+describe("frame picks", () => {
+ it("keeps a range's frames end-exclusive and renumbers them on the original's clock", () => {
+ expect(pickedFrames({ kind: "range", k0: 3, k1: 6 }, 90)).toEqual([3, 4, 5]);
+ expect(selectFilter({ kind: "range", k0: 3, k1: 6 }, "30000/1001")).toEqual([
+ "select=between(n\\,3\\,5)",
+ "setpts=N/(30000/1001)/TB",
+ ]);
+ expect(selectFilter({ kind: "at", ks: [2, 9] }, "30")[0]).toBe("select=eq(n\\,2)+eq(n\\,9)");
+ expect(selectFilter({ kind: "all" }, "30")).toEqual([]);
+ });
+});
+
+describe.skipIf(noTools)("diffVideos", () => {
+ loadOpenCvFirst();
+ const ref = noTools ? "" : clip("ref.mp4", REF_ARGS);
+
+ it("passes a video against itself", async () => {
+ const r = await diffVideos({ reference: ref, yours: ref, outDir: join(dir, "same") });
+ expect(r.pass).toBe(true);
+ expect(r.ssim.frames).toBe(90);
+ expect(r.ssim.mean).toBeGreaterThan(0.999);
+ expect(r.worst).toEqual([]);
+ });
+
+ it("finds a wrong element by its cell when the whole frame still scores high", async () => {
+ // An 80x60 box over a 320x180 frame for one second: about 0.94 whole-frame SSIM.
+ const yours = clip("box.mp4", [
+ ...["-i", ref, "-vf"],
+ "drawbox=x=40:y=40:w=80:h=60:color=red:t=fill:enable='between(t,1,2)'",
+ ]);
+ const r = await diffVideos({ reference: ref, yours, outDir: join(dir, "box") });
+ expect(r.ssim.mean).toBeGreaterThan(0.92);
+ expect(r.ssim.cell_p05).toBeLessThan(0.8);
+ expect(r.pass).toBe(false);
+ const [first] = r.worst;
+ expect(first!.t).toBeGreaterThanOrEqual(1);
+ expect(first!.t).toBeLessThanOrEqual(2);
+ const [x, y, w, h] = first!.cell.roi;
+ expect(x < 120 && x + w > 40 && y < 100 && y + h > 40).toBe(true);
+ expect(existsSync(r.sheet!)).toBe(true);
+ });
+
+ it("draws the worst cell of a tall frame scaled for the sheet", async () => {
+ // 1080x1920 scales to 960x1706 for the sheet; the bottom row's box rounds a pixel past the edge.
+ const tall = clip("tall.mp4", ["-f", "lavfi", "-i", "testsrc2=d=1:r=30:s=1080x1920"]);
+ const yours = clip("tall-box.mp4", [
+ ...["-i", tall, "-vf"],
+ "drawbox=x=0:y=1500:w=1080:h=420:color=red:t=fill",
+ ]);
+ const r = await diffVideos({ reference: tall, yours, outDir: join(dir, "tall") });
+ expect(r.worst.length).toBeGreaterThan(0);
+ expect(r.worst[0]!.cell.roi[1]).toBe(1440);
+ });
+
+ it("fails a scene left empty on a plain background", async () => {
+ // A small dark label on white, gone from yours after 1.5 s: still about 0.97 whole-frame SSIM.
+ const label = "drawbox=x=40:y=20:w=36:h=12:color=0x303030:t=fill";
+ const page = clip("page.mp4", [
+ "-f",
+ "lavfi",
+ "-i",
+ "color=c=white:s=320x180:r=30:d=3",
+ "-vf",
+ label,
+ ]);
+ const yours = clip("emptied.mp4", [
+ ...["-f", "lavfi", "-i", "color=c=white:s=320x180:r=30:d=3", "-vf"],
+ `${label}:enable='lt(t,1.5)'`,
+ ]);
+ const r = await diffVerdicts({ reference: page, yours, outDir: join(dir, "emptied") });
+ expect(r.missing_content.pass).toBe(false);
+ expect(r.missing_content.share).toBeGreaterThan(0.45);
+ expect(r.missing_content.spans[0]![0]).toBeCloseTo(1.5, 1);
+ expect(r.pass).toBe(false);
+ const same = await diffVerdicts({ reference: page, yours: page, outDir: join(dir, "page") });
+ expect(same.missing_content).toMatchObject({ share: 0, pass: true });
+ // A regenerated segment's picture is its own: what it leaves out is not missing.
+ const regen = await diffVerdicts({
+ reference: page,
+ yours,
+ segments: parseSegments("## S01 · 0–3 s · AI shot\nPixels: regenerated\n"),
+ outDir: join(dir, "emptied-regen"),
+ });
+ expect(regen.missing_content).toMatchObject({ share: 0, pass: true });
+ });
+
+ it("reports missing texture apart from missing shapes, without failing it", async () => {
+ // A fine 4 px checker in the bottom-left cell: flat at an eighth of the width, so texture, not structure.
+ const checker =
+ "if(lt(X\\,80)*gte(Y\\,135)\\,if(mod(floor(X/4)+floor(Y/4)\\,2)\\,60\\,200)\\,235)";
+ const grain = clip("grain.mp4", [
+ ...["-f", "lavfi", "-i", "color=c=white:s=320x180:r=30:d=2", "-vf"],
+ `format=gray,geq=lum='${checker}',format=yuv420p`,
+ ]);
+ const plain = clip("plain.mp4", [
+ ...["-f", "lavfi", "-i", "color=c=white:s=320x180:r=30:d=2", "-vf"],
+ "format=gray,geq=lum=235,format=yuv420p",
+ ]);
+ const r = await diffVerdicts({ reference: grain, yours: plain, outDir: join(dir, "grain") });
+ expect(r.missing_content).toMatchObject({ share: 0, pass: true });
+ expect(r.missing_content.texture.share).toBeGreaterThan(0.9);
+ expect(r.warnings.some((w) => w.includes("reported, not failed"))).toBe(true);
+ });
+
+ it("scores only a range, on the original's frame numbers", async () => {
+ const yours = clip("late.mp4", [
+ ...["-i", ref, "-vf"],
+ "drawbox=x=0:y=0:w=320:h=180:color=black:t=fill:enable='gte(t,2)'",
+ ]);
+ const r = await diffVerdicts({
+ reference: ref,
+ yours,
+ range: [0.5, 1.5],
+ outDir: join(dir, "range"),
+ });
+ expect(r.ssim.frames).toBe(30);
+ expect(r.window).toEqual([0.5, 1.5]);
+ expect(r.pass).toBe(true);
+ });
+
+ it("reports a cut a few frames late as missing and extra", async () => {
+ const two = (name: string, at: number) =>
+ clip(name, [
+ ...["-f", "lavfi", "-i", `color=c=0x2050c0:s=320x180:r=30:d=${at}`],
+ ...["-f", "lavfi", "-i", `color=c=0xe0c040:s=320x180:r=30:d=${3 - at}`],
+ ...["-filter_complex", "[0][1]concat=n=2:v=1[v]", "-map", "[v]"],
+ ]);
+ const r = await diffVerdicts({
+ reference: two("cut-ref.mp4", 1),
+ yours: two("cut-late.mp4", 1.1),
+ outDir: join(dir, "cuts"),
+ });
+ expect(r.cuts?.reference).toEqual([1]);
+ expect(r.cuts?.missing).toEqual([1]);
+ expect(r.cuts?.extra).toEqual([1.1]);
+ expect(r.pass).toBe(false);
+ });
+
+ it("matches a soft cut in the original with a hard one in yours", async () => {
+ // Grey 0x80 to 0x8b changes the signature by 10 levels: a soft cut. Yours jumps further on the same frame.
+ const step = (name: string, to: string, at: number) =>
+ clip(name, [
+ ...["-f", "lavfi", "-i", `color=c=0x808080:s=320x180:r=30:d=${at}`],
+ ...["-f", "lavfi", "-i", `color=c=${to}:s=320x180:r=30:d=${3 - at}`],
+ ...["-filter_complex", "[0][1]concat=n=2:v=1[v]", "-map", "[v]"],
+ ]);
+ const soft = step("soft-ref.mp4", "0x8b8b8b", 1);
+ const r = await diffVerdicts({
+ reference: soft,
+ yours: step("soft-hard.mp4", "0xa0a0a0", 1),
+ outDir: join(dir, "soft"),
+ });
+ expect(r.cuts).toMatchObject({ reference: [1], missing: [], extra: [], pass: true });
+ const late = await diffVerdicts({
+ reference: soft,
+ yours: step("soft-late.mp4", "0xa0a0a0", 1.2),
+ outDir: join(dir, "soft-late"),
+ });
+ expect(late.cuts).toMatchObject({ missing: [1], extra: [1.2], pass: false });
+ });
+});
diff --git a/packages/cli/src/measure/diff.ts b/packages/cli/src/measure/diff.ts
new file mode 100644
index 0000000000..8c7964d65a
--- /dev/null
+++ b/packages/cli/src/measure/diff.ts
@@ -0,0 +1,1381 @@
+// A rebuild against its original, frame by frame: per-frame SSIM on the original's clock for the whole frame and
+// each cell of a 4x4 grid, the worst moments with their worst cell boxed, cuts on both sides, and per-segment
+// verdicts. The second side is a video file (a render) or a project folder, whose frames are captured at the
+// original's frame times without rendering.
+import {
+ copyFileSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+ rmSync,
+ statSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { basename, dirname, join, resolve } from "node:path";
+import { confirmsCut, cutsIn, frameChanges, signatures } from "./cuts.js";
+import {
+ drawnFrames,
+ drawnVerdict,
+ readDrawn,
+ scoreDrawnFrame,
+ type DrawnVerdict,
+} from "./drawn.js";
+import { compareEnergy, energyCurve, type EnergyComparison } from "./energy.js";
+import { compareLook, look, sameLook, type LookComparison } from "./look.js";
+import {
+ decode,
+ Fix,
+ frameAt,
+ pearson,
+ probeVideo,
+ round,
+ runFfmpeg,
+ videoClip,
+ writeImage,
+ type Clip,
+ type Roi,
+ type VideoInfo,
+} from "./media.js";
+import {
+ AT_CUT_S,
+ clipUses,
+ generatedClips,
+ personVerdict,
+ placeClips,
+ type GeneratedClip,
+ type PersonVerdict,
+} from "./person.js";
+import type { Segment } from "./segments.js";
+
+// To be calibrated on the reverse bench; light-reverse's rebuilt moments scored 0.885–0.958 mean SSIM.
+export const DEFAULT_MIN_MEAN = 0.92;
+export const DEFAULT_MIN_P05 = 0.85;
+/**
+ * The worst cell of most frames: a missing or misplaced element drags one cell, not the frame. Provisional: four
+ * no-API rebuilds scored 0.67–0.98 and synthetic wrong elements 0.71–0.76.
+ */
+export const DEFAULT_MIN_CELL = 0.75;
+// A regenerated shot moves about as much as the original's.
+const ENERGY_RATIO: [number, number] = [0.8, 1.25];
+const GRID = 4;
+const ALL_CELLS = Array.from({ length: GRID * GRID }, (_, c) => c);
+const WORST_GAP_S = 0.5;
+const SHEET_W = 960;
+const CUT_SLACK = 1;
+// A segment's cell is left to its regenerated region when the region covers more than this share of it.
+const REGION_CELL_SHARE = 0.1;
+// Missing content: cells read at this width, from at most this many frames.
+const MISSING_W = 192;
+const MISSING_SAMPLES = 1800;
+// A cell is empty when the original's luma spread reaches MISSING_DETAIL and yours is flat (under MISSING_FLAT and
+// MISSING_KEEP of the original's); over MISSING_MAX_SHARE of frames with one fails. Weaker blur is SSIM's to grade.
+const MISSING_DETAIL = 8;
+const MISSING_KEEP = 0.35;
+const MISSING_FLAT = 4;
+const MISSING_MAX_SHARE = 0.02;
+// Missing structure: the original's cell still spreads MISSING_DETAIL at 1/STRUCTURE_SCALE of the width (shapes,
+// cards); otherwise it is texture (a credit line, grain), reported, not failed.
+const STRUCTURE_SCALE = 8;
+// Whole-frame reuse: a cut covering this share of the original's frame plays the whole frame (and a Regenerated box
+// this large judges nothing by pixels); a frame whose median cell scores REUSE_SSIM shows it.
+const WHOLE_FRAME_SHARE = 0.9;
+const REUSE_SSIM = 0.9;
+// Drawn things carried along with it for longer than this fail.
+const REUSE_MAX_FRAMES = 2;
+// Shorter matches are not reuse: a generated shot starts from a clean still of the original's first frame.
+const REUSE_MIN_S = 0.5;
+// A whole-frame still shows where yours, grey at STILL_W wide, is within STILL_DIFF of it in most of the 4x4 cells.
+const STILL_W = 96;
+const STILL_DIFF = 4;
+
+/** Which of the original's frames are compared. */
+export type Pick =
+ | { kind: "all" }
+ | { kind: "range"; k0: number; k1: number }
+ | { kind: "at"; ks: number[] };
+
+export interface Thresholds {
+ mean: number;
+ p05: number;
+ cell: number;
+}
+
+export interface DiffOptions {
+ reference: string;
+ /** A video file, or a project folder holding index.html. */
+ yours: string;
+ at?: number[];
+ range?: [number, number];
+ segments?: Segment[];
+ thresholds?: Partial;
+ worst?: number;
+ sbs?: boolean;
+ outDir: string;
+ /** Render-ready timeout for a project folder's capture. */
+ timeoutMs?: number;
+ /** The project's media ledger (`.media/manifest.jsonl`): its cuts from the original show whole-frame reuse. */
+ ledger?: string;
+ /** The project folder, to find the ledger's generated clips (default: yours, or the folder holding `.media`). */
+ project?: string;
+ /** Drawn elements to score by themselves, segments or not: boxes in the original's pixels, optional windows. */
+ drawn?: { box: [number, number, number, number]; window?: [number, number] }[];
+ log?: (message: string) => void;
+}
+
+export interface Scores {
+ frames: number;
+ mean: number;
+ p05: number;
+ min: number;
+ /** The 5th percentile of each frame's worst cell. */
+ cell_p05: number;
+}
+
+export interface Moment {
+ t: number;
+ frame: number;
+ ssim: number;
+ /** The frame's worst cell of a 4x4 grid, in the original's pixels, and both sides of it at full size. */
+ cell: { roi: [number, number, number, number]; ssim: number; picture: string };
+}
+
+export interface SegmentVerdict {
+ id: string;
+ window: [number, number];
+ pixels: Segment["pixels"];
+ pass: boolean | null;
+ ssim?: Scores;
+ /** A regenerated segment with no person in it (a product shot): judged by motion and look. */
+ energy?: EnergyComparison;
+ look?: LookComparison;
+ /** What `pass` covers, in words: which pixels SSIM scored, and what was judged otherwise. */
+ scored?: string;
+ /** A rebuilt or reused segment's regenerated region; `ssim` then scores the cells outside it. */
+ regenerated?: { roi: [number, number, number, number] };
+ /**
+ * The re-shot person: three gates decide (framing, text carried in the generated clip, lip sync); motion energy
+ * and look are reported, not judged.
+ */
+ person?: PersonVerdict & { energy?: EnergyComparison; look?: LookComparison };
+ /** Each `Drawn:` element over the regenerated person, scored by itself (drawn.ts), in the order written. */
+ drawn?: (DrawnVerdict & { id: string })[];
+ /** A segment scored by SSIM: the 4x4 cell with the lowest mean over it, and the moment it is lowest. */
+ worst_cell?: { roi: Roi; ssim: number; t: number };
+ note?: string;
+}
+
+export interface CutReport {
+ reference: number[];
+ yours: number[];
+ /** The original's cuts with no cut within a frame of them in yours. */
+ missing: number[];
+ extra: number[];
+ pass: boolean;
+}
+
+export interface MissingContent {
+ /** Share of compared frames with a cell whose shapes the original has and yours leaves flat. */
+ share: number;
+ /** The longest such stretches, in seconds. */
+ spans: [number, number][];
+ pass: boolean;
+ /** Frames where yours leaves flat only the original's fine texture in a cell: reported, not failed. */
+ texture: { share: number; spans: [number, number][] };
+}
+
+export interface WholeFrameReuse {
+ /** Stretches where yours plays a whole-frame cut of the original, in seconds. */
+ spans: [number, number][];
+ /** The times (in the original) of the ledger's whole-frame stills that show in yours. */
+ stills: number[];
+ share: number;
+ /** Those inside segments that quote copy: the original's drawn things played along, a copy. */
+ drawn: [number, number][];
+ pass: boolean;
+}
+
+export interface DiffResult {
+ pass: boolean;
+ reference: string;
+ yours: string;
+ mode: "video" | "project";
+ window: [number, number];
+ thresholds: Thresholds;
+ ssim: Scores;
+ missing_content: MissingContent;
+ whole_frame_reuse?: WholeFrameReuse;
+ worst: Moment[];
+ cuts?: CutReport;
+ duration?: { reference: number; yours: number; pass: boolean };
+ sound?: ReturnType;
+ segments?: SegmentVerdict[];
+ /** What decides the verdict: every drawn element and each rebuilt segment's area outside the person. */
+ components?: { passed: number; total: number; mean: number | null };
+ /** The re-shot person over the film: the gates that decide, and what is only reported. */
+ person?: PersonSummary;
+ /** Each `drawn` option's element (D1, D2, …), scored by itself: reported, not judged. */
+ drawn?: (DrawnVerdict & { id: string })[];
+ sheet?: string;
+ sbs?: string;
+ log: string;
+ /** Every compared frame's SSIM and worst cell. */
+ frames: string;
+ warnings: string[];
+}
+
+export interface PersonSummary {
+ /** Each gate over every segment: false when one fails, null when none could be measured. */
+ gates: { framing: boolean | null; text: boolean | null; sync: boolean | null };
+ /** Segments failing each gate. */
+ failed: { framing: string[]; text: string[]; sync: string[] };
+ /** Median of the segments' motion energy ratios (yours over the original's): reported, not judged. */
+ energy: number | null;
+ /**
+ * Generated clips that start at one of the original's cuts, of those placed on the film, and the original's cuts
+ * inside the person's segments where no clip starts (a jump cut played as one take): reported.
+ */
+ shots_at_cuts: {
+ at_cuts: number;
+ total: number;
+ off: { clip: string; start: number }[];
+ cuts_without_shot: number[];
+ };
+ clips: GeneratedClip[];
+}
+
+interface Series {
+ /** Whole-frame SSIM per compared frame. */
+ frame: number[];
+ /** Each frame's 16 cell scores, row by row. */
+ cells: number[][];
+}
+
+const pct = (sorted: number[], p: number) =>
+ sorted[Math.min(sorted.length - 1, Math.floor(p * sorted.length))] ?? 0;
+
+function scores(frame: number[], worstCell: number[]): Scores {
+ const sorted = [...frame].sort((a, b) => a - b);
+ const n = sorted.length;
+ return {
+ frames: n,
+ mean: round(n ? sorted.reduce((s, v) => s + v, 0) / n : 0, 4),
+ p05: round(pct(sorted, 0.05), 4),
+ min: round(sorted[0] ?? 0, 4),
+ cell_p05: round(
+ pct(
+ [...worstCell].sort((a, b) => a - b),
+ 0.05,
+ ),
+ 4,
+ ),
+ };
+}
+
+const passes = (s: Scores, t: Thresholds) =>
+ s.frames > 0 && s.mean >= t.mean && s.p05 >= t.p05 && s.cell_p05 >= t.cell;
+
+/** The original's frame indexes a pick compares, in order. */
+export function pickedFrames(pick: Pick, total: number): number[] {
+ if (pick.kind === "at") return pick.ks;
+ const [k0, k1] = pick.kind === "range" ? [pick.k0, pick.k1] : [0, total];
+ return Array.from({ length: Math.max(0, k1 - k0) }, (_, i) => k0 + i);
+}
+
+/** The filters that keep a pick's frames of a stream, renumbered from 0 on the original's clock. */
+export function selectFilter(pick: Pick, fpsText: string): string[] {
+ const pts = `setpts=N/(${fpsText})/TB`;
+ if (pick.kind === "all") return [];
+ if (pick.kind === "range") return [`select=between(n\\,${pick.k0}\\,${pick.k1 - 1})`, pts];
+ return [`select=${pick.ks.map((k) => `eq(n\\,${k})`).join("+")}`, pts];
+}
+
+/** Even cell sizes keep 4:2:0 chroma aligned; the last row and column drop at most a pixel or two. */
+const cellSize = (w: number, h: number): [number, number] => [
+ Math.floor(w / (2 * GRID)) * 2,
+ Math.floor(h / (2 * GRID)) * 2,
+];
+
+/**
+ * Per-frame SSIM (ffmpeg's All: luma and chroma) of yours against the original, in the pick's order, for the
+ * whole frame and each cell: a wrong box over an eighth of the frame still scores 0.94 whole-frame.
+ */
+function ssimSeries(ref: Clip, yours: Clip, logPath: string): Series {
+ const side = (filters: string[]) => [...filters, "setsar=1", "format=yuv420p"].join(",");
+ const n = GRID * GRID + 1;
+ const tags = (p: string) => Array.from({ length: n }, (_, i) => `[${p}${i}]`).join("");
+ const [cw, ch] = cellSize(ref.width, ref.height);
+ const graph = [
+ `[0:v]${side(ref.filters)},split=${n}${tags("r")}`,
+ `[1:v]${side([...yours.filters, `scale=${ref.width}:${ref.height}:flags=bicubic`])},split=${n}${tags("o")}`,
+ "[o0][r0]ssim=stats_file=-:shortest=1[s0]",
+ ...Array.from({ length: GRID * GRID }, (_, i) => {
+ const crop = `crop=${cw}:${ch}:${(i % GRID) * cw}:${Math.floor(i / GRID) * ch}`;
+ const k = i + 1;
+ return `[r${k}]${crop}[rc${k}];[o${k}]${crop}[oc${k}];[oc${k}][rc${k}]ssim=stats_file=cell${i}.log:shortest=1[s${k}]`;
+ }),
+ ].join(";");
+ // Cell logs are written beside ffmpeg's working folder, so their names need no filtergraph escaping.
+ const work = mkdtempSync(join(tmpdir(), "hf-diff-cells-"));
+ const all = (text: string) => [...text.matchAll(/All:([\d.]+)/g)].map((m) => Number(m[1]));
+ try {
+ const maps = Array.from({ length: n }, (_, i) => ["-map", `[s${i}]`]).flat();
+ const text = runFfmpeg(
+ [...ref.input, ...yours.input, "-filter_complex", graph, ...maps, "-f", "null", "-"],
+ undefined,
+ work,
+ ).toString();
+ writeFileSync(logPath, text);
+ const frame = all(text);
+ const perCell = Array.from({ length: GRID * GRID }, (_, i) =>
+ all(readFileSync(join(work, `cell${i}.log`), "utf8")),
+ );
+ return { frame, cells: frame.map((_, f) => perCell.map((cell) => cell[f] ?? 1)) };
+ } finally {
+ rmSync(work, { recursive: true, force: true });
+ }
+}
+
+/** Stretches where a cell the original fills is flat in yours, by each cell's luma spread (SSIM scores near-blank
+ * patches alike). `judged(k)` lists the cells of the original's frame k it applies to; a person's gesture is theirs. */
+function missingContent(
+ ref: Clip,
+ yours: Clip,
+ ks: number[],
+ fps: number,
+ judged: (k: number) => number[] = () => ALL_CELLS,
+): MissingContent {
+ const stride = Math.max(1, Math.ceil(ks.length / MISSING_SAMPLES));
+ const w = MISSING_W;
+ const h = Math.max(GRID * 2, Math.round((w * ref.height) / ref.width / GRID) * GRID);
+ const [cw, ch] = [
+ w / STRUCTURE_SCALE,
+ Math.max(GRID, Math.round(h / STRUCTURE_SCALE / GRID) * GRID),
+ ];
+ const thin =
+ stride > 1 ? [`select=not(mod(n\\,${stride}))`, `setpts=N/(${fps / stride})/TB`] : [];
+ const spreads = (clip: Clip, sw: number, sh: number) =>
+ decode(clip.input, [...clip.filters, ...thin, `scale=${sw}:${sh}`], sw, sh, true).frames.map(
+ (px) => cellSpreads(px, sw, sh),
+ );
+ const [a, b, coarse] = [spreads(ref, w, h), spreads(yours, w, h), spreads(ref, cw, ch)];
+ // The thinning select can pass one frame past the pick; times come from ks, so stop with it.
+ const n = Math.min(a.length, b.length, coarse.length, Math.ceil(ks.length / stride));
+ const kinds = Array.from({ length: n }, (_, j) => {
+ const empty = judged(ks[j * stride]!).filter((c) => {
+ const s = a[j]![c]!;
+ return s >= MISSING_DETAIL && b[j]![c]! < Math.min(MISSING_FLAT, MISSING_KEEP * s);
+ });
+ return {
+ structure: empty.some((c) => coarse[j]![c]! >= MISSING_DETAIL),
+ texture: empty.length > 0,
+ };
+ });
+ const spansOf = (on: boolean[]) => {
+ const spans: [number, number][] = [];
+ on.forEach((e, j) => {
+ if (!e) return;
+ const t = round(ks[j * stride]! / fps, 3);
+ const end = round((ks[Math.min(ks.length - 1, (j + 1) * stride - 1)]! + 1) / fps, 3);
+ const last = spans.at(-1);
+ if (last && on[j - 1]) last[1] = end;
+ else spans.push([t, end]);
+ });
+ return spans
+ .sort((x, y) => y[1] - y[0] - (x[1] - x[0]))
+ .slice(0, 8)
+ .sort((x, y) => x[0] - y[0]);
+ };
+ const structure = kinds.map((k) => k.structure);
+ const texture = kinds.map((k) => k.texture && !k.structure);
+ const share = n ? structure.filter(Boolean).length / n : 0;
+ return {
+ share: round(share, 4),
+ spans: spansOf(structure),
+ pass: share <= MISSING_MAX_SHARE,
+ texture: {
+ share: round(n ? texture.filter(Boolean).length / n : 0, 4),
+ spans: spansOf(texture),
+ },
+ };
+}
+
+/** Each grid cell's luma standard deviation, row by row. */
+function cellSpreads(px: Uint8Array, w: number, h: number): number[] {
+ const [cw, ch] = [Math.floor(w / GRID), Math.floor(h / GRID)];
+ return Array.from({ length: GRID * GRID }, (_, c) => {
+ const [x0, y0] = [(c % GRID) * cw, Math.floor(c / GRID) * ch];
+ let [s, ss] = [0, 0];
+ for (let y = y0; y < y0 + ch; y++)
+ for (let x = x0; x < x0 + cw; x++) {
+ const v = px[y * w + x]!;
+ s += v;
+ ss += v * v;
+ }
+ const m = s / (cw * ch);
+ return Math.sqrt(Math.max(0, ss / (cw * ch) - m * m));
+ });
+}
+
+/** The `count` frames with the lowest worst cell, at least WORST_GAP_S apart; near-perfect frames are skipped. */
+function worstIndexes(worstCell: number[], ks: number[], fps: number, count: number): number[] {
+ const order = worstCell
+ .map((_, i) => i)
+ .filter((i) => worstCell[i]! < 0.98)
+ .sort((a, b) => worstCell[a]! - worstCell[b]!);
+ const out: number[] = [];
+ for (const i of order) {
+ if (out.length >= count) break;
+ if (out.every((j) => Math.abs(ks[i]! - ks[j]!) / fps >= WORST_GAP_S)) out.push(i);
+ }
+ return out.sort((a, b) => ks[a]! - ks[b]!);
+}
+
+/** One frame of a clip (its i-th after the clip's own filters) at `w`x`h` RGB. */
+function frameOf(clip: Clip, i: number, w: number, h: number): Uint8Array {
+ const { frames } = decode(
+ clip.input,
+ [...clip.filters, `select=eq(n\\,${i})`, `scale=${w}:${h}`],
+ w,
+ h,
+ false,
+ 1,
+ );
+ if (!frames[0]) throw new Fix(`could not read frame ${i}`, "check both videos play to their end");
+ return frames[0];
+}
+
+/** A red rectangle drawn into RGB bytes, clipped to the picture (a scaled box can round a pixel past its edge). */
+function outline(px: Uint8Array, w: number, [x, y, bw, bh]: number[], t = 3) {
+ const h = px.length / 3 / w;
+ for (let yy = y!; yy < Math.min(h, y! + bh!); yy++)
+ for (let xx = x!; xx < Math.min(w, x! + bw!); xx++) {
+ const edge = yy - y! < t || y! + bh! - 1 - yy < t || xx - x! < t || x! + bw! - 1 - xx < t;
+ if (edge) px.set([255, 40, 40], (yy * w + xx) * 3);
+ }
+}
+
+function cutReport(ref: Clip, yours: Clip, k0: number, fps: number): CutReport {
+ const [da, db] = [ref, yours].map((c) => frameChanges(signatures(c.input, c.filters).frames));
+ const [a, b] = [cutsIn(da!), cutsIn(db!)];
+ const used = new Set();
+ const missing: number[] = [];
+ for (const cut of a) {
+ const hit = b.find((g) => !used.has(g.frame) && Math.abs(g.frame - cut.frame) <= CUT_SLACK);
+ // A soft cut is near the line: a clear change on the other side matches it.
+ if (hit) used.add(hit.frame);
+ else if (!(cut.soft && confirmsCut(db!, cut))) missing.push(cut.frame);
+ }
+ const extra = b.filter((g) => !used.has(g.frame) && !(g.soft && confirmsCut(da!, g)));
+ const t = (f: number) => round((k0 + f) / fps, 3);
+ return {
+ reference: a.map((c) => t(c.frame)),
+ yours: b.map((c) => t(c.frame)),
+ missing: missing.map(t),
+ extra: extra.map((c) => t(c.frame)),
+ pass: missing.length === 0 && extra.length === 0,
+ };
+}
+
+/** Captures a project's frames at the original's frame times as a numbered picture sequence. */
+async function captureProject(
+ projectDir: string,
+ times: number[],
+ opts: DiffOptions,
+ ref: VideoInfo,
+): Promise<{ clip: Clip; dir: string }> {
+ const { captureSnapshots } = await import("../commands/snapshot.js");
+ const shots = mkdtempSync(join(tmpdir(), "hf-diff-shots-"));
+ const seq = mkdtempSync(join(tmpdir(), "hf-diff-seq-"));
+ try {
+ const captured = await captureSnapshots(projectDir, {
+ at: times,
+ includeEnd: false,
+ outputDir: shots,
+ timeout: opts.timeoutMs,
+ log: opts.log ?? (() => {}),
+ record: false,
+ });
+ if (captured.paths.length !== times.length)
+ throw new Fix(
+ `captured ${captured.paths.length} of ${times.length} frames from ${projectDir}`,
+ "run npx hyperframes check on the project, then diff again",
+ );
+ captured.paths.forEach((p, i) =>
+ copyFileSync(resolve(projectDir, p), join(seq, `${String(i).padStart(6, "0")}.png`)),
+ );
+ } catch (err) {
+ rmSync(seq, { recursive: true, force: true });
+ throw err;
+ } finally {
+ rmSync(shots, { recursive: true, force: true });
+ }
+ return {
+ dir: seq,
+ clip: {
+ input: ["-framerate", ref.fpsText, "-i", join(seq, "%06d.png")],
+ filters: [],
+ width: ref.width,
+ height: ref.height,
+ fps: ref.fps,
+ },
+ };
+}
+
+function regeneratedVerdict(
+ s: Segment,
+ reference: string,
+ yours: string,
+ ref: VideoInfo,
+ roi?: Roi,
+) {
+ const seconds = s.end - s.start;
+ const [a, b] = [videoClip(reference, s.start, seconds, ref), videoClip(yours, s.start, seconds)];
+ // Yours may be another size: the region is the same share of its frame.
+ const mine = roi && scaleRoi(roi, b.width / ref.width, b.height / ref.height);
+ const energy = compareEnergy(energyCurve(a, roi), energyCurve(b, mine));
+ const looks = compareLook(look(a, 2, roi), look(b, 2, mine));
+ const moves = energy.mean_ratio >= ENERGY_RATIO[0] && energy.mean_ratio <= ENERGY_RATIO[1];
+ return { pass: moves && sameLook(looks), energy, look: looks };
+}
+
+const scaleRoi = ([x, y, w, h]: Roi, sx: number, sy: number): Roi => {
+ const [x0, y0] = [Math.round((x * sx) / 2) * 2, Math.round((y * sy) / 2) * 2];
+ return [
+ x0,
+ y0,
+ Math.max(2, Math.round((w * sx) / 2) * 2),
+ Math.max(2, Math.round((h * sy) / 2) * 2),
+ ];
+};
+
+/** A segment's regenerated region in the original's pixels, clipped to the frame; shares when every value is ≤ 1. */
+export function regionRoi(
+ box: [number, number, number, number],
+ width: number,
+ height: number,
+): Roi {
+ const [sx, sy] = box.every((v) => v <= 1) ? [width, height] : [1, 1];
+ const roi = scaleRoi(box, sx, sy);
+ const [x, y] = [Math.min(roi[0], width - 2), Math.min(roi[1], height - 2)];
+ return [x, y, Math.min(roi[2], width - x), Math.min(roi[3], height - y)];
+}
+
+/** The grid cells (row by row) a region covers no more than REGION_CELL_SHARE of. */
+export function cellsOutside(roi: Roi, width: number, height: number): number[] {
+ const [cw, ch] = cellSize(width, height);
+ return ALL_CELLS.filter((c) => {
+ const [x, y] = [(c % GRID) * cw, Math.floor(c / GRID) * ch];
+ const ox = Math.max(0, Math.min(x + cw, roi[0] + roi[2]) - Math.max(x, roi[0]));
+ const oy = Math.max(0, Math.min(y + ch, roi[1] + roi[3]) - Math.max(y, roi[1]));
+ return ox * oy <= REGION_CELL_SHARE * cw * ch;
+ });
+}
+
+interface VerdictContext {
+ reference: string;
+ yours: string;
+ ref: VideoInfo;
+ mode: DiffResult["mode"];
+ t: Thresholds;
+ /** A segment's drawn elements, scored by themselves. */
+ drawn: Map;
+ /** A segment's re-shot person, by the three gates. */
+ person: Map;
+}
+
+function segmentVerdicts(
+ segments: Segment[],
+ series: Series,
+ worstCell: number[],
+ ks: number[],
+ ctx: VerdictContext,
+): SegmentVerdict[] {
+ return segments.map((s) => {
+ const head = { id: s.id, window: [s.start, s.end] as [number, number], pixels: s.pixels };
+ if (s.pixels === "regenerated" && !s.drawn) {
+ if (ctx.mode !== "video")
+ return {
+ ...head,
+ pass: null,
+ note: "regenerated pixels are judged on a render: diff a render",
+ };
+ const moved = regeneratedVerdict(s, ctx.reference, ctx.yours, ctx.ref);
+ const person = ctx.person.get(s);
+ // No face to judge (a product shot): motion and look decide.
+ if (!person || person.pass === null) return { ...head, ...moved };
+ return {
+ ...head,
+ pass: person.pass,
+ scored: "the person: framing, text carried in the generated clip, lip sync",
+ person: { ...person, energy: moved.energy, look: moved.look },
+ };
+ }
+ const [a, b] = [frameAt(s.start, ctx.ref.fps), frameAt(s.end, ctx.ref.fps)];
+ const mine = ks.flatMap((k, i) => (k >= a && k < b && i < series.frame.length ? [i] : []));
+ if (!mine.length)
+ return { ...head, pass: null, note: "no compared frame falls in this segment" };
+ if (s.regenerated || s.pixels === "regenerated")
+ return mixedVerdict(s, head, mine, series, ctx);
+ const st = scores(
+ mine.map((i) => series.frame[i]!),
+ mine.map((i) => worstCell[i]!),
+ );
+ return {
+ ...head,
+ pass: passes(st, ctx.t),
+ ssim: st,
+ worst_cell: lowestCell(mine, series, ks, ctx.ref),
+ };
+ });
+}
+
+/** Of these frames, the cell with the lowest mean SSIM, and the time it is lowest. */
+function lowestCell(
+ mine: number[],
+ series: Series,
+ ks: number[],
+ ref: { width: number; height: number; fps: number },
+): { roi: Roi; ssim: number; t: number } {
+ const means = series.cells[mine[0]!]!.map(
+ (_, c) => mine.reduce((sum, i) => sum + series.cells[i]![c]!, 0) / mine.length,
+ );
+ const c = means.indexOf(Math.min(...means));
+ const at = mine.reduce((lo, i) => (series.cells[i]![c]! < series.cells[lo]![c]! ? i : lo));
+ const [cw, ch] = cellSize(ref.width, ref.height);
+ return {
+ roi: [(c % GRID) * cw, Math.floor(c / GRID) * ch, cw, ch],
+ ssim: round(means[c]!, 4),
+ t: round(ks[at]! / ref.fps, 3),
+ };
+}
+
+/** A segment with a regenerated person (its box, or the whole frame): the person by motion and look, the cells
+ * outside the box by SSIM, and each drawn element over the person by itself. */
+// fallow-ignore-next-line complexity
+function mixedVerdict(
+ s: Segment,
+ head: { id: string; window: [number, number]; pixels: Segment["pixels"] },
+ mine: number[],
+ series: Series,
+ ctx: VerdictContext,
+): SegmentVerdict {
+ const whole = s.pixels === "regenerated";
+ const roi: Roi = whole
+ ? [0, 0, ctx.ref.width, ctx.ref.height]
+ : regionRoi(s.regenerated!, ctx.ref.width, ctx.ref.height);
+ const rest = whole ? [] : cellsOutside(roi, ctx.ref.width, ctx.ref.height);
+ const moved =
+ ctx.mode === "video"
+ ? regeneratedVerdict(s, ctx.reference, ctx.yours, ctx.ref, whole ? undefined : roi)
+ : undefined;
+ const gates = ctx.person.get(s);
+ const person =
+ gates || moved
+ ? {
+ ...(gates ?? { gates: { framing: null, text: null, sync: null }, pass: null }),
+ energy: moved?.energy,
+ look: moved?.look,
+ }
+ : undefined;
+ const st = rest.length
+ ? scores(
+ mine.map((i) => rest.reduce((sum, c) => sum + series.cells[i]![c]!, 0) / rest.length),
+ mine.map((i) => Math.min(...rest.map((c) => series.cells[i]![c]!))),
+ )
+ : undefined;
+ const drawn = ctx.drawn.get(s) ?? [];
+ const verdicts = [
+ st ? passes(st, ctx.t) : null,
+ person?.pass ?? null,
+ ...drawn.map((d) => d.pass),
+ ];
+ const pass = verdicts.includes(false) ? false : verdicts.every((p) => p === null) ? null : true;
+ const scored = [
+ st
+ ? `SSIM: the ${rest.length} cells outside the regenerated box`
+ : drawn.length
+ ? "drawn elements only (no cell is outside the regenerated box)"
+ : "no pixels (the regenerated box covers every cell)",
+ "the person: framing, text carried in the generated clip, lip sync (motion and look reported)",
+ ...(drawn.length ? [`${drawn.length} drawn elements, each scored by itself`] : []),
+ ].join("; ");
+ const note =
+ ctx.mode === "project"
+ ? { note: `the regenerated ${whole ? "picture" : "region"} is judged on a render` }
+ : {};
+ const parts = {
+ pass,
+ scored,
+ ...(st ? { ssim: st } : {}),
+ ...(drawn.length ? { drawn } : {}),
+ ...(person ? { person } : {}),
+ };
+ return { ...head, ...parts, ...(whole ? {} : { regenerated: { roi } }), ...note };
+}
+
+/**
+ * The drawn elements over a regenerated person, each scored by itself on its window inside its segment (drawn.ts),
+ * from one decode of each side.
+ */
+function scoreDrawn(
+ segments: Segment[],
+ refClip: Clip,
+ yours: Clip,
+ ks: number[],
+ ref: VideoInfo,
+ available: number,
+): Map {
+ const jobs = segments.flatMap((s) => drawnOf(s, ref).map((d) => ({ s, ...d })));
+ const verdicts = scoreElements(jobs, refClip, yours, ks, ref, available);
+ const out = new Map();
+ jobs.forEach((j, n) => out.set(j.s, [...(out.get(j.s) ?? []), verdicts[n]!]));
+ return out;
+}
+
+/** Drawn elements scored by themselves on their windows, in order, from one decode of each side. */
+function scoreElements(
+ elements: { id: string; box: Roi; window: [number, number] }[],
+ refClip: Clip,
+ yours: Clip,
+ ks: number[],
+ ref: VideoInfo,
+ available: number,
+): (DrawnVerdict & { id: string })[] {
+ const jobs = elements.map((d) => ({
+ ...d,
+ frames: drawnFrames(ks, ref.fps, ...d.window, available),
+ }));
+ const live = jobs.filter((j) => j.frames.length);
+ const [a, b] = [refClip, yours].map((clip) => readDrawn(clip, live, ref.width, ref.height));
+ return jobs.map((j) => {
+ const n = live.indexOf(j);
+ const pairs =
+ n < 0 ? [] : a![n]!.map((fa, i) => [fa, b![n]![i]] as const).filter(([, fb]) => fb);
+ const frames = pairs.map(([fa, fb]) => scoreDrawnFrame(fa, fb!, j.box[2], j.box[3]));
+ return { id: j.id, ...drawnVerdict(j.box, j.window, frames) };
+ });
+}
+
+/** A segment's drawn elements over a regenerated person: id, box in the original's pixels, window. */
+function drawnOf(s: Segment, ref: VideoInfo): { id: string; box: Roi; window: [number, number] }[] {
+ if (!(s.regenerated || s.pixels === "regenerated")) return [];
+ return (s.drawn ?? []).map((d, n) => ({
+ id: `${s.id}.D${n + 1}`,
+ box: regionRoi(d.box, ref.width, ref.height),
+ window: [Math.max(s.start, d.window?.[0] ?? s.start), Math.min(s.end, d.window?.[1] ?? s.end)],
+ }));
+}
+
+/** The film's headline: the components that decide it, and the person's gates and what is reported. */
+function headline(
+ segments: SegmentVerdict[],
+ clips: GeneratedClip[],
+ t: Thresholds,
+ cuts: number[] = [],
+): { components: NonNullable; person: PersonSummary } {
+ const parts = segments.flatMap((v) => [
+ ...(v.ssim ? [{ pass: passes(v.ssim, t), score: v.ssim.mean }] : []),
+ ...(v.drawn ?? []).flatMap((d) =>
+ d.pass === null ? [] : [{ pass: d.pass, score: d.score ?? 0 }],
+ ),
+ ]);
+ const people = segments.flatMap((v) =>
+ v.person ? [{ id: v.id, window: v.window, ...v.person }] : [],
+ );
+ const gate = (key: "framing" | "text" | "sync") => {
+ const g = people.map((p) => p.gates[key]);
+ return g.includes(false) ? false : g.some((x) => x === true) ? true : null;
+ };
+ const ratios = people.flatMap((p) => (p.energy ? [p.energy.mean_ratio] : []));
+ const placed = clips.filter((c) => c.at_cut !== undefined);
+ return {
+ components: {
+ passed: parts.filter((p) => p.pass).length,
+ total: parts.length,
+ mean: parts.length
+ ? round(parts.reduce((sum, p) => sum + p.score, 0) / parts.length, 4)
+ : null,
+ },
+ person: {
+ gates: { framing: gate("framing"), text: gate("text"), sync: gate("sync") },
+ failed: {
+ framing: people.filter((p) => p.gates.framing === false).map((p) => p.id),
+ text: people.filter((p) => p.gates.text === false).map((p) => p.id),
+ sync: people.filter((p) => p.gates.sync === false).map((p) => p.id),
+ },
+ energy: ratios.length
+ ? round([...ratios].sort((a, b) => a - b)[ratios.length >> 1]!, 3)
+ : null,
+ shots_at_cuts: {
+ at_cuts: placed.filter((c) => c.at_cut).length,
+ total: placed.length,
+ off: placed.flatMap((c) => (c.at_cut ? [] : [{ clip: c.path, start: c.offset! }])),
+ cuts_without_shot: placed.length
+ ? cuts.filter(
+ (k) =>
+ people.some((p) => k > p.window[0] && k < p.window[1]) &&
+ !placed.some((c) => Math.abs(c.offset! - k) <= AT_CUT_S),
+ )
+ : [],
+ },
+ clips,
+ },
+ };
+}
+
+/** A media ledger's cuts from the original that show its whole frame: video windows and the times of stills. */
+export function wholeFrameCuts(
+ ledger: string,
+ width: number,
+ height: number,
+): { windows: [number, number][]; stills: number[] } {
+ const isRecord = (v: unknown): v is Record =>
+ typeof v === "object" && v !== null;
+ const numbers = (v: unknown) =>
+ Array.isArray(v) ? v.filter((x): x is number => typeof x === "number") : [];
+ type Cut = { window: [number, number] } | { at: number };
+ // fallow-ignore-next-line complexity
+ const cuts = ledger.split("\n").flatMap((line): Cut[] => {
+ let entry: unknown;
+ try {
+ entry = JSON.parse(line);
+ } catch {
+ return [];
+ }
+ if (!isRecord(entry) || !isRecord(entry.provenance) || entry.provenance.provider !== "original")
+ return [];
+ const p = entry.provenance;
+ const [window, roi] = [numbers(p.window), numbers(p.roi)];
+ // A cut with no region is the whole frame.
+ const area = roi.length === 4 ? roi[2]! * roi[3]! : width * height;
+ if (area < WHOLE_FRAME_SHARE * width * height) return [];
+ if (entry.type === "video" && window.length === 2)
+ return [{ window: [window[0]!, window[1]!] }];
+ return entry.type === "image" && typeof p.at === "number" ? [{ at: p.at }] : [];
+ });
+ return {
+ windows: cuts.flatMap((c) => ("window" in c ? [c.window] : [])),
+ stills: [...new Set(cuts.flatMap((c) => ("at" in c ? [c.at] : [])))].sort((a, b) => a - b),
+ };
+}
+
+/** For each still (a time in the original), which compared frames of yours show it. */
+function stillsShown(ref: Clip, yours: Clip, stills: number[], fps: number): boolean[][] {
+ if (!stills.length) return [];
+ const h = Math.max(GRID, Math.round((STILL_W * ref.height) / ref.width / GRID) * GRID);
+ const read = (clip: Clip, extra: string[] = [], limit?: number) =>
+ decode(
+ clip.input,
+ [...clip.filters, ...extra, `scale=${STILL_W}:${h}`],
+ STILL_W,
+ h,
+ true,
+ limit,
+ ).frames;
+ const mine = read(yours);
+ return stills.map((at) => {
+ const still = read(ref, [`select=eq(n\\,${frameAt(at, fps)})`], 1)[0];
+ if (!still) return mine.map(() => false);
+ return mine.map((px) => {
+ const cells = cellDiffs(px, still, STILL_W, h).sort((a, b) => a - b);
+ return pct(cells, 0.5) <= STILL_DIFF;
+ });
+ });
+}
+
+/** The mean absolute difference of two grey pictures in each 4x4 cell. */
+function cellDiffs(a: Uint8Array, b: Uint8Array, w: number, h: number): number[] {
+ const [cw, ch] = [Math.floor(w / GRID), Math.floor(h / GRID)];
+ return ALL_CELLS.map((c) => {
+ const [x0, y0] = [(c % GRID) * cw, Math.floor(c / GRID) * ch];
+ let sum = 0;
+ for (let y = y0; y < y0 + ch; y++)
+ for (let x = x0; x < x0 + cw; x++) sum += Math.abs(a[y * w + x]! - b[y * w + x]!);
+ return sum / (cw * ch);
+ });
+}
+
+/** The ledger beside a project or its segments file (a copy may be named media-manifest.jsonl). */
+export function findLedger(yours: string, segmentsFile?: string): string | undefined {
+ const dirs = [
+ ...(existsSync(yours) && statSync(yours).isDirectory() ? [yours] : []),
+ ...(segmentsFile ? [dirname(segmentsFile)] : []),
+ ];
+ return dirs
+ .flatMap((d) => [join(d, ".media", "manifest.jsonl"), join(d, "media-manifest.jsonl")])
+ .find((f) => existsSync(f));
+}
+
+/** Runs of compared frames that are on, as [start, end) seconds. */
+function frameSpans(on: boolean[], ks: number[], fps: number): [number, number][] {
+ const spans: [number, number][] = [];
+ on.forEach((v, i) => {
+ if (!v) return;
+ const last = spans.at(-1);
+ if (last && on[i - 1] && ks[i] === ks[i - 1]! + 1) last[1] = round((ks[i]! + 1) / fps, 3);
+ else spans.push([round(ks[i]! / fps, 3), round((ks[i]! + 1) / fps, 3)]);
+ });
+ return spans;
+}
+
+/** Where yours plays one of the original's whole-frame cuts (in its window, most cells near its pixels, for REUSE_MIN_S
+ * or longer) or shows one of its stills, and where that segment draws copy: the drawn things came with the footage. */
+function wholeFrameReuse(
+ cuts: { windows: [number, number][]; stills: number[] },
+ stills: boolean[][],
+ series: Series,
+ ks: number[],
+ fps: number,
+ segments?: Segment[],
+): WholeFrameReuse {
+ const inside = (k: number, a: number, b: number) => k >= frameAt(a, fps) && k < frameAt(b, fps);
+ const played = series.frame.map(
+ (_, i) =>
+ cuts.windows.some(([a, b]) => inside(ks[i]!, a, b)) &&
+ pct(
+ [...series.cells[i]!].sort((x, y) => x - y),
+ 0.5,
+ ) >= REUSE_SSIM,
+ );
+ const long = longRuns(played, ks, Math.ceil(REUSE_MIN_S * fps));
+ const shown = long.map((v, i) => v || stills.some((on) => on[i]));
+ const drawn = shown.map(
+ (v, i) => v && !!segments?.some((s) => s.copy && inside(ks[i]!, s.start, s.end)),
+ );
+ return {
+ spans: frameSpans(shown, ks, fps),
+ stills: cuts.stills.filter((_, j) => stills[j]?.some(Boolean)),
+ share: round(shown.filter(Boolean).length / Math.max(1, shown.length), 4),
+ drawn: frameSpans(drawn, ks, fps),
+ pass: drawn.filter(Boolean).length <= REUSE_MAX_FRAMES,
+ };
+}
+
+/** `on` with its runs of consecutive frames shorter than `min` turned off. */
+export function longRuns(on: boolean[], ks: number[], min: number): boolean[] {
+ const out = [...on];
+ for (let i = 0; i < on.length; ) {
+ if (!on[i]) {
+ i++;
+ continue;
+ }
+ let j = i + 1;
+ while (j < on.length && on[j] && ks[j] === ks[j - 1]! + 1) j++;
+ if (j - i < min) out.fill(false, i, j);
+ i = j;
+ }
+ return out;
+}
+
+/** Regenerated boxes that hide what should be judged by pixels. */
+function regionWarnings(segments: Segment[], ref: VideoInfo): string[] {
+ return segments.flatMap((s) => {
+ const box = s.regenerated && regionRoi(s.regenerated, ref.width, ref.height);
+ if (s.drawn || !(box || s.pixels === "regenerated")) return [];
+ if (box && box[2] * box[3] >= WHOLE_FRAME_SHARE * ref.width * ref.height)
+ return [
+ `${s.id}: its Regenerated box covers the whole frame, so nothing in it is judged by pixels: box the person, and give each drawn element over them a Drawn: x, y, w, h line`,
+ ];
+ return s.copy
+ ? [
+ `${s.id} draws copy over a regenerated person: a drawn element inside the person's box is judged by pixels only with its own Drawn: x, y, w, h line`,
+ ]
+ : [];
+ });
+}
+
+async function worstMoments(
+ picks: number[],
+ ctx: { refClip: Clip; yours: Clip; series: Series; ks: number[]; ref: VideoInfo; outDir: string },
+): Promise<{ worst: Moment[]; sheet?: string }> {
+ const { ref, series } = ctx;
+ const sw = Math.min(SHEET_W, ref.width);
+ const sh = Math.max(2, Math.round((ref.height * sw) / ref.width / 2) * 2);
+ const [cw, ch] = cellSize(ref.width, ref.height);
+ const worst: Moment[] = [];
+ const images: string[] = [];
+ const labels: string[] = [];
+ for (const [n, i] of picks.entries()) {
+ const cells = series.cells[i]!;
+ const c = cells.indexOf(Math.min(...cells));
+ const roi: Moment["cell"]["roi"] = [(c % GRID) * cw, Math.floor(c / GRID) * ch, cw, ch];
+ const scaled = roi.map((v, j) =>
+ Math.round((v * (j % 2 ? sh : sw)) / (j % 2 ? ref.height : ref.width)),
+ );
+ const t = round(ctx.ks[i]! / ref.fps, 3);
+ const tag = `worst-${String(n + 1).padStart(2, "0")}`;
+ // The failing cell at full size, original | yours, to read text and edges.
+ const [fa, fb] = [
+ frameOf(ctx.refClip, i, ref.width, ref.height),
+ frameOf(ctx.yours, i, ref.width, ref.height),
+ ];
+ const pair = new Uint8Array((2 * cw + 4) * ch * 3).fill(255);
+ for (let y = 0; y < ch; y++)
+ [fa, fb].forEach((f, side) =>
+ pair.set(
+ f.subarray(
+ ((roi[1] + y) * ref.width + roi[0]) * 3,
+ ((roi[1] + y) * ref.width + roi[0] + cw) * 3,
+ ),
+ (y * (2 * cw + 4) + side * (cw + 4)) * 3,
+ ),
+ );
+ const cellPicture = writeImage(join(ctx.outDir, `${tag}-cell.png`), pair, 2 * cw + 4, ch);
+ const [a, b] = [frameOf(ctx.refClip, i, sw, sh), frameOf(ctx.yours, i, sw, sh)];
+ outline(a, sw, scaled);
+ outline(b, sw, scaled);
+ images.push(writeImage(join(ctx.outDir, `${tag}-original.png`), a, sw, sh));
+ images.push(writeImage(join(ctx.outDir, `${tag}-yours.png`), b, sw, sh));
+ labels.push(
+ `original ${t}s`,
+ `yours ${t}s · ssim ${round(series.frame[i]!, 3)} · cell ${round(cells[c]!, 2)}`,
+ );
+ worst.push({
+ t,
+ frame: ctx.ks[i]!,
+ ssim: round(series.frame[i]!, 4),
+ cell: { roi, ssim: round(cells[c]!, 3), picture: cellPicture },
+ });
+ }
+ if (!images.length) return { worst };
+ const { createContactSheet } = await import("../capture/contactSheet.js");
+ const sheet = await createContactSheet(images, join(ctx.outDir, "worst.jpg"), {
+ cols: 2,
+ maxImages: images.length,
+ cellWidth: 640,
+ labelMode: "custom",
+ labels,
+ });
+ return { worst, ...(sheet ? { sheet } : {}) };
+}
+
+/** Loudness every 10 ms of the first 20 s, as a rising-edge curve: where sounds start. */
+function onsetCurve(path: string): number[] {
+ // On the sound's own timestamps (first_pts=0 pads up to its first decoded sample), not the probe's start_time:
+ // ffmpeg 5.1 drops an HE-AAC edit list's skip twice, keeps the rest timestamped right, and still probes 0.
+ const raw = runFfmpeg([
+ ...["-i", path, "-vn", "-af", "aresample=async=1:first_pts=0"],
+ ...["-t", "20", "-ac", "1", "-ar", "8000", "-f", "f32le", "-"],
+ ]);
+ const samples = new Float32Array(raw.buffer, raw.byteOffset, Math.floor(raw.byteLength / 4));
+ const rms: number[] = [];
+ for (let i = 0; i + 80 <= samples.length; i += 80) {
+ let s = 0;
+ for (let j = i; j < i + 80; j++) s += samples[j]! ** 2;
+ rms.push(Math.sqrt(s / 80));
+ }
+ return rms.map((v, i) => Math.max(0, v - (rms[i - 1] ?? v)));
+}
+
+/** How far yours' sound sits from the original's (positive: yours is late), from where sounds start. */
+export function soundOffset(reference: string, yours: string, ref: VideoInfo, mine: VideoInfo) {
+ if (!ref.audio || !mine.audio)
+ return { original: ref.audio, yours: mine.audio, pass: ref.audio === mine.audio };
+ const [a, b] = [onsetCurve(reference), onsetCurve(yours)];
+ let best: [number, number] = [-2, 0];
+ for (let lag = -50; lag <= 50; lag++) {
+ const n = Math.min(a.length, b.length) - Math.abs(lag);
+ if (n < 50) continue;
+ const [i, j] = [Math.max(0, -lag), Math.max(0, lag)];
+ const r = pearson(a.slice(i, i + n), b.slice(j, j + n)) ?? -2;
+ if (r > best[0]) best = [r, lag];
+ }
+ const offset = best[1] * 10;
+ // Steady sound (a held pad, room tone) has too few starts to align: say so rather than fail it.
+ if (best[0] <= 0.3)
+ return {
+ offset_ms: null,
+ match: round(best[0], 2),
+ pass: true,
+ note: "too few distinct sounds to align",
+ };
+ return { offset_ms: offset, match: round(best[0], 2), pass: Math.abs(offset) <= 1000 / ref.fps };
+}
+
+function sideBySide(reference: string, yours: string, ref: VideoInfo, out: string): string {
+ runFfmpeg([
+ ...["-y", "-i", reference, "-i", yours, "-filter_complex"],
+ `[0:v]setsar=1[a];[1:v]scale=${ref.width}:${ref.height},setsar=1[b];[a][b]hstack=inputs=2,pad=ceil(iw/2)*2:ceil(ih/2)*2[v]`,
+ ...["-map", "[v]", "-map", "0:a?", "-c:v", "libx264", "-crf", "20", "-pix_fmt", "yuv420p"],
+ ...["-c:a", "aac", "-shortest", out],
+ ]);
+ return out;
+}
+
+function choosePick(opts: DiffOptions, ref: VideoInfo): Pick {
+ if (opts.at)
+ return {
+ kind: "at",
+ ks: [...new Set(opts.at.map((t) => frameAt(t, ref.fps)))].sort((x, y) => x - y),
+ };
+ if (opts.range)
+ return {
+ kind: "range",
+ k0: frameAt(opts.range[0], ref.fps),
+ k1: Math.min(ref.frames, Math.ceil(opts.range[1] * ref.fps - 1e-6)),
+ };
+ return { kind: "all" };
+}
+
+// fallow-ignore-next-line complexity
+export async function diffVideos(options: DiffOptions): Promise {
+ // ffmpeg runs in a scratch folder (see ssimSeries), so every path it reads is absolute.
+ const opts = { ...options, reference: resolve(options.reference), yours: resolve(options.yours) };
+ const ref = probeVideo(opts.reference);
+ const warnings: string[] = [];
+ if (ref.vfr)
+ warnings.push(
+ "the original's frame rate varies, so frame times drift: npx hyperframes measure probe makes a constant-rate copy",
+ );
+ const mode = existsSync(opts.yours) && statSync(opts.yours).isDirectory() ? "project" : "video";
+ if (mode === "project" && !existsSync(join(opts.yours, "index.html")))
+ throw new Fix(`${opts.yours} has no index.html`, "pass a project folder or a rendered video");
+ if (mode === "project" && !opts.at && !opts.range && opts.segments?.length)
+ opts.range = [
+ Math.min(...opts.segments.map((s) => s.start)),
+ Math.max(...opts.segments.map((s) => s.end)),
+ ];
+ if (mode === "project" && !opts.at && !opts.range)
+ throw new Fix(
+ "a project folder is compared at chosen times, not whole",
+ "pass --at t1,t2 or --range start,end, or render it and diff the render",
+ );
+ const pick = choosePick(opts, ref);
+ const ks = pickedFrames(pick, ref.frames);
+ if (!ks.length || ks.some((k) => k >= ref.frames))
+ throw new Fix(
+ `the original has ${ref.frames} frames (${round(ref.duration, 2)} s)`,
+ "pick times inside it",
+ );
+
+ const select = selectFilter(pick, ref.fpsText);
+ const refClip: Clip = { ...videoClip(opts.reference, 0, undefined, ref), filters: select };
+ let yours: Clip;
+ let seqDir: string | undefined;
+ let yoursInfo: VideoInfo | undefined;
+ if (mode === "project") {
+ const captured = await captureProject(
+ opts.yours,
+ ks.map((k) => k / ref.fps),
+ opts,
+ ref,
+ );
+ [yours, seqDir] = [captured.clip, captured.dir];
+ } else {
+ yoursInfo = probeVideo(opts.yours);
+ yours = {
+ ...videoClip(opts.yours, 0, undefined, yoursInfo),
+ filters: [`fps=${ref.fpsText}`, ...select],
+ };
+ }
+
+ try {
+ mkdirSync(opts.outDir, { recursive: true });
+ for (const f of readdirSync(opts.outDir))
+ if (/^worst-/.test(f)) rmSync(join(opts.outDir, f), { force: true });
+ const logPath = join(opts.outDir, "ssim.log");
+ const series = ssimSeries(refClip, yours, logPath);
+ if (!series.frame.length)
+ throw new Fix("ffmpeg compared no frames", "check both videos play and overlap in time");
+ if (series.frame.length < ks.length)
+ warnings.push(`yours ends early: ${series.frame.length} of ${ks.length} frames compared`);
+ const worstCell = series.cells.map((cells) => Math.min(...cells));
+ // Every compared frame, to find the stretches that fail.
+ writeFileSync(
+ join(opts.outDir, "frames.tsv"),
+ [
+ "t\tframe\tssim\tworst_cell\tcell",
+ ...series.frame.map((v, i) => {
+ const c = series.cells[i]!.indexOf(worstCell[i]!);
+ return [
+ round(ks[i]! / ref.fps, 3),
+ ks[i],
+ round(v, 4),
+ round(worstCell[i]!, 4),
+ `r${Math.floor(c / GRID)}c${c % GRID}`,
+ ].join("\t");
+ }),
+ ].join("\n") + "\n",
+ );
+ const t: Thresholds = {
+ mean: opts.thresholds?.mean ?? DEFAULT_MIN_MEAN,
+ p05: opts.thresholds?.p05 ?? DEFAULT_MIN_P05,
+ cell: opts.thresholds?.cell ?? DEFAULT_MIN_CELL,
+ };
+ const overall = scores(series.frame, worstCell);
+ const missing = missingContent(refClip, yours, ks, ref.fps, (k) => {
+ const s = opts.segments?.find(
+ (seg) => k >= frameAt(seg.start, ref.fps) && k < frameAt(seg.end, ref.fps),
+ );
+ if (s?.pixels === "regenerated") return [];
+ return s?.regenerated
+ ? cellsOutside(regionRoi(s.regenerated, ref.width, ref.height), ref.width, ref.height)
+ : ALL_CELLS;
+ });
+ if (!missing.pass)
+ warnings.push(
+ `${Math.round(missing.share * 100)}% of frames leave empty what the original fills (${missing.spans.map(([a, b]) => `${a}–${b} s`).join(", ")}): build what is missing there`,
+ );
+ if (missing.texture.share > MISSING_MAX_SHARE)
+ warnings.push(
+ `${Math.round(missing.texture.share * 100)}% of frames lack fine texture or small detail the original has (${missing.texture.spans.map(([a, b]) => `${a}–${b} s`).join(", ")}): reported, not failed`,
+ );
+ const picks = worstIndexes(worstCell, ks, ref.fps, opts.worst ?? 4);
+ const { worst, sheet } = await worstMoments(picks, {
+ refClip,
+ yours,
+ series,
+ ks,
+ ref,
+ outDir: opts.outDir,
+ });
+ const cuts = pick.kind === "at" ? undefined : cutReport(refClip, yours, ks[0]!, ref.fps);
+ const duration =
+ yoursInfo && pick.kind === "all"
+ ? {
+ reference: round(ref.pictureDuration, 3),
+ yours: round(yoursInfo.pictureDuration, 3),
+ pass: Math.abs(ref.pictureDuration - yoursInfo.pictureDuration) <= 1.5 / ref.fps,
+ }
+ : undefined;
+ const ledgerText =
+ opts.ledger && existsSync(opts.ledger) ? readFileSync(opts.ledger, "utf8") : undefined;
+ const people = new Map();
+ let clips: ReturnType = [];
+ if (opts.segments && yoursInfo) {
+ const project =
+ opts.project ??
+ (opts.ledger && basename(dirname(opts.ledger)) === ".media"
+ ? dirname(dirname(opts.ledger))
+ : undefined);
+ const refCuts = cuts?.reference ?? [];
+ const uses = project
+ ? await clipUses(project).catch(() => new Map())
+ : new Map();
+ clips = ledgerText ? placeClips(generatedClips(ledgerText), project, ref, refCuts, uses) : [];
+ if (clips.length && clips.every((c) => !c.info))
+ warnings.push(
+ "the ledger's generated clips are not found, so text carried in them is not checked: pass --project ",
+ );
+ for (const s of opts.segments)
+ if (s.regenerated || s.pixels === "regenerated")
+ people.set(
+ s,
+ await personVerdict({
+ ref,
+ yours: yoursInfo,
+ window: [s.start, s.end],
+ cuts: refCuts,
+ clips,
+ drawn: drawnOf(s, ref),
+ }),
+ );
+ }
+ const segments = opts.segments
+ ? segmentVerdicts(opts.segments, series, worstCell, ks, {
+ reference: opts.reference,
+ yours: opts.yours,
+ ref,
+ mode,
+ t,
+ drawn: scoreDrawn(opts.segments, refClip, yours, ks, ref, series.frame.length),
+ person: people,
+ })
+ : undefined;
+ if (opts.segments) warnings.push(...regionWarnings(opts.segments, ref));
+ const elements = opts.drawn?.length
+ ? scoreElements(
+ opts.drawn.map((d, n) => ({
+ id: `D${n + 1}`,
+ box: regionRoi(d.box, ref.width, ref.height),
+ window: d.window ?? [0, round(ref.pictureDuration, 3)],
+ })),
+ refClip,
+ yours,
+ ks,
+ ref,
+ series.frame.length,
+ )
+ : undefined;
+ const ledger = ledgerText ? wholeFrameCuts(ledgerText, ref.width, ref.height) : undefined;
+ const reuse =
+ ledger && (ledger.windows.length || ledger.stills.length)
+ ? wholeFrameReuse(
+ ledger,
+ stillsShown({ ...refClip, filters: [] }, yours, ledger.stills, ref.fps),
+ series,
+ ks,
+ ref.fps,
+ opts.segments,
+ )
+ : undefined;
+ if (reuse && !reuse.pass) {
+ const seconds = reuse.drawn.reduce((sum, [a, b]) => sum + b - a, 0);
+ warnings.push(
+ `${round(seconds, 2)} s play the original's whole frame with its drawn things in it (${reuse.drawn.map(([a, b]) => `${a}–${b} s`).join(", ")}): a copy, not a reverse. Cut only the camera image, each piece on its own box, and rebuild what is drawn`,
+ );
+ for (const v of segments ?? [])
+ if (reuse.drawn.some(([a, b]) => a < v.window[1] && b > v.window[0])) {
+ v.pass = false;
+ v.note = "plays the original's whole frame with its drawn things: a copy";
+ }
+ } else if (reuse?.spans.length && !opts.segments)
+ warnings.push(
+ `${Math.round(reuse.share * 100)}% of frames play the original's whole frame: pass --segments to tell footage from copied drawings`,
+ );
+ const sound =
+ yoursInfo && pick.kind === "all"
+ ? soundOffset(opts.reference, opts.yours, ref, yoursInfo)
+ : undefined;
+ const sbs =
+ opts.sbs && mode === "video"
+ ? sideBySide(opts.reference, opts.yours, ref, join(opts.outDir, "sbs.mp4"))
+ : undefined;
+
+ const judged = segments ? segments.every((s) => s.pass !== false) : passes(overall, t);
+ const top = segments
+ ? headline(
+ segments,
+ clips.map(({ info: _info, file: _file, still: _still, ...c }) => c),
+ t,
+ cuts?.reference,
+ )
+ : undefined;
+ const complete = series.frame.length === ks.length;
+ return {
+ pass:
+ judged &&
+ complete &&
+ missing.pass &&
+ (reuse?.pass ?? true) &&
+ (cuts?.pass ?? true) &&
+ (duration?.pass ?? true) &&
+ (sound?.pass ?? true),
+ reference: opts.reference,
+ yours: opts.yours,
+ mode,
+ window: [round(ks[0]! / ref.fps, 3), round((ks.at(-1)! + 1) / ref.fps, 3)],
+ thresholds: t,
+ ssim: overall,
+ missing_content: missing,
+ ...(reuse ? { whole_frame_reuse: reuse } : {}),
+ worst,
+ ...(cuts ? { cuts } : {}),
+ ...(duration ? { duration } : {}),
+ ...(sound ? { sound } : {}),
+ ...(top ? top : {}),
+ ...(segments ? { segments } : {}),
+ ...(elements ? { drawn: elements } : {}),
+ ...(sheet ? { sheet } : {}),
+ ...(sbs ? { sbs } : {}),
+ log: logPath,
+ frames: join(opts.outDir, "frames.tsv"),
+ warnings,
+ };
+ } finally {
+ if (seqDir) rmSync(seqDir, { recursive: true, force: true });
+ }
+}
diff --git a/packages/cli/src/measure/drawn.test.ts b/packages/cli/src/measure/drawn.test.ts
new file mode 100644
index 0000000000..cb8c6ceb37
--- /dev/null
+++ b/packages/cli/src/measure/drawn.test.ts
@@ -0,0 +1,74 @@
+import { describe, expect, it } from "vitest";
+import { DRAWN_MIN_MEAN, drawnVerdict, scoreDrawnFrame } from "./drawn.js";
+
+const [W, H] = [160, 48];
+
+/** A crop: a background, then bars standing in for letters (x, width) in one colour. */
+function crop(
+ background: (x: number, y: number) => [number, number, number],
+ bars: [number, number][],
+ ink: [number, number, number] = [255, 255, 255],
+ dy = 0,
+): Uint8Array {
+ const px = new Uint8Array(W * H * 3);
+ for (let y = 0; y < H; y++)
+ for (let x = 0; x < W; x++) {
+ const on = y >= 10 + dy && y < 38 + dy && bars.some(([a, w]) => x >= a && x < a + w);
+ px.set(on ? ink : background(x, y), (y * W + x) * 3);
+ }
+ return px;
+}
+
+// Two different backgrounds behind the same letters: a warm room and a cool, striped one.
+const room = (x: number, y: number): [number, number, number] => [90 + (x % 7), 60 + (y % 5), 40];
+const street = (x: number, _y: number): [number, number, number] => [
+ 30,
+ 70 + ((x >> 3) % 2) * 25,
+ 110,
+];
+const word: [number, number][] = [10, 30, 50, 70, 90, 110, 130].map((x) => [x, 8]);
+
+describe("scoreDrawnFrame", () => {
+ it("scores the same letters over a different background as a match", () => {
+ const f = scoreDrawnFrame(crop(room, word), crop(street, word), W, H);
+ expect(f.score).toBeGreaterThan(DRAWN_MIN_MEAN);
+ expect(f.offset).toEqual([0, 0]);
+ });
+
+ it("forgives a pixel or two of offset and says how far", () => {
+ const f = scoreDrawnFrame(crop(room, word), crop(street, word, undefined, 2), W, H);
+ expect(f.score).toBeGreaterThan(DRAWN_MIN_MEAN);
+ expect(f.offset).toEqual([0, 2]);
+ });
+
+ it("fails lighter weight, wider tracking, a doubled letter and another fill", () => {
+ const light = word.map(([x]): [number, number] => [x, 4]);
+ const wide = word.map(([x, w], i): [number, number] => [x + i * 3, w]);
+ const doubled = [...word, ...word.map(([x, w]): [number, number] => [x + 12, w])];
+ for (const yours of [
+ crop(street, light),
+ crop(street, wide),
+ crop(street, doubled),
+ crop(street, word, [250, 210, 0]),
+ ])
+ expect(scoreDrawnFrame(crop(room, word), yours, W, H).score).toBeLessThan(DRAWN_MIN_MEAN);
+ });
+
+ it("scores a missing element as nothing matched, and nothing on both sides as no frame", () => {
+ expect(scoreDrawnFrame(crop(room, word), crop(street, []), W, H).score).toBeLessThan(0.5);
+ const flat = () => [128, 128, 128] as [number, number, number];
+ expect(scoreDrawnFrame(crop(flat, []), crop(flat, []), W, H).score).toBeNull();
+ });
+});
+
+describe("drawnVerdict", () => {
+ it("passes on the mean and the 5th percentile of the frames, and reports ink weight", () => {
+ const good = scoreDrawnFrame(crop(room, word), crop(street, word), W, H);
+ const gone = scoreDrawnFrame(crop(room, word), crop(street, []), W, H);
+ const v = drawnVerdict([0, 0, W, H], [0, 1], Array(10).fill(good));
+ expect(v).toMatchObject({ pass: true, frames: 10, ink: 1 });
+ const bad = drawnVerdict([0, 0, W, H], [0, 1], [...Array(9).fill(good), gone]);
+ expect(bad.pass).toBe(false);
+ expect(drawnVerdict([0, 0, W, H], [0, 1], [])).toMatchObject({ pass: null, frames: 0 });
+ });
+});
diff --git a/packages/cli/src/measure/drawn.ts b/packages/cli/src/measure/drawn.ts
new file mode 100644
index 0000000000..9d74b76e6a
--- /dev/null
+++ b/packages/cli/src/measure/drawn.ts
@@ -0,0 +1,227 @@
+// A drawn element (text, a badge, a card) over a regenerated person, scored by itself, since what is behind it differs
+// on purpose: each frame aligns the element's ink on both sides within a few pixels and asks how much of either side's
+// ink the other matches in colour. Wrong weight, size, fill or a late onset leave ink unmatched; a new background none.
+import { mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { round, runFfmpeg, type Clip, type Roi } from "./media.js";
+
+export const DRAWN_MIN_MEAN = 0.8;
+const DRAWN_MIN_P05 = 0.65;
+// A pixel is ink when its colour is this far (RGB distance) from its neighbourhood's median.
+const INK_CONTRAST = 60;
+// Two pixels match within this RGB distance, one pixel apart at most, after aligning the sides this many pixels.
+const MATCH_COLOUR = 45;
+const ALIGN = 3;
+// Fewer ink pixels than this on both sides: nothing drawn in that frame on either side.
+const MIN_INK = 30;
+const MAX_FPS = 10;
+
+export interface DrawnFrame {
+ /** Share of both sides' ink the other side matches (F1 of matched ink), or null when neither side has ink. */
+ score: number | null;
+ /** Where yours sits against the original, x and y in pixels (within ±3; further lowers the score). */
+ offset: [number, number];
+ inkOriginal: number;
+ inkYours: number;
+}
+
+export interface DrawnVerdict {
+ box: Roi;
+ window: [number, number];
+ frames: number;
+ pass: boolean | null;
+ /** Mean and 5th percentile of the frames' scores. */
+ score?: number;
+ p05?: number;
+ /** Median of the frames' offsets. */
+ offset?: [number, number];
+ /** Yours' ink over the original's, median of frames where both have ink: under 1 is lighter or smaller. */
+ ink?: number;
+}
+
+/** Each pixel's colour distance from the median colour of the blocks around it. */
+// fallow-ignore-next-line complexity
+export function contrast(px: Uint8Array, w: number, h: number): Float32Array {
+ const bs = Math.max(4, Math.floor(Math.max(8, Math.floor(h / 2)) / 2));
+ const [gw, gh] = [Math.ceil(w / bs), Math.ceil(h / bs)];
+ const med = new Float32Array(gw * gh * 3);
+ const hist = new Uint32Array(256);
+ for (let by = 0; by < gh; by++)
+ for (let bx = 0; bx < gw; bx++) {
+ const [x0, x1] = [Math.max(0, (bx - 1) * bs), Math.min(w, (bx + 2) * bs)];
+ const [y0, y1] = [Math.max(0, (by - 1) * bs), Math.min(h, (by + 2) * bs)];
+ const half = ((x1 - x0) * (y1 - y0)) / 2;
+ for (let c = 0; c < 3; c++) {
+ hist.fill(0);
+ for (let y = y0; y < y1; y++)
+ for (let x = x0; x < x1; x++) hist[px[(y * w + x) * 3 + c]!]!++;
+ let [v, seen] = [0, 0];
+ while (v < 255 && seen + hist[v]! < half) seen += hist[v++]!;
+ med[(by * gw + bx) * 3 + c] = v;
+ }
+ }
+ const out = new Float32Array(w * h);
+ for (let y = 0; y < h; y++)
+ for (let x = 0; x < w; x++) {
+ const [o, m] = [(y * w + x) * 3, (Math.floor(y / bs) * gw + Math.floor(x / bs)) * 3];
+ out[y * w + x] = Math.hypot(
+ px[o]! - med[m]!,
+ px[o + 1]! - med[m + 1]!,
+ px[o + 2]! - med[m + 2]!,
+ );
+ }
+ return out;
+}
+
+const inkOf = (px: Uint8Array, w: number, h: number) => {
+ const c = contrast(px, w, h);
+ return Uint8Array.from(c, (v) => (v > INK_CONTRAST ? 1 : 0));
+};
+
+/** One frame of an element: the original's and yours' RGB crops of the same box. */
+// fallow-ignore-next-line complexity
+export function scoreDrawnFrame(a: Uint8Array, b: Uint8Array, w: number, h: number): DrawnFrame {
+ const [ia, ib] = [inkOf(a, w, h), inkOf(b, w, h)];
+ const [na, nb] = [ia.reduce((s, v) => s + v, 0), ib.reduce((s, v) => s + v, 0)];
+ if (na + nb < MIN_INK) return { score: null, offset: [0, 0], inkOriginal: na, inkYours: nb };
+ let mostOverlappingShift = { iou: -1, dx: 0, dy: 0 };
+ for (let dy = -ALIGN; dy <= ALIGN; dy++)
+ for (let dx = -ALIGN; dx <= ALIGN; dx++) {
+ let [both, either] = [0, 0];
+ for (let y = 0; y < h; y++) {
+ const sy = y - dy;
+ for (let x = 0; x < w; x++) {
+ const sx = x - dx;
+ const vb = sy >= 0 && sy < h && sx >= 0 && sx < w ? ib[sy * w + sx]! : 0;
+ const va = ia[y * w + x]!;
+ both += va & vb;
+ either += va | vb;
+ }
+ }
+ const iou = either ? both / either : 0;
+ if (iou > mostOverlappingShift.iou) mostOverlappingShift = { iou, dx, dy };
+ }
+ // Ink on either side counts as matched when the other side has a pixel of its colour within one pixel.
+ const at = (x: number, y: number) =>
+ (Math.min(h - 1, Math.max(0, y)) * w + Math.min(w - 1, Math.max(0, x))) * 3;
+ const near = (p: Uint8Array, o: number, q: Uint8Array, x: number, y: number) => {
+ for (let ry = -1; ry <= 1; ry++)
+ for (let rx = -1; rx <= 1; rx++) {
+ const k = at(x + rx, y + ry);
+ if (Math.hypot(p[o]! - q[k]!, p[o + 1]! - q[k + 1]!, p[o + 2]! - q[k + 2]!) < MATCH_COLOUR)
+ return true;
+ }
+ return false;
+ };
+ let [hitA, hitB, inkA, inkB] = [0, 0, 0, 0];
+ for (let y = 0; y < h; y++)
+ for (let x = 0; x < w; x++) {
+ const i = y * w + x;
+ const [sx, sy] = [x - mostOverlappingShift.dx, y - mostOverlappingShift.dy];
+ const inB = sy >= 0 && sy < h && sx >= 0 && sx < w && ib[sy * w + sx] === 1;
+ if (ia[i]) {
+ inkA++;
+ if (near(a, i * 3, b, sx, sy)) hitA++;
+ }
+ if (inB) {
+ inkB++;
+ if (near(b, at(sx, sy), a, x, y)) hitB++;
+ }
+ }
+ const [recall, precision] = [inkA ? hitA / inkA : 0, inkB ? hitB / inkB : 0];
+ return {
+ score: recall + precision ? (2 * recall * precision) / (recall + precision) : 0,
+ offset: [0 - mostOverlappingShift.dx, 0 - mostOverlappingShift.dy],
+ inkOriginal: na,
+ inkYours: nb,
+ };
+}
+
+const median = (v: number[]) => [...v].sort((x, y) => x - y)[v.length >> 1] ?? 0;
+
+export function drawnVerdict(
+ box: Roi,
+ window: [number, number],
+ frames: DrawnFrame[],
+): DrawnVerdict {
+ const head = { box, window, frames: frames.length };
+ const scored = frames.flatMap((f) => (f.score === null ? [] : [f]));
+ if (!scored.length) return { ...head, pass: null };
+ const sorted = scored.map((f) => f.score!).sort((x, y) => x - y);
+ const mean = sorted.reduce((s, v) => s + v, 0) / sorted.length;
+ const p05 = sorted[Math.min(sorted.length - 1, Math.floor(0.05 * sorted.length))]!;
+ const both = scored.filter((f) => f.inkOriginal >= MIN_INK && f.inkYours >= MIN_INK);
+ return {
+ ...head,
+ pass: mean >= DRAWN_MIN_MEAN && p05 >= DRAWN_MIN_P05,
+ score: round(mean, 3),
+ p05: round(p05, 3),
+ offset: [median(scored.map((f) => f.offset[0])), median(scored.map((f) => f.offset[1]))],
+ ...(both.length ? { ink: round(median(both.map((f) => f.inkYours / f.inkOriginal)), 2) } : {}),
+ };
+}
+
+export interface DrawnJob {
+ box: Roi;
+ /** Indexes into the compared frames (the clips' frames after their own filters), in order. */
+ frames: number[];
+}
+
+/**
+ * Each job's crops from a clip scaled to `width`x`height` (the original's size), one decode for all of them:
+ * `frames[j][n]` is job j's n-th frame, RGB at the box's size.
+ */
+export function readDrawn(
+ clip: Clip,
+ jobs: DrawnJob[],
+ width: number,
+ height: number,
+): Uint8Array[][] {
+ if (!jobs.length) return [];
+ const work = mkdtempSync(join(tmpdir(), "hf-diff-drawn-"));
+ try {
+ const tags = jobs.map((_, j) => `[d${j}]`).join("");
+ const graph = [
+ `[0:v]${[...clip.filters, "setsar=1", `scale=${width}:${height}:flags=bicubic`].join(",")},split=${jobs.length}${tags}`,
+ ...jobs.map(({ box: [x, y, w, h], frames }, j) => {
+ const pick = frames.map((k) => `eq(n\\,${k})`).join("+");
+ return `[d${j}]select=${pick},crop=${w}:${h}:${x}:${y},format=rgb24[e${j}]`;
+ }),
+ ].join(";");
+ const outs = jobs.flatMap((_, j) => [
+ ...["-map", `[e${j}]`, "-fps_mode", "passthrough", "-f", "rawvideo", `e${j}.rgb`],
+ ]);
+ runFfmpeg([...clip.input, "-an", "-filter_complex", graph, ...outs], undefined, work);
+ return jobs.map(({ box: [, , w, h] }, j) => {
+ const raw = readFileSync(join(work, `e${j}.rgb`));
+ const size = w * h * 3;
+ const frames: Uint8Array[] = [];
+ for (let i = 0; i + size <= raw.length; i += size) frames.push(raw.subarray(i, i + size));
+ return frames;
+ });
+ } finally {
+ rmSync(work, { recursive: true, force: true });
+ }
+}
+
+/** The compared frames (indexes into `ks`) inside [a, b) seconds, thinned to MAX_FPS. */
+export function drawnFrames(
+ ks: number[],
+ fps: number,
+ a: number,
+ b: number,
+ available: number,
+): number[] {
+ const stride = Math.max(1, Math.round(fps / MAX_FPS));
+ const inside = ks.flatMap((k, i) =>
+ i < available && k / fps >= a - 1e-6 && k / fps < b - 1e-6 ? [i] : [],
+ );
+ // Every stride-th frame of a run of consecutive frames; moments already that far apart (--at) all count.
+ let last = -Infinity;
+ return inside.filter((i) => {
+ if (ks[i]! - last < stride) return false;
+ last = ks[i]!;
+ return true;
+ });
+}
diff --git a/packages/cli/src/measure/energy.ts b/packages/cli/src/measure/energy.ts
new file mode 100644
index 0000000000..99a5157169
--- /dev/null
+++ b/packages/cli/src/measure/energy.ts
@@ -0,0 +1,44 @@
+// Body and camera motion where the pixels differ (a regenerated shot, another person, another room), ported from
+// the Studio's motion-energy.mjs. Both clips share one 12 fps grid, as mixed 24/30 fps skews per-frame differences.
+import { meanAbsDiff, pearson, ratioOf, readClip, round, type Clip, type Roi } from "./media.js";
+
+const ENERGY_RATE = 12;
+const STILL_SHOT_GREY_LEVELS = 0.1;
+
+export function energyCurve(clip: Clip, roi?: Roi): number[] {
+ const { frames } = readClip(clip, { fps: ENERGY_RATE, width: 270, gray: true, roi });
+ return frames.slice(1).map((f, i) => meanAbsDiff(f, frames[i]!));
+}
+
+export interface EnergyComparison {
+ /** Pearson r of the two curves at the best lag within ±1 s; only meaningful when the action is the same. */
+ r: number;
+ lag_s: number;
+ peak_ratio: number;
+ /** Amount of movement, yours over the reference's. */
+ mean_ratio: number;
+}
+
+export function compareEnergy(ref: number[], yours: number[]): EnergyComparison {
+ let best: [number, number] = [-2, 0];
+ for (let lag = -ENERGY_RATE; lag <= ENERGY_RATE; lag++) {
+ const [aa, bb] =
+ lag >= 0
+ ? [ref.slice(0, ref.length - lag), yours.slice(lag)]
+ : [ref.slice(-lag), yours.slice(0, yours.length + lag)];
+ if (Math.min(aa.length, bb.length) > 8) {
+ const r = pearson(aa, bb) ?? 0;
+ if (r > best[0]) best = [r, lag];
+ }
+ }
+ const mean = (v: number[]) => v.reduce((s, x) => s + x, 0) / (v.length || 1);
+ return {
+ r: round(best[0] === -2 ? 0 : best[0]),
+ lag_s: round(best[1] / ENERGY_RATE, 2),
+ peak_ratio: round(
+ ratioOf(Math.max(...yours, 0), Math.max(...ref, 0), STILL_SHOT_GREY_LEVELS),
+ 2,
+ ),
+ mean_ratio: round(ratioOf(mean(yours), mean(ref), STILL_SHOT_GREY_LEVELS), 2),
+ };
+}
diff --git a/packages/cli/src/measure/events.test.ts b/packages/cli/src/measure/events.test.ts
new file mode 100644
index 0000000000..6b9597b110
--- /dev/null
+++ b/packages/cli/src/measure/events.test.ts
@@ -0,0 +1,107 @@
+import { execFileSync } from "node:child_process";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, describe, expect, it } from "vitest";
+import { findFFmpeg, findFFprobe } from "../browser/ffmpeg.js";
+import { cutClip, cutStill } from "../commands/measure/extract.js";
+import { detectEvents, lookWindows } from "./events.js";
+import { probeVideo, readFrames } from "./media.js";
+
+const ffmpeg = findFFmpeg();
+const noTools = !ffmpeg || !findFFprobe();
+const dir = mkdtempSync(join(tmpdir(), "hf-events-test-"));
+afterAll(() => rmSync(dir, { recursive: true, force: true }));
+
+function clip(name: string, args: string[]): string {
+ const out = join(dir, name);
+ execFileSync(ffmpeg!, ["-hide_banner", "-loglevel", "error", "-y", ...args, out]);
+ return out;
+}
+
+describe.skipIf(noTools)("detectEvents", () => {
+ // 25 fps, 3 s: a box appears at 0.52 s, the whole frame flashes white on frame 30 (1.2 s) only, the background
+ // cuts from dark blue to dark green at 2.0 s.
+ const video = noTools
+ ? ""
+ : clip("events.mp4", [
+ ...["-f", "lavfi", "-i", "color=c=0x101830:s=320x180:r=25:d=2"],
+ ...["-f", "lavfi", "-i", "color=c=0x103018:s=320x180:r=25:d=1"],
+ "-filter_complex",
+ "[0][1]concat=n=2:v=1[bg];[bg]" +
+ "drawbox=x=200:y=100:w=60:h=40:color=white:t=fill:enable='gte(n,13)'," +
+ "drawbox=x=0:y=0:w=320:h=180:color=white:t=fill:enable='eq(n,30)'[v]",
+ ...["-map", "[v]", "-pix_fmt", "yuv420p", "-c:v", "libx264", "-crf", "0"],
+ ]);
+
+ it("tells an appear, a one-frame flash, a cut and a hold apart, each on its frame", () => {
+ const info = probeVideo(video);
+ const found = detectEvents({
+ info,
+ start: 0,
+ end: 3,
+ roi: [0, 0, 320, 180],
+ grid: { cols: 4, rows: 4 },
+ });
+ const of = (type: string) => found.events.filter((e) => e.type === type);
+ expect(of("appear").map((e) => e.frame)).toEqual([13]);
+ expect(of("appear")[0]!.cells).toEqual(["r2c2", "r2c3", "r3c2", "r3c3"]);
+ expect(of("flash").map((e) => [e.frame, e.frames])).toEqual([[30, 1]]);
+ expect(of("cut").map((e) => e.frame)).toEqual([50]);
+ expect(of("hold").length).toBeGreaterThan(0);
+
+ const windows = lookWindows(found.events, info.fps);
+ expect(windows.map((w) => w.what[0]!.split(" ")[0])).toEqual(["appear", "flash", "cut"]);
+ expect(windows[1]!.onset_frames).toEqual([30]);
+ });
+});
+
+describe.skipIf(noTools)("extract", () => {
+ // Every frame's luma is 40 + 3 × its frame number, with B-frames so the first frame does not start at 0.
+ const video = noTools
+ ? ""
+ : clip("counter.mp4", [
+ ...[
+ "-f",
+ "lavfi",
+ "-i",
+ "nullsrc=s=64x36:r=25:d=2",
+ "-vf",
+ "geq=lum='40+3*N':cb=128:cr=128",
+ ],
+ ...["-pix_fmt", "yuv420p", "-c:v", "libx264", "-qp", "0", "-bf", "3"],
+ ]);
+ // Grey output is full range; the clip's luma is limited range (16–235).
+ const levelOf = (path: string) => {
+ const { frames } = readFrames(path, { gray: true });
+ return frames.map((f) =>
+ Math.round((((f.reduce((s, v) => s + v, 0) / f.length) * 219) / 255 + 16 - 40) / 3),
+ );
+ };
+
+ it("cuts the still shown at a time", async () => {
+ const out = join(dir, "still.png");
+ const r = await cutStill(probeVideo(video), 0.52, [8, 8, 32, 16], out);
+ expect(r.frame).toBe(13);
+ expect(levelOf(out)).toEqual([13]);
+ });
+
+ it("cuts a clip of exactly the frames in its window at 30 fps too", () => {
+ const thirty = clip("counter30.mp4", [
+ ...["-f", "lavfi", "-i", "nullsrc=s=64x36:r=30:d=4", "-vf", "geq=lum='40+3*N':cb=128:cr=128"],
+ ...["-pix_fmt", "yuv420p", "-c:v", "libx264", "-qp", "0", "-bf", "3"],
+ ]);
+ const out = join(dir, "clip30.mp4");
+ const r = cutClip(probeVideo(thirty), 31 / 30, 37 / 30, [0, 0, 32, 16], out, { crf: 0 });
+ expect(r.frames).toBe(6);
+ expect(levelOf(out)).toEqual([31, 32, 33, 34, 35, 36]);
+ });
+
+ it("cuts a clip of exactly the frames in its window", () => {
+ const out = join(dir, "clip.mp4");
+ const r = cutClip(probeVideo(video), 0.4, 0.8, [0, 0, 33, 17], out, { crf: 0 });
+ expect(r.frames).toBe(10);
+ expect(r.roi).toEqual([0, 0, 32, 16]);
+ expect(levelOf(out)).toEqual([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]);
+ });
+});
diff --git a/packages/cli/src/measure/events.ts b/packages/cli/src/measure/events.ts
new file mode 100644
index 0000000000..d7fe8c90dd
--- /dev/null
+++ b/packages/cli/src/measure/events.ts
@@ -0,0 +1,434 @@
+// When things change on screen (from the Studio's viral-clone events.mjs), by frame-to-frame grey difference in an ROI
+// or grid cells: cuts, flashes (frames that return to the picture before), appears and disappears, holds (0.3 s or
+// more) and other motion, by frame. The map adds the sound's onsets and beats and groups windows worth a close look.
+import { findCuts } from "./cuts.js";
+import { grey, readClip, round, videoClip, writeImage, type Roi, type VideoInfo } from "./media.js";
+
+// The width motion-rhythm reads motion at, so its still threshold carries over.
+const EVENT_W = 160;
+const CUT_SHARE = 0.7;
+const CUT_GRID = 4;
+const HOLD_S = 0.3;
+const STEP_MAX_S = 0.5;
+const FLASH_FRAMES = 2;
+const STRIP_MAX = 24;
+const STRIP_W = 1200;
+// Events closer than this share one window to look at, up to WINDOW_MAX_S: a talking head changes somewhere all
+// the time, and one 20 s window shows nothing frame by frame.
+const WINDOW_GAP_S = 0.25;
+const WINDOW_MAX_S = 1.5;
+
+/** A grid cell; rect is x0,y0,x1,y1 in working pixels, end exclusive. */
+interface Cell {
+ name: string;
+ rect: [number, number, number, number];
+}
+
+export type EventType = "cut" | "flash" | "appear" | "disappear" | "change" | "hold";
+
+export interface ScreenEvent {
+ type: EventType;
+ t: number;
+ frame: number;
+ frames?: number;
+ seconds?: number;
+ cells?: string[];
+ roi?: number[];
+ magnitude?: number;
+}
+
+/** An event with the frames and box its strip pair shows (working pixels). */
+interface Shown extends ScreenEvent {
+ before: number;
+ after: number;
+ rect: number[] | null;
+}
+
+function cells(cols: number, rows: number, w: number, h: number): Cell[] {
+ return Array.from({ length: rows * cols }, (_, i) => {
+ const [r, c] = [Math.floor(i / cols), i % cols];
+ return {
+ name: `r${r}c${c}`,
+ rect: [
+ Math.floor((c * w) / cols),
+ Math.floor((r * h) / rows),
+ Math.floor(((c + 1) * w) / cols),
+ Math.floor(((r + 1) * h) / rows),
+ ],
+ };
+ });
+}
+
+/** Mean absolute difference of two frames inside `rect`. */
+function diff(a: Uint8Array, b: Uint8Array, w: number, [x0, y0, x1, y1]: number[]): number {
+ let s = 0;
+ for (let y = y0!; y < y1!; y++)
+ for (let x = x0!; x < x1!; x++) s += Math.abs(a[y * w + x]! - b[y * w + x]!);
+ return s / Math.max(1, (x1! - x0!) * (y1! - y0!));
+}
+
+/** Mean and standard deviation of grey inside `rect`. */
+function level(f: Uint8Array, w: number, [x0, y0, x1, y1]: number[]) {
+ let [s, s2] = [0, 0];
+ for (let y = y0!; y < y1!; y++)
+ for (let x = x0!; x < x1!; x++) {
+ s += f[y * w + x]!;
+ s2 += f[y * w + x]! ** 2;
+ }
+ const n = Math.max(1, (x1! - x0!) * (y1! - y0!));
+ return { mean: s / n, std: Math.sqrt(Math.max(0, s2 / n - (s / n) ** 2)) };
+}
+
+/** Each frame's change from the one before inside `rect` (frame 0: 0). */
+const changes = (g: Uint8Array[], w: number, rect: number[]) =>
+ g.map((f, i) => (i ? diff(f, g[i - 1]!, w, rect) : 0));
+
+/** Runs of frames changing by over twice the series' 25th percentile and 2 grey levels; one quiet frame bridged. */
+function bursts(d: number[]): [number, number][] {
+ const q = d.slice(1).sort((a, b) => a - b);
+ const act = Math.max(2, 2 * (q[Math.floor(q.length / 4)] ?? 0));
+ const out: [number, number][] = [];
+ for (let i = 1; i < d.length; i++) {
+ if (d[i]! <= act) continue;
+ const last = out.at(-1);
+ if (last && i - last[1] <= 2) last[1] = i;
+ else out.push([i, i]);
+ }
+ return out;
+}
+
+/** Still runs of HOLD_S or more by motion-rhythm's still threshold: [first frame of the held picture, its frames]. */
+function stills(d: number[], fps: number): [number, number][] {
+ const q = d.slice(1).sort((a, b) => a - b);
+ const floor = Math.min(1.5, Math.max(0.5, 2 * (q[Math.floor(q.length / 10)] ?? 0)));
+ const out: [number, number][] = [];
+ for (let i = 1, run = 0; i <= d.length; i++) {
+ if (i < d.length && d[i]! <= floor) run++;
+ else {
+ if (run + 1 >= HOLD_S * fps) out.push([i - run - 1, run + 1]);
+ run = 0;
+ }
+ }
+ return out;
+}
+
+/** Joins items whose `near(a, b)` holds, transitively. */
+function groups(items: T[], near: (a: T, b: T) => boolean): T[][] {
+ const root = items.map((_, i) => i);
+ const find = (i: number): number => (root[i] === i ? i : (root[i] = find(root[i]!)));
+ for (let i = 0; i < items.length; i++)
+ for (let j = i + 1; j < items.length; j++)
+ if (near(items[i]!, items[j]!)) root[find(i)] = find(j);
+ const out = new Map();
+ items.forEach((it, i) => out.set(find(i), [...(out.get(find(i)) ?? []), it]));
+ return [...out.values()];
+}
+
+/**
+ * Frames where CUT_SHARE of the cells change by `thr` or more at once. Two such frames a frame or two apart whose
+ * second returns to the picture before the first are a flash, not two cuts.
+ */
+function cutFrames(g: Uint8Array[], w: number, cutCells: Cell[], thr: number) {
+ const d = cutCells.map((c) => changes(g, w, c.rect));
+ const hits = g
+ .map((_, i) => i)
+ .filter((i) => i > 0 && d.filter((x) => x[i]! >= thr).length >= CUT_SHARE * cutCells.length);
+ const cuts: [number, number][] = [];
+ const flashes: [number, number][] = [];
+ for (let k = 0; k < hits.length; k++) {
+ const [i, j] = [hits[k]!, hits[k + 1]];
+ const last = cuts.at(-1);
+ if (
+ j !== undefined &&
+ j - i <= FLASH_FRAMES &&
+ diff(g[j]!, g[i - 1]!, w, [0, 0, w, g[0]!.length / w]) < thr
+ ) {
+ flashes.push([i, j - 1]);
+ k++;
+ } else if (last && i === last[1] + 1)
+ last[1] = i; // a whip or a short dissolve: one cut over several frames
+ else cuts.push([i, i]);
+ }
+ return { cuts, flashes, d };
+}
+
+interface Burst {
+ ci: number;
+ c: Cell;
+ a: number;
+ b: number;
+ net: number;
+ peak: number;
+}
+
+/** Each region's bursts outside the cuts and flashes, split into steps, local flashes and other motion. */
+// fallow-ignore-next-line complexity
+function bursting(
+ g: Uint8Array[],
+ w: number,
+ regions: Cell[],
+ skip: (a: number, b: number) => boolean,
+ thr: number,
+ fps: number,
+) {
+ const settle = Math.round(HOLD_S * fps);
+ const steps: Burst[] = [];
+ const flashes: Burst[] = [];
+ const moves: Burst[] = [];
+ for (const [ci, c] of regions.entries()) {
+ const d = changes(g, w, c.rect);
+ for (const [a, b] of bursts(d)) {
+ if (skip(a, b)) continue;
+ const net = diff(g[b]!, g[a - 1]!, w, c.rect);
+ const peak = Math.max(...d.slice(a, b + 1));
+ const burst = { ci, c, a, b, net, peak };
+ // a flash lights up for a frame or two and the region returns to how it was
+ if (
+ b - a + 1 <= FLASH_FRAMES &&
+ peak >= 2 * thr &&
+ b + 1 < g.length &&
+ diff(g[b + 1]!, g[a - 1]!, w, c.rect) < thr
+ ) {
+ flashes.push(burst);
+ continue;
+ }
+ // a step joins two looks that each last: the region moves under a third as much in the 0.3 s either side
+ const was = diff(g[a - 1]!, g[Math.max(0, a - 1 - settle)]!, w, c.rect);
+ const now = diff(g[b]!, g[Math.min(g.length - 1, b + settle)]!, w, c.rect);
+ const step = net >= thr && b - a + 1 <= STEP_MAX_S * fps && Math.max(was, now) <= net / 3;
+ (step ? steps : moves).push(burst);
+ }
+ }
+ return { steps, flashes, moves };
+}
+
+export interface DetectOptions {
+ info: VideoInfo;
+ start: number;
+ end: number;
+ /** One region, or (when `grid` is given) the whole frame split into cells. */
+ roi: Roi;
+ grid?: { cols: number; rows: number };
+ thr?: number;
+}
+
+export interface Detected {
+ fps: number;
+ frames: number;
+ events: ScreenEvent[];
+ /** Working-size RGB frames and the events a strip should show, for drawing. */
+ rgb: Uint8Array[];
+ w: number;
+ h: number;
+ shown: Shown[];
+}
+
+/** Every cut, flash, step, change and hold of a window of a video. */
+export function detectEvents(opts: DetectOptions): Detected {
+ const { info, start, end, roi, grid } = opts;
+ const thr = opts.thr ?? 5;
+ const fps = info.fps;
+ const whole: Roi = [0, 0, info.width, info.height];
+ const sameAsWhole = roi.every((v, i) => v === whole[i]);
+ const clip = videoClip(info.path, start, end - start, info);
+ const { frames: rgb, w, h } = readClip(clip, { roi, width: EVENT_W });
+ const g = rgb.map(grey);
+ const wholeG = sameAsWhole ? g : readClip(clip, { width: EVENT_W, gray: true }).frames;
+ const wholeH = wholeG[0] ? wholeG[0].length / EVENT_W : h;
+ const f0 = Math.ceil(start * fps - 1e-6);
+ const at = (i: number) => ({ frame: f0 + i, t: round((f0 + i) / fps, 3) });
+ if (g.length < 3) return { fps, frames: g.length, events: [], rgb, w, h, shown: [] };
+
+ // Cuts are read on the whole frame: the grid's own cells, or with an ROI a 4x4 grid of the whole frame.
+ const cutCells = cells(grid?.cols ?? CUT_GRID, grid?.rows ?? CUT_GRID, EVENT_W, wholeH);
+ const cut = cutFrames(wholeG, EVENT_W, cutCells, thr);
+ // A fast handheld move or whip changes most cells on frame after frame: motion, not a run of cuts. A cut is one
+ // the brightness test diff uses also finds (cuts.ts), or a change that stands alone in time.
+ const real = new Set(
+ findCuts(wholeG).flatMap((c) => Array.from({ length: c.frames }, (_, i) => c.frame + i)),
+ );
+ const alone = ([i, j]: [number, number]) =>
+ j === i && cut.cuts.every(([a, b]) => (a === i && b === j) || b < i - 3 || a > j + 3);
+ cut.cuts = cut.cuts.filter((c) => real.has(c[0]) || alone(c));
+ const single: Cell = { name: "roi", rect: [0, 0, w, h] };
+ const regions = grid ? cells(grid.cols, grid.rows, w, h) : [single];
+ const covered = (a: number, b: number) =>
+ [...cut.cuts, ...cut.flashes].some(([x, y]) => x <= b && a <= y);
+ const { steps, flashes, moves } = bursting(g, w, regions, covered, thr, fps);
+ const cols = grid?.cols ?? 1;
+ const touching = (s: Burst, o: Burst) =>
+ Math.abs(Math.floor(s.ci / cols) - Math.floor(o.ci / cols)) <= 1 &&
+ Math.abs((s.ci % cols) - (o.ci % cols)) <= 1;
+ const overlap = (s: Burst, o: Burst) => s.a <= o.b + 2 && o.a <= s.b + 2;
+ const [kx, ky] = [roi[2] / w, roi[3] / h];
+ const event = (grp: Burst[], type: EventType, size: number): Shown => {
+ const [a, b] = [Math.min(...grp.map((s) => s.a)), Math.max(...grp.map((s) => s.b))];
+ const rect = [0, 1, 2, 3].map((k) =>
+ (k < 2 ? Math.min : Math.max)(...grp.map((s) => s.c.rect[k]!)),
+ );
+ const where = grid
+ ? {
+ cells: [...new Set(grp.map((s) => s.c.name))].sort(),
+ roi: [
+ rect[0]! * kx + roi[0],
+ rect[1]! * ky + roi[1],
+ (rect[2]! - rect[0]!) * kx,
+ (rect[3]! - rect[1]!) * ky,
+ ].map(Math.round),
+ }
+ : {};
+ return {
+ type,
+ ...at(a),
+ frames: b - a + 1,
+ ...where,
+ magnitude: round(size, 1),
+ before: a - 1,
+ after: b,
+ rect: grid ? rect : null,
+ };
+ };
+ const stepEvents = groups(steps, (s, o) => overlap(s, o) && touching(s, o)).map((grp) => {
+ const e = event(grp, "change", grp.reduce((m, s) => m + s.net, 0) / grp.length);
+ const box = e.rect ?? [0, 0, w, h];
+ const [was, now] = [level(g[e.before]!, w, box), level(g[e.after]!, w, box)];
+ const up = Math.abs(now.std - was.std) >= 2 ? now.std > was.std : now.mean > was.mean;
+ return { ...e, type: up ? ("appear" as const) : ("disappear" as const) };
+ });
+ const flashEvents = [
+ ...groups(flashes, (s, o) => overlap(s, o) && touching(s, o)).map((grp) =>
+ event(grp, "flash", Math.max(...grp.map((s) => s.peak))),
+ ),
+ ...cut.flashes.map(([i, j]) => ({
+ type: "flash" as const,
+ ...at(i),
+ frames: j - i + 1,
+ magnitude: round(cut.d.reduce((m, d) => m + d[i]!, 0) / cut.d.length, 1),
+ before: i - 1,
+ after: i,
+ rect: null,
+ })),
+ ];
+ const moveEvents = groups(moves, overlap).map((grp) =>
+ event(grp, "change", Math.max(...grp.map((s) => s.peak))),
+ );
+ const cutEvents: Shown[] = cut.cuts.map(([i, j]) => ({
+ type: "cut",
+ ...at(i),
+ ...(j > i ? { frames: j - i + 1 } : {}),
+ magnitude: round(cut.d.reduce((m, d) => m + d[i]!, 0) / cut.d.length, 1),
+ before: i - 1,
+ after: j,
+ rect: null,
+ }));
+ const still = changes(grid ? wholeG : g, EVENT_W, [0, 0, EVENT_W, grid ? wholeH : h]);
+ const held: ScreenEvent[] = stills(still, fps).map(([i, n]) => ({
+ type: "hold",
+ ...at(i),
+ seconds: round(n / fps, 2),
+ }));
+
+ // The strip keeps the biggest: cuts and flashes, then steps by cells × magnitude, then changes by magnitude.
+ const weight = (e: Shown) => (e.cells?.length ?? 1) * (e.magnitude ?? 0);
+ const order = (x: ScreenEvent, y: ScreenEvent) => x.frame - y.frame;
+ const shown = [
+ ...cutEvents,
+ ...flashEvents,
+ ...[...stepEvents].sort((x, y) => weight(y) - weight(x)),
+ ...[...moveEvents].sort((x, y) => (y.magnitude ?? 0) - (x.magnitude ?? 0)),
+ ]
+ .slice(0, STRIP_MAX)
+ .sort(order);
+ const plain = ({ before: _b, after: _a, rect: _r, ...e }: Shown): ScreenEvent => e;
+ const events = [...cutEvents, ...flashEvents, ...stepEvents, ...moveEvents].map(plain);
+ return { fps, frames: g.length, events: [...events, ...held].sort(order), rgb, w, h, shown };
+}
+
+/** One picture of each shown event's before|after pair, its region boxed in red. */
+export function drawStrip(d: Detected, out: string): string {
+ const { rgb, w, h, shown } = d;
+ const per = Math.max(1, Math.floor(STRIP_W / (2 * w + 12)));
+ const cw = per * (2 * w + 12);
+ const ch = Math.ceil(shown.length / per) * (h + 8);
+ const px = new Uint8Array(cw * ch * 3).fill(255);
+ shown.forEach((e, k) => {
+ const [ox, oy] = [(k % per) * (2 * w + 12), Math.floor(k / per) * (h + 8)];
+ [e.before, e.after].forEach((f, side) => {
+ const x0 = ox + side * (w + 2);
+ for (let y = 0; y < h; y++)
+ px.set(rgb[f]!.subarray(y * w * 3, (y + 1) * w * 3), ((oy + y) * cw + x0) * 3);
+ if (!e.rect) return;
+ const [rx0, ry0, rx1, ry1] = e.rect;
+ for (let y = ry0!; y < ry1!; y++)
+ for (let x = rx0!; x < rx1!; x++)
+ if (y === ry0 || y === ry1! - 1 || x === rx0 || x === rx1! - 1)
+ px.set([255, 0, 0], ((oy + y) * cw + x0 + x) * 3);
+ });
+ });
+ return writeImage(out, px, cw, ch);
+}
+
+export interface LookWindow {
+ start: number;
+ end: number;
+ /** What happens, e.g. "cut", "appear r1c2,r1c3", "flash 1f". */
+ what: string[];
+ /** Sound onsets inside the window, seconds. */
+ onsets?: number[];
+ /** The frames its events start on: a strip of the window must show these. */
+ onset_frames: number[];
+}
+
+/** Every event but holds, merged into the windows worth looking at frame by frame, two frames padded either side. */
+export function lookWindows(
+ events: ScreenEvent[],
+ fps: number,
+ onsets: number[] = [],
+): LookWindow[] {
+ const pad = 2 / fps;
+ const spans = events
+ .filter((e) => e.type !== "hold")
+ .map((e) => {
+ const where = e.cells ? ` ${e.cells.join(",")}` : "";
+ const len = e.type === "flash" ? ` ${e.frames}f` : "";
+ return {
+ a: e.t - pad,
+ b: e.t + ((e.frames ?? 1) - 1) / fps + pad,
+ what: `${e.type}${where}${len}`,
+ frame: e.frame,
+ };
+ })
+ .sort((x, y) => x.a - y.a);
+ const out: Omit[] = [];
+ for (const s of spans) {
+ const last = out.at(-1);
+ if (last && s.a - last.end <= WINDOW_GAP_S && s.b - last.start <= WINDOW_MAX_S) {
+ last.end = Math.max(last.end, s.b);
+ last.what.push(s.what);
+ last.onset_frames.push(s.frame);
+ } else out.push({ start: s.a, end: s.b, what: [s.what], onset_frames: [s.frame] });
+ }
+ return out.map((wnd) => {
+ const hits = onsets.filter((t) => t >= wnd.start && t <= wnd.end);
+ return {
+ start: round(Math.max(0, wnd.start), 3),
+ end: round(wnd.end, 3),
+ what: wnd.what,
+ ...(hits.length ? { onsets: hits.map((t) => round(t, 3)) } : {}),
+ onset_frames: [...new Set(wnd.onset_frames)].sort((x, y) => x - y),
+ };
+ });
+}
+
+/** How many of each type, for a summary line. */
+export function countEvents(events: ScreenEvent[]): Record {
+ const count = (type: EventType) => events.filter((e) => e.type === type).length;
+ return {
+ cut: count("cut"),
+ flash: count("flash"),
+ appear: count("appear"),
+ disappear: count("disappear"),
+ change: count("change"),
+ hold: count("hold"),
+ };
+}
diff --git a/packages/cli/src/measure/face.test.ts b/packages/cli/src/measure/face.test.ts
new file mode 100644
index 0000000000..9f012f3d9d
--- /dev/null
+++ b/packages/cli/src/measure/face.test.ts
@@ -0,0 +1,149 @@
+import { execFileSync } from "node:child_process";
+import { cpSync, existsSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir, userInfo } from "node:os";
+import { join } from "node:path";
+import { afterAll, describe, expect, it } from "vitest";
+import { findFFmpeg, findFFprobe } from "../browser/ffmpeg.js";
+import { againstStart, faceBoxes, faceFit, minWindow, readSamples, sampleFrames } from "./face.js";
+import { probeVideo, runFfmpeg } from "./media.js";
+import { OPENCV_DIR } from "./opencv.js";
+
+// As in opencv.test.ts: borrow this machine's verified opencv.js cache, skip without one.
+const cached = join(userInfo().homedir, ".cache", "hyperframes", "opencv", "4.10.0");
+if (existsSync(join(cached, "opencv.js")) && !existsSync(join(OPENCV_DIR, "opencv.js")))
+ cpSync(cached, OPENCV_DIR, { recursive: true });
+const media = !!findFFmpeg() && !!findFFprobe();
+const opencv = media && existsSync(join(OPENCV_DIR, "opencv.js"));
+const dir = mkdtempSync(join(tmpdir(), "hf-face-test-"));
+afterAll(() => rmSync(dir, { recursive: true, force: true }));
+
+describe("sampleFrames", () => {
+ it("spreads the samples evenly, the last frame included, each once", () => {
+ expect(sampleFrames(30, 0, 1, 4)).toEqual([0, 10, 19, 29]);
+ expect(sampleFrames(30, 2, 2.1, 12)).toEqual([60, 61, 62]);
+ expect(sampleFrames(24, 1, 1.01, 8)).toEqual([24]);
+ });
+});
+
+describe("minWindow", () => {
+ it("is a step of the cascades' 20 px x 1.1 ladder, no larger than the share", () => {
+ expect(minWindow(1280, 0)).toBe(20);
+ expect(minWindow(400, 0.04)).toBe(20);
+ // 4% of 1280 is 51.2 px: 20 x 1.1^9 = 47.2 is the last step under it.
+ expect(minWindow(1280, 0.04)).toBe(47);
+ expect(minWindow(1080, 0.04)).toBe(43);
+ });
+});
+
+describe("againstStart", () => {
+ it("reads a generated shot from its own start and a full render on film time", () => {
+ // A 5.2 s HeyGen shot for the original's 9.5-12.27 s: its face is at 0-2.77 s of the clip, not 9.5.
+ expect(againstStart(5.17, 12.27, 9.5)).toBe(0);
+ // A shot longer than the window but shorter than the film is still its own clip.
+ expect(againstStart(7.29, 12.27, 2.77)).toBe(0);
+ expect(againstStart(12.27, 12.27, 9.5)).toBe(9.5);
+ expect(againstStart(12.3, 12.27, 9.5)).toBe(9.5);
+ });
+});
+
+describe("faceFit", () => {
+ const at = (t: number, ...boxes: number[][]) => ({ t, boxes });
+ const canvas = { width: 720, height: 1280 };
+
+ it("gives the scale about the centre and the x, y that land the clip's face on the original's", () => {
+ // The clip's face, 0.1 high at (0.5, 0.4); the original's twice the size, 10 px right and 20 px up of where
+ // scaling about the centre puts it: centre y 640 + 2 (512 - 640) - 20 = 364.
+ const clip = [0, 0.5, 1, 1.5].map((t) => at(t, [0.45, 0.35, 0.1, 0.1]));
+ const [w, h] = [0.2, 0.2];
+ const [cx, cy] = [(360 + 10) / 720, 364 / 1280];
+ const original = [0, 0.5, 1, 1.5].map((t) =>
+ at(t, [cx - w / 2, cy - h / 2, w, h], [0.05, 0.05, 0.03, 0.03]),
+ );
+ const fit = faceFit(original, clip, canvas, canvas);
+ expect(fit.moments).toBe(4);
+ expect(fit.transform).toEqual({ scale: 2, x: 10, y: -20 });
+ expect(fit.residual).toBe(0);
+ });
+
+ it("fits a clip of another size through object-fit: cover, and shrugs off a stray moment", () => {
+ // 768x1344 under a 720x1280 canvas: cover scales it by 1280/1344 and crops its sides; its face then sits
+ // where the original's is, at the same height, so nothing moves.
+ const s0 = 1280 / 1344;
+ const ox = (720 - 768 * s0) / 2;
+ const [fx, fy, fh] = [360, 500, 200];
+ const clipBox = [
+ (fx - ox - fh / 2) / (768 * s0),
+ (fy - fh / 2) / 1280,
+ fh / (768 * s0),
+ fh / 1280,
+ ];
+ const origBox = [(fx - fh / 2) / 720, (fy - fh / 2) / 1280, fh / 720, fh / 1280];
+ const clip = [0, 0.25, 0.5, 0.75, 1].map((t) => at(t, clipBox));
+ const original = [0, 0.25, 0.5, 0.75, 1].map((t, i) =>
+ at(t + 0.02, i === 2 ? [0.1, 0.1, 0.4, 0.4] : origBox),
+ );
+ const fit = faceFit(original, clip, canvas, { width: 768, height: 1344 });
+ expect(fit.transform).toEqual({ scale: 1, x: 0, y: 0 });
+ });
+
+ it("gives no transform without faces on both sides at enough moments", () => {
+ const fit = faceFit(
+ [at(0, [0.4, 0.3, 0.2, 0.1]), at(1)],
+ [at(0, [0.4, 0.3, 0.2, 0.1]), at(1, [0.4, 0.3, 0.2, 0.1])],
+ canvas,
+ canvas,
+ );
+ expect(fit).toEqual({ moments: 1, transform: null });
+ // Moments farther apart than a tenth of a second do not pair.
+ expect(
+ faceFit(
+ [at(0, [0.4, 0.3, 0.2, 0.1]), at(1, [0.4, 0.3, 0.2, 0.1])],
+ [at(0.5, [0.4, 0.3, 0.2, 0.1]), at(1.5, [0.4, 0.3, 0.2, 0.1])],
+ canvas,
+ canvas,
+ ).transform,
+ ).toBeNull();
+ });
+});
+
+describe.skipIf(!media)("readSamples", () => {
+ // Every frame different, keyframes 2.5 s apart and B-frames: what a seek has to get right.
+ const video = join(dir, "frames.mp4");
+ if (media)
+ execFileSync(findFFmpeg()!, [
+ ...["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=s=160x96:r=30:d=8"],
+ ...["-c:v", "libx264", "-g", "75", "-bf", "2", "-pix_fmt", "yuv420p", video],
+ ]);
+
+ it("seeks to the same frames that decoding from the start picks", () => {
+ const info = probeVideo(video);
+ // Nearby samples (one pass) and samples seconds apart (a seek each), off and on keyframes.
+ const ks = [1, 2, 40, 74, 75, 76, 140, 141, 210, 239];
+ const got = readSamples(info, ks, 80, 48);
+ const raw = runFfmpeg([
+ ...["-i", video, "-an", "-vf"],
+ `select=${ks.map((k) => `eq(n\\,${k})`).join("+")},scale=80:48,format=gray`,
+ ...["-fps_mode", "passthrough", "-f", "rawvideo", "-"],
+ ]);
+ expect(got).toHaveLength(ks.length);
+ got.forEach((f, i) =>
+ expect(Buffer.compare(f, raw.subarray(i * 80 * 48, (i + 1) * 80 * 48))).toBe(0),
+ );
+ });
+});
+
+describe.skipIf(!opencv)("faceBoxes", () => {
+ const video = join(dir, "blank.mp4");
+ if (opencv)
+ execFileSync(findFFmpeg()!, [
+ ...["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=0x406080:s=320x568:r=30:d=4"],
+ ...["-c:v", "libx264", "-pix_fmt", "yuv420p", video],
+ ]);
+
+ it("labels every sampled frame and finds no face in a blank one", async () => {
+ const r = await faceBoxes(probeVideo(video), 1, 3, 5);
+ expect(r.map((s) => s.frame)).toEqual([30, 45, 60, 74, 89]);
+ expect(r.map((s) => s.t)).toEqual([1, 1.5, 2, 2.467, 2.967]);
+ expect(r.every((s) => s.boxes.length === 0)).toBe(true);
+ });
+});
diff --git a/packages/cli/src/measure/face.ts b/packages/cli/src/measure/face.ts
new file mode 100644
index 0000000000..7d185613f0
--- /dev/null
+++ b/packages/cli/src/measure/face.ts
@@ -0,0 +1,249 @@
+// How big the face is and where, ported from hf-media's face_size: OpenCV's frontal and profile Haar cascades on
+// evenly spaced frames, graded by face height over frame height. A regenerated presenter keeps the likeness from
+// FACE_HOLDS up; below FACE_FLOOR a video model cannot carry one at all (the harness's face-size eval, 2026-10-08).
+import { frameAt, round, runFfmpeg, type VideoInfo } from "./media.js";
+import { greyMat, loadOpenCv } from "./opencv.js";
+
+const FACE_HOLDS = 0.25;
+const FACE_SLIDES = 0.15;
+const FACE_FLOOR = 0.06;
+/**
+ * The smallest face looked for by default, as a share of the frame's height: well under FACE_FLOOR, and it skips the
+ * cascades' costliest windows. A minimum on their ladder keeps the full search's boxes; scaling the frame moves them.
+ */
+const FACE_MIN = 0.04;
+const WORK_W = 960;
+const STEP = 1.1;
+const WINDOW_PX = 20;
+// Samples closer than this share one decode from the first of them; farther ones get a seek of their own.
+const RUN_S = 2;
+
+type Verdict = "pass" | "warn" | "fail" | "unmeasured";
+const ORDER: Verdict[] = ["fail", "unmeasured", "warn", "pass"];
+
+export function faceVerdict(height: number | null, cast = false): Verdict {
+ if (height === null) return "unmeasured";
+ if (height >= FACE_HOLDS) return "pass";
+ return height < (cast ? FACE_SLIDES : FACE_FLOOR) ? "fail" : "warn";
+}
+
+/** `samples` frame indices spread evenly over [start, end), the last frame included. */
+export function sampleFrames(fps: number, start: number, end: number, samples: number): number[] {
+ const k0 = frameAt(start, fps);
+ const k1 = Math.max(k0, Math.ceil(end * fps - 1e-6) - 1);
+ const n = Math.min(samples, k1 - k0 + 1);
+ return [
+ ...new Set(
+ Array.from({ length: n }, (_, i) => k0 + Math.round((i * (k1 - k0)) / Math.max(1, n - 1))),
+ ),
+ ];
+}
+
+/** The largest window on the cascades' 20 px x 1.1^k ladder that is no more than `share` of a frame `h` high. */
+export function minWindow(h: number, share: number): number {
+ const steps = Math.floor(Math.log(Math.max(1, (share * h) / WINDOW_PX)) / Math.log(STEP) + 1e-9);
+ return Math.round(WINDOW_PX * STEP ** steps);
+}
+
+/** Frames `ks` (indices from the first) as grey bytes at `w` x `h`, keeping the video's aspect. Each run of nearby
+ * frames is one ffmpeg pass from its first frame to its last; a variable-rate video, which a seek can't index, is read
+ * from its start. */
+export function readSamples(info: VideoInfo, ks: number[], w: number, h: number): Uint8Array[] {
+ const runs: number[][] = [];
+ for (const k of ks) {
+ const run = runs.at(-1);
+ if (run && (info.vfr || (k - run.at(-1)!) / info.fps <= RUN_S)) run.push(k);
+ else runs.push([k]);
+ }
+ const size = w * h;
+ return runs.flatMap((run) => {
+ // Half a frame early: an input seek drops the frames before it, so the first one left is frame run[0].
+ const k0 = info.vfr ? 0 : run[0]!;
+ const seek = k0 > 0 ? ["-ss", ((k0 - 0.5) / info.fps).toFixed(6)] : [];
+ const filters = [
+ `select=${run.map((k) => `eq(n\\,${k - k0})`).join("+")}`,
+ ...(w !== info.width || h !== info.height ? [`scale=${w}:${h}`] : []),
+ "format=gray",
+ ];
+ const raw = runFfmpeg([
+ ...seek,
+ "-i",
+ info.path,
+ "-an",
+ "-vf",
+ filters.join(","),
+ "-fps_mode",
+ "passthrough",
+ "-frames:v",
+ String(run.length),
+ "-f",
+ "rawvideo",
+ "-",
+ ]);
+ const frames: Uint8Array[] = [];
+ for (let i = 0; i + size <= raw.length; i += size) frames.push(raw.subarray(i, i + size));
+ return frames;
+ });
+}
+
+/**
+ * Each sampled frame's faces as [x, y, w, h] shares of the frame. `minFace` is the smallest face looked for as a
+ * share of the frame's height (default FACE_MIN; 0 looks down to the cascades' 20 px, for crowds).
+ */
+export async function faceBoxes(
+ info: VideoInfo,
+ start: number,
+ end: number,
+ samples: number,
+ opts: { minFace?: number } = {},
+) {
+ const cv = await loadOpenCv((m) => console.error(m));
+ const ks = sampleFrames(info.fps, start, end, samples);
+ const w = Math.min(WORK_W, info.width);
+ const h =
+ w === info.width
+ ? info.height
+ : Math.max(2, Math.round((info.height * w) / info.width / 2) * 2);
+ const frames = readSamples(info, ks, w, h);
+ const min = minWindow(h, opts.minFace ?? FACE_MIN);
+ const cascades = ["haarcascade_frontalface_alt2.xml", "haarcascade_profileface.xml"].map(
+ (name) => {
+ const c = new cv.CascadeClassifier();
+ c.load(name);
+ return c;
+ },
+ );
+ try {
+ return frames.map((px, i) => {
+ const gray = greyMat(cv, px, w, h);
+ const boxes: number[][] = [];
+ try {
+ for (const c of cascades) {
+ const found = new cv.RectVector();
+ c.detectMultiScale(gray, found, STEP, 5, 0, new cv.Size(min, min));
+ for (let j = 0; j < found.size(); j++) {
+ const r = found.get(j);
+ boxes.push([r.x / w, r.y / h, r.width / w, r.height / h]);
+ }
+ found.delete();
+ }
+ } finally {
+ gray.delete();
+ }
+ return { frame: ks[i]!, t: round(ks[i]! / info.fps, 3), boxes };
+ });
+ } finally {
+ for (const c of cascades) c.delete();
+ }
+}
+
+/** The subject's face among a frame's: the largest, or the smallest when the person is cast in a crowd. */
+function subjectFace(boxes: number[][], cast = false): number[] | null {
+ return boxes.reduce(
+ (a, b) => (!a || (cast ? b[3]! < a[3]! : b[3]! > a[3]!) ? b : a),
+ null,
+ );
+}
+
+/** The subject's face (largest, or the smallest when the person is cast in a crowd), its median and last height. */
+export function faceSummary(
+ samples: { frame: number; t: number; boxes: number[][] }[],
+ cast = false,
+) {
+ const pick = (boxes: number[][]) => subjectFace(boxes, cast);
+ const seen = samples.flatMap((s) => {
+ const b = pick(s.boxes);
+ return b ? [{ t: s.t, box: b.map((v) => round(v, 4)) }] : [];
+ });
+ const heights = seen.map((s) => s.box[3]!).sort((a, b) => a - b);
+ const height = heights.length ? heights[heights.length >> 1]! : null;
+ const lastFace = pick(samples.at(-1)?.boxes ?? []);
+ const last = lastFace ? lastFace[3]! : null;
+ const verdicts = [faceVerdict(height, cast), faceVerdict(last, cast)];
+ return {
+ frames_sampled: samples.length,
+ frames_with_face: seen.length,
+ face_height: height === null ? null : round(height, 3),
+ last_face_height: last === null ? null : round(last, 3),
+ verdict: verdicts.reduce((a, b) => (ORDER.indexOf(b) < ORDER.indexOf(a) ? b : a)),
+ bands: { pass: FACE_HOLDS, cast_fail_below: FACE_SLIDES, fail_below: FACE_FLOOR },
+ boxes: seen,
+ ...(last === null
+ ? {
+ note: "no face at the last sampled frame (turned away, covered or missed): look at the frames",
+ }
+ : {}),
+ };
+}
+
+const median = (v: number[]) => [...v].sort((x, y) => x - y)[v.length >> 1]!;
+
+/** Fewest moments with a face on both sides that a fit is given from. */
+export const FIT_MIN_FACES = 2;
+const PAIR_S = 0.1;
+
+/**
+ * Where --against starts reading the clip: a render as long as the original runs on film time, so at --from; a
+ * shot of its own (a generated clip) starts at its own 0.
+ */
+export function againstStart(clipDuration: number, originalDuration: number, from: number): number {
+ return Math.abs(clipDuration - originalDuration) <= 0.5 ? from : 0;
+}
+
+/** The GSAP transform putting a cover-fit clip's face on the original's: `scale` about the clip's centre, then `x`, `y`
+ * in canvas pixels. Moments pair by time within PAIR_S and each side's faces are medianed, so one stray detection can't
+ * move it. `residual` is the median distance left between the faces, in the original's face heights. */
+export function faceFit(
+ original: { t: number; boxes: number[][] }[],
+ clip: { t: number; boxes: number[][] }[],
+ canvas: { width: number; height: number },
+ clipSize: { width: number; height: number },
+ cast = false,
+) {
+ const pairs = original.flatMap((o) => {
+ const near = clip.reduce<(typeof clip)[number] | null>(
+ (p, q) => (!p || Math.abs(q.t - o.t) < Math.abs(p.t - o.t) ? q : p),
+ null,
+ );
+ if (!near || Math.abs(near.t - o.t) > PAIR_S) return [];
+ const [a, b] = [subjectFace(o.boxes, cast), subjectFace(near.boxes, cast)];
+ return a && b ? [{ a, b }] : [];
+ });
+ if (pairs.length < FIT_MIN_FACES) return { moments: pairs.length, transform: null };
+ const { width: W, height: H } = canvas;
+ // object-fit: cover, centred: the clip's pixel (u, v) lands on the canvas at (ox + u s0, oy + v s0).
+ const s0 = Math.max(W / clipSize.width, H / clipSize.height);
+ const [cw, ch] = [clipSize.width * s0, clipSize.height * s0];
+ const [ox, oy] = [(W - cw) / 2, (H - ch) / 2];
+ const face = (b: number[], w: number, h: number, x0: number, y0: number) => ({
+ x: x0 + (b[0]! + b[2]! / 2) * w,
+ y: y0 + (b[1]! + b[3]! / 2) * h,
+ h: b[3]! * h,
+ });
+ const os = pairs.map((p) => face(p.a, W, H, 0, 0));
+ const cs = pairs.map((p) => face(p.b, cw, ch, ox, oy));
+ const mid = (v: { x: number; y: number; h: number }[]) => ({
+ x: median(v.map((f) => f.x)),
+ y: median(v.map((f) => f.y)),
+ h: median(v.map((f) => f.h)),
+ });
+ const [o, c] = [mid(os), mid(cs)];
+ const scale = o.h / c.h;
+ // About the element's centre (GSAP's default transform origin): p -> centre + scale (p - centre) + (x, y).
+ const x = o.x - (W / 2 + scale * (c.x - W / 2));
+ const y = o.y - (H / 2 + scale * (c.y - H / 2));
+ const residual = median(
+ pairs.map((_, i) => {
+ const [p, q] = [os[i]!, cs[i]!];
+ const [mx, my] = [W / 2 + scale * (q.x - W / 2) + x, H / 2 + scale * (q.y - H / 2) + y];
+ return Math.hypot(mx - p.x, my - p.y) / p.h;
+ }),
+ );
+ return {
+ moments: pairs.length,
+ transform: { scale: round(scale, 3), x: round(x, 1), y: round(y, 1) },
+ original_face: { centre: [round(o.x, 1), round(o.y, 1)], height: round(o.h, 1) },
+ clip_face: { centre: [round(c.x, 1), round(c.y, 1)], height: round(c.h, 1) },
+ residual: round(residual, 3),
+ };
+}
diff --git a/packages/cli/src/measure/faceVerdict.test.ts b/packages/cli/src/measure/faceVerdict.test.ts
new file mode 100644
index 0000000000..b2921815b5
--- /dev/null
+++ b/packages/cli/src/measure/faceVerdict.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from "vitest";
+import { faceSummary, faceVerdict } from "./face.js";
+
+describe("faces", () => {
+ it("grades the subject's face by its height", () => {
+ expect(faceVerdict(0.3)).toBe("pass");
+ expect(faceVerdict(0.1)).toBe("warn");
+ expect(faceVerdict(0.1, true)).toBe("fail");
+ expect(faceVerdict(null)).toBe("unmeasured");
+ const r = faceSummary([
+ {
+ frame: 0,
+ t: 0,
+ boxes: [
+ [0.4, 0.2, 0.2, 0.3],
+ [0.1, 0.1, 0.05, 0.08],
+ ],
+ },
+ { frame: 5, t: 0.2, boxes: [] },
+ ]);
+ expect(r.face_height).toBe(0.3);
+ expect(r.verdict).toBe("unmeasured");
+ });
+});
diff --git a/packages/cli/src/measure/look.ts b/packages/cli/src/measure/look.ts
new file mode 100644
index 0000000000..112318bbaf
--- /dev/null
+++ b/packages/cli/src/measure/look.ts
@@ -0,0 +1,87 @@
+// The look of a stretch of film as numbers, ported from the Studio's look-stats.mjs: mean luma and contrast
+// (0–255), mean saturation (0–1, HSV), the share of black-and-white frames (under 2% of mid-tone pixels carry
+// colour, so a colour face in a white room is not black and white) and warmth (mean R − B, negative is cool).
+import { ratioOf, readClip, round, type Clip, type Roi } from "./media.js";
+
+// Under these a frame has no light, contrast or colour to speak of, on the scales above.
+const LOOK_FLOOR = { luma: 1, contrast: 1, saturation: 0.01 };
+
+export interface Look {
+ frames: number;
+ luma: number;
+ contrast: number;
+ saturation: number;
+ bw_share: number;
+ warmth: number;
+}
+
+/** Sampled at `fps`, 160 px wide; `roi` measures one region, e.g. a person. */
+export function look(clip: Clip, fps = 2, roi?: Roi): Look {
+ const { frames } = readClip(clip, { fps, width: 160, roi });
+ const per = frames.map((f) => {
+ let [l, l2, s, warm, mid, tinted] = [0, 0, 0, 0, 0, 0];
+ const n = f.length / 3;
+ for (let i = 0; i < f.length; i += 3) {
+ const [r, g, b] = [f[i]!, f[i + 1]!, f[i + 2]!];
+ const y = 0.299 * r + 0.587 * g + 0.114 * b;
+ const [mx, mn] = [Math.max(r, g, b), Math.min(r, g, b)];
+ l += y;
+ l2 += y * y;
+ s += mx ? (mx - mn) / mx : 0;
+ warm += r - b;
+ if (y > 40 && y < 220) {
+ mid++;
+ if (mx - mn > 25) tinted++;
+ }
+ }
+ const mean = l / n;
+ return {
+ luma: mean,
+ contrast: Math.sqrt(Math.max(0, l2 / n - mean * mean)),
+ sat: s / n,
+ warm: warm / n,
+ bw: tinted < 0.02 * Math.max(1, mid),
+ };
+ });
+ const avg = (k: "luma" | "contrast" | "sat" | "warm") =>
+ per.reduce((a, p) => a + p[k], 0) / (per.length || 1);
+ return {
+ frames: per.length,
+ luma: round(avg("luma"), 1),
+ contrast: round(avg("contrast"), 1),
+ saturation: round(avg("sat"), 3),
+ bw_share: round(per.filter((p) => p.bw).length / (per.length || 1), 2),
+ warmth: round(avg("warm"), 1),
+ };
+}
+
+export interface LookComparison {
+ luma_ratio: number;
+ contrast_ratio: number;
+ saturation_ratio: number;
+ bw_share_diff: number;
+ warmth_diff: number;
+}
+
+/** Yours over the reference's: ratios near 1 and differences near 0 are the same look. */
+export function compareLook(ref: Look, yours: Look): LookComparison {
+ const ratio = (k: "luma" | "contrast" | "saturation") =>
+ round(ratioOf(yours[k], ref[k], LOOK_FLOOR[k]), 2);
+ return {
+ luma_ratio: ratio("luma"),
+ contrast_ratio: ratio("contrast"),
+ saturation_ratio: ratio("saturation"),
+ bw_share_diff: round(yours.bw_share - ref.bw_share, 2),
+ warmth_diff: round(yours.warmth - ref.warmth, 1),
+ };
+}
+
+/** The same look within a regenerated shot's tolerance (to be calibrated on the bench). */
+export function sameLook(c: LookComparison): boolean {
+ return (
+ Math.abs(c.luma_ratio - 1) <= 0.15 &&
+ Math.abs(c.contrast_ratio - 1) <= 0.25 &&
+ Math.abs(c.saturation_ratio - 1) <= 0.25 &&
+ Math.abs(c.warmth_diff) <= 12
+ );
+}
diff --git a/packages/cli/src/measure/media.ts b/packages/cli/src/measure/media.ts
new file mode 100644
index 0000000000..1f10ee20b5
--- /dev/null
+++ b/packages/cli/src/measure/media.ts
@@ -0,0 +1,359 @@
+// Decode with ffmpeg into raw arrays, so measuring and comparing need nothing but node and ffmpeg.
+// Ported from the Studio's viral-clone media.mjs and tool.mjs.
+import { execFileSync } from "node:child_process";
+import { existsSync, mkdirSync } from "node:fs";
+import { join, resolve } from "node:path";
+import { findFFmpeg, findFFprobe, getFFmpegInstallHint } from "../browser/ffmpeg.js";
+
+const MAX_BUFFER = 1 << 30;
+/** ffmpeg flags on every run. Inline before a spread, the ffprobe `--` contract test reads them as a probe wrapper. */
+const FFMPEG_QUIET = ["-nostdin", "-v", "error"];
+
+/** An error whose message says what to run instead; commands print `fix` as its own line. */
+export class Fix extends Error {
+ constructor(
+ problem: string,
+ readonly fix: string,
+ ) {
+ super(problem);
+ this.name = "Fix";
+ }
+}
+
+export function ffmpegBin(): string {
+ const bin = findFFmpeg();
+ if (!bin) throw new Fix("ffmpeg is not installed", getFFmpegInstallHint());
+ return bin;
+}
+
+function ffprobeBin(): string {
+ const bin = findFFprobe();
+ if (!bin) throw new Fix("ffprobe is not installed", getFFmpegInstallHint());
+ return bin;
+}
+
+/** Runs ffmpeg and returns its stdout; `input` is piped to stdin. */
+export function runFfmpeg(args: string[], input?: Buffer, cwd?: string): Buffer {
+ return execFileSync(ffmpegBin(), [...FFMPEG_QUIET, ...args], {
+ maxBuffer: MAX_BUFFER,
+ windowsHide: true,
+ ...(input ? { input } : {}),
+ ...(cwd ? { cwd } : {}),
+ });
+}
+
+export interface VideoInfo {
+ path: string;
+ width: number;
+ height: number;
+ fps: number;
+ /** The frame rate as ffmpeg writes it, e.g. 30000/1001. */
+ fpsText: string;
+ duration: number;
+ /** The picture's length: the container's can run on with a longer sound track. */
+ pictureDuration: number;
+ frames: number;
+ audio: boolean;
+ /** Seconds the sound starts after the picture (0 when it starts with it or there is none). */
+ audioStart: number;
+ /** Frames over seconds, which a variable-rate video's nominal rate does not tell. */
+ avgFps: number;
+ /** The container's frame rate and the stream's average differ: frames are not evenly spaced. */
+ vfr: boolean;
+ hdr: boolean;
+ codec: string;
+}
+
+interface ProbeStream {
+ codec_type?: string;
+ codec_name?: string;
+ width?: number;
+ height?: number;
+ r_frame_rate?: string;
+ avg_frame_rate?: string;
+ nb_frames?: string;
+ duration?: string;
+ start_time?: string;
+ color_transfer?: string;
+ side_data_list?: { rotation?: number }[];
+ tags?: { rotate?: string };
+}
+
+const rate = (text: string | undefined): number => {
+ const [a, b] = String(text ?? "0/1")
+ .split("/")
+ .map(Number);
+ return b ? (a ?? 0) / b : (a ?? 0);
+};
+
+/** Size (as displayed, rotation applied), clock and sound of a video. */
+// fallow-ignore-next-line complexity
+export function probeVideo(path: string): VideoInfo {
+ if (!existsSync(path))
+ throw new Fix(`no file at ${path}`, "pass the video's path from the project folder");
+ let json: { streams?: ProbeStream[]; format?: { duration?: string } };
+ try {
+ json = JSON.parse(
+ execFileSync(
+ ffprobeBin(),
+ ["-v", "error", "-show_streams", "-show_format", "-of", "json", "--", path],
+ { maxBuffer: MAX_BUFFER, windowsHide: true },
+ ).toString(),
+ );
+ } catch {
+ throw new Fix(`ffprobe cannot read ${path}`, "pass a video file (mp4, mov, webm)");
+ }
+ const streams = json.streams ?? [];
+ const video = streams.find((s) => s.codec_type === "video");
+ if (!video) throw new Fix(`${path} has no video stream`, "pass a video file, not audio");
+ const rotation = Math.abs(
+ Number(video.side_data_list?.find((d) => d.rotation !== undefined)?.rotation ?? 0) ||
+ Number(video.tags?.rotate ?? 0),
+ );
+ const turned = rotation % 180 === 90;
+ const fpsText = video.r_frame_rate && video.r_frame_rate !== "0/0" ? video.r_frame_rate : "30/1";
+ const fps = rate(fpsText);
+ const avg = rate(video.avg_frame_rate);
+ const duration = Number(json.format?.duration ?? video.duration ?? 0);
+ const counted = Number(video.nb_frames ?? 0);
+ const sound = streams.find((s) => s.codec_type === "audio");
+ const frames = counted > 0 ? counted : Math.round(duration * fps);
+ return {
+ path,
+ width: (turned ? video.height : video.width) ?? 0,
+ height: (turned ? video.width : video.height) ?? 0,
+ fps,
+ fpsText: fpsText.endsWith("/1") ? fpsText.slice(0, -2) : fpsText,
+ duration,
+ pictureDuration: Number(video.duration ?? 0) || frames / (avg || fps),
+ frames,
+ audio: Boolean(sound),
+ audioStart: Math.max(0, Number(sound?.start_time ?? 0) - Number(video.start_time ?? 0) || 0),
+ avgFps: avg || fps,
+ vfr: avg > 0 && Math.abs(avg - fps) / fps > 0.01,
+ hdr: /smpte2084|arib-std-b67/.test(video.color_transfer ?? ""),
+ codec: video.codec_name ?? "",
+ };
+}
+
+export type Roi = [x: number, y: number, w: number, h: number];
+
+export interface ReadOptions {
+ start?: number;
+ /** Seconds to read; omit for the rest of the file. */
+ seconds?: number;
+ roi?: Roi;
+ /** Output width (height follows the ROI's aspect, even); 0 or omitted keeps the ROI's size. */
+ width?: number;
+ gray?: boolean;
+ /** Resample to this rate; 0 or omitted reads every frame. */
+ fps?: number;
+ /** Stop after this many frames. */
+ limit?: number;
+}
+
+export interface Frames {
+ frames: Uint8Array[];
+ w: number;
+ h: number;
+}
+
+/**
+ * Frames from anywhere ffmpeg reads: a window of a video file, or a numbered picture sequence. `filters` run
+ * before any crop or scale, so a clip can pick frames (select, fps) without changing their size.
+ */
+export interface Clip {
+ input: string[];
+ filters: string[];
+ width: number;
+ height: number;
+ fps: number;
+}
+
+/** A window of a video file as a clip; `info` saves a probe when the caller has one. */
+export function videoClip(
+ path: string,
+ start = 0,
+ seconds?: number,
+ info = probeVideo(path),
+): Clip {
+ return {
+ input: [
+ ...(start > 0 ? ["-ss", String(start)] : []),
+ "-i",
+ path,
+ ...(seconds !== undefined ? ["-t", String(seconds)] : []),
+ ],
+ filters: [],
+ width: info.width,
+ height: info.height,
+ fps: info.fps,
+ };
+}
+
+/** A clip's frames of one ROI as raw RGB (or grey) bytes. */
+export function readClip(clip: Clip, opts: Omit = {}): Frames {
+ const { roi, width = 0, gray = false, fps = 0, limit } = opts;
+ const filters = [...clip.filters];
+ if (fps) filters.push(`fps=${fps}`);
+ let [w, h] = [clip.width, clip.height];
+ if (roi) {
+ filters.push(`crop=${roi[2]}:${roi[3]}:${roi[0]}:${roi[1]}`);
+ [w, h] = [roi[2], roi[3]];
+ }
+ if (width && width !== w) {
+ const outH = Math.max(2, Math.round((h * width) / w / 2) * 2);
+ filters.push(`scale=${width}:${outH}`);
+ [w, h] = [width, outH];
+ }
+ return decode(clip.input, filters, w, h, gray, limit);
+}
+
+/** The frame shown at `t`, picked by its index: seeking by time can land a frame early or late. */
+export function readFrameAt(
+ info: VideoInfo,
+ t: number,
+ opts: Omit = {},
+): Frames {
+ const k = Math.min(info.frames - 1, frameAt(t, info.fps));
+ return readClip(
+ { ...videoClip(info.path, 0, undefined, info), filters: [`select=eq(n\\,${k})`] },
+ { ...opts, limit: 1 },
+ );
+}
+
+/** Frames of one ROI of a video file as raw RGB (or grey) bytes. */
+export function readFrames(path: string, opts: ReadOptions = {}): Frames {
+ return readClip(videoClip(path, opts.start, opts.seconds), opts);
+}
+
+/** Every frame (or the first `limit`) ffmpeg's `input` arguments yield after `filters`, which must end at `w`x`h`. */
+export function decode(
+ input: string[],
+ filters: string[],
+ w: number,
+ h: number,
+ gray = false,
+ limit?: number,
+): Frames {
+ const raw = runFfmpeg([
+ ...input,
+ "-an",
+ "-vf",
+ [...filters, `format=${gray ? "gray" : "rgb24"}`].join(","),
+ ...(limit ? ["-frames:v", String(limit)] : []),
+ "-f",
+ "rawvideo",
+ "-",
+ ]);
+ const size = w * h * (gray ? 1 : 3);
+ const frames: Uint8Array[] = [];
+ for (let i = 0; i + size <= raw.length; i += size) frames.push(raw.subarray(i, i + size));
+ return { frames, w, h };
+}
+
+/** BT.601 luma of RGB bytes. */
+export function grey(rgb: Uint8Array): Uint8Array {
+ const out = new Uint8Array(rgb.length / 3);
+ for (let i = 0; i < out.length; i++)
+ out[i] = (77 * rgb[3 * i]! + 150 * rgb[3 * i + 1]! + 29 * rgb[3 * i + 2]!) >> 8;
+ return out;
+}
+
+/** Mean absolute difference of two equal-length byte arrays. */
+export function meanAbsDiff(a: Uint8Array, b: Uint8Array): number {
+ let s = 0;
+ for (let i = 0; i < a.length; i++) s += Math.abs(a[i]! - b[i]!);
+ return s / (a.length || 1);
+}
+
+/** Writes raw RGB (or grey) bytes as an image; the extension picks the format. */
+export function writeImage(path: string, px: Uint8Array, w: number, h: number, gray = false) {
+ const header = Buffer.from(`${gray ? "P5" : "P6"}\n${w} ${h}\n255\n`);
+ runFfmpeg(
+ ["-y", "-f", gray ? "pgm_pipe" : "ppm_pipe", "-i", "-", "-frames:v", "1", path],
+ Buffer.concat([header, Buffer.from(px.buffer, px.byteOffset, px.byteLength)]),
+ );
+ return path;
+}
+
+export const round = (n: number, d = 3) => Math.round(n * 10 ** d) / 10 ** d;
+
+/** Yours over the reference; two values under `floor` are both nothing, and nothing matches nothing. */
+export const ratioOf = (yours: number, ref: number, floor: number): number =>
+ yours < floor && ref < floor ? 1 : yours / (ref || 1e-9);
+
+/** "1,2.5,4" as numbers. */
+export function parseNumbers(text: unknown, flag: string): number[] {
+ const out = String(text ?? "")
+ .split(",")
+ .filter((s) => s.trim() !== "")
+ .map(Number);
+ if (!out.length || out.some((n) => !Number.isFinite(n)))
+ throw new Fix(
+ `${flag} must be numbers separated by commas, got "${String(text)}"`,
+ `${flag} 1.2,3.4`,
+ );
+ return out;
+}
+
+/** "start,end" seconds with 0 <= start < end. */
+export function parseRange(text: unknown, flag = "--range"): [number, number] {
+ const v = parseNumbers(text, flag);
+ if (v.length !== 2 || v[0]! < 0 || v[1]! <= v[0]!)
+ throw new Fix(
+ `${flag} must be start,end seconds with start < end, got "${String(text)}"`,
+ `${flag} 2.1,4.5`,
+ );
+ return [v[0]!, v[1]!];
+}
+
+/** "x,y,w,h" in pixels, inside a `width`x`height` frame when one is given. */
+export function parseRoi(text: unknown, width?: number, height?: number): Roi {
+ const v = parseNumbers(text, "--roi").map(Math.round);
+ if (v.length !== 4 || v[2]! <= 0 || v[3]! <= 0)
+ throw new Fix(
+ `--roi must be x,y,w,h with a positive size, got "${String(text)}"`,
+ "--roi 100,200,400,300",
+ );
+ const roi: Roi = [v[0]!, v[1]!, v[2]!, v[3]!];
+ if (
+ width &&
+ height &&
+ (roi[0] < 0 || roi[1] < 0 || roi[0] + roi[2] > width || roi[1] + roi[3] > height)
+ )
+ throw new Fix(
+ `--roi ${roi.join(",")} runs past the ${width}x${height} frame`,
+ `keep it inside 0,0,${width},${height}`,
+ );
+ return roi;
+}
+
+/** The folder a tool writes its pictures to, made on demand: --out, or .hyperframes/ in the current folder. */
+export function outDir(out: unknown, tool: string): string {
+ const dir = typeof out === "string" && out ? resolve(out) : resolve(join(".hyperframes", tool));
+ mkdirSync(dir, { recursive: true });
+ return dir;
+}
+
+/** The frame shown at time `t`, allowing for times printed to the millisecond (38/24 s printed as 1.583). */
+export const frameAt = (t: number, fps: number) =>
+ Math.max(0, Math.floor((t + 0.0005) * fps + 1e-6));
+
+/** JSON with each innermost array or object on one line: readable, and a fraction of the tokens. */
+export const formatJson = (value: unknown) =>
+ JSON.stringify(value, null, 1).replace(/[[{][^[\]{}]*[\]}]/g, (m) => m.replace(/\n\s*/g, " "));
+
+/** Pearson correlation of two series over their common length; null when either one is flat. */
+export function pearson(a: number[], b: number[]): number | null {
+ const n = Math.min(a.length, b.length);
+ const ma = a.slice(0, n).reduce((s, v) => s + v, 0) / n;
+ const mb = b.slice(0, n).reduce((s, v) => s + v, 0) / n;
+ let [num, da, db] = [0, 0, 0];
+ for (let i = 0; i < n; i++) {
+ num += (a[i]! - ma) * (b[i]! - mb);
+ da += (a[i]! - ma) ** 2;
+ db += (b[i]! - mb) ** 2;
+ }
+ return da && db ? num / Math.sqrt(da * db) : null;
+}
diff --git a/packages/cli/src/measure/opencv.ts b/packages/cli/src/measure/opencv.ts
new file mode 100644
index 0000000000..6cdcb4f541
--- /dev/null
+++ b/packages/cli/src/measure/opencv.ts
@@ -0,0 +1,175 @@
+// OpenCV for the measuring tools that need it (template tracking, optical flow, faces), as opencv.js: one WebAssembly
+// file that gives every machine the same numbers. It is not shipped in the CLI; the first use downloads it and the
+// Haar face models, pinned by size and sha256, into ~/.cache/hyperframes/opencv//.
+import { mkdirSync, readFileSync, renameSync, rmSync } from "node:fs";
+import { createRequire } from "node:module";
+import { homedir } from "node:os";
+import { join } from "node:path";
+import { downloadToFile } from "../cloud/download.js";
+import { verifies, type ModelFile } from "../whisper/modelFile.js";
+import { Fix } from "./media.js";
+
+const VERSION = "4.10.0";
+export const OPENCV_DIR = join(homedir(), ".cache", "hyperframes", "opencv", VERSION);
+
+interface Pinned extends ModelFile {
+ url: string;
+}
+
+// opencv.js is @techstark/opencv-js 4.10.0-release.1 (Apache-2.0); the cascades are OpenCV's own (BSD-3-Clause).
+const CASCADES = "https://raw.githubusercontent.com/opencv/opencv/4.10.0/data/haarcascades";
+const FILES: readonly Pinned[] = [
+ {
+ name: "opencv.js",
+ bytes: 10_378_215,
+ sha256: "19b46167b59efbef9cc3836264b0b657110833e4b1df84282004b8b3141c048d",
+ url: "https://cdn.jsdelivr.net/npm/@techstark/opencv-js@4.10.0-release.1/dist/opencv.js",
+ },
+ {
+ name: "haarcascade_frontalface_alt2.xml",
+ bytes: 540_616,
+ sha256: "7b0c967d9abbdfbde025eb9c786947d151b6426040d07a8f9562ed8fd90724b4",
+ url: `${CASCADES}/haarcascade_frontalface_alt2.xml`,
+ },
+ {
+ name: "haarcascade_profileface.xml",
+ bytes: 828_514,
+ sha256: "b39a4a3be45539db146a7fc1d3e761a292c196eb88421185e6a615b3055e612d",
+ url: `${CASCADES}/haarcascade_profileface.xml`,
+ },
+];
+
+/** The parts of the OpenCV API the measuring tools use. */
+export interface Mat {
+ rows: number;
+ cols: number;
+ data32F: Float32Array;
+ data64F: Float64Array;
+ data: Uint8Array;
+ delete(): void;
+}
+interface Size {
+ width: number;
+ height: number;
+}
+export interface Rect {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+export interface RectVector {
+ size(): number;
+ get(i: number): Rect;
+ delete(): void;
+}
+export interface Cv {
+ Mat: new () => Mat;
+ RectVector: new () => RectVector;
+ Size: new (w: number, h: number) => Size;
+ CascadeClassifier: new () => {
+ load(path: string): boolean;
+ detectMultiScale(
+ gray: Mat,
+ out: RectVector,
+ scale: number,
+ neighbours: number,
+ flags: number,
+ min: Size,
+ ): void;
+ delete(): void;
+ };
+ matFromArray(rows: number, cols: number, type: number, data: ArrayLike): Mat;
+ matchTemplate(image: Mat, templ: Mat, result: Mat, method: number): void;
+ minMaxLoc(src: Mat): {
+ minVal: number;
+ maxVal: number;
+ minLoc: { x: number; y: number };
+ maxLoc: { x: number; y: number };
+ };
+ calcOpticalFlowFarneback(
+ prev: Mat,
+ next: Mat,
+ flow: Mat,
+ pyrScale: number,
+ levels: number,
+ winsize: number,
+ iterations: number,
+ polyN: number,
+ polySigma: number,
+ flags: number,
+ ): void;
+ estimateAffine2D(from: Mat, to: Mat): Mat;
+ FS_createDataFile(
+ parent: string,
+ name: string,
+ data: Uint8Array,
+ read: boolean,
+ write: boolean,
+ own: boolean,
+ ): void;
+ CV_8UC1: number;
+ CV_32FC2: number;
+ TM_CCOEFF_NORMED: number;
+}
+
+const isCv = (v: unknown): v is Cv =>
+ typeof v === "object" && v !== null && "Mat" in v && "matFromArray" in v;
+
+/** Every pinned file present and verified; the missing ones fetched. */
+// fallow-ignore-next-line complexity
+async function ensureOpenCv(onStatus?: (message: string) => void): Promise {
+ const missing: Pinned[] = [];
+ for (const f of FILES) if (!(await verifies(join(OPENCV_DIR, f.name), f))) missing.push(f);
+ if (!missing.length) return;
+ mkdirSync(OPENCV_DIR, { recursive: true });
+ for (const f of missing) {
+ onStatus?.(`Downloading ${f.name} (${Math.round(f.bytes / 1e5) / 10} MB, once)...`);
+ const temp = join(OPENCV_DIR, `${f.name}.part-${process.pid}`);
+ try {
+ await downloadToFile(f.url, temp);
+ if (!(await verifies(temp, f)))
+ throw new Fix(
+ `${f.name} did not match its pinned size and sha256`,
+ "run the command again to retry the download",
+ );
+ renameSync(temp, join(OPENCV_DIR, f.name));
+ } catch (err) {
+ if (err instanceof Fix) throw err;
+ throw new Fix(
+ `could not download ${f.name} (${err instanceof Error ? err.message : String(err)})`,
+ "check the network and run the command again",
+ );
+ } finally {
+ rmSync(temp, { force: true });
+ }
+ }
+}
+
+let loaded: Promise | null = null;
+
+/** opencv.js, ready to call, with the face models in its file system. Loaded once per process. */
+export function loadOpenCv(onStatus?: (message: string) => void): Promise {
+ loaded ??= (async () => {
+ await ensureOpenCv(onStatus);
+ const mod: unknown = createRequire(import.meta.url)(join(OPENCV_DIR, "opencv.js"));
+ if (typeof mod !== "object" || mod === null) throw new Error("opencv.js did not load");
+ // Wait on its init hook, never on the module: it is a thenable that does not settle under await.
+ await new Promise((resolve) => {
+ if ("Mat" in mod) resolve();
+ else Object.assign(mod, { onRuntimeInitialized: () => resolve() });
+ });
+ // Ready now; without its `then`, promises can carry it like any other object.
+ Reflect.deleteProperty(mod, "then");
+ if (!isCv(mod)) throw new Error("opencv.js did not initialize");
+ const cv = mod;
+ for (const f of FILES.filter((x) => x.name.endsWith(".xml")))
+ cv.FS_createDataFile("/", f.name, readFileSync(join(OPENCV_DIR, f.name)), true, false, false);
+ return cv;
+ })();
+ return loaded;
+}
+
+/** Grey bytes as an 8-bit single-channel Mat. */
+export const greyMat = (cv: Cv, px: Uint8Array, w: number, h: number) =>
+ cv.matFromArray(h, w, cv.CV_8UC1, px);
diff --git a/packages/cli/src/measure/person.ts b/packages/cli/src/measure/person.ts
new file mode 100644
index 0000000000..352289ddc3
--- /dev/null
+++ b/packages/cli/src/measure/person.ts
@@ -0,0 +1,547 @@
+// A re-shot person never matches the original by pixels, so pixels do not judge them. Three gates do: the framing
+// is clearly wrong (face centre or height off the original's, per shot), the generated clip carries the original's
+// words (its motion guide's text came along), or the lips are out of sync. The rest (motion energy, look, whether
+// each generated clip starts at one of the original's cuts) is reported, not judged.
+import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { contrast } from "./drawn.js";
+import { faceBoxes } from "./face.js";
+import { pearson, probeVideo, round, runFfmpeg, type Roi, type VideoInfo } from "./media.js";
+import { avSync, type SyncResult } from "./sync.js";
+
+/** A shot's framing is clearly wrong when, by the shot's medians, the face centre sits over FRAMING_SHIFT face heights
+ * from the original's or its height is outside FRAMING_SCALE of it. Faces at FACE_RATE a second; shorter shots than
+ * FRAMING_MIN_S have too few faces to judge. */
+const FRAMING_SHIFT = 0.3;
+const FRAMING_SCALE: [number, number] = [0.8, 1.25];
+const FRAMING_MIN_S = 1;
+const FRAMING_MIN_FACES = 3;
+const FACE_RATE = 4;
+/** Picture against sound (positive: the picture is late), the broadcast tolerance; judged on high confidence only. */
+const SYNC_MS: [number, number] = [-125, 45];
+const SYNC_MIN_S = 2;
+const SYNC_MIN_SPEECH = 0.3;
+/** A clip carries a drawn element's text when, of the original's sharp ink (over TEXT_CONTRAST) that differs by
+ * DRAWN_DIFF from the clean still and where yours draws over the clip, the share the clip matches within two pixels in
+ * colour (TEXT_COLOUR) reaches CARRIED_TEXT; the clip shares person and place, so only carried letters match. */
+const CARRIED_TEXT = 0.35;
+const TEXT_CONTRAST = 140;
+const DRAWN_DIFF = 60;
+const TEXT_COLOUR = 15;
+const TEXT_MIN_INK = 50;
+const CARRIED_SAMPLES = 8;
+/** A generated clip found by its sound needs this correlation with the original's; it starts at a cut within this. */
+const LOCATE_MIN = 0.6;
+export const AT_CUT_S = 0.1;
+const ENVELOPE_RATE = 100;
+
+export interface GeneratedClip {
+ /** As the ledger writes it, relative to the project. */
+ path: string;
+ /** The still it was made from (a clean frame of the original), relative to the project. */
+ reference?: string;
+ /** Film time of the clip's first frame, and how well its sound matched the original's there. */
+ offset?: number;
+ match?: number;
+ window?: [number, number];
+ /** Where the film shows it: film window, the clip's time at its start, and its playback rate. */
+ uses?: ClipUse[];
+ /** Whether it starts within AT_CUT_S of the film's start or one of the original's cuts. */
+ at_cut?: boolean;
+ note?: string;
+}
+
+export interface ClipUse {
+ window: [number, number];
+ from: number;
+ rate: number;
+}
+
+export interface ShotFraming {
+ window: [number, number];
+ /** Medians: face centre distance in the original's face heights, and yours' face height over the original's. */
+ shift: number;
+ scale: number;
+ pass: boolean;
+}
+
+export interface CarriedText {
+ drawn: string;
+ clip: string;
+ window: [number, number];
+ /** How well the generated clip's ink inside the box matches the original's text there. */
+ score: number;
+ carried: boolean;
+}
+
+export interface PersonVerdict {
+ /** Each gate: false when it fails, null when it could not be measured. */
+ gates: { framing: boolean | null; text: boolean | null; sync: boolean | null };
+ pass: boolean | null;
+ framing?: ShotFraming[];
+ text?: CarriedText[];
+ sync?: {
+ window: [number, number];
+ lag_ms: number | null;
+ original_lag_ms: number | null;
+ confidence: string;
+ pass: boolean | null;
+ }[];
+}
+
+const isRecord = (v: unknown): v is Record => typeof v === "object" && v !== null;
+
+/** The ledger's generated videos (HeyGen), with the film window it records when it does. */
+export function generatedClips(ledger: string): GeneratedClip[] {
+ // fallow-ignore-next-line complexity
+ return ledger.split("\n").flatMap((line) => {
+ let entry: unknown;
+ try {
+ entry = JSON.parse(line);
+ } catch {
+ return [];
+ }
+ if (!isRecord(entry) || entry.type !== "video" || typeof entry.path !== "string") return [];
+ const p = entry.provenance;
+ if (!isRecord(p) || p.provider !== "heygen") return [];
+ const w = Array.isArray(p.window) ? p.window.filter((v) => typeof v === "number") : [];
+ const refs = Array.isArray(p.references)
+ ? p.references.filter((v) => typeof v === "string")
+ : [];
+ return [
+ {
+ path: entry.path,
+ ...(refs[0] ? { reference: refs[0] } : {}),
+ ...(w.length === 2 ? { offset: w[0]!, window: [w[0]!, w[1]!] as [number, number] } : {}),
+ },
+ ];
+ });
+}
+
+/** Loudness every 10 ms of a file's sound. */
+function envelope(path: string): number[] {
+ const raw = runFfmpeg([...["-i", path, "-vn", "-ac", "1", "-ar", "8000", "-f", "f32le", "-"]]);
+ const s = new Float32Array(
+ raw.buffer.slice(raw.byteOffset, raw.byteOffset + (raw.byteLength & ~3)),
+ );
+ const step = 8000 / ENVELOPE_RATE;
+ const out: number[] = [];
+ for (let i = 0; i + step <= s.length; i += step) {
+ let e = 0;
+ for (let j = i; j < i + step; j++) e += s[j]! ** 2;
+ out.push(Math.sqrt(e / step));
+ }
+ return out;
+}
+
+/**
+ * Where `b` sits inside `a` (index of a where b[0] lands) and the correlation there, over lags that keep at least
+ * nine tenths of b inside a.
+ */
+function bestLag(a: number[], b: number[]): { lag: number; r: number } {
+ let best = { lag: 0, r: -2 };
+ const keep = Math.ceil(0.9 * b.length);
+ for (let lag = -(b.length - keep); lag <= a.length - keep; lag++) {
+ const [i0, i1] = [Math.max(0, -lag), Math.min(b.length, a.length - lag)];
+ const n = i1 - i0;
+ if (n < Math.max(50, keep)) continue;
+ const r = pearson(a.slice(i0 + lag, i1 + lag), b.slice(i0, i1)) ?? -2;
+ if (r > best.r) best = { lag, r };
+ }
+ return best;
+}
+
+/** Each generated clip on the film: it starts at the ledger's window, else where its sound lines up with the original,
+ * and shows where the timeline's `uses` place it (by path), else over its whole window. Paths resolve in the project */
+export function placeClips(
+ clips: GeneratedClip[],
+ project: string | undefined,
+ ref: VideoInfo,
+ cuts: number[],
+ shown: Map = new Map(),
+): (GeneratedClip & { file?: string; info?: VideoInfo; still?: string })[] {
+ let whole: number[] | undefined;
+ // fallow-ignore-next-line complexity
+ return clips.map((c) => {
+ const file = project ? join(project, c.path) : undefined;
+ let info: VideoInfo | undefined;
+ try {
+ info = file ? probeVideo(file) : undefined;
+ } catch {
+ info = undefined;
+ }
+ if (!info || !file) return { ...c, note: "the clip's file is not in the project" };
+ const uses = shown.get(normalize(c.path));
+ let placed: GeneratedClip = c;
+ if (c.offset === undefined && info.audio && ref.audio) {
+ whole ??= envelope(ref.path);
+ const { lag, r } = bestLag(whole, envelope(file));
+ const offset = round(lag / ENVELOPE_RATE + ref.audioStart - info.audioStart, 3);
+ placed =
+ r >= LOCATE_MIN
+ ? { ...c, offset, match: round(r, 2) }
+ : { ...c, match: round(r, 2), note: "its sound does not match the original's" };
+ }
+ if (placed.offset === undefined && uses?.length)
+ placed = { ...placed, offset: round(uses[0]!.window[0] - uses[0]!.from / uses[0]!.rate, 3) };
+ if (placed.offset === undefined)
+ return {
+ ...placed,
+ file,
+ info,
+ note: placed.note ?? "no window in the ledger, no sound and no place in the project",
+ };
+ const offset = placed.offset;
+ const end = Math.min(ref.pictureDuration, offset + info.pictureDuration);
+ return {
+ ...placed,
+ window: placed.window ?? [round(Math.max(0, offset), 3), round(end, 3)],
+ uses: uses ?? [
+ {
+ window: [round(Math.max(0, offset), 3), round(end, 3)],
+ from: Math.max(0, -offset),
+ rate: 1,
+ },
+ ],
+ at_cut: [0, ...cuts].some((t) => Math.abs(t - offset) <= AT_CUT_S),
+ file,
+ info,
+ ...(c.reference && existsSync(join(project!, c.reference))
+ ? { still: join(project!, c.reference) }
+ : {}),
+ };
+ });
+}
+
+/** Where a project's timeline shows each video file, by project-relative path. */
+export async function clipUses(project: string): Promise> {
+ const out = new Map();
+ const index = join(project, "index.html");
+ if (!existsSync(index)) return out;
+ const [{ ensureDOMParser }, { describeProject }] = await Promise.all([
+ import("../utils/dom.js"),
+ import("../timeline/describeProject.js"),
+ ]);
+ ensureDOMParser();
+ const timeline = await describeProject(index);
+ for (const row of timeline.tracks.find((t) => t.kind === "video")?.rows ?? []) {
+ if (!row.src || row.absEnd <= row.absStart) continue;
+ const key = normalize(row.src);
+ const use = {
+ window: [round(row.absStart, 3), round(row.absEnd, 3)] as [number, number],
+ from: row.mediaStart ?? 0,
+ rate: row.playbackRate ?? 1,
+ };
+ out.set(key, [...(out.get(key) ?? []), use]);
+ }
+ return out;
+}
+
+/** A project-relative path written one way. */
+const normalize = (p: string) => p.replace(/^\.\//, "").replace(/\\/g, "/");
+
+/** RGB crops of one box at these times: the picture scaled to cover `w`x`h` (the original's size) first. */
+function boxAt(
+ info: VideoInfo,
+ times: number[],
+ box: Roi,
+ w: number,
+ h: number,
+): (Uint8Array | undefined)[] {
+ const ks = times.map((t) => Math.max(0, Math.min(info.frames - 1, Math.round(t * info.fps))));
+ const unique = [...new Set(ks)].sort((x, y) => x - y);
+ const work = mkdtempSync(join(tmpdir(), "hf-person-"));
+ try {
+ const filters = [
+ `select=${unique.map((k) => `eq(n\\,${k})`).join("+")}`,
+ `scale=${w}:${h}:force_original_aspect_ratio=increase:flags=bicubic`,
+ `crop=${w}:${h}`,
+ `crop=${box[2]}:${box[3]}:${box[0]}:${box[1]}`,
+ "format=rgb24",
+ ].join(",");
+ runFfmpeg(
+ [
+ ...["-i", info.path, "-an", "-vf", filters, "-fps_mode", "passthrough"],
+ ...["-f", "rawvideo", "out.rgb"],
+ ],
+ undefined,
+ work,
+ );
+ const raw = readFileSync(join(work, "out.rgb"));
+ const size = box[2] * box[3] * 3;
+ return ks.map((k) => {
+ const i = unique.indexOf(k) * size;
+ return i + size <= raw.length ? raw.subarray(i, i + size) : undefined;
+ });
+ } finally {
+ rmSync(work, { recursive: true, force: true });
+ }
+}
+
+/** Within `r` pixels of (x, y), some pixel passes `test`. */
+function nearby(
+ w: number,
+ h: number,
+ x: number,
+ y: number,
+ r: number,
+ test: (k: number) => boolean,
+) {
+ for (let dy = -r; dy <= r; dy++)
+ for (let dx = -r; dx <= r; dx++) {
+ const [xx, yy] = [Math.min(w - 1, Math.max(0, x + dx)), Math.min(h - 1, Math.max(0, y + dy))];
+ if (test(yy * w + xx)) return true;
+ }
+ return false;
+}
+
+const dist = (p: Uint8Array, i: number, q: Uint8Array, k: number) =>
+ Math.hypot(p[i * 3]! - q[k * 3]!, p[i * 3 + 1]! - q[k * 3 + 1]!, p[i * 3 + 2]! - q[k * 3 + 2]!);
+
+/** One frame: the share of the original's letters (apart from the still and from what yours draws) the clip shows. */
+// fallow-ignore-next-line complexity
+export function carriedFrame(
+ original: Uint8Array,
+ clip: Uint8Array,
+ still: Uint8Array | undefined,
+ w: number,
+ h: number,
+ yours: Uint8Array | undefined,
+): number | null {
+ const [sharp, inked] = [contrast(original, w, h), contrast(clip, w, h)];
+ let [n, hit] = [0, 0];
+ for (let y = 0; y < h; y++)
+ for (let x = 0; x < w; x++) {
+ const i = y * w + x;
+ if (sharp[i]! <= TEXT_CONTRAST) continue;
+ if (still && !nearby(w, h, x, y, 2, (k) => dist(original, k, still, k) > DRAWN_DIFF))
+ continue;
+ if (yours && !nearby(w, h, x, y, 2, (k) => dist(yours, k, clip, k) > DRAWN_DIFF)) continue;
+ n++;
+ const same = (k: number) =>
+ inked[k]! > TEXT_CONTRAST && dist(original, i, clip, k) < TEXT_COLOUR;
+ if (nearby(w, h, x, y, 2, same)) hit++;
+ }
+ return n >= TEXT_MIN_INK ? hit / n : null;
+}
+
+/** One box of a still picture, scaled to cover `w`x`h` (the original's size) first. */
+function stillBox(path: string, box: Roi, w: number, h: number): Uint8Array | undefined {
+ try {
+ const raw = runFfmpeg([
+ ...["-i", path, "-frames:v", "1", "-vf"],
+ `scale=${w}:${h}:force_original_aspect_ratio=increase:flags=bicubic,crop=${w}:${h},crop=${box[2]}:${box[3]}:${box[0]}:${box[1]},format=rgb24`,
+ ...["-f", "rawvideo", "-"],
+ ]);
+ return raw.length >= box[2] * box[3] * 3 ? new Uint8Array(raw) : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+/** Whether a generated clip alone carries the original's text inside a drawn element's box over its window: a clean
+ * clip shows the person and place behind the letters, one made from a motion guide with words on it shows the words. */
+function carriedText(
+ ref: VideoInfo,
+ yours: VideoInfo,
+ clip: { path: string; info: VideoInfo; uses: ClipUse[]; still?: string },
+ drawn: { id: string; box: Roi; window: [number, number] },
+): CarriedText | undefined {
+ // The film times both show, each with the clip's own time there.
+ const spans = clip.uses.flatMap((u) => {
+ const [a, b] = [Math.max(drawn.window[0], u.window[0]), Math.min(drawn.window[1], u.window[1])];
+ return b - a >= 1 / ref.fps ? [{ a, b, u }] : [];
+ });
+ const total = spans.reduce((s, x) => s + x.b - x.a, 0);
+ if (!total) return undefined;
+ // Evenly spread samples over the shown spans.
+ const times = Array.from({ length: CARRIED_SAMPLES }, (_, i) => {
+ let at = ((i + 0.5) * total) / CARRIED_SAMPLES;
+ for (const x of spans) {
+ if (at <= x.b - x.a)
+ return { t: x.a + at, c: x.u.from + (at + x.a - x.u.window[0]) * x.u.rate };
+ at -= x.b - x.a;
+ }
+ const x = spans.at(-1)!;
+ return { t: x.b, c: x.u.from + (x.b - x.u.window[0]) * x.u.rate };
+ });
+ const orig = boxAt(
+ ref,
+ times.map((x) => x.t),
+ drawn.box,
+ ref.width,
+ ref.height,
+ );
+ const generated = boxAt(
+ clip.info,
+ times.map((x) => x.c),
+ drawn.box,
+ ref.width,
+ ref.height,
+ );
+ const mine = boxAt(
+ yours,
+ times.map((x) => x.t),
+ drawn.box,
+ ref.width,
+ ref.height,
+ );
+ const still = clip.still ? stillBox(clip.still, drawn.box, ref.width, ref.height) : undefined;
+ const scores = orig.flatMap((o, i) => {
+ const g = generated[i];
+ const s = o && g ? carriedFrame(o, g, still, drawn.box[2], drawn.box[3], mine[i]) : null;
+ return s === null ? [] : [s];
+ });
+ if (!scores.length) return undefined;
+ const score = scores.reduce((s, v) => s + v, 0) / scores.length;
+ return {
+ drawn: drawn.id,
+ clip: clip.path,
+ window: [round(spans[0]!.a, 3), round(spans.at(-1)!.b, 3)],
+ score: round(score, 3),
+ carried: score >= CARRIED_TEXT,
+ };
+}
+
+const median = (v: number[]) => [...v].sort((x, y) => x - y)[v.length >> 1]!;
+
+const centre = (b: number[]) => [b[0]! + b[2]! / 2, b[1]! + b[3]! / 2] as const;
+
+/** The original's shots inside a window: split at its cuts. */
+function shotsIn(window: [number, number], cuts: number[]): [number, number][] {
+ const edges = [window[0], ...cuts.filter((t) => t > window[0] && t < window[1]), window[1]];
+ return edges.slice(1).map((e, i) => [edges[i]!, e]);
+}
+
+/** One shot's framing from both sides' faces at the same moments (boxes as shares of an `aspect`-wide frame): the
+ * original's largest face against yours' nearest, by the shot's medians, so one stray detection (a photo) can't. */
+export function shotFraming(
+ window: [number, number],
+ original: { t: number; boxes: number[][] }[],
+ yours: { t: number; boxes: number[][] }[],
+ aspect = 1,
+): ShotFraming | undefined {
+ const inside = (s: { t: number }) => s.t >= window[0] && s.t < window[1];
+ // Across, a share of the frame is `aspect` times longer than down.
+ const apart = (b: number[], x: number, y: number) =>
+ Math.hypot((centre(b)[0] - x) * aspect, centre(b)[1] - y);
+ const [a, b] = [original.filter(inside), yours.filter(inside)];
+ const moments = a.flatMap((o, i) => {
+ const y = b[i];
+ if (!o.boxes.length || !y?.boxes.length) return [];
+ const subject = o.boxes.reduce((p, q) => (q[3]! > p[3]! ? q : p));
+ const [ox, oy] = centre(subject);
+ const near = y.boxes.reduce((p, q) => (apart(q, ox, oy) < apart(p, ox, oy) ? q : p));
+ return [{ shift: apart(near, ox, oy) / subject[3]!, scale: near[3]! / subject[3]! }];
+ });
+ if (moments.length < FRAMING_MIN_FACES) return undefined;
+ const shift = round(median(moments.map((m) => m.shift)), 3);
+ const scale = round(median(moments.map((m) => m.scale)), 3);
+ return {
+ window: [round(window[0], 3), round(window[1], 3)],
+ shift,
+ scale,
+ pass: shift <= FRAMING_SHIFT && scale >= FRAMING_SCALE[0] && scale <= FRAMING_SCALE[1],
+ };
+}
+
+/** Lips in sync: the lag inside SYNC_MS, judged only when the reading is confident (it is a motion proxy). */
+export function syncPass(r: Pick): boolean | null {
+ if (r.confidence !== "high" || r.best_lag_ms === null) return null;
+ return r.best_lag_ms >= SYNC_MS[0] && r.best_lag_ms <= SYNC_MS[1];
+}
+
+/** A segment's person: framing per shot, carried text per drawn element, lip sync per long speaking shot. */
+export async function personVerdict(opts: {
+ ref: VideoInfo;
+ yours: VideoInfo;
+ window: [number, number];
+ cuts: number[];
+ clips: (GeneratedClip & { info?: VideoInfo; still?: string })[];
+ drawn: { id: string; box: Roi; window: [number, number] }[];
+}): Promise {
+ const { ref, yours, window } = opts;
+ const shots = shotsIn(window, opts.cuts);
+ const n = Math.max(2, Math.round((window[1] - window[0]) * FACE_RATE));
+ // A face inside a drawn element (a photo on a card) is not the person.
+ const drawnFace = (t: number, b: number[]) =>
+ opts.drawn.some(({ box: [x, y, w, h], window: [a, z] }) => {
+ const [cx, cy] = [(b[0]! + b[2]! / 2) * ref.width, (b[1]! + b[3]! / 2) * ref.height];
+ return t >= a && t < z && cx >= x && cx < x + w && cy >= y && cy < y + h;
+ });
+ const people = (samples: Awaited>) =>
+ samples.map((f) => ({ ...f, boxes: f.boxes.filter((b) => !drawnFace(f.t, b)) }));
+ const [fo, fy] = [
+ people(await faceBoxes(ref, window[0], window[1], n)),
+ people(await faceBoxes(yours, window[0], window[1], n)),
+ ];
+ const framing = shots.flatMap((s) =>
+ s[1] - s[0] >= FRAMING_MIN_S
+ ? [shotFraming(s, fo, fy, ref.width / ref.height)].filter((f) => f !== undefined)
+ : [],
+ );
+ const text = opts.drawn.flatMap((d) =>
+ opts.clips.flatMap((c) =>
+ c.info && c.uses
+ ? [
+ carriedText(
+ ref,
+ yours,
+ { path: c.path, info: c.info, uses: c.uses, still: c.still },
+ d,
+ ),
+ ].filter((t) => t !== undefined)
+ : [],
+ ),
+ );
+ const sync = shots.flatMap((s) => {
+ if (s[1] - s[0] < SYNC_MIN_S || !yours.audio) return [];
+ const mouth = (
+ info: VideoInfo,
+ samples: { t: number; boxes: number[][] }[],
+ ): Roi | undefined => {
+ const boxes = samples
+ .filter((f) => f.t >= s[0] && f.t < s[1] && f.boxes.length)
+ .map((f) => f.boxes.reduce((x, y) => (y[3]! > x[3]! ? y : x)));
+ if (boxes.length < FRAMING_MIN_FACES) return undefined;
+ const [x, y, w, h] = [0, 1, 2, 3].map((i) => median(boxes.map((b) => b[i]!)));
+ const roi: Roi = [
+ Math.round(((x! + 0.2 * w!) * info.width) / 2) * 2,
+ Math.round(((y! + 0.62 * h!) * info.height) / 2) * 2,
+ Math.max(8, Math.round((0.6 * w! * info.width) / 2) * 2),
+ Math.max(8, Math.round((0.38 * h! * info.height) / 2) * 2),
+ ];
+ return roi[0] + roi[2] <= info.width && roi[1] + roi[3] <= info.height ? roi : undefined;
+ };
+ const [mo, my] = [mouth(ref, fo), mouth(yours, fy)];
+ if (!my) return [];
+ const mine = avSync(yours, my, s[0], s[1]);
+ if (mine.speech_active_fraction < SYNC_MIN_SPEECH) return [];
+ const theirs = mo && ref.audio ? avSync(ref, mo, s[0], s[1]) : undefined;
+ return [
+ {
+ window: [round(s[0], 3), round(s[1], 3)] as [number, number],
+ lag_ms: mine.best_lag_ms,
+ original_lag_ms: theirs?.best_lag_ms ?? null,
+ confidence: mine.confidence,
+ pass: syncPass(mine),
+ },
+ ];
+ });
+ const gate = (v: (boolean | null)[]) =>
+ v.includes(false) ? false : v.some((p) => p === true) ? true : null;
+ const gates = {
+ framing: gate(framing.map((f) => f.pass)),
+ text: gate(text.map((t) => !t.carried)),
+ sync: gate(sync.map((s) => s.pass)),
+ };
+ const all = Object.values(gates);
+ return {
+ gates,
+ pass: all.includes(false) ? false : all.some((g) => g === true) ? true : null,
+ ...(framing.length ? { framing } : {}),
+ ...(text.length ? { text } : {}),
+ ...(sync.length ? { sync } : {}),
+ };
+}
diff --git a/packages/cli/src/measure/segments.ts b/packages/cli/src/measure/segments.ts
new file mode 100644
index 0000000000..5d1052cdf6
--- /dev/null
+++ b/packages/cli/src/measure/segments.ts
@@ -0,0 +1,84 @@
+// A segments file: `## S01 · 0.00–2.40 s · title` headings, each with optional lines
+// `Pixels: rebuilt | reused | regenerated`, `Regenerated: x, y, w, h` (source pixels, or shares of the frame when
+// all are ≤ 1), `Drawn: x, y, w, h` with an optional `a–b s`, and `Copy:` quoting a string; see `Segment`.
+import { existsSync, readFileSync } from "node:fs";
+import { Fix } from "./media.js";
+
+/** rebuilt: drawn in HTML; reused: cut from the original; regenerated: new media made for it. */
+export type PixelSource = "rebuilt" | "reused" | "regenerated";
+
+export interface Segment {
+ id: string;
+ start: number;
+ end: number;
+ title: string;
+ pixels: PixelSource;
+ /** A regenerated region inside a rebuilt or reused segment: [x, y, w, h], pixels or shares of the frame. */
+ regenerated?: [number, number, number, number];
+ /** Drawn elements over a regenerated person: their boxes, judged by pixels, and when they show. */
+ drawn?: { box: [number, number, number, number]; window?: [number, number] }[];
+ /** The segment quotes copy: it has drawn text. */
+ copy?: true;
+}
+
+const HEADING =
+ /^##\s+(S\d+)\s*[·|-]\s*(\d+(?:\.\d+)?)\s*[–—-]\s*(\d+(?:\.\d+)?)\s*s\b\s*(?:[·|-]\s*(.*))?$/gm;
+const SOURCES: readonly PixelSource[] = ["rebuilt", "reused", "regenerated"];
+const PIXELS = /^Pixels:\s*(rebuilt|reused|regenerated)\b/im;
+const NUMBER = String.raw`(\d+(?:\.\d+)?)`;
+const SEP = String.raw`(?:\s*,\s*|\s+)`;
+const DRAWN = new RegExp(
+ `^Drawn:\\s*${NUMBER}${SEP}${NUMBER}${SEP}${NUMBER}${SEP}${NUMBER}(?:.*?${NUMBER}\\s*[–—-]\\s*${NUMBER}\\s*s\\b)?`,
+ "gim",
+);
+const COPY = /^Copy:.*["“”]\S/im;
+const REGION =
+ /^Regenerated:\s*(\d+(?:\.\d+)?)(?:\s*,\s*|\s+)(\d+(?:\.\d+)?)(?:\s*,\s*|\s+)(\d+(?:\.\d+)?)(?:\s*,\s*|\s+)(\d+(?:\.\d+)?)/im;
+
+export function parseSegments(markdown: string): Segment[] {
+ const heads = [...markdown.matchAll(HEADING)];
+ // fallow-ignore-next-line complexity
+ return heads.map((m, i) => {
+ const body = markdown.slice(m.index! + m[0].length, heads[i + 1]?.index ?? markdown.length);
+ const found = PIXELS.exec(body)?.[1]?.toLowerCase();
+ const pixels = SOURCES.find((source) => source === found) ?? "rebuilt";
+ const r = REGION.exec(body);
+ const region: Segment["regenerated"] = r
+ ? [Number(r[1]), Number(r[2]), Number(r[3]), Number(r[4])]
+ : undefined;
+ const drawn = [...body.matchAll(DRAWN)].flatMap((d) => {
+ const box: [number, number, number, number] = [
+ Number(d[1]),
+ Number(d[2]),
+ Number(d[3]),
+ Number(d[4]),
+ ];
+ if (box[2] <= 0 || box[3] <= 0) return [];
+ return [d[5] ? { box, window: [Number(d[5]), Number(d[6])] as [number, number] } : { box }];
+ });
+ return {
+ id: m[1]!,
+ start: Number(m[2]),
+ end: Number(m[3]),
+ title: (m[4] ?? "").trim(),
+ pixels,
+ ...(region && pixels !== "regenerated" && region[2]! > 0 && region[3]! > 0
+ ? { regenerated: region }
+ : {}),
+ ...(drawn.length ? { drawn } : {}),
+ ...(COPY.test(body) ? { copy: true as const } : {}),
+ };
+ });
+}
+
+export function readSegments(path: string): Segment[] {
+ if (!existsSync(path))
+ throw new Fix(`no segments file at ${path}`, "pass a file of `## S01 · a–b s` segments");
+ const segments = parseSegments(readFileSync(path, "utf8"));
+ if (!segments.length)
+ throw new Fix(
+ `${path} has no "## S01 · 0.00–2.40 s · title" segment headings`,
+ "write one `## S01 · a–b s · title` heading per segment",
+ );
+ return segments;
+}
diff --git a/packages/cli/src/measure/sync.test.ts b/packages/cli/src/measure/sync.test.ts
new file mode 100644
index 0000000000..566d92e873
--- /dev/null
+++ b/packages/cli/src/measure/sync.test.ts
@@ -0,0 +1,85 @@
+import { execFileSync } from "node:child_process";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, describe, expect, it } from "vitest";
+import { findFFmpeg, findFFprobe } from "../browser/ffmpeg.js";
+import { probeVideo } from "./media.js";
+import { syncPass } from "./person.js";
+import { avSync } from "./sync.js";
+
+const ffmpeg = findFFmpeg();
+const dir = mkdtempSync(join(tmpdir(), "hf-sync-test-"));
+afterAll(() => rmSync(dir, { recursive: true, force: true }));
+
+// Uneven bursts so only one lag lines them up.
+const BURSTS = [
+ [0.3, 0.5],
+ [0.9, 1.0],
+ [1.4, 1.7],
+ [2.1, 2.2],
+ [2.5, 2.8],
+];
+const during = (shift: number) =>
+ BURSTS.map(([a, b]) => `between(t,${a! + shift},${b! + shift})`).join("+");
+
+const MOUTH: [number, number, number, number] = [24, 40, 48, 16];
+
+function inStep(): string {
+ const out = join(dir, "in-step.mp4");
+ execFileSync(ffmpeg!, [
+ ...["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=0x404040:s=96x96:r=30:d=3"],
+ ...["-f", "lavfi", "-i", "sine=f=220:d=3"],
+ "-filter_complex",
+ `[0]drawbox=x=24:y=40:w=48:h=16:color=white:t=fill:enable='${during(0)}'[v];` +
+ `[1]volume='if(${during(0)},1,0)':eval=frame[a]`,
+ ...["-map", "[v]", "-map", "[a]", "-pix_fmt", "yuv420p", "-c:v", "libx264", "-qp", "0", out],
+ ]);
+ return out;
+}
+
+/** The same streams with one of them stamped 0.2 s later, as a real muxer leaves it. */
+function shifted(source: string, late: "video" | "audio"): string {
+ const out = join(dir, `${late}-late.mp4`);
+ const [first, second] =
+ late === "video" ? [["-itsoffset", "0.2"], []] : [[], ["-itsoffset", "0.2"]];
+ execFileSync(ffmpeg!, [
+ ...["-v", "error", "-y", ...first, "-i", source, ...second, "-i", source],
+ ...["-map", "0:v", "-map", "1:a", "-c", "copy", out],
+ ]);
+ return out;
+}
+
+describe.skipIf(!ffmpeg || !findFFprobe())("avSync", () => {
+ it("reads the sound on its own timestamps, not from its first sample", () => {
+ const aligned = inStep();
+ expect(Math.abs(avSync(probeVideo(aligned), MOUTH, 0, 3).best_lag_ms!)).toBeLessThan(20);
+ expect(Math.abs(avSync(probeVideo(aligned), MOUTH, 0.2, 2.9).best_lag_ms!)).toBeLessThan(20);
+ const quiet = avSync(probeVideo(shifted(aligned, "audio")), MOUTH, 0, 3);
+ expect(quiet.best_lag_ms).toBeGreaterThan(-230);
+ expect(quiet.best_lag_ms).toBeLessThan(-170);
+ expect(syncPass(quiet)).toBe(false);
+ const inside = avSync(probeVideo(shifted(aligned, "audio")), MOUTH, 0.2, 2.9);
+ expect(inside.best_lag_ms).toBeLessThan(-170);
+ const late = avSync(probeVideo(shifted(aligned, "video")), MOUTH, 0, 3);
+ expect(late.best_lag_ms).toBeGreaterThan(170);
+ expect(late.best_lag_ms).toBeLessThan(230);
+ });
+
+ it("finds a picture two frames late", () => {
+ const out = join(dir, "late.mp4");
+ execFileSync(ffmpeg!, [
+ ...["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=0x404040:s=96x96:r=30:d=3"],
+ ...["-f", "lavfi", "-i", "sine=f=220:d=3"],
+ "-filter_complex",
+ `[0]drawbox=x=24:y=40:w=48:h=16:color=white:t=fill:enable='${during(2 / 30)}'[v];` +
+ `[1]volume='if(${during(0)},1,0)':eval=frame[a]`,
+ ...["-map", "[v]", "-map", "[a]", "-pix_fmt", "yuv420p", "-c:v", "libx264", "-qp", "0", out],
+ ]);
+ const r = avSync(probeVideo(out), [24, 40, 48, 16], 0, 3);
+ expect(r.best_lag_frames).toBeGreaterThan(1.5);
+ expect(r.best_lag_frames).toBeLessThan(2.5);
+ expect(r.best_lag_ms).toBeGreaterThan(0);
+ expect(r.confidence).not.toBe("none");
+ });
+});
diff --git a/packages/cli/src/measure/sync.ts b/packages/cli/src/measure/sync.ts
new file mode 100644
index 0000000000..4690cf7d39
--- /dev/null
+++ b/packages/cli/src/measure/sync.ts
@@ -0,0 +1,139 @@
+// Picture against sound for a person speaking, ported from the Studio's hf-media av_sync: per frame the mouth
+// region's mean luma change, per frame the change of the sound's loudness, and the lag where the two correlate best.
+// A motion and energy proxy, not phoneme sync: head motion, gestures, cuts and music in the ROI or mix move it.
+import {
+ Fix,
+ pearson,
+ readClip,
+ round,
+ runFfmpeg,
+ videoClip,
+ type Roi,
+ type VideoInfo,
+} from "./media.js";
+
+const RATE = 16000;
+
+/** Mono samples of the window at RATE Hz. */
+function samples(info: VideoInfo, start: number, seconds: number): Float32Array {
+ const raw = runFfmpeg([
+ ...["-ss", String(start), "-i", info.path, "-t", String(seconds), "-vn"],
+ ...["-af", "aresample=async=1:first_pts=0"],
+ ...["-ac", "1", "-ar", String(RATE), "-f", "f32le", "-"],
+ ]);
+ return new Float32Array(raw.buffer.slice(raw.byteOffset, raw.byteOffset + (raw.byteLength & ~3)));
+}
+
+export interface SyncResult {
+ best_lag_frames: number | null;
+ best_lag_ms: number | null;
+ peak_correlation: number | null;
+ zero_lag_correlation: number | null;
+ margin_over_other_lags: number | null;
+ confidence: "high" | "medium" | "low" | "none";
+ speech_active_fraction: number;
+ mouth_motion_mean: number;
+ note: string | null;
+}
+
+// fallow-ignore-next-line complexity
+export function avSync(
+ info: VideoInfo,
+ mouth: Roi,
+ start: number,
+ end: number,
+ maxLagMs = 400,
+): SyncResult {
+ if (!info.audio)
+ throw new Fix(
+ `${info.path} has no sound`,
+ "measure sync needs the picture and its sound in one file",
+ );
+ if (!(maxLagMs > 0)) throw new Fix("--max-lag-ms must be positive", "--max-lag-ms 400");
+ const { frames, w, h } = readClip(videoClip(info.path, start, end - start, info), {
+ roi: mouth,
+ width: 160,
+ gray: true,
+ });
+ const motion = frames.map((f, i) => {
+ if (!i) return 0;
+ let s = 0;
+ for (let k = 0; k < f.length; k++) s += Math.abs(f[k]! - frames[i - 1]![k]!);
+ return s / (w * h);
+ });
+ const audio = samples(info, start, end - start);
+ const frame = 1 / info.fps;
+ const envelope = frames.map((_, i) => {
+ const [a, b] = [Math.floor(i * frame * RATE), Math.floor((i + 1) * frame * RATE)];
+ const chunk = audio.subarray(a, Math.max(b, a + 1));
+ let s = 0;
+ for (const v of chunk) s += v * v;
+ return chunk.length ? Math.sqrt(s / chunk.length) : 0;
+ });
+ const speech = envelope.slice(1).map((v, i) => Math.abs(v - envelope[i]!));
+ const mouthMotion = motion.slice(1);
+ const reach = Math.max(1, Math.round(maxLagMs / 1000 / frame));
+ // Positive lag: the mouth moves after the sound, the picture is late.
+ const curve = Array.from({ length: 2 * reach + 1 }, (_, i) => {
+ const lag = i - reach;
+ const [a, b] =
+ lag >= 0
+ ? [speech.slice(0, speech.length - lag), mouthMotion.slice(lag)]
+ : [speech.slice(-lag), mouthMotion.slice(0, lag)];
+ return { lag, r: Math.min(a.length, b.length) < 10 ? null : pearson(a, b) };
+ });
+ const top = Math.max(...envelope);
+ const active = top > 0 ? envelope.filter((v) => v > 0.1 * top).length / envelope.length : 0;
+ const base = {
+ speech_active_fraction: round(active, 3),
+ mouth_motion_mean: round(mouthMotion.reduce((s, v) => s + v, 0) / (mouthMotion.length || 1), 3),
+ };
+ const valid = curve.filter((c) => c.r !== null);
+ if (!valid.length)
+ return {
+ best_lag_frames: null,
+ best_lag_ms: null,
+ peak_correlation: null,
+ zero_lag_correlation: null,
+ margin_over_other_lags: null,
+ confidence: "none",
+ ...base,
+ note: "no mouth motion or no change in the sound in this window; check the ROI and the window",
+ };
+ const best = curve.reduce(
+ (b, c, i) => ((c.r ?? -Infinity) > (curve[b]!.r ?? -Infinity) ? i : b),
+ 0,
+ );
+ const peak = curve[best]!.r!;
+ // A parabola through the peak and its neighbours places it between frames.
+ let shift = 0;
+ const [left, right] = [curve[best - 1]?.r, curve[best + 1]?.r];
+ if (typeof left === "number" && typeof right === "number") {
+ const bend = left - 2 * peak + right;
+ if (bend < 0) shift = (0.5 * (left - right)) / bend;
+ }
+ const lag = curve[best]!.lag;
+ const rest = curve.filter((c) => Math.abs(c.lag - lag) > 2 && c.r !== null).map((c) => c.r!);
+ const margin = rest.length ? peak - Math.max(...rest) : null;
+ const edge = best === 0 || best === curve.length - 1;
+ const confidence =
+ peak >= 0.5 && margin !== null && margin >= 0.1 && !edge && active >= 0.1
+ ? "high"
+ : peak >= 0.3 && !edge
+ ? "medium"
+ : "low";
+ const notes = [
+ ...(edge ? ["the peak is at the search edge; raise --max-lag-ms or check the window"] : []),
+ ...(active < 0.1 ? ["little speech in this window; choose a span with continuous speech"] : []),
+ ];
+ return {
+ best_lag_frames: round(lag + shift, 2),
+ best_lag_ms: round((lag + shift) * frame * 1000, 1),
+ peak_correlation: round(peak, 3),
+ zero_lag_correlation: round(curve.find((c) => c.lag === 0)?.r ?? 0, 3),
+ margin_over_other_lags: margin === null ? null : round(margin, 3),
+ confidence,
+ ...base,
+ note: notes.join("; ") || null,
+ };
+}
diff --git a/packages/cli/src/media-use/lib/adopt.mjs b/packages/cli/src/media-use/lib/adopt.mjs
index b140ed02c7..e9950ffbf0 100644
--- a/packages/cli/src/media-use/lib/adopt.mjs
+++ b/packages/cli/src/media-use/lib/adopt.mjs
@@ -9,18 +9,19 @@ const AUDIO_EXT = new Set([".mp3", ".wav", ".ogg", ".m4a", ".aac"]);
const IMAGE_EXT = new Set([".jpg", ".jpeg", ".png", ".gif", ".webp", ".svg", ".ico"]);
const VIDEO_EXT = new Set([".mp4", ".webm", ".mov"]);
+function audioKind(filePath) {
+ const words = filePath.toLowerCase().split(/[^a-z0-9]+/);
+ const has = (test) => words.some(test);
+ if (has((w) => w === "bgm" || w === "music" || w === "soundtrack")) return "bgm";
+ if (has((w) => w === "sfx" || w === "fx" || (w.startsWith("sound") && w !== "soundtrack")))
+ return "sfx";
+ if (has((w) => w.startsWith("voice") || w.startsWith("narrat"))) return "voice";
+ return "bgm";
+}
+
function inferType(filePath) {
const ext = extname(filePath).toLowerCase();
- if (AUDIO_EXT.has(ext)) {
- const lower = filePath.toLowerCase();
- if (lower.includes("/bgm/") || lower.includes("/music/") || lower.startsWith("bgm/"))
- return "bgm";
- if (lower.includes("/sfx/") || lower.includes("/sound") || lower.startsWith("sfx/"))
- return "sfx";
- if (lower.includes("/voice/") || lower.includes("/narrat") || lower.startsWith("voice/"))
- return "voice";
- return "bgm";
- }
+ if (AUDIO_EXT.has(ext)) return audioKind(filePath);
if (IMAGE_EXT.has(ext)) {
if (ext === ".svg" || ext === ".ico") return "icon";
return "image";
diff --git a/packages/cli/src/media-use/lib/adopt.test.mjs b/packages/cli/src/media-use/lib/adopt.test.mjs
index a961ae1776..9e9484380b 100644
--- a/packages/cli/src/media-use/lib/adopt.test.mjs
+++ b/packages/cli/src/media-use/lib/adopt.test.mjs
@@ -74,6 +74,28 @@ function runTests() {
cleanup();
});
+ test("labels an audio file by its folder or its file name, not always bgm", () => {
+ setup();
+ drop("voice-intro.mp3");
+ drop("sfx-click.mp3");
+ drop("narration.mp3");
+ drop("soundtrack/main.mp3");
+ drop("track.mp3");
+ drop("soundfx/pop.mp3");
+ const types = Object.fromEntries(
+ adoptExistingAssets(tmp).map((record) => [record.path, record.type]),
+ );
+ assert.deepEqual(types, {
+ "assets/voice-intro.mp3": "voice",
+ "assets/sfx-click.mp3": "sfx",
+ "assets/narration.mp3": "voice",
+ "assets/soundtrack/main.mp3": "bgm",
+ "assets/track.mp3": "bgm",
+ "assets/soundfx/pop.mp3": "sfx",
+ });
+ cleanup();
+ });
+
let passed = 0;
let failed = 0;
for (const { name, fn } of tests) {
diff --git a/packages/cli/src/media-use/lib/heygen-cli.mjs b/packages/cli/src/media-use/lib/heygen-cli.mjs
index 214b93ae9e..3873b4c616 100644
--- a/packages/cli/src/media-use/lib/heygen-cli.mjs
+++ b/packages/cli/src/media-use/lib/heygen-cli.mjs
@@ -10,8 +10,8 @@ export const HEYGEN_MIN_VERSION = "0.3.0";
// installer text out of the runtime module; the docs are the safer source of
// truth for platform-specific setup.
export const HEYGEN_INSTALL_COMMAND =
- "Install the CLI from https://developers.heygen.com/cli, then run: heygen auth login --oauth";
-export const HEYGEN_AUTH_COMMAND = "heygen auth login --oauth";
+ "Install the CLI from https://developers.heygen.com/cli, then run: hyperframes auth login";
+export const HEYGEN_AUTH_COMMAND = "hyperframes auth login";
export const HEYGEN_UPDATE_COMMAND = "heygen update";
export const HEYGEN_CLIENT_SOURCE_ARGV = ["--headers", "X-HeyGen-Client-Source: media-use"];
diff --git a/packages/cli/src/media-use/lib/index-gen.d.mts b/packages/cli/src/media-use/lib/index-gen.d.mts
new file mode 100644
index 0000000000..1f0a9196ff
--- /dev/null
+++ b/packages/cli/src/media-use/lib/index-gen.d.mts
@@ -0,0 +1 @@
+export function regenerateIndex(projectDir: string): void;
diff --git a/packages/cli/src/media-use/lib/manifest.d.mts b/packages/cli/src/media-use/lib/manifest.d.mts
index f282474e28..d8f19e0a91 100644
--- a/packages/cli/src/media-use/lib/manifest.d.mts
+++ b/packages/cli/src/media-use/lib/manifest.d.mts
@@ -18,3 +18,24 @@ export function withReservedFileSync(
ext: string,
populate: (reservation: Reservation) => T,
): T;
+
+export interface MediaRecord {
+ id: string;
+ type: string;
+ path: string;
+ source: string;
+ description: string;
+ duration?: number;
+ provenance?: Record;
+}
+export function recordInPlace(
+ projectDir: string,
+ record: {
+ type: string;
+ path: string;
+ source: string;
+ description?: string;
+ duration?: number;
+ provenance?: Record;
+ },
+): MediaRecord;
diff --git a/packages/cli/src/media-use/lib/telemetry.mjs b/packages/cli/src/media-use/lib/telemetry.mjs
index 182e3505b5..3bc278a6b8 100644
--- a/packages/cli/src/media-use/lib/telemetry.mjs
+++ b/packages/cli/src/media-use/lib/telemetry.mjs
@@ -1,7 +1,7 @@
// Usage tracking shares the CLI and Studio identity. Properties stay coarse and
// never carry intent text, file names, or paths.
-import { randomUUID } from "node:crypto";
+import { createHash, randomUUID } from "node:crypto";
import * as fs from "node:fs";
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
@@ -119,21 +119,51 @@ function anonymousId() {
}
}
-function heygenAccountDistinctId() {
- const file = join(process.env.HEYGEN_CONFIG_DIR || join(homedir(), ".heygen"), "credentials");
+// The HyperFrames user id for a HeyGen username: the same sha256-derived UUID
+// the CLI (auth/telemetryIdentity.ts), web app and Desktop key PostHog on.
+const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+export function heygenUserId(username) {
+ if (UUID_PATTERN.test(username)) return username;
+ const hash = createHash("sha256").update(username).digest();
+ hash[6] = (hash[6] & 0x0f) | 0x50;
+ hash[8] = (hash[8] & 0x3f) | 0x80;
+ const hex = hash.toString("hex");
+ return [
+ hex.slice(0, 8),
+ hex.slice(8, 12),
+ hex.slice(12, 16),
+ hex.slice(16, 20),
+ hex.slice(20, 32),
+ ].join("-");
+}
+
+// The signed-in HeyGen account, keyed like the CLI's own identify call: the
+// username's user id, else the lowercased email (lowercased so different stored
+// casing never splits one person). `heygen_username` is the cross-project join
+// column for the Snowflake event table.
+function heygenAccount() {
+ const root = process.env.HYPERFRAMES_CONFIG_DIR || join(homedir(), ".hyperframes");
+ const file = join(root, ...(process.env.HYPERFRAMES_ENV === "dev" ? ["dev"] : []), "credentials");
try {
if (!existsSync(file)) return null;
const raw = readFileSync(file, "utf8").trim();
if (!raw.startsWith("{")) return null;
const parsed = JSON.parse(raw);
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
+ if (!parsed.api_key && !parsed.oauth) return null;
const user = parsed.user;
if (!user || typeof user !== "object" || Array.isArray(user)) return null;
- const id = typeof user.email === "string" && user.email.trim() ? user.email : user.username;
- // Lowercased so this joins with the CLI's own identify call regardless of
- // the account's stored email casing — two different-case distinct ids
- // would otherwise split one person across two PostHog profiles.
- return typeof id === "string" && id.trim() ? id.trim().toLowerCase() : null;
+ const email =
+ typeof user.email === "string" && user.email.trim() ? user.email.trim().toLowerCase() : null;
+ const username =
+ typeof user.username === "string" && user.username.trim() ? user.username : null;
+ const traits = {};
+ if (email) traits.email = email;
+ if (username) traits.heygen_username = username;
+ if (username) return { distinctId: heygenUserId(username), traits };
+ if (email) return { distinctId: email, traits };
+ return null;
} catch {
return null;
}
@@ -149,7 +179,7 @@ function showTelemetryNotice() {
console.error(
[
"media-use sends usage telemetry: media type, resolution source, and provider; never intent text, file names, or paths.",
- "If you sign in to HeyGen, usage links to your account email or username. Opt out with HYPERFRAMES_NO_TELEMETRY=1 or DO_NOT_TRACK=1.",
+ "If you sign in to HeyGen, usage links to your account (email and username). Opt out with HYPERFRAMES_NO_TELEMETRY=1 or DO_NOT_TRACK=1.",
].join("\n"),
);
updateSharedConfig({ telemetryNoticeShown: true });
@@ -182,12 +212,14 @@ async function postEvent(event, properties, distinctId) {
]);
}
-async function identifyAccount(anonId) {
- if (optedOut() || identifiedAccount) return;
- const distinctId = heygenAccountDistinctId();
- if (!distinctId) return;
+async function identifyAccount(anonId, account) {
+ if (optedOut() || identifiedAccount || !account) return;
identifiedAccount = true;
- await postEvent("$identify", { $anon_distinct_id: anonId }, distinctId);
+ await postEvent(
+ "$identify",
+ { $anon_distinct_id: anonId, $set: account.traits },
+ account.distinctId,
+ );
}
/**
@@ -199,8 +231,11 @@ export async function track(event, properties = {}) {
if (optedOut()) return;
showTelemetryNotice();
const anonId = anonymousId();
- await identifyAccount(anonId);
- await postEvent(event, properties, anonId);
+ const account = heygenAccount();
+ await identifyAccount(anonId, account);
+ const username = account?.traits.heygen_username;
+ if (!username) return postEvent(event, properties, anonId);
+ await postEvent(event, { ...properties, heygen_username: username }, heygenUserId(username));
}
export function __anonymousIdForTest() {
diff --git a/packages/cli/src/media-use/lib/telemetry.test.mjs b/packages/cli/src/media-use/lib/telemetry.test.mjs
index 19db85a4cb..fc0b021bac 100644
--- a/packages/cli/src/media-use/lib/telemetry.test.mjs
+++ b/packages/cli/src/media-use/lib/telemetry.test.mjs
@@ -19,6 +19,8 @@ function sandbox() {
const home = join(root, "home");
mkdirSync(home, { recursive: true });
process.env.HOME = home;
+ delete process.env.HYPERFRAMES_CONFIG_DIR;
+ delete process.env.HYPERFRAMES_ENV;
process.env.HYPERFRAMES_MEDIA_HOME = home;
return { root, home };
}
@@ -181,10 +183,13 @@ test("track identifies a signed-in HeyGen account once and still sends events",
join(home, ".hyperframes/config.json"),
JSON.stringify({ anonymousId: "anon-1" }),
);
- mkdirSync(join(home, ".heygen"), { recursive: true });
+ mkdirSync(join(home, ".hyperframes"), { recursive: true });
writeFileSync(
- join(home, ".heygen/credentials"),
- JSON.stringify({ user: { email: "alice@example.com", username: "alice" } }),
+ join(home, ".hyperframes/credentials"),
+ JSON.stringify({
+ api_key: "hg_test",
+ user: { email: "alice@example.com", username: "alice" },
+ }),
);
await track("media_use_resolve", { type: "bgm", source: "search" });
@@ -193,9 +198,19 @@ test("track identifies a signed-in HeyGen account once and still sends events",
const batch = parseFetchBodies(calls);
const identify = batch.filter((item) => item.event === "$identify");
assert.equal(identify.length, 1);
- assert.equal(identify[0].distinct_id, "alice@example.com");
+ // heygenUserId("alice"): the same id the CLI's own login identify uses.
+ assert.equal(identify[0].distinct_id, "2bd806c9-7f0e-50af-9a1f-c3328fa763a9");
assert.equal(identify[0].properties.$anon_distinct_id, "anon-1");
- assert.equal(batch.filter((item) => item.event === "media_use_resolve").length, 2);
+ assert.deepEqual(identify[0].properties.$set, {
+ email: "alice@example.com",
+ heygen_username: "alice",
+ });
+ const resolves = batch.filter((item) => item.event === "media_use_resolve");
+ assert.equal(resolves.length, 2);
+ assert.ok(resolves.every((item) => item.properties.heygen_username === "alice"));
+ assert.ok(
+ resolves.every((item) => item.distinct_id === "2bd806c9-7f0e-50af-9a1f-c3328fa763a9"),
+ );
} finally {
globalThis.fetch = originalFetch;
restoreEnv(savedEnv);
@@ -204,7 +219,50 @@ test("track identifies a signed-in HeyGen account once and still sends events",
}
});
-test("track identifies with a lowercased email regardless of stored casing", async () => {
+test("track uses the selected dev HyperFrames account instead of a HeyGen or production login", async () => {
+ const savedEnv = { ...process.env };
+ const originalFetch = globalThis.fetch;
+ const { root, home } = sandbox();
+ const calls = [];
+ globalThis.fetch = async (url, options) => {
+ calls.push({ url, options });
+ return { ok: true };
+ };
+ try {
+ withoutTelemetryOptOut();
+ process.env.HYPERFRAMES_CONFIG_DIR = join(home, "hf-auth");
+ process.env.HYPERFRAMES_ENV = "dev";
+ process.env.HEYGEN_CONFIG_DIR = join(home, "heygen");
+ for (const [dir, email] of [
+ [process.env.HEYGEN_CONFIG_DIR, "other@example.com"],
+ [process.env.HYPERFRAMES_CONFIG_DIR, "prod@example.com"],
+ [join(process.env.HYPERFRAMES_CONFIG_DIR, "dev"), "dev@example.com"],
+ ]) {
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(
+ join(dir, "credentials"),
+ JSON.stringify({
+ oauth: { access_token: "test-access" },
+ user: { email, username: email },
+ }),
+ );
+ }
+ await track("media_use_resolve", { type: "voice" });
+ const identify = parseFetchBodies(calls).filter((item) => item.event === "$identify");
+ assert.equal(identify.length, 1);
+ assert.equal(identify[0].properties.$set.heygen_username, "dev@example.com");
+ const event = parseFetchBodies(calls).find((item) => item.event === "media_use_resolve");
+ assert.equal(event.properties.heygen_username, "dev@example.com");
+ assert.equal(event.distinct_id, identify[0].distinct_id);
+ } finally {
+ globalThis.fetch = originalFetch;
+ restoreEnv(savedEnv);
+ rmSync(root, { recursive: true, force: true });
+ __resetTelemetryForTest();
+ }
+});
+
+test("track falls back to a lowercased email when the account has no username", async () => {
const savedEnv = { ...process.env };
const originalFetch = globalThis.fetch;
const { root, home } = sandbox();
@@ -220,10 +278,10 @@ test("track identifies with a lowercased email regardless of stored casing", asy
join(home, ".hyperframes/config.json"),
JSON.stringify({ anonymousId: "anon-3" }),
);
- mkdirSync(join(home, ".heygen"), { recursive: true });
+ mkdirSync(join(home, ".hyperframes"), { recursive: true });
writeFileSync(
- join(home, ".heygen/credentials"),
- JSON.stringify({ user: { email: "Alice@Example.com", username: "alice" } }),
+ join(home, ".hyperframes/credentials"),
+ JSON.stringify({ api_key: "hg_test", user: { email: "Alice@Example.com" } }),
);
await track("media_use_resolve", { type: "bgm", source: "search" });
@@ -269,6 +327,7 @@ test("track does not identify when signed out", async () => {
);
assert.equal(batch[0].event, "media_use_resolve");
assert.equal(batch[0].distinct_id, "anon-2");
+ assert.equal(batch[0].properties.heygen_username, undefined);
} finally {
globalThis.fetch = originalFetch;
restoreEnv(savedEnv);
diff --git a/packages/cli/src/media-use/resolve.test.mjs b/packages/cli/src/media-use/resolve.test.mjs
index dc8a2ce01b..c1f366db35 100644
--- a/packages/cli/src/media-use/resolve.test.mjs
+++ b/packages/cli/src/media-use/resolve.test.mjs
@@ -1422,7 +1422,7 @@ async function captureResolveEvent({ provider, type = "bgm", intent }) {
// never touch the real developer machine, and point the host at the local
// server. HEYGEN_CONFIG_DIR is sandboxed too -- runResolve's env is
// {...process.env, ...env}, so a developer with that var set to a real
- // credentials dir would otherwise have heygenAccountDistinctId() read
+ // credentials dir would otherwise have heygenAccount() read
// their real email into this test's local-server payload despite HOME
// being sandboxed (HEYGEN_CONFIG_DIR, not HOME, resolves the credentials
// path). Every other test in this file keeps its untouched default env.
diff --git a/packages/cli/src/registry/captionLastGroup.chromium.test.ts b/packages/cli/src/registry/captionLastGroup.chromium.test.ts
new file mode 100644
index 0000000000..a602b862af
--- /dev/null
+++ b/packages/cli/src/registry/captionLastGroup.chromium.test.ts
@@ -0,0 +1,71 @@
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { readFileSync } from "node:fs";
+import { createRequire } from "node:module";
+import puppeteer, { type Browser } from "puppeteer-core";
+
+const executablePath = process.env.PUPPETEER_EXECUTABLE_PATH;
+const componentHtml = readFileSync(
+ new URL(
+ "../../../../registry/components/caption-highlight/caption-highlight.html",
+ import.meta.url,
+ ),
+ "utf8",
+);
+const gsapScript = readFileSync(
+ createRequire(new URL("../../../core/package.json", import.meta.url)).resolve(
+ "gsap/dist/gsap.min.js",
+ ),
+ "utf8",
+);
+
+/** Scaled demo words: the last group opens before the old 7.95 s cap and its last word ends after it. */
+const STRETCH = 1.15;
+const LAST_WORD_START_S = 7.3 * STRETCH;
+const LAST_WORD_END_S = 7.7 * STRETCH;
+
+function stretchedComponent(): string {
+ const wordsStart = componentHtml.indexOf("var WORDS = [");
+ const wordsEnd = componentHtml.indexOf("];", wordsStart);
+ const words = componentHtml
+ .slice(wordsStart, wordsEnd)
+ .replace(/(start|end): ([\d.]+)/g, (_, key, value) => `${key}: ${Number(value) * STRETCH}`);
+ return (componentHtml.slice(0, wordsStart) + words + componentHtml.slice(wordsEnd)).replace(
+ /`,
+ );
+}
+
+describe.runIf(executablePath)("caption-highlight last group in Chromium", () => {
+ let browser: Browser;
+
+ beforeAll(async () => {
+ browser = await puppeteer.launch({ executablePath, args: ["--no-sandbox"] });
+ });
+
+ afterAll(async () => {
+ await browser?.close();
+ });
+
+ async function lastGroupVisibleAt(time: number): Promise {
+ const page = await browser.newPage();
+ try {
+ await page.setContent(stretchedComponent());
+ return await page.evaluate((t) => {
+ const timeline = (
+ window as unknown as { __timelines: Record }
+ ).__timelines["caption-highlight"];
+ timeline!.seek(t);
+ const groups = document.querySelectorAll(".hl-group");
+ const style = getComputedStyle(groups[groups.length - 1]!);
+ return style.visibility !== "hidden" && Number(style.opacity) > 0;
+ }, time);
+ } finally {
+ await page.close();
+ }
+ }
+
+ it("shows the last phrase from its first word to just before its last word ends", async () => {
+ expect(await lastGroupVisibleAt(LAST_WORD_START_S)).toBe(true);
+ expect(await lastGroupVisibleAt(LAST_WORD_END_S - 0.05)).toBe(true);
+ });
+});
diff --git a/packages/cli/src/registry/registryComponents.test.ts b/packages/cli/src/registry/registryComponents.test.ts
index 4f3cfa1969..0352fa464b 100644
--- a/packages/cli/src/registry/registryComponents.test.ts
+++ b/packages/cli/src/registry/registryComponents.test.ts
@@ -56,6 +56,18 @@ describe("registry components", () => {
expect(invalidMedia).toEqual([]);
});
+ it("never caps a caption's last group at a fixed demo-length constant", () => {
+ const capped: string[] = [];
+
+ for (const entry of readdirSync(componentsDir, { withFileTypes: true })) {
+ if (!entry.isDirectory() || !entry.name.startsWith("caption-")) continue;
+ const html = readFileSync(join(componentsDir, entry.name, `${entry.name}.html`), "utf8");
+ if (/nextStart\s*=[^;]*:\s*\d+(?:\.\d+)?;/.test(html)) capped.push(entry.name);
+ }
+
+ expect(capped).toEqual([]);
+ });
+
it("ships demos without source-less media", async () => {
const invalidMedia: string[] = [];
diff --git a/packages/cli/src/registry/resolver.test.ts b/packages/cli/src/registry/resolver.test.ts
index 910a0c065d..8ee896e337 100644
--- a/packages/cli/src/registry/resolver.test.ts
+++ b/packages/cli/src/registry/resolver.test.ts
@@ -278,6 +278,14 @@ describe("registry resolver", () => {
);
});
+ it("names the closest items when the requested one is not in the registry", async () => {
+ mockFetch();
+ const baseUrl = uniqueBaseUrl();
+ await expect(resolveItemWithDependencies("alpha-gamma-reveal", { baseUrl })).rejects.toThrow(
+ /Item "alpha-gamma-reveal" not found in registry\. Closest: alpha, gamma\. Available: /,
+ );
+ });
+
it("throws a clear cycle error for circular dependencies", async () => {
mockFetch({ dependencies: { alpha: ["gamma"], beta: ["alpha"], gamma: ["beta"] } });
const baseUrl = uniqueBaseUrl();
diff --git a/packages/cli/src/registry/resolver.ts b/packages/cli/src/registry/resolver.ts
index f22e40909e..fe59b3a0b4 100644
--- a/packages/cli/src/registry/resolver.ts
+++ b/packages/cli/src/registry/resolver.ts
@@ -7,6 +7,7 @@
import type { ItemType, RegistryItem, RegistryManifestEntry } from "@hyperframes/core";
import { fetchItemManifest, fetchRegistryManifest, DEFAULT_REGISTRY_URL } from "./remote.js";
import { runWithConcurrencyLimit } from "../utils/concurrency.js";
+import { closestNames } from "../utils/didYouMean.js";
export interface ResolveOptions {
baseUrl?: string;
@@ -145,9 +146,13 @@ export async function resolveItemWithDependencies(
const entry = entries.find((e) => e.name === name);
if (!entry) {
const available = entries.map((e) => e.name).join(", ");
+ const close = closestNames(
+ name,
+ entries.map((e) => e.name),
+ );
throw new Error(
available.length > 0
- ? `Item "${name}" not found in registry. Available: ${available}`
+ ? `Item "${name}" not found in registry.${close.length > 0 ? ` Closest: ${close.join(", ")}.` : ""} Available: ${available}`
: unreachableRegistryMessage(name, options.baseUrl),
);
}
diff --git a/packages/cli/src/server/gsapVendor.ts b/packages/cli/src/server/gsapVendor.ts
new file mode 100644
index 0000000000..80c2764ecb
--- /dev/null
+++ b/packages/cli/src/server/gsapVendor.ts
@@ -0,0 +1,50 @@
+import { existsSync } from "node:fs";
+import { createRequire } from "node:module";
+import { dirname, join, resolve } from "node:path";
+import { GSAP_CDN_VERSION, gsapCdnDist } from "@hyperframes/core/gsap-cdn";
+import { readBundleFile } from "./readBundleFile.js";
+
+export const GSAP_VENDOR_FILES = new Set([
+ "gsap.min.js",
+ "CustomEase.min.js",
+ "MotionPathPlugin.min.js",
+]);
+
+function installedGsapDist(): string | null {
+ try {
+ const coreRequire = createRequire(resolve(__dirname, "..", "..", "..", "core", "package.json"));
+ return join(dirname(coreRequire.resolve("gsap/package.json")), "dist");
+ } catch {
+ return null;
+ }
+}
+
+/** The bundled GSAP dist dir, or null so preview keeps loading GSAP from jsDelivr. */
+export function resolveGsapVendorDir(): string | null {
+ const vendored = join("vendor", "npm", `gsap@${GSAP_CDN_VERSION}`, "dist");
+ const candidates = [
+ resolve(__dirname, vendored),
+ // Running from source: the built CLI next door, then core's installed gsap.
+ resolve(__dirname, "..", "..", "dist", vendored),
+ installedGsapDist(),
+ ];
+ for (const dir of candidates) {
+ if (!dir) continue;
+ if (!existsSync(join(dir, "gsap.min.js"))) continue;
+ const manifest = readBundleFile(join(dir, "..", "package.json"));
+ if (manifest && JSON.parse(manifest.toString("utf-8")).version !== GSAP_CDN_VERSION) continue;
+ return dir;
+ }
+ return null;
+}
+
+const CDN_DIST = gsapCdnDist();
+
+/** The bundled copy of a jsDelivr GSAP file at the CLI's own version, or null for any other URL. */
+export function bundledGsapFor(url: string): { body: Buffer; contentType: string } | null {
+ if (!url.startsWith(CDN_DIST)) return null;
+ const file = url.slice(CDN_DIST.length);
+ const dir = GSAP_VENDOR_FILES.has(file) ? resolveGsapVendorDir() : null;
+ const body = dir ? readBundleFile(join(dir, file)) : null;
+ return body ? { body, contentType: "text/javascript; charset=utf-8" } : null;
+}
diff --git a/packages/cli/src/server/portUtils.test.ts b/packages/cli/src/server/portUtils.test.ts
index e21a9f6a2d..ac5562367f 100644
--- a/packages/cli/src/server/portUtils.test.ts
+++ b/packages/cli/src/server/portUtils.test.ts
@@ -2,10 +2,11 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { createServer, type Server } from "node:net";
import { spawn } from "node:child_process";
import { resolve } from "node:path";
-import { createServer as createHttpServer, type Server as HttpServer } from "node:http";
+import { createServer as createHttpServer, get, type Server as HttpServer } from "node:http";
import {
PORT_PROBE_HOSTS,
activeServerOnPort,
+ closeServer,
detectHyperframesServer,
findPortAndServe,
testPortOnAllHosts,
@@ -306,3 +307,25 @@ describe("detectHyperframesServer", () => {
expect(result).toEqual({ type: "match" });
});
});
+
+describe("closeServer", () => {
+ it("closes while a client holds an event stream open", async () => {
+ const server = createHttpServer((_req, res) => {
+ res.writeHead(200, { "content-type": "text/event-stream" });
+ res.write(": open\n\n");
+ });
+ const port = await new Promise((resolve) =>
+ server.listen(0, "127.0.0.1", () =>
+ resolve((server.address() as import("node:net").AddressInfo).port),
+ ),
+ );
+ await new Promise((resolve) =>
+ get(`http://127.0.0.1:${port}/`, (res) => {
+ res.on("error", () => {});
+ resolve();
+ }).on("error", () => {}),
+ );
+ await closeServer(server);
+ expect(server.listening).toBe(false);
+ });
+});
diff --git a/packages/cli/src/server/portUtils.ts b/packages/cli/src/server/portUtils.ts
index c0a1971118..3c13d1967f 100644
--- a/packages/cli/src/server/portUtils.ts
+++ b/packages/cli/src/server/portUtils.ts
@@ -413,6 +413,12 @@ export async function killActiveServers(
return { killed, unverified };
}
+/** Stops `server` once every open connection is closed too; an open Studio tab holds its event stream for its life. */
+export function closeServer(server: import("@hono/node-server").ServerType): Promise {
+ if ("closeAllConnections" in server) server.closeAllConnections();
+ return new Promise((resolve) => server.close(() => resolve()));
+}
+
// ── Smart port selection ───────────────────────────────────────────────────
export type FindPortResult =
diff --git a/packages/cli/src/server/studioRenderTelemetry.test.ts b/packages/cli/src/server/studioRenderTelemetry.test.ts
index 0b9e1c0b18..13e1e93807 100644
--- a/packages/cli/src/server/studioRenderTelemetry.test.ts
+++ b/packages/cli/src/server/studioRenderTelemetry.test.ts
@@ -121,6 +121,10 @@ const fullPerf: RenderPerfSummary = {
},
tmpPeakBytes: 1024,
captureAvgMs: 13,
+ captureSeekAvgMs: 3,
+ captureBeforeCaptureAvgMs: 1,
+ captureScreenshotAvgMs: 8,
+ encoderWaitAvgMs: 2,
capturePeakMs: 25,
observability: fullObservability,
};
@@ -165,6 +169,10 @@ describe("studioRenderTelemetry", () => {
// speedRatio = compositionDurationMs / elapsedMs = 10000 / 5000 = 2
expect(p.speedRatio).toBe(2);
expect(p.captureAvgMs).toBe(13);
+ expect(p.captureSeekAvgMs).toBe(3);
+ expect(p.captureBeforeCaptureAvgMs).toBe(1);
+ expect(p.captureScreenshotAvgMs).toBe(8);
+ expect(p.encoderWaitAvgMs).toBe(2);
expect(p.capturePeakMs).toBe(25);
expect(p.tmpPeakBytes).toBe(1024);
// stages
diff --git a/packages/cli/src/server/studioRenderTelemetry.ts b/packages/cli/src/server/studioRenderTelemetry.ts
index 67f52df086..458cf48429 100644
--- a/packages/cli/src/server/studioRenderTelemetry.ts
+++ b/packages/cli/src/server/studioRenderTelemetry.ts
@@ -100,6 +100,10 @@ function perfPayload(
totalFrames: perf.totalFrames,
speedRatio,
captureAvgMs: perf.captureAvgMs,
+ captureSeekAvgMs: perf.captureSeekAvgMs,
+ captureBeforeCaptureAvgMs: perf.captureBeforeCaptureAvgMs,
+ captureScreenshotAvgMs: perf.captureScreenshotAvgMs,
+ encoderWaitAvgMs: perf.encoderWaitAvgMs,
capturePeakMs: perf.capturePeakMs,
tmpPeakBytes: perf.tmpPeakBytes,
...stagesPayload(perf.stages),
diff --git a/packages/cli/src/server/studioServer.test.ts b/packages/cli/src/server/studioServer.test.ts
index 1cb82924b3..962eef661d 100644
--- a/packages/cli/src/server/studioServer.test.ts
+++ b/packages/cli/src/server/studioServer.test.ts
@@ -891,6 +891,17 @@ describe("Studio file-change SSE", () => {
return { projectDir, projectUrl };
}
+ it("leaves no timer behind once the tab disconnects, so a stopping CLI can exit", async () => {
+ server = createStudioServer({ projectDir: tmpProject() });
+ const timeouts = vi.spyOn(globalThis, "setTimeout");
+ const [stream] = await subscribe(1);
+ await stream!.cancel();
+
+ const keepAlive = timeouts.mock.calls.filter(([, ms]) => (ms ?? 0) >= 30_000);
+ timeouts.mockRestore();
+ expect(keepAlive).toEqual([]);
+ });
+
it("marks a notes write as not affecting the preview, so the tab does not reload", async () => {
const { projectDir } = await previewedProject();
const [stream] = await subscribe(1);
diff --git a/packages/cli/src/server/studioServer.ts b/packages/cli/src/server/studioServer.ts
index 52c60eaaa3..48737960f7 100644
--- a/packages/cli/src/server/studioServer.ts
+++ b/packages/cli/src/server/studioServer.ts
@@ -12,10 +12,10 @@ import { existsSync, readFileSync, statSync, writeFileSync, unlinkSync } from "n
import { replaceFileAtomically } from "@hyperframes/core/atomic-file";
import { createHash } from "node:crypto";
import { fileURLToPath } from "node:url";
-import { resolve, join, basename, dirname, relative, sep } from "node:path";
-import { createRequire } from "node:module";
+import { resolve, join, basename, relative, sep } from "node:path";
import { readBundleFile } from "./readBundleFile.js";
import { GSAP_CDN_VERSION } from "@hyperframes/core/gsap-cdn";
+import { GSAP_VENDOR_FILES, resolveGsapVendorDir } from "./gsapVendor.js";
import {
createProjectWatcher,
shouldWatchProjectFile,
@@ -178,36 +178,6 @@ function resolveRuntimePath(): string {
// Same-origin root for the GSAP files the CLI ships (build-copy.mjs), laid out
// like an npm mirror so preview can ask for `/gsap@/dist/`.
const GSAP_LOCAL_ROOT = "/api/vendor/npm";
-const GSAP_VENDOR_FILES = new Set(["gsap.min.js", "CustomEase.min.js", "MotionPathPlugin.min.js"]);
-
-function installedGsapDist(): string | null {
- try {
- const coreRequire = createRequire(resolve(__dirname, "..", "..", "..", "core", "package.json"));
- return join(dirname(coreRequire.resolve("gsap/package.json")), "dist");
- } catch {
- return null;
- }
-}
-
-/** The bundled GSAP dist dir, or null so preview keeps loading GSAP from jsDelivr. */
-function resolveGsapVendorDir(): string | null {
- const vendored = join("vendor", "npm", `gsap@${GSAP_CDN_VERSION}`, "dist");
- const candidates = [
- resolve(__dirname, vendored),
- // Running from source: the built CLI next door, then core's installed gsap.
- resolve(__dirname, "..", "..", "dist", vendored),
- installedGsapDist(),
- ];
- for (const dir of candidates) {
- if (!dir) continue;
- if (!existsSync(join(dir, "gsap.min.js"))) continue;
- const manifest = readBundleFile(join(dir, "..", "package.json"));
- if (manifest && JSON.parse(manifest.toString("utf-8")).version !== GSAP_CDN_VERSION) continue;
- return dir;
- }
- return null;
-}
-
function readStudioManualEditManifestContent(projectDir: string): string {
const manifestPath = join(projectDir, STUDIO_MANUAL_EDITS_PATH);
if (!existsSync(manifestPath)) return "";
@@ -1034,14 +1004,8 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
if (shouldWatchProjectFile(changedPath)) listener(changedPath);
};
watcher.addListener(wrappedListener);
- stream.onAbort(() => watcher.removeListener(wrappedListener));
- try {
- while (true) {
- await stream.sleep(30000);
- }
- } finally {
- watcher.removeListener(wrappedListener);
- }
+ if (!stream.aborted) await new Promise((tabClosed) => stream.onAbort(tabClosed));
+ watcher.removeListener(wrappedListener);
});
});
diff --git a/packages/cli/src/telemetry/client.test.ts b/packages/cli/src/telemetry/client.test.ts
index e393ecaffd..c6a08d91cf 100644
--- a/packages/cli/src/telemetry/client.test.ts
+++ b/packages/cli/src/telemetry/client.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, it, vi, beforeEach } from "vitest";
+import { readFileSync, unlinkSync } from "node:fs";
// CI exports HYPERFRAMES_NO_TELEMETRY=1 (and users may set DO_NOT_TRACK), which
// makes shouldTrack() short-circuit — and it caches that decision for the module's
@@ -45,6 +46,9 @@ vi.mock("./canary.js", () => ({
canaryEventProperties: () => canaryProps(),
}));
+const signedIn = vi.hoisted(() => ({ username: undefined as string | undefined }));
+vi.mock("./signedInUser.js", () => ({ signedInHeygenUsername: () => signedIn.username }));
+
// Intercept the exit-time child process so flushSync delivery is assertable.
const spawnMock = vi.fn(() => ({ unref: vi.fn() }));
vi.mock("node:child_process", () => ({
@@ -277,12 +281,11 @@ describe("telemetry queue delivery", () => {
expect(batch[0]?.event).toBe("cli_command_result");
});
- it("flushSync hands the queue to a detached child that carries the payload", async () => {
+ it("flushSync hands the queue to a detached child that reads the payload from a file", async () => {
spawnMock.mockClear();
trackEvent("render_complete", { quality: "draft" });
flushSync();
- // The child was spawned detached with the batch inlined into its -e script.
expect(spawnMock).toHaveBeenCalledTimes(1);
const [execPath, args, opts] = spawnMock.mock.calls[0] as unknown as [
string,
@@ -291,9 +294,11 @@ describe("telemetry queue delivery", () => {
];
expect(execPath).toBe(process.execPath);
expect(args[0]).toBe("-e");
- expect(args[1]).toContain("render_complete");
- expect(args[1]).toMatch(/[0-9a-f-]{36}/); // event uuid rides along
+ const body = readFileSync(args[2] as string, "utf8");
+ expect(body).toContain("render_complete");
+ expect(body).toMatch(/[0-9a-f-]{36}/); // event uuid rides along
expect(opts).toMatchObject({ detached: true, windowsHide: true });
+ unlinkSync(args[2] as string);
// Queue handed to the child — nothing left for a regular flush.
const fetchMock = vi.fn(() => Promise.resolve(new Response("")));
@@ -301,6 +306,29 @@ describe("telemetry queue delivery", () => {
await flush();
expect(fetchMock).not.toHaveBeenCalled();
});
+
+ it("flushSync keeps a batch over the Windows 32,767-char command-line limit off the command line", () => {
+ spawnMock.mockClear();
+ for (let i = 0; i < 40; i += 1) trackEvent("render_observation", { note: "x".repeat(1_000) });
+ flushSync();
+
+ const [, args] = spawnMock.mock.calls[0] as unknown as [string, string[]];
+ const body = readFileSync(args[2] as string, "utf8");
+ unlinkSync(args[2] as string);
+ expect(body.length).toBeGreaterThan(32_767);
+ expect(args.join(" ").length).toBeLessThan(32_767);
+ });
+
+ it("flushSync warns when the child cannot be started", () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ spawnMock.mockImplementationOnce(() => {
+ throw new Error("spawn failed");
+ });
+ trackEvent("render_complete", { quality: "draft" });
+ flushSync();
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining("spawn failed"));
+ warn.mockRestore();
+ });
});
describe("canary cohort on every event", () => {
@@ -335,3 +363,40 @@ describe("canary cohort on every event", () => {
);
});
});
+
+describe("signed-in HeyGen account on every event", () => {
+ const firstEvent = (fetchMock: ReturnType) => {
+ const init = fetchMock.mock.calls[0]?.[1] as { body: string };
+ return (
+ JSON.parse(init.body) as {
+ batch: Array<{ distinct_id: string; properties: Record }>;
+ }
+ ).batch[0]!;
+ };
+
+ it("keys signed-in events on the account id and carries heygen_username", async () => {
+ signedIn.username = "alice";
+ const fetchMock = vi.fn(async () => ({ ok: true, status: 200 }) as Response);
+ vi.stubGlobal("fetch", fetchMock);
+
+ trackEvent("cli_command", { command: "render" });
+ await flush();
+
+ const event = firstEvent(fetchMock);
+ expect(event.distinct_id).toBe("2bd806c9-7f0e-50af-9a1f-c3328fa763a9");
+ expect(event.properties.heygen_username).toBe("alice");
+ });
+
+ it("goes back to the install id once signed out", async () => {
+ signedIn.username = undefined;
+ const fetchMock = vi.fn(async () => ({ ok: true, status: 200 }) as Response);
+ vi.stubGlobal("fetch", fetchMock);
+
+ trackEvent("cli_command", { command: "render" });
+ await flush();
+
+ const event = firstEvent(fetchMock);
+ expect(event.distinct_id).not.toBe("2bd806c9-7f0e-50af-9a1f-c3328fa763a9");
+ expect(event.properties.heygen_username).toBeUndefined();
+ });
+});
diff --git a/packages/cli/src/telemetry/client.ts b/packages/cli/src/telemetry/client.ts
index edfed5cb27..bda5c27fc6 100644
--- a/packages/cli/src/telemetry/client.ts
+++ b/packages/cli/src/telemetry/client.ts
@@ -10,6 +10,8 @@ import { c } from "../ui/colors.js";
import { diag } from "../ui/diagnostics.js";
import { getSystemMeta } from "./system.js";
import { canaryEventProperties } from "./canary.js";
+import { signedInHeygenUsername } from "./signedInUser.js";
+import { heygenUserId } from "../auth/telemetryIdentity.js";
import { enqueue, type EventProperties } from "./transport.js";
import { telemetryRuntimeOverride } from "./policy.js";
@@ -74,6 +76,7 @@ export function trackEvent(
if (!shouldTrack()) return;
const sys = getSystemMeta();
+ const heygenUsername = signedInHeygenUsername();
enqueue(
event,
{
@@ -130,8 +133,9 @@ export function trackEvent(
...canaryEventProperties(),
agent_env_hints: sys.agent_env_hints ?? undefined,
client: sys.client ?? undefined,
+ heygen_username: heygenUsername,
},
- distinctId,
+ distinctId ?? (heygenUsername ? heygenUserId(heygenUsername) : undefined),
);
}
@@ -155,10 +159,12 @@ export function showTelemetryNotice(): boolean {
// --json (the guard in cli.ts filters by command only), so a stdout banner
// would corrupt the JSON envelope of the very first `check --json` etc.
diag.notice();
- diag.notice(` ${c.dim("Hyperframes collects anonymous usage data to improve the tool.")}`);
+ diag.notice(
+ ` ${c.dim("Hyperframes collects usage data to improve the tool, anonymous until you sign in.")}`,
+ );
diag.notice(` ${c.dim("File paths and composition content are never collected.")}`);
diag.notice(
- ` ${c.dim("If you sign in to HeyGen, your account (email, or username) is linked to your usage.")}`,
+ ` ${c.dim("If you sign in to HeyGen, your account (email and username) is linked to your usage.")}`,
);
diag.notice();
diag.notice(` ${c.dim("Disable anytime:")} ${c.accent("hyperframes telemetry disable")}`);
diff --git a/packages/cli/src/telemetry/config.ts b/packages/cli/src/telemetry/config.ts
index 0af74c5982..430a5e2d85 100644
--- a/packages/cli/src/telemetry/config.ts
+++ b/packages/cli/src/telemetry/config.ts
@@ -575,6 +575,23 @@ export interface HyperframesConfig {
* telemetry rows of the renders it describes.
*/
recentRenders?: RecentRenderRecord[];
+ /** The newest local `check`: exit code and its top error codes, which `hyperframes feedback` attaches. */
+ lastCheck?: LastCheckRecord;
+}
+
+/** The newest `check` in {@link HyperframesConfig.lastCheck}; codes and counts only, no content or paths. */
+export interface LastCheckRecord {
+ at: string;
+ /** Absent while the check has not finished: it is still running, or was stopped. */
+ exitCode?: number;
+ codes: Record;
+}
+
+/** Remember the newest check so a later `hyperframes feedback` can name why it failed. */
+export function recordLastCheck(lastCheck: LastCheckRecord): void {
+ const config = readConfigFresh();
+ config.lastCheck = lastCheck;
+ writeConfig(config);
}
/** One entry in {@link HyperframesConfig.recentRenders}. */
diff --git a/packages/cli/src/telemetry/events.test.ts b/packages/cli/src/telemetry/events.test.ts
index c45b28a6fb..9c8146465a 100644
--- a/packages/cli/src/telemetry/events.test.ts
+++ b/packages/cli/src/telemetry/events.test.ts
@@ -1050,6 +1050,10 @@ describe("render telemetry events", () => {
stageCaptureSetupMs: 1860,
stageCaptureFrameMs: 3240,
captureAvgMs: 27,
+ captureSeekAvgMs: 6,
+ captureBeforeCaptureAvgMs: 2,
+ captureScreenshotAvgMs: 15,
+ encoderWaitAvgMs: 4,
});
expect(trackEvent).toHaveBeenCalledWith(
@@ -1059,6 +1063,10 @@ describe("render telemetry events", () => {
stage_capture_setup_ms: 1860,
stage_capture_frame_ms: 3240,
capture_avg_ms: 27,
+ capture_seek_avg_ms: 6,
+ capture_before_capture_avg_ms: 2,
+ capture_screenshot_avg_ms: 15,
+ encoder_wait_avg_ms: 4,
}),
undefined,
);
@@ -1395,11 +1403,14 @@ describe("auth login telemetry events", () => {
});
it("identifyUser emits a $identify alias linking the anon install to the identity", () => {
- identifyUser("alice@example.com");
+ identifyUser("user-id-1", { email: "alice@example.com", heygen_username: "alice" });
expect(trackEvent).toHaveBeenCalledWith(
"$identify",
- { $anon_distinct_id: "anon-test-123" },
- "alice@example.com",
+ {
+ $anon_distinct_id: "anon-test-123",
+ $set: { email: "alice@example.com", heygen_username: "alice" },
+ },
+ "user-id-1",
);
});
diff --git a/packages/cli/src/telemetry/events.ts b/packages/cli/src/telemetry/events.ts
index 95df698be3..8addd0f48b 100644
--- a/packages/cli/src/telemetry/events.ts
+++ b/packages/cli/src/telemetry/events.ts
@@ -442,6 +442,10 @@ export function trackRenderComplete(
captureAvgMs?: number;
/** Warmup-robust per-frame capture median (basis for speedup estimates). */
captureP50Ms?: number;
+ captureSeekAvgMs?: number;
+ captureBeforeCaptureAvgMs?: number;
+ captureScreenshotAvgMs?: number;
+ encoderWaitAvgMs?: number;
/** element count (speedup segmentation: injection comps read lower). */
videoCount?: number;
capturePeakMs?: number;
@@ -617,6 +621,10 @@ export function trackRenderComplete(
speed_ratio: props.speedRatio,
capture_avg_ms: props.captureAvgMs,
capture_p50_ms: props.captureP50Ms,
+ capture_seek_avg_ms: props.captureSeekAvgMs,
+ capture_before_capture_avg_ms: props.captureBeforeCaptureAvgMs,
+ capture_screenshot_avg_ms: props.captureScreenshotAvgMs,
+ encoder_wait_avg_ms: props.encoderWaitAvgMs,
video_count: props.videoCount,
capture_peak_ms: props.capturePeakMs,
peak_memory_mb: props.peakMemoryMb,
@@ -674,6 +682,7 @@ export function trackRenderError(
errorName?: string;
/** failedStage normalized to a stable snake_case code. */
failedStageCode?: string;
+ missingPathKind?: string;
errorMessage?: string;
elapsedMs?: number;
peakMemoryMb?: number;
@@ -702,6 +711,7 @@ export function trackRenderError(
failed_stage: props.failedStage,
error_name: props.errorName,
failed_stage_code: props.failedStageCode,
+ missing_path_kind: props.missingPathKind,
error_message: props.errorMessage ? redactTelemetryMessage(props.errorMessage) : undefined,
elapsed_ms: props.elapsedMs,
...renderOutputShapeEventProperties(props),
@@ -872,11 +882,15 @@ export function trackAuthLoginFailed(
// install's anonymousId, so events recorded before sign-in stitch to the same
// person instead of stranding as a separate anonymous profile. Routed through
// trackEvent so it shares the opt-out gate and flush path — a no-op when
-// telemetry is disabled. `distinctId` is the account email (else username);
-// see the privacy notice in showTelemetryNotice and docs/packages/cli.mdx.
-export function identifyUser(distinctId: string): void {
+// telemetry is disabled. Identity comes from auth/telemetryIdentity.ts; see
+// showTelemetryNotice and docs/packages/cli.mdx.
+export function identifyUser(distinctId: string, traits: Record = {}): void {
if (!distinctId) return;
- trackEvent("$identify", { $anon_distinct_id: readConfig().anonymousId }, distinctId);
+ trackEvent(
+ "$identify",
+ { $anon_distinct_id: readConfig().anonymousId, $set: traits },
+ distinctId,
+ );
}
// A render was rejected by the output-resolution/HDR pre-flight (P1-3)
diff --git a/packages/cli/src/telemetry/missingPathKind.test.ts b/packages/cli/src/telemetry/missingPathKind.test.ts
new file mode 100644
index 0000000000..c23386b94c
--- /dev/null
+++ b/packages/cli/src/telemetry/missingPathKind.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it } from "vitest";
+import { missingPathKind } from "./missingPathKind.js";
+
+const enoent = (path: string) =>
+ Object.assign(new Error(`ENOENT: no such file or directory, open '${path}'`), {
+ code: "ENOENT",
+ path,
+ });
+
+describe("missingPathKind", () => {
+ it.each([
+ [
+ "C:\\Users\\a\\AppData\\Local\\Temp\\hf-cache\\hfcache-v8-0a1b2c\\frame_000041.jpg",
+ "extract_cache",
+ ],
+ [
+ "/tmp/hf-render-Ab12Cd/compiled/__hyperframes_video_frames/v-s0/frame_000041.jpg",
+ "video_frames",
+ ],
+ [
+ "/proj/work-0a1b2c3d-1111-2222-3333-444455556666-Xy12Ab/captured-frames/frame_005280.jpg",
+ "captured_frames",
+ ],
+ ["C:\\Temp\\hf-render-Ab12Cd\\capture-attempt-1\\worker-3\\frame_000007.jpg", "worker_frames"],
+ ["/tmp/hf-render-Ab12Cd/capture-calibration/frame_000001.jpg", "calibration"],
+ ["/tmp/hf-render-Ab12Cd/compiled/index.html", "compiled"],
+ ["/tmp/hf-render-Ab12Cd/audio-work/mix.wav", "work_dir"],
+ ["/Users/a/Projects/Launch/assets/intro.mp4", "other"],
+ ])("names %s as %s", (path, kind) => {
+ expect(missingPathKind(enoent(path))).toBe(kind);
+ });
+
+ it("finds the missing file in an error's causes and in a message that only names it", () => {
+ const wrapped = new Error("[Parallel] Capture failed", {
+ cause: enoent("/tmp/hf-render-x/captured-frames/frame_1.jpg"),
+ });
+ expect(missingPathKind(wrapped)).toBe("captured_frames");
+ expect(
+ missingPathKind(
+ new Error("ENOENT: no such file or directory, open 'C:\\T\\hfcache-v8-ab\\frame_2.jpg'"),
+ ),
+ ).toBe("extract_cache");
+ });
+
+ it("names nothing when no file was missing", () => {
+ expect(missingPathKind(new Error("Composition has zero duration"))).toBeUndefined();
+ expect(
+ missingPathKind(Object.assign(new Error("EPERM: rename"), { code: "EPERM" })),
+ ).toBeUndefined();
+ });
+});
diff --git a/packages/cli/src/telemetry/missingPathKind.ts b/packages/cli/src/telemetry/missingPathKind.ts
new file mode 100644
index 0000000000..281d0cc7b3
--- /dev/null
+++ b/packages/cli/src/telemetry/missingPathKind.ts
@@ -0,0 +1,37 @@
+const KINDS: ReadonlyArray<[RegExp, string]> = [
+ [/(^|[\\/])hfcache-/, "extract_cache"],
+ [/(^|[\\/])__hyperframes_video_frames([\\/]|$)/, "video_frames"],
+ [/(^|[\\/])captured-frames([\\/]|$)/, "captured_frames"],
+ [
+ /(^|[\\/])(capture-attempt-\d+|retry-\d+-batch-\d+-worker-\d+|worker-\d+)([\\/]|$)/,
+ "worker_frames",
+ ],
+ [/(^|[\\/])capture-calibration/, "calibration"],
+ [/(^|[\\/])compiled([\\/]|$)/, "compiled"],
+ [/(^|[\\/])(hf-render-|work-[0-9a-f]{8}-)/, "work_dir"],
+];
+
+const quotedPath = (text: string) => /'([^']+)'/.exec(text)?.[1] ?? "";
+
+function errorChain(error: unknown): Error[] {
+ const chain: Error[] = [];
+ for (let seen = error; seen instanceof Error && chain.length < 5; seen = seen.cause)
+ chain.push(seen);
+ return chain;
+}
+
+function missingPathOf(error: unknown): string | undefined {
+ const enoent = errorChain(error).find(
+ (seen) => (seen as NodeJS.ErrnoException).code === "ENOENT",
+ );
+ if (enoent) return (enoent as NodeJS.ErrnoException).path ?? quotedPath(enoent.message);
+ const message = error instanceof Error ? error.message : String(error);
+ return /\bENOENT\b/.test(message) ? quotedPath(message) : undefined;
+}
+
+/** Which kind of file a render found missing (a fixed name, never the path), or undefined when nothing was missing. */
+export function missingPathKind(error: unknown): string | undefined {
+ const path = missingPathOf(error);
+ if (path === undefined) return undefined;
+ return KINDS.find(([pattern]) => pattern.test(path))?.[1] ?? "other";
+}
diff --git a/packages/cli/src/telemetry/signedInUser.test.ts b/packages/cli/src/telemetry/signedInUser.test.ts
new file mode 100644
index 0000000000..eaf5667b62
--- /dev/null
+++ b/packages/cli/src/telemetry/signedInUser.test.ts
@@ -0,0 +1,63 @@
+import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { signedInHeygenUsername } from "./signedInUser.js";
+
+describe("signedInHeygenUsername", () => {
+ let dir: string;
+
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), "hf-signed-in-"));
+ vi.stubEnv("HYPERFRAMES_CONFIG_DIR", dir);
+ vi.stubEnv("HYPERFRAMES_ENV", "prod");
+ vi.stubEnv("HEYGEN_CONFIG_DIR", join(dir, "heygen"));
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ rmSync(dir, { recursive: true, force: true });
+ });
+
+ const write = (contents: unknown, mtime: number, root = dir) => {
+ mkdirSync(root, { recursive: true });
+ const file = join(root, "credentials");
+ writeFileSync(file, typeof contents === "string" ? contents : JSON.stringify(contents));
+ utimesSync(file, mtime, mtime);
+ };
+
+ it("is undefined when nobody is signed in", () => {
+ expect(signedInHeygenUsername()).toBeUndefined();
+ write({ api_key: "hg_x" }, 1000);
+ expect(signedInHeygenUsername()).toBeUndefined();
+ write("hg_legacy_plain_key", 1001);
+ expect(signedInHeygenUsername()).toBeUndefined();
+ });
+
+ it("returns the raw username after sign-in and drops it after sign-out", () => {
+ write({ user: { username: "Alice" } }, 1999);
+ expect(signedInHeygenUsername()).toBeUndefined();
+ write({ api_key: "hg_x", user: { username: "Alice", email: "alice@example.com" } }, 2000);
+ expect(signedInHeygenUsername()).toBe("Alice");
+ write({ api_key: "hg_x" }, 2001);
+ expect(signedInHeygenUsername()).toBeUndefined();
+ rmSync(join(dir, "credentials"));
+ expect(signedInHeygenUsername()).toBeUndefined();
+ });
+
+ it("uses the selected OAuth environment without falling back to HeyGen or production", () => {
+ write({ api_key: "hg_other", user: { username: "Other" } }, 2000, join(dir, "heygen"));
+ expect(signedInHeygenUsername()).toBeUndefined();
+ write({ oauth: { access_token: "test-prod" }, user: { username: "Alice" } }, 2000);
+ write(
+ { oauth: { access_token: "test-dev" }, user: { username: "Bob" } },
+ 2000,
+ join(dir, "dev"),
+ );
+ expect(signedInHeygenUsername()).toBe("Alice");
+ vi.stubEnv("HYPERFRAMES_ENV", "dev");
+ expect(signedInHeygenUsername()).toBe("Bob");
+ rmSync(join(dir, "dev", "credentials"));
+ expect(signedInHeygenUsername()).toBeUndefined();
+ });
+});
diff --git a/packages/cli/src/telemetry/signedInUser.ts b/packages/cli/src/telemetry/signedInUser.ts
new file mode 100644
index 0000000000..9e90c0f446
--- /dev/null
+++ b/packages/cli/src/telemetry/signedInUser.ts
@@ -0,0 +1,32 @@
+import { closeSync, fstatSync, openSync, readFileSync } from "node:fs";
+import { credentialPath } from "../auth/paths.js";
+
+let cached: { path: string; mtimeMs: number; username: string | undefined } | undefined;
+
+function usernameOf(parsed: unknown): string | undefined {
+ if (!parsed || typeof parsed !== "object") return undefined;
+ const { user, api_key, oauth } = parsed as { user?: unknown; api_key?: unknown; oauth?: unknown };
+ if (!api_key && !oauth) return undefined;
+ if (!user || typeof user !== "object") return undefined;
+ const name = (user as { username?: unknown }).username;
+ return typeof name === "string" && name.trim() ? name : undefined;
+}
+
+/** The signed-in HeyGen username, put on every event so each row joins across projects by itself. */
+export function signedInHeygenUsername(): string | undefined {
+ const path = credentialPath();
+ let fd: number | undefined;
+ try {
+ fd = openSync(path, "r");
+ const { mtimeMs } = fstatSync(fd);
+ if (cached?.path === path && cached.mtimeMs === mtimeMs) return cached.username;
+ const username = usernameOf(JSON.parse(readFileSync(fd, "utf8")));
+ cached = { path, mtimeMs, username };
+ return username;
+ } catch {
+ cached = undefined;
+ return undefined;
+ } finally {
+ if (fd !== undefined) closeSync(fd);
+ }
+}
diff --git a/packages/cli/src/telemetry/transport.ts b/packages/cli/src/telemetry/transport.ts
index a7f9c335ee..5767a7061c 100644
--- a/packages/cli/src/telemetry/transport.ts
+++ b/packages/cli/src/telemetry/transport.ts
@@ -1,5 +1,9 @@
import { spawn } from "node:child_process";
import { randomUUID } from "node:crypto";
+import { unlinkSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { diag } from "../ui/diagnostics.js";
import { POSTHOG_API_KEY } from "./posthogKey.js";
import { readConfig } from "./config.js";
import { hostAnswers } from "../utils/hostAnswers.js";
@@ -35,7 +39,8 @@ export type EventPropertyValue =
| null
| undefined
| readonly string[]
- | Readonly>;
+ | Readonly>
+ | Readonly>;
export interface EventProperties {
[key: string]: EventPropertyValue;
@@ -169,18 +174,28 @@ export function flushSync(): void {
if (payload == null) return;
eventQueue = [];
+ // The batch rides in a file, not the command line: Windows caps a command line at 32,767 chars
+ // and a render's batch is larger, so the spawn threw and every event was lost.
+ const file = join(tmpdir(), `hyperframes-telemetry-${randomUUID()}.json`);
try {
+ writeFileSync(file, payload, { mode: 0o600 });
const child = spawn(
process.execPath,
[
"-e",
- `fetch(${JSON.stringify(`${POSTHOG_HOST}/batch/`)},{method:"POST",headers:{"Content-Type":"application/json"},body:${JSON.stringify(payload)},signal:AbortSignal.timeout(${FLUSH_TIMEOUT_MS})}).catch(()=>{})`,
+ `const f=require("node:fs"),b=f.readFileSync(process.argv[1],"utf8");f.unlinkSync(process.argv[1]);fetch(${JSON.stringify(`${POSTHOG_HOST}/batch/`)},{method:"POST",headers:{"Content-Type":"application/json"},body:b,signal:AbortSignal.timeout(${FLUSH_TIMEOUT_MS})}).catch(()=>{})`,
+ file,
],
{ detached: true, stdio: "ignore", windowsHide: true },
);
// Let the parent exit without waiting for the child
child.unref();
- } catch {
- // Silently ignore
+ } catch (error) {
+ try {
+ unlinkSync(file);
+ } catch {}
+ diag.warn(
+ `hyperframes: telemetry was not sent (${error instanceof Error ? error.message : error})`,
+ );
}
}
diff --git a/packages/cli/src/templates/blank/index.html b/packages/cli/src/templates/blank/index.html
index ce4c9b4ffe..827bfa5844 100644
--- a/packages/cli/src/templates/blank/index.html
+++ b/packages/cli/src/templates/blank/index.html
@@ -3,7 +3,7 @@
-
+
+
+`;
+ const flattenInnerRoot = (innerRoot: Element): Element => {
+ const clone = innerRoot.cloneNode(true) as Element;
+ clone.removeAttribute("data-composition-id");
+ clone.removeAttribute("id");
+ clone.setAttribute("data-hf-authored-id", "root");
+ clone.setAttribute("data-hf-inner-root", "true");
+ return clone;
+ };
+
+ const result = inlineSubCompositions(document, [host], {
+ resolveHtml: () => sceneHtml,
+ parseHtml: (html) => parseHTML(html).document,
+ flattenInnerRoot,
+ });
+
+ const page = new JSDOM(document.documentElement.outerHTML).window.document;
+ const selectors = result.styles.flatMap((style) =>
+ [...style.css.matchAll(/([^{}]+)\{/g)].map((match) => match[1]!.trim()),
+ );
+ const [box, title, before] = selectors.map(
+ (selector) => page.querySelectorAll(selector.replaceAll("::before", "")).length,
+ );
+ expect(box).toBe(1);
+ expect(title).toBe(1);
+ expect(before).toBe(1);
+ },
+ );
+
it("extracts elements from sub-composition with original rel and crossorigin", () => {
const subCompWithLinks = `
@@ -411,6 +461,25 @@ describe("inlineSubCompositions – #ID selector scoping divergence", () => {
expect(host.hasAttribute("data-timeline-locked")).toBe(true);
});
+ it("propagates data-no-timeline from inner root to host element", () => {
+ const stillSubComp = `
+
+
+ Hello
+
+`;
+
+ const document = makeHostDocument("captions");
+ const host = document.querySelector('[data-composition-src="intro.html"]')!;
+
+ inlineSubCompositions(document, [host], {
+ resolveHtml: () => stillSubComp,
+ parseHtml: (html) => parseHTML(html).document,
+ });
+
+ expect(host.hasAttribute("data-no-timeline")).toBe(true);
+ });
+
it("producer path propagates data-hf-authored-id to host when inner root has id", () => {
const document = makeHostDocument("intro");
const host = document.querySelector('[data-composition-src="intro.html"]')!;
diff --git a/packages/core/src/compiler/inlineSubCompositions.ts b/packages/core/src/compiler/inlineSubCompositions.ts
index 4951f666c9..3e65a3b24a 100644
--- a/packages/core/src/compiler/inlineSubCompositions.ts
+++ b/packages/core/src/compiler/inlineSubCompositions.ts
@@ -663,8 +663,8 @@ export function inlineSubCompositions(
// Rewrite relative asset paths before inlining so ../foo.svg from
// compositions/ resolves correctly when the content moves to root.
const assetEls = innerRoot
- ? innerRoot.querySelectorAll("[src], [href]")
- : contentDoc.querySelectorAll("[src], [href]");
+ ? innerRoot.querySelectorAll("[src], [href], [srcset]")
+ : contentDoc.querySelectorAll("[src], [href], [srcset]");
rewriteAssetPaths(
assetEls,
src,
@@ -693,6 +693,9 @@ export function inlineSubCompositions(
if (innerRoot?.hasAttribute("data-timeline-locked")) {
hostEl.setAttribute("data-timeline-locked", "");
}
+ if (innerRoot?.hasAttribute("data-no-timeline")) {
+ hostEl.setAttribute("data-no-timeline", "");
+ }
// Copy dimension attributes from inner root to host if missing
if (innerRoot) {
diff --git a/packages/core/src/compiler/srcset.ts b/packages/core/src/compiler/srcset.ts
index f62cdbb565..c1d5a80526 100644
--- a/packages/core/src/compiler/srcset.ts
+++ b/packages/core/src/compiler/srcset.ts
@@ -1,43 +1 @@
-function skipSrcsetDescriptors(srcset: string, position: number): number {
- let inParens = false;
- while (position < srcset.length) {
- const char = srcset.charAt(position++);
- if (char === "(") inParens = true;
- else if (char === ")") inParens = false;
- else if (char === "," && !inParens) break;
- }
- return position;
-}
-
-function readSrcsetUrl(srcset: string, position: number) {
- while (position < srcset.length && /[ \t\n\r\f,]/.test(srcset.charAt(position))) position++;
- const start = position;
- while (position < srcset.length && !/[ \t\n\r\f]/.test(srcset.charAt(position))) position++;
- let end = position;
- while (end > start && srcset.charAt(end - 1) === ",") end--;
- return { start, end, next: position };
-}
-
-export function rewriteSrcsetUrls(srcset: string, rewriteUrl: (url: string) => string): string {
- const parts: string[] = [];
- let position = 0;
- let written = 0;
-
- // Preserve URL commas per https://html.spec.whatwg.org/multipage/images.html#parse-a-srcset-attribute
- while (position < srcset.length) {
- const { start, end, next } = readSrcsetUrl(srcset, position);
- position = next;
- if (end > start) {
- const url = srcset.slice(start, end);
- const rewritten = rewriteUrl(url);
- if (rewritten !== url) {
- parts.push(srcset.slice(written, start), rewritten);
- written = end;
- }
- }
- if (end < position) continue;
-
- position = skipSrcsetDescriptors(srcset, position);
- }
- return parts.length > 0 ? parts.join("") + srcset.slice(written) : srcset;
-}
+export { rewriteSrcsetUrls } from "@hyperframes/parsers/asset-paths";
diff --git a/packages/core/src/figma/motionContextToDocs.test.ts b/packages/core/src/figma/motionContextToDocs.test.ts
index 859a32fadf..cd36d28424 100644
--- a/packages/core/src/figma/motionContextToDocs.test.ts
+++ b/packages/core/src/figma/motionContextToDocs.test.ts
@@ -82,6 +82,15 @@ function docs(repeat = 1) {
});
}
+function docsForSnippet(motionDev: string) {
+ return motionContextToDocs(
+ {
+ nodes: [{ nodeId: "1:2", nodeName: "Box", codeSnippets: { motionDev } }],
+ },
+ { selectorFor: () => "#box" },
+ );
+}
+
describe("motionContextToDocs", () => {
it("produces one doc per animated node with caller-supplied selectors", () => {
const out = docs();
@@ -127,6 +136,57 @@ describe("motionContextToDocs", () => {
expect(opacity?.times).toEqual([0, 0.0686, 0.2273, 1]);
});
+ it("keeps y values and timing separate when opacity appears first", () => {
+ const out = docsForSnippet(
+ ' ',
+ );
+ const opacity = out[0]?.tracks.find((track) => track.property === "opacity");
+ const y = out[0]?.tracks.find((track) => track.property === "y");
+
+ expect(opacity?.values).toEqual([0, 0, 1, 1]);
+ expect(opacity?.times).toEqual([0, 0.0444, 0.1333, 1]);
+ expect(y?.values).toEqual([120, 120, 0, 0]);
+ expect(y?.times).toEqual([0, 0.0444, 0.2222, 1]);
+ });
+
+ it("keeps opacity values and timing separate when y appears first", () => {
+ const out = docsForSnippet(
+ ' ',
+ );
+ const y = out[0]?.tracks.find((track) => track.property === "y");
+ const opacity = out[0]?.tracks.find((track) => track.property === "opacity");
+
+ expect(y?.values).toEqual([120, 120, 0, 0]);
+ expect(y?.times).toEqual([0, 0.0444, 0.2222, 1]);
+ expect(opacity?.values).toEqual([0, 0, 1, 1]);
+ expect(opacity?.times).toEqual([0, 0.0444, 0.1333, 1]);
+ });
+
+ it("uses each suffix property's own transition duration and ease", () => {
+ const out = docsForSnippet(
+ ' ',
+ );
+ const opacity = out[0]?.tracks.find((track) => track.property === "opacity");
+ const y = out[0]?.tracks.find((track) => track.property === "y");
+
+ expect(opacity).toMatchObject({ duration: 2.25, ease: ["easeIn"] });
+ expect(y).toMatchObject({ duration: 4.5, ease: ["easeOut"] });
+ });
+
+ it("does not read arrays or scalars from longer transition keys", () => {
+ const out = docsForSnippet(
+ ' ',
+ );
+
+ expect(out[0]?.tracks[0]).toMatchObject({
+ property: "y",
+ values: [120, 120, 0, 0],
+ times: [0, 0.0444, 0.2222, 1],
+ ease: ["easeOut", "easeOut", "easeOut"],
+ duration: 4.5,
+ });
+ });
+
it("preserves bezier easing arrays and applies the requested repeat", () => {
const knob = docs(2)[4]?.tracks[0];
expect(knob?.ease[0]).toEqual([0.539, 0, 0.312, 0.995]);
diff --git a/packages/core/src/figma/motionContextToDocs.ts b/packages/core/src/figma/motionContextToDocs.ts
index 7b07db9b49..b01633c46f 100644
--- a/packages/core/src/figma/motionContextToDocs.ts
+++ b/packages/core/src/figma/motionContextToDocs.ts
@@ -64,11 +64,14 @@ function escapeRegExp(text: string): string {
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
+function keyPattern(key: string, valuePattern: string): RegExp {
+ return new RegExp(`(? {
+ const { params, timeline } = overlappingZoom();
+ const zoom = new Map();
+ if (seekFirst !== undefined) seekGsapTimeline(timeline, seekFirst, true, undefined, FPS);
+ for (const frame of frames) {
+ seekGsapTimeline(timeline, frame / FPS - hostStart, true, undefined, FPS);
+ zoom.set(frame, params.z);
+ }
+ return zoom;
+}
+
+const range = (from: number, to: number, step = 1) =>
+ Array.from({ length: Math.ceil((to - from) / step) }, (_, i) => from + i * step);
+
+describe("a render that captures frames out of order", () => {
+ const inOrder = capture(range(0, FRAMES));
+
+ it("gives every frame the same value when 8 workers each capture every 8th frame", () => {
+ for (let worker = 0; worker < 8; worker++) {
+ for (const [frame, z] of capture(range(worker, FRAMES, 8))) {
+ expect([frame, z]).toEqual([frame, inOrder.get(frame)]);
+ }
+ }
+ });
+
+ it("gives every frame the same value when a chunk starts inside the overlap", () => {
+ for (const [frame, z] of capture(range(53, FRAMES))) {
+ expect([frame, z]).toEqual([frame, inOrder.get(frame)]);
+ }
+ });
+
+ it("gives every frame the same value in a scene whose host starts between two frames", () => {
+ const hostStart = 0.0125;
+ const sceneInOrder = capture(range(1, FRAMES), hostStart);
+ for (let worker = 0; worker < 8; worker++) {
+ for (const [frame, z] of capture(range(worker + 1, FRAMES, 8), hostStart)) {
+ expect(z).toBeCloseTo(sceneInOrder.get(frame)!, 9);
+ }
+ }
+ });
+
+ it("gives every frame the same value when a scene held at 0 jumps to a chunk start between two frames", () => {
+ const hostStart = 0.0125;
+ const sceneInOrder = capture(range(1, FRAMES), hostStart);
+ for (const [frame, z] of capture(range(53, FRAMES), hostStart, 0)) {
+ expect(z).toBeCloseTo(sceneInOrder.get(frame)!, 9);
+ }
+ });
+
+ it("replays no frame when no two tweens write the same property at once", () => {
+ const rendersOfTwoSeeks = (fps?: number) => {
+ const [a, b, c, d] = [{ x: 0 }, { x: 0 }, { x: 0 }, { x: 0 }];
+ const timeline = gsap.timeline({ paused: true });
+ timeline
+ .to(a, { x: 1, duration: 2 }, 0)
+ .to(b, { x: 1, duration: 2 }, 0)
+ .to(a, { x: 2, duration: 1 }, 2);
+ const pausedScene = gsap
+ .timeline()
+ .to(c, { x: 1, duration: 1 })
+ .to(c, { x: 2, duration: 1 }, 0.5);
+ timeline.add(pausedScene, 0.3);
+ pausedScene.pause();
+ timeline.add(gsap.timeline({ repeat: 3, yoyo: true }).to(d, { x: 1, duration: 0.5 }), 0);
+ const film = timeline as unknown as RuntimeTimelineLike;
+ let renders = 0;
+ const totalTime = film.totalTime!.bind(film);
+ film.totalTime = (...args) => (args.length ? (renders++, totalTime(...args)) : totalTime());
+ seekGsapTimeline(film, 0, true, undefined, fps);
+ seekGsapTimeline(film, 170 / FPS, true, undefined, fps);
+ return [renders, a.x, b.x, c.x, d.x];
+ };
+ expect(rendersOfTwoSeeks(FPS)).toEqual(rendersOfTwoSeeks());
+ });
+});
diff --git a/packages/core/src/runtime/adapters/gsap.steps.test.ts b/packages/core/src/runtime/adapters/gsap.steps.test.ts
index 1e2788e690..fc40d97c5d 100644
--- a/packages/core/src/runtime/adapters/gsap.steps.test.ts
+++ b/packages/core/src/runtime/adapters/gsap.steps.test.ts
@@ -1,7 +1,13 @@
// @vitest-environment happy-dom
import gsap from "gsap";
import { describe, expect, it } from "vitest";
-import { createGsapAdapter, rerenderGsapTimelineAt, seekGsapTimeline } from "./gsap";
+import {
+ createGsapAdapter,
+ holdFrameMarks,
+ holdLandingMarks,
+ rerenderGsapTimelineAt,
+ seekGsapTimeline,
+} from "./gsap";
import type { GsapStructureKey } from "./gsap";
import type { RuntimeTimelineLike } from "../types";
@@ -30,6 +36,16 @@ describe("gsap adapter on a step", () => {
expect(film.shown()).toEqual([false, true, false]);
});
+ it.each([undefined, 1, 2.7])(
+ "shows the first step's frame when seeking to 0 from %s s",
+ (from) => {
+ const film = steppedFilm();
+ if (from !== undefined) film.timeline.totalTime(from, true);
+ film.adapter.seek({ time: 0 });
+ expect(film.shown()).toEqual([true, false, false]);
+ },
+ );
+
it("fires a call on the step once when seeking onto it twice", () => {
const film = steppedFilm();
film.adapter.seek({ time: 2.5 });
@@ -761,3 +777,75 @@ describe("rerenderGsapTimelineAt with a structure key", () => {
}
});
});
+
+describe("holdLandingMarks", () => {
+ const FPS = 30;
+ // Motion blur's pose reads seek silently across the shutter, then land back on the frame.
+ function readsAround(timeline: gsap.core.Timeline, t: number, render: boolean, hold: boolean) {
+ const tl = timeline as unknown as RuntimeTimelineLike;
+ const key: GsapStructureKey | undefined = render
+ ? undefined
+ : { owner: timeline, version: "1" };
+ const put = hold ? holdLandingMarks(tl, key) : () => {};
+ for (const at of [t - 0.011, t - 0.004, t + 0.004, t + 0.011])
+ seekGsapTimeline(tl, at, true, key);
+ seekGsapTimeline(tl, t, true, key);
+ if (render) rerenderGsapTimelineAt(timeline, t);
+ put();
+ }
+ function play(timeline: gsap.core.Timeline, render: boolean, hold: boolean, frames: number) {
+ for (let frame = 0; frame <= frames; frame++) {
+ const t = frame / FPS;
+ seekGsapTimeline(timeline as unknown as RuntimeTimelineLike, t, false);
+ readsAround(timeline, t, render, hold);
+ }
+ }
+
+ it.each([false, true])(
+ "fires a call on a frame once across silent reads around it (render %s)",
+ (render) => {
+ const run = (hold: boolean) => {
+ let fires = 0;
+ let on = false;
+ const timeline = gsap.timeline({ paused: true });
+ timeline.to({}, { duration: 2 }, 0);
+ timeline.call(() => ((on = !on), fires++), [], 1);
+ play(timeline, render, hold, 45);
+ return { fires, on };
+ };
+ expect(run(false).fires).toBeGreaterThan(1);
+ expect(run(true)).toEqual({ fires: 1, on: true });
+ },
+ );
+
+ it("lands a render frame with the root drawn after its scenes, as the frame's own seek does", () => {
+ const shared = { x: 0 };
+ const scene = gsap.timeline({ paused: true });
+ scene.fromTo(shared, { x: 0 }, { x: 100, duration: 2, ease: "none" }, 0);
+ const root = gsap.timeline({ paused: true });
+ root.fromTo(shared, { x: 1000 }, { x: 2000, duration: 2, ease: "none" }, 0);
+ const tl = (timeline: gsap.core.Timeline) => timeline as unknown as RuntimeTimelineLike;
+ const seekBoth = (t: number, silent: boolean) => {
+ seekGsapTimeline(tl(scene), t, silent);
+ seekGsapTimeline(tl(root), t, silent);
+ };
+ seekBoth(0.5, false);
+ expect(shared.x).toBe(1250);
+ const land = holdFrameMarks({
+ scenes: [tl(scene)],
+ root: tl(root),
+ structureOf: () => undefined,
+ });
+ for (const at of [0.489, 0.496, 0.504, 0.511]) seekBoth(at, true);
+ land(() => seekBoth(0.5, true));
+ expect(shared.x).toBe(1250);
+ });
+
+ it("keeps two same-time sets in authored order after silent reads around a render frame", () => {
+ const value = { v: 0 };
+ const timeline = gsap.timeline({ paused: true });
+ timeline.to({}, { duration: 2 }, 0).set(value, { v: 1 }, 1).set(value, { v: 2 }, 1);
+ play(timeline, true, true, FPS);
+ expect(value.v).toBe(2);
+ });
+});
diff --git a/packages/core/src/runtime/adapters/gsap.ts b/packages/core/src/runtime/adapters/gsap.ts
index 020f17e8b4..83a333a63e 100644
--- a/packages/core/src/runtime/adapters/gsap.ts
+++ b/packages/core/src/runtime/adapters/gsap.ts
@@ -57,14 +57,20 @@ function renderOntoInAuthoredOrder(
timeline.totalTime(below ? t - REDRAW_STEP : t + REDRAW_STEP, true);
primeTweensStartingAt(children, t, below ? REDRAW_STEP : 0);
timeline.totalTime(t, true);
- if (!below && structure) reapplyStepsInAuthoredOrder(timeline, structure, t);
+ if (!below) reapplyStepsInAuthoredOrder(timeline, structure ?? ownStructureOf(children), t);
+}
+
+function ownStructureOf(children: unknown[]): GsapStructureKey | undefined {
+ const owner = (children[0] as GsapPlaced | undefined)?.parent;
+ return owner ? { owner, version: "" } : undefined;
}
function reapplyStepsInAuthoredOrder(
timeline: { getChildren?: RuntimeTimelineLike["getChildren"] },
- structure: GsapStructureKey,
+ structure: GsapStructureKey | undefined,
t: number,
): void {
+ if (!structure) return;
for (const step of stepsAt(timeline, structure, t)) {
const { ratio, _zTime, _act } = step;
step.render(0, true, true);
@@ -86,16 +92,151 @@ function gsapNeverRendered(timeline: RuntimeTimelineLike): boolean {
return rendered !== undefined && !rendered._initted;
}
+const lastRenderSeek = new WeakMap();
+const sharedPropertySpans = new WeakMap();
+const NOT_PROPERTIES = new Set([
+ "duration",
+ "ease",
+ "delay",
+ "repeat",
+ "repeatDelay",
+ "yoyo",
+ "yoyoEase",
+ "repeatRefresh",
+ "stagger",
+ "overwrite",
+ "immediateRender",
+ "lazy",
+ "id",
+ "paused",
+ "reversed",
+ "callbackScope",
+ "runBackwards",
+ "data",
+ "inherit",
+ "defaults",
+]);
+const EVERY_PROPERTY = new Set(["keyframes", "startAt", "transform"]);
+const SAME_PROPERTY: Record = {
+ scaleX: "scale",
+ scaleY: "scale",
+ autoAlpha: "opacity",
+ rotate: "rotation",
+};
+
+type PlacedTween = GsapPlaced & {
+ vars?: Record;
+ targets?: () => object[];
+};
+type PropertyWrite = { start: number; end: number; properties: Set | null };
+
+function propertiesWritten(vars: Record): Set | null {
+ const properties = new Set();
+ for (const key of Object.keys(vars)) {
+ if (EVERY_PROPERTY.has(key)) return null;
+ if (!key.startsWith("on") && !NOT_PROPERTIES.has(key))
+ properties.add(SAME_PROPERTY[key] ?? key);
+ }
+ return properties;
+}
+
+function spanOnParent(
+ [start, length]: [number, number],
+ parent: GsapPlaced,
+): [number, number] | null {
+ const speed = Number(parent._ts);
+ if (!speed) return null;
+ const [from, span] =
+ parent._repeat || speed < 0
+ ? [0, Number(parent.totalDuration?.() ?? Infinity)]
+ : [start, length];
+ return [Number(parent._start) + from / Math.abs(speed), span / Math.abs(speed)];
+}
+
+function writeOf(tween: PlacedTween, timeline: RuntimeTimelineLike): PropertyWrite | null {
+ let span: [number, number] | null = [Number(tween._start), Number(tween.totalDuration?.() ?? 0)];
+ for (let parent = tween.parent; span && parent && parent !== timeline; parent = parent.parent) {
+ span = spanOnParent(span, parent);
+ }
+ return (
+ span && {
+ start: span[0],
+ end: span[0] + span[1],
+ properties: propertiesWritten(tween.vars ?? {}),
+ }
+ );
+}
+
+function spansWhereTweensShareAProperty(timeline: RuntimeTimelineLike): [number, number][] {
+ const writes = new Map();
+ for (const child of timeline.getChildren?.(true, true, false) ?? []) {
+ const tween = child as PlacedTween;
+ const write = writeOf(tween, timeline);
+ if (!write) continue;
+ for (const target of tween.targets?.() ?? [])
+ writes.set(target, [...(writes.get(target) ?? []), write]);
+ }
+ return [...writes.values()].flatMap(overlapsOnOneTarget);
+}
+
+function sharesAProperty(a: PropertyWrite, b: PropertyWrite): boolean {
+ return !a.properties || !b.properties || [...a.properties].some((p) => b.properties!.has(p));
+}
+
+function overlapsOnOneTarget(writes: PropertyWrite[]): [number, number][] {
+ const spans: [number, number][] = [];
+ writes.sort((x, y) => x.start - y.start);
+ writes.forEach((first, i) => {
+ for (const second of writes.slice(i + 1)) {
+ if (second.start >= first.end) break;
+ if (sharesAProperty(first, second))
+ spans.push([second.start, Math.min(first.end, second.end)]);
+ }
+ });
+ return spans;
+}
+
+function framesSkippedSinceLastSeek(
+ timeline: RuntimeTimelineLike,
+ t: number,
+ fps: number,
+ version = "",
+): number[] {
+ const last = lastRenderSeek.get(timeline);
+ lastRenderSeek.set(timeline, t);
+ const skipped =
+ last === undefined ? Math.floor(t * fps + 1e-6) : Math.ceil((t - last) * fps - 1e-6) - 1;
+ if (skipped < 1) return [];
+ let cached = sharedPropertySpans.get(timeline);
+ if (cached?.version !== version) {
+ cached = { version, spans: spansWhereTweensShareAProperty(timeline) };
+ sharedPropertySpans.set(timeline, cached);
+ }
+ const replay = new Set();
+ for (const [from, to] of cached.spans) {
+ const nearest = Math.max(1, Math.ceil((t - to) * fps - 1e-6) - 1);
+ const farthest = Math.min(skipped, Math.floor((t - from) * fps + 1e-6) + 1);
+ for (let back = nearest; back <= farthest; back++) replay.add(back);
+ }
+ return [...replay].sort((x, y) => y - x).map((back) => t - back / fps);
+}
+
export function seekGsapTimeline(
timeline: RuntimeTimelineLike,
t: number,
suppressEvents: boolean,
structure?: GsapStructureKey,
+ renderFps?: number,
): boolean {
if (typeof timeline.totalTime !== "function") {
if (typeof timeline.seek === "function") timeline.seek(t, suppressEvents);
return false;
}
+ if (renderFps) {
+ for (const time of framesSkippedSinceLastSeek(timeline, t, renderFps, structure?.version)) {
+ timeline.totalTime(time, suppressEvents);
+ }
+ }
const from = Number(timeline.totalTime());
timeline.totalTime(t, suppressEvents);
if (t < from && structure) reapplyStepsInAuthoredOrder(timeline, structure, t);
@@ -175,6 +316,7 @@ type GsapPlaced = {
_repeat?: number;
parent?: GsapPlaced | null;
getChildren?: unknown;
+ totalDuration?: () => number;
};
function startOnOwner(child: GsapPlaced, owner: object): number | null {
@@ -230,7 +372,9 @@ function stepsAt(
structure: GsapStructureKey,
t: number,
): GsapStep[] {
- const { points } = placedLandingMarks(timeline, structure);
+ const { points } = structure.version
+ ? placedLandingMarks(timeline, structure)
+ : placeLandingMarks(timeline, structure);
const steps: GsapStep[] = [];
for (let i = firstPointFrom(points, t - PLAYHEAD_FLOAT_NOISE); i < points.length; i++) {
if (points[i]!.at > t + PLAYHEAD_FLOAT_NOISE) break;
@@ -239,6 +383,53 @@ function stepsAt(
return steps;
}
+export function holdLandingMarks(
+ timeline: { getChildren?: RuntimeTimelineLike["getChildren"] },
+ structure?: GsapStructureKey,
+): () => void {
+ const placed = structure ? placedLandingMarks(timeline, structure) : null;
+ const marks = placed
+ ? [...placed.always, ...placed.points.map((point) => point.mark)]
+ : childrenWithLandingMarksIn(timeline);
+ const held = marks.map((mark) => [mark, mark.ratio, mark._zTime, mark._act] as const);
+ return () => {
+ for (const [mark, ratio, zTime, active] of held) {
+ mark.ratio = ratio;
+ mark._zTime = zTime;
+ mark._act = active;
+ }
+ };
+}
+
+export function holdFrameMarks({
+ scenes,
+ root,
+ structureOf,
+}: {
+ scenes: RuntimeTimelineLike[];
+ root: RuntimeTimelineLike | null;
+ structureOf: (timeline: RuntimeTimelineLike) => GsapStructureKey | undefined;
+}): (landBack: () => void) => void {
+ const rootLandsLast = root ? [...scenes, root] : scenes;
+ const marks = rootLandsLast.map((timeline) => holdLandingMarks(timeline, structureOf(timeline)));
+ return (landBack) => {
+ landBack();
+ for (const timeline of rootLandsLast) {
+ if (timeline.totalTime && !structureOf(timeline)) {
+ rerenderGsapTimelineAt(
+ {
+ totalTime: timeline.totalTime.bind(timeline),
+ totalDuration: timeline.totalDuration?.bind(timeline),
+ getChildren: timeline.getChildren?.bind(timeline),
+ },
+ Number(timeline.totalTime()),
+ );
+ }
+ }
+ for (const put of marks) put();
+ };
+}
+
function landingMarksOf(
timeline: { getChildren?: RuntimeTimelineLike["getChildren"] },
structure: GsapStructureKey | undefined,
diff --git a/packages/core/src/runtime/adapters/seek-dispatch.test.ts b/packages/core/src/runtime/adapters/seek-dispatch.test.ts
index 6c503e013b..07f6be3f0c 100644
--- a/packages/core/src/runtime/adapters/seek-dispatch.test.ts
+++ b/packages/core/src/runtime/adapters/seek-dispatch.test.ts
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest";
import {
dispatchSeekEvent,
forceDispatchSeekEvent,
+ registerSeekCompletion,
resetSeekDispatchState,
waitForSeekCompletion,
type HfSeekEventDetail,
@@ -211,4 +212,53 @@ describe("seek-dispatch", () => {
]);
await expect(waitForSeekCompletion()).resolves.toBeUndefined();
});
+
+ // Main had no deadline: a hold that never settles waited out the caller's protocol timeout.
+ it("a seek with a hold that never settles ends at its deadline, naming what it still waits on", async () => {
+ registerSeekCompletion(new Promise(() => {}), "frame-source");
+ registerSeekCompletion(Promise.resolve(), "video-frame");
+ await expect(waitForSeekCompletion({ timeoutMs: 20 })).rejects.toThrow(
+ "seek did not settle within 20 ms: still waiting on frame-source",
+ );
+ });
+
+ it("holds registered while the barrier waits still end at the same deadline", async () => {
+ let stopped = false;
+ const again = (): void => {
+ if (stopped) return;
+ registerSeekCompletion(
+ new Promise((resolve) => setTimeout(() => (again(), resolve(undefined)), 1)),
+ "video-frame",
+ );
+ };
+ again();
+ const started = Date.now();
+ try {
+ await expect(waitForSeekCompletion({ timeoutMs: 50 })).rejects.toThrow(
+ /still waiting on video-frame/,
+ );
+ } finally {
+ stopped = true;
+ }
+ expect(Date.now() - started).toBeLessThan(1000);
+ });
+
+ it("without a caller's timeoutMs a seek waits as long as its holds take", async () => {
+ vi.useFakeTimers();
+ try {
+ let settle = () => {};
+ registerSeekCompletion(new Promise((resolve) => (settle = resolve)), "vfx");
+ const barrier = waitForSeekCompletion();
+ await vi.advanceTimersByTimeAsync(30 * 60_000);
+ settle();
+ await expect(barrier).resolves.toBeUndefined();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("a seek whose holds settle in time resolves as before", async () => {
+ registerSeekCompletion(new Promise((resolve) => setTimeout(resolve, 5)), "scene-window");
+ await expect(waitForSeekCompletion({ timeoutMs: 1000 })).resolves.toBeUndefined();
+ });
});
diff --git a/packages/core/src/runtime/adapters/seek-dispatch.ts b/packages/core/src/runtime/adapters/seek-dispatch.ts
index 2173e8b110..f6b81d68fa 100644
--- a/packages/core/src/runtime/adapters/seek-dispatch.ts
+++ b/packages/core/src/runtime/adapters/seek-dispatch.ts
@@ -20,8 +20,16 @@ import { swallow } from "../diagnostics";
let _lastDispatchedTime = -1;
type SeekCompletionResult = { status: "fulfilled" } | { status: "rejected"; reason: unknown };
-let _pendingCompletions = new Set>();
-let _videoFrameCompletions = new WeakSet>();
+/** What a seek waits on, named when the barrier stops waiting for it. */
+export type SeekHold =
+ | "video-frame"
+ | "hf-seek"
+ | "frame-source"
+ | "scene-window"
+ | "motion-blur"
+ | "vfx"
+ | "image-decode";
+let _pendingCompletions = new Map, SeekHold>();
let _pendingFailure: { reason: unknown } | undefined;
let _activeCompletionBarriers = 0;
@@ -50,7 +58,7 @@ function dispatch(time: number): void {
accepting = false;
}
if (pending.length === 0) return;
- registerSeekCompletion(Promise.all(pending));
+ registerSeekCompletion(Promise.all(pending), "hf-seek");
}
/**
@@ -63,12 +71,11 @@ function dispatch(time: number): void {
* its preview-side capture here, so the CLI seek paths that already await this
* barrier wait for a `self` chain's paint instead of racing it.
*/
-export function registerSeekCompletion(promise: Promise, kind?: "video-frame"): void {
+export function registerSeekCompletion(promise: Promise, hold: SeekHold): void {
const completion = promise
.then(() => ({ status: "fulfilled" }))
.catch((reason: unknown) => ({ status: "rejected", reason }));
- _pendingCompletions.add(completion);
- if (kind === "video-frame") _videoFrameCompletions.add(completion);
+ _pendingCompletions.set(completion, hold);
void completion.then((result) => {
if (!_pendingCompletions.delete(completion)) return;
if (result.status === "rejected" && _pendingFailure === undefined) {
@@ -105,9 +112,9 @@ export function isSeekCompletionBarrierActive(): boolean {
/** Settles with every pending completion, without consuming a failure the barrier reports. */
export async function seekCompletionsSettled(): Promise {
for (
- let pending = [..._pendingCompletions];
+ let pending = [..._pendingCompletions.keys()];
pending.length > 0;
- pending = [..._pendingCompletions]
+ pending = [..._pendingCompletions.keys()]
) {
await Promise.all(pending);
}
@@ -117,12 +124,34 @@ export function hasPendingSeekCompletion(): boolean {
return _pendingCompletions.size > 0;
}
-/** `videoFrames: false` skips only the video-frame holds: a geometry read needs every other completion. */
-export async function waitForSeekCompletion(options?: { videoFrames?: boolean }): Promise {
+/** All of `pending` settled, or null once `deadline` (epoch ms) passes first. */
+async function settledBy(
+ pending: Promise[],
+ deadline: number | undefined,
+): Promise {
+ if (deadline === undefined) return Promise.all(pending);
+ let timer: ReturnType | undefined;
+ const late = new Promise((resolve) => {
+ timer = setTimeout(() => resolve(null), Math.max(0, deadline - Date.now()));
+ });
+ try {
+ return await Promise.race([Promise.all(pending), late]);
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+/** `videoFrames: false` skips only video-frame holds. Past a caller's `timeoutMs` it throws, naming what is pending. */
+export async function waitForSeekCompletion(options?: {
+ videoFrames?: boolean;
+ timeoutMs?: number;
+}): Promise {
const awaited = () =>
[..._pendingCompletions].filter(
- (completion) => options?.videoFrames !== false || !_videoFrameCompletions.has(completion),
+ ([, hold]) => options?.videoFrames !== false || hold !== "video-frame",
);
+ const timeoutMs = options?.timeoutMs;
+ const deadline = timeoutMs === undefined ? undefined : Date.now() + timeoutMs;
_activeCompletionBarriers += 1;
let failed = _pendingFailure;
try {
@@ -130,7 +159,21 @@ export async function waitForSeekCompletion(options?: { videoFrames?: boolean })
// before either one consumes it.
await Promise.resolve();
for (let pending = awaited(); pending.length > 0; pending = awaited()) {
- const results = await Promise.all(pending);
+ // Holds that keep arriving past the deadline must not outrun it.
+ const results =
+ deadline === undefined || Date.now() < deadline
+ ? await settledBy(
+ pending.map(([completion]) => completion),
+ deadline,
+ )
+ : null;
+ if (!results) {
+ const holds = [...new Set(awaited().map(([, hold]) => hold))].join(", ");
+ throw Object.assign(
+ new Error(`seek did not settle within ${timeoutMs} ms: still waiting on ${holds}`),
+ { name: "SeekNotSettledError" },
+ );
+ }
const rejected = results.find((result) => result.status === "rejected");
if (failed === undefined && rejected?.status === "rejected") {
failed = { reason: rejected.reason };
@@ -152,8 +195,7 @@ export async function waitForSeekCompletion(options?: { videoFrames?: boolean })
/** Reset internal state — used in tests to prevent cross-test contamination. */
export function resetSeekDispatchState(): void {
_lastDispatchedTime = -1;
- _pendingCompletions = new Set();
- _videoFrameCompletions = new WeakSet();
+ _pendingCompletions = new Map();
_pendingFailure = undefined;
_activeCompletionBarriers = 0;
}
diff --git a/packages/core/src/runtime/audioClockSource.test.ts b/packages/core/src/runtime/audioClockSource.test.ts
index 9c8c178743..c3e4997b63 100644
--- a/packages/core/src/runtime/audioClockSource.test.ts
+++ b/packages/core/src/runtime/audioClockSource.test.ts
@@ -323,23 +323,20 @@ describe("the audio the playhead follows", () => {
expect(window.__player!.getTime()).toBeGreaterThan(1.4);
});
- it("holds the playhead for a playing clip that has no data, then lets the picture run on", async () => {
- const stuck = await playStarved();
+ it("holds the playhead for a playing clip that has no data until it has some", async () => {
+ await playStarved();
stepFrames(1);
const held = window.__player!.getTime();
- stepFrames(60);
+ stepFrames(5 * 60);
expect(window.__player!.getTime()).toBe(held);
- stepFrames(4 * 60); // past the 3 s hold
- expect(window.__player!.getTime()).toBeGreaterThan(0.5);
- expect(stuck.paused).toBe(false);
});
- it("brings a clip whose data arrives late in where the playhead is, without moving it back", async () => {
+ it("plays on from where it held once a clip's late data arrives", async () => {
const late = await playStarved();
stepFrames(5 * 60);
const before = window.__player!.getTime();
- expect(before).toBeGreaterThan(1);
- late.readyState = 4; // its data arrives and it plays on from its start, until media sync seeks it
+ expect(before).toBeLessThan(0.1);
+ late.readyState = 4;
for (let frame = 0; frame < 30; frame++) {
late.currentTime += 1 / 60;
stepFrames(1);
diff --git a/packages/core/src/runtime/captureMotionBlur/discover.ts b/packages/core/src/runtime/captureMotionBlur/discover.ts
index e397d360c2..8fb6f36a82 100644
--- a/packages/core/src/runtime/captureMotionBlur/discover.ts
+++ b/packages/core/src/runtime/captureMotionBlur/discover.ts
@@ -38,6 +38,7 @@ export interface DiscoverOptions {
/** Seek the composition (timeline + adapters) to a time. */
seek: (t: number) => void;
onStep?: (i: number, steps: number) => void;
+ onStepBoxes?: (i: number, boxes: ReadonlyArray) => void;
}
export interface Discovery {
@@ -187,6 +188,7 @@ export function discoverMovers({
fps,
seek,
onStep,
+ onStepBoxes,
}: DiscoverOptions): Discovery {
seek(0);
const all = [...scene.querySelectorAll("*")].filter(isHtmlElement);
@@ -230,6 +232,7 @@ export function discoverMovers({
dynamic.add(el);
rects[j] = el.getBoundingClientRect();
});
+ onStepBoxes?.(i, rects);
const away = fresh.filter(
(j) => edgeShift(baseRects[j], rects[j]) / framesPerStep >= MIN_SPEED,
);
@@ -270,3 +273,51 @@ export function discoverMovers({
const translationOnly = movers.length > 0 && movers.every((el) => !notPlain.has(el));
return { movers, dynamic, pads, translationOnly };
}
+
+export interface ScanOptions extends Omit {
+ seek: (t: number, suppressEvents: boolean) => void;
+ events: boolean;
+}
+
+/** Every changing element's box, at 1/64 px, as one number per step. */
+function boxesKey(boxes: ReadonlyArray): number {
+ let h = 0x811c9dc5;
+ const mix = (v: number): void => {
+ h = Math.imul(h ^ v, 0x01000193);
+ };
+ boxes.forEach((b, j) => {
+ if (!b) return;
+ for (const v of [j, b.left, b.top, b.width, b.height]) mix(Math.round(v * 64));
+ });
+ return h;
+}
+
+/** Discovery, and whether pose reads need callbacks: when they change an element's style or box. */
+export function scanMovers({
+ seek,
+ events,
+ onStep,
+ ...scan
+}: ScanOptions): Discovery & { readEvents: boolean } {
+ const quiet = (t: number): void => seek(t, true);
+ if (!events) return { ...discoverMovers({ ...scan, seek: quiet, onStep }), readEvents: false };
+ // Loud first: run after the silent scan, it starts at the end and fires a one-off call once more.
+ const loud: number[] = [];
+ const found = discoverMovers({
+ ...scan,
+ seek: (t) => seek(t, false),
+ onStep,
+ onStepBoxes: (i, boxes) => {
+ loud[i] = boxesKey(boxes);
+ },
+ });
+ let differs = false;
+ discoverMovers({
+ ...scan,
+ seek: quiet,
+ onStepBoxes: (i, boxes) => {
+ differs ||= boxesKey(boxes) !== loud[i];
+ },
+ });
+ return { ...found, readEvents: differs };
+}
diff --git a/packages/core/src/runtime/captureMotionBlur/filterTier.ts b/packages/core/src/runtime/captureMotionBlur/filterTier.ts
index 53e06d6c59..a56aad1e2f 100644
--- a/packages/core/src/runtime/captureMotionBlur/filterTier.ts
+++ b/packages/core/src/runtime/captureMotionBlur/filterTier.ts
@@ -6,7 +6,7 @@
*/
import { swallow } from "../diagnostics";
-import { discoverMovers } from "./discover";
+import { scanMovers } from "./discover";
import { planFilter, type FilterPlan } from "./filterPlan";
import { readMoverFrames } from "./frames";
import { createPoseReader } from "./pose";
@@ -105,6 +105,8 @@ export function createFilterTier(
const width = Number(root.getAttribute("data-width")) || root.offsetWidth;
const height = Number(root.getAttribute("data-height")) || root.offsetHeight;
const seek = (t: number): void => host.seek(t, !config.events);
+ let readEvents = false;
+ const readSeek = (t: number): void => host.seek(t, !readEvents);
let defs: SVGSVGElement | null = null;
let movers: HTMLElement[] = [];
let pads = new Map();
@@ -121,13 +123,15 @@ export function createFilterTier(
function discover(restoreTo: number): void {
scanned = host.timeline();
const s0 = performance.now();
- const found = discoverMovers({
+ const found = scanMovers({
scene: root,
durationSeconds: host.durationSeconds(),
fps: host.fps,
- seek,
+ seek: host.seek,
+ events: config.events,
});
seek(restoreTo);
+ readEvents = found.readEvents;
movers = found.movers;
pads = found.pads;
reader = createPoseReader(root, found.dynamic);
@@ -178,7 +182,8 @@ export function createFilterTier(
const read = readMoverFrames({
movers,
reader,
- seek,
+ seek: readSeek,
+ restore: readEvents ? undefined : host.holdFrame?.(),
t,
reads: engineMode ? RENDER_READS : PREVIEW_READS,
shutterSeconds: config.shutterDeg / 360 / host.fps,
diff --git a/packages/core/src/runtime/captureMotionBlur/frames.ts b/packages/core/src/runtime/captureMotionBlur/frames.ts
index 624c48a3ea..651d25a394 100644
--- a/packages/core/src/runtime/captureMotionBlur/frames.ts
+++ b/packages/core/src/runtime/captureMotionBlur/frames.ts
@@ -14,6 +14,7 @@ export interface FrameRequest {
movers: HTMLElement[];
reader: ReturnType;
seek: (t: number) => void;
+ restore?: (t: number) => void;
t: number;
/** Pose reads across the shutter; the taps between them are interpolated. */
reads: number;
@@ -40,7 +41,7 @@ export function readMoverFrames(req: FrameRequest): { els: HTMLElement[]; frames
r.reset();
visible.forEach((el, i) => poses[i]?.push(r.pose(el)));
}
- seek(t);
+ (req.restore ?? seek)(t);
r.reset();
const frames = visible.map((el, i) => {
const pad = req.pads?.get(el) ?? 0;
diff --git a/packages/core/src/runtime/captureMotionBlur/index.test.ts b/packages/core/src/runtime/captureMotionBlur/index.test.ts
index 3979c6ebe6..62030e8f3c 100644
--- a/packages/core/src/runtime/captureMotionBlur/index.test.ts
+++ b/packages/core/src/runtime/captureMotionBlur/index.test.ts
@@ -889,10 +889,25 @@ describe("painting", () => {
}).h;
initCaptureMotionBlur(eventful);
win.__hfMotionBlur?.probe();
- expect(eventful.seek.mock.calls.length).toBeGreaterThan(10);
- expect(eventful.seek.mock.calls.every(([, suppress]) => suppress === false)).toBe(true);
+ const loud = eventful.seek.mock.calls.filter(([, suppress]) => suppress === false);
+ expect(loud.length).toBeGreaterThan(10);
+ // The page goes back to the frame with callbacks on after the scan.
+ expect(eventful.seek.mock.calls.at(-1)?.[1]).toBe(false);
});
+ /** A slider that only a timeline callback moves, as a render(t) function would. */
+ function callbackHost() {
+ const { root, el, h } = movingHost({
+ "data-motion-blur": "on",
+ "data-motion-blur-events": "on",
+ });
+ const slide = h.seek;
+ const seek = vi.fn((t: number, suppress: boolean) => {
+ if (!suppress) slide(t, suppress);
+ });
+ return { root, el, h: { ...h, seek } };
+ }
+
it("seeks pose reads with events suppressed unless the root allows them", () => {
installHtmlInCanvas();
const quiet = host(makeRoot());
@@ -901,17 +916,128 @@ describe("painting", () => {
expect(quiet.seek.mock.calls.every(([, suppress]) => suppress === true)).toBe(true);
resetCaptureMotionBlurForTests();
- const eventful = movingHost({
- "data-motion-blur": "on",
- "data-motion-blur-events": "on",
- }).h;
- initCaptureMotionBlur(eventful);
+ const { h } = callbackHost();
+ initCaptureMotionBlur(h);
void paintCaptureMotionBlur(0.5, PLAY);
- const calls = eventful.seek.mock.calls;
+ const calls = h.seek.mock.calls;
expect(calls.at(-1)?.[1]).toBe(false);
expect(calls.some(([, suppress]) => suppress === false)).toBe(true);
});
+ // Each frame's reads step back to the frame from half a shutter ahead. A callback that keeps
+ // state (a simulation that replays from zero on a backward seek) would redo all of it per frame.
+ it("reads poses with callbacks off when callbacks move no mover, even with events on", () => {
+ installHtmlInCanvas();
+ const { h } = movingHost({ "data-motion-blur": "on", "data-motion-blur-events": "on" });
+ initCaptureMotionBlur(h);
+ win.__hfMotionBlur?.probe();
+ expect(win.__hfMotionBlur?.report().movers).toBe(1);
+ h.seek.mockClear();
+ void paintCaptureMotionBlur(0.5, PLAY);
+ const reads = h.seek.mock.calls.filter(([t]) => t > 0);
+ expect(reads.length).toBeGreaterThan(0);
+ expect(reads.every(([, suppress]) => suppress === true)).toBe(true);
+ });
+
+ it("lands silent reads back on the frame through the host's holdFrame, taken before the first read", () => {
+ installHtmlInCanvas();
+ const { h } = movingHost({ "data-motion-blur": "on", "data-motion-blur-events": "on" });
+ const order: string[] = [];
+ const seek = vi.fn((t: number, suppress: boolean) => {
+ h.seek(t, suppress);
+ order.push(`seek ${t.toFixed(3)}`);
+ });
+ const hold = vi.fn(() => {
+ order.push("hold");
+ return (t: number) => void order.push(`restore ${t}`);
+ });
+ initCaptureMotionBlur({ ...h, seek, holdFrame: hold });
+ win.__hfMotionBlur?.probe();
+ order.length = 0;
+ void paintCaptureMotionBlur(0.5, PLAY);
+ const first = order.findIndex((step) => step.startsWith("seek 0.4"));
+ expect(order.indexOf("hold")).toBeGreaterThanOrEqual(0);
+ expect(order.indexOf("hold")).toBeLessThan(first);
+ expect(order.at(-1)).toBe("restore 0.5");
+ expect(order.filter((step) => step === "seek 0.500")).toEqual([]);
+ });
+
+ it("does not hold the page when callbacks run in the reads", () => {
+ installHtmlInCanvas();
+ const { h } = callbackHost();
+ const hold = vi.fn(() => () => {});
+ initCaptureMotionBlur({ ...h, holdFrame: hold });
+ win.__hfMotionBlur?.probe();
+ void paintCaptureMotionBlur(0.5, PLAY);
+ expect(hold).not.toHaveBeenCalled();
+ });
+
+ it("fires a one-off timeline call an even number of times over a scan, so a toggle ends as it began", () => {
+ installHtmlInCanvas();
+ const { h } = movingHost({ "data-motion-blur": "on", "data-motion-blur-events": "on" });
+ // A call at 0.7 s that flips state each time an eventful seek crosses it, either way.
+ let at = 0;
+ let flipped = false;
+ const slide = h.seek;
+ const seek = vi.fn((t: number, suppress: boolean) => {
+ slide(t, suppress);
+ if (!suppress && Math.min(at, t) < 0.7 && Math.max(at, t) >= 0.7) flipped = !flipped;
+ at = t;
+ });
+ initCaptureMotionBlur({ ...h, seek });
+ win.__hfMotionBlur?.probe();
+ expect(seek.mock.calls.length).toBeGreaterThan(10);
+ expect(flipped).toBe(false);
+ });
+
+ // Both scans find the same mover and the same changing elements; only the mover's box differs.
+ it("reads poses with callbacks on when a callback pans a mover's tweened ancestor", () => {
+ installHtmlInCanvas();
+ const { root, el, h } = movingHost({
+ "data-motion-blur": "on",
+ "data-motion-blur-events": "on",
+ });
+ const rig = document.createElement("div");
+ root.append(rig);
+ rig.append(el);
+ const pan = () => Number(/,\s*([-\d.]+),\s*0\)$/.exec(rig.style.transform)?.[1] ?? 0);
+ const own = el.getBoundingClientRect.bind(el);
+ el.getBoundingClientRect = () => {
+ const b = own();
+ return { ...b, left: b.left + pan(), right: b.right + pan() } as DOMRect;
+ };
+ rig.getBoundingClientRect = () =>
+ ({ left: pan(), top: 0, right: pan() + 10, bottom: 10, width: 10, height: 10 }) as DOMRect;
+ const slide = h.seek;
+ const seek = vi.fn((t: number, suppress: boolean) => {
+ slide(t, suppress);
+ rig.style.opacity = String(1 - t / 2);
+ if (!suppress) rig.style.transform = `matrix(1, 0, 0, 1, ${-30 * t}, 0)`;
+ });
+ initCaptureMotionBlur({ ...h, seek });
+ win.__hfMotionBlur?.probe();
+ expect(win.__hfMotionBlur?.report().movers).toBe(1);
+ seek.mockClear();
+ void paintCaptureMotionBlur(0.5, PLAY);
+ const reads = seek.mock.calls.filter(([t]) => t > 0);
+ expect(reads.length).toBeGreaterThan(0);
+ expect(reads.every(([, suppress]) => suppress === false)).toBe(true);
+ });
+
+ it("reads poses with callbacks on when a callback moves a mover", () => {
+ installHtmlInCanvas();
+ const { h } = callbackHost();
+ initCaptureMotionBlur(h);
+ win.__hfMotionBlur?.probe();
+ expect(win.__hfMotionBlur?.report().movers).toBe(1);
+ h.seek.mockClear();
+ void paintCaptureMotionBlur(0.5, PLAY);
+ // Wrapping resyncs at host.now() (0) on its own; the shutter's reads are the rest.
+ const reads = h.seek.mock.calls.filter(([t]) => t > 0);
+ expect(reads.length).toBeGreaterThan(0);
+ expect(reads.every(([, suppress]) => suppress === false)).toBe(true);
+ });
+
it("fires timeline callbacks during discovery only when the root allows events", () => {
for (const events of [true, false]) {
installHtmlInCanvas();
@@ -1788,6 +1914,21 @@ describe("filter fallback", () => {
expect(el.style.filter).toBe("drop-shadow(0px 0px 4px red)");
});
+ it("reads poses with callbacks off when callbacks move no mover in the filter tier too", () => {
+ const { h } = movingHost({
+ "data-motion-blur": "on",
+ "data-motion-blur-events": "on",
+ "data-motion-blur-tier": "filter",
+ });
+ initCaptureMotionBlur(h);
+ win.__hfMotionBlur?.probe();
+ expect(win.__hfMotionBlur?.report()).toMatchObject({ tier: "filter", movers: 1 });
+ h.seek.mockClear();
+ void paintCaptureMotionBlur(0.5, PLAY);
+ expect(h.seek.mock.calls.length).toBeGreaterThan(0);
+ expect(h.seek.mock.calls.every(([, suppress]) => suppress === true)).toBe(true);
+ });
+
it("removes its filters and its SVG on teardown", () => {
const { el, h } = movingHost();
initCaptureMotionBlur(h);
diff --git a/packages/core/src/runtime/captureMotionBlur/index.ts b/packages/core/src/runtime/captureMotionBlur/index.ts
index dae1d42e55..7750c6fc7e 100644
--- a/packages/core/src/runtime/captureMotionBlur/index.ts
+++ b/packages/core/src/runtime/captureMotionBlur/index.ts
@@ -1,8 +1,8 @@
/**
* Capture motion blur, in preview and render. Root attributes: data-motion-blur="on"|"off",
* -shutter (0–720°, default 240), -samples (2–64; unset: at least 32, more for a long smear),
- * -events="on" (run timeline callbacks at sub-frame samples). PAGE_MOTION_BLUR_OFF_GLOBAL (engine blur, or a preview that
- * could not blur) turns all off.
+ * -events="on" (callbacks run in the scan, and in pose reads when they move a mover).
+ * PAGE_MOTION_BLUR_OFF_GLOBAL (engine blur, or a preview that could not blur) turns all off.
*
* Per frame: read movers' poses across the shutter (seeks, no paint), capture the root and crop
* the movers, hide them and capture the background, then redraw each along its path.
@@ -36,7 +36,7 @@ import {
import { swallow } from "../diagnostics";
import { createCompositor, type MoverFrame } from "./composite";
import { readMotionBlurSettings } from "../../motionBlurSettings";
-import { discoverMovers } from "./discover";
+import { scanMovers } from "./discover";
import { createFilterTier } from "./filterTier";
import { readMoverFrames } from "./frames";
import { createPoseReader } from "./pose";
@@ -238,20 +238,24 @@ function createInstance(host: CaptureMotionBlurHost, config: Config, form: HtmlI
}
const seek = (t: number): void => host.seek(t, !config.events);
+ let readEvents = false;
+ const readSeek = (t: number): void => host.seek(t, !readEvents);
function discover(restoreTo: number): void {
scannedTimeline = host.timeline();
const duration = host.durationSeconds();
const defects = createDefectScan(root, isAccelerated);
const s0 = performance.now();
- const found = discoverMovers({
+ const found = scanMovers({
scene: root,
durationSeconds: duration,
fps: host.fps,
- seek,
+ seek: host.seek,
+ events: config.events,
onStep: (i, steps) => defects.sample(i, steps, (i / steps) * duration),
});
seek(restoreTo);
+ readEvents = found.readEvents;
scanDefect = defects.result();
faceNow = defects.facesNow;
movers = found.movers;
@@ -266,7 +270,8 @@ function createInstance(host: CaptureMotionBlurHost, config: Config, form: HtmlI
return readMoverFrames({
movers,
reader,
- seek,
+ seek: readSeek,
+ restore: readEvents ? undefined : host.holdFrame?.(),
t,
reads,
shutterSeconds: config.shutterDeg / 360 / host.fps,
diff --git a/packages/core/src/runtime/captureMotionBlur/tier.ts b/packages/core/src/runtime/captureMotionBlur/tier.ts
index 0270dbaa77..04e0a315b9 100644
--- a/packages/core/src/runtime/captureMotionBlur/tier.ts
+++ b/packages/core/src/runtime/captureMotionBlur/tier.ts
@@ -11,6 +11,7 @@ export interface CaptureMotionBlurHost {
now: () => number;
/** Seek the timeline and adapters (not media) for a pose read. */
seek: (t: number, suppressEvents: boolean) => void;
+ holdFrame?: () => (t: number) => void;
ignoreMutations?: (write: () => void) => void;
}
diff --git a/packages/core/src/runtime/capturedMediaIdleRoute.test.ts b/packages/core/src/runtime/capturedMediaIdleRoute.test.ts
index d0dd8289ae..6ec6b0e848 100644
--- a/packages/core/src/runtime/capturedMediaIdleRoute.test.ts
+++ b/packages/core/src/runtime/capturedMediaIdleRoute.test.ts
@@ -98,6 +98,7 @@ function mount(bodyHtml: string): void {
`${bodyHtml}
`;
for (const el of document.querySelectorAll("audio")) {
+ Object.defineProperty(el, "readyState", { value: 4, configurable: true });
el.load = () => {};
el.play = vi.fn(() => Promise.resolve());
el.pause = vi.fn();
diff --git a/packages/core/src/runtime/clock.safariAudio.test.ts b/packages/core/src/runtime/clock.safariAudio.test.ts
new file mode 100644
index 0000000000..413c48342c
--- /dev/null
+++ b/packages/core/src/runtime/clock.safariAudio.test.ts
@@ -0,0 +1,96 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { TransportClock } from "./clock";
+import { syncRuntimeMedia, type RuntimeMediaClip } from "./media";
+
+// Safari's audio reports the time it was started or seeked to, ready to play, until output begins.
+const OUTPUT_START_MS = 150;
+const SEEKING_MS = 30;
+const TICK_MS = 16;
+
+function safariAudio(now: () => number) {
+ const el = document.createElement("audio");
+ document.body.appendChild(el);
+ let position = 0;
+ let movingFromMs = Infinity;
+ let paused = true;
+ let rate = 1;
+ let seeks = 0;
+ let seekingUntilMs = -Infinity;
+ const restart = () => (movingFromMs = now() + OUTPUT_START_MS);
+ const advance = (dtMs: number) => {
+ if (!paused && now() >= movingFromMs) position += (dtMs / 1000) * rate;
+ };
+ Object.defineProperties(el, {
+ paused: { configurable: true, get: () => paused },
+ seeking: { configurable: true, get: () => now() < seekingUntilMs },
+ readyState: { configurable: true, get: () => 4 },
+ duration: { configurable: true, get: () => 60 },
+ played: {
+ configurable: true,
+ get: () => ({ length: 1, start: () => 0, end: () => position }),
+ },
+ playbackRate: { configurable: true, get: () => rate, set: (v: number) => (rate = v) },
+ currentTime: {
+ configurable: true,
+ get: () => position,
+ set: (v: number) => {
+ seeks += 1;
+ seekingUntilMs = now() + SEEKING_MS;
+ position = v;
+ restart();
+ },
+ },
+ });
+ el.play = vi.fn(() => {
+ paused = false;
+ restart();
+ return Promise.resolve();
+ });
+ el.pause = vi.fn(() => void (paused = true));
+ return { el, advance, seeks: () => seeks };
+}
+
+/** Plays one audio clip for `seconds`; like the runtime, the playhead follows it once it is unpaused. */
+function playAudioClock(seconds: number) {
+ let ms = 0;
+ const audio = safariAudio(() => ms);
+ const clock = new TransportClock({ nowMs: () => ms, duration: 60 });
+ const clip: RuntimeMediaClip = {
+ el: audio.el,
+ start: 0,
+ mediaStart: 0,
+ duration: 60,
+ end: 60,
+ volume: null,
+ playbackRate: 1,
+ loop: false,
+ sourceDuration: null,
+ };
+ clock.play();
+ for (ms = TICK_MS; ms < seconds * 1000; ms += TICK_MS) {
+ audio.advance(TICK_MS);
+ if (!audio.el.paused)
+ clock.attachAudioSource({ el: audio.el, compositionStart: 0, mediaStart: 0 });
+ syncRuntimeMedia({
+ clips: [clip],
+ timeSeconds: clock.now(),
+ playing: true,
+ playbackRate: 1,
+ getCompositionDuration: () => 60,
+ });
+ }
+ return { seeks: audio.seeks(), time: clock.now(), audioTime: audio.el.currentTime };
+}
+
+describe("an audio clock whose output starts late, as Safari's does", () => {
+ afterEach(() => {
+ document.body.innerHTML = "";
+ });
+
+ it("plays through without seeking the audio it follows", () => {
+ const run = playAudioClock(10);
+ expect(run.seeks).toBe(0);
+ expect(run.time).toBeGreaterThan(9.5);
+ expect(Math.abs(run.time - run.audioTime)).toBeLessThan(0.1);
+ });
+});
diff --git a/packages/core/src/runtime/clock.test.ts b/packages/core/src/runtime/clock.test.ts
index fbfad2ec33..89f4bc92a7 100644
--- a/packages/core/src/runtime/clock.test.ts
+++ b/packages/core/src/runtime/clock.test.ts
@@ -338,7 +338,7 @@ describe("TransportClock", () => {
expect(clock.getSource()).toBe("monotonic");
});
- it("holds, never rewinds, the playhead for a clip that started late, then follows it", () => {
+ it("never rewinds the playhead for a clip that started late, and runs on while it catches up", () => {
const { clock, advance } = createClock({ duration: 30 });
clock.play();
advancePolled(clock, advance, 6300);
@@ -347,20 +347,43 @@ describe("TransportClock", () => {
expect(clock.now()).toBeCloseTo(6.3, 5);
advance(100);
sfx.currentTime = 0.02;
- expect(clock.now()).toBeCloseTo(6.3, 5);
+ expect(clock.now()).toBeCloseTo(6.4, 5); // steering catches the clip up; the playhead does not wait
advance(100);
- sfx.currentTime = 0.12;
- expect(clock.now()).toBeCloseTo(6.37, 5);
+ sfx.currentTime = 0.4; // now it is ahead of the playhead: the playhead follows it
+ expect(clock.now()).toBeCloseTo(6.65, 5);
});
- it("holds the playhead while its element seeks, even to a time ahead", () => {
+ it("keeps the playhead moving while a just-played element is frozen behind it, as WebKit leaves it", () => {
+ const { clock, advance } = createClock({ duration: 30 });
+ clock.play();
+ advancePolled(clock, advance, 6300);
+ const take = createMockAudioEl(0, false); // playing, its time frozen at its start
+ clock.attachAudioSource({ el: take, compositionStart: 6, mediaStart: 0 });
+ let previous = clock.now();
+ for (let i = 0; i < 20; i++) {
+ advance(16);
+ const now = clock.now();
+ expect(now).toBeGreaterThan(previous);
+ previous = now;
+ }
+ });
+
+ it("keeps the playhead moving while the element it follows is seeked", () => {
const { clock, advance } = createClock({ duration: 30 });
clock.play();
advancePolled(clock, advance, 2000);
- const voice = Object.assign(createMockAudioEl(3, false), { seeking: true });
+ const voice = Object.assign(createMockAudioEl(0.1, false), { seeking: false });
clock.attachAudioSource({ el: voice, compositionStart: 2, mediaStart: 0 });
- advance(150);
- expect(clock.now()).toBeCloseTo(2, 5);
+ expect(clock.now()).toBeCloseTo(2.1, 5);
+ voice.seeking = true;
+ voice.currentTime = 3; // WebKit reports the target at once
+ let previous = clock.now();
+ for (let i = 0; i < 20; i++) {
+ advance(16);
+ const now = clock.now();
+ expect(now).toBeGreaterThan(previous);
+ previous = now;
+ }
});
it("holds the playhead on an element that is buffering behind it", () => {
@@ -395,14 +418,18 @@ describe("TransportClock", () => {
expect(clock.now()).toBeCloseTo(0.316, 5);
});
- it("holds the playhead for a looping bed that starts late", () => {
+ it("keeps the playhead moving for a looping bed that starts late", () => {
const { clock, advance } = createClock({ duration: 30 });
clock.play();
advancePolled(clock, advance, 2000);
- const bed = Object.assign(createMockAudioEl(0, false), { loop: true, duration: 8 });
+ const bed = Object.assign(createMockAudioEl(0, false), {
+ loop: true,
+ duration: 8,
+ readyState: 4,
+ });
clock.attachAudioSource({ el: bed, compositionStart: 1.9, mediaStart: 0 });
advance(16);
- expect(clock.now()).toBeCloseTo(2, 5);
+ expect(clock.now()).toBeCloseTo(2.016, 5);
});
it("continues from the last audio time when the element drops out", () => {
diff --git a/packages/core/src/runtime/clock.ts b/packages/core/src/runtime/clock.ts
index be846c5989..85dfa97312 100644
--- a/packages/core/src/runtime/clock.ts
+++ b/packages/core/src/runtime/clock.ts
@@ -1,5 +1,4 @@
import { timeAtSourceTime, type RateSpec } from "../speedRamp.js";
-import { MEDIA_HARD_SYNC_SECONDS } from "./mediaSteer.js";
import { playRangeHoldTime } from "./protocol.js";
export type TransportClockSnapshot = {
@@ -77,7 +76,6 @@ export class TransportClock {
}
}
- // Monotonic fallback
this._applyStallCorrection();
const elapsed = (this._nowMs() - this._playStartMs) / 1000;
const t = this._baseTime + elapsed * this._rate;
@@ -90,16 +88,12 @@ export class TransportClock {
): number | null {
const { el, compositionStart, mediaStart, rate } = source;
if (el.paused || !Number.isFinite(el.currentTime)) return null;
- if (el.seeking) return this._lastNow;
+ if (el.seeking) return null;
const spec = rate ?? 1;
const time = timeAtSourceTime(spec, el.currentTime - mediaStart) + compositionStart;
- return time >= this._lastNow ? time : this._heldTimeWhenBehind(el, this._lastNow - time, spec);
- }
-
- private _heldTimeWhenBehind(el: HTMLMediaElement, behind: number, spec: RateSpec): number | null {
- if (el.loop && behind > timeAtSourceTime(spec, el.duration) / 2) return null;
- const buffering = el.readyState < HAVE_FUTURE_DATA;
- return buffering || behind <= MEDIA_HARD_SYNC_SECONDS ? this._lastNow : null;
+ if (time >= this._lastNow) return time;
+ const wrapped = el.loop && this._lastNow - time > timeAtSourceTime(spec, el.duration) / 2;
+ return !wrapped && el.readyState < HAVE_FUTURE_DATA ? this._lastNow : null;
}
/** Folds a >500ms gap since the last read into `_playStartMs` so it's never reported as played time. */
diff --git a/packages/core/src/runtime/frameSources.ts b/packages/core/src/runtime/frameSources.ts
index 6b944e9d65..e765e2103b 100644
--- a/packages/core/src/runtime/frameSources.ts
+++ b/packages/core/src/runtime/frameSources.ts
@@ -111,7 +111,7 @@ export function createFrameSourceAdapter(timing: {
if (!owned.has(source)) {
owned.add(source);
// Readiness trackers settle rejected setup; capture must also receive that failure.
- registerSeekCompletion(source.ready);
+ registerSeekCompletion(source.ready, "frame-source");
}
connected.push([element, source]);
}
@@ -140,7 +140,7 @@ export function createFrameSourceAdapter(timing: {
const localTime = Math.max(0, time - start);
const sourceTime =
readMediaStart(element) + sourceTimeAt(readElementRateSpec(element), localTime);
- registerSeekCompletion(source.seek(sourceTime));
+ registerSeekCompletion(source.seek(sourceTime), "frame-source");
}
},
getReadyPromise: () => {
diff --git a/packages/core/src/runtime/frozenPicture.test.ts b/packages/core/src/runtime/frozenPicture.test.ts
new file mode 100644
index 0000000000..3be68d3ba1
--- /dev/null
+++ b/packages/core/src/runtime/frozenPicture.test.ts
@@ -0,0 +1,70 @@
+import { describe, expect, it } from "vitest";
+import { hasFrozenPicture } from "./frozenPicture";
+import { mediaSourceTimeAt } from "./media";
+import type { RuntimeMediaClip } from "./types";
+
+type Facts = { readyState: number; currentTime: number };
+
+function clip(
+ over: Partial = {},
+ facts: Facts = { readyState: 4, currentTime: 0 },
+) {
+ const el = document.createElement("video");
+ Object.defineProperty(el, "readyState", { get: () => facts.readyState, configurable: true });
+ Object.defineProperty(el, "currentTime", { get: () => facts.currentTime, configurable: true });
+ const made: RuntimeMediaClip = {
+ el,
+ start: 0,
+ mediaStart: 0,
+ duration: 30,
+ end: 30,
+ volume: null,
+ playbackRate: 1,
+ loop: false,
+ sourceDuration: 30,
+ ...over,
+ };
+ return { clip: made, facts };
+}
+
+/** Plays `seconds` of film in 60 Hz ticks, the video's clock following its clip's timing; counts the frozen ticks. */
+function playFollowing(made: ReturnType, from: number, seconds: number) {
+ let frozen = 0;
+ for (let t = from; t <= from + seconds; t += 1 / 60) {
+ made.facts.currentTime = mediaSourceTimeAt(made.clip, t);
+ if (hasFrozenPicture([made.clip], t)) frozen += 1;
+ }
+ return frozen;
+}
+
+describe("hasFrozenPicture", () => {
+ it("is false while a video's clock follows its clip's timing and it has a frame", () => {
+ expect(playFollowing(clip(), 0, 4)).toBe(0);
+ });
+
+ it("is true for a video with no frame to show, though it is paused", () => {
+ const v = clip({}, { readyState: 0, currentTime: 0 });
+ expect(hasFrozenPicture([v.clip], 0)).toBe(true);
+ });
+
+ it("is true once a video's clock stands still for a second of film, and false again when it moves", () => {
+ const v = clip({}, { readyState: 4, currentTime: 2 });
+ hasFrozenPicture([v.clip], 10);
+ expect(hasFrozenPicture([v.clip], 10.5)).toBe(false);
+ expect(hasFrozenPicture([v.clip], 11.2)).toBe(true);
+ v.facts.currentTime = 3.2;
+ expect(hasFrozenPicture([v.clip], 12.3)).toBe(false);
+ });
+
+ it("never reads a looping clip's wrap as a stall", () => {
+ expect(playFollowing(clip({ loop: true, sourceDuration: 3 }), 0, 12)).toBe(0);
+ });
+
+ it("never reads a clip at the slowest rate as a stall", () => {
+ expect(playFollowing(clip({ playbackRate: 0.1 }), 0, 12)).toBe(0);
+ });
+
+ it("does not count a clip holding its last frame", () => {
+ expect(playFollowing(clip({ sourceDuration: 2, end: 30 }), 0, 8)).toBe(0);
+ });
+});
diff --git a/packages/core/src/runtime/frozenPicture.ts b/packages/core/src/runtime/frozenPicture.ts
new file mode 100644
index 0000000000..e5bb8ffbec
--- /dev/null
+++ b/packages/core/src/runtime/frozenPicture.ts
@@ -0,0 +1,46 @@
+import { isVideoElement } from "./domRealm";
+import { mediaSourceTimeAt } from "./media";
+import type { RuntimeMediaClip } from "./types";
+
+const FROZEN_PICTURE = {
+ lookSeconds: 1,
+ movedShare: 0.1,
+ minDueSeconds: 0.05,
+} as const;
+
+const HAVE_CURRENT_DATA = 2;
+
+type Look = { film: number; time: number };
+const looks = new WeakMap();
+const stood = new WeakSet();
+
+function look(el: HTMLVideoElement, film: number): void {
+ looks.set(el, { film, time: el.currentTime });
+}
+
+function judge(clip: RuntimeMediaClip, el: HTMLVideoElement, last: Look, film: number): void {
+ const due = mediaSourceTimeAt(clip, film) - mediaSourceTimeAt(clip, last.film);
+ const moved = el.currentTime - last.time;
+ const standing = due >= FROZEN_PICTURE.minDueSeconds && moved < due * FROZEN_PICTURE.movedShare;
+ if (standing) stood.add(el);
+ else stood.delete(el);
+}
+
+/** Whether any video in the window shows nothing, or its clock stands still against its clip's own timing. */
+export function hasFrozenPicture(clips: readonly RuntimeMediaClip[], filmTime: number): boolean {
+ let frozen = false;
+ for (const clip of clips) {
+ const el = clip.el;
+ if (!isVideoElement(el)) continue;
+ const last = looks.get(el);
+ if (!last || filmTime < last.film) {
+ look(el, filmTime);
+ stood.delete(el);
+ } else if (filmTime - last.film >= FROZEN_PICTURE.lookSeconds) {
+ judge(clip, el, last, filmTime);
+ look(el, filmTime);
+ }
+ if (el.readyState < HAVE_CURRENT_DATA || stood.has(el)) frozen = true;
+ }
+ return frozen;
+}
diff --git a/packages/core/src/runtime/init.buffering.test.ts b/packages/core/src/runtime/init.buffering.test.ts
new file mode 100644
index 0000000000..306d1d6899
--- /dev/null
+++ b/packages/core/src/runtime/init.buffering.test.ts
@@ -0,0 +1,123 @@
+import { afterEach, expect, it, vi } from "vitest";
+import { initSandboxRuntimeModular } from "./init";
+import { createMockTimeline, resetRuntimeFixtureDom } from "./runtimeSeekFixture.test-helpers";
+
+function audio(id: string, duration: number, readyState: { value: number; bufferedTo?: number }) {
+ const el = document.getElementById(id) as HTMLAudioElement;
+ let paused = true;
+ Object.defineProperties(el, {
+ duration: { value: duration, configurable: true },
+ readyState: { get: () => readyState.value, configurable: true },
+ buffered: {
+ get: () => ({ length: 1, start: () => 0, end: () => readyState.bufferedTo ?? 0 }),
+ configurable: true,
+ },
+ paused: { get: () => paused, configurable: true },
+ });
+ el.play = vi.fn(() => {
+ paused = false;
+ return Promise.resolve();
+ });
+ el.pause = vi.fn(() => {
+ if (!paused) el.dispatchEvent(new Event("pause"));
+ paused = true;
+ });
+ el.load = vi.fn();
+ return el;
+}
+
+function playPodcast(voiceStart = 0) {
+ resetRuntimeFixtureDom();
+ document.body.innerHTML =
+ '";
+ const voiceReady: { value: number; bufferedTo?: number } = { value: 1 };
+ const music = audio("music", 10, { value: 4 });
+ const voice = audio("voice", 4, voiceReady);
+ window.__timelines = { main: createMockTimeline(10) };
+
+ let now = 0;
+ const frames = new Map();
+ let nextFrame = 0;
+ vi.spyOn(performance, "now").mockImplementation(() => now);
+ window.requestAnimationFrame = (cb) => (frames.set(++nextFrame, cb), nextFrame);
+ window.cancelAnimationFrame = (id) => void frames.delete(id);
+ const states: Array<{ isPlaying: boolean; buffering: boolean }> = [];
+ vi.spyOn(window.parent, "postMessage").mockImplementation((message: unknown) => {
+ const m = message as { type?: string; isPlaying: boolean; buffering: boolean };
+ if (m?.type === "state") states.push({ isPlaying: m.isPlaying, buffering: m.buffering });
+ });
+
+ initSandboxRuntimeModular();
+ window.__player!.play();
+ const step = (ms: number) => {
+ now += ms;
+ const due = [...frames.values()];
+ frames.clear();
+ for (const cb of due) cb(now);
+ };
+ const playFor = (seconds: number) => {
+ for (let ms = 0; ms < seconds * 1000; ms += 1000 / 60) step(1000 / 60);
+ };
+ return { music, voice, voiceReady, states, playFor, step };
+}
+
+it("a track not ready pauses everything with Buffering, and resumes when it can play", () => {
+ const { music, voice, voiceReady, states, playFor } = playPodcast();
+
+ playFor(1);
+ expect(window.__player!.getTime()).toBeLessThan(0.1);
+ expect(music.paused).toBe(true);
+ expect(states.at(-1)).toEqual({ isPlaying: true, buffering: true });
+
+ voiceReady.value = 4;
+ playFor(1);
+ expect(window.__player!.getTime()).toBeGreaterThan(0.9);
+ expect(music.paused).toBe(false);
+ expect(voice.paused).toBe(false);
+ expect(states.at(-1)).toEqual({ isPlaying: true, buffering: false });
+});
+
+it("holds on the frame a slow tick skips into a clip with no data, after asking it to play", () => {
+ const { voice, states, playFor, step } = playPodcast(0.5);
+
+ playFor(0.4);
+ expect(voice.play).not.toHaveBeenCalled();
+ step(250);
+ expect(voice.play).toHaveBeenCalled();
+ expect(states.at(-1)).toEqual({ isPlaying: true, buffering: true });
+});
+
+it("resumes for a held clip with data buffered ahead that reports only its current frame, as WebKit's do", () => {
+ const { voiceReady, states, playFor } = playPodcast();
+
+ playFor(0.5);
+ voiceReady.value = 2;
+ playFor(0.5);
+ expect(states.at(-1)).toEqual({ isPlaying: true, buffering: true });
+
+ voiceReady.bufferedTo = 2;
+ playFor(1);
+ expect(window.__player!.getTime()).toBeGreaterThan(0.9);
+ expect(states.at(-1)).toEqual({ isPlaying: true, buffering: false });
+});
+
+it("a pause while buffering stays paused once the track is ready", () => {
+ const { music, voiceReady, states, playFor } = playPodcast();
+
+ playFor(0.5);
+ window.__player!.pause();
+ voiceReady.value = 4;
+ playFor(1);
+ expect(window.__player!.getTime()).toBeLessThan(0.1);
+ expect(music.paused).toBe(true);
+ expect(states.at(-1)).toEqual({ isPlaying: false, buffering: false });
+});
+
+afterEach(() => {
+ window.__hfRuntimeTeardown?.();
+ vi.restoreAllMocks();
+ resetRuntimeFixtureDom();
+});
diff --git a/packages/core/src/runtime/init.seekOrder.test.ts b/packages/core/src/runtime/init.seekOrder.test.ts
index 6a30f1d43e..e4e7eb839a 100644
--- a/packages/core/src/runtime/init.seekOrder.test.ts
+++ b/packages/core/src/runtime/init.seekOrder.test.ts
@@ -52,7 +52,7 @@ function mountTimingFilm() {
initSandboxRuntimeModular();
step(40);
let land = () => {};
- registerSeekCompletion(new Promise((resolve) => (land = resolve)));
+ registerSeekCompletion(new Promise((resolve) => (land = resolve)), "hf-seek");
posts.length = 0;
const editTiming = async () => {
document.getElementById("clip")!.setAttribute("data-duration", "12");
diff --git a/packages/core/src/runtime/init.startsOnce.test.ts b/packages/core/src/runtime/init.startsOnce.test.ts
new file mode 100644
index 0000000000..f2aca79d66
--- /dev/null
+++ b/packages/core/src/runtime/init.startsOnce.test.ts
@@ -0,0 +1,57 @@
+// @vitest-environment happy-dom
+
+import { afterEach, expect, it, vi } from "vitest";
+import { initSandboxRuntimeModular } from "./init";
+import { createMockTimeline, resetRuntimeFixtureDom } from "./runtimeSeekFixture.test-helpers";
+
+afterEach(() => {
+ window.__hfRuntimeTeardown?.();
+ vi.restoreAllMocks();
+ resetRuntimeFixtureDom();
+});
+
+it("reads a far clip's start once while playing, not on every frame", () => {
+ resetRuntimeFixtureDom();
+ let now = 0;
+ let id = 0;
+ const callbacks = new Map();
+ vi.spyOn(performance, "now").mockImplementation(() => now);
+ vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => {
+ callbacks.set(++id, callback);
+ return id;
+ });
+ vi.spyOn(window, "cancelAnimationFrame").mockImplementation((key) => {
+ callbacks.delete(key);
+ });
+ const step = (frames: number) => {
+ for (let i = 0; i < frames; i++) {
+ now += 33;
+ const pending = [...callbacks.values()];
+ callbacks.clear();
+ for (const callback of pending) callback(now);
+ }
+ };
+ const words = Array.from(
+ { length: 300 },
+ (_, i) => ` `,
+ );
+ document.body.innerHTML = `${words.join("")}
`;
+ window.__timelines = { main: createMockTimeline(60) };
+ initSandboxRuntimeModular();
+ const player = window.__player!;
+ const far = document.getElementById("w299")!;
+ const startReads = vi.fn();
+ const getAttribute = far.getAttribute.bind(far);
+ far.getAttribute = (name: string) => {
+ if (name === "data-start") startReads();
+ return getAttribute(name);
+ };
+
+ player.play();
+ step(5);
+ const afterWarmUp = startReads.mock.calls.length;
+ step(60);
+
+ expect(player.isPlaying()).toBe(true);
+ expect(startReads.mock.calls.length - afterWarmUp).toBe(0);
+});
diff --git a/packages/core/src/runtime/init.swapScenes.test.ts b/packages/core/src/runtime/init.swapScenes.test.ts
index 3cd4a58d5d..80a0cec09b 100644
--- a/packages/core/src/runtime/init.swapScenes.test.ts
+++ b/packages/core/src/runtime/init.swapScenes.test.ts
@@ -1924,6 +1924,28 @@ describe("the preview's scene window", () => {
}
});
+ it("settles when a scene it would retire cannot be retired, instead of planning it again forever", async () => {
+ bootWindowed([S0, S1, S2], trackingRoot().root);
+ await tick();
+ window.__hfSceneAnimations = { s0: [made.a1] };
+ window.__timelines.elsewhere = made.a1;
+ try {
+ await seekAndSettle(5);
+ const host = sceneHost("s0");
+ const has = host.hasAttribute.bind(host);
+ let asks = 0;
+ host.hasAttribute = (name: string) => {
+ // A runaway plan starves every timer; seeking back to s0 is what ends it, so a failure fails, not hangs.
+ if (name === "data-hf-scene-no-swap" && ++asks === 1000) window.__player?.seek(0.5);
+ return has(name);
+ };
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(asks).toBeLessThan(100);
+ } finally {
+ delete window.__hfSceneAnimations;
+ }
+ });
+
it("shows a scene mounted again after the visibility pass hid it by display and it unmounted", async () => {
const leaf: Scene = { ...S2, body: "two
", extraAttrs: ' style="position: static"' };
bootWindowed([S0, S1, leaf], trackingRoot().root);
diff --git a/packages/core/src/runtime/init.test.ts b/packages/core/src/runtime/init.test.ts
index 8423788bdc..3e5b6c44f0 100644
--- a/packages/core/src/runtime/init.test.ts
+++ b/packages/core/src/runtime/init.test.ts
@@ -263,6 +263,7 @@ describe("initSandboxRuntimeModular", () => {
delete window.__playerReady;
delete window.__renderReady;
delete (window as { __HF_EXPORT_RENDER_SEEK_CONFIG?: unknown }).__HF_EXPORT_RENDER_SEEK_CONFIG;
+ delete window.__HF_REPLAY_SKIPPED_FRAMES;
delete window.__hfTimelinesBuilding;
delete (window as { THREE?: unknown }).THREE;
delete (window as { __hfAutoNoopRegistered?: boolean }).__hfAutoNoopRegistered;
@@ -611,6 +612,25 @@ describe("initSandboxRuntimeModular", () => {
}
});
+ it("leaves hidden clips alone on every jump when the page has no timeline", () => {
+ document.body.innerHTML =
+ `` +
+ ` ` +
+ ` ` +
+ `
`;
+ window.__timelines = {};
+ initSandboxRuntimeModular();
+ const query = vi.spyOn(document, "querySelectorAll");
+ const looked = () =>
+ query.mock.calls.filter(([selector]) => selector === "[data-hf-clip-hidden]").length;
+ try {
+ for (const t of [0.5, 1, 1.5, 3, 6]) window.__player?.seek(t);
+ expect(looked()).toBe(0);
+ } finally {
+ query.mockRestore();
+ }
+ });
+
it("styles a hidden clip visible once while playing toward its start, far scene included", () => {
document.body.innerHTML =
`` +
@@ -1200,6 +1220,36 @@ describe("initSandboxRuntimeModular", () => {
});
});
+ it("gives a still the value playback shows when its capture page asks to replay skipped frames", () => {
+ const zoomFilm = () => {
+ const params = { z: 1 };
+ const timeline = gsap.timeline({ paused: true });
+ timeline.to(params, { z: 1.45, duration: 0.3, ease: "power4.out" }, 0.573);
+ timeline.set(params, { z: 1.04 }, 0.8);
+ timeline.to(params, { z: 1.12, duration: 1.39, ease: "power1.in" }, 0.869);
+ return { params, timeline };
+ };
+ const played = zoomFilm();
+ for (let frame = 0; frame <= 56; frame++) played.timeline.totalTime(frame / 60, true);
+ const root = document.createElement("div");
+ root.setAttribute("data-composition-id", "main");
+ root.setAttribute("data-root", "true");
+ root.setAttribute("data-start", "0");
+ root.setAttribute("data-duration", "3");
+ root.setAttribute("data-fps", "60");
+ root.setAttribute("data-width", "640");
+ root.setAttribute("data-height", "360");
+ document.body.appendChild(root);
+ const still = zoomFilm();
+ window.__timelines = { main: still.timeline as unknown as RuntimeTimelineLike };
+ window.__HF_REPLAY_SKIPPED_FRAMES = true;
+
+ initSandboxRuntimeModular();
+ window.__player?.renderSeek(56 / 60);
+
+ expect(still.params.z).toBeCloseTo(played.params.z, 9);
+ });
+
it("activates a nested outro on frame 584 when its authored start rounds just above it", () => {
const root = document.createElement("div");
root.setAttribute("data-composition-id", "main");
@@ -3957,6 +4007,16 @@ describe("initSandboxRuntimeModular", () => {
expect(startedAt[0]).toBeGreaterThanOrEqual(1 - 0.02);
});
+ it("primes a clip that starts later inside the tap on iOS, so a late start is not refused", () => {
+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue(
+ "Mozilla/5.0 (iPhone; CPU iPhone OS 26_5 like Mac OS X) AppleWebKit/605.1.15 Mobile/15E148",
+ );
+ const { sfx } = mountLateSfx();
+ window.__player?.play();
+ expect(sfx.play).toHaveBeenCalledTimes(1);
+ expect(sfx.pause).toHaveBeenCalledTimes(1);
+ });
+
const setRate = (playbackRate: number) =>
window.dispatchEvent(
new MessageEvent("message", {
diff --git a/packages/core/src/runtime/init.ts b/packages/core/src/runtime/init.ts
index a93258938a..9843e6fe60 100644
--- a/packages/core/src/runtime/init.ts
+++ b/packages/core/src/runtime/init.ts
@@ -26,6 +26,7 @@ import {
stopMediaDownload,
} from "./preloadMedia";
import { notePlaybackFrame, noteDisplayScale } from "./playbackHealth";
+import { hasFrozenPicture } from "./frozenPicture";
import { copiesReady } from "./previewCopies";
import { installRuntimeControlBridge, postRuntimeMessage, setRuntimeProtocolFps } from "./bridge";
import { instantTolerance } from "../clipFacts";
@@ -53,6 +54,7 @@ import { injectCompositionCssVariables } from "./getVariables";
import { createCssAdapter } from "./adapters/css";
import {
createGsapAdapter,
+ holdFrameMarks,
rerenderGsapTimelineAt,
seekGsapTimeline,
type GsapStructureKey,
@@ -84,6 +86,7 @@ import {
MEDIA_SYNC_TOLERANCE_SECONDS,
isUnplayable,
mediaSourceTimeAt,
+ primeMediaForLaterStarts,
readElementPlaybackRate,
readElementPlaybackStart,
readElementRateSpec,
@@ -550,6 +553,8 @@ export function initSandboxRuntimeModular(): void {
ensureColorGroupInertStyle(document);
const exportRenderFps = resolveExportRenderFps();
state.canonicalFps = exportRenderFps.fps ?? compositionFps() ?? state.canonicalFps;
+ const renderFps =
+ exportRenderFps.fps ?? (window.__HF_REPLAY_SKIPPED_FRAMES ? state.canonicalFps : undefined);
setRuntimeProtocolFps(state.canonicalFps);
if (window.__HF_EXPORT_RENDER_SEEK_CONFIG) {
const fpsDetail = JSON.stringify({
@@ -2945,12 +2950,23 @@ export function initSandboxRuntimeModular(): void {
// A clip's first visible style pass is slow; playing, each hidden clip gets it once just before its start.
const clipsNeverStyledVisible = new Set
();
const clipsStyledVisible = new WeakSet();
- const styleClipsDueVisibleOnce = (t: number) => {
+ let neverStyledStarts = { revision: -1, starts: new Map() };
+ const neverStyledStart = (el: StylableElement, revision: number): number => {
+ if (neverStyledStarts.revision !== revision)
+ neverStyledStarts = { revision, starts: new Map() };
+ let start = neverStyledStarts.starts.get(el);
+ if (start === undefined) {
+ start = resolveStartForElement(el, Number.NaN);
+ neverStyledStarts.starts.set(el, start);
+ }
+ return start;
+ };
+ const styleClipsDueVisibleOnce = (t: number, revision: number) => {
if (clipsNeverStyledVisible.size === 0 || !clock.isPlaying()) return;
const clips: StylableElement[] = [];
for (const el of clipsNeverStyledVisible) {
- const start = resolveStartForElement(el, Number.NaN);
- if (el.isConnected && el.hasAttribute(CLIP_HIDDEN_ATTR) && !(start <= t + LOOKAHEAD_SECONDS))
+ const start = neverStyledStart(el, revision);
+ if (!(start <= t + LOOKAHEAD_SECONDS) && el.isConnected && el.hasAttribute(CLIP_HIDDEN_ATTR))
continue;
clipsNeverStyledVisible.delete(el);
if (el.isConnected && el.hasAttribute(CLIP_HIDDEN_ATTR) && start > t) clips.push(el);
@@ -3404,6 +3420,8 @@ export function initSandboxRuntimeModular(): void {
// boundaries crossed in between.
let lastSyncedMediaTimeSeconds: number | null = null;
let mediaClipsInWindow: RuntimeMediaClip[] = [];
+ // Clips due now that could not play: every track holds until they can, so none runs on alone.
+ let bufferingFor: HTMLMediaElement[] = [];
// The one definition of "media the transport drives": timed itself, or hosted
// by a composition whose timing it inherits. Both the media cache and the
@@ -3737,12 +3755,12 @@ export function initSandboxRuntimeModular(): void {
const shouldPost =
force ||
frame !== state.bridgeLastPostedFrame ||
- state.isPlaying !== state.bridgeLastPostedPlaying ||
+ (state.isPlaying || bufferingFor.length > 0) !== state.bridgeLastPostedPlaying ||
state.bridgeMuted !== state.bridgeLastPostedMuted ||
now - state.bridgeLastPostedAt >= state.bridgeMaxPostIntervalMs;
if (!shouldPost) return;
state.bridgeLastPostedFrame = frame;
- state.bridgeLastPostedPlaying = state.isPlaying;
+ state.bridgeLastPostedPlaying = state.isPlaying || bufferingFor.length > 0;
state.bridgeLastPostedMuted = state.bridgeMuted;
state.bridgeLastPostedAt = now;
postRuntimeMessage({
@@ -3751,7 +3769,8 @@ export function initSandboxRuntimeModular(): void {
frame,
currentTime: state.currentTime || 0,
ended: clock.reachedEnd(),
- isPlaying: state.isPlaying,
+ isPlaying: state.bridgeLastPostedPlaying,
+ buffering: bufferingFor.length > 0,
muted: state.bridgeMuted,
playbackRate: state.playbackRate,
});
@@ -3971,6 +3990,19 @@ export function initSandboxRuntimeModular(): void {
seek: (t, suppressEvents) => {
seekRootChildrenAndAdapters(state.capturedTimeline, t, { suppressEvents });
},
+ // Silent pose reads re-arm GSAP's landing marks (a step at t would fire again), and a render
+ // seek, which has no structure, lands back on t without same-time steps' authored order.
+ holdFrame: () => {
+ const land = holdFrameMarks({
+ scenes: sceneTimelines().map(([, timeline]) => timeline),
+ root: state.capturedTimeline,
+ structureOf: gsapStructureOf,
+ });
+ return (t) =>
+ land(() =>
+ seekRootChildrenAndAdapters(state.capturedTimeline, t, { suppressEvents: true }),
+ );
+ },
ignoreMutations: withoutOwnCompositionRecords,
});
}
@@ -4555,7 +4587,11 @@ export function initSandboxRuntimeModular(): void {
({ name, start, end }) => start <= time && time <= end && parked(name),
);
if (windowWork) {
- if (landed) registerSeekCompletion(windowWork.then(() => windowWork));
+ if (landed)
+ registerSeekCompletion(
+ windowWork.then(() => windowWork),
+ "scene-window",
+ );
return landed !== undefined;
}
const near = scenesWanted(windowScenes, time, clock.isPlaying());
@@ -4577,6 +4613,7 @@ export function initSandboxRuntimeModular(): void {
const wantedNow = (name: string) =>
heldScenes.has(name) ||
scenesWanted(windowScenes, state.currentTime, clock.isPlaying()).has(name);
+ const parkedBeforeStep = parkedNames.size;
windowWork = (async () => {
if (landed) await mountScene(landed.name);
else if (toMount) {
@@ -4586,11 +4623,12 @@ export function initSandboxRuntimeModular(): void {
} else for (const { name } of toRetire) retireScene(name);
})().finally(() => {
windowWork = null;
- windowNear = "";
+ const stuckStepKeepsItsPlan = parkedNames.size === parkedBeforeStep;
+ windowNear = stuckStepKeepsItsPlan ? key : "";
moveSceneWindow(state.currentTime);
});
// A seek is not done until the scene it lands in is mounted.
- if (landed) registerSeekCompletion(windowWork);
+ if (landed) registerSeekCompletion(windowWork, "scene-window");
return landed !== undefined;
};
// Mounts the named scenes and keeps them mounted until the same holder's next call names others.
@@ -4688,13 +4726,32 @@ export function initSandboxRuntimeModular(): void {
colorGrading.redraw();
paintVfx(state.currentTime);
const blurred = paintCaptureMotionBlur(state.currentTime);
- if (blurred) registerSeekCompletion(blurred);
+ if (blurred) registerSeekCompletion(blurred, "motion-blur");
+ postState(true);
+ };
+
+ const haltPlayback = () => {
+ webAudio.stopAll();
+ clock.detachAudioSource();
+ clock.pause();
+ state.isPlaying = false;
+ state.currentTime = clock.now();
+ state.mediaForceSyncNextTick = true;
+ hardSyncAllMedia(state.currentTime);
+ const tl = state.capturedTimeline;
+ pauseTimelineIfPossible(tl);
+ runAdapters("pause");
+ syncMediaForCurrentState();
+ colorGrading.redraw();
+ // Paused: back to plain DOM so Studio can select inside the composition.
+ void paintCaptureMotionBlur(state.currentTime);
postState(true);
};
const transport: RuntimePlayerTransport = {
play: () => {
flushHeldSeek();
+ bufferingFor = [];
const tl = state.capturedTimeline;
if (clock.isPlaying()) return;
const dur = getSafeTimelineDurationSeconds(tl, 0);
@@ -4720,26 +4777,15 @@ export function initSandboxRuntimeModular(): void {
}
runAdapters("play");
syncMediaForCurrentState();
+ primeMediaForLaterStarts(resolveMediaClipIndex().clips.map((clip) => clip.el));
colorGrading.redraw();
postState(true);
},
pause: () => {
- if (!clock.isPlaying()) return;
- webAudio.stopAll();
- clock.detachAudioSource();
- clock.pause();
- state.isPlaying = false;
- state.currentTime = clock.now();
- state.mediaForceSyncNextTick = true;
- hardSyncAllMedia(state.currentTime);
- const tl = state.capturedTimeline;
- pauseTimelineIfPossible(tl);
- runAdapters("pause");
- syncMediaForCurrentState();
- colorGrading.redraw();
- // Paused: back to plain DOM so Studio can select inside the composition.
- void paintCaptureMotionBlur(state.currentTime);
- postState(true);
+ const wasBuffering = bufferingFor.length > 0;
+ bufferingFor = [];
+ if (clock.isPlaying()) haltPlayback();
+ else if (wasBuffering) postState(true);
},
seek: (timeSeconds, options) => {
const quantized = quantizeTimeToFrame(
@@ -4773,7 +4819,7 @@ export function initSandboxRuntimeModular(): void {
window.clearTimeout(capTimer);
if (heldSeek === held) flushHeldSeek();
});
- registerSeekCompletion(landed);
+ registerSeekCompletion(landed, "image-decode");
return landed;
},
renderSeek: (timeSeconds, options) => {
@@ -4799,7 +4845,7 @@ export function initSandboxRuntimeModular(): void {
colorGrading.redraw();
paintVfx(state.currentTime, { engineMode: true });
const blurred = paintCaptureMotionBlur(state.currentTime, { engineMode: true });
- if (blurred) registerSeekCompletion(blurred);
+ if (blurred) registerSeekCompletion(blurred, "motion-blur");
postState(true);
},
getTime: () => heldSeek?.time ?? clock.now(),
@@ -5084,7 +5130,7 @@ export function initSandboxRuntimeModular(): void {
const suppressEvents = options?.suppressEvents === true;
// Guarded: a partial timeline without pause() must still get its seek.
pauseTimelineIfPossible(timeline);
- seekGsapTimeline(timeline, timeSeconds, suppressEvents, gsapStructureOf(timeline));
+ seekGsapTimeline(timeline, timeSeconds, suppressEvents, gsapStructureOf(timeline), renderFps);
} catch (err) {
// The scene's own callback threw. A warning, not a script error: it must not turn a
// timed-out timeline wait into a script failure.
@@ -5157,6 +5203,15 @@ export function initSandboxRuntimeModular(): void {
return false;
}
};
+ const sceneTimelines = () => {
+ const timelines = (window.__timelines ?? {}) as Record;
+ const rootCompositionId =
+ resolveRootCompositionElement()?.getAttribute("data-composition-id") ?? null;
+ return Object.entries(timelines).filter(
+ (entry): entry is [string, RuntimeTimelineLike] =>
+ !!entry[1] && typeof entry[1] === "object" && entry[0] !== rootCompositionId,
+ );
+ };
const seekStandaloneRegisteredTimelines = (
timeSeconds: number,
revision: number,
@@ -5166,12 +5221,7 @@ export function initSandboxRuntimeModular(): void {
sceneClocks = new WeakMap();
sceneClocksRevision = revision;
}
- const timelines = (window.__timelines ?? {}) as Record;
- const rootCompositionId =
- resolveRootCompositionElement()?.getAttribute("data-composition-id") ?? null;
- for (const [compositionId, timeline] of Object.entries(timelines)) {
- if (!timeline || typeof timeline !== "object" || compositionId === rootCompositionId)
- continue;
+ for (const [compositionId, timeline] of sceneTimelines()) {
const scene = sceneClockOf(compositionId, timeline);
if (!scene) continue;
const sourceTime =
@@ -5280,14 +5330,14 @@ export function initSandboxRuntimeModular(): void {
const revision = opts?.revision ?? readCompositionTimingRevision();
if (revision !== tweensRenderedThrough.revision)
tweensRenderedThrough = { revision, time: Number.NEGATIVE_INFINITY };
- styleClipsDueVisibleOnce(t);
+ styleClipsDueVisibleOnce(t, revision);
const firstRenders = t > tweensRenderedThrough.time;
// Only clips holding a tween that renders for the first time on this seek need their authored style read.
const firstRendered =
firstRenders && tl ? clipsFirstRenderedIn(tl, tweensRenderedThrough.time, t) : null;
- // An empty set means no tween draws for the first time: nothing to show, so no page-wide query.
+ // An empty set, or a page with no timeline, means no tween draws for the first time: no page-wide query.
const hideClipsAgain =
- firstRenders && firstRendered?.size !== 0
+ firstRenders && firstRendered?.size !== 0 && (tl || sceneTimelines().length > 0)
? showHiddenClips(firstRendered ? (el) => firstRendered.has(el) : undefined)
: null;
// Scenes first, each paused on its own clock, so the root's pass skips them and its later
@@ -5315,7 +5365,7 @@ export function initSandboxRuntimeModular(): void {
try {
if (typeof tl.totalTime === "function") {
const structure = gsapStructureOf(tl);
- const redrawn = seekGsapTimeline(tl, tlSeekTime, suppressEvents, structure);
+ const redrawn = seekGsapTimeline(tl, tlSeekTime, suppressEvents, structure, renderFps);
if (!redrawn && !suppressEvents && !hasZeroDurationCallbackTween(tl, structure)) {
// The first seek is the only eventful one; the re-render only refreshes styles.
rerenderGsapTimelineAt(
@@ -5380,6 +5430,7 @@ export function initSandboxRuntimeModular(): void {
*/
const canParkTransport = (): boolean =>
!clock.isPlaying() &&
+ bufferingFor.length === 0 &&
!isExportRenderDrivingFrames() &&
// Without MutationObserver nothing can PUSH a DOM change: neither the
// composition-timing watcher nor the gesture watch attaches, and both fall
@@ -5525,15 +5576,20 @@ export function initSandboxRuntimeModular(): void {
requestTransportTick();
};
+ const isPlayableTrack = (el: HTMLMediaElement): boolean =>
+ el.isConnected &&
+ !isSilencedByHidden(el) &&
+ !isUnplayable(el) &&
+ !(el.ended && !el.loop) &&
+ (el.hasAttribute("src") || el.querySelector("source[src]") !== null);
+
const followedOrLongestRunningAudio = (
followed: HTMLMediaElement | null,
): { el: HTMLMediaElement; start: number } | null => {
const audioEls = queryForTransport("audio[data-start]");
let longest: { el: HTMLMediaElement; start: number; runsUntil: number } | null = null;
for (const el of followed ? [followed, ...audioEls] : audioEls) {
- if (!isMediaElement(el) || !el.isConnected) continue;
- if (isSilencedByHidden(el) || isUnplayable(el) || (el.ended && !el.loop)) continue;
- if (!el.hasAttribute("src") && !el.querySelector("source[src]")) continue;
+ if (!isMediaElement(el) || !isPlayableTrack(el)) continue;
const start = resolveAbsoluteMediaStartSeconds(el);
const kept = playedMediaWindow(el, start);
if (!Number.isFinite(start) || !isInClipWindow(state.currentTime, kept.start, kept.end))
@@ -5598,6 +5654,31 @@ export function initSandboxRuntimeModular(): void {
}
}
+ const READY_AHEAD_SECONDS = 1;
+ // WebKit reports a paused element as HAVE_CURRENT_DATA however much it has buffered, so read the ranges too.
+ const hasDataAhead = (el: HTMLMediaElement): boolean => {
+ if (el.readyState >= HTMLMediaElement.HAVE_FUTURE_DATA) return true;
+ if (el.readyState < HTMLMediaElement.HAVE_CURRENT_DATA) return false;
+ const until = Math.min(el.currentTime + READY_AHEAD_SECONDS, el.duration) - 0.01;
+ for (let i = 0; i < el.buffered.length; i++) {
+ if (el.buffered.start(i) <= el.currentTime && el.buffered.end(i) >= until) return true;
+ }
+ return false;
+ };
+
+ const mediaNotReadyAt = (t: number): HTMLMediaElement[] =>
+ state.nativeMediaSyncDisabled
+ ? []
+ : mediaClipsInWindow
+ .filter(
+ ({ el, start, end }) =>
+ isInClipWindow(t, start, end) &&
+ !hasDataAhead(el) &&
+ isPlayableTrack(el) &&
+ !webAudio.ownsElement(el),
+ )
+ .map(({ el }) => el);
+
const transportTick = () => {
if (state.tornDown || inTransportTick) return;
inTransportTick = true;
@@ -5700,6 +5781,7 @@ export function initSandboxRuntimeModular(): void {
waiting: mediaClipsInWindow.some(
({ el }) => el.tagName === "VIDEO" && !el.paused && el.readyState < 3,
),
+ frozen: hasFrozenPicture(mediaClipsInWindow, t),
layoutKey: `${window.innerWidth}x${window.innerHeight}@${window.devicePixelRatio}`,
});
}
@@ -5766,6 +5848,14 @@ export function initSandboxRuntimeModular(): void {
lastSyncedMediaTimeSeconds = null;
syncMediaForCurrentState(timingRevision);
}
+ // After media sync, so a clip that just fell due was asked to play, and fetch, before it holds.
+ const notReady = mediaNotReadyAt(state.currentTime);
+ if (clock.isPlaying() && notReady.length > 0) {
+ bufferingFor = notReady;
+ haltPlayback();
+ } else if (bufferingFor.length > 0 && !notReady.some((el) => bufferingFor.includes(el))) {
+ transport.play();
+ }
postState(false);
} finally {
inTransportTick = false;
diff --git a/packages/core/src/runtime/media.test.ts b/packages/core/src/runtime/media.test.ts
index cc9b9e1463..3525a8d37a 100644
--- a/packages/core/src/runtime/media.test.ts
+++ b/packages/core/src/runtime/media.test.ts
@@ -4,6 +4,7 @@ import { mediaElementTime } from "./mediaClock";
import {
evictMediaSyncState,
hasMediaSyncStateForTest,
+ primeMediaForLaterStarts,
readElementPlaybackRate,
readElementPlaybackStart,
refreshRuntimeMediaCache,
@@ -1822,6 +1823,34 @@ describe("syncRuntimeMedia", () => {
expect(clip.el.muted).toBe(true);
});
+ describe("priming for iOS", () => {
+ const iPhone =
+ "Mozilla/5.0 (iPhone; CPU iPhone OS 26_5 like Mac OS X) AppleWebKit/605.1.15 Mobile/15E148";
+ afterEach(() => vi.restoreAllMocks());
+
+ it("plays then pauses every idle unmuted take so iOS lets it start after the tap", () => {
+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue(iPhone);
+ const idle = createMockClip({ start: 20, end: 30 }).el;
+ const muted = createMockClip({ start: 20, end: 30 }).el;
+ const sounding = createMockClip({ start: 0, end: 10 }).el;
+ const order: string[] = [];
+ idle.play = vi.fn(() => (order.push("play"), Promise.resolve()));
+ idle.pause = vi.fn(() => void order.push("pause"));
+ muted.setAttribute("muted", "");
+ Object.defineProperty(sounding, "paused", { value: false });
+ primeMediaForLaterStarts([idle, muted, sounding]);
+ expect(order).toEqual(["play", "pause"]);
+ expect(muted.play).not.toHaveBeenCalled();
+ expect(sounding.pause).not.toHaveBeenCalled();
+ });
+
+ it("leaves every take parked where no tap is needed", () => {
+ const idle = createMockClip({ start: 20, end: 30 }).el;
+ primeMediaForLaterStarts([idle]);
+ expect(idle.play).not.toHaveBeenCalled();
+ });
+ });
+
it("fires onAutoplayBlocked when play() rejects with NotAllowedError", async () => {
const clip = createMockClip({ start: 0, end: 10 });
Object.defineProperty(clip.el, "readyState", { value: 4, writable: true });
@@ -2041,6 +2070,83 @@ describe("syncRuntimeMedia", () => {
expect(el.play).not.toHaveBeenCalled();
});
+ describe("where the browser reports presented frames", () => {
+ // A playing 24 fps video whose presented frames the test hands to the runtime's frame callback.
+ const reportingVideo = () => {
+ const clip = videoClip({ start: 0, end: 10, mediaStart: 0 });
+ const el = clip.el as HTMLVideoElement;
+ Object.defineProperty(el, "paused", { value: false, writable: true, configurable: true });
+ el.pause = vi.fn(() =>
+ Object.defineProperty(el, "paused", { value: true, writable: true, configurable: true }),
+ );
+ const pending: VideoFrameRequestCallback[] = [];
+ el.requestVideoFrameCallback = vi.fn((callback: VideoFrameRequestCallback) => {
+ pending.push(callback);
+ return pending.length;
+ });
+ const present = (mediaTime: number) => {
+ el.currentTime = mediaTime;
+ const frame = { mediaTime } as VideoFrameCallbackMetadata;
+ pending.splice(0).forEach((callback) => callback(0, frame));
+ };
+ return { clip, el, present };
+ };
+
+ it("plays a video in step with the playhead up to the last frame before its out-point", () => {
+ const { clip, el, present } = reportingVideo();
+ el.currentTime = 9.6;
+ tick(clip, 9.6);
+ present(9.9167);
+ el.currentTime = 9.97; // within one sync tolerance of the out-point, its frame not shown yet
+ tick(clip, 9.965);
+ expect(el.pause).not.toHaveBeenCalled();
+ present(9.9583); // the next frame, at 10, is the out-point's
+ expect(el.pause).toHaveBeenCalledTimes(1);
+ tick(clip, 9.99);
+ expect(el.play).not.toHaveBeenCalled();
+ });
+
+ it("holds a video on its last frame before the out-point when that frame is dropped", () => {
+ const { clip, el, present } = reportingVideo();
+ el.currentTime = 9.6;
+ tick(clip, 9.6);
+ present(9.875);
+ present(9.9167); // the frame at 9.9583 is dropped; the next one would be the out-point's
+ expect(el.pause).not.toHaveBeenCalled();
+ el.currentTime = 9.975;
+ tick(clip, 9.975);
+ expect(el.pause).toHaveBeenCalledTimes(1);
+ });
+
+ it("holds a video with an uneven cadence before a long step crosses the out-point", () => {
+ const { clip, el, present } = reportingVideo();
+ el.currentTime = 9.6;
+ tick(clip, 9.6);
+ present(9.8);
+ present(9.8833);
+ present(9.925); // a step as long as the earlier one would land past 10
+ expect(el.pause).toHaveBeenCalledTimes(1);
+ });
+
+ it("plays a held video again once a seek takes the playhead back", () => {
+ const { clip, el, present } = reportingVideo();
+ el.currentTime = 9.6;
+ tick(clip, 9.6);
+ present(9.9167);
+ present(9.9583);
+ expect(el.pause).toHaveBeenCalledTimes(1);
+ el.play = vi.fn(() => {
+ Object.defineProperty(el, "paused", { value: false, writable: true, configurable: true });
+ return Promise.resolve();
+ });
+ tick(clip, 2);
+ expect(el.currentTime).toBe(mediaElementTime(2));
+ expect(el.play).toHaveBeenCalledTimes(1);
+ tick(clip, 2.016);
+ expect(el.pause).toHaveBeenCalledTimes(1);
+ });
+ });
+
it("keeps a looping video playing when the playhead wraps a lap before it", () => {
const clip = videoClip({ start: 0, end: 10, mediaStart: 0, loop: true, sourceDuration: 0.4 });
const el = clip.el;
@@ -2063,7 +2169,16 @@ describe("syncRuntimeMedia", () => {
playAt: number,
sampleAt: number,
lag: number,
+ playheadRunning = true,
) => {
+ if (playheadRunning)
+ syncRuntimeMedia({
+ clips: [],
+ timeSeconds: playAt,
+ playing: true,
+ playbackRate: 1,
+ getCompositionDuration: () => 30,
+ });
tick(clip, playAt);
expect(clip.el.play).toHaveBeenCalledTimes(1);
Object.defineProperty(clip.el, "paused", {
@@ -2106,6 +2221,16 @@ describe("syncRuntimeMedia", () => {
expect(due75ms.el.play).toHaveBeenCalledTimes(1);
});
+ it("learns half the start delay of a video started by Play", () => {
+ startWithLag(videoClip({ start: 0, end: 10, mediaStart: 0 }), 0, 0.3, 0.074, false);
+ const due45ms = videoClip({ start: 10, end: 20, mediaStart: 0 });
+ tick(due45ms, 9.955);
+ expect(due45ms.el.play).not.toHaveBeenCalled();
+ const due35ms = videoClip({ start: 10, end: 20, mediaStart: 0 });
+ tick(due35ms, 9.965);
+ expect(due35ms.el.play).toHaveBeenCalledTimes(1);
+ });
+
it("learns from a video seeked and started in the same tick", () => {
const seeked = videoClip({ start: 0, end: 10, mediaStart: 0 });
seeked.el.currentTime = 0;
diff --git a/packages/core/src/runtime/media.ts b/packages/core/src/runtime/media.ts
index 101bdf883b..79686f091a 100644
--- a/packages/core/src/runtime/media.ts
+++ b/packages/core/src/runtime/media.ts
@@ -1,6 +1,6 @@
import { swallow } from "./diagnostics";
import { isClipVisibleAt, isInClipWindow } from "./clipWindow";
-import { mediaElementTime } from "./mediaClock";
+import { mediaElementTime, startsSoundOnlyInsideATap } from "./mediaClock";
import { sameInstant } from "../clipFacts";
import { interpolateVolumeGain } from "./mediaVolumeEnvelope.js";
import { elementVolumeLaneGain } from "./audioAutomationVolume.js";
@@ -16,6 +16,7 @@ import { registerSeekCompletion } from "./adapters/seek-dispatch.js";
import { cutToHostSlots, type HostSlot } from "../mediaTiming.js";
import {
forgetSteering,
+ markMediaRestarted,
isSteering,
MEDIA_HARD_SYNC_SECONDS,
MEDIA_SYNC_TOLERANCE_SECONDS,
@@ -203,6 +204,17 @@ function markPlayRequested(el: HTMLMediaElement): void {
el.addEventListener("error", clear, { once: true });
}
+// iOS refuses an unmuted start ~5 s after the tap unless that element played inside a tap: play-then-pause
+// each idle unmuted one from the tap's own call stack. Authored-muted clips start freely and stay deferred.
+export function primeMediaForLaterStarts(els: Iterable): void {
+ if (!startsSoundOnlyInsideATap()) return;
+ for (const el of els) {
+ if (el.defaultMuted || !el.paused || playRequested.has(el) || isUnplayable(el)) continue;
+ el.play().catch(() => {});
+ el.pause();
+ }
+}
+
// HTMLMediaElement.NETWORK_NO_SOURCE — no usable source (404 / unsupported).
const MEDIA_NETWORK_NO_SOURCE = 3;
// An element that errored or has no source can't play; re-issuing play() every
@@ -236,6 +248,7 @@ export function evictMediaSyncState(el: HTMLMediaElement): void {
lastRuntimeAppliedVolume.delete(el);
forgetSteering(el);
heldAhead.delete(el);
+ forgetOutPoint(el);
videoStarts.delete(el);
}
@@ -308,14 +321,74 @@ const MIN_NATIVE_PLAYBACK_RATE = 1 / 16;
const VIDEO_LEAD_HOLD_SECONDS = 0.1;
const heldAhead = new WeakSet();
+// Where a browser reports presented frames, a video nearing its out-point is paused on the last
+// frame before it, so a cut shows every frame up to the out-point and none past it.
+const OUT_POINT_WATCH_SECONDS = 0.5;
+const outPointWatch = new WeakMap();
+const heldAtOutPoint = new WeakMap();
+const lastFrameBefore = new WeakMap();
+const reportsFrames = (el: HTMLMediaElement): el is HTMLVideoElement =>
+ typeof (el as HTMLVideoElement).requestVideoFrameCallback === "function";
+
+function watchOutPoint(el: HTMLVideoElement, outPoint: number): void {
+ if (outPointWatch.get(el) === outPoint) return;
+ outPointWatch.set(el, outPoint);
+ let previous: number | null = null;
+ let shortestStep = Number.POSITIVE_INFINITY;
+ let longestStep = 0;
+ const onFrame = (_now: number, frame: VideoFrameCallbackMetadata) => {
+ if (outPointWatch.get(el) !== outPoint) return;
+ if (el.paused) {
+ outPointWatch.delete(el);
+ return;
+ }
+ // A seek between two frames is not a frame step; a dropped frame or an uneven cadence is a longer one.
+ const gap = previous === null ? Number.NaN : frame.mediaTime - previous;
+ if (gap > 0 && gap < VIDEO_LEAD_HOLD_SECONDS) {
+ shortestStep = Math.min(shortestStep, gap);
+ longestStep = Math.max(longestStep, gap);
+ const framesLeft = Math.floor((outPoint - 0.001 - frame.mediaTime) / shortestStep);
+ lastFrameBefore.set(el, { outPoint, at: frame.mediaTime + framesLeft * shortestStep });
+ }
+ previous = frame.mediaTime;
+ if (frame.mediaTime + (longestStep || MEDIA_SYNC_TOLERANCE_SECONDS) < outPoint - 0.001) {
+ el.requestVideoFrameCallback(onFrame);
+ return;
+ }
+ outPointWatch.delete(el);
+ heldAtOutPoint.set(el, outPoint);
+ heldAhead.add(el);
+ el.pause();
+ };
+ el.requestVideoFrameCallback(onFrame);
+}
+
+function forgetOutPoint(el: HTMLMediaElement): void {
+ outPointWatch.delete(el);
+ heldAtOutPoint.delete(el);
+ lastFrameBefore.delete(el);
+}
+
+/** Where a watched video is held: on the last frame before its out-point once its cadence is known. */
+function outPointHoldTime(el: HTMLMediaElement, outPoint: number, watched: boolean): number {
+ if (!watched) return outPoint - MEDIA_SYNC_TOLERANCE_SECONDS;
+ const last = lastFrameBefore.get(el);
+ return last?.outPoint === outPoint ? last.at : outPoint;
+}
+
// A muted video's clock is its audio track, which starts tens of ms after play(), so an upcoming
// video starts that early, hidden, by the delay learned from earlier starts.
let videoStartLatency: number | null = null;
-const videoStarts = new WeakMap();
+const videoStarts = new WeakMap<
+ HTMLMediaElement,
+ { offset: number; lead: number; at: number; weight: number }
+>();
+let playheadWasRunning = false;
/** Test-only seam. */
export function resetVideoStartLatency(): void {
videoStartLatency = null;
+ playheadWasRunning = false;
}
/** A quarter second in: its lag plus how early it started, capped at 0.1 s. */
@@ -323,7 +396,7 @@ function learnVideoStartLatency(el: HTMLMediaElement, time: number, offset: numb
const start = videoStarts.get(el);
if (!start || time < start.at) return;
videoStarts.delete(el);
- const sample = (offset - start.offset) / rate + start.lead;
+ const sample = ((offset - start.offset) / rate + start.lead) * start.weight;
const averaged = videoStartLatency === null ? sample : (videoStartLatency + sample) / 2;
videoStartLatency = Math.min(0.1, Math.max(0, averaged));
}
@@ -382,6 +455,9 @@ export function syncRuntimeMedia(params: {
getCompositionDuration: () => number;
}): void {
const forceMuteAll = !!(params.outputMuted || params.userMuted);
+ // A start at Play also waits on the playhead's start, so it counts half.
+ const startWeight = playheadWasRunning ? 1 : 0.5;
+ playheadWasRunning = params.playing && params.clockAdvancing !== false;
for (const clip of params.clips) {
const { el } = clip;
if (!el.isConnected) continue;
@@ -585,15 +661,27 @@ export function syncRuntimeMedia(params: {
// strict and force sync and is steered by rate; hard sync (>0.5s) and audio past its steer
// limit seek. A paused transport pauses it below, so a seek that pauses mid-playback lands it.
if (el.tagName === "VIDEO" && !isHeldVideoTail) {
+ const outPoint = mediaSourceTimeAt(clip, clip.end);
+ const watched = reportsFrames(el);
+ if (
+ watched &&
+ playing &&
+ !clip.loop &&
+ !el.paused &&
+ outPoint - currentElTime <= OUT_POINT_WATCH_SECONDS * baseRate
+ )
+ watchOutPoint(el, outPoint);
+ const atOutPoint = heldAtOutPoint.get(el) === outPoint;
// A loop's playhead wraps before its element, so its offset jumps by a lap: steering owns loops.
const ahead =
!clip.loop &&
(offset < -VIDEO_LEAD_HOLD_SECONDS ||
- currentElTime >= mediaSourceTimeAt(clip, clip.end) - MEDIA_SYNC_TOLERANCE_SECONDS);
+ atOutPoint ||
+ currentElTime >= outPointHoldTime(el, outPoint, watched));
if (!playing || (!ahead && offset >= -MEDIA_SYNC_TOLERANCE_SECONDS)) heldAhead.delete(el);
- else if (ahead && !el.paused) {
+ else if (ahead && (!el.paused || atOutPoint)) {
heldAhead.add(el);
- el.pause();
+ if (!el.paused) el.pause();
}
}
const holdingAhead = heldAhead.has(el);
@@ -668,9 +756,11 @@ export function syncRuntimeMedia(params: {
}
}
holdSeekBarrierUntilVideoLands(el);
+ markMediaRestarted(el);
}
playRequested.delete(el);
heldAhead.delete(el);
+ forgetOutPoint(el);
videoStarts.delete(el);
} else if (!playing) {
holdSeekBarrierUntilVideoLands(el);
@@ -697,9 +787,11 @@ export function syncRuntimeMedia(params: {
// fire between `load()` and `addEventListener` attachment, wedging
// the element waiting for a callback that never came.
markPlayRequested(el);
+ markMediaRestarted(el);
// Offset read after any seek above; a loop could wrap a lap before the sample.
if (isNonLoopVideo)
videoStarts.set(el, {
+ weight: startWeight,
offset: relTime - (el.currentTime || 0),
lead: Math.max(0, clip.start - params.timeSeconds) / params.playbackRate,
at: Math.max(params.timeSeconds, clip.start) + 0.25 * params.playbackRate,
diff --git a/packages/core/src/runtime/mediaClock.ts b/packages/core/src/runtime/mediaClock.ts
index e57970e9f6..14ce5766d6 100644
--- a/packages/core/src/runtime/mediaClock.ts
+++ b/packages/core/src/runtime/mediaClock.ts
@@ -3,3 +3,8 @@ export const MEDIA_ELEMENT_LEAD_SECONDS = 1e-5;
export function mediaElementTime(sourceSeconds: number): number {
return sourceSeconds + MEDIA_ELEMENT_LEAD_SECONDS;
}
+
+export function startsSoundOnlyInsideATap(): boolean {
+ const { userAgent, maxTouchPoints } = navigator;
+ return /iP(hone|ad|od)/.test(userAgent) || (/Macintosh/.test(userAgent) && maxTouchPoints > 1);
+}
diff --git a/packages/core/src/runtime/mediaSteer.test.ts b/packages/core/src/runtime/mediaSteer.test.ts
index e5ec4d49d7..4b199cdc9c 100644
--- a/packages/core/src/runtime/mediaSteer.test.ts
+++ b/packages/core/src/runtime/mediaSteer.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { forgetSteering, isSteering, steerMedia } from "./mediaSteer";
+import { forgetSteering, isSteering, markMediaRestarted, steerMedia } from "./mediaSteer";
const media = (tag: "audio" | "video") => document.createElement(tag);
@@ -20,6 +20,13 @@ describe("steerMedia", () => {
expect(isSteering(el)).toBe(false);
});
+ it("steers the lag a start left in audio, but still seeks one past hard sync", () => {
+ const el = media("audio");
+ markMediaRestarted(el);
+ expect(steerMedia(el, 0.3, 1, true).rate).toBeCloseTo(1.1, 9);
+ expect(steerMedia(el, 0.8, 1, true)).toEqual({ rate: 1, seek: true });
+ });
+
it("keeps steering until nearly back, and forgets on request", () => {
const el = media("audio");
steerMedia(el, 0.06, 1, true);
diff --git a/packages/core/src/runtime/mediaSteer.ts b/packages/core/src/runtime/mediaSteer.ts
index c47fa910b3..8533538d49 100644
--- a/packages/core/src/runtime/mediaSteer.ts
+++ b/packages/core/src/runtime/mediaSteer.ts
@@ -15,6 +15,12 @@ const AUDIO_STEER_LIMIT_SECONDS = 0.1;
/** Direction (+1 fast, -1 slow) an element is being steered in; absent when it plays at its authored rate. */
const steering = new WeakMap();
+/** Started or seeked, not yet moving in tolerance: its lag is its own output latency, which a seek only renews. */
+const catchingUp = new WeakSet();
+
+export function markMediaRestarted(el: HTMLMediaElement): void {
+ catchingUp.add(el);
+}
/** Rate or seek for media `offset` s behind (+) or ahead (-); a lag still growing (`settled` false) never seeks. */
export function steerMedia(
@@ -25,8 +31,11 @@ export function steerMedia(
audioOnly = el.tagName === "AUDIO",
): { rate: number; seek: boolean } {
const lag = Math.abs(offset);
- if (audioOnly && settled && lag > AUDIO_STEER_LIMIT_SECONDS) {
+ if (settled && lag <= MEDIA_SYNC_TOLERANCE_SECONDS) catchingUp.delete(el);
+ const seekable = !catchingUp.has(el) || lag > MEDIA_HARD_SYNC_SECONDS;
+ if (audioOnly && settled && lag > AUDIO_STEER_LIMIT_SECONDS && seekable) {
steering.delete(el);
+ catchingUp.add(el);
return { rate: baseRate, seek: true };
}
const direction = Math.sign(offset);
@@ -44,6 +53,7 @@ export function steerMedia(
/** Drop `el`'s steering: it was seeked, paused or replaced, so its old offset says nothing. */
export function forgetSteering(el: HTMLMediaElement): void {
steering.delete(el);
+ catchingUp.delete(el);
}
export function isSteering(el: HTMLMediaElement): boolean {
diff --git a/packages/core/src/runtime/playbackHealth.test.ts b/packages/core/src/runtime/playbackHealth.test.ts
index c00a4063f0..cf00803b44 100644
--- a/packages/core/src/runtime/playbackHealth.test.ts
+++ b/packages/core/src/runtime/playbackHealth.test.ts
@@ -21,6 +21,7 @@ type Health = {
worstFrameMs: number;
skippedShare: number;
waitingShare: number;
+ frozenShare: number;
gapP50Ms: number;
gapP95Ms: number;
} | null;
@@ -107,10 +108,18 @@ describe("playback health", () => {
play(20_000, 6, { waiting: true });
const waiting = healths().at(-1);
expect(waiting?.waitingShare).toBeGreaterThan(0.9);
+ expect(waiting?.frozenShare).toBe(0);
expect(waiting?.skippedShare).toBeLessThan(0.05);
expect(waiting?.gapP95Ms).toBeLessThan(20);
});
+ it("reports a frozen picture as its own share and leaves the choppy rule alone", () => {
+ play(1000, 6, { frozen: true });
+ const frozen = healths().at(-1);
+ expect(frozen?.frozenShare).toBeGreaterThan(0.9);
+ expect(frozen?.choppy).toBe(false);
+ });
+
it("does not count stalls in the first second after play starts", () => {
play(1000, 1, {}, 250);
play(2250, 4);
diff --git a/packages/core/src/runtime/playbackHealth.ts b/packages/core/src/runtime/playbackHealth.ts
index 6c1bcda744..65b943cc85 100644
--- a/packages/core/src/runtime/playbackHealth.ts
+++ b/packages/core/src/runtime/playbackHealth.ts
@@ -18,11 +18,12 @@ export type PlaybackHealthInput = {
hidden: boolean;
/** A playing video is waiting for data. */
waiting: boolean;
+ frozen?: boolean;
/** Anything that changes how heavy a frame is to draw (window size, zoom). */
layoutKey: string;
};
-type Sample = { atMs: number; gapMs: number; drawn: boolean; waiting: boolean };
+type Sample = { atMs: number; gapMs: number; drawn: boolean; waiting: boolean; frozen: boolean };
type Last = { ms: number; film: number; frame: number };
const FORWARD_JUMP_SECONDS = 0.5;
@@ -70,6 +71,7 @@ function measure(nowMs: number, fps: number, rate: number): void {
const due = (spanMs / 1000) * fps * rate;
const skipped = due > 0 ? 1 - Math.min(drawn, due) / due : 0;
const waitingMs = samples.reduce((sum, s) => sum + (s.waiting ? s.gapMs : 0), 0);
+ const frozenMs = samples.reduce((sum, s) => sum + (s.frozen ? s.gapMs : 0), 0);
const droppedShare = Math.max(skipped, waitingMs / spanMs);
const gaps = samples.map((sample) => sample.gapMs).sort((a, b) => a - b);
const gapAt = (share: number) => Math.round(gaps[Math.ceil(share * gaps.length) - 1] ?? 0);
@@ -83,6 +85,7 @@ function measure(nowMs: number, fps: number, rate: number): void {
worstFrameMs: Math.round(Math.max(...samples.map((sample) => sample.gapMs))),
skippedShare: Math.round(skipped * 1000) / 1000,
waitingShare: Math.round((waitingMs / spanMs) * 1000) / 1000,
+ frozenShare: Math.round((frozenMs / spanMs) * 1000) / 1000,
gapP50Ms: gapAt(0.5),
gapP95Ms: gapAt(0.95),
mode: "play",
@@ -117,6 +120,12 @@ export function notePlaybackFrame(input: PlaybackHealthInput): void {
return;
}
if (nowMs < warmEndMs) return;
- samples.push({ atMs: nowMs, gapMs, drawn: frame !== previous.frame, waiting: input.waiting });
+ samples.push({
+ atMs: nowMs,
+ gapMs,
+ drawn: frame !== previous.frame,
+ waiting: input.waiting,
+ frozen: input.frozen === true,
+ });
measure(nowMs, fps, rate);
}
diff --git a/packages/core/src/runtime/preloadMedia.test.ts b/packages/core/src/runtime/preloadMedia.test.ts
index 10bb62f308..32021d9e7e 100644
--- a/packages/core/src/runtime/preloadMedia.test.ts
+++ b/packages/core/src/runtime/preloadMedia.test.ts
@@ -116,6 +116,36 @@ describe("releasing a clip's download", () => {
expect(video.getAttribute("src")).toBe("a.mp4");
});
+ it("keeps a clip whose whole file is buffered", () => {
+ const video = document.createElement("video");
+ video.setAttribute("src", "a.mp4");
+ Object.defineProperty(video, "duration", { value: 6.67 });
+ Object.defineProperty(video, "buffered", {
+ value: { length: 1, start: () => 0, end: () => 6.67 },
+ });
+ video.load = vi.fn();
+
+ releaseMedia(video);
+ expect(video.load).not.toHaveBeenCalled();
+ expect(video.getAttribute("src")).toBe("a.mp4");
+ });
+
+ it.each([
+ [0, 15],
+ [430, 2642],
+ ])("releases a clip with only %s-%s s of a long file buffered", (from, to) => {
+ const video = document.createElement("video");
+ video.setAttribute("src", "a.mp4");
+ Object.defineProperty(video, "duration", { value: 2642 });
+ Object.defineProperty(video, "buffered", {
+ value: { length: 1, start: () => from, end: () => to },
+ });
+ video.load = vi.fn();
+
+ releaseMedia(video);
+ expect(video.load).toHaveBeenCalledTimes(1);
+ });
+
it("leaves a clip on children, their order and its markup untouched", () => {
const video = document.createElement("video");
video.innerHTML =
diff --git a/packages/core/src/runtime/preloadMedia.ts b/packages/core/src/runtime/preloadMedia.ts
index 8129ff3276..3e98d68de0 100644
--- a/packages/core/src/runtime/preloadMedia.ts
+++ b/packages/core/src/runtime/preloadMedia.ts
@@ -5,6 +5,8 @@ import { defersMedia } from "./timedClipHide";
import { swallow } from "./diagnostics";
import { mediaElementTime } from "./mediaClock";
+const MEDIA_EDGE_SECONDS = 0.1;
+
type PreloadableMedia = Pick<
HTMLMediaElement,
"id" | "tagName" | "getAttribute" | "preload" | "readyState" | "networkState" | "load"
@@ -73,8 +75,19 @@ export function stopMediaDownload(media: HTMLMediaElement): void {
media.load();
}
+function wholeFileBuffered(media: HTMLMediaElement): boolean {
+ const { buffered, duration } = media;
+ return (
+ Number.isFinite(duration) &&
+ duration > 0 &&
+ buffered.length === 1 &&
+ buffered.start(0) <= MEDIA_EDGE_SECONDS &&
+ buffered.end(0) >= duration - MEDIA_EDGE_SECONDS
+ );
+}
+
export function releaseMedia(media: HTMLMediaElement): void {
- if (media.querySelector("source")) return;
+ if (media.querySelector("source") || wholeFileBuffered(media)) return;
const src = media.getAttribute("src");
stopMediaDownload(media);
if (src !== null) media.setAttribute("src", src);
diff --git a/packages/core/src/runtime/types.ts b/packages/core/src/runtime/types.ts
index 78d70feb64..9147d3270d 100644
--- a/packages/core/src/runtime/types.ts
+++ b/packages/core/src/runtime/types.ts
@@ -62,6 +62,7 @@ export type RuntimeStateMessage = {
currentTime: number;
ended: boolean;
isPlaying: boolean;
+ buffering: boolean;
muted: boolean;
playbackRate: number;
};
@@ -278,6 +279,7 @@ export type RuntimePreviewHealthMessage = {
worstFrameMs: number;
skippedShare: number;
waitingShare: number;
+ frozenShare: number;
gapP50Ms: number;
gapP95Ms: number;
mode: "play";
diff --git a/packages/core/src/runtime/vfx.ts b/packages/core/src/runtime/vfx.ts
index 6f65a27e0d..e00b97a267 100644
--- a/packages/core/src/runtime/vfx.ts
+++ b/packages/core/src/runtime/vfx.ts
@@ -1412,5 +1412,8 @@ export function paintVfx(t: number, options?: { engineMode?: boolean }): void {
// `__hf_page_composite_resolve` — so a `self` chain painted nothing there, in
// silence. The runtime has to be able to finish its own frame.
if (options?.engineMode) armPageComposite();
- registerSeekCompletion(capturePreviewThenPaint(capturing, t, seq, options?.engineMode === true));
+ registerSeekCompletion(
+ capturePreviewThenPaint(capturing, t, seq, options?.engineMode === true),
+ "vfx",
+ );
}
diff --git a/packages/core/src/runtime/webAudioTransport.test.ts b/packages/core/src/runtime/webAudioTransport.test.ts
index 6df4424416..30db868cae 100644
--- a/packages/core/src/runtime/webAudioTransport.test.ts
+++ b/packages/core/src/runtime/webAudioTransport.test.ts
@@ -1822,6 +1822,25 @@ describe("WebAudioTransport", () => {
vi.unstubAllGlobals();
});
+ it("hands a clip that decodes short to its element, and keeps one short only by its priming", async () => {
+ // Measured in Chromium 156 and WebKit 27.2: a 4 s AAC file whose mdhd timescale says 44.1 kHz over a
+ // 48 kHz stream decodes to 3.669 s; Apple's HE-AAC of the same tone decodes to 4.0 s under a 4.133 s element.
+ const withDuration = (src: string, duration: number) =>
+ Object.assign(el(src), { duration }) as HTMLMediaElement;
+ const transport = transportWithDecode(async () => ({ duration: 3.669 }) as AudioBuffer);
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValue({ ok: true, arrayBuffer: async () => new ArrayBuffer(8) });
+ vi.stubGlobal("fetch", fetchMock);
+ expect(await transport.decodeAudioElement(withDuration("vo.m4a", 4))).toBeNull();
+ expect(failedSrcs(transport).has(key("vo.m4a"))).toBe(true);
+
+ const primed = transportWithDecode(async () => ({ duration: 4 }) as AudioBuffer);
+ expect(await primed.decodeAudioElement(withDuration("he.m4a", 4.133))).not.toBeNull();
+ expect(await primed.decodeAudioElement(withDuration("rec.webm", Infinity))).not.toBeNull();
+ vi.unstubAllGlobals();
+ });
+
it("fetches and decodes a source once when a play and a seek both ask before it decodes", async () => {
const decoded = {} as AudioBuffer;
const transport = transportWithDecode(async () => decoded);
diff --git a/packages/core/src/runtime/webAudioTransport.ts b/packages/core/src/runtime/webAudioTransport.ts
index d123820f13..0c12849c6b 100644
--- a/packages/core/src/runtime/webAudioTransport.ts
+++ b/packages/core/src/runtime/webAudioTransport.ts
@@ -228,6 +228,7 @@ const FOLLOWED_EVENTS = ["playing", "seeked", "ratechange"] as const;
// A pause to scrub or a reschedule mid-play keeps the output awake; a real idle lets it sleep.
const IDLE_SUSPEND_MS = 10000;
+const SHORT_DECODE_SECONDS = 0.25;
export class WebAudioTransport {
private _ctx: AudioContext | null = null;
@@ -394,6 +395,14 @@ export class WebAudioTransport {
// the same bad payload on every generation.
try {
const audioBuffer = await this._ctx.decodeAudioData(arrayBuffer);
+ // A file whose container timescale disagrees with its stream decodes short; its element plays it whole.
+ if (
+ Number.isFinite(el.duration) &&
+ el.duration - audioBuffer.duration > SHORT_DECODE_SECONDS
+ ) {
+ this._failedSrcs.add(src);
+ return null;
+ }
this._bufferCache.set(src, audioBuffer);
return audioBuffer;
} catch (err) {
diff --git a/packages/core/src/runtime/window.d.ts b/packages/core/src/runtime/window.d.ts
index 3b94f4b8e2..46c3dac3fd 100644
--- a/packages/core/src/runtime/window.d.ts
+++ b/packages/core/src/runtime/window.d.ts
@@ -115,6 +115,8 @@ declare global {
owner?: string;
};
__HF_PARITY_MODE?: boolean;
+ /** Set by still-capture pages: seeks replay skipped frames at the composition fps, as a render does. */
+ __HF_REPLAY_SKIPPED_FRAMES?: boolean;
/** Legacy debug-only fps hint. Render-mode runtime fps uses __HF_EXPORT_RENDER_SEEK_CONFIG.fps. */
__HF_FPS?: number;
__HF_MAX_DURATION_SEC?: number;
@@ -139,7 +141,10 @@ declare global {
* Await GPU work registered synchronously by `hf-seek` listeners through
* `event.detail.waitUntil(...)`; `videoFrames: false` skips the video-frame holds.
*/
- __hfWaitForSeekCompletion?: (options?: { videoFrames?: boolean }) => Promise;
+ __hfWaitForSeekCompletion?: (options?: {
+ videoFrames?: boolean;
+ timeoutMs?: number;
+ }) => Promise;
/**
* Canonical root-timeline start for a media element. Snapshot capture uses
* this runtime-owned resolver so reference expressions, authored timing
diff --git a/packages/core/src/telemetryRedaction.test.ts b/packages/core/src/telemetryRedaction.test.ts
index 6a6a9a5daf..5d5552061d 100644
--- a/packages/core/src/telemetryRedaction.test.ts
+++ b/packages/core/src/telemetryRedaction.test.ts
@@ -127,6 +127,42 @@ describe("non-Latin paths", () => {
});
});
+describe("paths with spaces", () => {
+ it.each([
+ "/Users/kim/내 드라이브/영상 프로젝트/clip.mp4",
+ "/Users/ivan/Мои документы/Проект Видео/видео.mp4",
+ "/Users/tanaka/マイ\u3000ドライブ/動画/clip.mp4",
+ "/Users/alex/Library/CloudStorage/GoogleDrive-alex@example.com/My Drive/Claude Projects/edit.mp4",
+ "/Users/alex/Dropbox (Personal)/Client Work/edit.mov",
+ "C:\\Users\\Kim\\OneDrive - Contoso\\Client Videos\\clip.mp4",
+ "\\\\fileserver\\Team Share\\clips\\clip.mp4",
+ ])("redacts every folder of %s", (path) => {
+ expect(redactTelemetryString(`ffprobe failed reading ${path}`)).toBe(
+ "ffprobe failed reading [path]",
+ );
+ });
+
+ it("keeps the words after the path", () => {
+ expect(redactTelemetryString("could not read /Users/kim/My Drive/clip.mp4 was not found")).toBe(
+ "could not read [path] was not found",
+ );
+ });
+
+ it.each([
+ " Duration: N/A, start: 0.000000, bitrate: N/A",
+ "Stream #0:0: Video: h264, 24/1 fps, 30000/1001 tbr",
+ "r_frame_rate=24/1 avg_frame_rate=30000/1001",
+ "input/output error then read/write failed",
+ ])("never joins ordinary ffprobe words into a path: %s", (line) => {
+ expect(redactTelemetryString(line)).toBe(line);
+ });
+
+ it("redacts spaced folders of a path that lost its root", () => {
+ const out = redactTelemetryString("could not open My Drive/Claude Projects/edit.mp4");
+ expect(out).not.toMatch(/Drive|Claude|Projects|edit/);
+ });
+});
+
describe("redactKnownPaths", () => {
// Shape matching has holes by construction. A caller that built the argv
// knows the exact path, so it can name it instead of hoping a regex does.
diff --git a/packages/core/src/telemetryRedaction.ts b/packages/core/src/telemetryRedaction.ts
index 84b12f90b4..fa923534f0 100644
--- a/packages/core/src/telemetryRedaction.ts
+++ b/packages/core/src/telemetryRedaction.ts
@@ -12,12 +12,6 @@ export function redactUrlQueryStrings(value: string): string {
.replace(/((?:X-(?:Amz|Goog)-[\w-]*|Signature)=)[^&\s]*/gi, "$1…");
}
-/**
- * Path characters we treat as part of a single segment. Space is deliberately
- * excluded: including it would let a match run past the path and swallow the
- * prose after it, and a path with a space still gets its remaining segments
- * redacted, which is the part that carries the identifying information.
- */
/**
* A path segment is defined by what ENDS it, not by an alphabet.
*
@@ -34,6 +28,10 @@ export function redactUrlQueryStrings(value: string): string {
*/
const SEGMENT = String.raw`[^\s/\\'"]+`;
+/** A folder that another separator follows may hold spaces (`My Drive`, `내 드라이브`, `OneDrive - Contoso`); only
+ * the last segment stops at a space, so prose after a path survives. Line breaks still end it. */
+const FOLDER = String.raw`${SEGMENT}(?:[^\S\r\n]+(?![A-Za-z]:[\\/])${SEGMENT})*(?=[\\/])`;
+
/** Same, minus the dot, so a trailing `.ext` can be matched separately. */
const SEGMENT_NODOT = String.raw`[^\s/\\'".]+`;
@@ -60,14 +58,15 @@ const TOKEN_TAIL = String.raw`[^\s'")]*`;
* host is kept and only the query is dropped.
*/
const ABSOLUTE_PATH = new RegExp(
- String.raw`(? {
expect(ENCODER_PRESETS.draft.codec).toBe("h264");
});
- it("high uses slow preset with low CRF for better quality", () => {
- expect(ENCODER_PRESETS.high.preset).toBe("slow");
+ it("high uses the fast preset with low CRF for better quality", () => {
+ expect(ENCODER_PRESETS.high.preset).toBe("fast");
expect(ENCODER_PRESETS.high.quality).toBeLessThan(ENCODER_PRESETS.standard.quality);
expect(ENCODER_PRESETS.high.codec).toBe("h264");
});
@@ -1071,7 +1071,7 @@ describe("buildEncoderArgs GPU preset mapping", () => {
expect(presetArg(args)).toBe("p4");
});
- it("translates the high slow preset to NVENC p5", () => {
+ it("translates the slow preset to NVENC p5", () => {
const args = buildEncoderArgs(
{ ...baseOptions, codec: "h264", preset: "slow", quality: 15, useGpu: true },
inputArgs,
diff --git a/packages/engine/src/services/chunkEncoder.ts b/packages/engine/src/services/chunkEncoder.ts
index 77c762aaf7..f3a598a73f 100644
--- a/packages/engine/src/services/chunkEncoder.ts
+++ b/packages/engine/src/services/chunkEncoder.ts
@@ -55,7 +55,7 @@ export type { EncoderOptions, EncodeResult, MuxResult } from "./chunkEncoder.typ
export const ENCODER_PRESETS = {
draft: { preset: "ultrafast", quality: 28, codec: "h264" as const },
standard: { preset: "medium", quality: 18, codec: "h264" as const },
- high: { preset: "slow", quality: 15, codec: "h264" as const },
+ high: { preset: "fast", quality: 15, codec: "h264" as const },
};
export interface EncoderPreset {
diff --git a/packages/engine/src/services/frameCapture-subTimelinePoll.test.ts b/packages/engine/src/services/frameCapture-subTimelinePoll.test.ts
index 343f4acd41..5848a485d0 100644
--- a/packages/engine/src/services/frameCapture-subTimelinePoll.test.ts
+++ b/packages/engine/src/services/frameCapture-subTimelinePoll.test.ts
@@ -174,8 +174,15 @@ describe("pollSubCompositionTimelines when a script failed on a page nothing can
describe("authorScriptsMayRegisterTimelines", () => {
const RUNTIME_ATTR = "data-hyperframes-preview-runtime";
- async function scan(html: string, files: Record = {}): Promise {
+ async function scan(
+ html: string,
+ files: Record = {},
+ registered: string[] = [],
+ ): Promise {
const { document } = parseHTML(html);
+ vi.stubGlobal("window", {
+ __timelines: Object.fromEntries(registered.map((id) => [id, {}])),
+ });
Object.defineProperty(document, "readyState", { value: "complete" });
vi.stubGlobal("document", document);
vi.stubGlobal("location", new URL("http://localhost:3000/index.html"));
@@ -193,7 +200,7 @@ describe("authorScriptsMayRegisterTimelines", () => {
AUTHORED_SOURCE_END,
);
} finally {
- delete (globalThis as { __hfAuthorScan?: boolean }).__hfAuthorScan;
+ delete (globalThis as { __hfAuthorScan?: unknown }).__hfAuthorScan;
vi.unstubAllGlobals();
}
}
@@ -210,7 +217,8 @@ describe("authorScriptsMayRegisterTimelines", () => {
const wrapped = (source: string) =>
``;
expect(await scan(wrapped("draw()"))).toBe(false);
- expect(await scan(wrapped("window.__timelines['a'] = tl"))).toBe(true);
+ const host = `
`;
+ expect(await scan(host + wrapped("window.__timelines['a'] = tl"))).toBe(true);
});
it("ignores the runtime, which mentions __timelines itself", async () => {
@@ -220,9 +228,14 @@ describe("authorScriptsMayRegisterTimelines", () => {
});
it("is true when an inline script or a template script registers one", async () => {
- expect(await scan(``)).toBe(true);
+ const host = (id: string) => `
`;
expect(
- await scan(` `),
+ await scan(`${host("a")}`),
+ ).toBe(true);
+ expect(
+ await scan(
+ `${host("b")} `,
+ ),
).toBe(true);
});
@@ -244,7 +257,7 @@ describe("authorScriptsMayRegisterTimelines", () => {
false,
);
expect(
- await scan(``, {
+ await scan(`
`, {
"/a.js": "window.__timelines.x = 1",
}),
).toBe(true);
@@ -253,4 +266,47 @@ describe("authorScriptsMayRegisterTimelines", () => {
true,
);
});
+
+ it("is false when no script registers an id that is still waited on", async () => {
+ const page = (scripts: string, registered: string[] = []) =>
+ scan(
+ `${scripts}`,
+ {},
+ registered,
+ );
+ const main = ``;
+ expect(await page(main, ["main"])).toBe(false);
+ expect(await page(main)).toBe(true);
+ expect(await page(`${main}`, ["main"])).toBe(
+ true,
+ );
+ });
+
+ it("answers true for a registration key it cannot read, so a late id is still waited on", async () => {
+ const hosts = `
`;
+ expect(
+ await scan(`${hosts}`, {}, []),
+ ).toBe(true);
+ expect(
+ await scan(
+ `${hosts}`,
+ ),
+ ).toBe(true);
+ });
+
+ it("waits on a sub-composition mounted twice, whose hosts carry the authored id", async () => {
+ const html = ``;
+ expect(await scan(html, {}, ["main"])).toBe(true);
+ });
+
+ it("answers true for a template-literal registration key", async () => {
+ const html =
+ '
';
+ expect(await scan(html)).toBe(true);
+ });
+
+ it("does not wait on a host that opted out or is in the skipped list", async () => {
+ const html = `
`;
+ expect(await scan(html)).toBe(false);
+ });
});
diff --git a/packages/engine/src/services/frameCapture.ts b/packages/engine/src/services/frameCapture.ts
index 693565d056..8e91a69069 100644
--- a/packages/engine/src/services/frameCapture.ts
+++ b/packages/engine/src/services/frameCapture.ts
@@ -1309,6 +1309,7 @@ async function cssEffectRiskFrames(
fps,
totalFrames,
totalFrames * MAX_RISK_FRAME_FRACTION,
+ { onProgress: session.options.onEffectScanProgress },
);
return live && withFramesAfterCallback(live, scan.callbackFrom, fps, totalFrames);
} catch (error) {
@@ -2068,15 +2069,18 @@ export interface IsolatedComposition {
elementId: string | null;
}
-// Runs in the page. False once every inline, template and same-origin script is read and none
-// mentions __timelines or imports code; an unreadable or module script, or a page still loading, answers true.
+// Runs in the page. False once every script is read and none can register an id still waited on;
+// an unreadable, module or importing script, a computed key, or a page still loading answers true.
export async function authorScriptsMayRegisterTimelines(
runtimeAttr: string,
authoredBegin: string,
authoredEnd: string,
+ skipIds: readonly string[] = [],
): Promise {
if (document.readyState !== "complete") return true;
- const memo = globalThis as { __hfAuthorScan?: boolean };
+ const memo = globalThis as {
+ __hfAuthorScan?: { opaque: boolean; mentions: boolean; ids: string[] };
+ };
memo.__hfAuthorScan ??= await (async () => {
const scripts = [
...Array.from(document.querySelectorAll("script")),
@@ -2084,34 +2088,62 @@ export async function authorScriptsMayRegisterTimelines(
Array.from(t.content.querySelectorAll("script")),
),
].filter((script) => !script.hasAttribute(runtimeAttr));
+ const scan = { opaque: false, mentions: false, ids: [] as string[] };
// Code that imports another file may register through it, which is not read here.
- const mayRegister = (code: string) =>
- code.includes("__timelines") || /\bimport\s*\(|^\s*import\s*[\w{*"']/m.test(code);
+ const mayImport = (code: string) => /\bimport\s*\(|^\s*import\s*[\w{*"']/m.test(code);
+ const read = (code: string) => {
+ if (mayImport(code)) scan.opaque = true;
+ if (!code.includes("__timelines")) return;
+ scan.mentions = true;
+ const literalKey = /__timelines\s*(?:\[\s*(["'])((?:(?!\1).)+)\1\s*\]|\.([A-Za-z_$][\w$]*))/g;
+ const rest = code
+ .replace(/__timelines\s*=\s*(?:window\.__timelines\s*\|\|\s*)?\{\s*\}/g, "")
+ .replace(literalKey, (_m, _q, bracketId, dotId) => {
+ scan.ids.push(bracketId ?? dotId);
+ return "";
+ });
+ if (rest.includes("__timelines")) scan.opaque = true;
+ };
for (const script of scripts) {
- if (script.type === "module") return true;
+ if (script.type === "module") return { ...scan, opaque: true };
if (!script.src) {
const text = script.textContent ?? "";
- const authored = text.includes(authoredBegin)
- ? text
- .split(authoredBegin)
- .slice(1)
- .map((region) => region.split(authoredEnd)[0])
- .join("\n")
- : text;
- if (mayRegister(authored)) return true;
+ read(
+ text.includes(authoredBegin)
+ ? text
+ .split(authoredBegin)
+ .slice(1)
+ .map((region) => region.split(authoredEnd)[0])
+ .join("\n")
+ : text,
+ );
continue;
}
const url = new URL(script.src, location.href);
- if (url.origin !== location.origin) return true;
+ if (url.origin !== location.origin) return { ...scan, opaque: true };
try {
- if (mayRegister(await (await fetch(url)).text())) return true;
+ read(await (await fetch(url)).text());
} catch {
- return true;
+ return { ...scan, opaque: true };
}
}
- return false;
+ return scan;
})();
- return memo.__hfAuthorScan;
+ const { opaque, mentions, ids } = memo.__hfAuthorScan;
+ if (opaque) return true;
+ if (!mentions) return false;
+ const timelines = (window as { __timelines?: Record }).__timelines ?? {};
+ return Array.from(document.querySelectorAll("[data-composition-id]")).some((host) => {
+ const id = host.getAttribute("data-composition-id");
+ const authoredId = host.getAttribute("data-hf-original-composition-id") ?? id;
+ return (
+ id &&
+ !host.hasAttribute("data-no-timeline") &&
+ !timelines[id] &&
+ !skipIds.includes(id) &&
+ ids.includes(authoredId ?? id)
+ );
+ });
}
export interface SubTimelinePollOptions {
@@ -2181,6 +2213,7 @@ export async function pollSubCompositionTimelines(
RUNTIME_BOOTSTRAP_ATTR,
AUTHORED_SOURCE_BEGIN,
AUTHORED_SOURCE_END,
+ knownUnregisteredIds,
)));
if (ready || shouldStop?.()) break;
const now = Date.now();
diff --git a/packages/engine/src/services/parallelCoordinator.test.ts b/packages/engine/src/services/parallelCoordinator.test.ts
index d6aa0dc331..de9a7e042e 100644
--- a/packages/engine/src/services/parallelCoordinator.test.ts
+++ b/packages/engine/src/services/parallelCoordinator.test.ts
@@ -153,11 +153,11 @@ describe("computeWorkerSizing", () => {
);
vi.mocked(totalmem).mockReturnValue(24 * 1024 ** 3);
vi.mocked(getHeapStatistics).mockReturnValue({
- heap_size_limit: 4192 * 1024 ** 2,
+ heap_size_limit: 2096 * 1024 ** 2,
} as ReturnType);
const sizing = computeWorkerSizing(1300, undefined, { concurrency: "auto" });
- expect(sizing.heapBasedWorkers).toBe(4);
- expect(sizing.workers).toBe(4);
+ expect(sizing.heapBasedWorkers).toBe(3);
+ expect(sizing.workers).toBe(3);
expect(sizing.boundBy).toBe("heap");
expect(sizing.exceedsHeapAdvisory).toBe(false);
expect(computeWorkerSizing(1300, 6, { concurrency: "auto" }).workers).toBe(6);
@@ -167,6 +167,35 @@ describe("computeWorkerSizing", () => {
expect(computeWorkerSizing(1300, undefined, { concurrency: "auto" }).workers).toBe(5);
});
+ it("keeps the desktop app's 4,192 MB heap at the old per-worker figure (#5149)", () => {
+ vi.mocked(cpus).mockReturnValue(
+ Array.from({ length: 14 }, () => ({}) as ReturnType[number]),
+ );
+ vi.mocked(totalmem).mockReturnValue(24 * 1024 ** 3);
+ vi.mocked(getHeapStatistics).mockReturnValue({
+ heap_size_limit: 4192 * 1024 ** 2,
+ } as ReturnType);
+ expect(computeWorkerSizing(1300, undefined, { concurrency: "auto" }).heapBasedWorkers).toBe(9);
+ Object.defineProperty(process.versions, "electron", { value: "44.2.0", configurable: true });
+ try {
+ const sizing = computeWorkerSizing(1300, undefined, { concurrency: "auto" });
+ expect(sizing.heapBasedWorkers).toBe(4);
+ expect(sizing.workers).toBe(4);
+ expect(sizing.boundBy).toBe("heap");
+ } finally {
+ delete (process.versions as Record).electron;
+ }
+ // A packaged app runs the CLI on its own plain Node, tagged as the desktop client.
+ vi.stubEnv("HYPERFRAMES_CLIENT", "desktop/1.4.0/stable");
+ try {
+ expect(computeWorkerSizing(1300, undefined, { concurrency: "auto" }).heapBasedWorkers).toBe(
+ 4,
+ );
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ });
+
it("sizes Apple-GPU disk capture by its own heap and core budget", () => {
vi.mocked(cpus).mockReturnValue(
Array.from({ length: 14 }, () => ({}) as ReturnType[number]),
diff --git a/packages/engine/src/services/parallelCoordinator.ts b/packages/engine/src/services/parallelCoordinator.ts
index 98d8afee77..e91ecde05f 100644
--- a/packages/engine/src/services/parallelCoordinator.ts
+++ b/packages/engine/src/services/parallelCoordinator.ts
@@ -31,7 +31,7 @@ import { DEFAULT_CONFIG, type EngineConfig } from "../config.js";
import { assertSwiftShader } from "../utils/assertSwiftShader.js";
import { readWebGlVendorInfoFromCanvas } from "../utils/readWebGlVendorInfoFromCanvas.js";
import { resolveHeadlessShellPath } from "./browserManager.js";
-import { getSystemTotalMb } from "./systemMemory.js";
+import { getCgroupCpuLimit, getSystemTotalMb } from "./systemMemory.js";
import {
CaptureFailure,
classifyCaptureFailure,
@@ -148,11 +148,14 @@ const MEMORY_PER_WORKER_MB = 1536;
// Parent-process V8 heap the coordinator itself needs regardless of worker
// count (compile artifacts, puppeteer sessions, encoder state).
const HEAP_RESERVED_MB = 1024;
-// Parent-process V8 heap consumed per worker (protocol buffers + in-flight
-// frame buffers). Derived from the field OOM: 6 workers exhausted a ~4GB
-// default heap ⇒ >~500MB/worker + base. Caps auto sizing; an explicit
-// `--workers N` is still the operator's call.
-const HEAP_PER_WORKER_MB = 640;
+// Parent heap per worker, by --trace-gc in a 10 GB container (10-28): 21 MB on a short film, 228 MB on a 1080×1920
+// video-heavy one (427 → 1,110 MB from 1 to 4 workers). 320 keeps 1.4× over that; `--workers N` still overrides.
+const HEAP_PER_WORKER_MB = 320;
+// The desktop app keeps the old figure: its 4,192 MB heap is where 5 workers ran out (#5149). A packaged app runs the
+// CLI on its own plain Node, so it is known by the client tag it sets on every CLI call, or by Electron itself.
+const DESKTOP_HEAP_PER_WORKER_MB = 640;
+const inDesktopApp = () =>
+ Boolean(process.versions.electron) || /^desktop\//.test(process.env.HYPERFRAMES_CLIENT ?? "");
// Apple-GPU disk capture measured ~15-25 MB parent heap per worker; 14 cores kept gaining to 8.
const APPLE_DISK_HEAP_PER_WORKER_MB = 128;
const APPLE_DISK_CORES_PER_WORKER = 1.75;
@@ -332,10 +335,19 @@ export function computeWorkerSizing(
1,
Math.floor(
(heapLimitMb - HEAP_RESERVED_MB) /
- (appleDisk ? APPLE_DISK_HEAP_PER_WORKER_MB : HEAP_PER_WORKER_MB),
+ (appleDisk
+ ? APPLE_DISK_HEAP_PER_WORKER_MB
+ : inDesktopApp()
+ ? DESKTOP_HEAP_PER_WORKER_MB
+ : HEAP_PER_WORKER_MB),
),
);
- const cpuBasedWorkers = Math.max(1, cpuCount - 2);
+ // A CPU quota (docker --cpus) bounds workers at its whole CPUs: at 3.5, 3 beat 2 and 4 (johnny, 10-28).
+ const cpuQuota = getCgroupCpuLimit();
+ const cpuBasedWorkers = Math.max(
+ 1,
+ cpuQuota === null ? cpuCount - 2 : Math.min(cpuCount - 2, Math.floor(cpuQuota)),
+ );
const memoryBasedWorkers = Math.max(1, Math.floor((totalMemoryMb * 0.5) / MEMORY_PER_WORKER_MB));
const frameBasedWorkers = Math.floor(totalFrames / MIN_FRAMES_PER_WORKER);
const captureCostMultiplier = Math.max(1, config?.captureCostMultiplier ?? 1);
diff --git a/packages/engine/src/services/riskFrames.test.ts b/packages/engine/src/services/riskFrames.test.ts
index d9856aef1c..5536098528 100644
--- a/packages/engine/src/services/riskFrames.test.ts
+++ b/packages/engine/src/services/riskFrames.test.ts
@@ -102,6 +102,52 @@ const frames = (live: Set | null) => [...(live ?? [])].sort((a, b) => a
const range = (from: number, count: number) => Array.from({ length: count }, (_, i) => from + i);
describe("scanCssEffectLiveFrames", () => {
+ it("stops after one chunk when the whole scan would hold back the first frame too long", async () => {
+ const seeks: number[] = [];
+ const page = makePage(between(0, 0));
+ const evaluate = page.evaluate.bind(page);
+ page.evaluate = (async (...args: Parameters) => {
+ seeks.push((args[1] as number[]).length);
+ return evaluate(...args);
+ }) as Page["evaluate"];
+ let clock = 0;
+ // 24 ms a frame, what a heavy page costs: 40,219 frames would take 16 minutes.
+ const now = () => (clock += 240 * 24);
+
+ expect(
+ await scanCssEffectLiveFrames(page, 60, 40_219, 40_219, { budgetMs: 60_000, now }),
+ ).toBeNull();
+ expect(seeks).toEqual([240]);
+ });
+
+ it("reports the frames scanned after each chunk", async () => {
+ const seen: Array<[number, number]> = [];
+
+ await scanCssEffectLiveFrames(makePage(between(0, 0)), 10, 500, 500, {
+ onProgress: (scanned, total) => seen.push([scanned, total]),
+ });
+ expect(seen).toEqual([
+ [240, 500],
+ [480, 500],
+ [500, 500],
+ ]);
+ });
+
+ it("scans to the end when the whole scan fits the budget", async () => {
+ let clock = 0;
+ const now = () => (clock += 240);
+
+ const live = await scanCssEffectLiveFrames(
+ makePage(between(2, 4)),
+ 10,
+ 1000,
+ 1000,
+ 60_000,
+ now,
+ );
+ expect(frames(live)).toEqual(range(20, 20));
+ });
+
it("returns the frames where the effect element shows", async () => {
const live = await scanCssEffectLiveFrames(makePage(between(2, 4)), 10, 100, 100);
expect(frames(live)).toEqual(range(20, 20));
diff --git a/packages/engine/src/services/riskFrames.ts b/packages/engine/src/services/riskFrames.ts
index 87d127753f..90e089b311 100644
--- a/packages/engine/src/services/riskFrames.ts
+++ b/packages/engine/src/services/riskFrames.ts
@@ -9,6 +9,9 @@ import { quantizeTimeToFrame } from "@hyperframes/core";
/** Frames per page round trip while scanning; a scan is one in-page loop per chunk. */
const SCAN_CHUNK_FRAMES = 240;
+/** Longest the scan may hold back the first frame; above it the whole render captures by screenshot. */
+const SCAN_BUDGET_MS = 120_000;
+
/**
* Above this share of risk frames the second browser and the switching cost outweigh the fast
* frames, so the whole render captures by screenshot as it always has.
@@ -26,53 +29,71 @@ const PIXELS_1080P = 1920 * 1080;
/** Risk ranges closer than this many frames are joined, so capture never alternates modes. */
export const RISK_RANGE_HYSTERESIS_FRAMES = 12;
+async function scanChunk(page: Page, times: number[]): Promise {
+ return page.evaluate(async (ts: number[]): Promise => {
+ type HfWindow = Window & {
+ __hf?: { seek?: (t: number) => void };
+ __hfWaitForSeekCompletion?: () => Promise;
+ __hfCssFxTargets?: Element[];
+ };
+ const w = window as HfWindow;
+ const targets = w.__hfCssFxTargets ?? [];
+ // A hidden element still shows a descendant that sets `visibility: visible` itself.
+ const paints = (el: Element): boolean =>
+ getComputedStyle(el).visibility !== "hidden" ||
+ Array.from(el.querySelectorAll("*")).some(
+ (d) => getComputedStyle(d).visibility === "visible",
+ );
+ const shows = (el: Element): boolean => {
+ for (let n: Element | null = el; n; n = n.parentElement) {
+ const cs = getComputedStyle(n);
+ if (cs.display === "none" || Number(cs.opacity) === 0) return false;
+ }
+ return paints(el);
+ };
+ const out: number[] = [];
+ for (let i = 0; i < ts.length; i++) {
+ w.__hf?.seek?.(ts[i] as number);
+ await w.__hfWaitForSeekCompletion?.();
+ if (targets.some(shows)) out.push(i);
+ }
+ return out;
+ }, times);
+}
+
+interface ScanOptions {
+ budgetMs?: number;
+ now?: () => number;
+ onProgress?: (scannedFrames: number, totalFrames: number) => void;
+}
+
/**
* Frames where a recorded effect element shows. Seeks the page forward, so use a throwaway one.
- * Null once more than `maxFrames` frames qualify.
+ * Null once more than `maxFrames` frames qualify, or once the whole scan would take over `budgetMs`.
*/
export async function scanCssEffectLiveFrames(
page: Page,
fps: number,
totalFrames: number,
maxFrames: number,
+ { budgetMs = SCAN_BUDGET_MS, now = () => performance.now(), onProgress }: ScanOptions = {},
): Promise | null> {
const live = new Set();
- for (let from = 0; from < totalFrames; from += SCAN_CHUNK_FRAMES) {
+ const started = now();
+ for (let from = 0; from < totalFrames && live.size <= maxFrames; from += SCAN_CHUNK_FRAMES) {
+ const to = Math.min(totalFrames, from + SCAN_CHUNK_FRAMES);
const times: number[] = [];
- for (let f = from; f < Math.min(totalFrames, from + SCAN_CHUNK_FRAMES); f++) {
- times.push(quantizeTimeToFrame(f / fps, fps));
+ for (let f = from; f < to; f++) times.push(quantizeTimeToFrame(f / fps, fps));
+ for (const i of await scanChunk(page, times)) live.add(from + i);
+ onProgress?.(to, totalFrames);
+ const projectedMs = ((now() - started) / to) * totalFrames;
+ if (to < totalFrames && projectedMs > budgetMs) {
+ console.error(
+ `[engine] fast capture: the effect scan of ${totalFrames} frames would take ` +
+ `${Math.round(projectedMs / 1000)} s, over its ${budgetMs / 1000} s budget`,
+ );
+ return null;
}
- const hits = await page.evaluate(async (ts: number[]): Promise => {
- type HfWindow = Window & {
- __hf?: { seek?: (t: number) => void };
- __hfWaitForSeekCompletion?: () => Promise;
- __hfCssFxTargets?: Element[];
- };
- const w = window as HfWindow;
- const targets = w.__hfCssFxTargets ?? [];
- // A hidden element still shows a descendant that sets `visibility: visible` itself.
- const paints = (el: Element): boolean =>
- getComputedStyle(el).visibility !== "hidden" ||
- Array.from(el.querySelectorAll("*")).some(
- (d) => getComputedStyle(d).visibility === "visible",
- );
- const shows = (el: Element): boolean => {
- for (let n: Element | null = el; n; n = n.parentElement) {
- const cs = getComputedStyle(n);
- if (cs.display === "none" || Number(cs.opacity) === 0) return false;
- }
- return paints(el);
- };
- const out: number[] = [];
- for (let i = 0; i < ts.length; i++) {
- w.__hf?.seek?.(ts[i] as number);
- await w.__hfWaitForSeekCompletion?.();
- if (targets.some(shows)) out.push(i);
- }
- return out;
- }, times);
- for (const i of hits) live.add(from + i);
- if (live.size > maxFrames) break;
}
return live.size > maxFrames ? null : live;
}
diff --git a/packages/engine/src/services/streamingEncoder.test.ts b/packages/engine/src/services/streamingEncoder.test.ts
index 0616ca47f8..328e801a7e 100644
--- a/packages/engine/src/services/streamingEncoder.test.ts
+++ b/packages/engine/src/services/streamingEncoder.test.ts
@@ -981,6 +981,33 @@ describe("spawnStreamingEncoder lifecycle and cleanup", () => {
await encoder.close();
});
+ it("reports how long writeFrame waited for FFmpeg to drain", async () => {
+ vi.useFakeTimers({ toFake: ["Date"] });
+ try {
+ const { spawn, calls } = createSpawnSpy();
+ vi.resetModules();
+ vi.doMock("child_process", () => ({ spawn }));
+
+ const { spawnStreamingEncoder } = await import("./streamingEncoder.js");
+ const dir = mkdtempSync(join(tmpdir(), "se-drain-wait-"));
+ const encoder = await spawnStreamingEncoder(join(dir, "out.mp4"), baseOptions);
+ const proc = calls[0]!.proc;
+
+ expect(await encoder.writeFrame(validJpeg)).toBe(true);
+ proc.stdin.write = (_chunk: Buffer): boolean => false;
+ const writePromise = encoder.writeFrame(validJpeg);
+ await Promise.resolve();
+ vi.setSystemTime(Date.now() + 40);
+ proc.stdin.emit("drain");
+ expect(await writePromise).toBe(true);
+
+ process.nextTick(() => proc.emit("close", 0));
+ expect((await encoder.close()).drainWaitMs).toBe(40);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it("does not accumulate process close listeners across repeated back-pressured writes", async () => {
const { spawn, calls } = createSpawnSpy();
vi.resetModules();
diff --git a/packages/engine/src/services/streamingEncoder.ts b/packages/engine/src/services/streamingEncoder.ts
index 51559326ab..b822896b06 100644
--- a/packages/engine/src/services/streamingEncoder.ts
+++ b/packages/engine/src/services/streamingEncoder.ts
@@ -191,6 +191,8 @@ export interface StreamingEncoderResult {
error?: string;
/** Stable machine-readable cause for failures safe to retry on a fresh host. */
failureReason?: "external_interruption";
+ /** Total time `writeFrame` waited for FFmpeg to drain its stdin pipe. */
+ drainWaitMs?: number;
}
export interface StreamingEncoder {
@@ -585,6 +587,7 @@ export async function spawnStreamingEncoder(
};
let inputFrameIndex = 0;
+ let drainWaitMs = 0;
const encoder: StreamingEncoder = {
writeFrame: async (buffer: Buffer): Promise => {
const stdin = ffmpeg.stdin;
@@ -626,7 +629,9 @@ export async function spawnStreamingEncoder(
return true;
}
+ const drainStart = Date.now();
const drainResult = await waitForDrainOrExit(stdin);
+ drainWaitMs += Date.now() - drainStart;
if (drainResult !== "drain" || exitStatus !== "running") {
return false;
}
@@ -692,7 +697,7 @@ export async function spawnStreamingEncoder(
const fileSize = existsSync(outputPath) ? statSync(outputPath).size : 0;
- return { success: true, durationMs, fileSize };
+ return { success: true, durationMs, fileSize, drainWaitMs };
},
getExitStatus: () => exitStatus,
diff --git a/packages/engine/src/services/systemMemory.test.ts b/packages/engine/src/services/systemMemory.test.ts
index f8c91528f4..f9cc8c5686 100644
--- a/packages/engine/src/services/systemMemory.test.ts
+++ b/packages/engine/src/services/systemMemory.test.ts
@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";
import {
_resetCgroupLimitCacheForTests,
isLowMemorySystem,
+ parseCgroupCpus,
LOW_MEMORY_TOTAL_MB_THRESHOLD,
parseCgroupLimitMb,
} from "./systemMemory.js";
@@ -155,6 +156,40 @@ describe("parseCgroupLimitMb", () => {
});
});
+describe("parseCgroupCpus", () => {
+ it("reads a v2 cpu.max quota as CPUs", () => {
+ expect(parseCgroupCpus("350000 100000\n", null, null)).toBe(3.5);
+ expect(parseCgroupCpus("max 100000", null, null)).toBeNull();
+ });
+
+ it("reads a v1 quota over its period, and -1 as no quota", () => {
+ expect(parseCgroupCpus(null, "400000\n", "100000\n")).toBe(4);
+ expect(parseCgroupCpus(null, "-1", "100000")).toBeNull();
+ });
+
+ it("ignores absent and malformed quotas", () => {
+ expect(parseCgroupCpus(null, null, null)).toBeNull();
+ for (const content of ["", "garbage", "0 100000", "100000 0"])
+ expect(parseCgroupCpus(content, null, null)).toBeNull();
+ });
+});
+
+describe("getCgroupCpuLimit", () => {
+ it("reads the quota from cpu.max, and none from a host without one", async () => {
+ await withSystemMemoryMocks(
+ { files: { "/sys/fs/cgroup/cpu.max": "350000 100000" } },
+ ({ getCgroupCpuLimit }) => expect(getCgroupCpuLimit()).toBe(3.5),
+ );
+ await withSystemMemoryMocks(
+ { files: { "/sys/fs/cgroup/cpu.max": "max 100000" } },
+ ({ getCgroupCpuLimit }) => expect(getCgroupCpuLimit()).toBeNull(),
+ );
+ await withSystemMemoryMocks({ platform: "darwin" }, ({ getCgroupCpuLimit }) =>
+ expect(getCgroupCpuLimit()).toBeNull(),
+ );
+ });
+});
+
describe("getCgroupMemoryLimitMb", () => {
it("returns only an actual cgroup limit and never host RAM", async () => {
await withSystemMemoryMocks(
diff --git a/packages/engine/src/services/systemMemory.ts b/packages/engine/src/services/systemMemory.ts
index f9f5c7139a..b30e00bc16 100644
--- a/packages/engine/src/services/systemMemory.ts
+++ b/packages/engine/src/services/systemMemory.ts
@@ -26,7 +26,12 @@ const CGROUP_V1_MEMORY_LIMIT_PATH = "/sys/fs/cgroup/memory/memory.limit_in_bytes
// Kernel no-limit sentinel is page-rounded 2^63-1 (~9223372036854771712); >= 2^60 is implausible as a real limit.
const CGROUP_V1_NO_LIMIT_CUTOFF_BYTES = 2n ** 60n;
+const CGROUP_V2_CPU_MAX_PATH = "/sys/fs/cgroup/cpu.max";
+const CGROUP_V1_CPU_QUOTA_PATH = "/sys/fs/cgroup/cpu/cpu.cfs_quota_us";
+const CGROUP_V1_CPU_PERIOD_PATH = "/sys/fs/cgroup/cpu/cpu.cfs_period_us";
+
let _cachedCgroupLimitMb: number | null | undefined;
+let _cachedCgroupCpus: number | null | undefined;
let _warnedCgroupReadFailure = false;
/** Parse cgroup v2/v1 memory limits from sysfs file contents into MiB. */
@@ -75,12 +80,48 @@ function parsePositiveByteLimitMb(content: string, noLimitCutoffBytes?: bigint):
return Number(bytes / BYTES_PER_MIB_BIGINT);
}
+/** The CPUs a cgroup quota allows (v2 `cpu.max`, else v1 quota over period), or null when it sets none. */
+export function parseCgroupCpus(
+ v2Content: string | null,
+ v1Quota: string | null,
+ v1Period: string | null,
+): number | null {
+ if (v2Content !== null) {
+ const [quota, period] = v2Content.trim().split(/\s+/);
+ return quotaCpus(quota, period);
+ }
+ return quotaCpus(v1Quota?.trim(), v1Period?.trim());
+}
+
+function quotaCpus(quota: string | undefined, period: string | undefined): number | null {
+ if (!quota || !period || !/^\d+$/.test(quota) || !/^\d+$/.test(period)) return null;
+ const [q, p] = [Number(quota), Number(period)];
+ return q > 0 && p > 0 ? q / p : null;
+}
+
/** Test-only: reset the cached cgroup memory probe. */
export function _resetCgroupLimitCacheForTests(): void {
_cachedCgroupLimitMb = undefined;
+ _cachedCgroupCpus = undefined;
_warnedCgroupReadFailure = false;
}
+/** The CPUs this process's cgroup may use (docker `--cpus`), or null off Linux or without a quota. */
+export function getCgroupCpuLimit(): number | null {
+ if (_cachedCgroupCpus !== undefined) return _cachedCgroupCpus;
+ if (process.platform !== "linux") return (_cachedCgroupCpus = null);
+ const v2 = readCgroupFile(CGROUP_V2_CPU_MAX_PATH);
+ _cachedCgroupCpus =
+ v2 !== null
+ ? parseCgroupCpus(v2, null, null)
+ : parseCgroupCpus(
+ null,
+ readCgroupFile(CGROUP_V1_CPU_QUOTA_PATH),
+ readCgroupFile(CGROUP_V1_CPU_PERIOD_PATH),
+ );
+ return _cachedCgroupCpus;
+}
+
/**
* Actual Linux cgroup memory ceiling in MiB, or null when the process is not
* cgroup-limited. Unlike getSystemTotalMb this never falls back to host RAM.
diff --git a/packages/engine/src/services/videoFrameExtractor.progress.test.ts b/packages/engine/src/services/videoFrameExtractor.progress.test.ts
new file mode 100644
index 0000000000..0f2fd74a90
--- /dev/null
+++ b/packages/engine/src/services/videoFrameExtractor.progress.test.ts
@@ -0,0 +1,63 @@
+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import { FFMPEG_PATH_ENV, getFfmpegBinary } from "../utils/ffmpegBinaries.js";
+import { runFfmpeg } from "../utils/runFfmpeg.js";
+import { extractVideoFramesRange } from "./videoFrameExtractor.js";
+
+describe.skipIf(process.platform === "win32")("extraction progress", () => {
+ const dir = mkdtempSync(join(tmpdir(), "hf-extract-progress-"));
+ const previousFfmpeg = process.env[FFMPEG_PATH_ENV];
+ const shim = join(dir, "ffmpeg-shim.sh");
+
+ beforeAll(() => {
+ writeFileSync(
+ shim,
+ [
+ "#!/bin/sh",
+ `case " $* " in *" -i "*) ;; *) exec "${getFfmpegBinary()}" "$@" ;; esac`,
+ "printf 'frame= 2 fps=1.0 time=00:00:02.00\\r' >&2",
+ 'until [ -f "$HF_TEST_SHIM_DIR/release" ]; do sleep 0.05; done',
+ `exec "${getFfmpegBinary()}" "$@"`,
+ ].join("\n"),
+ );
+ chmodSync(shim, 0o755);
+ });
+
+ afterAll(() => rmSync(dir, { recursive: true, force: true }));
+
+ it("reports frames while ffmpeg is still running", async () => {
+ const clip = join(dir, "clip.mp4");
+ const made = await runFfmpeg([
+ ...["-y", "-v", "error", "-f", "lavfi", "-i", "testsrc=s=32x32:d=4:r=1"],
+ ...["-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", clip],
+ ]);
+ expect(made.success, made.stderr).toBe(true);
+ const run = join(dir, "run");
+ mkdirSync(run, { recursive: true });
+ process.env.HF_TEST_SHIM_DIR = run;
+ process.env[FFMPEG_PATH_ENV] = shim;
+ let planned = 0;
+ let done = 0;
+ try {
+ const extraction = extractVideoFramesRange(clip, "clip", 0, 4, {
+ fps: 1,
+ outputDir: run,
+ onProgress: (p) => {
+ planned += p.planned ?? 0;
+ done += p.done ?? 0;
+ },
+ });
+ await vi.waitFor(() => expect(done).toBe(2), { timeout: 10_000 });
+ expect(planned).toBe(4);
+ writeFileSync(join(run, "release"), "");
+ await extraction;
+ } finally {
+ writeFileSync(join(run, "release"), "");
+ if (previousFfmpeg === undefined) delete process.env[FFMPEG_PATH_ENV];
+ else process.env[FFMPEG_PATH_ENV] = previousFfmpeg;
+ delete process.env.HF_TEST_SHIM_DIR;
+ }
+ }, 60_000);
+});
diff --git a/packages/engine/src/services/videoFrameExtractor.test.ts b/packages/engine/src/services/videoFrameExtractor.test.ts
index dd1e359769..dc23e387b6 100644
--- a/packages/engine/src/services/videoFrameExtractor.test.ts
+++ b/packages/engine/src/services/videoFrameExtractor.test.ts
@@ -16,6 +16,7 @@ import { tmpdir } from "node:os";
import { spawnSync } from "node:child_process";
import {
parseVideoElements,
+ hasGradedCanvas,
parseImageElements,
extractAllVideoFrames,
extractVideoFramesRange,
@@ -23,6 +24,7 @@ import {
createFrameLookupTable,
FrameLookupTable,
rebaseVideoToWindow,
+ alignClipStartToFirstOutputFrame,
resolveFrameFormat,
codecMayHaveAlpha,
decoderForCodec,
@@ -192,6 +194,14 @@ describe("resolveVideoExtractionDuration", () => {
expect(seconds).toBeCloseTo(4.6586, 3);
});
+ it("leaves media start untouched for a nested clip whose start sums to a frame boundary with float dust", () => {
+ // 3.3 + 1.3666666666666667 = 4.666666666666666, frame 140 at 30 fps
+ const clip = video({ start: 3.3 + 1.3666666666666667, end: 8, mediaStart: 1.35 });
+ alignClipStartToFirstOutputFrame(clip, 30);
+ expect(clip.mediaStart).toBe(1.35);
+ expect(clip.start).toBe(140 / 30);
+ });
+
it("snaps a float-noise composition start to the timeline origin so the first frame is kept", () => {
const clip = video({ start: -1, end: 8, playbackRate: 0.7 });
rebaseVideoToWindow(clip, { compositionStart: 2.2e-16, mediaStart: 0.7, durationSeconds: 5 });
@@ -738,6 +748,25 @@ describe("resolveFrameFormat", () => {
});
describe("parseVideoElements", () => {
+ it("marks a graded video and image, and only those", () => {
+ const html = `
+
+
+ `;
+ expect(parseVideoElements(html).map(({ id, graded }) => [id, graded])).toEqual([
+ ["g", true],
+ ["p", undefined],
+ ]);
+ expect(parseImageElements(html).map(({ id, graded }) => [id, graded])).toEqual([
+ ["gi", true],
+ ["pi", undefined],
+ ]);
+ expect(hasGradedCanvas(html)).toBe(false);
+ expect(
+ hasGradedCanvas(` `),
+ ).toBe(true);
+ });
+
it.each([
{
label: "valueless playback-start",
@@ -4417,3 +4446,212 @@ describe("parseVideoElements hidden flag", () => {
]);
});
});
+
+describe.skipIf(!HAS_FFMPEG)("a clip stored on a non-square pixel grid", () => {
+ const FIXTURE_DIR = mkdtempSync(join(tmpdir(), "hf-sar-"));
+ const SOURCE = join(FIXTURE_DIR, "anamorphic.mp4");
+
+ beforeAll(async () => {
+ const result = await runFfmpeg([
+ "-y",
+ "-v",
+ "error",
+ "-f",
+ "lavfi",
+ "-i",
+ "color=c=red:s=64x64:d=1:r=10",
+ "-vf",
+ "setsar=1/2",
+ "-c:v",
+ "libx264",
+ "-pix_fmt",
+ "yuv420p",
+ SOURCE,
+ ]);
+ if (!result.success) throw new Error(`fixture synthesis failed: ${result.stderr.slice(-400)}`);
+ }, 30_000);
+
+ afterAll(() => rmSync(FIXTURE_DIR, { recursive: true, force: true }), 30_000);
+
+ it("keeps the display shape of a rotated clip, whose autorotate swaps the pixel aspect", async () => {
+ const rotated = join(FIXTURE_DIR, "rotated.mp4");
+ // `-display_rotation` is an ffmpeg 6 input option; older builds take the same rotation as metadata.
+ const rotateWith = (args: string[]) =>
+ runFfmpeg(["-y", "-v", "error", ...args, "-c", "copy", rotated]);
+ let synth = await rotateWith(["-display_rotation:v:0", "90", "-i", SOURCE]);
+ if (!synth.success) synth = await rotateWith(["-i", SOURCE, "-metadata:s:v:0", "rotate=90"]);
+ expect(synth.success).toBe(true);
+ const outDir = join(FIXTURE_DIR, "out-rot");
+ mkdirSync(outDir, { recursive: true });
+ const video: VideoElement = {
+ id: "r",
+ src: rotated,
+ start: 0,
+ end: 1,
+ mediaStart: 0,
+ loop: false,
+ hasAudio: false,
+ };
+ const result = await extractAllVideoFrames([video], FIXTURE_DIR, {
+ fps: 10,
+ outputDir: outDir,
+ });
+ expect(result.errors).toEqual([]);
+ const probe = spawnSync("ffprobe", [
+ "-v",
+ "error",
+ "-show_entries",
+ "stream=width,height",
+ "-of",
+ "csv=p=0",
+ "--",
+ result.extracted[0]!.framePaths.get(0)!,
+ ]);
+ expect(probe.stdout.toString().trim()).toBe("128,64");
+ });
+
+ it("extracts frames at the shape Chrome displays, not the stored grid", async () => {
+ const outDir = join(FIXTURE_DIR, "out");
+ mkdirSync(outDir, { recursive: true });
+ const video: VideoElement = {
+ id: "v",
+ src: SOURCE,
+ start: 0,
+ end: 1,
+ mediaStart: 0,
+ loop: false,
+ hasAudio: false,
+ };
+ const result = await extractAllVideoFrames([video], FIXTURE_DIR, {
+ fps: 10,
+ outputDir: outDir,
+ });
+ expect(result.errors).toEqual([]);
+ const probe = spawnSync("ffprobe", [
+ "-v",
+ "error",
+ "-show_entries",
+ "stream=width,height",
+ "-of",
+ "csv=p=0",
+ "--",
+ result.extracted[0]!.framePaths.get(0)!,
+ ]);
+ expect(probe.stdout.toString().trim()).toBe("32,64");
+ });
+});
+
+// Each source frame N is a flat gray of 3N, so the frame a render shows reads straight off a pixel.
+describe.skipIf(!HAS_FFMPEG)("a clip whose data-start is off the frame grid", () => {
+ const FIXTURE_DIR = mkdtempSync(join(tmpdir(), "hf-offgrid-start-"));
+ const SOURCE = join(FIXTURE_DIR, "numbered.mp4");
+ const FPS = 30;
+
+ beforeAll(async () => {
+ const result = await runFfmpeg([
+ "-y",
+ "-v",
+ "error",
+ "-f",
+ "lavfi",
+ "-i",
+ "color=c=black:s=64x64:d=6:r=30",
+ "-vf",
+ "format=gray,geq=lum='N*3'",
+ "-c:v",
+ "libx264",
+ "-crf",
+ "0",
+ "-g",
+ "30",
+ "-pix_fmt",
+ "yuv420p",
+ SOURCE,
+ ]);
+ if (!result.success) throw new Error(`fixture synthesis failed: ${result.stderr.slice(-400)}`);
+ }, 30_000);
+
+ afterAll(() => rmSync(FIXTURE_DIR, { recursive: true, force: true }), 30_000);
+
+ async function sourceFramesShown(
+ start: number,
+ outputFrames: number[],
+ ): Promise<(number | null)[]> {
+ const outDir = join(FIXTURE_DIR, `out-${start}`);
+ mkdirSync(outDir, { recursive: true });
+ const video: VideoElement = {
+ id: "v",
+ src: SOURCE,
+ start,
+ end: start + 1.9,
+ mediaStart: start,
+ loop: false,
+ hasAudio: false,
+ };
+ const result = await extractAllVideoFrames([video], FIXTURE_DIR, {
+ fps: FPS,
+ outputDir: outDir,
+ });
+ expect(result.errors).toEqual([]);
+ const table = createFrameLookupTable([video], result.extracted, FPS);
+ return outputFrames.map((n) => {
+ const path = table.getFrame("v", n / FPS);
+ return path ? Math.round(readFirstFramePixel(path, 0, 0)[0] / 3) : null;
+ });
+ }
+
+ it("keeps a looped clip on the same source frame after every wrap", async () => {
+ const loopSource = join(FIXTURE_DIR, "loop.mp4");
+ const synth = await runFfmpeg([
+ "-y",
+ "-v",
+ "error",
+ "-f",
+ "lavfi",
+ "-i",
+ "color=c=black:s=64x64:d=2:r=30",
+ "-vf",
+ "format=gray,geq=lum='N*4'",
+ "-c:v",
+ "libx264",
+ "-crf",
+ "0",
+ "-pix_fmt",
+ "yuv420p",
+ loopSource,
+ ]);
+ expect(synth.success).toBe(true);
+ const outDir = join(FIXTURE_DIR, "out-loop");
+ mkdirSync(outDir, { recursive: true });
+ const video: VideoElement = {
+ id: "v",
+ src: loopSource,
+ start: 0.35,
+ end: 6.35,
+ mediaStart: 1,
+ loop: true,
+ hasAudio: false,
+ };
+ const result = await extractAllVideoFrames([video], FIXTURE_DIR, {
+ fps: FPS,
+ outputDir: outDir,
+ timelineEnd: 6,
+ });
+ expect(result.errors).toEqual([]);
+ const table = createFrameLookupTable([video], result.extracted, FPS);
+ const shown = [0, 1, 2, 3, 4].map((wrap) => {
+ const path = table.getFrame("v", (12 + wrap * FPS + 1) / FPS);
+ return path ? Math.round(readFirstFramePixel(path, 0, 0)[0] / 4) : null;
+ });
+ expect(new Set(shown).size).toBe(1);
+ }, 60_000);
+
+ it.each([1.95, 2.0001, 1.999999])(
+ "shows source frame N at output frame N for data-start=data-media-start=%s",
+ async (start) => {
+ const shown = await sourceFramesShown(start, [61, 62, 63, 64, 65]);
+ expect(shown).toEqual([61, 62, 63, 64, 65]);
+ },
+ 60_000,
+ );
+});
diff --git a/packages/engine/src/services/videoFrameExtractor.ts b/packages/engine/src/services/videoFrameExtractor.ts
index 31db07f547..1ebe2c60ff 100644
--- a/packages/engine/src/services/videoFrameExtractor.ts
+++ b/packages/engine/src/services/videoFrameExtractor.ts
@@ -12,6 +12,7 @@ import { basename, join } from "path";
import { cpus } from "os";
import { createConcurrencyLimit } from "../utils/concurrencyLimit.js";
import { parseHTML } from "linkedom";
+import { HF_COLOR_GRADING_ATTR } from "@hyperframes/core";
import { isPathInside } from "@hyperframes/parsers/asset-paths";
import { resolveProjectRelativeSrc } from "@hyperframes/parsers/asset-resolution";
import { alphaDecoderFor } from "@hyperframes/parsers/media-alpha";
@@ -45,6 +46,7 @@ import {
extractFinalVideoFrameTimestamp,
extractMediaMetadata,
ffmpegSeekSeconds,
+ formatFfmpegSeconds,
keyframeGapSeconds,
mediaFileIdentity,
readMetadataCache,
@@ -69,7 +71,7 @@ import {
UrlDownloadError,
writeUrlDownloadTelemetry,
} from "../utils/urlDownloader.js";
-import { runFfmpeg, type RunFfmpegResult } from "../utils/runFfmpeg.js";
+import { ffmpegStatsReader, runFfmpeg, type RunFfmpegResult } from "../utils/runFfmpeg.js";
import {
isFfmpegFilterAvailable,
isFfmpegHwaccelAvailable,
@@ -104,6 +106,7 @@ export interface VideoElement {
loop: boolean;
hasAudio: boolean;
hidden?: boolean;
+ graded?: boolean;
}
export interface ExtractedFrames {
@@ -292,6 +295,7 @@ export interface ExtractionOptions {
collectProbeFailures?: boolean;
/** Extract only these runs of output frames, named as a full extraction names them. CFR only. */
frameRanges?: readonly FrameRange[];
+ onProgress?: (progress: { planned?: number; done?: number }) => void;
/** A short decode of a remote source, only to count its frames: it waits on the network, so it runs wider. */
tailProbe?: boolean;
/**
@@ -843,6 +847,7 @@ export function parseVideoElements(html: string): VideoElement[] {
(isAudibleVideoElement(el) && isMemberGroupHidden(groupsById, el))
? { hidden: true }
: {}),
+ ...(el.hasAttribute(HF_COLOR_GRADING_ATTR) ? { graded: true } : {}),
});
}
@@ -854,6 +859,14 @@ export interface ImageElement {
src: string;
start: number;
end: number;
+ graded?: boolean;
+}
+
+export function hasGradedCanvas(html: string): boolean {
+ return (
+ parseHTML(unwrapTemplate(html)).document.querySelector(`canvas[${HF_COLOR_GRADING_ATTR}]`) !==
+ null
+ );
}
export function parseImageElements(html: string): ImageElement[] {
@@ -893,7 +906,13 @@ export function parseImageElements(html: string): ImageElement[] {
end = Infinity;
}
- images.push({ id, src, start, end });
+ images.push({
+ id,
+ src,
+ start,
+ end,
+ ...(el.hasAttribute(HF_COLOR_GRADING_ATTR) ? { graded: true } : {}),
+ });
}
return images;
@@ -990,6 +1009,18 @@ interface SegmentedExtraction {
segments: readonly FrameRange[];
gate: typeof inExtractionSlot;
runOptions: { signal?: AbortSignal; timeout: number };
+ onProgress?: ExtractionOptions["onProgress"];
+}
+
+function framesWrittenReader(onProgress: ExtractionOptions["onProgress"]) {
+ if (!onProgress) return undefined;
+ let seen = 0;
+ const read = ffmpegStatsReader(({ frames }) => {
+ if (frames === undefined || frames <= seen) return;
+ onProgress({ done: frames - seen });
+ seen = frames;
+ });
+ return (chunk: string) => read(chunk);
}
/** Split runs so no single ffmpeg process extracts more than `segmentFrames` frames. */
@@ -1029,12 +1060,12 @@ async function runSegmentedExtraction(job: SegmentedExtraction): Promise
@@ -1255,11 +1304,13 @@ async function extractVideoFramesRangeUnredacted(
segmentFrames,
),
runOptions,
+ onProgress: options.onProgress,
})
: inExtractionSlot(
async () =>
runFfmpeg([...hwaccel, ...args, ...filterArgsFor(startTime), ...encodeArgs], {
...runOptions,
+ onStderr: framesWrittenReader(options.onProgress),
timeout: stallTimeoutMs(
ffmpegProcessTimeout,
options.finalFrameOnly
@@ -1270,6 +1321,11 @@ async function extractVideoFramesRangeUnredacted(
}),
signal,
);
+ options.onProgress?.({
+ planned: options.frameRanges
+ ? options.frameRanges.reduce((sum, range) => sum + range.frames, 0)
+ : totalFrames,
+ });
let processResult = await extract(decodeWithVideoToolbox ? ["-hwaccel", "videotoolbox"] : []);
const ffmpegExitedFailing =
processResult.terminationReason === "exit" &&
@@ -1469,6 +1525,23 @@ export function isVideoPastTimelineEnd(video: Pick, timel
return video.start >= timelineEnd;
}
+export function alignClipStartToFirstOutputFrame(video: VideoElement, fps: number): void {
+ if (video.loop || !Number.isFinite(video.start) || video.start < 0 || !(fps > 0)) return;
+ const position = exportClipWindow(video.start, Infinity, fps).start * fps;
+ const firstFrame =
+ Math.abs(position - Math.round(position)) < 1e-6 ? Math.round(position) : Math.ceil(position);
+ const shift = firstFrame / fps - video.start;
+ // Float dust (a sum landing a hair off the grid) snaps the start; it never reaches mediaStart.
+ if (Math.abs(shift) < 1e-9) {
+ video.start = firstFrame / fps;
+ return;
+ }
+ const playbackRate = normalizeRateSpec(video.playbackRate);
+ video.mediaStart += sourceTimeAt(playbackRate, shift);
+ video.playbackRate = shiftRateLane(playbackRate, shift);
+ video.start += shift;
+}
+
/** Move a clip to its extraction window; a rate lane is shifted so it keeps integrating from the new origin. */
export function rebaseVideoToWindow(video: VideoElement, window: TimelineExtractionWindow): void {
if (window.preserveTimelinePhase) return;
@@ -2593,6 +2666,7 @@ export async function extractAllVideoFrames(
}
try {
const metadata = videoMetadata[index] ?? (await extractMediaMetadata(videoPath));
+ alignClipStartToFirstOutputFrame(video, fps);
const initialWindow = resolveVideoExtractionWindow(video, metadata, options.timelineEnd);
const window = await resolveFinalFrameExtractionWindow(
videoPath,
diff --git a/packages/engine/src/types.ts b/packages/engine/src/types.ts
index 606f2bbec9..a4b2436744 100644
--- a/packages/engine/src/types.ts
+++ b/packages/engine/src/types.ts
@@ -246,6 +246,7 @@ export interface CaptureOptions {
*/
deVerifySamples?: number;
deFrameFallback?: boolean;
+ onEffectScanProgress?: (scannedFrames: number, totalFrames: number) => void;
}
export interface CaptureVideoMetadataHint {
diff --git a/packages/engine/src/utils/ffprobe.test.ts b/packages/engine/src/utils/ffprobe.test.ts
index f87bd70e2f..708b1221d8 100644
--- a/packages/engine/src/utils/ffprobe.test.ts
+++ b/packages/engine/src/utils/ffprobe.test.ts
@@ -5,7 +5,12 @@ import { mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "fs
import { tmpdir } from "os";
import { basename, join, resolve } from "path";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
-import { extractMediaMetadata, extractPngMetadataFromBuffer, parseFrameRate } from "./ffprobe.js";
+import {
+ extractMediaMetadata,
+ extractPngMetadataFromBuffer,
+ formatFfmpegSeconds,
+ parseFrameRate,
+} from "./ffprobe.js";
function crc32(buf: Buffer): number {
let crc = 0xffffffff;
@@ -2235,3 +2240,17 @@ describe.skipIf(!HAS_FFPROBE)("VP8/VP9 decoded alpha plane probe on real files",
expect("alphaPlaneDecoded" in other).toBe(false);
});
});
+
+describe("formatFfmpegSeconds", () => {
+ it("never writes an exponent, which ffmpeg and ffprobe reject", () => {
+ expect(formatFfmpegSeconds(8.881784197001252e-16)).toBe("0");
+ expect(formatFfmpegSeconds(-8.881784197001252e-16)).toBe("0");
+ expect(formatFfmpegSeconds(1.5e-7)).toBe("0");
+ });
+
+ it("keeps ordinary times exactly as String() writes them", () => {
+ expect(formatFfmpegSeconds(1.35)).toBe("1.35");
+ expect(formatFfmpegSeconds(4.666666666666667)).toBe("4.666666666666667");
+ expect(formatFfmpegSeconds(0)).toBe("0");
+ });
+});
diff --git a/packages/engine/src/utils/ffprobe.ts b/packages/engine/src/utils/ffprobe.ts
index a847c04ecc..c55eeb6812 100644
--- a/packages/engine/src/utils/ffprobe.ts
+++ b/packages/engine/src/utils/ffprobe.ts
@@ -224,6 +224,7 @@ export interface VideoMetadata {
colorSpace: VideoColorSpace | null;
colorRange?: string;
pixelFormat?: string;
+ sampleAspectRatio?: number;
/** Decoded frame count from the video stream's `nb_frames`. Omitted when the
* container does not surface a reliable count (still images, malformed
* streams, or muxes that require `-count_packets` to populate). Callers
@@ -263,6 +264,7 @@ interface FFProbeStream {
nb_frames?: string;
nb_read_packets?: string;
pix_fmt?: string;
+ sample_aspect_ratio?: string;
r_frame_rate?: string;
avg_frame_rate?: string;
sample_rate?: string;
@@ -520,6 +522,11 @@ export function videoStartOnMediaTimeline(
return (metadata.videoStreamLeadSeconds ?? 0) + (metadata.mediaTimeOffsetSeconds ?? 0);
}
+export function formatFfmpegSeconds(seconds: number): string {
+ const text = String(seconds);
+ return text.includes("e") ? String(+seconds.toFixed(6)) : text;
+}
+
export function ffmpegSeekSeconds(
metadata: Pick,
mediaTime: number,
@@ -843,6 +850,13 @@ export function parseFrameRate(frameRateStr: string | undefined): number {
return rounded > 0 ? rounded : 0.01;
}
+export function parseSampleAspectRatio(value: string | undefined): number | undefined {
+ const [num, den] = (value ?? "").split(":").map(Number);
+ if (!num || !den || !Number.isFinite(num) || !Number.isFinite(den)) return undefined;
+ const ratio = num / den;
+ return Math.abs(ratio - 1) < 1e-3 ? undefined : ratio;
+}
+
/**
* Whether the first frame decoded with `decoder` (alpha-aware) has an alpha pixel format; undefined on any
* failure. ffprobe cannot pick a decoder, so ffmpeg writes the frame as rawvideo, which keeps its pix_fmt.
@@ -977,6 +991,7 @@ export async function extractMediaMetadata(filePath: string): Promise {
);
});
});
+
+describe("gradingKeepsSdr", () => {
+ const graded = { videos: [{}], images: [{ graded: true }] };
+ it("keeps auto renders with graded media SDR, never a forced mode or ungraded media", () => {
+ expect(gradingKeepsSdr(undefined, graded)).toBe(true);
+ expect(gradingKeepsSdr("auto", graded)).toBe(true);
+ expect(gradingKeepsSdr("force-hdr", graded)).toBe(false);
+ expect(gradingKeepsSdr("auto", { videos: [{}], images: [] })).toBe(false);
+ expect(gradingKeepsSdr("auto", { videos: [], images: [], gradedCanvas: true })).toBe(true);
+ });
+});
diff --git a/packages/engine/src/utils/hdr.ts b/packages/engine/src/utils/hdr.ts
index df0b75744e..9448743d35 100644
--- a/packages/engine/src/utils/hdr.ts
+++ b/packages/engine/src/utils/hdr.ts
@@ -142,6 +142,22 @@ export function findHdrAutoPromotion(
: null;
}
+/** Grading is SDR-only, so in auto mode a composition with graded media renders SDR, as `--sdr` does. */
+export function gradingKeepsSdr(
+ hdrMode: "auto" | "force-hdr" | "force-sdr" | undefined,
+ media: {
+ videos: readonly { graded?: boolean }[];
+ images: readonly { graded?: boolean }[];
+ gradedCanvas?: boolean;
+ },
+): boolean {
+ return (
+ (hdrMode ?? "auto") === "auto" &&
+ (media.gradedCanvas === true ||
+ [...media.videos, ...media.images].some(({ graded }) => graded === true))
+ );
+}
+
export function formatHdrAutoPromotionWarning(promotion: HdrAutoPromotion): string {
return `[Render] HDR auto-promotion triggered by "${promotion.triggeringAsset}", output: ${promotion.output.colorSpace} / ${promotion.output.codec}`;
}
diff --git a/packages/engine/src/utils/networkPolicy.test.ts b/packages/engine/src/utils/networkPolicy.test.ts
new file mode 100644
index 0000000000..9091421afb
--- /dev/null
+++ b/packages/engine/src/utils/networkPolicy.test.ts
@@ -0,0 +1,12 @@
+import { describe, expect, it } from "vitest";
+import { isBlockedNetworkHost } from "./networkPolicy.js";
+
+describe("special-use network list", () => {
+ it.each(["192.0.0.0", "192.0.0.8", "192.0.0.255", "192.0.2.1"])("blocks reserved %s", (ip) =>
+ expect(isBlockedNetworkHost(ip)).toBe(true),
+ );
+ // 192.0.64.0/18 is WordPress VIP (nasa.gov is 192.0.66.108): public, outside the two reserved /24s.
+ it.each(["192.0.66.108", "192.0.1.1", "192.0.3.1"])("leaves public %s reachable", (ip) =>
+ expect(isBlockedNetworkHost(ip)).toBe(false),
+ );
+});
diff --git a/packages/engine/src/utils/networkPolicy.ts b/packages/engine/src/utils/networkPolicy.ts
new file mode 100644
index 0000000000..f344f053ed
--- /dev/null
+++ b/packages/engine/src/utils/networkPolicy.ts
@@ -0,0 +1,56 @@
+import { BlockList, isIP } from "node:net";
+
+// The one list of special-use networks: asset downloads and the capture proxy both read it, so a site one can reach the other can too.
+const NON_PUBLIC_IPV4_ADDRESSES = new BlockList();
+for (const [network, prefix] of [
+ ["0.0.0.0", 8],
+ ["10.0.0.0", 8],
+ ["100.64.0.0", 10],
+ ["127.0.0.0", 8],
+ ["169.254.0.0", 16],
+ ["172.16.0.0", 12],
+ ["192.0.0.0", 24],
+ ["192.0.2.0", 24],
+ ["192.88.99.0", 24],
+ ["192.168.0.0", 16],
+ ["198.18.0.0", 15],
+ ["198.51.100.0", 24],
+ ["203.0.113.0", 24],
+ ["224.0.0.0", 4],
+ ["240.0.0.0", 4],
+] as const) {
+ NON_PUBLIC_IPV4_ADDRESSES.addSubnet(network, prefix, "ipv4");
+}
+const NON_PUBLIC_IPV6_ADDRESSES = new BlockList();
+for (const [network, prefix] of [
+ ["::", 128],
+ ["::1", 128],
+ ["::ffff:0:0", 96],
+ ["fc00::", 7],
+ ["fe80::", 10],
+ ["fec0::", 10],
+ ["ff00::", 8],
+ ["2001:db8::", 32],
+] as const) {
+ NON_PUBLIC_IPV6_ADDRESSES.addSubnet(network, prefix, "ipv6");
+}
+
+/** Literal-host policy shared by rendering and capture; DNS resolution remains trusted. */
+export function isBlockedNetworkHost(hostname: string): boolean {
+ const h = hostname
+ .toLowerCase()
+ .replace(/\.$/, "")
+ .replace(/^\[|\]$/g, "");
+ if (
+ h === "localhost" ||
+ h.endsWith(".localhost") ||
+ h.endsWith(".local") ||
+ h.endsWith(".internal")
+ )
+ return true;
+ const addressType = isIP(h);
+ if (addressType === 0) return false;
+ return addressType === 4
+ ? NON_PUBLIC_IPV4_ADDRESSES.check(h, "ipv4")
+ : NON_PUBLIC_IPV6_ADDRESSES.check(h, "ipv6");
+}
diff --git a/packages/engine/src/utils/urlDownloader.ts b/packages/engine/src/utils/urlDownloader.ts
index f45f00fc48..be12d65597 100644
--- a/packages/engine/src/utils/urlDownloader.ts
+++ b/packages/engine/src/utils/urlDownloader.ts
@@ -19,7 +19,8 @@ import {
import { createHash, randomUUID } from "crypto";
import dns from "node:dns";
import { fetchGoesThroughEnvProxy } from "@hyperframes/core/env-proxy";
-import { BlockList, isIP, type LookupFunction } from "node:net";
+import { type LookupFunction } from "node:net";
+import { isBlockedNetworkHost } from "./networkPolicy.js";
import { dirname, extname, join } from "path";
import { Readable, Transform } from "stream";
import { pipeline } from "stream/promises";
@@ -204,60 +205,6 @@ function isRetryableNetworkCause(error: unknown): boolean {
);
}
-const NON_PUBLIC_IPV4_ADDRESSES = new BlockList();
-for (const [network, prefix] of [
- ["0.0.0.0", 8],
- ["10.0.0.0", 8],
- ["100.64.0.0", 10],
- ["127.0.0.0", 8],
- ["169.254.0.0", 16],
- ["172.16.0.0", 12],
- ["192.0.0.0", 24],
- ["192.0.2.0", 24],
- ["192.88.99.0", 24],
- ["192.168.0.0", 16],
- ["198.18.0.0", 15],
- ["198.51.100.0", 24],
- ["203.0.113.0", 24],
- ["224.0.0.0", 4],
- ["240.0.0.0", 4],
-] as const) {
- NON_PUBLIC_IPV4_ADDRESSES.addSubnet(network, prefix, "ipv4");
-}
-const NON_PUBLIC_IPV6_ADDRESSES = new BlockList();
-for (const [network, prefix] of [
- ["::", 128],
- ["::1", 128],
- ["::ffff:0:0", 96],
- ["fc00::", 7],
- ["fe80::", 10],
- ["fec0::", 10],
- ["ff00::", 8],
- ["2001:db8::", 32],
-] as const) {
- NON_PUBLIC_IPV6_ADDRESSES.addSubnet(network, prefix, "ipv6");
-}
-
-/** Literal-host policy shared by rendering and capture; DNS resolution remains trusted. */
-export function isBlockedNetworkHost(hostname: string): boolean {
- const h = hostname
- .toLowerCase()
- .replace(/\.$/, "")
- .replace(/^\[|\]$/g, "");
- if (
- h === "localhost" ||
- h.endsWith(".localhost") ||
- h.endsWith(".local") ||
- h.endsWith(".internal")
- )
- return true;
- const addressType = isIP(h);
- if (addressType === 0) return false;
- return addressType === 4
- ? NON_PUBLIC_IPV4_ADDRESSES.check(h, "ipv4")
- : NON_PUBLIC_IPV6_ADDRESSES.check(h, "ipv6");
-}
-
/**
* Validate that a URL is safe to fetch on behalf of customer-supplied
* compositions. Throws if the URL is non-HTTPS or targets a private/reserved
diff --git a/packages/gcp-cloud-run/package.json b/packages/gcp-cloud-run/package.json
index 8137693911..50a94e9899 100644
--- a/packages/gcp-cloud-run/package.json
+++ b/packages/gcp-cloud-run/package.json
@@ -1,6 +1,6 @@
{
"name": "@hyperframes/gcp-cloud-run",
- "version": "0.8.214",
+ "version": "0.8.224",
"description": "Google Cloud Run + Workflows adapter for HyperFrames distributed rendering — request handler, client-side SDK, and Terraform module.",
"repository": {
"type": "git",
diff --git a/packages/inspector/package.json b/packages/inspector/package.json
index a4d54297ae..84bb4ee48b 100644
--- a/packages/inspector/package.json
+++ b/packages/inspector/package.json
@@ -1,6 +1,6 @@
{
"name": "@hyperframes/inspector",
- "version": "0.8.214",
+ "version": "0.8.224",
"repository": {
"type": "git",
"url": "https://github.com/heygen-com/hyperframes",
diff --git a/packages/lint/package.json b/packages/lint/package.json
index 8e7cd7768e..61047ec135 100644
--- a/packages/lint/package.json
+++ b/packages/lint/package.json
@@ -1,6 +1,6 @@
{
"name": "@hyperframes/lint",
- "version": "0.8.214",
+ "version": "0.8.224",
"repository": {
"type": "git",
"url": "https://github.com/heygen-com/hyperframes",
diff --git a/packages/lint/src/context.ts b/packages/lint/src/context.ts
index c01fbadd59..fd6e48c0b6 100644
--- a/packages/lint/src/context.ts
+++ b/packages/lint/src/context.ts
@@ -64,7 +64,17 @@ export function buildLintContext(html: string, options: HyperframeLinterOptions
rootRelativePath: style.rootRelativePath,
})),
];
- const scripts = structure.scripts;
+ const scripts = [
+ ...structure.scripts,
+ ...(options.externalScripts ?? []).map((script) => ({
+ attrs: script.attrs,
+ content: script.content,
+ raw: script.content,
+ index: -1,
+ file: script.file,
+ rootRelativePath: script.rootRelativePath,
+ })),
+ ];
const compositionIds = collectCompositionIds(tags);
const rootTag = findRootTag(source, tags);
const rootCompositionId = readDecodedAttr(rootTag?.raw || "", "data-composition-id");
diff --git a/packages/lint/src/project.test.ts b/packages/lint/src/project.test.ts
index ef57766efa..ac56524e08 100644
--- a/packages/lint/src/project.test.ts
+++ b/packages/lint/src/project.test.ts
@@ -1,7 +1,7 @@
import { describe, it, expect, afterEach, beforeEach, vi } from "vitest";
import { ChildProcess, execFile } from "node:child_process";
import { mkdirSync, mkdtempSync, writeFileSync, rmSync, symlinkSync } from "node:fs";
-import { join } from "node:path";
+import { dirname, join } from "node:path";
import { tmpdir } from "node:os";
import type { HyperframeLintFinding } from "./types.js";
import { lintProject } from "./project.js";
@@ -399,6 +399,71 @@ describe("missing_or_empty_sub_composition", () => {
});
});
+describe("missing_stylesheet_asset", () => {
+ const lintLinked = async (css: string, files: Record = {}) => {
+ const project = makeProject(
+ validHtml().replace(
+ "",
+ ' ',
+ ),
+ );
+ mkdirSync(join(project, "styles"), { recursive: true });
+ writeFileSync(join(project, "styles/main.css"), css);
+ for (const [name, body] of Object.entries(files)) {
+ mkdirSync(dirname(join(project, name)), { recursive: true });
+ writeFileSync(join(project, name), body);
+ }
+ const { results } = await lintProject(project);
+ return results
+ .flatMap((entry) => entry.result.findings)
+ .filter((finding) => finding.code === "missing_stylesheet_asset");
+ };
+
+ it("names the path that exists when a url() is relative to the wrong folder", async () => {
+ const findings = await lintLinked('@font-face{font-family:X;src:url("assets/fonts/x.ttf")}', {
+ "assets/fonts/x.ttf": "font",
+ });
+
+ expect(findings).toHaveLength(1);
+ expect(findings[0]).toMatchObject({ severity: "warning" });
+ expect(findings[0]?.message).toContain("assets/fonts/x.ttf");
+ expect(findings[0]?.fixHint).toContain("../assets/fonts/x.ttf");
+ });
+
+ it("hints the encoded url when the encoded file is in a parent folder", async () => {
+ const findings = await lintLinked('@font-face{src:url("fonts/Open%20Sans.ttf")}', {
+ "fonts/Open Sans.ttf": "font",
+ });
+
+ expect(findings).toHaveLength(1);
+ expect(findings[0]?.fixHint).toContain("../fonts/Open%20Sans.ttf");
+ });
+
+ it("asks for the file when it exists nowhere", async () => {
+ const findings = await lintLinked(".a{background:url(nope.png)}");
+
+ expect(findings).toHaveLength(1);
+ expect(findings[0]?.fixHint).toContain("Add");
+ });
+
+ it("stays quiet for urls that resolve beside the stylesheet, remote, data and placeholder urls", async () => {
+ const css = [
+ '@font-face{src:url("../assets/fonts/x.ttf")}',
+ ".a{background:url(img/a.png)} .b{background:url(https://cdn.example/b.png)}",
+ ".c{background:url(data:image/png;base64,AAAA)} .d{background:url(#frag)}",
+ ".e{background:url(${asset})}",
+ '@font-face{src:url("fonts/Open%20Sans.ttf")}',
+ ].join("\n");
+ const findings = await lintLinked(css, {
+ "assets/fonts/x.ttf": "font",
+ "styles/img/a.png": "png",
+ "styles/fonts/Open Sans.ttf": "font",
+ });
+
+ expect(findings).toEqual([]);
+ });
+});
+
describe("texture_mask_asset_not_found declarations", () => {
it("still reports a missing inline mask beside a malformed declaration", async () => {
const project = makeProject(
@@ -501,6 +566,46 @@ describe("template shell style sources", () => {
});
});
+describe("local script files", () => {
+ const registryFindings = async (project: string) =>
+ (await lintProject(project)).results
+ .flatMap((entry) => entry.result.findings)
+ .filter((finding) => finding.code === "missing_timeline_registry");
+
+ function projectWithScript(script: string, attrs = ""): string {
+ const project = makeProject(
+ `
+
+
+`,
+ );
+ writeFileSync(join(project, "animation.js"), script);
+ return project;
+ }
+
+ it("counts a timeline registered in a local script file", async () => {
+ const registered = projectWithScript(
+ 'window.__timelines = window.__timelines || {};\nwindow.__timelines["main"] = gsap.timeline({ paused: true });',
+ );
+ expect(await registryFindings(registered)).toEqual([]);
+ expect(await registryFindings(projectWithScript("console.log('no timeline')"))).toHaveLength(1);
+ });
+
+ it("reads a module script file as a module", async () => {
+ const project = projectWithScript(
+ 'import { gsap } from "gsap";\nwindow.__timelines = window.__timelines || {};\nwindow.__timelines["main"] = gsap.timeline({ paused: true });',
+ 'type="module"',
+ );
+
+ const codes = (await lintProject(project)).results
+ .flatMap((entry) => entry.result.findings)
+ .map((finding) => finding.code);
+
+ expect(codes).not.toContain("invalid_inline_script_syntax");
+ expect(codes).not.toContain("missing_timeline_registry");
+ });
+});
+
describe("sub-composition stylesheet links", () => {
function projectWithSharedFonts(compDir: string, href: string): string {
const project = makeProject(validHtml());
@@ -541,6 +646,77 @@ describe("sub-composition stylesheet links", () => {
).toEqual([]);
});
+ it("counts a font the root's linked stylesheet declares for a sub-composition that only uses it", async () => {
+ const project = makeProject(
+ validHtml().replace(
+ "",
+ ' ',
+ ),
+ );
+ mkdirSync(join(project, "assets"), { recursive: true });
+ writeFileSync(
+ join(project, "assets", "fonts.css"),
+ "@font-face{font-family:'Repro';src:local('Repro')}",
+ );
+ mkdirSync(join(project, "compositions"), { recursive: true });
+ const scene = (family: string) => `
+
+
+
Hello
+
+
+ `;
+ writeFileSync(join(project, "compositions", "scene.html"), scene("Repro"));
+ expect(await fontFaceFindings(project)).toEqual([]);
+ writeFileSync(join(project, "compositions", "scene.html"), scene("Nowhere"));
+ expect(await fontFaceFindings(project)).toHaveLength(1);
+ });
+
+ it("counts a Google Fonts link in the root for a sub-composition that uses the family", async () => {
+ const project = makeProject(
+ validHtml().replace(
+ "",
+ ' ',
+ ),
+ {
+ "scene.html": `
+
+
Hello
+
+ `,
+ },
+ );
+ expect(await fontFaceFindings(project)).toEqual([]);
+ });
+
+ it("counts a font a mounted composition declares, and ignores one only an unmounted file declares", async () => {
+ const mount = (file: string) =>
+ `
`;
+ const composition = (id: string, css: string) => `
+
+
Hello
+
+ `;
+ const files = (declaring: string) => ({
+ "scene.html": composition("scene", "#scene-title{font-family:'Repro'}"),
+ [`${declaring}.html`]: composition(
+ declaring,
+ "@font-face{font-family:'Repro';src:local('Repro')}",
+ ),
+ });
+ const withHosts = (...hosts: string[]) =>
+ validHtml().replace("", `${hosts.join("")}`);
+
+ expect(
+ await fontFaceFindings(
+ makeProject(withHosts(mount("scene"), mount("fonts")), files("fonts")),
+ ),
+ ).toEqual([]);
+ expect(
+ await fontFaceFindings(makeProject(withHosts(mount("scene")), files("unused"))),
+ ).toHaveLength(1);
+ });
+
it("reads the stylesheet next to the sub-composition when both exist", async () => {
const project = projectWithSharedFonts("compositions/frames", "fonts.css");
writeFileSync(join(project, "fonts.css"), "@font-face{font-family:'Other';src:local('Other')}");
diff --git a/packages/lint/src/project.ts b/packages/lint/src/project.ts
index bd31c920ce..33a1839db5 100644
--- a/packages/lint/src/project.ts
+++ b/packages/lint/src/project.ts
@@ -40,6 +40,7 @@ import {
lintVideoMediaStartPastEof,
} from "./hevcPreviewLint.js";
import { lintHyperframeHtml } from "./hyperframeLinter.js";
+import { collectGoogleFontFamilies, extractFontFaceFamilies } from "./rules/fonts.js";
import { lintProjectShaderScripts } from "./projectShaders.js";
import type {
HyperframeLintFinding,
@@ -154,6 +155,42 @@ export function collectExternalStyles(
return styles;
}
+const MAX_EXTERNAL_SCRIPT_BYTES = 1_000_000;
+
+function collectExternalScripts(
+ projectDir: string,
+ html: string,
+ compSrcPath?: string,
+): NonNullable {
+ const scripts: NonNullable = [];
+ const { document } = parseHTML(html);
+ for (const element of querySelectorAllIncludingTemplates(document, "script[src]")) {
+ const src = element.getAttribute("src") ?? "";
+ if (!isLocalStylesheetHref(src) || /\.min\.m?js(?:[?#]|$)/i.test(src)) continue;
+ const path = src.split(/[?#]/)[0] ?? src;
+ const besideFile = compSrcPath ? join(dirname(compSrcPath), path) : path;
+ const script =
+ resolveExistingLocalAsset(projectDir, besideFile) ??
+ (compSrcPath && staysInsideProjectRoot(path)
+ ? resolveExistingLocalAsset(projectDir, path)
+ : null);
+ if (!script) continue;
+ const read = readProjectFile(script.resolved);
+ if (read.kind !== "file" || read.text.length > MAX_EXTERNAL_SCRIPT_BYTES) continue;
+ const attrs = Array.from(element.attributes)
+ .map(({ name, value }) => `${name}="${value.replace(/&/g, "&").replace(/"/g, """)}"`)
+ .join(" ");
+ scripts.push({
+ src,
+ attrs,
+ content: read.text,
+ file: join(projectDir, script.rootRelativePath),
+ rootRelativePath: script.rootRelativePath,
+ });
+ }
+ return scripts;
+}
+
function collectCssSources(projectDir: string, html: string, compSrcPath?: string): CssSource[] {
const sources: CssSource[] = [];
const { document } = parseHTML(html);
@@ -198,6 +235,48 @@ function resolveCssAssetCandidates(
return resolveLocalAssetCandidates(projectDir, url);
}
+function mountedSources(
+ projectDir: string,
+ rootHtml: string,
+ rootCompSrcPath?: string,
+): HtmlSource[] {
+ const sources: HtmlSource[] = [{ html: rootHtml, compSrcPath: rootCompSrcPath }];
+ const seen = new Set();
+ for (const source of sources) {
+ const { document } = parseHTML(source.html);
+ for (const host of querySelectorAllIncludingTemplates(document, "[data-composition-src]")) {
+ const src = host.getAttribute("data-composition-src")?.trim();
+ if (!src || isUnresolvedAssetPlaceholder(src) || isRemoteOrInlineUrl(src)) continue;
+ const path = resolve(projectDir, src);
+ if (seen.has(path) || !isWithinProjectRoot(projectDir, path)) continue;
+ seen.add(path);
+ const read = readProjectFile(path);
+ if (read.kind !== "file") continue;
+ sources.push({
+ html: read.text,
+ compSrcPath: relative(resolve(projectDir), path).replace(/\\/g, "/"),
+ });
+ }
+ }
+ return sources;
+}
+
+function declaredProjectFontFamilies(projectDir: string, sources: HtmlSource[]): string[] {
+ const families = new Set();
+ for (const { html, compSrcPath } of sources) {
+ const { document } = parseHTML(html);
+ const styles = [
+ ...querySelectorAllIncludingTemplates(document, "style").map((style) => ({
+ content: style.textContent ?? "",
+ })),
+ ...collectLocalStylesheets(projectDir, document, compSrcPath),
+ ];
+ for (const family of extractFontFaceFamilies(styles)) families.add(family);
+ for (const family of collectGoogleFontFamilies(html, styles)) families.add(family);
+ }
+ return [...families];
+}
+
export async function lintProject(
projectDir: string,
entryFile?: string,
@@ -215,11 +294,17 @@ export async function lintProject(
let totalInfos = 0;
const rootHtml = readFileSync(indexPath, "utf-8");
+ const projectFontFamilies = declaredProjectFontFamilies(
+ projectDir,
+ mountedSources(projectDir, rootHtml, rootCompSrcPath),
+ );
const rootResult = await lintHyperframeHtml(rootHtml, {
...hostOptions,
filePath: indexPath,
compSrcPath: rootFile,
externalStyles: collectExternalStyles(projectDir, rootHtml, rootCompSrcPath),
+ projectFontFamilies,
+ externalScripts: collectExternalScripts(projectDir, rootHtml, rootCompSrcPath),
});
results.push({ file: rootFile, result: rootResult, contentHash: contentDigest(rootHtml) });
totalErrors += rootResult.errorCount;
@@ -262,6 +347,8 @@ export async function lintProject(
isSubComposition: true,
compSrcPath,
externalStyles: collectExternalStyles(projectDir, html, compSrcPath),
+ projectFontFamilies,
+ externalScripts: collectExternalScripts(projectDir, html, compSrcPath),
});
results.push({
file: `compositions/${file}`,
@@ -280,6 +367,7 @@ export async function lintProject(
...lintAudioSrcNotFound(projectDir, allHtmlSources),
...lintMissingLocalAsset(projectDir, allHtmlSources),
...lintTextureMaskAssetNotFound(projectDir, allHtmlSources),
+ ...lintLinkedStylesheetAssets(projectDir, allHtmlSources),
...(!entryFile ? lintMultipleRootCompositions(projectDir) : []),
...(!entryFile ? lintBlankRootWithStandaloneComposition(rootHtml, allHtmlSources) : []),
...lintDuplicateAudioTracks(projectDir, rootHtml),
@@ -575,6 +663,74 @@ function lintTextureMaskAssetNotFound(
});
}
+function nearestAncestorMatch(projectDir: string, cssRootRelativePath: string, url: string) {
+ const root = resolve(projectDir);
+ for (let dir = resolve(root, dirname(cssRootRelativePath), ".."); ; dir = dirname(dir)) {
+ if (!isWithinProjectRoot(projectDir, dir)) return null;
+ if (resolveLocalAssetCandidates(projectDir, relative(root, join(dir, url))).some(existsSync)) {
+ return relative(dirname(resolve(root, cssRootRelativePath)), join(dir, url)).replace(
+ /\\/g,
+ "/",
+ );
+ }
+ if (dir === root) return null;
+ }
+}
+
+function lintLinkedStylesheetAssets(
+ projectDir: string,
+ htmlSources: HtmlSource[],
+): HyperframeLintFinding[] {
+ const seen = new Set();
+ const findings: HyperframeLintFinding[] = [];
+ for (const { html, compSrcPath } of htmlSources) {
+ for (const { content, rootRelativePath } of collectLocalStylesheets(
+ projectDir,
+ parseHTML(html).document,
+ compSrcPath,
+ )) {
+ let root: postcss.Root;
+ try {
+ root = postcss.parse(content);
+ } catch (error) {
+ if (!(error instanceof postcss.CssSyntaxError)) throw error;
+ continue;
+ }
+ root.walkDecls((declaration) => {
+ if (/^(?:-webkit-)?mask-image$/i.test(declaration.prop)) return;
+ for (const match of declaration.value.matchAll(CSS_URL_RE)) {
+ const rawUrl = match[1] ?? match[2] ?? match[3] ?? "";
+ if (isUnresolvedAssetPlaceholder(rawUrl)) continue;
+ const url = cleanAssetUrl(rawUrl);
+ if (!url || isRemoteOrInlineUrl(url) || url.startsWith("/")) continue;
+ if (
+ resolveCssAssetCandidates(projectDir, url, undefined, rootRelativePath).some(existsSync)
+ )
+ continue;
+ const key = `${rootRelativePath}\0${url}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ const found = nearestAncestorMatch(projectDir, rootRelativePath, url);
+ findings.push({
+ code: "missing_stylesheet_asset",
+ severity: "warning",
+ file: join(projectDir, rootRelativePath),
+ message:
+ `${rootRelativePath} references url(${url}), which is not found beside the stylesheet ` +
+ `(looked in ${dirname(rootRelativePath)}/). The browser resolves url() from the stylesheet, so the file will 404.`,
+ fixHint: found
+ ? `A file exists at "${found}" relative to the stylesheet. Change the url() to that path.`
+ : `Add "${url}" beside the stylesheet, or point the url() at an existing file.`,
+ });
+ }
+ });
+ }
+ }
+ return findings;
+}
+
+const PAGES_OPENED_BESIDE_INDEX = new Set(["caption-skin.html", "podcast-lanes.html"]);
+
function lintMultipleRootCompositions(projectDir: string): HyperframeLintFinding[] {
const findings: HyperframeLintFinding[] = [];
try {
@@ -583,7 +739,7 @@ function lintMultipleRootCompositions(projectDir: string): HyperframeLintFinding
);
const rootCompositions: string[] = [];
for (const file of rootHtmlFiles) {
- if (file === "caption-skin.html") continue;
+ if (PAGES_OPENED_BESIDE_INDEX.has(file)) continue;
const content = readFileSync(join(projectDir, file), "utf-8");
if (/data-composition-id/i.test(content)) {
rootCompositions.push(file);
diff --git a/packages/lint/src/rules/core.ts b/packages/lint/src/rules/core.ts
index 9ab93b8fb1..69f9e581b5 100644
--- a/packages/lint/src/rules/core.ts
+++ b/packages/lint/src/rules/core.ts
@@ -626,10 +626,14 @@ export const coreRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [
}
if (/(?:^|\s)data-no-timeline(?=[\s=/]|$)/i.test(rootTag?.attrs || "")) return [];
const findings: HyperframeLintFinding[] = [];
+ const registered = [source, ...(options.externalScripts ?? []).map((script) => script.content)];
if (
- !TIMELINE_REGISTRY_INIT_PATTERN.test(source) &&
- !TIMELINE_REGISTRY_ASSIGN_PATTERN.test(source) &&
- !TIMELINE_REGISTRY_OBJECT_LITERAL_PATTERN.test(source)
+ !registered.some(
+ (text) =>
+ TIMELINE_REGISTRY_INIT_PATTERN.test(text) ||
+ TIMELINE_REGISTRY_ASSIGN_PATTERN.test(text) ||
+ TIMELINE_REGISTRY_OBJECT_LITERAL_PATTERN.test(text),
+ )
) {
findings.push({
code: "missing_timeline_registry",
@@ -839,9 +843,9 @@ export const coreRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [
({ scripts, locate }) => {
const findings: HyperframeLintFinding[] = [];
for (const script of scripts) {
- const type = readDecodedAttr(script.raw, "type")?.trim().toLowerCase() ?? "";
- if (readDecodedAttr(script.raw, "src") !== null || SCRIPT_SYNTAX_EXEMPT_TYPES.has(type))
- continue;
+ const tag = `
+`;
+ const flagged = async (html: string) =>
+ (await lintHyperframeHtml(html)).findings.some(
+ (f) => f.code === "gsap_fullscreen_overlay_starts_visible",
+ );
+
+ it("accepts gsap.set on a querySelector call with a literal selector", async () => {
+ expect(await flagged(scene('gsap.set(root.querySelector(".ov"), { opacity: 0 });'))).toBe(
+ false,
+ );
+ });
+
+ it("accepts gsap.set on a variable bound to a querySelector call", async () => {
+ expect(
+ await flagged(scene('const ov = root.querySelector(".ov"); gsap.set(ov, { opacity: 0 });')),
+ ).toBe(false);
+ });
+
+ it("accepts a descendant selector inside the query", async () => {
+ expect(
+ await flagged(
+ scene(
+ 'gsap.set(document.querySelector("[data-composition-id=scene] .ov"), { opacity: 0 });',
+ ),
+ ),
+ ).toBe(false);
+ });
+
+ it("accepts a querySelector variable written without semicolons", async () => {
+ expect(
+ await flagged(
+ scene('const ov = root.querySelector(".ov")\n gsap.set(ov, { opacity: 0 })'),
+ ),
+ ).toBe(false);
+ });
+
+ it("still flags an overlay nothing hides at zero", async () => {
+ expect(await flagged(scene(""))).toBe(true);
+ });
+ });
+
describe("gsap_fullscreen_overlay_starts_visible — the from() shape is not a defect", () => {
const overlay = (style: string, script: string) => `
diff --git a/packages/lint/src/rules/gsap.ts b/packages/lint/src/rules/gsap.ts
index d0611c9413..fef7ced7b2 100644
--- a/packages/lint/src/rules/gsap.ts
+++ b/packages/lint/src/rules/gsap.ts
@@ -253,7 +253,10 @@ function hiddenSetTargetSelectors(target: string, aliases: Map):
return parts
.flatMap((part) => {
const trimmed = part.trim();
- const resolved = /^(["'`])([^"'`]+)\1$/.exec(trimmed)?.[2] ?? aliases.get(trimmed);
+ const resolved =
+ /^(["'`])([^"'`]+)\1$/.exec(trimmed)?.[2] ??
+ /^[\w$.]+\.querySelector(?:All)?\(\s*(["'`])([^"'`]+)\1\s*\)$/.exec(trimmed)?.[2] ??
+ aliases.get(trimmed);
return resolved === undefined ? [] : resolved.split(",");
})
.map((selector) => selector.trim())
@@ -270,8 +273,13 @@ function extractStandaloneHiddenSelectors(script: string): Set {
)) {
aliases.set(match[1] ?? "", match[3] ?? "");
}
+ for (const match of source.matchAll(
+ /(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*[\w$.]+\.querySelector(?:All)?\(\s*(["'`])([^"'`]+)\2\s*\)/g,
+ )) {
+ aliases.set(match[1] ?? "", match[3] ?? "");
+ }
const pattern =
- /gsap\.set\s*\(\s*(\[[^[\]]*\]|"[^"]*"|'[^']*'|`[^`]*`|[^,()[\]]+?)\s*,\s*\{([\s\S]*?)\}\s*\)/g;
+ /gsap\.set\s*\(\s*(\[[^[\]]*\]|"[^"]*"|'[^']*'|`[^`]*`|[\w$.]+\.querySelector(?:All)?\(\s*(?:"[^"]*"|'[^']*'|`[^`]*`)\s*\)|[^,()[\]]+?)\s*,\s*\{([\s\S]*?)\}\s*\)/g;
let match: RegExpExecArray | null;
while ((match = pattern.exec(source)) !== null) {
// Skip callback/handler bodies; keep IIFEs (they run at parse time).
@@ -1194,7 +1202,14 @@ export const gsapRules: LintRule[] = [
(win.fromPropertyValues !== undefined && isHiddenGsapState(win.fromPropertyValues))),
);
if (startsHiddenAtZero) continue;
- if (selectors.some((selector) => authoredHiddenSelectors.has(selector))) continue;
+ if (
+ selectors.some((selector) =>
+ [...authoredHiddenSelectors].some(
+ (hidden) => hidden === selector || targetedSelectorTokens(hidden).has(selector),
+ ),
+ )
+ )
+ continue;
const firstVisible = visibilityWindows.find((win) => makesOverlayVisible(win));
if (!firstVisible) continue;
const selector =
diff --git a/packages/lint/src/rules/slideshow.test.ts b/packages/lint/src/rules/slideshow.test.ts
index 4e768db96d..eb711fa02f 100644
--- a/packages/lint/src/rules/slideshow.test.ts
+++ b/packages/lint/src/rules/slideshow.test.ts
@@ -51,6 +51,18 @@ describe("slideshow lint rule", () => {
expect(findings[0]!.code).toBe("slideshow_invalid");
});
+ it.each(['"0"', "1e400"])(
+ "reports invalid slide timing %s as slideshow_invalid",
+ async (start) => {
+ const html = `
+
+
`;
+ expect(await findSlideshow(html)).toEqual([
+ expect.objectContaining({ code: "slideshow_invalid", severity: "error" }),
+ ]);
+ },
+ );
+
it.each([null, {}, { id: "h1", label: 42, target: "deep" }])(
"reports malformed hotspot %j as a structure finding without crashing lint",
async (hotspot) => {
diff --git a/packages/lint/src/types.ts b/packages/lint/src/types.ts
index 21c39e99fc..d51f008884 100644
--- a/packages/lint/src/types.ts
+++ b/packages/lint/src/types.ts
@@ -47,6 +47,13 @@ export type HyperframeLinterOptions = {
file?: string;
rootRelativePath?: string;
}>;
+ externalScripts?: Array<{
+ src: string;
+ attrs: string;
+ content: string;
+ file: string;
+ rootRelativePath: string;
+ }>;
/**
* Set to `true` when linting compositions destined for distributed / Lambda
* rendering, where system-font capture (`allowSystemFontCapture`) is
@@ -55,6 +62,7 @@ export type HyperframeLinterOptions = {
* render time — the font will silently fall back to whatever the OS provides.
*/
distributed?: boolean;
+ projectFontFamilies?: string[];
/** Who is running the lint: Studio raises the structure rules to errors, the CLI keeps them warnings. */
host?: "studio" | "cli";
};
diff --git a/packages/parsers/package.json b/packages/parsers/package.json
index 0994a8a02c..bc58e34c4f 100644
--- a/packages/parsers/package.json
+++ b/packages/parsers/package.json
@@ -1,6 +1,6 @@
{
"name": "@hyperframes/parsers",
- "version": "0.8.214",
+ "version": "0.8.224",
"repository": {
"type": "git",
"url": "https://github.com/heygen-com/hyperframes",
diff --git a/packages/parsers/src/assetPaths.test.ts b/packages/parsers/src/assetPaths.test.ts
index 9e2a530e73..31f283647b 100644
--- a/packages/parsers/src/assetPaths.test.ts
+++ b/packages/parsers/src/assetPaths.test.ts
@@ -1,7 +1,7 @@
import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
-import { isPathInside } from "./assetPaths.js";
+import { isNonRelativeUrl, isPathInside } from "./assetPaths.js";
describe("isPathInside", () => {
it("accepts the parent itself and nested children", () => {
@@ -21,3 +21,31 @@ describe("isPathInside", () => {
expect(isPathInside(resolve("/project/..intro.mp4"), resolve("/project"))).toBe(true);
});
});
+
+describe("isNonRelativeUrl", () => {
+ it("treats any URL with a scheme as non-relative", () => {
+ for (const url of [
+ "mailto:hello@example.com",
+ "tel:+15551234567",
+ "blob:https://example.com/0f6f1a7e",
+ "about:blank",
+ "javascript:void(0)",
+ "HTTPS://cdn.example.com/logo.png",
+ "Data:image/png;base64,AAAA",
+ ]) {
+ expect(isNonRelativeUrl(url), url).toBe(true);
+ }
+ });
+
+ it("keeps relative paths and Windows drive letters relative", () => {
+ for (const url of [
+ "assets/logo.png",
+ "../logo.png",
+ "./a:b.png",
+ "logo.png?v=1",
+ "C:/media/x.mp4",
+ ]) {
+ expect(isNonRelativeUrl(url), url).toBe(false);
+ }
+ });
+});
diff --git a/packages/parsers/src/assetPaths.ts b/packages/parsers/src/assetPaths.ts
index a4821134a2..ddd504ad28 100644
--- a/packages/parsers/src/assetPaths.ts
+++ b/packages/parsers/src/assetPaths.ts
@@ -19,6 +19,8 @@ export const CSS_URL_RE = /\burl\(\s*(["']?)([^)"'\s](?:[^)"']*[^)"'\s])?)\1\s*\
/** Attributes that may contain relative asset paths. */
export const PATH_ATTRS = ["src", "href"] as const;
+const URL_SCHEME_OF_TWO_OR_MORE_CHARS_RE = /^[a-z][a-z0-9+.-]+:/i;
+
/** Returns true for URLs/prefixes that should never be rewritten. */
export function isNonRelativeUrl(val: string): boolean {
return (
@@ -28,7 +30,8 @@ export function isNonRelativeUrl(val: string): boolean {
val.startsWith("//") ||
val.startsWith("data:") ||
val.startsWith("#") ||
- val.startsWith("/")
+ val.startsWith("/") ||
+ URL_SCHEME_OF_TWO_OR_MORE_CHARS_RE.test(val)
);
}
diff --git a/packages/parsers/src/assets.ts b/packages/parsers/src/assets.ts
index bc0726a5ec..409fe697a9 100644
--- a/packages/parsers/src/assets.ts
+++ b/packages/parsers/src/assets.ts
@@ -2,3 +2,4 @@
// @hyperframes/parsers/asset-paths subpath so the main entry stays browser-safe.
export * from "./assetPaths.js";
export * from "./rewriteSubCompPaths.js";
+export { rewriteSrcsetUrls } from "./srcset.js";
diff --git a/packages/parsers/src/compositionContract.ts b/packages/parsers/src/compositionContract.ts
index 1c25c58c65..cd9b41af6f 100644
--- a/packages/parsers/src/compositionContract.ts
+++ b/packages/parsers/src/compositionContract.ts
@@ -8,6 +8,9 @@
export const COMPOSITION_CONTRACT_VERSION = 1 as const;
+/** Least a split leaves either side of its cut (s); timing is written to the ms, so less rounds to a 0-length half. */
+export const SPLIT_BOUNDARY_EPSILON_S = 0.03;
+
export const COMPOSITION_ATTRIBUTES = Object.freeze({
start: "data-start",
duration: "data-duration",
@@ -222,11 +225,8 @@ function derivedEndsAreConsistent(parsedEnd: number, canonicalEnd: number): bool
//
// The compiler (`compileTimingAttrs` in @hyperframes/core) writes
// `data-end = data-start + data-duration` into the bundled HTML so the runtime
-// can key off a single attribute. That derived attribute is legitimate — it is
-// not a legacy authoring shape. Treating it as `deprecated-end` here made the
-// linter fire `deprecated_data_end` on the compiler's own output whenever
-// StaticGuard re-validated a bundled composition, producing a false-positive
-// cluster reported in the field (n=25+ across cli-feedback crons 61-68).
+// can key off a single attribute. That derived attribute is not a legacy
+// authoring shape, so the compiler's own output is never flagged.
//
// We keep `deprecated-end` for the truly legacy shape (see `readLegacyEnd` —
// `data-end` present without `data-duration`) and for the *conflicting* case
diff --git a/packages/parsers/src/ffBinaries.test.ts b/packages/parsers/src/ffBinaries.test.ts
index 6ecec82644..d28e72d73c 100644
--- a/packages/parsers/src/ffBinaries.test.ts
+++ b/packages/parsers/src/ffBinaries.test.ts
@@ -184,7 +184,7 @@ describe("findFfBinary", () => {
function installerProject(
name: "ffmpeg" | "ffprobe",
- { viaInstaller = false, mode = 0o755 } = {},
+ { viaInstaller = false, mode = 0o755, content = "" as string | Buffer } = {},
) {
const project = realpathSync(mkdtempSync(join(tmpdir(), "hf-ff-installer-")));
const platformPackage = `@${name}-installer/${process.platform}-${process.arch}`;
@@ -205,16 +205,19 @@ describe("findFfBinary", () => {
);
}
const binary = join(packageDir, process.platform === "win32" ? `${name}.exe` : name);
- writeFileSync(binary, "");
+ writeFileSync(binary, content);
chmodSync(binary, mode);
return { project, binary };
}
+ let skipped: { ffmpeg?: string; ffprobe?: string } = {};
+
async function findInProjectDir(
project: string,
name: "ffmpeg" | "ffprobe",
systemBinaries: string[] = [],
) {
+ skipped = {};
vi.stubEnv("HYPERFRAMES_FFMPEG_PATH", "");
vi.stubEnv("HYPERFRAMES_FFPROBE_PATH", "");
process.env.PATH = "";
@@ -236,8 +239,10 @@ describe("findFfBinary", () => {
return { ...mocked, default: mocked };
});
try {
- const { findFfBinary } = await importFresh();
- return findFfBinary(name);
+ const { findFfBinary, getSkippedX86Binary } = await importFresh();
+ const found = findFfBinary(name);
+ skipped = { ffmpeg: getSkippedX86Binary("ffmpeg"), ffprobe: getSkippedX86Binary("ffprobe") };
+ return found;
} finally {
vi.unstubAllEnvs();
rmSync(project, { recursive: true, force: true });
@@ -279,6 +284,50 @@ describe("findFfBinary", () => {
},
);
+ describe.skipIf(process.platform === "win32")("on Apple Silicon without Rosetta", () => {
+ const machO = (cpu: number) => Buffer.from([0xcf, 0xfa, 0xed, 0xfe, cpu, 0x00, 0x00, 0x01]);
+
+ function asAppleSilicon() {
+ Object.defineProperty(process, "platform", { value: "darwin", configurable: true });
+ vi.spyOn(process, "arch", "get").mockReturnValue("arm64");
+ }
+
+ it("skips an x86_64 installer binary", async () => {
+ asAppleSilicon();
+ const { project } = installerProject("ffprobe", { content: machO(0x07) });
+
+ expect(await findInProjectDir(project, "ffprobe")).toBeUndefined();
+ });
+
+ it("names the skipped binary under its own name only", async () => {
+ asAppleSilicon();
+ const { project, binary } = installerProject("ffprobe", { content: machO(0x07) });
+
+ await findInProjectDir(project, "ffprobe");
+
+ expect(skipped).toEqual({ ffprobe: binary });
+ });
+
+ it("skips an x86_64 binary in the project's .hyperframes/bin", async () => {
+ asAppleSilicon();
+ const project = realpathSync(mkdtempSync(join(tmpdir(), "hf-ff-local-")));
+ mkdirSync(join(project, ".hyperframes", "bin"), { recursive: true });
+ const binary = join(project, ".hyperframes", "bin", "ffprobe");
+ writeFileSync(binary, machO(0x07));
+ chmodSync(binary, 0o755);
+
+ expect(await findInProjectDir(project, "ffprobe")).toBeUndefined();
+ expect(skipped.ffprobe).toBe(binary);
+ });
+
+ it("keeps an arm64 installer binary", async () => {
+ asAppleSilicon();
+ const { project, binary } = installerProject("ffprobe", { content: machO(0x0c) });
+
+ expect(await findInProjectDir(project, "ffprobe")).toBe(binary);
+ });
+ });
+
it("returns undefined when the binary is nowhere, and caches the miss until cleared", async () => {
delete process.env.HYPERFRAMES_FFMPEG_PATH;
Object.defineProperty(process, "platform", { value: "linux", configurable: true });
@@ -345,3 +394,25 @@ describe("findFfBinary", () => {
expect(execFileSync).toHaveBeenCalledTimes(2);
});
});
+
+describe("isX86OnlyMachO", () => {
+ function fixture(bytes: number[]): string {
+ const file = join(realpathSync(mkdtempSync(join(tmpdir(), "hf-macho-"))), "ffprobe");
+ writeFileSync(file, Buffer.from(bytes));
+ onTestFinished(() => rmSync(file, { force: true }));
+ return file;
+ }
+
+ it("flags a 64-bit x86_64 Mach-O (the ffprobe-static darwin/arm64 payload)", async () => {
+ const { isX86OnlyMachO } = await importFresh();
+ expect(isX86OnlyMachO(fixture([0xcf, 0xfa, 0xed, 0xfe, 0x07, 0x00, 0x00, 0x01]))).toBe(true);
+ });
+
+ it("passes an arm64 Mach-O, a universal binary, a script and a missing file", async () => {
+ const { isX86OnlyMachO } = await importFresh();
+ expect(isX86OnlyMachO(fixture([0xcf, 0xfa, 0xed, 0xfe, 0x0c, 0x00, 0x00, 0x01]))).toBe(false);
+ expect(isX86OnlyMachO(fixture([0xca, 0xfe, 0xba, 0xbe, 0x00, 0x00, 0x00, 0x02]))).toBe(false);
+ expect(isX86OnlyMachO(fixture([0x23, 0x21, 0x2f, 0x62, 0x69, 0x6e, 0x2f, 0x73]))).toBe(false);
+ expect(isX86OnlyMachO("/nonexistent/ffprobe")).toBe(false);
+ });
+});
diff --git a/packages/parsers/src/ffBinaries.ts b/packages/parsers/src/ffBinaries.ts
index 3c91cec4de..6e7b0d1aae 100644
--- a/packages/parsers/src/ffBinaries.ts
+++ b/packages/parsers/src/ffBinaries.ts
@@ -1,7 +1,7 @@
import { execFileSync } from "node:child_process";
-import { accessSync, constants, existsSync } from "node:fs";
+import { accessSync, closeSync, constants, existsSync, openSync, readSync } from "node:fs";
import { createRequire } from "node:module";
-import { delimiter, dirname, join, resolve } from "node:path";
+import { basename, delimiter, dirname, join, resolve } from "node:path";
/**
* Shared FFmpeg/FFprobe binary resolution for every package that shells out
@@ -41,11 +41,49 @@ function chooseBestPathCandidate(
);
}
+const MACHO_CPU_X86_64 = 0x01000007;
+const ROSETTA_RUNTIME = "/Library/Apple/usr/libexec/oah/libRosettaRuntime";
+
+// A Mach-O built only for x86_64 (some npm packages ship one under darwin/arm64). A universal
+// binary or an unreadable file is not one.
+export function isX86OnlyMachO(file: string): boolean {
+ const header = Buffer.alloc(8);
+ try {
+ const fd = openSync(file, "r");
+ try {
+ readSync(fd, header, 0, 8, 0);
+ } finally {
+ closeSync(fd);
+ }
+ } catch {
+ return false;
+ }
+ return header.readUInt32LE(0) === 0xfeedfacf && header.readUInt32LE(4) === MACHO_CPU_X86_64;
+}
+
+// Without Rosetta an Apple Silicon Mac cannot run an x86_64 binary, so it must not be chosen.
+function runsOnThisMac(candidate: string): boolean {
+ if (process.platform !== "darwin" || process.arch !== "arm64" || existsSync(ROSETTA_RUNTIME)) {
+ return true;
+ }
+ if (!isX86OnlyMachO(candidate)) return true;
+ const name = basename(candidate) as FfBinaryName;
+ if (!skippedX86Binaries.has(name)) skippedX86Binaries.set(name, candidate);
+ return false;
+}
+
+const skippedX86Binaries = new Map();
+
+/** The first x86_64-only `name` binary skipped on this Mac, for naming in the "not found" hint. */
+export function getSkippedX86Binary(name: FfBinaryName): string | undefined {
+ return skippedX86Binaries.get(name);
+}
+
function isExecutablePathCandidate(candidate: string): boolean {
if (process.platform === "win32") return existsSync(candidate);
try {
accessSync(candidate, constants.X_OK);
- return true;
+ return runsOnThisMac(candidate);
} catch {
return false;
}
@@ -95,7 +133,7 @@ const COMMON_BIN_DIRS =
function findInCommonDirsOrInstallerPackage(name: FfBinaryName): string | undefined {
for (const dir of COMMON_BIN_DIRS) {
const candidate = `${dir}/${name}`;
- if (existsSync(candidate)) return candidate;
+ if (existsSync(candidate) && runsOnThisMac(candidate)) return candidate;
}
return findInInstallerPackage(name);
}
@@ -106,7 +144,7 @@ function binaryFileName(name: FfBinaryName): string {
function findInProjectLocalBin(name: FfBinaryName): string | undefined {
const candidate = resolve(".hyperframes", "bin", binaryFileName(name));
- return existsSync(candidate) ? candidate : undefined;
+ return existsSync(candidate) && runsOnThisMac(candidate) ? candidate : undefined;
}
function tryResolve(fromFile: string, request: string): string | undefined {
@@ -205,4 +243,5 @@ export function findFfBinary(
export function clearFfBinaryLookupCache(): void {
pathLookupCache.clear();
lastMissAt.clear();
+ skippedX86Binaries.clear();
}
diff --git a/packages/parsers/src/rewriteSubCompPaths.ts b/packages/parsers/src/rewriteSubCompPaths.ts
index 9bb06dac0f..618d8f256a 100644
--- a/packages/parsers/src/rewriteSubCompPaths.ts
+++ b/packages/parsers/src/rewriteSubCompPaths.ts
@@ -16,6 +16,7 @@
// submodule so Windows builds don't emit backslash-separated paths (or worse,
// drive-letter-prefixed artifacts from `resolve("/", ...)`).
import { posix } from "path";
+import { rewriteSrcsetUrls } from "./srcset.js";
const { join, resolve, dirname } = posix;
import {
@@ -111,6 +112,12 @@ export function rewriteAssetPaths(
setAttr(el, attr, rewritten);
}
}
+ const srcset = getAttr(el, "srcset");
+ if (!srcset) continue;
+ const rewritten = rewriteSrcsetUrls(srcset, (url) =>
+ rewriteAssetPath(compSrcPath, url, assetExists),
+ );
+ if (rewritten !== srcset) setAttr(el, "srcset", rewritten);
}
}
diff --git a/packages/parsers/src/slideshow/parseSlideshow.test.ts b/packages/parsers/src/slideshow/parseSlideshow.test.ts
index 3a53d42590..20b74e69d2 100644
--- a/packages/parsers/src/slideshow/parseSlideshow.test.ts
+++ b/packages/parsers/src/slideshow/parseSlideshow.test.ts
@@ -64,6 +64,22 @@ describe("parseSlideshowManifest", () => {
expect(() => parseSlideshowManifest(html)).toThrow();
});
+ it.each(['"0"', "null", "true", "{}", "[]", "1e400"])(
+ "rejects nonnumeric or nonfinite slide bounds %s in main-line and branch slides",
+ (value) => {
+ for (const field of ["startTime", "endTime"]) {
+ const slide = `{"sceneId":"a","${field}":${value}}`;
+ for (const manifest of [
+ `{"slides":[${slide}]}`,
+ `{"slides":[],"slideSequences":[{"id":"deep","label":"Deep","slides":[${slide}]}]}`,
+ ]) {
+ const html = ``;
+ expect(() => parseSlideshowManifest(html)).toThrow("not a valid SlideshowManifest");
+ }
+ }
+ },
+ );
+
it.each([
null,
42,
diff --git a/packages/parsers/src/slideshow/parseSlideshow.ts b/packages/parsers/src/slideshow/parseSlideshow.ts
index 4281d2fc73..fc68b18656 100644
--- a/packages/parsers/src/slideshow/parseSlideshow.ts
+++ b/packages/parsers/src/slideshow/parseSlideshow.ts
@@ -53,6 +53,10 @@ function isOptionalNumberArray(v: unknown): boolean {
return v === undefined || (Array.isArray(v) && v.every((n) => typeof n === "number"));
}
+function isOptionalFiniteNumber(v: unknown): v is number | undefined {
+ return v === undefined || (typeof v === "number" && Number.isFinite(v));
+}
+
function isOptionalBoolean(v: unknown): v is boolean | undefined {
return v === undefined || typeof v === "boolean";
}
@@ -84,6 +88,7 @@ function isSlideRef(v: unknown): v is SlideRef {
if (!isRecord(v)) return false;
const r = v;
if (typeof r["sceneId"] !== "string") return false;
+ if (![r["startTime"], r["endTime"]].every(isOptionalFiniteNumber)) return false;
if (!isOptionalNumberArray(r["fragments"])) return false;
if (
r["hotspots"] !== undefined &&
diff --git a/packages/parsers/src/srcset.ts b/packages/parsers/src/srcset.ts
new file mode 100644
index 0000000000..f62cdbb565
--- /dev/null
+++ b/packages/parsers/src/srcset.ts
@@ -0,0 +1,43 @@
+function skipSrcsetDescriptors(srcset: string, position: number): number {
+ let inParens = false;
+ while (position < srcset.length) {
+ const char = srcset.charAt(position++);
+ if (char === "(") inParens = true;
+ else if (char === ")") inParens = false;
+ else if (char === "," && !inParens) break;
+ }
+ return position;
+}
+
+function readSrcsetUrl(srcset: string, position: number) {
+ while (position < srcset.length && /[ \t\n\r\f,]/.test(srcset.charAt(position))) position++;
+ const start = position;
+ while (position < srcset.length && !/[ \t\n\r\f]/.test(srcset.charAt(position))) position++;
+ let end = position;
+ while (end > start && srcset.charAt(end - 1) === ",") end--;
+ return { start, end, next: position };
+}
+
+export function rewriteSrcsetUrls(srcset: string, rewriteUrl: (url: string) => string): string {
+ const parts: string[] = [];
+ let position = 0;
+ let written = 0;
+
+ // Preserve URL commas per https://html.spec.whatwg.org/multipage/images.html#parse-a-srcset-attribute
+ while (position < srcset.length) {
+ const { start, end, next } = readSrcsetUrl(srcset, position);
+ position = next;
+ if (end > start) {
+ const url = srcset.slice(start, end);
+ const rewritten = rewriteUrl(url);
+ if (rewritten !== url) {
+ parts.push(srcset.slice(written, start), rewritten);
+ written = end;
+ }
+ }
+ if (end < position) continue;
+
+ position = skipSrcsetDescriptors(srcset, position);
+ }
+ return parts.length > 0 ? parts.join("") + srcset.slice(written) : srcset;
+}
diff --git a/packages/player/package.json b/packages/player/package.json
index 8040e8cea7..43bed8d6d7 100644
--- a/packages/player/package.json
+++ b/packages/player/package.json
@@ -1,6 +1,6 @@
{
"name": "@hyperframes/player",
- "version": "0.8.214",
+ "version": "0.8.224",
"description": "Embeddable web component for HyperFrames compositions",
"repository": {
"type": "git",
diff --git a/packages/player/src/hyperframes-player.test.ts b/packages/player/src/hyperframes-player.test.ts
index c16d9e41e3..9be3c73bc9 100644
--- a/packages/player/src/hyperframes-player.test.ts
+++ b/packages/player/src/hyperframes-player.test.ts
@@ -4236,6 +4236,32 @@ describe("HyperframesPlayer asset-ready gate", () => {
player.remove();
});
+ it("shows Buffering while the runtime holds playback for a track, and hides it on resume", async () => {
+ const player = (await createConnectedPlayer()) as PlayerInternal & {
+ _onMessage: (event: MessageEvent) => void;
+ paused: boolean;
+ };
+ const showSpy = vi.spyOn(player.shaderLoader, "showAssetsLoading");
+ const post = (buffering: boolean) =>
+ player._onMessage(
+ new MessageEvent("message", {
+ source: player.iframe.contentWindow,
+ data: { source: "hf-preview", type: "state", frame: 30, isPlaying: true, buffering },
+ }),
+ );
+
+ post(true);
+ await new Promise((resolve) => setTimeout(resolve, 160));
+ expect(player.hasAttribute("buffering")).toBe(true);
+ expect(showSpy).toHaveBeenCalledWith("Buffering", "");
+ expect(player.paused).toBe(false);
+
+ post(false);
+ expect(player.hasAttribute("buffering")).toBe(false);
+
+ player.remove();
+ });
+
it("keeps a shader load drawn over the loading card when assets-loading-ui switches to none", async () => {
const player = await createConnectedPlayer();
const { doc } = createStalledVideoDoc();
diff --git a/packages/player/src/hyperframes-player.ts b/packages/player/src/hyperframes-player.ts
index b6da0c9aab..7db233f58d 100644
--- a/packages/player/src/hyperframes-player.ts
+++ b/packages/player/src/hyperframes-player.ts
@@ -52,6 +52,7 @@ const ASSETS_READY_TIMEOUT_MS = 8_000;
const ASSETS_LOADING_ATTR = "assets-loading";
// "player" (default) draws the loading-assets card; "none" never does, like shader-loading="none".
const ASSETS_LOADING_UI_ATTR = "assets-loading-ui";
+const BUFFERING_ATTR = "buffering";
const LOW_POWER_IDLE_ATTR = "low-power-idle";
const DISABLE_CLICK_TO_PLAY_ATTR = "disable-click-to-play";
const RANGE_START_ATTR = "range-start";
@@ -136,6 +137,7 @@ class HyperframesPlayer extends HTMLElement {
private _pendingPlay = false;
private _assetsGeneration = 0;
private _assetsLoadingShowTimer: ReturnType | null = null;
+ private _bufferingShowTimer: ReturnType | null = null;
private _currentTime = 0;
private _duration = 0;
private _paused = true;
@@ -450,6 +452,7 @@ class HyperframesPlayer extends HTMLElement {
}
}
if (this._media.audioOwner === "parent") this._media.playAll();
+ else this._media.primeAll();
this.controlsApi?.updatePlaying(true);
if (!queuedForReady && announce) this._emit(new Event("play"));
if (directTimelineStarted && this._directTimelineAdapter) {
@@ -1271,6 +1274,7 @@ class HyperframesPlayer extends HTMLElement {
this._rejectRuntimeDataDelivery(channel, requestId, message),
onRuntimeTimelineReady: (duration, assetsReady) =>
this._onRuntimeTimelineReady(duration, assetsReady),
+ setBuffering: (buffering) => this._setBuffering(buffering),
setRuntimeFps: (fps) => {
this._runtimeFps = fps;
},
@@ -1374,6 +1378,23 @@ class HyperframesPlayer extends HTMLElement {
}, ASSETS_LOADING_SHOW_DELAY_MS);
}
+ private _setBuffering(buffering: boolean): void {
+ if (buffering) {
+ if (this._bufferingShowTimer !== null || this.hasAttribute(BUFFERING_ATTR)) return;
+ this._bufferingShowTimer = setTimeout(() => {
+ this._bufferingShowTimer = null;
+ this.setAttribute(BUFFERING_ATTR, "");
+ if (this.assetsLoadingUi !== "none") this.shaderLoader.showAssetsLoading("Buffering", "");
+ }, ASSETS_LOADING_SHOW_DELAY_MS);
+ return;
+ }
+ if (this._bufferingShowTimer !== null) clearTimeout(this._bufferingShowTimer);
+ this._bufferingShowTimer = null;
+ if (!this.hasAttribute(BUFFERING_ATTR)) return;
+ this.removeAttribute(BUFFERING_ATTR);
+ this.shaderLoader.hideAssetsLoading();
+ }
+
private _hasPendingFirstFrameAssets(doc: Document): boolean {
const { pendingMedia, pendingImages, fontsLoading } = scanPendingCompositionAssets(doc, {
scope: FIRST_FRAME_READINESS_SCOPE,
@@ -1441,6 +1462,7 @@ class HyperframesPlayer extends HTMLElement {
this._directTimelineAdapter = null;
this._directTimelineClock.stop();
this._stopParentTickClock();
+ this._setBuffering(false);
this.shaderLoader.reset();
this._media.resetForIframeLoad();
}
diff --git a/packages/player/src/parent-media.test.ts b/packages/player/src/parent-media.test.ts
index 3a34d5329b..c6c91139ca 100644
--- a/packages/player/src/parent-media.test.ts
+++ b/packages/player/src/parent-media.test.ts
@@ -167,6 +167,34 @@ describe("ParentMediaManager audio-src proxy lifecycle", () => {
});
});
+describe("ParentMediaManager priming", () => {
+ const iPhone =
+ "Mozilla/5.0 (iPhone; CPU iPhone OS 26_5 like Mac OS X) AppleWebKit/605.1.15 Mobile/15E148";
+ afterEach(() => vi.restoreAllMocks());
+
+ function primed() {
+ const mgr = makeManager();
+ mgr.setupFromUrl("https://example.test/a.mp3");
+ const el = mgr.entries[0].el;
+ const calls: string[] = [];
+ const play = el.play.bind(el);
+ el.play = () => (calls.push("play"), play());
+ const pause = el.pause.bind(el);
+ el.pause = () => (calls.push("pause"), pause());
+ mgr.primeAll();
+ return calls;
+ }
+
+ it("plays then pauses every idle copy so iOS lets it start after the tap", () => {
+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue(iPhone);
+ expect(primed()).toEqual(["play", "pause"]);
+ });
+
+ it("leaves the copies alone where no tap is needed", () => {
+ expect(primed()).toEqual([]);
+ });
+});
+
describe("ParentMediaManager across documents", () => {
afterEach(() => document.body.replaceChildren());
diff --git a/packages/player/src/parent-media.ts b/packages/player/src/parent-media.ts
index 3c73bcb478..496bb77931 100644
--- a/packages/player/src/parent-media.ts
+++ b/packages/player/src/parent-media.ts
@@ -14,7 +14,7 @@ import { isRealmElement, isRealmHtmlMediaElement } from "./media-element-guards.
import { isInClipWindow } from "@hyperframes/core/runtime/clip-window";
import { readClipTiming } from "@hyperframes/core/composition-contract";
import { readLinkTiming } from "@hyperframes/core/media-link";
-import { mediaElementTime } from "@hyperframes/core/runtime/media-clock";
+import { mediaElementTime, startsSoundOnlyInsideATap } from "@hyperframes/core/runtime/media-clock";
import {
MEDIA_SYNC_TOLERANCE_SECONDS,
forgetSteering,
@@ -219,6 +219,16 @@ export class ParentMediaManager {
for (const m of this._entries) this._playEntryIfActive(m);
}
+ /** iOS lets an element start with sound later only if it was played inside a tap; do it for every copy. */
+ primeAll(): void {
+ if (!startsSoundOnlyInsideATap()) return;
+ for (const m of this._entries) {
+ if (!m.el.paused) continue;
+ m.el.play().catch(() => {});
+ m.el.pause();
+ }
+ }
+
pauseAll(): void {
for (const m of this._entries) m.el.pause();
}
diff --git a/packages/player/src/runtime-message-handler.ts b/packages/player/src/runtime-message-handler.ts
index 3d73ec072a..1ae13ac120 100644
--- a/packages/player/src/runtime-message-handler.ts
+++ b/packages/player/src/runtime-message-handler.ts
@@ -48,6 +48,7 @@ export interface MessageHandlerCallbacks extends PlaybackStateCallbacks {
* player uses this as the cross-origin readiness signal because the
* same-origin composition probe cannot inspect CDN iframes. */
onRuntimeTimelineReady: (duration: number, assetsReady: boolean | undefined) => void;
+ setBuffering?: (buffering: boolean) => void;
setRuntimeFps?: (fps: number) => void;
setRuntimeOwnsPlayRange?: (owns: boolean) => void;
/** Called with the scene list whenever a "timeline" message is received. */
@@ -130,6 +131,7 @@ export function handleRuntimeMessage(
callbacks,
),
);
+ callbacks.setBuffering?.(data["buffering"] === true);
return;
}
diff --git a/packages/player/src/shader-loader-state.ts b/packages/player/src/shader-loader-state.ts
index 5de4e008c3..e9005a7e1e 100644
--- a/packages/player/src/shader-loader-state.ts
+++ b/packages/player/src/shader-loader-state.ts
@@ -145,11 +145,14 @@ export class ShaderLoaderState {
/** Second reason to show the same overlay — reuses the shader-transition
* panel's DOM rather than drawing a second one. */
- showAssetsLoading(): void {
+ showAssetsLoading(
+ title = "Loading assets",
+ detail = "Waiting for images, video and fonts to finish loading.",
+ ): void {
this.reset();
- this._el.title.textContent = "Loading assets";
- this._el.detail.textContent = "Waiting for images, video and fonts to finish loading.";
- this._el.root.setAttribute("aria-label", "Loading assets");
+ this._el.title.textContent = title;
+ this._el.detail.textContent = detail;
+ this._el.root.setAttribute("aria-label", title);
this._drawingAssets = true;
this.show();
}
diff --git a/packages/player/tests/playbench/webkit-stops.ts b/packages/player/tests/playbench/webkit-stops.ts
new file mode 100644
index 0000000000..67e229eec6
--- /dev/null
+++ b/packages/player/tests/playbench/webkit-stops.ts
@@ -0,0 +1,187 @@
+#!/usr/bin/env bun
+// Plays an edit in WebKit and counts how often the playhead stands still at the cuts, how often audio is seeked,
+// and how much of the time sounding audio stands still.
+// Flags: --edit tentake|primary, --runs 3, --browser webkit|chromium|manual, --port 8099.
+// webkit drives Playwright's WebKit (`playwright-core` and `playwright-core install webkit`); manual only serves
+// /host.html and waits for a real Safari to open it, click Play and post the result.
+import { existsSync } from "node:fs";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { buildEdit, compositionHtml, type EditSpec } from "./compositions.ts";
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const PLAYER_PKG = resolve(HERE, "../..");
+const REPO = resolve(PLAYER_PKG, "../..");
+const MEDIA = join(HERE, "_media");
+const arg = (name: string, d: string) => {
+ const i = process.argv.indexOf(`--${name}`);
+ return i > 0 ? (process.argv[i + 1] ?? d) : d;
+};
+const edit = buildEdit(arg("edit", "tentake") as EditSpec["name"]);
+const RUNS = Number(arg("runs", "3"));
+const STOP_MS = 50;
+
+const gsap = [
+ join(PLAYER_PKG, "node_modules/gsap/dist/gsap.min.js"),
+ join(REPO, "node_modules/gsap/dist/gsap.min.js"),
+].find(existsSync)!;
+const file = (p: string, type: string) =>
+ new Response(Bun.file(p), { headers: { "Content-Type": type, "Cache-Control": "no-store" } });
+
+const HOST = `
+
+Play
+
+
+`;
+
+type Result = { t0: number; end: number; samples: [number, number, string?][]; seeks?: number };
+
+/** Share of sounding-audio time an element's clock stood still for more than STOP_MS. */
+function audioFrozenPct(s: Result["samples"]): number {
+ let playing = 0;
+ let frozen = 0;
+ const since = new Map();
+ for (const [at, , els] of s) {
+ for (const entry of (els ?? "").split(" ").filter(Boolean)) {
+ const [id, rest] = entry.split(":");
+ const time = rest!.replace(/S?\d$/, "");
+ const last = since.get(id!);
+ if (last) playing += at - last.prev;
+ if (!last || last.time !== time) since.set(id!, { time, at, prev: at });
+ else {
+ if (at - last.at > STOP_MS) frozen += at - Math.max(last.prev, last.at + STOP_MS);
+ last.prev = at;
+ }
+ }
+ }
+ return playing > 0 ? Math.round((frozen / playing) * 1000) / 10 : 0;
+}
+
+/** Stops are runs where the playhead stood still for more than STOP_MS, each tied to the cut it started at. */
+export function measure(r: Result, cuts: number[]) {
+ const s = r.samples;
+ const stops: { at: number; ms: number }[] = [];
+ let from = 0;
+ for (let i = 1; i <= s.length; i++) {
+ if (i < s.length && s[i]![1] === s[from]![1]) continue;
+ const ms = (i < s.length ? s[i]![0] : r.end) - s[from]![0];
+ if (ms > STOP_MS && s[from]![1] > 0.5) stops.push({ at: s[from]![1], ms });
+ from = i;
+ }
+ const perCut = cuts.map((c) => stops.filter((x) => x.at >= c - 0.3 && x.at < c + 1.5));
+ const played = (r.end - r.t0) / 1000;
+ return {
+ seeks: r.seeks ?? 0,
+ audioFrozenPct: audioFrozenPct(s),
+ stops: stops.length,
+ stopsPerCut: stops.length / cuts.length,
+ longestMs: Math.round(Math.max(0, ...stops.map((x) => x.ms))),
+ cutsWithStop: perCut.filter((c) => c.length).length,
+ cuts: cuts.length,
+ last: s.length ? Math.round(s[s.length - 1]![1] * 100) / 100 : 0,
+ worst: [...stops]
+ .sort((a, b) => b.ms - a.ms)
+ .slice(0, 4)
+ .map((x) => `${x.at.toFixed(2)}s:${Math.round(x.ms)}ms`),
+ overrunS: Math.round((played - edit.duration) * 10) / 10,
+ };
+}
+
+const results: Result[] = [];
+const TRACE = process.argv.includes("--trace");
+let resolveResult: (() => void) | null = null;
+const server = Bun.serve({
+ port: Number(arg("port", "0")),
+ async fetch(req) {
+ const p = new URL(req.url).pathname;
+ const html = (b: string) => new Response(b, { headers: { "Content-Type": "text/html" } });
+ if (p === "/host.html") return html(HOST);
+ if (p === "/comp.html") return html(compositionHtml(edit, "/media"));
+ if (p === "/player.js")
+ return file(join(PLAYER_PKG, "dist/hyperframes-player.global.js"), "text/javascript");
+ if (p === "/vendor/hyperframe.runtime.iife.js")
+ return file(join(REPO, "packages/core/dist/hyperframe.runtime.iife.js"), "text/javascript");
+ if (p === "/vendor/gsap.min.js") return file(gsap, "text/javascript");
+ if (p === "/result") {
+ results.push((await req.json()) as Result);
+ resolveResult?.();
+ return new Response("ok");
+ }
+ if (p.startsWith("/media/")) {
+ const f = Bun.file(join(MEDIA, p.slice(7)));
+ const m = /^bytes=(\d+)-(\d*)$/.exec(req.headers.get("range") ?? "");
+ const h: Record = { "Content-Type": "video/mp4", "Accept-Ranges": "bytes" };
+ if (!m) return new Response(f, { headers: h });
+ const a = Number(m[1]);
+ const b = m[2] ? Math.min(Number(m[2]), f.size - 1) : f.size - 1;
+ h["Content-Range"] = `bytes ${a}-${b}/${f.size}`;
+ return new Response(f.slice(a, b + 1), { status: 206, headers: h });
+ }
+ return new Response("not found", { status: 404 });
+ },
+});
+const cuts = edit.takes.slice(1).map((t) => t.start);
+const origin = `http://127.0.0.1:${server.port}`;
+
+async function drivePlaywright(engine: "webkit" | "chromium") {
+ const name = "playwright-core"; // not a dependency: installed by hand, so kept out of the type check
+ const pw = (await import(name)) as Record; // oxlint-disable-line no-explicit-any
+ const browser = await pw[engine]!.launch({
+ executablePath: process.env.PLAYBENCH_BROWSER_PATH,
+ args: engine === "chromium" ? ["--autoplay-policy=no-user-gesture-required"] : [],
+ });
+ console.log(`${engine} ${browser.version()}`);
+ for (let i = 0; i < RUNS; i++) {
+ const page = await browser.newPage();
+ await page.goto(`${origin}/host.html`);
+ await page.waitForFunction(() => document.querySelector("hyperframes-player") !== null);
+ await page.waitForTimeout(8000); // media load
+ const done = new Promise((r) => (resolveResult = r));
+ await page.click("#go");
+ await done;
+ await page.close();
+ }
+ await browser.close();
+}
+
+const engine = arg("browser", "webkit");
+if (engine === "webkit" || engine === "chromium") await drivePlaywright(engine);
+else {
+ console.log(`open ${origin}/host.html in Safari, click Play (${RUNS} runs)`);
+ while (results.length < RUNS) await new Promise((r) => (resolveResult = r));
+}
+console.log(`${edit.name}: ${edit.takes.length} takes, ${edit.duration} s, ${RUNS} runs`);
+for (const [i, r] of results.entries()) {
+ console.log(`run ${i + 1}`, JSON.stringify(measure(r, cuts)));
+ if (TRACE) {
+ const w = measure(r, cuts).worst[0];
+ const at = w ? Number(w.split("s:")[0]) : 0;
+ const j = r.samples.findIndex((x) => x[1] >= at);
+ for (const x of r.samples.slice(Math.max(0, j - 6), j + 40))
+ console.log(` ${(x[0] - r.t0).toFixed(0)}ms t=${x[1].toFixed(3)} ${x[2]}`);
+ }
+}
+server.stop(true);
+process.exit(0);
diff --git a/packages/producer/package.json b/packages/producer/package.json
index 8f5b79037d..c086b9bff6 100644
--- a/packages/producer/package.json
+++ b/packages/producer/package.json
@@ -1,6 +1,6 @@
{
"name": "@hyperframes/producer",
- "version": "0.8.214",
+ "version": "0.8.224",
"description": "HTML-to-video rendering engine using Chrome's BeginFrame API",
"repository": {
"type": "git",
diff --git a/packages/producer/scripts/integration-tests.json b/packages/producer/scripts/integration-tests.json
index 1c5a9be944..3c0ce782cc 100644
--- a/packages/producer/scripts/integration-tests.json
+++ b/packages/producer/scripts/integration-tests.json
@@ -16,6 +16,7 @@
"src/services/distributed/planSizeCap.test.ts",
"src/services/distributed/planV2RemoteFiles.test.ts",
"src/services/distributed/renderChunk.test.ts",
+ "src/services/distributed/renderSpan.integration.test.ts",
"src/services/fileServer.test.ts",
"src/services/fileServer.file-race.test.ts",
"src/services/fileServer.listenError.test.ts",
diff --git a/packages/producer/src/index.ts b/packages/producer/src/index.ts
index 7d8193a7dc..1af687c293 100644
--- a/packages/producer/src/index.ts
+++ b/packages/producer/src/index.ts
@@ -24,6 +24,13 @@ export {
type RenderPerfSummary,
type ProgressCallback,
} from "./services/renderOrchestrator.js";
+export {
+ renderSpan,
+ RenderSpanUnsupportedError,
+ spanFrameRange,
+ type RenderSpanResult,
+} from "./services/distributed/renderSpan.js";
+export { extractSafeRenderErrorCode } from "./services/safeRenderErrorCode.js";
export {
RENDER_JOB_DIR,
createOwnedRenderDir,
diff --git a/packages/producer/src/server.ts b/packages/producer/src/server.ts
index 6fe066c83b..2f056e2131 100644
--- a/packages/producer/src/server.ts
+++ b/packages/producer/src/server.ts
@@ -51,6 +51,9 @@ import {
} from "@hyperframes/core";
import { parseEncoderOptions } from "@hyperframes/studio-server/encoder-options";
import { createRenderRequest, renderConfigFromRequest } from "./renderRequest.js";
+import { extractSafeRenderErrorCode } from "./services/safeRenderErrorCode.js";
+
+export { extractSafeRenderErrorCode };
// ---------------------------------------------------------------------------
// Types
@@ -128,29 +131,6 @@ interface PreparedRenderInput {
const DEFAULT_SERVER_FPS = { num: 30, den: 1 } as const;
const SSE_KEEPALIVE_MS = 30_000;
-const SAFE_RENDER_ERROR_CODES = new Set([
- "ASSET_MEDIA_TYPE_MISMATCH",
- "HEIF_IMAGE_CONVERSION_FAILED",
- "HEIF_TOOL_UNAVAILABLE",
- "NOT_MEDIA_PAYLOAD",
- "INVALID_VIDEO_METADATA",
- "VIDEO_SOURCE_UNRENDERABLE",
- "VIDEO_EXTRACTION_FAILED",
- "ENCODER_INTERRUPTED",
- "RENDER_TOO_SLOW",
- "RENDER_STAGE_STALLED",
-]);
-
-/**
- * Preserve only bounded producer error codes across JSON/SSE. Never derive a
- * code from the message: it may contain local paths or signed source URLs.
- */
-export function extractSafeRenderErrorCode(error: unknown): string | undefined {
- if (typeof error !== "object" || error === null || !("code" in error)) return undefined;
- const code = error.code;
- return typeof code === "string" && SAFE_RENDER_ERROR_CODES.has(code) ? code : undefined;
-}
-
export interface SafeRenderErrorMetadata {
errorCode: string;
errorOwner?: "system" | "user";
diff --git a/packages/producer/src/services/distributed/assemble.test.ts b/packages/producer/src/services/distributed/assemble.test.ts
index eee102dc5d..4f654757f1 100644
--- a/packages/producer/src/services/distributed/assemble.test.ts
+++ b/packages/producer/src/services/distributed/assemble.test.ts
@@ -684,7 +684,7 @@ describe("assemble()", () => {
it("cfr re-encode keeps the chunks' rate control", () => {
expect(cfrRateControlArgs({})).toEqual(["-preset", "medium", "-crf", "18"]);
- expect(cfrRateControlArgs({ quality: "high" })).toEqual(["-preset", "slow", "-crf", "15"]);
+ expect(cfrRateControlArgs({ quality: "high" })).toEqual(["-preset", "fast", "-crf", "15"]);
expect(cfrRateControlArgs({ quality: "standard", crf: 12 })).toEqual([
"-preset",
"medium",
diff --git a/packages/producer/src/services/distributed/renderSpan.integration.test.ts b/packages/producer/src/services/distributed/renderSpan.integration.test.ts
new file mode 100644
index 0000000000..db28a2abcc
--- /dev/null
+++ b/packages/producer/src/services/distributed/renderSpan.integration.test.ts
@@ -0,0 +1,129 @@
+import { afterAll, beforeAll, describe, expect, it } from "bun:test";
+import { spawnSync } from "node:child_process";
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { createRenderJob, executeRenderJob, RenderCancelledError } from "../renderOrchestrator.js";
+import { renderSpan } from "./renderSpan.js";
+
+const ROOT_HTML = `
+
+
+
+
+
+`;
+
+const SUB_HTML = `
+
+
+
+ `;
+
+function frames(path: string): Buffer[] {
+ const out = spawnSync(
+ "ffmpeg",
+ ["-v", "error", "-i", path, "-f", "rawvideo", "-pix_fmt", "rgb24", "-"],
+ { maxBuffer: 1 << 28 },
+ );
+ const size = 160 * 90 * 3;
+ const all = out.stdout;
+ return Array.from({ length: Math.floor(all.length / size) }, (_, i) =>
+ all.subarray(i * size, (i + 1) * size),
+ );
+}
+
+function meanDiff(a: Buffer, b: Buffer): number {
+ let sum = 0;
+ for (let i = 0; i < a.length; i++) sum += Math.abs(a[i]! - b[i]!);
+ return sum / a.length;
+}
+
+describe("renderSpan", () => {
+ let root: string;
+ let projectDir: string;
+
+ beforeAll(() => {
+ root = mkdtempSync(join(tmpdir(), "hf-render-span-"));
+ projectDir = join(root, "project");
+ mkdirSync(join(projectDir, "compositions"), { recursive: true });
+ writeFileSync(join(projectDir, "index.html"), ROOT_HTML);
+ writeFileSync(join(projectDir, "compositions", "sub.html"), SUB_HTML);
+ });
+
+ afterAll(() => rmSync(root, { recursive: true, force: true }));
+
+ it("renders the frames of the span the way a full render renders them, sub-composition included", async () => {
+ const fullPath = join(root, "full.mp4");
+ const job = createRenderJob({ fps: { num: 30, den: 1 }, quality: "draft", format: "mp4" });
+ await executeRenderJob(job, projectDir, fullPath);
+
+ const spanPath = join(root, "span.mp4");
+ const { framesEncoded } = await renderSpan(
+ projectDir,
+ { fps: 30, width: 160, height: 90, format: "mp4", quality: "draft", hdrMode: "force-sdr" },
+ { startSeconds: 0.5, endSeconds: 2 },
+ spanPath,
+ );
+ expect(framesEncoded).toBe(45);
+
+ const full = frames(fullPath);
+ const span = frames(spanPath);
+ expect(span.length).toBe(45);
+ const worstMatch = Math.max(...span.map((frame, i) => meanDiff(frame, full[15 + i]!)));
+ // The backdrop brightens about 2.8 levels a frame, so a span one frame off its place misses by more than this.
+ expect(worstMatch).toBeLessThan(1.5);
+ const oneFrameLate = span.map((frame, i) => meanDiff(frame, full[16 + i]!));
+ expect(Math.min(...oneFrameLate)).toBeGreaterThan(worstMatch);
+ }, 240_000);
+
+ it("stops when it is cancelled after planning, with no output written", async () => {
+ const scratch = join(root, "scratch");
+ mkdirSync(scratch, { recursive: true });
+ const previousTmp = process.env.TMPDIR;
+ process.env.TMPDIR = scratch;
+ const controller = new AbortController();
+ const outputPath = join(root, "cancelled.mp4");
+ try {
+ const running = renderSpan(
+ projectDir,
+ {
+ fps: 30,
+ width: 160,
+ height: 90,
+ format: "mp4",
+ quality: "draft",
+ hdrMode: "force-sdr",
+ chunkSize: 15,
+ abortSignal: controller.signal,
+ },
+ { startSeconds: 0 },
+ outputPath,
+ );
+ const firstPart = () =>
+ readdirSync(scratch).some((dir) =>
+ existsSync(join(scratch, dir, "parts", "part-0000.mp4")),
+ );
+ while (!firstPart()) await new Promise((done) => setTimeout(done, 20));
+ controller.abort();
+ await expect(running).rejects.toBeInstanceOf(RenderCancelledError);
+ expect(existsSync(outputPath)).toBe(false);
+ } finally {
+ if (previousTmp === undefined) delete process.env.TMPDIR;
+ else process.env.TMPDIR = previousTmp;
+ }
+ }, 240_000);
+});
diff --git a/packages/producer/src/services/distributed/renderSpan.test.ts b/packages/producer/src/services/distributed/renderSpan.test.ts
new file mode 100644
index 0000000000..c09b592277
--- /dev/null
+++ b/packages/producer/src/services/distributed/renderSpan.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from "bun:test";
+import { RenderSpanUnsupportedError, spanFrameRange } from "./renderSpan.js";
+
+describe("spanFrameRange", () => {
+ it("is the frames the seconds cover, to the end when --end is absent", () => {
+ expect(spanFrameRange(0.5, 1.5, 30, 90)).toEqual({ startFrame: 15, endFrame: 45 });
+ expect(spanFrameRange(1, undefined, 30, 90)).toEqual({ startFrame: 30, endFrame: 90 });
+ });
+
+ it("stops at the last frame of the film", () => {
+ expect(spanFrameRange(2, 9, 30, 90)).toEqual({ startFrame: 60, endFrame: 90 });
+ });
+
+ it("refuses a range with no frame, naming how long the film is", () => {
+ expect(() => spanFrameRange(3, 4, 30, 90)).toThrow(RenderSpanUnsupportedError);
+ expect(() => spanFrameRange(3, 4, 30, 90)).toThrow("90 frames at 30 fps (3s)");
+ });
+});
diff --git a/packages/producer/src/services/distributed/renderSpan.ts b/packages/producer/src/services/distributed/renderSpan.ts
new file mode 100644
index 0000000000..a75b26226e
--- /dev/null
+++ b/packages/producer/src/services/distributed/renderSpan.ts
@@ -0,0 +1,101 @@
+import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+import type { ChunkSliceJson } from "../render/stages/freezePlan.js";
+import { writeStitchedMp4 } from "./mp4Stitch.js";
+import { plan, type DistributedRenderConfig } from "./plan.js";
+import { renderChunk } from "./renderChunk.js";
+import { RenderCancelledError } from "../renderOrchestrator.js";
+
+export interface RenderSpanResult {
+ startFrame: number;
+ endFrame: number;
+ framesEncoded: number;
+}
+
+export class RenderSpanUnsupportedError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "RenderSpanUnsupportedError";
+ }
+}
+
+/** The frames `[startFrame, endFrame)` of a `totalFrames` timeline that `[startSeconds, endSeconds)` covers. */
+export function spanFrameRange(
+ startSeconds: number,
+ endSeconds: number | undefined,
+ fps: number,
+ totalFrames: number,
+): { startFrame: number; endFrame: number } {
+ const startFrame = Math.round(startSeconds * fps);
+ const endFrame = Math.min(
+ endSeconds === undefined ? totalFrames : Math.round(endSeconds * fps),
+ totalFrames,
+ );
+ if (!(endFrame > startFrame)) {
+ throw new RenderSpanUnsupportedError(
+ `The range ${startSeconds}s to ${endSeconds ?? "the end"}s holds no frame: the composition has ${totalFrames} frames at ${fps} fps (${totalFrames / fps}s).`,
+ );
+ }
+ return { startFrame, endFrame };
+}
+
+function throwIfAborted(signal: AbortSignal | undefined): void {
+ if (signal?.aborted) throw new RenderCancelledError("render_cancelled", "user_cancelled");
+}
+
+/** Renders `[startSeconds, endSeconds)` as a standalone mp4 from 0, with that span's audio, by chunk sub-ranges. */
+export async function renderSpan(
+ projectDir: string,
+ config: DistributedRenderConfig,
+ span: { startSeconds: number; endSeconds?: number },
+ outputPath: string,
+): Promise {
+ if (config.format !== "mp4") {
+ throw new RenderSpanUnsupportedError(
+ `--start/--end render mp4 only; ${config.format} is not supported for a range.`,
+ );
+ }
+ if (config.cfr === true) {
+ throw new RenderSpanUnsupportedError("--start/--end cannot be combined with a cfr re-encode.");
+ }
+ const workDir = mkdtempSync(join(tmpdir(), "hf-render-span-"));
+ try {
+ const planDir = join(workDir, "plan");
+ const partsDir = join(workDir, "parts");
+ mkdirSync(partsDir, { recursive: true });
+ // The span captures here in the browser a full render uses, so the container-only font guards do not apply.
+ const planned = await plan(
+ projectDir,
+ { ...config, rejectOnSystemFonts: false, failClosedFontFetch: false },
+ planDir,
+ { chunksCarryAudio: true },
+ );
+ const { startFrame, endFrame } = spanFrameRange(
+ span.startSeconds,
+ span.endSeconds,
+ config.fps,
+ planned.totalFrames,
+ );
+ const slices = JSON.parse(
+ readFileSync(join(planDir, "meta", "chunks.json"), "utf-8"),
+ ) as ChunkSliceJson[];
+ const parts: string[] = [];
+ for (const slice of slices) {
+ const range = {
+ startFrame: Math.max(slice.startFrame, startFrame),
+ endFrame: Math.min(slice.endFrame, endFrame),
+ };
+ if (range.endFrame <= range.startFrame) continue;
+ throwIfAborted(config.abortSignal);
+ const part = join(partsDir, `part-${String(parts.length).padStart(4, "0")}.mp4`);
+ await renderChunk(planDir, slice.index, part, { frameRange: range });
+ parts.push(part);
+ }
+ throwIfAborted(config.abortSignal);
+ await writeStitchedMp4(parts, outputPath);
+ return { startFrame, endFrame, framesEncoded: endFrame - startFrame };
+ } finally {
+ rmSync(workDir, { recursive: true, force: true });
+ }
+}
diff --git a/packages/producer/src/services/htmlCompiler.test.ts b/packages/producer/src/services/htmlCompiler.test.ts
index 7c81bfeba7..4ecaa9ea02 100644
--- a/packages/producer/src/services/htmlCompiler.test.ts
+++ b/packages/producer/src/services/htmlCompiler.test.ts
@@ -861,7 +861,8 @@ describe("detectRenderModeHints", () => {
entryPath,
`
`,
@@ -874,6 +875,12 @@ describe("detectRenderModeHints", () => {
"compositions/sibling.png",
);
expect(document.querySelector("#root")?.getAttribute("src")).toBe("root.png");
+ expect(document.querySelector("#sibling")?.getAttribute("srcset")).toBe(
+ "compositions/sibling.png 1x",
+ );
+ expect(document.querySelector("#responsive")?.getAttribute("srcset")).toBe(
+ "compositions/sibling.png 1x, root.png 2x",
+ );
});
it("reads the root's data-fx-chain as the composition's master chain, apart from any clip", async () => {
diff --git a/packages/producer/src/services/htmlCompiler.ts b/packages/producer/src/services/htmlCompiler.ts
index 72857aab2c..54a32d482d 100644
--- a/packages/producer/src/services/htmlCompiler.ts
+++ b/packages/producer/src/services/htmlCompiler.ts
@@ -118,6 +118,7 @@ export interface CompiledComposition {
audios: AudioElement[];
images: ImageElement[];
droppedMediaIds: Set;
+ gradedCanvas: boolean;
masterFxChain?: string;
unresolvedCompositions: UnresolvedElement[];
/** Assets that resolve outside projectDir. Keys are the path used in HTML, values are absolute filesystem paths. */
@@ -2007,7 +2008,7 @@ function rebaseDirectEntryAssetPaths(html: string, projectDir: string, htmlPath:
const { document } = parseHTML(html);
const assetExists = (path: string) => existsSync(resolve(projectDir, path));
rewriteAssetPaths(
- document.querySelectorAll("[src], [href]"),
+ document.querySelectorAll("[src], [href], [srcset]"),
entryPath,
(el: Element, attr: string) => el.getAttribute(attr),
(el: Element, attr: string, value: string) => el.setAttribute(attr, value),
@@ -2236,7 +2237,7 @@ export async function compileForRender(
// within one composition file: two scenes declaring `` — or
// two bare ``s, both auto-numbered `hf-video-0` — collapsed into one
// entry and injected frames onto whichever element came first. See #3340.
- const { videos, audios, images, droppedMediaIds } = collectRenderMedia(html);
+ const { videos, audios, images, droppedMediaIds, gradedCanvas } = collectRenderMedia(html);
const masterFxChain = parseMasterFxChain(html);
// Advisory video checks (sparse keyframes, VFR). Fire-and-forget — these spawn
@@ -2294,6 +2295,7 @@ export async function compileForRender(
audios,
images,
droppedMediaIds,
+ gradedCanvas,
...(masterFxChain ? { masterFxChain } : {}),
unresolvedCompositions,
externalAssets,
diff --git a/packages/producer/src/services/render/hdrMode.test.ts b/packages/producer/src/services/render/hdrMode.test.ts
index 0664a526f6..56922101cd 100644
--- a/packages/producer/src/services/render/hdrMode.test.ts
+++ b/packages/producer/src/services/render/hdrMode.test.ts
@@ -7,7 +7,14 @@
import { describe, expect, it, vi } from "vitest";
import type { ExtractionResult, VideoColorSpace } from "@hyperframes/engine";
-import { findRenderHdrAutoPromotionTrigger, resolveEffectiveHdrMode } from "./hdrMode.js";
+import {
+ findRenderHdrAutoPromotionTrigger,
+ rendersSdrOnly,
+ resolveEffectiveHdrMode,
+} from "./hdrMode.js";
+
+const NO_MEDIA = { videos: [], images: [] };
+const GRADED_VIDEO = { videos: [{ graded: true }, {}], images: [] };
function makeLog() {
return { error: vi.fn(), warn: vi.fn(), info: vi.fn(), debug: vi.fn() };
@@ -37,9 +44,41 @@ const HDR_PQ: VideoColorSpace = {
};
describe("resolveEffectiveHdrMode", () => {
+ it("keeps an auto render with graded media SDR when an HDR source would promote it, and says why", () => {
+ const log = makeLog();
+ const result = resolveEffectiveHdrMode({
+ media: GRADED_VIDEO,
+ hdrMode: "auto",
+ outputFormat: "mp4",
+ extractionResult: extractionWith([HDR_PQ]),
+ imageColorSpaces: [],
+ log,
+ });
+ expect(result).toBeUndefined();
+ expect(log.warn).toHaveBeenCalledWith(expect.stringContaining("color grading is SDR-only"));
+ expect(log.warn).not.toHaveBeenCalledWith(expect.stringContaining("auto-promotion"));
+ });
+
+ it("keeps --hdr with graded media HDR and warns that the grades are SDR", () => {
+ const log = makeLog();
+ const result = resolveEffectiveHdrMode({
+ media: { videos: [], images: [{ graded: true }] },
+ hdrMode: "force-hdr",
+ outputFormat: "mp4",
+ extractionResult: extractionWith([HDR_PQ]),
+ imageColorSpaces: [],
+ log,
+ });
+ expect(result).toEqual({ transfer: "pq" });
+ expect(log.warn).toHaveBeenCalledWith(
+ expect.stringContaining("graded elements are graded in SDR"),
+ );
+ });
+
it("returns undefined when force-sdr is set, regardless of HDR sources", () => {
const log = makeLog();
const result = resolveEffectiveHdrMode({
+ media: NO_MEDIA,
hdrMode: "force-sdr",
outputFormat: "mp4",
extractionResult: extractionWith([HDR_PQ]),
@@ -53,6 +92,7 @@ describe("resolveEffectiveHdrMode", () => {
it("auto-detects HDR from video sources when format=mp4", () => {
const log = makeLog();
const result = resolveEffectiveHdrMode({
+ media: NO_MEDIA,
hdrMode: undefined,
outputFormat: "mp4",
extractionResult: extractionWith([HDR_PQ]),
@@ -71,6 +111,7 @@ describe("resolveEffectiveHdrMode", () => {
it("auto-detects SDR with no HDR sources", () => {
const log = makeLog();
const result = resolveEffectiveHdrMode({
+ media: NO_MEDIA,
hdrMode: "auto",
outputFormat: "mp4",
extractionResult: extractionWith([]),
@@ -84,6 +125,7 @@ describe("resolveEffectiveHdrMode", () => {
it("force-hdr without sources falls back to HLG and warns", () => {
const log = makeLog();
const result = resolveEffectiveHdrMode({
+ media: NO_MEDIA,
hdrMode: "force-hdr",
outputFormat: "mp4",
extractionResult: extractionWith([]),
@@ -99,6 +141,7 @@ describe("resolveEffectiveHdrMode", () => {
it("force-hdr uses the dominant probed transfer when sources are HDR", () => {
const log = makeLog();
const result = resolveEffectiveHdrMode({
+ media: NO_MEDIA,
hdrMode: "force-hdr",
outputFormat: "mp4",
extractionResult: extractionWith([HDR_PQ]),
@@ -113,6 +156,7 @@ describe("resolveEffectiveHdrMode", () => {
for (const fmt of ["webm", "mov", "png-sequence"] as const) {
const log = makeLog();
const result = resolveEffectiveHdrMode({
+ media: NO_MEDIA,
hdrMode: "auto",
outputFormat: fmt,
extractionResult: extractionWith([HDR_PQ]),
@@ -135,6 +179,7 @@ describe("resolveEffectiveHdrMode", () => {
it("downgrades auto-detected HDR on hls with an SDR-only reason, not the alpha one", () => {
const log = makeLog();
const result = resolveEffectiveHdrMode({
+ media: NO_MEDIA,
hdrMode: "auto",
outputFormat: "hls",
extractionResult: extractionWith([HDR_PQ]),
@@ -154,6 +199,7 @@ describe("resolveEffectiveHdrMode", () => {
it("force-hdr without sources + non-mp4 format: still downgrades, two warns fire", () => {
const log = makeLog();
const result = resolveEffectiveHdrMode({
+ media: NO_MEDIA,
hdrMode: "force-hdr",
outputFormat: "webm",
extractionResult: extractionWith([]),
@@ -202,3 +248,11 @@ describe("findRenderHdrAutoPromotionTrigger", () => {
).toBe("assets/hero.png");
});
});
+
+describe("rendersSdrOnly", () => {
+ it("is true for an auto render with graded media, so HDR sources are tone-mapped before the grade", () => {
+ expect(rendersSdrOnly({ hdrMode: undefined, format: "mp4" }, GRADED_VIDEO)).toBe(true);
+ expect(rendersSdrOnly({ hdrMode: "auto", format: "mp4" }, NO_MEDIA)).toBe(false);
+ expect(rendersSdrOnly({ hdrMode: "force-hdr", format: "mp4" }, GRADED_VIDEO)).toBe(false);
+ });
+});
diff --git a/packages/producer/src/services/render/hdrMode.ts b/packages/producer/src/services/render/hdrMode.ts
index 7e2d4c6f0e..9160e021ba 100644
--- a/packages/producer/src/services/render/hdrMode.ts
+++ b/packages/producer/src/services/render/hdrMode.ts
@@ -12,6 +12,7 @@
import {
analyzeCompositionHdr,
formatHdrAutoPromotionWarning,
+ gradingKeepsSdr,
HDR_AUTO_PROMOTION_PIPELINE,
isHdrColorSpace,
sanitizeHdrAutoPromotionAsset,
@@ -21,8 +22,10 @@ import type { ProducerLogger } from "../../logger.js";
import type { RenderConfig } from "../renderOrchestrator.js";
type EffectiveHdr = { transfer: HdrTransfer } | undefined;
+type RenderMedia = Parameters[1];
type HdrModeInput = {
hdrMode: RenderConfig["hdrMode"];
+ media: RenderMedia;
outputFormat: NonNullable;
extractionResult: ExtractionResult | null | undefined;
imageColorSpaces: (VideoColorSpace | null)[];
@@ -69,18 +72,41 @@ export function findRenderHdrAutoPromotionTrigger(input: {
return input.images.find(({ id }) => input.nativeHdrImageIds.has(id))?.src;
}
+/** Warns when grading decided the output or will be wrong in it; true when it kept an HDR source's render SDR. */
+function logGradingResolution(
+ input: HdrModeInput,
+ hdrMode: NonNullable,
+ effectiveHdr: EffectiveHdr,
+ hasHdrSource: boolean,
+): boolean {
+ const keptSdr = hasHdrSource && gradingKeepsSdr(hdrMode, input.media);
+ if (keptSdr) {
+ input.log.warn(
+ "[Render] HDR source detected, but color grading is SDR-only, so rendering SDR: HDR sources are tone-mapped before the grade. Use --hdr to force HDR output (grades stay SDR).",
+ );
+ } else if (effectiveHdr && [...input.media.videos, ...input.media.images].some((m) => m.graded)) {
+ input.log.warn(
+ "[Render] HDR output with graded media: color grading is SDR-only, so graded elements are graded in SDR and placed in the HDR output.",
+ );
+ }
+ return keptSdr;
+}
+
function logHdrResolution(
input: HdrModeInput,
hdrMode: NonNullable,
effectiveHdr: EffectiveHdr,
forcedHdrWithoutSources: boolean,
+ hasHdrSource: boolean,
): void {
+ const keptSdrForGrading = logGradingResolution(input, hdrMode, effectiveHdr, hasHdrSource);
if (forcedHdrWithoutSources) {
input.log.warn(
"[Render] HDR forced by --hdr flag, but no HDR sources were detected, defaulting to HLG. SDR-only compositions may look perceptually wrong on HDR displays.",
);
}
if (!effectiveHdr) {
+ if (keptSdrForGrading) return;
input.log.info(
hdrMode === "force-sdr"
? "[Render] SDR forced by --sdr flag"
@@ -111,8 +137,15 @@ function formatCarriesHdr(format: NonNullable): boolean
return format === "mp4";
}
-export function rendersSdrOnly(config: Pick): boolean {
- return config.hdrMode === "force-sdr" || !formatCarriesHdr(config.format ?? "mp4");
+export function rendersSdrOnly(
+ config: Pick,
+ media: RenderMedia,
+): boolean {
+ return (
+ config.hdrMode === "force-sdr" ||
+ gradingKeepsSdr(config.hdrMode, media) ||
+ !formatCarriesHdr(config.format ?? "mp4")
+ );
}
export function resolveEffectiveHdrMode(input: HdrModeInput): EffectiveHdr {
@@ -126,7 +159,7 @@ export function resolveEffectiveHdrMode(input: HdrModeInput): EffectiveHdr {
let effectiveHdr: EffectiveHdr;
let forcedHdrWithoutSources = false;
- if (hdrMode === "force-sdr") {
+ if (hdrMode === "force-sdr" || gradingKeepsSdr(hdrMode, input.media)) {
effectiveHdr = undefined;
} else if (hdrMode === "force-hdr") {
if (info?.hasHdr && info.dominantTransfer) {
@@ -144,7 +177,7 @@ export function resolveEffectiveHdrMode(input: HdrModeInput): EffectiveHdr {
effectiveHdr = undefined;
}
- logHdrResolution(input, hdrMode, effectiveHdr, forcedHdrWithoutSources);
+ logHdrResolution(input, hdrMode, effectiveHdr, forcedHdrWithoutSources, info?.hasHdr === true);
return effectiveHdr;
}
diff --git a/packages/producer/src/services/render/observability.test.ts b/packages/producer/src/services/render/observability.test.ts
index 373661d0f1..e1fee535d4 100644
--- a/packages/producer/src/services/render/observability.test.ts
+++ b/packages/producer/src/services/render/observability.test.ts
@@ -186,6 +186,57 @@ describe("RenderObservabilityRecorder", () => {
vi.useRealTimers();
});
+ it("puts where the stage was waiting in its stall message", async () => {
+ vi.useFakeTimers();
+ const recorder = new RenderObservabilityRecorder({
+ pipelineStartMs: Date.now(),
+ log: makeLog(),
+ renderJobId: "render-stall-detail",
+ });
+ const stage = observeRenderStage(
+ recorder,
+ "capture_disk",
+ undefined,
+ () => new Promise(() => {}),
+ {
+ stall: {
+ progress: () => 0,
+ noProgressMs: 10_000,
+ firstProgressMs: 10_000,
+ detail: () => "Last phase per worker: worker 1 session_init.",
+ },
+ },
+ );
+ const caught = stage.catch((error: unknown) => error);
+ await vi.advanceTimersByTimeAsync(20_000);
+ expect(((await caught) as Error).message).toBe(
+ "[Render] capture_disk stalled: no progress for 10000ms (stuck at 0). Last phase per worker: worker 1 session_init.",
+ );
+ vi.useRealTimers();
+ });
+
+ it("tells the stall rule each time a capture attempt opens", async () => {
+ const recorder = new RenderObservabilityRecorder({
+ pipelineStartMs: Date.now(),
+ log: makeLog(),
+ renderJobId: "render-attempt-opened",
+ });
+ const attemptOpened = vi.fn();
+ await observeRenderStage(
+ recorder,
+ "capture_disk",
+ undefined,
+ async (openAttempt) => {
+ openAttempt();
+ openAttempt();
+ },
+ {
+ stall: { progress: () => 0, noProgressMs: 10_000, firstProgressMs: 10_000, attemptOpened },
+ },
+ );
+ expect(attemptOpened).toHaveBeenCalledTimes(2);
+ });
+
it("keeps emitting heartbeats every 120s once the initial ramp is exhausted", async () => {
vi.useFakeTimers();
const log = makeLog();
diff --git a/packages/producer/src/services/render/observability.ts b/packages/producer/src/services/render/observability.ts
index fad56b6e53..64027108c0 100644
--- a/packages/producer/src/services/render/observability.ts
+++ b/packages/producer/src/services/render/observability.ts
@@ -613,6 +613,8 @@ export interface StageStallRule {
complete?: () => boolean;
/** Allowed silence once `complete()` holds; defaults to `noProgressMs`. */
tailMs?: number;
+ detail?: () => string | undefined;
+ attemptOpened?: () => void;
}
/**
@@ -624,10 +626,10 @@ export class RenderStageStalledError extends CaptureFailure {
readonly owner = "system" as const;
readonly retryable = false as const;
- constructor(phase: string, silentMs: number, progress: number) {
+ constructor(phase: string, silentMs: number, progress: number, detail?: string) {
super({
kind: "protocol_timeout",
- message: `[Render] ${phase} stalled: no progress for ${silentMs}ms (stuck at ${progress}).`,
+ message: `[Render] ${phase} stalled: no progress for ${silentMs}ms (stuck at ${progress}).${detail ? ` ${detail}` : ""}`,
});
this.name = "RenderStageStalledError";
}
@@ -641,6 +643,7 @@ const STALL_POLL_MS = 5_000;
// A trip aborts the open attempt and gives the stage one more window to retry or settle; a trip with
// no live attempt fails the stage.
function watchStall(phase: string, rule: StageStallRule) {
+ const detail = rule.detail ?? (() => undefined);
let last = rule.progress();
let budgetMs = rule.firstProgressMs;
let lastChangeAt = Date.now();
@@ -662,7 +665,7 @@ function watchStall(phase: string, rule: StageStallRule) {
}
if (current !== last) return restartWindow(rule.noProgressMs);
if (Date.now() - lastChangeAt < budgetMs) return;
- const error = new RenderStageStalledError(phase, budgetMs, current);
+ const error = new RenderStageStalledError(phase, budgetMs, current, detail());
if (attempt && !attempt.signal.aborted) {
attempt.abort(error);
return restartWindow(rule.noProgressMs);
@@ -676,6 +679,7 @@ function watchStall(phase: string, rule: StageStallRule) {
const openAttempt: OpenStallAttempt = (parent) => {
attempt = new AbortController();
inTail = false;
+ rule.attemptOpened?.();
restartWindow(rule.firstProgressMs);
return parent ? AbortSignal.any([parent, attempt.signal]) : attempt.signal;
};
diff --git a/packages/producer/src/services/render/perfSummary.test.ts b/packages/producer/src/services/render/perfSummary.test.ts
index 28e6c8bb94..cd386b8479 100644
--- a/packages/producer/src/services/render/perfSummary.test.ts
+++ b/packages/producer/src/services/render/perfSummary.test.ts
@@ -75,3 +75,26 @@ describe("buildRenderPerfSummary drawElement gate reason", () => {
expect(summary.drawElement?.gateReason).toBe("css_effect:filter");
});
});
+
+describe("buildRenderPerfSummary capture phases", () => {
+ it("weights each worker's phase averages by the frames it captured", () => {
+ const summary = buildRenderPerfSummary({
+ ...baseInput,
+ perfStages: { encoderDrainWaitMs: 1500 },
+ dedupPerfs: [
+ { frames: 100, avgSeekMs: 10, avgBeforeCaptureMs: 4, avgScreenshotMs: 30 },
+ { frames: 50, avgSeekMs: 40, avgBeforeCaptureMs: 1, avgScreenshotMs: 60 },
+ ],
+ } as Parameters[0]);
+ expect(summary.captureSeekAvgMs).toBe(20);
+ expect(summary.captureBeforeCaptureAvgMs).toBe(3);
+ expect(summary.captureScreenshotAvgMs).toBe(40);
+ expect(summary.encoderWaitAvgMs).toBe(10);
+ });
+
+ it("leaves the phases unset when no frames or no streaming encoder ran", () => {
+ const summary = buildRenderPerfSummary(baseInput);
+ expect(summary.captureSeekAvgMs).toBeUndefined();
+ expect(summary.encoderWaitAvgMs).toBeUndefined();
+ });
+});
diff --git a/packages/producer/src/services/render/perfSummary.ts b/packages/producer/src/services/render/perfSummary.ts
index 8d0ef0f001..c3d5fdd7eb 100644
--- a/packages/producer/src/services/render/perfSummary.ts
+++ b/packages/producer/src/services/render/perfSummary.ts
@@ -242,6 +242,15 @@ function aggregateChromeMemory(perfs: CapturePerfSummary[]): RenderPerfSummary["
};
}
+function frameWeightedAvgMs(
+ perfs: CapturePerfSummary[],
+ avgOf: (perf: CapturePerfSummary) => number,
+): number | undefined {
+ const frames = perfs.reduce((sum, p) => sum + p.frames, 0);
+ if (frames === 0) return undefined;
+ return Math.round(perfs.reduce((sum, p) => sum + avgOf(p) * p.frames, 0) / frames);
+}
+
function aggregateDedup(perfs: CapturePerfSummary[]): RenderPerfSummary["staticDedup"] {
if (perfs.length === 0) return undefined;
const armed = perfs.some((p) => p.staticDedupArmed);
@@ -407,6 +416,13 @@ export function buildRenderPerfSummary(input: {
if (withSamples.length === 0) return undefined;
return withSamples.reduce((a, b) => (b.frames > a.frames ? b : a)).p50TotalMs;
})(),
+ captureSeekAvgMs: frameWeightedAvgMs(input.dedupPerfs, (p) => p.avgSeekMs),
+ captureBeforeCaptureAvgMs: frameWeightedAvgMs(input.dedupPerfs, (p) => p.avgBeforeCaptureMs),
+ captureScreenshotAvgMs: frameWeightedAvgMs(input.dedupPerfs, (p) => p.avgScreenshotMs),
+ encoderWaitAvgMs:
+ input.perfStages.encoderDrainWaitMs !== undefined && input.totalFrames > 0
+ ? Math.round(input.perfStages.encoderDrainWaitMs / input.totalFrames)
+ : undefined,
peakRssMb: Math.round(input.peakRssBytes / (1024 * 1024)),
peakHeapUsedMb: Math.round(input.peakHeapUsedBytes / (1024 * 1024)),
staticDedup: aggregateDedup(input.dedupPerfs),
diff --git a/packages/producer/src/services/render/shared.test.ts b/packages/producer/src/services/render/shared.test.ts
index 56c5d167b6..7015908923 100644
--- a/packages/producer/src/services/render/shared.test.ts
+++ b/packages/producer/src/services/render/shared.test.ts
@@ -2,8 +2,11 @@ import { describe, expect, it, setSystemTime } from "bun:test";
import type { ParallelProgress } from "@hyperframes/engine";
import type { RenderJob } from "../renderOrchestrator.js";
import {
+ describeWorkerPhases,
+ forgetWorkerPhases,
reportAssembleProgress,
reportEncodeProgress,
+ reportExtractProgress,
reportFrameProgress,
reportWorkerStartup,
resolveBrowserMediaEnd,
@@ -60,6 +63,30 @@ describe("reportWorkerStartup", () => {
});
});
+describe("describeWorkerPhases", () => {
+ it("names the last phase each worker reported, and nothing before any did", () => {
+ const job = { progress: 25 } as RenderJob;
+ expect(describeWorkerPhases(job)).toBeUndefined();
+ const phase = (workerId: number, name: string) =>
+ reportWorkerStartup(
+ job,
+ {
+ activeWorkers: 2,
+ latestWorkerPhase: { workerId, phase: name },
+ } as unknown as ParallelProgress,
+ undefined,
+ );
+ phase(0, "browser_launch");
+ phase(1, "session_init");
+ phase(0, "frame_capture");
+ expect(describeWorkerPhases(job)).toBe(
+ "Last phase per worker: worker 0 frame_capture, worker 1 session_init.",
+ );
+ forgetWorkerPhases(job);
+ expect(describeWorkerPhases(job)).toBeUndefined();
+ });
+});
+
describe("stage progress for machines", () => {
const job = () => ({ progress: 0, status: "rendering" }) as unknown as RenderJob;
const heard = (j: RenderJob) => {
@@ -80,6 +107,23 @@ describe("stage progress for machines", () => {
]);
});
+ it("moves extract_video from 10 to 20 by frames done", () => {
+ const j = job();
+ const { seen, onProgress } = heard(j);
+ reportExtractProgress(j, 0, 40, onProgress);
+ reportExtractProgress(j, 40, 40, onProgress);
+ expect(seen).toEqual([
+ { stage: "Extracting video frames", progress: 10, code: "extract_video", done: 0, total: 40 },
+ {
+ stage: "Extracting video frames",
+ progress: 20,
+ code: "extract_video",
+ done: 40,
+ total: 40,
+ },
+ ]);
+ });
+
it("moves encode from where capture left the bar to 90, never back", () => {
const j = job();
j.progress = 80;
diff --git a/packages/producer/src/services/render/shared.ts b/packages/producer/src/services/render/shared.ts
index a98e841260..1b7e64d60d 100644
--- a/packages/producer/src/services/render/shared.ts
+++ b/packages/producer/src/services/render/shared.ts
@@ -47,6 +47,7 @@ export interface CompositionMetadata {
videos: VideoElement[];
audios: AudioElement[];
images: ImageElement[];
+ gradedCanvas?: boolean;
masterFxChain?: string;
width: number;
height: number;
@@ -319,6 +320,29 @@ export function reportFrameProgress(
});
}
+const lastExtractReportAt = new WeakMap();
+
+/** Frames ffmpeg has written for the source videos, 10% to 20%. */
+export function reportExtractProgress(
+ job: RenderJob,
+ done: number,
+ total: number,
+ onProgress: ProgressCallback | undefined,
+): void {
+ if (total <= 0) return;
+ const frames = Math.min(done, total);
+ reportThrottled(
+ lastExtractReportAt,
+ job,
+ "Extracting video frames",
+ 10 + (10 * frames) / total,
+ onProgress,
+ frames === total,
+ { code: "extract_video", done: frames, total },
+ "preprocessing",
+ );
+}
+
const lastEncodeReportAt = new WeakMap();
/** Frames ffmpeg has encoded, from where capture left the bar up to 90%; same cadence as capture. */
@@ -366,7 +390,17 @@ export function reportAssembleProgress(
);
}
-const workerPhasesByJob = new WeakMap>();
+const workerPhasesByJob = new WeakMap>();
+
+export function forgetWorkerPhases(job: object): void {
+ workerPhasesByJob.delete(job);
+}
+
+export function describeWorkerPhases(job: object): string | undefined {
+ const phases = workerPhasesByJob.get(job);
+ if (!phases?.size) return undefined;
+ return `Last phase per worker: ${[...phases].map(([id, phase]) => `worker ${id} ${phase}`).join(", ")}.`;
+}
/** Browser warm-up before the first frame, from the parallel workers' phase events. */
export function reportWorkerStartup(
diff --git a/packages/producer/src/services/render/stages/captureHdrStage.ts b/packages/producer/src/services/render/stages/captureHdrStage.ts
index a45948da9d..0dfea38d66 100644
--- a/packages/producer/src/services/render/stages/captureHdrStage.ts
+++ b/packages/producer/src/services/render/stages/captureHdrStage.ts
@@ -129,6 +129,7 @@ export interface CaptureHdrStageResult {
captureDurationMs: number;
/** ffmpeg-reported encode duration; overlapped with capture. */
encodeMs: number;
+ encoderDrainWaitMs?: number;
warnings: CaptureWarning[];
}
@@ -174,6 +175,7 @@ export async function runCaptureHdrStage(
let lastBrowserConsole: string[] = [];
let captureDurationMs = 0;
let encodeMs = 0;
+ let encoderDrainWaitMs: number | undefined;
const nativeHdrIds = new Set([...nativeHdrVideoIds, ...nativeHdrImageIds]);
log.info(
@@ -446,6 +448,7 @@ export async function runCaptureHdrStage(
reportEncodeProgress(job, totalFrames, totalFrames, onProgress, encodeFrom);
captureDurationMs = Date.now() - stageStart;
encodeMs = hdrEncodeResult.durationMs;
+ encoderDrainWaitMs = hdrEncodeResult.drainWaitMs;
} catch (error) {
lastBrowserConsole = domSession.browserConsoleBuffer;
throw wrapCaptureStageError(error, lastBrowserConsole);
@@ -479,6 +482,7 @@ export async function runCaptureHdrStage(
hdrPerf,
captureDurationMs,
encodeMs,
+ encoderDrainWaitMs,
warnings: cloneCaptureWarnings(domSession.warnings),
};
}
diff --git a/packages/producer/src/services/render/stages/captureSegmentedStage.test.ts b/packages/producer/src/services/render/stages/captureSegmentedStage.test.ts
index 359852ae46..f570068e5b 100644
--- a/packages/producer/src/services/render/stages/captureSegmentedStage.test.ts
+++ b/packages/producer/src/services/render/stages/captureSegmentedStage.test.ts
@@ -265,7 +265,7 @@ describe("runCaptureSegmentedStage", () => {
written.push({ segment: outputPath, frame: buf.readUInt32BE(0) });
return true;
},
- close: async () => ({ success: true, durationMs: 5, fileSize: 1 }),
+ close: async () => ({ success: true, durationMs: 5, fileSize: 1, drainWaitMs: 2 }),
getExitStatus: () => "success" as const,
getExitError: () => undefined,
};
@@ -286,6 +286,9 @@ describe("runCaptureSegmentedStage", () => {
});
expect(result.success).toBe(true);
+ if (!result.success) throw new Error("unreachable");
+ expect(result.encodeMs).toBe(15);
+ expect(result.encoderDrainWaitMs).toBe(6);
expect(encoders).toEqual([
segmentOutputPath(join(fixtureRoot, "segments"), 0),
segmentOutputPath(join(fixtureRoot, "segments"), 1),
diff --git a/packages/producer/src/services/render/stages/captureSegmentedStage.ts b/packages/producer/src/services/render/stages/captureSegmentedStage.ts
index 678cbb0b00..7b5f69f8d3 100644
--- a/packages/producer/src/services/render/stages/captureSegmentedStage.ts
+++ b/packages/producer/src/services/render/stages/captureSegmentedStage.ts
@@ -31,6 +31,7 @@ import {
type CaptureSession,
type EngineConfig,
type StreamingEncoder,
+ type StreamingEncoderResult,
} from "@hyperframes/engine";
import type { FileServerHandle } from "../../fileServer.js";
import type { ProducerLogger } from "../../../logger.js";
@@ -124,6 +125,7 @@ export type CaptureSegmentedStageResult =
| {
success: true;
encodeMs: number;
+ encoderDrainWaitMs?: number;
probeSession: null;
lastBrowserConsole: string[];
workerCount: number;
@@ -226,8 +228,11 @@ async function captureSegmentFrames(
}
}
-/** Capture one segment into its own encoder. Returns the encoder's encode ms. */
-async function captureSegment(ctx: SegmentCaptureContext, segment: SegmentSlice): Promise {
+/** Capture one segment into its own encoder. Returns the encoder's result. */
+async function captureSegment(
+ ctx: SegmentCaptureContext,
+ segment: SegmentSlice,
+): Promise {
const segmentPath = segmentOutputPath(ctx.segmentDir, segment.index);
let encoder: StreamingEncoder;
try {
@@ -260,7 +265,7 @@ async function captureSegment(ctx: SegmentCaptureContext, segment: SegmentSlice)
// finished; absent only in unit tests, whose fake encoder writes none.
bytes: existsSync(segmentPath) ? statSync(segmentPath).size : 0,
});
- return encodeResult.durationMs;
+ return encodeResult;
} finally {
// A throw above (capture failure, abort, write error) leaves ffmpeg
// running; close() is idempotent so this is safe next to the success
@@ -367,6 +372,7 @@ interface SegmentWorker {
/** Counters shared by every worker; JS is single-threaded, so += is safe. */
interface SegmentTotals {
encodeMs: number;
+ encoderDrainWaitMs: number;
segmentRetries: number;
browserRecycles: number;
}
@@ -493,7 +499,12 @@ async function retryAfterTargetLoss(
// so a retry also restarts the cadence clock. Intended: the fresh browser
// is as new as a cadence restart would have made it.
await recycleWorkerSession(run, worker, "retry");
- run.totals.encodeMs += await captureSegment(worker.ctx, segment);
+ addSegmentEncode(run.totals, await captureSegment(worker.ctx, segment));
+}
+
+function addSegmentEncode(totals: SegmentTotals, result: StreamingEncoderResult): void {
+ totals.encodeMs += result.durationMs;
+ totals.encoderDrainWaitMs += result.drainWaitMs ?? 0;
}
async function runOneSegment(
@@ -510,7 +521,7 @@ async function runOneSegment(
segmentIndex: segment.index,
});
try {
- run.totals.encodeMs += await captureSegment(worker.ctx, segment);
+ addSegmentEncode(run.totals, await captureSegment(worker.ctx, segment));
} catch (err) {
if (err instanceof SegmentEncoderSpawnError) return onSegmentSpawnFailure(run, err, segment);
await retryAfterTargetLoss(run, worker, err, segment, segmentPath);
@@ -566,7 +577,7 @@ export async function runCaptureSegmentedStage(
const run: SegmentRun = {
input,
deps,
- totals: { encodeMs: 0, segmentRetries: 0, browserRecycles: 0 },
+ totals: { encodeMs: 0, encoderDrainWaitMs: 0, segmentRetries: 0, browserRecycles: 0 },
segments,
pending,
segmentDir,
@@ -632,6 +643,7 @@ export async function runCaptureSegmentedStage(
return {
success: true,
encodeMs: run.totals.encodeMs,
+ encoderDrainWaitMs: run.totals.encoderDrainWaitMs,
probeSession: null,
lastBrowserConsole,
workerCount: run.workerCount,
diff --git a/packages/producer/src/services/render/stages/captureStreamingStage.test.ts b/packages/producer/src/services/render/stages/captureStreamingStage.test.ts
index f64a6b10dd..49788768a5 100644
--- a/packages/producer/src/services/render/stages/captureStreamingStage.test.ts
+++ b/packages/producer/src/services/render/stages/captureStreamingStage.test.ts
@@ -19,7 +19,12 @@ type MinimalEngineConfig = {
};
const writeFrame = mock((_buffer: Buffer) => true);
-const closeEncoder = mock(async () => ({ success: true, durationMs: 123, fileSize: 42 }));
+const closeEncoder = mock(async () => ({
+ success: true,
+ durationMs: 123,
+ fileSize: 42,
+ drainWaitMs: 7,
+}));
const spawnStreamingEncoder = mock(async () => ({
writeFrame,
close: closeEncoder,
@@ -1193,6 +1198,7 @@ describe("runCaptureHdrStage", () => {
);
expect(closeEncoder).toHaveBeenCalledTimes(1);
expect(result.encodeMs).toBe(123);
+ expect(result.encoderDrainWaitMs).toBe(7);
});
it("wraps HDR capture failures with the browser console buffer", async () => {
diff --git a/packages/producer/src/services/render/stages/captureStreamingStage.ts b/packages/producer/src/services/render/stages/captureStreamingStage.ts
index e7d53d4173..ad9a1dcbcf 100644
--- a/packages/producer/src/services/render/stages/captureStreamingStage.ts
+++ b/packages/producer/src/services/render/stages/captureStreamingStage.ts
@@ -316,6 +316,7 @@ export type CaptureStreamingStageResult =
success: true;
/** Wall-clock ms for the encode phase (overlapped with capture; from the encoder's own report). */
encodeMs: number;
+ encoderDrainWaitMs?: number;
probeSession: CaptureSession | null;
lastBrowserConsole: string[];
workerCount: number;
@@ -1132,6 +1133,7 @@ export async function runCaptureStreamingStage(
return {
success: true,
encodeMs: encodeResult.durationMs,
+ encoderDrainWaitMs: encodeResult.drainWaitMs,
probeSession,
lastBrowserConsole,
workerCount,
diff --git a/packages/producer/src/services/render/stages/compileStage.ts b/packages/producer/src/services/render/stages/compileStage.ts
index f9bfda8d75..08957fcdb3 100644
--- a/packages/producer/src/services/render/stages/compileStage.ts
+++ b/packages/producer/src/services/render/stages/compileStage.ts
@@ -298,6 +298,7 @@ export async function runCompileStage(input: CompileStageInput): Promise;
+ onProgress?: ProgressCallback;
}
export interface ExtractVideosStageResult {
@@ -412,12 +419,14 @@ export async function runExtractVideosStage(
// Probe ORIGINAL color spaces before extraction (which may convert SDR→HDR).
// This is needed to identify which videos are natively HDR vs converted-SDR
- // for the two-pass compositing path. Skipped only in force-sdr mode to
- // avoid ffprobe overhead when the user has explicitly opted out.
+ // for the two-pass compositing path. Skipped when the render is SDR anyway:
+ // force-sdr, or auto mode with graded media (grading is SDR-only).
+ const probesHdr =
+ job.config.hdrMode !== "force-sdr" && !gradingKeepsSdr(job.config.hdrMode, composition);
const nativeHdrVideoIds = new Set();
const videoTransfers = new Map();
let hdrProbeTransientRetries = 0;
- if (job.config.hdrMode !== "force-sdr" && composition.videos.length > 0) {
+ if (probesHdr && composition.videos.length > 0) {
log?.info("Probing video color spaces...", { videoCount: composition.videos.length });
const probeFailures = await Promise.all(
composition.videos.map(async (v) => {
@@ -467,14 +476,13 @@ export async function runExtractVideosStage(
// Probe images for HDR color spaces (16-bit PNGs tagged BT.2020 PQ/HLG).
// Mirrors the video probe loop above so image-only compositions can
- // trigger HDR output without any video sources present. Skipped only in
- // force-sdr mode to avoid ffprobe overhead when the user has explicitly
- // opted out.
+ // trigger HDR output without any video sources present. Skipped when the
+ // video probe is.
const nativeHdrImageIds = new Set();
const imageTransfers = new Map();
const hdrImageSrcPaths = new Map();
const imageColorSpaces: (VideoColorSpace | null)[] = [];
- if (job.config.hdrMode !== "force-sdr" && composition.images.length > 0) {
+ if (probesHdr && composition.images.length > 0) {
const probed = await Promise.all(
composition.images.map(async (img) => {
// Same shared resolver as the video probe above — a percent-encoded
@@ -504,6 +512,8 @@ export async function runExtractVideosStage(
safeVideoExtractionSourceLogMetadata(v.src),
);
}
+ let framesPlanned = 0;
+ let framesDone = 0;
extractionResult = await extractAllVideoFrames(
composition.videos,
projectDir,
@@ -514,13 +524,18 @@ export async function runExtractVideosStage(
fps: job.config.fps,
outputDir: join(compiledDir, "__hyperframes_video_frames"),
format: job.config.videoFrameFormat ?? "auto",
- toneMapHdrToSdr: rendersSdrOnly(job.config),
+ toneMapHdrToSdr: rendersSdrOnly(job.config, composition),
timelineEnd: composition.duration,
maxTransientRetries: extractionPolicy.maxTransientRetries,
collectProbeFailures: extractionPolicy.failureMode === "enforce",
deferRangeExtraction,
contentKeyedDirs: [join(compiledDir, REMOTE_MEDIA_SUBDIR)],
urlByAbsentLocalPath,
+ onProgress: ({ planned = 0, done = 0 }) => {
+ framesPlanned += planned;
+ framesDone += done;
+ reportExtractProgress(job, framesDone, framesPlanned, input.onProgress);
+ },
},
abortSignal,
cfg,
diff --git a/packages/producer/src/services/renderMediaCollector.ts b/packages/producer/src/services/renderMediaCollector.ts
index e14aa059a2..bcd89aa6ff 100644
--- a/packages/producer/src/services/renderMediaCollector.ts
+++ b/packages/producer/src/services/renderMediaCollector.ts
@@ -26,6 +26,7 @@ import {
} from "@hyperframes/core/media-timing";
import {
parseVideoElements,
+ hasGradedCanvas,
parseImageElements,
parseAudioElements,
isSelfOrAncestorHidden,
@@ -211,6 +212,7 @@ export interface RenderMedia {
images: ImageElement[];
/** Ids of clips in the document that never play; the browser probe must not add them back. */
droppedMediaIds: Set;
+ gradedCanvas: boolean;
}
/**
@@ -261,7 +263,7 @@ export function collectRenderMedia(html: string): RenderMedia {
else droppedMediaIds.add(elementId);
}
- return { videos, audios, images, droppedMediaIds };
+ return { videos, audios, images, droppedMediaIds, gradedCanvas: hasGradedCanvas(html) };
}
function placeAudio(audio: AudioElement, window: HostWindow): AudioElement | null {
diff --git a/packages/producer/src/services/renderOrchestrator.test.ts b/packages/producer/src/services/renderOrchestrator.test.ts
index 8f28f4653b..8901773ff2 100644
--- a/packages/producer/src/services/renderOrchestrator.test.ts
+++ b/packages/producer/src/services/renderOrchestrator.test.ts
@@ -58,6 +58,7 @@ import {
calibrationCaptureConfig,
shouldPreferParallelDrawElement,
shouldPreferSingleWorkerDrawElement,
+ initialDeClampReason,
resolveDeSingleMinFrames,
isCaptureParallelStreamRouterEnabled,
shouldSegmentCapture,
@@ -1973,6 +1974,36 @@ describe("resolveDeviceScaleFactor", () => {
});
});
+describe("initialDeClampReason", () => {
+ const config = {
+ platform: "win32" as const,
+ browserGpuMode: "hardware" as const,
+ workerEncode: true,
+ };
+
+ it("labels a content gate from the compile stage as compile_gate, not disabled", () => {
+ expect(initialDeClampReason({ useDrawElement: false, deCompileGate: "3d", config })).toBe(
+ "compile_gate",
+ );
+ });
+
+ it("keeps config refusals and leaves an engaged render unlabeled", () => {
+ expect(initialDeClampReason({ useDrawElement: false, deCompileGate: undefined, config })).toBe(
+ "disabled",
+ );
+ expect(
+ initialDeClampReason({
+ useDrawElement: false,
+ deCompileGate: undefined,
+ config: { ...config, browserGpuMode: "software" },
+ }),
+ ).toBe("software_gpu");
+ expect(
+ initialDeClampReason({ useDrawElement: true, deCompileGate: undefined, config }),
+ ).toBeUndefined();
+ });
+});
+
describe("shouldPreferSingleWorkerDrawElement (DE priority inversion)", () => {
const eligible = {
workerCount: 5,
diff --git a/packages/producer/src/services/renderOrchestrator.ts b/packages/producer/src/services/renderOrchestrator.ts
index 9d4abc0ba1..b4bee80f17 100644
--- a/packages/producer/src/services/renderOrchestrator.ts
+++ b/packages/producer/src/services/renderOrchestrator.ts
@@ -134,7 +134,13 @@ import {
resolveDeliveryEncoderOptions,
validateDeliveryEncoderConfig,
} from "./render/deliveryEncoder.js";
-import { createMemorySampler, type MemorySampler, updateJobStatus } from "./render/shared.js";
+import {
+ createMemorySampler,
+ describeWorkerPhases,
+ forgetWorkerPhases,
+ type MemorySampler,
+ updateJobStatus,
+} from "./render/shared.js";
import { frameCacheOptions } from "./render/frameCacheBudget.js";
import { buildRenderErrorDetails } from "./render/cleanup.js";
import { publishRenderFailure } from "./render/renderEventPublisher.js";
@@ -513,6 +519,11 @@ export interface RenderPerfSummary {
* captured the most frames when parallel workers report separately.
*/
captureP50Ms?: number;
+ /** Per-frame capture phases, frame-weighted across sessions; encoder wait is FFmpeg back-pressure. */
+ captureSeekAvgMs?: number;
+ captureBeforeCaptureAvgMs?: number;
+ captureScreenshotAvgMs?: number;
+ encoderWaitAvgMs?: number;
/** Worst sub-composition timeline wait outcome across sessions. */
subTimelineWait?: SubTimelineWaitOutcome;
capturePeakMs?: number;
@@ -1186,6 +1197,8 @@ export function frameStallRule(
firstProgressMs: Math.max(FIRST_FRAME_STALL_MS, noProgressMs),
complete: () => (job.framesRendered ?? 0) >= totalFrames,
tailMs: Math.max(TAIL_STALL_MS, noProgressMs),
+ detail: () => describeWorkerPhases(job),
+ attemptOpened: () => forgetWorkerPhases(job),
};
}
@@ -2286,6 +2299,17 @@ export function shouldPreferSingleWorkerDrawElement(args: {
);
}
+/** Why drawElement is off before capture; the compile stage's content gates are not config refusals. */
+export function initialDeClampReason(args: {
+ useDrawElement: boolean;
+ deCompileGate: string | undefined;
+ config: Parameters[0];
+}): string | undefined {
+ if (args.useDrawElement) return undefined;
+ if (args.deCompileGate) return "compile_gate";
+ return explainDrawElementDisabled(args.config);
+}
+
/**
* The session kept drawElement but left some frames to a screenshot session. Only the
* single-worker streaming capture hands those over, so parallel drawElement must not be chosen.
@@ -3265,14 +3289,16 @@ async function executeRenderPipeline(input: {
// "Why not drawElement", explaining nothing). Re-derived from the same
// inputs `resolveConfig` used, so it cannot disagree with the decision.
// Later clamps overwrite this: a more specific reason always wins.
- let deClampReason: string | undefined = cfg.useDrawElement
- ? undefined
- : explainDrawElementDisabled({
- platform: process.platform,
- browserGpuMode: cfg.browserGpuMode,
- workerEncode: cfg.enableDrawElementWorkerEncode,
- chromeCeiling: chromeMajorCeiling(),
- });
+ let deClampReason = initialDeClampReason({
+ useDrawElement: cfg.useDrawElement,
+ deCompileGate,
+ config: {
+ platform: process.platform,
+ browserGpuMode: cfg.browserGpuMode,
+ workerEncode: cfg.enableDrawElementWorkerEncode,
+ chromeCeiling: chromeMajorCeiling(),
+ },
+ });
// "inverted" = fired and held; "reverted" = fired but the self-verify
// retry rolled back to the parallel path; undefined = never fired.
let deWorkerInversion: "inverted" | "reverted" | undefined;
@@ -3464,6 +3490,7 @@ async function executeRenderPipeline(input: {
assertNotAborted,
// Local staging can use links; distributed plan() alone requires real copies.
materializeSymlinks: false,
+ onProgress,
}),
);
const {
@@ -3530,6 +3557,7 @@ async function executeRenderPipeline(input: {
});
const effectiveHdr = resolveEffectiveHdrMode({
hdrMode: job.config.hdrMode,
+ media: composition,
outputFormat,
extractionResult,
imageColorSpaces,
@@ -3683,6 +3711,15 @@ async function executeRenderPipeline(input: {
// sample frame indices from this so they land inside the drained range.
compositionDurationSeconds: job.duration,
deFrameFallback: true,
+ // A line per scanned chunk, so a long effect scan reads as preparing, not as a stall.
+ onEffectScanProgress: (scanned, total) =>
+ updateJobStatus(
+ job,
+ "rendering",
+ `Checking effects, ${scanned} of ${total} frames`,
+ 25,
+ onProgress,
+ ),
requiresWebGpu: compositionRequiresWebGpu(compiled.html),
// Live route for Chrome memory (spec §5 Phase −1). The aggregate route
// through CapturePerfSummary only exists on success; a mid-capture
@@ -4704,6 +4741,7 @@ async function executeRenderPipeline(input: {
perfStages.captureFrameMs = hdrRes.captureDurationMs;
perfStages.captureSetupMs = Math.max(0, Date.now() - stage4Start - hdrRes.captureDurationMs);
perfStages.encodeMs = hdrRes.encodeMs;
+ perfStages.encoderDrainWaitMs = hdrRes.encoderDrainWaitMs ?? 0;
} else {
// ── Standard capture paths (SDR or DOM-only HDR) ──────────────────
// Streaming encode mode pipes frame buffers directly to FFmpeg stdin,
@@ -4905,6 +4943,7 @@ async function executeRenderPipeline(input: {
perfStages.captureFrameMs = Date.now() - captureFrameStart;
perfStages.captureSetupMs = Math.max(0, perfStages.captureMs - perfStages.captureFrameMs);
perfStages.encodeMs = segmentedRes.encodeMs;
+ perfStages.encoderDrainWaitMs = segmentedRes.encoderDrainWaitMs ?? 0;
log.info(
`[Render] Segmented capture complete: ${segmentedRes.segments} segment(s) concatenated.`,
{
@@ -5161,6 +5200,7 @@ async function executeRenderPipeline(input: {
perfStages.captureFrameMs = captureFrameMs;
perfStages.captureSetupMs = Math.max(0, perfStages.captureMs - captureFrameMs);
perfStages.encodeMs = streamingRes.encodeMs; // Overlapped with capture
+ perfStages.encoderDrainWaitMs = streamingRes.encoderDrainWaitMs ?? 0;
} else {
if (capturePlan.kind === "sdr_streaming") {
capturePlan = replanAfterFailure(capturePlan, { kind: "streaming_unavailable" });
diff --git a/packages/producer/src/services/safeRenderErrorCode.ts b/packages/producer/src/services/safeRenderErrorCode.ts
new file mode 100644
index 0000000000..1f86b88947
--- /dev/null
+++ b/packages/producer/src/services/safeRenderErrorCode.ts
@@ -0,0 +1,22 @@
+const SAFE_RENDER_ERROR_CODES = new Set([
+ "ASSET_MEDIA_TYPE_MISMATCH",
+ "HEIF_IMAGE_CONVERSION_FAILED",
+ "HEIF_TOOL_UNAVAILABLE",
+ "NOT_MEDIA_PAYLOAD",
+ "INVALID_VIDEO_METADATA",
+ "VIDEO_SOURCE_UNRENDERABLE",
+ "VIDEO_EXTRACTION_FAILED",
+ "ENCODER_INTERRUPTED",
+ "RENDER_TOO_SLOW",
+ "RENDER_STAGE_STALLED",
+]);
+
+/**
+ * Preserve only bounded producer error codes across JSON/SSE. Never derive a
+ * code from the message: it may contain local paths or signed source URLs.
+ */
+export function extractSafeRenderErrorCode(error: unknown): string | undefined {
+ if (typeof error !== "object" || error === null || !("code" in error)) return undefined;
+ const code = error.code;
+ return typeof code === "string" && SAFE_RENDER_ERROR_CODES.has(code) ? code : undefined;
+}
diff --git a/packages/sdk/package.json b/packages/sdk/package.json
index edd90ab611..52ec4111bc 100644
--- a/packages/sdk/package.json
+++ b/packages/sdk/package.json
@@ -1,6 +1,6 @@
{
"name": "@hyperframes/sdk",
- "version": "0.8.214",
+ "version": "0.8.224",
"description": "Headless, framework-neutral HyperFrames composition editing engine",
"repository": {
"type": "git",
diff --git a/packages/shader-transitions/package.json b/packages/shader-transitions/package.json
index 66f5b21972..cf30ec4875 100644
--- a/packages/shader-transitions/package.json
+++ b/packages/shader-transitions/package.json
@@ -1,6 +1,6 @@
{
"name": "@hyperframes/shader-transitions",
- "version": "0.8.214",
+ "version": "0.8.224",
"description": "WebGL shader transitions for HyperFrames compositions",
"repository": {
"type": "git",
diff --git a/packages/studio-server/package.json b/packages/studio-server/package.json
index ea3d3d9ec6..5370cf6900 100644
--- a/packages/studio-server/package.json
+++ b/packages/studio-server/package.json
@@ -1,6 +1,6 @@
{
"name": "@hyperframes/studio-server",
- "version": "0.8.214",
+ "version": "0.8.224",
"repository": {
"type": "git",
"url": "https://github.com/heygen-com/hyperframes",
diff --git a/packages/studio-server/src/helpers/backupJournal.test.ts b/packages/studio-server/src/helpers/backupJournal.test.ts
index 2930e2da43..bcdc0441f6 100644
--- a/packages/studio-server/src/helpers/backupJournal.test.ts
+++ b/packages/studio-server/src/helpers/backupJournal.test.ts
@@ -86,6 +86,47 @@ describe("snapshotBeforeWrite", () => {
.sort(),
).toEqual(["space", "underscore"]);
});
+
+ it("keeps separate bounded histories for long paths with the same basename", () => {
+ const projectDir = createProjectDir();
+ const directory = join(projectDir, "compositions", "scene/".repeat(30));
+ mkdirSync(join(directory, "first"), { recursive: true });
+ mkdirSync(join(directory, "second"), { recursive: true });
+ const first = join(directory, "first", "index.html");
+ const second = join(directory, "second", "index.html");
+
+ for (const { file, content } of [
+ { file: first, content: "older" },
+ { file: second, content: "other" },
+ { file: first, content: "newer" },
+ ]) {
+ writeFileSync(file, content);
+ expect(snapshotBeforeWrite(projectDir, file, { keepPerFile: 1 }).error).toBeUndefined();
+ }
+
+ const backupDir = join(projectDir, ".hyperframes", "backup");
+ const contents = readdirSync(backupDir).map((file) =>
+ readFileSync(join(backupDir, file), "utf8"),
+ );
+ expect(contents.sort()).toEqual(["newer", "other"]);
+ });
+
+ it("counts existing base64-named backups toward a long path's retention limit", () => {
+ const projectDir = createProjectDir();
+ const relativePath = `${"a".repeat(156)}.txt`;
+ const file = join(projectDir, relativePath);
+ writeFileSync(file, "current");
+ const backupDir = join(projectDir, ".hyperframes", "backup");
+ mkdirSync(backupDir, { recursive: true });
+ const legacyKey = Buffer.from(relativePath).toString("base64url");
+ writeFileSync(join(backupDir, `2000-01-01T00-00-00-000Z-${legacyKey}`), "old");
+
+ const result = snapshotBeforeWrite(projectDir, file, { keepPerFile: 1 });
+
+ if (!result.backupPath) throw new Error(result.error ?? "Missing backup path");
+ expect(readdirSync(backupDir)).toHaveLength(1);
+ expect(readFileSync(result.backupPath, "utf8")).toBe("current");
+ });
});
describe("snapshotBeforeWrite when the project folder is gone", () => {
diff --git a/packages/studio-server/src/helpers/backupJournal.ts b/packages/studio-server/src/helpers/backupJournal.ts
index a81334527c..417256fd08 100644
--- a/packages/studio-server/src/helpers/backupJournal.ts
+++ b/packages/studio-server/src/helpers/backupJournal.ts
@@ -1,5 +1,6 @@
import { readdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
import { Buffer } from "node:buffer";
+import { createHash } from "node:crypto";
import { join, relative } from "node:path";
import { isProjectRootMissing, isSafePath, mkdirWithinProject } from "./safePath.js";
@@ -10,10 +11,6 @@ export interface BackupJournalResult {
error?: string;
}
-function backupKeyForPath(path: string): string {
- return Buffer.from(path, "utf-8").toString("base64url");
-}
-
function timestampPrefix(): string {
return new Date().toISOString().replace(/[:.]/g, "-");
}
@@ -42,10 +39,14 @@ export function snapshotBeforeWrite(
const backupDir = join(projectDir, ".hyperframes", "backup");
mkdirWithinProject(projectDir, backupDir);
- const backupKey = backupKeyForPath(relativePath);
+ const pathKey = Buffer.from(relativePath, "utf-8").toString("base64url");
+ const backupKey =
+ pathKey.length <= 200
+ ? pathKey
+ : `sha256~${createHash("sha256").update(relativePath).digest("hex")}`;
const backupPath = nextBackupPath(backupDir, backupKey);
writeFileSync(backupPath, content);
- pruneBackups(backupDir, backupKey, options.keepPerFile ?? DEFAULT_KEEP_PER_FILE);
+ pruneBackups(backupDir, [pathKey, backupKey], options.keepPerFile ?? DEFAULT_KEEP_PER_FILE);
return { backupPath };
} catch (error) {
if (isProjectRootMissing(error)) throw error;
@@ -79,12 +80,11 @@ function nextBackupPath(backupDir: string, backupKey: string): string {
}
}
-function pruneBackups(backupDir: string, backupKey: string, keepPerFile: number): void {
+function pruneBackups(backupDir: string, backupKeys: string[], keepPerFile: number): void {
const keep = Math.max(1, Math.floor(keepPerFile));
- const suffix = `-${backupKey}`;
- const numberedSuffix = new RegExp(`-${backupKey}-\\d+$`);
+ const suffix = new RegExp(`-(?:${backupKeys.join("|")})(?:-\\d+)?$`);
const matches = readdirSync(backupDir)
- .filter((name) => name.endsWith(suffix) || numberedSuffix.test(name))
+ .filter((name) => suffix.test(name))
.map((name) => join(backupDir, name))
.sort((a, b) => {
return b.localeCompare(a);
diff --git a/packages/studio-server/src/helpers/loudness.test.ts b/packages/studio-server/src/helpers/loudness.test.ts
index 2a7eef5bd4..fc5c6c5522 100644
--- a/packages/studio-server/src/helpers/loudness.test.ts
+++ b/packages/studio-server/src/helpers/loudness.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import {
absoluteLoudnessPlan,
+ absoluteOutcome,
audioTags,
loudnessMeasureArgs,
updateAudioVolume,
@@ -180,6 +181,14 @@ describe("absoluteLoudnessPlan", () => {
expect(plan.limitedBy).toBe("true-peak");
});
+ it("never cuts a clip that is below the target because its peak is already past the ceiling", () => {
+ const plan = absoluteLoudnessPlan(track(-17.1, -0.5));
+ expect(plan.gainDb).toBeCloseTo(0, 6);
+ expect(plan.changeDb).toBeCloseTo(0, 6);
+ expect(plan.projectedLufs).toBeCloseTo(-17.1, 6);
+ expect(plan.limitedBy).toBe("true-peak");
+ });
+
it("attenuates a clip that is too loud", () => {
const plan = absoluteLoudnessPlan(track(-10, 0));
expect(plan.gainDb).toBeCloseTo(-6, 6);
@@ -215,3 +224,19 @@ describe("audioTags on hostile markup", () => {
expect(audioTags(html).map((t) => t.id)).toEqual(["vo"]);
});
});
+
+describe("absoluteOutcome", () => {
+ it("calls a clip at the target matched", () => {
+ expect(absoluteOutcome(absoluteLoudnessPlan(track(-16, -6, 1)), 1)).toBe("matched");
+ });
+
+ it("calls a clip a limit cannot move held, not matched", () => {
+ const plan = absoluteLoudnessPlan(track(-25, -0.5), -16);
+ expect(plan.limitedBy).toBe("true-peak");
+ expect(absoluteOutcome(plan, 1)).toBe("held");
+ });
+
+ it("calls a clip that needs a different gain a change", () => {
+ expect(absoluteOutcome(absoluteLoudnessPlan(track(-19.2, -8)), 1)).toBe("change");
+ });
+});
diff --git a/packages/studio-server/src/helpers/loudness.ts b/packages/studio-server/src/helpers/loudness.ts
index b976227bfa..18a1ac8aaa 100644
--- a/packages/studio-server/src/helpers/loudness.ts
+++ b/packages/studio-server/src/helpers/loudness.ts
@@ -540,10 +540,14 @@ export function absoluteLoudnessPlan(
["gain-ceiling", MAX_AUDIO_GAIN_DB],
["true-peak", peakRoomDb],
];
- const [limitedBy, appliedGainDb] = limits.reduce((lowest, candidate) =>
+ const [limitedBy, limitedGainDb] = limits.reduce((lowest, candidate) =>
candidate[1] < lowest[1] - 1e-9 ? candidate : lowest,
);
const previousGainDb = track.volume > 0 ? gainDb(track.volume) : 0;
+ const limitCannotCutAWantedBoost = wantedGainDb > previousGainDb;
+ const appliedGainDb = limitCannotCutAWantedBoost
+ ? Math.max(limitedGainDb, previousGainDb)
+ : limitedGainDb;
return {
targetId: track.id,
targetLufs,
@@ -557,3 +561,10 @@ export function absoluteLoudnessPlan(
limitedBy,
};
}
+
+export type AbsoluteOutcome = "matched" | "held" | "change";
+
+export function absoluteOutcome(plan: AbsoluteLoudnessPlan, tolerance: number): AbsoluteOutcome {
+ if (Math.abs(plan.changeDb) > tolerance) return "change";
+ return Math.abs(plan.projectedLufs - plan.targetLufs) <= tolerance ? "matched" : "held";
+}
diff --git a/packages/studio-server/src/helpers/projectSignature.test.ts b/packages/studio-server/src/helpers/projectSignature.test.ts
index 401f66139f..2623b20511 100644
--- a/packages/studio-server/src/helpers/projectSignature.test.ts
+++ b/packages/studio-server/src/helpers/projectSignature.test.ts
@@ -1,6 +1,7 @@
import { afterEach, describe, expect, it } from "vitest";
import {
closeSync,
+ mkdirSync,
fstatSync,
ftruncateSync,
futimesSync,
@@ -15,6 +16,7 @@ import { resolve } from "node:path";
import {
affectsProjectSignature,
createProjectSignature,
+ createProjectSignatureAsync,
listProjectFiles,
} from "./projectSignature.js";
@@ -106,3 +108,51 @@ describe("createProjectSignature", () => {
}
});
});
+
+describe("createProjectSignatureAsync", () => {
+ function fixture(): string {
+ const project = mkdtempSync(resolve(tmpdir(), "hf-signature-async-"));
+ temporaryProjects.push(project);
+ for (const dir of ["scenes", "assets/img", ".thumbnails", ".hyperframes"]) {
+ mkdirSync(resolve(project, dir), { recursive: true });
+ }
+ writeFileSync(resolve(project, "index.html"), "root");
+ writeFileSync(resolve(project, "scenes/a.html"), "a
");
+ writeFileSync(resolve(project, "scenes/b.js"), "export const b = 1;");
+ writeFileSync(resolve(project, "assets/img/logo.png"), Buffer.from([1, 2, 3, 4]));
+ writeFileSync(resolve(project, ".thumbnails/skipped.png"), "capture");
+ writeFileSync(resolve(project, ".hyperframes/studio-motion.json"), "{}");
+ return project;
+ }
+
+ it("returns the signature the synchronous walk returns", async () => {
+ const project = fixture();
+ expect(await createProjectSignatureAsync(project)).toBe(createProjectSignature(project));
+ const excluded = new Set(["scenes/a.html"]);
+ expect(await createProjectSignatureAsync(project, excluded)).toBe(
+ createProjectSignature(project, excluded),
+ );
+ });
+
+ it("changes when a text file changes, and ignores a skipped directory", async () => {
+ const project = fixture();
+ const before = await createProjectSignatureAsync(project);
+ writeFileSync(resolve(project, ".thumbnails/skipped.png"), "another capture");
+ expect(await createProjectSignatureAsync(project)).toBe(before);
+ writeFileSync(resolve(project, "scenes/a.html"), "A
");
+ expect(await createProjectSignatureAsync(project)).not.toBe(before);
+ });
+
+ it("lets the event loop run while it walks and reads", async () => {
+ const project = fixture();
+ for (let i = 0; i < 60; i++) writeFileSync(resolve(project, `scenes/s${i}.html`), `${i}`);
+ let turns = 0;
+ const tick = setInterval(() => turns++, 0);
+ try {
+ await createProjectSignatureAsync(project);
+ } finally {
+ clearInterval(tick);
+ }
+ expect(turns).toBeGreaterThan(1);
+ });
+});
diff --git a/packages/studio-server/src/helpers/projectSignature.ts b/packages/studio-server/src/helpers/projectSignature.ts
index c89b105f54..c521efd456 100644
--- a/packages/studio-server/src/helpers/projectSignature.ts
+++ b/packages/studio-server/src/helpers/projectSignature.ts
@@ -1,6 +1,7 @@
import { readRenderOutputsOrNone, isRenderOutput } from "./renderOutputs.js";
import { createHash } from "node:crypto";
import { lstatSync, readFileSync, readdirSync, type Stats } from "node:fs";
+import { lstat, readFile, readdir } from "node:fs/promises";
import { extname, isAbsolute, relative, resolve, sep } from "node:path";
import { isAtomicTempPath } from "@hyperframes/core/atomic-file";
import { isProjectIgnoredDir } from "@hyperframes/core/project-folders";
@@ -106,6 +107,16 @@ function signatureEntryStat(
}
}
+function signatureFileOf(file: string, stat: Stats): ProjectSignatureFile {
+ return {
+ file,
+ mtimeMs: stat.mtimeMs,
+ ctimeMs: stat.ctimeMs,
+ size: stat.size,
+ textContentEligible: isTextContentEligible(file, stat.size),
+ };
+}
+
function collectProjectSignatureFiles(
projectDir: string,
dir: string,
@@ -126,13 +137,7 @@ function collectProjectSignatureFiles(
if (stat.isDirectory()) {
collectProjectSignatureFiles(projectDir, file, files, outputs);
} else if (stat.isFile()) {
- files.push({
- file,
- mtimeMs: stat.mtimeMs,
- ctimeMs: stat.ctimeMs,
- size: stat.size,
- textContentEligible: isTextContentEligible(file, stat.size),
- });
+ files.push(signatureFileOf(file, stat));
}
}
}
@@ -152,17 +157,53 @@ function collectProjectSignatureManifestFiles(
continue;
}
if (stat.isSymbolicLink() || !stat.isFile()) continue;
- files.push({
- file,
- mtimeMs: stat.mtimeMs,
- ctimeMs: stat.ctimeMs,
- size: stat.size,
- textContentEligible: isTextContentEligible(file, stat.size),
- });
+ files.push(signatureFileOf(file, stat));
seen.add(file);
}
}
+async function signatureEntryStatAsync(
+ projectDir: string,
+ entry: string,
+ file: string,
+ outputs: readonly string[],
+): Promise {
+ if (isSkippedEntry(entry) || !isPathWithin(projectDir, file)) return null;
+ if (isRenderOutput(projectDir, file, outputs)) return null;
+ try {
+ const stat = await lstat(file);
+ return stat.isSymbolicLink() ? null : stat;
+ } catch {
+ return null;
+ }
+}
+
+async function collectProjectSignatureFilesAsync(
+ projectDir: string,
+ dir: string,
+ files: ProjectSignatureFile[],
+ outputs: readonly string[],
+): Promise {
+ let entries: string[];
+ try {
+ entries = (await readdir(dir)).sort();
+ } catch {
+ return;
+ }
+ const paths = entries.map((entry) => resolve(dir, entry));
+ const stats = await Promise.all(
+ entries.map((entry, i) => signatureEntryStatAsync(projectDir, entry, paths[i]!, outputs)),
+ );
+ for (const [i, stat] of stats.entries()) {
+ if (!stat) continue;
+ if (stat.isDirectory()) {
+ await collectProjectSignatureFilesAsync(projectDir, paths[i]!, files, outputs);
+ } else if (stat.isFile()) {
+ files.push(signatureFileOf(paths[i]!, stat));
+ }
+ }
+}
+
function createProjectFingerprint(projectDir: string, files: ProjectSignatureFile[]): string {
const hash = createHash("sha256");
for (const entry of files) {
@@ -187,6 +228,20 @@ function collectProjectFiles(normalizedProjectDir: string): ProjectSignatureFile
return collected;
}
+async function collectProjectFilesAsync(
+ normalizedProjectDir: string,
+): Promise {
+ const collected: ProjectSignatureFile[] = [];
+ await collectProjectSignatureFilesAsync(
+ normalizedProjectDir,
+ normalizedProjectDir,
+ collected,
+ readRenderOutputsOrNone(normalizedProjectDir),
+ );
+ collectProjectSignatureManifestFiles(normalizedProjectDir, collected);
+ return collected;
+}
+
/** The files a project is made of (the signature's set: source plus Studio's two manifests), paths with `/`. */
export function listProjectFiles(
projectDir: string,
@@ -219,6 +274,62 @@ export async function resolveProjectAndSignature(
return { project, signature: resolveProjectSignature(adapter, project.dir) };
}
+interface SignaturePlan {
+ dir: string;
+ files: ProjectSignatureFile[];
+ cacheKey: string;
+ fingerprint: string;
+ signedAt: number;
+}
+
+function planSignature(
+ dir: string,
+ collected: ProjectSignatureFile[],
+ excluding: ReadonlySet,
+ signedAt: number,
+): SignaturePlan {
+ const files = collected.filter(
+ (entry) => !excluding.has(relative(dir, entry.file).split(sep).join("/")),
+ );
+ files.sort((a, b) => a.file.localeCompare(b.file));
+ const cacheKey = excluding.size
+ ? `${dir}\0${createHash("sha256")
+ .update([...excluding].sort().join("\0"))
+ .digest("hex")}`
+ : dir;
+ return { dir, files, cacheKey, fingerprint: createProjectFingerprint(dir, files), signedAt };
+}
+
+function hashSignatureEntry(
+ hash: ReturnType,
+ dir: string,
+ entry: ProjectSignatureFile,
+ content: Buffer | null,
+): void {
+ hash.update(relative(dir, entry.file));
+ hash.update("\0");
+ hash.update(String(entry.size));
+ hash.update("\0");
+ hash.update(content ?? String(entry.mtimeMs));
+ hash.update("\0");
+}
+
+function finishSignature(plan: SignaturePlan, hash: ReturnType): string {
+ const signature = hash.digest("hex").slice(0, 24);
+ const settledATickBeforeSigning = plan.files.every(
+ (entry) => Math.max(entry.mtimeMs, entry.ctimeMs) < plan.signedAt - COARSEST_FILE_TIME_TICK_MS,
+ );
+ if (settledATickBeforeSigning) {
+ projectSignatureCache.set(plan.cacheKey, { fingerprint: plan.fingerprint, signature });
+ }
+ return signature;
+}
+
+const cachedSignature = (plan: SignaturePlan): string | undefined => {
+ const cached = projectSignatureCache.get(plan.cacheKey);
+ return cached?.fingerprint === plan.fingerprint ? cached.signature : undefined;
+};
+
/**
* Creates a stable preview cache-busting signature for project source plus Studio manifests.
* `excluding` (project-relative paths) leaves those files out.
@@ -227,45 +338,48 @@ export function createProjectSignature(
projectDir: string,
excluding: ReadonlySet = new Set(),
): string {
- const normalizedProjectDir = resolve(projectDir);
- const signedAt = Date.now();
- const collected = collectProjectFiles(normalizedProjectDir);
- const files = collected.filter(
- (entry) => !excluding.has(relative(normalizedProjectDir, entry.file).split(sep).join("/")),
- );
- files.sort((a, b) => a.file.localeCompare(b.file));
-
- const fingerprint = createProjectFingerprint(normalizedProjectDir, files);
- const cacheKey = excluding.size
- ? `${normalizedProjectDir}\0${createHash("sha256")
- .update([...excluding].sort().join("\0"))
- .digest("hex")}`
- : normalizedProjectDir;
- const cached = projectSignatureCache.get(cacheKey);
- if (cached?.fingerprint === fingerprint) return cached.signature;
+ const dir = resolve(projectDir);
+ const plan = planSignature(dir, collectProjectFiles(dir), excluding, Date.now());
+ const cached = cachedSignature(plan);
+ if (cached !== undefined) return cached;
const hash = createHash("sha256");
- for (const entry of files) {
- const relativePath = relative(normalizedProjectDir, entry.file);
- hash.update(relativePath);
- hash.update("\0");
- hash.update(String(entry.size));
- hash.update("\0");
+ for (const entry of plan.files) {
+ let content: Buffer | null = null;
if (entry.textContentEligible) {
try {
- hash.update(readFileSync(entry.file));
+ content = readFileSync(entry.file);
} catch {
- hash.update(String(entry.mtimeMs));
+ content = null;
}
- } else {
- hash.update(String(entry.mtimeMs));
}
- hash.update("\0");
+ hashSignatureEntry(hash, dir, entry, content);
}
- const signature = hash.digest("hex").slice(0, 24);
- const settledATickBeforeSigning = files.every(
- (entry) => Math.max(entry.mtimeMs, entry.ctimeMs) < signedAt - COARSEST_FILE_TIME_TICK_MS,
- );
- if (settledATickBeforeSigning) projectSignatureCache.set(cacheKey, { fingerprint, signature });
- return signature;
+ return finishSignature(plan, hash);
+}
+
+const SIGNATURE_READ_BATCH = 32;
+
+/** `createProjectSignature` without blocking the event loop: the same signature, with the walk and reads awaited. */
+export async function createProjectSignatureAsync(
+ projectDir: string,
+ excluding: ReadonlySet = new Set(),
+): Promise {
+ const dir = resolve(projectDir);
+ const signedAt = Date.now();
+ const plan = planSignature(dir, await collectProjectFilesAsync(dir), excluding, signedAt);
+ const cached = cachedSignature(plan);
+ if (cached !== undefined) return cached;
+
+ const hash = createHash("sha256");
+ for (let at = 0; at < plan.files.length; at += SIGNATURE_READ_BATCH) {
+ const batch = plan.files.slice(at, at + SIGNATURE_READ_BATCH);
+ const contents = await Promise.all(
+ batch.map((entry) =>
+ entry.textContentEligible ? readFile(entry.file).catch(() => null) : null,
+ ),
+ );
+ for (const [i, entry] of batch.entries()) hashSignatureEntry(hash, dir, entry, contents[i]!);
+ }
+ return finishSignature(plan, hash);
}
diff --git a/packages/studio-server/src/helpers/sourceMutation.ts b/packages/studio-server/src/helpers/sourceMutation.ts
index 4cda4cf4b9..1b26d9856b 100644
--- a/packages/studio-server/src/helpers/sourceMutation.ts
+++ b/packages/studio-server/src/helpers/sourceMutation.ts
@@ -12,7 +12,11 @@ import {
mintHfId,
walkCompositionDescendants,
} from "@hyperframes/parsers/hf-ids";
-import { readClipTiming, writeClipTiming } from "@hyperframes/core/composition-contract";
+import {
+ readClipTiming,
+ SPLIT_BOUNDARY_EPSILON_S,
+ writeClipTiming,
+} from "@hyperframes/core/composition-contract";
import { relinkSplitHalves } from "@hyperframes/core/media-link";
import { parseStyleDecls, patchStyleAttrString } from "./sourceStyleMutation.js";
@@ -41,7 +45,44 @@ export function parseSourceDocument(raw: string): {
return { document, wrappedFragment: !hasDocumentShell };
}
+/** Drops the rules that style `id` alone (every selector in the list names it), in each style sheet of the page. */
+function dropCssRulesForId(document: Document, id: string): void {
+ const idToken = `#${id}`;
+ const namesId = (selector: string) => {
+ let found = false;
+ selectorParser((selectors) => {
+ selectors.walkIds((node) => {
+ // an id inside :not() excludes the element, so the rule styles the others
+ let up = node.parent;
+ while (up && !(up.type === "pseudo" && up.value === ":not")) up = up.parent as typeof up;
+ if (node.value === id && !up) found = true;
+ });
+ }).processSync(selector);
+ return found;
+ };
+ for (const styleEl of document.querySelectorAll("style")) {
+ const css = styleEl.textContent ?? "";
+ if (!css.includes(idToken)) continue;
+ let root: postcss.Root;
+ try {
+ root = postcss.parse(css);
+ } catch {
+ continue;
+ }
+ let dropped = false;
+ root.walkRules((rule) => {
+ if (rule.selectors.length > 0 && rule.selectors.every(namesId)) {
+ rule.remove();
+ dropped = true;
+ }
+ });
+ if (dropped) styleEl.textContent = root.toString();
+ }
+}
+
+// A clone's rules replace whatever an earlier piece of that id left behind, so repeated cuts keep one set per id.
function duplicateCssRulesForId(document: Document, originalId: string, newId: string): void {
+ dropCssRulesForId(document, newId);
const idToken = `#${originalId}`;
const transform = selectorParser((selectors) => {
selectors.walkIds((node) => {
@@ -157,7 +198,9 @@ export function removeElementsFromHtml(
for (const target of targets) {
const element = findTargetElement(document, target);
if (!element) continue;
+ const id = element.getAttribute("id");
removeElementWithGsapCascade(document, element);
+ if (id && !document.getElementById(id)) dropCssRulesForId(document, id);
removed = true;
}
if (!removed) return source;
@@ -455,7 +498,11 @@ export function splitElementInHtml(
start = fallbackTiming.start;
duration = fallbackTiming.duration;
}
- if (duration <= 0 || splitTime <= start || splitTime >= start + duration) {
+ if (
+ duration <= 0 ||
+ splitTime < start + SPLIT_BOUNDARY_EPSILON_S ||
+ splitTime > start + duration - SPLIT_BOUNDARY_EPSILON_S
+ ) {
return { html: source, matched: false, newId: null };
}
diff --git a/packages/studio-server/src/helpers/sourceMutationSplitAndGroup.test.ts b/packages/studio-server/src/helpers/sourceMutationSplitAndGroup.test.ts
index 902a2d5e5f..8f8c589ac5 100644
--- a/packages/studio-server/src/helpers/sourceMutationSplitAndGroup.test.ts
+++ b/packages/studio-server/src/helpers/sourceMutationSplitAndGroup.test.ts
@@ -3,6 +3,7 @@ import { parseHTML } from "linkedom";
import { describe, expect, it } from "vitest";
import { readMediaOffsetSeconds } from "@hyperframes/parsers/media-duration";
import {
+ removeElementFromHtml,
splitElementInHtml,
relinkSplitHalvesInHtml,
unwrapElementsFromHtml,
@@ -23,6 +24,32 @@ describe("splitElementInHtml — hfId clone isolation", () => {
});
});
+// A second split at the same playhead: the first one wrote the left half's end rounded to the millisecond (2.346 for a
+// playhead at 2.3456), so the same cut lands a fraction inside that edge and its sliver rounded to data-duration="0".
+describe("splitElementInHtml — a cut at an existing edge", () => {
+ const clip = (start: number, duration: number) =>
+ ``;
+ const durations = (html: string) =>
+ [...parseHTML(html).document.querySelectorAll(".clip")].map((el) =>
+ Number(el.getAttribute("data-duration")),
+ );
+
+ it("leaves the file as it was when the cut is within the split margin of either edge", () => {
+ for (const at of [2.3456, 2.346, 1, 1.0004, 2.33]) {
+ const source = clip(1, 1.346);
+ const result = splitElementInHtml(source, { id: "a" }, at, "a-split");
+ expect(result.matched, `a cut at ${at}`).toBe(false);
+ expect(result.html, `a cut at ${at}`).toBe(source);
+ }
+ });
+
+ it("still cuts at the margin itself, and no half it writes is ever zero long", () => {
+ const result = splitElementInHtml(clip(1, 1.346), { id: "a" }, 1.03, "a-split");
+ expect(result.matched).toBe(true);
+ expect(durations(result.html)).toEqual([0.03, 1.316]);
+ });
+});
+
describe("splitElementInHtml", () => {
const source = ``;
@@ -513,3 +540,23 @@ describe("relinkSplitHalvesInHtml", () => {
expect(relinkSplitHalvesInHtml(source, ["i"])).toBe(source);
});
});
+
+describe("splitElementInHtml — id CSS rules across repeated cuts", () => {
+ it("keeps one rule set per live id when a clip is cut again and again", () => {
+ let html =
+ "" +
+ '
';
+ for (let i = 0; i < 5; i++) {
+ const tail = splitElementInHtml(html, { id: "a" }, 20 + i, `a-${i + 2}`);
+ const middle = splitElementInHtml(tail.html, { id: "a" }, 10 + i, "a-cut");
+ html = removeElementFromHtml(middle.html, { id: "a-cut" });
+ }
+ const css = /