@alpha2-sh/editor 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.
@@ -2,6 +2,7 @@
2
2
  // so encoded video never accumulates in memory. In-memory output is for small outputs sized up
3
3
  // front, never a silent fallback for a large one.
4
4
  import { estimatedOutputBytes, memoryOutputPeakBytes, MEMORY_OUTPUT_COPIES, MEMORY_OUTPUT_MARGIN, WritableFileDestination, } from "alpha2/export-destination";
5
+ import { containerPolicy } from "alpha2/containers";
5
6
  import { ExportFailureError } from "alpha2/export-failure";
6
7
  import { holdShared, whenUnheld } from "./locks.js";
7
8
  /** The most an in-memory output may hold at its peak unless asked otherwise. */
@@ -35,26 +36,30 @@ export function storageSupport() {
35
36
  * counts every write since its last disk scan, so `quota - usage` can be near zero on an empty
36
37
  * disk. A full disk fails at the write (`STORAGE_QUOTA_EXCEEDED`); the estimate is only reported.
37
38
  *
39
+ * `container` (default `mp4`) gives the temporary file its extension and the artifact its MIME
40
+ * type.
38
41
  * Returns `{ mode, destination, storageEstimate, abort, finish }`: `destination` is the sink's,
39
42
  * `abort` discards the file, and `finish(sinkOutput)` turns the finished output into the artifact's
40
43
  * fields.
41
44
  */
42
- export async function openExportOutput({ jobId, name, target, durationSeconds, videoBitrate, audioBitrate, }) {
45
+ export async function openExportOutput({ jobId, name, container = "mp4", target, durationSeconds, videoBitrate, audioBitrate, }) {
43
46
  const estimate = estimatedOutputBytes({
44
47
  durationSeconds,
45
48
  videoBitrate,
46
49
  audioBitrate,
47
50
  });
51
+ const policy = containerPolicy(container);
48
52
  const kind = target?.kind ?? "opfs";
49
53
  if (kind === "file")
50
54
  return openPickedFile(target.handle, estimate);
51
55
  if (kind === "opfs") {
52
- const opened = await openOriginPrivateFile(jobId, name, estimate);
56
+ const opened = await openOriginPrivateFile(jobId, name, policy, estimate);
53
57
  if (opened)
54
58
  return opened;
55
59
  }
56
60
  return openMemory(target?.maxBytes ?? DEFAULT_MEMORY_OUTPUT_LIMIT, estimate, {
57
61
  name,
62
+ mimeType: policy.mimeType,
58
63
  fellBack: kind !== "memory",
59
64
  });
60
65
  }
@@ -79,14 +84,14 @@ async function openPickedFile(handle, estimate) {
79
84
  }),
80
85
  };
81
86
  }
