@meframe/core 0.6.7 → 0.6.9

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 (101) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +7 -1
  3. package/dist/Meframe.d.ts +33 -0
  4. package/dist/Meframe.d.ts.map +1 -1
  5. package/dist/Meframe.js +78 -29
  6. package/dist/Meframe.js.map +1 -1
  7. package/dist/cache/AudioMixBlockCache.d.ts +13 -10
  8. package/dist/cache/AudioMixBlockCache.d.ts.map +1 -1
  9. package/dist/cache/AudioMixBlockCache.js +39 -26
  10. package/dist/cache/AudioMixBlockCache.js.map +1 -1
  11. package/dist/cache/CacheManager.d.ts +27 -2
  12. package/dist/cache/CacheManager.d.ts.map +1 -1
  13. package/dist/cache/CacheManager.js +32 -8
  14. package/dist/cache/CacheManager.js.map +1 -1
  15. package/dist/cache/l1/AudioL1Cache.d.ts +29 -8
  16. package/dist/cache/l1/AudioL1Cache.d.ts.map +1 -1
  17. package/dist/cache/l1/AudioL1Cache.js +133 -83
  18. package/dist/cache/l1/AudioL1Cache.js.map +1 -1
  19. package/dist/cache/l1/VideoL1Cache.d.ts +14 -0
  20. package/dist/cache/l1/VideoL1Cache.d.ts.map +1 -1
  21. package/dist/cache/l1/VideoL1Cache.js +71 -11
  22. package/dist/cache/l1/VideoL1Cache.js.map +1 -1
  23. package/dist/cache/l1/preview-cache-budget.d.ts +10 -0
  24. package/dist/cache/l1/preview-cache-budget.d.ts.map +1 -0
  25. package/dist/cache/l1/preview-cache-budget.js +37 -0
  26. package/dist/cache/l1/preview-cache-budget.js.map +1 -0
  27. package/dist/cache/resource/AudioSampleCache.d.ts +1 -0
  28. package/dist/cache/resource/AudioSampleCache.d.ts.map +1 -1
  29. package/dist/cache/resource/AudioSampleCache.js +3 -0
  30. package/dist/cache/resource/AudioSampleCache.js.map +1 -1
  31. package/dist/cache/resource/MP4IndexCache.d.ts +1 -0
  32. package/dist/cache/resource/MP4IndexCache.d.ts.map +1 -1
  33. package/dist/cache/resource/MP4IndexCache.js +3 -0
  34. package/dist/cache/resource/MP4IndexCache.js.map +1 -1
  35. package/dist/config/defaults.d.ts.map +1 -1
  36. package/dist/config/defaults.js +1 -0
  37. package/dist/config/defaults.js.map +1 -1
  38. package/dist/config/types.d.ts +10 -0
  39. package/dist/config/types.d.ts.map +1 -1
  40. package/dist/config/validation.d.ts.map +1 -1
  41. package/dist/config/validation.js +7 -0
  42. package/dist/config/validation.js.map +1 -1
  43. package/dist/controllers/PlaybackController.d.ts +2 -1
  44. package/dist/controllers/PlaybackController.d.ts.map +1 -1
  45. package/dist/controllers/PlaybackController.js +75 -46
  46. package/dist/controllers/PlaybackController.js.map +1 -1
  47. package/dist/controllers/PlaybackStateMachine.d.ts.map +1 -1
  48. package/dist/controllers/PlaybackStateMachine.js +4 -1
  49. package/dist/controllers/PlaybackStateMachine.js.map +1 -1
  50. package/dist/controllers/types.d.ts +1 -0
  51. package/dist/controllers/types.d.ts.map +1 -1
  52. package/dist/controllers/types.js.map +1 -1
  53. package/dist/model/patch.d.ts.map +1 -1
  54. package/dist/model/patch.js +28 -9
  55. package/dist/model/patch.js.map +1 -1
  56. package/dist/model/validation.d.ts.map +1 -1
  57. package/dist/model/validation.js +4 -0
  58. package/dist/model/validation.js.map +1 -1
  59. package/dist/orchestrator/AudioExportSession.d.ts +0 -5
  60. package/dist/orchestrator/AudioExportSession.d.ts.map +1 -1
  61. package/dist/orchestrator/AudioExportSession.js +8 -16
  62. package/dist/orchestrator/AudioExportSession.js.map +1 -1
  63. package/dist/orchestrator/AudioPreviewSession.d.ts +13 -0
  64. package/dist/orchestrator/AudioPreviewSession.d.ts.map +1 -1
  65. package/dist/orchestrator/AudioPreviewSession.js +151 -75
  66. package/dist/orchestrator/AudioPreviewSession.js.map +1 -1
  67. package/dist/orchestrator/AudioWindowPreparer.d.ts +38 -9
  68. package/dist/orchestrator/AudioWindowPreparer.d.ts.map +1 -1
  69. package/dist/orchestrator/AudioWindowPreparer.js +207 -55
  70. package/dist/orchestrator/AudioWindowPreparer.js.map +1 -1
  71. package/dist/orchestrator/ExportScheduler.d.ts.map +1 -1
  72. package/dist/orchestrator/ExportScheduler.js +4 -2
  73. package/dist/orchestrator/ExportScheduler.js.map +1 -1
  74. package/dist/orchestrator/Orchestrator.d.ts +31 -0
  75. package/dist/orchestrator/Orchestrator.d.ts.map +1 -1
  76. package/dist/orchestrator/Orchestrator.js +140 -13
  77. package/dist/orchestrator/Orchestrator.js.map +1 -1
  78. package/dist/orchestrator/VideoWindowDecodeSession.d.ts.map +1 -1
  79. package/dist/orchestrator/VideoWindowDecodeSession.js +10 -9
  80. package/dist/orchestrator/VideoWindowDecodeSession.js.map +1 -1
  81. package/dist/orchestrator/types.d.ts +4 -0
  82. package/dist/orchestrator/types.d.ts.map +1 -1
  83. package/dist/stages/compose/OfflineAudioMixer.d.ts +7 -2
  84. package/dist/stages/compose/OfflineAudioMixer.d.ts.map +1 -1
  85. package/dist/stages/compose/OfflineAudioMixer.js +86 -70
  86. package/dist/stages/compose/OfflineAudioMixer.js.map +1 -1
  87. package/dist/stages/load/ResourceLoader.d.ts +8 -0
  88. package/dist/stages/load/ResourceLoader.d.ts.map +1 -1
  89. package/dist/stages/load/ResourceLoader.js +117 -20
  90. package/dist/stages/load/ResourceLoader.js.map +1 -1
  91. package/dist/stages/load/TaskManager.d.ts +2 -2
  92. package/dist/stages/load/TaskManager.d.ts.map +1 -1
  93. package/dist/stages/load/TaskManager.js +11 -6
  94. package/dist/stages/load/TaskManager.js.map +1 -1
  95. package/dist/stages/load/types.d.ts +2 -0
  96. package/dist/stages/load/types.d.ts.map +1 -1
  97. package/dist/utils/errors.d.ts +3 -0
  98. package/dist/utils/errors.d.ts.map +1 -1
  99. package/dist/utils/errors.js +9 -0
  100. package/dist/utils/errors.js.map +1 -1
  101. package/package.json +1 -1
