@open-artifact/motion-export 0.0.0-stage → 0.12.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.
Files changed (81) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +5 -2
  4. package/package.json +54 -4
  5. package/src/build.d.ts +13 -0
  6. package/src/build.js +47 -0
  7. package/src/engine.d.ts +46 -0
  8. package/src/engine.js +225 -0
  9. package/src/errors.d.ts +79 -0
  10. package/src/errors.js +104 -0
  11. package/src/estimate.d.ts +27 -0
  12. package/src/estimate.js +103 -0
  13. package/src/filename.d.ts +14 -0
  14. package/src/filename.js +44 -0
  15. package/src/frame-source.d.ts +54 -0
  16. package/src/frame-source.js +1 -0
  17. package/src/frames.d.ts +36 -0
  18. package/src/frames.js +112 -0
  19. package/src/gif/encode.d.ts +23 -0
  20. package/src/gif/encode.js +60 -0
  21. package/src/gif/estimator.d.ts +50 -0
  22. package/src/gif/estimator.js +82 -0
  23. package/src/gif/surface.d.ts +8 -0
  24. package/src/gif/surface.js +20 -0
  25. package/src/index.d.ts +28 -0
  26. package/src/index.js +15 -0
  27. package/src/mov/encode.d.ts +25 -0
  28. package/src/mov/encode.js +48 -0
  29. package/src/mov/estimate.d.ts +22 -0
  30. package/src/mov/estimate.js +34 -0
  31. package/src/mov/plan.d.ts +32 -0
  32. package/src/mov/plan.js +21 -0
  33. package/src/mov/surface.d.ts +4 -0
  34. package/src/mov/surface.js +20 -0
  35. package/src/plan.d.ts +54 -0
  36. package/src/plan.js +76 -0
  37. package/src/problems.d.ts +10 -0
  38. package/src/problems.js +32 -0
  39. package/src/raster/document.d.ts +7 -0
  40. package/src/raster/document.js +15 -0
  41. package/src/raster/frame-entry.d.ts +1 -0
  42. package/src/raster/frame-entry.js +36 -0
  43. package/src/raster/host.d.ts +28 -0
  44. package/src/raster/host.js +191 -0
  45. package/src/raster/messages.d.ts +34 -0
  46. package/src/raster/messages.js +25 -0
  47. package/src/source/layout.d.ts +49 -0
  48. package/src/source/layout.js +83 -0
  49. package/src/source/names.d.ts +14 -0
  50. package/src/source/names.js +65 -0
  51. package/src/source/readme.d.ts +17 -0
  52. package/src/source/readme.js +43 -0
  53. package/src/source/zip.d.ts +27 -0
  54. package/src/source/zip.js +61 -0
  55. package/src/stage-frame.d.ts +8 -0
  56. package/src/stage-frame.js +39 -0
  57. package/src/standalone/audio-entry.d.ts +1 -0
  58. package/src/standalone/audio-entry.js +51 -0
  59. package/src/standalone/html.d.ts +35 -0
  60. package/src/standalone/html.js +60 -0
  61. package/src/types.d.ts +65 -0
  62. package/src/types.js +1 -0
  63. package/src/video/attempts.d.ts +34 -0
  64. package/src/video/attempts.js +49 -0
  65. package/src/video/avc.d.ts +15 -0
  66. package/src/video/avc.js +158 -0
  67. package/src/video/encode-attempt.d.ts +39 -0
  68. package/src/video/encode-attempt.js +154 -0
  69. package/src/video/encode.d.ts +6 -0
  70. package/src/video/encode.js +66 -0
  71. package/src/video/format.d.ts +20 -0
  72. package/src/video/format.js +34 -0
  73. package/src/video/output.d.ts +12 -0
  74. package/src/video/output.js +38 -0
  75. package/src/virtual.d.ts +11 -0
  76. package/src/visibility.d.ts +45 -0
  77. package/src/visibility.js +131 -0
  78. package/src/vite.d.ts +8 -0
  79. package/src/vite.js +43 -0
  80. package/src/words.d.ts +37 -0
  81. package/src/words.js +37 -0
