@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,61 @@
|
|
|
1
|
+
import { SNAPSHOT_SETTINGS } from '@openartifactsai/motion-core';
|
|
2
|
+
import { ExportCheckError, FrameRenderError, FrameStallError, RasterDecodeError, SnapshotLimitError } from "./errors.js";
|
|
3
|
+
import { MAX_RASTER_SIDE } from "./raster/host.js";
|
|
4
|
+
import { words } from "./words.js";
|
|
5
|
+
const fitsRaster = (side) => side >= 1 && side <= MAX_RASTER_SIDE;
|
|
6
|
+
export const layFrame = (under, over, pw, ph) => {
|
|
7
|
+
try {
|
|
8
|
+
const picture = new OffscreenCanvas(pw, ph);
|
|
9
|
+
const context = picture.getContext('2d');
|
|
10
|
+
if (context === null)
|
|
11
|
+
throw new Error('no 2d context to draw a frame on');
|
|
12
|
+
context.drawImage(under, 0, 0, pw, ph);
|
|
13
|
+
context.drawImage(over, 0, 0, pw, ph);
|
|
14
|
+
return picture.transferToImageBitmap();
|
|
15
|
+
}
|
|
16
|
+
finally {
|
|
17
|
+
under.close();
|
|
18
|
+
over.close();
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Frames from the stage, as pictures: the stage's snapshot drawn by the raster frame, over the backdrop the stage took
|
|
23
|
+
* out of it when it did (`lay`). A frame the film could not draw is a FrameRenderError; one the browser held up is a
|
|
24
|
+
* FrameStallError.
|
|
25
|
+
*/
|
|
26
|
+
export function stageExportFrame(source, raster, lay = layFrame) {
|
|
27
|
+
return async (t, width, height) => {
|
|
28
|
+
const facts = source.facts();
|
|
29
|
+
if (facts === null)
|
|
30
|
+
throw new FrameStallError(words.filmNotLoaded);
|
|
31
|
+
const answer = await source.frame(t, { scale: width / facts.width, smallMedia: false, readFx: SNAPSHOT_SETTINGS.fx === 'read', smooth: false, lift: true });
|
|
32
|
+
switch (answer.kind) {
|
|
33
|
+
case 'unloaded':
|
|
34
|
+
throw new FrameStallError(words.filmNotLoaded);
|
|
35
|
+
case 'failed':
|
|
36
|
+
throw answer.env ? new FrameStallError(answer.message) : new FrameRenderError(answer.message, t, answer.hold);
|
|
37
|
+
case 'picture': {
|
|
38
|
+
const { under } = answer;
|
|
39
|
+
if (!fitsRaster(answer.pw) || !fitsRaster(answer.ph) || Math.abs(answer.pw - width) > 1 || Math.abs(answer.ph - height) > 1) {
|
|
40
|
+
under?.close();
|
|
41
|
+
throw new ExportCheckError(words.frameTorn, 'torn_frame');
|
|
42
|
+
}
|
|
43
|
+
let over;
|
|
44
|
+
try {
|
|
45
|
+
over = await raster.raster(answer.svg, answer.pw, answer.ph);
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
under?.close();
|
|
49
|
+
if (error instanceof RasterDecodeError || error instanceof SnapshotLimitError)
|
|
50
|
+
throw new FrameRenderError(error.message, t, true);
|
|
51
|
+
throw error;
|
|
52
|
+
}
|
|
53
|
+
return under === undefined ? over : lay(under, over, answer.pw, answer.ph);
|
|
54
|
+
}
|
|
55
|
+
default: {
|
|
56
|
+
const never = answer;
|
|
57
|
+
return never;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { buildClock } from '@openartifactsai/motion-core';
|
|
2
|
+
import { FilmSoundPlayer, decodeNarration, identityTimeline, planNarration } from '@openartifactsai/motion-audio';
|
|
3
|
+
import { OFFLINE_AUDIO_GLOBAL, OFFLINE_DATA_ID, fromBase64, readOfflineData } from '@openartifactsai/motion-stage';
|
|
4
|
+
import { standaloneFootage } from "./clip-footage.js";
|
|
5
|
+
// The standalone page plays the film as recorded in play time, unretimed: its clock has no parts, so play time and film
|
|
6
|
+
// time are the same moments.
|
|
7
|
+
const asPlayed = buildClock([]);
|
|
8
|
+
function scoreData(score) {
|
|
9
|
+
return { ...score, events: score.events.map((event) => ({ ...event, t: asPlayed.toFilm(event.t) })) };
|
|
10
|
+
}
|
|
11
|
+
function narrationData(narration) {
|
|
12
|
+
return {
|
|
13
|
+
lines: narration.lines.map((line) => ({
|
|
14
|
+
at: asPlayed.toFilm(line.at),
|
|
15
|
+
dur: line.dur,
|
|
16
|
+
text: line.text,
|
|
17
|
+
audio: line.audio,
|
|
18
|
+
...(line.from !== undefined ? { from: line.from } : {}),
|
|
19
|
+
})),
|
|
20
|
+
...(narration.duck !== null ? { duck: narration.duck } : {}),
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
const BASE64_URL = /^data:[^;,]+;base64,/;
|
|
24
|
+
/** An asset's bytes: those it carries, or those of a `data:` URL it streams from (a clip); null for any other URL. */
|
|
25
|
+
function assetBytes(asset) {
|
|
26
|
+
if (asset.bytes !== undefined)
|
|
27
|
+
return asset.bytes;
|
|
28
|
+
const prefix = asset.url === undefined ? null : BASE64_URL.exec(asset.url);
|
|
29
|
+
if (prefix === null || asset.url === undefined)
|
|
30
|
+
return null;
|
|
31
|
+
try {
|
|
32
|
+
return fromBase64(asset.url.slice(prefix[0].length));
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/** The bytes of the assets the lines name: takes, and clips whose sound lines cut from. */
|
|
39
|
+
function takeBytes(names) {
|
|
40
|
+
const takes = new Map();
|
|
41
|
+
const text = document.getElementById(OFFLINE_DATA_ID)?.textContent ?? null;
|
|
42
|
+
if (text === null)
|
|
43
|
+
return takes;
|
|
44
|
+
const film = readOfflineData(text);
|
|
45
|
+
if (typeof film === 'string')
|
|
46
|
+
return takes;
|
|
47
|
+
for (const asset of film.assets) {
|
|
48
|
+
if (!names.has(asset.name) || !(asset.mime.startsWith('audio/') || asset.mime.startsWith('video/')))
|
|
49
|
+
continue;
|
|
50
|
+
const bytes = assetBytes(asset);
|
|
51
|
+
if (bytes !== null)
|
|
52
|
+
takes.set(asset.name, bytes);
|
|
53
|
+
}
|
|
54
|
+
return takes;
|
|
55
|
+
}
|
|
56
|
+
function makeScorePlayer() {
|
|
57
|
+
const player = new FilmSoundPlayer();
|
|
58
|
+
return {
|
|
59
|
+
async prepare(score, narration, duration, clips = []) {
|
|
60
|
+
const length = asPlayed.toFilm(duration);
|
|
61
|
+
const plan = narration === null ? null : planNarration(narrationData(narration), length);
|
|
62
|
+
const decoded = plan === null ? null : await decodeNarration(plan, takeBytes(new Set(plan.lines.map((line) => line.audio))));
|
|
63
|
+
player.load({ score: score === null ? null : scoreData(score), narration: decoded, timeline: identityTimeline(length) });
|
|
64
|
+
// The clips' own sound joins once their files are decoded.
|
|
65
|
+
player.setFootage(await standaloneFootage(clips));
|
|
66
|
+
},
|
|
67
|
+
start(t) {
|
|
68
|
+
player.setMuted(false);
|
|
69
|
+
player.play(t);
|
|
70
|
+
},
|
|
71
|
+
stop() {
|
|
72
|
+
player.pause();
|
|
73
|
+
},
|
|
74
|
+
now() {
|
|
75
|
+
return player.state.playing ? player.now() : null;
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
const factory = makeScorePlayer;
|
|
80
|
+
Reflect.set(window, OFFLINE_AUDIO_GLOBAL, factory);
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { ClipSoundUse } from '@openartifactsai/motion-core';
|
|
2
|
+
import type { Footage } from '@openartifactsai/motion-audio';
|
|
3
|
+
/** The clips' footage from the files written into the page; null when no clip sounds. */
|
|
4
|
+
export declare function standaloneFootage(uses: readonly ClipSoundUse[]): Promise<Footage | null>;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { loadFootage } from '@openartifactsai/motion-audio';
|
|
2
|
+
import { OFFLINE_DATA_ID, fromBase64, readOfflineData } from '@openartifactsai/motion-stage';
|
|
3
|
+
/** The standalone page's video files by name: the bytes written into the page, or those of an inline `data:` address. */
|
|
4
|
+
function videoFiles() {
|
|
5
|
+
const files = new Map();
|
|
6
|
+
const text = document.getElementById(OFFLINE_DATA_ID)?.textContent ?? null;
|
|
7
|
+
const film = text === null ? null : readOfflineData(text);
|
|
8
|
+
if (film === null || typeof film === 'string')
|
|
9
|
+
return files;
|
|
10
|
+
for (const asset of film.assets)
|
|
11
|
+
if (asset.mime.startsWith('video/'))
|
|
12
|
+
files.set(asset.name, asset);
|
|
13
|
+
return files;
|
|
14
|
+
}
|
|
15
|
+
function inlineBytes(file) {
|
|
16
|
+
if (file.bytes !== undefined)
|
|
17
|
+
return file.bytes;
|
|
18
|
+
const url = file.url ?? '';
|
|
19
|
+
const comma = url.indexOf(',');
|
|
20
|
+
if (!url.startsWith('data:') || comma < 0 || !url.slice(0, comma).endsWith(';base64'))
|
|
21
|
+
return null;
|
|
22
|
+
try {
|
|
23
|
+
return fromBase64(url.slice(comma + 1));
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/** The clips' footage from the files written into the page; null when no clip sounds. */
|
|
30
|
+
export async function standaloneFootage(uses) {
|
|
31
|
+
if (uses.length === 0)
|
|
32
|
+
return null;
|
|
33
|
+
const files = videoFiles();
|
|
34
|
+
return loadFootage(uses, async (name) => {
|
|
35
|
+
const file = files.get(name);
|
|
36
|
+
return file === undefined ? null : inlineBytes(file);
|
|
37
|
+
});
|
|
38
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { StageAsset, StageFilm } from '@openartifactsai/motion-stage';
|
|
2
|
+
import type { ExportedFile } from '../types.js';
|
|
3
|
+
/** The page reaches nothing outside itself: everything it plays is inside it. */
|
|
4
|
+
export declare const STANDALONE_CONTENT_SECURITY_POLICY = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; media-src data: blob:";
|
|
5
|
+
/** A typeface the page carries, with the licence that must travel with it. */
|
|
6
|
+
export interface FontLicenceNotice {
|
|
7
|
+
family: string;
|
|
8
|
+
licence: string;
|
|
9
|
+
text: string;
|
|
10
|
+
}
|
|
11
|
+
export interface StandaloneInput {
|
|
12
|
+
title: string;
|
|
13
|
+
film: StageFilm;
|
|
14
|
+
/** The narration's takes (audio assets, with their bytes), which the stage itself does not need. */
|
|
15
|
+
takes?: readonly StageAsset[];
|
|
16
|
+
/** The stage runtime (`virtual:motion-stage-runtime`). */
|
|
17
|
+
runtimeScript: string;
|
|
18
|
+
/** The offline player (`buildOfflinePlayer()`). */
|
|
19
|
+
playerScript: string;
|
|
20
|
+
/** Sets `window.filmAudio` (`virtual:motion-standalone-audio`); null for a silent page. */
|
|
21
|
+
audioScript: string | null;
|
|
22
|
+
background?: string;
|
|
23
|
+
licences?: readonly FontLicenceNotice[];
|
|
24
|
+
maxBytes?: number;
|
|
25
|
+
}
|
|
26
|
+
/** The film a standalone page carries: the stage's film with the narration's takes, without the page's own records. */
|
|
27
|
+
export declare function standaloneFilm(film: StageFilm, takes?: readonly StageAsset[]): StageFilm;
|
|
28
|
+
export declare const escapeHtml: (text: string) => string;
|
|
29
|
+
/** Text that cannot end the HTML comment it sits in. */
|
|
30
|
+
export declare const escapeHtmlComment: (text: string) => string;
|
|
31
|
+
/** One HTML file that plays the film offline: the film's data, the stage runtime, the sound and the player. */
|
|
32
|
+
export declare function standaloneHtml(input: StandaloneInput): string;
|
|
33
|
+
export declare const STANDALONE_MAX_BYTES: number;
|
|
34
|
+
/** The standalone page as a file to download; refused when it would pass `maxBytes`. */
|
|
35
|
+
export declare function standaloneFile(input: StandaloneInput): ExportedFile;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { CODE_SETTINGS, FETCHED_FONTS_MODULE, RECOLORED_MODULE, REFACED_MODULE, RETYPED_MODULE } from '@openartifactsai/motion-core';
|
|
2
|
+
import { OFFLINE_DATA_ID, OFFLINE_RUNTIME_ID, offlineDataText } from '@openartifactsai/motion-stage';
|
|
3
|
+
import { BYTES_PER_MEBIBYTE, SourceExportError, wholeMegabytes } from "../errors.js";
|
|
4
|
+
import { exportFilename } from "../filename.js";
|
|
5
|
+
import { inScript } from "../raster/document.js";
|
|
6
|
+
import { words } from "../words.js";
|
|
7
|
+
/** The page reaches nothing outside itself: everything it plays is inside it. */
|
|
8
|
+
export const STANDALONE_CONTENT_SECURITY_POLICY = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; media-src data: blob:";
|
|
9
|
+
/** Records the page keeps for itself: the editor has already applied them to the film it gives the stage. */
|
|
10
|
+
const PAGE_RECORDS = [RETYPED_MODULE, RECOLORED_MODULE, REFACED_MODULE, FETCHED_FONTS_MODULE];
|
|
11
|
+
/** The film a standalone page carries: the stage's film with the narration's takes, without the page's own records. */
|
|
12
|
+
export function standaloneFilm(film, takes = []) {
|
|
13
|
+
const names = new Set(film.assets.map((asset) => asset.name));
|
|
14
|
+
return {
|
|
15
|
+
...film,
|
|
16
|
+
modules: film.modules.filter((module) => !PAGE_RECORDS.includes(module.name)),
|
|
17
|
+
assets: [...film.assets, ...takes.filter((take) => !names.has(take.name))],
|
|
18
|
+
mode: 'final',
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
export const escapeHtml = (text) => text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
22
|
+
/** Text that cannot end the HTML comment it sits in. */
|
|
23
|
+
export const escapeHtmlComment = (text) => text.replace(/--+(!?)>/g, '- $1>').replace(/<!-/g, '< !-');
|
|
24
|
+
const CSS_COLOR = /^(#[0-9a-fA-F]{3,8}|[a-zA-Z]{3,20}|(rgb|hsl)a?\([0-9.,%\s/]{1,40}\))$/;
|
|
25
|
+
function pageStyle(background) {
|
|
26
|
+
const color = background !== undefined && CSS_COLOR.test(background) ? background : '#000';
|
|
27
|
+
return `html,body{margin:0;height:100%;background:${color}}#film{position:fixed;inset:0}`;
|
|
28
|
+
}
|
|
29
|
+
function licenceComment(licences) {
|
|
30
|
+
if (licences.length === 0)
|
|
31
|
+
return '';
|
|
32
|
+
const notices = licences.map((notice) => `${notice.family} (${notice.licence})\n\n${notice.text.trim()}`).join('\n\n----\n\n');
|
|
33
|
+
return '\n<!--\nThe typefaces in this page, each under its own licence:\n\n' + escapeHtmlComment(notices) + '\n-->\n';
|
|
34
|
+
}
|
|
35
|
+
/** One HTML file that plays the film offline: the film's data, the stage runtime, the sound and the player. */
|
|
36
|
+
export function standaloneHtml(input) {
|
|
37
|
+
const film = standaloneFilm(input.film, input.takes);
|
|
38
|
+
const audio = input.audioScript === null ? '' : '<script>' + inScript(input.audioScript) + '</script>';
|
|
39
|
+
return ('<!doctype html>\n<html lang="en"><head><meta charset="utf-8">' +
|
|
40
|
+
`<meta http-equiv="Content-Security-Policy" content="${STANDALONE_CONTENT_SECURITY_POLICY}">` +
|
|
41
|
+
'<meta name="viewport" content="width=device-width,initial-scale=1">' +
|
|
42
|
+
`<title>${escapeHtml(input.title)}</title><style>${pageStyle(input.background)}</style></head><body>` +
|
|
43
|
+
'<div id="film"></div>' +
|
|
44
|
+
`<script type="application/json" id="${OFFLINE_DATA_ID}">${offlineDataText(film)}</script>` +
|
|
45
|
+
`<script type="text/plain" id="${OFFLINE_RUNTIME_ID}">${inScript(input.runtimeScript)}</script>` +
|
|
46
|
+
audio +
|
|
47
|
+
'<script>' +
|
|
48
|
+
inScript(input.playerScript) +
|
|
49
|
+
'</script></body></html>' +
|
|
50
|
+
licenceComment(input.licences ?? []));
|
|
51
|
+
}
|
|
52
|
+
export const STANDALONE_MAX_BYTES = CODE_SETTINGS.maxMb * BYTES_PER_MEBIBYTE;
|
|
53
|
+
/** The standalone page as a file to download; refused when it would pass `maxBytes`. */
|
|
54
|
+
export function standaloneFile(input) {
|
|
55
|
+
const blob = new Blob([standaloneHtml(input)], { type: 'text/html;charset=utf-8' });
|
|
56
|
+
const maxBytes = input.maxBytes ?? STANDALONE_MAX_BYTES;
|
|
57
|
+
if (blob.size > maxBytes)
|
|
58
|
+
throw new SourceExportError(words.standaloneTooLarge(wholeMegabytes(maxBytes)), 'too_large');
|
|
59
|
+
return { blob, filename: exportFilename(input.title, 'html'), mime: 'text/html' };
|
|
60
|
+
}
|
package/src/types.d.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { PlaySeconds } from '@openartifactsai/motion-core';
|
|
2
|
+
export interface ExportDimensions {
|
|
3
|
+
width: number;
|
|
4
|
+
height: number;
|
|
5
|
+
}
|
|
6
|
+
/** The frames an export draws: `frames` of them, `fps` a second, at `width` × `height`. */
|
|
7
|
+
export interface FramePlan extends ExportDimensions {
|
|
8
|
+
fps: number;
|
|
9
|
+
frames: number;
|
|
10
|
+
}
|
|
11
|
+
export type ExportPhase = 'probe' | 'audio' | 'frames' | 'mux';
|
|
12
|
+
export interface ExportProgress {
|
|
13
|
+
done: number;
|
|
14
|
+
total: number;
|
|
15
|
+
phase: ExportPhase;
|
|
16
|
+
/** Video only: packets the encoder put out so far, and their bytes. */
|
|
17
|
+
packets?: number;
|
|
18
|
+
bytes?: number;
|
|
19
|
+
}
|
|
20
|
+
/** Frames that could not be drawn, each replaced by the one before. */
|
|
21
|
+
export interface HeldFrames {
|
|
22
|
+
count: number;
|
|
23
|
+
total: number;
|
|
24
|
+
first?: {
|
|
25
|
+
t: PlaySeconds;
|
|
26
|
+
message: string;
|
|
27
|
+
};
|
|
28
|
+
last?: PlaySeconds;
|
|
29
|
+
/** Frames asked for again after the page had been hidden: how many then came, and how many failed again. */
|
|
30
|
+
again?: {
|
|
31
|
+
good: number;
|
|
32
|
+
failed: number;
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/** One frame as a picture `width` × `height`; rejects with FrameRenderError or FrameStallError. */
|
|
36
|
+
export type ExportFrame = (t: PlaySeconds, width: number, height: number) => Promise<ImageBitmap>;
|
|
37
|
+
export interface ExportRunOptions {
|
|
38
|
+
onProgress?: (progress: ExportProgress) => void;
|
|
39
|
+
signal?: AbortSignal;
|
|
40
|
+
}
|
|
41
|
+
/** A finished export: what the editor hands to the downloads capability. */
|
|
42
|
+
export interface ExportedFile {
|
|
43
|
+
blob: Blob;
|
|
44
|
+
filename: string;
|
|
45
|
+
mime: string;
|
|
46
|
+
}
|
|
47
|
+
/** A finished video or GIF, with the frames it had to hold. */
|
|
48
|
+
export interface RenderedFile extends ExportedFile {
|
|
49
|
+
held: HeldFrames;
|
|
50
|
+
ms: number;
|
|
51
|
+
}
|
|
52
|
+
export interface ExportEstimate {
|
|
53
|
+
bytes: number;
|
|
54
|
+
/** Seconds the export should take. */
|
|
55
|
+
seconds: number;
|
|
56
|
+
label: string;
|
|
57
|
+
/** The bytes are a floor, not a guess. */
|
|
58
|
+
atLeast?: boolean;
|
|
59
|
+
/** MOV only: bytes a second of movement adds. */
|
|
60
|
+
mov?: {
|
|
61
|
+
bytesPerSecond: number;
|
|
62
|
+
};
|
|
63
|
+
}
|
package/src/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { ExportDimensions } from '../types.js';
|
|
2
|
+
import type { VideoFormat, VideoPlan } from './format.js';
|
|
3
|
+
/** One set-up of the video encoder. Some hardware encoders break on one and work with another. */
|
|
4
|
+
export interface EncoderAttempt {
|
|
5
|
+
latencyMode: 'quality' | 'realtime';
|
|
6
|
+
/** H.264 Baseline profile, which more hardware encodes. */
|
|
7
|
+
baseline?: true;
|
|
8
|
+
}
|
|
9
|
+
export interface EncoderAttemptOptions {
|
|
10
|
+
latencyMode: 'quality' | 'realtime';
|
|
11
|
+
fullCodecString?: string;
|
|
12
|
+
bitrateMode: 'variable';
|
|
13
|
+
hardwareAcceleration?: 'prefer-software';
|
|
14
|
+
}
|
|
15
|
+
export declare const FIRST_ATTEMPT: EncoderAttempt;
|
|
16
|
+
export declare const BASELINE_ATTEMPT: EncoderAttempt;
|
|
17
|
+
export declare const REALTIME_ATTEMPT: EncoderAttempt;
|
|
18
|
+
export declare const ENCODER_ATTEMPTS: readonly EncoderAttempt[];
|
|
19
|
+
/** The set-ups for a browser whose H.264 encoder takes Baseline only. */
|
|
20
|
+
export declare const BASELINE_REALTIME_ATTEMPT: EncoderAttempt;
|
|
21
|
+
export declare const BASELINE_ONLY_ATTEMPTS: readonly EncoderAttempt[];
|
|
22
|
+
export declare const ENCODER_SUPPORT_TIMEOUT_MS = 2000;
|
|
23
|
+
/** The H.264 level code a size needs. A level caps the frame's macroblocks and, through them, its longer side (the side
|
|
24
|
+
* in macroblocks, squared, may be at most eight times the cap). `raised` when the longer side alone asks for a higher
|
|
25
|
+
* level than the frame's area. */
|
|
26
|
+
export declare function avcLevelFor(size: ExportDimensions): {
|
|
27
|
+
level: string;
|
|
28
|
+
raised: boolean;
|
|
29
|
+
};
|
|
30
|
+
export declare function avcBaselineCodecString(size: ExportDimensions): string;
|
|
31
|
+
/** The High profile codec string an H.264 video needs when its longer side raises the level; undefined otherwise, which
|
|
32
|
+
* leaves the level to the encoder. */
|
|
33
|
+
export declare function avcHighCodecString(size: AttemptSize): string | undefined;
|
|
34
|
+
/** A size, and the codec when it is known. */
|
|
35
|
+
export type AttemptSize = ExportDimensions & {
|
|
36
|
+
format?: Pick<VideoFormat, 'videoCodec'>;
|
|
37
|
+
};
|
|
38
|
+
export declare function encoderAttemptOptions(attempt: EncoderAttempt, size: AttemptSize, preferSoftware: boolean): EncoderAttemptOptions;
|
|
39
|
+
/** The set-ups worth trying for a codec: Baseline is H.264's alone, and all there is when the encoder takes nothing else. */
|
|
40
|
+
export declare const attemptsFor: (plan: VideoPlan) => EncoderAttempt[];
|
|
41
|
+
/** What the encoder is asked about: a size, a bitrate and a codec. */
|
|
42
|
+
export type EncoderCheck = Pick<VideoPlan, 'width' | 'height' | 'videoBitrate'> & {
|
|
43
|
+
format: Pick<VideoFormat, 'videoCodec'>;
|
|
44
|
+
};
|
|
45
|
+
/** Whether the browser says it encodes with that set-up; false when it does not say in time. */
|
|
46
|
+
export declare function supportsEncoderAttempt(plan: EncoderCheck, options: Partial<EncoderAttemptOptions>, signal: AbortSignal | undefined): Promise<boolean>;
|
|
47
|
+
/**
|
|
48
|
+
* What the encoder learned across exports in this page: the set-up that last put frames out is tried first, and after
|
|
49
|
+
* a hardware encoder broke, later set-ups are tried in software.
|
|
50
|
+
*/
|
|
51
|
+
export interface EncoderMemory {
|
|
52
|
+
preferred: EncoderAttempt;
|
|
53
|
+
softwareOnRetry: boolean;
|
|
54
|
+
}
|
|
55
|
+
export declare const newEncoderMemory: () => EncoderMemory;
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { canEncodeVideo } from 'mediabunny';
|
|
2
|
+
import { isAborted } from "../errors.js";
|
|
3
|
+
export const FIRST_ATTEMPT = { latencyMode: 'quality' };
|
|
4
|
+
export const BASELINE_ATTEMPT = { latencyMode: 'quality', baseline: true };
|
|
5
|
+
export const REALTIME_ATTEMPT = { latencyMode: 'realtime' };
|
|
6
|
+
export const ENCODER_ATTEMPTS = [FIRST_ATTEMPT, BASELINE_ATTEMPT, REALTIME_ATTEMPT];
|
|
7
|
+
/** The set-ups for a browser whose H.264 encoder takes Baseline only. */
|
|
8
|
+
export const BASELINE_REALTIME_ATTEMPT = { latencyMode: 'realtime', baseline: true };
|
|
9
|
+
export const BASELINE_ONLY_ATTEMPTS = [BASELINE_ATTEMPT, BASELINE_REALTIME_ATTEMPT];
|
|
10
|
+
export const ENCODER_SUPPORT_TIMEOUT_MS = 2000;
|
|
11
|
+
/** The macroblocks a Baseline level allows a frame, and the level's code. */
|
|
12
|
+
const AVC_BASELINE_LEVELS = [
|
|
13
|
+
[1620, '1e'],
|
|
14
|
+
[3600, '1f'],
|
|
15
|
+
[5120, '20'],
|
|
16
|
+
[8192, '28'],
|
|
17
|
+
[8704, '2a'],
|
|
18
|
+
[22080, '32'],
|
|
19
|
+
];
|
|
20
|
+
/** The H.264 level code a size needs. A level caps the frame's macroblocks and, through them, its longer side (the side
|
|
21
|
+
* in macroblocks, squared, may be at most eight times the cap). `raised` when the longer side alone asks for a higher
|
|
22
|
+
* level than the frame's area. */
|
|
23
|
+
export function avcLevelFor(size) {
|
|
24
|
+
const across = Math.ceil(size.width / 16);
|
|
25
|
+
const down = Math.ceil(size.height / 16);
|
|
26
|
+
const codeFor = (macroblocks) => AVC_BASELINE_LEVELS.find(([most]) => macroblocks <= most)?.[1] ?? '33';
|
|
27
|
+
const byArea = codeFor(across * down);
|
|
28
|
+
const level = codeFor(Math.max(across * down, Math.max(across, down) ** 2 / 8));
|
|
29
|
+
return { level, raised: level !== byArea };
|
|
30
|
+
}
|
|
31
|
+
export function avcBaselineCodecString(size) {
|
|
32
|
+
return 'avc1.4200' + avcLevelFor(size).level;
|
|
33
|
+
}
|
|
34
|
+
/** The High profile codec string an H.264 video needs when its longer side raises the level; undefined otherwise, which
|
|
35
|
+
* leaves the level to the encoder. */
|
|
36
|
+
export function avcHighCodecString(size) {
|
|
37
|
+
if (size.format?.videoCodec !== 'avc')
|
|
38
|
+
return undefined;
|
|
39
|
+
const { level, raised } = avcLevelFor(size);
|
|
40
|
+
return raised ? 'avc1.6400' + level : undefined;
|
|
41
|
+
}
|
|
42
|
+
export function encoderAttemptOptions(attempt, size, preferSoftware) {
|
|
43
|
+
const fullCodecString = attempt.baseline === true ? avcBaselineCodecString(size) : avcHighCodecString(size);
|
|
44
|
+
return {
|
|
45
|
+
latencyMode: attempt.latencyMode,
|
|
46
|
+
...(fullCodecString !== undefined ? { fullCodecString } : {}),
|
|
47
|
+
bitrateMode: 'variable',
|
|
48
|
+
...(preferSoftware ? { hardwareAcceleration: 'prefer-software' } : {}),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/** The set-ups worth trying for a codec: Baseline is H.264's alone, and all there is when the encoder takes nothing else. */
|
|
52
|
+
export const attemptsFor = (plan) => plan.format.baselineOnly === true
|
|
53
|
+
? [...BASELINE_ONLY_ATTEMPTS]
|
|
54
|
+
: ENCODER_ATTEMPTS.filter((attempt) => plan.format.videoCodec === 'avc' || attempt.baseline !== true);
|
|
55
|
+
/** Whether the browser says it encodes with that set-up; false when it does not say in time. */
|
|
56
|
+
export function supportsEncoderAttempt(plan, options, signal) {
|
|
57
|
+
return new Promise((resolve) => {
|
|
58
|
+
if (isAborted(signal)) {
|
|
59
|
+
resolve(false);
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
const settle = (supported) => {
|
|
63
|
+
clearTimeout(timer);
|
|
64
|
+
signal?.removeEventListener('abort', refuse);
|
|
65
|
+
resolve(supported);
|
|
66
|
+
};
|
|
67
|
+
const refuse = () => settle(false);
|
|
68
|
+
const timer = setTimeout(refuse, ENCODER_SUPPORT_TIMEOUT_MS);
|
|
69
|
+
signal?.addEventListener('abort', refuse, { once: true });
|
|
70
|
+
canEncodeVideo(plan.format.videoCodec, { width: plan.width, height: plan.height, bitrate: plan.videoBitrate, ...options }).then(settle, refuse);
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
export const newEncoderMemory = () => ({ preferred: FIRST_ATTEMPT, softwareOnRetry: false });
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** What an avcC record's sequence parameter set says. */
|
|
2
|
+
export interface AvcStreamInfo {
|
|
3
|
+
fullRange: boolean;
|
|
4
|
+
profile: number;
|
|
5
|
+
refFrames: number;
|
|
6
|
+
/** max_num_reorder_frames, when the VUI has a bitstream restriction. */
|
|
7
|
+
reorderFrames?: number;
|
|
8
|
+
}
|
|
9
|
+
export declare function avcConfigBytes(description: AllowSharedBufferSource): Uint8Array;
|
|
10
|
+
/** Reads an avcC record's SPS; undefined when it cannot be read. */
|
|
11
|
+
export declare function readAvcStreamInfo(description: Uint8Array): AvcStreamInfo | undefined;
|
|
12
|
+
/** Whether an AVC stream sends frames in display order; undefined when it cannot be told. */
|
|
13
|
+
export declare function avcDecodesInOrder(config: VideoDecoderConfig | undefined): boolean | undefined;
|
|
14
|
+
/** Makes the decoder config's colour range say what the stream says, which some encoders report wrongly. */
|
|
15
|
+
export declare function repairAvcColorSpace(config: VideoDecoderConfig | undefined): void;
|
package/src/video/avc.js
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
const AVC_HIGH_PROFILES = [100, 110, 122, 244, 44, 83, 86, 118, 128, 138, 139, 134, 135];
|
|
2
|
+
const BASELINE_PROFILE = 66;
|
|
3
|
+
export function avcConfigBytes(description) {
|
|
4
|
+
return ArrayBuffer.isView(description)
|
|
5
|
+
? new Uint8Array(description.buffer, description.byteOffset, description.byteLength)
|
|
6
|
+
: new Uint8Array(description);
|
|
7
|
+
}
|
|
8
|
+
class BitReader {
|
|
9
|
+
#bytes;
|
|
10
|
+
#at = 0;
|
|
11
|
+
constructor(bytes) {
|
|
12
|
+
this.#bytes = bytes;
|
|
13
|
+
}
|
|
14
|
+
bits(count) {
|
|
15
|
+
let value = 0;
|
|
16
|
+
for (; count > 0; count--, this.#at++) {
|
|
17
|
+
const byte = this.#bytes[this.#at >> 3];
|
|
18
|
+
if (byte === undefined)
|
|
19
|
+
throw new RangeError('cut short');
|
|
20
|
+
value = value * 2 + ((byte >> (7 - (this.#at & 7))) & 1);
|
|
21
|
+
}
|
|
22
|
+
return value;
|
|
23
|
+
}
|
|
24
|
+
flag() {
|
|
25
|
+
return this.bits(1) === 1;
|
|
26
|
+
}
|
|
27
|
+
golomb() {
|
|
28
|
+
let zeros = 0;
|
|
29
|
+
while (this.bits(1) === 0)
|
|
30
|
+
zeros++;
|
|
31
|
+
return 2 ** zeros - 1 + this.bits(zeros);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
// The SPS without its emulation-prevention bytes (00 00 03 → 00 00).
|
|
35
|
+
function unescapedSps(sps) {
|
|
36
|
+
return sps.subarray(1).filter((byte, index, all) => !(byte === 3 && all[index - 1] === 0 && all[index - 2] === 0));
|
|
37
|
+
}
|
|
38
|
+
function skipHrd(reader) {
|
|
39
|
+
const count = reader.golomb() + 1;
|
|
40
|
+
reader.bits(8);
|
|
41
|
+
for (let index = 0; index < count; index++) {
|
|
42
|
+
reader.golomb();
|
|
43
|
+
reader.golomb();
|
|
44
|
+
reader.bits(1);
|
|
45
|
+
}
|
|
46
|
+
reader.bits(20);
|
|
47
|
+
}
|
|
48
|
+
/** The rest of the VUI, up to max_num_reorder_frames; undefined without a bitstream restriction. */
|
|
49
|
+
function readReorderFrames(reader, colourDescription) {
|
|
50
|
+
try {
|
|
51
|
+
if (colourDescription && reader.flag())
|
|
52
|
+
reader.bits(24);
|
|
53
|
+
if (reader.flag()) {
|
|
54
|
+
reader.golomb();
|
|
55
|
+
reader.golomb();
|
|
56
|
+
}
|
|
57
|
+
if (reader.flag())
|
|
58
|
+
reader.bits(65);
|
|
59
|
+
const nalHrd = reader.flag();
|
|
60
|
+
if (nalHrd)
|
|
61
|
+
skipHrd(reader);
|
|
62
|
+
const vclHrd = reader.flag();
|
|
63
|
+
if (vclHrd)
|
|
64
|
+
skipHrd(reader);
|
|
65
|
+
if (nalHrd || vclHrd)
|
|
66
|
+
reader.bits(1);
|
|
67
|
+
reader.bits(1);
|
|
68
|
+
if (!reader.flag())
|
|
69
|
+
return undefined;
|
|
70
|
+
reader.bits(1);
|
|
71
|
+
for (let index = 0; index < 4; index++)
|
|
72
|
+
reader.golomb();
|
|
73
|
+
return reader.golomb();
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
return undefined;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/** Reads an avcC record's SPS; undefined when it cannot be read. */
|
|
80
|
+
export function readAvcStreamInfo(description) {
|
|
81
|
+
const spsLength = ((description[6] ?? 0) << 8) | (description[7] ?? 0);
|
|
82
|
+
const sps = description.subarray(8, 8 + spsLength);
|
|
83
|
+
if (description[0] !== 1 || ((description[5] ?? 0) & 31) === 0 || ((sps[0] ?? 0) & 31) !== 7)
|
|
84
|
+
return undefined;
|
|
85
|
+
const reader = new BitReader(unescapedSps(sps));
|
|
86
|
+
try {
|
|
87
|
+
const profile = reader.bits(8);
|
|
88
|
+
reader.bits(16);
|
|
89
|
+
reader.golomb();
|
|
90
|
+
if (AVC_HIGH_PROFILES.includes(profile)) {
|
|
91
|
+
if (reader.golomb() === 3)
|
|
92
|
+
reader.bits(1);
|
|
93
|
+
reader.golomb();
|
|
94
|
+
reader.golomb();
|
|
95
|
+
reader.bits(1);
|
|
96
|
+
if (reader.flag())
|
|
97
|
+
return undefined;
|
|
98
|
+
}
|
|
99
|
+
reader.golomb();
|
|
100
|
+
const pocType = reader.golomb();
|
|
101
|
+
if (pocType === 1)
|
|
102
|
+
return undefined;
|
|
103
|
+
if (pocType === 0)
|
|
104
|
+
reader.golomb();
|
|
105
|
+
const refFrames = reader.golomb();
|
|
106
|
+
reader.bits(1);
|
|
107
|
+
reader.golomb();
|
|
108
|
+
reader.golomb();
|
|
109
|
+
if (!reader.flag())
|
|
110
|
+
reader.bits(1);
|
|
111
|
+
reader.bits(1);
|
|
112
|
+
if (reader.flag())
|
|
113
|
+
for (let index = 0; index < 4; index++)
|
|
114
|
+
reader.golomb();
|
|
115
|
+
if (!reader.flag())
|
|
116
|
+
return { fullRange: false, profile, refFrames };
|
|
117
|
+
if (reader.flag() && reader.bits(8) === 255)
|
|
118
|
+
reader.bits(32);
|
|
119
|
+
if (reader.flag())
|
|
120
|
+
reader.bits(1);
|
|
121
|
+
if (!reader.flag())
|
|
122
|
+
return { fullRange: false, profile, refFrames, reorderFrames: readReorderFrames(reader, false) };
|
|
123
|
+
reader.bits(3);
|
|
124
|
+
const fullRange = reader.flag();
|
|
125
|
+
return { fullRange, profile, refFrames, reorderFrames: readReorderFrames(reader, true) };
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
return undefined;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
/** Whether an AVC stream sends frames in display order; undefined when it cannot be told. */
|
|
132
|
+
export function avcDecodesInOrder(config) {
|
|
133
|
+
try {
|
|
134
|
+
const info = config?.description !== undefined && config.codec.startsWith('avc1') ? readAvcStreamInfo(avcConfigBytes(config.description)) : undefined;
|
|
135
|
+
if (info === undefined)
|
|
136
|
+
return undefined;
|
|
137
|
+
return info.reorderFrames === undefined ? info.refFrames === 1 || info.profile === BASELINE_PROFILE : info.reorderFrames === 0;
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
return undefined;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
/** Makes the decoder config's colour range say what the stream says, which some encoders report wrongly. */
|
|
144
|
+
export function repairAvcColorSpace(config) {
|
|
145
|
+
try {
|
|
146
|
+
const description = config?.description;
|
|
147
|
+
if (config === undefined || !config.codec.startsWith('avc1') || config.colorSpace == null || description === undefined)
|
|
148
|
+
return;
|
|
149
|
+
const fullRange = readAvcStreamInfo(avcConfigBytes(description))?.fullRange;
|
|
150
|
+
if (fullRange === undefined)
|
|
151
|
+
return;
|
|
152
|
+
const { primaries, transfer, matrix } = config.colorSpace;
|
|
153
|
+
config.colorSpace = { primaries, transfer, matrix, fullRange };
|
|
154
|
+
}
|
|
155
|
+
catch {
|
|
156
|
+
// A config that cannot be read is left as it is.
|
|
157
|
+
}
|
|
158
|
+
}
|