@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,6 +1,6 @@
1
- import { PlaybackState, PlaybackActionType, PlaybackCommandType } from "./types.js";
1
+ import { PlaybackActionType, PlaybackState, PlaybackCommandType } from "./types.js";
2
2
  import { MeframeEvent } from "../event/events.js";
3
- import { WaiterReplacedError, MP4MoovNotFoundError } from "../utils/errors.js";
3
+ import { isReportedToHost, WaiterReplacedError, MP4MoovNotFoundError } from "../utils/errors.js";
4
4
  import { VideoComposer } from "../stages/compose/VideoComposer.js";
5
5
  import { isVideoClip } from "../model/types.js";
6
6
  import { PlaybackStateMachine } from "./PlaybackStateMachine.js";
@@ -10,6 +10,19 @@ class PlaybackController {
10
10
  eventBus;
11
11
  canvas;
12
12
  videoComposer = null;
13
+ /** Settles when the first presentation at the start position has been composed. */
14
+ ready;
15
+ layerFailure;
16
+ // Sources (resource id, or clip id for layers without a resource) whose layer failure was already reported to the host.
17
+ /** Resource (or clip) id → the source URI its layer failure was last reported for. */
18
+ reportedLayerFailures = /* @__PURE__ */ new Map();
19
+ // Presentations compose one at a time, in dispatch order.
20
+ renderTail = Promise.resolve();
21
+ commandTasks = /* @__PURE__ */ new Set();
22
+ // Aborted whenever the state machine's token changes, so work for a replaced presentation stops.
23
+ renderAbort = new AbortController();
24
+ disposed = false;
25
+ disposePromise = null;
13
26
  // Playback time (external)
14
27
  currentTimeUs = 0;
15
28
  playbackRate = 1;
@@ -31,21 +44,11 @@ class PlaybackController {
31
44
  // 250ms
32
45
  // State machine
33
46
  fsm = new PlaybackStateMachine();
34
- // Coalesced seek (scrubbing): latest-wins, flush at most once per rAF.
35
- // UI is fire-and-forget; this avoids spawning/canceling on-demand decoders too aggressively.
36
- pendingSeekTimeUs = null;
37
- pendingSeekWaiters = [];
38
- seekFlushRafId = null;
39
- seekInFlight = null;
40
- // If user drags far away while a seek is decoding, cancel it to avoid visible lag.
41
- SEEK_CANCEL_DISTANCE_US = 5e6;
42
- // 5s
43
- isSeekActive() {
44
- return this.pendingSeekTimeUs !== null || this.seekInFlight !== null || this.fsm.snapshot.state === PlaybackState.Seeking;
45
- }
46
47
  // Unified window management for both video and audio
47
48
  preheatInProgress = false;
48
49
  lastPreheatTimeUs = -Infinity;
50
+ // Deduplicates 60Hz probe ticks that resolve to the exact same static video/image frame.
51
+ lastPresentedKey = null;
49
52
  // Pause-shrink: L1 hoarded frames serve no one while paused for long. The editor
50
53
  // spends most of its lifetime paused, so trim the frame cache down to a tight
51
54
  // window after a grace period. Playback refills through regular miss/preheat.
@@ -62,6 +65,7 @@ class PlaybackController {
62
65
  this.eventBus = eventBus;
63
66
  this.canvas = options.canvas;
64
67
  this.audioContext = new AudioContext();
68
+ this.layerFailure = options.layerFailure ?? "skip-layer";
65
69
  const model = orchestrator.compositionModel;
66
70
  const width = model?.renderConfig?.width || this.canvas.width || 720;
67
71
  const height = model?.renderConfig?.height || this.canvas.height || 1280;
@@ -70,7 +74,8 @@ class PlaybackController {
70
74
  height,
71
75
  fps: model?.fps || 30,
72
76
  backgroundColor: model?.renderConfig?.backgroundColor || "#000",
73
- externalCanvas: this.canvas
77
+ externalCanvas: this.canvas,
78
+ fonts: orchestrator.config.global.fonts
74
79
  });
75
80
  if (options.startUs !== void 0) {
76
81
  this.currentTimeUs = options.startUs;
@@ -82,22 +87,20 @@ class PlaybackController {
82
87
  this.loop = options.loop;
83
88
  }
84
89
  this.setupEventListeners();
90
+ this.ready = this.seek(options.startUs ?? 0);
91
+ this.ready.catch(() => {
92
+ });
85
93
  if (options.autoStart) {
86
- this.play();
94
+ void this.ready.then(() => this.play()).catch(() => {
95
+ });
87
96
  }
88
97
  }
89
- async renderCover() {
90
- const token = this.fsm.snapshot.token;
91
- await this.renderCurrentFrame(0, { mode: "blocking" }).catch(
92
- (error) => this.handlePlaybackError(error, token, {
93
- logPrefix: "[PlaybackController] Cover render failed:",
94
- emitPlaybackError: true,
95
- onError: { type: PlaybackActionType.Pause }
96
- })
97
- );
98
+ renderCover() {
99
+ return this.seek(this.currentTimeUs);
98
100
  }
99
101
  // ========= Public API =========
100
102
  play() {
103
+ if (this.disposed) return;
101
104
  this.cancelPauseShrink();
102
105
  if (this.shrinkInvalidatedWindow) {
103
106
  this.shrinkInvalidatedWindow = false;
@@ -108,6 +111,7 @@ class PlaybackController {
108
111
  this.dispatch({ type: PlaybackActionType.Play });
109
112
  }
110
113
  pause() {
114
+ if (this.disposed) return;
111
115
  this.lastFrameTime = 0;
112
116
  this.dispatch({ type: PlaybackActionType.Pause });
113
117
  if (!this.orchestrator.cacheManager.isExporting) {
@@ -121,6 +125,7 @@ class PlaybackController {
121
125
  this.pauseShrinkTimer = setTimeout(() => {
122
126
  this.pauseShrinkTimer = null;
123
127
  if (this.fsm.snapshot.state !== PlaybackState.Paused) return;
128
+ this.orchestrator.cancelActiveDecoding();
124
129
  this.orchestrator.cacheManager.videoL1Cache.shrink();
125
130
  this.shrinkInvalidatedWindow = true;
126
131
  }, PlaybackController.PAUSE_SHRINK_DELAY_MS);
@@ -132,70 +137,32 @@ class PlaybackController {
132
137
  }
133
138
  }
134
139
  stop() {
140
+ if (this.disposed) return;
141
+ this.lastPresentedKey = null;
135
142
  this.orchestrator.cancelActiveDecoding();
136
143
  this.cancelPauseShrink();
137
144
  this.dispatch({ type: PlaybackActionType.Stop });
138
145
  }
139
- async seek(timeUs) {
140
- this.orchestrator.cancelActiveDecoding();
141
- this.pendingSeekTimeUs = timeUs;
142
- const done = new Promise((resolve) => {
143
- this.pendingSeekWaiters.push(resolve);
144
- });
145
- if (this.seekFlushRafId === null) {
146
- this.seekFlushRafId = requestAnimationFrame(() => {
147
- this.seekFlushRafId = null;
148
- void this.flushCoalescedSeek();
146
+ seek(timeUs) {
147
+ if (this.disposed) {
148
+ const rejected = Promise.reject(new DOMException("Preview disposed", "AbortError"));
149
+ rejected.catch(() => {
149
150
  });
151
+ return rejected;
150
152
  }
151
- await done;
152
- }
153
- async flushCoalescedSeek() {
154
- const target = this.pendingSeekTimeUs;
155
- if (target === null) {
156
- const waiters = this.pendingSeekWaiters;
157
- this.pendingSeekWaiters = [];
158
- for (const resolve of waiters) resolve();
159
- return;
160
- }
161
- await this.performSeek(target);
162
- }
163
- async performSeek(target) {
164
- if (this.seekInFlight) {
165
- const distance = Math.abs(target - this.seekInFlight.targetUs);
166
- if (distance <= this.SEEK_CANCEL_DISTANCE_US) {
167
- return;
168
- }
169
- this.seekInFlight = null;
170
- }
171
- this.pendingSeekTimeUs = null;
172
- const { done } = this.dispatch({
153
+ const { token, done } = this.dispatch({
173
154
  type: PlaybackActionType.Seek,
174
- timeUs: target,
155
+ timeUs,
175
156
  durationUs: this.duration
176
157
  });
177
- this.seekInFlight = { targetUs: target, done };
178
- void done.finally(() => {
179
- const waiters = this.pendingSeekWaiters;
180
- this.pendingSeekWaiters = [];
181
- for (const resolve of waiters) resolve();
182
- if (this.seekInFlight?.targetUs === target) {
183
- this.seekInFlight = null;
184
- }
185
- if (!this.orchestrator.cacheManager.isExporting) {
186
- void this.audioSession.ensureAudioForTime(target, { mode: "probe" });
187
- }
188
- const shouldPreheatAfterSeek = this.pendingSeekTimeUs === null && !this.orchestrator.cacheManager.isExporting && this.fsm.snapshot.state === PlaybackState.Playing;
189
- if (shouldPreheatAfterSeek) {
190
- void this.preheatNextWindow();
191
- }
192
- if (this.pendingSeekTimeUs !== null && this.seekFlushRafId === null) {
193
- this.seekFlushRafId = requestAnimationFrame(() => {
194
- this.seekFlushRafId = null;
195
- void this.flushCoalescedSeek();
196
- });
158
+ const presented = done.then(() => {
159
+ if (!this.isCurrentToken(token)) {
160
+ throw new DOMException("Presentation replaced", "AbortError");
197
161
  }
198
162
  });
163
+ presented.catch(() => {
164
+ });
165
+ return presented;
199
166
  }
200
167
  setRate(rate) {
201
168
  const currentTimeUs = this.currentTimeUs;
@@ -215,7 +182,18 @@ class PlaybackController {
215
182
  return;
216
183
  }
217
184
  if (this.fsm.snapshot.state === PlaybackState.Playing) {
218
- void this.audioSession.startPlayback(this.currentTimeUs, this.audioContext);
185
+ const signal = this.renderAbort.signal;
186
+ const task = this.audioSession.startPlayback(this.currentTimeUs, this.audioContext, signal);
187
+ this.commandTasks.add(task);
188
+ task.then(
189
+ () => this.commandTasks.delete(task),
190
+ (error) => {
191
+ this.commandTasks.delete(task);
192
+ if (!signal.aborted && !isReportedToHost(error)) {
193
+ this.eventBus.emit(MeframeEvent.PlaybackError, error);
194
+ }
195
+ }
196
+ );
219
197
  }
220
198
  }
221
199
  setLoop(loop) {
@@ -238,8 +216,16 @@ class PlaybackController {
238
216
  }
239
217
  // ========= State machine wiring =========
240
218
  dispatch(action) {
219
+ const previous = this.fsm.snapshot.token;
241
220
  const { token, commands } = this.fsm.dispatch(action, { currentTimeUs: this.currentTimeUs });
221
+ if (token !== previous) {
222
+ this.renderAbort.abort(new DOMException("Presentation replaced", "AbortError"));
223
+ this.renderAbort = new AbortController();
224
+ }
242
225
  const done = this.executeCommands(commands, token);
226
+ this.commandTasks.add(done);
227
+ const forget = () => this.commandTasks.delete(done);
228
+ done.then(forget, forget);
243
229
  return { token, done };
244
230
  }
245
231
  executeCommands(commands, token) {
@@ -271,7 +257,9 @@ class PlaybackController {
271
257
  }
272
258
  handlePlaybackError(error, token, command) {
273
259
  if (!this.isCurrentToken(token)) return;
260
+ if (error?.name === "AbortError") return;
274
261
  if (command.ignoreWaiterReplacedError && error instanceof WaiterReplacedError) return;
262
+ if (command.clearCanvasOnError) this.queueClearCanvas();
275
263
  if (command.logPrefix) console.error(command.logPrefix, error);
276
264
  const onErrorDone = command.onError ? this.dispatch(command.onError).done : void 0;
277
265
  const normalizeError = (e) => {
@@ -279,7 +267,7 @@ class PlaybackController {
279
267
  return new Error(typeof e === "string" ? e : JSON.stringify(e));
280
268
  };
281
269
  const emit = () => {
282
- if (command.emitPlaybackError) {
270
+ if (command.emitPlaybackError && !isReportedToHost(error)) {
283
271
  const err = normalizeError(error);
284
272
  const recoverable = (
285
273
  // Waiter replaced is expected during rapid seek; safe to ignore.
@@ -313,7 +301,18 @@ class PlaybackController {
313
301
  case PlaybackCommandType.Par:
314
302
  return this.executePar(command.commands, token);
315
303
  case PlaybackCommandType.Try: {
316
- const handleError = (error) => this.handlePlaybackError(error, token, command);
304
+ const handleError = (error) => {
305
+ const handled = this.handlePlaybackError(error, token, command);
306
+ if (handled) {
307
+ return handled.then(() => {
308
+ throw error;
309
+ });
310
+ }
311
+ if (!(command.ignoreWaiterReplacedError && error instanceof WaiterReplacedError)) {
312
+ throw error;
313
+ }
314
+ return;
315
+ };
317
316
  try {
318
317
  const maybe = this.executeCommand(command.command, token);
319
318
  if (maybe) {
@@ -352,8 +351,7 @@ class PlaybackController {
352
351
  return;
353
352
  }
354
353
  case PlaybackCommandType.ClearCanvas: {
355
- this.clearCanvas();
356
- return;
354
+ return this.queueClearCanvas(token);
357
355
  }
358
356
  case PlaybackCommandType.SetLastAudioScheduleTime: {
359
357
  this.lastAudioScheduleTime = command.timeUs;
@@ -408,7 +406,11 @@ class PlaybackController {
408
406
  });
409
407
  }
410
408
  case PlaybackCommandType.StartAudioPlayback: {
411
- return this.audioSession.startPlayback(command.timeUs, this.audioContext);
409
+ return this.audioSession.startPlayback(
410
+ command.timeUs,
411
+ this.audioContext,
412
+ this.renderAbort.signal
413
+ );
412
414
  }
413
415
  case PlaybackCommandType.ProbeStartReady: {
414
416
  const audioReady = this.audioSession.isPreviewMixBlockCached(command.timeUs);
@@ -456,6 +458,11 @@ class PlaybackController {
456
458
  );
457
459
  });
458
460
  }
461
+ /** How long a sample scheduled at `audioContext.currentTime` takes to be heard: the clock leads the speaker by this much. */
462
+ outputLatencyUs() {
463
+ const { baseLatency = 0, outputLatency = 0 } = this.audioContext;
464
+ return (baseLatency + outputLatency) * 1e6;
465
+ }
459
466
  async onRafTick(token) {
460
467
  if (!this.isCurrentToken(token) || this.fsm.snapshot.state !== PlaybackState.Playing) {
461
468
  return;
@@ -466,7 +473,8 @@ class PlaybackController {
466
473
  candidateTimeUs,
467
474
  durationUs: this.duration,
468
475
  loop: this.loop,
469
- audioNowUs: this.audioContext.currentTime * 1e6
476
+ audioNowUs: this.audioContext.currentTime * 1e6,
477
+ outputLatencyUs: this.outputLatencyUs()
470
478
  });
471
479
  if (!this.isCurrentToken(token) || this.fsm.snapshot.state !== PlaybackState.Playing) {
472
480
  return;
@@ -485,13 +493,9 @@ class PlaybackController {
485
493
  });
486
494
  return;
487
495
  }
488
- const renderState = await this.orchestrator.getRenderState(this.currentTimeUs, {
489
- mode: "probe"
490
- });
491
- if (!this.isCurrentToken(token) || this.fsm.snapshot.state !== PlaybackState.Playing) {
492
- return;
493
- }
494
- if (!renderState) {
496
+ const rendered = await this.renderCurrentFrame(this.currentTimeUs, { mode: "probe", token });
497
+ if (!this.isCurrentToken(token) || this.fsm.snapshot.state !== PlaybackState.Playing) return;
498
+ if (!rendered) {
495
499
  playbackDiagnostic("playback.render-empty", {
496
500
  timeUs: this.currentTimeUs,
497
501
  state: this.fsm.snapshot.state
@@ -505,12 +509,6 @@ class PlaybackController {
505
509
  this.dispatch({ type: PlaybackActionType.EnterBuffering, timeUs: this.currentTimeUs });
506
510
  return;
507
511
  }
508
- playbackDiagnostic("playback.render", {
509
- timeUs: this.currentTimeUs,
510
- frameCount: this.frameCount
511
- });
512
- await this.compose(this.currentTimeUs, renderState);
513
- if (!this.isCurrentToken(token) || this.fsm.snapshot.state !== PlaybackState.Playing) return;
514
512
  this.finalizeFrameAndContinue(token);
515
513
  }
516
514
  finalizeFrameAndContinue(token) {
@@ -550,15 +548,17 @@ class PlaybackController {
550
548
  async preheatNextWindow() {
551
549
  const isExporting = this.orchestrator.cacheManager.isExporting;
552
550
  const isPreheatBusy = this.preheatInProgress;
553
- const shouldSkipPreheat = isExporting || isPreheatBusy || this.isSeekActive();
551
+ const shouldSkipPreheat = isExporting || isPreheatBusy || this.fsm.snapshot.state === PlaybackState.Seeking;
554
552
  if (shouldSkipPreheat) return;
555
553
  this.preheatInProgress = true;
556
554
  const token = this.fsm.snapshot.token;
557
555
  try {
558
556
  this.lastPreheatTimeUs = this.currentTimeUs;
559
557
  const windowStart = this.currentTimeUs;
560
- const windowEnd = windowStart + 1e6;
561
- const clipsInWindow = this.orchestrator.compositionModel?.getClipsInRange(windowStart, windowEnd) ?? [];
558
+ const lookaheadUs = this.orchestrator.getPreviewLookaheadUs?.() ?? 1e6;
559
+ const windowEnd = windowStart + lookaheadUs;
560
+ const model = this.orchestrator.compositionModel;
561
+ const clipsInWindow = model?.getClipsInRange(windowStart, windowEnd, model.mainTrackId) ?? [];
562
562
  for (const clip of clipsInWindow) {
563
563
  if (!isVideoClip(clip)) continue;
564
564
  const clipWindowStart = Math.max(0, windowStart - clip.startUs);
@@ -587,69 +587,188 @@ class PlaybackController {
587
587
  if (this.orchestrator.cacheManager.isExporting) return;
588
588
  void this.audioSession.ensureAudioForTime(timeUs, { mode: "probe" });
589
589
  }
590
- async renderCurrentFrame(timeUs, options) {
591
- if (!this.videoComposer) {
592
- console.error("[PlaybackController] VideoComposer not initialized");
593
- return;
594
- }
595
- const renderState = await this.orchestrator.getRenderState(timeUs, {
596
- mode: options.mode,
597
- relativeTimeUs: options.relativeTimeUs
590
+ /**
591
+ * Presentations compose one at a time. Resolves true when a frame was composed; a probe with no frame ready resolves false, any
592
+ * other missing frame rejects. The render state's native frames are released here, composed or not.
593
+ */
594
+ renderCurrentFrame(timeUs, options) {
595
+ const token = options.token ?? this.fsm.snapshot.token;
596
+ const signal = this.renderAbort.signal;
597
+ const render = async () => {
598
+ signal.throwIfAborted();
599
+ if (!this.isCurrentToken(token)) {
600
+ throw new DOMException("Presentation replaced", "AbortError");
601
+ }
602
+ let renderState = null;
603
+ try {
604
+ renderState = await this.orchestrator.getRenderState(timeUs, {
605
+ mode: options.mode,
606
+ relativeTimeUs: options.relativeTimeUs,
607
+ signal
608
+ });
609
+ signal.throwIfAborted();
610
+ if (!this.isCurrentToken(token)) {
611
+ throw new DOMException("Presentation replaced", "AbortError");
612
+ }
613
+ if (!renderState) {
614
+ if (options.mode === "probe") return false;
615
+ throw new Error("Required preview frame is unavailable");
616
+ }
617
+ const presentedKey = this.presentedFrameKey(renderState);
618
+ if (options.mode === "probe" && presentedKey !== null && presentedKey === this.lastPresentedKey) {
619
+ return true;
620
+ }
621
+ this.lastPresentedKey = null;
622
+ await this.compose(timeUs, renderState, signal);
623
+ signal.throwIfAborted();
624
+ this.lastPresentedKey = presentedKey;
625
+ return true;
626
+ } finally {
627
+ this.discardRenderState(renderState);
628
+ }
629
+ };
630
+ const done = this.renderTail.then(render);
631
+ this.renderTail = done.catch(() => {
598
632
  });
599
- if (!renderState) {
600
- if (this.fsm.snapshot.state === PlaybackState.Buffering && timeUs === this.currentTimeUs)
601
- return;
602
- this.clearCanvas();
603
- return;
633
+ return done;
634
+ }
635
+ /** The one release point of a render state that is not composed. Each owned frame is closed once; the layer then drops it. */
636
+ discardRenderState(renderState) {
637
+ for (const layer of renderState?.layers ?? []) {
638
+ if (layer.videoFrame && !layer.rcFrame) {
639
+ layer.videoFrame.close();
640
+ layer.videoFrame = void 0;
641
+ }
642
+ if (layer.ownedSource && layer.source) {
643
+ layer.source.close();
644
+ layer.source = null;
645
+ }
604
646
  }
605
- await this.compose(timeUs, renderState);
606
647
  }
607
- async compose(timeUs, renderState) {
608
- if (!this.videoComposer) return;
648
+ async compose(timeUs, renderState, signal) {
649
+ if (!this.videoComposer) throw new DOMException("Preview disposed", "AbortError");
609
650
  await this.videoComposer.composeFrame({
610
651
  timeUs,
611
652
  layers: renderState.layers,
612
- transition: renderState.transition
653
+ transition: renderState.transition,
654
+ signal,
655
+ // Under 'pause' a failed layer fails the frame, and the command that rendered it reports the error and pauses.
656
+ onLayerError: this.layerFailure === "skip-layer" ? (layer, error) => this.reportLayerFailure(layer, error) : void 0
613
657
  });
614
658
  }
659
+ /**
660
+ * A failed layer is left out of the frame. The host hears about it once per resource (or clip) and source: again only
661
+ * after the resource gets a new URI, or loads to ready (for example through `reloadResource`) and then fails again.
662
+ */
663
+ reportLayerFailure(layer, error) {
664
+ const origin = layer.origin;
665
+ const key = origin?.resourceId ?? origin?.clipId ?? layer.id;
666
+ const source = origin?.resourceId ? this.orchestrator.compositionModel?.getResource(origin.resourceId)?.uri ?? "" : "";
667
+ if (this.reportedLayerFailures.get(key) === source) return;
668
+ this.reportedLayerFailures.set(key, source);
669
+ const err = error instanceof Error ? error : new Error(String(error));
670
+ console.error("[PlaybackController] Layer render failed; the frame is drawn without it:", {
671
+ layerId: layer.id,
672
+ ...origin,
673
+ error: err
674
+ });
675
+ if (isReportedToHost(error)) return;
676
+ this.eventBus.emit(MeframeEvent.PlaybackError, err);
677
+ this.eventBus.emit(MeframeEvent.Error, {
678
+ source: "playback",
679
+ error: err,
680
+ context: {
681
+ layerId: layer.id,
682
+ clipId: origin?.clipId,
683
+ resourceId: origin?.resourceId,
684
+ layerFailure: this.layerFailure
685
+ },
686
+ recoverable: true
687
+ });
688
+ }
689
+ /**
690
+ * Stable presentation signature for static video/image frames so 60Hz rAF probe ticks
691
+ * skip redundant full-canvas redraws when a 24/30fps video resolves to the same frame.
692
+ * Returns null whenever the composition has transitions, text animations, transforms,
693
+ * filters, masks, or empty layers so those always re-compose.
694
+ */
695
+ presentedFrameKey(renderState) {
696
+ if (renderState.transition || renderState.layers.length === 0) return null;
697
+ const parts = [];
698
+ for (const layer of renderState.layers) {
699
+ if (layer.type !== "video" && layer.type !== "image" || layer.transform || layer.mask || Array.isArray(layer.filters) && layer.filters.length > 0) {
700
+ return null;
701
+ }
702
+ if (layer.type === "video") {
703
+ const ts = layer.videoFrame?.timestamp;
704
+ if (typeof ts !== "number") return null;
705
+ parts.push(
706
+ `v:${layer.id}:${layer.origin?.clipId ?? ""}:${layer.origin?.resourceId ?? ""}:${ts}:${layer.opacity ?? 1}:${layer.blendMode ?? ""}:${layer.visible ?? true}`
707
+ );
708
+ } else {
709
+ if (!layer.source) return null;
710
+ parts.push(
711
+ `i:${layer.id}:${layer.origin?.clipId ?? ""}:${layer.origin?.resourceId ?? ""}:${layer.opacity ?? 1}:${layer.blendMode ?? ""}:${layer.visible ?? true}`
712
+ );
713
+ }
714
+ }
715
+ return parts.join("|");
716
+ }
717
+ /** A resource that loads again may fail again; that failure is reported again. */
718
+ onResourceStageChange = (payload) => {
719
+ if (payload.newState === "ready") {
720
+ this.reportedLayerFailures.delete(payload.resourceId);
721
+ this.lastPresentedKey = null;
722
+ }
723
+ };
724
+ onPatchApplied = () => {
725
+ this.lastPresentedKey = null;
726
+ };
727
+ /** Clears the canvas in presentation order; with `token`, only while that operation is still current. */
728
+ queueClearCanvas(token) {
729
+ const done = this.renderTail.then(() => {
730
+ if (token === void 0 || this.isCurrentToken(token)) this.clearCanvas();
731
+ });
732
+ this.renderTail = done.catch(() => {
733
+ });
734
+ return done;
735
+ }
615
736
  clearCanvas() {
737
+ this.lastPresentedKey = null;
616
738
  const ctx = this.canvas.getContext("2d");
617
739
  if (ctx && "clearRect" in ctx) {
618
740
  ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
619
741
  }
620
742
  }
621
743
  // ========= Cleanup / event handlers =========
622
- async dispose() {
623
- this.stop();
624
- if (this.seekFlushRafId !== null) {
625
- cancelAnimationFrame(this.seekFlushRafId);
626
- this.seekFlushRafId = null;
627
- }
628
- this.pendingSeekTimeUs = null;
629
- const waiters = this.pendingSeekWaiters;
630
- this.pendingSeekWaiters = [];
631
- for (const resolve of waiters) resolve();
632
- this.eventBus.off(MeframeEvent.CacheCover, this.onCacheCover);
744
+ /** Pauses and waits for every command and presentation in flight; the controller stays usable. */
745
+ async drain() {
746
+ this.pause();
747
+ await Promise.allSettled([...this.commandTasks]);
748
+ await this.renderTail;
749
+ }
750
+ dispose() {
751
+ if (this.disposePromise) return this.disposePromise;
752
+ this.pause();
753
+ this.disposed = true;
754
+ this.cancelPauseShrink();
755
+ this.renderAbort.abort(new DOMException("Preview disposed", "AbortError"));
756
+ this.cancelRaf();
633
757
  this.eventBus.off(MeframeEvent.ModelSet, this.onModelSet);
634
- if (this.videoComposer) {
635
- this.videoComposer.dispose();
758
+ this.eventBus.off(MeframeEvent.PatchApplied, this.onPatchApplied);
759
+ this.eventBus.off(MeframeEvent.ResourceStageChange, this.onResourceStageChange);
760
+ this.disposePromise = (async () => {
761
+ await Promise.allSettled([...this.commandTasks]);
762
+ await this.renderTail;
763
+ this.videoComposer?.dispose();
636
764
  this.videoComposer = null;
637
- }
638
- if (this.audioContext.state !== "closed") await this.audioContext.close();
765
+ if (this.audioContext.state !== "closed") await this.audioContext.close();
766
+ })();
767
+ return this.disposePromise;
639
768
  }
640
- onCacheCover = () => {
641
- if (this.fsm.snapshot.state === PlaybackState.Idle && this.currentTimeUs === 0) {
642
- const token = this.fsm.snapshot.token;
643
- void this.renderCurrentFrame(0, { mode: "blocking" }).catch(
644
- (error) => this.handlePlaybackError(error, token, {
645
- logPrefix: "[PlaybackController] Cover render failed:",
646
- emitPlaybackError: true,
647
- onError: { type: PlaybackActionType.Pause }
648
- })
649
- );
650
- }
651
- };
652
769
  onModelSet = () => {
770
+ this.lastPresentedKey = null;
771
+ this.reportedLayerFailures.clear();
653
772
  if (!this.videoComposer || !this.orchestrator.compositionModel) return;
654
773
  this.dispatch({ type: PlaybackActionType.ModelSet });
655
774
  const model = this.orchestrator.compositionModel;
@@ -662,18 +781,14 @@ class PlaybackController {
662
781
  if (!this.orchestrator.cacheManager.isExporting) {
663
782
  void this.audioSession.ensureAudioForTime(this.currentTimeUs, { mode: "probe" });
664
783
  }
665
- const token = this.fsm.snapshot.token;
666
- void this.renderCurrentFrame(this.currentTimeUs, { mode: "blocking" }).catch(
667
- (error) => this.handlePlaybackError(error, token, {
668
- logPrefix: "[PlaybackController] Model render failed:",
669
- emitPlaybackError: true,
670
- onError: { type: PlaybackActionType.Pause }
671
- })
672
- );
784
+ this.ready = this.seek(this.currentTimeUs);
785
+ this.ready.catch(() => {
786
+ });
673
787
  };
674
788
  setupEventListeners() {
675
- this.eventBus.on(MeframeEvent.CacheCover, this.onCacheCover);
676
789
  this.eventBus.on(MeframeEvent.ModelSet, this.onModelSet);
790
+ this.eventBus.on(MeframeEvent.PatchApplied, this.onPatchApplied);
791
+ this.eventBus.on(MeframeEvent.ResourceStageChange, this.onResourceStageChange);
677
792
  }
678
793
  isVideoResourceReadyAtTime(timeUs) {
679
794
  const model = this.orchestrator.compositionModel;