@open-artifact/wasm-motion 0.0.0-stage → 0.12.0-rc.0

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.
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@open-artifact/wasm-motion",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.12.0-rc.0",
4
+ "description": "Motion pixel work compiled from crates/open-artifact-motion to WebAssembly (generated/, built by scripts/build-wasm.mjs): GIF quantizing and encoding, MOV (QuickTime Animation) writing, and the flash analysis.",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./src/index.d.ts",
9
+ "default": "./src/index.js"
10
+ },
11
+ "./package.json": "./package.json"
12
+ },
13
+ "files": [
14
+ "src",
15
+ "generated",
16
+ "LICENSE",
17
+ "NOTICE"
18
+ ],
19
+ "license": "Apache-2.0",
20
+ "author": {
21
+ "name": "Jim Liu 宝玉",
22
+ "url": "https://github.com/JimLiu"
23
+ },
24
+ "homepage": "https://github.com/JimLiu/open-artifact#readme",
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/JimLiu/open-artifact.git",
28
+ "directory": "packages/wasm-motion"
29
+ },
30
+ "bugs": {
31
+ "url": "https://github.com/JimLiu/open-artifact/issues"
32
+ },
33
+ "publishConfig": {
34
+ "access": "public",
35
+ "tag": "next"
36
+ },
37
+ "gitHead": "ac158a48a1e61fbbdd71f0f6e33ee9bdb24fd35f"
38
+ }
package/src/flash.d.ts ADDED
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Flash analysis (WCAG 2.3.1 general flashes) of a scene sampled at 30 fps:
3
+ * how fast its quickest three flashes over a large enough area are, and so
4
+ * the least share of its length it may be shortened to.
5
+ */
6
+ import { type RgbaPixels } from './module.ts';
7
+ /** Frames are sampled this many times a second. */
8
+ export declare const FLASH_SAMPLE_FPS = 30;
9
+ /** The film around a scene sampled too (seconds each side): flashes at its cuts count. */
10
+ export declare const FLASH_SAMPLE_PADDING_SECONDS = 1;
11
+ /** Longer scenes are not checked. */
12
+ export declare const FLASH_MAX_SCENE_SECONDS = 30;
13
+ /** Frames are rendered at this share of the film's size for the analysis. */
14
+ export declare const FLASH_RASTER_SCALE = 0.103;
15
+ /** What the analysis found. */
16
+ export interface FlashReport {
17
+ /** Frames analyzed. */
18
+ frames: number;
19
+ /** The quickest three flashes within the judged frames: the sample frames of their first and last transition. */
20
+ fastest: {
21
+ first: number;
22
+ last: number;
23
+ } | null;
24
+ /** How long the quickest three flashes took, seconds (`Infinity`: none). */
25
+ span: number;
26
+ /** The least share of its length the scene can be shortened to: 0 any, 1 none. */
27
+ safeScale: number;
28
+ }
29
+ /** Which frames to sample for a scene and which of them are judged. */
30
+ export interface FlashSampling {
31
+ /** The times to render, on the same clock as the scene's start (seconds). */
32
+ times: number[];
33
+ /** Transitions judged reach into sample frames `fromFrame`…`toFrame`. */
34
+ fromFrame: number;
35
+ toFrame: number;
36
+ }
37
+ /** A flash analyzer fed one sampled frame at a time. */
38
+ export interface FlashFrameAnalyzer {
39
+ /** Adds the next frame, `width` pixels wide; every frame must be the size of the first. */
40
+ add(pixels: RgbaPixels, width: number): void;
41
+ report(): FlashReport;
42
+ /** Releases the analyzer. */
43
+ dispose(): void;
44
+ }
45
+ /** The least share of its length a stretch whose quickest three flashes took `span` seconds can be shortened to. */
46
+ export declare function flashSafeScale(span: number): number;
47
+ /**
48
+ * The sampling of a scene starting at `sceneStart` and `sceneLength` long
49
+ * in a film `filmLength` long (all seconds on the film's own clock), with a
50
+ * second of film each side; `null` for a scene too long to check.
51
+ */
52
+ export declare function planFlashSampling(sceneStart: number, sceneLength: number, filmLength: number): FlashSampling | null;
53
+ /** An analyzer judging flashes that reach into sample frames `fromFrame`…`toFrame`. */
54
+ export declare function createFlashAnalyzer(range: {
55
+ fromFrame: number;
56
+ toFrame: number;
57
+ }): FlashFrameAnalyzer;
58
+ /** Analyzes frames sampled at 30 fps, all `width` pixels wide. */
59
+ export declare function analyzeFlashes(frames: Iterable<RgbaPixels>, options: {
60
+ width: number;
61
+ fromFrame: number;
62
+ toFrame: number;
63
+ }): FlashReport;
package/src/flash.js ADDED
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Flash analysis (WCAG 2.3.1 general flashes) of a scene sampled at 30 fps:
3
+ * how fast its quickest three flashes over a large enough area are, and so
4
+ * the least share of its length it may be shortened to.
5
+ */
6
+ import { pixelBytes, videoModule } from "./module.js";
7
+ /** Frames are sampled this many times a second. */
8
+ export const FLASH_SAMPLE_FPS = 30;
9
+ /** The film around a scene sampled too (seconds each side): flashes at its cuts count. */
10
+ export const FLASH_SAMPLE_PADDING_SECONDS = 1;
11
+ /** Longer scenes are not checked. */
12
+ export const FLASH_MAX_SCENE_SECONDS = 30;
13
+ /** Frames are rendered at this share of the film's size for the analysis. */
14
+ export const FLASH_RASTER_SCALE = 0.103;
15
+ /** Three flashes may take this long at the least (seconds). */
16
+ const SAFE_SPAN_SECONDS = 31 / 30;
17
+ /** The least share of its length a stretch whose quickest three flashes took `span` seconds can be shortened to. */
18
+ export function flashSafeScale(span) {
19
+ return Math.min(1, SAFE_SPAN_SECONDS / span);
20
+ }
21
+ /**
22
+ * The sampling of a scene starting at `sceneStart` and `sceneLength` long
23
+ * in a film `filmLength` long (all seconds on the film's own clock), with a
24
+ * second of film each side; `null` for a scene too long to check.
25
+ */
26
+ export function planFlashSampling(sceneStart, sceneLength, filmLength) {
27
+ if (sceneLength > FLASH_MAX_SCENE_SECONDS)
28
+ return null;
29
+ const from = Math.max(0, sceneStart - FLASH_SAMPLE_PADDING_SECONDS);
30
+ const fromFrame = Math.round((sceneStart - from) * FLASH_SAMPLE_FPS);
31
+ const until = Math.min(filmLength, sceneStart + sceneLength + FLASH_SAMPLE_PADDING_SECONDS);
32
+ const count = Math.max(0, Math.floor((until - from) * FLASH_SAMPLE_FPS + 1e-6) + 1);
33
+ return {
34
+ times: Array.from({ length: count }, (_, index) => from + index / FLASH_SAMPLE_FPS),
35
+ fromFrame,
36
+ toFrame: fromFrame + Math.round(sceneLength * FLASH_SAMPLE_FPS),
37
+ };
38
+ }
39
+ const toFrameIndex = (value) => Math.max(0, Math.min(0xffff_ffff, Math.round(value) || 0));
40
+ /** An analyzer judging flashes that reach into sample frames `fromFrame`…`toFrame`. */
41
+ export function createFlashAnalyzer(range) {
42
+ let analyzer = new (videoModule().FlashAnalyzer)(toFrameIndex(range.fromFrame), toFrameIndex(range.toFrame));
43
+ const open = () => {
44
+ if (analyzer === null)
45
+ throw new Error('The flash analyzer is released.');
46
+ return analyzer;
47
+ };
48
+ return {
49
+ add: (pixels, width) => open().add(pixelBytes(pixels), width),
50
+ report: () => {
51
+ const current = open();
52
+ const fastest = current.fastest();
53
+ const span = fastest.length === 2 ? (fastest[1] - fastest[0]) / FLASH_SAMPLE_FPS : Infinity;
54
+ return {
55
+ frames: current.frames,
56
+ fastest: fastest.length === 2 ? { first: fastest[0], last: fastest[1] } : null,
57
+ span,
58
+ safeScale: current.safeScale(),
59
+ };
60
+ },
61
+ dispose: () => {
62
+ analyzer?.free();
63
+ analyzer = null;
64
+ },
65
+ };
66
+ }
67
+ /** Analyzes frames sampled at 30 fps, all `width` pixels wide. */
68
+ export function analyzeFlashes(frames, options) {
69
+ const analyzer = createFlashAnalyzer(options);
70
+ try {
71
+ for (const frame of frames)
72
+ analyzer.add(frame, options.width);
73
+ return analyzer.report();
74
+ }
75
+ finally {
76
+ analyzer.dispose();
77
+ }
78
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * GIF sessions run step by step on the module: in the Worker, or in-thread
3
+ * where there is none. A session gathers sample frames for its palette,
4
+ * then encodes frames, moving finished bytes out of the module as it goes.
5
+ */
6
+ /** One step of a session. */
7
+ export type GifStep = {
8
+ kind: 'open';
9
+ width: number;
10
+ height: number;
11
+ repeat: number;
12
+ palette: Uint8Array | null;
13
+ } | {
14
+ kind: 'sample';
15
+ pixels: Uint8Array;
16
+ } | {
17
+ kind: 'add';
18
+ pixels: Uint8Array;
19
+ delayCs: number;
20
+ } | {
21
+ kind: 'finish';
22
+ } | {
23
+ kind: 'close';
24
+ };
25
+ /** What a step answers: the GIF's size so far after `add`, its bytes after `finish`. */
26
+ export type GifAnswer = number | Uint8Array | null;
27
+ /** Page → Worker. */
28
+ export interface GifStepMessage {
29
+ id: number;
30
+ session: number;
31
+ step: GifStep;
32
+ }
33
+ /** Worker → page. */
34
+ export type GifWorkerMessage = {
35
+ type: 'ready';
36
+ } | {
37
+ id: number;
38
+ type: 'done';
39
+ answer: GifAnswer;
40
+ } | {
41
+ id: number;
42
+ type: 'failed';
43
+ message: string;
44
+ fatal: boolean;
45
+ };
46
+ /** Runs one step of session `id`. A step that throws closes the session. */
47
+ export declare function runGifStep(id: number, step: GifStep): GifAnswer;
@@ -0,0 +1,106 @@
1
+ /**
2
+ * GIF sessions run step by step on the module: in the Worker, or in-thread
3
+ * where there is none. A session gathers sample frames for its palette,
4
+ * then encodes frames, moving finished bytes out of the module as it goes.
5
+ */
6
+ import { videoModule } from "./module.js";
7
+ const sessions = new Map();
8
+ function release(id) {
9
+ const session = sessions.get(id);
10
+ if (!session)
11
+ return;
12
+ session.samples?.free();
13
+ session.encoder?.free();
14
+ sessions.delete(id);
15
+ }
16
+ function sessionOf(id) {
17
+ const session = sessions.get(id);
18
+ if (!session)
19
+ throw new Error('The GIF session is closed.');
20
+ return session;
21
+ }
22
+ /** The encoder, made on the first frame with the palette given or picked from the samples (or that frame). */
23
+ function encoderOf(session, first) {
24
+ if (session.encoder)
25
+ return session.encoder;
26
+ const wasm = videoModule();
27
+ let palette = session.palette;
28
+ if (palette === null) {
29
+ const samples = session.samples ?? new wasm.GifPaletteBuilder(false);
30
+ if (session.samples === null)
31
+ samples.add(first);
32
+ palette = samples.finish();
33
+ samples.free();
34
+ session.samples = null;
35
+ }
36
+ session.encoder = new wasm.GifEncoder(session.width, session.height, palette, session.repeat);
37
+ return session.encoder;
38
+ }
39
+ function joined(chunks) {
40
+ const bytes = new Uint8Array(chunks.reduce((sum, chunk) => sum + chunk.length, 0));
41
+ let at = 0;
42
+ for (const chunk of chunks) {
43
+ bytes.set(chunk, at);
44
+ at += chunk.length;
45
+ }
46
+ return bytes;
47
+ }
48
+ /** Runs one step of session `id`. A step that throws closes the session. */
49
+ export function runGifStep(id, step) {
50
+ try {
51
+ switch (step.kind) {
52
+ case 'open': {
53
+ release(id);
54
+ sessions.set(id, {
55
+ width: step.width,
56
+ height: step.height,
57
+ repeat: step.repeat,
58
+ palette: step.palette,
59
+ samples: null,
60
+ encoder: null,
61
+ chunks: [],
62
+ byteLength: 0,
63
+ });
64
+ return null;
65
+ }
66
+ case 'sample': {
67
+ const session = sessionOf(id);
68
+ if (session.encoder || session.palette)
69
+ return null;
70
+ session.samples ??= new (videoModule().GifPaletteBuilder)(false);
71
+ session.samples.add(step.pixels);
72
+ return null;
73
+ }
74
+ case 'add': {
75
+ const session = sessionOf(id);
76
+ const encoder = encoderOf(session, step.pixels);
77
+ encoder.add(step.pixels, step.delayCs);
78
+ const ready = encoder.takeReady();
79
+ if (ready.length > 0)
80
+ session.chunks.push(ready);
81
+ session.byteLength = encoder.byteLength;
82
+ return session.byteLength;
83
+ }
84
+ case 'finish': {
85
+ const session = sessionOf(id);
86
+ if (!session.encoder)
87
+ throw new Error('A GIF needs at least one frame.');
88
+ session.chunks.push(session.encoder.finish());
89
+ const bytes = joined(session.chunks);
90
+ release(id);
91
+ return bytes;
92
+ }
93
+ case 'close':
94
+ release(id);
95
+ return null;
96
+ default: {
97
+ const never = step;
98
+ throw new Error(`Unknown GIF step ${String(never)}`);
99
+ }
100
+ }
101
+ }
102
+ catch (error) {
103
+ release(id);
104
+ throw error;
105
+ }
106
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * GIF encoding off the page's thread. A session takes sample frames for
3
+ * its palette, then the frames themselves, and hands back the file.
4
+ *
5
+ * In a page the steps run in a Worker (started on first use, stopped when
6
+ * idle). Where there are no Workers (Node tests, the CLI), or the Worker
7
+ * cannot start, the same steps run in-thread. Steps of a session run in
8
+ * the order they were asked for.
9
+ */
10
+ import { type RgbaPixels } from './module.ts';
11
+ /** Options of a GIF session. */
12
+ export interface GifSessionOptions {
13
+ width: number;
14
+ height: number;
15
+ /** Plays after the first (default 0: loop for ever). */
16
+ repeat?: number;
17
+ /** A palette to use (RGB triples); otherwise one is picked from the samples, or from the first frame. */
18
+ palette?: Uint8Array;
19
+ }
20
+ /**
21
+ * A GIF being written. The pixels given are handed over (moved to the
22
+ * Worker where they can be): do not use the arrays afterwards.
23
+ */
24
+ export interface GifSession {
25
+ /** Adds a frame the palette is picked from; ignored once frames are added or with a palette given. */
26
+ sample(pixels: RgbaPixels): Promise<void>;
27
+ /** Adds a frame shown for `delayCs` hundredths of a second; the GIF's size so far, in bytes. */
28
+ add(pixels: RgbaPixels, delayCs: number): Promise<number>;
29
+ /** Ends the GIF: its bytes. */
30
+ finish(): Promise<Uint8Array>;
31
+ /** Drops the session unfinished. */
32
+ close(): void;
33
+ }
34
+ /** Where sessions run: in a Worker, or in-thread. */
35
+ export declare function gifBackend(): 'worker' | 'inline';
36
+ /** Starts a GIF of `width` × `height`. */
37
+ export declare function openGifSession(options: GifSessionOptions): GifSession;
@@ -0,0 +1,187 @@
1
+ /**
2
+ * GIF encoding off the page's thread. A session takes sample frames for
3
+ * its palette, then the frames themselves, and hands back the file.
4
+ *
5
+ * In a page the steps run in a Worker (started on first use, stopped when
6
+ * idle). Where there are no Workers (Node tests, the CLI), or the Worker
7
+ * cannot start, the same steps run in-thread. Steps of a session run in
8
+ * the order they were asked for.
9
+ */
10
+ import { pixelBytes } from "./module.js";
11
+ /** How long an idle Worker is kept, ms. */
12
+ const IDLE_MS = 20_000;
13
+ let worker = null;
14
+ let workerReady = false;
15
+ /** The Worker could not start here: run in-thread from now on. */
16
+ let workerBroken = false;
17
+ let idleTimer;
18
+ let nextId = 1;
19
+ let nextSession = 1;
20
+ let openSessions = 0;
21
+ const pending = new Map();
22
+ /** Steps asked for before the Worker said it is ready. */
23
+ const waiting = [];
24
+ let inlineQueue = Promise.resolve();
25
+ /** Where sessions run: in a Worker, or in-thread. */
26
+ export function gifBackend() {
27
+ return typeof Worker === 'undefined' || workerBroken ? 'inline' : 'worker';
28
+ }
29
+ function runInline(job) {
30
+ inlineQueue = inlineQueue.then(async () => {
31
+ const { runGifStep } = await import("./gif-jobs.js");
32
+ try {
33
+ job.resolve(runGifStep(job.message.session, job.message.step));
34
+ }
35
+ catch (error) {
36
+ job.reject(error instanceof Error ? error : new Error(String(error)));
37
+ }
38
+ });
39
+ }
40
+ function stopWorker() {
41
+ clearTimeout(idleTimer);
42
+ worker?.terminate();
43
+ worker = null;
44
+ workerReady = false;
45
+ }
46
+ function scheduleIdle() {
47
+ clearTimeout(idleTimer);
48
+ if (worker && pending.size === 0 && waiting.length === 0 && openSessions === 0)
49
+ idleTimer = setTimeout(stopWorker, IDLE_MS);
50
+ }
51
+ /** Moves a step's pixels to the Worker when the array owns its whole buffer; copies them otherwise. */
52
+ function transferOf(step) {
53
+ if (step.kind !== 'sample' && step.kind !== 'add')
54
+ return [];
55
+ const { buffer, byteOffset, byteLength } = step.pixels;
56
+ return buffer instanceof ArrayBuffer && byteOffset === 0 && byteLength === buffer.byteLength ? [buffer] : [];
57
+ }
58
+ function post(target, job) {
59
+ pending.set(job.message.id, job);
60
+ try {
61
+ target.postMessage(job.message, transferOf(job.message.step));
62
+ }
63
+ catch (error) {
64
+ pending.delete(job.message.id);
65
+ job.reject(error instanceof Error ? error : new Error(String(error)));
66
+ }
67
+ }
68
+ /** The Worker failed: before it was ready, its steps run in-thread; after, they fail. */
69
+ function onWorkerError(event) {
70
+ event.preventDefault();
71
+ const held = waiting.splice(0);
72
+ const lost = [...pending.values()];
73
+ pending.clear();
74
+ if (!workerReady) {
75
+ workerBroken = true;
76
+ for (const job of held)
77
+ runInline(job);
78
+ }
79
+ else {
80
+ for (const job of [...lost, ...held])
81
+ job.reject(new Error('The GIF worker stopped.'));
82
+ }
83
+ stopWorker();
84
+ }
85
+ function onMessage(event) {
86
+ const message = event.data;
87
+ if (message.type === 'ready') {
88
+ workerReady = true;
89
+ const target = worker;
90
+ for (const job of waiting.splice(0))
91
+ if (target)
92
+ post(target, job);
93
+ return;
94
+ }
95
+ const job = pending.get(message.id);
96
+ if (!job)
97
+ return;
98
+ pending.delete(message.id);
99
+ if (message.type === 'done')
100
+ job.resolve(message.answer);
101
+ else {
102
+ // A trapped module is not reused.
103
+ if (message.fatal)
104
+ stopWorker();
105
+ job.reject(new Error(message.message));
106
+ }
107
+ scheduleIdle();
108
+ }
109
+ function getWorker() {
110
+ if (worker)
111
+ return worker;
112
+ if (workerBroken || typeof Worker === 'undefined')
113
+ return null;
114
+ try {
115
+ worker = new Worker(new URL('./worker.js', import.meta.url), { type: 'module', name: 'open-artifact-gif' });
116
+ }
117
+ catch {
118
+ workerBroken = true;
119
+ return null;
120
+ }
121
+ worker.addEventListener('message', onMessage);
122
+ worker.addEventListener('error', onWorkerError);
123
+ return worker;
124
+ }
125
+ function run(session, step) {
126
+ return new Promise((resolve, reject) => {
127
+ const job = { message: { id: nextId++, session, step }, resolve, reject };
128
+ const target = getWorker();
129
+ if (!target)
130
+ return runInline(job);
131
+ clearTimeout(idleTimer);
132
+ if (workerReady)
133
+ post(target, job);
134
+ else
135
+ waiting.push(job);
136
+ });
137
+ }
138
+ const toUint16 = (value) => Math.max(0, Math.min(65535, Math.round(value) || 0));
139
+ /** Starts a GIF of `width` × `height`. */
140
+ export function openGifSession(options) {
141
+ const session = nextSession++;
142
+ let open = true;
143
+ openSessions++;
144
+ const end = () => {
145
+ if (!open)
146
+ return;
147
+ open = false;
148
+ openSessions--;
149
+ scheduleIdle();
150
+ };
151
+ const step = (next) => {
152
+ if (!open)
153
+ return Promise.reject(new Error('The GIF session is closed.'));
154
+ const answer = run(session, next);
155
+ answer.catch(end);
156
+ return answer;
157
+ };
158
+ void step({
159
+ kind: 'open',
160
+ width: options.width,
161
+ height: options.height,
162
+ repeat: toUint16(options.repeat ?? 0),
163
+ palette: options.palette ?? null,
164
+ }).catch(() => { });
165
+ return {
166
+ sample: async (pixels) => {
167
+ await step({ kind: 'sample', pixels: pixelBytes(pixels) });
168
+ },
169
+ add: async (pixels, delayCs) => {
170
+ const answer = await step({ kind: 'add', pixels: pixelBytes(pixels), delayCs: toUint16(delayCs) });
171
+ return typeof answer === 'number' ? answer : 0;
172
+ },
173
+ finish: async () => {
174
+ const answer = await step({ kind: 'finish' });
175
+ end();
176
+ if (!(answer instanceof Uint8Array))
177
+ throw new Error('The GIF did not finish.');
178
+ return answer;
179
+ },
180
+ close: () => {
181
+ if (!open)
182
+ return;
183
+ void run(session, { kind: 'close' }).catch(() => { });
184
+ end();
185
+ },
186
+ };
187
+ }
package/src/gif.d.ts ADDED
@@ -0,0 +1,46 @@
1
+ /**
2
+ * GIF encoding in this thread: a palette picked from sample frames, then
3
+ * an encoder fed one frame at a time. Use it where blocking is fine (a
4
+ * Worker, Node, size estimates over a few frames); `openGifSession` runs
5
+ * the same work in a Worker for a page.
6
+ */
7
+ import { type RgbaPixels } from './module.ts';
8
+ /** Options of a palette. */
9
+ export interface GifPaletteOptions {
10
+ /** Count fewer pixels and refine less (for a quick palette of one frame). */
11
+ fast?: boolean;
12
+ }
13
+ /** Options of a GIF. */
14
+ export interface GifEncoderOptions {
15
+ width: number;
16
+ height: number;
17
+ /** The shared color table: RGB triples, at most 255 colors (see `buildGifPalette`). */
18
+ palette: Uint8Array;
19
+ /** Plays after the first (default 0: loop for ever). */
20
+ repeat?: number;
21
+ }
22
+ /** A GIF being written. */
23
+ export interface GifFrameEncoder {
24
+ /**
25
+ * Adds a frame of `width` × `height` RGBA pixels shown for `delayCs`
26
+ * hundredths of a second; the bytes it added (0 when nothing changed:
27
+ * the frame before is shown longer instead).
28
+ */
29
+ add(pixels: RgbaPixels, delayCs: number): number;
30
+ /** Bytes written so far. */
31
+ readonly byteLength: number;
32
+ /** The bytes written so far that no later frame changes, handed out once (keeps the module's memory small). */
33
+ takeReady(): Uint8Array;
34
+ /** Ends the GIF and releases the encoder; the bytes not handed out yet. */
35
+ finish(): Uint8Array;
36
+ /** Releases the encoder without finishing. */
37
+ dispose(): void;
38
+ }
39
+ /**
40
+ * A palette for frames (RGB triples, at most 255 colors): the exact colors
41
+ * when there are few, else large flat areas kept exact and the rest by a
42
+ * weighted median cut refined by k-means.
43
+ */
44
+ export declare function buildGifPalette(frames: Iterable<RgbaPixels>, options?: GifPaletteOptions): Uint8Array;
45
+ /** A looping GIF written frame by frame. */
46
+ export declare function createGifEncoder(options: GifEncoderOptions): GifFrameEncoder;
package/src/gif.js ADDED
@@ -0,0 +1,54 @@
1
+ /**
2
+ * GIF encoding in this thread: a palette picked from sample frames, then
3
+ * an encoder fed one frame at a time. Use it where blocking is fine (a
4
+ * Worker, Node, size estimates over a few frames); `openGifSession` runs
5
+ * the same work in a Worker for a page.
6
+ */
7
+ import { pixelBytes, videoModule } from "./module.js";
8
+ const toUint16 = (value) => Math.max(0, Math.min(65535, Math.round(value) || 0));
9
+ /**
10
+ * A palette for frames (RGB triples, at most 255 colors): the exact colors
11
+ * when there are few, else large flat areas kept exact and the rest by a
12
+ * weighted median cut refined by k-means.
13
+ */
14
+ export function buildGifPalette(frames, options = {}) {
15
+ const builder = new (videoModule().GifPaletteBuilder)(options.fast ?? false);
16
+ try {
17
+ for (const frame of frames)
18
+ builder.add(pixelBytes(frame));
19
+ return builder.finish();
20
+ }
21
+ finally {
22
+ builder.free();
23
+ }
24
+ }
25
+ /** A looping GIF written frame by frame. */
26
+ export function createGifEncoder(options) {
27
+ let encoder = new (videoModule().GifEncoder)(options.width, options.height, options.palette, toUint16(options.repeat ?? 0));
28
+ const open = () => {
29
+ if (encoder === null)
30
+ throw new Error('The GIF is finished.');
31
+ return encoder;
32
+ };
33
+ return {
34
+ add: (pixels, delayCs) => open().add(pixelBytes(pixels), toUint16(delayCs)),
35
+ get byteLength() {
36
+ return open().byteLength;
37
+ },
38
+ takeReady: () => open().takeReady(),
39
+ finish: () => {
40
+ const finishing = open();
41
+ encoder = null;
42
+ try {
43
+ return finishing.finish();
44
+ }
45
+ finally {
46
+ finishing.free();
47
+ }
48
+ },
49
+ dispose: () => {
50
+ encoder?.free();
51
+ encoder = null;
52
+ },
53
+ };
54
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The Motion type's pixel work, done by `crates/open-artifact-motion` compiled
3
+ * to WebAssembly: GIF palettes and encoding (in-thread, or in a Worker
4
+ * session for a page), MOV writing (QuickTime Animation with alpha, PCM
5
+ * sound) and the flash analysis of scenes.
6
+ */
7
+ export type { RgbaPixels } from './module.ts';
8
+ export { buildGifPalette, createGifEncoder } from './gif.ts';
9
+ export type { GifEncoderOptions, GifFrameEncoder, GifPaletteOptions } from './gif.ts';
10
+ export { createMovWriter } from './mov.ts';
11
+ export type { MovRepeats, MovSound, MovWriter, MovWriterOptions } from './mov.ts';
12
+ export { gifBackend, openGifSession } from './gif-session.ts';
13
+ export type { GifSession, GifSessionOptions } from './gif-session.ts';
14
+ export { FLASH_MAX_SCENE_SECONDS, FLASH_RASTER_SCALE, FLASH_SAMPLE_FPS, FLASH_SAMPLE_PADDING_SECONDS, analyzeFlashes, createFlashAnalyzer, flashSafeScale, planFlashSampling, } from './flash.ts';
15
+ export type { FlashFrameAnalyzer, FlashReport, FlashSampling } from './flash.ts';