---
name: hyperframes-video
description: Use when writing any NEW custom video composition (one HTML document rendered to MP4 by the HTML video renderer) — text and title animation, word-timed captions, mixed video/image/audio timelines, music and voiceover, transitions, charts, numeric tickers, logos and end cards, 3D or canvas. Covers the HTML composition format, GSAP timelines, clip timing, audio mixing, fonts, emoji and determinism rules.
category: video
---

# HyperFrames Video

New custom compositions are written as **one HTML document** and rendered to MP4 by `spiral/render-video`. Read its input schema, estimate the cost, then run it with `{ code, durationInFrames, fps, width, height }`.

- **Changing a video you already rendered:** keep the document you rendered, change only what the user asked, and render the whole changed document again.
- **Re-rendering without changes:** reuse the existing video; do not render again.
- **Frame rate and size:** pass `fps: 30` and 1920×1080 (or the requested aspect at 1080 on the short side) unless the user asks otherwise. Use 60 fps only for fast motion the user wants extra smooth; it doubles render time.
- The tool result is the final MP4. Its cost depends on the video's duration.

## Which guide to load

Our render contract below always wins over the vendored upstream guides. Each of them starts with a "Rendering with `spiral/render-video`" section that says what to ignore.

| Need                                                                                       | Load                      |
| ------------------------------------------------------------------------------------------ | ------------------------- |
| Contract details: `data-*` attributes, clips, tracks, determinism rules, common pitfalls   | `hyperframes-core`        |
| Motion rules, scene blueprints, transitions, text effects, Lottie/3D/canvas/other runtimes | `hyperframes-animation`   |
| Mixing, fades, ducking music under a voiceover, effects on a track                         | `hyperframes-audio`       |
| Actual media durations, asset inclusion, public URLs                                       | `durations-and-assets.md` |
| Captions: base layer, word timing, SRT, grouping, styling                                  | `captions.md`             |
| Audio-reactive visuals (waveforms, bars) in a custom composition                           | `audio-visualization.md`  |

Conflicts, where ours wins: one HTML document only (no project files, no sub-compositions), the root id is `root` with timeline key `root`, and no CLI, Studio or registry commands.

## Repeating a clip

Clips have no loop attribute (only `<audio>` supports `data-loop="true"`). To fill a window with a shorter video of probed length `L`, place consecutive `<video>` clips with `data-start = k * L`, `data-media-start = 0`, and trim the last `data-duration` to the remainder. If the source does not loop seamlessly (any AI-generated motion: dance, walking, running, character motion, music-video panels, backgrounds you cannot inspect), overlap adjacent clips by about 0.4 seconds and crossfade (`tl.to(outgoing, { opacity: 0, duration: 0.4 }, boundary - 0.4)` with the incoming clip starting at `boundary - 0.4`). Trim awkward startup frames with `data-media-start`.

## The render contract

The renderer opens the document in a browser, seeks a **paused** timeline to each frame and captures it. Nothing plays in real time.

1. Exactly one root element: `<div id="root" data-composition-id="root" data-start="0" data-width="W" data-height="H" data-duration="SECONDS">`.
2. `data-width`/`data-height` must equal the call's `width`/`height`, and `data-duration` must equal `durationInFrames / fps` in seconds. Omit `data-fps`, or set it equal to `fps`. Validation rejects any mismatch before charging.
3. Every timed element has `class="clip"`, a unique `id`, `data-start` and `data-duration` (seconds) and `data-track-index` (an integer; higher draws on top only through CSS `z-index`, which you set yourself).
4. Animation lives in **one paused GSAP timeline** registered as `window.__timelines.root`. Load GSAP with `<script src="gsap.min.js"></script>` — the renderer provides that file. No other local files exist.
5. All media `src` values are public `https` URLs. Other scripts must be pinned versions from `cdn.jsdelivr.net`, `cdnjs.cloudflare.com` or `unpkg.com`.

## Skeleton

