@phil65/demoreel 0.0.0-stage → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +207 -2
  3. package/THIRD_PARTY_NOTICES.md +31 -0
  4. package/dist/args.d.ts +41 -0
  5. package/dist/args.js +252 -0
  6. package/dist/cli.d.ts +2 -0
  7. package/dist/cli.js +468 -0
  8. package/dist/compose.d.ts +73 -0
  9. package/dist/compose.js +144 -0
  10. package/dist/env.d.ts +38 -0
  11. package/dist/env.js +182 -0
  12. package/dist/idle.d.ts +48 -0
  13. package/dist/idle.js +99 -0
  14. package/dist/index.d.ts +14 -0
  15. package/dist/index.js +13 -0
  16. package/dist/init.d.ts +19 -0
  17. package/dist/init.js +92 -0
  18. package/dist/layout.d.ts +52 -0
  19. package/dist/layout.js +55 -0
  20. package/dist/load.d.ts +2 -0
  21. package/dist/load.js +76 -0
  22. package/dist/marks.d.ts +69 -0
  23. package/dist/marks.js +153 -0
  24. package/dist/motion.d.ts +15 -0
  25. package/dist/motion.js +49 -0
  26. package/dist/openscreen/project.js +793 -0
  27. package/dist/openscreen.d.ts +14 -0
  28. package/dist/openscreen.js +41 -0
  29. package/dist/project.d.ts +143 -0
  30. package/dist/project.js +144 -0
  31. package/dist/record.d.ts +90 -0
  32. package/dist/record.js +189 -0
  33. package/dist/recorder.d.ts +41 -0
  34. package/dist/recorder.js +149 -0
  35. package/dist/render.d.ts +58 -0
  36. package/dist/render.js +139 -0
  37. package/dist/renderer/assets/CanvasPool-CHSHS1-v.js +23 -0
  38. package/dist/renderer/assets/Cursor_App-Starting-zEGhqPJj.svg +8 -0
  39. package/dist/renderer/assets/Cursor_Cross-BuZZnB_U.svg +5 -0
  40. package/dist/renderer/assets/Cursor_Default-DkmrqhKh.svg +5 -0
  41. package/dist/renderer/assets/Cursor_Hand-(Grabbing)-B-Qy-RsV.svg +5 -0
  42. package/dist/renderer/assets/Cursor_Hand-(Open)-DGrW1tFF.svg +5 -0
  43. package/dist/renderer/assets/Cursor_Hand-(Pointing)-Byy2KbtA.svg +5 -0
  44. package/dist/renderer/assets/Cursor_Help-D5NcyFpT.svg +8 -0
  45. package/dist/renderer/assets/Cursor_Move-CerM5f-0.svg +5 -0
  46. package/dist/renderer/assets/Cursor_Not-Allowed-3rttFVa5.svg +7 -0
  47. package/dist/renderer/assets/Cursor_Resize-North-East-South-West-CBd4tbCA.svg +5 -0
  48. package/dist/renderer/assets/Cursor_Resize-North-South-DOxgUIwF.svg +5 -0
  49. package/dist/renderer/assets/Cursor_Resize-North-West-South-East-hzXJFJ2_.svg +5 -0
  50. package/dist/renderer/assets/Cursor_Resize-West-East-rDJgc6AZ.svg +5 -0
  51. package/dist/renderer/assets/Cursor_Text-Cursor-Cn9rFLjY.svg +5 -0
  52. package/dist/renderer/assets/Cursor_Up-Arrow-CYyEN-dA.svg +4 -0
  53. package/dist/renderer/assets/Cursor_Wait-CK8tq-9y.svg +6 -0
  54. package/dist/renderer/assets/RenderTargetSystem-EAUH9iQk.js +404 -0
  55. package/dist/renderer/assets/browserAll-aHn2isHo.js +14 -0
  56. package/dist/renderer/assets/canvasUtils-n5g2f3_X.js +1 -0
  57. package/dist/renderer/assets/getTexelRangeRects-yD6MQ0xy.js +195 -0
  58. package/dist/renderer/assets/getTextureBatchBindGroup-Bwvgbco6.js +1 -0
  59. package/dist/renderer/assets/gif.worker-CjkyQP34.js +3 -0
  60. package/dist/renderer/assets/index-BwP6rH7I.js +556 -0
  61. package/dist/renderer/assets/init-C2Za5NQh.js +83 -0
  62. package/dist/renderer/assets/webworkerAll-JSSmbaR2.js +1 -0
  63. package/dist/renderer/index.html +13 -0
  64. package/dist/renderer/wallpapers/wallpaper1.jpg +0 -0
  65. package/dist/renderer/wallpapers/wallpaper12.jpg +0 -0
  66. package/dist/renderer/wallpapers/wallpaper5.jpg +0 -0
  67. package/dist/renderer/wasm/web-demuxer.wasm +0 -0
  68. package/dist/scene.d.ts +203 -0
  69. package/dist/scene.js +634 -0
  70. package/dist/server.d.ts +12 -0
  71. package/dist/server.js +116 -0
  72. package/dist/sheet.d.ts +37 -0
  73. package/dist/sheet.js +98 -0
  74. package/dist/types.d.ts +103 -0
  75. package/dist/types.js +2 -0
  76. package/dist/zoom.d.ts +57 -0
  77. package/dist/zoom.js +178 -0
  78. package/examples/demo-app/index.html +99 -0
  79. package/examples/local-demo.ts +21 -0
  80. package/licenses/colord.txt +21 -0
  81. package/licenses/earcut.txt +15 -0
  82. package/licenses/eventemitter3.txt +21 -0
  83. package/licenses/gif.js.txt +1 -0
  84. package/licenses/ismobilejs.txt +21 -0
  85. package/licenses/mediabunny.txt +373 -0
  86. package/licenses/motion-dom.txt +21 -0
  87. package/licenses/motion-utils.txt +21 -0
  88. package/licenses/openscreen.txt +21 -0
  89. package/licenses/parse-svg-path.txt +23 -0
  90. package/licenses/pixi-filters.txt +21 -0
  91. package/licenses/pixi.js.txt +21 -0
  92. package/licenses/web-demuxer.txt +21 -0
  93. package/package.json +74 -4