@@ -9,6 +9,8 @@ import { AudioSampleCache } from "./resource/AudioSampleCache.js";
9
9
  class CacheManager {
10
10
  videoL1Cache;
11
11
  audioL1Cache;
12
+ audioSources = /* @__PURE__ */ new Map();
13
+ audioMixMaxBytes;
12
14
  resourceCache;
13
15
  mp4IndexCache;
14
16
  audioSampleCache;
@@ -17,7 +19,8 @@ class CacheManager {
17
19
  isExporting = false;
18
20
  constructor(config, eventBus) {
19
21
  this.videoL1Cache = new VideoL1Cache(config.l1);
20
- this.audioL1Cache = new AudioL1Cache();
22
+ this.audioL1Cache = new AudioL1Cache(config.audio?.pcmMaxBytes);
23
+ this.audioMixMaxBytes = config.audio?.mixMaxBytes ?? 48 * 1024 * 1024;
21
24
  const opfsManager = new OPFSManager(0.85, config.opfsGateway);
22
25
  this.resourceCache = new ResourceCache(opfsManager, config.resource.projectId);
23
26
  this.mp4IndexCache = new MP4IndexCache();
@@ -34,8 +37,7 @@ class CacheManager {
34
37
  await this.resourceCache.init();
35
38
  }
36
39
  /**
37
- * Set window center for L1 cache management (unified for video and audio)
38
- * L1 cache uses center ±3.5s window for video, ±5s for audio
40
+ * Set the video window center. Audio residency is governed by leases and a byte budget.
39
41
  */
40
42
  setWindow(centerTimeUs) {
41
43
  this.videoL1Cache.setWindow(centerTimeUs);
@@ -65,20 +67,35 @@ class CacheManager {
65
67
  getMP4Index(resourceId) {
66
68
  return this.mp4IndexCache.get(resourceId);
67
69
  }
70
+ get audioCacheGeneration() {
71
+ return this.audioL1Cache.generation;
72
+ }
73
+ setAudioSource(clipId, sourceKey) {
74
+ this.audioSources.set(clipId, sourceKey);
75
+ }
76
+ pinAudioRange(sourceKey, startUs, endUs, copyBytes) {
77
+ return this.audioL1Cache.pinRange(sourceKey, startUs, endUs, copyBytes);
78
+ }
79
+ getAudioCacheStats() {
80
+ return this.audioL1Cache.getStats();
81
+ }
82
+ audioKey(clipId) {
83
+ return this.audioSources.get(clipId) ?? clipId;
84
+ }
68
85
  putClipAudioData(clipId, audioData, clipDurationUs, globalTimeUs) {
69
86
  this.audioL1Cache.putClipAudioData(clipId, audioData, clipDurationUs, globalTimeUs);
70
87
  }
71
88
  getClipPCMWithMetadata(clipId, startUs, endUs) {
72
- return this.audioL1Cache.getPCMWithMetadata(clipId, startUs, endUs);
89
+ return this.audioL1Cache.getPCMWithMetadata(this.audioKey(clipId), startUs, endUs);
73
90
  }
74
91
  hasClipPCM(clipId) {
75
- return this.audioL1Cache.hasClipPCM(clipId);
92
+ return this.audioL1Cache.hasClipPCM(this.audioKey(clipId));
76
93
  }
77
94
  /**
78
95
  * Check if a specific audio chunk is already cached (by timestamp)
79
96
  */
80
97
  hasAudioSlotAt(clipId, timestampUs) {
81
- return this.audioL1Cache.hasSlotAt(clipId, timestampUs);
98
+ return this.audioL1Cache.hasSlotAt(this.audioKey(clipId), timestampUs);
82
99
  }
83
100
  /**
84
101
  * Check if sufficient PCM data exists for the requested time window
@@ -86,7 +103,7 @@ class CacheManager {
86
103
  */
87
104
  hasWindowPCM(clipId, startUs, endUs, strictMode) {
88
105
  const threshold = strictMode ? EXPORT_PCM_COVERAGE_THRESHOLD : PREVIEW_PCM_COVERAGE_THRESHOLD;
89
- return this.audioL1Cache.getAudioRangeCoverage(clipId, startUs, endUs, threshold).covered;
106
+ return this.audioL1Cache.getAudioRangeCoverage(this.audioKey(clipId), startUs, endUs, threshold).covered;
90
107
  }
91
108
  /**
92
109
  * Get audio range coverage information for incremental decoding
@@ -97,12 +114,19 @@ class CacheManager {
97
114
  * @returns Coverage info { covered: boolean, coverageRatio: number }
98
115
  */
99
116
  getAudioRangeCoverage(clipId, startUs, endUs, threshold) {
100
- return this.audioL1Cache.getAudioRangeCoverage(clipId, startUs, endUs, threshold);
117
+ return this.audioL1Cache.getAudioRangeCoverage(
118
+ this.audioKey(clipId),
119
+ startUs,
120
+ endUs,
121
+ threshold
122
+ );
101
123
  }
102
124
  clearAudioCache() {
103
125
  this.audioL1Cache.clear();
126
+ this.audioSources.clear();
104
127
  }
105
128
  clearClipAudioData(clipId) {
129
+ this.audioSources.delete(clipId);
106
130
  this.audioL1Cache.clearClipPCM(clipId);
107
131
  }
108
132
  /**
@@ -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 /** 播放头前方保留时长,透传给 VideoL1Cache;不传则用其默认值(20s)。 */\n windowSizeUs?: number;\n /** 播放头后方保留时长,透传给 VideoL1Cache;不传则用其默认值(2s)。 */\n backwardWindowSizeUs?: number;\n maxGOPs?: number;\n gopIntervalUs?: number;\n };\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 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();\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 window center for L1 cache management (unified for video and audio)\n * L1 cache uses center ±3.5s window for video, ±5s for audio\n */\n setWindow(centerTimeUs: TimeUs): void {\n this.videoL1Cache.setWindow(centerTimeUs);\n // this.audioL1Cache.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 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(clipId, startUs, endUs);\n }\n\n hasClipPCM(clipId: string): boolean {\n return this.audioL1Cache.hasClipPCM(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(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(clipId, startUs, endUs, threshold).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(clipId, startUs, endUs, threshold);\n }\n\n clearAudioCache(): void {\n this.audioL1Cache.clear();\n }\n\n clearClipAudioData(clipId: string): void {\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":";;;;;;;;AAsDO,MAAM,aAAa;AAAA,EACf;AAAA,EACQ;AAAA,EACR;AAAA,EACA;AAAA,EACA;AAAA,EACD,uCAAuB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O,YAAY,WAAW,MAAM;AAClC,cAAI,KAAK,iBAAiB,IAAI,MAAM,MAAM,QAAQ;AAChD,iBAAK,iBAAiB,OAAO,MAAM;AAAA,UACrC;AACA,kBAAQ,KAAK;AAAA,QACf,GAAG,QAAQ,SAAS;AAAA,MACtB;AAAA,IACF,CAAC;AAAA,EACH;AAAA,EAEA,kBAAwB;AACtB,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 /**\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 }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;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;"}
@@ -12,7 +12,36 @@ interface AudioDataSlot {
12
12
  }
13
13
  export type { AudioDataSlot };
14
14
  export declare class AudioL1Cache {
15
+ readonly maxBytes: number;
15
16
  private audioDataByClip;
17
+ private readonly lru;
18
+ private readonly pins;
19
+ private readonly retired;
20
+ private bytes;
21
+ private epoch;
22
+ constructor(maxBytes?: number);
23
+ get generation(): number;
24
+ /** Reserve the read copy before decoding. Eviction never removes a pinned slot. */
25
+ pinRange(key: string, startUs: number, endUs: number, copyBytes: number): {
26
+ read: () => {
27
+ planes: Float32Array[];
28
+ sampleRate: number;
29
+ numberOfChannels: number;
30
+ } | null;
31
+ release: () => void;
32
+ };
33
+ getStats(): {
34
+ slots: number;
35
+ bytes: number;
36
+ maxBytes: number;
37
+ activeLeases: number;
38
+ reservedBytes: number;
39
+ pinnedBytes: number;
40
+ };
41
+ private slotBytes;
42
+ private reservedBytes;
43
+ private isPinned;
44
+ private makeRoom;
16
45
  putClipAudioData(clipId: string, audioData: AudioData, _clipDurationUs: TimeUs, globalTimeUs?: TimeUs): void;
17
46
  getSlotsInWindow(clipId: string, startUs: TimeUs, endUs: TimeUs): AudioDataSlot[] | null;
18
47
  getPCM(clipId: string, startUs: TimeUs, endUs: TimeUs): Float32Array[] | null;
@@ -40,14 +69,6 @@ export declare class AudioL1Cache {
40
69
  };
41
70
  private computeRangeCoverageDuration;
42
71
  clearClipPCM(clipId: string): void;
43
- /**
44
- * Update window center (unified global window)
45
- * Aligned with VideoL1Cache strategy: maintains a window of ±RADIUS around center
46
- */
47
- /**
48
- * Evict audio slots outside the global window (aligned with VideoL1Cache)
49
- * Skip if eviction is disabled (e.g., during export)
50
- */
51
72
  /**
52
73
  * Find insertion index for a new slot (aligned with VideoL1Cache)
53
74
  */
@@ -1 +1 @@
1
- {"version":3,"file":"AudioL1Cache.d.ts","sourceRoot":"","sources":["../../../src/cache/l1/AudioL1Cache.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAIhD,eAAO,MAAM,8BAA8B,OAAO,CAAC;AACnD,eAAO,MAAM,6BAA6B,OAAO,CAAC;AAElD,UAAU,aAAa;IACrB,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,YAAY,EAAE,CAAC;IACvB,UAAU,EAAE,MAAM,CAAC;IACnB,gBAAgB,EAAE,MAAM,CAAC;IACzB,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,YAAY,EAAE,aAAa,EAAE,CAAC;AAE9B,qBAAa,YAAY;IAEvB,OAAO,CAAC,eAAe,CAAsC;IAW7D,gBAAgB,CACd,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,SAAS,EACpB,eAAe,EAAE,MAAM,EACvB,YAAY,CAAC,EAAE,MAAM,GACpB,IAAI;IAkEP,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,aAAa,EAAE,GAAG,IAAI;IAmBxF,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,YAAY,EAAE,GAAG,IAAI;IAiG7E,kBAAkB,CAChB,MAAM,EAAE,MAAM,EACd,OAAO,EAAE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AG,OAAO;IAInC;;OAEG;IACH,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,WAAW,GAAE,MAAa,GAAG,OAAO;IAmBnF;;;;;;;OAOG;IACH,qBAAqB,CACnB,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,MAAM,EACb,SAAS,SAAiC,GACzC;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,aAAa,EAAE,MAAM,CAAA;KAAE;IAa9C,OAAO,CAAC,4BAA4B;IA+CpC,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IASlC;;OAEG;IACH,OAAO,CAAC,eAAe;IAIvB,KAAK,IAAI,IAAI;IAIb,KAAK,IAAI,IAAI;IAKb,OAAO,IAAI,IAAI;CAGhB"}
@@ -3,15 +3,89 @@ import { extractPlanesFromAudioData } from "../../utils/audio-data.js";
3
3
  const PREVIEW_PCM_COVERAGE_THRESHOLD = 0.95;
4
4
  const EXPORT_PCM_COVERAGE_THRESHOLD = 0.99;
5
5
  class AudioL1Cache {
6
+ constructor(maxBytes = 64 * 1024 * 1024) {
7
+ this.maxBytes = maxBytes;
8
+ if (!Number.isFinite(maxBytes) || maxBytes <= 0) throw new Error("Invalid PCM byte budget");
9
+ }
6
10
  // Aligned with VideoL1Cache: array of discrete audio data slots per clip
7
11
  audioDataByClip = /* @__PURE__ */ new Map();
8
- // Unified window management (aligned with VideoL1Cache)
9
- // All clips share the same global window center
10
- // private windowCenter: TimeUs = 0;
11
- // // Window radius aligned with video (±3.5s, but we use 5s for audio safety margin)
12
- // private readonly WINDOW_RADIUS = 5_000_000; // ±5s
13
- // private readonly EVICT_THROTTLE_MS = 500;
14
- // private lastEvictTime = 0;
12
+ lru = /* @__PURE__ */ new Map();
13
+ pins = /* @__PURE__ */ new Set();
14
+ retired = /* @__PURE__ */ new Map();
15
+ bytes = 0;
16
+ epoch = 0;
17
+ get generation() {
18
+ return this.epoch;
19
+ }
20
+ /** Reserve the read copy before decoding. Eviction never removes a pinned slot. */
21
+ pinRange(key, startUs, endUs, copyBytes) {
22
+ if (copyBytes * 2 > this.maxBytes) throw new RangeError("Audio PCM range exceeds byte budget");
23
+ if (!this.makeRoom(copyBytes))
24
+ throw new RangeError("Audio PCM budget is held by active readers");
25
+ const pin = { key, startUs, endUs, epoch: this.epoch, copyBytes };
26
+ this.pins.add(pin);
27
+ let released = false;
28
+ let data = null;
29
+ return {
30
+ read: () => {
31
+ if (released || pin.epoch !== this.epoch)
32
+ throw new DOMException("Audio cache invalidated", "AbortError");
33
+ data ??= this.getPCMWithMetadata(key, startUs, endUs);
34
+ if (data && data.planes.reduce((n, plane) => n + plane.byteLength, 0) > copyBytes) {
35
+ throw new RangeError("Audio PCM read exceeds reserved bytes");
36
+ }
37
+ return data;
38
+ },
39
+ release: () => {
40
+ if (released) return;
41
+ released = true;
42
+ data = null;
43
+ this.pins.delete(pin);
44
+ for (const [slot, owner] of this.retired) {
45
+ if (!this.isPinned(slot, owner.key, owner.epoch)) {
46
+ this.retired.delete(slot);
47
+ this.bytes -= this.slotBytes(slot);
48
+ }
49
+ }
50
+ }
51
+ };
52
+ }
53
+ getStats() {
54
+ return {
55
+ slots: this.lru.size + this.retired.size,
56
+ bytes: this.bytes,
57
+ maxBytes: this.maxBytes,
58
+ activeLeases: this.pins.size,
59
+ reservedBytes: this.reservedBytes(),
60
+ pinnedBytes: [...this.lru].reduce(
61
+ (n, [slot, key]) => n + (this.isPinned(slot, key) ? this.slotBytes(slot) : 0),
62
+ 0
63
+ ) + [...this.retired.keys()].reduce((n, slot) => n + this.slotBytes(slot), 0)
64
+ };
65
+ }
66
+ slotBytes(slot) {
67
+ return slot.planes.reduce((n, plane) => n + plane.byteLength, 0);
68
+ }
69
+ reservedBytes() {
70
+ return [...this.pins].reduce((n, pin) => n + pin.copyBytes, 0);
71
+ }
72
+ isPinned(slot, key, epoch = this.epoch) {
73
+ return [...this.pins].some(
74
+ (pin) => pin.key === key && pin.epoch === epoch && slot.timestampUs < pin.endUs && slot.timestampUs + slot.durationUs > pin.startUs
75
+ );
76
+ }
77
+ makeRoom(incomingBytes) {
78
+ for (const [slot, key] of this.lru) {
79
+ if (this.bytes + this.reservedBytes() + incomingBytes <= this.maxBytes) break;
80
+ if (this.isPinned(slot, key)) continue;
81
+ const slots = this.audioDataByClip.get(key);
82
+ slots.splice(slots.indexOf(slot), 1);
83
+ if (slots.length === 0) this.audioDataByClip.delete(key);
84
+ this.lru.delete(slot);
85
+ this.bytes -= this.slotBytes(slot);
86
+ }
87
+ return this.bytes + this.reservedBytes() + incomingBytes <= this.maxBytes;
88
+ }
15
89
  putClipAudioData(clipId, audioData, _clipDurationUs, globalTimeUs) {
16
90
  const numberOfChannels = audioData.numberOfChannels ?? 2;
17
91
  const numberOfFrames = audioData.numberOfFrames ?? 0;
@@ -22,8 +96,28 @@ class AudioL1Cache {
22
96
  audioData.close();
23
97
  return;
24
98
  }
25
- const planes = extractPlanesFromAudioData(audioData, numberOfChannels, numberOfFrames);
26
- audioData.close();
99
+ const incomingBytes = numberOfFrames * numberOfChannels * Float32Array.BYTES_PER_ELEMENT;
100
+ const existingSlots = this.audioDataByClip.get(clipId);
101
+ const existingIndex = existingSlots ? this.findInsertIndex(existingSlots, audioTimestampUs) : 0;
102
+ const duplicate = [existingSlots?.[existingIndex], existingSlots?.[existingIndex - 1]].find(
103
+ (slot2) => slot2 && Math.abs(slot2.timestampUs - audioTimestampUs) < 5e5 / sampleRate
104
+ );
105
+ if (duplicate) {
106
+ this.lru.delete(duplicate);
107
+ this.lru.set(duplicate, clipId);
108
+ audioData.close();
109
+ return;
110
+ }
111
+ if (!this.makeRoom(incomingBytes)) {
112
+ audioData.close();
113
+ throw new RangeError("Audio PCM byte budget exhausted");
114
+ }
115
+ let planes;
116
+ try {
117
+ planes = extractPlanesFromAudioData(audioData, numberOfChannels, numberOfFrames);
118
+ } finally {
119
+ audioData.close();
120
+ }
27
121
  const slot = {
28
122
  timestampUs: audioTimestampUs,
29
123
  durationUs: audioDurationUs,
@@ -38,22 +132,9 @@ class AudioL1Cache {
38
132
  this.audioDataByClip.set(clipId, slots);
39
133
  }
40
134
  const insertIndex = this.findInsertIndex(slots, audioTimestampUs);
41
- const DUPLICATE_THRESHOLD_US = 0.5 * 1e6 / sampleRate;
42
- if (insertIndex < slots.length) {
43
- const existingSlot = slots[insertIndex];
44
- const timeDiff = Math.abs(existingSlot.timestampUs - audioTimestampUs);
45
- if (timeDiff < DUPLICATE_THRESHOLD_US) {
46
- return;
47
- }
48
- }
49
- if (insertIndex > 0) {
50
- const prevSlot = slots[insertIndex - 1];
51
- const timeDiff = Math.abs(prevSlot.timestampUs - audioTimestampUs);
52
- if (timeDiff < DUPLICATE_THRESHOLD_US) {
53
- return;
54
- }
55
- }
56
135
  slots.splice(insertIndex, 0, slot);
136
+ this.lru.set(slot, clipId);
137
+ this.bytes += this.slotBytes(slot);
57
138
  }
58
139
  getSlotsInWindow(clipId, startUs, endUs) {
59
140
  const slots = this.audioDataByClip.get(clipId);
@@ -99,17 +180,18 @@ class AudioL1Cache {
99
180
  );
100
181
  return null;
101
182
  }
102
- const totalFrames = Math.ceil(requestedDurationUs / 1e6 * uniformSampleRate);
183
+ const totalFrames = Math.ceil(requestedDurationUs * uniformSampleRate / 1e6);
184
+ const startFrame = Math.round(startUs * uniformSampleRate / 1e6);
103
185
  const result = Array.from(
104
186
  { length: uniformChannels },
105
187
  () => new Float32Array(totalFrames)
106
188
  );
107
189
  for (const slot of overlappingSlots) {
190
+ this.lru.delete(slot);
191
+ this.lru.set(slot, clipId);
108
192
  const slotFrames = slot.planes[0]?.length ?? 0;
109
193
  if (slotFrames <= 0) continue;
110
- const slotStartFrame = Math.round(
111
- (slot.timestampUs - startUs) / 1e6 * uniformSampleRate
112
- );
194
+ const slotStartFrame = Math.round(slot.timestampUs * uniformSampleRate / 1e6) - startFrame;
113
195
  const slotEndFrame = slotStartFrame + slotFrames;
114
196
  const dstStartFrame = Math.max(0, slotStartFrame);
115
197
  const dstEndFrame = Math.min(totalFrames, slotEndFrame);
@@ -143,7 +225,7 @@ class AudioL1Cache {
143
225
  if (!planes) {
144
226
  return null;
145
227
  }
146
- const firstSlot = slots[0];
228
+ const firstSlot = this.getSlotsInWindow(clipId, startUs, endUs)[0];
147
229
  return {
148
230
  planes,
149
231
  sampleRate: firstSlot.sampleRate,
@@ -206,64 +288,32 @@ class AudioL1Cache {
206
288
  if (overlappingSlots.length === 0) {
207
289
  return { coveredDurationUs: 0, requestedDurationUs };
208
290
  }
209
- let coveredDurationUs = 0;
291
+ const sampleRate = overlappingSlots[0].sampleRate;
292
+ const requestedFrames = Math.ceil(requestedDurationUs * sampleRate / 1e6);
293
+ const startFrame = Math.round(startUs * sampleRate / 1e6);
294
+ let coveredFrames = 0;
295
+ let coveredEnd = 0;
210
296
  for (const slot of overlappingSlots) {
211
- const slotEndUs = slot.timestampUs + slot.durationUs;
212
- const overlapStart = Math.max(startUs, slot.timestampUs);
213
- const overlapEnd = Math.min(endUs, slotEndUs);
214
- if (overlapStart < overlapEnd) {
215
- coveredDurationUs += overlapEnd - overlapStart;
216
- }
297
+ const slotStartFrame = Math.round(slot.timestampUs * sampleRate / 1e6) - startFrame;
298
+ const overlapStart = Math.max(coveredEnd, 0, slotStartFrame);
299
+ const overlapEnd = Math.min(requestedFrames, slotStartFrame + (slot.planes[0]?.length ?? 0));
300
+ if (overlapEnd > overlapStart) coveredFrames += overlapEnd - overlapStart;
301
+ coveredEnd = Math.max(coveredEnd, overlapEnd);
217
302
  }
303
+ const coveredDurationUs = Math.min(
304
+ requestedDurationUs,
305
+ coveredFrames / sampleRate * 1e6
306
+ );
218
307
  return { coveredDurationUs, requestedDurationUs };
219
308
  }
220
309
  clearClipPCM(clipId) {
310
+ for (const slot of this.audioDataByClip.get(clipId) ?? []) {
311
+ this.lru.delete(slot);
312
+ if (this.isPinned(slot, clipId)) this.retired.set(slot, { key: clipId, epoch: this.epoch });
313
+ else this.bytes -= this.slotBytes(slot);
314
+ }
221
315
  this.audioDataByClip.delete(clipId);
222
316
  }
223
- /**
224
- * Update window center (unified global window)
225
- * Aligned with VideoL1Cache strategy: maintains a window of ±RADIUS around center
226
- */
227
- // setWindow(centerGlobalUs: TimeUs): void {
228
- // this.windowCenter = centerGlobalUs;
229
- // this.checkEviction();
230
- // }
231
- // private checkEviction(): void {
232
- // const now = Date.now();
233
- // if (now - this.lastEvictTime > this.EVICT_THROTTLE_MS) {
234
- // this.evictOutOfWindow();
235
- // this.lastEvictTime = now;
236
- // }
237
- // }
238
- /**
239
- * Evict audio slots outside the global window (aligned with VideoL1Cache)
240
- * Skip if eviction is disabled (e.g., during export)
241
- */
242
- // private evictOutOfWindow(): void {
243
- // const windowStart = Math.max(0, this.windowCenter - this.WINDOW_RADIUS);
244
- // const windowEnd = this.windowCenter + this.WINDOW_RADIUS;
245
- // for (const [clipId, slots] of this.audioDataByClip) {
246
- // const toKeep: AudioDataSlot[] = [];
247
- // for (const slot of slots) {
248
- // const globalTime = slot.globalTimeUs;
249
- // // Slots without globalTimeUs are kept (legacy)
250
- // if (globalTime === undefined) {
251
- // toKeep.push(slot);
252
- // continue;
253
- // }
254
- // // Keep slots within window
255
- // if (globalTime >= windowStart && globalTime <= windowEnd) {
256
- // toKeep.push(slot);
257
- // }
258
- // // Slots outside window are discarded (no close needed for Float32Array)
259
- // }
260
- // if (toKeep.length > 0) {
261
- // this.audioDataByClip.set(clipId, toKeep);
262
- // } else {
263
- // this.audioDataByClip.delete(clipId);
264
- // }
265
- // }
266
- // }
267
317
  /**
268
318
  * Find insertion index for a new slot (aligned with VideoL1Cache)
269
319
  */
@@ -271,11 +321,11 @@ class AudioL1Cache {
271
321
  return binarySearchFirst(slots, (slot) => slot.timestampUs >= timestamp);
272
322
  }
273
323
  flush() {
274
- this.audioDataByClip.clear();
324
+ this.clear();
275
325
  }
276
326
  clear() {
277
- this.flush();
278
- this.audioDataByClip.clear();
327
+ for (const key of this.audioDataByClip.keys()) this.clearClipPCM(key);
328
+ this.epoch++;
279
329
  }
280
330
  dispose() {
281
331
  this.clear();
@@ -1 +1 @@
1
- {"version":3,"file":"AudioL1Cache.js","sources":["../../../src/cache/l1/AudioL1Cache.ts"],"sourcesContent":["import type { TimeUs } from '../../model/types';\nimport { binarySearchFirst, binarySearchOverlapping } from '../../utils/binary-search';\nimport { extractPlanesFromAudioData } from '../../utils/audio-data';\n\nexport const PREVIEW_PCM_COVERAGE_THRESHOLD = 0.95;\nexport const EXPORT_PCM_COVERAGE_THRESHOLD = 0.99;\n\ninterface AudioDataSlot {\n timestampUs: TimeUs; // Resource timestamp (aligned with VideoL1Cache)\n durationUs: TimeUs;\n planes: Float32Array[]; // PCM data for this slot\n sampleRate: number;\n numberOfChannels: number;\n globalTimeUs?: TimeUs; // Global timeline time (for window management)\n}\n\nexport type { AudioDataSlot };\n\nexport class AudioL1Cache {\n // Aligned with VideoL1Cache: array of discrete audio data slots per clip\n private audioDataByClip = new Map<string, AudioDataSlot[]>();\n\n // Unified window management (aligned with VideoL1Cache)\n // All clips share the same global window center\n // private windowCenter: TimeUs = 0;\n\n // // Window radius aligned with video (±3.5s, but we use 5s for audio safety margin)\n // private readonly WINDOW_RADIUS = 5_000_000; // ±5s\n // private readonly EVICT_THROTTLE_MS = 500;\n // private lastEvictTime = 0;\n\n putClipAudioData(\n clipId: string,\n audioData: AudioData,\n _clipDurationUs: TimeUs,\n globalTimeUs?: TimeUs\n ): void {\n const numberOfChannels = audioData.numberOfChannels ?? 2;\n const numberOfFrames = audioData.numberOfFrames ?? 0;\n const sampleRate = audioData.sampleRate ?? 48_000;\n const audioTimestampUs = audioData.timestamp ?? 0;\n const audioDurationUs =\n audioData.duration ?? Math.round((numberOfFrames / sampleRate) * 1_000_000);\n\n if (!numberOfChannels || !numberOfFrames) {\n audioData.close();\n return;\n }\n\n // Extract PCM data\n const planes = extractPlanesFromAudioData(audioData, numberOfChannels, numberOfFrames);\n audioData.close();\n\n // Create audio data slot (aligned with video architecture)\n const slot: AudioDataSlot = {\n timestampUs: audioTimestampUs,\n durationUs: audioDurationUs,\n planes,\n sampleRate,\n numberOfChannels,\n globalTimeUs,\n };\n // Get or create slots array for this clip\n let slots = this.audioDataByClip.get(clipId);\n if (!slots) {\n slots = [];\n this.audioDataByClip.set(clipId, slots);\n }\n\n // Insert slot in sorted order (aligned with VideoL1Cache.addFrame)\n const insertIndex = this.findInsertIndex(slots, audioTimestampUs);\n\n // Deduplication: Check for duplicate or near-duplicate timestamp\n // Gapless head frames may be only a few samples long. Half a frame would\n // incorrectly discard the following frame; only merge the same sample position.\n const DUPLICATE_THRESHOLD_US = (0.5 * 1_000_000) / sampleRate;\n\n if (insertIndex < slots.length) {\n const existingSlot = slots[insertIndex]!;\n const timeDiff = Math.abs(existingSlot.timestampUs - audioTimestampUs);\n\n if (timeDiff < DUPLICATE_THRESHOLD_US) {\n // Near-duplicate detected, skip insertion\n return;\n }\n }\n\n // Also check previous slot to catch overlapping duplicates\n if (insertIndex > 0) {\n const prevSlot = slots[insertIndex - 1]!;\n const timeDiff = Math.abs(prevSlot.timestampUs - audioTimestampUs);\n\n if (timeDiff < DUPLICATE_THRESHOLD_US) {\n // Near-duplicate detected, skip insertion\n return;\n }\n }\n\n // Insert new slot\n slots.splice(insertIndex, 0, slot);\n }\n\n getSlotsInWindow(clipId: string, startUs: TimeUs, endUs: TimeUs): AudioDataSlot[] | null {\n const slots = this.audioDataByClip.get(clipId);\n if (!slots || slots.length === 0) {\n return null;\n }\n\n // Use binary search to find overlapping slots\n const overlappingSlots = binarySearchOverlapping(slots, startUs, endUs, (slot) => ({\n start: slot.timestampUs,\n end: slot.timestampUs + slot.durationUs,\n }));\n\n if (overlappingSlots.length === 0) {\n return null;\n }\n\n return overlappingSlots;\n }\n\n getPCM(clipId: string, startUs: TimeUs, endUs: TimeUs): Float32Array[] | null {\n const slots = this.audioDataByClip.get(clipId);\n if (!slots || slots.length === 0) {\n return null;\n }\n\n // Use binary search to find overlapping slots (O(log n + k) vs O(n))\n // Aligned with video GOP/frame search\n const overlappingSlots = binarySearchOverlapping(slots, startUs, endUs, (slot) => ({\n start: slot.timestampUs,\n end: slot.timestampUs + slot.durationUs,\n }));\n\n if (overlappingSlots.length === 0) {\n return null;\n }\n\n const requestedDurationUs = endUs - startUs;\n\n // Validate sample rate consistency across all slots\n const firstSlot = overlappingSlots[0]!;\n const uniformSampleRate = firstSlot.sampleRate;\n const uniformChannels = firstSlot.numberOfChannels;\n\n // Check if all slots have the same sample rate and channel count\n const hasUniformRate = overlappingSlots.every(\n (s) => s.sampleRate === uniformSampleRate && s.numberOfChannels === uniformChannels\n );\n\n if (!hasUniformRate) {\n console.error(\n `[AudioL1Cache] Inconsistent sample rates detected for clip ${clipId}:`,\n overlappingSlots.map((s) => ({\n timestamp: s.timestampUs,\n sampleRate: s.sampleRate,\n channels: s.numberOfChannels,\n }))\n );\n // Return null to avoid corrupted audio data\n // This will trigger re-decode with correct sample rate\n return null;\n }\n\n // Calculate total frame count needed.\n // Note: We intentionally keep ceil here to avoid truncating the requested range.\n const totalFrames = Math.ceil((requestedDurationUs / 1_000_000) * uniformSampleRate);\n\n // Initialize result arrays\n const result: Float32Array[] = Array.from(\n { length: uniformChannels },\n () => new Float32Array(totalFrames)\n );\n\n // Copy data from each overlapping slot.\n // IMPORTANT: Use frame-aligned mapping based on slot plane length instead of time-based floor/ceil.\n // This avoids off-by-one discontinuities at MP3/AAC frame boundaries caused by microsecond rounding.\n for (const slot of overlappingSlots) {\n const slotFrames = slot.planes[0]?.length ?? 0;\n if (slotFrames <= 0) continue;\n\n // Map slot start time to destination frame index (frame-aligned).\n const slotStartFrame = Math.round(\n ((slot.timestampUs - startUs) / 1_000_000) * uniformSampleRate\n );\n const slotEndFrame = slotStartFrame + slotFrames;\n\n // Intersect with requested destination buffer [0, totalFrames)\n const dstStartFrame = Math.max(0, slotStartFrame);\n const dstEndFrame = Math.min(totalFrames, slotEndFrame);\n const copyFrameCount = dstEndFrame - dstStartFrame;\n if (copyFrameCount <= 0) continue;\n\n // Source offset is derived from the chosen destination start.\n const srcOffsetFrames = dstStartFrame - slotStartFrame;\n\n for (let ch = 0; ch < uniformChannels; ch++) {\n const srcPlane = slot.planes[ch];\n const dstPlane = result[ch];\n if (!srcPlane || !dstPlane) continue;\n\n const actualCopyFrames = Math.min(\n copyFrameCount,\n srcPlane.length - srcOffsetFrames,\n dstPlane.length - dstStartFrame\n );\n if (actualCopyFrames <= 0) continue;\n\n dstPlane.set(\n srcPlane.subarray(srcOffsetFrames, srcOffsetFrames + actualCopyFrames),\n dstStartFrame\n );\n }\n }\n\n return result;\n }\n\n getPCMWithMetadata(\n clipId: string,\n startUs: TimeUs,\n endUs: TimeUs\n ): { planes: Float32Array[]; sampleRate: number; numberOfChannels: number } | null {\n const slots = this.audioDataByClip.get(clipId);\n if (!slots || slots.length === 0) {\n return null;\n }\n\n const planes = this.getPCM(clipId, startUs, endUs);\n if (!planes) {\n return null;\n }\n\n // Use first slot's metadata\n const firstSlot = slots[0]!;\n return {\n planes,\n sampleRate: firstSlot.sampleRate,\n numberOfChannels: firstSlot.numberOfChannels,\n };\n }\n\n hasClipPCM(clipId: string): boolean {\n return this.audioDataByClip.has(clipId);\n }\n\n /**\n * Check if a slot with specific timestamp exists (used for incremental decoding)\n */\n hasSlotAt(clipId: string, timestampUs: TimeUs, toleranceUs: number = 1000): boolean {\n const slots = this.audioDataByClip.get(clipId);\n if (!slots) return false;\n\n // Since slots are sorted, we can use binary search\n const index = this.findInsertIndex(slots, timestampUs);\n\n // Check index and index-1 (in case findInsertIndex lands after)\n if (index < slots.length) {\n const slot = slots[index];\n if (slot && Math.abs(slot.timestampUs - timestampUs) < toleranceUs) return true;\n }\n if (index > 0) {\n const slot = slots[index - 1];\n if (slot && Math.abs(slot.timestampUs - timestampUs) < toleranceUs) return true;\n }\n return false;\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), default 0.95\n * @returns Coverage info { covered: boolean, coverageRatio: number }\n */\n getAudioRangeCoverage(\n clipId: string,\n startUs: TimeUs,\n endUs: TimeUs,\n threshold = PREVIEW_PCM_COVERAGE_THRESHOLD\n ): { covered: boolean; coverageRatio: number } {\n const { coveredDurationUs, requestedDurationUs } = this.computeRangeCoverageDuration(\n clipId,\n startUs,\n endUs\n );\n const coverageRatio = requestedDurationUs > 0 ? coveredDurationUs / requestedDurationUs : 0;\n return {\n covered: coverageRatio >= threshold,\n coverageRatio,\n };\n }\n\n private computeRangeCoverageDuration(\n clipId: string,\n startUs: TimeUs,\n endUs: TimeUs\n ): { coveredDurationUs: TimeUs; requestedDurationUs: TimeUs } {\n const requestedDurationUs = Math.max(0, endUs - startUs);\n if (requestedDurationUs === 0) {\n return { coveredDurationUs: 0, requestedDurationUs: 0 };\n }\n\n const slots = this.audioDataByClip.get(clipId);\n if (!slots || slots.length === 0) {\n return { coveredDurationUs: 0, requestedDurationUs };\n }\n\n // Use binary search to find overlapping slots (O(log n + k))\n const overlappingSlots = binarySearchOverlapping(slots, startUs, endUs, (slot) => ({\n start: slot.timestampUs,\n end: slot.timestampUs + slot.durationUs,\n }));\n\n if (overlappingSlots.length === 0) {\n return { coveredDurationUs: 0, requestedDurationUs };\n }\n\n let coveredDurationUs = 0;\n for (const slot of overlappingSlots) {\n const slotEndUs = slot.timestampUs + slot.durationUs;\n const overlapStart = Math.max(startUs, slot.timestampUs);\n const overlapEnd = Math.min(endUs, slotEndUs);\n if (overlapStart < overlapEnd) {\n coveredDurationUs += overlapEnd - overlapStart;\n }\n }\n\n return { coveredDurationUs, requestedDurationUs };\n }\n\n clearClipPCM(clipId: string): void {\n this.audioDataByClip.delete(clipId);\n }\n\n /**\n * Update window center (unified global window)\n * Aligned with VideoL1Cache strategy: maintains a window of ±RADIUS around center\n */\n // setWindow(centerGlobalUs: TimeUs): void {\n // this.windowCenter = centerGlobalUs;\n // this.checkEviction();\n // }\n\n // private checkEviction(): void {\n // const now = Date.now();\n // if (now - this.lastEvictTime > this.EVICT_THROTTLE_MS) {\n // this.evictOutOfWindow();\n // this.lastEvictTime = now;\n // }\n // }\n\n /**\n * Evict audio slots outside the global window (aligned with VideoL1Cache)\n * Skip if eviction is disabled (e.g., during export)\n */\n // private evictOutOfWindow(): void {\n // const windowStart = Math.max(0, this.windowCenter - this.WINDOW_RADIUS);\n // const windowEnd = this.windowCenter + this.WINDOW_RADIUS;\n\n // for (const [clipId, slots] of this.audioDataByClip) {\n // const toKeep: AudioDataSlot[] = [];\n\n // for (const slot of slots) {\n // const globalTime = slot.globalTimeUs;\n\n // // Slots without globalTimeUs are kept (legacy)\n // if (globalTime === undefined) {\n // toKeep.push(slot);\n // continue;\n // }\n\n // // Keep slots within window\n // if (globalTime >= windowStart && globalTime <= windowEnd) {\n // toKeep.push(slot);\n // }\n // // Slots outside window are discarded (no close needed for Float32Array)\n // }\n\n // if (toKeep.length > 0) {\n // this.audioDataByClip.set(clipId, toKeep);\n // } else {\n // this.audioDataByClip.delete(clipId);\n // }\n // }\n // }\n\n /**\n * Find insertion index for a new slot (aligned with VideoL1Cache)\n */\n private findInsertIndex(slots: AudioDataSlot[], timestamp: TimeUs): number {\n return binarySearchFirst(slots, (slot) => slot.timestampUs >= timestamp);\n }\n\n flush(): void {\n this.audioDataByClip.clear();\n }\n\n clear(): void {\n this.flush();\n this.audioDataByClip.clear();\n // this.windowCenter = 0;\n }\n\n dispose(): void {\n this.clear();\n }\n}\n"],"names":[],"mappings":";;AAIO,MAAM,iCAAiC;AACvC,MAAM,gCAAgC;AAatC,MAAM,aAAa;AAAA;AAAA,EAEhB,sCAAsB,IAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAW9B,iBACE,QACA,WACA,iBACA,cACM;AACN,UAAM,mBAAmB,UAAU,oBAAoB;AACvD,UAAM,iBAAiB,UAAU,kBAAkB;AACnD,UAAM,aAAa,UAAU,cAAc;AAC3C,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c,KAAK;AAC1C,YAAM,eAAe,KAAK,IAAI,SAAS,KAAK,WAAW;AACvD,YAAM,aAAa,KAAK,IAAI,OAAO,SAAS;AAC5C,UAAI,eAAe,YAAY;AAC7B,6BAAqB,aAAa;AAAA,MACpC;AAAA,IACF;AAEA,WAAO,EAAE,mBAAmB,oBAAA;AAAA,EAC9B;AAAA,EAEA,aAAa,QAAsB;AACjC,SAAK,gBAAgB,OAAO,MAAM;AAAA,EACpC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAyDQ,gBAAgB,OAAwB,WAA2B;AACzE,WAAO,kBAAkB,OAAO,CAAC,SAAS,KAAK,eAAe,SAAS;AAAA,EACzE;AAAA,EAEA,QAAc;AACZ,SAAK,gBAAgB,MAAA;AAAA,EACvB;AAAA,EAEA,QAAc;AACZ,SAAK,MAAA;AACL,SAAK,gBAAgB,MAAA;AAAA,EAEvB;AAAA,EAEA,UAAgB;AACd,SAAK,MAAA;AAAA,EACP;AACF;"}
1
+ {"version":3,"file":"AudioL1Cache.js","sources":["../../../src/cache/l1/AudioL1Cache.ts"],"sourcesContent":["import type { TimeUs } from '../../model/types';\nimport { binarySearchFirst, binarySearchOverlapping } from '../../utils/binary-search';\nimport { extractPlanesFromAudioData } from '../../utils/audio-data';\n\nexport const PREVIEW_PCM_COVERAGE_THRESHOLD = 0.95;\nexport const EXPORT_PCM_COVERAGE_THRESHOLD = 0.99;\n\ninterface AudioDataSlot {\n timestampUs: TimeUs; // Resource timestamp (aligned with VideoL1Cache)\n durationUs: TimeUs;\n planes: Float32Array[]; // PCM data for this slot\n sampleRate: number;\n numberOfChannels: number;\n globalTimeUs?: TimeUs; // Global timeline time (for window management)\n}\n\nexport type { AudioDataSlot };\n\nexport class AudioL1Cache {\n // Aligned with VideoL1Cache: array of discrete audio data slots per clip\n private audioDataByClip = new Map<string, AudioDataSlot[]>();\n\n private readonly lru = new Map<AudioDataSlot, string>();\n private readonly pins = new Set<{\n key: string;\n startUs: number;\n endUs: number;\n epoch: number;\n copyBytes: number;\n }>();\n private readonly retired = new Map<AudioDataSlot, { key: string; epoch: number }>();\n private bytes = 0;\n private epoch = 0;\n\n constructor(readonly maxBytes = 64 * 1024 * 1024) {\n if (!Number.isFinite(maxBytes) || maxBytes <= 0) throw new Error('Invalid PCM byte budget');\n }\n\n get generation(): number {\n return this.epoch;\n }\n\n /** Reserve the read copy before decoding. Eviction never removes a pinned slot. */\n pinRange(key: string, startUs: number, endUs: number, copyBytes: number) {\n if (copyBytes * 2 > this.maxBytes) throw new RangeError('Audio PCM range exceeds byte budget');\n if (!this.makeRoom(copyBytes))\n throw new RangeError('Audio PCM budget is held by active readers');\n const pin = { key, startUs, endUs, epoch: this.epoch, copyBytes };\n this.pins.add(pin);\n let released = false;\n let data: ReturnType<AudioL1Cache['getPCMWithMetadata']> = null;\n return {\n read: () => {\n if (released || pin.epoch !== this.epoch)\n throw new DOMException('Audio cache invalidated', 'AbortError');\n data ??= this.getPCMWithMetadata(key, startUs, endUs);\n if (data && data.planes.reduce((n, plane) => n + plane.byteLength, 0) > copyBytes) {\n throw new RangeError('Audio PCM read exceeds reserved bytes');\n }\n return data;\n },\n release: () => {\n if (released) return;\n released = true;\n data = null;\n this.pins.delete(pin);\n for (const [slot, owner] of this.retired) {\n if (!this.isPinned(slot, owner.key, owner.epoch)) {\n this.retired.delete(slot);\n this.bytes -= this.slotBytes(slot);\n }\n }\n },\n };\n }\n\n getStats() {\n return {\n slots: this.lru.size + this.retired.size,\n bytes: this.bytes,\n maxBytes: this.maxBytes,\n activeLeases: this.pins.size,\n reservedBytes: this.reservedBytes(),\n pinnedBytes:\n [...this.lru].reduce(\n (n, [slot, key]) => n + (this.isPinned(slot, key) ? this.slotBytes(slot) : 0),\n 0\n ) + [...this.retired.keys()].reduce((n, slot) => n + this.slotBytes(slot), 0),\n };\n }\n\n private slotBytes(slot: AudioDataSlot): number {\n return slot.planes.reduce((n, plane) => n + plane.byteLength, 0);\n }\n\n private reservedBytes(): number {\n return [...this.pins].reduce((n, pin) => n + pin.copyBytes, 0);\n }\n\n private isPinned(slot: AudioDataSlot, key: string, epoch = this.epoch): boolean {\n return [...this.pins].some(\n (pin) =>\n pin.key === key &&\n pin.epoch === epoch &&\n slot.timestampUs < pin.endUs &&\n slot.timestampUs + slot.durationUs > pin.startUs\n );\n }\n\n private makeRoom(incomingBytes: number): boolean {\n for (const [slot, key] of this.lru) {\n if (this.bytes + this.reservedBytes() + incomingBytes <= this.maxBytes) break;\n if (this.isPinned(slot, key)) continue;\n const slots = this.audioDataByClip.get(key)!;\n slots.splice(slots.indexOf(slot), 1);\n if (slots.length === 0) this.audioDataByClip.delete(key);\n this.lru.delete(slot);\n this.bytes -= this.slotBytes(slot);\n }\n return this.bytes + this.reservedBytes() + incomingBytes <= this.maxBytes;\n }\n\n putClipAudioData(\n clipId: string,\n audioData: AudioData,\n _clipDurationUs: TimeUs,\n globalTimeUs?: TimeUs\n ): void {\n const numberOfChannels = audioData.numberOfChannels ?? 2;\n const numberOfFrames = audioData.numberOfFrames ?? 0;\n const sampleRate = audioData.sampleRate ?? 48_000;\n const audioTimestampUs = audioData.timestamp ?? 0;\n const audioDurationUs =\n audioData.duration ?? Math.round((numberOfFrames / sampleRate) * 1_000_000);\n\n if (!numberOfChannels || !numberOfFrames) {\n audioData.close();\n return;\n }\n\n const incomingBytes = numberOfFrames * numberOfChannels * Float32Array.BYTES_PER_ELEMENT;\n const existingSlots = this.audioDataByClip.get(clipId);\n const existingIndex = existingSlots ? this.findInsertIndex(existingSlots, audioTimestampUs) : 0;\n const duplicate = [existingSlots?.[existingIndex], existingSlots?.[existingIndex - 1]].find(\n (slot) => slot && Math.abs(slot.timestampUs - audioTimestampUs) < 500_000 / sampleRate\n );\n if (duplicate) {\n this.lru.delete(duplicate);\n this.lru.set(duplicate, clipId);\n audioData.close();\n return;\n }\n if (!this.makeRoom(incomingBytes)) {\n audioData.close();\n throw new RangeError('Audio PCM byte budget exhausted');\n }\n\n // Extract PCM data\n let planes: Float32Array[];\n try {\n planes = extractPlanesFromAudioData(audioData, numberOfChannels, numberOfFrames);\n } finally {\n audioData.close();\n }\n\n // Create audio data slot (aligned with video architecture)\n const slot: AudioDataSlot = {\n timestampUs: audioTimestampUs,\n durationUs: audioDurationUs,\n planes,\n sampleRate,\n numberOfChannels,\n globalTimeUs,\n };\n // Get or create slots array for this clip\n let slots = this.audioDataByClip.get(clipId);\n if (!slots) {\n slots = [];\n this.audioDataByClip.set(clipId, slots);\n }\n\n // Insert slot in sorted order (aligned with VideoL1Cache.addFrame)\n const insertIndex = this.findInsertIndex(slots, audioTimestampUs);\n\n // Insert new slot\n slots.splice(insertIndex, 0, slot);\n this.lru.set(slot, clipId);\n this.bytes += this.slotBytes(slot);\n }\n\n getSlotsInWindow(clipId: string, startUs: TimeUs, endUs: TimeUs): AudioDataSlot[] | null {\n const slots = this.audioDataByClip.get(clipId);\n if (!slots || slots.length === 0) {\n return null;\n }\n\n // Use binary search to find overlapping slots\n const overlappingSlots = binarySearchOverlapping(slots, startUs, endUs, (slot) => ({\n start: slot.timestampUs,\n end: slot.timestampUs + slot.durationUs,\n }));\n\n if (overlappingSlots.length === 0) {\n return null;\n }\n\n return overlappingSlots;\n }\n\n getPCM(clipId: string, startUs: TimeUs, endUs: TimeUs): Float32Array[] | null {\n const slots = this.audioDataByClip.get(clipId);\n if (!slots || slots.length === 0) {\n return null;\n }\n\n // Use binary search to find overlapping slots (O(log n + k) vs O(n))\n // Aligned with video GOP/frame search\n const overlappingSlots = binarySearchOverlapping(slots, startUs, endUs, (slot) => ({\n start: slot.timestampUs,\n end: slot.timestampUs + slot.durationUs,\n }));\n\n if (overlappingSlots.length === 0) {\n return null;\n }\n\n const requestedDurationUs = endUs - startUs;\n\n // Validate sample rate consistency across all slots\n const firstSlot = overlappingSlots[0]!;\n const uniformSampleRate = firstSlot.sampleRate;\n const uniformChannels = firstSlot.numberOfChannels;\n\n // Check if all slots have the same sample rate and channel count\n const hasUniformRate = overlappingSlots.every(\n (s) => s.sampleRate === uniformSampleRate && s.numberOfChannels === uniformChannels\n );\n\n if (!hasUniformRate) {\n console.error(\n `[AudioL1Cache] Inconsistent sample rates detected for clip ${clipId}:`,\n overlappingSlots.map((s) => ({\n timestamp: s.timestampUs,\n sampleRate: s.sampleRate,\n channels: s.numberOfChannels,\n }))\n );\n // Return null to avoid corrupted audio data\n // This will trigger re-decode with correct sample rate\n return null;\n }\n\n // Calculate total frame count needed.\n // Note: We intentionally keep ceil here to avoid truncating the requested range.\n // Match read reservations and coverage: dividing first can round an exact\n // 44.1 kHz frame count upward and exceed the lease by one sample frame.\n const totalFrames = Math.ceil((requestedDurationUs * uniformSampleRate) / 1_000_000);\n const startFrame = Math.round((startUs * uniformSampleRate) / 1_000_000);\n\n // Initialize result arrays\n const result: Float32Array[] = Array.from(\n { length: uniformChannels },\n () => new Float32Array(totalFrames)\n );\n\n // Copy data from each overlapping slot.\n // IMPORTANT: Use frame-aligned mapping based on slot plane length instead of time-based floor/ceil.\n // This avoids off-by-one discontinuities at MP3/AAC frame boundaries caused by microsecond rounding.\n for (const slot of overlappingSlots) {\n this.lru.delete(slot);\n this.lru.set(slot, clipId);\n const slotFrames = slot.planes[0]?.length ?? 0;\n if (slotFrames <= 0) continue;\n\n // Map slot start time to destination frame index (frame-aligned).\n // Round absolute resource positions before subtracting. A seek halfway\n // between samples otherwise turns timestamp jitter into gaps/overlaps.\n const slotStartFrame =\n Math.round((slot.timestampUs * uniformSampleRate) / 1_000_000) - startFrame;\n const slotEndFrame = slotStartFrame + slotFrames;\n\n // Intersect with requested destination buffer [0, totalFrames)\n const dstStartFrame = Math.max(0, slotStartFrame);\n const dstEndFrame = Math.min(totalFrames, slotEndFrame);\n const copyFrameCount = dstEndFrame - dstStartFrame;\n if (copyFrameCount <= 0) continue;\n\n // Source offset is derived from the chosen destination start.\n const srcOffsetFrames = dstStartFrame - slotStartFrame;\n\n for (let ch = 0; ch < uniformChannels; ch++) {\n const srcPlane = slot.planes[ch];\n const dstPlane = result[ch];\n if (!srcPlane || !dstPlane) continue;\n\n const actualCopyFrames = Math.min(\n copyFrameCount,\n srcPlane.length - srcOffsetFrames,\n dstPlane.length - dstStartFrame\n );\n if (actualCopyFrames <= 0) continue;\n\n dstPlane.set(\n srcPlane.subarray(srcOffsetFrames, srcOffsetFrames + actualCopyFrames),\n dstStartFrame\n );\n }\n }\n\n return result;\n }\n\n getPCMWithMetadata(\n clipId: string,\n startUs: TimeUs,\n endUs: TimeUs\n ): { planes: Float32Array[]; sampleRate: number; numberOfChannels: number } | null {\n const slots = this.audioDataByClip.get(clipId);\n if (!slots || slots.length === 0) {\n return null;\n }\n\n const planes = this.getPCM(clipId, startUs, endUs);\n if (!planes) {\n return null;\n }\n\n // Use first slot's metadata\n const firstSlot = this.getSlotsInWindow(clipId, startUs, endUs)![0]!;\n return {\n planes,\n sampleRate: firstSlot.sampleRate,\n numberOfChannels: firstSlot.numberOfChannels,\n };\n }\n\n hasClipPCM(clipId: string): boolean {\n return this.audioDataByClip.has(clipId);\n }\n\n /**\n * Check if a slot with specific timestamp exists (used for incremental decoding)\n */\n hasSlotAt(clipId: string, timestampUs: TimeUs, toleranceUs: number = 1000): boolean {\n const slots = this.audioDataByClip.get(clipId);\n if (!slots) return false;\n\n // Since slots are sorted, we can use binary search\n const index = this.findInsertIndex(slots, timestampUs);\n\n // Check index and index-1 (in case findInsertIndex lands after)\n if (index < slots.length) {\n const slot = slots[index];\n if (slot && Math.abs(slot.timestampUs - timestampUs) < toleranceUs) return true;\n }\n if (index > 0) {\n const slot = slots[index - 1];\n if (slot && Math.abs(slot.timestampUs - timestampUs) < toleranceUs) return true;\n }\n return false;\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), default 0.95\n * @returns Coverage info { covered: boolean, coverageRatio: number }\n */\n getAudioRangeCoverage(\n clipId: string,\n startUs: TimeUs,\n endUs: TimeUs,\n threshold = PREVIEW_PCM_COVERAGE_THRESHOLD\n ): { covered: boolean; coverageRatio: number } {\n const { coveredDurationUs, requestedDurationUs } = this.computeRangeCoverageDuration(\n clipId,\n startUs,\n endUs\n );\n const coverageRatio = requestedDurationUs > 0 ? coveredDurationUs / requestedDurationUs : 0;\n return {\n covered: coverageRatio >= threshold,\n coverageRatio,\n };\n }\n\n private computeRangeCoverageDuration(\n clipId: string,\n startUs: TimeUs,\n endUs: TimeUs\n ): { coveredDurationUs: TimeUs; requestedDurationUs: TimeUs } {\n const requestedDurationUs = Math.max(0, endUs - startUs);\n if (requestedDurationUs === 0) {\n return { coveredDurationUs: 0, requestedDurationUs: 0 };\n }\n\n const slots = this.audioDataByClip.get(clipId);\n if (!slots || slots.length === 0) {\n return { coveredDurationUs: 0, requestedDurationUs };\n }\n\n // Use binary search to find overlapping slots (O(log n + k))\n const overlappingSlots = binarySearchOverlapping(slots, startUs, endUs, (slot) => ({\n start: slot.timestampUs,\n end: slot.timestampUs + slot.durationUs,\n }));\n\n if (overlappingSlots.length === 0) {\n return { coveredDurationUs: 0, requestedDurationUs };\n }\n\n // Match getPCM's sample-aligned copy positions. Rounded WebCodecs timestamps\n // leave sub-microsecond gaps at 44.1 kHz that are not missing PCM samples.\n const sampleRate = overlappingSlots[0]!.sampleRate;\n const requestedFrames = Math.ceil((requestedDurationUs * sampleRate) / 1_000_000);\n const startFrame = Math.round((startUs * sampleRate) / 1_000_000);\n let coveredFrames = 0;\n let coveredEnd = 0;\n for (const slot of overlappingSlots) {\n const slotStartFrame = Math.round((slot.timestampUs * sampleRate) / 1_000_000) - startFrame;\n const overlapStart = Math.max(coveredEnd, 0, slotStartFrame);\n const overlapEnd = Math.min(requestedFrames, slotStartFrame + (slot.planes[0]?.length ?? 0));\n if (overlapEnd > overlapStart) coveredFrames += overlapEnd - overlapStart;\n coveredEnd = Math.max(coveredEnd, overlapEnd);\n }\n const coveredDurationUs = Math.min(\n requestedDurationUs,\n (coveredFrames / sampleRate) * 1_000_000\n );\n\n return { coveredDurationUs, requestedDurationUs };\n }\n\n clearClipPCM(clipId: string): void {\n for (const slot of this.audioDataByClip.get(clipId) ?? []) {\n this.lru.delete(slot);\n if (this.isPinned(slot, clipId)) this.retired.set(slot, { key: clipId, epoch: this.epoch });\n else this.bytes -= this.slotBytes(slot);\n }\n this.audioDataByClip.delete(clipId);\n }\n\n /**\n * Find insertion index for a new slot (aligned with VideoL1Cache)\n */\n private findInsertIndex(slots: AudioDataSlot[], timestamp: TimeUs): number {\n return binarySearchFirst(slots, (slot) => slot.timestampUs >= timestamp);\n }\n\n flush(): void {\n this.clear();\n }\n\n clear(): void {\n for (const key of this.audioDataByClip.keys()) this.clearClipPCM(key);\n this.epoch++;\n }\n\n dispose(): void {\n this.clear();\n }\n}\n"],"names":["slot"],"mappings":";;AAIO,MAAM,iCAAiC;AACvC,MAAM,gCAAgC;AAatC,MAAM,aAAa;AAAA,EAgBxB,YAAqB,WAAW,KAAK,OAAO,MAAM;AAA7B,SAAA,WAAA;AACnB,QAAI,CAAC,OAAO,SAAS,QAAQ,KAAK,YAAY,EAAG,OAAM,IAAI,MAAM,yBAAyB;AAAA,EAC5F;AAAA;AAAA,EAhBQ,sCAAsB,IAAA;AAAA,EAEb,0BAAU,IAAA;AAAA,EACV,2BAAW,IAAA;AAAA,EAOX,8BAAc,IAAA;AAAA,EACvB,QAAQ;AAAA,EACR,QAAQ;AAAA,EAMhB,IAAI,aAAqB;AACvB,WAAO,KAAK;AAAA,EACd;AAAA;AAAA,EAGA,SAAS,KAAa,SAAiB,OAAe,WAA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