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
@@ -0,0 +1,116 @@
1
+ /** See {@link VideoLatencyProbe}. */
2
+ export type EncoderProbeOutcome = "output" | "silent" | "failed" | "timed-out";
3
+ /**
4
+ * How `videoEncoderLatencyMode` (`alpha2/mediabunny`) chose `mode`. `ms` is the total probe time
5
+ * and `outcome` the last probe's result: `"output"` (a chunk came out), `"silent"` (flushed with no
6
+ * output), `"failed"`, `"timed-out"` (inconclusive) or `"unavailable"` (no `VideoEncoder`).
7
+ * `cached` means a definitive answer from an earlier export was reused.
8
+ */
9
+ export interface VideoLatencyProbe {
10
+ readonly mode: "quality" | "realtime";
11
+ readonly ms: number;
12
+ readonly outcome: EncoderProbeOutcome | "unavailable";
13
+ readonly cached: boolean;
14
+ }
15
+ /**
16
+ * AAC-LC delay probe result: `"output"` (encoded and decoded), `"failed"` (encoder or decoder
17
+ * error), `"timed-out"`, or `"unavailable"` (no WebCodecs audio).
18
+ */
19
+ export type AacProbeOutcome = "output" | "failed" | "timed-out" | "unavailable";
20
+ /** Result of `aacEncoderPrimingProbe` (`alpha2/mediabunny`). */
21
+ export interface AacEncoderProbe {
22
+ /** Sample rate the stream declares; undefined when there was no output. */
23
+ readonly rate?: number;
24
+ /** Priming in frames; 0 when not found or the stream is at another rate. */
25
+ readonly delay: number;
26
+ readonly outcome: AacProbeOutcome;
27
+ /** Total probe time. */
28
+ readonly ms: number;
29
+ /** Probes run; a timeout triggers a second. */
30
+ readonly attempts: number;
31
+ }
32
+ /** Encoder latency over the frames one export encoded. */
33
+ export interface EncodeLatency {
34
+ readonly mean: number;
35
+ readonly max: number;
36
+ readonly count: number;
37
+ }
38
+ /** Timing and memory of one browser export, in milliseconds and bytes. */
39
+ export interface BrowserExportPerformance {
40
+ readonly pipelineEnabled: true;
41
+ /** Time waiting for source frames to be decoded, converted and uploaded. */
42
+ readonly sourceSupplyMs: number;
43
+ /** Worker/wasm evaluation, render, submission and response time. */
44
+ readonly frameSubmitMs: number;
45
+ /** End-to-end GPU mapping latency, including time overlapped with other work. */
46
+ readonly readbackMapLatencyMs: number;
47
+ /** Time for which ordered export progress was blocked on GPU mapping. */
48
+ readonly readbackWaitMs: number;
49
+ /** Same as `readbackWaitMs`, under the native host's name. */
50
+ readonly readbackBlockingMs: number;
51
+ /** Time a rendered frame waited behind earlier writes before its own write began. */
52
+ readonly encodeQueueWaitMs: number;
53
+ /**
54
+ * Time in the sink's video write, including waiting for encoder queue space. Encoding itself is
55
+ * measured by `videoEncodeLatencyMs`.
56
+ */
57
+ readonly videoWriteWaitMs: number;
58
+ /** Time to flush the encoders and finalize the file after the last frame. */
59
+ readonly finishMs: number;
60
+ /** Configured limit on concurrent readbacks. */
61
+ readonly maxInFlightReadbacks: number;
62
+ /** Configured limit on pending video writes. */
63
+ readonly maxPendingVideoWrites: number;
64
+ /** Readback bytes the loop may hold at once. */
65
+ readonly inFlightByteBudget: number;
66
+ readonly stagingBytesPerFrame: number;
67
+ readonly peakReadbackBytes: number;
68
+ /** Raw video bytes read back from GPU staging buffers. */
69
+ readonly outputReadbackBytes: number;
70
+ /** Bytes copied to pack read-back planes tight where `VideoFrame` ignores `layout`; else 0. */
71
+ readonly outputRepackBytes: number;
72
+ readonly peakEncodeQueueBytes: number;
73
+ /** Pending readbacks plus writes, peak and average over the loop's turns. */
74
+ readonly maxPendingMediaEvents: number;
75
+ readonly averagePendingMediaEvents: number;
76
+ readonly peakInFlightReadbacks: number;
77
+ /** Peak pending video writes. */
78
+ readonly maxEncodeQueueEvents: number;
79
+ /** Frames that waited for an earlier write. */
80
+ readonly encodeBackpressureCount: number;
81
+ /** Frames submitted while writes were pending. */
82
+ readonly pipelineOverlapFrames: number;
83
+ /** Per-frame encoder time, hand-over to packet; zero when the sink does not report it. */
84
+ readonly videoEncodeLatencyMs: EncodeLatency;
85
+ }
86
+ /** Accumulator for {@link BrowserExportPerformance}. */
87
+ export declare class ExportMetrics {
88
+ #private;
89
+ sourceSupplyMs: number;
90
+ frameSubmitMs: number;
91
+ readbackMapLatencyMs: number;
92
+ readbackWaitMs: number;
93
+ encodeQueueWaitMs: number;
94
+ videoWriteWaitMs: number;
95
+ finishMs: number;
96
+ stagingBytesPerFrame: number;
97
+ peakReadbackBytes: number;
98
+ outputReadbackBytes: number;
99
+ outputRepackBytes: number;
100
+ peakEncodeQueueBytes: number;
101
+ maxPendingMediaEvents: number;
102
+ peakInFlightReadbacks: number;
103
+ maxEncodeQueueEvents: number;
104
+ encodeBackpressureCount: number;
105
+ pipelineOverlapFrames: number;
106
+ constructor(limits: {
107
+ readonly maxInFlightReadbacks: number;
108
+ readonly maxPendingVideoWrites: number;
109
+ readonly inFlightByteBudget: number;
110
+ });
111
+ /** Records the pending readbacks plus writes at one turn of the loop. */
112
+ samplePending(depth: number): void;
113
+ finish(videoEncodeLatencyMs?: EncodeLatency): BrowserExportPerformance;
114
+ }
115
+ /** Every field of {@link BrowserExportPerformance}, in report order. */
116
+ export declare const BROWSER_EXPORT_PERFORMANCE_FIELDS: readonly (keyof BrowserExportPerformance)[];
@@ -0,0 +1,74 @@
1
+ // Shared metrics for browser export loops. A field with the same name as a native host field
2
+ // measures the same quantity.
3
+ /** Accumulator for {@link BrowserExportPerformance}. */
4
+ export class ExportMetrics {
5
+ sourceSupplyMs = 0;
6
+ frameSubmitMs = 0;
7
+ readbackMapLatencyMs = 0;
8
+ readbackWaitMs = 0;
9
+ encodeQueueWaitMs = 0;
10
+ videoWriteWaitMs = 0;
11
+ finishMs = 0;
12
+ stagingBytesPerFrame = 0;
13
+ peakReadbackBytes = 0;
14
+ outputReadbackBytes = 0;
15
+ outputRepackBytes = 0;
16
+ peakEncodeQueueBytes = 0;
17
+ maxPendingMediaEvents = 0;
18
+ peakInFlightReadbacks = 0;
19
+ maxEncodeQueueEvents = 0;
20
+ encodeBackpressureCount = 0;
21
+ pipelineOverlapFrames = 0;
22
+ #pendingTotal = 0;
23
+ #pendingSamples = 0;
24
+ #limits;
25
+ constructor(limits) {
26
+ this.#limits = limits;
27
+ }
28
+ /** Records the pending readbacks plus writes at one turn of the loop. */
29
+ samplePending(depth) {
30
+ this.maxPendingMediaEvents = Math.max(this.maxPendingMediaEvents, depth);
31
+ this.#pendingTotal += depth;
32
+ this.#pendingSamples += 1;
33
+ }
34
+ finish(videoEncodeLatencyMs) {
35
+ return {
36
+ pipelineEnabled: true,
37
+ sourceSupplyMs: this.sourceSupplyMs,
38
+ frameSubmitMs: this.frameSubmitMs,
39
+ readbackMapLatencyMs: this.readbackMapLatencyMs,
40
+ readbackWaitMs: this.readbackWaitMs,
41
+ readbackBlockingMs: this.readbackWaitMs,
42
+ encodeQueueWaitMs: this.encodeQueueWaitMs,
43
+ videoWriteWaitMs: this.videoWriteWaitMs,
44
+ finishMs: this.finishMs,
45
+ maxInFlightReadbacks: this.#limits.maxInFlightReadbacks,
46
+ maxPendingVideoWrites: this.#limits.maxPendingVideoWrites,
47
+ inFlightByteBudget: this.#limits.inFlightByteBudget,
48
+ stagingBytesPerFrame: this.stagingBytesPerFrame,
49
+ peakReadbackBytes: this.peakReadbackBytes,
50
+ outputReadbackBytes: this.outputReadbackBytes,
51
+ outputRepackBytes: this.outputRepackBytes,
52
+ peakEncodeQueueBytes: this.peakEncodeQueueBytes,
53
+ maxPendingMediaEvents: this.maxPendingMediaEvents,
54
+ averagePendingMediaEvents: this.#pendingSamples === 0
55
+ ? 0
56
+ : this.#pendingTotal / this.#pendingSamples,
57
+ peakInFlightReadbacks: this.peakInFlightReadbacks,
58
+ maxEncodeQueueEvents: this.maxEncodeQueueEvents,
59
+ encodeBackpressureCount: this.encodeBackpressureCount,
60
+ pipelineOverlapFrames: this.pipelineOverlapFrames,
61
+ videoEncodeLatencyMs: videoEncodeLatencyMs ?? {
62
+ mean: 0,
63
+ max: 0,
64
+ count: 0,
65
+ },
66
+ };
67
+ }
68
+ }
69
+ /** Every field of {@link BrowserExportPerformance}, in report order. */
70
+ export const BROWSER_EXPORT_PERFORMANCE_FIELDS = Object.freeze(Object.keys(new ExportMetrics({
71
+ maxInFlightReadbacks: 0,
72
+ maxPendingVideoWrites: 0,
73
+ inFlightByteBudget: 0,
74
+ }).finish()));
@@ -1,67 +1,84 @@
1
1
  /**
2
- * A reference retry policy for exports, decided from classified failures and the attempts so far.
2
+ * Reference retry policy for exports, decided from classified failures and the attempt history.
3
+ * It is pure: the caller schedules and runs attempts.
3
4
  *
4
- * It is a policy, not a mechanism: a service calls it with its own history and options and decides
5
- * what to do with the answer. The defaults (three attempts, backing off one second, then two, then
6
- * four) are shared by every caller, so services built on it retry alike.
5
+ * An export is retried whole on a fresh device or host process. Attempts may change the in-flight
6
+ * budget, the renderer and the video encoder, never the output settings.
7
7
  *
8
- * An export is retried whole, with a fresh device or host process, never resumed mid-file. What
9
- * changes between attempts is only how much it keeps in flight: a failure that is evidence of
10
- * memory exhaustion steps down to a smaller profile, and a transient one (a lost device, a crashed
11
- * host, a refused mapping) retries as it was, stepping down only if it recurs at the same point.
12
- * Output settings (resolution, rate, codec, quality, color, audio) are never changed by a retry.
13
- * The encoder can change: under the native host's `inputPolicy: auto`, a budget too small for the
14
- * GPU-resident path's surfaces takes the readback path and its encoder, so the bitstream may
15
- * differ; pin `inputPolicy` to keep it.
8
+ * - `DEVICE_HUNG`, or a GPU loss recurring at the same frame, is never retried on the GPU; it moves
9
+ * to the CPU renderer when available, else stops.
10
+ * - Memory exhaustion steps down to a smaller profile.
11
+ * - An encode failure retries once with the software video encoder when available.
12
+ * - `RESOURCE_BUSY` retries unchanged after the longer of its `retryAfterMs` and the backoff.
13
+ * - Other transient failures retry unchanged and step down only if they recur at the same point.
14
+ * A browser that has already lost the GPU twice moves to the CPU or stops, since the browser
15
+ * withdraws GPU access at the next reset.
16
+ *
17
+ * Under the native host's `inputPolicy: auto` a small budget can also switch to the readback path
18
+ * and its encoder, changing the bitstream; pin `inputPolicy` to avoid that.
16
19
  */
