@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
@@ -0,0 +1,149 @@
1
+ /**
2
+ * Viewport recorder based on CDP `Page.startScreencast`.
3
+ *
4
+ * Every frame carries the compositor's swap timestamp, so we keep exact timing and later let
5
+ * ffmpeg turn the variable-rate JPEG stream into a constant-rate H.264 MP4 (concat demuxer with
6
+ * per-frame durations). Chromium only emits frames when something changes; idle periods simply
7
+ * become long frame durations.
8
+ */
9
+ import { spawn } from "node:child_process";
10
+ import fs from "node:fs";
11
+ import path from "node:path";
12
+ import { ffmpegBin } from "./env.js";
13
+ export class ScreencastRecorder {
14
+ session = null;
15
+ frames = [];
16
+ lastFrameData = null;
17
+ pending = [];
18
+ stopTs = 0;
19
+ firstFrame;
20
+ resolveFirst;
21
+ frameSize = { width: 0, height: 0 };
22
+ page;
23
+ dir;
24
+ opts;
25
+ constructor(page, dir, opts) {
26
+ this.page = page;
27
+ this.dir = dir;
28
+ this.opts = opts;
29
+ fs.mkdirSync(dir, { recursive: true });
30
+ this.firstFrame = new Promise((r) => {
31
+ this.resolveFirst = r;
32
+ });
33
+ }
34
+ /** Epoch ms of the first frame; all telemetry is expressed relative to this. */
35
+ get t0() {
36
+ return this.frames[0]?.ts ?? 0;
37
+ }
38
+ async start() {
39
+ const session = await this.page.context().newCDPSession(this.page);
40
+ this.session = session;
41
+ session.on("Page.screencastFrame", (ev) => {
42
+ const index = this.frames.length;
43
+ // Skip byte-identical repaints (e.g. idle WebGL/Three.js requestAnimationFrame loops)
44
+ // so encode() holds the previous frame and frameTimes reflects real visual changes.
45
+ if (index > 0 && ev.data === this.lastFrameData) {
46
+ session.send("Page.screencastFrameAck", { sessionId: ev.sessionId }).catch(() => { });
47
+ return;
48
+ }
49
+ this.lastFrameData = ev.data;
50
+ const file = path.join(this.dir, `f${String(index).padStart(6, "0")}.jpg`);
51
+ const ts = (ev.metadata.timestamp ?? Date.now() / 1000) * 1000;
52
+ this.frames.push({ file, ts });
53
+ this.pending.push(fs.promises.writeFile(file, Buffer.from(ev.data, "base64")));
54
+ if (index === 0) {
55
+ this.frameSize = {
56
+ width: Math.round(ev.metadata.deviceWidth * (ev.metadata.pageScaleFactor ?? 1)),
57
+ height: Math.round(ev.metadata.deviceHeight * (ev.metadata.pageScaleFactor ?? 1)),
58
+ };
59
+ this.resolveFirst();
60
+ }
61
+ session.send("Page.screencastFrameAck", { sessionId: ev.sessionId }).catch(() => { });
62
+ });
63
+ await session.send("Page.startScreencast", {
64
+ format: "jpeg",
65
+ quality: this.opts.quality ?? 92,
66
+ maxWidth: this.opts.maxWidth,
67
+ maxHeight: this.opts.maxHeight,
68
+ everyNthFrame: 1,
69
+ });
70
+ // Nudge a repaint so the first frame arrives even on a static page.
71
+ await this.page.evaluate(() => {
72
+ const el = document.createElement("div");
73
+ el.style.cssText = "position:fixed;left:0;top:0;width:1px;height:1px;opacity:0.01;pointer-events:none";
74
+ document.body.appendChild(el);
75
+ requestAnimationFrame(() => requestAnimationFrame(() => el.remove()));
76
+ });
77
+ await this.firstFrame;
78
+ }
79
+ /** Recording-clock times (ms since the first frame) of all captured frames. */
80
+ get frameTimes() {
81
+ return this.frames.map((f) => Math.round((f.ts - this.t0) * 10) / 10);
82
+ }
83
+ /** Current time on the recording clock (ms since first frame). */
84
+ now() {
85
+ return Date.now() - this.t0;
86
+ }
87
+ async stop() {
88
+ this.stopTs = Date.now();
89
+ await this.session?.send("Page.stopScreencast").catch(() => { });
90
+ await Promise.all(this.pending);
91
+ return { durationMs: this.stopTs - this.t0, frameCount: this.frames.length };
92
+ }
93
+ /**
94
+ * Encode the captured frames to a CFR H.264 MP4: for every output frame time we pick the
95
+ * latest captured frame (sample-and-hold) and pipe its JPEG to ffmpeg, so timing is exact.
96
+ */
97
+ async encode(outPath, fps = 30) {
98
+ const first = await fs.promises.readFile(this.frames[0].file);
99
+ this.frameSize = jpegSize(first) ?? this.frameSize;
100
+ const total = Math.max(1, Math.round(((this.stopTs - this.t0) / 1000) * fps));
101
+ const ff = spawn(ffmpegBin(), [
102
+ "-y", "-loglevel", "error",
103
+ "-f", "image2pipe", "-framerate", String(fps), "-c:v", "mjpeg", "-i", "-",
104
+ "-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2,format=yuv420p",
105
+ "-c:v", "libx264", "-preset", "veryfast", "-crf", "16", "-g", String(fps),
106
+ "-movflags", "+faststart", outPath,
107
+ ], { stdio: ["pipe", "ignore", "pipe"] });
108
+ let err = "";
109
+ ff.stderr.on("data", (d) => {
110
+ err += d;
111
+ });
112
+ const done = new Promise((resolve, reject) => {
113
+ ff.on("error", reject);
114
+ ff.on("close", (code) => (code === 0 ? resolve() : reject(new Error(`ffmpeg exited ${code}: ${err}`))));
115
+ });
116
+ let idx = 0;
117
+ let cachedIdx = -1;
118
+ let cached = first;
119
+ for (let k = 0; k < total; k++) {
120
+ const t = this.t0 + (k * 1000) / fps;
121
+ while (idx + 1 < this.frames.length && this.frames[idx + 1].ts <= t)
122
+ idx++;
123
+ if (idx !== cachedIdx) {
124
+ cached = await fs.promises.readFile(this.frames[idx].file);
125
+ cachedIdx = idx;
126
+ }
127
+ if (!ff.stdin.write(cached))
128
+ await new Promise((r) => ff.stdin.once("drain", r));
129
+ }
130
+ ff.stdin.end();
131
+ await done;
132
+ return { outputFrames: total };
133
+ }
134
+ }
135
+ /** Reads width/height from a JPEG's SOF marker. */
136
+ function jpegSize(buf) {
137
+ let i = 2;
138
+ while (i + 9 < buf.length) {
139
+ if (buf[i] !== 0xff)
140
+ return null;
141
+ const marker = buf[i + 1];
142
+ const len = buf.readUInt16BE(i + 2);
143
+ if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
144
+ return { height: buf.readUInt16BE(i + 5), width: buf.readUInt16BE(i + 7) };
145
+ }
146
+ i += 2 + len;
147
+ }
148
+ return null;
149
+ }
@@ -0,0 +1,58 @@
1
+ import { type GpuMode } from "./env.ts";
2
+ export interface CursorStyle {
3
+ /** Cursor scale (OpenScreen default 3). */
4
+ size?: number;
5
+ smoothing?: number;
6
+ motionBlur?: number;
7
+ clickBounce?: number;
8
+ show?: boolean;
9
+ }
10
+ export interface RenderOptions {
11
+ projectPath: string;
12
+ /** Default: the project path with `.mp4`. */
13
+ outputPath?: string;
14
+ frameRate?: number;
15
+ /** OpenScreen export quality: medium (720p), good (1080p), source. Default: the project's. */
16
+ quality?: "medium" | "good" | "source";
17
+ cursor?: CursorStyle;
18
+ /** `"auto"` (default): use the GPU if one works, else SwiftShader with a warning. */
19
+ gpu?: GpuMode;
20
+ /** Print browser console output. */
21
+ verbose?: boolean;
22
+ /** Progress / warning logger (default: console.error). */
23
+ log?: (msg: string) => void;
24
+ /** Called with 0-100. */
25
+ onProgress?: (percent: number) => void;
26
+ timeoutMs?: number;
27
+ }
28
+ export interface RenderResult {
29
+ outputPath: string;
30
+ width: number;
31
+ height: number;
32
+ bitrate: number;
33
+ bytes: number;
34
+ warnings: string[];
35
+ gpu: boolean;
36
+ renderMs: number;
37
+ setupMs: number;
38
+ totalMs: number;
39
+ }
40
+ /** Resolves the project's screen video (absolute, or relative to the project file). */
41
+ export declare function projectVideoPath(project: {
42
+ media?: {
43
+ screenVideoPath?: string;
44
+ };
45
+ videoPath?: string;
46
+ }, projectPath: string): string;
47
+ export declare function renderProject(opts: RenderOptions): Promise<RenderResult>;
48
+ export interface ValidationResult {
49
+ valid: boolean;
50
+ /** Media paths as OpenScreen resolves them. */
51
+ media: unknown;
52
+ /** Editor fields OpenScreen's normalizeProjectEditor would change (should be empty). */
53
+ changedByNormalize: string[];
54
+ /** The normalised editor state (what OpenScreen would load). */
55
+ normalized: Record<string, unknown> | null;
56
+ }
57
+ /** Runs OpenScreen's own validateProjectData / normalizeProjectEditor on a project (file or object). */
58
+ export declare function validateProject(project: string | Record<string, unknown>): Promise<ValidationResult>;
package/dist/render.js ADDED
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Headless export: serves the prebuilt renderer bundle (dist/renderer, OpenScreen's
3
+ * VideoExporter) from a tiny local server, opens it in headless Chromium and lets OpenScreen's
4
+ * own WebCodecs + Pixi pipeline render the MP4. Validation runs OpenScreen's
5
+ * validateProjectData / normalizeProjectEditor in Node (dist/openscreen/project.js).
6
+ */
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+ import { DemoreelError, launchChromium, renderArgs } from "./env.js";
10
+ import { openscreenProjectApi, rendererDir } from "./openscreen.js";
11
+ import { sendFile, serveStatic } from "./server.js";
12
+ function readProject(projectPath) {
13
+ if (!fs.existsSync(projectPath))
14
+ throw new DemoreelError(`project not found: ${projectPath}`);
15
+ try {
16
+ return JSON.parse(fs.readFileSync(projectPath, "utf8"));
17
+ }
18
+ catch (e) {
19
+ throw new DemoreelError(`${projectPath} is not valid JSON: ${e.message}`);
20
+ }
21
+ }
22
+ /** Resolves the project's screen video (absolute, or relative to the project file). */
23
+ export function projectVideoPath(project, projectPath) {
24
+ const v = project.media?.screenVideoPath ?? project.videoPath;
25
+ if (!v)
26
+ throw new DemoreelError(`${projectPath} has no media.screenVideoPath`);
27
+ const p = v.startsWith("file://") ? new URL(v).pathname : v;
28
+ return path.isAbsolute(p) ? p : path.resolve(path.dirname(projectPath), p);
29
+ }
30
+ export async function renderProject(opts) {
31
+ const t0 = Date.now();
32
+ const log = opts.log ?? ((m) => console.error(m));
33
+ const projectPath = path.resolve(opts.projectPath);
34
+ const project = readProject(projectPath);
35
+ const v = await validateProject(projectPath);
36
+ if (!v.valid)
37
+ throw new DemoreelError(`${projectPath} fails OpenScreen's validateProjectData()`);
38
+ const videoPath = projectVideoPath(project, projectPath);
39
+ if (!fs.existsSync(videoPath))
40
+ throw new DemoreelError(`recording not found: ${videoPath}`, "re-run `demoreel run`");
41
+ const cursorFile = `${videoPath}.cursor.json`;
42
+ const cursorData = fs.existsSync(cursorFile) ? JSON.parse(fs.readFileSync(cursorFile, "utf8")) : null;
43
+ const outputPath = path.resolve(opts.outputPath ?? projectPath.replace(/\.openscreen$/, "") + ".mp4");
44
+ fs.mkdirSync(path.dirname(outputPath), { recursive: true });
45
+ const mediaUrl = `/__demoreel/media/${encodeURIComponent(path.basename(videoPath))}`;
46
+ const handlers = [
47
+ (req, res, url) => {
48
+ if (url.pathname !== mediaUrl)
49
+ return false;
50
+ sendFile(req, res, videoPath);
51
+ return true;
52
+ },
53
+ (req, res, url) => {
54
+ if (url.pathname !== "/__demoreel/output" || req.method !== "POST")
55
+ return false;
56
+ const tmp = `${outputPath}.part`;
57
+ const out = fs.createWriteStream(tmp);
58
+ req.pipe(out);
59
+ out.on("finish", () => {
60
+ fs.renameSync(tmp, outputPath);
61
+ res.writeHead(200).end("ok");
62
+ });
63
+ out.on("error", (e) => res.writeHead(500).end(String(e)));
64
+ return true;
65
+ },
66
+ ];
67
+ const server = await serveStatic(rendererDir(), handlers);
68
+ const gl = await renderArgs(opts.gpu ?? "auto", log);
69
+ const browser = await launchChromium({ args: gl.args });
70
+ try {
71
+ const page = await browser.newPage();
72
+ page.on("console", (m) => {
73
+ const t = m.text();
74
+ if (t.startsWith("[demoreel] progress ")) {
75
+ opts.onProgress?.(Number(t.slice(20)));
76
+ return;
77
+ }
78
+ if (opts.verbose)
79
+ log(` [browser] ${t}`);
80
+ });
81
+ const pageErrors = [];
82
+ page.on("pageerror", (e) => {
83
+ pageErrors.push(e.message);
84
+ if (opts.verbose)
85
+ log(` [pageerror] ${e.message}`);
86
+ });
87
+ await page.goto(`${server.url}/index.html`);
88
+ await page.waitForFunction(() => window.demoreelReady, null, {
89
+ timeout: 60_000,
90
+ });
91
+ const tReady = Date.now();
92
+ const result = await page.evaluate((req) => window.demoreel.render(req), {
93
+ project,
94
+ cursorData,
95
+ videoUrl: mediaUrl,
96
+ frameRate: opts.frameRate ?? 30,
97
+ quality: opts.quality,
98
+ cursor: opts.cursor,
99
+ });
100
+ return {
101
+ outputPath,
102
+ width: result.width,
103
+ height: result.height,
104
+ bitrate: result.bitrate,
105
+ bytes: result.bytes,
106
+ warnings: result.warnings ?? [],
107
+ renderMs: result.renderMs,
108
+ gpu: gl.gpu,
109
+ setupMs: tReady - t0,
110
+ totalMs: Date.now() - t0,
111
+ };
112
+ }
113
+ catch (e) {
114
+ const msg = e.message ?? String(e);
115
+ if (/VideoEncoder|isConfigSupported|codec/i.test(msg) && !/upload/.test(msg)) {
116
+ throw new DemoreelError(`render failed in OpenScreen's exporter: ${msg.split("\n")[0]}`, "try --no-gpu, or `demoreel doctor`");
117
+ }
118
+ throw e;
119
+ }
120
+ finally {
121
+ await browser.close().catch(() => { });
122
+ await server.close();
123
+ }
124
+ }
125
+ /** Runs OpenScreen's own validateProjectData / normalizeProjectEditor on a project (file or object). */
126
+ export async function validateProject(project) {
127
+ const data = typeof project === "string" ? readProject(path.resolve(project)) : project;
128
+ const os = await openscreenProjectApi();
129
+ const valid = os.validateProjectData(data);
130
+ if (!valid)
131
+ return { valid: false, media: null, changedByNormalize: [], normalized: null };
132
+ const normalized = os.normalizeProjectEditor(data.editor);
133
+ const changedByNormalize = [];
134
+ for (const [k, v] of Object.entries(data.editor)) {
135
+ if (JSON.stringify(v) !== JSON.stringify(normalized[k]))
136
+ changedByNormalize.push(k);
137
+ }
138
+ return { valid, media: os.resolveProjectMedia(data), changedByNormalize, normalized };
139
+ }