@alpha2-sh/editor 0.2.2 → 0.3.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/README.md CHANGED
@@ -38,7 +38,7 @@ editor.dispose();
38
38
 
39
39
  ## Browser bridge
40
40
 
41
- `@alpha2-sh/editor/browser` connects a session to the engine in the browser: import, preview, playback with audio, and export to an MP4 file through WebCodecs.
41
+ `@alpha2-sh/editor/browser` connects a session to the engine in the browser: import, preview, playback with audio, and export to an MP4, MOV, MKV or WebM file through WebCodecs.
42
42
 
43
43
  ```js
44
44
  import { createEditor, createEmptyDocument } from "@alpha2-sh/editor";
@@ -75,7 +75,7 @@ const placed = editor.dispatch({
75
75
  if (!placed.ok) throw placed.error;
76
76
  await bridge.seek(0);
77
77
 
78
- const artifact = await bridge.startExport({ videoCodec: "avc" }).result;
78
+ const artifact = await bridge.startExport({ container: "webm" }).result;
79
79
  // artifact.kind "file": a temporary file in the origin's private storage; release it once downloaded.
80
80
  if (artifact.kind === "file") await artifact.release();
81
81
 
@@ -86,7 +86,7 @@ await editor.dispose();
86
86
  - Import checks each file with the engine (media, fonts, `.cube` LUTs, SRT and WebVTT captions through `importCaptions`) and adds it to the document in one undoable step. `importSequence` imports numbered PNG or OpenEXR files as one image sequence.
87
87
  - `bindPreview` draws on a canvas. With `runtimeAssets.workerFactory`, a worker running the `@alpha2-sh/editor/preview-worker` entry renders the preview off the main thread; without one, or when the worker fails, the main thread does. `hashWorkerFactory` (`@alpha2-sh/editor/hash-worker`) and `extensionsWorkerFactory` (`@alpha2-sh/editor/extensions-worker`, with `extensionsWasmUrl`) move file hashing and SVG, animated image, Lottie and OpenEXR reading into workers too.
88
88
  - `seek`, `play` and `pause` move the playhead; with audio, playback follows the audio clock. Audio preview needs a cross-origin isolated page; editing and video preview do not.
89
- - `startExport` returns a job with `result`, progress (`subscribe`) and `cancel`. The output goes to a temporary file in the origin's private storage by default (`release()` deletes it), to a file the user picked (`output: { kind: "file", handle }`), or to memory (`output: { kind: "memory", maxBytes }`). Whether the browser encodes a codec is the browser's to say: `bridge.videoEncoders()` asks ahead, and an export with a codec the browser does not encode is refused before it renders.
89
+ - `startExport` returns a job with `result`, progress (`subscribe`) and `cancel`. `container` (`mp4` by default, `mov`, `mkv` or `webm`) names the file and decides the codecs: an absent `videoCodec` or `audioCodec` is the container's default (H.264 and AAC, or VP9 and Opus for WebM, with Opus where a browser cannot encode AAC in MP4 or MKV), and one the container does not offer is refused. The output goes to a temporary file in the origin's private storage by default (`release()` deletes it), to a file the user picked (`output: { kind: "file", handle }`), or to memory (`output: { kind: "memory", maxBytes }`). Whether the browser encodes a codec is the browser's to say: `bridge.videoEncoders()` asks ahead, and an export with a codec the browser does not encode is refused before it renders.
90
90
 
91
91
  ## React
92
92
 
@@ -2,6 +2,7 @@ import { frameAt, frameStart } from "../core/time.js";
2
2
  import { compileEditorDocument, EditorError, sequenceEnd, } from "../core/document.js";
3
3
  import { captionsAsset } from "../core/captions.js";
4
4
  import { MAX_CAPTION_FILE_BYTES } from "alpha2/project";
5
+ import { containerPolicy } from "alpha2/containers";
5
6
  import { drawnEffectResources, shownSources } from "../core/compositions.js";
6
7
  import { ResourceRegistry } from "./resources.js";
7
8
  import { ExportJob, requireExportFrameRate } from "./jobs.js";
@@ -197,7 +198,8 @@ export function createMediaAdapter({ extensionsWasmUrl, wasmUrl, hashWorkerFacto
197
198
  * @returns {import("./types.js").BrowserBridge}
198
199
  */
199
200
  export function createBrowserBridge(options) {
200
- const { editor, runtimeAssets = {}, mediaAdapter = createMediaAdapter(runtimeAssets), resourceLimit = 128, audio = true, onError = () => { }, assetDecisions, } = options;
201
+ const { editor, runtimeAssets = {}, mediaAdapter = createMediaAdapter(runtimeAssets), resourceLimit = 128, audio = true, onError = () => { }, assetDecisions, previewScale: initialPreviewScale = 0.5, } = options;
202
+ let previewScale = checkedPreviewScale(initialPreviewScale);
201
203
  // A test's stand-in for origin storage, kept out of the public options.
202
204
  const proxyStore =
203
205
  /** @type {{ proxyStore?: ProxyStore }} */ (options).proxyStore ??
@@ -428,7 +430,12 @@ export function createBrowserBridge(options) {
428
430
  // How the current or last playback was asked for, so a recovered preview plays on alike.
429
431
  playRequest = null, renderScheduled = false, raf = 0, playClock = null, loadRevision = 0, loadedAssets = new Map(), loadedSelection = "", loadedFonts = null, audioKey = null,
430
432
  // What the preview worker holds from its last load.
431
- workerSent = new Map(), workerFonts = null, refreshFrame = 0, monitorVolume = 1, playGeneration = 0, sessionGeneration = editor.generation;
433
+ workerSent = new Map(), workerFonts = null, refreshFrame = 0, monitorVolume = 1,
434
+ // Tracing the drawing renderer applies, kept for every renderer a binding makes.
435
+ passTiming = false, traceUploads = false,
436
+ // The worker's last renderer diagnostics snapshot, and counters since `bindPreview`: playback
437
+ // refreshes that asked for no frame, and frames copied to the bound canvas.
438
+ workerDiagnostics = null, skippedRequests = 0, bitmapTransfers = 0, playGeneration = 0, sessionGeneration = editor.generation;
432
439
  /**
433
440
  * Preview's media for a source of `document`: what the engine selected, the original unless it is
434
441
  * offline, opened as the document's source says.
@@ -744,11 +751,11 @@ export function createBrowserBridge(options) {
744
751
  reportRefusedFonts(refused, "preview");
745
752
  }
746
753
  engine.loadProject(compiled.project);
747
- engine.resize(compiled.project.settings.width, compiled.project.settings.height);
748
- if (boundCanvas.width !== compiled.project.settings.width)
749
- boundCanvas.width = compiled.project.settings.width;
750
- if (boundCanvas.height !== compiled.project.settings.height)
751
- boundCanvas.height = compiled.project.settings.height;
754
+ // Frames render at the document's size times the preview scale, and the surfaces are that
755
+ // size: the engine rounds it.
756
+ let renderSize = engine.previewSize;
757
+ engine.resize(renderSize[0], renderSize[1]);
758
+ // Sources are fitted in document space; the render scales them.
752
759
  sources.setOutputSize(compiled.project.settings.width, compiled.project.settings.height);
753
760
  audioKey = null;
754
761
  if (workerPreview) {
@@ -792,15 +799,18 @@ export function createBrowserBridge(options) {
792
799
  workerSent = new Map();
793
800
  workerFonts = null;
794
801
  try {
795
- await workerPreview.replaceProject(compiled.project, ++loadRevision, workerAssets, sendFonts ? allFonts : null, keep);
802
+ const reply = await workerPreview.replaceProject(compiled.project, ++loadRevision, workerAssets, sendFonts ? allFonts : null, keep);
796
803
  workerSent = new Map(used);
797
804
  workerFonts = allFonts;
805
+ if (reply?.renderSize)
806
+ renderSize = reply.renderSize;
798
807
  }
799
808
  catch (error) {
800
809
  // The main renderer has just loaded the same project.
801
810
  await abandonWorker(error);
802
811
  }
803
812
  }
813
+ sizeBoundCanvas(renderSize);
804
814
  renderKey = key;
805
815
  }
806
816
  if (settled && audioKey !== key) {
@@ -1036,10 +1046,15 @@ export function createBrowserBridge(options) {
1036
1046
  if (workerPreview) {
1037
1047
  try {
1038
1048
  const result = await workerPreview.seek(at);
1039
- if (result.bitmap)
1049
+ if (result.engineDiagnostics)
1050
+ workerDiagnostics = result.engineDiagnostics;
1051
+ // An unchanged frame comes without a bitmap: the canvas still shows it.
1052
+ if (result.bitmap) {
1040
1053
  boundCanvas
1041
1054
  .getContext("bitmaprenderer")
1042
1055
  .transferFromImageBitmap(result.bitmap);
1056
+ bitmapTransfers += 1;
1057
+ }
1043
1058
  return result.rendered;
1044
1059
  }
1045
1060
  catch (error) {
@@ -1049,16 +1064,38 @@ export function createBrowserBridge(options) {
1049
1064
  await abandonWorker(error);
1050
1065
  }
1051
1066
  }
1052
- const rendered = await engine.render(at / 120000, {
1067
+ const { rendered, unchanged } = await engine.render(at / 120000, {
1053
1068
  generation: engine.generation,
1054
1069
  context: context(project, library),
1055
1070
  });
1056
- if (rendered && copySurface)
1071
+ // An unchanged frame was not presented: the bound canvas still shows the last copy.
1072
+ if (rendered && !unchanged && copySurface) {
1057
1073
  boundCanvas
1058
1074
  .getContext("bitmaprenderer")
1059
1075
  .transferFromImageBitmap(engine.canvas.transferToImageBitmap());
1076
+ bitmapTransfers += 1;
1077
+ }
1060
1078
  return rendered;
1061
1079
  }
1080
+ /** Gives the bound canvas the size frames render at, which `size` is, unless it has it. */
1081
+ function sizeBoundCanvas(size) {
1082
+ if (!boundCanvas || !size)
1083
+ return;
1084
+ if (boundCanvas.width !== size[0])
1085
+ boundCanvas.width = size[0];
1086
+ if (boundCanvas.height !== size[1])
1087
+ boundCanvas.height = size[1];
1088
+ }
1089
+ /** Applies the bridge's tracing to the renderers drawing now. */
1090
+ function applyTracing() {
1091
+ if (engine) {
1092
+ engine.traceUploads = traceUploads;
1093
+ engine.setPassTiming?.(passTiming);
1094
+ }
1095
+ void workerPreview
1096
+ ?.setTracing({ passTiming, traceUploads })
1097
+ .catch(() => { });
1098
+ }
1062
1099
  /**
1063
1100
  * Gives up the preview worker after `error`, whether it failed to start, to load a project or to
1064
1101
  * draw: the main renderer, which loads every project the worker does, draws from then on, off
@@ -1179,7 +1216,7 @@ export function createBrowserBridge(options) {
1179
1216
  playing = true;
1180
1217
  playRequest = { rate, loop, policy };
1181
1218
  const clock = (playClock = engine.playbackClock(policy, project.settings.frame_rate, rate, tick, performance.now()));
1182
- // For a policy that waits for frames: the tick last asked for, and whether it has been shown.
1219
+ // The tick last asked for, and for a policy that waits for frames, whether it has been shown.
1183
1220
  let requested = null, presented = false;
1184
1221
  const step = (now) => {
1185
1222
  if (!playing || disposed || generation !== playGeneration)
@@ -1208,15 +1245,17 @@ export function createBrowserBridge(options) {
1208
1245
  .catch(onError);
1209
1246
  return;
1210
1247
  }
1211
- // A waiting policy asks for each frame once and moves on only after it is shown; the others
1212
- // ask for the newest time and let late frames go.
1213
- const due = waits ? requested !== tick : true;
1214
- if (due && !renderScheduled) {
1248
+ // The clock asks for frame starts, so every policy asks for each frame once however often
1249
+ // the display refreshes; a waiting policy also moves on only after it is shown, and the
1250
+ // others let late frames go.
1251
+ const due = requested !== tick;
1252
+ if (!due)
1253
+ skippedRequests += 1;
1254
+ else if (!renderScheduled) {
1215
1255
  renderScheduled = true;
1216
- if (waits) {
1217
- requested = tick;
1256
+ requested = tick;
1257
+ if (waits)
1218
1258
  presented = false;
1219
- }
1220
1259
  const at = tick;
1221
1260
  void enqueue(() => generation !== playGeneration ? false : renderAt(at, project))
1222
1261
  .then(() => {
@@ -1254,12 +1293,14 @@ export function createBrowserBridge(options) {
1254
1293
  extensionsWasmUrl: runtimeAssets.extensionsWasmUrl,
1255
1294
  });
1256
1295
  const { Engine } = await import("./runtime/engine.js");
1296
+ // Until a project loads and gives the render size (see `loaded`).
1257
1297
  canvas.width = editor.document.project.settings.width;
1258
1298
  canvas.height = editor.document.project.settings.height;
1259
1299
  boundCanvas = canvas;
1260
1300
  copySurface = false;
1261
1301
  await workerPreview?.dispose();
1262
1302
  workerPreview = null;
1303
+ workerDiagnostics = null;
1263
1304
  const useWorker = features.worker.available && typeof canvas.getContext === "function";
1264
1305
  engine = new Engine(useWorker ? new OffscreenCanvas(canvas.width, canvas.height) : canvas, sources, library, runtimeAssets);
1265
1306
  mixer = new EngineAudioMixer(runtimeAssets, { enabled: audio });
@@ -1268,7 +1309,9 @@ export function createBrowserBridge(options) {
1268
1309
  supplier = new AudioWindowSupplier(library);
1269
1310
  try {
1270
1311
  await engine.start();
1312
+ engine.setPreviewScale(previewScale);
1271
1313
  capabilities = capabilityReport(engine.capabilityReport());
1314
+ await registerKeptEffects();
1272
1315
  // The surface already shows copied frames (its context is a bitmap renderer's).
1273
1316
  if (useWorker && workerGivenUp)
1274
1317
  copySurface = true;
@@ -1290,11 +1333,16 @@ export function createBrowserBridge(options) {
1290
1333
  // A worker that cannot start leaves the surface to the main renderer.
1291
1334
  try {
1292
1335
  await workerPreview.ready;
1336
+ await workerPreview.setPreviewScale(previewScale);
1337
+ if (effectDefinitions.size)
1338
+ await workerPreview.registerEffects(keptEffects());
1293
1339
  }
1294
1340
  catch (error) {
1295
1341
  await abandonWorker(error);
1296
1342
  }
1297
1343
  }
1344
+ if (passTiming || traceUploads)
1345
+ applyTracing();
1298
1346
  if (disposed || token !== binding) {
1299
1347
  await engine.dispose();
1300
1348
  engine = null;
@@ -1346,6 +1394,68 @@ export function createBrowserBridge(options) {
1346
1394
  }
1347
1395
  return true;
1348
1396
  }
1397
+ /**
1398
+ * Runtime effects `registerEffects` kept, by `id@version`, with their JSON text, in the order they
1399
+ * came: every renderer the bridge makes registers them.
1400
+ */
1401
+ const effectDefinitions = new Map();
1402
+ const keptEffects = () => [...effectDefinitions.values()].map(({ definition }) => definition);
1403
+ function registerEffects(definitions) {
1404
+ return enqueue(async () => {
1405
+ const added = new Map();
1406
+ for (const definition of definitions) {
1407
+ if (typeof definition?.id !== "string" ||
1408
+ !Number.isInteger(definition.version))
1409
+ throw new EditorError("invalid_effect", "An effect definition needs a string id and an integer version", "effects");
1410
+ const key = `${definition.id}@${definition.version}`;
1411
+ const text = JSON.stringify(definition);
1412
+ const known = (added.get(key) ?? effectDefinitions.get(key))?.text;
1413
+ if (known === text)
1414
+ continue;
1415
+ if (known !== undefined)
1416
+ throw new EditorError("effect_conflict", `Effect ${key} is registered with another definition; a changed effect takes another version`, "effects", key);
1417
+ added.set(key, { definition, text });
1418
+ }
1419
+ if (!added.size)
1420
+ return;
1421
+ const fresh = [...added.values()].map(({ definition }) => definition);
1422
+ // The main renderer loads every project the worker does, so both hold every effect.
1423
+ if (engine)
1424
+ await engine.registerEffects(fresh);
1425
+ if (workerPreview) {
1426
+ try {
1427
+ await workerPreview.registerEffects(fresh);
1428
+ }
1429
+ catch (error) {
1430
+ // The main renderer has just registered the same definitions.
1431
+ await abandonWorker(error);
1432
+ }
1433
+ }
1434
+ for (const [key, entry] of added)
1435
+ effectDefinitions.set(key, entry);
1436
+ // A frame that drew one of them failed; it draws now.
1437
+ if (engine)
1438
+ refreshPreview();
1439
+ });
1440
+ }
1441
+ /**
1442
+ * Registers the kept runtime effects on the main renderer `buildPreview` just started, one by
1443
+ * one: one its device refuses (kept while no preview was bound, so never compiled) is dropped and
1444
+ * reported, and the others draw. A device lost meanwhile drops none: the next render makes the
1445
+ * preview again, which registers them again.
1446
+ */
1447
+ async function registerKeptEffects() {
1448
+ const kept = [...effectDefinitions];
1449
+ const results = await Promise.allSettled(kept.map(([, { definition }]) => engine.registerEffects([definition])));
1450
+ if (engine.deviceLost)
1451
+ return;
1452
+ for (const [index, result] of results.entries()) {
1453
+ if (result.status === "fulfilled")
1454
+ continue;
1455
+ effectDefinitions.delete(kept[index][0]);
1456
+ onError(result.reason);
1457
+ }
1458
+ }
1349
1459
  /** Whether a renderer is ready, making it again first if a lost GPU left none. */
1350
1460
  async function previewReady() {
1351
1461
  if (engine)
@@ -1354,11 +1464,43 @@ export function createBrowserBridge(options) {
1354
1464
  return false;
1355
1465
  return recoverPreview();
1356
1466
  }
1467
+ /**
1468
+ * Renders the preview at `scale` times the document's size from now on, sizing the surfaces to
1469
+ * it, and draws the current frame again. Resolves once that frame is drawn.
1470
+ */
1471
+ async function setPreviewScale(scale) {
1472
+ const next = checkedPreviewScale(scale);
1473
+ if (next === previewScale)
1474
+ return;
1475
+ previewScale = next;
1476
+ await enqueue(async () => {
1477
+ if (!engine || disposed)
1478
+ return;
1479
+ engine.setPreviewScale(previewScale);
1480
+ let size = renderKey === null ? null : engine.previewSize;
1481
+ if (size)
1482
+ engine.resize(size[0], size[1]);
1483
+ if (workerPreview) {
1484
+ try {
1485
+ const reply = await workerPreview.setPreviewScale(previewScale);
1486
+ if (reply?.renderSize)
1487
+ size = reply.renderSize;
1488
+ }
1489
+ catch (error) {
1490
+ await abandonWorker(error);
1491
+ }
1492
+ }
1493
+ sizeBoundCanvas(size);
1494
+ await renderAt(tick, await loaded());
1495
+ });
1496
+ }
1357
1497
  async function bindPreview(canvas) {
1358
1498
  const token = ++binding;
1359
1499
  await enqueue(async () => {
1360
1500
  recoveryPending = false;
1361
1501
  workerGivenUp = false;
1502
+ skippedRequests = 0;
1503
+ bitmapTransfers = 0;
1362
1504
  if (!(await buildPreview(canvas, token)))
1363
1505
  return;
1364
1506
  // The surface is bound; a failing first frame is reported like any later one.
@@ -1596,7 +1738,7 @@ export function createBrowserBridge(options) {
1596
1738
  throw new EditorError("export_busy", "Only one export may run per bridge", "export");
1597
1739
  requireExportFrameRate(options.frameRate);
1598
1740
  materializeText(editor.document);
1599
- const snapshot = editor.document, revision = editor.revision;
1741
+ const snapshot = editor.document, revision = editor.revision, effects = keptEffects();
1600
1742
  const compiled = compileEditorDocument(snapshot);
1601
1743
  if (compiled.diagnostics.length)
1602
1744
  throw compiled.diagnostics[0];
@@ -1647,6 +1789,8 @@ export function createBrowserBridge(options) {
1647
1789
  signal.throwIfAborted();
1648
1790
  await renderer.start();
1649
1791
  signal.throwIfAborted();
1792
+ await renderer.registerEffects(effects, "export");
1793
+ signal.throwIfAborted();
1650
1794
  renderer.loadProject(project, "export");
1651
1795
  const refused = renderer.setCaptionFonts(fontStack);
1652
1796
  // Heard once per job, not once per attempt.
@@ -1662,7 +1806,6 @@ export function createBrowserBridge(options) {
1662
1806
  if (range.end <= range.start)
1663
1807
  throw new EditorError("empty_export", "Project has no exportable range", "export");
1664
1808
  const settings = project.settings;
1665
- const name = `${project.name}.mp4`;
1666
1809
  const { written, output, result } = await exportTimeline({
1667
1810
  engine: renderer.wasm,
1668
1811
  project,
@@ -1679,9 +1822,10 @@ export function createBrowserBridge(options) {
1679
1822
  audioSupplier: audio,
1680
1823
  range: { start: range.start / 120000, end: range.end / 120000 },
1681
1824
  options: attemptOptions(options, attempt, project.settings),
1682
- openOutput: (estimate) => openExportOutput({
1825
+ openOutput: ({ container, ...estimate }) => openExportOutput({
1683
1826
  jobId: attempt.id.replace(/[^\w-]/g, "_"),
1684
- name,
1827
+ name: `${project.name}.${containerPolicy(container).extensions[0]}`,
1828
+ container,
1685
1829
  target: options.output,
1686
1830
  ...estimate,
1687
1831
  }),
@@ -2161,11 +2305,33 @@ export function createBrowserBridge(options) {
2161
2305
  return monitorVolume;
2162
2306
  },
2163
2307
  setTraceUploads(value) {
2164
- if (engine)
2165
- engine.traceUploads = value;
2308
+ traceUploads = value === true;
2309
+ applyTracing();
2310
+ },
2311
+ setPassTiming(enabled) {
2312
+ passTiming = enabled === true;
2313
+ applyTracing();
2166
2314
  },
2315
+ get previewScale() {
2316
+ return previewScale;
2317
+ },
2318
+ setPreviewScale,
2167
2319
  get diagnostics() {
2168
- return engine?.lastDiagnostics ?? null;
2320
+ // The renderer that draws: in worker mode the main-thread one does not.
2321
+ const snapshot = workerPreview
2322
+ ? workerDiagnostics
2323
+ : (engine?.lastDiagnostics ?? null);
2324
+ if (!snapshot)
2325
+ return null;
2326
+ return {
2327
+ ...snapshot,
2328
+ host: {
2329
+ ...snapshot.host,
2330
+ skippedRequests,
2331
+ bitmapTransfers,
2332
+ previewScale,
2333
+ },
2334
+ };
2169
2335
  },
2170
2336
  get tick() {
2171
2337
  return tick;
@@ -2196,6 +2362,7 @@ export function createBrowserBridge(options) {
2196
2362
  get catalog() {
2197
2363
  return engine?.catalog ?? null;
2198
2364
  },
2365
+ registerEffects,
2199
2366
  // A source's own media while it is online, whichever preview reads: its size, file and peaks
2200
2367
  // are the original's.
2201
2368
  getAsset: (id) => (preferredPreviewMedia === "proxies" &&
@@ -2203,6 +2370,15 @@ export function createBrowserBridge(options) {
2203
2370
  library.get(id),
2204
2371
  };
2205
2372
  }
2373
+ /**
2374
+ * `scale` as a preview resolution scale: finite, above 0 and at most 8, as the engine's quality
2375
+ * profile takes it.
2376
+ */
2377
+ function checkedPreviewScale(scale) {
2378
+ if (typeof scale !== "number" || !(scale > 0 && scale <= 8))
2379
+ throw new EditorError("invalid_preview_scale", "The preview scale must be a number above 0 and at most 8", "preview");
2380
+ return scale;
2381
+ }
2206
2382
  /**
2207
2383
  * Whether the engine draws a source itself, so no file backs it: a generated source or a
2208
2384
  * composition.
@@ -10,6 +10,8 @@ export class Engine {
10
10
  library: any;
11
11
  kind: string;
12
12
  traceUploads: boolean;
13
+ /** Which preview draws with this renderer, as its diagnostics report it. */
14
+ backend: string;
13
15
  lastDiagnostics: any;
14
16
  lastRenderMs: number;
15
17
  onDiagnostics: any;
@@ -19,6 +21,19 @@ export class Engine {
19
21
  effectCatalog: any;
20
22
  }>;
21
23
  catalog: any;
24
+ /**
25
+ * Turns per-pass GPU and CPU timing on or off; the passes then appear in `lastDiagnostics`.
26
+ * Off by default: timing is profiling cost, not rendering work.
27
+ */
28
+ setPassTiming(enabled: any): void;
29
+ /**
30
+ * Sets the preview resolution scale (the engine's `QualityProfile` resolution scale; 1 renders
31
+ * at the document's size) and returns the loaded project's render size as `[width, height]`, or
32
+ * null with no project loaded. Throws for a scale the engine refuses.
33
+ */
34
+ setPreviewScale(scale: any): any[] | null;
35
+ /** The loaded project's render size at the preview scale, `[width, height]`, or null. */
36
+ get previewSize(): any[] | null;
22
37
  /** The renderer's part of the capability report: GPU, color, and playback. */
23
38
  capabilityReport(): any;
24
39
  /** A clock for one run of playback; see the engine's `PlaybackPolicy`. */
@@ -46,6 +61,15 @@ export class Engine {
46
61
  * failure stay known, so the next load neither leaks nor repeats them.
47
62
  */
48
63
  loadProject(project: any, operation?: string): void;
64
+ /**
65
+ * Compiles runtime effect definitions (`alpha2/effects` `EffectDefinition`s) on this renderer's
66
+ * device and registers them, all or none. An `id@version` this renderer holds already is skipped:
67
+ * a definition never changes under its version.
68
+ *
69
+ * Throws `invalid_effect` naming the first definition the engine refuses, with its diagnostics;
70
+ * then none of the call's definitions is registered.
71
+ */
72
+ registerEffects(definitions: any, operation?: string): Promise<void>;
49
73
  /**
50
74
  * Registers the fonts caption tracks draw with, in fallback order. An SVG's text draws with the
51
75
  * same fonts, as the native host draws it with its caption fonts. Returns the fonts the engine
@@ -77,7 +101,9 @@ export class Engine {
77
101
  get generation(): number;
78
102
  /**
79
103
  * Requests one frame. Concurrent requests collapse to the most recent one so that scrubbing never
80
- * queues a backlog of stale frames.
104
+ * queues a backlog of stale frames. Resolves `{ rendered, unchanged }`: `rendered` is false when
105
+ * the request was superseded, and `unchanged` says the frame equals the one already shown, so
106
+ * nothing was drawn or presented and the surface still shows it.
81
107
  */
82
108
  render(seconds: any, { generation, context }?: {
83
109
  generation?: null | undefined;
@@ -9,6 +9,8 @@ import { EditorError } from "../../core/document.js";
9
9
  const RESULT_CACHE_FRAMES = 6;
10
10
  /** The diagnostics panel refreshes at this rate, not at the render rate. */
11
11
  const DIAGNOSTICS_INTERVAL_MS = 250;
12
+ /** A runtime effect definition's identity, `id@version`, as the engine names it. */
13
+ const effectKey = (definition) => `${definition.id}@${definition.version}`;
12
14
  /**
13
15
  * The wasm renderer of one preview or export: owns the engine instance, its frame supply, and a
14
16
  * render queue that collapses to the newest request.
@@ -25,6 +27,11 @@ export class Engine {
25
27
  #lastDiagnosticsAt = 0;
26
28
  #fps = [];
27
29
  #effectResources = new Map();
30
+ /** The runtime effects registered on this renderer, as `id@version`. */
31
+ #effects = new Set();
32
+ /** Frames the player drew, and frames it found equal to the one shown; cumulative. */
33
+ #renders = 0;
34
+ #unchanged = 0;
28
35
  /** What `supply` uploaded for the export frame the engine has not rendered yet. */
29
36
  #exportUploads = [];
30
37
  constructor(canvas, sources, library, runtimeAssets = {}) {
@@ -34,6 +41,8 @@ export class Engine {
34
41
  this.library = library;
35
42
  this.kind = "wasm";
36
43
  this.traceUploads = false;
44
+ /** Which preview draws with this renderer, as its diagnostics report it. */
45
+ this.backend = "main-thread";
37
46
  this.lastDiagnostics = null;
38
47
  this.lastRenderMs = 0;
39
48
  this.onDiagnostics = null;
@@ -71,6 +80,31 @@ export class Engine {
71
80
  #sizeResultCache() {
72
81
  this.#registry.setResultCacheBudget(RESULT_CACHE_FRAMES * this.canvas.width * this.canvas.height * 8);
73
82
  }
83
+ /**
84
+ * Turns per-pass GPU and CPU timing on or off; the passes then appear in `lastDiagnostics`.
85
+ * Off by default: timing is profiling cost, not rendering work.
86
+ */
87
+ setPassTiming(enabled) {
88
+ this.#registry?.setPassTiming(enabled);
89
+ }
90
+ /**
91
+ * Sets the preview resolution scale (the engine's `QualityProfile` resolution scale; 1 renders
92
+ * at the document's size) and returns the loaded project's render size as `[width, height]`, or
93
+ * null with no project loaded. Throws for a scale the engine refuses.
94
+ */
95
+ setPreviewScale(scale) {
96
+ if (!this.#registry)
97
+ throw new Error("the renderer is not initialized");
98
+ this.#registry.setPreviewScale(scale);
99
+ this.#revision += 1;
100
+ return this.previewSize;
101
+ }
102
+ /** The loaded project's render size at the preview scale, `[width, height]`, or null. */
103
+ get previewSize() {
104
+ if (!this.#registry || !this.#project)
105
+ return null;
106
+ return Array.from(this.#registry.previewSize);
107
+ }
74
108
  /** The renderer's part of the capability report: GPU, color, and playback. */
75
109
  capabilityReport() {
76
110
  return this.#registry
@@ -154,6 +188,46 @@ export class Engine {
154
188
  this.#revision += 1;
155
189
  this.#registry.resetPlayer();
156
190
  }
191
+ /**
192
+ * Compiles runtime effect definitions (`alpha2/effects` `EffectDefinition`s) on this renderer's
193
+ * device and registers them, all or none. An `id@version` this renderer holds already is skipped:
194
+ * a definition never changes under its version.
195
+ *
196
+ * Throws `invalid_effect` naming the first definition the engine refuses, with its diagnostics;
197
+ * then none of the call's definitions is registered.
198
+ */
199
+ async registerEffects(definitions, operation = "preview") {
200
+ if (!this.#registry)
201
+ throw new Error("the renderer is not initialized");
202
+ const fresh = definitions.filter((definition) => !this.#effects.has(effectKey(definition)));
203
+ const refusal = (definition, error) => new EditorError("invalid_effect", `Effect ${effectKey(definition)} is not one the engine runs: ${error instanceof Error ? error.message : String(error)}`, operation, effectKey(definition), true, { cause: error });
204
+ // `compileEffect` throws for a definition it refuses before compiling, else its promise
205
+ // rejects with the shader's diagnostics.
206
+ const compiled = await Promise.allSettled(fresh.map(async (definition) => this.#registry.compileEffect(JSON.stringify(definition))));
207
+ const failed = compiled.findIndex(({ status }) => status === "rejected");
208
+ if (failed !== -1) {
209
+ for (const result of compiled)
210
+ if (result.status === "fulfilled")
211
+ result.value.free?.();
212
+ throw refusal(fresh[failed], compiled[failed].reason);
213
+ }
214
+ const registered = [];
215
+ for (const [index, definition] of fresh.entries()) {
216
+ try {
217
+ this.#registry.registerCompiledEffect(compiled[index].value);
218
+ }
219
+ catch (error) {
220
+ for (const later of compiled.slice(index + 1))
221
+ later.value.free?.();
222
+ for (const done of registered)
223
+ this.#registry.unregisterEffect(done.id, done.version);
224
+ throw refusal(definition, error);
225
+ }
226
+ registered.push(definition);
227
+ }
228
+ for (const definition of registered)
229
+ this.#effects.add(effectKey(definition));
230
+ }
157
231
  /**
158
232
  * Registers the fonts caption tracks draw with, in fallback order. An SVG's text draws with the
159
233
  * same fonts, as the native host draws it with its caption fonts. Returns the fonts the engine
@@ -239,7 +313,9 @@ export class Engine {
239
313
  }
240
314
  /**
241
315
  * Requests one frame. Concurrent requests collapse to the most recent one so that scrubbing never
242
- * queues a backlog of stale frames.
316
+ * queues a backlog of stale frames. Resolves `{ rendered, unchanged }`: `rendered` is false when
317
+ * the request was superseded, and `unchanged` says the frame equals the one already shown, so
318
+ * nothing was drawn or presented and the surface still shows it.
243
319
  */
244
320
  render(seconds, { generation = null, context } = {}) {
245
321
  if (!this.#registry)
@@ -288,7 +364,7 @@ export class Engine {
288
364
  const isCurrent = () => revision === this.#revision &&
289
365
  (generation === null || generation === this.#generation);
290
366
  if (!isCurrent())
291
- return false;
367
+ return { rendered: false, unchanged: false };
292
368
  await this.sources.release(context.liveSourceIds);
293
369
  const started = performance.now();
294
370
  const playback = await this.#supply.render(BigInt(secondsToTicks(seconds)), {
@@ -302,10 +378,15 @@ export class Engine {
302
378
  isCurrent,
303
379
  });
304
380
  if (!playback)
305
- return false;
381
+ return { rendered: false, unchanged: false };
382
+ const unchanged = playback.unchanged === true;
383
+ if (unchanged)
384
+ this.#unchanged += 1;
385
+ else
386
+ this.#renders += 1;
306
387
  this.lastRenderMs = performance.now() - started;
307
388
  this.#sampleDiagnostics();
308
- return true;
389
+ return { rendered: true, unchanged };
309
390
  }
310
391
  #sampleDiagnostics() {
311
392
  const now = performance.now();
@@ -326,6 +407,10 @@ export class Engine {
326
407
  fps: Number(this.fps.toFixed(1)),
327
408
  renderMs: Number(this.lastRenderMs.toFixed(2)),
328
409
  uploadedFrames: this.#registry.uploadedFrameCount,
410
+ renders: this.#renders,
411
+ unchanged: this.#unchanged,
412
+ renderSize: [this.canvas.width, this.canvas.height],
413
+ backend: this.backend,
329
414
  };
330
415
  this.lastDiagnostics = diagnostics;
331
416
  this.onDiagnostics?.(diagnostics);