@meframe/core 0.6.13 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +47 -0
- package/README.md +17 -5
- package/dist/Meframe.d.ts +14 -3
- package/dist/Meframe.d.ts.map +1 -1
- package/dist/Meframe.js +22 -12
- package/dist/Meframe.js.map +1 -1
- package/dist/cache/CacheManager.d.ts +2 -0
- package/dist/cache/CacheManager.d.ts.map +1 -1
- package/dist/cache/CacheManager.js +5 -0
- package/dist/cache/CacheManager.js.map +1 -1
- package/dist/cache/l1/VideoL1Cache.d.ts +2 -0
- package/dist/cache/l1/VideoL1Cache.d.ts.map +1 -1
- package/dist/cache/l1/VideoL1Cache.js +13 -7
- package/dist/cache/l1/VideoL1Cache.js.map +1 -1
- package/dist/cache/resource/ResourceCache.d.ts +0 -12
- package/dist/cache/resource/ResourceCache.d.ts.map +1 -1
- package/dist/cache/resource/ResourceCache.js +0 -24
- package/dist/cache/resource/ResourceCache.js.map +1 -1
- package/dist/config/defaults.d.ts.map +1 -1
- package/dist/config/defaults.js +4 -1
- package/dist/config/defaults.js.map +1 -1
- package/dist/config/index.d.ts +1 -1
- package/dist/config/index.d.ts.map +1 -1
- package/dist/config/types.d.ts +29 -0
- package/dist/config/types.d.ts.map +1 -1
- package/dist/config/validation.d.ts.map +1 -1
- package/dist/config/validation.js +3 -0
- package/dist/config/validation.js.map +1 -1
- package/dist/controllers/PlaybackController.d.ts +38 -9
- package/dist/controllers/PlaybackController.d.ts.map +1 -1
- package/dist/controllers/PlaybackController.js +269 -154
- package/dist/controllers/PlaybackController.js.map +1 -1
- package/dist/controllers/PlaybackStateMachine.d.ts.map +1 -1
- package/dist/controllers/PlaybackStateMachine.js +2 -1
- package/dist/controllers/PlaybackStateMachine.js.map +1 -1
- package/dist/controllers/types.d.ts +10 -2
- package/dist/controllers/types.d.ts.map +1 -1
- package/dist/controllers/types.js.map +1 -1
- package/dist/event/events.d.ts +2 -0
- package/dist/event/events.d.ts.map +1 -1
- package/dist/event/events.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/model/CompositionModel.d.ts +0 -1
- package/dist/model/CompositionModel.d.ts.map +1 -1
- package/dist/model/CompositionModel.js +0 -6
- package/dist/model/CompositionModel.js.map +1 -1
- package/dist/model/patch.js +12 -12
- package/dist/model/patch.js.map +1 -1
- 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
- package/dist/node_modules/.pnpm/mp4-muxer@5.2.2_patch_hash_452653ac44da4ef32d244694e500e34d084eaa3c4232515ddec962eacc5f30ea/node_modules/mp4-muxer/build/mp4-muxer.js.map +1 -0
- package/dist/orchestrator/AudioExportSession.d.ts +28 -3
- package/dist/orchestrator/AudioExportSession.d.ts.map +1 -1
- package/dist/orchestrator/AudioExportSession.js +131 -15
- package/dist/orchestrator/AudioExportSession.js.map +1 -1
- package/dist/orchestrator/AudioPreviewSession.d.ts +6 -1
- package/dist/orchestrator/AudioPreviewSession.d.ts.map +1 -1
- package/dist/orchestrator/AudioPreviewSession.js +57 -18
- package/dist/orchestrator/AudioPreviewSession.js.map +1 -1
- package/dist/orchestrator/AudioWindowPreparer.d.ts +5 -4
- package/dist/orchestrator/AudioWindowPreparer.d.ts.map +1 -1
- package/dist/orchestrator/AudioWindowPreparer.js +76 -28
- package/dist/orchestrator/AudioWindowPreparer.js.map +1 -1
- package/dist/orchestrator/CompositionPlanner.d.ts +5 -2
- package/dist/orchestrator/CompositionPlanner.d.ts.map +1 -1
- package/dist/orchestrator/CompositionPlanner.js +8 -3
- package/dist/orchestrator/CompositionPlanner.js.map +1 -1
- package/dist/orchestrator/ExportScheduler.d.ts +1 -0
- package/dist/orchestrator/ExportScheduler.d.ts.map +1 -1
- package/dist/orchestrator/ExportScheduler.js +177 -106
- package/dist/orchestrator/ExportScheduler.js.map +1 -1
- package/dist/orchestrator/Orchestrator.d.ts +30 -4
- package/dist/orchestrator/Orchestrator.d.ts.map +1 -1
- package/dist/orchestrator/Orchestrator.js +264 -111
- package/dist/orchestrator/Orchestrator.js.map +1 -1
- package/dist/orchestrator/PreviewFrameScheduler.d.ts +21 -1
- package/dist/orchestrator/PreviewFrameScheduler.d.ts.map +1 -1
- package/dist/orchestrator/PreviewFrameScheduler.js +129 -30
- package/dist/orchestrator/PreviewFrameScheduler.js.map +1 -1
- package/dist/orchestrator/VideoWindowDecodeSession.d.ts +22 -1
- package/dist/orchestrator/VideoWindowDecodeSession.d.ts.map +1 -1
- package/dist/orchestrator/VideoWindowDecodeSession.js +426 -198
- package/dist/orchestrator/VideoWindowDecodeSession.js.map +1 -1
- package/dist/orchestrator/aac-window-timeline.d.ts +1 -1
- package/dist/orchestrator/aac-window-timeline.d.ts.map +1 -1
- package/dist/orchestrator/aac-window-timeline.js +10 -2
- package/dist/orchestrator/aac-window-timeline.js.map +1 -1
- package/dist/orchestrator/types.d.ts +5 -1
- package/dist/orchestrator/types.d.ts.map +1 -1
- package/dist/stages/compose/FrameRateConverter.d.ts +2 -1
- package/dist/stages/compose/FrameRateConverter.d.ts.map +1 -1
- package/dist/stages/compose/LayerRenderPolicy.d.ts +14 -0
- package/dist/stages/compose/LayerRenderPolicy.d.ts.map +1 -0
- package/dist/stages/compose/LayerRenderPolicy.js +18 -0
- package/dist/stages/compose/LayerRenderPolicy.js.map +1 -0
- package/dist/stages/compose/OfflineAudioMixer.d.ts +2 -0
- package/dist/stages/compose/OfflineAudioMixer.d.ts.map +1 -1
- package/dist/stages/compose/OfflineAudioMixer.js +14 -2
- package/dist/stages/compose/OfflineAudioMixer.js.map +1 -1
- package/dist/stages/compose/OwnedFrameTransform.d.ts +52 -0
- package/dist/stages/compose/OwnedFrameTransform.d.ts.map +1 -0
- package/dist/stages/compose/OwnedFrameTransform.js +154 -0
- package/dist/stages/compose/OwnedFrameTransform.js.map +1 -0
- package/dist/stages/compose/TransitionProcessor.js +0 -1
- package/dist/stages/compose/TransitionProcessor.js.map +1 -1
- package/dist/stages/compose/VideoComposer.d.ts +12 -2
- package/dist/stages/compose/VideoComposer.d.ts.map +1 -1
- package/dist/stages/compose/VideoComposer.js +100 -92
- package/dist/stages/compose/VideoComposer.js.map +1 -1
- package/dist/stages/compose/text-renderers/basic-text-renderer.d.ts.map +1 -1
- package/dist/stages/compose/text-renderers/basic-text-renderer.js +24 -21
- package/dist/stages/compose/text-renderers/basic-text-renderer.js.map +1 -1
- package/dist/stages/compose/text-renderers/caption-stagger-entrance-renderer.d.ts.map +1 -1
- package/dist/stages/compose/text-renderers/caption-stagger-entrance-renderer.js +110 -99
- package/dist/stages/compose/text-renderers/caption-stagger-entrance-renderer.js.map +1 -1
- package/dist/stages/compose/text-renderers/character-ktv-renderer.d.ts.map +1 -1
- package/dist/stages/compose/text-renderers/character-ktv-renderer.js +41 -38
- package/dist/stages/compose/text-renderers/character-ktv-renderer.js.map +1 -1
- package/dist/stages/compose/text-renderers/word-by-word-renderer.d.ts.map +1 -1
- package/dist/stages/compose/text-renderers/word-by-word-renderer.js +47 -39
- package/dist/stages/compose/text-renderers/word-by-word-renderer.js.map +1 -1
- package/dist/stages/compose/text-renderers/word-fancy-renderer.d.ts.map +1 -1
- package/dist/stages/compose/text-renderers/word-fancy-renderer.js +54 -48
- package/dist/stages/compose/text-renderers/word-fancy-renderer.js.map +1 -1
- package/dist/stages/compose/text-utils/text-metrics.d.ts.map +1 -1
- package/dist/stages/compose/text-utils/text-metrics.js +6 -4
- package/dist/stages/compose/text-utils/text-metrics.js.map +1 -1
- package/dist/stages/compose/types.d.ts +12 -0
- package/dist/stages/compose/types.d.ts.map +1 -1
- package/dist/stages/decode/BaseDecoder.d.ts +5 -0
- package/dist/stages/decode/BaseDecoder.d.ts.map +1 -1
- package/dist/stages/decode/BaseDecoder.js +52 -10
- package/dist/stages/decode/BaseDecoder.js.map +1 -1
- package/dist/stages/decode/preview-video-decoder.d.ts +48 -2
- package/dist/stages/decode/preview-video-decoder.d.ts.map +1 -1
- package/dist/stages/decode/preview-video-decoder.js +241 -71
- package/dist/stages/decode/preview-video-decoder.js.map +1 -1
- package/dist/stages/decode/video-decoder.d.ts +2 -11
- package/dist/stages/decode/video-decoder.d.ts.map +1 -1
- package/dist/stages/decode/video-decoder.js +60 -61
- package/dist/stages/decode/video-decoder.js.map +1 -1
- package/dist/stages/encode/BaseEncoder.d.ts +9 -2
- package/dist/stages/encode/BaseEncoder.d.ts.map +1 -1
- package/dist/stages/encode/BaseEncoder.js +90 -59
- package/dist/stages/encode/BaseEncoder.js.map +1 -1
- package/dist/stages/load/ResourceLoader.d.ts +69 -8
- package/dist/stages/load/ResourceLoader.d.ts.map +1 -1
- package/dist/stages/load/ResourceLoader.js +248 -67
- package/dist/stages/load/ResourceLoader.js.map +1 -1
- package/dist/stages/load/TaskManager.d.ts.map +1 -1
- package/dist/stages/load/TaskManager.js +9 -3
- package/dist/stages/load/TaskManager.js.map +1 -1
- package/dist/stages/load/types.d.ts +2 -2
- package/dist/stages/load/types.d.ts.map +1 -1
- package/dist/stages/mux/MP4Muxer.d.ts +7 -1
- package/dist/stages/mux/MP4Muxer.d.ts.map +1 -1
- package/dist/stages/mux/MP4Muxer.js +8 -10
- package/dist/stages/mux/MP4Muxer.js.map +1 -1
- package/dist/stages/mux/MuxManager.d.ts +7 -0
- package/dist/stages/mux/MuxManager.d.ts.map +1 -1
- package/dist/stages/mux/MuxManager.js +9 -0
- package/dist/stages/mux/MuxManager.js.map +1 -1
- package/dist/types.d.ts +1 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/utils/errors.d.ts +2 -0
- package/dist/utils/errors.d.ts.map +1 -1
- package/dist/utils/errors.js +10 -1
- package/dist/utils/errors.js.map +1 -1
- package/dist/utils/until-aborted.d.ts +8 -0
- package/dist/utils/until-aborted.d.ts.map +1 -0
- package/dist/utils/until-aborted.js +33 -0
- package/dist/utils/until-aborted.js.map +1 -0
- package/dist/worker/WorkerChannel.d.ts.map +1 -1
- package/dist/worker/WorkerChannel.js +45 -10
- package/dist/worker/WorkerChannel.js.map +1 -1
- package/dist/worker/worker-manifest.js +1 -1
- package/dist/worker/worker-manifest.js.map +1 -1
- package/dist/workers/stages/export/{export.worker.C8jKSbVj.js → export.worker.BG8HA7dY.js} +745 -450
- package/dist/workers/stages/export/export.worker.BG8HA7dY.js.map +1 -0
- package/dist/workers/worker-manifest.json +1 -1
- package/package.json +1 -1
- package/dist/node_modules/.pnpm/mp4-muxer@5.2.2/node_modules/mp4-muxer/build/mp4-muxer.js.map +0 -1
- package/dist/workers/stages/export/export.worker.C8jKSbVj.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,53 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.7.0] - 2026-11-24
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- `PreviewHandle.ready` settles when the first presentation at the start position is composed; `seek()` returns a promise that settles once the presentation for its target is composed, or rejects with `AbortError` when a later seek replaced it.
|
|
15
|
+
- `PlaybackTimeUpdate.outputLatencyUs`: the playback `AudioContext`'s `baseLatency + outputLatency`.
|
|
16
|
+
- `encode.audio.encoderFactory` lets the host supply the export AAC encoder; the muxer writes an edit list for the exact PCM interval the encoder was fed. `Meframe.setCompositionModel(model, { startUs })` loads the clip active at `startUs`.
|
|
17
|
+
- Preview registers configured fonts on `document.fonts`.
|
|
18
|
+
- `Meframe.reloadResource(resourceId)` loads a resource of the current model again without a new model. The engine drops what it parsed from the old bytes and calls `load.ensureCached` before it reads cached bytes again. It replaces reaching into `orchestrator.resourceLoader.load`.
|
|
19
|
+
- `preview.layerFailure: 'skip-layer' | 'pause'` (default `'skip-layer'`) chooses what preview does when a visible layer throws while a frame is composed. Exported as `PreviewLayerFailurePolicy`.
|
|
20
|
+
|
|
21
|
+
### Changed
|
|
22
|
+
|
|
23
|
+
- Continuous preview keeps its decoder, the GOP bytes it read and the frames past a window's end for the next forward window, instead of decoding again from the keyframe on every preheat. A running decode is extended in place. Two idle clips stay warm; a cancelled preview (a scrub, an export, a longer pause, a new or patched model) releases them.
|
|
24
|
+
- Preview looks 2 s ahead with a cache of at least 60 frames and 256 MiB, and 1 s below that.
|
|
25
|
+
- Playback does not compose a tick again that resolves to the frame already on the canvas. Transitions, text, transforms, filters and masks are always composed.
|
|
26
|
+
- The continuous preview decoder no longer asks a `prefer-software` decoder for low latency, which turned off FFmpeg's frame threads. Hardware and `no-preference` decoders, scrub and export are unchanged.
|
|
27
|
+
- Disposal is owned and awaited: `Orchestrator`, `ResourceLoader`, `PlaybackController` and decode sessions return promises that settle after in-flight loads, decodes and audio work have drained; native frames, bitmaps and codecs are released by their owner. Cache reads for preview hand out a native clone when the caller owns the frame.
|
|
28
|
+
- Video decode batches wait for `VideoDecoder.flush()`; abort and timeout reject instead of returning a partial batch. Encoders and decoders gain `cancel()`.
|
|
29
|
+
- `ResourceLoader` never deletes the bytes the host owns; corrupted cached bytes are reported instead of deleted. `ResourceCache.deleteResource`, `deleteAudioResource`, `clear` and `CompositionModel.updateResourceState` are removed.
|
|
30
|
+
- A live resource id that arrives with a new type or URI (in `setCompositionModel` or `applyPatch`, or removed and added back with a different URI) is accepted. Its load is cancelled, its index and parsed data are dropped, it becomes `pending`, and it is loaded again: `ensureCached` is called with the new resource even when bytes for the id are already cached. Loads still running for the old source publish nothing. An id added back with the URI it had before removal (undo) keeps using its cached bytes. `setCompositionModel` and `applyPatch` no longer pre-validate identities, and `ResourceLoader.validateResourceIdentities` and `resourcesAfterPatch` are removed. `ResourceSupersededError` is no longer thrown for an identity change; it still ends an export whose source index was replaced again during its one retry.
|
|
31
|
+
- A read or parse failure the engine can attribute to a resource (`ResourceCorruptedError`, not found, empty stream, missing moov, `InvalidStateError` after the host's retries, and range reads while decoding video or reading WAV PCM) sets that resource's state to `error` with the error name as `code`, emits `load:error`, and drops its index and parsed data. The next load of the resource asks the host through `ensureCached` before it uses cached bytes. Nothing is deleted.
|
|
32
|
+
- The muxer keeps every AAC packet (tiny packets are no longer dropped) and `mp4-muxer@5.2.2` is patched (`patches/`) to write audio edit lists.
|
|
33
|
+
- The worker manifest is fetched with `cache: 'no-cache'`.
|
|
34
|
+
- Scrub seeks are no longer coalesced per animation frame; a later seek cancels the previous one through a token. A seek whose target has no frame rejects and clears the canvas, so a frame from another time is not left on screen; a seek replaced by a later one leaves the last presented frame.
|
|
35
|
+
- A visible layer that fails to render: export fails the whole frame. Preview, by default (`preview.layerFailure: 'skip-layer'`), draws the frame without that layer, keeps playing, and reports the failure once per resource (or per clip for layers without a resource) through `playback:error` and `error` with the layer, clip and resource ids. It is reported again after the resource gets a new URI, or after it loads to ready (for example through `reloadResource`) and fails again. If the failed layer is the main video, the background shows through. With `'pause'`, preview fails the frame, reports it and pauses. Every layer is drawn inside its own `save()`/`restore()`, and every compose renderer restores in a `finally`, so a layer that throws mid-draw leaves neither canvas state nor extra levels on the save stack for the next layer or frame.
|
|
36
|
+
- Preview video decode has a 2 s watchdog: when `flush()` does not settle in time the whole batch fails instead of returning partial frames. Windows hardware decode still needs a run on real hardware.
|
|
37
|
+
- A video decode batch whose `flush()` settles without a single frame rejects again, as it did before decode batches awaited `flush()`.
|
|
38
|
+
|
|
39
|
+
### Fixed
|
|
40
|
+
|
|
41
|
+
- Preview no longer decodes a clip's last GOP again from its keyframe when a window reaches the end of the stream: the frames the flush produced past the window's end are kept for the next windows instead of being closed with the decoder. A clip that outlasts its video track (an MP4 whose audio is longer, for example) no longer decodes that GOP again on every preheat either: preview asks for no frame past the track's end, and a decoder that was read to its end is not started again for one.
|
|
42
|
+
- Continuous preview no longer loses the first chunk of the next GOP, its keyframe, when the decoder reaches the window's target while that GOP is being read.
|
|
43
|
+
- Preview frames whose decoder reports no duration are cached for the length of their sample, also after a scrub, and a frame cached too short is replaced. The composition's frame time was used, which left gaps in the cache when it was shorter than the source's.
|
|
44
|
+
- An aborted continuous preview decode ends at once while the decoder is flushing, instead of after the 5 s watchdog, and a frame whose delivery throws is closed.
|
|
45
|
+
- A frame whose composition failed on the cleared canvas is composed again on the next tick, and so is an image layer without its source.
|
|
46
|
+
- A preview request that extends a running decode no longer ends without a frame, or leaves a gap in the cache, when the extension arrives during the final flush, after the decoder gave up frames, or after the decode session stopped.
|
|
47
|
+
- The canvas save stack no longer grows by one level per frame with a wipe transition: the wipe saved again inside the save `composeFrame` already makes for transitions, and only one of the two was restored. Text renderers and `measureTextWidth` restore their state when drawing throws.
|
|
48
|
+
- The frame-rate converter closes buffered source frames and undelivered output when its stream is cancelled or fails. Export worker disposal uses `cancel()` instead of waiting for the encoder to flush. A throwing codec `close()` no longer stops the rest of teardown.
|
|
49
|
+
|
|
50
|
+
### Integration
|
|
51
|
+
|
|
52
|
+
- Mesh, medeo-fe and meframe-service must adapt to async `seek()` / `dispose()`, the failure semantics above and the removed APIs before upgrading.
|
|
53
|
+
- Bytes belong to the host. When a resource's URI changes under the same id, the engine calls `ensureCached` with the new resource; the host compares the URI its cached file came from and downloads again when it differs. Returning without writing new bytes means the engine parses whatever is cached for the id.
|
|
54
|
+
- When a resource reports `resource:state` = `error` for its bytes, the host repairs its cached file (e.g. downloads it again) and calls `Meframe.reloadResource(id)`. A consumer that needs the resource also retries the load on its own; that retry asks `ensureCached` first, so a host that repairs inside `ensureCached` needs no explicit reload. A paused preview shows the repaired resource after the next seek or play.
|
|
55
|
+
- Preview no longer pauses when a layer fails unless the host sets `preview: { layerFailure: 'pause' }` (Mesh sets it). Export fails either way. Windows flush/watchdog and Safari AAC need runs on real hardware before upgrading.
|
|
56
|
+
|
|
10
57
|
## [0.6.13] - 2026-11-02
|
|
11
58
|
|
|
12
59
|
### Fixed
|
package/README.md
CHANGED
|
@@ -56,11 +56,23 @@ export default defineConfig({
|
|
|
56
56
|
`load()` 时仍会检查 OPFS 字节是否存在,缺失时调用宿主重新交付;宿主未写入字节
|
|
57
57
|
则报 `ResourceNotCachedError`。这次检查只查询文件是否存在,不读取完整音频。
|
|
58
58
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
59
|
+
缓存字节归宿主所有,引擎不删除 `resource` 下的文件。同一资源 ID 换了 URI 或类型
|
|
60
|
+
(新模型、`applyPatch`,或删除后用新 URI 加回)时,引擎丢掉这个 ID 已解析的索引和
|
|
61
|
+
数据,把资源置回 `pending` 并重新加载:即使这个 ID 已有缓存字节,也会先用新 URI
|
|
62
|
+
调用 `ensureCached`。宿主要比对缓存文件来自哪个 URI,不一致就重新下载。
|
|
63
|
+
|
|
64
|
+
引擎能归到某个资源的读取或解析失败(文件缺失、内容为空、找不到 moov、宿主重试后
|
|
65
|
+
仍是 `InvalidStateError`,包括解码时的分段读取)会把该资源的 `resource:state` 置为
|
|
66
|
+
`error`(带错误码)并停用它的索引。宿主修好缓存文件后调用
|
|
67
|
+
`Meframe.reloadResource(id)` 重新加载,不需要重设模型。
|
|
68
|
+
|
|
69
|
+
导出的 OPFS 读取恢复会用新索引重算未输出范围、最多重试一次;失败通过
|
|
70
|
+
`export:error` 和导出 Promise 上报。`ResourceSupersededError` 表示处理期间资源
|
|
71
|
+
被替换,不能按用户主动取消的 `AbortError` 忽略。
|
|
72
|
+
|
|
73
|
+
预览时某个可见图层绘制失败,默认(`preview.layerFailure: 'skip-layer'`)这一帧
|
|
74
|
+
不画该图层、继续播放,并按资源(没有资源时按片段)只上报一次;设为 `'pause'`
|
|
75
|
+
则这一帧失败并暂停播放。导出遇到图层失败总是失败。
|
|
64
76
|
|
|
65
77
|
独立音频支持 MP3、MP4/M4A 和小端 RIFF/WAVE:整数 PCM 8/16/24/32 位、
|
|
66
78
|
IEEE 浮点 PCM 32/64 位,以及对应的 WAVE_FORMAT_EXTENSIBLE 子格式。
|
package/dist/Meframe.d.ts
CHANGED
|
@@ -12,8 +12,8 @@ export declare class Meframe {
|
|
|
12
12
|
state: MeframeState;
|
|
13
13
|
/** Configuration - immutable after construction */
|
|
14
14
|
readonly config: ResolvedConfig;
|
|
15
|
-
/** Composition model - managed via setCompositionModel() */
|
|
16
|
-
model: CompositionModel | null;
|
|
15
|
+
/** Composition model - owned by the orchestrator, managed via setCompositionModel() */
|
|
16
|
+
get model(): CompositionModel | null;
|
|
17
17
|
/** Plugin manager for extensions */
|
|
18
18
|
readonly pluginManager: PluginManager;
|
|
19
19
|
/** Event bus for subscribing to Meframe events */
|
|
@@ -72,11 +72,22 @@ export declare class Meframe {
|
|
|
72
72
|
/**
|
|
73
73
|
* Set the composition model
|
|
74
74
|
*/
|
|
75
|
-
setCompositionModel(model: CompositionModel | CompositionModelData
|
|
75
|
+
setCompositionModel(model: CompositionModel | CompositionModelData, options?: {
|
|
76
|
+
startUs?: TimeUs;
|
|
77
|
+
}): Promise<void>;
|
|
76
78
|
/**
|
|
77
79
|
* Apply a patch to the composition model
|
|
78
80
|
*/
|
|
79
81
|
applyPatch(patch: CompositionPatch): Promise<void>;
|
|
82
|
+
/**
|
|
83
|
+
* Load a resource of the current model again, without setting a new model.
|
|
84
|
+
*
|
|
85
|
+
* Call it after repairing the bytes of a resource the engine reported as failed (`resource:state` with `error`). The
|
|
86
|
+
* engine drops what it parsed from the old bytes and calls `load.ensureCached` for the resource before it reads cached bytes
|
|
87
|
+
* again. Resolves when the resource is ready; rejects with the load error when it fails again. A paused preview shows the
|
|
88
|
+
* repaired resource after the next seek or play.
|
|
89
|
+
*/
|
|
90
|
+
reloadResource(resourceId: string): Promise<void>;
|
|
80
91
|
/**
|
|
81
92
|
* Start preview and return a handle for control
|
|
82
93
|
*/
|
package/dist/Meframe.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Meframe.d.ts","sourceRoot":"","sources":["../src/Meframe.ts"],"names":[],"mappings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G,cAAc,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAMvD;;OAEG;IACH,YAAY,CAAC,OAAO,CAAC,EAAE;QACrB,MAAM,CAAC,EAAE,iBAAiB,CAAC;QAC3B,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,SAAS,CAAC,EAAE,OAAO,CAAC;KACrB,GAAG,aAAa;IAqCjB;;;OAGG;IACG,MAAM,CACV,KAAK,EAAE,gBAAgB,GAAG,oBAAoB,EAC9C,OAAO,EAAE,aAAa,GAAG;QAAE,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE,GAC/C,OAAO,CAAC,IAAI,CAAC;IAEV,MAAM,CACV,KAAK,EAAE,gBAAgB,GAAG,oBAAoB,EAC9C,OAAO,EAAE,aAAa,GAAG;QACvB,UAAU,EAAE,QAAQ,CAAC;QACrB,SAAS,EAAE,CAAC,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAC;KACzD,GACA,OAAO,CAAC,IAAI,CAAC;IAoDhB;;OAEG;IACH,YAAY,IAAI,IAAI;IAIpB;;OAEG;IACH,WAAW,IAAI,IAAI;IAInB;;OAEG;IACH,YAAY,IAAI,IAAI;IAIpB;;OAEG;IACH,cAAc,IAAI,OAAO;IAIzB;;OAEG;IACH,cAAc,IAAI,MAAM;IAIxB;;;OAGG;IACG,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAYjC;;OAEG;IACH,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;YAIV,eAAe;IA4B7B;;OAEG;IACH,OAAO,CAAC,QAAQ;IAYhB;;OAEG;IACH,OAAO,CAAC,kBAAkB;IAM1B;;OAEG;IACH,OAAO,CAAC,WAAW;CAWpB"}
|
package/dist/Meframe.js
CHANGED
|
@@ -14,8 +14,10 @@ class Meframe {
|
|
|
14
14
|
state = "idle";
|
|
15
15
|
/** Configuration - immutable after construction */
|
|
16
16
|
config;
|
|
17
|
-
/** Composition model - managed via setCompositionModel() */
|
|
18
|
-
model
|
|
17
|
+
/** Composition model - owned by the orchestrator, managed via setCompositionModel() */
|
|
18
|
+
get model() {
|
|
19
|
+
return this.orchestrator?.compositionModel ?? null;
|
|
20
|
+
}
|
|
19
21
|
/** Plugin manager for extensions */
|
|
20
22
|
pluginManager;
|
|
21
23
|
/** Event bus for subscribing to Meframe events */
|
|
@@ -111,14 +113,13 @@ class Meframe {
|
|
|
111
113
|
/**
|
|
112
114
|
* Set the composition model
|
|
113
115
|
*/
|
|
114
|
-
async setCompositionModel(model) {
|
|
116
|
+
async setCompositionModel(model, options) {
|
|
115
117
|
return this.queueModelOperation(async () => {
|
|
116
118
|
this.ensureNotDestroyed();
|
|
117
|
-
this.playbackController?.
|
|
119
|
+
await this.playbackController?.drain();
|
|
118
120
|
const compositionModel = model instanceof CompositionModel ? model : new CompositionModel(model);
|
|
119
|
-
await this.orchestrator.setCompositionModel(compositionModel);
|
|
121
|
+
await this.orchestrator.setCompositionModel(compositionModel, options);
|
|
120
122
|
this.ensureNotDestroyed();
|
|
121
|
-
this.model = compositionModel;
|
|
122
123
|
this.setState("ready");
|
|
123
124
|
this.eventBus.emit(MeframeEvent.Ready, {
|
|
124
125
|
trackCount: model.tracks.length,
|
|
@@ -141,9 +142,21 @@ class Meframe {
|
|
|
141
142
|
}
|
|
142
143
|
await this.orchestrator.applyPatch(patch);
|
|
143
144
|
this.ensureNotDestroyed();
|
|
144
|
-
this.model = this.orchestrator.compositionModel;
|
|
145
145
|
});
|
|
146
146
|
}
|
|
147
|
+
/**
|
|
148
|
+
* Load a resource of the current model again, without setting a new model.
|
|
149
|
+
*
|
|
150
|
+
* Call it after repairing the bytes of a resource the engine reported as failed (`resource:state` with `error`). The
|
|
151
|
+
* engine drops what it parsed from the old bytes and calls `load.ensureCached` for the resource before it reads cached bytes
|
|
152
|
+
* again. Resolves when the resource is ready; rejects with the load error when it fails again. A paused preview shows the
|
|
153
|
+
* repaired resource after the next seek or play.
|
|
154
|
+
*/
|
|
155
|
+
async reloadResource(resourceId) {
|
|
156
|
+
this.ensureNotDestroyed();
|
|
157
|
+
if (!this.model) throw new Error("No composition model set");
|
|
158
|
+
await this.orchestrator.reloadResource(resourceId);
|
|
159
|
+
}
|
|
147
160
|
/**
|
|
148
161
|
* Start preview and return a handle for control
|
|
149
162
|
*/
|
|
@@ -159,16 +172,14 @@ class Meframe {
|
|
|
159
172
|
this.playbackController = new PlaybackController(this.orchestrator, this.eventBus, {
|
|
160
173
|
canvas,
|
|
161
174
|
startUs: options?.startUs,
|
|
162
|
-
autoStart: options?.autoStart
|
|
175
|
+
autoStart: options?.autoStart,
|
|
176
|
+
layerFailure: this.config.preview?.layerFailure
|
|
163
177
|
});
|
|
164
178
|
}
|
|
165
179
|
const controller = this.playbackController;
|
|
166
180
|
if (!controller) {
|
|
167
181
|
throw new Error("PlaybackController unavailable");
|
|
168
182
|
}
|
|
169
|
-
if (isNewController) {
|
|
170
|
-
void controller.renderCover();
|
|
171
|
-
}
|
|
172
183
|
void controller.preheatNextWindow();
|
|
173
184
|
controller.preheatAudioAt(options?.startUs ?? 0);
|
|
174
185
|
return controller;
|
|
@@ -274,7 +285,6 @@ class Meframe {
|
|
|
274
285
|
await this.pluginManager.disposeAll();
|
|
275
286
|
await this.orchestrator.dispose();
|
|
276
287
|
this.eventBus.dispose();
|
|
277
|
-
this.model = null;
|
|
278
288
|
this.setState("destroyed");
|
|
279
289
|
}
|
|
280
290
|
/**
|
package/dist/Meframe.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Meframe.js","sources":["../src/Meframe.ts"],"sourcesContent":["/**\n * Meframe - Main entry point for the media processing framework\n */\n\nimport type { MeframeConfig, ResolvedConfig, MeframeState, ExportOptions } from './types';\nimport type { CompositionModelData, CompositionPatch, TimeUs } from './model/types';\nimport type { PreviewHandle } from './controllers/types';\nimport type { Plugin } from './plugins/types';\nimport { CompositionModel } from './model/CompositionModel';\nimport { loadConfig } from './config';\nimport { Orchestrator } from './orchestrator/Orchestrator';\nimport { PlaybackController } from './controllers/PlaybackController';\nimport { ExportController } from './controllers/ExportController';\nimport { PluginManager } from './plugins/PluginManager';\nimport { EventBus } from './event/EventBus';\nimport { MeframeEvent, type EventPayloadMap } from './event/events';\nimport { checkBrowserCompatibility } from './utils/platform-utils';\nimport { BrowserCompatibilityError } from './utils/errors';\n\nexport class Meframe {\n /** Current state - managed internally via setState() */\n state: MeframeState = 'idle';\n /** Configuration - immutable after construction */\n readonly config: ResolvedConfig;\n /** Composition model - managed via setCompositionModel() */\n model: CompositionModel | null = null;\n /** Plugin manager for extensions */\n readonly pluginManager: PluginManager;\n /** Event bus for subscribing to Meframe events */\n readonly events: Pick<EventBus<EventPayloadMap>, 'on' | 'off' | 'once'>;\n\n private orchestrator: Orchestrator;\n private eventBus: EventBus<EventPayloadMap>;\n private playbackController: PlaybackController | null = null;\n private exportController: ExportController;\n private exportTask: Promise<Blob | null> | null = null;\n private canvas?: HTMLCanvasElement;\n\n /**\n * Check if current browser is compatible with Meframe\n * Returns compatibility info including browser name, version, and missing features\n */\n static checkCompatibility(): ReturnType<typeof checkBrowserCompatibility> {\n return checkBrowserCompatibility();\n }\n\n private constructor(config: ResolvedConfig) {\n this.config = config;\n this.eventBus = new EventBus<EventPayloadMap>();\n this.events = this.eventBus.asReadonly();\n this.pluginManager = new PluginManager(this);\n\n if (!config.load?.ensureCached) {\n throw new Error(\n 'Meframe requires load.ensureCached — host app must own download (e.g. asset-cache)'\n );\n }\n\n // Initialize orchestrator with configuration and shared eventBus\n // Worker paths are passed via config\n this.orchestrator = new Orchestrator({\n projectId: config.global.projectId,\n maxWorkers: (config as any).maxWorkers,\n cacheConfig: config.cache as any,\n eventBus: this.eventBus,\n workerPath: config.global.workerPath,\n workerExtension: config.global.workerExtension,\n resourceLoader: {\n ensureCached: config.load.ensureCached,\n },\n opfsGateway: config.load?.opfsGateway,\n });\n\n this.exportController = new ExportController(this.orchestrator);\n }\n\n /**\n * Create a new Meframe instance\n */\n static async create(config: MeframeConfig = {}): Promise<Meframe> {\n // Check browser compatibility first\n const compatibility = checkBrowserCompatibility();\n if (!compatibility.webCodecsAvailable || !compatibility.opfsAvailable) {\n throw new BrowserCompatibilityError(compatibility);\n }\n\n // Load and resolve configuration using ConfigLoader\n const resolvedConfig = await loadConfig({ override: config });\n const instance = new Meframe(resolvedConfig);\n await instance.initialize();\n return instance;\n }\n\n /**\n * Initialize the core engine\n */\n private async initialize(): Promise<void> {\n this.setState('loading');\n\n try {\n // Initialize orchestrator (sets up workers and cache)\n await this.orchestrator.initialize();\n\n // Initialize plugins if provided\n const plugins = (this.config as any).plugins;\n if (plugins && Array.isArray(plugins)) {\n for (const plugin of plugins) {\n // Ensure plugin type matches the Plugin interface\n if (plugin && typeof plugin === 'object' && 'name' in plugin && 'install' in plugin) {\n this.pluginManager.register(plugin as Plugin);\n }\n }\n }\n\n this.setState('idle');\n } catch (error) {\n this.setState('error');\n throw error;\n }\n }\n\n private disposing = false;\n private disposeTask: Promise<void> | null = null;\n private modelOperationQueue: Promise<unknown> = Promise.resolve();\n\n private queueModelOperation(work: () => Promise<void>): Promise<void> {\n const task = this.modelOperationQueue.then(work, work);\n this.modelOperationQueue = task.then(\n () => undefined,\n () => undefined\n );\n return task;\n }\n\n getLifecycleSnapshot() {\n return {\n disposed: this.state === 'destroyed',\n ...this.orchestrator.getAudioLifecycleSnapshot(),\n };\n }\n\n /**\n * Set the composition model\n */\n async setCompositionModel(model: CompositionModel | CompositionModelData): Promise<void> {\n return this.queueModelOperation(async () => {\n this.ensureNotDestroyed();\n\n this.playbackController?.pause();\n\n // Convert plain object to CompositionModel instance if needed\n const compositionModel =\n model instanceof CompositionModel ? model : new CompositionModel(model);\n\n // Set the model in orchestrator\n await this.orchestrator.setCompositionModel(compositionModel);\n this.ensureNotDestroyed();\n this.model = compositionModel;\n\n this.setState('ready');\n this.eventBus.emit(MeframeEvent.Ready, {\n trackCount: model.tracks.length,\n clipCount: model.tracks.reduce(\n (acc: number, track: any) => acc + track.clips?.length || 0,\n 0\n ),\n durationUs: model.durationUs,\n });\n // await this.playbackController?.renderCover();\n });\n }\n\n /**\n * Apply a patch to the composition model\n */\n async applyPatch(patch: CompositionPatch): Promise<void> {\n return this.queueModelOperation(async () => {\n this.ensureNotDestroyed();\n\n if (!this.model) {\n throw new Error('No composition model set');\n }\n\n // Apply patch through orchestrator\n await this.orchestrator.applyPatch(patch);\n this.ensureNotDestroyed();\n\n // Patch is applied to the model by orchestrator\n this.model = this.orchestrator.compositionModel!;\n });\n }\n\n /**\n * Start preview and return a handle for control\n */\n startPreview(options?: {\n canvas?: HTMLCanvasElement;\n startUs?: TimeUs;\n autoStart?: boolean;\n }): PreviewHandle {\n this.ensureReady();\n\n // Use provided canvas or the one from config\n const canvas = options?.canvas || this.canvas;\n if (!canvas) {\n throw new Error('Canvas is required for preview');\n }\n\n // Store canvas for later use\n this.canvas = canvas;\n\n const isNewController = !this.playbackController;\n if (isNewController) {\n this.playbackController = new PlaybackController(this.orchestrator as any, this.eventBus, {\n canvas,\n startUs: options?.startUs,\n autoStart: options?.autoStart,\n });\n }\n\n const controller = this.playbackController;\n if (!controller) {\n throw new Error('PlaybackController unavailable');\n }\n\n // First controller: ModelSet already fired before the listener existed, so render\n // cover here. Reused controller: onModelSet already triggered renderCurrentFrame\n // after setCompositionModel — skip renderCover to avoid racing decodeFromResource.\n if (isNewController) {\n void controller.renderCover();\n }\n void controller.preheatNextWindow();\n // Warm up the first audio mix block in the background so the first\n // play/autoplay doesn't stall on a cold block (main cause of preview\n // start latency after the video first frame is already painted).\n controller.preheatAudioAt(options?.startUs ?? 0);\n\n // Return preview handle\n return controller;\n }\n\n /**\n * Export the composition\n * Uses ExportController for direct export\n */\n async export(\n model: CompositionModel | CompositionModelData,\n options: ExportOptions & { exportMode?: 'blob' }\n ): Promise<Blob>;\n\n async export(\n model: CompositionModel | CompositionModelData,\n options: ExportOptions & {\n exportMode: 'stream';\n onMuxData: (data: Uint8Array, position: number) => void;\n }\n ): Promise<null>;\n\n async export(\n model: CompositionModel | CompositionModelData,\n options: ExportOptions\n ): Promise<Blob | null> {\n this.ensureReady();\n if (this.state === 'exporting' || this.exportTask)\n throw new Error('Export already in progress');\n this.playbackController?.pause();\n this.setState('exporting');\n\n console.info('[Meframe] Export is starting, exportMode:', options.exportMode);\n try {\n this.ensureNotDestroyed();\n // Convert plain object to CompositionModel instance if needed\n const compositionModel =\n model instanceof CompositionModel ? model : new CompositionModel(model);\n if (!compositionModel) {\n throw new Error('No export composition model set');\n }\n\n // Delegate to ExportController\n const task =\n options.exportMode === 'stream'\n ? this.exportController.export(\n compositionModel,\n options as ExportOptions & {\n exportMode: 'stream';\n onMuxData: (data: Uint8Array, position: number) => void;\n }\n )\n : this.exportController.export(\n compositionModel,\n options as ExportOptions & { exportMode?: 'blob' }\n );\n\n this.exportTask = task;\n const blob = await task;\n this.ensureNotDestroyed();\n this.setState('ready');\n console.info('[Meframe] Export is completed successfully');\n return blob;\n } catch (error) {\n console.error('[Meframe] Export error:', error);\n if (!this.disposing) this.setState('error');\n throw error;\n } finally {\n this.exportTask = null;\n }\n }\n\n /**\n * Cancel ongoing export operation\n */\n cancelExport(): void {\n this.exportController.cancel();\n }\n\n /**\n * Pause ongoing export operation\n */\n pauseExport(): void {\n this.exportController.pause();\n }\n\n /**\n * Resume paused export operation\n */\n resumeExport(): void {\n this.exportController.resume();\n }\n\n /**\n * Check if export is paused\n */\n isExportPaused(): boolean {\n return this.exportController.isPaused();\n }\n\n /**\n * Get current playback time\n */\n getCurrentTime(): number {\n return this.playbackController?.currentTimeUs || 0;\n }\n\n /**\n * Clear all L1/L2 cache data\n * Useful for debugging or forcing re-render\n */\n async clearCache(): Promise<void> {\n return this.queueModelOperation(async () => {\n this.ensureReady();\n this.playbackController?.stop();\n this.orchestrator.audio.preview.invalidatePreviewMixCache();\n this.orchestrator.audio.prepare.invalidate();\n this.orchestrator.cacheManager.clear();\n await this.orchestrator.audio.preview.drain();\n await this.orchestrator.audio.prepare.drain();\n });\n }\n\n /**\n * Clean up and destroy the instance\n */\n dispose(): Promise<void> {\n return (this.disposeTask ??= this.disposeInstance());\n }\n\n private async disposeInstance(): Promise<void> {\n if (this.state === 'destroyed') return;\n\n this.disposing = true;\n this.exportController.cancel();\n this.orchestrator.audio.prepare.invalidate();\n this.orchestrator.audio.preview.stopPlayback();\n this.orchestrator.audio.preview.invalidatePreviewMixCache();\n this.orchestrator.resourceLoader.dispose();\n await this.modelOperationQueue;\n await this.exportTask?.catch(() => undefined);\n // Stop playback\n this.playbackController?.stop();\n await this.playbackController?.dispose();\n this.playbackController = null;\n\n // Cleanup plugins\n await this.pluginManager.disposeAll();\n\n // Dispose orchestrator (stops workers and clears cache)\n await this.orchestrator.dispose();\n\n // Clear event bus\n this.eventBus.dispose();\n\n this.model = null;\n this.setState('destroyed');\n }\n\n /**\n * Set internal state\n */\n private setState(state: MeframeState): void {\n const oldState = this.state;\n this.state = state;\n\n // Emit state change event\n // Use a generic event for now, can be added to MeframeEvent enum later\n this.eventBus.emit('state:changed' as any, {\n oldState,\n newState: state,\n });\n }\n\n /**\n * Ensure the instance is not destroyed\n */\n private ensureNotDestroyed(): void {\n if (this.state === 'destroyed' || this.disposing) {\n throw new Error('Core instance is destroyed');\n }\n }\n\n /**\n * Ensure the instance is ready\n */\n private ensureReady(): void {\n this.ensureNotDestroyed();\n\n if (!this.model) {\n throw new Error('No composition model set');\n }\n\n if (this.state === 'loading' || this.state === 'idle') {\n throw new Error('Core is not ready');\n }\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;AAmBO,MAAM,QAAQ;AAAA;AAAA,EAEnB,QAAsB;AAAA;AAAA,EAEb;AAAA;AAAA,EAET,QAAiC;AAAA;AAAA,EAExB;AAAA;AAAA,EAEA;AAAA,EAED;AAAA,EACA;AAAA,EACA,qBAAgD;AAAA,EAChD;AAAA,EACA,aAA0C;AAAA,EAC1C;AAAA;AAAA;AAAA;AAAA;AAAA,EAMR,OAAO,qB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7C,QAAI,KAAK,UAAU,YAAa;AAEhC,SAAK,YAAY;AACjB,SAAK,iBAAiB,OAAA;AACtB,SAAK,aAAa,MAAM,QAAQ,WAAA;AAChC,SAAK,aAAa,MAAM,QAAQ,aAAA;AAChC,SAAK,aAAa,MAAM,QAAQ,0BAAA;AAChC,SAAK,aAAa,eAAe,QAAA;AACjC,UAAM,KAAK;AACX,UAAM,KAAK,YAAY,MAAM,MAAM,MAAS;AAE5C,SAAK,oBAAoB,KAAA;AACzB,UAAM,KAAK,oBAAoB,QAAA;AAC/B,SAAK,qBAAqB;AAG1B,UAAM,KAAK,cAAc,WAAA;AAGzB,UAAM,KAAK,aAAa,QAAA;AAGxB,SAAK,SAAS,QAAA;AAEd,SAAK,QAAQ;AACb,SAAK,SAAS,WAAW;AAAA,EAC3B;AAAA;AAAA;AAAA;AAAA,EAKQ,SAAS,OAA2B;AAC1C,UAAM,WAAW,KAAK;AACtB,SAAK,QAAQ;AAIb,SAAK,SAAS,KAAK,iBAAwB;AAAA,MACzC;AAAA,MACA,UAAU;AAAA,IAAA,CACX;AAAA,EACH;AAAA;AAAA;AAAA;AAAA,EAKQ,qBAA2B;AACjC,QAAI,KAAK,UAAU,eAAe,KAAK,WAAW;AAChD,YAAM,IAAI,MAAM,4BAA4B;AAAA,IAC9C;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKQ,cAAoB;AAC1B,SAAK,mBAAA;AAEL,QAAI,CAAC,KAAK,OAAO;AACf,YAAM,IAAI,MAAM,0BAA0B;AAAA,IAC5C;AAEA,QAAI,KAAK,UAAU,aAAa,KAAK,UAAU,QAAQ;AACrD,YAAM,IAAI,MAAM,mBAAmB;AAAA,IACrC;AAAA,EACF;AACF;"}
|
|
1
|
+
{"version":3,"file":"Meframe.js","sources":["../src/Meframe.ts"],"sourcesContent":["/**\n * Meframe - Main entry point for the media processing framework\n */\n\nimport type { MeframeConfig, ResolvedConfig, MeframeState, ExportOptions } from './types';\nimport type { CompositionModelData, CompositionPatch, TimeUs } from './model/types';\nimport type { PreviewHandle } from './controllers/types';\nimport type { Plugin } from './plugins/types';\nimport { CompositionModel } from './model/CompositionModel';\nimport { loadConfig } from './config';\nimport { Orchestrator } from './orchestrator/Orchestrator';\nimport { PlaybackController } from './controllers/PlaybackController';\nimport { ExportController } from './controllers/ExportController';\nimport { PluginManager } from './plugins/PluginManager';\nimport { EventBus } from './event/EventBus';\nimport { MeframeEvent, type EventPayloadMap } from './event/events';\nimport { checkBrowserCompatibility } from './utils/platform-utils';\nimport { BrowserCompatibilityError } from './utils/errors';\n\nexport class Meframe {\n /** Current state - managed internally via setState() */\n state: MeframeState = 'idle';\n /** Configuration - immutable after construction */\n readonly config: ResolvedConfig;\n /** Composition model - owned by the orchestrator, managed via setCompositionModel() */\n get model(): CompositionModel | null {\n return this.orchestrator?.compositionModel ?? null;\n }\n /** Plugin manager for extensions */\n readonly pluginManager: PluginManager;\n /** Event bus for subscribing to Meframe events */\n readonly events: Pick<EventBus<EventPayloadMap>, 'on' | 'off' | 'once'>;\n\n private orchestrator: Orchestrator;\n private eventBus: EventBus<EventPayloadMap>;\n private playbackController: PlaybackController | null = null;\n private exportController: ExportController;\n private exportTask: Promise<Blob | null> | null = null;\n private canvas?: HTMLCanvasElement;\n\n /**\n * Check if current browser is compatible with Meframe\n * Returns compatibility info including browser name, version, and missing features\n */\n static checkCompatibility(): ReturnType<typeof checkBrowserCompatibility> {\n return checkBrowserCompatibility();\n }\n\n private constructor(config: ResolvedConfig) {\n this.config = config;\n this.eventBus = new EventBus<EventPayloadMap>();\n this.events = this.eventBus.asReadonly();\n this.pluginManager = new PluginManager(this);\n\n if (!config.load?.ensureCached) {\n throw new Error(\n 'Meframe requires load.ensureCached — host app must own download (e.g. asset-cache)'\n );\n }\n\n // Initialize orchestrator with configuration and shared eventBus\n // Worker paths are passed via config\n this.orchestrator = new Orchestrator({\n projectId: config.global.projectId,\n maxWorkers: (config as any).maxWorkers,\n cacheConfig: config.cache as any,\n eventBus: this.eventBus,\n workerPath: config.global.workerPath,\n workerExtension: config.global.workerExtension,\n resourceLoader: {\n ensureCached: config.load.ensureCached,\n },\n opfsGateway: config.load?.opfsGateway,\n });\n\n this.exportController = new ExportController(this.orchestrator);\n }\n\n /**\n * Create a new Meframe instance\n */\n static async create(config: MeframeConfig = {}): Promise<Meframe> {\n // Check browser compatibility first\n const compatibility = checkBrowserCompatibility();\n if (!compatibility.webCodecsAvailable || !compatibility.opfsAvailable) {\n throw new BrowserCompatibilityError(compatibility);\n }\n\n // Load and resolve configuration using ConfigLoader\n const resolvedConfig = await loadConfig({ override: config });\n const instance = new Meframe(resolvedConfig);\n await instance.initialize();\n return instance;\n }\n\n /**\n * Initialize the core engine\n */\n private async initialize(): Promise<void> {\n this.setState('loading');\n\n try {\n // Initialize orchestrator (sets up workers and cache)\n await this.orchestrator.initialize();\n\n // Initialize plugins if provided\n const plugins = (this.config as any).plugins;\n if (plugins && Array.isArray(plugins)) {\n for (const plugin of plugins) {\n // Ensure plugin type matches the Plugin interface\n if (plugin && typeof plugin === 'object' && 'name' in plugin && 'install' in plugin) {\n this.pluginManager.register(plugin as Plugin);\n }\n }\n }\n\n this.setState('idle');\n } catch (error) {\n this.setState('error');\n throw error;\n }\n }\n\n private disposing = false;\n private disposeTask: Promise<void> | null = null;\n private modelOperationQueue: Promise<unknown> = Promise.resolve();\n\n private queueModelOperation(work: () => Promise<void>): Promise<void> {\n const task = this.modelOperationQueue.then(work, work);\n this.modelOperationQueue = task.then(\n () => undefined,\n () => undefined\n );\n return task;\n }\n\n getLifecycleSnapshot() {\n return {\n disposed: this.state === 'destroyed',\n ...this.orchestrator.getAudioLifecycleSnapshot(),\n };\n }\n\n /**\n * Set the composition model\n */\n async setCompositionModel(\n model: CompositionModel | CompositionModelData,\n options?: { startUs?: TimeUs }\n ): Promise<void> {\n return this.queueModelOperation(async () => {\n this.ensureNotDestroyed();\n\n await this.playbackController?.drain();\n\n // Convert plain object to CompositionModel instance if needed\n const compositionModel =\n model instanceof CompositionModel ? model : new CompositionModel(model);\n\n // Set the model in orchestrator\n await this.orchestrator.setCompositionModel(compositionModel, options);\n this.ensureNotDestroyed();\n\n this.setState('ready');\n this.eventBus.emit(MeframeEvent.Ready, {\n trackCount: model.tracks.length,\n clipCount: model.tracks.reduce(\n (acc: number, track: any) => acc + track.clips?.length || 0,\n 0\n ),\n durationUs: model.durationUs,\n });\n // await this.playbackController?.renderCover();\n });\n }\n\n /**\n * Apply a patch to the composition model\n */\n async applyPatch(patch: CompositionPatch): Promise<void> {\n return this.queueModelOperation(async () => {\n this.ensureNotDestroyed();\n\n if (!this.model) {\n throw new Error('No composition model set');\n }\n\n // Apply patch through orchestrator\n await this.orchestrator.applyPatch(patch);\n this.ensureNotDestroyed();\n });\n }\n\n /**\n * Load a resource of the current model again, without setting a new model.\n *\n * Call it after repairing the bytes of a resource the engine reported as failed (`resource:state` with `error`). The\n * engine drops what it parsed from the old bytes and calls `load.ensureCached` for the resource before it reads cached bytes\n * again. Resolves when the resource is ready; rejects with the load error when it fails again. A paused preview shows the\n * repaired resource after the next seek or play.\n */\n async reloadResource(resourceId: string): Promise<void> {\n this.ensureNotDestroyed();\n if (!this.model) throw new Error('No composition model set');\n await this.orchestrator.reloadResource(resourceId);\n }\n\n /**\n * Start preview and return a handle for control\n */\n startPreview(options?: {\n canvas?: HTMLCanvasElement;\n startUs?: TimeUs;\n autoStart?: boolean;\n }): PreviewHandle {\n this.ensureReady();\n\n // Use provided canvas or the one from config\n const canvas = options?.canvas || this.canvas;\n if (!canvas) {\n throw new Error('Canvas is required for preview');\n }\n\n // Store canvas for later use\n this.canvas = canvas;\n\n const isNewController = !this.playbackController;\n if (isNewController) {\n this.playbackController = new PlaybackController(this.orchestrator as any, this.eventBus, {\n canvas,\n startUs: options?.startUs,\n autoStart: options?.autoStart,\n layerFailure: this.config.preview?.layerFailure,\n });\n }\n\n const controller = this.playbackController;\n if (!controller) {\n throw new Error('PlaybackController unavailable');\n }\n\n void controller.preheatNextWindow();\n // Warm up the first audio mix block in the background so the first\n // play/autoplay doesn't stall on a cold block (main cause of preview\n // start latency after the video first frame is already painted).\n controller.preheatAudioAt(options?.startUs ?? 0);\n\n // Return preview handle\n return controller;\n }\n\n /**\n * Export the composition\n * Uses ExportController for direct export\n */\n async export(\n model: CompositionModel | CompositionModelData,\n options: ExportOptions & { exportMode?: 'blob' }\n ): Promise<Blob>;\n\n async export(\n model: CompositionModel | CompositionModelData,\n options: ExportOptions & {\n exportMode: 'stream';\n onMuxData: (data: Uint8Array, position: number) => void;\n }\n ): Promise<null>;\n\n async export(\n model: CompositionModel | CompositionModelData,\n options: ExportOptions\n ): Promise<Blob | null> {\n this.ensureReady();\n if (this.state === 'exporting' || this.exportTask)\n throw new Error('Export already in progress');\n this.playbackController?.pause();\n this.setState('exporting');\n\n console.info('[Meframe] Export is starting, exportMode:', options.exportMode);\n try {\n this.ensureNotDestroyed();\n // Convert plain object to CompositionModel instance if needed\n const compositionModel =\n model instanceof CompositionModel ? model : new CompositionModel(model);\n if (!compositionModel) {\n throw new Error('No export composition model set');\n }\n\n // Delegate to ExportController\n const task =\n options.exportMode === 'stream'\n ? this.exportController.export(\n compositionModel,\n options as ExportOptions & {\n exportMode: 'stream';\n onMuxData: (data: Uint8Array, position: number) => void;\n }\n )\n : this.exportController.export(\n compositionModel,\n options as ExportOptions & { exportMode?: 'blob' }\n );\n\n this.exportTask = task;\n const blob = await task;\n this.ensureNotDestroyed();\n this.setState('ready');\n console.info('[Meframe] Export is completed successfully');\n return blob;\n } catch (error) {\n console.error('[Meframe] Export error:', error);\n if (!this.disposing) this.setState('error');\n throw error;\n } finally {\n this.exportTask = null;\n }\n }\n\n /**\n * Cancel ongoing export operation\n */\n cancelExport(): void {\n this.exportController.cancel();\n }\n\n /**\n * Pause ongoing export operation\n */\n pauseExport(): void {\n this.exportController.pause();\n }\n\n /**\n * Resume paused export operation\n */\n resumeExport(): void {\n this.exportController.resume();\n }\n\n /**\n * Check if export is paused\n */\n isExportPaused(): boolean {\n return this.exportController.isPaused();\n }\n\n /**\n * Get current playback time\n */\n getCurrentTime(): number {\n return this.playbackController?.currentTimeUs || 0;\n }\n\n /**\n * Clear all L1/L2 cache data\n * Useful for debugging or forcing re-render\n */\n async clearCache(): Promise<void> {\n return this.queueModelOperation(async () => {\n this.ensureReady();\n this.playbackController?.stop();\n this.orchestrator.audio.preview.invalidatePreviewMixCache();\n this.orchestrator.audio.prepare.invalidate();\n this.orchestrator.cacheManager.clear();\n await this.orchestrator.audio.preview.drain();\n await this.orchestrator.audio.prepare.drain();\n });\n }\n\n /**\n * Clean up and destroy the instance\n */\n dispose(): Promise<void> {\n return (this.disposeTask ??= this.disposeInstance());\n }\n\n private async disposeInstance(): Promise<void> {\n if (this.state === 'destroyed') return;\n\n this.disposing = true;\n this.exportController.cancel();\n this.orchestrator.audio.prepare.invalidate();\n this.orchestrator.audio.preview.stopPlayback();\n this.orchestrator.audio.preview.invalidatePreviewMixCache();\n this.orchestrator.resourceLoader.dispose();\n await this.modelOperationQueue;\n await this.exportTask?.catch(() => undefined);\n // Stop playback\n this.playbackController?.stop();\n await this.playbackController?.dispose();\n this.playbackController = null;\n\n // Cleanup plugins\n await this.pluginManager.disposeAll();\n\n // Dispose orchestrator (stops workers and clears cache)\n await this.orchestrator.dispose();\n\n // Clear event bus\n this.eventBus.dispose();\n\n this.setState('destroyed');\n }\n\n /**\n * Set internal state\n */\n private setState(state: MeframeState): void {\n const oldState = this.state;\n this.state = state;\n\n // Emit state change event\n // Use a generic event for now, can be added to MeframeEvent enum later\n this.eventBus.emit('state:changed' as any, {\n oldState,\n newState: state,\n });\n }\n\n /**\n * Ensure the instance is not destroyed\n */\n private ensureNotDestroyed(): void {\n if (this.state === 'destroyed' || this.disposing) {\n throw new Error('Core instance is destroyed');\n }\n }\n\n /**\n * Ensure the instance is ready\n */\n private ensureReady(): void {\n this.ensureNotDestroyed();\n\n if (!this.model) {\n throw new Error('No composition model set');\n }\n\n if (this.state === 'loading' || this.state === 'idle')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eAAe,KAAK,WAAW;AAChD,YAAM,IAAI,MAAM,4BAA4B;AAAA,IAC9C;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKQ,cAAoB;AAC1B,SAAK,mBAAA;AAEL,QAAI,CAAC,KAAK,OAAO;AACf,YAAM,IAAI,MAAM,0BAA0B;AAAA,IAC5C;AAEA,QAAI,KAAK,UAAU,aAAa,KAAK,UAAU,QAAQ;AACrD,YAAM,IAAI,MAAM,mBAAmB;AAAA,IACrC;AAAA,EACF;AACF;"}
|
|
@@ -128,6 +128,8 @@ export declare class CacheManager {
|
|
|
128
128
|
* @param globalTimeUs - Global timestamp for event emission and window management
|
|
129
129
|
*/
|
|
130
130
|
addFrame(frame: VideoFrame, clipId: string, frameDuration: TimeUs, trackId: string, globalTimeUs: TimeUs): RcFrame;
|
|
131
|
+
/** A caller that owns the frame gets a native clone it closes; otherwise the cache entry itself is returned. */
|
|
132
|
+
cloneForCaller(frame: RcFrame | null, owned: boolean): RcFrame | VideoFrame | null;
|
|
131
133
|
/**
|
|
132
134
|
* Get frame from L1 cache
|
|
133
135
|
* @param timeUs - Clip-relative timestamp (0-based)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CacheManager.d.ts","sourceRoot":"","sources":["../../src/cache/CacheManager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AACnC,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEjD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAQvD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM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,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAInD;;OAEG;IACH,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAIxC;;OAEG;IACH,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO;IAIpC,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO;IAI5F;;;;OAIG;IACH,gBAAgB,CACd,MAAM,EAAE,MAAM,EACd,OAAO,GAAE;QAAE,aAAa,CAAC,EAAE,MAAM,CAAC;QAAC,SAAS,CAAC,EAAE,MAAM,CAAC;QAAC,WAAW,CAAC,EAAE,MAAM,CAAA;KAAO,GACjF,OAAO,CAAC,OAAO,CAAC;IA0CnB,eAAe,IAAI,IAAI;IAIvB,KAAK,IAAI,IAAI;IAKb,WAAW;;;IAMX;;;OAGG;IACH,uBAAuB,CAAC,MAAM,EAAE,MAAM,EAAE,gBAAgB,EAAE,MAAM,GAAG,IAAI;CAsBxE"}
|
|
@@ -159,6 +159,11 @@ class CacheManager {
|
|
|
159
159
|
});
|
|
160
160
|
return rcFrame;
|
|
161
161
|
}
|
|
162
|
+
/** A caller that owns the frame gets a native clone it closes; otherwise the cache entry itself is returned. */
|
|
163
|
+
cloneForCaller(frame, owned) {
|
|
164
|
+
if (!frame || !owned) return frame;
|
|
165
|
+
return frame.use((value) => value.clone());
|
|
166
|
+
}
|
|
162
167
|
/**
|
|
163
168
|
* Get frame from L1 cache
|
|
164
169
|
* @param timeUs - Clip-relative timestamp (0-based)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CacheManager.js","sources":["../../src/cache/CacheManager.ts"],"sourcesContent":["import type { TimeUs } from '../model/types';\nimport { RcFrame } from '../model';\nimport { VideoL1Cache } from './l1/VideoL1Cache';\nimport { MeframeEvent } from '../event/events';\nimport type { EventBus } from '../event/EventBus';\nimport type { EventPayloadMap } from '../event/events';\nimport {\n AudioL1Cache,\n EXPORT_PCM_COVERAGE_THRESHOLD,\n PREVIEW_PCM_COVERAGE_THRESHOLD,\n} from './l1/AudioL1Cache';\nimport { isDOMException, ResourceCorruptedError, WaiterReplacedError } from '../utils/errors';\nimport { OPFSManager } from './storage/opfs/OPFSManager';\nimport type { MeframeOpfsGateway } from './storage/opfs/gateway';\nimport { ResourceCache } from './resource/ResourceCache';\nimport { MP4IndexCache } from './resource/MP4IndexCache';\nimport { AudioSampleCache } from './resource/AudioSampleCache';\nimport type { MP4Index } from '../stages/demux/types';\n\ninterface CacheManagerConfig {\n l1: {\n maxMemoryMB: number;\n maxFrames?: number;\n /** 播放头前方保留时长,透传给 VideoL1Cache;不传则用其默认值(20s)。 */\n windowSizeUs?: number;\n /** 播放头后方保留时长,透传给 VideoL1Cache;不传则用其默认值(2s)。 */\n backwardWindowSizeUs?: number;\n maxGOPs?: number;\n gopIntervalUs?: number;\n };\n audio?: { pcmMaxBytes?: number; mixMaxBytes?: number };\n resource: {\n projectId: string;\n };\n opfsGateway?: MeframeOpfsGateway;\n}\n\ninterface ClipReadyWaiter {\n clipId: string;\n minFrameCount: number;\n startTimeUs: TimeUs;\n currentCount: number;\n resolve: (ready: boolean) => void;\n reject: (reason?: unknown) => void;\n timeoutId?: ReturnType<typeof setTimeout>;\n}\n\n/**\n * CacheManager for Window Cache Architecture\n *\n * Core features:\n * - L1 (VRAM) for composed VideoFrames (window cache ±3s)\n * - ResourceCache (OPFS) for original MP4 files\n * - MP4IndexCache (RAM) for GOP/Sample indexes\n * - AudioSampleCache (RAM) for extracted audio chunks\n */\nexport class CacheManager {\n readonly videoL1Cache: VideoL1Cache;\n private readonly audioL1Cache: AudioL1Cache;\n private readonly audioSources = new Map<string, string>();\n readonly audioMixMaxBytes: number;\n readonly resourceCache: ResourceCache;\n readonly mp4IndexCache: MP4IndexCache;\n readonly audioSampleCache: AudioSampleCache;\n private clipReadyWaiters = new Map<string, ClipReadyWaiter>();\n private eventBus?: EventBus<EventPayloadMap>;\n isExporting = false;\n\n constructor(config: CacheManagerConfig, eventBus?: EventBus<EventPayloadMap>) {\n this.videoL1Cache = new VideoL1Cache(config.l1);\n this.audioL1Cache = new AudioL1Cache(config.audio?.pcmMaxBytes);\n this.audioMixMaxBytes = config.audio?.mixMaxBytes ?? 48 * 1024 * 1024;\n\n const opfsManager = new OPFSManager(0.85, config.opfsGateway);\n this.resourceCache = new ResourceCache(opfsManager, config.resource.projectId);\n this.mp4IndexCache = new MP4IndexCache();\n this.audioSampleCache = new AudioSampleCache();\n this.eventBus = eventBus;\n }\n\n beginExport(): void {\n this.isExporting = true;\n }\n\n endExport(): void {\n this.isExporting = false;\n }\n\n async init(): Promise<void> {\n await this.resourceCache.init();\n }\n\n /**\n * Set the video window center. Audio residency is governed by leases and a byte budget.\n */\n setWindow(centerTimeUs: TimeUs): void {\n this.videoL1Cache.setWindow(centerTimeUs);\n }\n\n /**\n * Check if resource exists in OPFS cache\n */\n async hasResourceInCache(resourceId: string): Promise<boolean> {\n return await this.resourceCache.hasResource(resourceId);\n }\n\n /**\n * Read byte range from resource (for GOP-level access)\n */\n async readResourceRange(resourceId: string, start: number, end: number): Promise<ArrayBuffer> {\n try {\n return await this.resourceCache.readRange(resourceId, start, end);\n } catch (error) {\n if (isDOMException(error, 'NotFoundError')) {\n throw new ResourceCorruptedError(resourceId, 'OPFS file missing');\n }\n throw error;\n }\n }\n\n /**\n * Get MP4 index for a resource\n */\n getMP4Index(resourceId: string): MP4Index | null {\n return this.mp4IndexCache.get(resourceId);\n }\n\n get audioCacheGeneration(): number {\n return this.audioL1Cache.generation;\n }\n\n setAudioSource(clipId: string, sourceKey: string): void {\n this.audioSources.set(clipId, sourceKey);\n }\n\n pinAudioRange(sourceKey: string, startUs: TimeUs, endUs: TimeUs, copyBytes: number) {\n return this.audioL1Cache.pinRange(sourceKey, startUs, endUs, copyBytes);\n }\n\n getAudioCacheStats() {\n return this.audioL1Cache.getStats();\n }\n\n private audioKey(clipId: string): string {\n return this.audioSources.get(clipId) ?? clipId;\n }\n\n putClipAudioData(\n clipId: string,\n audioData: AudioData,\n clipDurationUs: TimeUs,\n globalTimeUs?: TimeUs\n ): void {\n this.audioL1Cache.putClipAudioData(clipId, audioData, clipDurationUs, globalTimeUs);\n }\n\n getClipPCMWithMetadata(\n clipId: string,\n startUs: TimeUs,\n endUs: TimeUs\n ): { planes: Float32Array[]; sampleRate: number; numberOfChannels: number } | null {\n return this.audioL1Cache.getPCMWithMetadata(this.audioKey(clipId), startUs, endUs);\n }\n\n hasClipPCM(clipId: string): boolean {\n return this.audioL1Cache.hasClipPCM(this.audioKey(clipId));\n }\n\n /**\n * Check if a specific audio chunk is already cached (by timestamp)\n */\n hasAudioSlotAt(clipId: string, timestampUs: TimeUs): boolean {\n return this.audioL1Cache.hasSlotAt(this.audioKey(clipId), timestampUs);\n }\n\n /**\n * Check if sufficient PCM data exists for the requested time window\n * Returns true only if at least threshold (default 80%) of requested duration is available\n */\n hasWindowPCM(clipId: string, startUs: TimeUs, endUs: TimeUs, strictMode?: boolean): boolean {\n const threshold = strictMode ? EXPORT_PCM_COVERAGE_THRESHOLD : PREVIEW_PCM_COVERAGE_THRESHOLD;\n return this.audioL1Cache.getAudioRangeCoverage(this.audioKey(clipId), startUs, endUs, threshold)\n .covered;\n }\n\n /**\n * Get audio range coverage information for incremental decoding\n * @param clipId - Clip identifier\n * @param startUs - Range start time in microseconds\n * @param endUs - Range end time in microseconds\n * @param threshold - Coverage threshold (0-1)\n * @returns Coverage info { covered: boolean, coverageRatio: number }\n */\n getAudioRangeCoverage(\n clipId: string,\n startUs: TimeUs,\n endUs: TimeUs,\n threshold?: number\n ): { covered: boolean; coverageRatio: number } {\n return this.audioL1Cache.getAudioRangeCoverage(\n this.audioKey(clipId),\n startUs,\n endUs,\n threshold\n );\n }\n\n clearAudioCache(): void {\n this.audioL1Cache.clear();\n this.audioSources.clear();\n }\n\n clearClipAudioData(clipId: string): void {\n // Resource PCM may be shared by other clips. Detach this clip; LRU owns residency.\n this.audioSources.delete(clipId);\n this.audioL1Cache.clearClipPCM(clipId);\n }\n\n /**\n * Add a frame to L1 cache\n * Handles event notifications (CacheCover, ComposeFrameReady)\n * @param frame - VideoFrame to add\n * @param clipId - Clip identifier\n * @param frameDuration - Frame duration in microseconds\n * @param trackId - Track identifier\n * @param globalTimeUs - Global timestamp for event emission and window management\n */\n addFrame(\n frame: VideoFrame,\n clipId: string,\n frameDuration: TimeUs,\n trackId: string,\n globalTimeUs: TimeUs\n ): RcFrame {\n const rcFrame = this.videoL1Cache.addFrame(frame, clipId, frameDuration, trackId, globalTimeUs);\n\n const relativeTimeUs = frame.timestamp ?? 0;\n\n // Check and notify clip ready\n this.checkAndNotifyClipReady(clipId, relativeTimeUs);\n\n // Emit cover event for first frame (globalTimeUs = 0 in composition)\n if (globalTimeUs === 0) {\n this.eventBus?.emit(MeframeEvent.CacheCover, {\n timeUs: globalTimeUs,\n clipId,\n level: 'L1',\n size: rcFrame.sizeEstimate ?? 0,\n });\n }\n\n // Emit frame ready event\n this.eventBus?.emit(MeframeEvent.ComposeFrameReady, {\n timeUs: globalTimeUs,\n frameNumber: Math.floor(globalTimeUs / frameDuration),\n renderTimeMs: 0,\n trackId,\n clipId,\n });\n\n return rcFrame;\n }\n\n /**\n * Get frame from L1 cache\n * @param timeUs - Clip-relative timestamp (0-based)\n * @param clipId - Clip identifier\n */\n getFrame(timeUs: TimeUs, clipId: string): RcFrame | null {\n return this.videoL1Cache.get(timeUs, clipId);\n }\n\n async invalidateClip(clipId: string): Promise<void> {\n this.videoL1Cache.invalidateClip(clipId);\n }\n\n /**\n * Evict a clip from L1 cache\n */\n invalidateClipInL1(clipId: string): void {\n this.videoL1Cache.invalidateClip(clipId);\n }\n\n /**\n * Check if a clip is cached in L1\n */\n hasClipInL1(clipId: string): boolean {\n return this.videoL1Cache.hasClip(clipId);\n }\n\n hasFramesInRange(clipId: string, startUs: TimeUs, endUs: TimeUs, minFrames: number): boolean {\n return this.videoL1Cache.hasFramesInRange(clipId, startUs, endUs, minFrames);\n }\n\n /**\n * Wait for a clip to have minimum frames cached\n * Used by PlaybackController for buffering state\n * Only one waiter per clip - new waiter replaces old one\n */\n waitForClipReady(\n clipId: string,\n options: { minFrameCount?: number; timeoutMs?: number; startTimeUs?: TimeUs } = {}\n ): Promise<boolean> {\n const minFrameCount = options.minFrameCount ?? 30;\n const startTimeUs = options.startTimeUs ?? 0;\n\n // Check if already have enough frames\n const currentFrameCount = this.videoL1Cache.getClipFrameCount(clipId, startTimeUs);\n if (currentFrameCount >= minFrameCount) {\n return Promise.resolve(true);\n }\n\n // Cancel previous waiter if exists\n const oldWaiter = this.clipReadyWaiters.get(clipId);\n if (oldWaiter) {\n if (oldWaiter.timeoutId) {\n clearTimeout(oldWaiter.timeoutId);\n }\n oldWaiter.reject(new WaiterReplacedError(clipId));\n }\n\n return new Promise<boolean>((resolve, reject) => {\n const waiter: ClipReadyWaiter = {\n clipId,\n minFrameCount,\n startTimeUs,\n currentCount: currentFrameCount,\n resolve,\n reject,\n };\n\n this.clipReadyWaiters.set(clipId, waiter);\n\n if (options.timeoutMs && options.timeoutMs > 0) {\n waiter.timeoutId = setTimeout(() => {\n if (this.clipReadyWaiters.get(clipId) === waiter) {\n this.clipReadyWaiters.delete(clipId);\n }\n resolve(false);\n }, options.timeoutMs);\n }\n });\n }\n\n clearVideoCache(): void {\n this.videoL1Cache.clear();\n }\n\n clear(): void {\n this.clearVideoCache();\n this.clearAudioCache();\n }\n\n getMetadata() {\n return {\n l1: this.videoL1Cache.getMetadata(),\n };\n }\n\n /**\n * Check if incoming frame satisfies clip ready condition\n * O(1) complexity - only checks single waiter and increments counter\n */\n checkAndNotifyClipReady(clipId: string, frameTimestampUs: TimeUs): void {\n const waiter = this.clipReadyWaiters.get(clipId);\n if (!waiter) {\n return;\n }\n\n // Count all frames if startTimeUs is 0 (buffering scenario)\n // Otherwise only count frames at or after the target start time\n const shouldCount = waiter.startTimeUs === 0 || frameTimestampUs >= waiter.startTimeUs;\n\n if (shouldCount) {\n waiter.currentCount++;\n\n if (waiter.currentCount >= waiter.minFrameCount) {\n if (waiter.timeoutId) {\n clearTimeout(waiter.timeoutId);\n }\n waiter.resolve(true);\n this.clipReadyWaiters.delete(clipId);\n }\n }\n }\n}\n"],"names":[],"mappings":";;;;;;;;AAwDO,MAAM,aAAa;AAAA,EACf;AAAA,EACQ;AAAA,EACA,mCAAmB,IAAA;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACD,uCAAuB,IAAA;AAAA,EACvB;AAAA,EACR,cAAc;AAAA,EAEd,YAAY,QAA4B,UAAsC;AAC5E,SAAK,eAAe,IAAI,aAAa,OAAO,EAAE;AAC9C,SAAK,eAAe,IAAI,aAAa,OAAO,OAAO,WAAW;AAC9D,SAAK,mBAAmB,OAAO,OAAO,eAAe,KAAK,OAAO;AAEjE,UAAM,cAAc,IAAI,YAAY,MAAM,OAAO,WAAW;AAC5D,SAAK,gBAAgB,IAAI,cAAc,aAAa,OAAO,SAAS,SAAS;AAC7E,SAAK,gBAAgB,IAAI,cAAA;AACzB,SAAK,mBAAmB,IAAI,iBAAA;AAC5B,SAAK,WAAW;AAAA,EAClB;AAAA,EAEA,cAAoB;AAClB,SAAK,cAAc;AAAA,EACrB;AAAA,EAEA,YAAkB;AAChB,SAAK,cAAc;AAAA,EACrB;AAAA,EAEA,MAAM,OAAsB;AAC1B,UAAM,KAAK,cAAc,KAAA;AAAA,EAC3B;AAAA;AAAA;AAAA;AAAA,EAKA,UAAU,cAA4B;AACpC,SAAK,aAAa,UAAU,YAAY;AAAA,EAC1C;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,mBAAmB,YAAsC;AAC7D,WAAO,MAAM,KAAK,cAAc,YAAY,UAAU;AAAA,EACxD;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,kBAAkB,YAAoB,OAAe,KAAmC;AAC5F,QAAI;AACF,a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ACtB,SAAK,aAAa,MAAA;AAAA,EACpB;AAAA,EAEA,QAAc;AACZ,SAAK,gBAAA;AACL,SAAK,gBAAA;AAAA,EACP;AAAA,EAEA,cAAc;AACZ,WAAO;AAAA,MACL,IAAI,KAAK,aAAa,YAAA;AAAA,IAAY;AAAA,EAEtC;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,wBAAwB,QAAgB,kBAAgC;AACtE,UAAM,SAAS,KAAK,iBAAiB,IAAI,MAAM;AAC/C,QAAI,CAAC,QAAQ;AACX;AAAA,IACF;AAIA,UAAM,cAAc,OAAO,gBAAgB,KAAK,oBAAoB,OAAO;AAE3E,QAAI,aAAa;AACf,aAAO;AAEP,UAAI,OAAO,gBAAgB,OAAO,eAAe;AAC/C,YAAI,OAAO,WAAW;AACpB,uBAAa,OAAO,SAAS;AAAA,QAC/B;AACA,eAAO,QAAQ,IAAI;AACnB,aAAK,iBAAiB,OAAO,MAAM;AAAA,MACrC;AAAA,IACF;AAAA,EACF;AACF;"}
|
|
1
|
+
{"version":3,"file":"CacheManager.js","sources":["../../src/cache/CacheManager.ts"],"sourcesContent":["import type { TimeUs } from '../model/types';\nimport { RcFrame } from '../model';\nimport { VideoL1Cache } from './l1/VideoL1Cache';\nimport { MeframeEvent } from '../event/events';\nimport type { EventBus } from '../event/EventBus';\nimport type { EventPayloadMap } from '../event/events';\nimport {\n AudioL1Cache,\n EXPORT_PCM_COVERAGE_THRESHOLD,\n PREVIEW_PCM_COVERAGE_THRESHOLD,\n} from './l1/AudioL1Cache';\nimport { isDOMException, ResourceCorruptedError, WaiterReplacedError } from '../utils/errors';\nimport { OPFSManager } from './storage/opfs/OPFSManager';\nimport type { MeframeOpfsGateway } from './storage/opfs/gateway';\nimport { ResourceCache } from './resource/ResourceCache';\nimport { MP4IndexCache } from './resource/MP4IndexCache';\nimport { AudioSampleCache } from './resource/AudioSampleCache';\nimport type { MP4Index } from '../stages/demux/types';\n\ninterface CacheManagerConfig {\n l1: {\n maxMemoryMB: number;\n maxFrames?: number;\n /** 播放头前方保留时长,透传给 VideoL1Cache;不传则用其默认值(20s)。 */\n windowSizeUs?: number;\n /** 播放头后方保留时长,透传给 VideoL1Cache;不传则用其默认值(2s)。 */\n backwardWindowSizeUs?: number;\n maxGOPs?: number;\n gopIntervalUs?: number;\n };\n audio?: { pcmMaxBytes?: number; mixMaxBytes?: number };\n resource: {\n projectId: string;\n };\n opfsGateway?: MeframeOpfsGateway;\n}\n\ninterface ClipReadyWaiter {\n clipId: string;\n minFrameCount: number;\n startTimeUs: TimeUs;\n currentCount: number;\n resolve: (ready: boolean) => void;\n reject: (reason?: unknown) => void;\n timeoutId?: ReturnType<typeof setTimeout>;\n}\n\n/**\n * CacheManager for Window Cache Architecture\n *\n * Core features:\n * - L1 (VRAM) for composed VideoFrames (window cache ±3s)\n * - ResourceCache (OPFS) for original MP4 files\n * - MP4IndexCache (RAM) for GOP/Sample indexes\n * - AudioSampleCache (RAM) for extracted audio chunks\n */\nexport class CacheManager {\n readonly videoL1Cache: VideoL1Cache;\n private readonly audioL1Cache: AudioL1Cache;\n private readonly audioSources = new Map<string, string>();\n readonly audioMixMaxBytes: number;\n readonly resourceCache: ResourceCache;\n readonly mp4IndexCache: MP4IndexCache;\n readonly audioSampleCache: AudioSampleCache;\n private clipReadyWaiters = new Map<string, ClipReadyWaiter>();\n private eventBus?: EventBus<EventPayloadMap>;\n isExporting = false;\n\n constructor(config: CacheManagerConfig, eventBus?: EventBus<EventPayloadMap>) {\n this.videoL1Cache = new VideoL1Cache(config.l1);\n this.audioL1Cache = new AudioL1Cache(config.audio?.pcmMaxBytes);\n this.audioMixMaxBytes = config.audio?.mixMaxBytes ?? 48 * 1024 * 1024;\n\n const opfsManager = new OPFSManager(0.85, config.opfsGateway);\n this.resourceCache = new ResourceCache(opfsManager, config.resource.projectId);\n this.mp4IndexCache = new MP4IndexCache();\n this.audioSampleCache = new AudioSampleCache();\n this.eventBus = eventBus;\n }\n\n beginExport(): void {\n this.isExporting = true;\n }\n\n endExport(): void {\n this.isExporting = false;\n }\n\n async init(): Promise<void> {\n await this.resourceCache.init();\n }\n\n /**\n * Set the video window center. Audio residency is governed by leases and a byte budget.\n */\n setWindow(centerTimeUs: TimeUs): void {\n this.videoL1Cache.setWindow(centerTimeUs);\n }\n\n /**\n * Check if resource exists in OPFS cache\n */\n async hasResourceInCache(resourceId: string): Promise<boolean> {\n return await this.resourceCache.hasResource(resourceId);\n }\n\n /**\n * Read byte range from resource (for GOP-level access)\n */\n async readResourceRange(resourceId: string, start: number, end: number): Promise<ArrayBuffer> {\n try {\n return await this.resourceCache.readRange(resourceId, start, end);\n } catch (error) {\n if (isDOMException(error, 'NotFoundError')) {\n throw new ResourceCorruptedError(resourceId, 'OPFS file missing');\n }\n throw error;\n }\n }\n\n /**\n * Get MP4 index for a resource\n */\n getMP4Index(resourceId: string): MP4Index | null {\n return this.mp4IndexCache.get(resourceId);\n }\n\n get audioCacheGeneration(): number {\n return this.audioL1Cache.generation;\n }\n\n setAudioSource(clipId: string, sourceKey: string): void {\n this.audioSources.set(clipId, sourceKey);\n }\n\n pinAudioRange(sourceKey: string, startUs: TimeUs, endUs: TimeUs, copyBytes: number) {\n return this.audioL1Cache.pinRange(sourceKey, startUs, endUs, copyBytes);\n }\n\n getAudioCacheStats() {\n return this.audioL1Cache.getStats();\n }\n\n private audioKey(clipId: string): string {\n return this.audioSources.get(clipId) ?? clipId;\n }\n\n putClipAudioData(\n clipId: string,\n audioData: AudioData,\n clipDurationUs: TimeUs,\n globalTimeUs?: TimeUs\n ): void {\n this.audioL1Cache.putClipAudioData(clipId, audioData, clipDurationUs, globalTimeUs);\n }\n\n getClipPCMWithMetadata(\n clipId: string,\n startUs: TimeUs,\n endUs: TimeUs\n ): { planes: Float32Array[]; sampleRate: number; numberOfChannels: number } | null {\n return this.audioL1Cache.getPCMWithMetadata(this.audioKey(clipId), startUs, endUs);\n }\n\n hasClipPCM(clipId: string): boolean {\n return this.audioL1Cache.hasClipPCM(this.audioKey(clipId));\n }\n\n /**\n * Check if a specific audio chunk is already cached (by timestamp)\n */\n hasAudioSlotAt(clipId: string, timestampUs: TimeUs): boolean {\n return this.audioL1Cache.hasSlotAt(this.audioKey(clipId), timestampUs);\n }\n\n /**\n * Check if sufficient PCM data exists for the requested time window\n * Returns true only if at least threshold (default 80%) of requested duration is available\n */\n hasWindowPCM(clipId: string, startUs: TimeUs, endUs: TimeUs, strictMode?: boolean): boolean {\n const threshold = strictMode ? EXPORT_PCM_COVERAGE_THRESHOLD : PREVIEW_PCM_COVERAGE_THRESHOLD;\n return this.audioL1Cache.getAudioRangeCoverage(this.audioKey(clipId), startUs, endUs, threshold)\n .covered;\n }\n\n /**\n * Get audio range coverage information for incremental decoding\n * @param clipId - Clip identifier\n * @param startUs - Range start time in microseconds\n * @param endUs - Range end time in microseconds\n * @param threshold - Coverage threshold (0-1)\n * @returns Coverage info { covered: boolean, coverageRatio: number }\n */\n getAudioRangeCoverage(\n clipId: string,\n startUs: TimeUs,\n endUs: TimeUs,\n threshold?: number\n ): { covered: boolean; coverageRatio: number } {\n return this.audioL1Cache.getAudioRangeCoverage(\n this.audioKey(clipId),\n startUs,\n endUs,\n threshold\n );\n }\n\n clearAudioCache(): void {\n this.audioL1Cache.clear();\n this.audioSources.clear();\n }\n\n clearClipAudioData(clipId: string): void {\n // Resource PCM may be shared by other clips. Detach this clip; LRU owns residency.\n this.audioSources.delete(clipId);\n this.audioL1Cache.clearClipPCM(clipId);\n }\n\n /**\n * Add a frame to L1 cache\n * Handles event notifications (CacheCover, ComposeFrameReady)\n * @param frame - VideoFrame to add\n * @param clipId - Clip identifier\n * @param frameDuration - Frame duration in microseconds\n * @param trackId - Track identifier\n * @param globalTimeUs - Global timestamp for event emission and window management\n */\n addFrame(\n frame: VideoFrame,\n clipId: string,\n frameDuration: TimeUs,\n trackId: string,\n globalTimeUs: TimeUs\n ): RcFrame {\n const rcFrame = this.videoL1Cache.addFrame(frame, clipId, frameDuration, trackId, globalTimeUs);\n\n const relativeTimeUs = frame.timestamp ?? 0;\n\n // Check and notify clip ready\n this.checkAndNotifyClipReady(clipId, relativeTimeUs);\n\n // Emit cover event for first frame (globalTimeUs = 0 in composition)\n if (globalTimeUs === 0) {\n this.eventBus?.emit(MeframeEvent.CacheCover, {\n timeUs: globalTimeUs,\n clipId,\n level: 'L1',\n size: rcFrame.sizeEstimate ?? 0,\n });\n }\n\n // Emit frame ready event\n this.eventBus?.emit(MeframeEvent.ComposeFrameReady, {\n timeUs: globalTimeUs,\n frameNumber: Math.floor(globalTimeUs / frameDuration),\n renderTimeMs: 0,\n trackId,\n clipId,\n });\n\n return rcFrame;\n }\n\n /** A caller that owns the frame gets a native clone it closes; otherwise the cache entry itself is returned. */\n cloneForCaller(frame: RcFrame | null, owned: boolean): RcFrame | VideoFrame | null {\n if (!frame || !owned) return frame;\n return frame.use((value) => value.clone());\n }\n\n /**\n * Get frame from L1 cache\n * @param timeUs - Clip-relative timestamp (0-based)\n * @param clipId - Clip identifier\n */\n getFrame(timeUs: TimeUs, clipId: string): RcFrame | null {\n return this.videoL1Cache.get(timeUs, clipId);\n }\n\n async invalidateClip(clipId: string): Promise<void> {\n this.videoL1Cache.invalidateClip(clipId);\n }\n\n /**\n * Evict a clip from L1 cache\n */\n invalidateClipInL1(clipId: string): void {\n this.videoL1Cache.invalidateClip(clipId);\n }\n\n /**\n * Check if a clip is cached in L1\n */\n hasClipInL1(clipId: string): boolean {\n return this.videoL1Cache.hasClip(clipId);\n }\n\n hasFramesInRange(clipId: string, startUs: TimeUs, endUs: TimeUs, minFrames: number): boolean {\n return this.videoL1Cache.hasFramesInRange(clipId, startUs, endUs, minFrames);\n }\n\n /**\n * Wait for a clip to have minimum frames cached\n * Used by PlaybackController for buffering state\n * Only one waiter per clip - new waiter replaces old one\n */\n waitForClipReady(\n clipId: string,\n options: { minFrameCount?: number; timeoutMs?: number; startTimeUs?: TimeUs } = {}\n ): Promise<boolean> {\n const minFrameCount = options.minFrameCount ?? 30;\n const startTimeUs = options.startTimeUs ?? 0;\n\n // Check if already have enough frames\n const currentFrameCount = this.videoL1Cache.getClipFrameCount(clipId, startTimeUs);\n if (currentFrameCount >= minFrameCount) {\n return Promise.resolve(true);\n }\n\n // Cancel previous waiter if exists\n const oldWaiter = this.clipReadyWaiters.get(clipId);\n if (oldWaiter) {\n if (oldWaiter.timeoutId) {\n clearTimeout(oldWaiter.timeoutId);\n }\n oldWaiter.reject(new WaiterReplacedError(clipId));\n }\n\n return new Promise<boolean>((resolve, reject) => {\n const waiter: ClipReadyWaiter = {\n clipId,\n minFrameCount,\n startTimeUs,\n currentCount: currentFrameCount,\n resolve,\n reject,\n };\n\n this.clipReadyWaiters.set(clipId, waiter);\n\n if (options.timeoutMs && options.timeoutMs > 0) {\n waiter.timeoutId = setTimeout(() => {\n if (this.clipReadyWaiters.get(clipId) === waiter) {\n this.clipReadyWaiters.delete(clipId);\n }\n resolve(false);\n }, options.timeoutMs);\n }\n });\n }\n\n clearVideoCache(): void {\n this.videoL1Cache.clear();\n }\n\n clear(): void {\n this.clearVideoCache();\n this.clearAudioCache();\n }\n\n getMetadata() {\n return {\n l1: this.videoL1Cache.getMetadata(),\n };\n }\n\n /**\n * Check if incoming frame satisfies clip ready condition\n * O(1) complexity - only checks single waiter and increments counter\n */\n checkAndNotifyClipReady(clipId: string, frameTimestampUs: TimeUs): void {\n const waiter = this.clipReadyWaiters.get(clipId);\n if (!waiter) {\n return;\n }\n\n // Count all frames if startTimeUs is 0 (buffering scenario)\n // Otherwise only count frames at or after the target start time\n const shouldCount = waiter.startTimeUs === 0 || frameTimestampUs >= waiter.startTimeUs;\n\n if (shouldCount) {\n waiter.currentCount++;\n\n if (waiter.currentCount >= waiter.minFrameCount) {\n if (waiter.timeoutId) {\n clearTimeout(waiter.timeoutId);\n }\n waiter.resolve(true);\n this.clipReadyWaiters.delete(clipId);\n }\n }\n }\n}\n"],"names":[],"mappings":";;;;;;;;AAwDO,MAAM,aAAa;AAAA,EACf;AAAA,EACQ;AA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MACL,IAAI,KAAK,aAAa,YAAA;AAAA,IAAY;AAAA,EAEtC;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,wBAAwB,QAAgB,kBAAgC;AACtE,UAAM,SAAS,KAAK,iBAAiB,IAAI,MAAM;AAC/C,QAAI,CAAC,QAAQ;AACX;AAAA,IACF;AAIA,UAAM,cAAc,OAAO,gBAAgB,KAAK,oBAAoB,OAAO;AAE3E,QAAI,aAAa;AACf,aAAO;AAEP,UAAI,OAAO,gBAAgB,OAAO,eAAe;AAC/C,YAAI,OAAO,WAAW;AACpB,uBAAa,OAAO,SAAS;AAAA,QAC/B;AACA,eAAO,QAAQ,IAAI;AACnB,aAAK,iBAAiB,OAAO,MAAM;AAAA,MACrC;AAAA,IACF;AAAA,EACF;AACF;"}
|
|
@@ -67,6 +67,8 @@ export declare class VideoL1Cache {
|
|
|
67
67
|
get(timeUs: TimeUs, clipId: string): RcFrame | null;
|
|
68
68
|
/** Return only a frame whose presentation interval contains the requested time. */
|
|
69
69
|
getCovering(clipId: string, timeUs: TimeUs): RcFrame | null;
|
|
70
|
+
/** First timestamp inside [startUs, endUs) not covered by contiguous L1 frames (or endUs when fully covered). */
|
|
71
|
+
firstUncovered(clipId: string, startUs: TimeUs, endUs: TimeUs): TimeUs;
|
|
70
72
|
/** A count cannot establish continuity: cached frames may all lie after a hole. */
|
|
71
73
|
covers(clipId: string, startUs: TimeUs, endUs: TimeUs): boolean;
|
|
72
74
|
addFrame(frame: VideoFrame, clipId: string, frameDuration: TimeUs, trackId: string, globalTimeUs?: TimeUs): RcFrame;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"VideoL1Cache.d.ts","sourceRoot":"","sources":["../../../src/cache/l1/VideoL1Cache.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAEtC,OAAO,EAAyB,KAAK,kBAAkB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AE,MAAM,GAAG,OAAO;IAK/D,QAAQ,CACN,KAAK,EAAE,UAAU,EACjB,MAAM,EAAE,MAAM,EACd,aAAa,EAAE,MAAM,EACrB,OAAO,EAAE,MAAM,EACf,YAAY,CAAC,EAAE,MAAM,GACpB,OAAO;IA8CV,OAAO,CAAC,iBAAiB;IA4BzB,OAAO,CAAC,gBAAgB;IAiBxB,OAAO,CAAC,aAAa;IAcrB,OAAO,CAAC,eAAe;IAQvB,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAcpC,OAAO,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO;IAKhC,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,MAAM,GAAG,MAAM;IAkB/D;;;OAGG;IACH,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO;IAiB5F,KAAK,IAAI,IAAI;IAeb,WAAW,IAAI,eAAe;IAU9B,OAAO,CAAC,eAAe;CAGxB"}
|
|
@@ -118,26 +118,32 @@ class VideoL1Cache {
|
|
|
118
118
|
if (!frames?.length) return null;
|
|
119
119
|
const next = binarySearchFirst(frames, (frame2) => frame2.timestampUs > timeUs + 1);
|
|
120
120
|
const frame = frames[next - 1];
|
|
121
|
-
return frame && frame.timestampUs + frame.durationUs > timeUs ? frame : null;
|
|
121
|
+
return frame && frame.timestampUs + frame.durationUs + 1 > timeUs ? frame : null;
|
|
122
122
|
}
|
|
123
|
-
/**
|
|
124
|
-
|
|
123
|
+
/** First timestamp inside [startUs, endUs) not covered by contiguous L1 frames (or endUs when fully covered). */
|
|
124
|
+
firstUncovered(clipId, startUs, endUs) {
|
|
125
|
+
if (endUs <= startUs) return endUs;
|
|
125
126
|
let coveredUntil = startUs;
|
|
126
127
|
for (const frame of this.framesByClip.get(clipId) ?? []) {
|
|
127
128
|
const end = frame.timestampUs + frame.durationUs;
|
|
128
129
|
if (end <= coveredUntil) continue;
|
|
129
|
-
if (frame.timestampUs > coveredUntil + 1) return
|
|
130
|
+
if (frame.timestampUs > coveredUntil + 1) return coveredUntil;
|
|
130
131
|
coveredUntil = end;
|
|
131
|
-
if (coveredUntil >= endUs - 1) return
|
|
132
|
+
if (coveredUntil >= endUs - 1) return endUs;
|
|
132
133
|
}
|
|
133
|
-
return
|
|
134
|
+
return coveredUntil;
|
|
135
|
+
}
|
|
136
|
+
/** A count cannot establish continuity: cached frames may all lie after a hole. */
|
|
137
|
+
covers(clipId, startUs, endUs) {
|
|
138
|
+
if (endUs <= startUs) return false;
|
|
139
|
+
return this.firstUncovered(clipId, startUs, endUs) >= endUs - 1;
|
|
134
140
|
}
|
|
135
141
|
addFrame(frame, clipId, frameDuration, trackId, globalTimeUs) {
|
|
136
142
|
const rcFrame = RcFrame.wrap(frame, {
|
|
137
143
|
trackId,
|
|
138
144
|
clipId,
|
|
139
145
|
timestampUs: frame.timestamp ?? 0,
|
|
140
|
-
durationUs: frame.duration
|
|
146
|
+
durationUs: frame.duration !== null && frame.duration > 0 ? frame.duration : frameDuration,
|
|
141
147
|
globalTimeUs
|
|
142
148
|
// Store global timestamp for window eviction
|
|
143
149
|
});
|