82
- async function openOriginPrivateFile(jobId, name, estimate) {
87
+ async function openOriginPrivateFile(jobId, name, policy, estimate) {
83
88
  const storage = globalThis.navigator?.storage;
84
89
  if (typeof storage?.getDirectory !== "function")
85
90
  return null;
86
91
  let directory;
87
92
  let handle;
88
93
  let writable;
89
- const fileName = `${Date.now()}-${jobId}.mp4`;
94
+ const fileName = `${Date.now()}-${jobId}.${policy.extensions[0]}`;
90
95
  // Held from before the file exists until it is removed, so another page's sweep leaves it alone.
91
96
  const lease = await holdShared(exportLock(fileName));
92
97
  try {
@@ -138,7 +143,7 @@ async function openOriginPrivateFile(jobId, name, estimate) {
138
143
  const file = await handle.getFile();
139
144
  return {
140
145
  kind: "file",
141
- file: new File([file], name, { type: "video/mp4" }),
146
+ file: new File([file], name, { type: policy.mimeType }),
142
147
  name,
143
148
  bytes: output.bytes,
144
149
  release: remove,
@@ -165,7 +170,7 @@ async function reportedStorage(storage, estimate) {
165
170
  belowEstimate: quota - usage < needed,
166
171
  };
167
172
  }
168
- function openMemory(limit, estimate, { name, fellBack }) {
173
+ function openMemory(limit, estimate, { name, mimeType, fellBack }) {
169
174
  const peak = memoryOutputPeakBytes(estimate);
170
175
  if (peak > limit)
171
176
  throw refused("RESOURCE_LIMIT", `${fellBack ? "This browser cannot write the export to disk, and an" : "An"} output of about ${megabytes(estimate)} needs up to ${megabytes(peak)} of memory while it is kept in memory, over the ${megabytes(limit)} limit. Export a shorter range or use the native exporter.`, { requestedBytes: peak, resource: "js" });
@@ -181,7 +186,7 @@ function openMemory(limit, estimate, { name, fellBack }) {
181
186
  abort: async () => { },
182
187
  finish: async (output) => ({
183
188
  kind: "blob",
184
- blob: new Blob([output.buffer], { type: "video/mp4" }),
189
+ blob: new Blob([output.buffer], { type: mimeType }),
185
190
  name,
186
191
  bytes: output.buffer.byteLength,
187
192
  }),
@@ -17,16 +17,24 @@ export const DEFAULT_RASTER_BUDGET_BYTES: number;
17
17
  export const DEFAULT_PROVIDER_SOURCE_BYTES: number;
18
18
  /** The host side of the engine's per-frame source requests for one renderer (preview or export). */
19
19
  export class SourcePixels {
20
- constructor(library: any, { decoderLimit, rasterBudgetBytes, providerSourceBytes, extensionsWasmUrl, }?: {
20
+ constructor(library: any, { decoderLimit, rasterBudgetBytes, providerSourceBytes, extensionsWasmUrl, videoDecode, }?: {
21
21
  decoderLimit?: number | undefined;
22
22
  rasterBudgetBytes?: number | undefined;
23
23
  providerSourceBytes?: number | undefined;
24
+ videoDecode?: string | undefined;
24
25
  });
25
26
  decoderLimit: number;
26
27
  rasterBudgetBytes: number;
27
28
  providerSourceBytes: number;
28
29
  library: any;
29
30
  extensionsWasmUrl: any;
31
+ /**
32
+ * How video decodes: `"auto"` lets the browser pick, a hardware decoder where it has one;
33
+ * `"software"` decodes on the CPU, so no frame needs a GPU readback, except a source the
34
+ * browser has no software decoder for, which decodes as `"auto"` and is reported in
35
+ * `decodeFallbacks`.
36
+ */
37
+ videoDecode: string;
30
38
  get diagnostics(): {
31
39
  liveDecoders: number;
32
40
  retainedFrameBytes: any;
@@ -58,16 +66,19 @@ export class SourcePixels {
58
66
  /**
59
67
  * Bound method handed to `FrameSupply` as its `pixelsFor` callback. `sourceId` is the source the
60
68
  * engine asked for, which the layer may stand in for (a proxy has an ID of its own): decoders are
61
- * kept per source, as `release` names them.
69
+ * kept per source, as `release` names them. `decode: "software"` asks for the frame decoded on
70
+ * the CPU (see `#softwareFrame`).
62
71
  */
63
- pixelsFor: (layer: any, seconds: any, { preferVideoFrame, consumerId, sourceId }?: {
72
+ pixelsFor: (layer: any, seconds: any, { preferVideoFrame, consumerId, sourceId, decode }?: {
64
73
  preferVideoFrame?: boolean | undefined;
65
74
  consumerId?: any;
66
75
  }) => Promise<any>;
67
76
  /**
68
- * The sources whose frames fell back from WebCodecs decoding, one entry each: the last reason,
69
- * how many frames, and whether its decoding stopped for good (it could not open, or failed
70
- * {@link MAX_DECODE_FAILURES} frames running). A browser export reports it.
77
+ * What fell back, per source and kind: `"element-seek"`, frames read by element seeks rather
78
+ * than decoded, with the last reason, how many frames, and whether its decoding stopped for good
79
+ * (it could not open, or failed {@link MAX_DECODE_FAILURES} frames running);
80
+ * `"software-unavailable"`, a source `videoDecode: "software"` decoded as `"auto"` because the
81
+ * browser has no software decoder for it (`frames` 0). A browser export reports it.
71
82
  */
72
83
  get decodeFallbacks(): any[];
73
84
  /** Keeps decoder sessions bounded to consumers needed by the current frame. */
@@ -53,7 +53,9 @@ export class SourcePixels {
53
53
  #fonts = [];
54
54
  /** What each SVG's pixels are with the fonts it was drawn with, for `contentOf`. */
55
55
  #fontContents = new WeakMap();
56
- constructor(library, { decoderLimit = 32, rasterBudgetBytes = DEFAULT_RASTER_BUDGET_BYTES, providerSourceBytes = DEFAULT_PROVIDER_SOURCE_BYTES, extensionsWasmUrl, } = {}) {
56
+ constructor(library, { decoderLimit = 32, rasterBudgetBytes = DEFAULT_RASTER_BUDGET_BYTES, providerSourceBytes = DEFAULT_PROVIDER_SOURCE_BYTES, extensionsWasmUrl, videoDecode = "auto", } = {}) {
57
+ if (videoDecode !== "auto" && videoDecode !== "software")
58
+ throw new RangeError('videoDecode must be "auto" or "software"');
57
59
  if (!Number.isSafeInteger(rasterBudgetBytes) || rasterBudgetBytes <= 0)
58
60
  throw new RangeError("rasterBudgetBytes must be a positive integer");
59
61
  if (!Number.isSafeInteger(providerSourceBytes) || providerSourceBytes <= 0)
@@ -63,6 +65,13 @@ export class SourcePixels {
63
65
  this.providerSourceBytes = providerSourceBytes;
64
66
  this.library = library;
65
67
  this.extensionsWasmUrl = extensionsWasmUrl;
68
+ /**
69
+ * How video decodes: `"auto"` lets the browser pick, a hardware decoder where it has one;
70
+ * `"software"` decodes on the CPU, so no frame needs a GPU readback, except a source the
71
+ * browser has no software decoder for, which decodes as `"auto"` and is reported in
72
+ * `decodeFallbacks`.
73
+ */
74
+ this.videoDecode = videoDecode;
66
75
  }
67
76
  get diagnostics() {
68
77
  const decoders = [...this.#decoders.values()]
@@ -126,10 +135,13 @@ export class SourcePixels {
126
135
  /**
127
136
  * Bound method handed to `FrameSupply` as its `pixelsFor` callback. `sourceId` is the source the
128
137
  * engine asked for, which the layer may stand in for (a proxy has an ID of its own): decoders are
129
- * kept per source, as `release` names them.
138
+ * kept per source, as `release` names them. `decode: "software"` asks for the frame decoded on
139
+ * the CPU (see `#softwareFrame`).
130
140
  */
131
- pixelsFor = async (layer, seconds, { preferVideoFrame = false, consumerId = layer.id, sourceId } = {}) => {
141
+ pixelsFor = async (layer, seconds, { preferVideoFrame = false, consumerId = layer.id, sourceId, decode } = {}) => {
132
142
  const asset = layer.asset ?? layer;
143
+ if (decode === "software")
144
+ return this.#softwareFrame(asset, seconds, consumerId, sourceId ?? asset.id);
133
145
  if (asset.provider)
134
146
  return this.#providerPixels(asset, providerKey(asset, consumerId), seconds);
135
147
  if (asset.kind === "text")
@@ -480,7 +492,7 @@ export class SourcePixels {
480
492
  decoder = undefined;
481
493
  }
482
494
  if (!decoder) {
483
- if (this.#decoders.size >= this.decoderLimit)
495
+ if (this.#cursorCount() >= this.decoderLimit)
484
496
  throw Object.assign(new Error("Video decoder budget reached"), {
485
497
  code: "resource_budget",
486
498
  });
@@ -501,7 +513,7 @@ export class SourcePixels {
501
513
  }
502
514
  // A decoder that cannot open (a codec the browser cannot decode) is the fallback's for good.
503
515
  try {
504
- decoder.video ??= await (decoder.opening ??= MediabunnyVideoDecoder.open(asset.id, asset.file));
516
+ decoder.video ??= await (decoder.opening ??= this.#openVideo(decoder));
505
517
  }
506
518
  catch (error) {
507
519
  decoder.opening = null;
@@ -522,7 +534,7 @@ export class SourcePixels {
522
534
  // decoder's surfaces do not hold up.
523
535
  closeOpened(decoder);
524
536
  try {
525
- decoder.opening = MediabunnyVideoDecoder.open(asset.id, asset.file);
537
+ decoder.opening = this.#openVideo(decoder);
526
538
  decoder.video = await decoder.opening;
527
539
  decoded = await decoder.video.refill(request);
528
540
  }
@@ -544,6 +556,96 @@ export class SourcePixels {
544
556
  chromaSiting: decoded.chromaSiting,
545
557
  };
546
558
  }
559
+ /** Decoder cursors the budget counts: the software cursors of recovered frames are not. */
560
+ #cursorCount() {
561
+ let count = 0;
562
+ for (const decoder of this.#decoders.values())
563
+ if (!decoder.software)
564
+ count += 1;
565
+ return count;
566
+ }
567
+ /**
568
+ * Opens `decoder`'s source as `videoDecode` says. A source the browser has no software decoder
569
+ * for opens as `"auto"`, for good, and is reported once in `decodeFallbacks`.
570
+ */
571
+ async #openVideo(decoder) {
572
+ const { asset } = decoder;
573
+ if (this.videoDecode !== "software" || decoder.softwareUnavailable)
574
+ return MediabunnyVideoDecoder.open(asset.id, asset.file);
575
+ try {
576
+ return await MediabunnyVideoDecoder.open(asset.id, asset.file, {
577
+ hardwareAcceleration: "prefer-software",
578
+ });
579
+ }
580
+ catch (error) {
581
+ if (error?.code !== "software_decode_unavailable")
582
+ throw error;
583
+ decoder.softwareUnavailable = true;
584
+ const key = `software-unavailable\u0000${decoder.sourceId}`;
585
+ if (!this.#fallbacks.has(key))
586
+ this.#fallbacks.set(key, {
587
+ kind: "software-unavailable",
588
+ sourceId: decoder.sourceId,
589
+ reason: String(error.message),
590
+ frames: 0,
591
+ permanent: false,
592
+ });
593
+ return MediabunnyVideoDecoder.open(asset.id, asset.file);
594
+ }
595
+ }
596
+ /**
597
+ * The frame at `seconds` decoded on the CPU, on a cursor of its own beside the consumer's: what
598
+ * `FrameSupply` asks for when the browser could not read a hardware frame back. Rejects rather
599
+ * than falling back to an element seek, whose frame would be the browser's again.
600
+ *
601
+ * The cursor shares the consumer's source and consumer IDs, so `retainConsumers` and `release`
602
+ * close it with the consumer's; it stays open between frames, as readback failures come in runs
603
+ * and the next one then decodes on from it.
604
+ */
605
+ async #softwareFrame(asset, seconds, consumerId, sourceId) {
606
+ if (!asset.file)
607
+ throw new Error(`${asset.id} has no file to decode in software`);
608
+ const cursor = `${decoderCursorKey(sourceId, consumerId)}\u0000software`;
609
+ let decoder = this.#decoders.get(cursor);
610
+ if (decoder && decoder.asset !== asset) {
611
+ await closeDecoder(decoder);
612
+ this.#decoders.delete(cursor);
613
+ decoder = undefined;
614
+ }
615
+ if (!decoder) {
616
+ decoder = {
617
+ sourceId,
618
+ asset,
619
+ consumerId,
620
+ software: true,
621
+ opening: null,
622
+ video: null,
623
+ };
624
+ this.#decoders.set(cursor, decoder);
625
+ }
626
+ try {
627
+ decoder.video ??= await (decoder.opening ??= MediabunnyVideoDecoder.open(asset.id, asset.file, { hardwareAcceleration: "prefer-software" }));
628
+ const decoded = await decoder.video.refill({
629
+ sourceId: asset.id,
630
+ mediaTimeTicks: BigInt(Math.round(seconds * TICKS_PER_SECOND)),
631
+ reason: "prefetch",
632
+ generation: 0,
633
+ });
634
+ return {
635
+ kind: "video-frame",
636
+ frame: decoded.frame,
637
+ rotation: decoded.rotationDegrees ?? 0,
638
+ mirror: decoded.mirror ?? false,
639
+ chromaSiting: decoded.chromaSiting,
640
+ physicalTimeMicroseconds: decoded.frame.timestamp,
641
+ };
642
+ }
643
+ catch (error) {
644
+ // The next request opens it again.
645
+ closeOpened(decoder);
646
+ throw error;
647
+ }
648
+ }
547
649
  /**
548
650
  * Records that `decoder`'s frame falls back to an element seek because of `error`; `permanent`
549
651
  * applies it to every later frame of the cursor.
@@ -554,6 +656,7 @@ export class SourcePixels {
554
656
  const reason = String(error?.message ?? error);
555
657
  const known = this.#fallbacks.get(decoder.sourceId);
556
658
  this.#fallbacks.set(decoder.sourceId, {
659
+ kind: "element-seek",
557
660
  sourceId: decoder.sourceId,
558
661
  reason,
559
662
  frames: (known?.frames ?? 0) + 1,
@@ -565,9 +668,11 @@ export class SourcePixels {
565
668
  return null;
566
669
  }
567
670
  /**
568
- * The sources whose frames fell back from WebCodecs decoding, one entry each: the last reason,
569
- * how many frames, and whether its decoding stopped for good (it could not open, or failed
570
- * {@link MAX_DECODE_FAILURES} frames running). A browser export reports it.
671
+ * What fell back, per source and kind: `"element-seek"`, frames read by element seeks rather
672
+ * than decoded, with the last reason, how many frames, and whether its decoding stopped for good
673
+ * (it could not open, or failed {@link MAX_DECODE_FAILURES} frames running);
674
+ * `"software-unavailable"`, a source `videoDecode: "software"` decoded as `"auto"` because the
675
+ * browser has no software decoder for it (`frames` 0). A browser export reports it.
571
676
  */
572
677
  get decodeFallbacks() {
573
678
  return [...this.#fallbacks.values()].map((entry) => ({ ...entry }));
@@ -1,6 +1,6 @@
1
1
  import type { Generator, MediaFingerprint, Project } from "alpha2/project";
2
2
  import type { AssetBinding, ConformReport, MediaPurpose } from "alpha2/assets";
3
- import type { BuiltinEffectCatalog } from "alpha2/effects";
3
+ import type { BuiltinEffectCatalog, EffectDefinition } from "alpha2/effects";
4
4
  import type { EditorSession } from "../core/session.js";
5
5
  import type { CapabilityReport, PlaybackPolicy } from "alpha2";
6
6
  import type { Capability } from "../ports/index.js";
@@ -180,15 +180,35 @@ export interface BrowserBridgeOptions {
180
180
  * module, loaded on first use.
181
181
  */
182
182
  readonly assetDecisions?: AssetBinding;
183
+ /**
184
+ * The preview resolution scale, default 0.5: frames render at the document's size times it
185
+ * (rounded as the engine rounds), above 0 and at most 8. At 1 the preview renders at the
186
+ * document's resolution, and text and effects match export pixel for pixel. See
187
+ * `BrowserBridge.setPreviewScale`.
188
+ */
189
+ readonly previewScale?: number;
183
190
  }
184
- /** Options of `BrowserBridge.startExport`. The file is an MP4. */
191
+ /** Options of `BrowserBridge.startExport`. */
185
192
  export interface BrowserExportOptions {
186
193
  /**
187
- * Default `avc`. Whether this browser encodes it is the browser's to say ({@link
188
- * BrowserBridge.videoEncoders}); an export with one it does not is refused before it renders, as
194
+ * The file format, default `mp4`. It names the file and decides which codecs an export may ask
195
+ * for (see `alpha2/containers`): `mov` takes no VP9, AV1 or Opus, and `webm` takes only VP9, AV1
196
+ * and Opus. A codec the container does not offer is refused before the export renders, as
189
197
  * `INVALID_INPUT`.
190
198
  */
199
+ readonly container?: "mp4" | "mov" | "mkv" | "webm";
200
+ /**
201
+ * Default: the container's (`avc`, or `vp9` for `webm`). Whether this browser encodes it is the
202
+ * browser's to say ({@link BrowserBridge.videoEncoders}); an export with one it does not is
203
+ * refused before it renders, as `INVALID_INPUT`.
204
+ */
191
205
  readonly videoCodec?: "avc" | "hevc" | "vp9" | "av1";
206
+ /**
207
+ * Default: the first of the container's audio codecs this browser encodes, in the container's
208
+ * order (AAC, then Opus, for `mp4` and `mkv`; AAC for `mov`; Opus for `webm`). A codec asked for
209
+ * that this browser cannot encode is refused before the export renders, as `INVALID_INPUT`.
210
+ */
211
+ readonly audioCodec?: "aac" | "opus";
192
212
  /**
193
213
  * One of the engine's quality levels (`very-low`, `low`, `medium`, `high`, `very-high`),
194
214
  * default `high`. The engine resolves it to a bitrate for the codec, size, and frame rate,
@@ -199,7 +219,8 @@ export interface BrowserExportOptions {
199
219
  readonly audioQuality?: string;
200
220
  /**
201
221
  * Default `true`. Audio is written only when an audible source is shown. An export with
202
- * audio is refused before it renders on a browser that encodes neither AAC nor Opus.
222
+ * audio is refused before it renders on a browser that encodes none of the container's audio
223
+ * codecs.
203
224
  */
204
225
  readonly includeAudio?: boolean;
205
226
  /**
@@ -238,6 +259,16 @@ export interface BrowserExportOptions {
238
259
  readonly memory?: {
239
260
  readonly inFlightBytes?: number;
240
261
  };
262
+ /**
263
+ * How source video decodes: `auto` (the default) lets the browser pick, a hardware decoder where
264
+ * it has one; `software` decodes on the CPU, so no frame is read back from the GPU, except a
265
+ * source the browser has no software decoder for, which decodes as `auto` and is reported in the
266
+ * result's `report.decodeFallbacks` (`kind: "software-unavailable"`). Either way the engine
267
+ * converts the same decoded values; a frame the browser cannot read back is decoded again in
268
+ * software. Another value is refused when the export starts, with an `EditorError`
269
+ * `invalid_video_decode`.
270
+ */
271
+ readonly videoDecode?: "auto" | "software";
241
272
  }
242
273
  /** Where a browser export writes its file. */
243
274
  export type ExportOutputTarget = {
@@ -326,12 +357,63 @@ export interface BrowserBridge {
326
357
  setMonitorVolume(value: number): void;
327
358
  /** The monitor volume `setMonitorVolume` last set; 1 until then. */
328
359
  readonly monitorVolume: number;
329
- /** Logs every source upload of the preview engine to the console, for debugging. */
360
+ /**
361
+ * Logs every source upload of the renderer that draws the preview (the worker's in worker mode)
362
+ * to the console, for debugging. Kept for later bindings.
363
+ */
330
364
  setTraceUploads(value: boolean): void;
331
- /** The preview engine's latest diagnostics sample (taken at most every 250 ms), or `null`. */
365
+ /**
366
+ * Turns per-pass GPU and CPU timing of the renderer that draws the preview on or off; the
367
+ * passes then appear in `diagnostics`. Off by default, since timing is profiling cost. Kept for
368
+ * later bindings.
369
+ */
370
+ setPassTiming(enabled: boolean): void;
371
+ /** The preview resolution scale (see `BrowserBridgeOptions.previewScale`). */
372
+ readonly previewScale: number;
373
+ /**
374
+ * Renders the preview at `scale` times the document's size from now on, and draws the current
375
+ * frame again; resolves once it is drawn. The bound canvas's backing store is always the size
376
+ * frames render at, not the document's: a host sizes the canvas on the page with CSS (as
377
+ * `EditorPreview` does). Rejects with `invalid_preview_scale` for a scale that is not above 0 and at
378
+ * most 8.
379
+ */
380
+ setPreviewScale(scale: number): Promise<void>;
381
+ /**
382
+ * The latest diagnostics sample of the renderer that draws the preview (taken at most every
383
+ * 250 ms; in worker mode the worker's), or `null`. Its `host` block holds, with the renderer's
384
+ * timing:
385
+ * - `renders`: frames the player drew;
386
+ * - `unchanged`: frames found equal to the one shown, so neither drawn nor presented;
387
+ * - `skippedRequests`: playback refreshes that asked for no frame, the one shown being the
388
+ * frame the clock asked for;
389
+ * - `bitmapTransfers`: frames copied to the bound canvas from another surface;
390
+ * - `renderSize`: `[width, height]` frames render at;
391
+ * - `previewScale`, and `backend` (`worker` or `main-thread`).
392
+ * Counters are cumulative (`renders` and `unchanged` per renderer, the others since
393
+ * `bindPreview`): subtract two samples for a rate.
394
+ */
332
395
  readonly diagnostics: Readonly<Record<string, unknown>> | null;
333
396
  /** The engine's built-in effects and transitions; `null` until a preview is bound. */
334
397
  readonly catalog: BuiltinEffectCatalog | null;
398
+ /**
399
+ * Adds runtime effects (and transitions) beyond the built-in catalog, so the document can draw
400
+ * them by `id@version`: every renderer the bridge makes registers them, the preview's (in its
401
+ * worker and on the main thread, and again after a lost GPU) and each export attempt's. They
402
+ * belong to the bridge, not the document: loading another project keeps them.
403
+ *
404
+ * With a preview bound, the definitions are compiled on its device, all or none, and the current
405
+ * frame is drawn again; the call rejects with `invalid_effect` naming the first one the engine
406
+ * refuses, and keeps none of them. Without one they are kept unchecked: `bindPreview` compiles
407
+ * them, and one refused then is dropped and reported to `onError` as `invalid_effect`. An export
408
+ * registers those kept when it starts, and an export attempt the engine refuses one in fails with
409
+ * `invalid_effect`.
410
+ *
411
+ * A definition registered already under the same `id@version` is skipped; a different one under
412
+ * it is refused (`effect_conflict`): a changed effect takes another version. Rejects with
413
+ * `invalid_effect` for a definition without a string `id` and an integer `version`, and once the
414
+ * bridge is disposed (`disposed`).
415
+ */
416
+ registerEffects(definitions: readonly EffectDefinition[]): Promise<void>;
335
417
  /**
336
418
  * Source `id` of the draft: its original while it is online, even where preview reads a proxy
337
419
  * (see {@link BrowserBridge.setPreviewMedia}), else the kept proxy standing in for it; opened
@@ -548,7 +630,8 @@ export interface BrowserBridge {
548
630
  * decisions must be loaded: call {@link BrowserBridge.conform} first, or pass `assetDecisions`.
549
631
  *
550
632
  * Throws synchronously when the bridge is disposed (`disposed`), another export runs
551
- * (`export_busy`), `frameRate` is not one the engine reads (`invalid_frame_rate`), the asset
633
+ * (`export_busy`), `frameRate` is not one the engine reads (`invalid_frame_rate`), `videoDecode`
634
+ * is not `auto` or `software` (`invalid_video_decode`), the asset
552
635
  * decisions are not loaded (`conform_pending`), the media is not ready (`ConformError`), or the
553
636
  * document does not compile. Everything later is reported through the job's `result`.
554
637
  */
@@ -581,16 +664,43 @@ export interface WorkerPreview {
581
664
  * previous call sent that stay as they were, so their decoders stay open. Any other asset is
582
665
  * released. `fonts: null` keeps the registered fonts.
583
666
  */
584
- replaceProject(project: Project, revision: number, assets?: readonly RuntimeAsset[], fonts?: readonly RuntimeFont[] | null, keep?: readonly string[]): Promise<void>;
667
+ replaceProject(project: Project, revision: number, assets?: readonly RuntimeAsset[], fonts?: readonly RuntimeFont[] | null, keep?: readonly string[]): Promise<{
668
+ /** `[width, height]` frames render at, which the worker's canvas now is; `null` when empty. */
669
+ renderSize: readonly [number, number] | null;
670
+ }>;
585
671
  /**
586
672
  * Renders the frame at `tick`. `rendered` is `false` for an empty project or a render
587
- * cancelled meanwhile. `bitmap` is present only with `bitmapOutput`, and the caller owns it.
673
+ * cancelled meanwhile. `unchanged` says the frame equals the one already shown, so nothing was
674
+ * drawn or presented and no `bitmap` comes: the surface it was copied to still shows it.
675
+ * `bitmap` is present only with `bitmapOutput`, and the caller owns it. `diagnostics` are the
676
+ * source decoders'; `engineDiagnostics` is the renderer's diagnostics sample, present when it
677
+ * is newer than the one the last reply carried.
588
678
  */
589
679
  seek(tick: number): Promise<{
590
680
  rendered: boolean;
681
+ unchanged: boolean;
591
682
  bitmap?: ImageBitmap;
592
683
  diagnostics: Readonly<Record<string, number>>;
684
+ engineDiagnostics?: Readonly<Record<string, unknown>>;
593
685
  }>;
686
+ /**
687
+ * Sets the preview resolution scale (see `BrowserBridgeOptions.previewScale`) and sizes the
688
+ * worker's canvas to it.
689
+ */
690
+ setPreviewScale(scale: number): Promise<{
691
+ renderSize: readonly [number, number] | null;
692
+ }>;
693
+ /** Turns per-pass timing and upload logging of the worker's renderer on or off. */
694
+ setTracing(options: {
695
+ passTiming?: boolean;
696
+ traceUploads?: boolean;
697
+ }): Promise<void>;
698
+ /**
699
+ * Compiles and registers runtime effects on the worker's renderer, all or none (see
700
+ * {@link BrowserBridge.registerEffects}); an `id@version` it holds already is skipped. Rejects
701
+ * with `invalid_effect` naming the first one the engine refuses.
702
+ */
703
+ registerEffects(effects: readonly EffectDefinition[]): Promise<void>;
594
704
  /** Mixes `frames` project-rate samples from `startSample`, one array per channel. */
595
705
  mix(startSample: number, frames: number): Promise<Float32Array[]>;
596
706
  /** Drops the render in flight; its `seek` resolves with `rendered: false`. */
@@ -11,8 +11,19 @@ import { AudioWindowSupplier, mixBlock } from "./runtime/audio.js";
11
11
  * decoders, and detaches the message handler.
12
12
  */
13
13
  export function installEditorWorker(scope) {
14
- let engine = null, pixels = null, audio = null, sessionId = null, bitmapOutput = false, currentProject = null, revision = -1, tail = Promise.resolve();
14
+ let engine = null, pixels = null, audio = null, sessionId = null, bitmapOutput = false, currentProject = null, revision = -1,
15
+ // The renderer's diagnostics snapshot last posted: a seek reply carries a new one only.
16
+ sentDiagnostics = null, tail = Promise.resolve();
15
17
  const assets = new Map(), library = { get: (id) => assets.get(id) };
18
+ const hasContent = (project) => project?.timeline.tracks.some((track) => (track.clips?.length ?? 0) + (track.captions?.cues.length ?? 0)) ?? false;
19
+ // The canvas is the size frames render at, the document's size times the preview scale; with
20
+ // nothing loaded it stays as it is.
21
+ const sizeCanvas = () => {
22
+ const size = hasContent(currentProject) ? engine.previewSize : null;
23
+ if (size)
24
+ engine.resize(size[0], size[1]);
25
+ return size;
26
+ };
16
27
  const context = () => ({
17
28
  width: engine.project.settings.width,
18
29
  height: engine.project.settings.height,
@@ -50,8 +61,9 @@ export function installEditorWorker(scope) {
50
61
  });
51
62
  const { Engine } = await import("./runtime/engine.js");
52
63
  engine = new Engine(request.canvas ??
53
- new OffscreenCanvas(request.width ?? 16, request.height ?? 16), pixels, library, request.runtimeAssets);
64
+ new OffscreenCanvas(request.width ?? 16, request.height ?? 16), pixels, library, request.runtimeAssets, { unreadableFrames: "present" });
54
65
  audio = new AudioWindowSupplier(library);
66
+ engine.backend = "worker";
55
67
  await engine.start();
56
68
  }
57
69
  else {
@@ -71,38 +83,57 @@ export function installEditorWorker(scope) {
71
83
  if (request.fonts)
72
84
  engine.setCaptionFonts(request.fonts);
73
85
  currentProject = request.project;
74
- if (currentProject.timeline.tracks.some((track) => (track.clips?.length ?? 0) +
75
- (track.captions?.cues.length ?? 0)))
86
+ if (hasContent(currentProject))
76
87
  engine.loadProject(request.project);
77
- engine.resize(request.project.settings.width, request.project.settings.height);
88
+ const renderSize = sizeCanvas();
89
+ // Sources are fitted in document space; the render scales them.
78
90
  pixels.setOutputSize(request.project.settings.width, request.project.settings.height);
79
91
  audio.configure(engine.audioEngine, request.project);
80
92
  revision = request.revision;
93
+ scope.postMessage({ ...response, ok: true, value: { renderSize } });
94
+ return;
81
95
  }
82
96
  else if (type === "seek") {
83
97
  const generation = engine.generation;
84
- const rendered = arrived !== epoch ||
85
- !currentProject?.timeline.tracks.some((track) => (track.clips?.length ?? 0) +
86
- (track.captions?.cues.length ?? 0))
87
- ? false
98
+ const { rendered, unchanged } = arrived !== epoch || !hasContent(currentProject)
99
+ ? { rendered: false, unchanged: false }
88
100
  : await engine.render(request.tick / 120000, {
89
101
  generation,
90
102
  context: context(),
91
103
  });
92
- const bitmap = rendered && bitmapOutput
104
+ // An unchanged frame was not presented: the surface it was copied to still shows it.
105
+ const bitmap = rendered && !unchanged && bitmapOutput
93
106
  ? engine.canvas.transferToImageBitmap()
94
107
  : null;
108
+ const engineDiagnostics = engine.lastDiagnostics !== sentDiagnostics
109
+ ? engine.lastDiagnostics
110
+ : null;
111
+ sentDiagnostics = engine.lastDiagnostics;
95
112
  scope.postMessage({
96
113
  ...response,
97
114
  ok: true,
98
115
  value: {
99
116
  rendered,
117
+ unchanged,
100
118
  diagnostics: pixels.diagnostics,
119
+ ...(engineDiagnostics ? { engineDiagnostics } : {}),
101
120
  ...(bitmap ? { bitmap } : {}),
102
121
  },
103
122
  }, bitmap ? [bitmap] : []);
104
123
  return;
105
124
  }
125
+ else if (type === "set-preview-scale") {
126
+ engine.setPreviewScale(request.scale);
127
+ const renderSize = sizeCanvas();
128
+ scope.postMessage({ ...response, ok: true, value: { renderSize } });
129
+ return;
130
+ }
131
+ else if (type === "set-tracing") {
132
+ if (request.passTiming !== undefined)
133
+ engine.setPassTiming(request.passTiming);
134
+ if (request.traceUploads !== undefined)
135
+ engine.traceUploads = request.traceUploads;
136
+ }
106
137
  else if (type === "audio-mix") {
107
138
  await audio.supply(request.startSample, request.frames);
108
139
  const planes = mixBlock(engine.audioEngine, request.startSample, request.frames, false);
@@ -114,6 +145,8 @@ export function installEditorWorker(scope) {
114
145
  engine.resize(request.width, request.height);
115
146
  else if (type === "register-fonts")
116
147
  engine.setCaptionFonts(request.fonts);
148
+ else if (type === "register-effects")
149
+ await engine.registerEffects(request.effects);
117
150
  else if (type === "dispose") {
118
151
  await audio.close();
119
152
  await engine.dispose();
@@ -217,6 +250,18 @@ export function createWorkerPreview(worker, { sessionId = crypto.randomUUID(), r
217
250
  await ready;
218
251
  return call("seek", { tick });
219
252
  },
253
+ async setPreviewScale(scale) {
254
+ await ready;
255
+ return call("set-preview-scale", { scale });
256
+ },
257
+ async setTracing(options) {
258
+ await ready;
259
+ return call("set-tracing", options);
260
+ },
261
+ async registerEffects(effects) {
262
+ await ready;
263
+ return call("register-effects", { effects });
264
+ },
220
265
  async mix(startSample, frames) {
221
266
  await ready;
222
267
  return call("audio-mix", { startSample, frames });