autokast 0.0.0 → 0.1.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 (79) hide show
  1. package/LICENSE +29 -0
  2. package/README.md +165 -0
  3. package/dist/cli.d.ts +2 -0
  4. package/dist/cli.js +300 -0
  5. package/dist/index.d.ts +4 -0
  6. package/dist/index.js +4 -0
  7. package/dist/inspect.d.ts +26 -0
  8. package/dist/inspect.js +193 -0
  9. package/dist/record/animations.d.ts +7 -0
  10. package/dist/record/animations.js +34 -0
  11. package/dist/record/capture.d.ts +85 -0
  12. package/dist/record/capture.js +202 -0
  13. package/dist/record/cast.d.ts +142 -0
  14. package/dist/record/cast.js +680 -0
  15. package/dist/record/cursor-style.d.ts +33 -0
  16. package/dist/record/cursor-style.js +252 -0
  17. package/dist/record/defaults.d.ts +96 -0
  18. package/dist/record/defaults.js +125 -0
  19. package/dist/record/editor.d.ts +11 -0
  20. package/dist/record/editor.js +48 -0
  21. package/dist/record/frame-pump.d.ts +91 -0
  22. package/dist/record/frame-pump.js +306 -0
  23. package/dist/record/index.d.ts +11 -0
  24. package/dist/record/index.js +287 -0
  25. package/dist/record/motion.d.ts +48 -0
  26. package/dist/record/motion.js +112 -0
  27. package/dist/record/pace.d.ts +69 -0
  28. package/dist/record/pace.js +133 -0
  29. package/dist/record/random.d.ts +12 -0
  30. package/dist/record/random.js +24 -0
  31. package/dist/record/scroll.d.ts +71 -0
  32. package/dist/record/scroll.js +249 -0
  33. package/dist/record/timeline.d.ts +34 -0
  34. package/dist/record/timeline.js +44 -0
  35. package/dist/render/background.d.ts +12 -0
  36. package/dist/render/background.js +209 -0
  37. package/dist/render/browser.d.ts +46 -0
  38. package/dist/render/browser.js +223 -0
  39. package/dist/render/camera.d.ts +119 -0
  40. package/dist/render/camera.js +372 -0
  41. package/dist/render/captions.d.ts +114 -0
  42. package/dist/render/captions.js +254 -0
  43. package/dist/render/color.d.ts +23 -0
  44. package/dist/render/color.js +78 -0
  45. package/dist/render/compositor.d.ts +185 -0
  46. package/dist/render/compositor.js +656 -0
  47. package/dist/render/cursor.d.ts +85 -0
  48. package/dist/render/cursor.js +314 -0
  49. package/dist/render/cursors/shapes.d.ts +34 -0
  50. package/dist/render/cursors/shapes.js +268 -0
  51. package/dist/render/defaults.d.ts +91 -0
  52. package/dist/render/defaults.js +139 -0
  53. package/dist/render/easing.d.ts +13 -0
  54. package/dist/render/easing.js +40 -0
  55. package/dist/render/effects.d.ts +39 -0
  56. package/dist/render/effects.js +91 -0
  57. package/dist/render/encoder.d.ts +52 -0
  58. package/dist/render/encoder.js +226 -0
  59. package/dist/render/index.d.ts +19 -0
  60. package/dist/render/index.js +138 -0
  61. package/dist/render/keycaps.d.ts +67 -0
  62. package/dist/render/keycaps.js +270 -0
  63. package/dist/render/scene.d.ts +59 -0
  64. package/dist/render/scene.js +230 -0
  65. package/dist/render/source.d.ts +21 -0
  66. package/dist/render/source.js +57 -0
  67. package/dist/render/spring.d.ts +11 -0
  68. package/dist/render/spring.js +47 -0
  69. package/dist/render/stage.d.ts +59 -0
  70. package/dist/render/stage.js +91 -0
  71. package/dist/render/timeline.d.ts +70 -0
  72. package/dist/render/timeline.js +157 -0
  73. package/dist/session.d.ts +14 -0
  74. package/dist/session.js +33 -0
  75. package/dist/types.d.ts +708 -0
  76. package/dist/types.js +1 -0
  77. package/package.json +61 -3
  78. package/skills/autokast/SKILL.md +300 -0
  79. package/skills/autokast/reference/jupyterlab.md +100 -0
