@alpha2-sh/editor 0.2.1 → 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.
@@ -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
  }),
@@ -1,6 +1,6 @@
1
- import type { MediaFingerprint, Project } from "alpha2/project";
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
  /**
@@ -273,6 +294,37 @@ export interface ProxyRemoval {
273
294
  * ticks (120000 per second). Methods that change the document dispatch through the session, so
274
295
  * they are undoable.
275
296
  */
297
+ /** A rectangle in fractions of the canvas, y down, as a text style's `position` is. */
298
+ export interface CanvasRect {
299
+ readonly left: number;
300
+ readonly top: number;
301
+ readonly right: number;
302
+ readonly bottom: number;
303
+ }
304
+ /**
305
+ * Where a text generator's text lies on the picture it draws, before its clip's transform and
306
+ * effects: what {@link BrowserBridge.measureText} answers.
307
+ */
308
+ export interface TextBounds {
309
+ /**
310
+ * The box the style's `anchor` and `position` place: `max_width` wide, every line's em box tall,
311
+ * and the whole pixels of outline and background padding around that.
312
+ */
313
+ readonly layout: CanvasRect;
314
+ /**
315
+ * From the start of the line that starts farthest left to the end of the one that ends farthest
316
+ * right, as tall as `layout`, with the same decorations around it. It moves only as the lines'
317
+ * advances do, not as glyphs with more or less ink are typed: steady handles for a text clip.
318
+ */
319
+ readonly content: CanvasRect;
320
+ /**
321
+ * What the text draws: its glyphs, their outline, and the background's boxes. Every pixel the
322
+ * frame gives the text meets it, give or take the pixel the texture's sampling spreads it by;
323
+ * `null` when the text draws nothing (only spaces).
324
+ */
325
+ readonly ink: CanvasRect | null;
326
+ readonly lineCount: number;
327
+ }
276
328
  export interface BrowserBridge {
277
329
  /** Where the preview renders: nowhere until `bindPreview`, then a worker or the main thread. */
278
330
  readonly previewBackend: "unbound" | "worker" | "main-thread";
@@ -295,12 +347,63 @@ export interface BrowserBridge {
295
347
  setMonitorVolume(value: number): void;
296
348
  /** The monitor volume `setMonitorVolume` last set; 1 until then. */
297
349
  readonly monitorVolume: number;
298
- /** Logs every source upload of the preview engine to the console, for debugging. */
350
+ /**
351
+ * Logs every source upload of the renderer that draws the preview (the worker's in worker mode)
352
+ * to the console, for debugging. Kept for later bindings.
353
+ */
299
354
  setTraceUploads(value: boolean): void;
300
- /** The preview engine's latest diagnostics sample (taken at most every 250 ms), or `null`. */
355
+ /**
356
+ * Turns per-pass GPU and CPU timing of the renderer that draws the preview on or off; the
357
+ * passes then appear in `diagnostics`. Off by default, since timing is profiling cost. Kept for
358
+ * later bindings.
359
+ */
360
+ setPassTiming(enabled: boolean): void;
361
+ /** The preview resolution scale (see `BrowserBridgeOptions.previewScale`). */
362
+ readonly previewScale: number;
363
+ /**
364
+ * Renders the preview at `scale` times the document's size from now on, and draws the current
365
+ * frame again; resolves once it is drawn. The bound canvas's backing store is always the size
366
+ * frames render at, not the document's: a host sizes the canvas on the page with CSS (as
367
+ * `EditorPreview` does). Rejects with `invalid_preview_scale` for a scale that is not above 0 and at
368
+ * most 8.
369
+ */
370
+ setPreviewScale(scale: number): Promise<void>;
371
+ /**
372
+ * The latest diagnostics sample of the renderer that draws the preview (taken at most every
373
+ * 250 ms; in worker mode the worker's), or `null`. Its `host` block holds, with the renderer's
374
+ * timing:
375
+ * - `renders`: frames the player drew;
376
+ * - `unchanged`: frames found equal to the one shown, so neither drawn nor presented;
377
+ * - `skippedRequests`: playback refreshes that asked for no frame, the one shown being the
378
+ * frame the clock asked for;
379
+ * - `bitmapTransfers`: frames copied to the bound canvas from another surface;
380
+ * - `renderSize`: `[width, height]` frames render at;
381
+ * - `previewScale`, and `backend` (`worker` or `main-thread`).
382
+ * Counters are cumulative (`renders` and `unchanged` per renderer, the others since
383
+ * `bindPreview`): subtract two samples for a rate.
384
+ */
301
385
  readonly diagnostics: Readonly<Record<string, unknown>> | null;
302
386
  /** The engine's built-in effects and transitions; `null` until a preview is bound. */
303
387
  readonly catalog: BuiltinEffectCatalog | null;
388
+ /**
389
+ * Adds runtime effects (and transitions) beyond the built-in catalog, so the document can draw
390
+ * them by `id@version`: every renderer the bridge makes registers them, the preview's (in its
391
+ * worker and on the main thread, and again after a lost GPU) and each export attempt's. They
392
+ * belong to the bridge, not the document: loading another project keeps them.
393
+ *
394
+ * With a preview bound, the definitions are compiled on its device, all or none, and the current
395
+ * frame is drawn again; the call rejects with `invalid_effect` naming the first one the engine
396
+ * refuses, and keeps none of them. Without one they are kept unchecked: `bindPreview` compiles
397
+ * them, and one refused then is dropped and reported to `onError` as `invalid_effect`. An export
398
+ * registers those kept when it starts, and an export attempt the engine refuses one in fails with
399
+ * `invalid_effect`.
400
+ *
401
+ * A definition registered already under the same `id@version` is skipped; a different one under
402
+ * it is refused (`effect_conflict`): a changed effect takes another version. Rejects with
403
+ * `invalid_effect` for a definition without a string `id` and an integer `version`, and once the
404
+ * bridge is disposed (`disposed`).
405
+ */
406
+ registerEffects(definitions: readonly EffectDefinition[]): Promise<void>;
304
407
  /**
305
408
  * Source `id` of the draft: its original while it is online, even where preview reads a proxy
306
409
  * (see {@link BrowserBridge.setPreviewMedia}), else the kept proxy standing in for it; opened
@@ -418,6 +521,17 @@ export interface BrowserBridge {
418
521
  * name tables.
419
522
  */
420
523
  captionFontFamilies(): Promise<string[]>;
524
+ /**
525
+ * Where the engine draws a text generator's text (see {@link TextBounds}): laid out as preview
526
+ * lays it out, with the same fonts, at the draft's canvas size, without rendering. A clip's
527
+ * transform maps these rectangles as it maps the rest of its picture.
528
+ *
529
+ * Rejects a generator that is not a valid text generator (`INVALID_INPUT`), with no fonts to
530
+ * draw it, and once the bridge is disposed (`disposed`).
531
+ */
532
+ measureText(generator: Extract<Generator, {
533
+ type: "text";
534
+ }>): Promise<TextBounds>;
421
535
  /**
422
536
  * The files a native export of `document` (the current one by default) needs, for upload:
423
537
  * shown media (or their proxies with `media: "proxies"`), an image sequence's frames, font
@@ -539,16 +653,43 @@ export interface WorkerPreview {
539
653
  * previous call sent that stay as they were, so their decoders stay open. Any other asset is
540
654
  * released. `fonts: null` keeps the registered fonts.
541
655
  */
542
- replaceProject(project: Project, revision: number, assets?: readonly RuntimeAsset[], fonts?: readonly RuntimeFont[] | null, keep?: readonly string[]): Promise<void>;
656
+ replaceProject(project: Project, revision: number, assets?: readonly RuntimeAsset[], fonts?: readonly RuntimeFont[] | null, keep?: readonly string[]): Promise<{
657
+ /** `[width, height]` frames render at, which the worker's canvas now is; `null` when empty. */
658
+ renderSize: readonly [number, number] | null;
659
+ }>;
543
660
  /**
544
661
  * Renders the frame at `tick`. `rendered` is `false` for an empty project or a render
545
- * cancelled meanwhile. `bitmap` is present only with `bitmapOutput`, and the caller owns it.
662
+ * cancelled meanwhile. `unchanged` says the frame equals the one already shown, so nothing was
663
+ * drawn or presented and no `bitmap` comes: the surface it was copied to still shows it.
664
+ * `bitmap` is present only with `bitmapOutput`, and the caller owns it. `diagnostics` are the
665
+ * source decoders'; `engineDiagnostics` is the renderer's diagnostics sample, present when it
666
+ * is newer than the one the last reply carried.
546
667
  */
547
668
  seek(tick: number): Promise<{
548
669
  rendered: boolean;
670
+ unchanged: boolean;
549
671
  bitmap?: ImageBitmap;
550
672
  diagnostics: Readonly<Record<string, number>>;
673
+ engineDiagnostics?: Readonly<Record<string, unknown>>;
674
+ }>;
675
+ /**
676
+ * Sets the preview resolution scale (see `BrowserBridgeOptions.previewScale`) and sizes the
677
+ * worker's canvas to it.
678
+ */
679
+ setPreviewScale(scale: number): Promise<{
680
+ renderSize: readonly [number, number] | null;
551
681
  }>;
682
+ /** Turns per-pass timing and upload logging of the worker's renderer on or off. */
683
+ setTracing(options: {
684
+ passTiming?: boolean;
685
+ traceUploads?: boolean;
686
+ }): Promise<void>;
687
+ /**
688
+ * Compiles and registers runtime effects on the worker's renderer, all or none (see
689
+ * {@link BrowserBridge.registerEffects}); an `id@version` it holds already is skipped. Rejects
690
+ * with `invalid_effect` naming the first one the engine refuses.
691
+ */
692
+ registerEffects(effects: readonly EffectDefinition[]): Promise<void>;
552
693
  /** Mixes `frames` project-rate samples from `startSample`, one array per channel. */
553
694
  mix(startSample: number, frames: number): Promise<Float32Array[]>;
554
695
  /** 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,
@@ -52,6 +63,7 @@ export function installEditorWorker(scope) {
52
63
  engine = new Engine(request.canvas ??
53
64
  new OffscreenCanvas(request.width ?? 16, request.height ?? 16), pixels, library, request.runtimeAssets);
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 });
@@ -1,6 +1,6 @@
1
1
  import { addTransition, resizeTransition, removeTransition, } from "./transitions.js";
2
2
  import * as edit from "alpha2/edit";
3
- import { drawnEffectResources, effectStack, findComposition, freeCompositionId, freeNodeId, groupNodes, ungroupNode, inputKeys, correspondingCompositions, ownComposition, withEffectStack, withoutUndrawn, withInput, withoutNodes, shownSources, } from "./compositions.js";
3
+ import { drawnEffectResources, effectStack, findComposition, freeCompositionId, freeNodeId, groupNodes, ungroupNode, acceptsInput, correspondingCompositions, ownComposition, withEffectStack, withoutUndrawn, withInput, withoutNodes, shownSources, } from "./compositions.js";
4
4
  import { rememberValid, withValidated } from "./validated.js";
5
5
  import { EditorError, validateDocument, validateDocumentShape, assertProjection, indexDocument, transitionInstanceId, withInstanceIds, } from "./document.js";
6
6
  const NO_NAMES = Object.freeze({});
@@ -687,7 +687,7 @@ function reduce(document, command) {
687
687
  : n),
688
688
  };
689
689
  }
690
- if (!inputKeys(op).includes(key))
690
+ if (!acceptsInput(op, key))
691
691
  fail(`No input ${String(key)} on node ${command.to}`, command.to);
692
692
  const connected = withInput(op, key, command.type === "graph.connect" ? command.from : null);
693
693
  return {
@@ -97,9 +97,10 @@ export declare function shownSources(project: Project, tracks?: Project["timelin
97
97
  */
98
98
  export declare function drawnEffectResources(project: Project, tracks?: Project["timeline"]["tracks"]): Set<string>;
99
99
  /**
100
- * A node input as graph commands name it: `input`, `from`, `to`, `matte`, or a merge layer's index.
100
+ * A node input as graph commands name it: `input`, `from`, `to`, `matte`, an effect's named input
101
+ * as `inputs.<name>`, or a merge layer's or group port's index.
101
102
  */
102
- export type InputKey = "input" | "from" | "to" | "matte" | number;
103
+ export type InputKey = "input" | "from" | "to" | "matte" | `inputs.${string}` | number;
103
104
  /** The input keys of a node's operation, in order. */
104
105
  export declare function inputKeys(op: CompositionNode["op"]): InputKey[];
105
106
  /**
@@ -137,10 +138,21 @@ export declare function compositionReads(compositions: readonly Composition[]):
137
138
  /** The node an input reads, or `undefined` when it is unconnected or absent. */
138
139
  export declare function inputOf(op: CompositionNode["op"], key: InputKey): string | undefined;
139
140
  /**
140
- * `op` with input `key` reading `node` (`null` disconnects it). Throws when `op` has no input
141
- * `key`.
141
+ * Whether `op` has input `key`, or can take it: an effect node takes any well-named
142
+ * `inputs.<name>`, whether or not its definition declares it.
143
+ */
144
+ export declare function acceptsInput(op: CompositionNode["op"], key: InputKey): boolean;
145
+ /**
146
+ * `op` with input `key` reading `node` (`null` disconnects it, keeping an effect's named input).
147
+ * An effect's named input is added when it has none of the name. Throws when `op` cannot take
148
+ * input `key`.
142
149
  */
143
150
  export declare function withInput(op: CompositionNode["op"], key: InputKey, node: string | null): CompositionNode["op"];
151
+ /**
152
+ * `op` without its effect input `name`; an effect left with none has no `inputs`, as the model
153
+ * writes it. Any other operation is returned as it is.
154
+ */
155
+ export declare function withoutEffectInput(op: CompositionNode["op"], name: string): CompositionNode["op"];
144
156
  /**
145
157
  * How a composition is drawn, which decides what its clip nodes and group inputs read, as the
146
158
  * engine plans it.
@@ -44,7 +44,10 @@ export function effectStack(project, clip) {
44
44
  if (node.op.type === "clip") {
45
45
  return stack.length + 1 === nodes.size ? stack.reverse() : undefined;
46
46
  }
47
- if (node.op.type !== "effect" || node.op.input == null)
47
+ // An effect reading named inputs reads another branch, which a stack cannot show.
48
+ if (node.op.type !== "effect" ||
49
+ node.op.input == null ||
50
+ Object.keys(node.op.inputs ?? {}).length > 0)
48
51
  return undefined;
49
52
  stack.push({ id: node.id, effect: node.op.effect, bypass: !!node.bypass });
50
53
  at = node.op.input;
@@ -302,6 +305,10 @@ function divide(value, num, den, rounding) {
302
305
  function inputsOf(op) {
303
306
  switch (op.type) {
304
307
  case "effect":
308
+ return [
309
+ op.input,
310
+ ...effectInputNames(op).map((name) => op.inputs[name]),
311
+ ].filter((id) => id != null);
305
312
  case "transform":
306
313
  case "shape_mask":
307
314
  return op.input != null ? [op.input] : [];
@@ -393,10 +400,26 @@ function drawn(project, tracks) {
393
400
  }
394
401
  return { sources: used, resources };
395
402
  }
403
+ /** A name an effect node may give a named input, as the model requires. */
404
+ const EFFECT_INPUT_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
405
+ /** The name of the effect input `key` names, or `undefined` for any other key. */
406
+ function effectInputName(key) {
407
+ return typeof key === "string" && key.startsWith("inputs.")
408
+ ? key.slice("inputs.".length)
409
+ : undefined;
410
+ }
411
+ /** An effect node's named inputs, in name order, as the model keeps them. */
412
+ function effectInputNames(op) {
413
+ return Object.keys(op.inputs ?? {}).sort();
414
+ }
396
415
  /** The input keys of a node's operation, in order. */
397
416
  export function inputKeys(op) {
398
417
  switch (op.type) {
399
418
  case "effect":
419
+ return [
420
+ "input",
421
+ ...effectInputNames(op).map((name) => `inputs.${name}`),
422
+ ];
400
423
  case "transform":
401
424
  case "shape_mask":
402
425
  return ["input"];
@@ -508,16 +531,37 @@ export function inputOf(op, key) {
508
531
  : op.type === "group"
509
532
  ? (op.inputs?.[key] ?? undefined)
510
533
  : undefined;
534
+ const name = effectInputName(key);
535
+ if (name !== undefined)
536
+ return op.type === "effect"
537
+ ? Object.hasOwn(op.inputs ?? {}, name)
538
+ ? (op.inputs[name] ?? undefined)
539
+ : undefined
540
+ : undefined;
511
541
  const value = op[key];
512
542
  return typeof value === "string" ? value : undefined;
513
543
  }
514
544
  /**
515
- * `op` with input `key` reading `node` (`null` disconnects it). Throws when `op` has no input
516
- * `key`.
545
+ * Whether `op` has input `key`, or can take it: an effect node takes any well-named
546
+ * `inputs.<name>`, whether or not its definition declares it.
547
+ */
548
+ export function acceptsInput(op, key) {
549
+ const name = effectInputName(key);
550
+ if (name !== undefined)
551
+ return op.type === "effect" && EFFECT_INPUT_NAME.test(name);
552
+ return inputKeys(op).includes(key);
553
+ }
554
+ /**
555
+ * `op` with input `key` reading `node` (`null` disconnects it, keeping an effect's named input).
556
+ * An effect's named input is added when it has none of the name. Throws when `op` cannot take
557
+ * input `key`.
517
558
  */
518
559
  export function withInput(op, key, node) {
519
- if (!inputKeys(op).includes(key))
560
+ if (!acceptsInput(op, key))
520
561
  throw new Error(`A ${op.type} node has no input ${String(key)}`);
562
+ const name = effectInputName(key);
563
+ if (name !== undefined && op.type === "effect")
564
+ return { ...op, inputs: { ...(op.inputs ?? {}), [name]: node } };
521
565
  if (typeof key === "number" && op.type === "merge")
522
566
  return {
523
567
  ...op,
@@ -530,6 +574,17 @@ export function withInput(op, key, node) {
530
574
  };
531
575
  return { ...op, [key]: node };
532
576
  }
577
+ /**
578
+ * `op` without its effect input `name`; an effect left with none has no `inputs`, as the model
579
+ * writes it. Any other operation is returned as it is.
580
+ */
581
+ export function withoutEffectInput(op, name) {
582
+ if (op.type !== "effect" || !Object.hasOwn(op.inputs ?? {}, name))
583
+ return op;
584
+ const { [name]: _removed, ...rest } = op.inputs;
585
+ const { inputs: _inputs, ...without } = op;
586
+ return Object.keys(rest).length > 0 ? { ...without, inputs: rest } : without;
587
+ }
533
588
  /**
534
589
  * What stops `composition`'s output from rendering when it is drawn as `use`: no output, an
535
590
  * unconnected input a node the output reaches uses (only the pass-through input of a bypassed node,
@@ -16,17 +16,20 @@ const EDITOR_FAILURE_CODES = Object.freeze({
16
16
  conform_pending: "UNKNOWN",
17
17
  disposed: "UNKNOWN",
18
18
  duplicate_resource: "INVALID_INPUT",
19
+ effect_conflict: "INVALID_INPUT",
19
20
  empty_export: "INVALID_INPUT",
20
21
  export_busy: "UNKNOWN",
21
22
  invalid_asset: "INVALID_INPUT",
22
23
  invalid_captions: "INVALID_INPUT",
23
24
  invalid_command: "INVALID_INPUT",
24
25
  invalid_document: "INVALID_INPUT",
26
+ invalid_effect: "INVALID_INPUT",
25
27
  invalid_effect_resource: "INVALID_INPUT",
26
28
  invalid_font: "INVALID_INPUT",
27
29
  invalid_frame_rate: "INVALID_INPUT",
28
30
  invalid_metadata: "INVALID_INPUT",
29
31
  invalid_policy: "INVALID_INPUT",
32
+ invalid_preview_scale: "INVALID_INPUT",
30
33
  invalid_project: "INVALID_INPUT",
31
34
  invalid_projection: "INVALID_INPUT",
32
35
  invalid_rate: "INVALID_INPUT",
@@ -24,7 +24,8 @@ export interface NativeAsset {
24
24
  }
25
25
  /**
26
26
  * Export settings for a native job: the browser export's options, plus the MPEG-4 Part 2 codec the
27
- * host can encode.
27
+ * host can encode. `container`, `videoCodec` and `audioCodec` go to the host as given; an absent
28
+ * one is the container's default there, as in the browser.
28
29
  */
29
30
  export interface NativeExportOptions extends Omit<BrowserExportOptions, "videoCodec"> {
30
31
  readonly videoCodec?: BrowserExportOptions["videoCodec"] | "mpeg4-part2";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alpha2-sh/editor",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "Headless Project-based editing sessions and browser adapters for alpha2.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -60,11 +60,11 @@
60
60
  "build": "rm -rf dist && tsc -p tsconfig.json"
61
61
  },
62
62
  "peerDependencies": {
63
- "alpha2": "0.2.1",
63
+ "alpha2": "0.3.0",
64
64
  "react": "^19.3.0"
65
65
  },
66
66
  "devDependencies": {
67
- "alpha2": "0.2.1",
67
+ "alpha2": "0.3.0",
68
68
  "react": "19.3.0",
69
69
  "react-dom": "19.3.0",
70
70
  "@types/react": "19.3.0",