alpha2 0.2.2 → 0.3.1

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/README.md CHANGED
@@ -13,7 +13,7 @@ npm install alpha2
13
13
  - The WebAssembly modules need Chrome 96, Firefox 89 or Safari 16.4, or later.
14
14
  - Serve `.wasm` files as `application/wasm`; otherwise the loader falls back to a slower way of compiling them and warns.
15
15
  - Audio preview needs a cross-origin isolated page (`Cross-Origin-Opener-Policy: same-origin`, `Cross-Origin-Embedder-Policy: require-corp`).
16
- - [mediabunny](https://www.npmjs.com/package/mediabunny) is an optional dependency, for the decoders and the MP4 writer in `alpha2/mediabunny`. It installs `@types/dom-webcodecs` 0.1.13, whose declarations clash with TypeScript 5.9's DOM library. A TypeScript application either compiles with `skipLibCheck` or adds `"overrides": { "@types/dom-webcodecs": "0.1.19" }` to its `package.json`; one that imports `alpha2/mediabunny` also needs `"ESNext.Disposable"` in its `lib`.
16
+ - [mediabunny](https://www.npmjs.com/package/mediabunny) is an optional dependency, for the decoders and the MP4, MOV, MKV and WebM writer in `alpha2/mediabunny`. It installs `@types/dom-webcodecs` 0.1.13, whose declarations clash with TypeScript 5.9's DOM library. A TypeScript application either compiles with `skipLibCheck` or adds `"overrides": { "@types/dom-webcodecs": "0.1.19" }` to its `package.json`; one that imports `alpha2/mediabunny` also needs `"ESNext.Disposable"` in its `lib`.
17
17
 
18
18
  ## Render a frame
19
19
 
@@ -66,7 +66,7 @@ for (;;) {
66
66
  engine.endExport();
67
67
  ```
68
68
 
69
- A `waiting` ticket names the source frames the next frame needs (`missingFrames`); upload them and ask again, and the export continues at the same frame. `beginExportFrame` can be called again before a readback resolves, so that the GPU renders the next frame while the last one is read back. `exportToSink` in `alpha2/exporter` runs an export this way into an encoder sink, and `MediabunnyMp4Sink` in `alpha2/mediabunny` is a WebCodecs and MP4 sink for it.
69
+ A `waiting` ticket names the source frames the next frame needs (`missingFrames`); upload them and ask again, and the export continues at the same frame. `beginExportFrame` can be called again before a readback resolves, so that the GPU renders the next frame while the last one is read back. `exportToSink` in `alpha2/exporter` runs an export this way into an encoder sink, and `MediabunnySink` in `alpha2/mediabunny` is a WebCodecs sink for it that writes MP4, MOV, MKV or WebM.
70
70
 
71
71
  ## Audio
72
72
 
@@ -87,24 +87,26 @@ For preview, `alpha2/audio-timeline` moves the mixed blocks to the audio thread
87
87
  | `alpha2/builder` | `ProjectBuilder`: documents from seconds, with generated ids. |
88
88
  | `alpha2/edit` | Editing operations on a project: split, trim, ripple, roll, slip, slide, retime, insert, overwrite, append, move. |
89
89
  | `alpha2/captions` | SRT and WebVTT import into caption tracks. |
90
+ | `alpha2/geometry` | Shape geometry for editors, from the engine's own code: item bounds, hit tests, nearest points, path lengths, trims, resampling, convert to path, motion paths. |
90
91
  | `alpha2/effects` | Effect definitions and the built-in catalog's types; `RuntimeEffectRegistry`, a typed wrapper for registering WGSL effects and effect resources at run time. |
91
92
  | `alpha2/extensions`, `alpha2/extensions-wasm` | SVG, animated image, Lottie, OpenEXR and image sequence sources, from their own WebAssembly module (`loadExtensions`). |
92
93
  | `alpha2/text` | Text rasterizers: `WasmTextRasterizer` (the engine's, the same pixels as a native export) and `OffscreenTextRasterizer` (the browser's). |
93
94
  | `alpha2/assets` | Media identity, proxies and conform reports. |
94
95
  | `alpha2/frame-supply` | `FrameSupply`: decodes and uploads the frames a time needs. |
95
96
  | `alpha2/media` | Decoder contracts, `WebCodecsVideoDecoder`, `DecoderRefillCoordinator`. |
96
- | `alpha2/mediabunny` | Decoders and an MP4 sink on mediabunny (an optional dependency). |
97
+ | `alpha2/mediabunny` | Decoders and an MP4, MOV, MKV and WebM sink on mediabunny (an optional dependency). |
97
98
  | `alpha2/hdr-frames`, `alpha2/video-frames` | Uploading planar and HDR `VideoFrame`s; `VideoFrame`s from exported I420 planes. |
98
99
  | `alpha2/player`, `alpha2/worker` | `Alpha2Player` and the render worker. |
99
100
  | `alpha2/exporter` | `Alpha2Exporter` and `exportToSink`. |
100
101
  | `alpha2/export-destination` | Where an export's bytes go: a file, or memory. |
101
102
  | `alpha2/export-failure`, `alpha2/export-retry` | How export failures are classified, and a retry policy over them. |
103
+ | `alpha2/containers` | The export containers (MP4, MOV, MKV, WebM) and the codecs each offers. |
102
104
  | `alpha2/rate-control` | Output bitrates for the engine's quality levels. |
103
105
  | `alpha2/audio`, `alpha2/audio-worker` | Offline audio rendering into a sink, in a worker or not. |
104
106
  | `alpha2/audio-timeline`, `alpha2/audio-worklet`, `alpha2/audio-worklet-processor` | Real-time audio: the shared ring, its pump, and the AudioWorklet and its processor module. |
105
107
  | `alpha2/loudness`, `alpha2/waveform` | Loudness measurement and normalization; waveform summaries. |
106
108
  | `alpha2/robustness` | Browser capability detection and degradation reports. |
107
- | `alpha2` | `alpha2/assets`, `audio`, `audio-timeline`, `audio-worker`, `audio-worklet`, `effects`, `exporter`, `extensions`, `frame-supply`, `hdr-frames`, `loudness`, `media`, `player`, `project`, `rate-control`, `robustness`, `text`, `waveform` and `worker` in one import. |
109
+ | `alpha2` | `alpha2/assets`, `audio`, `audio-timeline`, `audio-worker`, `audio-worklet`, `containers`, `effects`, `exporter`, `extensions`, `frame-supply`, `hdr-frames`, `loudness`, `media`, `player`, `project`, `rate-control`, `robustness`, `text`, `waveform` and `worker` in one import. |
108
110
 
109
111
  Each module's declarations document its API.
110
112
 
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Export containers: the file formats an export is written in, and which codecs each one offers.
3
+ *
4
+ * This is the engine's container policy (`alpha2_media::Container`), mirrored here as a constant so
5
+ * a browser sink, or a client of a native host, can validate a request before it opens an encoder
6
+ * or starts a host. Both copies are pinned by the shared corpus
7
+ * `tests/cases/export-container-corpus.json`. A container offers only the codecs its mainstream
8
+ * players decode in it, which is narrower than what mediabunny writes: QuickTime does not play
9
+ * VP9, AV1 or Opus in a MOV.
10
+ */
11
+ import { type BrowserVideoCodec, type EngineVideoCodec } from "./rate-control.js";
12
+ /** The containers an export can be written in. */
13
+ export type ExportContainer = "mp4" | "mov" | "mkv" | "webm";
14
+ /** The audio codecs an export can carry. */
15
+ export type ExportAudioCodec = "aac" | "opus";
16
+ /** One container's policy. */
17
+ export interface ContainerPolicy {
18
+ readonly id: ExportContainer;
19
+ /** Lowercase file extensions without the dot; the first names an exported file. */
20
+ readonly extensions: readonly string[];
21
+ readonly mimeType: string;
22
+ /** Offered video codecs in the engine's spelling, the default first. */
23
+ readonly video: readonly EngineVideoCodec[];
24
+ /** Offered audio codecs, the default first; also the order a browser falls back in. */
25
+ readonly audio: readonly ExportAudioCodec[];
26
+ }
27
+ /** Every container's policy, in the engine's order. */
28
+ export declare const EXPORT_CONTAINERS: readonly ContainerPolicy[];
29
+ /** Why an export format request cannot be resolved. */
30
+ export type ExportFormatErrorReason = "unknown" | "unknown-extension" | "extension-mismatch" | "video-codec-not-offered" | "audio-codec-not-offered";
31
+ /** A container or codec request the policy refuses. */
32
+ export declare class ExportFormatError extends RangeError {
33
+ readonly reason: ExportFormatErrorReason;
34
+ constructor(reason: ExportFormatErrorReason, message: string);
35
+ }
36
+ /**
37
+ * The policy of a container.
38
+ *
39
+ * @throws ExportFormatError When `container` is not one of {@link EXPORT_CONTAINERS}.
40
+ */
41
+ export declare function containerPolicy(container: string): ContainerPolicy;
42
+ /** The container a file extension (without the dot) names, case-insensitively. */
43
+ export declare function containerFromExtension(extension: string): ExportContainer | undefined;
44
+ /** The video codec a browser export in `container` gets when it names none. */
45
+ export declare function defaultVideoCodec(container: ExportContainer): BrowserVideoCodec;
46
+ /** The audio codecs `container` offers, in the order a browser tries them. */
47
+ export declare function offeredAudioCodecs(container: ExportContainer): readonly ExportAudioCodec[];
48
+ /** A resolved export format, in the engine's codec spelling. */
49
+ export interface EngineExportFormat {
50
+ readonly container: ExportContainer;
51
+ readonly videoCodec: EngineVideoCodec;
52
+ readonly audioCodec: ExportAudioCodec;
53
+ }
54
+ /**
55
+ * Resolves an export's container and codecs, in the engine's codec spelling (`h264`): the same rule
56
+ * as the engine's `resolve_export_format`, which a native host applies to the same request.
57
+ *
58
+ * - `container` names the container. When it is absent, `extension` names it, and with neither
59
+ * (a browser export, which writes no path) it is MP4.
60
+ * - A named container and an extension must agree.
61
+ * - An absent codec is the container's default, and a named one must be one it offers.
62
+ *
63
+ * @throws ExportFormatError When the request breaks one of these rules.
64
+ */
65
+ export declare function resolveEngineExportFormat(request: {
66
+ readonly container?: string;
67
+ /** The output's extension without the dot, empty when it has none. */
68
+ readonly extension?: string;
69
+ readonly videoCodec?: string;
70
+ readonly audioCodec?: string;
71
+ }): EngineExportFormat;
72
+ /** A resolved export format, in the browser's codec spelling. */
73
+ export interface ExportFormat {
74
+ readonly container: ExportContainer;
75
+ readonly videoCodec: BrowserVideoCodec;
76
+ readonly audioCodec: ExportAudioCodec;
77
+ }
78
+ /**
79
+ * {@link resolveEngineExportFormat} in the browser's codec spelling (`avc`), for a browser sink.
80
+ *
81
+ * @throws ExportFormatError When the request breaks one of its rules.
82
+ */
83
+ export declare function resolveExportFormat(request: {
84
+ readonly container?: string;
85
+ /** The output's extension without the dot, empty when it has none. */
86
+ readonly extension?: string;
87
+ readonly videoCodec?: BrowserVideoCodec;
88
+ readonly audioCodec?: ExportAudioCodec;
89
+ }): ExportFormat;
@@ -0,0 +1,150 @@
1
+ /**
2
+ * Export containers: the file formats an export is written in, and which codecs each one offers.
3
+ *
4
+ * This is the engine's container policy (`alpha2_media::Container`), mirrored here as a constant so
5
+ * a browser sink, or a client of a native host, can validate a request before it opens an encoder
6
+ * or starts a host. Both copies are pinned by the shared corpus
7
+ * `tests/cases/export-container-corpus.json`. A container offers only the codecs its mainstream
8
+ * players decode in it, which is narrower than what mediabunny writes: QuickTime does not play
9
+ * VP9, AV1 or Opus in a MOV.
10
+ */
11
+ import { engineVideoCodec, } from "./rate-control.js";
12
+ /** Every container's policy, in the engine's order. */
13
+ export const EXPORT_CONTAINERS = [
14
+ {
15
+ id: "mp4",
16
+ extensions: ["mp4", "m4v"],
17
+ mimeType: "video/mp4",
18
+ video: ["h264", "hevc", "vp9", "av1", "mpeg4-part2"],
19
+ audio: ["aac", "opus"],
20
+ },
21
+ {
22
+ id: "mov",
23
+ extensions: ["mov"],
24
+ mimeType: "video/quicktime",
25
+ video: ["h264", "hevc", "mpeg4-part2"],
26
+ audio: ["aac"],
27
+ },
28
+ {
29
+ id: "mkv",
30
+ extensions: ["mkv"],
31
+ mimeType: "video/x-matroska",
32
+ video: ["h264", "hevc", "vp9", "av1", "mpeg4-part2"],
33
+ audio: ["aac", "opus"],
34
+ },
35
+ {
36
+ id: "webm",
37
+ extensions: ["webm"],
38
+ mimeType: "video/webm",
39
+ video: ["vp9", "av1"],
40
+ audio: ["opus"],
41
+ },
42
+ ];
43
+ /** A container or codec request the policy refuses. */
44
+ export class ExportFormatError extends RangeError {
45
+ reason;
46
+ constructor(reason, message) {
47
+ super(message);
48
+ this.name = "ExportFormatError";
49
+ this.reason = reason;
50
+ }
51
+ }
52
+ /**
53
+ * The policy of a container.
54
+ *
55
+ * @throws ExportFormatError When `container` is not one of {@link EXPORT_CONTAINERS}.
56
+ */
57
+ export function containerPolicy(container) {
58
+ const policy = EXPORT_CONTAINERS.find((entry) => entry.id === container);
59
+ if (policy === undefined)
60
+ throw new ExportFormatError("unknown", `unknown container "${container}"; expected one of ${EXPORT_CONTAINERS.map((entry) => entry.id).join(", ")}`);
61
+ return policy;
62
+ }
63
+ /** The container a file extension (without the dot) names, case-insensitively. */
64
+ export function containerFromExtension(extension) {
65
+ const lower = extension.toLowerCase();
66
+ return EXPORT_CONTAINERS.find((entry) => entry.extensions.includes(lower))
67
+ ?.id;
68
+ }
69
+ /** The video codec a browser export in `container` gets when it names none. */
70
+ export function defaultVideoCodec(container) {
71
+ return browserVideoCodec(containerPolicy(container).video[0]);
72
+ }
73
+ /** The audio codecs `container` offers, in the order a browser tries them. */
74
+ export function offeredAudioCodecs(container) {
75
+ return containerPolicy(container).audio;
76
+ }
77
+ /**
78
+ * Resolves an export's container and codecs, in the engine's codec spelling (`h264`): the same rule
79
+ * as the engine's `resolve_export_format`, which a native host applies to the same request.
80
+ *
81
+ * - `container` names the container. When it is absent, `extension` names it, and with neither
82
+ * (a browser export, which writes no path) it is MP4.
83
+ * - A named container and an extension must agree.
84
+ * - An absent codec is the container's default, and a named one must be one it offers.
85
+ *
86
+ * @throws ExportFormatError When the request breaks one of these rules.
87
+ */
88
+ export function resolveEngineExportFormat(request) {
89
+ const policy = resolveContainer(request.container, request.extension);
90
+ const video = request.videoCodec ?? policy.video[0];
91
+ if (!policy.video.includes(video))
92
+ throw new ExportFormatError("video-codec-not-offered", `${policy.id} does not offer video codec ${video}; it offers ${policy.video.join(", ")}`);
93
+ const audio = request.audioCodec ?? policy.audio[0];
94
+ if (!policy.audio.includes(audio))
95
+ throw new ExportFormatError("audio-codec-not-offered", `${policy.id} does not offer audio codec ${audio}; it offers ${policy.audio.join(", ")}`);
96
+ return {
97
+ container: policy.id,
98
+ videoCodec: video,
99
+ audioCodec: audio,
100
+ };
101
+ }
102
+ /**
103
+ * {@link resolveEngineExportFormat} in the browser's codec spelling (`avc`), for a browser sink.
104
+ *
105
+ * @throws ExportFormatError When the request breaks one of its rules.
106
+ */
107
+ export function resolveExportFormat(request) {
108
+ const { videoCodec, ...rest } = request;
109
+ const format = resolveEngineExportFormat({
110
+ ...rest,
111
+ ...(videoCodec === undefined
112
+ ? {}
113
+ : { videoCodec: engineVideoCodec(videoCodec) }),
114
+ });
115
+ return {
116
+ container: format.container,
117
+ videoCodec: browserVideoCodec(format.videoCodec),
118
+ audioCodec: format.audioCodec,
119
+ };
120
+ }
121
+ function resolveContainer(container, extension) {
122
+ if (container !== undefined) {
123
+ const policy = containerPolicy(container);
124
+ if (extension !== undefined &&
125
+ !policy.extensions.includes(extension.toLowerCase())) {
126
+ const found = extension === "" ? "no extension" : `".${extension}"`;
127
+ throw new ExportFormatError("extension-mismatch", `a ${policy.id} output must end in ${dotted(policy.extensions)}, not ${found}`);
128
+ }
129
+ return policy;
130
+ }
131
+ if (extension === undefined)
132
+ return containerPolicy("mp4");
133
+ const named = containerFromExtension(extension);
134
+ if (named !== undefined)
135
+ return containerPolicy(named);
136
+ const every = dotted(EXPORT_CONTAINERS.flatMap((entry) => entry.extensions));
137
+ throw new ExportFormatError("unknown-extension", extension === ""
138
+ ? `the output has no extension to name its container; use one of ${every}`
139
+ : `the output extension ".${extension}" names no container; use one of ${every}`);
140
+ }
141
+ function dotted(extensions) {
142
+ return extensions.map((extension) => `.${extension}`).join(", ");
143
+ }
144
+ function browserVideoCodec(codec) {
145
+ if (codec === "h264")
146
+ return "avc";
147
+ if (codec === "mpeg4-part2")
148
+ throw new ExportFormatError("video-codec-not-offered", "the browser has no mpeg4-part2 encoder");
149
+ return codec;
150
+ }
package/dist/effects.d.ts CHANGED
@@ -14,6 +14,10 @@ export interface EffectResourceSpec {
14
14
  readonly name: string;
15
15
  readonly kind: EffectResourceKind;
16
16
  }
17
+ /** An image an effect samples besides its source; an effect node binds it under `inputs.<name>`. */
18
+ export interface EffectInputSpec {
19
+ readonly name: string;
20
+ }
17
21
  /** Host-loaded bytes for one project effect resource. */
18
22
  export type EffectResourceData = {
19
23
  readonly id: string;
@@ -26,7 +30,7 @@ export interface BuiltinEffectCatalogEntry {
26
30
  readonly id: string;
27
31
  readonly version: number;
28
32
  readonly kind: EffectKind;
29
- readonly inputs: 1 | 2;
33
+ readonly inputs: readonly EffectInputSpec[];
30
34
  readonly label: string;
31
35
  readonly group: string;
32
36
  readonly params: readonly (EffectParameter & {
@@ -100,7 +104,13 @@ export interface EffectDefinition {
100
104
  readonly id: string;
101
105
  readonly version: number;
102
106
  readonly kind: EffectKind;
103
- readonly inputs: 1 | 2;
107
+ /**
108
+ * Images the effect samples besides its source, at most 8; only `kind: "effect"` declares them.
109
+ * The shader reads each as `sample_<name>(uv) -> vec4f` (premultiplied, sRGB-encoded, clamped at
110
+ * the edges, as `sample_src`) and `size_<name>() -> vec2f` (the bound texture's size in texels).
111
+ * The wrapper declares `input_<name>`, `sample_<name>` and `size_<name>`, so a body must not.
112
+ */
113
+ readonly inputs?: readonly EffectInputSpec[];
104
114
  readonly params?: readonly EffectParameter[];
105
115
  readonly resources?: readonly EffectResourceSpec[];
106
116
  /** WGSL the engine places into its effect shader; compile errors reject registration. */
@@ -105,6 +105,13 @@ export interface FrameSupplyDecodeOptions {
105
105
  * own), so a host keys what it keeps per source by this, as `liveSourceIds` names sources.
106
106
  */
107
107
  readonly sourceId: string;
108
+ /**
109
+ * `"software"`: decode this frame on the CPU, on a cursor of its own beside `consumerId`'s, and
110
+ * resolve with a `VideoFrame`. The supply asks for it when the browser could not read a
111
+ * hardware-decoded frame back; a host that cannot decode the source in software rejects. Absent
112
+ * for every other request.
113
+ */
114
+ readonly decode?: "software";
108
115
  }
109
116
  /** Host callbacks and frame geometry for one `supply` call. */
110
117
  export interface FrameSupplyOptions {
@@ -159,6 +166,25 @@ export interface FrameSupplyConfig extends FrameRetentionOptions {
159
166
  * default), or the browser (`"browser"`); see {@link VideoConversion}.
160
167
  */
161
168
  readonly videoConversion?: VideoConversion;
169
+ /**
170
+ * What becomes of a frame whose planes the browser cannot read back, once reading them again
171
+ * has failed: `"redecode"` (the default) decodes it again in software, which decodes the same
172
+ * picture, and fails the supply if that fails too; `"present"` gives it to the browser's
173
+ * conversion instead, unless the engine must convert it (HDR, or color the project declares),
174
+ * for a preview, where a frame shown at once matters more than the engine's conversion.
175
+ */
176
+ readonly unreadableFrames?: "redecode" | "present";
177
+ }
178
+ /** How a {@link FrameSupply} recovered frames the browser could not read back; cumulative. */
179
+ export interface ReadbackRecoveryStats {
180
+ /** Frames whose planes the browser still could not read back after the repeated reads. */
181
+ readonly unreadableFrames: number;
182
+ /** Reads repeated on the same frame. */
183
+ readonly readbackRetries: number;
184
+ /** Frames decoded again in software and copied from that decode. */
185
+ readonly redecodedFrames: number;
186
+ /** Frames given to the browser's conversion (`unreadableFrames: "present"`). */
187
+ readonly presentedFrames: number;
162
188
  }
163
189
  /**
164
190
  * Keeps completed source upload generations resident within a byte budget, releasing the oldest
@@ -204,6 +230,11 @@ export interface PlaybackResult {
204
230
  readonly presentedTimeTicks: number | null;
205
231
  readonly missingSources: readonly string[];
206
232
  readonly repeated: boolean;
233
+ /**
234
+ * The frame equals the one presented last, so the engine neither rendered nor presented it: the
235
+ * canvas still shows it, and a host copying the canvas elsewhere need not copy it again.
236
+ */
237
+ readonly unchanged: boolean;
207
238
  }
208
239
  /**
209
240
  * Engine surface this module drives.
@@ -293,6 +324,8 @@ export declare class FrameSupply {
293
324
  * source-side cost, apart from any output readback.
294
325
  */
295
326
  get sourceTransfer(): SourceTransferStats;
327
+ /** Frames the browser could not read back, and how they were recovered; cumulative. */
328
+ get readbackRecovery(): ReadbackRecoveryStats;
296
329
  /**
297
330
  * Uploads every source the engine asks for at one timestamp. Browser video stays as a
298
331
  * `VideoFrame` until the WebGPU external-image copy consumes it.
@@ -1,6 +1,6 @@
1
1
  // The engine's immutable project snapshot is the sole authority for frame keys. The host must not
2
2
  // derive them itself, for example by rounding (timelineSeconds - clip.start).
3
- import { copyPlanarYuvFrame, isHdrVideoFrame, isPlanarVideoFrame, PlanarCopyPool, uploadPlanarYuvFrame, } from "./hdr-frames.js";
3
+ import { isHdrVideoFrame, isPlanarVideoFrame, PlanarCopyPool, readPlanarYuvFrame, uploadPlanarYuvFrame, } from "./hdr-frames.js";
4
4
  import { decoderConsumerId } from "./media.js";
5
5
  import { sendsBitmaps, uploadPresentedFrame, } from "./presented-frames.js";
6
6
  import { PhysicalFrameAliases, } from "./physical-frames.js";
@@ -91,8 +91,15 @@ export class FrameSupply {
91
91
  #decodeWaiters = [];
92
92
  #cachedImageBytes = 0;
93
93
  #videoConversion;
94
+ #unreadableFrames;
94
95
  #planarCopyFrames = 0;
95
96
  #planarCopyBytes = 0;
97
+ #readback = {
98
+ unreadableFrames: 0,
99
+ readbackRetries: 0,
100
+ redecodedFrames: 0,
101
+ presentedFrames: 0,
102
+ };
96
103
  /** Buffers the planar copies reuse; each is given back once its upload has taken it. */
97
104
  #planarCopies = new PlanarCopyPool();
98
105
  #imageUse = 0n;
@@ -123,6 +130,10 @@ export class FrameSupply {
123
130
  if (videoConversion !== "engine" && videoConversion !== "browser")
124
131
  throw new RangeError('videoConversion must be "engine" or "browser"');
125
132
  this.#videoConversion = videoConversion;
133
+ const unreadableFrames = options.unreadableFrames ?? "redecode";
134
+ if (unreadableFrames !== "redecode" && unreadableFrames !== "present")
135
+ throw new RangeError('unreadableFrames must be "redecode" or "present"');
136
+ this.#unreadableFrames = unreadableFrames;
126
137
  this.#retainer = new FrameGenerationRetainer((generation) => this.#engine.releaseFrameGeneration(generation), options);
127
138
  }
128
139
  /** Bytes of rendered source textures kept resident; see {@link FrameRetentionOptions}. */
@@ -144,6 +155,10 @@ export class FrameSupply {
144
155
  planarCopyBytes: this.#planarCopyBytes,
145
156
  };
146
157
  }
158
+ /** Frames the browser could not read back, and how they were recovered; cumulative. */
159
+ get readbackRecovery() {
160
+ return { ...this.#readback };
161
+ }
147
162
  #trace(sourceId, mediaTimeTicks, pixels) {
148
163
  if (!this.onUpload)
149
164
  return;
@@ -267,18 +282,24 @@ export class FrameSupply {
267
282
  }
268
283
  let upload;
269
284
  if (planar !== undefined) {
270
- // The copy takes the frame over and closes it, failed or not.
285
+ // The copy takes the frame over and closes it, unless it hands it back for the
286
+ // browser's own upload below (`unreadableFrames: "present"`).
271
287
  decoded[decodedIndex] = { need, layer, source: null };
272
- const copied = await this.#copyPlanar(videoFrame, planar.declared);
273
- try {
274
- upload = uploadPlanarYuvFrame(this.#planarEngine(), need.sourceId, sourceTicks, copied, width, height);
288
+ const copied = await this.#copyPlanar(need, layer, videoFrame, planar, pixelsFor);
289
+ if (copied === undefined) {
290
+ decoded[decodedIndex] = { need, layer, source: videoFrame };
275
291
  }
276
- finally {
277
- // The upload copied the planes into the engine before it returned.
278
- this.#planarCopies.release(copied.data);
292
+ else {
293
+ try {
294
+ upload = uploadPlanarYuvFrame(this.#planarEngine(), need.sourceId, sourceTicks, copied, width, height);
295
+ }
296
+ finally {
297
+ // The upload copied the planes into the engine before it returned.
298
+ this.#planarCopies.release(copied.data);
299
+ }
279
300
  }
280
301
  }
281
- else {
302
+ if (upload === undefined) {
282
303
  const engine = this.#presentedEngine();
283
304
  const presented = [
284
305
  need.sourceId,
@@ -414,24 +435,111 @@ export class FrameSupply {
414
435
  isHdrVideoFrame(source.frame) ||
415
436
  (this.#videoConversion === "engine" && isPlanarVideoFrame(source.frame))))
416
437
  return { need, layer, source };
417
- return { need, layer, source, planar: { declared } };
418
- }
419
- /** Copies a frame out planar for the engine to convert; the copy closes the frame. */
420
- async #copyPlanar(source, declared) {
421
- const copied = await copyPlanarYuvFrame(source.frame, declared === undefined ? null : JSON.parse(declared), {
422
- ...(source.physicalTimeMicroseconds === undefined
423
- ? {}
424
- : { physicalTimeMicroseconds: source.physicalTimeMicroseconds }),
425
- ...(source.rotation === undefined ? {} : { rotation: source.rotation }),
426
- ...(source.mirror === undefined ? {} : { mirror: source.mirror }),
427
- ...(source.chromaSiting === undefined
428
- ? {}
429
- : { chromaSiting: source.chromaSiting }),
430
- }, this.#planarCopies);
438
+ return {
439
+ need,
440
+ layer,
441
+ source,
442
+ planar: {
443
+ declared,
444
+ required: enginesColor || isHdrVideoFrame(source.frame),
445
+ },
446
+ };
447
+ }
448
+ /**
449
+ * Copies a frame out planar for the engine to convert, and closes it.
450
+ *
451
+ * A frame whose planes the browser cannot read back (Chrome, now and then, for hardware-decoded
452
+ * frames) is read again, then decoded again in software and copied from that decode: the codecs
453
+ * define their decoding exactly, so the engine converts the planes it would have. With
454
+ * `unreadableFrames: "present"`, a frame the engine need not convert resolves `undefined`
455
+ * instead, left open for the browser's conversion. Rejects, the frame closed, when the copy
456
+ * fails otherwise or the software decode cannot serve it.
457
+ */
458
+ async #copyPlanar(need, layer, source, planar, pixelsFor) {
459
+ let copied;
460
+ try {
461
+ copied = await this.#readPlanes(source, planar.declared);
462
+ }
463
+ catch (error) {
464
+ if (!isUnreadableFrame(error)) {
465
+ source.frame.close();
466
+ throw error;
467
+ }
468
+ this.#readback.unreadableFrames += 1;
469
+ if (this.#unreadableFrames === "present" &&
470
+ !planar.required &&
471
+ takesPresentedFrames(this.#engine)) {
472
+ this.#readback.presentedFrames += 1;
473
+ return undefined;
474
+ }
475
+ const timestamp = source.physicalTimeMicroseconds ?? source.frame.timestamp;
476
+ source.frame.close();
477
+ copied = await this.#redecodePlanar(need, layer, planar, timestamp, pixelsFor, error);
478
+ }
479
+ source.frame.close();
431
480
  this.#planarCopyFrames += 1;
432
481
  this.#planarCopyBytes += copied.data.byteLength;
433
482
  return copied;
434
483
  }
484
+ /**
485
+ * The frame's planes, read again up to {@link READBACK_RETRIES} times, a task apart, while the
486
+ * browser fails to read them back. Leaves the frame open.
487
+ */
488
+ async #readPlanes(source, declared) {
489
+ const color = declared === undefined ? null : JSON.parse(declared);
490
+ for (let retry = 0;; retry += 1) {
491
+ try {
492
+ return await readPlanarYuvFrame(source.frame, color, planarIdentity(source), this.#planarCopies);
493
+ }
494
+ catch (error) {
495
+ if (retry >= READBACK_RETRIES || !isUnreadableFrame(error))
496
+ throw error;
497
+ this.#readback.readbackRetries += 1;
498
+ await nextTask();
499
+ }
500
+ }
501
+ }
502
+ /**
503
+ * Decodes `need` again in software and copies that frame out planar. Rejects with `cause` when
504
+ * the host cannot decode it in software, decodes another picture (another timestamp), or that
505
+ * copy fails too.
506
+ */
507
+ async #redecodePlanar(need, layer, planar, timestamp, pixelsFor, cause) {
508
+ const unrecovered = (reason, error = cause) => new Error(`the browser could not read back the frame of ${need.sourceId} at ${need.mediaTimeTicks}, and ${reason}`, { cause: error });
509
+ let decoded;
510
+ try {
511
+ decoded = await this.#decodeCursor(`${keyForNeed(need, layer)}\u0000software`, () => pixelsFor(layer, Number(BigInt(need.mediaTimeTicks)) / TICKS_PER_SECOND, {
512
+ preferVideoFrame: true,
513
+ consumerId: consumerOf(need),
514
+ sourceId: need.sourceId,
515
+ decode: "software",
516
+ }));
517
+ }
518
+ catch (error) {
519
+ throw unrecovered("decoding it again in software failed", error);
520
+ }
521
+ if (decoded === null ||
522
+ !("kind" in decoded) ||
523
+ decoded.kind !== "video-frame")
524
+ throw unrecovered("decoding it again in software gave no VideoFrame");
525
+ const again = decoded;
526
+ try {
527
+ const at = again.physicalTimeMicroseconds ?? again.frame.timestamp;
528
+ if (at !== timestamp)
529
+ throw unrecovered(`decoding it again in software gave the frame at ${at} us`);
530
+ const copied = await this.#readPlanes(again, planar.declared);
531
+ this.#readback.redecodedFrames += 1;
532
+ return copied;
533
+ }
534
+ catch (error) {
535
+ throw error instanceof Error && error.cause === cause
536
+ ? error
537
+ : unrecovered("the software decode's frame could not be copied either", error);
538
+ }
539
+ finally {
540
+ again.frame.close();
541
+ }
542
+ }
435
543
  /** The engine's presented RGBA uploads, called on the engine. */
436
544
  #presenter() {
437
545
  const engine = this.#engine;
@@ -726,6 +834,36 @@ function validatePositiveInteger(value, name) {
726
834
  throw new RangeError(`${name} must be a positive safe integer`);
727
835
  }
728
836
  }
837
+ /** Reads repeated on a frame whose planes the browser could not read back, before decoding again. */
838
+ const READBACK_RETRIES = 2;
839
+ /**
840
+ * Whether a planar copy failed because the browser could not read a GPU-backed frame back: Chrome
841
+ * rejects `copyTo` with `InvalidStateError` ("Failed to read VideoFrame data."), now and then, for
842
+ * hardware-decoded frames. A closed frame rejects with the same name, but the supply owns the
843
+ * frames it copies and has not closed them.
844
+ */
845
+ function isUnreadableFrame(error) {
846
+ return (typeof DOMException !== "undefined" &&
847
+ error instanceof DOMException &&
848
+ error.name === "InvalidStateError");
849
+ }
850
+ /** What a planar copy of `source` carries beyond the frame (see `PlanarFrameIdentity`). */
851
+ function planarIdentity(source) {
852
+ return {
853
+ ...(source.physicalTimeMicroseconds === undefined
854
+ ? {}
855
+ : { physicalTimeMicroseconds: source.physicalTimeMicroseconds }),
856
+ ...(source.rotation === undefined ? {} : { rotation: source.rotation }),
857
+ ...(source.mirror === undefined ? {} : { mirror: source.mirror }),
858
+ ...(source.chromaSiting === undefined
859
+ ? {}
860
+ : { chromaSiting: source.chromaSiting }),
861
+ };
862
+ }
863
+ /** Resolves once the browser has run other tasks, such as the GPU process's replies. */
864
+ function nextTask() {
865
+ return new Promise((resolve) => setTimeout(resolve, 0));
866
+ }
729
867
  /** Whether `engine` takes presented `VideoFrame` uploads (`uploadPresentedVideoFrame`). */
730
868
  function takesPresentedFrames(engine) {
731
869
  return typeof engine.uploadPresentedVideoFrame === "function";