Explainer videos and product demos made by your AI agent. Free and open source: a local voice (Kokoro), word timing (Whisper) and a canvas renderer turn a script into a narrated MP4.
JavaScript ai-agentsanimationcanvasclaude-codecodexexplainer-videoffmpegjavascriptkokoroproduct-demotext-to-speechvideo-generationwhisper
Add platform formats with safe areas (youtube, shorts, tiktok, reels, vertical, instagram, linkedin, square), a pace setting for the whole video, and the formats command
Vincent Schmalbach77c83107a2cb
diff --git a/AGENTS.md b/AGENTS.mdindex eb9566d..0f3b354 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -61,7 +61,9 @@ everything you need in one message. Typical reasons to ask:Projects go in `videos/`, which git ignores. Pick the look for theaudience: `paper` (friendly, hand drawn, the default), `clean` (productsand business), `chalk` (teaching), `blueprint` (engineering), `midnight`- (developer tools). Add `--size 9:16` for Shorts, Reels and TikTok.+ (developer tools). Pick the size for where the video goes (see "Sizes for+ each platform" below), for example `--size tiktok` or `--size linkedin`.+ Add `--pace 1.2` when the user wants a quicker video.3. **Write `script.md`.** The narration comes first and sets the timing foreverything else. See "How to write the narration" below.@@ -236,9 +238,48 @@ is not. If anything is wrong, change the prompt and make it again. Keep textout of images and put words on screen with `s.text` instead. Use images forthings icons cannot show, and keep one style through the whole video.+## Sizes for each platform++Set `size` to the place the video goes. `explainroo formats` lists them.++| Size | Pixels | For |+|---|---|---|+| `youtube` (or `16:9`) | 1920 x 1080 | YouTube and other wide players |+| `shorts` | 1080 x 1920 | YouTube Shorts |+| `tiktok` | 1080 x 1920 | TikTok |+| `reels` | 1080 x 1920 | Instagram and Facebook Reels |+| `vertical` | 1080 x 1920 | one file for Shorts, TikTok and Reels |+| `instagram` | 1080 x 1350 | Instagram and Facebook feed posts |+| `linkedin` | 1080 x 1350 | the LinkedIn feed |+| `square` (or `1:1`) | 1080 x 1080 | square posts on X, LinkedIn and Facebook |++`9:16`, `4:5` and `WIDTHxHEIGHT` also work.++Shorts, TikTok and Reels put their own buttons, the account name and the+post text on top of the video. With `shorts`, `tiktok`, `reels` and+`vertical`, explainroo keeps out of those spots: `s.safe` is the part the app+leaves free, `s.cx` and `s.cy` are its center, the captions sit just above the+app's bottom band, and the watermark moves to the top right corner. `check`+warns about any text outside that area. Plain `9:16` has no such margins, so+use it only when the video is not meant for those apps.++Vertical videos have little room. Stack things instead of putting them side+by side, use fewer words on screen, and place everything from `s.safe`.++## Pace++`pace` makes the whole video quicker or slower. At 1.3 the voice speaks 30%+faster, and the pauses, the time before and after each scene, the+transitions and every animation get 30% shorter. Word and marker cues follow+the voice, and times in seconds in `scenes.js` are shortened too, so a scene+keeps its rhythm. 1 is the normal pace; 1.15 to 1.3 suits social media and+viewers who know the topic, above 1.4 gets hard to follow. `speed` changes+only the voice.+## The watermark-Every video gets a small "explainroo.com" in the bottom right corner. The+Every video gets a small "explainroo.com" in the bottom right corner (top+right on Shorts, TikTok and Reels, where the corner is covered). Theuser can turn it off with `"watermark": false` in `video.json`, or change itto their own text. If the user asks about it, tell them it is their choice,and that keeping it helps more people find this free project.@@ -261,10 +302,11 @@ videos/<name>/|---|---|---|| `title` | from the script | shown in the preview || `theme` | `paper` | `paper`, `clean`, `chalk`, `blueprint`, `midnight` |-| `size` | `16:9` | `16:9`, `9:16`, `1:1`, `4:5` or `WIDTHxHEIGHT` |+| `size` | `16:9` | a platform (`youtube`, `shorts`, `tiktok`, `reels`, `vertical`, `instagram`, `linkedin`, `square`), `16:9`, `9:16`, `1:1`, `4:5` or `WIDTHxHEIGHT` || `fps` | 30 | 24, 25, 30, 50 or 60 || `voice` | `af_heart` | see `explainroo voices` |-| `speed` | 0.9 | voice speed, 0.6 to 1.6 |+| `speed` | 0.9 | voice speed only, 0.6 to 1.6 |+| `pace` | 1 | speed of the whole video (voice, pauses, animations), 0.7 to 1.6 || `music` | `true` | `true` (the look's style), `warm`, `upbeat`, `calm`, `tech`, `playful`, `{ "style", "volume" }` or `false` || `sfx` | `true` | sound effects: `true`, `"minimal"` or `false` || `captions` | `"auto"` | text of the narration at the bottom; auto turns it on for vertical and square videos |@@ -273,7 +315,7 @@ videos/<name>/| `sentenceGap`, `paragraphGap` | 0.3, 0.55 | pauses in the narration || `loudness` | -14 | target loudness in LUFS || `boil` | 0 | redraws per second of hand-drawn lines; 0 keeps them still |-| `watermark` | `"explainroo.com"` | text in the bottom right corner, or `false` |+| `watermark` | `"explainroo.com"` | small text in a corner, or `false` || `images` | none | `{ "model": "best" or "cheap", "style": "..." }` |The looks:@@ -290,7 +332,7 @@ The looks:| Command | What it does ||---|---|-| `init <dir>` | creates a project (`--theme`, `--size`, `--voice`, `--title`) |+| `init <dir>` | creates a project (`--theme`, `--size`, `--pace`, `--voice`, `--title`) || `voice [project]` | makes the narration and the word times, cached per scene || `preview [project]` | a live preview in the browser that reloads when you save || `still [project] [times]` | PNG pictures at `12.5`, `scene`, `[email protected]` or `scene@end` |@@ -301,7 +343,7 @@ The looks:| `image [project] <name> "<prompt>"` | makes an illustration with OpenRouter || `images [project]` | lists the images and what they cost || `voices`, `say "text"` | lists the 28 voices, or makes a sample |-| `themes`, `icons <word>` | lists the looks, searches the 1,854 icons |+| `themes`, `formats`, `icons <word>` | lists the looks and the sizes, searches the 1,854 icons || `doctor` | checks the setup (`--fetch` downloads the speech models) |## Scene API@@ -320,8 +362,9 @@ export default {};```-The canvas is 1920 x 1080 for 16:9 (1080 x 1920 for 9:16, 1080 x 1080 for-1:1, 1080 x 1350 for 4:5). Coordinates are pixels from the top left. `x` and+The canvas is 1920 x 1080 for 16:9 (1080 x 1920 for the vertical sizes,+1080 x 1080 for square, 1080 x 1350 for `instagram`, `linkedin` and 4:5).+Coordinates are pixels from the top left. `x` and`y` are the center of an element unless the method says otherwise.### Time@@ -336,7 +379,8 @@ The canvas is 1920 x 1080 for 16:9 (1080 x 1920 for 9:16, 1080 x 1080 for| `s.cue(word, n = 1)` | when the n-th time a word or phrase is spoken starts || `s.cueEnd(word, n = 1)` | when it ends || `s.mark(name)` | the time of a `[#name]` marker |-| `s.time(v)` | turns a number, a word or `"#marker"` into seconds |+| `s.time(v)` | turns a number, a word or `"#marker"` into seconds (numbers are divided by the pace) |+| `s.pace` | the video's pace (1 is normal) || `s.p(at, dur = 0.6, ease = 'inOut')` | 0 to 1 progress for your own animation || `s.since(at)`, `s.between(a, b)` | seconds since a time, or whether now is between two times || `s.video` | `{ duration, frames, fps, width, height, scenes }` of the whole video |@@ -353,8 +397,8 @@ Easing names: `linear`, `in`, `out`, `inOut`, `outBack`, `outElastic`,| Member | Meaning ||---|---|-| `s.W`, `s.H`, `s.cx`, `s.cy` | canvas size and center |-| `s.safe` | `{ x, y, w, h, left, top, right, bottom }` with a 7% margin |+| `s.W`, `s.H`, `s.cx`, `s.cy` | canvas size and the center of the safe area |+| `s.safe` | `{ x, y, w, h, left, top, right, bottom }`: the area for content (a 7% margin, or the part a platform leaves free) || `s.row(n, { width, x })` | n x positions spread over a width || `s.col(n, { height, y })` | n y positions spread over a height || `s.grid(cols, rows, { x, y, w, h, gap })` | cells `{ x, y, w, h }`, row by row |diff --git a/engine/audio/music.js b/engine/audio/music.jsindex 63577d0..44c47fe 100644--- a/engine/audio/music.js+++ b/engine/audio/music.js@@ -469,7 +469,7 @@ export function musicPlan(music = {}) {const def = STYLES[name];const seed = music.seed ?? 1;const keyRoot = music.key != null && music.key !== '' ? parseKey(music.key) : KEYS[makeRng(hashSeed('key', name, seed)).pick(def.keys)];- const bpm = clamp(Number(music.bpm) || def.bpm, 40, 200);+ const bpm = clamp((Number(music.bpm) || def.bpm) * (Number(music.tempo) || 1), 40, 200);return { style: name, seed, keyRoot, key: KEY_LABELS[keyRoot], bpm, mixDb: def.mixDb || 0 };}diff --git a/engine/captions.js b/engine/captions.jsindex a703601..ae71278 100644--- a/engine/captions.js+++ b/engine/captions.js@@ -32,7 +32,9 @@ export function buildPhrases(timeline, maxChars) {return phrases;}-export function drawCaptions(ctx, phrases, T, theme, W, H) {+// `area` ({ cx, bottom, maxWidth }) places the captions inside a platform's+// safe area, right above the band the app covers with its own text.+export function drawCaptions(ctx, phrases, T, theme, W, H, area = null) {const ph = phrases.find((p) => T >= p.start - 0.08 && T < p.until);if (!ph) return;const vertical = H > W;@@ -44,7 +46,7 @@ export function drawCaptions(ctx, phrases, T, theme, W, H) {ctx.textAlign = 'left';const space = ctx.measureText(' ').width;const widths = ph.words.map((w) => ctx.measureText(w.text).width);- const maxLine = W * (vertical ? 0.8 : 0.7);+ const maxLine = area ? area.maxWidth - size * 1.1 : W * (vertical ? 0.8 : 0.7);const lines = [[]];let lw = 0;ph.words.forEach((w, i) => {@@ -59,17 +61,18 @@ export function drawCaptions(ctx, phrases, T, theme, W, H) {const lh = size * 1.3;const boxW = Math.max(...lines.map((l) => l.reduce((a, i, k) => a + widths[i] + (k ? space : 0), 0))) + size * 1.1;const boxH = lines.length * lh + size * 0.55;- const cy = vertical ? H * 0.74 : H - Math.max(96, H * 0.1) - boxH / 2 + lh / 2;+ const cx = area ? area.cx : W / 2;+ const cy = area ? area.bottom - boxH / 2 : vertical ? H * 0.74 : H - Math.max(96, H * 0.1) - boxH / 2 + lh / 2;const fadeIn = ease.out(clamp((T - (ph.start - 0.08)) / 0.15));const fadeOut = 1 - clamp((T - (ph.until - 0.15)) / 0.15);ctx.globalAlpha = Math.min(fadeIn, fadeOut);ctx.fillStyle = theme.caption.bg;ctx.beginPath();- ctx.roundRect(W / 2 - boxW / 2, cy - boxH / 2, boxW, boxH, Math.min(22, boxH / 2));+ ctx.roundRect(cx - boxW / 2, cy - boxH / 2, boxW, boxH, Math.min(22, boxH / 2));ctx.fill();lines.forEach((l, li) => {const total = l.reduce((a, i, k) => a + widths[i] + (k ? space : 0), 0);- let x = W / 2 - total / 2;+ let x = cx - total / 2;const y = cy - boxH / 2 + size * 0.275 + lh * li + lh / 2;for (const i of l) {const w = ph.words[i];diff --git a/engine/layout.js b/engine/layout.jsnew file mode 100644index 0000000..2a581c7--- /dev/null+++ b/engine/layout.js@@ -0,0 +1,24 @@+// Where scene content may go. Normal sizes keep a 7% margin. Platform formats+// (tiktok, reels, shorts, vertical) keep clear of the app's own buttons and+// text, and with captions on, the captions sit at the bottom of that area.+export function layoutAreas(config, W, H) {+ const m = Math.round(Math.min(W, H) * 0.07);+ const f = config.safe;+ if (!f) {+ return { safe: { x: m, y: m, w: W - 2 * m, h: H - 2 * m, left: m, top: m, right: W - m, bottom: H - m }, captions: null };+ }+ const left = Math.round(W * f.left);+ const right = W - Math.round(W * f.right);+ const appTop = Math.round(H * f.top);+ // The watermark sits in the top right corner of the free area.+ const top = config.watermark ? appTop + Math.round(Math.min(W, H) * 0.028 * 1.6) + 16 : appTop;+ const appBottom = H - Math.round(H * f.bottom);+ let bottom = appBottom;+ let captions = null;+ if (config.captions) {+ captions = { cx: (left + right) / 2, bottom: appBottom - 10, maxWidth: right - left };+ // Room for two caption lines (58px text) plus a gap above them.+ bottom = appBottom - 10 - Math.round(58 * 1.3 * 2 + 58 * 0.55) - 24;+ }+ return { safe: { x: left, y: top, w: right - left, h: bottom - top, left, top, right, bottom }, captions, app: { left, top: appTop, right, bottom: appBottom } };+}diff --git a/engine/runtime.js b/engine/runtime.jsindex f0c7979..bc8c6f1 100644--- a/engine/runtime.js+++ b/engine/runtime.js@@ -7,6 +7,7 @@ import { Pen } from './pen.js';import { drawTransition } from './transitions.js';import { buildPhrases, drawCaptions } from './captions.js';import { hashStr, mulberry32, suggest, contrast, opaque, withAlpha } from './util.js';+import { layoutAreas } from './layout.js';const AUTO_TRANSITION = { paper: 'brush', clean: 'slide', chalk: 'brush', blueprint: 'wipe', midnight: 'zoom' };@@ -58,6 +59,10 @@ export class Engine {this.scenesModule = scenes;this.W = config.width;this.H = config.height;+ const areas = layoutAreas(config, this.W, this.H);+ this.safeArea = areas.safe;+ this.captionArea = areas.captions;+ this.appArea = areas.app || null;this.fps = config.fps;this.scale = scale;this.theme = getTheme(config.theme);@@ -154,7 +159,7 @@ export class Engine {}if (this.phrases.length) {ctx.setTransform(this.scale, 0, 0, this.scale, 0, 0);- drawCaptions(ctx, this.phrases, T, this.theme, this.W, this.H);+ drawCaptions(ctx, this.phrases, T, this.theme, this.W, this.H, this.captionArea);}if (this.config.watermark) {ctx.setTransform(this.scale, 0, 0, this.scale, 0, 0);@@ -163,7 +168,9 @@ export class Engine {}// Small text in the bottom right corner of every frame, on a soft backing- // so it stays readable over any scene.+ // so it stays readable over any scene. Platform formats cover that corner+ // with the app's own buttons, so there it sits at the top right of the part+ // of the frame the app leaves free.drawWatermark(ctx, text) {const th = this.theme;const m = Math.min(this.W, this.H);@@ -178,8 +185,8 @@ export class Engine {const w = ctx.measureText(text).width;const padX = size * 0.6;const h = size * 1.6;- const x = this.W - margin;- const y = this.H - margin - h / 2;+ const x = this.appArea ? this.appArea.right : this.W - margin;+ const y = this.appArea ? this.appArea.top + h / 2 : this.H - margin - h / 2;ctx.fillStyle = withAlpha(th.bg, 0.72);ctx.beginPath();ctx.roundRect(x - w - padX * 2, y - h / 2, w + padX * 2, h, h / 2);@@ -304,6 +311,13 @@ export class Engine {const label = tx.text.length > 40 ? tx.text.slice(0, 37) + '...' : tx.text;if (tx.x0 < -1 || tx.y0 < -1 || tx.x1 > W + 1 || tx.y1 > H + 1) {once(`off:${sc.id}:${tx.text}`, () => add('error', sc.id, t, `"${label}" runs off the frame (${Math.round(tx.x0)},${Math.round(tx.y0)} to ${Math.round(tx.x1)},${Math.round(tx.y1)} in a ${W}x${H} frame)`));+ } else if (this.appArea) {+ const a = this.appArea;+ if (tx.x0 < a.left - 2 || tx.y0 < a.top - 2 || tx.x1 > a.right + 2 || tx.y1 > a.bottom + 2) {+ once(`app:${sc.id}:${tx.text}`, () => add('warn', sc.id, t, `"${label}" is outside the ${this.config.format} safe area (${a.left},${a.top} to ${a.right},${a.bottom}), where the app's buttons, name or caption can cover it`));+ } else if (this.captionArea && tx.y1 > this.safeArea.bottom + 2 && tx.x1 > a.left && tx.x0 < a.right) {+ once(`cap:${sc.id}:${tx.text}`, () => add('warn', sc.id, t, `"${label}" reaches into the caption band below y=${this.safeArea.bottom}; keep scene content above s.safe.bottom`));+ }} else if (tx.x0 < margin || tx.y0 < margin || tx.x1 > W - margin || tx.y1 > H - margin) {once(`edge:${sc.id}:${tx.text}`, () => add('warn', sc.id, t, `"${label}" sits closer than ${margin}px to the edge`));}diff --git a/engine/stage.js b/engine/stage.jsindex 8c3ff76..fe2fc3a 100644--- a/engine/stage.js+++ b/engine/stage.js@@ -24,8 +24,14 @@ export class Stage {this.pen = engine.pen;this.W = engine.W;this.H = engine.H;- this.cx = this.W / 2;- this.cy = this.H / 2;+ // Platform formats (tiktok, reels, shorts...) keep content inside the part+ // of the frame the app leaves free, so the center moves with it.+ this.safe = engine.safeArea;+ this.platform = Boolean(engine.config.safe);+ this.cx = this.platform ? this.safe.x + this.safe.w / 2 : this.W / 2;+ this.cy = this.platform ? this.safe.y + this.safe.h / 2 : this.H / 2;+ // pace > 1 makes every animation, pause and numeric time shorter.+ this.pace = engine.timeline.pace || 1;this.t = t;this.T = scene.start + t;this.dur = scene.dur;@@ -41,8 +47,6 @@ export class Stage {this.ease = ease;this.lerp = lerp;this.clamp = clamp;- const m = Math.round(Math.min(this.W, this.H) * 0.07);- this.safe = { x: m, y: m, w: this.W - 2 * m, h: this.H - 2 * m, left: m, top: m, right: this.W - m, bottom: this.H - m };this._ids = new Map();this._kindSeq = Object.create(null);this._suppress = 0;@@ -86,7 +90,7 @@ export class Stage {// Accepts seconds, "#mark" or a spoken word/phrase.time(v) {- if (typeof v === 'number') return v;+ if (typeof v === 'number') return v / this.pace;if (typeof v === 'string') return v.startsWith('#') ? this.mark(v.slice(1)) : this.cue(v);if (v === undefined || v === null) return 0;throw new SceneError(`a time must be seconds, a spoken word or "#mark", not ${JSON.stringify(v)}`);@@ -95,7 +99,7 @@ export class Stage {// 0..1 progress of an animation that starts at `at` and lasts `dur`.p(at, dur = 0.6, easing = 'inOut') {const a = this.time(at);- return easeFn(easing)(clamp((this.t - a) / dur));+ return easeFn(easing)(clamp((this.t - a) / (dur / this.pace)));}since(at) {@@ -131,14 +135,14 @@ export class Stage {// ---------- layout ----------row(n, o = {}) {- const width = o.width ?? this.W * 0.72;+ const width = o.width ?? this._w(0.72);const x = o.x ?? this.cx;if (n <= 1) return [x];return Array.from({ length: n }, (_, i) => x - width / 2 + (width * i) / (n - 1));}col(n, o = {}) {- const height = o.height ?? this.H * 0.56;+ const height = o.height ?? (this.platform ? this.safe.h * 0.7 : this.H * 0.56);const y = o.y ?? this.cy;if (n <= 1) return [y];return Array.from({ length: n }, (_, i) => y - height / 2 + (height * i) / (n - 1));@@ -182,13 +186,13 @@ export class Stage {const enter = o.enter ?? extra.enter ?? this.theme.enter[kind] ?? this.theme.enter.shape ?? 'fade';const at = this.time(o.at ?? 0);const out = o.out === undefined ? Infinity : this.time(o.out);- const dur = o.dur ?? extra.dur ?? DEFAULT_DUR[enter] ?? 0.6;+ const dur = (o.dur ?? extra.dur ?? DEFAULT_DUR[enter] ?? 0.6) / this.pace;this._record(kind, at, dur, o, extra);if (this._suppress > 0) return null;if (this.t < at) return null;let q = 0;if (this.t >= out) {- q = clamp((this.t - out) / (o.outDur ?? 0.45));+ q = clamp((this.t - out) / ((o.outDur ?? 0.45) / this.pace));if (q >= 1 || o.exit === 'none') return null;}return { p: clamp((this.t - at) / dur), q, at, dur, enter, exit: o.exit ?? 'fade', local: this.t - at };@@ -421,12 +425,22 @@ export class Stage {return this._text(str, o, o.kind || 'text');}+ // A width of `f` times the frame, never wider than the platform safe area.+ _w(f) {+ return this.platform ? Math.min(this.W * f, this.safe.w) : this.W * f;+ }++ // A height `f` of the way down the frame (or down the safe area).+ _y(f) {+ return this.platform ? this.safe.y + this.safe.h * f : this.H * f;+ }+title(str, o = {}) {- return this._text(str, { font: 'display', size: 104, y: this.H * 0.44, maxWidth: this.W * 0.82, lineHeight: 1.12, ...o }, 'title');+ return this._text(str, { font: 'display', size: 104, y: this._y(0.44), maxWidth: this._w(0.82), lineHeight: 1.12, ...o }, 'title');}subtitle(str, o = {}) {- return this._text(str, { font: 'body', size: 46, color: 'muted', y: this.H * 0.6, maxWidth: this.W * 0.7, ...o }, 'text');+ return this._text(str, { font: 'body', size: 46, color: 'muted', y: this._y(0.6), maxWidth: this._w(0.7), ...o }, 'text');}note(str, o = {}) {@@ -442,7 +456,7 @@ export class Stage {const weight = o.weight ?? (o.bold ? BOLD[role] ?? 700 : undefined);const font = fontString(th, role, size, weight);const align = o.align ?? 'center';- const lay = layoutText(ctx, { str: String(str), font, size, maxWidth: o.maxWidth ?? o.width ?? this.W * 0.8, lineHeight: o.lineHeight ?? 1.24 });+ const lay = layoutText(ctx, { str: String(str), font, size, maxWidth: o.maxWidth ?? o.width ?? this._w(0.8), lineHeight: o.lineHeight ?? 1.24 });const x = o.x ?? this.cx;const y = o.y ?? this.cy;const left = align === 'left' ? x : align === 'right' ? x - lay.width : x - lay.width / 2;@@ -817,7 +831,7 @@ export class Stage {let w = o.w;let h = o.h;if (!w && !h) {- w = Math.min(this.W * 0.6, img.naturalWidth);+ w = Math.min(this._w(0.6), img.naturalWidth);h = w / ratio;} else if (!h) h = w / ratio;else if (!w) w = h * ratio;@@ -958,9 +972,9 @@ export class Stage {const th = this.theme;const ctx = this.ctx;const size = o.size ?? 50;- const x = o.x ?? this.W * 0.2;- let y = o.y ?? this.H * 0.3;- const width = o.width ?? this.W * 0.62;+ const x = o.x ?? (this.platform ? this.safe.x + this.safe.w * 0.06 : this.W * 0.2);+ let y = o.y ?? this._y(0.3);+ const width = o.width ?? this._w(0.62);const gap = o.gap ?? size * 0.55;const bullet = o.bullet ?? 'dot';const indent = size * 1.25;@@ -1051,8 +1065,8 @@ export class Stage {const items = data.map((d, i) => (typeof d === 'number' ? { value: d } : d)).map((d, i) => ({ ...d, color: d.color ?? palette(th, i) }));const x = o.x ?? this.cx;const y = o.y ?? this.cy;- const w = o.w ?? this.W * 0.56;- const h = o.h ?? this.H * 0.46;+ const w = o.w ?? this._w(0.56);+ const h = o.h ?? (this.platform ? this.safe.h * 0.46 : this.H * 0.46);const max = o.max ?? Math.max(...items.map((d) => d.value)) * 1.12;const n = items.length;const slot = w / n;@@ -1121,8 +1135,8 @@ export class Stage {const ctx = this.ctx;const x = o.x ?? this.cx;const y = o.y ?? this.cy;- const w = o.w ?? this.W * 0.6;- const h = o.h ?? this.H * 0.44;+ const w = o.w ?? this._w(0.6);+ const h = o.h ?? (this.platform ? this.safe.h * 0.44 : this.H * 0.44);const lo = o.min ?? Math.min(0, ...values);const hi = o.max ?? Math.max(...values) * 1.1;const pts = values.map((v, i) => [x - w / 2 + (w * i) / Math.max(1, values.length - 1), y + h / 2 - ((v - lo) / (hi - lo || 1)) * h]);@@ -1233,7 +1247,7 @@ export class Stage {const charW = ctx.measureText('M').width;ctx.restore();const numW = o.lineNumbers === false ? 0 : charW * (String(lines.length).length + 2);- const w = o.w ?? Math.min(this.W * 0.86, Math.max(...lines.map((l) => l.length)) * charW + numW + pad * 2);+ const w = o.w ?? Math.min(this._w(0.86), Math.max(...lines.map((l) => l.length)) * charW + numW + pad * 2);const h = o.h ?? lines.length * lh + pad * 1.6 + barH;const x = o.x ?? this.cx;const y = o.y ?? this.cy;@@ -1330,7 +1344,7 @@ export class Stage {const pad = size * 0.9;const barH = size * 1.5;const items = lines.map((l) => (typeof l === 'string' ? (l.startsWith('$ ') ? { cmd: l.slice(2) } : { out: l }) : l));- const w = o.w ?? this.W * 0.62;+ const w = o.w ?? this._w(0.62);const rows = items.reduce((n, it) => n + String(it.cmd ?? it.out ?? '').split('\n').length, 0);const h = o.h ?? Math.max(rows, o.rows ?? 0) * lh + barH + pad * 1.6;const x = o.x ?? this.cx;diff --git a/src/cli.js b/src/cli.jsindex 2c92f49..9be4881 100644--- a/src/cli.js+++ b/src/cli.js@@ -1,7 +1,7 @@// explainroo command line.import fs from 'node:fs';import path from 'node:path';-import { loadProject, ProjectError, THEMES, MUSIC_STYLES } from './project.js';+import { loadProject, ProjectError, THEMES, MUSIC_STYLES, FORMATS, resolveSize, normalizeConfig } from './project.js';import { ScriptError } from './script.js';import { prepare, makeState } from './pipeline.js';import { render } from './render.js';@@ -20,7 +20,7 @@ const HELP = `explainroo ${VERSION}: narrated explainer videos from codeUsage: explainroo <command> [project] [options]Make a video- init <dir> create a project (--theme, --size, --voice, --title)+ init <dir> create a project (--theme, --size, --pace, --voice, --title)voice [project] generate narration and word timings (cached)preview [project] live preview in your browser, reloads on save (--port)still [project] [t…] PNG stills: "12.5", "scene", "[email protected]" (default: end of every scene)@@ -37,6 +37,7 @@ Images (optional, needs an OpenRouter API key)Referencevoices list voices; "explainroo say 'text' --voice am_michael" to hear onethemes list looks+ formats list sizes for YouTube, Shorts, TikTok, Reels, Instagram, LinkedInicons <word…> search the 1,800+ built-in iconsdoctor check ffmpeg, Chrome and the speech models (--fetch downloads them)@@ -179,6 +180,14 @@ export async function main(argv) {print(THEMES.map((t) => `${t.padEnd(10)} ${desc[t]}`).join('\n') + `\n\nmusic styles: ${MUSIC_STYLES.join(', ')}`, { themes: desc, music: MUSIC_STYLES });return 0;}+ case 'formats': {+ const rows = Object.entries(FORMATS).map(([name, f]) => {+ const safe = f.safe ? ` keeps clear: top ${pct(f.safe.top)}, bottom ${pct(f.safe.bottom)}, left ${pct(f.safe.left)}, right ${pct(f.safe.right)}` : '';+ return `${name.padEnd(10)} ${`${f.size[0]}x${f.size[1]}`.padEnd(10)} ${f.use}${safe}`;+ });+ print(rows.join('\n') + '\n\nAlso: 16:9, 9:16, 1:1, 4:5 or WIDTHxHEIGHT. Set it with "size" in video.json or init --size.', { formats: FORMATS });+ return 0;+ }case 'icons': return icons(pos, print);case 'doctor': return doctor(flags, log, print);default:@@ -198,8 +207,12 @@ export async function main(argv) {}}+function pct(x) {+ return `${Math.round(x * 100)}%`;+}+function init(dir, flags, print) {- if (!dir) throw new ProjectError('usage: explainroo init <dir> [--theme paper] [--size 16:9] [--voice af_heart] [--title "..."]');+ if (!dir) throw new ProjectError('usage: explainroo init <dir> [--theme paper] [--size youtube|tiktok|linkedin|...] [--pace 1.2] [--voice af_heart] [--title "..."]');const target = path.resolve(dir);if (fs.existsSync(path.join(target, 'video.json'))) throw new ProjectError(`${target} already has a video.json`);const theme = flags.theme || 'paper';@@ -209,7 +222,11 @@ function init(dir, flags, print) {const title = flags.title || path.basename(target).replace(/[-_]+/g, ' ').replace(/^\w/, (c) => c.toUpperCase());fs.mkdirSync(path.join(target, 'assets'), { recursive: true });const tpl = path.join(ROOT, 'templates', 'starter');- const config = { title, theme, size: flags.size || '16:9', voice, music: true, captions: 'auto' };+ const size = flags.size || '16:9';+ resolveSize(size);+ const config = { title, theme, size, voice, music: true, captions: 'auto' };+ if (flags.pace !== undefined) config.pace = num(flags.pace, 'pace');+ normalizeConfig(config);fs.writeFileSync(path.join(target, 'video.json'), JSON.stringify(config, null, 2) + '\n');fs.writeFileSync(path.join(target, 'script.md'), fs.readFileSync(path.join(tpl, 'script.md'), 'utf8').replace('{{title}}', title));fs.writeFileSync(path.join(target, 'scenes.js'), fs.readFileSync(path.join(tpl, 'scenes.js'), 'utf8').replace(/\{\{title\}\}/g, title.replace(/'/g, "\\'")));diff --git a/src/project.js b/src/project.jsindex 2139bfc..17705a6 100644--- a/src/project.js+++ b/src/project.js@@ -14,6 +14,21 @@ export const TRANSITIONS = ['auto', 'fade', 'slide', 'wipe', 'zoom', 'brush', 'cexport const THEME_MUSIC = { paper: 'warm', clean: 'upbeat', chalk: 'calm', blueprint: 'tech', midnight: 'tech' };const ASPECTS = { '16:9': [1920, 1080], '9:16': [1080, 1920], '1:1': [1080, 1080], '4:5': [1080, 1350] };+// Named formats for the usual places a video goes. Vertical apps draw their+// own buttons, names and captions over the video; `safe` is the part of the+// frame they leave free, as fractions of the frame. The numbers follow the+// platforms' safe-zone templates as of 2026 and move a little with app updates.+export const FORMATS = {+ youtube: { size: [1920, 1080], use: 'YouTube and other wide players' },+ shorts: { size: [1080, 1920], use: 'YouTube Shorts', safe: { top: 0.15, right: 0.12, bottom: 0.35, left: 0.06 } },+ tiktok: { size: [1080, 1920], use: 'TikTok', safe: { top: 0.125, right: 0.2, bottom: 0.34, left: 0.11 } },+ reels: { size: [1080, 1920], use: 'Instagram and Facebook Reels', safe: { top: 0.14, right: 0.11, bottom: 0.35, left: 0.06 } },+ vertical: { size: [1080, 1920], use: 'one file for Shorts, TikTok and Reels', safe: { top: 0.15, right: 0.2, bottom: 0.35, left: 0.11 } },+ instagram: { size: [1080, 1350], use: 'Instagram and Facebook feed posts' },+ linkedin: { size: [1080, 1350], use: 'the LinkedIn feed' },+ square: { size: [1080, 1080], use: 'square posts on X, LinkedIn and Facebook' },+};+export const DEFAULTS = {title: null,theme: 'paper',@@ -21,6 +36,7 @@ export const DEFAULTS = {fps: 30,voice: 'af_heart',speed: 0.9,+ pace: 1,music: true,sfx: true,captions: 'auto',@@ -44,9 +60,10 @@ function fail(msg) {}export function resolveSize(size) {+ if (FORMATS[size]) return { width: FORMATS[size].size[0], height: FORMATS[size].size[1], safe: FORMATS[size].safe || null };if (ASPECTS[size]) return { width: ASPECTS[size][0], height: ASPECTS[size][1] };const m = /^(\d{3,4})x(\d{3,4})$/.exec(String(size));- if (!m) fail(`size must be one of ${Object.keys(ASPECTS).join(', ')} or WIDTHxHEIGHT, not "${size}"`);+ if (!m) fail(`size must be a format (${Object.keys(FORMATS).join(', ')}), a ratio (${Object.keys(ASPECTS).join(', ')}) or WIDTHxHEIGHT, not "${size}"`);const width = Number(m[1]);const height = Number(m[2]);if (width % 2 || height % 2) fail('size width and height must be even numbers (H.264 needs that)');@@ -60,6 +77,8 @@ export function normalizeConfig(raw) {if (!THEMES.includes(cfg.theme)) fail(`theme must be one of ${THEMES.join(', ')}, not "${cfg.theme}"`);if (!VOICES[cfg.voice]) fail(`voice "${cfg.voice}" does not exist. Run "explainroo voices" for the list.`);if (!(cfg.speed >= 0.6 && cfg.speed <= 1.6)) fail('speed must be between 0.6 and 1.6');+ if (!(cfg.pace >= 0.7 && cfg.pace <= 1.6)) fail('pace must be between 0.7 and 1.6 (1 is normal, 1.3 is 30% faster)');+ if (cfg.speed * cfg.pace > 1.8) fail(`speed ${cfg.speed} times pace ${cfg.pace} makes the voice too fast; keep speed x pace at 1.8 or below`);if (![24, 25, 30, 50, 60].includes(cfg.fps)) fail('fps must be 24, 25, 30, 50 or 60');if (!TRANSITIONS.includes(cfg.transition)) fail(`transition must be one of ${TRANSITIONS.join(', ')}`);if (![true, false, 'minimal'].includes(cfg.sfx)) fail('sfx must be true, false or "minimal"');@@ -82,15 +101,18 @@ export function normalizeConfig(raw) {if (music === true) music = { style: THEME_MUSIC[cfg.theme] };else if (typeof music === 'string') music = { style: music };if (music) {- music = { volume: 0.5, seed: cfg.seed, ...music };+ // A faster pace plays the music a little faster too.+ music = { volume: 0.5, seed: cfg.seed, tempo: Math.sqrt(cfg.pace), ...music };if (!MUSIC_STYLES.includes(music.style)) fail(`music style must be one of ${MUSIC_STYLES.join(', ')}, not "${music.style}"`);if (!(music.volume >= 0 && music.volume <= 1)) fail('music.volume must be between 0 and 1');}cfg.music = music || null;- const { width, height } = resolveSize(cfg.size);+ const { width, height, safe } = resolveSize(cfg.size);cfg.width = width;cfg.height = height;+ cfg.format = FORMATS[cfg.size] ? cfg.size : null;+ cfg.safe = safe || null;if (cfg.captions === 'auto') cfg.captions = height >= width;return cfg;}diff --git a/src/script.js b/src/script.jsindex 334eaa6..a640953 100644--- a/src/script.js+++ b/src/script.js@@ -195,7 +195,7 @@ export function parseScript(source) {// the text between explicit pauses) and is sent to the TTS model on its own,// which keeps every request well under the model's context limit and gives// exact control over the silence between sentences.-export function speechChunks(units, { sentenceGap = 0.3, paragraphGap = 0.55 } = {}) {+export function speechChunks(units, { sentenceGap = 0.3, paragraphGap = 0.55, pace = 1 } = {}) {const chunks = [];let cur = null;let gapBefore = 0;@@ -206,7 +206,7 @@ export function speechChunks(units, { sentenceGap = 0.3, paragraphGap = 0.55 } =units.forEach((u, index) => {if (u.type === 'pause') {close();- gapBefore = u.paragraph ? Math.max(gapBefore, paragraphGap) : gapBefore + u.sec;+ gapBefore = u.paragraph ? Math.max(gapBefore, paragraphGap / pace) : gapBefore + u.sec / pace;return;}if (u.type !== 'word') return;@@ -218,7 +218,7 @@ export function speechChunks(units, { sentenceGap = 0.3, paragraphGap = 0.55 } =cur.words.push({ unitIndex: index, display: u.display, spoken: u.spoken });if (/[.!?…]["'’)\]]*$/.test(u.spoken)) {close();- gapBefore = sentenceGap;+ gapBefore = sentenceGap / pace;}});close();diff --git a/src/timeline.js b/src/timeline.jsindex e011702..a192fd5 100644--- a/src/timeline.js+++ b/src/timeline.js@@ -1,12 +1,14 @@// Lays scenes end to end. A scene lasts for its lead-in, its narration and a// short hold; scenes without narration last `min` seconds (default 3).-// All times are snapped to the frame grid.+// `pace` shortens every lead-in, hold and transition (the voice is already+// faster). All times are snapped to the frame grid.export const TRANSITION_SECONDS = 0.7;export function buildTimeline(project, voices) {const { config, script } = project;const fps = config.fps;+ const pace = config.pace || 1;const snap = (t) => Math.round(t * fps) / fps;const scenes = [];const voiceSpans = [];@@ -14,11 +16,11 @@ export function buildTimeline(project, voices) {script.scenes.forEach((scene, index) => {const v = voices[scene.id] || { duration: 0, words: [], marks: {}, chunks: [] };const a = scene.attrs;- const lead = v.duration ? (a.lead ?? config.lead) : 0;+ const lead = v.duration ? (a.lead ?? config.lead) / pace : 0;const isLast = index === script.scenes.length - 1;- const hold = (a.hold ?? config.hold) + (isLast ? config.end : 0);- let dur = v.duration ? lead + v.duration + hold : (a.min ?? 3) + (isLast ? config.end : 0);- if (a.min) dur = Math.max(dur, a.min);+ const hold = ((a.hold ?? config.hold) + (isLast ? config.end : 0)) / pace;+ let dur = v.duration ? lead + v.duration + hold : ((a.min ?? 3) + (isLast ? config.end : 0)) / pace;+ if (a.min) dur = Math.max(dur, a.min / pace);dur = Math.max(snap(dur), 1);const start = snap(t);const transition = index === 0 ? 'none' : (a.transition || config.transition);@@ -44,7 +46,8 @@ export function buildTimeline(project, voices) {height: config.height,duration: snap(t),frames: Math.round(snap(t) * fps),- transitionSeconds: TRANSITION_SECONDS,+ transitionSeconds: TRANSITION_SECONDS / pace,+ pace,scenes,voiceSpans,};diff --git a/src/voice.js b/src/voice.jsindex 4f5bdc7..f840fb6 100644--- a/src/voice.js+++ b/src/voice.js@@ -20,7 +20,7 @@ function sceneHash(scene, chunks, config) {ASR_MODEL,dtype: ttsDtype(),voice: config.voice,- speed: config.speed,+ speed: config.speed * config.pace,chunks: chunks.map((c) => [c.gapBefore, c.text]),})).digest('hex')@@ -48,7 +48,7 @@ export async function synthesize(project, { force = false, log = () => {}, onlyconst result = {};const todo = [];for (const scene of project.script.scenes) {- const chunks = speechChunks(scene.units, { sentenceGap: config.sentenceGap, paragraphGap: config.paragraphGap });+ const chunks = speechChunks(scene.units, { sentenceGap: config.sentenceGap, paragraphGap: config.paragraphGap, pace: config.pace });const hash = sceneHash(scene, chunks, config);const cached = readVoice(project, scene.id);const hasAudio = !chunks.length || fs.existsSync(voicePaths(project, scene.id).wav);@@ -102,7 +102,7 @@ async function synthesizeScene(project, scene, chunks, hash, tts, log) {pieces.push(new Float32Array(Math.round(gap * sr)));cursor += Math.round(gap * sr);}- const audio = await tts.generate(chunk.text, { voice: config.voice, speed: config.speed });+ const audio = await tts.generate(chunk.text, { voice: config.voice, speed: config.speed * config.pace });const samples = trimSilence(audio.audio, audio.sampling_rate || sr);const start = cursor / sr;const dur = samples.length / sr;diff --git a/templates/starter/scenes.js b/templates/starter/scenes.jsindex f826b27..6e73f9a 100644--- a/templates/starter/scenes.js+++ b/templates/starter/scenes.js@@ -5,22 +5,27 @@export default {hook(s) {- s.title('{{title}}', { y: s.H * 0.4 });- s.icon('mouse-pointer-click', { y: s.H * 0.66, size: 130, at: '#click', color: 'accent' });+ s.title('{{title}}', { y: s.safe.y + s.safe.h * 0.38 });+ s.icon('mouse-pointer-click', { y: s.safe.y + s.safe.h * 0.7, size: 130, at: '#click', color: 'accent' });},steps(s) {- s.text('Three steps', { font: 'display', size: 76, y: 170, at: 0 });- const xs = s.row(3, { width: 1180 });- s.box('Find the server', { id: 'find', x: xs[0], y: 560, icon: 'search', color: 'blue', at: '#one' });- s.box('Ask for the page', { id: 'ask', x: xs[1], y: 560, icon: 'send', color: 'green', at: '#two' });- s.box('Draw it', { id: 'draw', x: xs[2], y: 560, icon: 'paintbrush', color: 'purple', at: '#three' });+ // s.safe is the part of the frame that is free for content. Wide videos+ // show the steps side by side, tall ones stack them.+ const tall = s.H > s.W;+ s.text('Three steps', { font: 'display', size: 76, y: s.safe.y + 50, at: 0 });+ const spots = tall+ ? s.col(3, { y: s.safe.y + s.safe.h * 0.6, height: s.safe.h * 0.66 }).map((y) => ({ x: s.cx, y }))+ : s.row(3, { width: Math.min(1180, s.safe.w - 260) }).map((x) => ({ x, y: s.cy }));+ s.box('Find the server', { id: 'find', ...spots[0], icon: 'search', color: 'blue', at: '#one' });+ s.box('Ask for the page', { id: 'ask', ...spots[1], icon: 'send', color: 'green', at: '#two' });+ s.box('Draw it', { id: 'draw', ...spots[2], icon: 'paintbrush', color: 'purple', at: '#three' });s.arrow('find', 'ask', { at: s.cue('Then') - 0.4 });s.arrow('ask', 'draw', { at: s.cue('Finally') - 0.4 });},outro(s) {- s.number(3, { suffix: ' steps', y: s.H * 0.42, at: 0.2 });- s.subtitle('in less time than a blink', { at: '#fast', y: s.H * 0.62 });+ s.number(3, { suffix: ' steps', y: s.safe.y + s.safe.h * 0.42, at: 0.2 });+ s.subtitle('in less time than a blink', { at: '#fast', y: s.safe.y + s.safe.h * 0.62 });},};diff --git a/test/formats-pace.test.js b/test/formats-pace.test.jsnew file mode 100644index 0000000..3312e9b--- /dev/null+++ b/test/formats-pace.test.js@@ -0,0 +1,65 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { parseScript, speechChunks } from '../src/script.js';+import { normalizeConfig, resolveSize, FORMATS, ProjectError } from '../src/project.js';+import { buildTimeline } from '../src/timeline.js';+import { layoutAreas } from '../engine/layout.js';++const close = (a, b) => assert.ok(Math.abs(a - b) < 1e-9, `${a} is not ${b}`);++test('named formats resolve to their size and safe area', () => {+ assert.deepEqual(resolveSize('youtube'), { width: 1920, height: 1080, safe: null });+ assert.equal(resolveSize('tiktok').height, 1920);+ assert.ok(resolveSize('tiktok').safe.bottom > 0.3);+ assert.deepEqual(resolveSize('linkedin'), { width: 1080, height: 1350, safe: null });+ const cfg = normalizeConfig({ size: 'reels' });+ assert.equal(cfg.format, 'reels');+ assert.equal(cfg.captions, true);+ assert.deepEqual(cfg.safe, FORMATS.reels.safe);+ assert.equal(normalizeConfig({ size: '9:16' }).safe, null);+ assert.throws(() => normalizeConfig({ size: 'myspace' }), ProjectError);+});++test('platform safe area keeps content above the captions and clear of the buttons', () => {+ const cfg = normalizeConfig({ size: 'tiktok' });+ const { safe, captions, app } = layoutAreas(cfg, 1080, 1920);+ assert.equal(app.bottom, 1920 - Math.round(1920 * FORMATS.tiktok.safe.bottom));+ assert.ok(captions.bottom < app.bottom);+ assert.ok(safe.bottom < captions.bottom - 150);+ assert.equal(safe.right, 1080 - Math.round(1080 * FORMATS.tiktok.safe.right));+ const plain = layoutAreas(normalizeConfig({ size: '16:9' }), 1920, 1080);+ assert.equal(plain.captions, null);+ assert.equal(plain.safe.left, Math.round(1080 * 0.07));+});++test('pace must stay in range and must not make the voice too fast', () => {+ assert.equal(normalizeConfig({}).pace, 1);+ assert.equal(normalizeConfig({ pace: 1.3 }).pace, 1.3);+ assert.throws(() => normalizeConfig({ pace: 3 }), ProjectError);+ assert.throws(() => normalizeConfig({ speed: 1.5, pace: 1.3 }), ProjectError);+ assert.equal(normalizeConfig({ pace: 1.44 }).music.tempo, 1.2);+});++test('pace shortens pauses between sentences and explicit pauses', () => {+ const { scenes } = parseScript('## a\nOne. Two. [pause 1] Three.');+ const normal = speechChunks(scenes[0].units, { sentenceGap: 0.3 });+ const fast = speechChunks(scenes[0].units, { sentenceGap: 0.3, pace: 1.5 });+ assert.equal(normal[1].gapBefore, 0.3);+ close(fast[1].gapBefore, 0.2);+ assert.ok(Math.abs(normal[2].gapBefore - 1.3) < 1e-9);+ assert.ok(Math.abs(fast[2].gapBefore - 1.3 / 1.5) < 1e-9);+});++test('pace shortens lead-ins, holds and transitions', () => {+ const src = '## a\nHi.\n\n## b {min=3}\n';+ const voice = { a: { duration: 1, words: [{ text: 'Hi.', start: 0, end: 1 }], marks: {}, chunks: [{ start: 0, end: 1 }] } };+ const cfg = { fps: 30, lead: 0.3, hold: 0.6, end: 0 };+ const normal = buildTimeline({ config: normalizeConfig(cfg), script: parseScript(src) }, voice);+ const fast = buildTimeline({ config: normalizeConfig({ ...cfg, pace: 1.5 }), script: parseScript(src) }, voice);+ assert.equal(normal.scenes[0].dur, Math.round((0.3 + 1 + 0.6) * 30) / 30);+ assert.equal(fast.scenes[0].dur, Math.round((0.2 + 1 + 0.4) * 30) / 30);+ close(fast.scenes[0].words[0].start, 0.2);+ assert.equal(fast.scenes[1].dur, 2);+ assert.ok(fast.transitionSeconds < normal.transitionSeconds);+ assert.equal(fast.pace, 1.5);+});