alpha2 0.4.6 → 0.5.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.
Files changed (119) hide show
  1. package/README.md +5 -4
  2. package/THIRD_PARTY_NOTICES.md +4 -0
  3. package/dist/abort.d.ts +12 -0
  4. package/dist/abort.js +48 -0
  5. package/dist/active-clock.d.ts +35 -0
  6. package/dist/active-clock.js +99 -0
  7. package/dist/assets.d.ts +28 -22
  8. package/dist/assets.js +8 -12
  9. package/dist/audio-layout.d.ts +52 -74
  10. package/dist/audio-layout.js +114 -148
  11. package/dist/audio-timeline.d.ts +89 -117
  12. package/dist/audio-timeline.js +102 -118
  13. package/dist/audio-worker.d.ts +12 -21
  14. package/dist/audio-worker.js +8 -13
  15. package/dist/audio-worklet-processor.js +45 -58
  16. package/dist/audio-worklet.d.ts +45 -76
  17. package/dist/audio-worklet.js +44 -79
  18. package/dist/audio.d.ts +15 -23
  19. package/dist/audio.js +9 -13
  20. package/dist/builder.d.ts +45 -63
  21. package/dist/builder.js +49 -45
  22. package/dist/capabilities.d.ts +99 -16
  23. package/dist/capabilities.js +2 -2
  24. package/dist/captions.d.ts +45 -22
  25. package/dist/captions.js +60 -15
  26. package/dist/chroma-siting.d.ts +24 -41
  27. package/dist/chroma-siting.js +38 -71
  28. package/dist/containers.d.ts +41 -30
  29. package/dist/containers.js +59 -27
  30. package/dist/decoder-fallback.d.ts +13 -0
  31. package/dist/decoder-fallback.js +38 -0
  32. package/dist/decoder-order.d.ts +24 -39
  33. package/dist/decoder-order.js +28 -42
  34. package/dist/edit.d.ts +77 -154
  35. package/dist/edit.js +98 -180
  36. package/dist/effects.d.ts +108 -177
  37. package/dist/effects.js +7 -9
  38. package/dist/export-destination.d.ts +25 -41
  39. package/dist/export-destination.js +20 -32
  40. package/dist/export-failure.d.ts +34 -59
  41. package/dist/export-failure.js +54 -48
  42. package/dist/export-metrics.d.ts +116 -0
  43. package/dist/export-metrics.js +74 -0
  44. package/dist/export-retry.d.ts +46 -29
  45. package/dist/export-retry.js +86 -51
  46. package/dist/exporter.d.ts +67 -116
  47. package/dist/exporter.js +133 -133
  48. package/dist/extensions.d.ts +69 -115
  49. package/dist/extensions.js +55 -82
  50. package/dist/frame-intake.d.ts +92 -0
  51. package/dist/frame-intake.js +114 -0
  52. package/dist/frame-supply.d.ts +96 -162
  53. package/dist/frame-supply.js +181 -171
  54. package/dist/generated/project-schema.d.ts +701 -485
  55. package/dist/generated/project-schema.js +55 -2
  56. package/dist/generated/project-shape.js +261 -16
  57. package/dist/geometry.d.ts +28 -34
  58. package/dist/geometry.js +18 -23
  59. package/dist/gpu-recovery.d.ts +92 -0
  60. package/dist/gpu-recovery.js +135 -0
  61. package/dist/hdr-frames.d.ts +82 -67
  62. package/dist/hdr-frames.js +112 -49
  63. package/dist/index.d.ts +4 -0
  64. package/dist/index.js +4 -0
  65. package/dist/json-text.d.ts +13 -23
  66. package/dist/json-text.js +10 -20
  67. package/dist/layout-values.d.ts +14 -22
  68. package/dist/layout-values.js +18 -21
  69. package/dist/layout.d.ts +48 -63
  70. package/dist/layout.js +37 -37
  71. package/dist/loudness.d.ts +27 -32
  72. package/dist/loudness.js +19 -23
  73. package/dist/media.d.ts +85 -237
  74. package/dist/media.js +133 -287
  75. package/dist/mediabunny.d.ts +166 -245
  76. package/dist/mediabunny.js +741 -580
  77. package/dist/physical-frames.d.ts +5 -17
  78. package/dist/physical-frames.js +4 -11
  79. package/dist/player.d.ts +56 -47
  80. package/dist/player.js +155 -40
  81. package/dist/presented-frames.d.ts +2 -7
  82. package/dist/presented-frames.js +3 -8
  83. package/dist/project.d.ts +73 -117
  84. package/dist/project.js +384 -445
  85. package/dist/rate-control.d.ts +9 -23
  86. package/dist/rate-control.js +7 -18
  87. package/dist/renderer-choice.d.ts +41 -0
  88. package/dist/renderer-choice.js +82 -0
  89. package/dist/repacked-bytes.d.ts +0 -2
  90. package/dist/repacked-bytes.js +2 -5
  91. package/dist/robustness.d.ts +25 -37
  92. package/dist/robustness.js +71 -54
  93. package/dist/sha256.d.ts +5 -13
  94. package/dist/sha256.js +9 -24
  95. package/dist/text.d.ts +97 -71
  96. package/dist/text.js +33 -70
  97. package/dist/video-frames.d.ts +7 -25
  98. package/dist/video-frames.js +12 -29
  99. package/dist/waveform.d.ts +5 -11
  100. package/dist/waveform.js +4 -9
  101. package/dist/worker-error.d.ts +5 -20
  102. package/dist/worker-error.js +8 -25
  103. package/dist/worker.d.ts +82 -95
  104. package/dist/worker.js +235 -143
  105. package/package.json +26 -2
  106. package/wasm/alpha2_audio_worklet.wasm +0 -0
  107. package/wasm/alpha2_extensions.d.ts +26 -47
  108. package/wasm/alpha2_extensions.js +26 -47
  109. package/wasm/alpha2_extensions_bg.wasm +0 -0
  110. package/wasm/alpha2_wasm.d.ts +460 -567
  111. package/wasm/alpha2_wasm.js +594 -594
  112. package/wasm/alpha2_wasm_bg.wasm +0 -0
  113. package/wasm/alpha2_wasm_bg.wasm.d.ts +15 -8
  114. package/wasm/rust-crate-licenses.md +2 -2
  115. package/wasm/snippets/{alpha2-wasm-c62e60c964e88a52 → alpha2-wasm-1313375d424845c0}/inline1.js +1 -0
  116. package/wasm/snippets/alpha2-wasm-1313375d424845c0/inline2.js +82 -0
  117. package/wasm/snippets/alpha2-wasm-c62e60c964e88a52/inline2.js +0 -52
  118. /package/wasm/snippets/{alpha2-wasm-c62e60c964e88a52 → alpha2-wasm-1313375d424845c0}/inline0.js +0 -0
  119. /package/wasm/snippets/{alpha2-wasm-c62e60c964e88a52 → alpha2-wasm-1313375d424845c0}/inline3.js +0 -0
