@meframe/core 0.6.13 → 0.7.2

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 (209) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/README.md +17 -5
  3. package/dist/Meframe.d.ts +14 -3
  4. package/dist/Meframe.d.ts.map +1 -1
  5. package/dist/Meframe.js +22 -12
  6. package/dist/Meframe.js.map +1 -1
  7. package/dist/cache/CacheManager.d.ts +2 -0
  8. package/dist/cache/CacheManager.d.ts.map +1 -1
  9. package/dist/cache/CacheManager.js +5 -0
  10. package/dist/cache/CacheManager.js.map +1 -1
  11. package/dist/cache/l1/VideoL1Cache.d.ts +2 -0
  12. package/dist/cache/l1/VideoL1Cache.d.ts.map +1 -1
  13. package/dist/cache/l1/VideoL1Cache.js +13 -7
  14. package/dist/cache/l1/VideoL1Cache.js.map +1 -1
  15. package/dist/cache/l2/IndexedDBStore.d.ts +1 -2
  16. package/dist/cache/l2/IndexedDBStore.d.ts.map +1 -1
  17. package/dist/cache/l2/L2Cache.d.ts +3 -2
  18. package/dist/cache/l2/L2Cache.d.ts.map +1 -1
  19. package/dist/cache/l2/L2OPFSStore.d.ts +3 -3
  20. package/dist/cache/l2/L2OPFSStore.d.ts.map +1 -1
  21. package/dist/cache/l2/OPFSStore.d.ts +1 -2
  22. package/dist/cache/l2/OPFSStore.d.ts.map +1 -1
  23. package/dist/cache/resource/AudioSampleCache.d.ts +12 -0
  24. package/dist/cache/resource/AudioSampleCache.d.ts.map +1 -1
  25. package/dist/cache/resource/AudioSampleCache.js +39 -5
  26. package/dist/cache/resource/AudioSampleCache.js.map +1 -1
  27. package/dist/cache/resource/ResourceCache.d.ts +4 -12
  28. package/dist/cache/resource/ResourceCache.d.ts.map +1 -1
  29. package/dist/cache/resource/ResourceCache.js +7 -24
  30. package/dist/cache/resource/ResourceCache.js.map +1 -1
  31. package/dist/config/defaults.d.ts.map +1 -1
  32. package/dist/config/defaults.js +4 -1
  33. package/dist/config/defaults.js.map +1 -1
  34. package/dist/config/index.d.ts +1 -1
  35. package/dist/config/index.d.ts.map +1 -1
  36. package/dist/config/types.d.ts +29 -0
  37. package/dist/config/types.d.ts.map +1 -1
  38. package/dist/config/validation.d.ts.map +1 -1
  39. package/dist/config/validation.js +3 -0
  40. package/dist/config/validation.js.map +1 -1
  41. package/dist/controllers/PlaybackController.d.ts +38 -9
  42. package/dist/controllers/PlaybackController.d.ts.map +1 -1
  43. package/dist/controllers/PlaybackController.js +269 -154
  44. package/dist/controllers/PlaybackController.js.map +1 -1
  45. package/dist/controllers/PlaybackStateMachine.d.ts.map +1 -1
  46. package/dist/controllers/PlaybackStateMachine.js +2 -1
  47. package/dist/controllers/PlaybackStateMachine.js.map +1 -1
  48. package/dist/controllers/types.d.ts +10 -2
  49. package/dist/controllers/types.d.ts.map +1 -1
  50. package/dist/controllers/types.js.map +1 -1
  51. package/dist/event/events.d.ts +2 -0
  52. package/dist/event/events.d.ts.map +1 -1
  53. package/dist/event/events.js.map +1 -1
  54. package/dist/index.d.ts +2 -2
  55. package/dist/index.d.ts.map +1 -1
  56. package/dist/index.js +1 -1
  57. package/dist/index.js.map +1 -1
  58. package/dist/model/CompositionModel.d.ts +0 -1
  59. package/dist/model/CompositionModel.d.ts.map +1 -1
  60. package/dist/model/CompositionModel.js +0 -6
  61. package/dist/model/CompositionModel.js.map +1 -1
  62. package/dist/model/patch.js +12 -12
  63. package/dist/model/patch.js.map +1 -1
  64. package/dist/node_modules/.pnpm/{mp4-muxer@5.2.2 → mp4-muxer@5.2.2_patch_hash_452653ac44da4ef32d244694e500e34d084eaa3c4232515ddec962eacc5f30ea}/node_modules/mp4-muxer/build/mp4-muxer.js +17 -3
  65. package/dist/node_modules/.pnpm/mp4-muxer@5.2.2_patch_hash_452653ac44da4ef32d244694e500e34d084eaa3c4232515ddec962eacc5f30ea/node_modules/mp4-muxer/build/mp4-muxer.js.map +1 -0
  66. package/dist/orchestrator/AudioExportSession.d.ts +28 -3
  67. package/dist/orchestrator/AudioExportSession.d.ts.map +1 -1
  68. package/dist/orchestrator/AudioExportSession.js +131 -15
  69. package/dist/orchestrator/AudioExportSession.js.map +1 -1
  70. package/dist/orchestrator/AudioPreviewSession.d.ts +6 -1
  71. package/dist/orchestrator/AudioPreviewSession.d.ts.map +1 -1
  72. package/dist/orchestrator/AudioPreviewSession.js +57 -18
  73. package/dist/orchestrator/AudioPreviewSession.js.map +1 -1
  74. package/dist/orchestrator/AudioWindowPreparer.d.ts +6 -4
  75. package/dist/orchestrator/AudioWindowPreparer.d.ts.map +1 -1
  76. package/dist/orchestrator/AudioWindowPreparer.js +247 -54
  77. package/dist/orchestrator/AudioWindowPreparer.js.map +1 -1
  78. package/dist/orchestrator/CompositionPlanner.d.ts +5 -2
  79. package/dist/orchestrator/CompositionPlanner.d.ts.map +1 -1
  80. package/dist/orchestrator/CompositionPlanner.js +8 -3
  81. package/dist/orchestrator/CompositionPlanner.js.map +1 -1
  82. package/dist/orchestrator/ExportScheduler.d.ts +1 -0
  83. package/dist/orchestrator/ExportScheduler.d.ts.map +1 -1
  84. package/dist/orchestrator/ExportScheduler.js +177 -106
  85. package/dist/orchestrator/ExportScheduler.js.map +1 -1
  86. package/dist/orchestrator/Orchestrator.d.ts +30 -4
  87. package/dist/orchestrator/Orchestrator.d.ts.map +1 -1
  88. package/dist/orchestrator/Orchestrator.js +264 -111
  89. package/dist/orchestrator/Orchestrator.js.map +1 -1
  90. package/dist/orchestrator/PreviewFrameScheduler.d.ts +21 -1
  91. package/dist/orchestrator/PreviewFrameScheduler.d.ts.map +1 -1
  92. package/dist/orchestrator/PreviewFrameScheduler.js +129 -30
  93. package/dist/orchestrator/PreviewFrameScheduler.js.map +1 -1
  94. package/dist/orchestrator/VideoWindowDecodeSession.d.ts +22 -1
  95. package/dist/orchestrator/VideoWindowDecodeSession.d.ts.map +1 -1
  96. package/dist/orchestrator/VideoWindowDecodeSession.js +426 -198
  97. package/dist/orchestrator/VideoWindowDecodeSession.js.map +1 -1
  98. package/dist/orchestrator/aac-window-timeline.d.ts +6 -2
  99. package/dist/orchestrator/aac-window-timeline.d.ts.map +1 -1
  100. package/dist/orchestrator/aac-window-timeline.js +156 -19
  101. package/dist/orchestrator/aac-window-timeline.js.map +1 -1
  102. package/dist/orchestrator/types.d.ts +5 -1
  103. package/dist/orchestrator/types.d.ts.map +1 -1
  104. package/dist/stages/compose/FrameRateConverter.d.ts +2 -1
  105. package/dist/stages/compose/FrameRateConverter.d.ts.map +1 -1
  106. package/dist/stages/compose/LayerRenderPolicy.d.ts +14 -0
  107. package/dist/stages/compose/LayerRenderPolicy.d.ts.map +1 -0
  108. package/dist/stages/compose/LayerRenderPolicy.js +18 -0
  109. package/dist/stages/compose/LayerRenderPolicy.js.map +1 -0
  110. package/dist/stages/compose/OfflineAudioMixer.d.ts +2 -0
  111. package/dist/stages/compose/OfflineAudioMixer.d.ts.map +1 -1
  112. package/dist/stages/compose/OfflineAudioMixer.js +14 -2
  113. package/dist/stages/compose/OfflineAudioMixer.js.map +1 -1
  114. package/dist/stages/compose/OwnedFrameTransform.d.ts +52 -0
  115. package/dist/stages/compose/OwnedFrameTransform.d.ts.map +1 -0
  116. package/dist/stages/compose/OwnedFrameTransform.js +154 -0
  117. package/dist/stages/compose/OwnedFrameTransform.js.map +1 -0
  118. package/dist/stages/compose/TransitionProcessor.js +0 -1
  119. package/dist/stages/compose/TransitionProcessor.js.map +1 -1
  120. package/dist/stages/compose/VideoComposer.d.ts +12 -2
  121. package/dist/stages/compose/VideoComposer.d.ts.map +1 -1
  122. package/dist/stages/compose/VideoComposer.js +100 -92
  123. package/dist/stages/compose/VideoComposer.js.map +1 -1
  124. package/dist/stages/compose/text-renderers/basic-text-renderer.d.ts.map +1 -1
  125. package/dist/stages/compose/text-renderers/basic-text-renderer.js +24 -21
  126. package/dist/stages/compose/text-renderers/basic-text-renderer.js.map +1 -1
  127. package/dist/stages/compose/text-renderers/caption-stagger-entrance-renderer.d.ts.map +1 -1
  128. package/dist/stages/compose/text-renderers/caption-stagger-entrance-renderer.js +110 -99
  129. package/dist/stages/compose/text-renderers/caption-stagger-entrance-renderer.js.map +1 -1
  130. package/dist/stages/compose/text-renderers/character-ktv-renderer.d.ts.map +1 -1
  131. package/dist/stages/compose/text-renderers/character-ktv-renderer.js +41 -38
  132. package/dist/stages/compose/text-renderers/character-ktv-renderer.js.map +1 -1
  133. package/dist/stages/compose/text-renderers/word-by-word-renderer.d.ts.map +1 -1
  134. package/dist/stages/compose/text-renderers/word-by-word-renderer.js +47 -39
  135. package/dist/stages/compose/text-renderers/word-by-word-renderer.js.map +1 -1
  136. package/dist/stages/compose/text-renderers/word-fancy-renderer.d.ts.map +1 -1
  137. package/dist/stages/compose/text-renderers/word-fancy-renderer.js +54 -48
  138. package/dist/stages/compose/text-renderers/word-fancy-renderer.js.map +1 -1
  139. package/dist/stages/compose/text-utils/text-metrics.d.ts.map +1 -1
  140. package/dist/stages/compose/text-utils/text-metrics.js +6 -4
  141. package/dist/stages/compose/text-utils/text-metrics.js.map +1 -1
  142. package/dist/stages/compose/types.d.ts +12 -0
  143. package/dist/stages/compose/types.d.ts.map +1 -1
  144. package/dist/stages/decode/BaseDecoder.d.ts +5 -0
  145. package/dist/stages/decode/BaseDecoder.d.ts.map +1 -1
  146. package/dist/stages/decode/BaseDecoder.js +52 -10
  147. package/dist/stages/decode/BaseDecoder.js.map +1 -1
  148. package/dist/stages/decode/preview-video-decoder.d.ts +48 -2
  149. package/dist/stages/decode/preview-video-decoder.d.ts.map +1 -1
  150. package/dist/stages/decode/preview-video-decoder.js +241 -71
  151. package/dist/stages/decode/preview-video-decoder.js.map +1 -1
  152. package/dist/stages/decode/video-decoder.d.ts +2 -11
  153. package/dist/stages/decode/video-decoder.d.ts.map +1 -1
  154. package/dist/stages/decode/video-decoder.js +60 -61
  155. package/dist/stages/decode/video-decoder.js.map +1 -1
  156. package/dist/stages/demux/MP3FrameParser.d.ts +18 -0
  157. package/dist/stages/demux/MP3FrameParser.d.ts.map +1 -1
  158. package/dist/stages/demux/MP3FrameParser.js +143 -11
  159. package/dist/stages/demux/MP3FrameParser.js.map +1 -1
  160. package/dist/stages/demux/MP4IndexParser.d.ts +32 -21
  161. package/dist/stages/demux/MP4IndexParser.d.ts.map +1 -1
  162. package/dist/stages/demux/MP4IndexParser.js +202 -309
  163. package/dist/stages/demux/MP4IndexParser.js.map +1 -1
  164. package/dist/stages/demux/sample-collector.d.ts +35 -0
  165. package/dist/stages/demux/sample-collector.d.ts.map +1 -0
  166. package/dist/stages/demux/sample-collector.js +105 -0
  167. package/dist/stages/demux/sample-collector.js.map +1 -0
  168. package/dist/stages/encode/BaseEncoder.d.ts +9 -2
  169. package/dist/stages/encode/BaseEncoder.d.ts.map +1 -1
  170. package/dist/stages/encode/BaseEncoder.js +90 -59
  171. package/dist/stages/encode/BaseEncoder.js.map +1 -1
  172. package/dist/stages/load/ResourceLoader.d.ts +71 -18
  173. package/dist/stages/load/ResourceLoader.d.ts.map +1 -1
  174. package/dist/stages/load/ResourceLoader.js +369 -143
  175. package/dist/stages/load/ResourceLoader.js.map +1 -1
  176. package/dist/stages/load/TaskManager.d.ts.map +1 -1
  177. package/dist/stages/load/TaskManager.js +9 -3
  178. package/dist/stages/load/TaskManager.js.map +1 -1
  179. package/dist/stages/load/types.d.ts +2 -2
  180. package/dist/stages/load/types.d.ts.map +1 -1
  181. package/dist/stages/mux/MP4Muxer.d.ts +7 -1
  182. package/dist/stages/mux/MP4Muxer.d.ts.map +1 -1
  183. package/dist/stages/mux/MP4Muxer.js +8 -10
  184. package/dist/stages/mux/MP4Muxer.js.map +1 -1
  185. package/dist/stages/mux/MuxManager.d.ts +7 -0
  186. package/dist/stages/mux/MuxManager.d.ts.map +1 -1
  187. package/dist/stages/mux/MuxManager.js +9 -0
  188. package/dist/stages/mux/MuxManager.js.map +1 -1
  189. package/dist/types.d.ts +1 -1
  190. package/dist/types.d.ts.map +1 -1
  191. package/dist/utils/errors.d.ts +2 -0
  192. package/dist/utils/errors.d.ts.map +1 -1
  193. package/dist/utils/errors.js +10 -1
  194. package/dist/utils/errors.js.map +1 -1
  195. package/dist/utils/until-aborted.d.ts +8 -0
  196. package/dist/utils/until-aborted.d.ts.map +1 -0
  197. package/dist/utils/until-aborted.js +33 -0
  198. package/dist/utils/until-aborted.js.map +1 -0
  199. package/dist/worker/WorkerChannel.d.ts.map +1 -1
  200. package/dist/worker/WorkerChannel.js +45 -10
  201. package/dist/worker/WorkerChannel.js.map +1 -1
  202. package/dist/worker/worker-manifest.js +1 -1
  203. package/dist/worker/worker-manifest.js.map +1 -1
  204. package/dist/workers/stages/export/{export.worker.C8jKSbVj.js → export.worker.BG8HA7dY.js} +745 -450
  205. package/dist/workers/stages/export/export.worker.BG8HA7dY.js.map +1 -0
  206. package/dist/workers/worker-manifest.json +1 -1
  207. package/package.json +23 -22
  208. package/dist/node_modules/.pnpm/mp4-muxer@5.2.2/node_modules/mp4-muxer/build/mp4-muxer.js.map +0 -1
  209. package/dist/workers/stages/export/export.worker.C8jKSbVj.js.map +0 -1