17
20
  import type { ExportFailure } from "./export-failure.js";
18
- /** How much an attempt keeps in flight, as a fraction of each budget it would otherwise use. */
21
+ /** In-flight budget scale for an attempt. */
19
22
  export interface RetryProfile {
20
- /** Identifies the profile in `history`; profiles are matched by name. */
23
+ /** Profiles in `history` are matched by name. */
21
24
  readonly name: string;
22
- /** The fraction of each in-flight budget the attempt uses, in `(0, 1]`. */
25
+ /** Fraction of each in-flight budget, in `(0, 1]`. */
23
26
  readonly memoryScale: number;
24
27
  }
25
- /** The profiles attempts step down through: everything, half, a quarter. */
28
+ /** Default profiles: full, half and quarter budgets. */
26
29
  export declare const RETRY_PROFILES: readonly RetryProfile[];
27
- /** One failed attempt, as the policy reads it. */
30
+ export type AttemptRenderer = "gpu" | "cpu";
31
+ /** `default` lets the runtime choose the video encoder. */
32
+ export type AttemptVideoEncoder = "default" | "software";
33
+ /** One failed attempt. */
28
34
  export interface AttemptOutcome {
29
- /** The attempt's classified failure. */
30
35
  readonly failure: ExportFailure;
31
- /** The profile the attempt ran with. */
32
36
  readonly profile: RetryProfile;
37
+ readonly renderer: AttemptRenderer;
38
+ readonly videoEncoder: AttemptVideoEncoder;
33
39
  }
