@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.
Files changed (97) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +5 -2
  4. package/package.json +58 -4
  5. package/src/build.d.ts +17 -0
  6. package/src/build.js +52 -0
  7. package/src/captions-file.d.ts +13 -0
  8. package/src/captions-file.js +15 -0
  9. package/src/clip/in-worker.d.ts +49 -0
  10. package/src/clip/in-worker.js +96 -0
  11. package/src/clip/jobs.d.ts +28 -0
  12. package/src/clip/jobs.js +2 -0
  13. package/src/clip/part.d.ts +25 -0
  14. package/src/clip/part.js +112 -0
  15. package/src/clip/problem.d.ts +25 -0
  16. package/src/clip/problem.js +10 -0
  17. package/src/clip/worker.d.ts +2 -0
  18. package/src/clip/worker.js +24 -0
  19. package/src/engine.d.ts +46 -0
  20. package/src/engine.js +225 -0
  21. package/src/errors.d.ts +78 -0
  22. package/src/errors.js +102 -0
  23. package/src/estimate.d.ts +27 -0
  24. package/src/estimate.js +103 -0
  25. package/src/filename.d.ts +14 -0
  26. package/src/filename.js +44 -0
  27. package/src/frame-source.d.ts +57 -0
  28. package/src/frame-source.js +1 -0
  29. package/src/frames-video.d.ts +45 -0
  30. package/src/frames-video.js +52 -0
  31. package/src/frames.d.ts +36 -0
  32. package/src/frames.js +112 -0
  33. package/src/gif/encode.d.ts +23 -0
  34. package/src/gif/encode.js +60 -0
  35. package/src/gif/estimator.d.ts +50 -0
  36. package/src/gif/estimator.js +82 -0
  37. package/src/gif/surface.d.ts +8 -0
  38. package/src/gif/surface.js +20 -0
  39. package/src/index.d.ts +34 -0
  40. package/src/index.js +18 -0
  41. package/src/mov/encode.d.ts +32 -0
  42. package/src/mov/encode.js +69 -0
  43. package/src/mov/estimate.d.ts +20 -0
  44. package/src/mov/estimate.js +33 -0
  45. package/src/mov/plan.d.ts +25 -0
  46. package/src/mov/plan.js +14 -0
  47. package/src/mov/surface.d.ts +4 -0
  48. package/src/mov/surface.js +20 -0
  49. package/src/plan.d.ts +54 -0
  50. package/src/plan.js +76 -0
  51. package/src/problems.d.ts +10 -0
  52. package/src/problems.js +32 -0
  53. package/src/raster/document.d.ts +7 -0
  54. package/src/raster/document.js +15 -0
  55. package/src/raster/frame-entry.d.ts +1 -0
  56. package/src/raster/frame-entry.js +36 -0
  57. package/src/raster/host.d.ts +28 -0
  58. package/src/raster/host.js +191 -0
  59. package/src/raster/messages.d.ts +34 -0
  60. package/src/raster/messages.js +25 -0
  61. package/src/source/layout.d.ts +49 -0
  62. package/src/source/layout.js +83 -0
  63. package/src/source/names.d.ts +14 -0
  64. package/src/source/names.js +65 -0
  65. package/src/source/readme.d.ts +17 -0
  66. package/src/source/readme.js +43 -0
  67. package/src/source/zip.d.ts +27 -0
  68. package/src/source/zip.js +61 -0
  69. package/src/stage-frame.d.ts +12 -0
  70. package/src/stage-frame.js +61 -0
  71. package/src/standalone/audio-entry.d.ts +1 -0
  72. package/src/standalone/audio-entry.js +80 -0
  73. package/src/standalone/clip-footage.d.ts +4 -0
  74. package/src/standalone/clip-footage.js +38 -0
  75. package/src/standalone/html.d.ts +35 -0
  76. package/src/standalone/html.js +60 -0
  77. package/src/types.d.ts +63 -0
  78. package/src/types.js +1 -0
  79. package/src/video/attempts.d.ts +55 -0
  80. package/src/video/attempts.js +73 -0
  81. package/src/video/avc.d.ts +15 -0
  82. package/src/video/avc.js +158 -0
  83. package/src/video/encode-attempt.d.ts +39 -0
  84. package/src/video/encode-attempt.js +157 -0
  85. package/src/video/encode.d.ts +6 -0
  86. package/src/video/encode.js +66 -0
  87. package/src/video/format.d.ts +22 -0
  88. package/src/video/format.js +41 -0
  89. package/src/video/output.d.ts +12 -0
  90. package/src/video/output.js +38 -0
  91. package/src/virtual.d.ts +11 -0
  92. package/src/visibility.d.ts +45 -0
  93. package/src/visibility.js +131 -0
  94. package/src/vite.d.ts +8 -0
  95. package/src/vite.js +43 -0
  96. package/src/words.d.ts +37 -0
  97. package/src/words.js +37 -0