@@ -5,19 +5,32 @@ import { createImageBitmapFromBlob } from "../../utils/image-utils.js";
5
5
  import { MP4IndexParser } from "../demux/MP4IndexParser.js";
6
6
  import { MP3FrameParser } from "../demux/MP3FrameParser.js";
7
7
  import { WAVIndexParser } from "../demux/WAVIndexParser.js";
8
- import { ResourceNotCachedError, NotMP4Error, MP4MoovNotFoundError, isTerminalMediaResourceError, ResourceCorruptedError, EmptyStreamError, isDOMException, toResourceErrorInfo, UnsupportedAudioContainerError } from "../../utils/errors.js";
8
+ import { ResourceNotCachedError, NotMP4Error, MP4MoovNotFoundError, isTerminalMediaResourceError, UnsupportedAudioContainerError, ResourceCorruptedError, EmptyStreamError, isDOMException, toResourceErrorInfo, markReportedToHost, ResourceSupersededError } from "../../utils/errors.js";
9
+ import { untilAborted } from "../../utils/until-aborted.js";
9
10
  class ResourceLoader {
10
11
  cacheManager;
11
- model;
12
+ getCompositionModel;
13
+ get model() {
14
+ return this.getCompositionModel();
15
+ }
12
16
  taskManager;
13
17
  eventBus;
14
- onStateChange;
15
18
  onResourceInvalidated;
16
19
  blobCache = /* @__PURE__ */ new Map();
17
- parsingIndexes = /* @__PURE__ */ new Set();
20
+ parsingIndexes = /* @__PURE__ */ new Map();
18
21
  disposed = false;
22
+ running = /* @__PURE__ */ new Set();
23
+ imageControllers = /* @__PURE__ */ new Set();
24
+ loadOwners = /* @__PURE__ */ new Map();
25
+ readOwners = /* @__PURE__ */ new Set();
26
+ disposePromise = null;
27
+ // null is the tombstone of a removed resource; only a string is a live identity.
19
28
  sourceIdentities = /* @__PURE__ */ new Map();
20
29
  sourceRevisions = /* @__PURE__ */ new Map();
30
+ // The last live identity of each id, kept across removal so an id added back can be compared with what its bytes were.
31
+ lastLiveIdentities = /* @__PURE__ */ new Map();
32
+ // Ids whose next load must ask the host (ensureCached) even when bytes for the id are already cached.
33
+ unconfirmedSources = /* @__PURE__ */ new Set();
21
34
  consumers = /* @__PURE__ */ new Map();
22
35
  ensureCached;
23
36
  // Preloading state
@@ -33,11 +46,45 @@ class ResourceLoader {
33
46
  const preloadConcurrency = config.preloadConcurrency ?? 1;
34
47
  this.taskManager = new TaskManager(maxConcurrent, preloadConcurrency);
35
48
  this.eventBus = options.eventBus;
36
- this.onStateChange = options.onStateChange;
37
49
  this.onResourceInvalidated = options.onResourceInvalidated;
38
50
  this.cacheManager = options.cacheManager;
51
+ this.getCompositionModel = options.getCompositionModel;
39
52
  this.ensureCached = options.ensureCached;
40
53
  }
54
+ /**
55
+ * Settled work is removed from `running`; drain and dispose wait on what is still in flight. An owner signal ends the operation
56
+ * even when the host never answers the read it awaits. `discard` releases a native result that arrives after the owner aborted;
57
+ * the result has no caller then, so it is released there, once.
58
+ */
59
+ track(promise, signal, discard) {
60
+ const tracked = untilAborted(promise, signal, discard);
61
+ this.running.add(tracked);
62
+ const forget = () => this.running.delete(tracked);
63
+ tracked.then(forget, forget);
64
+ return tracked;
65
+ }
66
+ /**
67
+ * Waits for `promise` on behalf of an operation that owns `signal`. The wait ends with that signal, with drain or dispose (which
68
+ * abort every owner in `readOwners`), or when the promise settles. The promise is not cancelled, so a host read that never
69
+ * answers cannot hold drain, dispose or a replacement.
70
+ */
71
+ awaitOwned(promise, signal) {
72
+ const owner = new AbortController();
73
+ const abortWithCaller = () => owner.abort(signal?.reason);
74
+ this.readOwners.add(owner);
75
+ if (signal?.aborted) abortWithCaller();
76
+ else signal?.addEventListener("abort", abortWithCaller, { once: true });
77
+ return this.track(promise, owner.signal).finally(() => {
78
+ this.readOwners.delete(owner);
79
+ signal?.removeEventListener("abort", abortWithCaller);
80
+ });
81
+ }
82
+ /** Aborts every owner that awaitOwned registered; drain and dispose call it. */
83
+ abortReads() {
84
+ for (const owner of this.readOwners) {
85
+ owner.abort(new DOMException("Resource loader disposed", "AbortError"));
86
+ }
87
+ }
41
88
  assertTaskCurrent(task) {
42
89
  const resource = this.model?.getResource(task.resourceId);
43
90
  if (this.disposed || task.controller?.signal.aborted || !resource || resource.uri !== task.resource.uri || resource.type !== task.resource.type || task.sourceRevision !== void 0 && task.sourceRevision !== this.sourceRevisions.get(task.resourceId)) {
@@ -68,29 +115,52 @@ class ResourceLoader {
68
115
  else signal?.addEventListener("abort", abort, { once: true });
69
116
  });
70
117
  }
71
- async refreshResourceIdentities(model) {
72
- const deletes = [];
118
+ /**
119
+ * Records each resource's source identity (type and URI) and retires in-memory data that belongs to an older source.
120
+ *
121
+ * A live id that arrives with a new type or URI, or one added back after it was removed, is re-identified: its load task is
122
+ * cancelled, its index and parsed data are dropped, its revision moves on (so work for the old source publishes nothing), it
123
+ * becomes `pending`, and its next load calls the host's `ensureCached` with the new resource, even when bytes for the id are
124
+ * already cached. The host decides whether those bytes match; the engine never deletes them. Returns the re-identified ids;
125
+ * the caller starts their loads (`startPreloading(ids)`) once the model is in place.
126
+ */
127
+ refreshResourceIdentities(model) {
73
128
  for (const [id, identity] of this.sourceIdentities) {
74
129
  if (identity && !model.resources.has(id)) {
75
- this.sourceIdentities.set(id, "");
130
+ this.sourceIdentities.set(id, null);
76
131
  this.sourceRevisions.set(id, (this.sourceRevisions.get(id) ?? 0) + 1);
77
132
  this.taskManager.cancelTask(id);
78
133
  }
79
134
  }
135
+ const reidentified = [];
80
136
  for (const [id, resource] of model.resources) {
81
137
  const identity = JSON.stringify([resource.type, resource.uri]);
82
138
  const old = this.sourceIdentities.get(id);
83
139
  this.sourceIdentities.set(id, identity);
84
- if (old !== identity) this.sourceRevisions.set(id, (this.sourceRevisions.get(id) ?? 0) + 1);
85
- if (old !== void 0 && old !== identity) {
86
- this.taskManager.cancelTask(id);
87
- this.invalidateResourceData(id);
88
- resource.state = "pending";
89
- deletes.push(this.cacheManager.resourceCache.deleteResource(id));
90
- deletes.push(this.cacheManager.resourceCache.deleteAudioResource(id));
140
+ if (old === identity) continue;
141
+ if (old === void 0) {
142
+ this.sourceRevisions.set(id, (this.sourceRevisions.get(id) ?? 0) + 1);
143
+ continue;
91
144
  }
145
+ this.taskManager.cancelTask(id);
146
+ this.invalidateResourceData(id);
147
+ if (this.lastLiveIdentities.get(id) !== identity) this.unconfirmedSources.add(id);
148
+ this.markPending(resource);
149
+ reidentified.push(id);
150
+ }
151
+ for (const [id, identity] of this.sourceIdentities) {
152
+ if (identity) this.lastLiveIdentities.set(id, identity);
153
+ }
154
+ return reidentified;
155
+ }
156
+ /** Resets a resource to `pending` and reports the change when it is the live model's resource. */
157
+ markPending(resource) {
158
+ if (this.model?.resources.get(resource.id) === resource) {
159
+ this.updateResourceState(resource.id, "pending");
160
+ return;
92
161
  }
93
- await Promise.all(deletes);
162
+ resource.state = "pending";
163
+ resource.error = void 0;
94
164
  }
95
165
  invalidateResourceData(resourceId, task) {
96
166
  const hadData = this.cacheManager.mp4IndexCache.has(resourceId) || this.cacheManager.audioSampleCache.has(resourceId) || this.blobCache.has(resourceId);
@@ -102,7 +172,7 @@ class ResourceLoader {
102
172
  this.blobCache.delete(resourceId);
103
173
  if (hadData) this.onResourceInvalidated?.(resourceId);
104
174
  }
105
- commitParsedMP4(task, result) {
175
+ commitParsedMP4(task, result, readRange) {
106
176
  this.publishMP4Index(task, result.index);
107
177
  if (result.audioSamples && result.audioMetadata) {
108
178
  this.cacheManager.audioSampleCache.set(
@@ -110,6 +180,13 @@ class ResourceLoader {
110
180
  result.audioSamples,
111
181
  result.audioMetadata
112
182
  );
183
+ } else if (result.audioMetadata && readRange && (result.index.tracks.audio?.samples.length ?? 0) > 0) {
184
+ this.cacheManager.audioSampleCache.setIndexed(
185
+ task.resourceId,
186
+ result.index.tracks.audio.samples,
187
+ result.audioMetadata,
188
+ readRange
189
+ );
113
190
  } else {
114
191
  this.cacheManager.audioSampleCache.delete(task.resourceId);
115
192
  }
@@ -125,7 +202,13 @@ class ResourceLoader {
125
202
  }
126
203
  async invokeEnsureCached(task, options) {
127
204
  this.assertTaskCurrent(task);
128
- const videoParseStream = options?.withVideoParseStream && task.resource.type === "video" ? (stream) => this.parseIndexFromStream(task, stream) : void 0;
205
+ let streamResult = null;
206
+ const videoParseStream = options?.withVideoParseStream && task.resource.type === "video" ? async (stream) => {
207
+ streamResult = await this.parseIndexFromStream(task, stream, void 0, {
208
+ lazyAudio: true,
209
+ deferCommit: true
210
+ });
211
+ } : void 0;
129
212
  await this.ensureCached({
130
213
  signal: task.controller?.signal,
131
214
  resourceId: task.resourceId,
@@ -140,21 +223,41 @@ class ResourceLoader {
140
223
  videoParseStream
141
224
  });
142
225
  this.assertTaskCurrent(task);
226
+ return streamResult;
227
+ }
228
+ createVideoIndexedRange(task) {
229
+ const { resourceId, sourceRevision } = task;
230
+ return async (start, end) => {
231
+ if (this.disposed || sourceRevision !== void 0 && this.sourceRevisions.get(resourceId) !== sourceRevision) {
232
+ throw new DOMException("Resource load superseded", "AbortError");
233
+ }
234
+ return await this.cacheManager.readResourceRange(resourceId, start, end);
235
+ };
236
+ }
237
+ createAudioIndexedRange(resourceId, sourceRevision) {
238
+ return async (start, end) => {
239
+ if (this.disposed || this.sourceRevisions.get(resourceId) !== sourceRevision) {
240
+ throw new DOMException("Resource load superseded", "AbortError");
241
+ }
242
+ return await this.cacheManager.resourceCache.readAudioRange(resourceId, start, end);
243
+ };
143
244
  }
144
245
  throwIfBytesMissing(resourceId) {
145
246
  throw new ResourceNotCachedError(resourceId);
146
247
  }
147
- async setModel(model) {
148
- this.model = model;
149
- await this.refreshResourceIdentities(model);
248
+ async setModel(model, options) {
249
+ this.refreshResourceIdentities(model);
250
+ const timeUs = Math.max(0, options?.startUs ?? 0);
251
+ const active = (clip) => clip.startUs <= timeUs && timeUs < clip.startUs + clip.durationUs;
150
252
  const mainTrack = model.tracks.find(
151
253
  (track) => track.kind === "video" && track.id === (model.mainTrackId || "main")
152
254
  );
153
- if (mainTrack?.clips?.[0] && hasResourceId(mainTrack.clips[0])) {
255
+ const initialClip = mainTrack?.clips?.find(active);
256
+ if (mainTrack && initialClip && hasResourceId(initialClip)) {
154
257
  try {
155
- await this.load(mainTrack.clips[0].resourceId, {
258
+ await this.load(initialClip.resourceId, {
156
259
  isPreload: false,
157
- clipId: mainTrack.clips[0].id,
260
+ clipId: initialClip.id,
158
261
  trackId: mainTrack.id
159
262
  });
160
263
  } catch (error) {
@@ -166,7 +269,7 @@ class ResourceLoader {
166
269
  }
167
270
  const audioTracksSpeech = model.tracks.filter((t) => t.kind === "audio" && t.id === "speech");
168
271
  for (const track of audioTracksSpeech) {
169
- const speechClip = track.clips[0];
272
+ const speechClip = track.clips.find(active);
170
273
  if (!speechClip || !hasResourceId(speechClip)) {
171
274
  continue;
172
275
  }
@@ -188,7 +291,7 @@ class ResourceLoader {
188
291
  }
189
292
  const audioTracksBgm = model.tracks.filter((t) => t.kind === "audio" && t.id === "bgm");
190
293
  for (const track of audioTracksBgm) {
191
- const bgmClip = track.clips[0];
294
+ const bgmClip = track.clips.find(active);
192
295
  if (!bgmClip || !hasResourceId(bgmClip)) {
193
296
  continue;
194
297
  }
@@ -218,7 +321,8 @@ class ResourceLoader {
218
321
  this.startPreloading();
219
322
  }
220
323
  }
221
- startPreloading() {
324
+ /** Preloads the pending resources that clips use, in timeline order; with `only`, just those ids. */
325
+ startPreloading(only) {
222
326
  if (!this.model || !this.isPreloadingEnabled) return;
223
327
  const tracks = this.model.tracks.filter(
224
328
  (track) => track.kind === "video" || track.kind === "audio"
@@ -229,6 +333,7 @@ class ResourceLoader {
229
333
  for (let clipIndex = 0; clipIndex < track.clips.length; clipIndex++) {
230
334
  const clip = track.clips[clipIndex];
231
335
  if (!clip || !hasResourceId(clip)) continue;
336
+ if (only && !only.has(clip.resourceId)) continue;
232
337
  preloadItems.push({
233
338
  track,
234
339
  clip,
@@ -264,10 +369,11 @@ class ResourceLoader {
264
369
  return task;
265
370
  }
266
371
  processQueue() {
372
+ if (this.disposed) return;
267
373
  while (this.taskManager.canProcess) {
268
374
  const task = this.taskManager.getNextTask();
269
375
  if (!task) break;
270
- this.startLoad(task);
376
+ this.track(this.startLoad(task), task.controller?.signal);
271
377
  }
272
378
  }
273
379
  /**
@@ -275,28 +381,32 @@ class ResourceLoader {
275
381
  */
276
382
  async loadVideoResource(task) {
277
383
  const indexReady = this.cacheManager.mp4IndexCache.has(task.resourceId);
278
- const cached = await this.cacheManager.hasResourceInCache(task.resourceId);
384
+ const cached = !this.unconfirmedSources.has(task.resourceId) && await this.cacheManager.hasResourceInCache(task.resourceId);
279
385
  this.assertTaskCurrent(task);
280
386
  if (indexReady && cached) {
281
387
  return;
282
388
  }
283
389
  if (cached) {
284
390
  try {
285
- await this.ensureIndexParsed(task.resourceId);
391
+ await this.ensureIndexParsed(task.resourceId, task.controller?.signal);
286
392
  this.assertTaskCurrent(task);
287
393
  return;
288
394
  } catch (error) {
289
395
  this.assertTaskCurrent(task);
290
- if (error instanceof ResourceCorruptedError || error instanceof EmptyStreamError || error instanceof MP4MoovNotFoundError) {
291
- await this.cacheManager.resourceCache.deleteResource(task.resourceId);
292
- this.assertTaskCurrent(task);
293
- } else {
294
- throw error;
295
- }
396
+ throw error;
296
397
  }
297
398
  }
298
399
  this.invalidateResourceData(task.resourceId, task);
299
- await this.invokeEnsureCached(task, { withVideoParseStream: true });
400
+ const streamResult = await this.invokeEnsureCached(task, { withVideoParseStream: true });
401
+ if (streamResult && !streamResult.audioBeforeMoov) {
402
+ const stillCached = await this.cacheManager.hasResourceInCache(task.resourceId);
403
+ this.assertTaskCurrent(task);
404
+ if (stillCached) {
405
+ this.commitParsedMP4(task, streamResult, this.createVideoIndexedRange(task));
406
+ return;
407
+ }
408
+ this.cacheManager.mp4IndexCache.delete(task.resourceId);
409
+ }
300
410
  if (this.cacheManager.mp4IndexCache.has(task.resourceId)) {
301
411
  const stillCached = await this.cacheManager.hasResourceInCache(task.resourceId);
302
412
  this.assertTaskCurrent(task);
@@ -306,7 +416,7 @@ class ResourceLoader {
306
416
  const bytesReady = await this.cacheManager.hasResourceInCache(task.resourceId);
307
417
  this.assertTaskCurrent(task);
308
418
  if (bytesReady) {
309
- await this.ensureIndexParsed(task.resourceId);
419
+ await this.ensureIndexParsed(task.resourceId, task.controller?.signal);
310
420
  return;
311
421
  }
312
422
  this.throwIfBytesMissing(task.resourceId);
@@ -345,16 +455,62 @@ class ResourceLoader {
345
455
  this.cacheManager.audioSampleCache.setPCM(resourceId, index);
346
456
  return;
347
457
  }
348
- const buffer = await this.cacheManager.resourceCache.readAudioResource(resourceId);
458
+ if (isMp4FamilyContainer(header)) {
459
+ const stream2 = await this.cacheManager.resourceCache.openAudioResourceReadStream(resourceId);
460
+ this.assertTaskCurrent(task);
461
+ const audioReadRange2 = this.createAudioIndexedRange(resourceId, task.sourceRevision);
462
+ const parser = new MP4IndexParser();
463
+ const result = await parser.parseFromStream(stream2, {
464
+ resourceId,
465
+ signal: task.controller?.signal,
466
+ readRange: audioReadRange2,
467
+ lazyAudio: true
468
+ });
469
+ this.commitParsedMP4(task, result, audioReadRange2);
470
+ return;
471
+ }
472
+ const stream = await this.cacheManager.resourceCache.openAudioResourceReadStream(resourceId);
473
+ this.assertTaskCurrent(task);
474
+ const parsed = await MP3FrameParser.parseIndexFromStream(stream, {
475
+ signal: task.controller?.signal
476
+ });
349
477
  this.assertTaskCurrent(task);
350
- await this.parseAudioResourceBytes(resourceId, new Uint8Array(buffer), task);
478
+ if (parsed.looksLikeAdts) {
479
+ throw new UnsupportedAudioContainerError(
480
+ resourceId,
481
+ "an ADTS AAC stream (often a renamed .aac or mislabeled .mp3)"
482
+ );
483
+ }
484
+ if (!parsed.config) {
485
+ throw new UnsupportedAudioContainerError(
486
+ resourceId,
487
+ "not a recognizable MP3 stream (no valid frame chain found)"
488
+ );
489
+ }
490
+ const audioReadRange = this.createAudioIndexedRange(resourceId, task.sourceRevision);
491
+ const audioConfig = {
492
+ codec: "mp3",
493
+ sampleRate: parsed.config.sampleRate,
494
+ numberOfChannels: parsed.config.channels
495
+ };
496
+ this.cacheManager.audioSampleCache.setIndexed(
497
+ resourceId,
498
+ parsed.samples,
499
+ audioConfig,
500
+ audioReadRange,
501
+ {
502
+ mainDataBytes: parsed.mainDataBytes,
503
+ gapless: parsed.gapless ? {
504
+ skipSamples: parsed.gapless.skipSamples,
505
+ trimEndSamples: parsed.gapless.trimEndSamples,
506
+ samplesPerFrame: parsed.gapless.samplesPerFrame
507
+ } : void 0
508
+ }
509
+ );
351
510
  return;
352
511
  } catch (error) {
353
512
  this.assertTaskCurrent(task);
354
- if (!isDOMException(error, "InvalidStateError") && !isDOMException(error, "NotFoundError") && !(error instanceof EmptyStreamError) && !(error instanceof ResourceCorruptedError) && !(error instanceof MP4MoovNotFoundError))
355
- throw error;
356
- console.warn(`[ResourceLoader][audio-opfs] ${resourceId} cached file unusable:`, error);
357
- await this.cacheManager.resourceCache.deleteAudioResource(resourceId);
513
+ throw error;
358
514
  }
359
515
  }
360
516
  this.throwIfBytesMissing(resourceId);
@@ -387,11 +543,11 @@ class ResourceLoader {
387
543
  */
388
544
  async startLoad(task) {
389
545
  this.taskManager.activateTask(task);
546
+ this.loadOwners.set(task.resourceId, task);
390
547
  let loadError;
391
548
  try {
392
549
  this.updateResourceState(task.resourceId, "loading");
393
550
  this.updateLoadStage(task.resourceId, "loading");
394
- task.controller = new AbortController();
395
551
  switch (task.resource.type) {
396
552
  case "image":
397
553
  await this.ensureImageBlob(task);
@@ -408,16 +564,15 @@ class ResourceLoader {
408
564
  break;
409
565
  }
410
566
  this.assertTaskCurrent(task);
567
+ this.unconfirmedSources.delete(task.resourceId);
411
568
  this.updateResourceState(task.resourceId, "ready");
412
569
  this.updateLoadStage(task.resourceId, "ready");
413
570
  } catch (error) {
414
571
  task.error = error;
415
572
  loadError = error;
416
- if (!this.disposed && !task.controller?.signal.aborted && this.model?.getResource(task.resourceId)?.uri === task.resource.uri) {
417
- this.updateResourceState(task.resourceId, "error", toResourceErrorInfo(error));
418
- this.updateLoadStage(task.resourceId, "error", toResourceErrorInfo(error));
419
- }
573
+ this.failLoad(task.resourceId, task.resource.uri, task, error);
420
574
  } finally {
575
+ if (this.loadOwners.get(task.resourceId) === task) this.loadOwners.delete(task.resourceId);
421
576
  this.taskManager.completeTask(task.resourceId, loadError, task);
422
577
  this.processQueue();
423
578
  }
@@ -425,12 +580,12 @@ class ResourceLoader {
425
580
  /**
426
581
  * Ensure MP4 index is parsed for a cached resource
427
582
  */
428
- async ensureIndexParsed(resourceId) {
583
+ async ensureIndexParsed(resourceId, signal) {
429
584
  if (this.cacheManager.mp4IndexCache.has(resourceId)) {
430
585
  return;
431
586
  }
432
587
  while (this.parsingIndexes.has(resourceId)) {
433
- await new Promise((resolve) => setTimeout(resolve, 50));
588
+ await this.awaitOwned(this.parsingIndexes.get(resourceId), signal);
434
589
  }
435
590
  if (this.cacheManager.mp4IndexCache.has(resourceId)) {
436
591
  return;
@@ -439,38 +594,65 @@ class ResourceLoader {
439
594
  if (!resource) throw new Error(`Resource ${resourceId} not found`);
440
595
  const source = { ...resource };
441
596
  const sourceRevision = this.sourceRevisions.get(resourceId);
597
+ const parseOwner = new AbortController();
442
598
  const parseTask = {
443
599
  resourceId,
444
600
  resource: source,
445
601
  sourceRevision,
602
+ controller: parseOwner,
446
603
  bytesLoaded: 0,
447
604
  totalBytes: 0,
448
605
  startTime: Date.now(),
449
606
  isPreload: false
450
607
  };
451
- this.parsingIndexes.add(resourceId);
608
+ let release;
609
+ const settled = new Promise((resolve) => {
610
+ release = resolve;
611
+ });
612
+ const releaseWithOwner = () => {
613
+ parseOwner.abort(signal?.reason);
614
+ if (this.parsingIndexes.get(resourceId) === settled) this.parsingIndexes.delete(resourceId);
615
+ release();
616
+ };
617
+ this.parsingIndexes.set(resourceId, settled);
618
+ signal?.addEventListener("abort", releaseWithOwner, { once: true });
619
+ if (signal?.aborted) releaseWithOwner();
452
620
  try {
453
621
  const cached = await this.cacheManager.hasResourceInCache(resourceId);
454
622
  if (!cached) {
455
623
  throw new ResourceCorruptedError(resourceId, "File not found in OPFS or is empty");
456
624
  }
457
625
  const stream = await this.createOPFSReadStream(resourceId);
458
- await this.parseIndexFromStream(parseTask, stream);
626
+ const parseRange = async (start, end) => {
627
+ this.assertTaskCurrent(parseTask);
628
+ const range = await this.cacheManager.readResourceRange(resourceId, start, end);
629
+ this.assertTaskCurrent(parseTask);
630
+ return range;
631
+ };
632
+ const indexedRange = async (start, end) => {
633
+ if (this.disposed || this.sourceRevisions.get(resourceId) !== sourceRevision) {
634
+ throw new DOMException("Resource load superseded", "AbortError");
635
+ }
636
+ return await this.cacheManager.readResourceRange(resourceId, start, end);
637
+ };
638
+ await this.parseIndexFromStream(parseTask, stream, parseRange, {
639
+ lazyAudio: true,
640
+ indexedReadRange: indexedRange
641
+ });
459
642
  } catch (error) {
460
643
  this.assertTaskCurrent(parseTask);
461
644
  if (error instanceof EmptyStreamError || error instanceof ResourceCorruptedError || error instanceof MP4MoovNotFoundError) {
462
- console.warn(`[ResourceLoader] Corrupted cache detected for ${resourceId}, clearing...`);
463
- try {
464
- await this.cacheManager.resourceCache.deleteResource(resourceId);
465
- this.assertTaskCurrent(parseTask);
466
- this.cacheManager.mp4IndexCache.delete(resourceId);
467
- } catch (deleteError) {
468
- console.error(`[ResourceLoader] Failed to clear corrupted cache:`, deleteError);
469
- }
645
+ console.warn(
646
+ `[ResourceLoader] Corrupted cache detected for ${resourceId}; the parent-owned bytes are kept`
647
+ );
648
+ this.assertTaskCurrent(parseTask);
649
+ this.cacheManager.mp4IndexCache.delete(resourceId);
470
650
  }
471
651
  throw error;
472
652
  } finally {
473
- this.parsingIndexes.delete(resourceId);
653
+ signal?.removeEventListener("abort", releaseWithOwner);
654
+ if (this.parsingIndexes.get(resourceId) === settled) this.parsingIndexes.delete(resourceId);
655
+ release();
474
656
  }
475
657
  }
476
658
  /**
@@ -488,82 +670,20 @@ class ResourceLoader {
488
670
  }
489
671
  }
490
672
  /**
491
- * Parse a cached audio resource by container: M4A/MP4-family containers go
492
- * through the MP4 moov parser (correct codec + description, e.g. AAC);
493
- * bare MP3 streams go through the MP3 frame parser. Feeding M4A/AAC bytes
494
- * to the MP3 parser produced malformed chunks and killed playback with
495
- * "mpa: invalid packet length".
496
- */
497
- async parseAudioResourceBytes(resourceId, bytes, task) {
498
- if (isMp4FamilyContainer(bytes)) {
499
- const stream = new ReadableStream({
500
- start(controller) {
501
- controller.enqueue(bytes);
502
- controller.close();
503
- }
504
- });
505
- const parser = new MP4IndexParser();
506
- const result = await parser.parseFromStream(stream, { resourceId });
507
- this.commitParsedMP4(task, result);
508
- return;
509
- }
510
- if (MP3FrameParser.looksLikeAdts(bytes)) {
511
- throw new UnsupportedAudioContainerError(
512
- resourceId,
513
- "an ADTS AAC stream (often a renamed .aac or mislabeled .mp3)"
514
- );
515
- }
516
- this.parseAudioBuffer(resourceId, bytes);
517
- }
518
- /**
519
- * Parse raw MP3 bytes into EncodedAudioChunks and store in AudioSampleCache.
520
- */
521
- parseAudioBuffer(resourceId, uint8Array) {
522
- const parser = new MP3FrameParser();
523
- const { frames, config } = parser.push(uint8Array);
524
- const remainingFrames = parser.flush();
525
- const allFrames = [...frames, ...remainingFrames];
526
- if (!config) {
527
- throw new UnsupportedAudioContainerError(
528
- resourceId,
529
- "not a recognizable MP3 stream (no valid frame chain found)"
530
- );
531
- }
532
- const audioChunks = allFrames.map(
533
- (frame) => new EncodedAudioChunk({
534
- type: "key",
535
- timestamp: frame.timestampUs,
536
- duration: frame.durationUs,
537
- data: frame.data
538
- })
539
- );
540
- const audioConfig = {
541
- codec: "mp3",
542
- sampleRate: config.sampleRate,
543
- numberOfChannels: config.channels
544
- };
545
- const gapless = parser.getGaplessInfo();
546
- this.cacheManager.audioSampleCache.set(
547
- resourceId,
548
- audioChunks,
549
- audioConfig,
550
- gapless ? {
551
- skipSamples: gapless.skipSamples,
552
- trimEndSamples: gapless.trimEndSamples,
553
- samplesPerFrame: gapless.samplesPerFrame
554
- } : void 0
555
- );
556
- }
557
- /**
558
- * Parse moov from stream and cache index + audio samples + decode first frame
673
+ * Parse moov from stream and cache index + audio samples + decode first frame.
674
+ * When `deferCommit` is true (host download stream), returns the parse result without committing
675
+ * `audioSampleCache` prematurely before OPFS bytes are fully persisted.
559
676
  */
560
- async parseIndexFromStream(task, stream) {
677
+ async parseIndexFromStream(task, stream, readRange, options) {
561
678
  const { resourceId, clipId } = task;
562
679
  try {
563
680
  const parser = new MP4IndexParser();
564
681
  const shouldExtractFirstGOP = clipId ? this.shouldExtractCover(clipId) : false;
565
682
  const result = await parser.parseFromStream(stream, {
566
683
  resourceId,
684
+ signal: task.controller?.signal,
685
+ readRange,
686
+ lazyAudio: options?.lazyAudio,
567
687
  onFirstFrameReady: shouldExtractFirstGOP ? (index, chunks) => {
568
688
  this.publishMP4Index(task, index);
569
689
  this.eventBus?.emit(MeframeEvent.ResourceFirstFrameReady, {
@@ -574,7 +694,10 @@ class ResourceLoader {
574
694
  });
575
695
  } : void 0
576
696
  });
577
- this.commitParsedMP4(task, result);
697
+ if (!options?.deferCommit && !result.audioBeforeMoov) {
698
+ this.commitParsedMP4(task, result, options?.indexedReadRange ?? readRange);
699
+ }
700
+ return result;
578
701
  } catch (error) {
579
702
  if (error instanceof NotMP4Error) {
580
703
  console.error(
@@ -590,7 +713,15 @@ class ResourceLoader {
590
713
  throw error;
591
714
  }
592
715
  }
593
- async loadImage(resource) {
716
+ loadImage(resource, signal) {
717
+ const owner = new AbortController();
718
+ return this.track(
719
+ this.loadImageInternal(resource, signal, owner),
720
+ owner.signal,
721
+ (image) => image.close()
722
+ );
723
+ }
724
+ async loadImageInternal(resource, signal, owner) {
594
725
  const existingBlob = this.blobCache.get(resource.id);
595
726
  if (existingBlob) {
596
727
  const imageBitmap = await createImageBitmapFromBlob(existingBlob);
@@ -599,12 +730,18 @@ class ResourceLoader {
599
730
  const task = {
600
731
  resourceId: resource.id,
601
732
  resource,
733
+ sourceRevision: this.sourceRevisions.get(resource.id),
602
734
  bytesLoaded: 0,
603
735
  totalBytes: 0,
604
736
  startTime: Date.now(),
605
737
  isPreload: false,
606
- controller: new AbortController()
738
+ controller: owner
607
739
  };
740
+ const abortWithCaller = () => owner.abort(signal?.reason);
741
+ this.imageControllers.add(owner);
742
+ this.loadOwners.set(resource.id, task);
743
+ if (signal?.aborted) abortWithCaller();
744
+ else signal?.addEventListener("abort", abortWithCaller, { once: true });
608
745
  let loadError;
609
746
  try {
610
747
  this.updateResourceState(resource.id, "loading");
@@ -612,13 +749,72 @@ class ResourceLoader {
612
749
  const blob = this.blobCache.get(resource.id);
613
750
  if (!blob) throw new Error(`Failed to load image ${resource.id}`);
614
751
  const imageBitmap = await createImageBitmapFromBlob(blob);
752
+ this.unconfirmedSources.delete(resource.id);
615
753
  this.updateResourceState(resource.id, "ready");
616
754
  return imageBitmap;
617
755
  } catch (error) {
618
756
  loadError = error;
619
- this.updateResourceState(resource.id, "error", toResourceErrorInfo(error));
757
+ this.failLoad(resource.id, resource.uri, task, loadError);
620
758
  throw loadError;
759
+ } finally {
760
+ if (this.loadOwners.get(resource.id) === task) this.loadOwners.delete(resource.id);
761
+ this.imageControllers.delete(owner);
762
+ signal?.removeEventListener("abort", abortWithCaller);
763
+ }
764
+ }
765
+ failLoad(resourceId, resourceUri, task, error) {
766
+ if (this.model?.getResource(resourceId)?.uri !== resourceUri) return;
767
+ if (this.loadOwners.get(resourceId) !== task) return;
768
+ if (task.sourceRevision !== void 0 && task.sourceRevision !== this.sourceRevisions.get(resourceId))
769
+ return;
770
+ if (this.disposed || task.controller?.signal.aborted) {
771
+ this.updateResourceState(resourceId, "pending");
772
+ return;
773
+ }
774
+ this.markFailed(resourceId, error);
775
+ }
776
+ /**
777
+ * Puts a resource whose bytes could not be read or parsed into `error`. Its index and parsed data are dropped, so nothing reads
778
+ * through them, and its next load (a consumer's retry or `reloadResource`) asks the host through ensureCached before using
779
+ * cached bytes again. The bytes themselves are the host's and are never deleted.
780
+ */
781
+ markFailed(resourceId, error) {
782
+ this.invalidateResourceData(resourceId);
783
+ this.unconfirmedSources.add(resourceId);
784
+ const info = toResourceErrorInfo(error);
785
+ this.updateResourceState(resourceId, "error", info);
786
+ markReportedToHost(error);
787
+ this.updateLoadStage(resourceId, "error", info);
788
+ }
789
+ /**
790
+ * Attributes a failed read of a resource's bytes outside a load (e.g. a range read while decoding) to that resource.
791
+ * `isCurrent` says whether the reader still works on the resource's current source; a failure for an older source, a
792
+ * cancellation, or a failure while a load of the resource is running (that load decides the state) changes nothing.
793
+ * Returns true when the resource was put into `error`; the caller still rethrows the error.
794
+ */
795
+ reportByteFailure(resourceId, error, isCurrent) {
796
+ if (this.disposed || isAbortLike(error) || !isCurrent()) return false;
797
+ if (!this.model?.getResource(resourceId)) return false;
798
+ if (this.taskManager.hasActiveTask(resourceId) || this.loadOwners.has(resourceId)) return false;
799
+ this.markFailed(resourceId, error);
800
+ return true;
801
+ }
802
+ /**
803
+ * Loads a resource again, typically after the host repaired its bytes in response to `resource:state` = `error`. The
804
+ * in-memory index and data are dropped and the host's ensureCached is called before cached bytes are used. A load already in
805
+ * flight for the resource is awaited instead of being replaced. Rejects with the load's error when it fails again.
806
+ */
807
+ async reloadResource(resourceId, options) {
808
+ if (this.disposed || options?.signal?.aborted)
809
+ throw new DOMException("Resource load aborted", "AbortError");
810
+ const resource = this.model?.getResource(resourceId);
811
+ if (!resource) throw new Error(`Resource ${resourceId} not found`);
812
+ if (!this.taskManager.hasActiveTask(resourceId)) {
813
+ this.invalidateResourceData(resourceId);
814
+ this.unconfirmedSources.add(resourceId);
815
+ this.updateResourceState(resourceId, "pending");
621
816
  }
817
+ await this.load(resourceId, { isPreload: false, signal: options?.signal });
622
818
  }
623
819
  updateResourceState(resourceId, state, error) {
624
820
  const resource = this.model?.resources.get(resourceId);
@@ -637,7 +833,6 @@ class ResourceLoader {
637
833
  newState: state
638
834
  });
639
835
  }
640
- this.onStateChange?.(resourceId, state);
641
836
  }
642
837
  updateLoadStage(resourceId, state, error) {
643
838
  const resource = this.model?.resources.get(resourceId);
@@ -718,7 +913,10 @@ class ResourceLoader {
718
913
  const hasIndex = this.cacheManager.mp4IndexCache.has(resourceId);
719
914
  if (hasIndex) {
720
915
  const sourceRevision = this.sourceRevisions.get(resourceId);
721
- const cached = await this.cacheManager.hasResourceInCache(resourceId);
916
+ const cached = await this.awaitOwned(
917
+ this.cacheManager.hasResourceInCache(resourceId),
918
+ options?.signal
919
+ );
722
920
  if (this.disposed || options?.signal?.aborted || sourceRevision !== this.sourceRevisions.get(resourceId))
723
921
  throw new DOMException("Resource load superseded", "AbortError");
724
922
  if (cached) {
@@ -728,7 +926,10 @@ class ResourceLoader {
728
926
  this.updateResourceState(resourceId, "pending");
729
927
  } else if (resource.type === "audio") {
730
928
  const sourceRevision = this.sourceRevisions.get(resourceId);
731
- const cached = await this.cacheManager.resourceCache.hasAudioResource(resourceId);
929
+ const cached = await this.awaitOwned(
930
+ this.cacheManager.resourceCache.hasAudioResource(resourceId),
931
+ options?.signal
932
+ );
732
933
  if (this.disposed || options?.signal?.aborted || sourceRevision !== this.sourceRevisions.get(resourceId))
733
934
  throw new DOMException("Resource load superseded", "AbortError");
734
935
  if (cached && this.cacheManager.audioSampleCache.has(resourceId)) return;
@@ -812,14 +1013,36 @@ class ResourceLoader {
812
1013
  get taskQueue() {
813
1014
  return this.taskManager.taskQueue;
814
1015
  }
815
- dispose() {
1016
+ /** Aborts the image downloads that run outside TaskManager, so drain and dispose do not wait on a download nobody cancels. */
1017
+ abortImageLoads() {
1018
+ for (const controller of this.imageControllers) {
1019
+ controller.abort(new DOMException("Resource loader disposed", "AbortError"));
1020
+ }
1021
+ }
1022
+ async drain() {
1023
+ this.taskManager.clear();
1024
+ this.abortImageLoads();
1025
+ this.abortReads();
1026
+ this.parsingIndexes.clear();
1027
+ await Promise.allSettled([...this.running]);
1028
+ }
1029
+ async dispose() {
1030
+ if (this.disposed) return this.disposePromise;
816
1031
  this.disposed = true;
817
1032
  this.taskManager.clear();
1033
+ this.abortImageLoads();
1034
+ this.abortReads();
818
1035
  this.consumers.clear();
819
- this.blobCache.clear();
820
- this.sourceIdentities.clear();
821
- this.sourceRevisions.clear();
822
- this.model = void 0;
1036
+ this.disposePromise = (async () => {
1037
+ await Promise.allSettled([...this.running]);
1038
+ this.blobCache.clear();
1039
+ this.parsingIndexes.clear();
1040
+ this.sourceIdentities.clear();
1041
+ this.sourceRevisions.clear();
1042
+ this.lastLiveIdentities.clear();
1043
+ this.unconfirmedSources.clear();
1044
+ })();
1045
+ return this.disposePromise;
823
1046
  }
824
1047
  /**
825
1048
  * Check if a clip needs cover extraction (first GOP decode)
@@ -836,6 +1059,9 @@ function isMp4FamilyContainer(bytes) {
836
1059
  const tag = String.fromCharCode(bytes[4] ?? 0, bytes[5] ?? 0, bytes[6] ?? 0, bytes[7] ?? 0);
837
1060
  return tag === "ftyp";
838
1061
  }
1062
+ function isAbortLike(error) {
1063
+ return error?.name === "AbortError" || error instanceof ResourceSupersededError;
1064
+ }
839
1065
  export {
840
1066
  ResourceLoader
841
1067
  };