34
- /** Overrides for {@link decideRetry}'s defaults. */
40
+ /** Options for {@link decideRetry}. */
35
41
  export interface RetryPolicyOptions {
36
- /** Attempts in all, the first included. Default 3. */
42
+ /** Total attempts, including the first. Default 3. */
37
43
  readonly maxAttempts?: number;
38
44
  /** Delay before attempt `n + 1`, given `n` failed attempts. Default `1000 * 2^(n-1)` ms. */
39
45
  readonly backoffMs?: (failedAttempts: number) => number;
40
46
  /** Profiles to step down through, largest first. Default {@link RETRY_PROFILES}. */
41
47
  readonly profiles?: readonly RetryProfile[];
48
+ /** Whether the caller can run an attempt on a CPU renderer. Default false. */
49
+ readonly cpuRenderer?: boolean;
50
+ /** GPU losses this browser page has already seen, from any work. Default 0. */
51
+ readonly pageGpuLosses?: number;
52
+ /**
53
+ * Whether a software video encoder is available (`canEncodeInSoftware` in `alpha2/mediabunny`).
54
+ * Default true.
55
+ */
56
+ readonly softwareVideoEncoder?: boolean;
42
57
  }
43
58
  /**
44
- * What {@link decideRetry} decided: retry after `delayMs` with `profile`, or
45
- * stop. `reason` is a human-readable explanation for logs and diagnostics.
59
+ * Result of {@link decideRetry}. On stop, `failure` is the failure as the policy read it (a loss
60
+ * recurring at the same frame becomes `DEVICE_HUNG`). `reason` is a human-readable explanation.
46
61
  */
