@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
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { buildGifPalette, createGifEncoder } from '@openartifactsai/wasm-motion';
|
|
2
|
+
import { createOpaqueSurface } from "./surface.js";
|
|
3
|
+
/** Where in the film a GIF estimate looks: each a pair of frames, one frame apart. */
|
|
4
|
+
export const GIF_PROBE_FRACTIONS = [0.1, 0.5, 0.85];
|
|
5
|
+
/** Where it looks next when a pair rests (the two frames are the same), for as long as the preset allows. */
|
|
6
|
+
export const GIF_EXTRA_PROBE_FRACTIONS = [0.2803, 0.6623, 0.4262, 0.718, 0.1902, 0.5721, 0.9541, 0.3361, 0.0443];
|
|
7
|
+
export const DEFAULT_GIF_MEASURE_TOOLS = {
|
|
8
|
+
palette: (frames) => buildGifPalette(frames),
|
|
9
|
+
encoder: (size, palette) => {
|
|
10
|
+
const encoder = createGifEncoder({ width: size.width, height: size.height, palette });
|
|
11
|
+
return { add: (pixels, delayCs) => encoder.add(pixels, delayCs), dispose: () => encoder.dispose() };
|
|
12
|
+
},
|
|
13
|
+
yieldTask: () => new Promise((resolve) => setTimeout(resolve, 0)),
|
|
14
|
+
};
|
|
15
|
+
function equalPixels(left, right) {
|
|
16
|
+
if (left.length !== right.length)
|
|
17
|
+
return false;
|
|
18
|
+
const a = new Uint32Array(left.buffer, left.byteOffset, left.length >> 2);
|
|
19
|
+
const b = new Uint32Array(right.buffer, right.byteOffset, right.length >> 2);
|
|
20
|
+
for (let index = 0; index < a.length; index++)
|
|
21
|
+
if (a[index] !== b[index])
|
|
22
|
+
return false;
|
|
23
|
+
return true;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Guesses a GIF's size from pairs of frames: the largest first frame, plus the average change a frame brings times the
|
|
27
|
+
* frames after the first.
|
|
28
|
+
*/
|
|
29
|
+
export function createGifEstimator(plan, surface = createOpaqueSurface, tools = DEFAULT_GIF_MEASURE_TOOLS) {
|
|
30
|
+
const target = surface(plan);
|
|
31
|
+
const samples = new Map();
|
|
32
|
+
const ordered = () => [...samples].sort(([a], [b]) => a - b).map(([, pair]) => pair);
|
|
33
|
+
const paired = () => ordered().flatMap(([first, second]) => (first !== undefined && second !== undefined ? [[first, second]] : []));
|
|
34
|
+
return {
|
|
35
|
+
add(image, probe, side) {
|
|
36
|
+
target.paint(image);
|
|
37
|
+
const pair = samples.get(probe) ?? [undefined, undefined];
|
|
38
|
+
pair[side] = target.pixels();
|
|
39
|
+
samples.set(probe, pair);
|
|
40
|
+
},
|
|
41
|
+
rests: () => paired().some(([first, second]) => equalPixels(first, second)),
|
|
42
|
+
async measure(signal) {
|
|
43
|
+
const pairs = paired();
|
|
44
|
+
if (pairs.length === 0)
|
|
45
|
+
return null;
|
|
46
|
+
const palette = tools.palette(ordered().flatMap((pair) => pair.filter((pixels) => pixels !== undefined)));
|
|
47
|
+
const allFirsts = tools.encoder(plan, palette);
|
|
48
|
+
let largestFirst = 0;
|
|
49
|
+
let seconds = 0;
|
|
50
|
+
let firsts = 0;
|
|
51
|
+
let encodeMs = 0;
|
|
52
|
+
try {
|
|
53
|
+
let startedAt = performance.now();
|
|
54
|
+
for (const [first, second] of pairs) {
|
|
55
|
+
const one = tools.encoder(plan, palette);
|
|
56
|
+
try {
|
|
57
|
+
largestFirst = Math.max(largestFirst, one.add(first, plan.delayCs));
|
|
58
|
+
seconds += one.add(second, plan.delayCs);
|
|
59
|
+
}
|
|
60
|
+
finally {
|
|
61
|
+
one.dispose();
|
|
62
|
+
}
|
|
63
|
+
encodeMs += performance.now() - startedAt;
|
|
64
|
+
firsts += allFirsts.add(first, plan.delayCs);
|
|
65
|
+
await tools.yieldTask();
|
|
66
|
+
if (signal?.aborted === true)
|
|
67
|
+
return null;
|
|
68
|
+
startedAt = performance.now();
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
finally {
|
|
72
|
+
allFirsts.dispose();
|
|
73
|
+
}
|
|
74
|
+
return gifMeasureOf({ largestFirst, seconds, firsts, encodeMs, pairs: pairs.length, frames: plan.frames });
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
export function gifMeasureOf(input) {
|
|
79
|
+
const msPerFrame = input.encodeMs / (input.pairs * 2);
|
|
80
|
+
const guess = Math.round(input.largestFirst + (input.seconds / input.pairs) * (input.frames - 1));
|
|
81
|
+
return input.firsts > guess && input.pairs <= input.frames ? { bytes: input.firsts, msPerFrame, atLeast: true } : { bytes: guess, msPerFrame };
|
|
82
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { ExportDimensions } from '../types.js';
|
|
2
|
+
/** Where a GIF's frames are drawn on black and read back as RGBA. */
|
|
3
|
+
export interface ExportSurface {
|
|
4
|
+
paint(image: CanvasImageSource | null): void;
|
|
5
|
+
pixels(): Uint8ClampedArray<ArrayBuffer>;
|
|
6
|
+
}
|
|
7
|
+
export type SurfaceMaker = (size: ExportDimensions) => ExportSurface;
|
|
8
|
+
export declare function createOpaqueSurface(size: ExportDimensions): ExportSurface;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { ExportCheckError } from "../errors.js";
|
|
2
|
+
import { words } from "../words.js";
|
|
3
|
+
export function createOpaqueSurface(size) {
|
|
4
|
+
const canvas = document.createElement('canvas');
|
|
5
|
+
canvas.width = size.width;
|
|
6
|
+
canvas.height = size.height;
|
|
7
|
+
const context = canvas.getContext('2d', { alpha: false, willReadFrequently: true });
|
|
8
|
+
if (context === null)
|
|
9
|
+
throw new ExportCheckError(words.noCanvas, 'no_canvas');
|
|
10
|
+
context.imageSmoothingQuality = 'high';
|
|
11
|
+
context.fillStyle = '#000';
|
|
12
|
+
return {
|
|
13
|
+
paint: (image) => {
|
|
14
|
+
context.fillRect(0, 0, size.width, size.height);
|
|
15
|
+
if (image !== null)
|
|
16
|
+
context.drawImage(image, 0, 0, size.width, size.height);
|
|
17
|
+
},
|
|
18
|
+
pixels: () => context.getImageData(0, 0, size.width, size.height).data,
|
|
19
|
+
};
|
|
20
|
+
}
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
export { createExportEngine } from './engine.js';
|
|
2
|
+
export type { ExportEngine, ExportEngineOptions, ExportResult } from './engine.js';
|
|
3
|
+
export type { FilmFacts, FrameRequest, FrameSource, StageFrame } from './frame-source.js';
|
|
4
|
+
export type { ExportDimensions, ExportEstimate, ExportFrame, ExportPhase, ExportProgress, ExportRunOptions, ExportedFile, FramePlan, HeldFrames, RenderedFile, } from './types.js';
|
|
5
|
+
export { EXPORT_AUDIO_BITRATE, GIF_HEAVY_BYTES, MAX_EXPORT_FPS, VIDEO_FRAME_RATES, VIDEO_HEIGHTS, chooseVideoBitrate, estimateVideoBytes, fitExportDimensions, isVideoHeight, planGifFrames, planVideoFrames, resolveGifPreset, resolveVideoSettings, } from './plan.js';
|
|
6
|
+
export type { GifPlan, GifPreset, GifPresetName, VideoFramePlan, VideoHeight, VideoQuality, VideoSettings } from './plan.js';
|
|
7
|
+
export { VideoPartError } from './clip/problem.js';
|
|
8
|
+
export type { VideoFileFacts, VideoPart, VideoPartProblem } from './clip/problem.js';
|
|
9
|
+
export { convertVideoPart, readVideoFile } from './clip/in-worker.js';
|
|
10
|
+
export type { StartVideoWorker, VideoPartOptions } from './clip/in-worker.js';
|
|
11
|
+
export { describeVideoFormat } from './video/format.js';
|
|
12
|
+
export type { ExportAudioCodec, ExportVideoCodec, VideoFormat, VideoPlan } from './video/format.js';
|
|
13
|
+
export { newEncoderMemory } from './video/attempts.js';
|
|
14
|
+
export type { EncoderMemory } from './video/attempts.js';
|
|
15
|
+
export type { EncodeTryListener, EncodeTryOutcome } from './visibility.js';
|
|
16
|
+
export { gifSeconds, videoSeconds } from './estimate.js';
|
|
17
|
+
export { MOV_SETTINGS, STEREO_PCM_BYTES_PER_SECOND, estimateMovHeaderBytes, planMovFrames, storesWholeFrames, } from './mov/plan.js';
|
|
18
|
+
export type { MovChoices, MovPlan, MovSettings } from './mov/plan.js';
|
|
19
|
+
export { movSeconds } from './mov/estimate.js';
|
|
20
|
+
export { failedProblem, gifExportFormat, heldProblem, videoExportFormat } from './problems.js';
|
|
21
|
+
export { BYTES_PER_MEBIBYTE, EncoderFailure, EncoderSilentError, ExportCheckError, FrameRenderError, FrameStallError, GifTooLargeError, MovMemoryError, SkippedVideoFramesError, SourceExportError, VideoUnsupportedError, isAbortError, } from './errors.js';
|
|
22
|
+
export type { ExportCheckCode, SourceRefusalCode } from './errors.js';
|
|
23
|
+
export { exportFileStem, exportFilename } from './filename.js';
|
|
24
|
+
export { createRasterHost } from './raster/host.js';
|
|
25
|
+
export type { RasterCache, RasterHost, RasterHostOptions } from './raster/host.js';
|
|
26
|
+
export { STANDALONE_MAX_BYTES, standaloneFile, standaloneFilm, standaloneHtml } from './standalone/html.js';
|
|
27
|
+
export type { FontLicenceNotice, StandaloneInput } from './standalone/html.js';
|
|
28
|
+
export { SOURCE_MAX_BYTES, buildSourceZip } from './source/zip.js';
|
|
29
|
+
export type { SourceZip, SourceZipInput } from './source/zip.js';
|
|
30
|
+
export { captionsFile, captionsTrackNames } from './captions-file.js';
|
|
31
|
+
export type { CaptionsTrack } from './captions-file.js';
|
|
32
|
+
export { SCORE_MIDI_FILE, sourceFolder } from './source/layout.js';
|
|
33
|
+
export type { SourceAsset, SourceFolder, SourceFolderInput, SourceFont, SourceModule } from './source/layout.js';
|
|
34
|
+
export { words as exportWords, formatLabels } from './words.js';
|
package/src/index.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export { createExportEngine } from "./engine.js";
|
|
2
|
+
export { EXPORT_AUDIO_BITRATE, GIF_HEAVY_BYTES, MAX_EXPORT_FPS, VIDEO_FRAME_RATES, VIDEO_HEIGHTS, chooseVideoBitrate, estimateVideoBytes, fitExportDimensions, isVideoHeight, planGifFrames, planVideoFrames, resolveGifPreset, resolveVideoSettings, } from "./plan.js";
|
|
3
|
+
export { VideoPartError } from "./clip/problem.js";
|
|
4
|
+
export { convertVideoPart, readVideoFile } from "./clip/in-worker.js";
|
|
5
|
+
export { describeVideoFormat } from "./video/format.js";
|
|
6
|
+
export { newEncoderMemory } from "./video/attempts.js";
|
|
7
|
+
export { gifSeconds, videoSeconds } from "./estimate.js";
|
|
8
|
+
export { MOV_SETTINGS, STEREO_PCM_BYTES_PER_SECOND, estimateMovHeaderBytes, planMovFrames, storesWholeFrames, } from "./mov/plan.js";
|
|
9
|
+
export { movSeconds } from "./mov/estimate.js";
|
|
10
|
+
export { failedProblem, gifExportFormat, heldProblem, videoExportFormat } from "./problems.js";
|
|
11
|
+
export { BYTES_PER_MEBIBYTE, EncoderFailure, EncoderSilentError, ExportCheckError, FrameRenderError, FrameStallError, GifTooLargeError, MovMemoryError, SkippedVideoFramesError, SourceExportError, VideoUnsupportedError, isAbortError, } from "./errors.js";
|
|
12
|
+
export { exportFileStem, exportFilename } from "./filename.js";
|
|
13
|
+
export { createRasterHost } from "./raster/host.js";
|
|
14
|
+
export { STANDALONE_MAX_BYTES, standaloneFile, standaloneFilm, standaloneHtml } from "./standalone/html.js";
|
|
15
|
+
export { SOURCE_MAX_BYTES, buildSourceZip } from "./source/zip.js";
|
|
16
|
+
export { captionsFile, captionsTrackNames } from "./captions-file.js";
|
|
17
|
+
export { SCORE_MIDI_FILE, sourceFolder } from "./source/layout.js";
|
|
18
|
+
export { words as exportWords, formatLabels } from "./words.js";
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { createMovWriter } from '@openartifactsai/wasm-motion';
|
|
2
|
+
import type { MovSound } from '@openartifactsai/wasm-motion';
|
|
3
|
+
import type { SurfaceMaker } from '../gif/surface.js';
|
|
4
|
+
import type { ExportFrame, ExportProgress, HeldFrames } from '../types.js';
|
|
5
|
+
import type { MovPlan, MovSettings } from './plan.js';
|
|
6
|
+
export interface MovEncodeOptions {
|
|
7
|
+
plan: MovPlan;
|
|
8
|
+
frame: ExportFrame;
|
|
9
|
+
/** The film's sound, rendered; null for a silent movie. */
|
|
10
|
+
audio: AudioBuffer | null;
|
|
11
|
+
supersample: boolean;
|
|
12
|
+
settings?: MovSettings;
|
|
13
|
+
surface?: SurfaceMaker;
|
|
14
|
+
writer?: typeof createMovWriter;
|
|
15
|
+
page?: Document;
|
|
16
|
+
onProgress?: (progress: ExportProgress) => void;
|
|
17
|
+
signal?: AbortSignal;
|
|
18
|
+
}
|
|
19
|
+
export interface EncodedMov {
|
|
20
|
+
blob: Blob;
|
|
21
|
+
held: HeldFrames;
|
|
22
|
+
ms: number;
|
|
23
|
+
}
|
|
24
|
+
/** The sound as the interleaved 16-bit PCM a MOV stores. */
|
|
25
|
+
export declare function movSound(audio: AudioBuffer): MovSound;
|
|
26
|
+
/** What the browser throws when it has no memory left for a buffer, or could not keep a file it was handed. */
|
|
27
|
+
export declare const isOutOfMemory: (error: unknown) => boolean;
|
|
28
|
+
/**
|
|
29
|
+
* Draws every frame on a clear surface into a QuickTime Animation movie with the sound. A movie too big for the
|
|
30
|
+
* browser to hold stops with a {@link MovMemoryError}, its bytes let go.
|
|
31
|
+
*/
|
|
32
|
+
export declare function encodeMov(options: MovEncodeOptions): Promise<EncodedMov>;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { encodePcmWave } from '@openartifactsai/motion-audio';
|
|
2
|
+
import { createMovWriter } from '@openartifactsai/wasm-motion';
|
|
3
|
+
import { MovMemoryError } from "../errors.js";
|
|
4
|
+
import { renderExportFrames } from "../frames.js";
|
|
5
|
+
import { MOV_SETTINGS } from "./plan.js";
|
|
6
|
+
import { createAlphaSurface } from "./surface.js";
|
|
7
|
+
const WAVE_HEADER_BYTES = 44;
|
|
8
|
+
/** The sound as the interleaved 16-bit PCM a MOV stores. */
|
|
9
|
+
export function movSound(audio) {
|
|
10
|
+
return { pcm: encodePcmWave(audio).subarray(WAVE_HEADER_BYTES), sampleRate: audio.sampleRate, channels: audio.numberOfChannels };
|
|
11
|
+
}
|
|
12
|
+
/** What the browser throws when it has no memory left for a buffer, or could not keep a file it was handed. */
|
|
13
|
+
export const isOutOfMemory = (error) => error instanceof RangeError || (error instanceof DOMException && error.name === 'NotReadableError');
|
|
14
|
+
const holding = (make) => {
|
|
15
|
+
try {
|
|
16
|
+
return make();
|
|
17
|
+
}
|
|
18
|
+
catch (error) {
|
|
19
|
+
throw isOutOfMemory(error) ? new MovMemoryError(error) : error;
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
/** The movie as a file, read back at its end so a file the browser could not keep stops here, not in the download. */
|
|
23
|
+
async function movFile(parts) {
|
|
24
|
+
const blob = holding(() => new Blob(parts, { type: 'video/quicktime' }));
|
|
25
|
+
try {
|
|
26
|
+
if (blob.size > 0)
|
|
27
|
+
await blob.slice(blob.size - 1).arrayBuffer();
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
throw isOutOfMemory(error) ? new MovMemoryError(error) : error;
|
|
31
|
+
}
|
|
32
|
+
return blob;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Draws every frame on a clear surface into a QuickTime Animation movie with the sound. A movie too big for the
|
|
36
|
+
* browser to hold stops with a {@link MovMemoryError}, its bytes let go.
|
|
37
|
+
*/
|
|
38
|
+
export async function encodeMov(options) {
|
|
39
|
+
const { plan, signal } = options;
|
|
40
|
+
const settings = options.settings ?? MOV_SETTINGS;
|
|
41
|
+
const startedAt = performance.now();
|
|
42
|
+
const audio = options.audio;
|
|
43
|
+
const sound = audio === null ? null : holding(() => movSound(audio));
|
|
44
|
+
const target = (options.surface ?? createAlphaSurface)(plan);
|
|
45
|
+
const writer = (options.writer ?? createMovWriter)({ width: plan.width, height: plan.height, fps: plan.fps, keyEvery: settings.keyEvery, repeats: settings.repeats });
|
|
46
|
+
try {
|
|
47
|
+
const held = await renderExportFrames({
|
|
48
|
+
plan,
|
|
49
|
+
frame: options.frame,
|
|
50
|
+
scale: options.supersample ? 2 : 1,
|
|
51
|
+
...(signal !== undefined ? { signal } : {}),
|
|
52
|
+
...(options.page !== undefined ? { page: options.page } : {}),
|
|
53
|
+
...(options.onProgress !== undefined ? { onProgress: options.onProgress } : {}),
|
|
54
|
+
draw: (bitmap, index) => {
|
|
55
|
+
if (bitmap !== null || index === 0)
|
|
56
|
+
target.paint(bitmap);
|
|
57
|
+
},
|
|
58
|
+
commit: () => {
|
|
59
|
+
holding(() => writer.add(target.pixels()));
|
|
60
|
+
},
|
|
61
|
+
});
|
|
62
|
+
options.onProgress?.({ done: plan.frames, total: plan.frames, phase: 'mux' });
|
|
63
|
+
const blob = await movFile(holding(() => writer.finish(sound)));
|
|
64
|
+
return { blob, held, ms: performance.now() - startedAt };
|
|
65
|
+
}
|
|
66
|
+
finally {
|
|
67
|
+
writer.dispose();
|
|
68
|
+
}
|
|
69
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { ExportSurface } from '../gif/surface.js';
|
|
2
|
+
import type { MovPlan } from './plan.js';
|
|
3
|
+
/** What a MOV of the film should come to, from the frames probed. */
|
|
4
|
+
export interface MovMeasure {
|
|
5
|
+
/** The movie's bytes if it moved all the way through. */
|
|
6
|
+
bytes: number;
|
|
7
|
+
/** Bytes a second of movement adds. */
|
|
8
|
+
bytesPerSecond: number;
|
|
9
|
+
/** Milliseconds encoding a frame takes. */
|
|
10
|
+
encodeMs: number;
|
|
11
|
+
}
|
|
12
|
+
/** Measures probed frames as a MOV stores a frame that moves: whole, every one a key frame. */
|
|
13
|
+
export interface MovProbe {
|
|
14
|
+
add(bitmap: ImageBitmap): void;
|
|
15
|
+
measure(withAudio: boolean): MovMeasure;
|
|
16
|
+
dispose(): void;
|
|
17
|
+
}
|
|
18
|
+
export declare function createMovProbe(plan: MovPlan, duration: number, surface: ExportSurface): MovProbe;
|
|
19
|
+
/** Seconds a MOV takes to make: its frames drawn and encoded, the sound, and a second to finish. */
|
|
20
|
+
export declare function movSeconds(frames: number, frameMs: number, encodeMs: number, duration: number, withAudio: boolean): number;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { createMovWriter } from '@openartifactsai/wasm-motion';
|
|
2
|
+
import { AUDIO_RENDER_MS_PER_SECOND } from "../estimate.js";
|
|
3
|
+
import { STEREO_PCM_BYTES_PER_SECOND, estimateMovHeaderBytes } from "./plan.js";
|
|
4
|
+
export function createMovProbe(plan, duration, surface) {
|
|
5
|
+
const writer = createMovWriter({ width: plan.width, height: plan.height, fps: plan.fps, keyEvery: 1, repeats: 'whole' });
|
|
6
|
+
let largest = 0;
|
|
7
|
+
let encodeMs = 0;
|
|
8
|
+
let probed = 0;
|
|
9
|
+
return {
|
|
10
|
+
add(bitmap) {
|
|
11
|
+
surface.paint(bitmap);
|
|
12
|
+
const pixels = surface.pixels();
|
|
13
|
+
const startedAt = performance.now();
|
|
14
|
+
largest = Math.max(largest, writer.add(pixels));
|
|
15
|
+
encodeMs += performance.now() - startedAt;
|
|
16
|
+
probed++;
|
|
17
|
+
},
|
|
18
|
+
measure(withAudio) {
|
|
19
|
+
const pcmBytes = withAudio ? Math.ceil(duration * STEREO_PCM_BYTES_PER_SECOND) : 0;
|
|
20
|
+
const bytesPerSecond = largest * plan.fps;
|
|
21
|
+
return {
|
|
22
|
+
bytes: Math.round(estimateMovHeaderBytes(plan.frames) + pcmBytes + bytesPerSecond * duration),
|
|
23
|
+
bytesPerSecond,
|
|
24
|
+
encodeMs: encodeMs / Math.max(1, probed),
|
|
25
|
+
};
|
|
26
|
+
},
|
|
27
|
+
dispose: () => writer.dispose(),
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
/** Seconds a MOV takes to make: its frames drawn and encoded, the sound, and a second to finish. */
|
|
31
|
+
export function movSeconds(frames, frameMs, encodeMs, duration, withAudio) {
|
|
32
|
+
return Math.round((frames * (frameMs + encodeMs) + (withAudio ? duration * AUDIO_RENDER_MS_PER_SECOND : 0)) / 1000 + 1);
|
|
33
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { MovRepeats } from '@openartifactsai/wasm-motion';
|
|
2
|
+
import type { FilmFacts } from '../frame-source.js';
|
|
3
|
+
import type { FramePlan } from '../types.js';
|
|
4
|
+
/** Bytes a second of 48 kHz stereo 16-bit PCM takes. */
|
|
5
|
+
export declare const STEREO_PCM_BYTES_PER_SECOND = 192000;
|
|
6
|
+
/** How a MOV is written: how often a frame is stored whole, and what a repeated frame becomes. */
|
|
7
|
+
export interface MovSettings {
|
|
8
|
+
keyEvery: number;
|
|
9
|
+
repeats: MovRepeats;
|
|
10
|
+
}
|
|
11
|
+
export declare const MOV_SETTINGS: Readonly<MovSettings>;
|
|
12
|
+
/** What a person picks for a MOV. */
|
|
13
|
+
export interface MovChoices {
|
|
14
|
+
/** The short side, in pixels: 720 or 1080. */
|
|
15
|
+
height: number;
|
|
16
|
+
fps?: number;
|
|
17
|
+
/** Draw each frame at twice the size and scale it down. */
|
|
18
|
+
supersample?: boolean;
|
|
19
|
+
}
|
|
20
|
+
export type MovPlan = FramePlan;
|
|
21
|
+
export declare function planMovFrames(film: Pick<FilmFacts, 'width' | 'height' | 'fps' | 'duration'>, choices: Partial<MovChoices>): MovPlan;
|
|
22
|
+
/** The most the movie's atoms take for `frames` frames, with room to spare. */
|
|
23
|
+
export declare const estimateMovHeaderBytes: (frames: number) => number;
|
|
24
|
+
/** Every frame is stored whole, so a still second costs as much as a moving one. */
|
|
25
|
+
export declare const storesWholeFrames: (settings?: Pick<MovSettings, "keyEvery" | "repeats">) => boolean;
|
package/src/mov/plan.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { MAX_EXPORT_FPS, fitExportDimensions, isVideoHeight } from "../plan.js";
|
|
2
|
+
/** Bytes a second of 48 kHz stereo 16-bit PCM takes. */
|
|
3
|
+
export const STEREO_PCM_BYTES_PER_SECOND = 192_000;
|
|
4
|
+
export const MOV_SETTINGS = { keyEvery: 1, repeats: 'unchanged' };
|
|
5
|
+
export function planMovFrames(film, choices) {
|
|
6
|
+
const size = fitExportDimensions(film, isVideoHeight(choices.height) ? choices.height : 1080);
|
|
7
|
+
const wanted = typeof choices.fps === 'number' && Number.isFinite(choices.fps) ? choices.fps : film.fps;
|
|
8
|
+
const fps = Math.max(1, Math.min(wanted, Math.max(1, film.fps), MAX_EXPORT_FPS));
|
|
9
|
+
return { ...size, fps, frames: Math.max(1, Math.round(film.duration * fps)) };
|
|
10
|
+
}
|
|
11
|
+
/** The most the movie's atoms take for `frames` frames, with room to spare. */
|
|
12
|
+
export const estimateMovHeaderBytes = (frames) => frames * 16 + 16_384;
|
|
13
|
+
/** Every frame is stored whole, so a still second costs as much as a moving one. */
|
|
14
|
+
export const storesWholeFrames = (settings = MOV_SETTINGS) => settings.repeats === 'whole' && settings.keyEvery === 1;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { ExportSurface } from '../gif/surface.js';
|
|
2
|
+
import type { ExportDimensions } from '../types.js';
|
|
3
|
+
/** Where a MOV's frames are drawn on nothing, so what the film leaves clear stays transparent. */
|
|
4
|
+
export declare function createAlphaSurface(size: ExportDimensions): ExportSurface;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { ExportCheckError } from "../errors.js";
|
|
2
|
+
import { words } from "../words.js";
|
|
3
|
+
/** Where a MOV's frames are drawn on nothing, so what the film leaves clear stays transparent. */
|
|
4
|
+
export function createAlphaSurface(size) {
|
|
5
|
+
const canvas = document.createElement('canvas');
|
|
6
|
+
canvas.width = size.width;
|
|
7
|
+
canvas.height = size.height;
|
|
8
|
+
const context = canvas.getContext('2d', { willReadFrequently: true });
|
|
9
|
+
if (context === null)
|
|
10
|
+
throw new ExportCheckError(words.noCanvas, 'no_canvas');
|
|
11
|
+
context.imageSmoothingQuality = 'high';
|
|
12
|
+
return {
|
|
13
|
+
paint: (image) => {
|
|
14
|
+
context.clearRect(0, 0, size.width, size.height);
|
|
15
|
+
if (image !== null)
|
|
16
|
+
context.drawImage(image, 0, 0, size.width, size.height);
|
|
17
|
+
},
|
|
18
|
+
pixels: () => context.getImageData(0, 0, size.width, size.height).data,
|
|
19
|
+
};
|
|
20
|
+
}
|
package/src/plan.d.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { FilmFacts } from './frame-source.js';
|
|
2
|
+
import type { ExportDimensions, FramePlan } from './types.js';
|
|
3
|
+
export declare const EXPORT_AUDIO_BITRATE = 128000;
|
|
4
|
+
export declare const VIDEO_HEIGHTS: readonly [720, 1080];
|
|
5
|
+
export type VideoHeight = (typeof VIDEO_HEIGHTS)[number];
|
|
6
|
+
export declare const VIDEO_FRAME_RATES: readonly [24, 30, 60];
|
|
7
|
+
export declare const MAX_EXPORT_FPS = 120;
|
|
8
|
+
export type VideoQuality = 'low' | 'medium' | 'high';
|
|
9
|
+
/** What a person picks for a video. */
|
|
10
|
+
export interface VideoSettings {
|
|
11
|
+
/** The short side, in pixels. */
|
|
12
|
+
height: number;
|
|
13
|
+
fps?: number;
|
|
14
|
+
quality?: VideoQuality;
|
|
15
|
+
maxVideoBitrate?: number;
|
|
16
|
+
/** Draw each frame at twice the size and scale it down. */
|
|
17
|
+
supersample?: boolean;
|
|
18
|
+
}
|
|
19
|
+
export interface VideoFramePlan extends FramePlan {
|
|
20
|
+
videoBitrate: number;
|
|
21
|
+
}
|
|
22
|
+
export declare const evenDimension: (value: number) => number;
|
|
23
|
+
/** The film's size with its short side at `shortSide` (never larger than the film's own), in even pixels. */
|
|
24
|
+
export declare function fitExportDimensions(film: ExportDimensions, shortSide: number): ExportDimensions;
|
|
25
|
+
export declare function chooseVideoBitrate(size: ExportDimensions, fps: number, quality?: VideoQuality): number;
|
|
26
|
+
/** The video bitrate that keeps a file of `duration` seconds, with its audio, under `maxBytes`. */
|
|
27
|
+
export declare function videoBitrateWithinBudget(duration: number, maxBytes: number): number;
|
|
28
|
+
export declare const isVideoHeight: (value: unknown) => value is VideoHeight;
|
|
29
|
+
/**
|
|
30
|
+
* Settings as the export uses them: a known height (1080 otherwise), a quality, and a bitrate that keeps the file
|
|
31
|
+
* within the export's size budget.
|
|
32
|
+
*/
|
|
33
|
+
export declare function resolveVideoSettings(settings: Partial<VideoSettings>, film: Pick<FilmFacts, 'duration'>): VideoSettings & {
|
|
34
|
+
quality: VideoQuality;
|
|
35
|
+
};
|
|
36
|
+
export declare function planVideoFrames(film: FilmFacts, settings: VideoSettings): VideoFramePlan;
|
|
37
|
+
export declare function estimateVideoBytes(plan: Pick<VideoFramePlan, 'videoBitrate'>, duration: number, withAudio: boolean): number;
|
|
38
|
+
export type GifPresetName = 'standard' | 'small';
|
|
39
|
+
export interface GifPreset {
|
|
40
|
+
shortSide: number;
|
|
41
|
+
/** Hundredths of a second each frame shows. */
|
|
42
|
+
delayCs: number;
|
|
43
|
+
maxBytes: number;
|
|
44
|
+
/** How long an estimate may spend on extra probes when the film rests. */
|
|
45
|
+
estimateExtraMs: number;
|
|
46
|
+
}
|
|
47
|
+
export interface GifPlan extends FramePlan {
|
|
48
|
+
delayCs: number;
|
|
49
|
+
}
|
|
50
|
+
/** A GIF preset; the small one is never larger nor faster than the standard one. */
|
|
51
|
+
export declare function resolveGifPreset(name: GifPresetName): GifPreset;
|
|
52
|
+
/** A GIF above this many bytes is heavy to share. */
|
|
53
|
+
export declare const GIF_HEAVY_BYTES: number;
|
|
54
|
+
export declare function planGifFrames(film: Pick<FilmFacts, 'width' | 'height' | 'duration'>, preset: Pick<GifPreset, 'shortSide' | 'delayCs'>): GifPlan;
|
package/src/plan.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { EXPORT_SETTINGS, GIF_SETTINGS } from '@openartifactsai/motion-core';
|
|
2
|
+
import { BYTES_PER_MEBIBYTE } from "./errors.js";
|
|
3
|
+
export const EXPORT_AUDIO_BITRATE = 128_000;
|
|
4
|
+
export const VIDEO_HEIGHTS = [720, 1080];
|
|
5
|
+
export const VIDEO_FRAME_RATES = [24, 30, 60];
|
|
6
|
+
export const MAX_EXPORT_FPS = 120;
|
|
7
|
+
const QUALITY_MULTIPLIERS = { high: 1, medium: 0.5, low: 0.25 };
|
|
8
|
+
export const evenDimension = (value) => Math.max(2, Math.round(value / 2) * 2);
|
|
9
|
+
/** The film's size with its short side at `shortSide` (never larger than the film's own), in even pixels. */
|
|
10
|
+
export function fitExportDimensions(film, shortSide) {
|
|
11
|
+
const sourceSide = Math.min(film.width, film.height);
|
|
12
|
+
const targetSide = Math.min(shortSide, sourceSide);
|
|
13
|
+
return { width: evenDimension((film.width * targetSide) / sourceSide), height: evenDimension((film.height * targetSide) / sourceSide) };
|
|
14
|
+
}
|
|
15
|
+
export function chooseVideoBitrate(size, fps, quality = 'high') {
|
|
16
|
+
const rate = fps > 45 ? 1 : quality === 'high' || fps > 20 ? 0.8 : 0.64;
|
|
17
|
+
return Math.round((Math.min(size.width, size.height) >= 1000 ? 8_000_000 : 5_000_000) * rate * QUALITY_MULTIPLIERS[quality]);
|
|
18
|
+
}
|
|
19
|
+
/** The video bitrate that keeps a file of `duration` seconds, with its audio, under `maxBytes`. */
|
|
20
|
+
export function videoBitrateWithinBudget(duration, maxBytes) {
|
|
21
|
+
return Math.floor((maxBytes * 0.9 * 8) / Math.max(1, duration) - EXPORT_AUDIO_BITRATE);
|
|
22
|
+
}
|
|
23
|
+
export const isVideoHeight = (value) => typeof value === 'number' && VIDEO_HEIGHTS.includes(value);
|
|
24
|
+
const isQuality = (value) => value === 'low' || value === 'medium' || value === 'high';
|
|
25
|
+
/**
|
|
26
|
+
* Settings as the export uses them: a known height (1080 otherwise), a quality, and a bitrate that keeps the file
|
|
27
|
+
* within the export's size budget.
|
|
28
|
+
*/
|
|
29
|
+
export function resolveVideoSettings(settings, film) {
|
|
30
|
+
const maxBytes = EXPORT_SETTINGS.maxMb * BYTES_PER_MEBIBYTE;
|
|
31
|
+
const budget = Math.max(videoBitrateWithinBudget(film.duration, maxBytes), EXPORT_SETTINGS.floorKbps * 1000);
|
|
32
|
+
return {
|
|
33
|
+
height: isVideoHeight(settings.height) ? settings.height : 1080,
|
|
34
|
+
...(typeof settings.fps === 'number' && Number.isFinite(settings.fps) ? { fps: settings.fps } : {}),
|
|
35
|
+
quality: isQuality(settings.quality) ? settings.quality : 'high',
|
|
36
|
+
maxVideoBitrate: Math.min(settings.maxVideoBitrate ?? Number.POSITIVE_INFINITY, budget),
|
|
37
|
+
supersample: settings.supersample === true,
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
export function planVideoFrames(film, settings) {
|
|
41
|
+
const size = fitExportDimensions(film, settings.height);
|
|
42
|
+
const wanted = settings.fps !== undefined && Number.isFinite(settings.fps) ? settings.fps : film.fps;
|
|
43
|
+
const fps = Math.max(1, Math.min(wanted, Math.max(1, film.fps), MAX_EXPORT_FPS));
|
|
44
|
+
const videoBitrate = Math.min(chooseVideoBitrate(size, fps, settings.quality), settings.maxVideoBitrate ?? Number.POSITIVE_INFINITY);
|
|
45
|
+
return { ...size, fps, frames: Math.max(1, Math.round(film.duration * fps)), videoBitrate };
|
|
46
|
+
}
|
|
47
|
+
export function estimateVideoBytes(plan, duration, withAudio) {
|
|
48
|
+
return Math.round(((duration * (plan.videoBitrate + (withAudio ? EXPORT_AUDIO_BITRATE : 0))) / 8) * 1.02 + 4096);
|
|
49
|
+
}
|
|
50
|
+
/** A GIF preset; the small one is never larger nor faster than the standard one. */
|
|
51
|
+
export function resolveGifPreset(name) {
|
|
52
|
+
const maxBytes = GIF_SETTINGS.maxMb * BYTES_PER_MEBIBYTE;
|
|
53
|
+
const estimateExtraMs = GIF_SETTINGS.estimateExtraS * 1000;
|
|
54
|
+
const standard = GIF_SETTINGS.standard;
|
|
55
|
+
switch (name) {
|
|
56
|
+
case 'standard':
|
|
57
|
+
return { shortSide: standard.shortSide, delayCs: standard.delayCs, maxBytes, estimateExtraMs };
|
|
58
|
+
case 'small':
|
|
59
|
+
return {
|
|
60
|
+
shortSide: Math.min(GIF_SETTINGS.small.shortSide, standard.shortSide),
|
|
61
|
+
delayCs: Math.max(GIF_SETTINGS.small.delayCs, standard.delayCs),
|
|
62
|
+
maxBytes,
|
|
63
|
+
estimateExtraMs,
|
|
64
|
+
};
|
|
65
|
+
default: {
|
|
66
|
+
const never = name;
|
|
67
|
+
return never;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
/** A GIF above this many bytes is heavy to share. */
|
|
72
|
+
export const GIF_HEAVY_BYTES = Math.min(GIF_SETTINGS.heavyMb, GIF_SETTINGS.maxMb) * BYTES_PER_MEBIBYTE;
|
|
73
|
+
export function planGifFrames(film, preset) {
|
|
74
|
+
const fps = 100 / preset.delayCs;
|
|
75
|
+
return { ...fitExportDimensions(film, preset.shortSide), delayCs: preset.delayCs, fps, frames: Math.max(1, Math.round(film.duration * fps)) };
|
|
76
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { ExportFormat, ExportProblem } from '@openartifactsai/motion-core';
|
|
2
|
+
import type { GifPlan } from './plan.js';
|
|
3
|
+
import type { HeldFrames } from './types.js';
|
|
4
|
+
import type { VideoPlan } from './video/format.js';
|
|
5
|
+
/** The held frames of an export, as a problem to tell the agent about; null when every frame was drawn. */
|
|
6
|
+
export declare function heldProblem(held: HeldFrames, saved: boolean): ExportProblem | null;
|
|
7
|
+
/** An export that stopped because of the film (a frame it could not draw); null for any other failure. */
|
|
8
|
+
export declare function failedProblem(error: unknown): ExportProblem | null;
|
|
9
|
+
export declare const videoExportFormat: (plan: Pick<VideoPlan, "width" | "height" | "fps">) => ExportFormat;
|
|
10
|
+
export declare const gifExportFormat: (plan: Pick<GifPlan, "width" | "height" | "delayCs">) => ExportFormat;
|
package/src/problems.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { MAX_EXPORT_ERROR_CHARS } from '@openartifactsai/motion-core';
|
|
2
|
+
import { FrameRenderError } from "./errors.js";
|
|
3
|
+
/** The held frames of an export, as a problem to tell the agent about; null when every frame was drawn. */
|
|
4
|
+
export function heldProblem(held, saved) {
|
|
5
|
+
if (held.count === 0)
|
|
6
|
+
return null;
|
|
7
|
+
return {
|
|
8
|
+
kind: 'held',
|
|
9
|
+
count: held.count,
|
|
10
|
+
total: held.total,
|
|
11
|
+
...(held.first !== undefined ? { first: { t: held.first.t, message: held.first.message.slice(0, MAX_EXPORT_ERROR_CHARS) } } : {}),
|
|
12
|
+
...(held.last !== undefined ? { last: held.last } : {}),
|
|
13
|
+
saved,
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
/** An export that stopped because of the film (a frame it could not draw); null for any other failure. */
|
|
17
|
+
export function failedProblem(error) {
|
|
18
|
+
if (!(error instanceof FrameRenderError))
|
|
19
|
+
return null;
|
|
20
|
+
const t = error.t;
|
|
21
|
+
return { kind: 'failed', t, message: error.message.slice(0, MAX_EXPORT_ERROR_CHARS) };
|
|
22
|
+
}
|
|
23
|
+
export const videoExportFormat = (plan) => ({
|
|
24
|
+
kind: 'video',
|
|
25
|
+
height: Math.min(plan.width, plan.height),
|
|
26
|
+
fps: plan.fps,
|
|
27
|
+
});
|
|
28
|
+
export const gifExportFormat = (plan) => ({
|
|
29
|
+
kind: 'gif',
|
|
30
|
+
shortSide: Math.min(plan.width, plan.height),
|
|
31
|
+
delayCs: plan.delayCs,
|
|
32
|
+
});
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** A script's text made safe to sit inside a <script> element. */
|
|
2
|
+
export declare function inScript(text: string): string;
|
|
3
|
+
/** The raster frame can run its own script and read data: pictures, and nothing else. */
|
|
4
|
+
export declare const RASTER_CONTENT_SECURITY_POLICY = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data: blob:; font-src data:";
|
|
5
|
+
/** A picture made only of a foreignObject: drawing it first shows whether this browser can draw snapshots at all. */
|
|
6
|
+
export declare const FOREIGN_OBJECT_TEST_SVG = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"2\" height=\"2\"><foreignObject width=\"2\" height=\"2\"><div xmlns=\"http://www.w3.org/1999/xhtml\" style=\"width:2px;height:2px;background:#000\"></div></foreignObject></svg>";
|
|
7
|
+
export declare function rasterDocument(script: string): string;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** A script's text made safe to sit inside a <script> element. */
|
|
2
|
+
export function inScript(text) {
|
|
3
|
+
return text.replace(/<\/(script)/gi, '<\\/$1').replace(/<!-{2}/g, '<\\x21--');
|
|
4
|
+
}
|
|
5
|
+
/** The raster frame can run its own script and read data: pictures, and nothing else. */
|
|
6
|
+
export const RASTER_CONTENT_SECURITY_POLICY = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data: blob:; font-src data:";
|
|
7
|
+
/** A picture made only of a foreignObject: drawing it first shows whether this browser can draw snapshots at all. */
|
|
8
|
+
export const FOREIGN_OBJECT_TEST_SVG = '<svg xmlns="http://www.w3.org/2000/svg" width="2" height="2"><foreignObject width="2" height="2"><div xmlns="http://www.w3.org/1999/xhtml" style="width:2px;height:2px;background:#000"></div></foreignObject></svg>';
|
|
9
|
+
export function rasterDocument(script) {
|
|
10
|
+
return ('<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="' +
|
|
11
|
+
RASTER_CONTENT_SECURITY_POLICY +
|
|
12
|
+
'"></head><body><script>' +
|
|
13
|
+
inScript(script) +
|
|
14
|
+
'</script></body></html>');
|
|
15
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { drawSnapshot, makeHoldFirstDraw, whyNoDecode } from '@openartifactsai/motion-stage/raster';
|
|
2
|
+
import { isRasterRequest } from "./messages.js";
|
|
3
|
+
// Runs in the raster frame: an opaque origin, so a snapshot's pictures cannot taint what the page reads back.
|
|
4
|
+
const holdFirstDraw = makeHoldFirstDraw();
|
|
5
|
+
let retained = document.createElement('canvas');
|
|
6
|
+
const reply = (message, transfer = []) => parent.postMessage(message, '*', transfer);
|
|
7
|
+
const messageOf = (error) => (error instanceof Error ? error.message : String(error));
|
|
8
|
+
async function bitmapOf(surface) {
|
|
9
|
+
return surface instanceof ImageBitmap ? surface : createImageBitmap(surface);
|
|
10
|
+
}
|
|
11
|
+
addEventListener('message', (event) => {
|
|
12
|
+
const request = event.data;
|
|
13
|
+
if (event.source !== parent || !isRasterRequest(request))
|
|
14
|
+
return;
|
|
15
|
+
const fail = (error) => reply({ rid: request.rid, error: messageOf(error) });
|
|
16
|
+
try {
|
|
17
|
+
const picture = new Image();
|
|
18
|
+
picture.onload = () => {
|
|
19
|
+
holdFirstDraw(request.svg, request.waitMs, () => {
|
|
20
|
+
drawSnapshot(picture, request.pw, request.ph, retained)
|
|
21
|
+
.then(bitmapOf)
|
|
22
|
+
.then((bitmap) => reply({ rid: request.rid, bitmap }, [bitmap]))
|
|
23
|
+
.catch((error) => {
|
|
24
|
+
retained = document.createElement('canvas');
|
|
25
|
+
fail(error);
|
|
26
|
+
});
|
|
27
|
+
});
|
|
28
|
+
};
|
|
29
|
+
picture.onerror = () => fail('snapshot decode failed (foreignObject)' + whyNoDecode(request.svg));
|
|
30
|
+
picture.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(request.svg);
|
|
31
|
+
}
|
|
32
|
+
catch (error) {
|
|
33
|
+
fail(error);
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
reply({ rasterReady: true });
|