@openartifactsai/motion-export 0.0.0-stage → 0.23.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/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +5 -2
- package/package.json +58 -4
- package/src/build.d.ts +17 -0
- package/src/build.js +52 -0
- package/src/captions-file.d.ts +13 -0
- package/src/captions-file.js +15 -0
- package/src/clip/in-worker.d.ts +49 -0
- package/src/clip/in-worker.js +96 -0
- package/src/clip/jobs.d.ts +28 -0
- package/src/clip/jobs.js +2 -0
- package/src/clip/part.d.ts +25 -0
- package/src/clip/part.js +112 -0
- package/src/clip/problem.d.ts +25 -0
- package/src/clip/problem.js +10 -0
- package/src/clip/worker.d.ts +2 -0
- package/src/clip/worker.js +24 -0
- package/src/engine.d.ts +46 -0
- package/src/engine.js +225 -0
- package/src/errors.d.ts +78 -0
- package/src/errors.js +102 -0
- package/src/estimate.d.ts +27 -0
- package/src/estimate.js +103 -0
- package/src/filename.d.ts +14 -0
- package/src/filename.js +44 -0
- package/src/frame-source.d.ts +57 -0
- package/src/frame-source.js +1 -0
- package/src/frames-video.d.ts +45 -0
- package/src/frames-video.js +52 -0
- package/src/frames.d.ts +36 -0
- package/src/frames.js +112 -0
- package/src/gif/encode.d.ts +23 -0
- package/src/gif/encode.js +60 -0
- package/src/gif/estimator.d.ts +50 -0
- package/src/gif/estimator.js +82 -0
- package/src/gif/surface.d.ts +8 -0
- package/src/gif/surface.js +20 -0
- package/src/index.d.ts +34 -0
- package/src/index.js +18 -0
- package/src/mov/encode.d.ts +32 -0
- package/src/mov/encode.js +69 -0
- package/src/mov/estimate.d.ts +20 -0
- package/src/mov/estimate.js +33 -0
- package/src/mov/plan.d.ts +25 -0
- package/src/mov/plan.js +14 -0
- package/src/mov/surface.d.ts +4 -0
- package/src/mov/surface.js +20 -0
- package/src/plan.d.ts +54 -0
- package/src/plan.js +76 -0
- package/src/problems.d.ts +10 -0
- package/src/problems.js +32 -0
- package/src/raster/document.d.ts +7 -0
- package/src/raster/document.js +15 -0
- package/src/raster/frame-entry.d.ts +1 -0
- package/src/raster/frame-entry.js +36 -0
- package/src/raster/host.d.ts +28 -0
- package/src/raster/host.js +191 -0
- package/src/raster/messages.d.ts +34 -0
- package/src/raster/messages.js +25 -0
- package/src/source/layout.d.ts +49 -0
- package/src/source/layout.js +83 -0
- package/src/source/names.d.ts +14 -0
- package/src/source/names.js +65 -0
- package/src/source/readme.d.ts +17 -0
- package/src/source/readme.js +43 -0
- package/src/source/zip.d.ts +27 -0
- package/src/source/zip.js +61 -0
- package/src/stage-frame.d.ts +12 -0
- package/src/stage-frame.js +61 -0
- package/src/standalone/audio-entry.d.ts +1 -0
- package/src/standalone/audio-entry.js +80 -0
- package/src/standalone/clip-footage.d.ts +4 -0
- package/src/standalone/clip-footage.js +38 -0
- package/src/standalone/html.d.ts +35 -0
- package/src/standalone/html.js +60 -0
- package/src/types.d.ts +63 -0
- package/src/types.js +1 -0
- package/src/video/attempts.d.ts +55 -0
- package/src/video/attempts.js +73 -0
- package/src/video/avc.d.ts +15 -0
- package/src/video/avc.js +158 -0
- package/src/video/encode-attempt.d.ts +39 -0
- package/src/video/encode-attempt.js +157 -0
- package/src/video/encode.d.ts +6 -0
- package/src/video/encode.js +66 -0
- package/src/video/format.d.ts +22 -0
- package/src/video/format.js +41 -0
- package/src/video/output.d.ts +12 -0
- package/src/video/output.js +38 -0
- package/src/virtual.d.ts +11 -0
- package/src/visibility.d.ts +45 -0
- package/src/visibility.js +131 -0
- package/src/vite.d.ts +8 -0
- package/src/vite.js +43 -0
- package/src/words.d.ts +37 -0
- package/src/words.js +37 -0
package/src/estimate.js
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { playSeconds } from '@openartifactsai/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;
|
package/src/filename.js
ADDED
|
@@ -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,57 @@
|
|
|
1
|
+
import type { PlaySeconds } from '@openartifactsai/motion-core';
|
|
2
|
+
import type { FilmSound } from '@openartifactsai/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
|
+
/** An export's frame: the stage may take a painted backdrop out of the snapshot and give it as `under`. */
|
|
10
|
+
lift?: boolean;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* The stage's answer to a frame request.
|
|
14
|
+
* - `picture`: the snapshot as SVG, `pw` × `ph` pixels; `under`, when there is one, is drawn under it.
|
|
15
|
+
* - `failed`: the stage's `frame-error`. `hold`: the frame before may stand in. `env`: the browser's doing (a tab in
|
|
16
|
+
* the background, or no answer in time), not the film's.
|
|
17
|
+
* - `unloaded`: there is no film on the stage.
|
|
18
|
+
*/
|
|
19
|
+
export type StageFrame = {
|
|
20
|
+
kind: 'picture';
|
|
21
|
+
svg: string;
|
|
22
|
+
pw: number;
|
|
23
|
+
ph: number;
|
|
24
|
+
under?: ImageBitmap;
|
|
25
|
+
} | {
|
|
26
|
+
kind: 'failed';
|
|
27
|
+
message: string;
|
|
28
|
+
hold: boolean;
|
|
29
|
+
env: boolean;
|
|
30
|
+
} | {
|
|
31
|
+
kind: 'unloaded';
|
|
32
|
+
};
|
|
33
|
+
/** The film as an export plans it. */
|
|
34
|
+
export interface FilmFacts {
|
|
35
|
+
title: string;
|
|
36
|
+
width: number;
|
|
37
|
+
height: number;
|
|
38
|
+
fps: number;
|
|
39
|
+
/** How long the film plays, after the scenes retimed by hand. */
|
|
40
|
+
duration: PlaySeconds;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* What the editor gives the export engine, over its stage controller. `frame` resolves with the stage's answer and
|
|
44
|
+
* rejects only when no frame can come any more (the stage is gone); a stage that does not answer in time resolves
|
|
45
|
+
* `{kind: 'failed', env: true, hold: true}`.
|
|
46
|
+
*/
|
|
47
|
+
export interface FrameSource {
|
|
48
|
+
/** Null while no film is loaded. */
|
|
49
|
+
facts(): FilmFacts | null;
|
|
50
|
+
frame(t: PlaySeconds, request: FrameRequest): Promise<StageFrame>;
|
|
51
|
+
/** The film's sound as played (the sound player's `sound`); null when it has none. */
|
|
52
|
+
sound(): FilmSound | null;
|
|
53
|
+
/** Stops playback before frames are asked for; the function returned puts the stage back as it was. */
|
|
54
|
+
borrow(): () => Promise<void>;
|
|
55
|
+
/** How long a snapshot waits for words clipped at its first draw (Firefox). */
|
|
56
|
+
clippedTextWaitMs(): number;
|
|
57
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A silent MP4 from frames the caller draws: the video encoder of the
|
|
3
|
+
* Motion exports (codec choice, bitrate, the set-ups tried in turn), with
|
|
4
|
+
* no film and no sound. Other editors load it on its own
|
|
5
|
+
* (`@openartifactsai/motion-export/frames`) to turn something they paint
|
|
6
|
+
* into a short video.
|
|
7
|
+
*/
|
|
8
|
+
import type { ExportDimensions, ExportFrame, ExportProgress, HeldFrames } from './types.js';
|
|
9
|
+
import { newEncoderMemory } from './video/attempts.js';
|
|
10
|
+
import type { EncoderMemory } from './video/attempts.js';
|
|
11
|
+
import type { VideoFormat, VideoPlan } from './video/format.js';
|
|
12
|
+
export type { ExportFrame, HeldFrames } from './types.js';
|
|
13
|
+
export type { VideoFormat } from './video/format.js';
|
|
14
|
+
export type { EncoderMemory } from './video/attempts.js';
|
|
15
|
+
export { newEncoderMemory };
|
|
16
|
+
/** The video's size (even pixels), frame rate and number of frames. */
|
|
17
|
+
export interface FramesVideoSize extends ExportDimensions {
|
|
18
|
+
fps: number;
|
|
19
|
+
frames: number;
|
|
20
|
+
}
|
|
21
|
+
/** The plan for a video of that size; null when this browser encodes no video at that size. */
|
|
22
|
+
export declare function planFramesVideo(size: FramesVideoSize): Promise<VideoPlan | null>;
|
|
23
|
+
/**
|
|
24
|
+
* Whether this browser can encode a video of that size: the codecs it would
|
|
25
|
+
* use, or null when it has no video encoder or encodes none of them (also
|
|
26
|
+
* when asking fails).
|
|
27
|
+
*/
|
|
28
|
+
export declare function canEncodeFramesVideo(size: FramesVideoSize): Promise<VideoFormat | null>;
|
|
29
|
+
export interface FramesVideoOptions extends FramesVideoSize {
|
|
30
|
+
/** Frame at `t` seconds as a picture `width` × `height`; the encoder closes each picture it is given. */
|
|
31
|
+
frame: ExportFrame;
|
|
32
|
+
/** What the encoder learned in earlier videos of this page (default: nothing). */
|
|
33
|
+
memory?: EncoderMemory;
|
|
34
|
+
onProgress?: (progress: ExportProgress) => void;
|
|
35
|
+
signal?: AbortSignal;
|
|
36
|
+
}
|
|
37
|
+
export interface FramesVideo {
|
|
38
|
+
bytes: Uint8Array<ArrayBuffer>;
|
|
39
|
+
format: VideoFormat;
|
|
40
|
+
/** Frames that could not be drawn, each replaced by the one before. */
|
|
41
|
+
held: HeldFrames;
|
|
42
|
+
ms: number;
|
|
43
|
+
}
|
|
44
|
+
/** Encodes the frames as a silent MP4. Rejects when the browser encodes no video at that size, or the encoder fails. */
|
|
45
|
+
export declare function encodeFramesVideo(options: FramesVideoOptions): Promise<FramesVideo>;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A silent MP4 from frames the caller draws: the video encoder of the
|
|
3
|
+
* Motion exports (codec choice, bitrate, the set-ups tried in turn), with
|
|
4
|
+
* no film and no sound. Other editors load it on its own
|
|
5
|
+
* (`@openartifactsai/motion-export/frames`) to turn something they paint
|
|
6
|
+
* into a short video.
|
|
7
|
+
*/
|
|
8
|
+
import { EXPORT_SETTINGS } from '@openartifactsai/motion-core';
|
|
9
|
+
import { chooseVideoBitrate } from "./plan.js";
|
|
10
|
+
import { newEncoderMemory } from "./video/attempts.js";
|
|
11
|
+
import { encodeVideo } from "./video/encode.js";
|
|
12
|
+
import { chooseExportCodecs } from "./video/format.js";
|
|
13
|
+
export { newEncoderMemory };
|
|
14
|
+
/** The plan for a video of that size; null when this browser encodes no video at that size. */
|
|
15
|
+
export async function planFramesVideo(size) {
|
|
16
|
+
const videoBitrate = chooseVideoBitrate(size, size.fps);
|
|
17
|
+
const format = await chooseExportCodecs(size, videoBitrate);
|
|
18
|
+
return format === null ? null : { width: size.width, height: size.height, fps: size.fps, frames: size.frames, videoBitrate, format };
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Whether this browser can encode a video of that size: the codecs it would
|
|
22
|
+
* use, or null when it has no video encoder or encodes none of them (also
|
|
23
|
+
* when asking fails).
|
|
24
|
+
*/
|
|
25
|
+
export async function canEncodeFramesVideo(size) {
|
|
26
|
+
try {
|
|
27
|
+
return (await planFramesVideo(size))?.format ?? null;
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/** Encodes the frames as a silent MP4. Rejects when the browser encodes no video at that size, or the encoder fails. */
|
|
34
|
+
export async function encodeFramesVideo(options) {
|
|
35
|
+
const plan = await planFramesVideo(options);
|
|
36
|
+
if (plan === null)
|
|
37
|
+
throw new Error('This browser cannot encode video at this size.');
|
|
38
|
+
const made = await encodeVideo({
|
|
39
|
+
plan,
|
|
40
|
+
frame: options.frame,
|
|
41
|
+
audio: null,
|
|
42
|
+
firstPacketMs: EXPORT_SETTINGS.firstPacketS * 1000,
|
|
43
|
+
nextOnBreak: EXPORT_SETTINGS.onBreak === 'next',
|
|
44
|
+
rangeFromStream: EXPORT_SETTINGS.rangeLabel === 'stream',
|
|
45
|
+
lastInSoftware: EXPORT_SETTINGS.lastTry === 'software',
|
|
46
|
+
stalls: EXPORT_SETTINGS.stallsInView,
|
|
47
|
+
memory: options.memory ?? newEncoderMemory(),
|
|
48
|
+
...(options.onProgress !== undefined ? { onProgress: options.onProgress } : {}),
|
|
49
|
+
...(options.signal !== undefined ? { signal: options.signal } : {}),
|
|
50
|
+
});
|
|
51
|
+
return { bytes: made.bytes, format: plan.format, held: made.held, ms: made.ms };
|
|
52
|
+
}
|
package/src/frames.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { ExportFrame, ExportProgress, FramePlan, HeldFrames } from './types.js';
|
|
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 '@openartifactsai/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.js';
|
|
2
|
+
import type { ExportFrame, ExportProgress, HeldFrames } from '../types.js';
|
|
3
|
+
import type { SurfaceMaker } from './surface.js';
|
|
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 '@openartifactsai/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
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { RgbaPixels } from '@openartifactsai/wasm-motion';
|
|
2
|
+
import type { GifPlan } from '../plan.js';
|
|
3
|
+
import type { ExportDimensions } from '../types.js';
|
|
4
|
+
import type { SurfaceMaker } from './surface.js';
|
|
5
|
+
/** Where in the film a GIF estimate looks: each a pair of frames, one frame apart. */
|
|
6
|
+
export declare const GIF_PROBE_FRACTIONS: readonly number[];
|
|
7
|
+
/** Where it looks next when a pair rests (the two frames are the same), for as long as the preset allows. */
|
|
8
|
+
export declare const GIF_EXTRA_PROBE_FRACTIONS: readonly number[];
|
|
9
|
+
export interface GifSizeEncoder {
|
|
10
|
+
/** The bytes the frame added. */
|
|
11
|
+
add(pixels: RgbaPixels, delayCs: number): number;
|
|
12
|
+
dispose(): void;
|
|
13
|
+
}
|
|
14
|
+
/** What measuring needs; the defaults run the GIF encoder in this thread. */
|
|
15
|
+
export interface GifMeasureTools {
|
|
16
|
+
palette(frames: readonly RgbaPixels[]): Uint8Array;
|
|
17
|
+
encoder(size: ExportDimensions, palette: Uint8Array): GifSizeEncoder;
|
|
18
|
+
yieldTask(): Promise<void>;
|
|
19
|
+
}
|
|
20
|
+
export declare const DEFAULT_GIF_MEASURE_TOOLS: GifMeasureTools;
|
|
21
|
+
export interface GifMeasure {
|
|
22
|
+
bytes: number;
|
|
23
|
+
/** Encoding time per frame. */
|
|
24
|
+
msPerFrame: number;
|
|
25
|
+
/** The bytes are a floor: the first frames alone came to more than the guess. */
|
|
26
|
+
atLeast?: boolean;
|
|
27
|
+
}
|
|
28
|
+
export interface GifEstimator {
|
|
29
|
+
/** Paints frame `side` (0 or 1) of probe `probe`; null for a held frame. */
|
|
30
|
+
add(image: CanvasImageSource | null, probe: number, side: 0 | 1): void;
|
|
31
|
+
/** Some probe's two frames are the same: the film rests there, and more probes give a fairer guess. */
|
|
32
|
+
rests(): boolean;
|
|
33
|
+
measure(signal?: AbortSignal): Promise<GifMeasure | null>;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Guesses a GIF's size from pairs of frames: the largest first frame, plus the average change a frame brings times the
|
|
37
|
+
* frames after the first.
|
|
38
|
+
*/
|
|
39
|
+
export declare function createGifEstimator(plan: GifPlan, surface?: SurfaceMaker, tools?: GifMeasureTools): GifEstimator;
|
|
40
|
+
export interface GifMeasureInput {
|
|
41
|
+
largestFirst: number;
|
|
42
|
+
/** Bytes the second frames of all pairs added. */
|
|
43
|
+
seconds: number;
|
|
44
|
+
/** Bytes of one GIF fed every pair's first frame. */
|
|
45
|
+
firsts: number;
|
|
46
|
+
encodeMs: number;
|
|
47
|
+
pairs: number;
|
|
48
|
+
frames: number;
|
|
49
|
+
}
|
|
50
|
+
export declare function gifMeasureOf(input: GifMeasureInput): GifMeasure;
|