@@ -0,0 +1,79 @@
1
+ import type { PlaySeconds } from '@open-artifact/motion-core';
2
+ /** A frame the film could not draw. `hold`: the frame before stands in for it and the export goes on. */
3
+ export declare class FrameRenderError extends Error {
4
+ name: string;
5
+ readonly t: PlaySeconds;
6
+ readonly hold: boolean;
7
+ constructor(message: string, t: PlaySeconds, hold?: boolean);
8
+ }
9
+ /** A frame that did not come: the browser's doing (a tab in the background), not the film's. */
10
+ export declare class FrameStallError extends Error {
11
+ name: string;
12
+ }
13
+ /** The raster frame gave no answer in time. */
14
+ export declare class RasterStallError extends FrameStallError {
15
+ name: string;
16
+ }
17
+ /** The raster frame could not decode or draw a snapshot. */
18
+ export declare class RasterDecodeError extends Error {
19
+ name: string;
20
+ }
21
+ /** The raster host was disposed while frames were still asked for. */
22
+ export declare class RasterGoneError extends Error {
23
+ name: string;
24
+ }
25
+ export declare class SnapshotLimitError extends Error {
26
+ name: string;
27
+ }
28
+ export type ExportCheckCode = 'no_canvas' | 'no_output' | 'skipped_frames' | 'no_film' | 'torn_frame';
29
+ /** An export that cannot finish, with a code an editor can act on. */
30
+ export declare class ExportCheckError extends Error {
31
+ name: string;
32
+ readonly code: ExportCheckCode;
33
+ constructor(message: string, code: ExportCheckCode);
34
+ }
35
+ export declare class SkippedVideoFramesError extends ExportCheckError {
36
+ name: string;
37
+ readonly skipped: number;
38
+ readonly frames: number;
39
+ constructor(skipped: number, frames: number);
40
+ }
41
+ export declare class VideoUnsupportedError extends Error {
42
+ name: string;
43
+ constructor();
44
+ }
45
+ /** The encoder put nothing out in time. */
46
+ export declare class EncoderSilentError extends Error {
47
+ name: string;
48
+ constructor(cause?: unknown);
49
+ }
50
+ /** The encoder broke while the page stayed in view: worth a try with the next set-up. */
51
+ export declare class EncoderFailure extends Error {
52
+ name: string;
53
+ readonly failure: Error;
54
+ constructor(failure: Error);
55
+ }
56
+ export declare class GifTooLargeError extends Error {
57
+ name: string;
58
+ readonly maxBytes: number;
59
+ constructor(maxBytes: number);
60
+ }
61
+ /** The MOV passed its limit; `maxBytes` is that limit. */
62
+ export declare class MovTooLargeError extends Error {
63
+ name: string;
64
+ readonly maxBytes: number;
65
+ constructor(maxBytes: number);
66
+ }
67
+ export type SourceRefusalCode = 'too_large' | 'unreadable';
68
+ /** The source ZIP or the standalone page could not be made. */
69
+ export declare class SourceExportError extends Error {
70
+ name: string;
71
+ readonly code: SourceRefusalCode;
72
+ constructor(message: string, code: SourceRefusalCode);
73
+ }
74
+ export declare const BYTES_PER_MEBIBYTE = 1048576;
75
+ export declare const wholeMegabytes: (bytes: number) => number;
76
+ export declare const exportAbortError: () => DOMException;
77
+ export declare const isAbortError: (error: unknown) => boolean;
78
+ export declare const isAborted: (signal: AbortSignal | undefined) => boolean;
79
+ export declare const asError: (error: unknown) => Error;
package/src/errors.js ADDED
@@ -0,0 +1,104 @@
1
+ import { words } from "./words.js";
2
+ /** A frame the film could not draw. `hold`: the frame before stands in for it and the export goes on. */
3
+ export class FrameRenderError extends Error {
4
+ name = 'FrameRenderError';
5
+ t;
6
+ hold;
7
+ constructor(message, t, hold = true) {
8
+ super(message);
9
+ this.t = t;
10
+ this.hold = hold;
11
+ }
12
+ }
13
+ /** A frame that did not come: the browser's doing (a tab in the background), not the film's. */
14
+ export class FrameStallError extends Error {
15
+ name = 'FrameStallError';
16
+ }
17
+ /** The raster frame gave no answer in time. */
18
+ export class RasterStallError extends FrameStallError {
19
+ name = 'RasterStallError';
20
+ }
21
+ /** The raster frame could not decode or draw a snapshot. */
22
+ export class RasterDecodeError extends Error {
23
+ name = 'RasterDecodeError';
24
+ }
25
+ /** The raster host was disposed while frames were still asked for. */
26
+ export class RasterGoneError extends Error {
27
+ name = 'RasterGoneError';
28
+ }
29
+ export class SnapshotLimitError extends Error {
30
+ name = 'SnapshotLimitError';
31
+ }
32
+ /** An export that cannot finish, with a code an editor can act on. */
33
+ export class ExportCheckError extends Error {
34
+ name = 'ExportCheckError';
35
+ code;
36
+ constructor(message, code) {
37
+ super(message);
38
+ this.code = code;
39
+ }
40
+ }
41
+ export class SkippedVideoFramesError extends ExportCheckError {
42
+ name = 'SkippedVideoFramesError';
43
+ skipped;
44
+ frames;
45
+ constructor(skipped, frames) {
46
+ super(words.skippedFrames(skipped, frames), 'skipped_frames');
47
+ this.skipped = skipped;
48
+ this.frames = frames;
49
+ }
50
+ }
51
+ export class VideoUnsupportedError extends Error {
52
+ name = 'VideoUnsupportedError';
53
+ constructor() {
54
+ super(words.videoUnsupported);
55
+ }
56
+ }
57
+ /** The encoder put nothing out in time. */
58
+ export class EncoderSilentError extends Error {
59
+ name = 'EncoderSilentError';
60
+ constructor(cause) {
61
+ super(words.encoderSilent, cause === undefined ? undefined : { cause });
62
+ }
63
+ }
64
+ /** The encoder broke while the page stayed in view: worth a try with the next set-up. */
65
+ export class EncoderFailure extends Error {
66
+ name = 'EncoderFailure';
67
+ failure;
68
+ constructor(failure) {
69
+ super(failure.message);
70
+ this.failure = failure;
71
+ }
72
+ }
73
+ export class GifTooLargeError extends Error {
74
+ name = 'GifTooLargeError';
75
+ maxBytes;
76
+ constructor(maxBytes) {
77
+ super(words.gifTooLarge(wholeMegabytes(maxBytes)));
78
+ this.maxBytes = maxBytes;
79
+ }
80
+ }
81
+ /** The MOV passed its limit; `maxBytes` is that limit. */
82
+ export class MovTooLargeError extends Error {
83
+ name = 'MovTooLargeError';
84
+ maxBytes;
85
+ constructor(maxBytes) {
86
+ super(words.movTooLarge(Math.max(1, Math.round(maxBytes / BYTES_PER_MEBIBYTE))));
87
+ this.maxBytes = maxBytes;
88
+ }
89
+ }
90
+ /** The source ZIP or the standalone page could not be made. */
91
+ export class SourceExportError extends Error {
92
+ name = 'SourceExportError';
93
+ code;
94
+ constructor(message, code) {
95
+ super(message);
96
+ this.code = code;
97
+ }
98
+ }
99
+ export const BYTES_PER_MEBIBYTE = 1_048_576;
100
+ export const wholeMegabytes = (bytes) => Math.floor(bytes / BYTES_PER_MEBIBYTE);
101
+ export const exportAbortError = () => new DOMException(words.exportCancelled, 'AbortError');
102
+ export const isAbortError = (error) => error instanceof DOMException && error.name === 'AbortError';
103
+ export const isAborted = (signal) => signal !== undefined && signal.aborted;
104
+ export const asError = (error) => (error instanceof Error ? error : new Error(String(error)));
@@ -0,0 +1,27 @@
1
+ import type { PlaySeconds } from '@open-artifact/motion-core';
2
+ import type { GifEstimator, GifMeasure } from './gif/estimator.ts';
3
+ import type { GifPlan, GifPreset } from './plan.ts';
4
+ import type { ExportDimensions, ExportFrame } from './types.ts';
5
+ /** Where in the film a video estimate times its frames. */
6
+ export declare const VIDEO_PROBE_FRACTIONS: readonly number[];
7
+ /** Milliseconds of rendering the sound takes per second of film. */
8
+ export declare const AUDIO_RENDER_MS_PER_SECOND = 250;
9
+ /**
10
+ * Draws a frame at each moment and hands it to `use`; the average milliseconds a good frame took. Held frames are
11
+ * skipped, unless every frame was held: then the first one's error is thrown.
12
+ */
13
+ export declare function probeFrames(frame: ExportFrame, times: readonly PlaySeconds[], size: ExportDimensions, signal: AbortSignal | undefined, use?: (bitmap: ImageBitmap, index: number) => void): Promise<number>;
14
+ /** Seconds a video takes to make: its frames, the sound, and a second to finish. */
15
+ export declare function videoSeconds(frames: number, msPerFrame: number, duration: number, withAudio: boolean): number;
16
+ /** Seconds a GIF takes to make: drawing and encoding each frame, and a second to finish. */
17
+ export declare function gifSeconds(frames: number, frameMs: number, encodeMs: number): number;
18
+ /** Pairs of moments one GIF frame apart, at each fraction of the film. */
19
+ export declare function gifProbeTimes(fractions: readonly number[], duration: number, fps: number): PlaySeconds[];
20
+ /**
21
+ * Probes the GIF's frames in pairs, and more of them while the film rests and the preset's extra time lasts; the
22
+ * estimator's measure and the milliseconds a frame took to draw.
23
+ */
24
+ export declare function probeGif(frame: ExportFrame, plan: GifPlan, preset: Pick<GifPreset, 'estimateExtraMs'>, duration: number, estimator: GifEstimator, signal: AbortSignal | undefined): Promise<{
25
+ measure: GifMeasure;
26
+ frameMs: number;
27
+ } | null>;
@@ -0,0 +1,103 @@
1
+ import { playSeconds } from '@open-artifact/motion-core';
2
+ import { FrameRenderError, FrameStallError, isAborted } from "./errors.js";
3
+ import { GIF_EXTRA_PROBE_FRACTIONS, GIF_PROBE_FRACTIONS } from "./gif/estimator.js";
4
+ /** Where in the film a video estimate times its frames. */
5
+ export const VIDEO_PROBE_FRACTIONS = [0.1, 0.5, 0.85];
6
+ /** Milliseconds of rendering the sound takes per second of film. */
7
+ export const AUDIO_RENDER_MS_PER_SECOND = 250;
8
+ /** Resolves with the promise's value, or null once the signal aborts. */
9
+ async function unlessAborted(signal, promise) {
10
+ if (signal === undefined)
11
+ return promise;
12
+ let stop = () => undefined;
13
+ const aborted = new Promise((resolve) => {
14
+ stop = () => resolve(null);
15
+ });
16
+ signal.addEventListener('abort', stop, { once: true });
17
+ if (signal.aborted)
18
+ stop();
19
+ try {
20
+ return await Promise.race([promise, aborted]);
21
+ }
22
+ finally {
23
+ signal.removeEventListener('abort', stop);
24
+ }
25
+ }
26
+ /**
27
+ * Draws a frame at each moment and hands it to `use`; the average milliseconds a good frame took. Held frames are
28
+ * skipped, unless every frame was held: then the first one's error is thrown.
29
+ */
30
+ export async function probeFrames(frame, times, size, signal, use) {
31
+ let good = 0;
32
+ let totalMs = 0;
33
+ let firstHeld = null;
34
+ for (const [index, t] of times.entries()) {
35
+ if (isAborted(signal))
36
+ break;
37
+ const startedAt = performance.now();
38
+ const pending = frame(t, size.width, size.height);
39
+ const bitmap = await unlessAborted(signal, pending.catch((error) => {
40
+ if (!(error instanceof FrameRenderError) || !error.hold)
41
+ throw error;
42
+ firstHeld ??= error;
43
+ return null;
44
+ }));
45
+ if (isAborted(signal)) {
46
+ pending.then((late) => late.close(), () => undefined);
47
+ break;
48
+ }
49
+ if (bitmap === null)
50
+ continue;
51
+ good++;
52
+ totalMs += performance.now() - startedAt;
53
+ try {
54
+ use?.(bitmap, index);
55
+ }
56
+ finally {
57
+ bitmap.close();
58
+ }
59
+ }
60
+ if (good === 0 && firstHeld !== null)
61
+ throw firstHeld;
62
+ return totalMs / Math.max(1, good);
63
+ }
64
+ /** Seconds a video takes to make: its frames, the sound, and a second to finish. */
65
+ export function videoSeconds(frames, msPerFrame, duration, withAudio) {
66
+ return Math.round((frames * msPerFrame + (withAudio ? duration * AUDIO_RENDER_MS_PER_SECOND : 0) + 1000) / 1000);
67
+ }
68
+ /** Seconds a GIF takes to make: drawing and encoding each frame, and a second to finish. */
69
+ export function gifSeconds(frames, frameMs, encodeMs) {
70
+ return Math.round((frames * (frameMs + encodeMs)) / 1000 + 1);
71
+ }
72
+ /** Pairs of moments one GIF frame apart, at each fraction of the film. */
73
+ export function gifProbeTimes(fractions, duration, fps) {
74
+ return fractions.flatMap((fraction) => [playSeconds(duration * fraction), playSeconds(Math.min(duration, duration * fraction + 1 / fps))]);
75
+ }
76
+ /**
77
+ * Probes the GIF's frames in pairs, and more of them while the film rests and the preset's extra time lasts; the
78
+ * estimator's measure and the milliseconds a frame took to draw.
79
+ */
80
+ export async function probeGif(frame, plan, preset, duration, estimator, signal) {
81
+ const probe = (fractions) => probeFrames(frame, gifProbeTimes(fractions, duration, plan.fps), plan, signal, (bitmap, index) => estimator.add(bitmap, fractions[index >> 1] ?? 0, index % 2 === 0 ? 0 : 1));
82
+ const frameMs = await probe(GIF_PROBE_FRACTIONS);
83
+ if (estimator.rests()) {
84
+ const startedAt = performance.now();
85
+ for (const fraction of GIF_EXTRA_PROBE_FRACTIONS) {
86
+ if (isAborted(signal) || performance.now() - startedAt >= preset.estimateExtraMs)
87
+ break;
88
+ try {
89
+ await probe([fraction]);
90
+ }
91
+ catch (error) {
92
+ if (error instanceof FrameStallError)
93
+ break;
94
+ if (!(error instanceof FrameRenderError && error.hold))
95
+ throw error;
96
+ }
97
+ }
98
+ }
99
+ if (isAborted(signal))
100
+ return null;
101
+ const measure = await estimator.measure(signal);
102
+ return measure === null ? null : { measure, frameMs };
103
+ }
@@ -0,0 +1,14 @@
1
+ export declare const FALLBACK_FILE_STEM = "video";
2
+ /**
3
+ * The title as an ASCII stem: lower case, plain letters and digits joined by dashes. For names that must stay plain,
4
+ * as the source folder's root.
5
+ */
6
+ export declare function exportFileStem(title: string): string;
7
+ /**
8
+ * The title as a downloaded file's name, then the extension. Case, letters of any script and spaces are kept; what a
9
+ * file name cannot hold or would not show goes, whitespace runs become one space, leading and trailing dots and spaces
10
+ * go, and the name is cut to 120 code points. A title with nothing left is named `video`.
11
+ */
12
+ export declare function downloadFileName(title: string, extension: string): string;
13
+ /** An exported file's name: the video, MOV, GIF, standalone page and source folder all keep the title. */
14
+ export declare const exportFilename: (title: string, extension: string) => string;
@@ -0,0 +1,44 @@
1
+ export const FALLBACK_FILE_STEM = 'video';
2
+ const MAX_STEM_CHARS = 60;
3
+ /** A downloaded file's name, less its extension, in code points. */
4
+ const MAX_NAME_CODE_POINTS = 120;
5
+ /**
6
+ * What a file name leaves out: control, format and other invisible characters, lone surrogates, line and paragraph
7
+ * separators, and a few that draw blank or not at all (the blank Braille pattern, the object replacement character,
8
+ * the Egyptian hieroglyph format controls and the musical null notehead).
9
+ */
10
+ const UNSEEN = /[\p{Cf}\p{Cs}\p{Zl}\p{Zp}\p{Default_Ignorable_Code_Point}\u0000-\u001f\u007f-\u009f⠀\u{13441}\u{13442}\u{1d159}]/gu;
11
+ /** Characters a file system or a download refuses, each run of them taken as a space. */
12
+ const RESERVED = /[/\\:*?"<>|%]+/g;
13
+ /**
14
+ * The title as an ASCII stem: lower case, plain letters and digits joined by dashes. For names that must stay plain,
15
+ * as the source folder's root.
16
+ */
17
+ export function exportFileStem(title) {
18
+ const stem = title
19
+ .toLowerCase()
20
+ .normalize('NFKD')
21
+ .replace(/\p{M}+/gu, '')
22
+ .replace(/[^a-z0-9]+/g, '-')
23
+ .replace(/^-+|-+$/g, '')
24
+ .slice(0, MAX_STEM_CHARS)
25
+ .replace(/-+$/, '');
26
+ return stem === '' ? FALLBACK_FILE_STEM : stem;
27
+ }
28
+ /**
29
+ * The title as a downloaded file's name, then the extension. Case, letters of any script and spaces are kept; what a
30
+ * file name cannot hold or would not show goes, whitespace runs become one space, leading and trailing dots and spaces
31
+ * go, and the name is cut to 120 code points. A title with nothing left is named `video`.
32
+ */
33
+ export function downloadFileName(title, extension) {
34
+ const kept = title
35
+ .replace(/[\t\n\r]/g, ' ')
36
+ .replace(UNSEEN, '')
37
+ .replace(RESERVED, ' ')
38
+ .replace(/\s+/g, ' ')
39
+ .replace(/^[\s.]+|[\s.]+$/g, '');
40
+ const name = Array.from(kept).slice(0, MAX_NAME_CODE_POINTS).join('').replace(/[\s.]+$/, '');
41
+ return (name === '' ? FALLBACK_FILE_STEM : name) + '.' + extension;
42
+ }
43
+ /** An exported file's name: the video, MOV, GIF, standalone page and source folder all keep the title. */
44
+ export const exportFilename = (title, extension) => downloadFileName(title, extension);
@@ -0,0 +1,54 @@
1
+ import type { PlaySeconds } from '@open-artifact/motion-core';
2
+ import type { FilmSound } from '@open-artifact/motion-audio';
3
+ /** What a frame request asks the stage for: a snapshot `scale` times the film's size. */
4
+ export interface FrameRequest {
5
+ scale: number;
6
+ smallMedia: boolean;
7
+ readFx: boolean;
8
+ smooth: boolean;
9
+ }
10
+ /**
11
+ * The stage's answer to a frame request.
12
+ * - `picture`: the snapshot as SVG, `pw` × `ph` pixels.
13
+ * - `failed`: the stage's `frame-error`. `hold`: the frame before may stand in. `env`: the browser's doing (a tab in
14
+ * the background, or no answer in time), not the film's.
15
+ * - `unloaded`: there is no film on the stage.
16
+ */
17
+ export type StageFrame = {
18
+ kind: 'picture';
19
+ svg: string;
20
+ pw: number;
21
+ ph: number;
22
+ } | {
23
+ kind: 'failed';
24
+ message: string;
25
+ hold: boolean;
26
+ env: boolean;
27
+ } | {
28
+ kind: 'unloaded';
29
+ };
30
+ /** The film as an export plans it. */
31
+ export interface FilmFacts {
32
+ title: string;
33
+ width: number;
34
+ height: number;
35
+ fps: number;
36
+ /** How long the film plays, after the scenes retimed by hand. */
37
+ duration: PlaySeconds;
38
+ }
39
+ /**
40
+ * What the editor gives the export engine, over its stage controller. `frame` resolves with the stage's answer and
41
+ * rejects only when no frame can come any more (the stage is gone); a stage that does not answer in time resolves
42
+ * `{kind: 'failed', env: true, hold: true}`.
43
+ */
44
+ export interface FrameSource {
45
+ /** Null while no film is loaded. */
46
+ facts(): FilmFacts | null;
47
+ frame(t: PlaySeconds, request: FrameRequest): Promise<StageFrame>;
48
+ /** The film's sound as played (the sound player's `sound`); null when it has none. */
49
+ sound(): FilmSound | null;
50
+ /** Stops playback before frames are asked for; the function returned puts the stage back as it was. */
51
+ borrow(): () => Promise<void>;
52
+ /** How long a snapshot waits for words clipped at its first draw (Firefox). */
53
+ clippedTextWaitMs(): number;
54
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,36 @@
1
+ import type { ExportFrame, ExportProgress, FramePlan, HeldFrames } from './types.ts';
2
+ /** A held frame that took longer than this, and much longer than good ones, counts toward giving up. */
3
+ export declare const HELD_FRAME_SLOW_MS = 250;
4
+ export declare const MAX_COUNTED_FRAME_WAIT_MS = 15000;
5
+ /** Slow failures add up to this much waiting at most before the export stops. */
6
+ export declare const MAX_HELD_FRAME_WAIT_MS = 20000;
7
+ /** How long good frames took and how long slow failures kept the export waiting. */
8
+ export interface FrameTiming {
9
+ waitMs: number;
10
+ goodMs: number;
11
+ good: number;
12
+ }
13
+ export declare const newFrameTiming: () => FrameTiming;
14
+ /**
15
+ * The frame, or null for a held one (counted in `held`). Throws what cannot be held, and gives up once failing
16
+ * frames have kept the export waiting too long.
17
+ */
18
+ export declare function awaitExportFrame(frame: Promise<ImageBitmap>, held: HeldFrames, timing: FrameTiming, started: {
19
+ at: number;
20
+ }): Promise<ImageBitmap | null>;
21
+ export interface RenderFramesOptions {
22
+ plan: FramePlan;
23
+ frame: ExportFrame;
24
+ /** Frames are drawn this many times the plan's size (2 to supersample). */
25
+ scale: number;
26
+ signal?: AbortSignal;
27
+ page?: Document;
28
+ stalls?: number;
29
+ onProgress?: (progress: ExportProgress) => void;
30
+ /** Draws frame `index`; null when it was held. */
31
+ draw(bitmap: ImageBitmap | null, index: number): void;
32
+ /** Hands frame `index` on (to the encoder); the next frame is drawn meanwhile. */
33
+ commit(index: number): void | Promise<void>;
34
+ }
35
+ /** Draws every frame of the plan in order, asking for the next while the last is handed on. */
36
+ export declare function renderExportFrames(options: RenderFramesOptions): Promise<HeldFrames>;
package/src/frames.js ADDED
@@ -0,0 +1,112 @@
1
+ import { playSeconds } from '@open-artifact/motion-core';
2
+ import { FrameRenderError, exportAbortError, isAborted } from "./errors.js";
3
+ import { STALLS_IN_VIEW, retryBackgroundFrame } from "./visibility.js";
4
+ import { words } from "./words.js";
5
+ /** A held frame that took longer than this, and much longer than good ones, counts toward giving up. */
6
+ export const HELD_FRAME_SLOW_MS = 250;
7
+ export const MAX_COUNTED_FRAME_WAIT_MS = 15_000;
8
+ /** Slow failures add up to this much waiting at most before the export stops. */
9
+ export const MAX_HELD_FRAME_WAIT_MS = 20_000;
10
+ export const newFrameTiming = () => ({ waitMs: 0, goodMs: 0, good: 0 });
11
+ /**
12
+ * The frame, or null for a held one (counted in `held`). Throws what cannot be held, and gives up once failing
13
+ * frames have kept the export waiting too long.
14
+ */
15
+ export async function awaitExportFrame(frame, held, timing, started) {
16
+ try {
17
+ const bitmap = await frame;
18
+ timing.goodMs += Math.min(performance.now() - started.at, MAX_COUNTED_FRAME_WAIT_MS);
19
+ timing.good++;
20
+ return bitmap;
21
+ }
22
+ catch (error) {
23
+ if (!(error instanceof FrameRenderError) || !error.hold)
24
+ throw error;
25
+ held.count++;
26
+ const first = (held.first ??= { t: error.t, message: error.message });
27
+ held.last = error.t;
28
+ const waited = performance.now() - started.at;
29
+ if (waited > HELD_FRAME_SLOW_MS && (timing.good === 0 || waited > (3 * timing.goodMs) / timing.good))
30
+ timing.waitMs += Math.min(waited, MAX_COUNTED_FRAME_WAIT_MS);
31
+ if (timing.waitMs > MAX_HELD_FRAME_WAIT_MS)
32
+ throw new FrameRenderError(words.slowFailures(held.count, error.t, first.message), error.t, false);
33
+ return null;
34
+ }
35
+ }
36
+ const closeLater = (pending) => {
37
+ pending?.then((bitmap) => bitmap.close(), () => undefined);
38
+ };
39
+ /** Draws every frame of the plan in order, asking for the next while the last is handed on. */
40
+ export async function renderExportFrames(options) {
41
+ const { plan, signal, onProgress } = options;
42
+ const page = options.page ?? document;
43
+ const controller = new AbortController();
44
+ const held = { count: 0, total: plan.frames };
45
+ const started = { at: 0 };
46
+ const frame = retryBackgroundFrame((t, width, height) => {
47
+ started.at = performance.now();
48
+ return options.frame(playSeconds(t), width, height);
49
+ }, controller.signal, page, {
50
+ stalls: options.stalls ?? STALLS_IN_VIEW,
51
+ onAgain: (good) => {
52
+ const again = (held.again ??= { good: 0, failed: 0 });
53
+ if (good)
54
+ again.good++;
55
+ else
56
+ again.failed++;
57
+ },
58
+ });
59
+ let rejectAbort = () => undefined;
60
+ const aborted = new Promise((_resolve, reject) => {
61
+ rejectAbort = reject;
62
+ });
63
+ aborted.catch(() => undefined);
64
+ const abort = () => {
65
+ controller.abort();
66
+ rejectAbort(exportAbortError());
67
+ };
68
+ signal?.addEventListener('abort', abort, { once: true });
69
+ const timing = newFrameTiming();
70
+ const width = plan.width * options.scale;
71
+ const height = plan.height * options.scale;
72
+ let pending = null;
73
+ try {
74
+ pending = frame(0, width, height);
75
+ for (let index = 0; index < plan.frames; index++) {
76
+ if (isAborted(signal))
77
+ throw exportAbortError();
78
+ const current = pending ?? frame(index / plan.fps, width, height);
79
+ const bitmap = await Promise.race([awaitExportFrame(current, held, timing, started), aborted]);
80
+ pending = null;
81
+ if (isAborted(signal)) {
82
+ bitmap?.close();
83
+ throw exportAbortError();
84
+ }
85
+ pending = index + 1 < plan.frames ? frame((index + 1) / plan.fps, width, height) : null;
86
+ pending?.catch(() => undefined);
87
+ try {
88
+ options.draw(bitmap, index);
89
+ }
90
+ finally {
91
+ bitmap?.close();
92
+ }
93
+ await options.commit(index);
94
+ if (isAborted(signal))
95
+ throw exportAbortError();
96
+ onProgress?.({ done: index + 1, total: plan.frames, phase: 'frames' });
97
+ }
98
+ if (isAborted(signal))
99
+ throw exportAbortError();
100
+ if (held.count === plan.frames)
101
+ throw new FrameRenderError(words.noFrame(held.first?.message ?? ''), held.first?.t ?? playSeconds(0), false);
102
+ return held;
103
+ }
104
+ catch (error) {
105
+ closeLater(pending);
106
+ throw error;
107
+ }
108
+ finally {
109
+ controller.abort();
110
+ signal?.removeEventListener('abort', abort);
111
+ }
112
+ }
@@ -0,0 +1,23 @@
1
+ import type { GifPlan } from '../plan.ts';
2
+ import type { ExportFrame, ExportProgress, HeldFrames } from '../types.ts';
3
+ import type { SurfaceMaker } from './surface.ts';
4
+ /** Frames sampled, spread over the film, for the GIF's one palette. */
5
+ export declare const GIF_PALETTE_SAMPLES = 24;
6
+ export interface GifEncodeOptions {
7
+ plan: GifPlan;
8
+ /** The film's length in seconds, as played. */
9
+ duration: number;
10
+ frame: ExportFrame;
11
+ maxBytes: number;
12
+ surface?: SurfaceMaker;
13
+ page?: Document;
14
+ onProgress?: (progress: ExportProgress) => void;
15
+ signal?: AbortSignal;
16
+ }
17
+ export interface EncodedGif {
18
+ bytes: Uint8Array;
19
+ held: HeldFrames;
20
+ ms: number;
21
+ }
22
+ /** Draws sample frames for the palette, then every frame into the GIF; stops once it passes `maxBytes`. */
23
+ export declare function encodeGif(options: GifEncodeOptions): Promise<EncodedGif>;
@@ -0,0 +1,60 @@
1
+ import { openGifSession } from '@open-artifact/wasm-motion';
2
+ import { GifTooLargeError } from "../errors.js";
3
+ import { renderExportFrames } from "../frames.js";
4
+ import { createOpaqueSurface } from "./surface.js";
5
+ /** Frames sampled, spread over the film, for the GIF's one palette. */
6
+ export const GIF_PALETTE_SAMPLES = 24;
7
+ /** Draws sample frames for the palette, then every frame into the GIF; stops once it passes `maxBytes`. */
8
+ export async function encodeGif(options) {
9
+ const { plan, signal, maxBytes } = options;
10
+ const startedAt = performance.now();
11
+ const target = (options.surface ?? createOpaqueSurface)(plan);
12
+ const session = openGifSession({ width: plan.width, height: plan.height });
13
+ const shared = {
14
+ frame: options.frame,
15
+ scale: 1,
16
+ ...(signal !== undefined ? { signal } : {}),
17
+ ...(options.page !== undefined ? { page: options.page } : {}),
18
+ };
19
+ try {
20
+ const samples = Math.min(GIF_PALETTE_SAMPLES, plan.frames);
21
+ const sampled = [];
22
+ await renderExportFrames({
23
+ ...shared,
24
+ plan: { ...plan, fps: samples / Math.max(options.duration, 1e-3), frames: samples },
25
+ draw: (bitmap) => {
26
+ if (bitmap === null)
27
+ return;
28
+ target.paint(bitmap);
29
+ const sample = session.sample(target.pixels());
30
+ sample.catch(() => undefined);
31
+ sampled.push(sample);
32
+ },
33
+ commit: () => undefined,
34
+ });
35
+ await Promise.all(sampled);
36
+ let size = 0;
37
+ const held = await renderExportFrames({
38
+ ...shared,
39
+ plan,
40
+ ...(options.onProgress !== undefined ? { onProgress: options.onProgress } : {}),
41
+ draw: (bitmap, index) => {
42
+ if (bitmap !== null || index === 0)
43
+ target.paint(bitmap);
44
+ },
45
+ commit: async () => {
46
+ size = await session.add(target.pixels(), plan.delayCs);
47
+ if (size > maxBytes)
48
+ throw new GifTooLargeError(maxBytes);
49
+ },
50
+ });
51
+ options.onProgress?.({ done: plan.frames, total: plan.frames, phase: 'mux' });
52
+ const bytes = await session.finish();
53
+ if (bytes.length > maxBytes)
54
+ throw new GifTooLargeError(maxBytes);
55
+ return { bytes, held, ms: performance.now() - startedAt };
56
+ }
57
+ finally {
58
+ session.close();
59
+ }
60
+ }