47
62
  export type RetryDecision = {
48
63
  readonly retry: true;
49
64
  readonly delayMs: number;
50
65
  readonly profile: RetryProfile;
66
+ readonly renderer: AttemptRenderer;
67
+ readonly videoEncoder: AttemptVideoEncoder;
51
68
  readonly reason: string;
52
69
  } | {
53
70
  readonly retry: false;
54
71
  readonly reason: string;
72
+ readonly failure: ExportFailure | undefined;
55
73
  };
56
74
  /**
57
- * Whether a retry could succeed where `failure` did: not for invalid input or a GPU validation
58
- * error, a budget or storage refusal, a cancellation, or a file that could not be written or
59
- * downloaded (a finished file is downloaded again, not rendered again).
75
+ * Whether a retry could help. False for invalid input, validation errors, budget or storage
76
+ * refusals, cancellation, `DEVICE_HUNG`, output I/O failures and download failures. Use
77
+ * {@link decideRetry} to also consider a CPU renderer.
60
78
  */
61
79
  export declare function isRetryableFailure(failure: ExportFailure): boolean;
62
80
  /**
63
- * Whether to try again after the attempts in `history` (oldest first) failed,
64
- * and how. An empty history decides not to retry. Pure: it schedules nothing,
65
- * and the caller waits `delayMs` and runs the next attempt itself.
81
+ * Decides whether and how to retry after the failed attempts in `history` (oldest first). An empty
82
+ * history never retries. The caller waits `delayMs` and runs the next attempt.
66
83
  */