@@ -0,0 +1,91 @@
1
+ import type { BackgroundOptions, EasingName, EncodeOptions, FollowMode, RenderOptions, Session, Size } from '../types.ts';
2
+ export interface ResolvedShadow {
3
+ color: string;
4
+ blur: number;
5
+ offsetY: number;
6
+ }
7
+ export interface ResolvedAutoZoom {
8
+ scale: number;
9
+ hold: number;
10
+ mergeWindow: number;
11
+ }
12
+ /**
13
+ * Render options with every default filled in. Pixel values are for a 1080-pixel output;
14
+ * the compositor scales them with `unit`.
15
+ */
16
+ export interface ResolvedOptions {
17
+ output: string;
18
+ format: 'mp4' | 'webm' | 'gif';
19
+ size: Size;
20
+ fps: number;
21
+ /**
22
+ * Scale of pixel-valued options: the short side of the output over 1080.
23
+ */
24
+ unit: number;
25
+ background: BackgroundOptions;
26
+ frame: {
27
+ padding: number;
28
+ radius: number;
29
+ shadow: ResolvedShadow | false;
30
+ chrome: 'none' | 'window' | 'browser';
31
+ title: string;
32
+ chromeTheme: 'light' | 'dark';
33
+ address: boolean | string;
34
+ origin: string;
35
+ };
36
+ cursor: {
37
+ visible: boolean;
38
+ size: number;
39
+ smoothing: number;
40
+ pressScale: number;
41
+ hideAfter: number;
42
+ motionBlur: number;
43
+ tilt: number;
44
+ click: {
45
+ type: 'ripple' | 'ring' | 'none';
46
+ color: string;
47
+ size: number;
48
+ duration: number;
49
+ };
50
+ };
51
+ zoom: {
52
+ auto: ResolvedAutoZoom | false;
53
+ mode: 'camera' | 'crop';
54
+ edges: 'fill' | 'keep';
55
+ maxScale: number;
56
+ duration: number;
57
+ easing: EasingName;
58
+ follow: FollowMode;
59
+ followSpeed: number;
60
+ levels: Record<string, number>;
61
+ motionBlur: number;
62
+ };
63
+ captions: {
64
+ position: 'bottom' | 'top';
65
+ fontSize: number;
66
+ fontFamily: string;
67
+ };
68
+ keystrokes: {
69
+ show: 'none' | 'shortcuts' | 'all';
70
+ position: 'bottom' | 'top';
71
+ labels: 'mac' | 'pc';
72
+ };
73
+ encode: Required<Omit<EncodeOptions, 'ffmpegPath' | 'crf' | 'preset'>> & EncodeOptions;
74
+ range: {
75
+ start: number;
76
+ end: number;
77
+ };
78
+ onProgress?: (done: number, total: number) => void;
79
+ }
80
+ /**
81
+ * Deep-merges plain objects. Arrays and other values replace; `undefined` is skipped.
82
+ */
83
+ export declare function deepMerge<T>(base: T, ...layers: unknown[]): T;
84
+ /**
85
+ * Turns a background string (preset name or CSS color) into background options.
86
+ */
87
+ export declare function normalizeBackground(value: BackgroundOptions | string, presets: readonly string[]): BackgroundOptions;
88
+ /**
89
+ * Resolves render options: defaults, then the session's options, then `options`.
90
+ */
91
+ export declare function resolveOptions(session: Session, options: RenderOptions | undefined, presets: readonly string[], outputDuration: number): ResolvedOptions;
@@ -0,0 +1,139 @@
1
+ import path from 'node:path';
2
+ const DEFAULT_BACKGROUND = 'dusk';
3
+ const DEFAULT_SHADOW = {
4
+ color: 'rgba(8, 10, 18, 0.6)',
5
+ blur: 72,
6
+ offsetY: 30,
7
+ };
8
+ const DEFAULT_AUTO_ZOOM = { scale: 1.8, hold: 1500, mergeWindow: 2500 };
9
+ const DEFAULTS = {
10
+ size: { width: 1920, height: 1080 },
11
+ fps: 60,
12
+ background: DEFAULT_BACKGROUND,
13
+ frame: {
14
+ padding: 0.07,
15
+ radius: 16,
16
+ shadow: DEFAULT_SHADOW,
17
+ chrome: 'none',
18
+ title: '',
19
+ chromeTheme: 'light',
20
+ address: true,
21
+ origin: '',
22
+ },
23
+ cursor: {
24
+ visible: true,
25
+ size: 1.9,
26
+ smoothing: 0.3,
27
+ pressScale: 0.82,
28
+ hideAfter: 0,
29
+ motionBlur: 0.5,
30
+ tilt: 1,
31
+ click: { type: 'ripple', color: 'auto', size: 26, duration: 520 },
32
+ },
33
+ zoom: {
34
+ auto: false,
35
+ mode: 'camera',
36
+ edges: 'fill',
37
+ maxScale: 3,
38
+ duration: 900,
39
+ easing: 'smooth',
40
+ follow: 'edge',
41
+ followSpeed: 1,
42
+ levels: { wide: 1.3, medium: 1.6, close: 2.2 },
43
+ motionBlur: 0,
44
+ },
45
+ captions: { position: 'bottom', fontSize: 40, fontFamily: 'Inter Display' },
46
+ keystrokes: {
47
+ show: 'none',
48
+ position: 'bottom',
49
+ labels: process.platform === 'darwin' ? 'mac' : 'pc',
50
+ },
51
+ encode: { quality: 'standard', pixelFormat: 'yuv420p' },
52
+ };
53
+ function isPlainObject(value) {
54
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
55
+ }
56
+ /**
57
+ * Deep-merges plain objects. Arrays and other values replace; `undefined` is skipped.
58
+ */
59
+ export function deepMerge(base, ...layers) {
60
+ let result = base;
61
+ for (const layer of layers)
62
+ result = mergeTwo(result, layer);
63
+ return result;
64
+ }
65
+ function mergeTwo(base, layer) {
66
+ if (layer === undefined)
67
+ return base;
68
+ if (!isPlainObject(base) || !isPlainObject(layer))
69
+ return layer;
70
+ const out = { ...base };
71
+ for (const [key, value] of Object.entries(layer)) {
72
+ if (key === 'background' || key === 'onProgress' || key === 'range') {
73
+ if (value !== undefined)
74
+ out[key] = value;
75
+ }
76
+ else {
77
+ out[key] = mergeTwo(base[key], value);
78
+ }
79
+ }
80
+ return out;
81
+ }
82
+ /**
83
+ * Turns a background string (preset name or CSS color) into background options.
84
+ */
85
+ export function normalizeBackground(value, presets) {
86
+ if (typeof value !== 'string')
87
+ return value;
88
+ return presets.includes(value)
89
+ ? { type: 'preset', name: value }
90
+ : { type: 'solid', color: value };
91
+ }
92
+ function evenSize(size, pixelFormat) {
93
+ const round = (v) => Math.max(2, Math.round(v));
94
+ const w = round(size.width);
95
+ const h = round(size.height);
96
+ if (!/^yuv4[12][02]/.test(pixelFormat))
97
+ return { width: w, height: h };
98
+ return { width: w + (w % 2), height: h + (h % 2) };
99
+ }
100
+ /**
101
+ * Resolves render options: defaults, then the session's options, then `options`.
102
+ */
103
+ export function resolveOptions(session, options, presets, outputDuration) {
104
+ const merged = deepMerge(DEFAULTS, session.render, options);
105
+ const output = path.resolve(merged.output ?? `${session.name || 'autokast'}.mp4`);
106
+ const ext = path.extname(output).toLowerCase();
107
+ const format = ext === '.webm' ? 'webm' : ext === '.gif' ? 'gif' : 'mp4';
108
+ const encode = merged.encode;
109
+ const size = evenSize(merged.size, encode.pixelFormat);
110
+ const fps = Math.min(240, Math.max(1, merged.fps));
111
+ const auto = merged.zoom.auto;
112
+ const shadow = merged.frame.shadow;
113
+ const start = Math.max(0, merged.range?.start ?? 0);
114
+ const end = Math.min(outputDuration, merged.range?.end ?? outputDuration);
115
+ return {
116
+ output,
117
+ format,
118
+ size,
119
+ fps,
120
+ unit: Math.min(size.width, size.height) / 1080,
121
+ background: normalizeBackground(merged.background, presets),
122
+ frame: {
123
+ ...merged.frame,
124
+ shadow: shadow === false ? false : { ...DEFAULT_SHADOW, ...shadow },
125
+ },
126
+ cursor: merged.cursor,
127
+ zoom: {
128
+ ...merged.zoom,
129
+ auto: auto === true ? DEFAULT_AUTO_ZOOM : auto ? { ...DEFAULT_AUTO_ZOOM, ...auto } : false,
130
+ maxScale: Math.max(1, merged.zoom.maxScale),
131
+ followSpeed: Math.max(0.05, merged.zoom.followSpeed),
132
+ },
133
+ captions: merged.captions,
134
+ keystrokes: merged.keystrokes,
135
+ encode,
136
+ range: { start, end: Math.max(start, end) },
137
+ onProgress: merged.onProgress,
138
+ };
139
+ }
@@ -0,0 +1,13 @@
1
+ import type { EasingName } from '../types.ts';
2
+ export type EasingFunction = (t: number) => number;
3
+ export declare const EASING_NAMES: EasingName[];
4
+ /**
5
+ * Returns the easing function for a name. The result clamps its input to [0, 1].
6
+ */
7
+ export declare function easing(name: EasingName | undefined): EasingFunction;
8
+ /**
9
+ * Cubic Hermite smoothstep, clamped.
10
+ */
11
+ export declare function smoothstep(edge0: number, edge1: number, x: number): number;
12
+ export declare function clamp(value: number, min: number, max: number): number;
13
+ export declare function lerp(a: number, b: number, t: number): number;
@@ -0,0 +1,40 @@
1
+ /**
2
+ * The default camera curve: the integral of a skewed bell-shaped velocity t^3 (1 - t)^4.
3
+ * It has no linear middle, a quick but soft start and a long, soft landing.
4
+ */
5
+ function smooth(t) {
6
+ const t2 = t * t;
7
+ const t4 = t2 * t2;
8
+ return t4 * (70 - 224 * t + 280 * t2 - 160 * t2 * t + 35 * t4);
9
+ }
10
+ const EASINGS = {
11
+ linear: (t) => t,
12
+ easeInOutCubic: (t) => (t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2),
13
+ easeInOutQuart: (t) => (t < 0.5 ? 8 * t ** 4 : 1 - (-2 * t + 2) ** 4 / 2),
14
+ easeInOutQuint: (t) => (t < 0.5 ? 16 * t ** 5 : 1 - (-2 * t + 2) ** 5 / 2),
15
+ easeOutCubic: (t) => 1 - (1 - t) ** 3,
16
+ easeOutQuart: (t) => 1 - (1 - t) ** 4,
17
+ easeOutExpo: (t) => (t >= 1 ? 1 : (1 - 2 ** (-10 * t)) / (1 - 2 ** -10)),
18
+ smooth,
19
+ };
20
+ export const EASING_NAMES = Object.keys(EASINGS);
21
+ /**
22
+ * Returns the easing function for a name. The result clamps its input to [0, 1].
23
+ */
24
+ export function easing(name) {
25
+ const fn = (name && EASINGS[name]) || smooth;
26
+ return (t) => (t <= 0 ? 0 : t >= 1 ? 1 : fn(t));
27
+ }
28
+ /**
29
+ * Cubic Hermite smoothstep, clamped.
30
+ */
31
+ export function smoothstep(edge0, edge1, x) {
32
+ const t = clamp((x - edge0) / (edge1 - edge0), 0, 1);
33
+ return t * t * (3 - 2 * t);
34
+ }
35
+ export function clamp(value, min, max) {
36
+ return value < min ? min : value > max ? max : value;
37
+ }
38
+ export function lerp(a, b, t) {
39
+ return a + (b - a) * t;
40
+ }
@@ -0,0 +1,39 @@
1
+ import type { SKRSContext2D } from '@napi-rs/canvas';
2
+ import type { Rect, SpotlightEvent } from '../types.ts';
3
+ import { type Rgba } from './color.ts';
4
+ import type { TimedEvent } from './timeline.ts';
5
+ export interface ClickStyle {
6
+ type: 'ripple' | 'ring' | 'none';
7
+ /**
8
+ * Fixed color, or null to adapt to the page under the click.
9
+ */
10
+ color: Rgba | null;
11
+ /**
12
+ * Final radius in output pixels at camera scale 1.
13
+ */
14
+ radius: number;
15
+ duration: number;
16
+ }
17
+ /**
18
+ * Click color with the most contrast against the page under the click (WCAG ratio, mean
19
+ * of a small area). White wins near-ties, so saturated mid-tone buttons get a white ring.
20
+ */
21
+ export declare function adaptiveClickColor(pageLuminance: number): Rgba;
22
+ export declare function parseClickColor(color: string | undefined): Rgba | null;
23
+ /**
24
+ * Draws one click effect at output position (x, y). `age` is in output ms; `scale` is
25
+ * the camera scale times the resolution unit. A ripple is a thin ring that expands and
26
+ * fades, over a very light fill that is gone by mid-life; a soft halo in the opposite
27
+ * tone keeps the ring readable on mid-tones. A ring is a slightly heavier ring alone.
28
+ */
29
+ export declare function drawClick(ctx: SKRSContext2D, style: ClickStyle, color: Rgba, x: number, y: number, age: number, scale: number): void;
30
+ /**
31
+ * Visibility of a spotlight at output time `t`, 0 to 1.
32
+ */
33
+ export declare function spotlightAmount(event: TimedEvent<SpotlightEvent>, t: number): number;
34
+ /**
35
+ * Dims the content outside the spotlight rectangle. Called with the content transform
36
+ * set (CSS pixels to output pixels) and the content clip active. The opening eases in
37
+ * from slightly larger, which reads as the light focusing.
38
+ */
39
+ export declare function drawSpotlight(ctx: SKRSContext2D, event: TimedEvent<SpotlightEvent>, amount: number, viewport: Rect, unit: number): void;
@@ -0,0 +1,91 @@
1
+ import { parseColor, rgba } from "./color.js";
2
+ import { smoothstep } from "./easing.js";
3
+ const INK = { r: 16, g: 18, b: 24, a: 1 };
4
+ const LIGHT = { r: 255, g: 255, b: 255, a: 1 };
5
+ const contrast = (a, b) => (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
6
+ /**
7
+ * Click color with the most contrast against the page under the click (WCAG ratio, mean
8
+ * of a small area). White wins near-ties, so saturated mid-tone buttons get a white ring.
9
+ */
10
+ export function adaptiveClickColor(pageLuminance) {
11
+ const white = contrast(1, pageLuminance);
12
+ const ink = contrast(0.006, pageLuminance);
13
+ return white >= ink * 0.75 ? LIGHT : INK;
14
+ }
15
+ export function parseClickColor(color) {
16
+ if (!color || color === 'auto')
17
+ return null;
18
+ return parseColor(color) ?? INK;
19
+ }
20
+ /**
21
+ * Draws one click effect at output position (x, y). `age` is in output ms; `scale` is
22
+ * the camera scale times the resolution unit. A ripple is a thin ring that expands and
23
+ * fades, over a very light fill that is gone by mid-life; a soft halo in the opposite
24
+ * tone keeps the ring readable on mid-tones. A ring is a slightly heavier ring alone.
25
+ */
26
+ export function drawClick(ctx, style, color, x, y, age, scale) {
27
+ if (style.type === 'none' || age < 0 || age >= style.duration)
28
+ return;
29
+ const p = age / style.duration;
30
+ const u = Math.max(0.5, scale);
31
+ const grow = 1 - (1 - p) ** 3;
32
+ const r = style.radius * scale * (0.3 + 0.7 * grow);
33
+ const fade = (1 - p) ** 1.25 * smoothstep(0, 0.05, p);
34
+ const halo = color === LIGHT ? INK : LIGHT;
35
+ const ring = style.type === 'ring';
36
+ ctx.save();
37
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
38
+ if (!ring) {
39
+ ctx.fillStyle = rgba(color, 0.14 * (1 - p) ** 4 * smoothstep(0, 0.05, p));
40
+ ctx.beginPath();
41
+ ctx.arc(x, y, r, 0, Math.PI * 2);
42
+ ctx.fill();
43
+ }
44
+ ctx.lineWidth = (ring ? 2.8 : 2.4 - 0.8 * p) * u;
45
+ ctx.strokeStyle = rgba(color, 0.95 * fade);
46
+ ctx.shadowColor = rgba(halo, 0.38 * fade);
47
+ ctx.shadowBlur = 3 * u;
48
+ ctx.beginPath();
49
+ ctx.arc(x, y, Math.max(0, r - ctx.lineWidth / 2), 0, Math.PI * 2);
50
+ ctx.stroke();
51
+ ctx.restore();
52
+ }
53
+ const SPOT_FADE_IN = 320;
54
+ const SPOT_FADE_OUT = 360;
55
+ const SPOT_PADDING = 10;
56
+ const SPOT_RADIUS = 12;
57
+ /**
58
+ * Visibility of a spotlight at output time `t`, 0 to 1.
59
+ */
60
+ export function spotlightAmount(event, t) {
61
+ const start = event.out;
62
+ const end = event.out + Math.max(0, event.duration);
63
+ if (t < start || t > end + SPOT_FADE_OUT)
64
+ return 0;
65
+ return Math.min(smoothstep(start, start + SPOT_FADE_IN, t), 1 - smoothstep(end, end + SPOT_FADE_OUT, t));
66
+ }
67
+ /**
68
+ * Dims the content outside the spotlight rectangle. Called with the content transform
69
+ * set (CSS pixels to output pixels) and the content clip active. The opening eases in
70
+ * from slightly larger, which reads as the light focusing.
71
+ */
72
+ export function drawSpotlight(ctx, event, amount, viewport, unit) {
73
+ if (amount <= 0)
74
+ return;
75
+ const pad = (event.padding ?? SPOT_PADDING) + 14 * (1 - amount);
76
+ const r = event.rect;
77
+ const radius = event.radius ?? SPOT_RADIUS;
78
+ ctx.save();
79
+ ctx.beginPath();
80
+ ctx.rect(viewport.x, viewport.y, viewport.width, viewport.height);
81
+ ctx.roundRect(r.x - pad, r.y - pad, r.width + 2 * pad, r.height + 2 * pad, radius);
82
+ ctx.fillStyle = `rgba(6, 8, 14, ${(0.58 * amount).toFixed(4)})`;
83
+ ctx.fill('evenodd');
84
+ ctx.beginPath();
85
+ ctx.roundRect(r.x - pad, r.y - pad, r.width + 2 * pad, r.height + 2 * pad, radius);
86
+ const t = ctx.getTransform();
87
+ ctx.lineWidth = (1.2 * unit) / Math.max(1e-6, Math.hypot(t.a, t.b));
88
+ ctx.strokeStyle = `rgba(255, 255, 255, ${(0.28 * amount).toFixed(4)})`;
89
+ ctx.stroke();
90
+ ctx.restore();
91
+ }
@@ -0,0 +1,52 @@
1
+ import type { Size } from '../types.ts';
2
+ import type { ResolvedOptions } from './defaults.ts';
3
+ /**
4
+ * The ffmpeg binary: `encode.ffmpegPath`, then `AUTOKAST_FFMPEG`, then `ffmpeg` on PATH.
5
+ */
6
+ export declare function ffmpegPath(options: ResolvedOptions): string;
7
+ /**
8
+ * Fails early, with install advice, when ffmpeg cannot run.
9
+ */
10
+ export declare function checkFfmpeg(binary: string): Promise<void>;
11
+ /**
12
+ * Arguments that encode raw RGBA frames from stdin into `output`.
13
+ */
14
+ export declare function encoderArgs(format: 'mp4' | 'webm' | 'mkv', size: Size, fps: number, encode: ResolvedOptions['encode'], output: string): string[];
15
+ /**
16
+ * GIF fps and width: 25 fps (GIF delays are in hundredths of a second) and at most
17
+ * 1280 pixels wide.
18
+ */
19
+ export declare function gifSettings(size: Size, fps: number): {
20
+ fps: number;
21
+ width: number;
22
+ };
23
+ /**
24
+ * Arguments that turn a lossless intermediate into an optimized GIF with its own palette.
25
+ */
26
+ export declare function gifArgs(input: string, output: string, fps: number, width: number): string[];
27
+ /**
28
+ * Runs ffmpeg to completion, with its stderr in the error on failure.
29
+ */
30
+ export declare function runFfmpeg(binary: string, args: string[]): Promise<void>;
31
+ /**
32
+ * An ffmpeg process fed through stdin, with backpressure and clear failures.
33
+ */
34
+ export declare class FfmpegProcess {
35
+ private readonly child;
36
+ private stderr;
37
+ private failure;
38
+ private readonly done;
39
+ constructor(binary: string, args: string[]);
40
+ /**
41
+ * Writes one frame; waits when the pipe is full.
42
+ */
43
+ write(data: Buffer): Promise<void>;
44
+ /**
45
+ * Closes the input and waits for ffmpeg to exit.
46
+ */
47
+ finish(): Promise<void>;
48
+ /**
49
+ * Stops ffmpeg (after an error in the render loop).
50
+ */
51
+ kill(): void;
52
+ }
@@ -0,0 +1,226 @@
1
+ import { spawn } from 'node:child_process';
2
+ const X264 = {
3
+ draft: { preset: 'veryfast', crf: 24 },
4
+ standard: { preset: 'medium', crf: 16 },
5
+ high: { preset: 'slow', crf: 12 },
6
+ max: { preset: 'slow', crf: 6 },
7
+ };
8
+ const VP9 = {
9
+ draft: { cpu: 5, crf: 38 },
10
+ standard: { cpu: 2, crf: 28 },
11
+ high: { cpu: 1, crf: 20 },
12
+ max: { cpu: 1, crf: 10 },
13
+ };
14
+ const COLOR_TAGS = [
15
+ '-colorspace',
16
+ 'bt709',
17
+ '-color_primaries',
18
+ 'bt709',
19
+ '-color_trc',
20
+ 'bt709',
21
+ '-color_range',
22
+ 'tv',
23
+ ];
24
+ /*
25
+ * Newer ffmpeg versions take the color tags from the frames, not from the output options,
26
+ * so the filter chain sets them too.
27
+ */
28
+ const FRAME_TAGS = 'setparams=colorspace=bt709:color_primaries=bt709:color_trc=bt709:range=tv';
29
+ /**
30
+ * The ffmpeg binary: `encode.ffmpegPath`, then `AUTOKAST_FFMPEG`, then `ffmpeg` on PATH.
31
+ */
32
+ export function ffmpegPath(options) {
33
+ return options.encode.ffmpegPath || process.env.AUTOKAST_FFMPEG || 'ffmpeg';
34
+ }
35
+ /**
36
+ * Fails early, with install advice, when ffmpeg cannot run.
37
+ */
38
+ export async function checkFfmpeg(binary) {
39
+ await new Promise((resolve, reject) => {
40
+ const child = spawn(binary, ['-version'], { stdio: 'ignore' });
41
+ child.on('error', (error) => {
42
+ reject(new Error(error.code === 'ENOENT'
43
+ ? `ffmpeg not found ("${binary}"). Install ffmpeg, or set encode.ffmpegPath or the AUTOKAST_FFMPEG environment variable.`
44
+ : `Cannot run ffmpeg ("${binary}"): ${error.message}`));
45
+ });
46
+ child.on('close', (code) => code === 0 ? resolve() : reject(new Error(`"${binary} -version" exited with code ${code}.`)));
47
+ });
48
+ }
49
+ /**
50
+ * Arguments that encode raw RGBA frames from stdin into `output`.
51
+ */
52
+ export function encoderArgs(format, size, fps, encode, output) {
53
+ const input = [
54
+ '-y',
55
+ '-hide_banner',
56
+ '-loglevel',
57
+ 'error',
58
+ '-f',
59
+ 'rawvideo',
60
+ '-pix_fmt',
61
+ 'rgba',
62
+ '-s',
63
+ `${size.width}x${size.height}`,
64
+ '-framerate',
65
+ String(fps),
66
+ '-i',
67
+ 'pipe:0',
68
+ ];
69
+ if (format === 'mkv') {
70
+ return [...input, '-c:v', 'libx264rgb', '-preset', 'ultrafast', '-qp', '0', output];
71
+ }
72
+ const pixelFormat = encode.pixelFormat;
73
+ const convert = [
74
+ '-vf',
75
+ `scale=out_color_matrix=bt709:out_range=tv:flags=accurate_rnd+full_chroma_int,format=${pixelFormat},${FRAME_TAGS}`,
76
+ ];
77
+ if (format === 'webm') {
78
+ const q = VP9[encode.quality] ?? VP9.standard;
79
+ return [
80
+ ...input,
81
+ ...convert,
82
+ '-c:v',
83
+ 'libvpx-vp9',
84
+ '-crf',
85
+ String(encode.crf ?? q.crf),
86
+ '-b:v',
87
+ '0',
88
+ '-deadline',
89
+ 'good',
90
+ '-cpu-used',
91
+ String(q.cpu),
92
+ '-row-mt',
93
+ '1',
94
+ '-pix_fmt',
95
+ pixelFormat,
96
+ ...COLOR_TAGS,
97
+ output,
98
+ ];
99
+ }
100
+ const q = X264[encode.quality] ?? X264.standard;
101
+ return [
102
+ ...input,
103
+ ...convert,
104
+ '-c:v',
105
+ 'libx264',
106
+ '-preset',
107
+ encode.preset ?? q.preset,
108
+ '-crf',
109
+ String(encode.crf ?? q.crf),
110
+ '-x264-params',
111
+ 'aq-mode=3:colorprim=bt709:transfer=bt709:colormatrix=bt709',
112
+ '-pix_fmt',
113
+ pixelFormat,
114
+ ...COLOR_TAGS,
115
+ '-movflags',
116
+ '+faststart',
117
+ output,
118
+ ];
119
+ }
120
+ /**
121
+ * GIF fps and width: 25 fps (GIF delays are in hundredths of a second) and at most
122
+ * 1280 pixels wide.
123
+ */
124
+ export function gifSettings(size, fps) {
125
+ return { fps: Math.min(fps, 25), width: Math.min(size.width, 1280) };
126
+ }
127
+ /**
128
+ * Arguments that turn a lossless intermediate into an optimized GIF with its own palette.
129
+ */
130
+ export function gifArgs(input, output, fps, width) {
131
+ const filter = `fps=${fps},scale=${width}:-1:flags=lanczos,split[a][b];` +
132
+ `[a]palettegen=max_colors=256:stats_mode=diff[p];` +
133
+ `[b][p]paletteuse=dither=sierra2_4a:diff_mode=rectangle`;
134
+ return [
135
+ '-y',
136
+ '-hide_banner',
137
+ '-loglevel',
138
+ 'error',
139
+ '-i',
140
+ input,
141
+ '-vf',
142
+ filter,
143
+ '-loop',
144
+ '0',
145
+ output,
146
+ ];
147
+ }
148
+ /**
149
+ * Runs ffmpeg to completion, with its stderr in the error on failure.
150
+ */
151
+ export function runFfmpeg(binary, args) {
152
+ return new FfmpegProcess(binary, args).finish();
153
+ }
154
+ /**
155
+ * An ffmpeg process fed through stdin, with backpressure and clear failures.
156
+ */
157
+ export class FfmpegProcess {
158
+ child;
159
+ stderr = '';
160
+ failure = null;
161
+ done;
162
+ constructor(binary, args) {
163
+ this.child = spawn(binary, args, { stdio: ['pipe', 'ignore', 'pipe'] });
164
+ this.child.stderr?.on('data', (chunk) => {
165
+ this.stderr = (this.stderr + chunk.toString()).slice(-4000);
166
+ });
167
+ this.child.stdin?.on('error', (error) => {
168
+ this.failure ??= error;
169
+ });
170
+ this.done = new Promise((resolve, reject) => {
171
+ this.child.on('error', (error) => {
172
+ this.failure = error;
173
+ reject(new Error(`Cannot run ffmpeg ("${binary}"): ${error.message}`));
174
+ });
175
+ this.child.on('close', (code, signal) => {
176
+ if (code === 0)
177
+ resolve();
178
+ else {
179
+ const reason = signal ? `signal ${signal}` : `code ${code}`;
180
+ this.failure ??= new Error(`ffmpeg exited with ${reason}`);
181
+ reject(new Error(`ffmpeg failed (${reason}):\n${this.stderr.trim() || '(no output)'}`));
182
+ }
183
+ });
184
+ });
185
+ this.done.catch(() => { });
186
+ }
187
+ /**
188
+ * Writes one frame; waits when the pipe is full.
189
+ */
190
+ async write(data) {
191
+ if (this.failure)
192
+ await this.done;
193
+ const stdin = this.child.stdin;
194
+ if (!stdin || stdin.destroyed) {
195
+ await this.done;
196
+ throw new Error('ffmpeg closed its input.');
197
+ }
198
+ if (!stdin.write(data)) {
199
+ await new Promise((resolve) => {
200
+ const finish = () => {
201
+ stdin.off('drain', finish);
202
+ this.child.off('close', finish);
203
+ resolve();
204
+ };
205
+ stdin.on('drain', finish);
206
+ this.child.on('close', finish);
207
+ });
208
+ if (this.failure)
209
+ await this.done;
210
+ }
211
+ }
212
+ /**
213
+ * Closes the input and waits for ffmpeg to exit.
214
+ */
215
+ async finish() {
216
+ this.child.stdin?.end();
217
+ await this.done;
218
+ }
219
+ /**
220
+ * Stops ffmpeg (after an error in the render loop).
221
+ */
222
+ kill() {
223
+ this.child.stdin?.destroy();
224
+ this.child.kill('SIGKILL');
225
+ }
226
+ }