@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
@@ -1,8 +1,9 @@
1
- import { decodePreviewChunks } from "../stages/decode/preview-video-decoder.js";
1
+ import { PersistentPreviewVideoDecoder } from "../stages/decode/preview-video-decoder.js";
2
2
  import { videoClipPlaybackRate, isVideoClip } from "../model/types.js";
3
- import { binarySearchRange, binarySearchOverlapping } from "../utils/binary-search.js";
3
+ import { binarySearchFirst, binarySearchRange, binarySearchOverlapping } from "../utils/binary-search.js";
4
4
  import { decodeChunksWithoutFlush, decodeChunksForScrub } from "../stages/decode/video-decoder.js";
5
- import { ResourceSupersededError, ResourceCorruptedError, isDOMException } from "../utils/errors.js";
5
+ import { ResourceSupersededError } from "../utils/errors.js";
6
+ import { untilAborted } from "../utils/until-aborted.js";
6
7
  class VideoWindowDecodeSession {
7
8
  /**
8
9
  * Static method to decode and cache first frame from extracted GOP chunks
@@ -53,11 +54,33 @@ class VideoWindowDecodeSession {
53
54
  targetTimeUs;
54
55
  isDisposed = false;
55
56
  cancelled = false;
57
+ tasks = /* @__PURE__ */ new Set();
58
+ abortController = new AbortController();
59
+ disposePromise = null;
56
60
  sourceIndex;
57
61
  exportRetryReader;
58
62
  get aborted() {
59
63
  return this.cancelled || this.mp4IndexCache.get(this.resourceId) !== this.sourceIndex;
60
64
  }
65
+ /** Settled work leaves `tasks`; dispose waits for the work, and an aborted session ends its host reads. */
66
+ track(promise) {
67
+ const work = promise.then(
68
+ () => {
69
+ },
70
+ () => {
71
+ }
72
+ );
73
+ this.tasks.add(work);
74
+ void work.then(() => this.tasks.delete(work));
75
+ const caller = untilAborted(promise, this.abortController.signal);
76
+ caller.then(
77
+ () => {
78
+ },
79
+ () => {
80
+ }
81
+ );
82
+ return caller;
83
+ }
61
84
  assertResourceCurrent() {
62
85
  if (this.cancelled) throw new DOMException("Video decode cancelled", "AbortError");
63
86
  if (this.mp4IndexCache.get(this.resourceId) !== this.sourceIndex) {
@@ -66,6 +89,17 @@ class VideoWindowDecodeSession {
66
89
  }
67
90
  decodedFrames = [];
68
91
  loggedDecodedStreamDimensions = false;
92
+ // Persistent preview decode state reused across consecutive forward preheat windows.
93
+ previewDecoder = null;
94
+ previewStreamIndex = null;
95
+ previewTargetEndUs = 0;
96
+ previewNextSampleIndex = -1;
97
+ previewGopCursor = -1;
98
+ previewStreamStartUs = 0;
99
+ previewLastConsumedEndUs = -Infinity;
100
+ previewAcceleration;
101
+ previewChunkDurations = /* @__PURE__ */ new Map();
102
+ cachedGop = null;
69
103
  constructor(config) {
70
104
  this.clipId = config.clipId;
71
105
  this.resourceId = config.resourceId;
@@ -89,7 +123,10 @@ class VideoWindowDecodeSession {
89
123
  /**
90
124
  * Decode a window range, write raw frames to L1 cache
91
125
  */
92
- async decodeWindow(startUs, endUs) {
126
+ decodeWindow(startUs, endUs) {
127
+ return this.track(this.decodeWindowInternal(startUs, endUs));
128
+ }
129
+ async decodeWindowInternal(startUs, endUs) {
93
130
  if (this.isDisposed) {
94
131
  throw new Error("Session already disposed");
95
132
  }
@@ -116,62 +153,182 @@ class VideoWindowDecodeSession {
116
153
  }
117
154
  await this.handleVideoResource(startUs, endUs);
118
155
  }
156
+ /** Extend an active forward preview decode window in-place without restarting the decoder. */
157
+ extendPreviewWindow(endUs) {
158
+ if (endUs > this.previewTargetEndUs) {
159
+ this.previewTargetEndUs = endUs;
160
+ }
161
+ }
162
+ resetPreviewStream() {
163
+ this.previewDecoder?.close();
164
+ this.previewDecoder = null;
165
+ this.previewStreamIndex = null;
166
+ this.previewNextSampleIndex = -1;
167
+ this.previewGopCursor = -1;
168
+ this.previewStreamStartUs = 0;
169
+ this.previewLastConsumedEndUs = -Infinity;
170
+ this.previewChunkDurations.clear();
171
+ this.cachedGop = null;
172
+ }
119
173
  /** Preview-only streaming path. Export retains its independent decode pipeline. */
120
- async decodePreviewWindow(startUs, endUs, onFrame) {
174
+ decodePreviewWindow(startUs, endUs, onFrame) {
175
+ return this.track(this.decodePreviewWindowInternal(startUs, endUs, onFrame));
176
+ }
177
+ async decodePreviewWindowInternal(startUs, endUs, onFrame) {
121
178
  const resource = this.compositionModel.getResource(this.resourceId);
122
179
  if (resource?.type === "image") {
123
180
  await this.handleImageResource(resource, startUs, endUs);
124
181
  onFrame();
125
182
  return;
126
183
  }
184
+ if (this.aborted || this.cacheManager.isExporting) {
185
+ this.resetPreviewStream();
186
+ return;
187
+ }
127
188
  const index = this.mp4IndexCache.get(this.resourceId);
128
189
  const video = index?.tracks.video;
129
190
  if (!index || !video) throw new Error(`No video index for ${this.resourceId}`);
130
- const window = this.calculateGOPRangesForWindow(index, startUs, endUs);
131
- for (const gop of window.gops) {
132
- if (this.aborted) return;
133
- const first = gop.keyframeSampleIndex;
134
- const last = Math.min(video.samples.length, first + gop.sampleCount);
135
- let byteStart = Infinity, byteEnd = 0;
136
- for (let i = first; i < last; i++) {
137
- const sample = video.samples[i];
138
- byteStart = Math.min(byteStart, sample.byteOffset);
139
- byteEnd = Math.max(byteEnd, sample.byteOffset + sample.byteLength);
191
+ if (video.gopIndex.length === 0 || video.samples.length === 0) return;
192
+ this.previewTargetEndUs = endUs;
193
+ const missingStartUs = this.cacheManager.videoL1Cache.firstUncovered(
194
+ this.clipId,
195
+ startUs,
196
+ this.previewTargetEndUs
197
+ );
198
+ if (missingStartUs >= this.previewTargetEndUs - 1) return;
199
+ if (this.previewStreamIndex === index && this.previewDecoder?.isExhausted && this.previewLastConsumedEndUs > -Infinity && missingStartUs >= this.previewLastConsumedEndUs - 1) {
200
+ return;
201
+ }
202
+ const firstGopAfter = binarySearchFirst(
203
+ video.gopIndex,
204
+ (gop) => gop.startTimeUs > missingStartUs
205
+ );
206
+ const targetGopIdx = Math.max(0, firstGopAfter - 1);
207
+ const targetGop = video.gopIndex[targetGopIdx];
208
+ const runDecode = async () => {
209
+ const canReuse = this.previewDecoder !== null && this.previewDecoder.canContinue && this.previewStreamIndex === index && this.previewDecoder.earliestPendingPtsUs < Infinity && this.previewNextSampleIndex >= 0 && this.previewNextSampleIndex <= video.samples.length && targetGop.keyframeSampleIndex <= this.previewNextSampleIndex && missingStartUs >= (this.previewLastConsumedEndUs > -Infinity ? Math.min(this.previewDecoder.earliestPendingPtsUs, this.previewLastConsumedEndUs) : this.previewStreamStartUs) - 1;
210
+ if (!canReuse) {
211
+ this.resetPreviewStream();
212
+ this.previewStreamIndex = index;
213
+ this.previewGopCursor = targetGopIdx;
214
+ this.previewNextSampleIndex = targetGop.keyframeSampleIndex;
215
+ this.previewStreamStartUs = targetGopIdx === 0 ? 0 : targetGop.startTimeUs;
216
+ this.previewLastConsumedEndUs = -Infinity;
217
+ this.previewDecoder = new PersistentPreviewVideoDecoder(
218
+ {
219
+ codec: video.codec,
220
+ width: video.width,
221
+ height: video.height,
222
+ description: video.description
223
+ },
224
+ this.previewAcceleration
225
+ );
140
226
  }
141
- if (byteEnd <= byteStart) continue;
142
- const data = await this.readResourceRangeWithRecovery(byteStart, byteEnd);
143
- if (this.aborted) return;
144
- const chunks = this.buildEncodedChunksFromSamples(
145
- data,
146
- byteStart,
147
- video.samples,
148
- first,
149
- last
150
- );
151
- await decodePreviewChunks(
152
- chunks,
153
- {
154
- codec: video.codec,
155
- width: video.width,
156
- height: video.height,
157
- description: video.description
158
- },
159
- (frame) => {
160
- if (frame.timestamp >= endUs) {
161
- frame.close();
162
- return true;
227
+ const decoder = this.previewDecoder;
228
+ const nextChunk = async () => {
229
+ while (this.previewNextSampleIndex < video.samples.length) {
230
+ if (this.aborted || this.cacheManager.isExporting) return null;
231
+ const idx = this.previewNextSampleIndex;
232
+ const sample = video.samples[idx];
233
+ if (!sample || sample.byteLength <= 0) {
234
+ this.previewNextSampleIndex = idx + 1;
235
+ continue;
163
236
  }
164
- const duration = frame.duration ?? Math.round(1e6 / this.fps);
165
- if (frame.timestamp + duration > startUs && frame.timestamp < endUs) {
166
- const cached = this.cacheManager.videoL1Cache.getCovering(this.clipId, frame.timestamp);
167
- if (cached?.timestampUs === frame.timestamp) frame.close();
168
- else this.cacheFrame(frame);
169
- onFrame();
170
- } else frame.close();
171
- return false;
172
- },
173
- () => this.aborted || this.cacheManager.isExporting
174
- );
237
+ while (this.previewGopCursor < video.gopIndex.length && idx >= video.gopIndex[this.previewGopCursor].keyframeSampleIndex + video.gopIndex[this.previewGopCursor].sampleCount) {
238
+ this.previewGopCursor++;
239
+ }
240
+ const gopIdx = this.previewGopCursor;
241
+ let gopBuffer = this.cachedGop?.gopIdx === gopIdx ? this.cachedGop : null;
242
+ if (!gopBuffer) {
243
+ let byteStart = sample.byteOffset;
244
+ let byteEnd = sample.byteOffset + sample.byteLength;
245
+ const gop = video.gopIndex[gopIdx];
246
+ if (gop) {
247
+ const first = gop.keyframeSampleIndex;
248
+ const last = Math.min(video.samples.length, first + gop.sampleCount);
249
+ byteStart = Infinity;
250
+ byteEnd = 0;
251
+ for (let i = first; i < last; i++) {
252
+ const s = video.samples[i];
253
+ byteStart = Math.min(byteStart, s.byteOffset);
254
+ byteEnd = Math.max(byteEnd, s.byteOffset + s.byteLength);
255
+ }
256
+ }
257
+ if (!Number.isFinite(byteStart) || byteEnd <= byteStart) {
258
+ this.previewNextSampleIndex = idx + 1;
259
+ continue;
260
+ }
261
+ const raw = await this.readCurrentResourceRange(byteStart, byteEnd);
262
+ if (this.aborted || this.cacheManager.isExporting) return null;
263
+ gopBuffer = { gopIdx, byteStart, data: new Uint8Array(raw) };
264
+ this.cachedGop = gopBuffer;
265
+ }
266
+ this.previewNextSampleIndex = idx + 1;
267
+ const rel = sample.byteOffset - gopBuffer.byteStart;
268
+ if (rel < 0 || rel + sample.byteLength > gopBuffer.data.byteLength) continue;
269
+ const timestamp = Math.round(sample.timestamp);
270
+ const duration = Math.max(1, Math.ceil(sample.duration));
271
+ this.previewChunkDurations.set(timestamp, duration);
272
+ return new EncodedVideoChunk({
273
+ type: sample.isKeyframe ? "key" : "delta",
274
+ timestamp,
275
+ duration,
276
+ data: gopBuffer.data.subarray(rel, rel + sample.byteLength)
277
+ });
278
+ }
279
+ return null;
280
+ };
281
+ const shouldAbort = () => this.aborted || this.cacheManager.isExporting;
282
+ while (!shouldAbort()) {
283
+ const result = await decoder.decodeUntil(
284
+ nextChunk,
285
+ (frame) => {
286
+ if (frame.timestamp >= this.previewTargetEndUs) {
287
+ return "hold";
288
+ }
289
+ const chunkDuration = this.previewChunkDurations.get(frame.timestamp);
290
+ if (chunkDuration !== void 0) this.previewChunkDurations.delete(frame.timestamp);
291
+ const duration = frame.duration !== null && frame.duration > 0 ? frame.duration : chunkDuration ?? Math.round(1e6 / this.fps);
292
+ this.previewLastConsumedEndUs = Math.max(
293
+ this.previewLastConsumedEndUs,
294
+ frame.timestamp + duration
295
+ );
296
+ if (frame.timestamp + duration + 1 > missingStartUs && frame.timestamp < this.previewTargetEndUs) {
297
+ const cached = this.cacheManager.videoL1Cache.getCovering(
298
+ this.clipId,
299
+ frame.timestamp
300
+ );
301
+ if (cached?.timestampUs === frame.timestamp && cached.durationUs >= duration) {
302
+ frame.close();
303
+ } else {
304
+ this.cacheFrame(frame, 0, duration);
305
+ }
306
+ onFrame();
307
+ } else {
308
+ frame.close();
309
+ }
310
+ return "consumed";
311
+ },
312
+ shouldAbort
313
+ );
314
+ if (!result.reachedTarget || !decoder.canContinue) break;
315
+ if (decoder.earliestPendingPtsUs >= this.previewTargetEndUs) break;
316
+ }
317
+ if (shouldAbort()) {
318
+ this.resetPreviewStream();
319
+ }
320
+ };
321
+ try {
322
+ await runDecode();
323
+ } catch (error) {
324
+ const usedSoftware = this.previewDecoder?.hardwareAcceleration === "prefer-software";
325
+ this.resetPreviewStream();
326
+ if (!this.aborted && !this.cacheManager.isExporting && !usedSoftware && error instanceof Error && error.message === "Decoding error.") {
327
+ this.previewAcceleration = "prefer-software";
328
+ await runDecode();
329
+ } else if (!this.aborted) {
330
+ throw error;
331
+ }
175
332
  }
176
333
  }
177
334
  /**
@@ -179,7 +336,10 @@ class VideoWindowDecodeSession {
179
336
  * Decode only the minimum frames needed to present a true frame near targetTimeUs.
180
337
  * This avoids the heavy 3s window decode used for playback preheating.
181
338
  */
182
- async decodeScrub(targetTimeUs) {
339
+ decodeScrub(targetTimeUs) {
340
+ return this.track(this.decodeScrubInternal(targetTimeUs));
341
+ }
342
+ async decodeScrubInternal(targetTimeUs) {
183
343
  if (this.isDisposed) {
184
344
  throw new Error("Session already disposed");
185
345
  }
@@ -198,17 +358,26 @@ class VideoWindowDecodeSession {
198
358
  * Handle image resource by creating a VideoFrame from ImageBitmap
199
359
  */
200
360
  async handleImageResource(resource, startUs, endUs) {
201
- const image = await this.resourceLoader.loadImage(resource);
361
+ const image = await this.resourceLoader.loadImage(resource, this.abortController.signal);
202
362
  if (!image) return;
363
+ if (this.aborted) {
364
+ image.close();
365
+ return;
366
+ }
203
367
  const clip = this.compositionModel.findClip(this.clipId);
204
368
  if (clip) {
205
369
  startUs = clip.trimStartUs ?? 0;
206
370
  endUs = startUs + clip.durationUs * videoClipPlaybackRate(clip);
207
371
  }
208
- const frame = new VideoFrame(image, {
209
- timestamp: startUs,
210
- duration: endUs - startUs
211
- });
372
+ let frame;
373
+ try {
374
+ frame = new VideoFrame(image, {
375
+ timestamp: startUs,
376
+ duration: endUs - startUs
377
+ });
378
+ } finally {
379
+ image.close();
380
+ }
212
381
  this.cacheFrame(frame);
213
382
  }
214
383
  /**
@@ -224,10 +393,7 @@ class VideoWindowDecodeSession {
224
393
  console.warn("[VideoWindowDecodeSession] no GOPs found for window");
225
394
  return;
226
395
  }
227
- const gopData = await this.readResourceRangeWithRecovery(
228
- gopWindow.byteStart,
229
- gopWindow.byteEnd
230
- );
396
+ const gopData = await this.readCurrentResourceRange(gopWindow.byteStart, gopWindow.byteEnd);
231
397
  if (this.aborted) {
232
398
  return;
233
399
  }
@@ -270,7 +436,7 @@ class VideoWindowDecodeSession {
270
436
  byteEnd = Math.max(byteEnd, s.byteOffset + s.byteLength);
271
437
  }
272
438
  if (!Number.isFinite(byteStart) || byteEnd <= byteStart) return;
273
- const gopData = await this.readResourceRangeWithRecovery(byteStart, byteEnd);
439
+ const gopData = await this.readCurrentResourceRange(byteStart, byteEnd);
274
440
  if (this.aborted) return;
275
441
  const chunks = this.buildEncodedChunksFromSamples(
276
442
  gopData,
@@ -304,7 +470,8 @@ class VideoWindowDecodeSession {
304
470
  for (const frame of [before, after]) {
305
471
  if (!frame) continue;
306
472
  try {
307
- this.cacheFrame(frame);
473
+ const chunk = chunks.find(({ timestamp }) => timestamp === frame.timestamp);
474
+ this.cacheFrame(frame, 0, chunk?.duration ?? void 0);
308
475
  } catch {
309
476
  frame.close();
310
477
  }
@@ -320,12 +487,12 @@ class VideoWindowDecodeSession {
320
487
  if (relativeOffset < 0 || relativeOffset + sample.byteLength > data.byteLength) {
321
488
  continue;
322
489
  }
323
- const sampleData = dataView.slice(relativeOffset, relativeOffset + sample.byteLength);
490
+ const sampleData = dataView.subarray(relativeOffset, relativeOffset + sample.byteLength);
324
491
  chunks.push(
325
492
  new EncodedVideoChunk({
326
493
  type: sample.isKeyframe ? "key" : "delta",
327
- timestamp: sample.timestamp,
328
- duration: sample.duration,
494
+ timestamp: Math.round(sample.timestamp),
495
+ duration: Math.max(1, Math.ceil(sample.duration)),
329
496
  data: sampleData
330
497
  })
331
498
  );
@@ -430,19 +597,19 @@ class VideoWindowDecodeSession {
430
597
  height: videoTrack.height,
431
598
  description: videoTrack.description
432
599
  },
433
- timeoutMs ? { timeoutMs } : void 0
600
+ { ...timeoutMs ? { timeoutMs } : {}, signal: this.abortController.signal }
434
601
  );
435
602
  this.decodedFrames = result.frames;
436
603
  }
437
604
  /**
438
605
  * Cache a single frame to L1 with proper timestamp calculations
439
606
  */
440
- cacheFrame(frame, globalTimeOffset = 0) {
607
+ cacheFrame(frame, globalTimeOffset = 0, durationOverride) {
441
608
  if (this.aborted) {
442
609
  frame.close();
443
610
  return;
444
611
  }
445
- const frameDuration = frame.duration ?? Math.round(1e6 / this.fps);
612
+ const frameDuration = durationOverride ?? (frame.duration !== null && frame.duration > 0 ? frame.duration : Math.round(1e6 / this.fps));
446
613
  const clip = this.compositionModel.findClip(this.clipId);
447
614
  let frameGlobalTime;
448
615
  if (clip && isVideoClip(clip)) {
@@ -498,157 +665,218 @@ class VideoWindowDecodeSession {
498
665
  const videoTrack = index.tracks.video;
499
666
  const gopWindow = this.calculateGOPRangesForWindow(index, startUs, endUs);
500
667
  let resumeUs = startUs;
501
- return new ReadableStream({
502
- start: async (controller) => {
503
- try {
504
- if (gopWindow.gops.length === 0) {
505
- console.warn("[VideoWindowDecodeSession] No GOPs found for range");
506
- controller.close();
668
+ const owned = [];
669
+ let finished = false;
670
+ let failure = null;
671
+ let wake = null;
672
+ const notify = () => {
673
+ const resume = wake;
674
+ wake = null;
675
+ resume?.();
676
+ };
677
+ const releaseOwned = () => {
678
+ for (const frame of owned.splice(0)) frame.close();
679
+ };
680
+ const onAbort = () => fail(this.abortController.signal.reason);
681
+ const end = () => this.abortController.signal.removeEventListener("abort", onAbort);
682
+ const admit = (frame) => {
683
+ if (this.cancelled || failure !== null || finished) {
684
+ frame.close();
685
+ return;
686
+ }
687
+ owned.push(frame);
688
+ notify();
689
+ };
690
+ const finish = () => {
691
+ finished = true;
692
+ notify();
693
+ };
694
+ const fail = (error) => {
695
+ end();
696
+ releaseOwned();
697
+ failure = error;
698
+ notify();
699
+ };
700
+ this.abortController.signal.addEventListener("abort", onAbort, { once: true });
701
+ const produce = async () => {
702
+ try {
703
+ if (gopWindow.gops.length === 0) {
704
+ console.warn("[VideoWindowDecodeSession] No GOPs found for range");
705
+ finish();
706
+ return;
707
+ }
708
+ const batchSize = 10;
709
+ for (let i = 0; i < gopWindow.gops.length; i += batchSize) {
710
+ this.assertResourceCurrent();
711
+ if (this.aborted) {
712
+ finish();
507
713
  return;
508
714
  }
509
- const batchSize = 10;
510
- for (let i = 0; i < gopWindow.gops.length; i += batchSize) {
511
- this.assertResourceCurrent();
512
- if (this.aborted) {
513
- controller.close();
514
- return;
715
+ const batchGOPs = gopWindow.gops.slice(i, Math.min(i + batchSize, gopWindow.gops.length));
716
+ let batchByteStart = Infinity;
717
+ let batchByteEnd = 0;
718
+ for (const gop of batchGOPs) {
719
+ const startSample = videoTrack.samples[gop.keyframeSampleIndex];
720
+ const endSampleIdx = gop.keyframeSampleIndex + gop.sampleCount - 1;
721
+ const endSample = videoTrack.samples[endSampleIdx];
722
+ if (startSample && endSample) {
723
+ batchByteStart = Math.min(batchByteStart, startSample.byteOffset);
724
+ batchByteEnd = Math.max(batchByteEnd, endSample.byteOffset + endSample.byteLength);
515
725
  }
516
- const batchGOPs = gopWindow.gops.slice(
517
- i,
518
- Math.min(i + batchSize, gopWindow.gops.length)
519
- );
520
- let batchByteStart = Infinity;
521
- let batchByteEnd = 0;
522
- for (const gop of batchGOPs) {
523
- const startSample = videoTrack.samples[gop.keyframeSampleIndex];
524
- const endSampleIdx = gop.keyframeSampleIndex + gop.sampleCount - 1;
525
- const endSample = videoTrack.samples[endSampleIdx];
526
- if (startSample && endSample) {
527
- batchByteStart = Math.min(batchByteStart, startSample.byteOffset);
528
- batchByteEnd = Math.max(batchByteEnd, endSample.byteOffset + endSample.byteLength);
726
+ }
727
+ const gopData = await this.readCurrentResourceRange(batchByteStart, batchByteEnd);
728
+ if (this.aborted) {
729
+ finish();
730
+ return;
731
+ }
732
+ const batchChunks = await this.demuxGOPData(gopData, index, {
733
+ gops: batchGOPs,
734
+ byteStart: batchByteStart,
735
+ byteEnd: batchByteEnd
736
+ });
737
+ await this.decodeChunks(batchChunks, index);
738
+ this.assertResourceCurrent();
739
+ if (this.aborted) {
740
+ this.releaseDecodedFrames();
741
+ finish();
742
+ return;
743
+ }
744
+ for (const frame of this.decodedFrames) {
745
+ if (frame.timestamp >= startUs && frame.timestamp < endUs) {
746
+ if (!this.loggedDecodedStreamDimensions) {
747
+ console.info(
748
+ "decodeRangeToStream:",
749
+ "Id:",
750
+ this.resourceId,
751
+ "videoTrack:",
752
+ videoTrack.width,
753
+ "x",
754
+ videoTrack.height,
755
+ "displaySize:",
756
+ frame.displayWidth,
757
+ "x",
758
+ frame.displayHeight,
759
+ "codedSize:",
760
+ frame.codedWidth,
761
+ "x",
762
+ frame.codedHeight,
763
+ "startUs:",
764
+ startUs,
765
+ "endUs:",
766
+ endUs,
767
+ "duration:",
768
+ frame.duration,
769
+ "Uri:",
770
+ this.resourceUri
771
+ );
772
+ this.loggedDecodedStreamDimensions = true;
529
773
  }
774
+ admit(frame);
775
+ resumeUs = Math.max(resumeUs, frame.timestamp + 1);
776
+ } else {
777
+ frame.close();
530
778
  }
531
- const gopData = await this.readResourceRangeWithRecovery(batchByteStart, batchByteEnd);
532
- if (this.aborted) {
533
- controller.close();
534
- return;
535
- }
536
- const batchChunks = await this.demuxGOPData(gopData, index, {
537
- gops: batchGOPs,
538
- byteStart: batchByteStart,
539
- byteEnd: batchByteEnd
540
- });
541
- await this.decodeChunks(batchChunks, index);
542
- this.assertResourceCurrent();
543
- if (this.aborted) {
544
- this.releaseDecodedFrames();
545
- controller.close();
546
- return;
547
- }
548
- for (const frame of this.decodedFrames) {
549
- if (frame.timestamp >= startUs && frame.timestamp < endUs) {
550
- if (!this.loggedDecodedStreamDimensions) {
551
- console.info(
552
- "decodeRangeToStream:",
553
- "Id:",
554
- this.resourceId,
555
- "videoTrack:",
556
- videoTrack.width,
557
- "x",
558
- videoTrack.height,
559
- "displaySize:",
560
- frame.displayWidth,
561
- "x",
562
- frame.displayHeight,
563
- "codedSize:",
564
- frame.codedWidth,
565
- "x",
566
- frame.codedHeight,
567
- "startUs:",
568
- startUs,
569
- "endUs:",
570
- endUs,
571
- "duration:",
572
- frame.duration,
573
- "Uri:",
574
- this.resourceUri
575
- );
576
- this.loggedDecodedStreamDimensions = true;
779
+ }
780
+ this.decodedFrames = [];
781
+ }
782
+ finish();
783
+ } catch (error) {
784
+ this.releaseDecodedFrames();
785
+ if (error instanceof ResourceSupersededError && allowRecovery && !this.cancelled) {
786
+ try {
787
+ this.sourceIndex = this.mp4IndexCache.get(this.resourceId);
788
+ const retry = this.createExportFrameStream(resumeUs, endUs, false).getReader();
789
+ this.exportRetryReader = retry;
790
+ try {
791
+ while (true) {
792
+ const next = await retry.read();
793
+ if (this.cancelled) {
794
+ next.value?.close();
795
+ finish();
796
+ return;
577
797
  }
578
- controller.enqueue(frame);
579
- resumeUs = Math.max(resumeUs, frame.timestamp + 1);
580
- } else {
581
- frame.close();
798
+ if (next.done) break;
799
+ admit(next.value);
582
800
  }
801
+ finish();
802
+ } finally {
803
+ this.exportRetryReader = void 0;
804
+ retry.releaseLock();
583
805
  }
584
- this.decodedFrames = [];
806
+ } catch (retryError) {
807
+ fail(retryError);
808
+ }
809
+ } else fail(error);
810
+ }
811
+ };
812
+ return new ReadableStream(
813
+ {
814
+ start: () => {
815
+ void this.track(produce());
816
+ },
817
+ pull: async (controller) => {
818
+ while (owned.length === 0 && !finished && failure === null) {
819
+ await new Promise((resolve) => {
820
+ wake = resolve;
821
+ });
822
+ }
823
+ if (failure !== null) {
824
+ controller.error(failure);
825
+ return;
826
+ }
827
+ if (owned.length > 0) {
828
+ controller.enqueue(owned.shift());
829
+ return;
585
830
  }
831
+ end();
586
832
  controller.close();
587
- } catch (error) {
833
+ },
834
+ cancel: () => {
835
+ this.cancelled = true;
836
+ void this.exportRetryReader?.cancel().catch(() => {
837
+ });
838
+ releaseOwned();
588
839
  this.releaseDecodedFrames();
589
- if (error instanceof ResourceSupersededError && allowRecovery && !this.cancelled) {
590
- try {
591
- this.sourceIndex = this.mp4IndexCache.get(this.resourceId);
592
- const retry = this.createExportFrameStream(resumeUs, endUs, false).getReader();
593
- this.exportRetryReader = retry;
594
- try {
595
- while (true) {
596
- const next = await retry.read();
597
- if (this.cancelled) {
598
- next.value?.close();
599
- controller.close();
600
- return;
601
- }
602
- if (next.done) break;
603
- controller.enqueue(next.value);
604
- }
605
- controller.close();
606
- } finally {
607
- this.exportRetryReader = void 0;
608
- retry.releaseLock();
609
- }
610
- } catch (retryError) {
611
- controller.error(retryError);
612
- }
613
- } else controller.error(error);
840
+ this.abortController.abort(new DOMException("Decode stream cancelled", "AbortError"));
614
841
  }
615
842
  },
616
- cancel: () => {
617
- this.cancelled = true;
618
- void this.exportRetryReader?.cancel().catch(() => {
619
- });
620
- this.releaseDecodedFrames();
621
- }
622
- });
843
+ { highWaterMark: 0 }
844
+ );
623
845
  }
624
- async readResourceRangeWithRecovery(start, end) {
625
- const checkCurrent = () => {
626
- this.assertResourceCurrent();
627
- };
628
- checkCurrent();
846
+ async readCurrentResourceRange(start, end) {
847
+ this.assertResourceCurrent();
848
+ let bytes;
629
849
  try {
630
- const bytes = await this.cacheManager.readResourceRange(this.resourceId, start, end);
631
- checkCurrent();
632
- return bytes;
850
+ bytes = await untilAborted(
851
+ this.cacheManager.readResourceRange(this.resourceId, start, end),
852
+ this.abortController.signal
853
+ );
633
854
  } catch (error) {
634
- const recoverable = error instanceof ResourceCorruptedError || isDOMException(error, "InvalidStateError");
635
- if (!recoverable) throw error;
636
- checkCurrent();
637
- await this.cacheManager.resourceCache.deleteResource(this.resourceId);
638
- await this.resourceLoader.load(this.resourceId, { isPreload: false, clipId: this.clipId });
639
- checkCurrent();
640
- const bytes = await this.cacheManager.readResourceRange(this.resourceId, start, end);
641
- checkCurrent();
642
- return bytes;
855
+ this.resourceLoader.reportByteFailure(
856
+ this.resourceId,
857
+ error,
858
+ () => !this.cancelled && this.mp4IndexCache.get(this.resourceId) === this.sourceIndex
859
+ );
860
+ throw error;
643
861
  }
862
+ this.assertResourceCurrent();
863
+ return bytes;
644
864
  }
645
- async dispose() {
646
- if (this.isDisposed) return;
647
- this.cancelled = true;
648
- await this.exportRetryReader?.cancel().catch(() => {
649
- });
650
- this.releaseDecodedFrames();
865
+ dispose() {
866
+ if (this.disposePromise) return this.disposePromise;
651
867
  this.isDisposed = true;
868
+ this.cancelled = true;
869
+ const inFlight = [...this.tasks];
870
+ this.resetPreviewStream();
871
+ this.abortController.abort(new DOMException("Decode session disposed", "AbortError"));
872
+ this.disposePromise = (async () => {
873
+ await this.exportRetryReader?.cancel().catch(() => {
874
+ });
875
+ await Promise.allSettled(inFlight);
876
+ this.resetPreviewStream();
877
+ this.releaseDecodedFrames();
878
+ })();
879
+ return this.disposePromise;
652
880
  }
653
881
  }
654
882
  export {