67
84
  export declare function decideRetry(history: readonly AttemptOutcome[], options?: RetryPolicyOptions): RetryDecision;
@@ -1,26 +1,28 @@
1
1
  /**
2
- * A reference retry policy for exports, decided from classified failures and the attempts so far.
2
+ * Reference retry policy for exports, decided from classified failures and the attempt history.
3
+ * It is pure: the caller schedules and runs attempts.
3
4
  *
4
- * It is a policy, not a mechanism: a service calls it with its own history and options and decides
5
- * what to do with the answer. The defaults (three attempts, backing off one second, then two, then
6
- * four) are shared by every caller, so services built on it retry alike.
5
+ * An export is retried whole on a fresh device or host process. Attempts may change the in-flight
6
+ * budget, the renderer and the video encoder, never the output settings.
7
7
  *
8
- * An export is retried whole, with a fresh device or host process, never resumed mid-file. What
9
- * changes between attempts is only how much it keeps in flight: a failure that is evidence of
10
- * memory exhaustion steps down to a smaller profile, and a transient one (a lost device, a crashed
11
- * host, a refused mapping) retries as it was, stepping down only if it recurs at the same point.
12
- * Output settings (resolution, rate, codec, quality, color, audio) are never changed by a retry.
13
- * The encoder can change: under the native host's `inputPolicy: auto`, a budget too small for the
14
- * GPU-resident path's surfaces takes the readback path and its encoder, so the bitstream may
15
- * differ; pin `inputPolicy` to keep it.
8
+ * - `DEVICE_HUNG`, or a GPU loss recurring at the same frame, is never retried on the GPU; it moves
9
+ * to the CPU renderer when available, else stops.
10
+ * - Memory exhaustion steps down to a smaller profile.
11
+ * - An encode failure retries once with the software video encoder when available.
12
+ * - `RESOURCE_BUSY` retries unchanged after the longer of its `retryAfterMs` and the backoff.
13
+ * - Other transient failures retry unchanged and step down only if they recur at the same point.
14
+ * A browser that has already lost the GPU twice moves to the CPU or stops, since the browser
15
+ * withdraws GPU access at the next reset.
16
+ *
17
+ * Under the native host's `inputPolicy: auto` a small budget can also switch to the readback path
18
+ * and its encoder, changing the bitstream; pin `inputPolicy` to avoid that.
16
19
  */
17
- /** The profiles attempts step down through: everything, half, a quarter. */
20
+ /** Default profiles: full, half and quarter budgets. */
18
21
  export const RETRY_PROFILES = Object.freeze([
19
22
  Object.freeze({ name: "default", memoryScale: 1 }),
20
23
  Object.freeze({ name: "reduced", memoryScale: 0.5 }),
21
24
  Object.freeze({ name: "minimal", memoryScale: 0.25 }),
22
25
  ]);