@@ -0,0 +1,39 @@
1
+ import type { ExportFrame, ExportProgress, HeldFrames } from '../types.js';
2
+ import type { EncodeTryListener, HiddenWatch } from '../visibility.js';
3
+ import type { EncoderAttempt, EncoderMemory } from './attempts.js';
4
+ import type { VideoPlan } from './format.js';
5
+ export declare const SUPERSAMPLE_SCALE = 2;
6
+ export interface VideoEncodeOptions {
7
+ plan: VideoPlan;
8
+ frame: ExportFrame;
9
+ /** The film's sound, rendered; null for a silent file. */
10
+ audio: AudioBuffer | null;
11
+ supersample?: boolean;
12
+ /** How long the encoder may stay silent, while the page is visible, before the try is given up. */
13
+ firstPacketMs?: number;
14
+ /** A set-up that breaks is followed by the next. */
15
+ nextOnBreak?: boolean;
16
+ /** The colour range is read from the stream, not trusted from the encoder. */
17
+ rangeFromStream?: boolean;
18
+ /** After every set-up put nothing out, one more try in software. */
19
+ lastInSoftware?: boolean;
20
+ onTry?: EncodeTryListener;
21
+ stalls?: number;
22
+ page?: Document;
23
+ memory: EncoderMemory;
24
+ onProgress?: (progress: ExportProgress) => void;
25
+ signal?: AbortSignal;
26
+ }
27
+ export interface VideoAttemptResult {
28
+ bytes: Uint8Array<ArrayBuffer>;
29
+ held: HeldFrames;
30
+ }
31
+ export interface AttemptContext {
32
+ attempt: EncoderAttempt;
33
+ preferSoftware: boolean;
34
+ retried: boolean;
35
+ hidden: HiddenWatch;
36
+ reordered(): void;
37
+ }
38
+ /** One try at the video with one encoder set-up. */
39
+ export declare function encodeVideoAttempt(options: VideoEncodeOptions, context: AttemptContext): Promise<VideoAttemptResult>;
@@ -0,0 +1,157 @@
1
+ import { AudioBufferSource, CanvasSource } from 'mediabunny';
2
+ import { EncoderFailure, EncoderSilentError, ExportCheckError, SkippedVideoFramesError, asError, exportAbortError, isAborted } from "../errors.js";
3
+ import { renderExportFrames } from "../frames.js";
4
+ import { EXPORT_AUDIO_BITRATE } from "../plan.js";
5
+ import { withVisibleTimeout } from "../visibility.js";
6
+ import { words } from "../words.js";
7
+ import { BASELINE_ONLY_ATTEMPTS, FIRST_ATTEMPT, encoderAttemptOptions } from "./attempts.js";
8
+ import { avcDecodesInOrder, repairAvcColorSpace } from "./avc.js";
9
+ import { createMp4Output } from "./output.js";
10
+ /** Errors a hardware encoder throws when it breaks: another set-up may work. */
11
+ const RETRYABLE_ENCODER_ERRORS = ['OperationError', 'EncodingError'];
12
+ export const SUPERSAMPLE_SCALE = 2;
13
+ function makeCanvas(width, height) {
14
+ if (typeof OffscreenCanvas !== 'undefined')
15
+ return new OffscreenCanvas(width, height);
16
+ const canvas = document.createElement('canvas');
17
+ canvas.width = width;
18
+ canvas.height = height;
19
+ return canvas;
20
+ }
21
+ function context2d(canvas) {
22
+ return canvas instanceof HTMLCanvasElement ? canvas.getContext('2d', { alpha: false }) : canvas.getContext('2d', { alpha: false });
23
+ }
24
+ /** One try at the video with one encoder set-up. */
25
+ export async function encodeVideoAttempt(options, context) {
26
+ const { plan, signal, memory } = options;
27
+ const { attempt } = context;
28
+ const isFirst = attempt === FIRST_ATTEMPT || (plan.format.baselineOnly === true && attempt === BASELINE_ONLY_ATTEMPTS[0]);
29
+ // Frames the encoder skipped send the next export back to the first attempt, unless that is the one that skipped them.
30
+ const offFirst = attempt !== FIRST_ATTEMPT;
31
+ const onProgress = options.onProgress ?? (() => undefined);
32
+ const canvas = makeCanvas(plan.width, plan.height);
33
+ const draw = context2d(canvas);
34
+ if (draw === null)
35
+ throw new ExportCheckError(words.noCanvas, 'no_canvas');
36
+ draw.imageSmoothingEnabled = true;
37
+ draw.imageSmoothingQuality = 'high';
38
+ const { output, file } = createMp4Output();
39
+ const controller = new AbortController();
40
+ let packets = 0;
41
+ let packetBytes = 0;
42
+ let lastTimestamp = Number.NEGATIVE_INFINITY;
43
+ let warnedOutOfOrder = false;
44
+ let inOrder;
45
+ const onEncodedPacket = (packet, meta) => {
46
+ if (options.rangeFromStream === true)
47
+ repairAvcColorSpace(meta?.decoderConfig);
48
+ packets++;
49
+ packetBytes += packet.byteLength;
50
+ if (controller.signal.aborted)
51
+ return;
52
+ memory.preferred = attempt;
53
+ inOrder ??= avcDecodesInOrder(meta?.decoderConfig);
54
+ if (packet.timestamp < lastTimestamp && inOrder === true && !warnedOutOfOrder) {
55
+ warnedOutOfOrder = true;
56
+ console.info(`video export: the encoder began to send frames out of order at about frame ${packets} of ${plan.frames} (set-up ${JSON.stringify(attempt)})`);
57
+ context.reordered();
58
+ }
59
+ lastTimestamp = packet.timestamp;
60
+ };
61
+ const videoSource = new CanvasSource(canvas, {
62
+ codec: plan.format.videoCodec,
63
+ bitrate: plan.videoBitrate,
64
+ keyFrameInterval: 2,
65
+ ...encoderAttemptOptions(attempt, plan, context.preferSoftware),
66
+ onEncodedPacket,
67
+ });
68
+ output.addVideoTrack(videoSource, { frameRate: plan.fps });
69
+ const audioSource = options.audio !== null && plan.format.audioCodec !== null ? new AudioBufferSource({ codec: plan.format.audioCodec, bitrate: EXPORT_AUDIO_BITRATE }) : null;
70
+ if (audioSource !== null)
71
+ output.addAudioTrack(audioSource);
72
+ let rejectEncoder = () => undefined;
73
+ const encoderAborted = new Promise((_resolve, reject) => {
74
+ rejectEncoder = reject;
75
+ });
76
+ encoderAborted.catch(() => undefined);
77
+ let cancelled;
78
+ const abortEncoding = () => {
79
+ cancelled = output.cancel().catch(() => undefined);
80
+ rejectEncoder(exportAbortError());
81
+ };
82
+ signal?.addEventListener('abort', abortEncoding, { once: true });
83
+ const firstPacketMs = options.firstPacketMs ?? 0;
84
+ const waitForFirstPacket = (operation) => packets > 0 || firstPacketMs <= 0
85
+ ? operation
86
+ : new Promise((resolve, reject) => {
87
+ withVisibleTimeout(operation, firstPacketMs, () => {
88
+ if (packets === 0)
89
+ reject(new EncoderSilentError());
90
+ }, controller.signal, options.page).then(resolve, reject);
91
+ });
92
+ const run = (operation, finishing = false) => Promise.race([waitForFirstPacket(operation), encoderAborted]).catch((error) => {
93
+ if (error instanceof EncoderSilentError)
94
+ throw error;
95
+ if (options.nextOnBreak === true &&
96
+ error instanceof DOMException &&
97
+ RETRYABLE_ENCODER_ERRORS.includes(error.name) &&
98
+ !finishing &&
99
+ !context.hidden.seen())
100
+ throw new EncoderFailure(error);
101
+ throw (!isFirst || context.retried) && packets === 0 ? new EncoderSilentError(error) : error;
102
+ });
103
+ let held;
104
+ try {
105
+ await output.start();
106
+ held = await renderExportFrames({
107
+ plan,
108
+ frame: options.frame,
109
+ scale: options.supersample === true ? SUPERSAMPLE_SCALE : 1,
110
+ ...(signal !== undefined ? { signal } : {}),
111
+ ...(options.page !== undefined ? { page: options.page } : {}),
112
+ ...(options.stalls !== undefined ? { stalls: options.stalls } : {}),
113
+ onProgress: (progress) => onProgress({ ...progress, packets, bytes: packetBytes }),
114
+ draw: (bitmap, index) => {
115
+ if (bitmap === null && index > 0)
116
+ return;
117
+ draw.fillStyle = '#000';
118
+ draw.fillRect(0, 0, plan.width, plan.height);
119
+ if (bitmap !== null)
120
+ draw.drawImage(bitmap, 0, 0, plan.width, plan.height);
121
+ },
122
+ commit: (index) => run(videoSource.add(index / plan.fps, 1 / plan.fps)),
123
+ });
124
+ onProgress({ done: plan.frames, total: plan.frames, phase: 'mux' });
125
+ if (audioSource !== null && options.audio !== null) {
126
+ await audioSource.add(options.audio);
127
+ audioSource.close();
128
+ }
129
+ videoSource.close();
130
+ await run(output.finalize(), audioSource !== null);
131
+ if (isAborted(signal))
132
+ throw exportAbortError();
133
+ if (packets === 0)
134
+ throw new EncoderSilentError();
135
+ const skipped = plan.frames - packets;
136
+ if (skipped > 0 && offFirst) {
137
+ memory.preferred = FIRST_ATTEMPT;
138
+ throw new SkippedVideoFramesError(skipped, plan.frames);
139
+ }
140
+ }
141
+ catch (error) {
142
+ await cancelled;
143
+ if (output.state !== 'canceled' && output.state !== 'finalized')
144
+ await output.cancel().catch(() => undefined);
145
+ if (isAborted(signal))
146
+ throw exportAbortError();
147
+ throw asError(error);
148
+ }
149
+ finally {
150
+ controller.abort();
151
+ signal?.removeEventListener('abort', abortEncoding);
152
+ }
153
+ const bytes = file();
154
+ if (bytes === null)
155
+ throw new ExportCheckError(words.noOutput, 'no_output');
156
+ return { bytes, held };
157
+ }
@@ -0,0 +1,6 @@
1
+ import type { VideoAttemptResult, VideoEncodeOptions } from './encode-attempt.js';
2
+ export interface EncodedVideo extends VideoAttemptResult {
3
+ ms: number;
4
+ }
5
+ /** Makes the video, trying the encoder set-ups in turn while one breaks without putting frames out. */
6
+ export declare function encodeVideo(options: VideoEncodeOptions): Promise<EncodedVideo>;
@@ -0,0 +1,66 @@
1
+ import { EncoderFailure, EncoderSilentError, exportAbortError, isAborted } from "../errors.js";
2
+ import { trackEncodeTry } from "../visibility.js";
3
+ import { BASELINE_ATTEMPT, FIRST_ATTEMPT, attemptsFor, encoderAttemptOptions, supportsEncoderAttempt } from "./attempts.js";
4
+ import { encodeVideoAttempt } from "./encode-attempt.js";
5
+ /**
6
+ * One more try in software after every set-up broke: only when allowed, when a broken set-up is followed by the
7
+ * next, for H.264, and when the encoder put out nothing at all.
8
+ */
9
+ const softwareLastTryApplies = (options, error) => options.lastInSoftware === true &&
10
+ options.nextOnBreak === true &&
11
+ options.plan.format.videoCodec === 'avc' &&
12
+ error instanceof EncoderSilentError &&
13
+ error.cause === undefined;
14
+ const describeCause = (cause) => (cause instanceof Error ? cause.name : typeof cause);
15
+ /** Makes the video, trying the encoder set-ups in turn while one breaks without putting frames out. */
16
+ export async function encodeVideo(options) {
17
+ const { plan, signal, memory } = options;
18
+ const startedAt = performance.now();
19
+ const attempts = attemptsFor(plan);
20
+ const start = Math.max(0, attempts.indexOf(memory.preferred));
21
+ let firstError;
22
+ let triedSoftware = false;
23
+ for (let index = 0;; index++) {
24
+ const lastTry = index === attempts.length;
25
+ const attempt = lastTry ? BASELINE_ATTEMPT : attempts[(start + index) % attempts.length] ?? FIRST_ATTEMPT;
26
+ const softwareRetry = !lastTry && memory.softwareOnRetry && attempt !== FIRST_ATTEMPT && (attempt.baseline === true || plan.format.videoCodec !== 'avc');
27
+ const preferSoftware = lastTry || (softwareRetry && (await supportsEncoderAttempt(plan, encoderAttemptOptions(attempt, plan, true), signal)));
28
+ if (isAborted(signal))
29
+ throw exportAbortError();
30
+ triedSoftware ||= softwareRetry;
31
+ if (softwareRetry)
32
+ options.onProgress?.({ done: 0, total: plan.frames, phase: 'frames' });
33
+ try {
34
+ const result = await trackEncodeTry(options.onTry, signal, (hidden, reordered) => encodeVideoAttempt(options, { attempt, preferSoftware, retried: index > 0, hidden, reordered }), options.page);
35
+ return { ...result, ms: performance.now() - startedAt };
36
+ }
37
+ catch (error) {
38
+ const broke = error instanceof EncoderFailure;
39
+ if (!broke && !(error instanceof EncoderSilentError))
40
+ throw error;
41
+ firstError ??= broke ? error.failure : error;
42
+ const another = index + 1 < attempts.length ||
43
+ (index + 1 === attempts.length &&
44
+ !triedSoftware &&
45
+ softwareLastTryApplies(options, firstError) &&
46
+ (await supportsEncoderAttempt(plan, encoderAttemptOptions(BASELINE_ATTEMPT, plan, true), signal)));
47
+ memory.softwareOnRetry ||= broke && !lastTry;
48
+ if (!another || isAborted(signal))
49
+ memory.preferred = FIRST_ATTEMPT;
50
+ if (isAborted(signal))
51
+ throw exportAbortError();
52
+ const cause = broke ? error.failure : error.cause;
53
+ console.info('video export: the encoder ' +
54
+ (cause === undefined ? 'put out nothing' : `broke (${describeCause(cause)})${broke ? '' : ' before it put anything out'}`) +
55
+ ` with ${JSON.stringify(attempt)}${preferSoftware ? ', in software' : ''}` +
56
+ (another ? '; trying the next set-up' : `; giving up with the first try’s ${firstError.name}`));
57
+ if (!another)
58
+ throw firstError;
59
+ options.onProgress?.({ done: 0, total: plan.frames, phase: 'frames' });
60
+ }
61
+ finally {
62
+ if (lastTry)
63
+ memory.preferred = FIRST_ATTEMPT;
64
+ }
65
+ }
66
+ }
@@ -0,0 +1,22 @@
1
+ import type { FilmFacts } from '../frame-source.js';
2
+ import type { VideoFramePlan, VideoSettings } from '../plan.js';
3
+ import type { ExportDimensions } from '../types.js';
4
+ export type ExportVideoCodec = 'avc' | 'vp9' | 'av1';
5
+ export type ExportAudioCodec = 'aac' | 'opus';
6
+ /** The codecs a video is made with, and how that is said to people. */
7
+ export interface VideoFormat {
8
+ label: string;
9
+ note?: string;
10
+ videoCodec: ExportVideoCodec;
11
+ audioCodec: ExportAudioCodec | null;
12
+ /** The H.264 encoder takes the Constrained Baseline profile only. */
13
+ baselineOnly?: true;
14
+ }
15
+ export interface VideoPlan extends VideoFramePlan {
16
+ format: VideoFormat;
17
+ }
18
+ /** The format a pair of codecs makes: H.264 with AAC first, else whatever this browser can encode. */
19
+ export declare function describeVideoFormat(videoCodec: ExportVideoCodec, audioCodec: ExportAudioCodec | null): VideoFormat;
20
+ /** The best codecs this browser encodes at that size; null when it encodes no video at all. */
21
+ export declare function chooseExportCodecs(size: ExportDimensions, bitrate: number): Promise<VideoFormat | null>;
22
+ export declare function planVideoExport(film: FilmFacts, settings: VideoSettings): Promise<VideoPlan | null>;
@@ -0,0 +1,41 @@
1
+ import { getFirstEncodableAudioCodec, getFirstEncodableVideoCodec } from 'mediabunny';
2
+ import { EXPORT_AUDIO_BITRATE, planVideoFrames } from "../plan.js";
3
+ import { formatLabels } from "../words.js";
4
+ import { avcBaselineCodecString, supportsEncoderAttempt } from "./attempts.js";
5
+ const isVideoCodec = (codec) => codec === 'avc' || codec === 'vp9' || codec === 'av1';
6
+ const isAudioCodec = (codec) => codec === 'aac' || codec === 'opus';
7
+ /** The format a pair of codecs makes: H.264 with AAC first, else whatever this browser can encode. */
8
+ export function describeVideoFormat(videoCodec, audioCodec) {
9
+ if (videoCodec === 'avc') {
10
+ if (audioCodec === 'aac')
11
+ return { label: formatLabels.avcAac, videoCodec, audioCodec };
12
+ if (audioCodec === 'opus')
13
+ return { label: formatLabels.avcOpus, note: formatLabels.avcOpusNote, videoCodec, audioCodec };
14
+ return { label: formatLabels.avcSilent, note: formatLabels.avcSilentNote, videoCodec, audioCodec: null };
15
+ }
16
+ const audio = audioCodec === 'opus' ? audioCodec : null;
17
+ return { label: formatLabels.other(videoCodec, audio !== null), note: formatLabels.otherNote(audio !== null), videoCodec, audioCodec: audio };
18
+ }
19
+ /** The best codecs this browser encodes at that size; null when it encodes no video at all. */
20
+ export async function chooseExportCodecs(size, bitrate) {
21
+ if (typeof VideoEncoder === 'undefined' || typeof VideoFrame === 'undefined')
22
+ return null;
23
+ const asked = { width: size.width, height: size.height, bitrate };
24
+ const avc = await getFirstEncodableVideoCodec(['avc'], asked);
25
+ // An encoder that takes H.264 only as Constrained Baseline, at the level the size needs, still makes H.264.
26
+ const baselineOnly = avc === null &&
27
+ (await supportsEncoderAttempt({ ...size, videoBitrate: bitrate, format: { videoCodec: 'avc' } }, { fullCodecString: avcBaselineCodecString(size) }, undefined));
28
+ const videoCodec = avc !== null || baselineOnly ? 'avc' : await getFirstEncodableVideoCodec(['vp9', 'av1'], asked);
29
+ if (!isVideoCodec(videoCodec))
30
+ return null;
31
+ const audioCodec = typeof AudioEncoder === 'undefined'
32
+ ? null
33
+ : await getFirstEncodableAudioCodec(videoCodec === 'avc' ? ['aac', 'opus'] : ['opus'], { numberOfChannels: 2, sampleRate: 48_000, bitrate: EXPORT_AUDIO_BITRATE });
34
+ const format = describeVideoFormat(videoCodec, isAudioCodec(audioCodec) ? audioCodec : null);
35
+ return baselineOnly ? { ...format, baselineOnly: true } : format;
36
+ }
37
+ export async function planVideoExport(film, settings) {
38
+ const frames = planVideoFrames(film, settings);
39
+ const format = await chooseExportCodecs(frames, frames.videoBitrate);
40
+ return format === null ? null : { ...frames, format };
41
+ }
@@ -0,0 +1,12 @@
1
+ import { Output } from 'mediabunny';
2
+ /** An MP4 being written in memory. `file()` hands out its bytes once, or null when nothing was written. */
3
+ export interface Mp4Output {
4
+ output: Output;
5
+ file(): Uint8Array<ArrayBuffer> | null;
6
+ }
7
+ /**
8
+ * Runs `make` while ArrayBuffer.prototype.resize is hidden: the muxer grows its buffers with it where it exists, and
9
+ * Chrome's resizable buffers can fail to transfer to the encoder.
10
+ */
11
+ export declare function withoutResizableArrayBuffers<T>(make: () => T): T;
12
+ export declare function createMp4Output(): Mp4Output;
@@ -0,0 +1,38 @@
1
+ import { Mp4OutputFormat, Output, StreamTarget } from 'mediabunny';
2
+ /**
3
+ * Runs `make` while ArrayBuffer.prototype.resize is hidden: the muxer grows its buffers with it where it exists, and
4
+ * Chrome's resizable buffers can fail to transfer to the encoder.
5
+ */
6
+ export function withoutResizableArrayBuffers(make) {
7
+ const resize = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, 'resize');
8
+ if (resize?.configurable !== true || !Object.isExtensible(ArrayBuffer.prototype))
9
+ return make();
10
+ Reflect.deleteProperty(ArrayBuffer.prototype, 'resize');
11
+ try {
12
+ return make();
13
+ }
14
+ finally {
15
+ Object.defineProperty(ArrayBuffer.prototype, 'resize', resize);
16
+ }
17
+ }
18
+ export function createMp4Output() {
19
+ const writes = [];
20
+ const target = new StreamTarget(new WritableStream({
21
+ write: (chunk) => {
22
+ writes.push(chunk);
23
+ },
24
+ }));
25
+ return {
26
+ output: withoutResizableArrayBuffers(() => new Output({ format: new Mp4OutputFormat({ fastStart: 'in-memory' }), target })),
27
+ file: () => {
28
+ if (writes.length === 0)
29
+ return null;
30
+ const length = writes.reduce((end, chunk) => Math.max(end, chunk.position + chunk.data.byteLength), 0);
31
+ const bytes = new Uint8Array(length);
32
+ for (const chunk of writes)
33
+ bytes.set(chunk.data, chunk.position);
34
+ writes.length = 0;
35
+ return bytes;
36
+ },
37
+ };
38
+ }
@@ -0,0 +1,11 @@
1
+ /** The raster frame's script text, from the `motionExportScripts()` Vite plugin. */
2
+ declare module 'virtual:motion-raster-frame' {
3
+ const script: string;
4
+ export default script;
5
+ }
6
+
7
+ /** The standalone page's audio script text, from the `motionExportScripts()` Vite plugin. */
8
+ declare module 'virtual:motion-standalone-audio' {
9
+ const script: string;
10
+ export default script;
11
+ }
@@ -0,0 +1,45 @@
1
+ /** A frame that failed after this long on a page that was hidden meanwhile is asked for again. */
2
+ export declare const HIDDEN_FRAME_SLOW_MS = 15000;
3
+ export declare const FRAME_RETRY_PAUSE_MS = 1000;
4
+ /** How many times a frame that stalls with the page in view is asked for again. */
5
+ export declare const STALLS_IN_VIEW: 2;
6
+ /** Resolves once the page is visible; rejects with an AbortError when the signal aborts first. */
7
+ export declare function waitForVisibleDocument(page: Document, signal: AbortSignal): Promise<void>;
8
+ /**
9
+ * Calls `onTimeout` when `promise` has not settled after `timeoutMs` of the page being visible: a hidden page's
10
+ * encoder may be throttled, which is no reason to give up on it.
11
+ */
12
+ export declare function withVisibleTimeout<T>(promise: Promise<T>, timeoutMs: number, onTimeout: () => void, signal: AbortSignal | undefined, page?: Document): Promise<T>;
13
+ /** Whether the page was hidden at any moment since the watch began. */
14
+ export interface HiddenWatch {
15
+ seen(): boolean;
16
+ stop(): void;
17
+ }
18
+ export declare function watchDocumentHidden(page?: Document): HiddenWatch;
19
+ /** How one encoder try went. */
20
+ export type EncodeTryOutcome = {
21
+ kind: 'made';
22
+ } | {
23
+ kind: 'reordered';
24
+ } | {
25
+ kind: 'cancelled';
26
+ } | {
27
+ kind: 'threw';
28
+ error: unknown;
29
+ };
30
+ export type EncodeTryListener = (outcome: EncodeTryOutcome, hidden: boolean) => void;
31
+ /** Runs one encoder try, watching whether the page was hidden meanwhile, and tells `onTry` how it went. */
32
+ export declare function trackEncodeTry<Result>(onTry: EncodeTryListener | undefined, signal: AbortSignal | undefined, encode: (hidden: HiddenWatch, reordered: () => void) => Promise<Result>, page?: Document): Promise<Result>;
33
+ export interface RetryOptions {
34
+ /** How many times a frame that stalls with the page in view is asked for again. */
35
+ stalls: number;
36
+ pause?: () => Promise<void>;
37
+ /** Told, for a frame that failed and was asked for again, whether it then came. */
38
+ onAgain?: (good: boolean) => void;
39
+ }
40
+ /**
41
+ * Asks again for a frame that stalled, or that failed (held) slowly or while the page was hidden: a background tab's
42
+ * timers and decoders are throttled, so such a failure says nothing about the film. A stall with the page in view is
43
+ * asked for again `stalls` times, after a pause; with the page hidden, once it is visible.
44
+ */
45
+ export declare function retryBackgroundFrame<Arguments extends unknown[], Result>(render: (...args: Arguments) => Promise<Result>, signal: AbortSignal, page: Document, options: RetryOptions): (...args: Arguments) => Promise<Result>;
@@ -0,0 +1,131 @@
1
+ import { EXPORT_SETTINGS } from '@openartifactsai/motion-core';
2
+ import { FrameRenderError, FrameStallError, exportAbortError } from "./errors.js";
3
+ import { words } from "./words.js";
4
+ /** A frame that failed after this long on a page that was hidden meanwhile is asked for again. */
5
+ export const HIDDEN_FRAME_SLOW_MS = 15_000;
6
+ export const FRAME_RETRY_PAUSE_MS = 1000;
7
+ /** How many times a frame that stalls with the page in view is asked for again. */
8
+ export const STALLS_IN_VIEW = EXPORT_SETTINGS.stallsInView;
9
+ const pauseBeforeRetry = () => new Promise((resolve) => setTimeout(resolve, FRAME_RETRY_PAUSE_MS));
10
+ /** Resolves once the page is visible; rejects with an AbortError when the signal aborts first. */
11
+ export function waitForVisibleDocument(page, signal) {
12
+ return new Promise((resolve, reject) => {
13
+ const check = () => {
14
+ if (page.hidden && !signal.aborted)
15
+ return;
16
+ page.removeEventListener('visibilitychange', check);
17
+ signal.removeEventListener('abort', check);
18
+ if (signal.aborted)
19
+ reject(exportAbortError());
20
+ else
21
+ resolve();
22
+ };
23
+ page.addEventListener('visibilitychange', check);
24
+ signal.addEventListener('abort', check);
25
+ check();
26
+ });
27
+ }
28
+ /**
29
+ * Calls `onTimeout` when `promise` has not settled after `timeoutMs` of the page being visible: a hidden page's
30
+ * encoder may be throttled, which is no reason to give up on it.
31
+ */
32
+ export function withVisibleTimeout(promise, timeoutMs, onTimeout, signal, page = document) {
33
+ if (timeoutMs <= 0 || signal?.aborted === true)
34
+ return promise;
35
+ let timer;
36
+ const restart = () => {
37
+ clearTimeout(timer);
38
+ if (!page.hidden)
39
+ timer = setTimeout(onTimeout, timeoutMs);
40
+ };
41
+ const cleanup = () => {
42
+ clearTimeout(timer);
43
+ page.removeEventListener('visibilitychange', restart);
44
+ signal?.removeEventListener('abort', cleanup);
45
+ };
46
+ page.addEventListener('visibilitychange', restart);
47
+ signal?.addEventListener('abort', cleanup);
48
+ restart();
49
+ promise.then(cleanup, cleanup);
50
+ return promise;
51
+ }
52
+ export function watchDocumentHidden(page = document) {
53
+ let hidden = page.hidden;
54
+ const check = () => {
55
+ hidden = true;
56
+ };
57
+ page.addEventListener('visibilitychange', check);
58
+ return { seen: () => hidden, stop: () => page.removeEventListener('visibilitychange', check) };
59
+ }
60
+ /** Runs one encoder try, watching whether the page was hidden meanwhile, and tells `onTry` how it went. */
61
+ export async function trackEncodeTry(onTry, signal, encode, page = document) {
62
+ const hidden = watchDocumentHidden(page);
63
+ let outcome = { kind: 'made' };
64
+ try {
65
+ return await encode(hidden, () => {
66
+ outcome = { kind: 'reordered' };
67
+ });
68
+ }
69
+ catch (error) {
70
+ outcome = signal?.aborted === true ? { kind: 'cancelled' } : { kind: 'threw', error };
71
+ throw error;
72
+ }
73
+ finally {
74
+ hidden.stop();
75
+ try {
76
+ onTry?.(outcome, hidden.seen());
77
+ }
78
+ catch {
79
+ // A listener's failure is not the export's.
80
+ }
81
+ }
82
+ }
83
+ /**
84
+ * Asks again for a frame that stalled, or that failed (held) slowly or while the page was hidden: a background tab's
85
+ * timers and decoders are throttled, so such a failure says nothing about the film. A stall with the page in view is
86
+ * asked for again `stalls` times, after a pause; with the page hidden, once it is visible.
87
+ */
88
+ export function retryBackgroundFrame(render, signal, page, options) {
89
+ let stallsLeft = options.stalls;
90
+ const pause = options.pause ?? pauseBeforeRetry;
91
+ return async (...args) => {
92
+ let askedAgain = false;
93
+ for (;;) {
94
+ let hidden = page.hidden;
95
+ let changed = false;
96
+ const note = () => {
97
+ changed = true;
98
+ hidden ||= page.hidden;
99
+ };
100
+ page.addEventListener('visibilitychange', note);
101
+ const startedAt = Date.now();
102
+ try {
103
+ const result = await render(...args);
104
+ if (askedAgain)
105
+ options.onAgain?.(true);
106
+ return result;
107
+ }
108
+ catch (error) {
109
+ hidden ||= page.hidden;
110
+ const slow = (hidden || changed) && Date.now() - startedAt > HIDDEN_FRAME_SLOW_MS;
111
+ const held = error instanceof FrameRenderError && error.hold;
112
+ const worth = error instanceof FrameStallError || (held && (slow || (hidden && !page.hidden)));
113
+ const inViewSpent = !hidden && (!(stallsLeft > 0) || (error instanceof Error && error.message === words.filmNotLoaded));
114
+ if (!worth || signal.aborted || inViewSpent) {
115
+ if (askedAgain && held)
116
+ options.onAgain?.(false);
117
+ throw error;
118
+ }
119
+ askedAgain ||= error instanceof FrameRenderError;
120
+ }
121
+ finally {
122
+ page.removeEventListener('visibilitychange', note);
123
+ }
124
+ if (!hidden) {
125
+ stallsLeft--;
126
+ await pause();
127
+ }
128
+ await waitForVisibleDocument(page, signal);
129
+ }
130
+ };
131
+ }
package/src/vite.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ import type { Plugin } from 'vite';
2
+ export declare const RASTER_FRAME_MODULE = "virtual:motion-raster-frame";
3
+ export declare const STANDALONE_AUDIO_MODULE = "virtual:motion-standalone-audio";
4
+ /**
5
+ * Gives the page the export's scripts as strings: `import rasterFrame from 'virtual:motion-raster-frame'` and
6
+ * `import standaloneAudio from 'virtual:motion-standalone-audio'`.
7
+ */
8
+ export declare function motionExportScripts(): Plugin;
package/src/vite.js ADDED
@@ -0,0 +1,43 @@
1
+ import { RASTER_FRAME_ENTRY, STANDALONE_AUDIO_ENTRY, buildExportScriptFresh } from "./build.js";
2
+ export const RASTER_FRAME_MODULE = 'virtual:motion-raster-frame';
3
+ export const STANDALONE_AUDIO_MODULE = 'virtual:motion-standalone-audio';
4
+ const ENTRIES = new Map([
5
+ ['\0' + RASTER_FRAME_MODULE, RASTER_FRAME_ENTRY],
6
+ ['\0' + STANDALONE_AUDIO_MODULE, STANDALONE_AUDIO_ENTRY],
7
+ ]);
8
+ /**
9
+ * Gives the page the export's scripts as strings: `import rasterFrame from 'virtual:motion-raster-frame'` and
10
+ * `import standaloneAudio from 'virtual:motion-standalone-audio'`.
11
+ */
12
+ export function motionExportScripts() {
13
+ const watched = new Map();
14
+ return {
15
+ name: 'motion-export-scripts',
16
+ resolveId(id) {
17
+ return ENTRIES.has('\0' + id) ? '\0' + id : null;
18
+ },
19
+ async load(id) {
20
+ const entry = ENTRIES.get(id);
21
+ if (entry === undefined)
22
+ return null;
23
+ const built = await buildExportScriptFresh(entry);
24
+ watched.set(id, new Set(built.inputs));
25
+ for (const input of built.inputs)
26
+ this.addWatchFile(input);
27
+ return 'export default ' + JSON.stringify(built.script) + ';\n';
28
+ },
29
+ // A script's source is not in the page's module graph: its change makes the virtual module stale by hand.
30
+ handleHotUpdate({ file, server }) {
31
+ const stale = [...watched]
32
+ .filter(([, inputs]) => inputs.has(file))
33
+ .flatMap(([id]) => {
34
+ const module = server.moduleGraph.getModuleById(id);
35
+ if (!module)
36
+ return [];
37
+ server.moduleGraph.invalidateModule(module);
38
+ return [module];
39
+ });
40
+ return stale.length > 0 ? stale : undefined;
41
+ },
42
+ };
43
+ }