@@ -1,8 +1,4 @@
1
- /**
2
- * What makes two decoded frames the same pixels once uploaded: the source and
3
- * its content generation, the decoded timestamp and duration, and the size and
4
- * orientation the upload is made at.
5
- */
1
+ /** Fields that make two decoded frames the same pixels once uploaded. */
6
2
  export interface PhysicalFrameIdentity {
7
3
  readonly sourceId: string;
8
4
  readonly contentGeneration: number;
@@ -15,29 +11,21 @@ export interface PhysicalFrameIdentity {
15
11
  readonly rotation: 0 | 90 | 180 | 270;
16
12
  readonly mirror: boolean;
17
13
  }
18
- /** The engine's key for an uploaded frame: a source and an exact media time. */
19
14
  export interface ExactFrameKey {
20
15
  readonly sourceId: string;
21
16
  readonly mediaTimeTicks: bigint;
22
17
  }
23
18
  /**
24
- * Maps each recently uploaded decoded frame to the exact key it was last
25
- * uploaded under, so a distinct request that decodes to the same frame can
26
- * alias the existing upload instead of uploading it again.
27
- *
28
- * Holds at most 512 entries and evicts the least recently recorded. An exact
29
- * key belongs to at most one identity.
19
+ * Maps recently uploaded frames to their exact key, so a request that decodes to the same frame
20
+ * aliases the existing upload. LRU of 512 entries; an exact key belongs to at most one identity.
30
21
  */
31
22
  export declare class PhysicalFrameAliases {
32
23
  #private;
33
24
  /**
34
- * Serves `requested` from the upload already recorded for `identity`, through
35
- * `aliasExact` (which asks the engine to alias the existing key). Returns
36
- * `false` when nothing is recorded or the engine refused; the entry is
37
- * dropped either way, and on `false` the caller uploads and calls `record`.
25
+ * Serves `requested` from the upload recorded for `identity`. On `false` (nothing recorded or
26
+ * the engine refused) the caller uploads and calls `record`.
38
27
  */
39
28
  alias(identity: PhysicalFrameIdentity, requested: ExactFrameKey, aliasExact: (existing: ExactFrameKey, requested: ExactFrameKey) => boolean): boolean;
40
- /** Records that `exact` now holds the upload of `identity`. */
41
29
  record(identity: PhysicalFrameIdentity, exact: ExactFrameKey): void;
42
30
  clear(): void;
43
31
  }
@@ -1,19 +1,13 @@
1
1
  const MAX_PHYSICAL_FRAME_ALIASES = 512;
2
2
  /**
3
- * Maps each recently uploaded decoded frame to the exact key it was last
4
- * uploaded under, so a distinct request that decodes to the same frame can
5
- * alias the existing upload instead of uploading it again.
6
- *
7
- * Holds at most 512 entries and evicts the least recently recorded. An exact
8
- * key belongs to at most one identity.
3
+ * Maps recently uploaded frames to their exact key, so a request that decodes to the same frame
4
+ * aliases the existing upload. LRU of 512 entries; an exact key belongs to at most one identity.
9
5
  */
10
6
  export class PhysicalFrameAliases {
11
7
  #entries = new Map();
12
8
  /**
13
- * Serves `requested` from the upload already recorded for `identity`, through
14
- * `aliasExact` (which asks the engine to alias the existing key). Returns
15
- * `false` when nothing is recorded or the engine refused; the entry is
16
- * dropped either way, and on `false` the caller uploads and calls `record`.
9
+ * Serves `requested` from the upload recorded for `identity`. On `false` (nothing recorded or
10
+ * the engine refused) the caller uploads and calls `record`.
17
11
  */
18
12
  alias(identity, requested, aliasExact) {
19
13
  const key = physicalKey(identity);
@@ -27,7 +21,6 @@ export class PhysicalFrameAliases {
27
21
  this.#entries.set(key, requested);
28
22
  return true;
29
23
  }
30
- /** Records that `exact` now holds the upload of `identity`. */
31
24
  record(identity, exact) {
32
25
  const key = physicalKey(identity);
33
26
  this.#forgetExact(exact, key);
package/dist/player.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import type { ChromaSiting } from "./hdr-frames.js";
2
+ import { GpuRecoveryLadder, type GpuLossReport, type RecoveryStep, type SurfaceProbe } from "./gpu-recovery.js";
3
+ import type { RendererChoice } from "./renderer-choice.js";
2
4
  import { type DecoderRefillRequest } from "./media.js";
3
5
  /** One decoded frame transferred to the worker-owned render backend. */
4
6
  export interface DecodedVideoFrame {
@@ -8,50 +10,44 @@ export interface DecodedVideoFrame {
8
10
  /** PTS of the physical frame selected by the decoder. */
9
11
  readonly decodedTimeTicks: bigint;
10
12
  readonly frame: VideoFrame;
11
- /**
12
- * Clockwise stream display rotation applied by the GPU presentation pass, after `mirror`.
13
- */
13
+ /** Clockwise display rotation, applied after `mirror`. */
14
14
  readonly rotationDegrees?: 0 | 90 | 180 | 270;
15
- /** Whether the stream mirrors the frame left to right before it turns. */
15
+ /** Horizontal mirror applied before rotation. */
16
16
  readonly mirror?: boolean;
17
- /**
18
- * Where chroma samples sit, which WebCodecs does not report: see `chromaSitingForStream`.
19
- */
17
+ /** Chroma sample position, which WebCodecs does not report; see `chromaSitingForStream`. */
20
18
  readonly chromaSiting?: ChromaSiting;
21
19
  /** Seek/recovery generation; stale frames are closed without upload. */
22
20
  readonly generation: number;
21
+ /**
22
+ * Set when the frame was decoded in software on request ({@link DecoderRefillRequest.decode}). A
23
+ * render host that cannot take it refuses the source instead of asking again.
24
+ */
25
+ readonly decode?: "software";
23
26
  }
24
27
  /** A source frame a presentation needed and did not have. */
25
28
  export interface MissingFrame {
26
29
  readonly clipId: string;
27
30
  /**
28
- * The composition step that reads the source, when a media step does rather than the clip
29
- * itself; absent for the clip's own source. Each reader keeps its own decode cursor.
31
+ * The composition step reading the source when it is not the clip itself. Each reader keeps its
32
+ * own decode cursor.
30
33
  */
31
34
  readonly readerId?: string;
32
35
  readonly sourceId: string;
33
- /**
34
- * The source time the clip needs, from the snapshot that was presented. A trimmed, offset, or
35
- * retimed clip needs its source at a time other than the timeline's, so this, not
36
- * `requestedTimeTicks`, is what to decode.
37
- */
36
+ /** The source time to decode; differs from timeline time for trimmed or retimed clips. */
38
37
  readonly mediaTimeTicks: bigint;
38
+ /** `"software"` when the refill must decode this frame in software. */
39
+ readonly decode?: "software";
39
40
  }
40
41
  /** Result of one real-time presentation attempt. */
41
42
  export interface PresentedFrame {
42
43
  readonly requestedTimeTicks: bigint;
43
44
  /** The time whose picture is on screen; absent when nothing was presented. */
44
45
  readonly presentedTimeTicks?: bigint;
45
- /** Sources the presentation lacked a frame of. */
46
46
  readonly missingSources: readonly string[];
47
- /** Each clip's missing frame, with the source time to decode. */
48
47
  readonly missingFrames: readonly MissingFrame[];
49
48
  /** Whether the previous picture was shown again instead of a new one. */
50
49
  readonly repeated: boolean;
51
- /**
52
- * Whether the frame equals the one on screen, so nothing was rendered or presented: the canvas
53
- * still shows it.
54
- */
50
+ /** Whether the frame equals the one on screen, so nothing was rendered or presented. */
55
51
  readonly unchanged: boolean;
56
52
  }
57
53
  /** The worker-side renderer an {@link Alpha2Player} drives. */
@@ -60,61 +56,74 @@ export interface RenderBackend {
60
56
  initialize(canvas: OffscreenCanvas): Promise<void>;
61
57
  /** Takes ownership of `frame.frame` and closes it once uploaded. */
62
58
  uploadVideoFrame(frame: DecodedVideoFrame): Promise<void>;
63
- /** Draws timeline time `timeTicks` with the frames uploaded so far. */
64
59
  present(timeTicks: bigint): Promise<PresentedFrame>;
65
- /** Drops uploaded frames ahead of a seek. */
66
60
  reset(): Promise<void>;
61
+ /** Whether {@link RenderBackend.recover} must run before the next presentation. */
62
+ isDeviceLost(): boolean;
63
+ lossReport(): GpuLossReport | undefined;
64
+ probeSurface(): Promise<SurfaceProbe>;
67
65
  /**
68
- * Whether the GPU device was lost and {@link RenderBackend.recover} must run before the next
69
- * presentation.
66
+ * Makes the renderer `step` names, on `canvas` for a fresh-surface step, and resolves to it
67
+ * (`undefined` if the backend does not say). Drops uploaded frames. Rejects when the renderer
68
+ * cannot be made; the backend stays lost.
70
69
  */
71
- isDeviceLost(): boolean;
72
- /** Replaces a lost device; uploaded frames are gone afterwards. */
73
- recover(): Promise<void>;
74
- /** Releases the backend; it is not used again. */
70
+ recover(step: RecoveryStep, canvas?: OffscreenCanvas): Promise<RendererChoice | undefined>;
75
71
  dispose(): void;
76
72
  }
73
+ export interface Alpha2PlayerOptions {
74
+ /** Called with the frames a presentation lacked; resolve after uploading what it decoded. */
75
+ readonly onRefill?: (requests: readonly DecoderRefillRequest[]) => void | Promise<void>;
76
+ /**
77
+ * Returns a new same-size canvas, already transferred to an `OffscreenCanvas`, to replace the one
78
+ * on screen. Recoveries that need a fresh surface call it once per step; without it they fail
79
+ * with a fatal `GPU_DEVICE_LOST`.
80
+ */
81
+ readonly replaceSurface?: () => Promise<OffscreenCanvas>;
82
+ readonly onRendererChange?: (choice: RendererChoice) => void;
83
+ readonly recovery?: GpuRecoveryLadder;
84
+ }
77
85
  /**
78
86
  * Real-time browser runner that serializes presentation and recovers device loss.
79
87
  *
80
- * It keeps no clock: `present` shows the time it is given. For playback with audio, give it
81
- * `AudioPlaybackClock.timelineTicks`, which follows the audio device, so the picture stays with the
82
- * sound instead of drifting on the wall clock.
88
+ * It keeps no clock: `present` shows the time it is given. For playback with audio, pass
89
+ * `AudioPlaybackClock.timelineTicks` so the picture follows the audio device.
90
+ *
91
+ * A presentation that lacks source frames asks `onRefill` for them, then presents the same time
92
+ * again. Frames uploaded after `onRefill` resolves show only on the next presentation.
93
+ *
94
+ * A frame the backend rejects with `SOFTWARE_DECODE_REQUIRED` is requested once more with
95
+ * `decode: "software"`; a source with no planar format is requested in software from then on.
96
+ * `onRefill` must honor `decode` (a `DecoderRefillCoordinator` does).
83
97
  *
84
- * A presentation that lacks source frames asks `onRefill` for them and, once the frames it uploads
85
- * have arrived, presents the same time again, so the time asked for is the one that shows.
86
- * `onRefill` should resolve after uploading what it decoded: frames uploaded later reach the screen
87
- * only with the next presentation.
98
+ * A lost GPU is recovered on the next presentation through a {@link GpuRecoveryLadder}. When every
99
+ * step fails, that presentation and all later ones reject with the same fatal error.
88
100
  */
89
101
  export declare class Alpha2Player {
90
102
  #private;
91
- constructor(backend: RenderBackend, onRefill?: (requests: readonly DecoderRefillRequest[]) => void | Promise<void>);
103
+ constructor(backend: RenderBackend, options?: Alpha2PlayerOptions);
92
104
  /** Initializes the backend on `canvas`; every other method throws before this resolves. */
93
105
  initialize(canvas: OffscreenCanvas): Promise<void>;
94
106
  /**
95
- * Uploads a decoded frame, taking it over: it is closed when it is not uploaded. A frame from an
96
- * earlier generation (decoded before the last seek or device recovery) is closed and dropped.
107
+ * Uploads a decoded frame, taking ownership. Frames from an earlier generation (before the last
108
+ * seek or recovery) are closed and dropped.
97
109
  *
98
110
  * @throws Before {@link Alpha2Player.initialize} has resolved and after
99
111
  * {@link Alpha2Player.dispose}, having closed the frame.
100
112
  */
101
113
  uploadVideoFrame(frame: DecodedVideoFrame): Promise<void>;
102
114
  /**
103
- * Presents `timeTicks`, recovering a lost device first and refilling missing
104
- * frames through `onRefill`. Resolves `undefined` when a later `present` or
105
- * `seek` superseded this one.
115
+ * Presents `timeTicks`, recovering a lost device first and refilling missing frames through
116
+ * `onRefill`. Resolves `undefined` when a later `present` or `seek` superseded this one.
106
117
  *
107
- * Presentations that overlap a recovery wait for it rather than starting another, and reject
108
- * with its error when it fails; the next presentation after a failure tries again.
118
+ * Rejects with a fatal `GPU_DEVICE_LOST` when no renderer can be made (or a fresh surface was
119
+ * needed without `replaceSurface`); every later presentation rejects the same way.
109
120
  *
110
121
  * @throws Before {@link Alpha2Player.initialize} has resolved.
111
122
  */
112
123
  present(timeTicks: bigint): Promise<PresentedFrame | undefined>;
113
124
  /**
114
- * Seeks to `timeTicks`: frames decoded for earlier requests are dropped when
115
- * they arrive, the backend is reset, and the target is presented once
116
- * `onRefill` has delivered its frames. Resolves `undefined` when a later
117
- * request superseded it.
125
+ * Seeks to `timeTicks`, dropping frames decoded for earlier requests, and presents the target
126
+ * once `onRefill` has delivered. Resolves `undefined` when a later request superseded it.
118
127
  *
119
128
  * @throws Before {@link Alpha2Player.initialize} has resolved.
120
129
  */
package/dist/player.js CHANGED
@@ -1,36 +1,48 @@
1
+ import { GpuRecoveryLadder, } from "./gpu-recovery.js";
2
+ import { Alpha2WasmError } from "./worker-error.js";
3
+ import { softwareDecodeRequest, } from "./frame-intake.js";
1
4
  import { decoderConsumerId, } from "./media.js";
2
5
  /**
3
6
  * Real-time browser runner that serializes presentation and recovers device loss.
4
7
  *
5
- * It keeps no clock: `present` shows the time it is given. For playback with audio, give it
6
- * `AudioPlaybackClock.timelineTicks`, which follows the audio device, so the picture stays with the
7
- * sound instead of drifting on the wall clock.
8
+ * It keeps no clock: `present` shows the time it is given. For playback with audio, pass
9
+ * `AudioPlaybackClock.timelineTicks` so the picture follows the audio device.
8
10
  *
9
- * A presentation that lacks source frames asks `onRefill` for them and, once the frames it uploads
10
- * have arrived, presents the same time again, so the time asked for is the one that shows.
11
- * `onRefill` should resolve after uploading what it decoded: frames uploaded later reach the screen
12
- * only with the next presentation.
11
+ * A presentation that lacks source frames asks `onRefill` for them, then presents the same time
12
+ * again. Frames uploaded after `onRefill` resolves show only on the next presentation.
13
+ *
14
+ * A frame the backend rejects with `SOFTWARE_DECODE_REQUIRED` is requested once more with
15
+ * `decode: "software"`; a source with no planar format is requested in software from then on.
16
+ * `onRefill` must honor `decode` (a `DecoderRefillCoordinator` does).
17
+ *
18
+ * A lost GPU is recovered on the next presentation through a {@link GpuRecoveryLadder}. When every
19
+ * step fails, that presentation and all later ones reject with the same fatal error.
13
20
  */
14
21
  export class Alpha2Player {
15
22
  #backend;
16
23
  #initialized = false;
17
24
  #latestRequest = 0;
18
25
  #generation = 0;
19
- /**
20
- * Frames handed to the backend, so a refill that uploaded nothing is not followed by a
21
- * presentation that cannot differ.
22
- */
26
+ // Skips re-presenting after a refill that uploaded nothing.
23
27
  #uploads = 0;
24
- /**
25
- * The device recovery in flight, which every presentation that finds the device lost waits for
26
- * instead of starting its own: one recovery makes the renderer again, however many presentations
27
- * overlap it.
28
- */
28
+ // Shared by every presentation that finds the device lost.
29
29
  #recovering;
30
+ #terminal;
31
+ #replaceSurface;
32
+ #onRendererChange;
33
+ #ladder;
30
34
  #onRefill;
31
- constructor(backend, onRefill) {
35
+ #softwareSources = new Set();
36
+ // Frames sent back for a software decode and not yet requested again.
37
+ #softwareFrames = new Map();
38
+ // Frames already requested in software since the last seek; each is requested once.
39
+ #reissued = new Set();
40
+ constructor(backend, options = {}) {
32
41
  this.#backend = backend;
33
- this.#onRefill = onRefill;
42
+ this.#onRefill = options.onRefill;
43
+ this.#replaceSurface = options.replaceSurface;
44
+ this.#onRendererChange = options.onRendererChange;
45
+ this.#ladder = options.recovery ?? new GpuRecoveryLadder();
34
46
  }
35
47
  /** Initializes the backend on `canvas`; every other method throws before this resolves. */
36
48
  async initialize(canvas) {
@@ -38,8 +50,8 @@ export class Alpha2Player {
38
50
  this.#initialized = true;
39
51
  }
40
52
  /**
41
- * Uploads a decoded frame, taking it over: it is closed when it is not uploaded. A frame from an
42
- * earlier generation (decoded before the last seek or device recovery) is closed and dropped.
53
+ * Uploads a decoded frame, taking ownership. Frames from an earlier generation (before the last
54
+ * seek or recovery) are closed and dropped.
43
55
  *
44
56
  * @throws Before {@link Alpha2Player.initialize} has resolved and after
45
57
  * {@link Alpha2Player.dispose}, having closed the frame.
@@ -54,21 +66,37 @@ export class Alpha2Player {
54
66
  frame.frame.close();
55
67
  return;
56
68
  }
57
- await this.#backend.uploadVideoFrame(frame);
69
+ try {
70
+ await this.#backend.uploadVideoFrame(frame);
71
+ }
72
+ catch (error) {
73
+ // The backend closed the frame; it is requested again in software after the refill.
74
+ const request = softwareDecodeRequest(error);
75
+ if (request === undefined || frame.decode === "software")
76
+ throw error;
77
+ const key = frameKey(request.sourceId, request.mediaTimeTicks);
78
+ if (this.#reissued.has(key))
79
+ throw error;
80
+ if (request.reason === "non-planar")
81
+ this.#softwareSources.add(request.sourceId);
82
+ this.#softwareFrames.set(key, request.reason);
83
+ return;
84
+ }
58
85
  this.#uploads += 1;
59
86
  }
60
87
  /**
61
- * Presents `timeTicks`, recovering a lost device first and refilling missing
62
- * frames through `onRefill`. Resolves `undefined` when a later `present` or
63
- * `seek` superseded this one.
88
+ * Presents `timeTicks`, recovering a lost device first and refilling missing frames through
89
+ * `onRefill`. Resolves `undefined` when a later `present` or `seek` superseded this one.
64
90
  *
65
- * Presentations that overlap a recovery wait for it rather than starting another, and reject
66
- * with its error when it fails; the next presentation after a failure tries again.
91
+ * Rejects with a fatal `GPU_DEVICE_LOST` when no renderer can be made (or a fresh surface was
92
+ * needed without `replaceSurface`); every later presentation rejects the same way.
67
93
  *
68
94
  * @throws Before {@link Alpha2Player.initialize} has resolved.
69
95
  */
70
96
  async present(timeTicks) {
71
97
  this.#assertInitialized();
98
+ if (this.#terminal !== undefined)
99
+ throw this.#terminal;
72
100
  const request = ++this.#latestRequest;
73
101
  let reason = "prefetch";
74
102
  if (this.#recovering !== undefined || this.#backend.isDeviceLost()) {
@@ -79,16 +107,16 @@ export class Alpha2Player {
79
107
  return request === this.#latestRequest ? result : undefined;
80
108
  }
81
109
  /**
82
- * Seeks to `timeTicks`: frames decoded for earlier requests are dropped when
83
- * they arrive, the backend is reset, and the target is presented once
84
- * `onRefill` has delivered its frames. Resolves `undefined` when a later
85
- * request superseded it.
110
+ * Seeks to `timeTicks`, dropping frames decoded for earlier requests, and presents the target
111
+ * once `onRefill` has delivered. Resolves `undefined` when a later request superseded it.
86
112
  *
87
113
  * @throws Before {@link Alpha2Player.initialize} has resolved.
88
114
  */
89
115
  async seek(timeTicks) {
90
116
  this.#assertInitialized();
91
117
  this.#generation += 1;
118
+ this.#softwareFrames.clear();
119
+ this.#reissued.clear();
92
120
  const request = ++this.#latestRequest;
93
121
  await this.#backend.reset();
94
122
  return this.#presentFilled(timeTicks, request, "seek");
@@ -99,11 +127,10 @@ export class Alpha2Player {
99
127
  this.#backend.dispose();
100
128
  this.#initialized = false;
101
129
  }
102
- /** Joins the recovery in flight, or starts one; the generation moves once per recovery. */
103
130
  #recover() {
104
131
  this.#recovering ??= (async () => {
105
132
  try {
106
- await this.#backend.recover();
133
+ await this.#climbDown();
107
134
  this.#generation += 1;
108
135
  }
109
136
  finally {
@@ -112,16 +139,65 @@ export class Alpha2Player {
112
139
  })();
113
140
  return this.#recovering;
114
141
  }
142
+ async #climbDown() {
143
+ const report = this.#backend.lossReport() ?? {
144
+ hung: false,
145
+ frameIndex: null,
146
+ timeTicks: null,
147
+ gpuMs: null,
148
+ message: "the GPU device was lost",
149
+ };
150
+ let step = this.#ladder.onLoss(report, await this.#backend.probeSurface());
151
+ for (;;) {
152
+ let canvas;
153
+ try {
154
+ if (step.surface === "fresh") {
155
+ if (this.#replaceSurface === undefined) {
156
+ throw this.#fail(new Alpha2WasmError({
157
+ code: "GPU_DEVICE_LOST",
158
+ message: `${report.message}, and the canvas cannot take another renderer: give Alpha2Player a replaceSurface option`,
159
+ fatal: true,
160
+ }));
161
+ }
162
+ canvas = await this.#replaceSurface();
163
+ }
164
+ const choice = await this.#backend.recover(step, canvas);
165
+ if (choice !== undefined)
166
+ this.#onRendererChange?.(choice);
167
+ return;
168
+ }
169
+ catch (error) {
170
+ if (error === this.#terminal)
171
+ throw error;
172
+ const next = this.#ladder.onRecoveryFailed(step, error);
173
+ if (next === "terminal") {
174
+ const message = error instanceof Error ? error.message : String(error);
175
+ const terminal = new Alpha2WasmError({
176
+ code: "GPU_DEVICE_LOST",
177
+ message: `${report.message}, and no renderer could be made again (${message})`,
178
+ fatal: true,
179
+ });
180
+ Object.defineProperty(terminal, "cause", {
181
+ value: error,
182
+ configurable: true,
183
+ });
184
+ throw this.#fail(terminal);
185
+ }
186
+ step = next;
187
+ }
188
+ }
189
+ }
190
+ #fail(error) {
191
+ this.#terminal = error;
192
+ return error;
193
+ }
115
194
  #assertInitialized() {
116
195
  if (!this.#initialized) {
117
196
  throw new Error("Alpha2Player must be initialized before use");
118
197
  }
119
198
  }
120
- /**
121
- * Presents `timeTicks`, and again after each refill that uploaded something while frames are
122
- * missing. Each round must lack fewer frames than the last, so a source that never arrives ends
123
- * it; a newer request ends it too, since that one will be shown instead.
124
- */
199
+ // Re-presents after each refill while frames are missing. Each round must lack fewer frames
200
+ // than the last, so a source that never arrives ends the loop.
125
201
  async #presentFilled(timeTicks, request, reason) {
126
202
  let result = await this.#backend.present(timeTicks);
127
203
  let lacking = Number.POSITIVE_INFINITY;
@@ -140,23 +216,62 @@ export class Alpha2Player {
140
216
  async #requestMissing(result, reason) {
141
217
  if (result.missingFrames.length === 0 || this.#onRefill === undefined)
142
218
  return;
143
- // Two clips of one source at one time need one decode; each reads through its own cursor,
144
- // which the first of them names.
219
+ // Two clips of one source at one time need one decode, through the first clip's cursor.
145
220
  const requested = new Set();
146
221
  const requests = [];
147
222
  for (const { clipId, readerId, sourceId, mediaTimeTicks, } of result.missingFrames) {
148
- const key = `${sourceId}\u0000${mediaTimeTicks}`;
223
+ const key = frameKey(sourceId, mediaTimeTicks);
149
224
  if (requested.has(key))
150
225
  continue;
151
226
  requested.add(key);
227
+ const software = this.#softwareSources.has(sourceId) || this.#softwareFrames.has(key);
228
+ if (software && this.#softwareFrames.delete(key))
229
+ this.#reissued.add(key);
152
230
  requests.push({
153
231
  sourceId,
154
232
  mediaTimeTicks,
155
233
  reason,
156
234
  generation: this.#generation,
157
235
  consumerId: decoderConsumerId(clipId, readerId),
236
+ ...(software ? { decode: "software" } : {}),
158
237
  });
159
238
  }
160
239
  await this.#onRefill(requests);
240
+ await this.#refillInSoftware(requests);
241
+ }
242
+ // An unreadable frame whose source has no software decoder fails with `FRAME_SUPPLY_FAILED`.
243
+ async #refillInSoftware(requests) {
244
+ const again = new Map();
245
+ for (const request of requests) {
246
+ const key = frameKey(request.sourceId, request.mediaTimeTicks);
247
+ const why = this.#softwareFrames.get(key);
248
+ if (why === undefined)
249
+ continue;
250
+ this.#softwareFrames.delete(key);
251
+ this.#reissued.add(key);
252
+ const group = again.get(why) ?? [];
253
+ group.push({ ...request, decode: "software" });
254
+ again.set(why, group);
255
+ }
256
+ const nonPlanar = again.get("non-planar");
257
+ if (nonPlanar !== undefined)
258
+ await this.#onRefill?.(nonPlanar);
259
+ const unreadable = again.get("unreadable");
260
+ if (unreadable === undefined)
261
+ return;
262
+ try {
263
+ await this.#onRefill?.(unreadable);
264
+ }
265
+ catch (error) {
266
+ if (error?.code !==
267
+ "PLANAR_DECODE_UNAVAILABLE")
268
+ throw error;
269
+ throw Object.assign(new Error(`the browser could not read back the frame of ${unreadable
270
+ .map(({ sourceId }) => sourceId)
271
+ .join(", ")}, and decoding it again in software failed`, { cause: error.cause ?? error }), { code: "FRAME_SUPPLY_FAILED" });
272
+ }
161
273
  }
162
274
  }
275
+ function frameKey(sourceId, mediaTimeTicks) {
276
+ return `${sourceId}\u0000${mediaTimeTicks}`;
277
+ }
@@ -1,16 +1,11 @@
1
1
  import type { FrameUploadReceipt } from "./effects.js";
2
- /** The engine calls {@link uploadPresentedFrame} makes. */
3
2
  export interface PresentedFrameEngine {
4
3
  /** `"bitmap"` where the engine copies frames through a canvas after WebGPU refused one. */
5
4
  readonly videoFrameCopy?: string;
6
5
  uploadPresentedVideoFrame(sourceId: string, mediaTimeTicks: bigint, frame: VideoFrame, width: number, height: number, rotation: number, mirror: boolean): FrameUploadReceipt;
7
- /** `uploadPresentedVideoFrame` for a bitmap made with `premultiplyAlpha: "none"`. */
6
+ /** Expects a bitmap made with `premultiplyAlpha: "none"`. */
8
7
  uploadPresentedImageBitmap?(sourceId: string, mediaTimeTicks: bigint, bitmap: ImageBitmap, width: number, height: number, rotation: number, mirror: boolean): FrameUploadReceipt;
9
8
  }
10
- /** Whether {@link uploadPresentedFrame} sends `engine` bitmaps instead of frames. */
11
9
  export declare function sendsBitmaps(engine: PresentedFrameEngine): boolean;
12
- /**
13
- * Uploads `frame`, as a bitmap where {@link sendsBitmaps}, and closes it either way. A frame that
14
- * cannot be made into a bitmap is sent as it is.
15
- */
10
+ /** Uploads `frame`, as a bitmap where {@link sendsBitmaps}, falling back to the frame itself. */
16
11
  export declare function uploadPresentedFrame(engine: PresentedFrameEngine, sourceId: string, mediaTimeTicks: bigint, frame: VideoFrame, width: number, height: number, rotation: number, mirror: boolean): Promise<FrameUploadReceipt>;
@@ -1,22 +1,17 @@
1
- // Presented VideoFrame uploads. Where WebGPU refuses a VideoFrame (Firefox), the engine draws each
2
- // frame on a 2D canvas on the calling thread; a bitmap from `createImageBitmap` skips that draw.
3
- /** Whether {@link uploadPresentedFrame} sends `engine` bitmaps instead of frames. */
1
+ // Where WebGPU refuses a VideoFrame (Firefox), the engine draws each frame on a 2D canvas on the
2
+ // calling thread; sending a bitmap from `createImageBitmap` skips that draw.
4
3
  export function sendsBitmaps(engine) {
5
4
  return (engine.videoFrameCopy === "bitmap" &&
6
5
  typeof engine.uploadPresentedImageBitmap === "function" &&
7
6
  typeof createImageBitmap === "function");
8
7
  }
9
- /**
10
- * Uploads `frame`, as a bitmap where {@link sendsBitmaps}, and closes it either way. A frame that
11
- * cannot be made into a bitmap is sent as it is.
12
- */
8
+ /** Uploads `frame`, as a bitmap where {@link sendsBitmaps}, falling back to the frame itself. */
13
9
  export async function uploadPresentedFrame(engine, sourceId, mediaTimeTicks, frame, width, height, rotation, mirror) {
14
10
  const send = () => engine.uploadPresentedVideoFrame(sourceId, mediaTimeTicks, frame, width, height, rotation, mirror);
15
11
  if (!sendsBitmaps(engine) || engine.uploadPresentedImageBitmap === undefined)
16
12
  return send();
17
13
  let bitmap;
18
14
  try {
19
- // The display size, as the engine's canvas draws it.
20
15
  bitmap = await createImageBitmap(frame, {
21
16
  premultiplyAlpha: "none",
22
17
  resizeWidth: frame.displayWidth,