23
- /** Failures the same request would meet again, or that a retry cannot help. */
24
26
  const PERMANENT = new Set([
25
27
  "CANCELLED",
26
28
  "INVALID_INPUT",
@@ -28,24 +30,28 @@ const PERMANENT = new Set([
28
30
  "RESOURCE_LIMIT",
29
31
  "STORAGE_QUOTA_EXCEEDED",
30
32
  "OUTPUT_IO_FAILED",
33
+ // `decideRetry` still retries this on a CPU renderer when the caller has one.
34
+ "DEVICE_HUNG",
31
35
  ]);
32
- /** Failures that are evidence of memory running out. */
33
36
  const MEMORY = new Set([
34
37
  "OUT_OF_MEMORY",
35
38
  "ALLOCATION_FAILED",
36
39
  ]);
40
+ const GPU_LOSSES = new Set([
41
+ "DEVICE_LOST",
42
+ "GPU_TIMEOUT",
43
+ ]);
37
44
  /**
38
- * Whether a retry could succeed where `failure` did: not for invalid input or a GPU validation
39
- * error, a budget or storage refusal, a cancellation, or a file that could not be written or
40
- * downloaded (a finished file is downloaded again, not rendered again).
45
+ * Whether a retry could help. False for invalid input, validation errors, budget or storage
46
+ * refusals, cancellation, `DEVICE_HUNG`, output I/O failures and download failures. Use
47
+ * {@link decideRetry} to also consider a CPU renderer.
41
48
  */
42
49
  export function isRetryableFailure(failure) {
43
50
  return !PERMANENT.has(failure.code) && failure.phase !== "download";
44
51
  }
45
52
  /**
46
- * Whether to try again after the attempts in `history` (oldest first) failed,
47
- * and how. An empty history decides not to retry. Pure: it schedules nothing,
48
- * and the caller waits `delayMs` and runs the next attempt itself.
53
+ * Decides whether and how to retry after the failed attempts in `history` (oldest first). An empty
54
+ * history never retries. The caller waits `delayMs` and runs the next attempt.
49
55
  */
50
56
  export function decideRetry(history, options = {}) {
51
57
  const maxAttempts = options.maxAttempts ?? 3;
@@ -53,44 +59,73 @@ export function decideRetry(history, options = {}) {
53
59
  const backoff = options.backoffMs ?? ((failed) => 1_000 * 2 ** (failed - 1));
54
60
  const last = history.at(-1);
55
61
  if (last === undefined)
56
- return { retry: false, reason: "nothing failed" };
62
+ return { retry: false, reason: "nothing failed", failure: undefined };
57
63
  const { failure } = last;
58
- if (!isRetryableFailure(failure))
59
- return {
60
- retry: false,
61
- reason: `${failure.code} at ${failure.phase} is not helped by a retry`,
62
- };
63
- if (history.length >= maxAttempts)
64
- return {
65
- retry: false,
66
- reason: `all ${maxAttempts} attempts failed`,
67
- };
64
+ // Explains a skipped rule; appended to the deciding rule's reason.
65
+ let note = "";
66
+ const stop = (why, final = failure) => ({
67
+ retry: false,
68
+ reason: why + note,
69
+ failure: final,
70
+ });
71
+ const attemptsLeft = history.length < maxAttempts;
68
72
  const index = Math.max(0, profiles.findIndex((profile) => profile.name === last.profile.name));
69
73
  const smaller = profiles[index + 1];
70
- const retry = (profile, reason) => ({
74
+ const retry = (why, changes = {}) => ({
71
75
  retry: true,
72
- delayMs: Math.max(0, backoff(history.length)),
73
- profile,
74
- reason,
76
+ delayMs: changes.delayMs ?? Math.max(0, backoff(history.length)),
77
+ profile: changes.profile ?? profiles[index] ?? last.profile,
78
+ renderer: changes.renderer ?? last.renderer,
79
+ videoEncoder: changes.videoEncoder ?? last.videoEncoder,
80
+ reason: why + note,
75
81
  });
76
- if (MEMORY.has(failure.code))
77
- return smaller
78
- ? retry(smaller, `${failure.code}: retrying with less in flight (${smaller.name})`)
79
- : {
80
- retry: false,
81
- reason: `${failure.code} with the smallest profile (${last.profile.name}): nothing left to reduce`,
82
- };
83
82
  const previous = history.at(-2);
84
- const repeated = previous !== undefined &&
85
- previous.failure.code === failure.code &&
83
+ const samePoint = previous !== undefined &&
86
84
  previous.failure.phase === failure.phase &&
87
85
  (previous.failure.frameIndex ?? null) === (failure.frameIndex ?? null);
86
+ const recurredLoss = GPU_LOSSES.has(failure.code) &&
87
+ previous !== undefined &&
88
+ previous.renderer === "gpu" &&
89
+ (GPU_LOSSES.has(previous.failure.code) ||
90
+ previous.failure.code === "DEVICE_HUNG") &&
91
+ (previous.failure.frameIndex ?? null) === (failure.frameIndex ?? null);
92
+ if (failure.code === "DEVICE_HUNG" || recurredLoss) {
93
+ const hung = { ...failure, code: "DEVICE_HUNG" };
94
+ if (last.renderer === "gpu" && options.cpuRenderer === true && attemptsLeft)
95
+ return retry(`${failure.code}: the export's own GPU work stops the GPU; retrying on the CPU renderer`, { renderer: "cpu" });
96
+ return stop(`${failure.code}: the export's own GPU work stops the GPU, and ${last.renderer === "cpu"
97
+ ? "it failed on the CPU renderer too"
98
+ : "there is no CPU renderer to retry on"}`, hung);
99
+ }
100
+ if (!isRetryableFailure(failure))
101
+ return stop(`${failure.code} at ${failure.phase} is not helped by a retry`);
102
+ if (!attemptsLeft)
103
+ return stop(`all ${maxAttempts} attempts failed`);
104
+ if (MEMORY.has(failure.code))
105
+ return smaller
106
+ ? retry(`${failure.code}: retrying with less in flight (${smaller.name})`, { profile: smaller })
107
+ : stop(`${failure.code} with the smallest profile (${last.profile.name}): nothing left to reduce`);
108
+ if (failure.phase === "encode" && last.videoEncoder === "default") {
109
+ if (options.softwareVideoEncoder !== false)
110
+ return retry(`${failure.code} while encoding: retrying with the software video encoder`, { videoEncoder: "software" });
111
+ note =
112
+ " (this browser has no software video encoder for the export to switch to)";
113
+ }
114
+ if (failure.code === "RESOURCE_BUSY")
115
+ return retry(`${failure.code}: retrying when the device may be free`, {
116
+ delayMs: Math.max(0, failure.retryAfterMs ?? 0, backoff(history.length)),
117
+ });
118
+ const repeated = samePoint && previous?.failure.code === failure.code;
119
+ if (!repeated && GPU_LOSSES.has(failure.code)) {
120
+ if (failure.origin === "browser" && (options.pageGpuLosses ?? 0) >= 2)
121
+ return options.cpuRenderer === true && last.renderer === "gpu"
122
+ ? retry(`${failure.code}: the browser withdraws GPU access after a second GPU reset; retrying on the CPU renderer`, { renderer: "cpu" })
123
+ : stop(`${failure.code}: the browser withdraws GPU access after a second GPU reset`);
124
+ return retry(`${failure.code}: retrying on a fresh ${failure.origin === "browser" ? "device" : "host"}`);
125
+ }
88
126
  if (!repeated)
89
- return retry(profiles[index] ?? last.profile, `${failure.code}: retrying on a fresh ${failure.origin === "browser" ? "device" : "host"}`);
127
+ return retry(`${failure.code}: retrying on a fresh ${failure.origin === "browser" ? "device" : "host"}`);
90
128
  return smaller
91
- ? retry(smaller, `${failure.code} again at the same point: retrying with less in flight (${smaller.name})`)
92
- : {
93
- retry: false,
94
- reason: `${failure.code} again at the same point with the smallest profile: stopping early`,
95
- };
129
+ ? retry(`${failure.code} again at the same point: retrying with less in flight (${smaller.name})`, { profile: smaller })
130
+ : stop(`${failure.code} again at the same point with the smallest profile: stopping early`);
96
131
  }