```html
<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <style>
      html,
      body {
        margin: 0;
        background: #000;
      }
      #root {
        position: relative;
        width: 1080px;
        height: 1920px;
        overflow: hidden;
        font-family: Inter, system-ui, sans-serif;
      }
      .fill {
        position: absolute;
        inset: 0;
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      #title {
        position: absolute;
        top: 260px;
        width: 100%;
        text-align: center;
        color: #fff;
        font-size: 104px;
        font-weight: 800;
        z-index: 10;
      }
    </style>
  </head>
  <body>
    <div
      id="root"
      data-composition-id="root"
      data-start="0"
      data-width="1080"
      data-height="1920"
      data-duration="12"
    >
      <video
        id="broll"
        class="clip fill"
        src="VIDEO_URL"
        data-start="0"
        data-duration="12"
        data-media-start="2"
        data-track-index="0"
        muted
      ></video>
      <audio
        id="voice"
        class="clip"
        src="VOICE_URL"
        data-start="0.5"
        data-duration="11"
        data-track-index="1"
        data-volume="1"
      ></audio>
      <audio
        id="music"
        class="clip"
        src="MUSIC_URL"
        data-start="0"
        data-duration="12"
        data-track-index="2"
        data-volume="0.15"
        data-loop="true"
      ></audio>
      <div id="title" class="clip" data-start="0" data-duration="12" data-track-index="3">Launch day 🚀</div>
    </div>
    <script src="gsap.min.js"></script>
    <script>
      const tl = gsap.timeline({ paused: true });
      tl.from("#title", { y: -120, opacity: 0, duration: 0.8, ease: "back.out(2)" }, 0);
      tl.to("#title", { scale: 1.1, duration: 0.4, yoyo: true, repeat: 1 }, 6);
      window.__timelines = { root: tl };
    </script>
  </body>
</html>
```

## Media clips

| Need                           | How                                                                                                   |
| ------------------------------ | ----------------------------------------------------------------------------------------------------- |
| Trim a source                  | `data-media-start` = seconds into the source where playback begins.                                   |
| Picture only                   | `<video … muted>`. Every `<video>` is either `muted` or `data-has-audio="true"`.                      |
| Video with its own sound       | `<video … data-has-audio="true">` (no `muted`).                                                       |
| Volume                         | `data-volume` (1 = unchanged, 0 = silent, up to ~4 to boost). Voice ≈ 1, music under voice ≈ 0.1–0.2. |
| Fades                          | `data-fade-in` / `data-fade-out` in seconds on audio or video clips.                                  |
| Speed                          | `data-playback-rate` (0.1–10).                                                                        |
| Loop music for the whole video | `data-loop="true"` on the `<audio>`; the renderer repeats it to fill `data-duration`.                 |
| Still image for a time window  | `<img class="clip" …>` with its own start/duration.                                                   |

Clips are hidden outside their window automatically; you only animate what happens inside it. Size and position media with CSS (`object-fit: cover|contain`).

## Durations (non-negotiable)

Full rules and probe commands: `durations-and-assets.md`.

Never guess media durations. Use the duration from the generation or word-timing result, or probe the file with your own FFprobe (`ffprobe -v error -show_entries format=duration -of default=nw=1:nk=1 '<url>'`); with Spiral tools only, see `durations-and-assets.md` (media understanding, labelled approximate). Then:

- `data-duration` of each clip ≤ the remaining source length after `data-media-start`.
- The root `data-duration` covers the last clip end; set `durationInFrames = round(seconds × fps)` from that same number.
- Caption timestamps are **milliseconds** (normalised as in `captions.md`, "Getting word timing"); divide by 1000 for timeline positions.

## Asset inclusion (non-negotiable)

Every generated and user-supplied asset the video needs must be in the FIRST render: base footage or images, voiceover, music, logo, end card. Captions alone are not a video; include their base layer. A render that succeeds without the user's media is still a failed task.

## Animation rules

