@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,112 @@
1
+ /**
2
+ * A part of a video file the person picked, read and converted so it can be stored with a film: an H.264 MP4 with AAC
3
+ * sound, small enough for the upload limit (`videoEncodePlan` sizes it; a file still too large is made again smaller).
4
+ * The page runs these in a worker (`./worker.ts`), so the file's demuxers stay out of the page.
5
+ */
6
+ import { ALL_FORMATS, BlobSource, Conversion, Input, canEncodeAudio, canEncodeVideo } from 'mediabunny';
7
+ import { MAX_VIDEO_UPLOAD_BYTES, looksLikeVideoFile, videoEncodePlan } from '@openartifactsai/motion-core';
8
+ import { createMp4Output, withoutResizableArrayBuffers } from "../video/output.js";
9
+ import { VideoPartError } from "./problem.js";
10
+ const HEAD_BYTES = 16;
11
+ /** Reads a file's length and frame; throws a {@link VideoPartError} for one that is not a video this browser reads. */
12
+ export async function readVideoFile(file) {
13
+ const head = new Uint8Array(await file.slice(0, HEAD_BYTES).arrayBuffer());
14
+ if (!looksLikeVideoFile(head))
15
+ throw new VideoPartError('not-video');
16
+ const input = new Input({ source: new BlobSource(file), formats: ALL_FORMATS });
17
+ try {
18
+ const video = await input.getPrimaryVideoTrack();
19
+ if (video === null)
20
+ throw new VideoPartError('not-video');
21
+ if (!(await video.canDecode()))
22
+ throw new VideoPartError('unreadable');
23
+ const duration = await input.computeDuration();
24
+ const stats = await video.computePacketStats(60).catch(() => null);
25
+ const audio = await input.getPrimaryAudioTrack();
26
+ if (!(duration > 0) || !(video.displayWidth > 0 && video.displayHeight > 0))
27
+ throw new VideoPartError('unreadable');
28
+ return {
29
+ duration,
30
+ width: video.displayWidth,
31
+ height: video.displayHeight,
32
+ fps: stats !== null && stats.averagePacketRate > 0 ? stats.averagePacketRate : null,
33
+ hasSound: audio !== null && (await audio.canDecode()),
34
+ };
35
+ }
36
+ catch (error) {
37
+ throw error instanceof VideoPartError ? error : new VideoPartError('unreadable', error);
38
+ }
39
+ finally {
40
+ input.dispose();
41
+ }
42
+ }
43
+ /** Whether this browser can write the picture a part is converted to (without sound it is stored silent). */
44
+ export async function canConvertVideo(plan) {
45
+ try {
46
+ return await canEncodeVideo('avc', { width: plan.width, height: plan.height, bitrate: plan.bitrate, frameRate: plan.fps });
47
+ }
48
+ catch {
49
+ return false;
50
+ }
51
+ }
52
+ async function convertOnce(file, options, plan, report) {
53
+ const input = new Input({ source: new BlobSource(file), formats: ALL_FORMATS });
54
+ const mp4 = createMp4Output();
55
+ try {
56
+ const audioOk = options.facts.hasSound && (await canEncodeAudio('aac', { bitrate: plan.audioBitrate }).catch(() => false));
57
+ const conversion = await withoutResizableArrayBuffers(() => Conversion.init({
58
+ input,
59
+ output: mp4.output,
60
+ tracks: 'primary',
61
+ trim: { start: options.start, end: options.end },
62
+ video: { codec: 'avc', width: plan.width, height: plan.height, fit: 'contain', bitrate: plan.bitrate, frameRate: plan.fps, forceTranscode: true },
63
+ audio: audioOk ? { codec: 'aac', bitrate: plan.audioBitrate, forceTranscode: true } : { discard: true },
64
+ showWarnings: false,
65
+ }));
66
+ if (!conversion.isValid || !conversion.utilizedTracks.some((track) => track.isVideoTrack()))
67
+ throw new VideoPartError('no-encoder');
68
+ conversion.onProgress = (progress) => report(progress);
69
+ const abort = () => void conversion.cancel();
70
+ options.signal?.addEventListener('abort', abort, { once: true });
71
+ try {
72
+ await conversion.execute();
73
+ }
74
+ finally {
75
+ options.signal?.removeEventListener('abort', abort);
76
+ }
77
+ options.signal?.throwIfAborted();
78
+ const bytes = mp4.file();
79
+ if (bytes === null)
80
+ throw new VideoPartError('failed');
81
+ return { bytes, width: plan.width, height: plan.height, sound: audioOk && conversion.utilizedTracks.some((track) => track.isAudioTrack()) };
82
+ }
83
+ finally {
84
+ input.dispose();
85
+ }
86
+ }
87
+ /**
88
+ * Converts the part `start`–`end` of `file`: smaller at each try while the result is over the upload limit. Throws a
89
+ * {@link VideoPartError}, or the abort reason once `signal` aborts.
90
+ */
91
+ export async function convertVideoPart(file, options) {
92
+ const seconds = options.end - options.start;
93
+ for (let attempt = 0;; attempt++) {
94
+ const plan = videoEncodePlan(options.facts, seconds, attempt);
95
+ if (plan === null)
96
+ throw new VideoPartError('too-large');
97
+ if (attempt === 0 && !(await canConvertVideo(plan)))
98
+ throw new VideoPartError('no-encoder');
99
+ let part;
100
+ try {
101
+ part = await convertOnce(file, options, plan, (progress) => options.onProgress?.(progress));
102
+ }
103
+ catch (error) {
104
+ options.signal?.throwIfAborted();
105
+ throw error instanceof VideoPartError ? error : new VideoPartError('failed', error);
106
+ }
107
+ if (part.bytes.byteLength <= MAX_VIDEO_UPLOAD_BYTES) {
108
+ options.onProgress?.(1);
109
+ return part;
110
+ }
111
+ }
112
+ }
@@ -0,0 +1,25 @@
1
+ /** What reading and converting a picked video can end in, shared by the page and the worker that does the work. */
2
+ /** Why a video part could not be had: not a video, one this browser cannot read or write, or too large even when made smaller. */
3
+ export type VideoPartProblem = 'not-video' | 'unreadable' | 'no-encoder' | 'too-large' | 'failed';
4
+ export declare const VIDEO_PART_PROBLEMS: readonly VideoPartProblem[];
5
+ export declare class VideoPartError extends Error {
6
+ readonly problem: VideoPartProblem;
7
+ constructor(problem: VideoPartProblem, cause?: unknown);
8
+ }
9
+ /** What reading a video file found. */
10
+ export interface VideoFileFacts {
11
+ duration: number;
12
+ width: number;
13
+ height: number;
14
+ /** Frames a second, when the file says. */
15
+ fps: number | null;
16
+ hasSound: boolean;
17
+ }
18
+ /** The converted part. */
19
+ export interface VideoPart {
20
+ bytes: Uint8Array<ArrayBuffer>;
21
+ width: number;
22
+ height: number;
23
+ /** The part keeps the file's sound (false when the file has none, or this browser could not write it). */
24
+ sound: boolean;
25
+ }
@@ -0,0 +1,10 @@
1
+ /** What reading and converting a picked video can end in, shared by the page and the worker that does the work. */
2
+ export const VIDEO_PART_PROBLEMS = ['not-video', 'unreadable', 'no-encoder', 'too-large', 'failed'];
3
+ export class VideoPartError extends Error {
4
+ problem;
5
+ constructor(problem, cause) {
6
+ super(`video part: ${problem}`, cause === undefined ? undefined : { cause });
7
+ this.name = 'VideoPartError';
8
+ this.problem = problem;
9
+ }
10
+ }
@@ -0,0 +1,2 @@
1
+ /** The video worker: reads or converts the file it is sent, then answers once. */
2
+ export {};
@@ -0,0 +1,24 @@
1
+ /** The video worker: reads or converts the file it is sent, then answers once. */
2
+ import { convertVideoPart, readVideoFile } from "./part.js";
3
+ import { VideoPartError } from "./problem.js";
4
+ const scope = self;
5
+ const answer = (message, transfer = []) => scope.postMessage(message, { transfer });
6
+ async function run(job) {
7
+ try {
8
+ if (job.job === 'read') {
9
+ answer({ kind: 'read', facts: await readVideoFile(job.file) });
10
+ return;
11
+ }
12
+ const part = await convertVideoPart(job.file, {
13
+ start: job.start,
14
+ end: job.end,
15
+ facts: job.facts,
16
+ onProgress: (value) => answer({ kind: 'progress', value }),
17
+ });
18
+ answer({ kind: 'converted', bytes: part.bytes, width: part.width, height: part.height, sound: part.sound }, [part.bytes.buffer]);
19
+ }
20
+ catch (error) {
21
+ answer({ kind: 'failed', problem: error instanceof VideoPartError ? error.problem : 'failed' });
22
+ }
23
+ }
24
+ scope.onmessage = (event) => void run(event.data);
@@ -0,0 +1,46 @@
1
+ import type { ExportFormat, ExportProblem } from '@openartifactsai/motion-core';
2
+ import type { FrameSource } from './frame-source.js';
3
+ import type { MovChoices } from './mov/plan.js';
4
+ import type { GifMeasureTools } from './gif/estimator.js';
5
+ import type { SurfaceMaker } from './gif/surface.js';
6
+ import type { GifPresetName, VideoSettings } from './plan.js';
7
+ import type { RasterCache } from './raster/host.js';
8
+ import type { ExportEstimate, ExportRunOptions, RenderedFile } from './types.js';
9
+ import type { EncoderMemory } from './video/attempts.js';
10
+ import type { VideoFormat } from './video/format.js';
11
+ import type { EncodeTryListener } from './visibility.js';
12
+ export interface ExportEngineOptions {
13
+ source: FrameSource;
14
+ /** The raster frame's script (`virtual:motion-raster-frame`, or `buildRasterFrame()`). */
15
+ rasterScript: string;
16
+ document?: Document;
17
+ /** Which encoder set-up worked last; kept by the editor across exports. */
18
+ memory?: EncoderMemory;
19
+ onTry?: EncodeTryListener;
20
+ rasterCache?: RasterCache;
21
+ surface?: SurfaceMaker;
22
+ /** Where a MOV's frames are drawn and read back with their alpha. */
23
+ alphaSurface?: SurfaceMaker;
24
+ gifTools?: GifMeasureTools;
25
+ }
26
+ /** A finished video or GIF, with what to tell the agent about it. */
27
+ export interface ExportResult extends RenderedFile {
28
+ format: ExportFormat;
29
+ /** Frames that had to be held; null when every frame was drawn. */
30
+ problem: ExportProblem | null;
31
+ }
32
+ export interface ExportEngine {
33
+ /** The format a video with these settings would be; null when this browser cannot make one. */
34
+ videoFormat(settings: Partial<VideoSettings>): Promise<VideoFormat | null>;
35
+ estimateVideo(settings: Partial<VideoSettings>, signal?: AbortSignal): Promise<ExportEstimate | null>;
36
+ estimateGif(preset: GifPresetName, signal?: AbortSignal): Promise<ExportEstimate | null>;
37
+ estimateMov(choices: Partial<MovChoices>, signal?: AbortSignal): Promise<ExportEstimate | null>;
38
+ /** Rejects with the error that stopped it; `failedProblem(error)` says whether the film was to blame. */
39
+ exportVideo(settings: Partial<VideoSettings>, options?: ExportRunOptions): Promise<ExportResult>;
40
+ exportGif(preset: GifPresetName, options?: ExportRunOptions): Promise<ExportResult>;
41
+ /** A QuickTime Animation movie that keeps the film's transparent background, with its sound as PCM. */
42
+ exportMov(choices: Partial<MovChoices>, options?: ExportRunOptions): Promise<ExportResult>;
43
+ dispose(): void;
44
+ }
45
+ /** Makes videos, GIFs and MOVs of the film a FrameSource draws. */
46
+ export declare function createExportEngine(options: ExportEngineOptions): ExportEngine;
package/src/engine.js ADDED
@@ -0,0 +1,225 @@
1
+ import { EXPORT_SETTINGS, playSeconds } from '@openartifactsai/motion-core';
2
+ import { renderFilmAudio } from '@openartifactsai/motion-audio';
3
+ import { ExportCheckError, VideoUnsupportedError, exportAbortError, isAborted } from "./errors.js";
4
+ import { VIDEO_PROBE_FRACTIONS, gifSeconds, probeFrames, probeGif, videoSeconds } from "./estimate.js";
5
+ import { exportFilename } from "./filename.js";
6
+ import { encodeGif } from "./gif/encode.js";
7
+ import { createGifEstimator } from "./gif/estimator.js";
8
+ import { encodeMov } from "./mov/encode.js";
9
+ import { createMovProbe, movSeconds } from "./mov/estimate.js";
10
+ import { planMovFrames } from "./mov/plan.js";
11
+ import { createAlphaSurface } from "./mov/surface.js";
12
+ import { estimateVideoBytes, planGifFrames, resolveGifPreset, resolveVideoSettings } from "./plan.js";
13
+ import { gifExportFormat, heldProblem, videoExportFormat } from "./problems.js";
14
+ import { createRasterHost } from "./raster/host.js";
15
+ import { stageExportFrame } from "./stage-frame.js";
16
+ import { newEncoderMemory } from "./video/attempts.js";
17
+ import { encodeVideo } from "./video/encode.js";
18
+ import { planVideoExport } from "./video/format.js";
19
+ import { formatLabels, words } from "./words.js";
20
+ const audible = (sound) => sound !== null && (sound.score.sounds.length > 0 || (sound.speech?.clips.length ?? 0) > 0 || (sound.footage?.pieces.length ?? 0) > 0);
21
+ const withSignal = (signal) => (signal !== undefined ? { signal } : {});
22
+ /** Makes videos, GIFs and MOVs of the film a FrameSource draws. */
23
+ export function createExportEngine(options) {
24
+ const { source } = options;
25
+ const page = options.document ?? document;
26
+ const memory = options.memory ?? newEncoderMemory();
27
+ const plans = new Map();
28
+ const rasters = new Set();
29
+ const facts = () => {
30
+ const known = source.facts();
31
+ if (known === null)
32
+ throw new ExportCheckError(words.noFilm, 'no_film');
33
+ return known;
34
+ };
35
+ const planFor = (film, settings) => {
36
+ const resolved = resolveVideoSettings(settings, film);
37
+ const key = JSON.stringify([film.width, film.height, film.fps, film.duration, resolved]);
38
+ let plan = plans.get(key);
39
+ if (plan === undefined) {
40
+ plan = planVideoExport(film, resolved).then((made) => (made !== null && EXPORT_SETTINGS.withoutH264 === 'none' && made.format.videoCodec !== 'avc' ? null : made));
41
+ plan.catch(() => plans.delete(key));
42
+ plans.set(key, plan);
43
+ }
44
+ return plan;
45
+ };
46
+ /** Runs `work` with the stage lent to the export and a raster frame of its own; both are given back after. */
47
+ async function withStage(work) {
48
+ const release = source.borrow();
49
+ const raster = createRasterHost({
50
+ script: options.rasterScript,
51
+ document: page,
52
+ clippedTextWaitMs: () => source.clippedTextWaitMs(),
53
+ ...(options.rasterCache !== undefined ? { cache: options.rasterCache } : {}),
54
+ });
55
+ rasters.add(raster);
56
+ try {
57
+ return await work(stageExportFrame(source, raster));
58
+ }
59
+ finally {
60
+ rasters.delete(raster);
61
+ raster.dispose();
62
+ await release();
63
+ }
64
+ }
65
+ return {
66
+ async videoFormat(settings) {
67
+ const film = source.facts();
68
+ return film === null ? null : ((await planFor(film, settings))?.format ?? null);
69
+ },
70
+ async estimateVideo(settings, signal) {
71
+ const film = facts();
72
+ const plan = await planFor(film, settings);
73
+ if (plan === null || isAborted(signal))
74
+ return null;
75
+ const withAudio = plan.format.audioCodec !== null && audible(source.sound());
76
+ const scale = settings.supersample === true ? 2 : 1;
77
+ const size = { width: plan.width * scale, height: plan.height * scale };
78
+ const msPerFrame = await withStage((frame) => probeFrames(frame, VIDEO_PROBE_FRACTIONS.map((fraction) => playSeconds(film.duration * fraction)), size, signal));
79
+ if (isAborted(signal))
80
+ return null;
81
+ return {
82
+ bytes: estimateVideoBytes(plan, film.duration, withAudio),
83
+ seconds: videoSeconds(plan.frames, msPerFrame, film.duration, withAudio),
84
+ label: plan.format.label,
85
+ };
86
+ },
87
+ async estimateGif(presetName, signal) {
88
+ const film = facts();
89
+ const preset = resolveGifPreset(presetName);
90
+ const plan = planGifFrames(film, preset);
91
+ const estimator = createGifEstimator(plan, options.surface, options.gifTools);
92
+ const probed = await withStage((frame) => probeGif(frame, plan, preset, film.duration, estimator, signal));
93
+ if (probed === null || isAborted(signal))
94
+ return null;
95
+ return {
96
+ bytes: probed.measure.bytes,
97
+ seconds: gifSeconds(plan.frames, probed.frameMs, probed.measure.msPerFrame),
98
+ label: formatLabels.gif,
99
+ ...(probed.measure.atLeast === true ? { atLeast: true } : {}),
100
+ };
101
+ },
102
+ async estimateMov(choices, signal) {
103
+ const film = facts();
104
+ const plan = planMovFrames(film, choices);
105
+ const withAudio = audible(source.sound());
106
+ const scale = choices.supersample === true ? 2 : 1;
107
+ const probe = createMovProbe(plan, film.duration, (options.alphaSurface ?? createAlphaSurface)(plan));
108
+ try {
109
+ const frameMs = await withStage((frame) => probeFrames(frame, VIDEO_PROBE_FRACTIONS.map((fraction) => playSeconds(film.duration * fraction)), { width: plan.width * scale, height: plan.height * scale }, signal, (bitmap) => probe.add(bitmap)));
110
+ if (isAborted(signal))
111
+ return null;
112
+ const measure = probe.measure(withAudio);
113
+ return {
114
+ bytes: measure.bytes,
115
+ seconds: movSeconds(plan.frames, frameMs, measure.encodeMs, film.duration, withAudio),
116
+ label: formatLabels.mov,
117
+ mov: { bytesPerSecond: measure.bytesPerSecond },
118
+ };
119
+ }
120
+ finally {
121
+ probe.dispose();
122
+ }
123
+ },
124
+ async exportVideo(settings, run = {}) {
125
+ const film = facts();
126
+ const plan = await planFor(film, settings);
127
+ if (plan === null)
128
+ throw new VideoUnsupportedError();
129
+ const sound = source.sound();
130
+ let audio = null;
131
+ if (plan.format.audioCodec !== null && audible(sound)) {
132
+ run.onProgress?.({ done: 0, total: plan.frames, phase: 'audio' });
133
+ audio = (await renderFilmAudio(sound)).buffer;
134
+ }
135
+ if (isAborted(run.signal))
136
+ throw exportAbortError();
137
+ const made = await withStage((frame) => encodeVideo({
138
+ plan,
139
+ frame,
140
+ audio,
141
+ supersample: settings.supersample === true,
142
+ firstPacketMs: EXPORT_SETTINGS.firstPacketS * 1000,
143
+ nextOnBreak: EXPORT_SETTINGS.onBreak === 'next',
144
+ rangeFromStream: EXPORT_SETTINGS.rangeLabel === 'stream',
145
+ lastInSoftware: EXPORT_SETTINGS.lastTry === 'software',
146
+ stalls: EXPORT_SETTINGS.stallsInView,
147
+ page,
148
+ memory,
149
+ ...(options.onTry !== undefined ? { onTry: options.onTry } : {}),
150
+ ...(run.onProgress !== undefined ? { onProgress: run.onProgress } : {}),
151
+ ...withSignal(run.signal),
152
+ }));
153
+ return {
154
+ blob: new Blob([made.bytes], { type: 'video/mp4' }),
155
+ filename: exportFilename(film.title, 'mp4'),
156
+ mime: 'video/mp4',
157
+ held: made.held,
158
+ ms: made.ms,
159
+ format: videoExportFormat(plan),
160
+ problem: heldProblem(made.held, true),
161
+ };
162
+ },
163
+ async exportGif(presetName, run = {}) {
164
+ const film = facts();
165
+ const preset = resolveGifPreset(presetName);
166
+ const plan = planGifFrames(film, preset);
167
+ const made = await withStage((frame) => encodeGif({
168
+ plan,
169
+ duration: film.duration,
170
+ frame,
171
+ maxBytes: preset.maxBytes,
172
+ page,
173
+ ...(options.surface !== undefined ? { surface: options.surface } : {}),
174
+ ...(run.onProgress !== undefined ? { onProgress: run.onProgress } : {}),
175
+ ...withSignal(run.signal),
176
+ }));
177
+ return {
178
+ blob: new Blob([made.bytes.slice()], { type: 'image/gif' }),
179
+ filename: exportFilename(film.title, 'gif'),
180
+ mime: 'image/gif',
181
+ held: made.held,
182
+ ms: made.ms,
183
+ format: gifExportFormat(plan),
184
+ problem: heldProblem(made.held, true),
185
+ };
186
+ },
187
+ async exportMov(choices, run = {}) {
188
+ const film = facts();
189
+ const plan = planMovFrames(film, choices);
190
+ const sound = source.sound();
191
+ let audio = null;
192
+ if (audible(sound)) {
193
+ run.onProgress?.({ done: 0, total: plan.frames, phase: 'audio' });
194
+ audio = (await renderFilmAudio(sound)).buffer;
195
+ }
196
+ if (isAborted(run.signal))
197
+ throw exportAbortError();
198
+ const made = await withStage((frame) => encodeMov({
199
+ plan,
200
+ frame,
201
+ audio,
202
+ supersample: choices.supersample === true,
203
+ page,
204
+ ...(options.alphaSurface !== undefined ? { surface: options.alphaSurface } : {}),
205
+ ...(run.onProgress !== undefined ? { onProgress: run.onProgress } : {}),
206
+ ...withSignal(run.signal),
207
+ }));
208
+ return {
209
+ blob: made.blob,
210
+ filename: exportFilename(film.title, 'mov'),
211
+ mime: 'video/quicktime',
212
+ held: made.held,
213
+ ms: made.ms,
214
+ format: videoExportFormat(plan),
215
+ problem: heldProblem(made.held, true),
216
+ };
217
+ },
218
+ dispose() {
219
+ for (const raster of rasters)
220
+ raster.dispose();
221
+ rasters.clear();
222
+ plans.clear();
223
+ },
224
+ };
225
+ }
@@ -0,0 +1,78 @@
1
+ import type { PlaySeconds } from '@openartifactsai/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 browser could not hold the MOV being made: it ran out of memory for the frames or the file. */
62
+ export declare class MovMemoryError extends Error {
63
+ name: string;
64
+ constructor(cause: unknown);
65
+ }
66
+ export type SourceRefusalCode = 'too_large' | 'unreadable';
67
+ /** The source ZIP or the standalone page could not be made. */
68
+ export declare class SourceExportError extends Error {
69
+ name: string;
70
+ readonly code: SourceRefusalCode;
71
+ constructor(message: string, code: SourceRefusalCode);
72
+ }
73
+ export declare const BYTES_PER_MEBIBYTE = 1048576;
74
+ export declare const wholeMegabytes: (bytes: number) => number;
75
+ export declare const exportAbortError: () => DOMException;
76
+ export declare const isAbortError: (error: unknown) => boolean;
77
+ export declare const isAborted: (signal: AbortSignal | undefined) => boolean;
78
+ export declare const asError: (error: unknown) => Error;
package/src/errors.js ADDED
@@ -0,0 +1,102 @@
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 browser could not hold the MOV being made: it ran out of memory for the frames or the file. */
82
+ export class MovMemoryError extends Error {
83
+ name = 'MovMemoryError';
84
+ constructor(cause) {
85
+ super(words.movOutOfMemory, { cause });
86
+ }
87
+ }
88
+ /** The source ZIP or the standalone page could not be made. */
89
+ export class SourceExportError extends Error {
90
+ name = 'SourceExportError';
91
+ code;
92
+ constructor(message, code) {
93
+ super(message);
94
+ this.code = code;
95
+ }
96
+ }
97
+ export const BYTES_PER_MEBIBYTE = 1_048_576;
98
+ export const wholeMegabytes = (bytes) => Math.floor(bytes / BYTES_PER_MEBIBYTE);
99
+ export const exportAbortError = () => new DOMException(words.exportCancelled, 'AbortError');
100
+ export const isAbortError = (error) => error instanceof DOMException && error.name === 'AbortError';
101
+ export const isAborted = (signal) => signal !== undefined && signal.aborted;
102
+ export const asError = (error) => (error instanceof Error ? error : new Error(String(error)));
@@ -0,0 +1,27 @@
1
+ import type { PlaySeconds } from '@openartifactsai/motion-core';
2
+ import type { GifEstimator, GifMeasure } from './gif/estimator.js';
3
+ import type { GifPlan, GifPreset } from './plan.js';
4
+ import type { ExportDimensions, ExportFrame } from './types.js';
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>;