package/dist/env.d.ts ADDED
@@ -0,0 +1,38 @@
1
+ import type { Browser, BrowserType, LaunchOptions } from "playwright";
2
+ export declare class DemoreelError extends Error {
3
+ readonly fix?: string;
4
+ constructor(message: string, fix?: string);
5
+ }
6
+ export declare const INSTALL_CHROMIUM: string;
7
+ /** Playwright's `chromium`, from the `playwright` peer dependency (or `playwright-core`). */
8
+ export declare function loadChromium(): Promise<BrowserType>;
9
+ /** Launches headless Chromium, turning Playwright's install errors into actionable ones. */
10
+ export declare function launchChromium(opts?: LaunchOptions): Promise<Browser>;
11
+ /** The ffmpeg binary: $DEMOREEL_FFMPEG, $FFMPEG_PATH or `ffmpeg` on PATH. */
12
+ export declare function ffmpegBin(): string;
13
+ export declare function ffprobeBin(): string;
14
+ /** Throws a DemoreelError unless ffmpeg (with libx264) is available. */
15
+ export declare function checkFfmpeg(bin?: string): void;
16
+ /** Runs a command, resolving with stdout; rejects with the tail of stderr. */
17
+ export declare function run(cmd: string, args: string[], opts?: {
18
+ cwd?: string;
19
+ }): Promise<string>;
20
+ export declare const SOFTWARE_GL_ARGS: string[];
21
+ /** Candidate GPU flag sets per platform, best first. */
22
+ export declare function gpuArgCandidates(platform?: NodeJS.Platform): string[][];
23
+ export interface GpuProbe {
24
+ gpu: boolean;
25
+ args: string[];
26
+ renderer: string;
27
+ /** VideoEncoder supports H.264 (avc1.640033) at 1080p. */
28
+ h264: boolean;
29
+ }
30
+ /** Finds a working hardware GL flag set, else returns the SwiftShader (software) one. */
31
+ export declare function detectGpu(): Promise<GpuProbe>;
32
+ export type GpuMode = boolean | "auto";
33
+ /** Chromium args for rendering: GPU when asked/available, SwiftShader otherwise. */
34
+ export declare function renderArgs(mode: GpuMode, log?: (msg: string) => void): Promise<{
35
+ args: string[];
36
+ gpu: boolean;
37
+ renderer?: string;
38
+ }>;
package/dist/env.js ADDED
@@ -0,0 +1,182 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ /**
10
+ * Runtime environment: Playwright/Chromium, ffmpeg and GPU detection, with errors that say
11
+ * exactly how to fix the problem.
12
+ */
13
+ import { spawn, spawnSync } from "node:child_process";
14
+ export class DemoreelError extends Error {
15
+ fix;
16
+ constructor(message, fix) {
17
+ super(fix ? `${message}\n fix: ${fix}` : message);
18
+ this.name = "DemoreelError";
19
+ this.fix = fix;
20
+ }
21
+ }
22
+ const isLinux = process.platform === "linux";
23
+ export const INSTALL_CHROMIUM = isLinux ? "npx playwright install --with-deps chromium" : "npx playwright install chromium";
24
+ let chromiumPromise = null;
25
+ /** Playwright's `chromium`, from the `playwright` peer dependency (or `playwright-core`). */
26
+ export function loadChromium() {
27
+ chromiumPromise ??= (async () => {
28
+ for (const name of ["playwright", "playwright-core"]) {
29
+ try {
30
+ const mod = (await import(__rewriteRelativeImportExtension(name)));
31
+ const chromium = mod.chromium ?? mod.default?.chromium;
32
+ if (chromium)
33
+ return chromium;
34
+ }
35
+ catch {
36
+ // try the next one
37
+ }
38
+ }
39
+ throw new DemoreelError("Playwright is not installed (demoreel needs it as a peer dependency).", `npm install -D playwright && ${INSTALL_CHROMIUM}`);
40
+ })();
41
+ return chromiumPromise;
42
+ }
43
+ /** Launches headless Chromium, turning Playwright's install errors into actionable ones. */
44
+ export async function launchChromium(opts = {}) {
45
+ const chromium = await loadChromium();
46
+ try {
47
+ return await chromium.launch({ headless: true, ...opts });
48
+ }
49
+ catch (e) {
50
+ const msg = e.message ?? String(e);
51
+ if (/Executable doesn't exist|browserType\.launch: .*not found|Please run the following command/i.test(msg)) {
52
+ throw new DemoreelError("Chromium for Playwright is not installed.", INSTALL_CHROMIUM);
53
+ }
54
+ if (/error while loading shared libraries|Host system is missing dependencies/i.test(msg)) {
55
+ throw new DemoreelError("Chromium cannot start: system libraries are missing.", "npx playwright install-deps chromium (needs sudo)");
56
+ }
57
+ throw e;
58
+ }
59
+ }
60
+ /** The ffmpeg binary: $DEMOREEL_FFMPEG, $FFMPEG_PATH or `ffmpeg` on PATH. */
61
+ export function ffmpegBin() {
62
+ return process.env.DEMOREEL_FFMPEG || process.env.FFMPEG_PATH || "ffmpeg";
63
+ }
64
+ export function ffprobeBin() {
65
+ if (process.env.DEMOREEL_FFPROBE)
66
+ return process.env.DEMOREEL_FFPROBE;
67
+ const ff = ffmpegBin();
68
+ return ff === "ffmpeg" ? "ffprobe" : ff.replace(/ffmpeg(\.exe)?$/, "ffprobe$1");
69
+ }
70
+ const FFMPEG_FIX = process.platform === "darwin"
71
+ ? "brew install ffmpeg"
72
+ : process.platform === "win32"
73
+ ? "winget install ffmpeg (or set DEMOREEL_FFMPEG=C:\\path\\to\\ffmpeg.exe)"
74
+ : "sudo apt install ffmpeg (or dnf/pacman; or set DEMOREEL_FFMPEG=/path/to/ffmpeg)";
75
+ /** Throws a DemoreelError unless ffmpeg (with libx264) is available. */
76
+ export function checkFfmpeg(bin = ffmpegBin()) {
77
+ const r = spawnSync(bin, ["-hide_banner", "-encoders"], { encoding: "utf8" });
78
+ if (r.error || r.status !== 0) {
79
+ throw new DemoreelError(`ffmpeg not found (tried "${bin}"); it encodes the recording.`, FFMPEG_FIX);
80
+ }
81
+ if (!/libx264/.test(r.stdout)) {
82
+ throw new DemoreelError(`ffmpeg at "${bin}" has no libx264 encoder.`, FFMPEG_FIX);
83
+ }
84
+ }
85
+ /** Runs a command, resolving with stdout; rejects with the tail of stderr. */
86
+ export function run(cmd, args, opts = {}) {
87
+ return new Promise((resolve, reject) => {
88
+ const p = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"], cwd: opts.cwd });
89
+ let out = "";
90
+ let err = "";
91
+ p.stdout.on("data", (d) => {
92
+ out += d;
93
+ });
94
+ p.stderr.on("data", (d) => {
95
+ err += d;
96
+ });
97
+ p.on("error", (e) => {
98
+ if (e.code === "ENOENT" && /ff(mpeg|probe)/.test(cmd))
99
+ reject(new DemoreelError(`${cmd} not found.`, FFMPEG_FIX));
100
+ else
101
+ reject(e);
102
+ });
103
+ p.on("close", (code) => (code === 0 ? resolve(out) : reject(new Error(`${cmd} exited ${code}: ${err.slice(-2000)}`))));
104
+ });
105
+ }
106
+ // ---- GPU ------------------------------------------------------------------------------------
107
+ export const SOFTWARE_GL_ARGS = ["--enable-unsafe-swiftshader", "--use-gl=swiftshader"];
108
+ /** Candidate GPU flag sets per platform, best first. */
109
+ export function gpuArgCandidates(platform = process.platform) {
110
+ const base = ["--enable-gpu", "--ignore-gpu-blocklist"];
111
+ if (platform === "darwin")
112
+ return [[...base, "--use-angle=metal"]];
113
+ if (platform === "win32")
114
+ return [[...base, "--use-angle=d3d11"]];
115
+ return [
116
+ [...base, "--use-angle=vulkan", "--enable-features=Vulkan"],
117
+ [...base, "--use-angle=gl"],
118
+ ];
119
+ }
120
+ const SOFTWARE_RENDERER = /swiftshader|llvmpipe|softpipe|lavapipe|basic render|software/i;
121
+ async function probeArgs(args) {
122
+ let browser = null;
123
+ try {
124
+ browser = await launchChromium({ args });
125
+ const page = await browser.newPage();
126
+ // WebCodecs needs a secure context; serve a blank page on a fake https origin.
127
+ await page.route("https://demoreel.invalid/**", (r) => r.fulfill({ body: "<html></html>", contentType: "text/html" }));
128
+ await page.goto("https://demoreel.invalid/");
129
+ return await page.evaluate(async () => {
130
+ const gl = document.createElement("canvas").getContext("webgl2");
131
+ let renderer = "none";
132
+ if (gl) {
133
+ const ext = gl.getExtension("WEBGL_debug_renderer_info");
134
+ renderer = String(ext ? gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER));
135
+ }
136
+ let h264 = false;
137
+ try {
138
+ h264 = Boolean((await VideoEncoder.isConfigSupported({ codec: "avc1.640033", width: 1920, height: 1080 })).supported);
139
+ }
140
+ catch {
141
+ h264 = false;
142
+ }
143
+ return { renderer, h264 };
144
+ });
145
+ }
146
+ catch (e) {
147
+ if (e instanceof DemoreelError)
148
+ throw e;
149
+ return null;
150
+ }
151
+ finally {
152
+ await browser?.close().catch(() => { });
153
+ }
154
+ }
155
+ let gpuCache = null;
156
+ /** Finds a working hardware GL flag set, else returns the SwiftShader (software) one. */
157
+ export function detectGpu() {
158
+ gpuCache ??= (async () => {
159
+ for (const args of gpuArgCandidates()) {
160
+ const r = await probeArgs(args);
161
+ if (r && r.renderer !== "none" && !SOFTWARE_RENDERER.test(r.renderer))
162
+ return { gpu: true, args, ...r };
163
+ }
164
+ const sw = await probeArgs(SOFTWARE_GL_ARGS);
165
+ return { gpu: false, args: SOFTWARE_GL_ARGS, renderer: sw?.renderer ?? "none", h264: sw?.h264 ?? false };
166
+ })();
167
+ return gpuCache;
168
+ }
169
+ /** Chromium args for rendering: GPU when asked/available, SwiftShader otherwise. */
170
+ export async function renderArgs(mode, log = () => { }) {
171
+ if (mode === false)
172
+ return { args: SOFTWARE_GL_ARGS, gpu: false };
173
+ const probe = await detectGpu();
174
+ if (!probe.h264) {
175
+ throw new DemoreelError("This Chromium build cannot encode H.264 with WebCodecs (needed by OpenScreen's exporter).", `${INSTALL_CHROMIUM} (Playwright's Chromium includes H.264; distro builds may not)`);
176
+ }
177
+ if (probe.gpu)
178
+ return { args: probe.args, gpu: true, renderer: probe.renderer };
179
+ log(`warning: no usable GPU found (WebGL renderer: ${probe.renderer}); rendering with SwiftShader (software), ` +
180
+ "which is several times slower. Use a machine with a GPU, or lower --fps / the viewport for drafts.");
181
+ return { args: probe.args, gpu: false, renderer: probe.renderer };
182
+ }
package/dist/idle.d.ts ADDED
@@ -0,0 +1,48 @@
1
+ /**
2
+ * "Trim idle": finds stretches where nothing happens (no action in progress, no cursor
3
+ * motion, no caption, no zoom transition, no burst of visual change) and cuts them down
4
+ * with OpenScreen trim regions, or speeds them up with speed regions.
5
+ * Also maps recording times to output times through those regions.
6
+ */
7
+ import type { ActionRecord, Caption, CursorSample, SpeedRegion, TrimRegion, ZoomRegion } from "./types.ts";
8
+ export interface IdleOptions {
9
+ /** Idle stretches shorter than this are left alone. */
10
+ minMs: number;
11
+ /** How much of each idle stretch to keep (split evenly before/after the cut). */
12
+ keepMs: number;
13
+ /** `trim` cuts the stretch, `speed` plays it faster. */
14
+ mode: "trim" | "speed";
15
+ /** Playback speed for `mode: "speed"` (OpenScreen allows 0.1-16). */
16
+ speed: number;
17
+ /** Ignore raw screencast frame bursts (useful for apps with continuous rAF / WebGL / spinners). */
18
+ ignoreFrames?: boolean;
19
+ }
20
+ export declare const DEFAULT_IDLE_OPTIONS: IdleOptions;
21
+ type Interval = [number, number];
22
+ export interface IdleInput {
23
+ durationMs: number;
24
+ actions: ActionRecord[];
25
+ captions: Caption[];
26
+ samples: CursorSample[];
27
+ zoomRegions: ZoomRegion[];
28
+ /** Screencast frame times; bursts of frames (animation, page load) count as activity. */
29
+ frameTimes?: number[];
30
+ }
31
+ /** Busy intervals of a recording (anything a viewer should see at normal speed). */
32
+ export declare function busyIntervals(input: IdleInput, opts?: {
33
+ ignoreFrames?: boolean;
34
+ }): Interval[];
35
+ /** Idle stretches (complement of the busy intervals) longer than `minMs`. */
36
+ export declare function idleIntervals(input: IdleInput, minMs?: number, opts?: {
37
+ ignoreFrames?: boolean;
38
+ }): Interval[];
39
+ export declare function deriveIdleRegions(input: IdleInput, partial?: Partial<IdleOptions>): {
40
+ trimRegions: TrimRegion[];
41
+ speedRegions: SpeedRegion[];
42
+ };
43
+ /**
44
+ * Maps a recording time (ms) to the rendered output's time (ms) through trim and speed
45
+ * regions. Times inside a trimmed range map to the cut point.
46
+ */
47
+ export declare function sourceToOutputMs(t: number, trims?: TrimRegion[], speeds?: SpeedRegion[]): number;
48
+ export {};
package/dist/idle.js ADDED
@@ -0,0 +1,99 @@
1
+ export const DEFAULT_IDLE_OPTIONS = { minMs: 1200, keepMs: 600, mode: "trim", speed: 3, ignoreFrames: false };
2
+ /** OpenScreen zoom envelope (constants.ts TRANSITION_WINDOW_MS / ZOOM_IN_TRANSITION_WINDOW_MS). */
3
+ const ZOOM_IN_BEFORE_MS = 1022;
4
+ const ZOOM_IN_AFTER_MS = 500;
5
+ const ZOOM_OUT_AFTER_MS = 1016;
6
+ function mergeIntervals(list) {
7
+ const sorted = list.filter(([a, b]) => b > a).sort((x, y) => x[0] - y[0]);
8
+ const out = [];
9
+ for (const iv of sorted) {
10
+ const last = out[out.length - 1];
11
+ if (last && iv[0] <= last[1])
12
+ last[1] = Math.max(last[1], iv[1]);
13
+ else
14
+ out.push([iv[0], iv[1]]);
15
+ }
16
+ return out;
17
+ }
18
+ /** Busy intervals of a recording (anything a viewer should see at normal speed). */
19
+ export function busyIntervals(input, opts = {}) {
20
+ const busy = [];
21
+ for (const a of input.actions) {
22
+ if (a.kind === "pause" || a.kind === "caption")
23
+ continue;
24
+ busy.push([a.startMs - 150, a.endMs + 250]);
25
+ }
26
+ for (const c of input.captions)
27
+ busy.push([c.startMs - 200, c.endMs + 200]);
28
+ for (const z of input.zoomRegions) {
29
+ busy.push([z.startMs - ZOOM_IN_BEFORE_MS, z.startMs + ZOOM_IN_AFTER_MS]);
30
+ busy.push([z.endMs - 100, z.endMs + ZOOM_OUT_AFTER_MS]);
31
+ }
32
+ const s = input.samples;
33
+ for (let i = 1; i < s.length; i++) {
34
+ const moved = Math.abs(s[i].cx - s[i - 1].cx) + Math.abs(s[i].cy - s[i - 1].cy) > 1e-4;
35
+ if (moved || s[i].interactionType !== "move")
36
+ busy.push([s[i - 1].timeMs - 100, s[i].timeMs + 150]);
37
+ }
38
+ if (!opts.ignoreFrames) {
39
+ // >= 3 frames within 300 ms: something animates or paints.
40
+ const f = input.frameTimes ?? [];
41
+ for (let i = 2; i < f.length; i++) {
42
+ if (f[i] - f[i - 2] <= 300)
43
+ busy.push([f[i - 2] - 100, f[i] + 200]);
44
+ }
45
+ }
46
+ return mergeIntervals(busy);
47
+ }
48
+ /** Idle stretches (complement of the busy intervals) longer than `minMs`. */
49
+ export function idleIntervals(input, minMs = DEFAULT_IDLE_OPTIONS.minMs, opts = {}) {
50
+ const busy = busyIntervals(input, opts);
51
+ const out = [];
52
+ let cursor = 0;
53
+ for (const [a, b] of busy) {
54
+ if (a - cursor >= minMs)
55
+ out.push([cursor, a]);
56
+ cursor = Math.max(cursor, b);
57
+ }
58
+ if (input.durationMs - cursor >= minMs)
59
+ out.push([cursor, input.durationMs]);
60
+ return out;
61
+ }
62
+ export function deriveIdleRegions(input, partial = {}) {
63
+ const opts = { ...DEFAULT_IDLE_OPTIONS, ...partial };
64
+ const half = opts.keepMs / 2;
65
+ const cuts = idleIntervals(input, Math.max(opts.minMs, opts.keepMs + 100), { ignoreFrames: opts.ignoreFrames })
66
+ // keep the final hold (zoom-out, last frame) a bit longer than other stretches
67
+ .map(([a, b]) => [Math.round(a + half), Math.round(b - (b >= input.durationMs ? Math.max(half, 900) : half))])
68
+ .filter(([a, b]) => b - a >= 100);
69
+ if (opts.mode === "speed") {
70
+ const speed = Math.round(Math.min(16, Math.max(0.1, opts.speed)) * 100) / 100;
71
+ return {
72
+ trimRegions: [],
73
+ speedRegions: cuts.map(([a, b], i) => ({ id: `speed-${i + 1}`, startMs: a, endMs: b, speed })),
74
+ };
75
+ }
76
+ return {
77
+ trimRegions: cuts.map(([a, b], i) => ({ id: `trim-${i + 1}`, startMs: a, endMs: b })),
78
+ speedRegions: [],
79
+ };
80
+ }
81
+ /**
82
+ * Maps a recording time (ms) to the rendered output's time (ms) through trim and speed
83
+ * regions. Times inside a trimmed range map to the cut point.
84
+ */
85
+ export function sourceToOutputMs(t, trims = [], speeds = []) {
86
+ let out = t;
87
+ for (const r of trims) {
88
+ if (t >= r.endMs)
89
+ out -= r.endMs - r.startMs;
90
+ else if (t > r.startMs)
91
+ out -= t - r.startMs;
92
+ }
93
+ for (const r of speeds) {
94
+ // Overlap with trims is not modelled (demoreel never writes both).
95
+ const covered = Math.max(0, Math.min(t, r.endMs) - r.startMs);
96
+ out -= covered - covered / r.speed;
97
+ }
98
+ return out;
99
+ }
@@ -0,0 +1,14 @@
1
+ /** demoreel: scripted product demo videos (videos as code), rendered by OpenScreen's exporter. */
2
+ export { type DryRunError, type DryRunOptions, type DryRunResult, type RecordOptions, type RecordResult, type Scenario, type ScenarioContext, defineScenario, dryRunScenario, recordScenario, resolveStorageState, } from "./record.ts";
3
+ export { type ActionOptions, applyZoomAnchor, DEFAULT_PACING, describeTarget, type HighlightOptions, type PacingOptions, resolveTarget, Scene, type SceneClock, type Target, type TargetSpec, ZOOM_ATTRIBUTE, type ZoomOptions as SceneZoomOptions, } from "./scene.ts";
4
+ export { DEFAULT_ZOOM_OPTIONS, DEPTH_SCALES, deriveZoomRegions, depthForBox, normalizeDepth, type ZoomOptions } from "./zoom.ts";
5
+ export { DEFAULT_IDLE_OPTIONS, deriveIdleRegions, idleIntervals, type IdleOptions, sourceToOutputMs } from "./idle.ts";
6
+ export { buildCursorData, buildProject, type BuildProjectOptions, captionAnnotations, DEFAULT_LOOK, type LookOptions, normalizeSamples, type OpenScreenProject, writeProject, } from "./project.ts";
7
+ export { buildMarks, type Marks, type MarkPoint, type MarkRegion, type MarkSpan, type MarksInput } from "./marks.ts";
8
+ export { stageLayout, type StageLayout } from "./layout.ts";
9
+ export { compose, rezoom, readTimeline, type Timeline, TIMELINE_VERSION } from "./compose.ts";
10
+ export { type CursorStyle, type RenderOptions, type RenderResult, renderProject, type ValidationResult, validateProject } from "./render.ts";
11
+ export { contactSheet, findFramesheet, reviewSheet, type SheetOptions, type SheetResult } from "./sheet.ts";
12
+ export { DemoreelError, detectGpu, type GpuMode, type GpuProbe } from "./env.ts";
13
+ export { loadScenario } from "./load.ts";
14
+ export type * from "./types.ts";
package/dist/index.js ADDED
@@ -0,0 +1,13 @@
1
+ /** demoreel: scripted product demo videos (videos as code), rendered by OpenScreen's exporter. */
2
+ export { defineScenario, dryRunScenario, recordScenario, resolveStorageState, } from "./record.js";
3
+ export { applyZoomAnchor, DEFAULT_PACING, describeTarget, resolveTarget, Scene, ZOOM_ATTRIBUTE, } from "./scene.js";
4
+ export { DEFAULT_ZOOM_OPTIONS, DEPTH_SCALES, deriveZoomRegions, depthForBox, normalizeDepth } from "./zoom.js";
5
+ export { DEFAULT_IDLE_OPTIONS, deriveIdleRegions, idleIntervals, sourceToOutputMs } from "./idle.js";
6
+ export { buildCursorData, buildProject, captionAnnotations, DEFAULT_LOOK, normalizeSamples, writeProject, } from "./project.js";
7
+ export { buildMarks } from "./marks.js";
8
+ export { stageLayout } from "./layout.js";
9
+ export { compose, rezoom, readTimeline, TIMELINE_VERSION } from "./compose.js";
10
+ export { renderProject, validateProject } from "./render.js";
11
+ export { contactSheet, findFramesheet, reviewSheet } from "./sheet.js";
12
+ export { DemoreelError, detectGpu } from "./env.js";
13
+ export { loadScenario } from "./load.js";
package/dist/init.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ export interface InitOptions {
2
+ dir: string;
3
+ /** Scenario name (default "demo"). */
4
+ name?: string;
5
+ /** Record this URL instead of the bundled demo app. */
6
+ url?: string;
7
+ /** Write a .mjs scenario instead of .ts. */
8
+ js?: boolean;
9
+ force?: boolean;
10
+ }
11
+ export declare function scenarioTemplate(opts: {
12
+ name: string;
13
+ url?: string;
14
+ js?: boolean;
15
+ ext?: string;
16
+ }): string;
17
+ /** `type` of the nearest package.json ("commonjs" if none says "module"). */
18
+ export declare function packageType(dir: string): "module" | "commonjs";
19
+ export declare function initProject(opts: InitOptions): string[];
package/dist/init.js ADDED
@@ -0,0 +1,92 @@
1
+ /** `demoreel init`: scaffolds an example scenario (plus a copy of the bundled demo app). */
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { DemoreelError } from "./env.js";
5
+ import { PACKAGE_ROOT } from "./openscreen.js";
6
+ export function scenarioTemplate(opts) {
7
+ const header = opts.js
8
+ ? `// @ts-check\nimport { defineScenario } from "@phil65/demoreel";\n`
9
+ : `import { defineScenario } from "@phil65/demoreel";\n`;
10
+ if (opts.url) {
11
+ return `${header}
12
+ export default defineScenario({
13
+ name: ${JSON.stringify(opts.name)},
14
+ viewport: { width: 1920, height: 1080 },
15
+ async run(scene) {
16
+ await scene.goto(${JSON.stringify(opts.url)});
17
+ await scene.caption("What this page does, in one line", { duration: 3000 });
18
+ // Replace the selectors below with real ones from your page:
19
+ await scene.hover("h1", { dwell: 1200 });
20
+ // await scene.click("text=Get started", { navigates: true });
21
+ // await scene.type("input[type=search]", "hello");
22
+ // await scene.zoom("main", { depth: 2, duration: 2500 });
23
+ // await scene.highlight(".pricing", { duration: 2000 });
24
+ await scene.pause(800);
25
+ },
26
+ });
27
+ `;
28
+ }
29
+ return `${header}
30
+ /** Records the bundled demo app (./demo-app). Run: npx demoreel run ${opts.name}.scenario.${opts.ext ?? (opts.js ? "mjs" : "ts")} */
31
+ export default defineScenario({
32
+ name: ${JSON.stringify(opts.name)},
33
+ serve: "./demo-app",
34
+ viewport: { width: 1920, height: 1080 },
35
+ cssZoom: 1.5,
36
+ async run(scene, { baseUrl }) {
37
+ await scene.goto(\`\${baseUrl}/\`);
38
+ await scene.caption("Add a task in seconds", { duration: 3000 });
39
+ await scene.type("#title", "Ship the demo video");
40
+ await scene.type("#owner", "Phil");
41
+ await scene.click("#add", { label: "add task" });
42
+ await scene.pause(600);
43
+ await scene.caption("Filter and complete tasks", { duration: 3500 });
44
+ await scene.click('[data-filter="open"]');
45
+ await scene.click("#list li:nth-child(2) .check", { label: "complete" });
46
+ await scene.highlight("#count", { duration: 1600 });
47
+ await scene.click('[data-filter="all"]');
48
+ await scene.pause(800);
49
+ },
50
+ });
51
+ `;
52
+ }
53
+ /** `type` of the nearest package.json ("commonjs" if none says "module"). */
54
+ export function packageType(dir) {
55
+ for (let d = path.resolve(dir);; d = path.dirname(d)) {
56
+ const pj = path.join(d, "package.json");
57
+ if (fs.existsSync(pj)) {
58
+ try {
59
+ return JSON.parse(fs.readFileSync(pj, "utf8")).type === "module" ? "module" : "commonjs";
60
+ }
61
+ catch {
62
+ return "commonjs";
63
+ }
64
+ }
65
+ if (path.dirname(d) === d)
66
+ return "commonjs";
67
+ }
68
+ }
69
+ export function initProject(opts) {
70
+ const dir = path.resolve(opts.dir);
71
+ const name = opts.name ?? "demo";
72
+ // .ts is only ESM in a "type": "module" package; elsewhere use the explicit ESM extensions.
73
+ const esm = packageType(dir) === "module";
74
+ const ext = opts.js ? (esm ? "js" : "mjs") : esm ? "ts" : "mts";
75
+ const file = path.join(dir, `${name}.scenario.${ext}`);
76
+ const written = [];
77
+ fs.mkdirSync(dir, { recursive: true });
78
+ if (fs.existsSync(file) && !opts.force)
79
+ throw new DemoreelError(`${file} exists (use --force to overwrite)`);
80
+ fs.writeFileSync(file, scenarioTemplate({ name, url: opts.url, js: opts.js, ext }));
81
+ written.push(file);
82
+ if (!opts.url) {
83
+ const src = path.join(PACKAGE_ROOT, "examples", "demo-app", "index.html");
84
+ const dest = path.join(dir, "demo-app", "index.html");
85
+ if (!fs.existsSync(dest) || opts.force) {
86
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
87
+ fs.copyFileSync(src, dest);
88
+ written.push(dest);
89
+ }
90
+ }
91
+ return written;
92
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Geometry of OpenScreen's composite: where the recording sits on the output canvas ("stage")
3
+ * and how a zoom region transforms it. Mirrors frameRenderer.ts::updateLayout (padding),
4
+ * compositeLayout.ts::centerRect, focusUtils.ts::clampFocusToScale and
5
+ * zoomTransform.ts::computeZoomTransform for the no-webcam, no-crop case demoreel writes.
6
+ */
7
+ import type { Box, Depth, Viewport } from "./types.ts";
8
+ /** OpenScreen ZOOM_DEPTH_SCALES (src/components/video-editor/types.ts). */
9
+ export declare const DEPTH_SCALES: Record<Depth, number>;
10
+ /** A rectangle in stage-normalised coordinates (0-1 of the output canvas). */
11
+ export interface NormRect {
12
+ x: number;
13
+ y: number;
14
+ w: number;
15
+ h: number;
16
+ }
17
+ export interface StageLayout {
18
+ /** Output canvas aspect ratio (width / height). */
19
+ aspect: number;
20
+ /** The recording's rectangle on the stage, normalised. */
21
+ video: NormRect;
22
+ }
23
+ export declare function aspectValue(aspectRatio: string, video: Viewport): number;
24
+ /** Where the (uncropped) recording lands on the output canvas, for a padding of 0-100. */
25
+ export declare function stageLayout(video: Viewport, opts: {
26
+ padding: number;
27
+ aspectRatio: string;
28
+ }): StageLayout;
29
+ /** Viewport px -> stage-normalised point. */
30
+ export declare function toStage(layout: StageLayout, vp: Viewport, p: {
31
+ x: number;
32
+ y: number;
33
+ }): {
34
+ x: number;
35
+ y: number;
36
+ };
37
+ export declare function boxToStage(layout: StageLayout, vp: Viewport, b: Box): NormRect;
38
+ /** OpenScreen clamps the focus so a zoomed view never leaves the stage. */
39
+ export declare function clampFocus(focus: {
40
+ cx: number;
41
+ cy: number;
42
+ }, scale: number): {
43
+ cx: number;
44
+ cy: number;
45
+ };
46
+ /** Applies a fully zoomed-in region (scale about the clamped focus) to a stage rect. */
47
+ export declare function zoomRect(r: NormRect, depth: Depth, focus: {
48
+ cx: number;
49
+ cy: number;
50
+ }): NormRect;
51
+ /** Clips a rect to the unit square; null if nothing is left. */
52
+ export declare function clipUnit(r: NormRect): NormRect | null;
package/dist/layout.js ADDED
@@ -0,0 +1,55 @@
1
+ /** OpenScreen ZOOM_DEPTH_SCALES (src/components/video-editor/types.ts). */
2
+ export const DEPTH_SCALES = { 1: 1.25, 2: 1.5, 3: 1.8, 4: 2.2, 5: 3.5, 6: 5.0 };
3
+ export function aspectValue(aspectRatio, video) {
4
+ if (aspectRatio === "native")
5
+ return video.width / video.height;
6
+ const m = /^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)$/.exec(aspectRatio);
7
+ if (!m)
8
+ return 16 / 9;
9
+ return Number(m[1]) / Number(m[2]);
10
+ }
11
+ /** Where the (uncropped) recording lands on the output canvas, for a padding of 0-100. */
12
+ export function stageLayout(video, opts) {
13
+ const aspect = aspectValue(opts.aspectRatio, video);
14
+ const paddingScale = 1 - (Math.min(100, Math.max(0, opts.padding)) / 100) * 0.4;
15
+ // Work on a canvas of height 1 and width `aspect`.
16
+ const maxW = aspect * paddingScale;
17
+ const maxH = paddingScale;
18
+ const scale = Math.min(maxW / video.width, maxH / video.height);
19
+ const w = (video.width * scale) / aspect;
20
+ const h = video.height * scale;
21
+ return { aspect, video: { x: (1 - w) / 2, y: (1 - h) / 2, w, h } };
22
+ }
23
+ /** Viewport px -> stage-normalised point. */
24
+ export function toStage(layout, vp, p) {
25
+ return {
26
+ x: layout.video.x + (p.x / vp.width) * layout.video.w,
27
+ y: layout.video.y + (p.y / vp.height) * layout.video.h,
28
+ };
29
+ }
30
+ export function boxToStage(layout, vp, b) {
31
+ const a = toStage(layout, vp, b);
32
+ return { x: a.x, y: a.y, w: (b.width / vp.width) * layout.video.w, h: (b.height / vp.height) * layout.video.h };
33
+ }
34
+ /** OpenScreen clamps the focus so a zoomed view never leaves the stage. */
35
+ export function clampFocus(focus, scale) {
36
+ const m = Math.min(0.5, 1 / (2 * scale));
37
+ const c = (v) => Math.min(1 - m, Math.max(m, Math.min(1, Math.max(0, v))));
38
+ return { cx: c(focus.cx), cy: c(focus.cy) };
39
+ }
40
+ /** Applies a fully zoomed-in region (scale about the clamped focus) to a stage rect. */
41
+ export function zoomRect(r, depth, focus) {
42
+ const s = DEPTH_SCALES[depth];
43
+ const f = clampFocus(focus, s);
44
+ return { x: 0.5 + (r.x - f.cx) * s, y: 0.5 + (r.y - f.cy) * s, w: r.w * s, h: r.h * s };
45
+ }
46
+ /** Clips a rect to the unit square; null if nothing is left. */
47
+ export function clipUnit(r) {
48
+ const x0 = Math.max(0, r.x);
49
+ const y0 = Math.max(0, r.y);
50
+ const x1 = Math.min(1, r.x + r.w);
51
+ const y1 = Math.min(1, r.y + r.h);
52
+ if (x1 - x0 <= 1e-4 || y1 - y0 <= 1e-4)
53
+ return null;
54
+ return { x: x0, y: y0, w: x1 - x0, h: y1 - y0 };
55
+ }
package/dist/load.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import type { Scenario } from "./record.ts";
2
+ export declare function loadScenario(file: string): Promise<Scenario>;