- Tween with the timeline only: `tl.from/to/fromTo/set(target, vars, positionSeconds)`. Position every tween explicitly (third argument) so timing never depends on order.
- Use eases and staggers freely (`stagger: 0.08`, `ease: "power3.out"`). `yoyo`/`repeat` must be finite.
- Forbidden (they break frame-accurate rendering): `Date.now()`, `performance.now()`, `requestAnimationFrame`, `setTimeout`/`setInterval` for motion, unseeded `Math.random()`, `fetch`/XHR after load, autoplaying media, CSS `transition`.
- Randomness: use a seeded generator, for example `const rnd = (s) => ((Math.sin(s * 9301 + 49297) * 233280) % 1 + 1) % 1;`.

### Per-frame logic (tickers, charts, counters, waveforms)

When state is a function of time rather than a tween, drive it from the timeline's `onUpdate`. The renderer fires it for every seeked frame:

```js
const FPS = 30;
function draw(t) {
  const frame = Math.round(t * FPS);
  document.getElementById("count").textContent = Math.round(Math.min(1, t / 3) * 12500).toLocaleString(
    "en-US",
  );
  document.getElementById("bar").style.width = `${Math.min(100, t * 25)}%`;
}
const tl = gsap.timeline({ paused: true, onUpdate: () => draw(tl.time()) });
tl.set({}, {}, 12); // timeline length = composition duration
draw(0);
window.__timelines = { root: tl };
```

## Word-timed captions

See `captions.md` for the base-layer rule, SRT input, grouping and styling. Minimal version:

Group words into short lines (about 3–6 words), show the active line, and highlight the active word:

```js
const WORDS = /* normalised words { text, start, end } in ms */ [];
const cap = document.getElementById("captions");
function drawCaptions(t) {
  const ms = t * 1000;
  const i = WORDS.findIndex((w, k) => ms >= w.start && (k === WORDS.length - 1 || ms < WORDS[k + 1].start));
  if (i < 0 || ms > WORDS[WORDS.length - 1].end) {
    cap.innerHTML = "";
    return;
  }
  const start = Math.floor(i / 4) * 4;
  cap.innerHTML = WORDS.slice(start, start + 4)
    .map((w, k) => `<span class="${start + k === i ? "on" : ""}">${w.text.replace(/</g, "&lt;")}</span>`)
    .join(" ");
}
```

Style `.on` with a contrasting background (for example `#FFFF00` on black text) and keep captions inside the safe area (≥ 80px from the bottom on vertical video, clear of platform UI). Call `drawCaptions(t)` from `draw(t)` as above.

## Text, fonts and emoji

- Google Fonts work: `<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;800&display=swap" rel="stylesheet">`. Always end the `font-family` stack with a generic family.
- Emoji render in color; put them directly in the text.
- Size text for the frame: on 1080×1920, headlines 90–140px, captions 56–72px, never below 40px. Exact copy (URLs, prices, legal text) belongs in HTML text, not in generated imagery.

## Transitions and layout

- Crossfade: overlap two clips by the transition length and tween the outgoing one to `opacity: 0` and the incoming one from `opacity: 0`.
- Slide or zoom: tween `x`, `y`, `scale` on the clip element.
- Ken Burns on stills: `tl.fromTo("#img1", { scale: 1 }, { scale: 1.08, duration: clipSeconds, ease: "none" }, clipStart)`.
- Split screens, picture-in-picture and grids are plain CSS: absolute positioning, `clip-path`, `border-radius`, `box-shadow`.

## Libraries

Load pinned builds only from the allowed CDNs, initialize them before the timeline is registered, and drive them from `draw(t)`:

- Charts: d3 (`https://cdn.jsdelivr.net/npm/d3@7.9.0/dist/d3.min.js`) — compute layouts once, update attributes in `draw(t)`.
- 3D: three.js — render the scene inside `draw(t)` with the camera/object state derived from `t`.
- Lottie: lottie-web — load with `autoplay: false`, then `anim.goToAndStop(t * 1000)` in `draw(t)`. Inline the animation JSON in the script (no fetch).

## When validation fails

The renderer refuses a composition that breaks the rules at no charge, naming each problem (root size/duration mismatch, missing `id` on media, a non-https `src`, a disallowed script host, lint findings with fixes). Fix all of them and render again.
