@meframe/core 0.0.4 → 0.0.5

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 (111) hide show
  1. package/dist/Meframe.d.ts +16 -7
  2. package/dist/Meframe.d.ts.map +1 -1
  3. package/dist/Meframe.js +70 -86
  4. package/dist/Meframe.js.map +1 -1
  5. package/dist/cache/CacheManager.d.ts +27 -10
  6. package/dist/cache/CacheManager.d.ts.map +1 -1
  7. package/dist/cache/CacheManager.js +92 -30
  8. package/dist/cache/CacheManager.js.map +1 -1
  9. package/dist/cache/L2Cache.d.ts +31 -2
  10. package/dist/cache/L2Cache.d.ts.map +1 -1
  11. package/dist/cache/L2Cache.js +245 -44
  12. package/dist/cache/L2Cache.js.map +1 -1
  13. package/dist/cache/l1/VideoL1Cache.d.ts +1 -1
  14. package/dist/cache/l1/VideoL1Cache.js.map +1 -1
  15. package/dist/controllers/PreRenderService.d.ts +21 -4
  16. package/dist/controllers/PreRenderService.d.ts.map +1 -1
  17. package/dist/controllers/PreRenderService.js +67 -5
  18. package/dist/controllers/PreRenderService.js.map +1 -1
  19. package/dist/model/CompositionModel.d.ts +1 -1
  20. package/dist/model/CompositionModel.js +1 -1
  21. package/dist/model/CompositionModel.js.map +1 -1
  22. package/dist/model/patch.d.ts +1 -1
  23. package/dist/model/patch.js.map +1 -1
  24. package/dist/node_modules/.pnpm/mp4-muxer@5.2.2/node_modules/mp4-muxer/build/mp4-muxer.js +1858 -0
  25. package/dist/node_modules/.pnpm/mp4-muxer@5.2.2/node_modules/mp4-muxer/build/mp4-muxer.js.map +1 -0
  26. package/dist/orchestrator/ClipSessionManager.d.ts +1 -2
  27. package/dist/orchestrator/ClipSessionManager.d.ts.map +1 -1
  28. package/dist/orchestrator/ClipSessionManager.js +1 -0
  29. package/dist/orchestrator/ClipSessionManager.js.map +1 -1
  30. package/dist/orchestrator/CompositionPlanner.d.ts +1 -1
  31. package/dist/orchestrator/CompositionPlanner.js +1 -1
  32. package/dist/orchestrator/CompositionPlanner.js.map +1 -1
  33. package/dist/orchestrator/Orchestrator.d.ts +9 -1
  34. package/dist/orchestrator/Orchestrator.d.ts.map +1 -1
  35. package/dist/orchestrator/Orchestrator.js +65 -35
  36. package/dist/orchestrator/Orchestrator.js.map +1 -1
  37. package/dist/orchestrator/VideoClipSession.d.ts +11 -4
  38. package/dist/orchestrator/VideoClipSession.d.ts.map +1 -1
  39. package/dist/orchestrator/VideoClipSession.js +54 -28
  40. package/dist/orchestrator/VideoClipSession.js.map +1 -1
  41. package/dist/stages/compose/GlobalAudioSession.d.ts +28 -1
  42. package/dist/stages/compose/GlobalAudioSession.d.ts.map +1 -1
  43. package/dist/stages/compose/GlobalAudioSession.js +133 -5
  44. package/dist/stages/compose/GlobalAudioSession.js.map +1 -1
  45. package/dist/stages/compose/VideoComposer.d.ts +1 -0
  46. package/dist/stages/compose/VideoComposer.d.ts.map +1 -1
  47. package/dist/stages/demux/MP4Demuxer.d.ts.map +1 -1
  48. package/dist/stages/encode/AudioChunkEncoder.d.ts +2 -1
  49. package/dist/stages/encode/AudioChunkEncoder.d.ts.map +1 -1
  50. package/dist/stages/encode/AudioChunkEncoder.js +41 -0
  51. package/dist/stages/encode/AudioChunkEncoder.js.map +1 -0
  52. package/dist/stages/encode/BaseEncoder.d.ts +7 -3
  53. package/dist/stages/encode/BaseEncoder.d.ts.map +1 -1
  54. package/dist/stages/encode/BaseEncoder.js +173 -0
  55. package/dist/stages/encode/BaseEncoder.js.map +1 -0
  56. package/dist/stages/encode/ClipEncoderManager.d.ts +64 -0
  57. package/dist/stages/encode/ClipEncoderManager.d.ts.map +1 -0
  58. package/dist/stages/encode/index.d.ts +1 -1
  59. package/dist/stages/encode/index.d.ts.map +1 -1
  60. package/dist/stages/load/ResourceLoader.d.ts.map +1 -1
  61. package/dist/stages/load/ResourceLoader.js +17 -12
  62. package/dist/stages/load/ResourceLoader.js.map +1 -1
  63. package/dist/stages/load/TaskManager.d.ts +1 -1
  64. package/dist/stages/load/TaskManager.d.ts.map +1 -1
  65. package/dist/stages/load/TaskManager.js +2 -2
  66. package/dist/stages/load/TaskManager.js.map +1 -1
  67. package/dist/stages/load/types.d.ts +2 -2
  68. package/dist/stages/load/types.d.ts.map +1 -1
  69. package/dist/stages/mux/MP4Muxer.d.ts +19 -38
  70. package/dist/stages/mux/MP4Muxer.d.ts.map +1 -1
  71. package/dist/stages/mux/MP4Muxer.js +60 -0
  72. package/dist/stages/mux/MP4Muxer.js.map +1 -0
  73. package/dist/stages/mux/MuxManager.d.ts +27 -0
  74. package/dist/stages/mux/MuxManager.d.ts.map +1 -0
  75. package/dist/stages/mux/MuxManager.js +148 -0
  76. package/dist/stages/mux/MuxManager.js.map +1 -0
  77. package/dist/stages/mux/index.d.ts +1 -0
  78. package/dist/stages/mux/index.d.ts.map +1 -1
  79. package/dist/stages/mux/types.d.ts +1 -0
  80. package/dist/stages/mux/types.d.ts.map +1 -1
  81. package/dist/types.d.ts +1 -1
  82. package/dist/types.d.ts.map +1 -1
  83. package/dist/worker/WorkerPool.d.ts.map +1 -1
  84. package/dist/worker/WorkerPool.js +2 -4
  85. package/dist/worker/WorkerPool.js.map +1 -1
  86. package/dist/worker/types.d.ts +1 -4
  87. package/dist/worker/types.d.ts.map +1 -1
  88. package/dist/worker/types.js +0 -3
  89. package/dist/worker/types.js.map +1 -1
  90. package/dist/worker/worker-event-whitelist.d.ts.map +1 -1
  91. package/dist/workers/MP4Demuxer.js +7049 -6
  92. package/dist/workers/MP4Demuxer.js.map +1 -1
  93. package/dist/workers/WorkerChannel.js +0 -3
  94. package/dist/workers/WorkerChannel.js.map +1 -1
  95. package/dist/workers/stages/compose/video-compose.worker.js +25 -14
  96. package/dist/workers/stages/compose/video-compose.worker.js.map +1 -1
  97. package/dist/workers/stages/decode/decode.worker.js +25 -16
  98. package/dist/workers/stages/decode/decode.worker.js.map +1 -1
  99. package/dist/workers/stages/demux/audio-demux.worker.js +4 -4
  100. package/dist/workers/stages/demux/audio-demux.worker.js.map +1 -1
  101. package/dist/workers/stages/demux/video-demux.worker.js +9 -7
  102. package/dist/workers/stages/demux/video-demux.worker.js.map +1 -1
  103. package/dist/workers/stages/encode/encode.worker.js +191 -195
  104. package/dist/workers/stages/encode/encode.worker.js.map +1 -1
  105. package/package.json +2 -1
  106. package/dist/stages/encode/EncoderPool.d.ts +0 -28
  107. package/dist/stages/encode/EncoderPool.d.ts.map +0 -1
  108. package/dist/workers/mp4box.all.js +0 -7049
  109. package/dist/workers/mp4box.all.js.map +0 -1
  110. package/dist/workers/stages/mux/mux.worker.js +0 -501
  111. package/dist/workers/stages/mux/mux.worker.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"L2Cache.js","sources":["../../src/cache/L2Cache.ts"],"sourcesContent":["import type { TimeUs } from '../model/types';\n// import type { ClipMetadata } from './types';\nimport { binarySearchRange } from '../utils/binary-search';\n\ninterface ChunkBatch {\n startUs: TimeUs;\n durationUs: TimeUs;\n byteOffset: number;\n byteLength: number;\n}\n\ninterface ChunkRecord {\n clipId: string;\n track: 'video' | 'audio';\n fileName: string;\n batches: ChunkBatch[];\n lastAccess: number;\n totalBytes: number;\n}\n\ninterface L2Config {\n maxSizeMB: number;\n projectId: string;\n}\n\nexport class L2Cache {\n private db: IDBDatabase | null = null;\n private opfsRoot: FileSystemDirectoryHandle | null = null;\n readonly maxSize: number;\n readonly projectId: string;\n private initPromise: Promise<void> | null = null;\n\n constructor(config: L2Config) {\n this.maxSize = config.maxSizeMB * 1024 * 1024;\n this.projectId = config.projectId;\n }\n\n async init(): Promise<void> {\n if (this.initPromise) return this.initPromise;\n\n this.initPromise = this.initStorage();\n return this.initPromise;\n }\n\n async get(timeUs: TimeUs, clipId: string): Promise<EncodedVideoChunk | EncodedAudioChunk | null> {\n await this.init();\n\n if (!this.db) return null;\n\n // Query IndexedDB for chunk metadata\n const tx = this.db.transaction('chunks', 'readonly');\n const store = tx.objectStore('chunks');\n const records = await this.collectRecords(store, clipId);\n\n for (const record of records) {\n const batch = binarySearchRange(record.batches, timeUs, (b) => ({\n start: b.startUs,\n end: b.startUs + b.durationUs,\n }));\n\n if (!batch) {\n continue;\n }\n\n const chunkData = await this.readFromOPFS(record.fileName, batch);\n if (!chunkData) continue;\n\n this.updateLastAccess(record.clipId, record.track);\n\n return this.createChunk(chunkData, timeUs, record.track);\n }\n\n return null;\n }\n\n async put(\n clipId: string,\n chunks: Array<EncodedVideoChunk | EncodedAudioChunk>,\n track: 'video' | 'audio'\n ): Promise<void> {\n await this.init();\n\n if (!this.db || !this.opfsRoot) return;\n\n const fileName = `clip-${clipId}-${track[0]}1.${track === 'video' ? 'webm' : 'm4a'}`;\n\n // Write chunks to OPFS\n const batches = await this.writeToOPFS(fileName, chunks);\n\n // Calculate total size\n const totalBytes = batches.reduce((sum, b) => sum + b.byteLength, 0);\n\n // Update IndexedDB index\n const tx = this.db.transaction('chunks', 'readwrite');\n const store = tx.objectStore('chunks');\n\n const record: ChunkRecord = {\n clipId,\n track,\n fileName,\n batches,\n lastAccess: Date.now(),\n totalBytes,\n };\n\n await this.promisifyRequest(store.put(record));\n\n // Check and enforce quota\n await this.enforceQuota();\n }\n\n async invalidateRange(startUs: TimeUs, endUs: TimeUs, clipId?: string): Promise<void> {\n await this.init();\n\n if (!this.db) return;\n\n const tx = this.db.transaction('chunks', 'readwrite');\n const store = tx.objectStore('chunks');\n const keysToDelete: Array<[string, string]> = [];\n\n // Iterate through all records\n const cursor = store.openCursor();\n await new Promise<void>((resolve) => {\n cursor.onsuccess = (event) => {\n const cursor = (event.target as IDBRequest).result;\n if (!cursor) {\n resolve();\n return;\n }\n\n const record: ChunkRecord = cursor.value;\n\n if (clipId && record.clipId !== clipId) {\n cursor.continue();\n return;\n }\n\n // Check if any batch overlaps with invalidation range\n const hasOverlap = record.batches.some((batch) => {\n const batchEnd = batch.startUs + batch.durationUs;\n return batch.startUs < endUs && batchEnd > startUs;\n });\n\n if (hasOverlap) {\n keysToDelete.push([record.clipId, record.track]);\n }\n\n cursor.continue();\n };\n });\n\n // Delete invalidated entries\n for (const key of keysToDelete) {\n await this.deleteEntry(key[0], key[1]);\n }\n }\n\n async invalidateClip(clipId: string): Promise<void> {\n await this.init();\n\n if (!this.db) return;\n\n const tx = this.db.transaction('chunks', 'readwrite');\n const store = tx.objectStore('chunks');\n const records = await this.collectRecords(store, clipId);\n\n for (const record of records) {\n await this.deleteEntry(record.clipId, record.track);\n }\n }\n\n async clear(): Promise<void> {\n await this.init();\n\n if (!this.db || !this.opfsRoot) return;\n\n // Clear IndexedDB\n const tx = this.db.transaction(['chunks', 'meta'], 'readwrite');\n await this.promisifyRequest(tx.objectStore('chunks').clear());\n await this.promisifyRequest(tx.objectStore('meta').clear());\n\n // Clear OPFS files\n const projectDir = await this.opfsRoot.getDirectoryHandle(`meframe-project-${this.projectId}`, {\n create: false,\n });\n await this.opfsRoot.removeEntry(projectDir.name, { recursive: true });\n }\n\n private async initStorage(): Promise<void> {\n // Initialize OPFS\n this.opfsRoot = await navigator.storage.getDirectory();\n\n // Initialize IndexedDB\n const request = indexedDB.open('meframe_cache', 1);\n\n request.onupgradeneeded = (event) => {\n const db = (event.target as IDBOpenDBRequest).result;\n\n // chunks store with composite key\n if (!db.objectStoreNames.contains('chunks')) {\n const store = db.createObjectStore('chunks', {\n keyPath: ['clipId', 'track'],\n });\n store.createIndex('lastAccess', 'lastAccess');\n }\n\n // meta store\n if (!db.objectStoreNames.contains('meta')) {\n db.createObjectStore('meta', { keyPath: 'projectId' });\n }\n };\n\n this.db = await new Promise((resolve, reject) => {\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n });\n }\n\n private async readFromOPFS(fileName: string, batch: ChunkBatch): Promise<ArrayBuffer | null> {\n if (!this.opfsRoot) return null;\n\n const projectDir = await this.opfsRoot.getDirectoryHandle(`meframe-project-${this.projectId}`, {\n create: false,\n });\n const fileHandle = await projectDir.getFileHandle(fileName);\n const file = await fileHandle.getFile();\n const slice = file.slice(batch.byteOffset, batch.byteOffset + batch.byteLength);\n return await slice.arrayBuffer();\n }\n\n private async writeToOPFS(\n fileName: string,\n chunks: Array<EncodedVideoChunk | EncodedAudioChunk>\n ): Promise<ChunkBatch[]> {\n if (!this.opfsRoot) return [];\n\n const projectDir = await this.opfsRoot.getDirectoryHandle(`meframe-project-${this.projectId}`, {\n create: true,\n });\n const fileHandle = await projectDir.getFileHandle(fileName, { create: true });\n const writable = await fileHandle.createWritable();\n\n const batches: ChunkBatch[] = [];\n let offset = 0;\n\n for (const chunk of chunks) {\n const data = await this.chunkToArrayBuffer(chunk);\n await writable.write({ type: 'write', position: offset, data });\n\n batches.push({\n startUs: chunk.timestamp,\n durationUs: chunk.duration || 0,\n byteOffset: offset,\n byteLength: data.byteLength,\n });\n\n offset += data.byteLength;\n }\n\n await writable.close();\n return batches;\n }\n\n private async chunkToArrayBuffer(\n chunk: EncodedVideoChunk | EncodedAudioChunk\n ): Promise<ArrayBuffer> {\n const buffer = new ArrayBuffer(chunk.byteLength);\n chunk.copyTo(buffer);\n return buffer;\n }\n\n private createChunk(\n data: ArrayBuffer,\n timeUs: TimeUs,\n track: 'video' | 'audio'\n ): EncodedVideoChunk | EncodedAudioChunk {\n if (track === 'video') {\n return new EncodedVideoChunk({\n type: 'key', // Should be determined from metadata\n timestamp: timeUs,\n data,\n });\n } else {\n return new EncodedAudioChunk({\n type: 'key',\n timestamp: timeUs,\n data,\n });\n }\n }\n\n private async updateLastAccess(clipId: string, track: string): Promise<void> {\n if (!this.db) return;\n\n const tx = this.db.transaction('chunks', 'readwrite');\n const store = tx.objectStore('chunks');\n const record = await this.promisifyRequest<ChunkRecord>(store.get([clipId, track]));\n\n if (record) {\n record.lastAccess = Date.now();\n await this.promisifyRequest(store.put(record));\n }\n }\n\n private async deleteEntry(clipId: string, track: string): Promise<void> {\n if (!this.db) return;\n\n const tx = this.db.transaction('chunks', 'readwrite');\n const store = tx.objectStore('chunks');\n const record = await this.promisifyRequest<ChunkRecord>(store.get([clipId, track]));\n\n if (record && this.opfsRoot) {\n // Delete OPFS file\n const projectDir = await this.opfsRoot.getDirectoryHandle(\n `meframe-project-${this.projectId}`,\n { create: false }\n );\n await projectDir.removeEntry(record.fileName);\n }\n\n // Delete IndexedDB record\n await this.promisifyRequest(store.delete([clipId, track]));\n }\n\n private async enforceQuota(): Promise<void> {\n const estimate = await navigator.storage.estimate();\n const usage = estimate.usage || 0;\n\n if (usage <= this.maxSize) return;\n\n if (!this.db) return;\n\n // Delete oldest entries until under quota\n const tx = this.db.transaction('chunks', 'readwrite');\n const store = tx.objectStore('chunks');\n const index = store.index('lastAccess');\n\n let bytesDeleted = 0;\n const toDelete = usage - this.maxSize;\n\n const cursor = index.openCursor();\n await new Promise<void>((resolve) => {\n cursor.onsuccess = async (event) => {\n const cursor = (event.target as IDBRequest).result;\n if (!cursor || bytesDeleted >= toDelete) {\n resolve();\n return;\n }\n\n const record: ChunkRecord = cursor.value;\n await this.deleteEntry(record.clipId, record.track);\n bytesDeleted += record.totalBytes;\n\n cursor.continue();\n };\n });\n }\n\n private async collectRecords(store: IDBObjectStore, clipId: string): Promise<ChunkRecord[]> {\n const records: ChunkRecord[] = [];\n const cursor = store.openCursor();\n await new Promise<void>((resolve) => {\n cursor.onsuccess = (event) => {\n const cursor = (event.target as IDBRequest).result;\n if (!cursor) {\n resolve();\n return;\n }\n\n const record: ChunkRecord = cursor.value;\n if (record.clipId === clipId) {\n records.push(record);\n }\n\n cursor.continue();\n };\n });\n return records;\n }\n\n private promisifyRequest<T>(request: IDBRequest): Promise<T> {\n return new Promise((resolve, reject) => {\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n });\n }\n\n getMetadata(): {\n maxSizeMB: number;\n usedSizeMB: number;\n entries: number;\n hitRate: number;\n } {\n // This is a simplified implementation\n // In a real implementation, we would track actual usage\n return {\n maxSizeMB: this.maxSize / (1024 * 1024),\n usedSizeMB: 0, // Would need to track actual usage\n entries: 0, // Would need to track actual entries\n hitRate: 0, // Would need to track hits and misses\n };\n }\n\n async hasAvailableQuota(sizeMB: number): Promise<boolean> {\n if (typeof navigator === 'undefined' || !navigator.storage?.estimate) {\n // L2Cache requires storage API to function\n throw new Error('Storage API not available');\n }\n\n const estimate = await navigator.storage.estimate();\n const availableMB = ((estimate.quota || 0) - (estimate.usage || 0)) / (1024 * 1024);\n return availableMB >= sizeMB;\n }\n}\n"],"names":["cursor"],"mappings":";AAyBO,MAAM,QAAQ;AAAA,EACX,KAAyB;AAAA,EACzB,WAA6C;AAAA,EAC5C;AAAA,EACA;AAAA,EACD,cAAoC;AAAA,EAE5C,YAAY,QAAkB;AAC5B,SAAK,UAAU,OAAO,YAAY,OAAO;AACzC,SAAK,YAAY,OAAO;AAAA,EAC1B;AAAA,EAEA,MAAM,OAAsB;AAC1B,QAAI,KAAK,YAAa,QAAO,KAAK;AAElC,SAAK,cAAc,KAAK,YAAA;AACxB,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,MAAM,IAAI,QAAgB,QAAuE;AAC/F,UAAM,KAAK,KAAA;AAEX,QAAI,CAAC,KAAK,GAAI,QAAO;AAGrB,UAAM,KAAK,KAAK,GAAG,YAAY,UAAU,UAAU;AACnD,UAAM,QAAQ,GAAG,YAAY,QAAQ;AACrC,UAAM,UAAU,MAAM,KAAK,eAAe,OAAO,MAAM;AAEvD,eAAW,UAAU,SAAS;AAC5B,YAAM,QAAQ,kBAAkB,OAAO,SAAS,QAAQ,CAAC,OAAO;AAAA,QAC9D,OAAO,EAAE;AAAA,QACT,KAAK,EAAE,UAAU,EAAE;AAAA,MAAA,EACnB;AAEF,UAAI,CAAC,OAAO;AACV;AAAA,MACF;AAEA,YAAM,YAAY,MAAM,KAAK,aAAa,OAAO,UAAU,KAAK;AAChE,UAAI,CAAC,UAAW;AAEhB,WAAK,iBAAiB,OAAO,QAAQ,OAAO,KAAK;AAEjD,aAAO,KAAK,YAAY,WAAW,QAAQ,OAAO,KAAK;AAAA,IACzD;AAEA,WAAO;AAAA,EACT;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sB;AAC5C,YAAI,CAACA,SAAQ;AACX,kBAAA;AACA;AAAA,QACF;AAEA,cAAM,SAAsBA,QAAO;AACnC,YAAI,OAAO,WAAW,QAAQ;AAC5B,kBAAQ,KAAK,MAAM;AAAA,QACrB;AAEAA,gBAAO,SAAA;AAAA,MACT;AAAA,IACF,CAAC;AACD,WAAO;AAAA,EACT;AAAA,EAEQ,iBAAoB,SAAiC;AAC3D,WAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,cAAQ,YAAY,MAAM,QAAQ,QAAQ,MAAM;AAChD,cAAQ,UAAU,MAAM,OAAO,QAAQ,KAAK;AAAA,IAC9C,CAAC;AAAA,EACH;AAAA,EAEA,cAKE;AAGA,WAAO;AAAA,MACL,WAAW,KAAK,WAAW,OAAO;AAAA,MAClC,YAAY;AAAA;AAAA,MACZ,SAAS;AAAA;AAAA,MACT,SAAS;AAAA;AAAA,IAAA;AAAA,EAEb;AAAA,EAEA,MAAM,kBAAkB,QAAkC;AACxD,QAAI,OAAO,cAAc,eAAe,CAAC,UAAU,SAAS,UAAU;AAEpE,YAAM,IAAI,MAAM,2BAA2B;AAAA,IAC7C;AAEA,UAAM,WAAW,MAAM,UAAU,QAAQ,SAAA;AACzC,UAAM,gBAAgB,SAAS,SAAS,MAAM,SAAS,SAAS,OAAO,OAAO;AAC9E,WAAO,eAAe;AAAA,EACxB;AACF;"}
1
+ {"version":3,"file":"L2Cache.js","sources":["../../src/cache/L2Cache.ts"],"sourcesContent":["import type { TimeUs } from '../model/types';\n// import type { ClipMetadata } from './types';\nimport { binarySearchRange } from '../utils/binary-search';\n\ninterface ChunkBatch {\n startUs: TimeUs;\n durationUs: TimeUs;\n byteOffset: number;\n byteLength: number;\n type: 'key' | 'delta'; // Store chunk type for correct reconstruction\n}\n\ninterface ChunkRecord {\n clipId: string; // IndexedDB keyPath uses clipId\n track: 'video' | 'audio';\n fileName: string;\n batches: ChunkBatch[];\n lastAccess: number;\n totalBytes: number;\n isComplete: boolean; // Mark if clip is fully rendered\n expectedDurationUs?: number; // Expected duration for validation\n metadata?: {\n codec?: string;\n description?: Uint8Array;\n codedWidth?: number;\n codedHeight?: number;\n displayAspectWidth?: number;\n displayAspectHeight?: number;\n colorSpace?: VideoColorSpaceInit;\n hardwareAcceleration?: HardwareAcceleration;\n optimizeForLatency?: boolean;\n sampleRate?: number;\n numberOfChannels?: number;\n };\n}\n\ninterface L2Config {\n maxSizeMB: number;\n projectId: string;\n}\n\nexport class L2Cache {\n private db: IDBDatabase | null = null;\n private opfsRoot: FileSystemDirectoryHandle | null = null;\n readonly maxSize: number;\n readonly projectId: string;\n private initPromise: Promise<void> | null = null;\n\n constructor(config: L2Config) {\n this.maxSize = config.maxSizeMB * 1024 * 1024;\n this.projectId = config.projectId;\n }\n\n async init(): Promise<void> {\n if (this.initPromise) return this.initPromise;\n\n this.initPromise = this.initStorage();\n return this.initPromise;\n }\n\n async get(timeUs: TimeUs, clipId: string): Promise<EncodedVideoChunk | EncodedAudioChunk | null> {\n await this.init();\n\n if (!this.db) return null;\n\n // Query IndexedDB for chunk metadata\n const tx = this.db.transaction('chunks', 'readonly');\n const store = tx.objectStore('chunks');\n const records = await this.collectRecords(store, clipId);\n\n for (const record of records) {\n const batch = binarySearchRange(record.batches, timeUs, (b) => ({\n start: b.startUs,\n end: b.startUs + b.durationUs,\n }));\n\n if (!batch) {\n continue;\n }\n\n const chunkData = await this.readFromOPFS(record.fileName, batch);\n if (!chunkData) continue;\n\n this.updateLastAccess(record.clipId, record.track);\n\n return this.createChunk(chunkData, timeUs, record.track, batch.type, batch.durationUs);\n }\n\n return null;\n }\n\n async put(\n clipId: string,\n chunks: Array<EncodedVideoChunk | EncodedAudioChunk>,\n track: 'video' | 'audio',\n options?: {\n isComplete?: boolean;\n expectedDurationUs?: number;\n metadata?: any;\n }\n ): Promise<void> {\n await this.init();\n\n if (!this.db || !this.opfsRoot) {\n console.warn(`[L2Cache] put aborted: db=${!!this.db}, opfsRoot=${!!this.opfsRoot}`);\n return;\n }\n if (chunks.length === 0) return;\n\n const fileName = `clip-${clipId}-${track[0]}1.${track === 'video' ? 'webm' : 'm4a'}`;\n\n // Step 1: Read existing record (separate transaction)\n let existingRecord: ChunkRecord | undefined;\n {\n const tx = this.db.transaction('chunks', 'readonly');\n const store = tx.objectStore('chunks');\n existingRecord = await this.promisifyRequest<ChunkRecord>(store.get([clipId, track]));\n }\n\n // Step 2: Validate consistency - if IndexedDB has record but OPFS file missing, delete the record\n if (existingRecord) {\n const projectDir = await this.opfsRoot.getDirectoryHandle(\n `meframe-project-${this.projectId}`,\n {\n create: true,\n }\n );\n try {\n await projectDir.getFileHandle(existingRecord.fileName, { create: false });\n } catch (error) {\n if ((error as any)?.name === 'NotFoundError') {\n await this.deleteEntry(clipId, track);\n existingRecord = undefined;\n }\n }\n }\n\n // Step 3: Deduplicate based on timestamp\n let chunksToWrite = chunks;\n if (existingRecord && existingRecord.batches.length > 0) {\n const lastBatch = existingRecord.batches[existingRecord.batches.length - 1];\n if (lastBatch) {\n const lastTimestamp = lastBatch.startUs;\n // Filter out chunks with timestamp <= lastTimestamp\n chunksToWrite = chunks.filter((chunk) => chunk.timestamp > lastTimestamp);\n\n if (chunksToWrite.length === 0) {\n return;\n }\n }\n }\n\n // Step 3: Write to OPFS (no active transaction)\n const newBatches = await this.appendToOPFS(fileName, chunksToWrite, existingRecord?.batches);\n\n // Step 4: Update IndexedDB (new transaction)\n {\n const tx = this.db.transaction('chunks', 'readwrite');\n const store = tx.objectStore('chunks');\n\n const record: ChunkRecord = {\n clipId,\n track,\n fileName,\n batches: existingRecord?.batches ? [...existingRecord.batches, ...newBatches] : newBatches,\n lastAccess: Date.now(),\n totalBytes:\n (existingRecord?.totalBytes || 0) + newBatches.reduce((sum, b) => sum + b.byteLength, 0),\n isComplete: options?.isComplete ?? existingRecord?.isComplete ?? false,\n expectedDurationUs: options?.expectedDurationUs ?? existingRecord?.expectedDurationUs,\n metadata: options?.metadata ?? existingRecord?.metadata,\n };\n\n store.put(record);\n // Wait for transaction to complete, not just the request\n await new Promise<void>((resolve, reject) => {\n tx.oncomplete = () => {\n resolve();\n };\n tx.onerror = () => {\n console.error(`[L2Cache] Transaction error for ${clipId} ${track}:`, tx.error);\n reject(tx.error);\n };\n });\n }\n\n // Check and enforce quota\n await this.enforceQuota();\n }\n\n async invalidateRange(startUs: TimeUs, endUs: TimeUs, clipId?: string): Promise<void> {\n await this.init();\n\n if (!this.db) return;\n\n const tx = this.db.transaction('chunks', 'readwrite');\n const store = tx.objectStore('chunks');\n const keysToDelete: Array<[string, string]> = [];\n\n // Iterate through all records\n const cursor = store.openCursor();\n await new Promise<void>((resolve) => {\n cursor.onsuccess = (event) => {\n const cursor = (event.target as IDBRequest).result;\n if (!cursor) {\n resolve();\n return;\n }\n\n const record: ChunkRecord = cursor.value;\n\n if (clipId && record.clipId !== clipId) {\n cursor.continue();\n return;\n }\n\n // Check if any batch overlaps with invalidation range\n const hasOverlap = record.batches.some((batch) => {\n const batchEnd = batch.startUs + batch.durationUs;\n return batch.startUs < endUs && batchEnd > startUs;\n });\n\n if (hasOverlap) {\n keysToDelete.push([record.clipId, record.track]);\n }\n\n cursor.continue();\n };\n });\n\n // Delete invalidated entries\n for (const key of keysToDelete) {\n await this.deleteEntry(key[0], key[1]);\n }\n }\n\n /**\n * Check if clip has cached data in L2\n */\n async hasClip(clipId: string, track: 'video' | 'audio'): Promise<boolean> {\n await this.init();\n\n if (!this.db) return false;\n\n const tx = this.db.transaction('chunks', 'readonly');\n const store = tx.objectStore('chunks');\n const record = await this.promisifyRequest<ChunkRecord>(store.get([clipId, track]));\n\n return record !== undefined && record.batches && record.batches.length > 0;\n }\n\n /**\n * Check if clip has complete cached data in L2\n */\n async hasCompleteClip(clipId: string, track: 'video' | 'audio'): Promise<boolean> {\n await this.init();\n\n if (!this.db) {\n console.warn(`[L2Cache] hasCompleteClip: db not initialized`);\n return false;\n }\n\n const tx = this.db.transaction('chunks', 'readonly');\n const store = tx.objectStore('chunks');\n const record = await this.promisifyRequest<ChunkRecord>(store.get([clipId, track]));\n\n const result = record?.isComplete === true;\n return result;\n }\n\n /**\n * Mark clip as complete in L2 cache\n */\n async markComplete(clipId: string, track: 'video' | 'audio'): Promise<void> {\n await this.init();\n\n if (!this.db) return;\n\n const tx = this.db.transaction('chunks', 'readwrite');\n const store = tx.objectStore('chunks');\n const record = await this.promisifyRequest<ChunkRecord>(store.get([clipId, track]));\n\n if (record) {\n record.isComplete = true;\n record.lastAccess = Date.now();\n store.put(record);\n // Wait for transaction to complete\n await new Promise<void>((resolve, reject) => {\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n });\n console.log(`[L2Cache] markComplete(${clipId}, ${track}): marked successfully`);\n } else {\n console.warn(`[L2Cache] markComplete(${clipId}, ${track}): no record found, cannot mark`);\n }\n }\n\n async invalidateClip(clipId: string): Promise<void> {\n await this.init();\n\n if (!this.db) return;\n\n // Collect records to delete\n const recordsToDelete: ChunkRecord[] = [];\n {\n const tx = this.db.transaction('chunks', 'readonly');\n const store = tx.objectStore('chunks');\n recordsToDelete.push(...(await this.collectRecords(store, clipId)));\n }\n\n // Delete each record\n for (const record of recordsToDelete) {\n await this.deleteEntry(record.clipId, record.track);\n }\n }\n\n /**\n * Create a readable stream of encoded chunks for export\n * Reads chunks in timestamp order from OPFS\n */\n async createReadStream(\n clipId: string,\n track: 'video' | 'audio'\n ): Promise<ReadableStream<EncodedVideoChunk | EncodedAudioChunk> | null> {\n await this.init();\n\n if (!this.db || !this.opfsRoot) return null;\n\n // Get chunk record\n const tx = this.db.transaction('chunks', 'readonly');\n const store = tx.objectStore('chunks');\n const record = await this.promisifyRequest<ChunkRecord>(store.get([clipId, track]));\n\n if (!record || record.batches.length === 0) {\n return null;\n }\n\n // Clone batches array for stream iteration\n const batches = [...record.batches];\n let batchIndex = 0;\n\n return new ReadableStream<EncodedVideoChunk | EncodedAudioChunk>({\n pull: async (controller) => {\n if (batchIndex >= batches.length) {\n controller.close();\n return;\n }\n\n const batch = batches[batchIndex];\n if (!batch) {\n controller.close();\n return;\n }\n\n // Read chunk data from OPFS\n const chunkData = await this.readFromOPFS(record.fileName, batch);\n if (!chunkData) {\n controller.error(new Error(`Failed to read chunk at index ${batchIndex}`));\n return;\n }\n\n // Create encoded chunk with correct type and duration\n const chunk = this.createChunk(\n chunkData,\n batch.startUs,\n track,\n batch.type,\n batch.durationUs\n );\n controller.enqueue(chunk);\n\n batchIndex++;\n },\n });\n }\n\n async clear(): Promise<void> {\n await this.init();\n\n if (!this.db || !this.opfsRoot) {\n console.warn('[L2Cache] clear() called but db or opfsRoot not available');\n return;\n }\n\n // Clear IndexedDB\n try {\n const tx = this.db.transaction(['chunks', 'meta'], 'readwrite');\n await this.promisifyRequest(tx.objectStore('chunks').clear());\n await this.promisifyRequest(tx.objectStore('meta').clear());\n } catch (error) {\n console.error('[L2Cache] Failed to clear IndexedDB:', error);\n throw error;\n }\n\n // Clear OPFS files\n try {\n const projectDir = await this.opfsRoot.getDirectoryHandle(\n `meframe-project-${this.projectId}`,\n {\n create: false,\n }\n );\n await this.opfsRoot.removeEntry(projectDir.name, { recursive: true });\n } catch (error) {\n if ((error as any)?.name !== 'NotFoundError') {\n console.warn('[L2Cache] Failed to clear OPFS:', error);\n }\n }\n }\n\n private async initStorage(): Promise<void> {\n // Initialize OPFS\n this.opfsRoot = await navigator.storage.getDirectory();\n\n // Initialize IndexedDB\n const request = indexedDB.open('meframe_cache', 1);\n\n request.onupgradeneeded = (event) => {\n const db = (event.target as IDBOpenDBRequest).result;\n\n // chunks store with composite key [clipId, track]\n if (!db.objectStoreNames.contains('chunks')) {\n const store = db.createObjectStore('chunks', {\n keyPath: ['clipId', 'track'],\n });\n store.createIndex('lastAccess', 'lastAccess');\n }\n\n // meta store\n if (!db.objectStoreNames.contains('meta')) {\n db.createObjectStore('meta', { keyPath: 'projectId' });\n }\n };\n\n this.db = await new Promise((resolve, reject) => {\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n });\n }\n\n private async readFromOPFS(fileName: string, batch: ChunkBatch): Promise<ArrayBuffer | null> {\n if (!this.opfsRoot) return null;\n\n const projectDir = await this.opfsRoot.getDirectoryHandle(`meframe-project-${this.projectId}`, {\n create: false,\n });\n const fileHandle = await projectDir.getFileHandle(fileName);\n const file = await fileHandle.getFile();\n const slice = file.slice(batch.byteOffset, batch.byteOffset + batch.byteLength);\n return await slice.arrayBuffer();\n }\n\n /**\n * Append chunks to OPFS file (or create new file)\n * Supports incremental writing for streaming scenarios\n */\n private async appendToOPFS(\n fileName: string,\n chunks: Array<EncodedVideoChunk | EncodedAudioChunk>,\n existingBatches?: ChunkBatch[]\n ): Promise<ChunkBatch[]> {\n if (!this.opfsRoot) return [];\n\n const projectDir = await this.opfsRoot.getDirectoryHandle(`meframe-project-${this.projectId}`, {\n create: true,\n });\n const fileHandle = await projectDir.getFileHandle(fileName, { create: true });\n\n // Calculate starting offset from existing batches\n let offset = 0;\n if (existingBatches && existingBatches.length > 0) {\n const lastBatch = existingBatches[existingBatches.length - 1];\n if (lastBatch) {\n offset = lastBatch.byteOffset + lastBatch.byteLength;\n }\n }\n\n const writable = await fileHandle.createWritable({ keepExistingData: true });\n\n const batches: ChunkBatch[] = [];\n\n for (const chunk of chunks) {\n const data = await this.chunkToArrayBuffer(chunk);\n await writable.write({ type: 'write', position: offset, data });\n\n batches.push({\n startUs: chunk.timestamp,\n durationUs: chunk.duration || 0,\n byteOffset: offset,\n byteLength: data.byteLength,\n type: chunk.type,\n });\n\n offset += data.byteLength;\n }\n\n await writable.close();\n return batches;\n }\n\n private async chunkToArrayBuffer(\n chunk: EncodedVideoChunk | EncodedAudioChunk\n ): Promise<ArrayBuffer> {\n const buffer = new ArrayBuffer(chunk.byteLength);\n chunk.copyTo(buffer);\n return buffer;\n }\n\n private createChunk(\n data: ArrayBuffer,\n timeUs: TimeUs,\n track: 'video' | 'audio',\n chunkType: 'key' | 'delta' = 'key',\n durationUs: TimeUs = 0\n ): EncodedVideoChunk | EncodedAudioChunk {\n if (track === 'video') {\n return new EncodedVideoChunk({\n type: chunkType,\n timestamp: timeUs,\n duration: durationUs,\n data,\n });\n } else {\n return new EncodedAudioChunk({\n type: chunkType,\n timestamp: timeUs,\n duration: durationUs,\n data,\n });\n }\n }\n\n private async updateLastAccess(clipId: string, track: string): Promise<void> {\n if (!this.db) return;\n\n const tx = this.db.transaction('chunks', 'readwrite');\n const store = tx.objectStore('chunks');\n const record = await this.promisifyRequest<ChunkRecord>(store.get([clipId, track]));\n\n if (record) {\n record.lastAccess = Date.now();\n await this.promisifyRequest(store.put(record));\n }\n }\n\n private async deleteEntry(clipId: string, track: string): Promise<void> {\n if (!this.db) return;\n\n // Step 1: Get record info\n let record: ChunkRecord | undefined;\n {\n const tx = this.db.transaction('chunks', 'readonly');\n const store = tx.objectStore('chunks');\n record = await this.promisifyRequest<ChunkRecord>(store.get([clipId, track]));\n }\n\n // Step 2: Delete OPFS file (outside transaction)\n if (record && this.opfsRoot) {\n try {\n const projectDir = await this.opfsRoot.getDirectoryHandle(\n `meframe-project-${this.projectId}`,\n { create: false }\n );\n await projectDir.removeEntry(record.fileName);\n } catch (error) {\n console.warn(`[L2Cache] Failed to delete OPFS file ${record.fileName}:`, error);\n }\n }\n\n // Step 3: Delete IndexedDB record (new transaction)\n {\n const tx = this.db.transaction('chunks', 'readwrite');\n const store = tx.objectStore('chunks');\n await this.promisifyRequest(store.delete([clipId, track]));\n }\n }\n\n private async enforceQuota(): Promise<void> {\n const estimate = await navigator.storage.estimate();\n const usage = estimate.usage || 0;\n\n console.log(\n `[L2Cache] enforceQuota: usage=${(usage / 1024 / 1024).toFixed(2)}MB, maxSize=${(this.maxSize / 1024 / 1024).toFixed(2)}MB`\n );\n\n if (usage <= this.maxSize) return;\n\n console.warn(\n `[L2Cache] Quota exceeded! Deleting oldest entries: usage=${usage}, maxSize=${this.maxSize}`\n );\n\n if (!this.db) return;\n\n // Delete oldest entries until under quota\n const tx = this.db.transaction('chunks', 'readwrite');\n const store = tx.objectStore('chunks');\n const index = store.index('lastAccess');\n\n let bytesDeleted = 0;\n const toDelete = usage - this.maxSize;\n\n const cursor = index.openCursor();\n await new Promise<void>((resolve) => {\n cursor.onsuccess = async (event) => {\n const cursor = (event.target as IDBRequest).result;\n if (!cursor || bytesDeleted >= toDelete) {\n resolve();\n return;\n }\n\n const record: ChunkRecord = cursor.value;\n await this.deleteEntry(record.clipId, record.track);\n bytesDeleted += record.totalBytes;\n\n cursor.continue();\n };\n });\n }\n\n private async collectRecords(store: IDBObjectStore, clipId: string): Promise<ChunkRecord[]> {\n const records: ChunkRecord[] = [];\n const cursor = store.openCursor();\n await new Promise<void>((resolve) => {\n cursor.onsuccess = (event) => {\n const cursor = (event.target as IDBRequest).result;\n if (!cursor) {\n resolve();\n return;\n }\n\n const record: ChunkRecord = cursor.value;\n if (record.clipId === clipId) {\n records.push(record);\n }\n\n cursor.continue();\n };\n });\n return records;\n }\n\n private promisifyRequest<T>(request: IDBRequest): Promise<T> {\n return new Promise((resolve, reject) => {\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n });\n }\n\n getMetadata(): {\n maxSizeMB: number;\n usedSizeMB: number;\n entries: number;\n hitRate: number;\n } {\n // This is a simplified implementation\n // In a real implementation, we would track actual usage\n return {\n maxSizeMB: this.maxSize / (1024 * 1024),\n usedSizeMB: 0, // Would need to track actual usage\n entries: 0, // Would need to track actual entries\n hitRate: 0, // Would need to track hits and misses\n };\n }\n\n async hasAvailableQuota(sizeMB: number): Promise<boolean> {\n if (typeof navigator === 'undefined' || !navigator.storage?.estimate) {\n // L2Cache requires storage API to function\n throw new Error('Storage API not available');\n }\n\n const estimate = await navigator.storage.estimate();\n const availableMB = ((estimate.quota || 0) - (estimate.usage || 0)) / (1024 * 1024);\n return availableMB >= sizeMB;\n }\n\n /**\n * Get chunk metadata (decoderConfig) for a specific clip\n */\n async getClipMetadata(clipId: string, track: 'video' | 'audio'): Promise<any | null> {\n await this.init();\n\n if (!this.db) return null;\n\n const tx = this.db.transaction('chunks', 'readonly');\n const store = tx.objectStore('chunks');\n const record = await this.promisifyRequest<ChunkRecord>(store.get([clipId, track]));\n\n return record?.metadata || null;\n }\n}\n"],"names":["cursor"],"mappings":";AAyCO,MAAM,QAAQ;AAAA,EACX,KAAyB;AAAA,EACzB,WAA6C;AAAA,EAC5C;AAAA,EACA;AAAA,EACD,cAAoC;AAAA,EAE5C,YAAY,QAAkB;AAC5B,SAAK,UAAU,OAAO,YAAY,OAAO;AACzC,SAAK,YAAY,OAAO;AAAA,EAC1B;AAAA,EAEA,MAAM,OAAsB;AAC1B,QAAI,KAAK,YAAa,QAAO,KAAK;AAElC,SAAK,cAAc,KAAK,YAAA;AACxB,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,MAAM,IAAI,QAAgB,QAAuE;AAC/F,UAAM,KAAK,KAAA;AAEX,QAAI,CAAC,KAAK,GAAI,QAAO;AAGrB,UAAM,KAAK,KAAK,GAAG,YAAY,UAAU,UAAU;AACnD,UAAM,QAAQ,GAAG,YAAY,QAAQ;AACrC,UAAM,UAAU,MAAM,KAAK,eAAe,OAAO,MAAM;AAEvD,eAAW,UAAU,SAAS;AAC5B,YAAM,QAAQ,kBAAkB,OAAO,SAAS,QAAQ,CAAC,OAAO;AAAA,QAC9D,OAAO,EAAE;AAAA,QACT,KAAK,EAAE,UAAU,EAAE;AAAA,MAAA,EACnB;AAEF,UAAI,CAAC,OAAO;AACV;AAAA,MACF;AAEA,YAAM,YAAY,MAAM,KAAK,aAAa,OAAO,UAAU,KAAK;AAChE,UAAI,CAAC,UAAW;AAEhB,WAAK,iBAAiB,OAAO,QAAQ,OAAO,KAAK;AAEjD,aAAO,KAAK,YAAY,WAAW,QAAQ,OAAO,OAAO,MAAM,MAAM,MAAM,UAAU;AAAA,IACvF;AAEA,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,IACJ,QACA,QACA,OACA,SAKe;AACf,UAAM,KAAK,KAAA;AAEX,QAAI,CAAC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EAA,gBAAO,SAAA;AAAA,MACT;AAAA,IACF,CAAC;AACD,WAAO;AAAA,EACT;AAAA,EAEQ,iBAAoB,SAAiC;AAC3D,WAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,cAAQ,YAAY,MAAM,QAAQ,QAAQ,MAAM;AAChD,cAAQ,UAAU,MAAM,OAAO,QAAQ,KAAK;AAAA,IAC9C,CAAC;AAAA,EACH;AAAA,EAEA,cAKE;AAGA,WAAO;AAAA,MACL,WAAW,KAAK,WAAW,OAAO;AAAA,MAClC,YAAY;AAAA;AAAA,MACZ,SAAS;AAAA;AAAA,MACT,SAAS;AAAA;AAAA,IAAA;AAAA,EAEb;AAAA,EAEA,MAAM,kBAAkB,QAAkC;AACxD,QAAI,OAAO,cAAc,eAAe,CAAC,UAAU,SAAS,UAAU;AAEpE,YAAM,IAAI,MAAM,2BAA2B;AAAA,IAC7C;AAEA,UAAM,WAAW,MAAM,UAAU,QAAQ,SAAA;AACzC,UAAM,gBAAgB,SAAS,SAAS,MAAM,SAAS,SAAS,OAAO,OAAO;AAC9E,WAAO,eAAe;AAAA,EACxB;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,gBAAgB,QAAgB,OAA+C;AACnF,UAAM,KAAK,KAAA;AAEX,QAAI,CAAC,KAAK,GAAI,QAAO;AAErB,UAAM,KAAK,KAAK,GAAG,YAAY,UAAU,UAAU;AACnD,UAAM,QAAQ,GAAG,YAAY,QAAQ;AACrC,UAAM,SAAS,MAAM,KAAK,iBAA8B,MAAM,IAAI,CAAC,QAAQ,KAAK,CAAC,CAAC;AAElF,WAAO,QAAQ,YAAY;AAAA,EAC7B;AACF;"}
@@ -14,7 +14,7 @@ export interface L1CacheMetadata {
14
14
  clipCount: number;
15
15
  }
16
16
  /**
17
- * Simplified VideoL1Cache for 3-Clip strategy
17
+ * Simplified VideoL1Cache for 2-Clip strategy
18
18
  *
19
19
  * Clip lifecycle is managed by ClipSessionManager:
20
20
  * - No LRU eviction (clips evicted explicitly)
@@ -1 +1 @@
1
- {"version":3,"file":"VideoL1Cache.js","sources":["../../../src/cache/l1/VideoL1Cache.ts"],"sourcesContent":["import type { TimeUs } from '../../model/types';\nimport type { GOP } from '../types';\nimport { RcFrame } from '../../model';\nimport { findFrameIndex, findGopIndex } from './gop-utils';\n\nconst DEFAULT_GOP_INTERVAL_US = 2_000_000;\nconst BYTES_PER_MB = 1024 * 1024;\n\ninterface L1Config {\n maxMemoryMB: number;\n maxGOPs?: number;\n gopIntervalUs?: number;\n}\n\ninterface L1CacheEntry {\n key: string;\n clipId: string;\n gopIndex: number;\n gopStartUs: TimeUs;\n durationUs: TimeUs;\n frames: RcFrame[];\n size: number;\n}\n\nexport interface L1CacheMetadata {\n size: number;\n maxSize: number;\n entries: number;\n clipCount: number;\n}\n\n/**\n * Simplified VideoL1Cache for 3-Clip strategy\n *\n * Clip lifecycle is managed by ClipSessionManager:\n * - No LRU eviction (clips evicted explicitly)\n * - No capacity limits (fixed 3 clips)\n * - Simple GOP storage per clip\n */\nexport class VideoL1Cache {\n private readonly entriesByClip = new Map<string, L1CacheEntry[]>();\n private maxMemoryBytes: number;\n private gopIntervalUs: number;\n private currentBytes = 0;\n\n constructor(config: L1Config) {\n this.maxMemoryBytes = config.maxMemoryMB * BYTES_PER_MB;\n this.gopIntervalUs = config.gopIntervalUs ?? DEFAULT_GOP_INTERVAL_US;\n }\n\n get(timeUs: TimeUs, clipId: string): RcFrame | null {\n const clipEntries = this.entriesByClip.get(clipId);\n if (!clipEntries || clipEntries.length === 0) {\n return null;\n }\n\n const entry = this.findEntryByTime(clipEntries, timeUs);\n if (!entry) {\n return null;\n }\n\n const frameIndex = findFrameIndex(\n {\n index: entry.gopIndex,\n startUs: entry.gopStartUs,\n durationUs: entry.durationUs,\n frames: entry.frames,\n isKeyframe: true,\n clipId: entry.clipId,\n },\n timeUs\n );\n if (frameIndex === -1) {\n return null;\n }\n\n return entry.frames[frameIndex] ?? null;\n }\n\n putGOP(gop: GOP, clipId: string, trackId: string): void {\n const gopIndex = gop.index ?? gop.startUs;\n const existing = this.getEntryExact(clipId, gopIndex);\n\n const frames = this.wrapFrames(gop.frames, clipId, gop.durationUs, trackId);\n\n if (existing) {\n existing.gopStartUs = gop.startUs;\n this.mergeFrames(existing, frames, gop.durationUs);\n return;\n }\n\n const entry = this.createEntry(clipId, {\n gopIndex,\n startUs: gop.startUs,\n durationUs: gop.durationUs,\n frames,\n isKeyframe: gop.isKeyframe,\n });\n\n this.registerEntry(entry);\n this.currentBytes += entry.size;\n }\n\n addFrame(\n frame: VideoFrame,\n clipId: string,\n frameDuration: TimeUs,\n trackId: string,\n gopSerial?: number,\n isKeyframe?: boolean\n ): RcFrame | null {\n const timestamp = frame.timestamp ?? 0;\n const gopIndex =\n typeof gopSerial === 'number' ? gopSerial : findGopIndex(timestamp, this.gopIntervalUs);\n const existing = this.getEntryExact(clipId, gopIndex);\n\n const rcFrame = this.wrapFrame(frame, clipId, frameDuration, trackId, gopSerial, isKeyframe);\n\n if (existing) {\n this.mergeFrames(existing, [rcFrame], frameDuration);\n return rcFrame;\n }\n\n const entry = this.createEntry(clipId, {\n gopIndex,\n startUs: timestamp,\n durationUs: frameDuration,\n frames: [rcFrame],\n isKeyframe: isKeyframe ?? true,\n });\n\n this.registerEntry(entry);\n this.currentBytes += entry.size;\n return rcFrame;\n }\n\n /**\n * Evict all cache entries for a specific clip\n */\n evictClip(clipId: string): void {\n const entries = this.entriesByClip.get(clipId);\n if (!entries) return;\n\n for (const entry of entries) {\n this.closeFrames(entry);\n this.currentBytes -= entry.size;\n }\n\n this.entriesByClip.delete(clipId);\n }\n\n /**\n * Check if a clip has any cached entries\n */\n isClipCached(clipId: string): boolean {\n const entries = this.entriesByClip.get(clipId);\n return !!entries && entries.length > 0;\n }\n\n /**\n * Get total frame count for a clip\n */\n getClipFrameCount(clipId: string): number {\n const entries = this.entriesByClip.get(clipId);\n if (!entries) return 0;\n return entries.reduce((sum, entry) => sum + entry.frames.length, 0);\n }\n\n invalidateRange(startUs: TimeUs, endUs: TimeUs, clipId?: string): void {\n for (const entry of this.iterateEntries()) {\n if (clipId && entry.clipId !== clipId) {\n continue;\n }\n\n const gopEnd = entry.gopStartUs + entry.durationUs;\n if (entry.gopStartUs < endUs && gopEnd > startUs) {\n this.removeEntry(entry);\n }\n }\n }\n\n clear(): void {\n for (const entries of this.entriesByClip.values()) {\n for (const entry of entries) {\n this.closeFrames(entry);\n }\n }\n this.entriesByClip.clear();\n this.currentBytes = 0;\n }\n\n getMetadata(): L1CacheMetadata {\n return {\n size: this.currentBytes,\n maxSize: this.maxMemoryBytes,\n entries: this.countEntries(),\n clipCount: this.entriesByClip.size,\n };\n }\n\n private registerEntry(entry: L1CacheEntry): void {\n const entries = this.ensureClipEntries(entry.clipId);\n const insertIndex = this.findInsertIndex(entries, entry.gopIndex);\n entries.splice(insertIndex, 0, entry);\n }\n\n private createEntry(\n clipId: string,\n gop: {\n gopIndex: number;\n startUs: TimeUs;\n durationUs: TimeUs;\n frames: RcFrame[];\n isKeyframe: boolean;\n }\n ): L1CacheEntry {\n const frames = this.normalizeFrames(gop.frames);\n const entry: L1CacheEntry = {\n key: this.composeKey(clipId, gop.gopIndex),\n clipId,\n gopIndex: gop.gopIndex,\n gopStartUs: gop.startUs,\n durationUs: gop.durationUs,\n frames,\n size: 0,\n };\n\n this.updateEntryStats(entry, this.deriveFallbackDuration(gop.durationUs, frames.length));\n return entry;\n }\n\n private mergeFrames(entry: L1CacheEntry, frames: RcFrame[], fallbackDuration: TimeUs): void {\n const durationFallback = this.deriveFallbackDuration(\n fallbackDuration,\n entry.frames.length + frames.length\n );\n for (const rcFrame of frames) {\n this.insertFrame(entry, rcFrame, durationFallback);\n }\n this.updateEntryStats(entry, durationFallback);\n }\n\n private insertFrame(entry: L1CacheEntry, frame: RcFrame, fallbackDuration: TimeUs): void {\n const timestamp = frame.timestampUs ?? entry.gopStartUs;\n const frames = entry.frames;\n const insertIndex = this.findFrameInsertIndex(frames, timestamp);\n\n if (\n insertIndex < frames.length &&\n (frames[insertIndex]?.timestampUs ?? entry.gopStartUs) === timestamp\n ) {\n const oldFrame = frames[insertIndex];\n frames[insertIndex] = frame;\n oldFrame?.close?.();\n } else {\n frames.splice(insertIndex, 0, frame);\n }\n\n entry.size += frame.sizeEstimate;\n const duration = frame.durationUs || fallbackDuration;\n entry.durationUs = Math.max(entry.durationUs, timestamp + duration - entry.gopStartUs);\n }\n\n private removeEntry(entry: L1CacheEntry): void {\n const clipEntries = this.entriesByClip.get(entry.clipId);\n if (clipEntries) {\n const index = clipEntries.findIndex((item) => item.gopIndex === entry.gopIndex);\n if (index !== -1) {\n clipEntries.splice(index, 1);\n }\n if (clipEntries.length === 0) {\n this.entriesByClip.delete(entry.clipId);\n }\n }\n\n this.closeFrames(entry);\n this.currentBytes -= entry.size;\n }\n\n private closeFrames(entry: L1CacheEntry): void {\n for (const frame of entry.frames) {\n frame?.close?.();\n }\n }\n\n private composeKey(clipId: string, gopIndex: number): string {\n return `${clipId}:${gopIndex}`;\n }\n\n private wrapFrame(\n frame: VideoFrame,\n clipId: string,\n frameDuration: TimeUs,\n trackId: string,\n gopSerial?: number,\n isKeyframe?: boolean\n ): RcFrame {\n return RcFrame.wrap(frame, {\n trackId,\n clipId,\n timestampUs: frame.timestamp ?? 0,\n durationUs: frame.duration ?? frameDuration,\n gopSerial,\n isKeyframe,\n });\n }\n\n private wrapFrames(\n frames: (RcFrame | VideoFrame)[],\n clipId: string,\n fallbackDuration: TimeUs,\n trackId: string\n ): RcFrame[] {\n const wrapped = frames.map((frame) =>\n frame instanceof RcFrame\n ? frame\n : this.wrapFrame(\n frame as VideoFrame,\n clipId,\n fallbackDuration / Math.max(frames.length, 1),\n trackId\n )\n );\n return this.normalizeFrames(wrapped);\n }\n\n private getEntryExact(clipId: string, gopIndex: number): L1CacheEntry | undefined {\n const entries = this.entriesByClip.get(clipId);\n if (!entries) return undefined;\n return entries.find((e) => e.gopIndex === gopIndex);\n }\n\n private findEntryByTime(entries: L1CacheEntry[], timeUs: TimeUs): L1CacheEntry | undefined {\n let low = 0;\n let high = entries.length - 1;\n\n while (low <= high) {\n const mid = Math.floor((low + high) / 2);\n const entry = entries[mid];\n if (!entry) break;\n\n if (timeUs < entry.gopStartUs) {\n high = mid - 1;\n } else if (timeUs >= entry.gopStartUs + entry.durationUs) {\n low = mid + 1;\n } else {\n return entry;\n }\n }\n\n return undefined;\n }\n\n private countEntries(): number {\n let count = 0;\n for (const clipEntries of this.entriesByClip.values()) {\n count += clipEntries.length;\n }\n return count;\n }\n\n private iterateEntries(): Iterable<L1CacheEntry> {\n const entries: L1CacheEntry[] = [];\n for (const clipEntries of this.entriesByClip.values()) {\n entries.push(...clipEntries);\n }\n return entries;\n }\n\n private ensureClipEntries(clipId: string): L1CacheEntry[] {\n let entries = this.entriesByClip.get(clipId);\n if (!entries) {\n entries = [];\n this.entriesByClip.set(clipId, entries);\n }\n return entries;\n }\n\n private findInsertIndex(entries: L1CacheEntry[], gopIndex: number): number {\n let low = 0;\n let high = entries.length;\n while (low < high) {\n const mid = Math.floor((low + high) / 2);\n const entry = entries[mid];\n if (entry && entry.gopIndex < gopIndex) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return low;\n }\n\n private findFrameInsertIndex(frames: RcFrame[], timestamp: TimeUs): number {\n let low = 0;\n let high = frames.length;\n while (low < high) {\n const mid = Math.floor((low + high) / 2);\n const midTs = frames[mid]?.timestampUs ?? 0;\n if (midTs < timestamp) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return low;\n }\n\n private normalizeFrames(frames: RcFrame[]): RcFrame[] {\n const seen = new Set<number>();\n const sorted = [...frames].sort((a, b) => (a.timestampUs ?? 0) - (b.timestampUs ?? 0));\n const result: RcFrame[] = [];\n for (const frame of sorted) {\n const ts = frame.timestampUs ?? 0;\n if (seen.has(ts)) {\n frame?.close?.();\n } else {\n seen.add(ts);\n result.push(frame);\n }\n }\n return result;\n }\n\n private updateEntryStats(entry: L1CacheEntry, fallbackDuration: TimeUs): void {\n entry.size = entry.frames.reduce((acc, frame) => acc + frame.sizeEstimate, 0);\n entry.durationUs = entry.frames.reduce((acc, frame) => {\n const duration = frame.durationUs || fallbackDuration;\n return Math.max(acc, (frame.timestampUs ?? entry.gopStartUs) + duration - entry.gopStartUs);\n }, entry.durationUs);\n }\n\n private deriveFallbackDuration(durationUs: TimeUs, frameCount: number): TimeUs {\n if (frameCount <= 1) {\n return durationUs || this.gopIntervalUs;\n }\n return Math.max(durationUs / frameCount, this.gopIntervalUs / frameCount);\n }\n}\n"],"names":[],"mappings":";;AAKA,MAAM,0BAA0B;AAChC,MAAM,eAAe,OAAO;AAiCrB,MAAM,aAAa;AAAA,EACP,oCAAoB,IAAA;AAAA,EAC7B;AAAA,EACA;AAAA,EACA,eAAe;AAAA,EAEvB,YAAY,QAAkB;AAC5B,SAAK,iBAAiB,OAAO,cAAc;AAC3C,SAAK,gBAAgB,OAAO,iBAAiB;AAAA,EAC/C;AAAA,EAEA,IAAI,QAAgB,QAAgC;AAClD,UAAM,cAAc,KAAK,cAAc,IAAI,MAAM;AACjD,QAAI,CAAC,eAAe,YAAY,WAAW,GAAG;AAC5C,aAAO;AAAA,IACT;AAEA,UAAM,QAAQ,KAAK,gBAAgB,aAAa,MAAM;AACtD,QAAI,CAAC,OAAO;AACV,aAAO;AAAA,IACT;AAEA,UAAM,aAAa;AAAA,MACjB;AAAA,QACE,OAAO,MAAM;AAAA,QACb,SAAS,MAAM;AAAA,QACf,YAAY,MAAM;AAAA,QAClB,QAAQ,MAAM;AAAA,QAEd,QAAQ,MAAM;AAAA,MAAA;AAAA,MAEhB;AAAA,IAAA;AAEF,QAAI,eAAe,IAAI;AACrB,aAAO;AAAA,IACT;AAEA,WAAO,MAAM,OAAO,UAAU,KAAK;AAAA,EACrC;AAAA,EAEA,OAAO,KAAU,QAAgB,SAAuB;AACtD,UAAM,WAAW,IAAI,SAAS,IAAI;AAClC,UAAM,WAAW,KAAK,cAAc,QAAQ,QAAQ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A,EACT;AAAA,EAEQ,gBAAgB,QAA8B;AACpD,UAAM,2BAAW,IAAA;AACjB,UAAM,SAAS,CAAC,GAAG,MAAM,EAAE,KAAK,CAAC,GAAG,OAAO,EAAE,eAAe,MAAM,EAAE,eAAe,EAAE;AACrF,UAAM,SAAoB,CAAA;AAC1B,eAAW,SAAS,QAAQ;AAC1B,YAAM,KAAK,MAAM,eAAe;AAChC,UAAI,KAAK,IAAI,EAAE,GAAG;AAChB,eAAO,QAAA;AAAA,MACT,OAAO;AACL,aAAK,IAAI,EAAE;AACX,eAAO,KAAK,KAAK;AAAA,MACnB;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAAA,EAEQ,iBAAiB,OAAqB,kBAAgC;AAC5E,UAAM,OAAO,MAAM,OAAO,OAAO,CAAC,KAAK,UAAU,MAAM,MAAM,cAAc,CAAC;AAC5E,UAAM,aAAa,MAAM,OAAO,OAAO,CAAC,KAAK,UAAU;AACrD,YAAM,WAAW,MAAM,cAAc;AACrC,aAAO,KAAK,IAAI,MAAM,MAAM,eAAe,MAAM,cAAc,WAAW,MAAM,UAAU;AAAA,IAC5F,GAAG,MAAM,UAAU;AAAA,EACrB;AAAA,EAEQ,uBAAuB,YAAoB,YAA4B;AAC7E,QAAI,cAAc,GAAG;AACnB,aAAO,cAAc,KAAK;AAAA,IAC5B;AACA,WAAO,KAAK,IAAI,aAAa,YAAY,KAAK,gBAAgB,UAAU;AAAA,EAC1E;AACF;"}
1
+ {"version":3,"file":"VideoL1Cache.js","sources":["../../../src/cache/l1/VideoL1Cache.ts"],"sourcesContent":["import type { TimeUs } from '../../model/types';\nimport type { GOP } from '../types';\nimport { RcFrame } from '../../model';\nimport { findFrameIndex, findGopIndex } from './gop-utils';\n\nconst DEFAULT_GOP_INTERVAL_US = 2_000_000;\nconst BYTES_PER_MB = 1024 * 1024;\n\ninterface L1Config {\n maxMemoryMB: number;\n maxGOPs?: number;\n gopIntervalUs?: number;\n}\n\ninterface L1CacheEntry {\n key: string;\n clipId: string;\n gopIndex: number;\n gopStartUs: TimeUs;\n durationUs: TimeUs;\n frames: RcFrame[];\n size: number;\n}\n\nexport interface L1CacheMetadata {\n size: number;\n maxSize: number;\n entries: number;\n clipCount: number;\n}\n\n/**\n * Simplified VideoL1Cache for 2-Clip strategy\n *\n * Clip lifecycle is managed by ClipSessionManager:\n * - No LRU eviction (clips evicted explicitly)\n * - No capacity limits (fixed 3 clips)\n * - Simple GOP storage per clip\n */\nexport class VideoL1Cache {\n private readonly entriesByClip = new Map<string, L1CacheEntry[]>();\n private maxMemoryBytes: number;\n private gopIntervalUs: number;\n private currentBytes = 0;\n\n constructor(config: L1Config) {\n this.maxMemoryBytes = config.maxMemoryMB * BYTES_PER_MB;\n this.gopIntervalUs = config.gopIntervalUs ?? DEFAULT_GOP_INTERVAL_US;\n }\n\n get(timeUs: TimeUs, clipId: string): RcFrame | null {\n const clipEntries = this.entriesByClip.get(clipId);\n if (!clipEntries || clipEntries.length === 0) {\n return null;\n }\n\n const entry = this.findEntryByTime(clipEntries, timeUs);\n if (!entry) {\n return null;\n }\n\n const frameIndex = findFrameIndex(\n {\n index: entry.gopIndex,\n startUs: entry.gopStartUs,\n durationUs: entry.durationUs,\n frames: entry.frames,\n isKeyframe: true,\n clipId: entry.clipId,\n },\n timeUs\n );\n if (frameIndex === -1) {\n return null;\n }\n\n return entry.frames[frameIndex] ?? null;\n }\n\n putGOP(gop: GOP, clipId: string, trackId: string): void {\n const gopIndex = gop.index ?? gop.startUs;\n const existing = this.getEntryExact(clipId, gopIndex);\n\n const frames = this.wrapFrames(gop.frames, clipId, gop.durationUs, trackId);\n\n if (existing) {\n existing.gopStartUs = gop.startUs;\n this.mergeFrames(existing, frames, gop.durationUs);\n return;\n }\n\n const entry = this.createEntry(clipId, {\n gopIndex,\n startUs: gop.startUs,\n durationUs: gop.durationUs,\n frames,\n isKeyframe: gop.isKeyframe,\n });\n\n this.registerEntry(entry);\n this.currentBytes += entry.size;\n }\n\n addFrame(\n frame: VideoFrame,\n clipId: string,\n frameDuration: TimeUs,\n trackId: string,\n gopSerial?: number,\n isKeyframe?: boolean\n ): RcFrame | null {\n const timestamp = frame.timestamp ?? 0;\n const gopIndex =\n typeof gopSerial === 'number' ? gopSerial : findGopIndex(timestamp, this.gopIntervalUs);\n const existing = this.getEntryExact(clipId, gopIndex);\n\n const rcFrame = this.wrapFrame(frame, clipId, frameDuration, trackId, gopSerial, isKeyframe);\n\n if (existing) {\n this.mergeFrames(existing, [rcFrame], frameDuration);\n return rcFrame;\n }\n\n const entry = this.createEntry(clipId, {\n gopIndex,\n startUs: timestamp,\n durationUs: frameDuration,\n frames: [rcFrame],\n isKeyframe: isKeyframe ?? true,\n });\n\n this.registerEntry(entry);\n this.currentBytes += entry.size;\n return rcFrame;\n }\n\n /**\n * Evict all cache entries for a specific clip\n */\n evictClip(clipId: string): void {\n const entries = this.entriesByClip.get(clipId);\n if (!entries) return;\n\n for (const entry of entries) {\n this.closeFrames(entry);\n this.currentBytes -= entry.size;\n }\n\n this.entriesByClip.delete(clipId);\n }\n\n /**\n * Check if a clip has any cached entries\n */\n isClipCached(clipId: string): boolean {\n const entries = this.entriesByClip.get(clipId);\n return !!entries && entries.length > 0;\n }\n\n /**\n * Get total frame count for a clip\n */\n getClipFrameCount(clipId: string): number {\n const entries = this.entriesByClip.get(clipId);\n if (!entries) return 0;\n return entries.reduce((sum, entry) => sum + entry.frames.length, 0);\n }\n\n invalidateRange(startUs: TimeUs, endUs: TimeUs, clipId?: string): void {\n for (const entry of this.iterateEntries()) {\n if (clipId && entry.clipId !== clipId) {\n continue;\n }\n\n const gopEnd = entry.gopStartUs + entry.durationUs;\n if (entry.gopStartUs < endUs && gopEnd > startUs) {\n this.removeEntry(entry);\n }\n }\n }\n\n clear(): void {\n for (const entries of this.entriesByClip.values()) {\n for (const entry of entries) {\n this.closeFrames(entry);\n }\n }\n this.entriesByClip.clear();\n this.currentBytes = 0;\n }\n\n getMetadata(): L1CacheMetadata {\n return {\n size: this.currentBytes,\n maxSize: this.maxMemoryBytes,\n entries: this.countEntries(),\n clipCount: this.entriesByClip.size,\n };\n }\n\n private registerEntry(entry: L1CacheEntry): void {\n const entries = this.ensureClipEntries(entry.clipId);\n const insertIndex = this.findInsertIndex(entries, entry.gopIndex);\n entries.splice(insertIndex, 0, entry);\n }\n\n private createEntry(\n clipId: string,\n gop: {\n gopIndex: number;\n startUs: TimeUs;\n durationUs: TimeUs;\n frames: RcFrame[];\n isKeyframe: boolean;\n }\n ): L1CacheEntry {\n const frames = this.normalizeFrames(gop.frames);\n const entry: L1CacheEntry = {\n key: this.composeKey(clipId, gop.gopIndex),\n clipId,\n gopIndex: gop.gopIndex,\n gopStartUs: gop.startUs,\n durationUs: gop.durationUs,\n frames,\n size: 0,\n };\n\n this.updateEntryStats(entry, this.deriveFallbackDuration(gop.durationUs, frames.length));\n return entry;\n }\n\n private mergeFrames(entry: L1CacheEntry, frames: RcFrame[], fallbackDuration: TimeUs): void {\n const durationFallback = this.deriveFallbackDuration(\n fallbackDuration,\n entry.frames.length + frames.length\n );\n for (const rcFrame of frames) {\n this.insertFrame(entry, rcFrame, durationFallback);\n }\n this.updateEntryStats(entry, durationFallback);\n }\n\n private insertFrame(entry: L1CacheEntry, frame: RcFrame, fallbackDuration: TimeUs): void {\n const timestamp = frame.timestampUs ?? entry.gopStartUs;\n const frames = entry.frames;\n const insertIndex = this.findFrameInsertIndex(frames, timestamp);\n\n if (\n insertIndex < frames.length &&\n (frames[insertIndex]?.timestampUs ?? entry.gopStartUs) === timestamp\n ) {\n const oldFrame = frames[insertIndex];\n frames[insertIndex] = frame;\n oldFrame?.close?.();\n } else {\n frames.splice(insertIndex, 0, frame);\n }\n\n entry.size += frame.sizeEstimate;\n const duration = frame.durationUs || fallbackDuration;\n entry.durationUs = Math.max(entry.durationUs, timestamp + duration - entry.gopStartUs);\n }\n\n private removeEntry(entry: L1CacheEntry): void {\n const clipEntries = this.entriesByClip.get(entry.clipId);\n if (clipEntries) {\n const index = clipEntries.findIndex((item) => item.gopIndex === entry.gopIndex);\n if (index !== -1) {\n clipEntries.splice(index, 1);\n }\n if (clipEntries.length === 0) {\n this.entriesByClip.delete(entry.clipId);\n }\n }\n\n this.closeFrames(entry);\n this.currentBytes -= entry.size;\n }\n\n private closeFrames(entry: L1CacheEntry): void {\n for (const frame of entry.frames) {\n frame?.close?.();\n }\n }\n\n private composeKey(clipId: string, gopIndex: number): string {\n return `${clipId}:${gopIndex}`;\n }\n\n private wrapFrame(\n frame: VideoFrame,\n clipId: string,\n frameDuration: TimeUs,\n trackId: string,\n gopSerial?: number,\n isKeyframe?: boolean\n ): RcFrame {\n return RcFrame.wrap(frame, {\n trackId,\n clipId,\n timestampUs: frame.timestamp ?? 0,\n durationUs: frame.duration ?? frameDuration,\n gopSerial,\n isKeyframe,\n });\n }\n\n private wrapFrames(\n frames: (RcFrame | VideoFrame)[],\n clipId: string,\n fallbackDuration: TimeUs,\n trackId: string\n ): RcFrame[] {\n const wrapped = frames.map((frame) =>\n frame instanceof RcFrame\n ? frame\n : this.wrapFrame(\n frame as VideoFrame,\n clipId,\n fallbackDuration / Math.max(frames.length, 1),\n trackId\n )\n );\n return this.normalizeFrames(wrapped);\n }\n\n private getEntryExact(clipId: string, gopIndex: number): L1CacheEntry | undefined {\n const entries = this.entriesByClip.get(clipId);\n if (!entries) return undefined;\n return entries.find((e) => e.gopIndex === gopIndex);\n }\n\n private findEntryByTime(entries: L1CacheEntry[], timeUs: TimeUs): L1CacheEntry | undefined {\n let low = 0;\n let high = entries.length - 1;\n\n while (low <= high) {\n const mid = Math.floor((low + high) / 2);\n const entry = entries[mid];\n if (!entry) break;\n\n if (timeUs < entry.gopStartUs) {\n high = mid - 1;\n } else if (timeUs >= entry.gopStartUs + entry.durationUs) {\n low = mid + 1;\n } else {\n return entry;\n }\n }\n\n return undefined;\n }\n\n private countEntries(): number {\n let count = 0;\n for (const clipEntries of this.entriesByClip.values()) {\n count += clipEntries.length;\n }\n return count;\n }\n\n private iterateEntries(): Iterable<L1CacheEntry> {\n const entries: L1CacheEntry[] = [];\n for (const clipEntries of this.entriesByClip.values()) {\n entries.push(...clipEntries);\n }\n return entries;\n }\n\n private ensureClipEntries(clipId: string): L1CacheEntry[] {\n let entries = this.entriesByClip.get(clipId);\n if (!entries) {\n entries = [];\n this.entriesByClip.set(clipId, entries);\n }\n return entries;\n }\n\n private findInsertIndex(entries: L1CacheEntry[], gopIndex: number): number {\n let low = 0;\n let high = entries.length;\n while (low < high) {\n const mid = Math.floor((low + high) / 2);\n const entry = entries[mid];\n if (entry && entry.gopIndex < gopIndex) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return low;\n }\n\n private findFrameInsertIndex(frames: RcFrame[], timestamp: TimeUs): number {\n let low = 0;\n let high = frames.length;\n while (low < high) {\n const mid = Math.floor((low + high) / 2);\n const midTs = frames[mid]?.timestampUs ?? 0;\n if (midTs < timestamp) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return low;\n }\n\n private normalizeFrames(frames: RcFrame[]): RcFrame[] {\n const seen = new Set<number>();\n const sorted = [...frames].sort((a, b) => (a.timestampUs ?? 0) - (b.timestampUs ?? 0));\n const result: RcFrame[] = [];\n for (const frame of sorted) {\n const ts = frame.timestampUs ?? 0;\n if (seen.has(ts)) {\n frame?.close?.();\n } else {\n seen.add(ts);\n result.push(frame);\n }\n }\n return result;\n }\n\n private updateEntryStats(entry: L1CacheEntry, fallbackDuration: TimeUs): void {\n entry.size = entry.frames.reduce((acc, frame) => acc + frame.sizeEstimate, 0);\n entry.durationUs = entry.frames.reduce((acc, frame) => {\n const duration = frame.durationUs || fallbackDuration;\n return Math.max(acc, (frame.timestampUs ?? entry.gopStartUs) + duration - entry.gopStartUs);\n }, entry.durationUs);\n }\n\n private deriveFallbackDuration(durationUs: TimeUs, frameCount: number): TimeUs {\n if (frameCount <= 1) {\n return durationUs || this.gopIntervalUs;\n }\n return Math.max(durationUs / frameCount, this.gopIntervalUs / frameCount);\n }\n}\n"],"names":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O,KAAK,KAAK;AAAA,MACnB;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAAA,EAEQ,iBAAiB,OAAqB,kBAAgC;AAC5E,UAAM,OAAO,MAAM,OAAO,OAAO,CAAC,KAAK,UAAU,MAAM,MAAM,cAAc,CAAC;AAC5E,UAAM,aAAa,MAAM,OAAO,OAAO,CAAC,KAAK,UAAU;AACrD,YAAM,WAAW,MAAM,cAAc;AACrC,aAAO,KAAK,IAAI,MAAM,MAAM,eAAe,MAAM,cAAc,WAAW,MAAM,UAAU;AAAA,IAC5F,GAAG,MAAM,UAAU;AAAA,EACrB;AAAA,EAEQ,uBAAuB,YAAoB,YAA4B;AAC7E,QAAI,cAAc,GAAG;AACnB,aAAO,cAAc,KAAK;AAAA,IAC5B;AACA,WAAO,KAAK,IAAI,aAAa,YAAY,KAAK,gBAAgB,UAAU;AAAA,EAC1E;AACF;"}
@@ -3,21 +3,32 @@ import { TimeUs } from '../model/types';
3
3
  import { Orchestrator } from '../orchestrator';
4
4
 
5
5
  /**
6
- * Simplified background pre-render service for 3-Clip strategy
6
+ * PreRenderService: Background pre-render for filling L2 cache
7
7
  *
8
- * In the 3-Clip strategy, ClipFetchQueue already handles Prev/Current/Next caching.
9
- * This service is kept minimal for compatibility but does minimal work.
8
+ * Dual-mode strategy:
9
+ * 1. When playback active: Ensure 2-Clip window (Prev/Current/Next) for preview
10
+ * 2. When idle: Continue rendering subsequent clips for L2 export cache
11
+ *
12
+ * Goals:
13
+ * - Maintain smooth preview (2-Clip L1 cache)
14
+ * - Build complete L2 cache for fast export
15
+ * - Operate in background without blocking
10
16
  */
11
17
  export declare class PreRenderService implements IPreRenderService {
12
18
  private orchestrator;
13
19
  private _isRunning;
20
+ private _isPaused;
14
21
  private renderLoopId;
15
22
  private _framesRendered;
16
23
  private _currentTimeUs;
24
+ private processedClips;
25
+ private isPlaybackActive;
17
26
  private strategy;
27
+ private isRendering;
28
+ private renderingPromises;
18
29
  constructor(orchestrator: Orchestrator, _eventBus: any);
19
30
  start(): void;
20
- stop(): void;
31
+ stop(): Promise<void>;
21
32
  pause(): void;
22
33
  resume(): void;
23
34
  setWindow(size: TimeUs): void;
@@ -26,10 +37,16 @@ export declare class PreRenderService implements IPreRenderService {
26
37
  clearQueue(): void;
27
38
  queueRange(_startUs: TimeUs, _endUs: TimeUs, _priority?: number): void;
28
39
  updatePlaybackTime(timeUs: TimeUs): void;
40
+ setPlaybackActive(active: boolean): void;
29
41
  get isRunning(): boolean;
30
42
  get queueSize(): number;
31
43
  get status(): PreRenderStatus;
32
44
  private scheduleNextRender;
33
45
  private renderTick;
46
+ /**
47
+ * Render a complete clip to L2 cache
48
+ * Creates dedicated pipeline that bypasses L1 window management
49
+ */
50
+ private renderClipToL2;
34
51
  }
35
52
  //# sourceMappingURL=PreRenderService.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"PreRenderService.d.ts","sourceRoot":"","sources":["../../src/controllers/PreRenderService.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAClF,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAEpD;;;;;GAKG;AACH,qBAAa,gBAAiB,YAAW,iBAAiB;IACxD,OAAO,CAAC,YAAY,CAAe;IACnC,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,YAAY,CAAuB;IAC3C,OAAO,CAAC,eAAe,CAAK;IAC5B,OAAO,CAAC,cAAc,CAAa;IACnC,OAAO,CAAC,QAAQ,CAKd;gBAEU,YAAY,EAAE,YAAY,EAAE,SAAS,EAAE,GAAG;IAItD,KAAK,IAAI,IAAI;IAMb,IAAI,IAAI,IAAI;IASZ,KAAK,IAAI,IAAI;IAIb,MAAM,IAAI,IAAI;IAId,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;IAI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IAAI;IAMP,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAW3B,KAAK,IAAI,IAAI;IAIb,MAAM,IAAI,IAAI;IAOd,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;IAI7B,WAAW,CAAC,QAAQ,EAAE,OAAO,CAAC,cAAc,CAAC,GAAG,IAAI;IAIpD,WAAW,CAAC,SAAS,EAAE,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,IAAI;IAIvD,UAAU,IAAI,IAAI;IAIlB,UAAU,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI;IAItE,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAIxC,iBAAiB,CAAC,MAAM,EAAE,OAAO,GAAG,IAAI;IAIxC,IAAI,SAAS,IAAI,OAAO,CAEvB;IAED,IAAI,SAAS,IAAI,MAAM,CAEtB;IAED,IAAI,MAAM,IAAI,eAAe,CAO5B;IAED,OAAO,CAAC,kBAAkB;YAYZ,UAAU;IAyDxB;;;OAGG;YACW,cAAc;CAe7B"}
@@ -1,15 +1,20 @@
1
1
  class PreRenderService {
2
2
  orchestrator;
3
3
  _isRunning = false;
4
+ _isPaused = false;
4
5
  renderLoopId = null;
5
6
  _framesRendered = 0;
6
7
  _currentTimeUs = 0;
8
+ processedClips = /* @__PURE__ */ new Set();
9
+ isPlaybackActive = false;
7
10
  strategy = {
8
11
  direction: "forward",
9
12
  lookahead: 3e6,
10
13
  lookbehind: 2e6,
11
14
  keyframesOnly: false
12
15
  };
16
+ isRendering = false;
17
+ renderingPromises = /* @__PURE__ */ new Map();
13
18
  constructor(orchestrator, _eventBus) {
14
19
  this.orchestrator = orchestrator;
15
20
  }
@@ -18,18 +23,22 @@ class PreRenderService {
18
23
  this._isRunning = true;
19
24
  this.scheduleNextRender();
20
25
  }
21
- stop() {
26
+ async stop() {
22
27
  this._isRunning = false;
23
28
  if (this.renderLoopId !== null) {
24
29
  cancelIdleCallback(this.renderLoopId);
25
30
  this.renderLoopId = null;
26
31
  }
32
+ this.renderingPromises.clear();
27
33
  }
28
34
  pause() {
29
- this.stop();
35
+ this._isPaused = true;
30
36
  }
31
37
  resume() {
32
- this.start();
38
+ this._isPaused = false;
39
+ if (this._isRunning && !this.renderLoopId) {
40
+ this.scheduleNextRender();
41
+ }
33
42
  }
34
43
  setWindow(size) {
35
44
  this.strategy.lookahead = size;
@@ -46,6 +55,9 @@ class PreRenderService {
46
55
  updatePlaybackTime(timeUs) {
47
56
  this._currentTimeUs = timeUs;
48
57
  }
58
+ setPlaybackActive(active) {
59
+ this.isPlaybackActive = active;
60
+ }
49
61
  get isRunning() {
50
62
  return this._isRunning;
51
63
  }
@@ -71,10 +83,60 @@ class PreRenderService {
71
83
  );
72
84
  }
73
85
  async renderTick() {
74
- if (!this._isRunning || !this.orchestrator.compositionModel) {
86
+ if (!this._isRunning || this._isPaused || !this.orchestrator.compositionModel) {
87
+ return;
88
+ }
89
+ const model = this.orchestrator.compositionModel;
90
+ if (this.isPlaybackActive) {
75
91
  return;
76
92
  }
77
- await this.orchestrator.ensureClipCache(this._currentTimeUs);
93
+ if (this.isRendering) {
94
+ return;
95
+ }
96
+ const videoTracks = model.tracks.filter((t) => t.kind === "video");
97
+ const allClips = videoTracks.flatMap((t) => t.clips);
98
+ if (allClips.length === 0) {
99
+ return;
100
+ }
101
+ let clipToRender = null;
102
+ for (const clip of allClips) {
103
+ if (!this.processedClips.has(clip.id)) {
104
+ const inL2 = await this.orchestrator.cacheManager.hasClipInL2(clip.id, "video");
105
+ if (!inL2) {
106
+ clipToRender = clip;
107
+ break;
108
+ } else {
109
+ this.processedClips.add(clip.id);
110
+ }
111
+ }
112
+ }
113
+ if (!clipToRender) {
114
+ void this.stop();
115
+ return;
116
+ }
117
+ this.isRendering = true;
118
+ try {
119
+ await this.renderClipToL2(clipToRender.id);
120
+ this.processedClips.add(clipToRender.id);
121
+ } catch (error) {
122
+ console.error(`[PreRenderService] Failed to render clip ${clipToRender.id}:`, error);
123
+ } finally {
124
+ this.isRendering = false;
125
+ }
126
+ }
127
+ /**
128
+ * Render a complete clip to L2 cache
129
+ * Creates dedicated pipeline that bypasses L1 window management
130
+ */
131
+ async renderClipToL2(clipId) {
132
+ const model = this.orchestrator.compositionModel;
133
+ if (!model) return;
134
+ const clip = model.findClip(clipId);
135
+ if (!clip) return;
136
+ await this.orchestrator.renderClipForL2(clipId);
137
+ const fps = model.fps || 30;
138
+ const expectedFrames = Math.ceil(clip.durationUs / 1e6 * fps);
139
+ this._framesRendered += expectedFrames;
78
140
  }
79
141
  }
80
142
  export {
@@ -1 +1 @@
1
- {"version":3,"file":"PreRenderService.js","sources":["../../src/controllers/PreRenderService.ts"],"sourcesContent":["import type { IPreRenderService, RenderStrategy, PreRenderStatus } from './types';\nimport type { TimeUs } from '../model/types';\nimport type { Orchestrator } from '../orchestrator';\n\n/**\n * Simplified background pre-render service for 3-Clip strategy\n *\n * In the 3-Clip strategy, ClipFetchQueue already handles Prev/Current/Next caching.\n * This service is kept minimal for compatibility but does minimal work.\n */\nexport class PreRenderService implements IPreRenderService {\n private orchestrator: Orchestrator;\n private _isRunning = false;\n private renderLoopId: number | null = null;\n private _framesRendered = 0;\n private _currentTimeUs: TimeUs = 0;\n private strategy: RenderStrategy = {\n direction: 'forward',\n lookahead: 3_000_000,\n lookbehind: 2_000_000,\n keyframesOnly: false,\n };\n\n constructor(orchestrator: Orchestrator, _eventBus: any) {\n this.orchestrator = orchestrator;\n }\n\n start(): void {\n if (this._isRunning) return;\n this._isRunning = true;\n this.scheduleNextRender();\n }\n\n stop(): void {\n this._isRunning = false;\n\n if (this.renderLoopId !== null) {\n cancelIdleCallback(this.renderLoopId);\n this.renderLoopId = null;\n }\n }\n\n pause(): void {\n this.stop();\n }\n\n resume(): void {\n this.start();\n }\n\n setWindow(size: TimeUs): void {\n this.strategy.lookahead = size;\n }\n\n setStrategy(strategy: Partial<RenderStrategy>): void {\n this.strategy = { ...this.strategy, ...strategy };\n }\n\n setPriority(_priority: 'low' | 'normal' | 'high'): void {\n // Simplified - no-op for 3-Clip strategy\n }\n\n clearQueue(): void {\n // Simplified - no-op for 3-Clip strategy\n }\n\n queueRange(_startUs: TimeUs, _endUs: TimeUs, _priority?: number): void {\n // Simplified - no-op for 3-Clip strategy\n }\n\n updatePlaybackTime(timeUs: TimeUs): void {\n this._currentTimeUs = timeUs;\n }\n\n get isRunning(): boolean {\n return this._isRunning;\n }\n\n get queueSize(): number {\n return 0;\n }\n\n get status(): PreRenderStatus {\n return {\n isRunning: this._isRunning,\n framesRendered: this._framesRendered,\n queueSize: 0,\n currentTimeUs: this._currentTimeUs,\n };\n }\n\n private scheduleNextRender(): void {\n if (!this._isRunning) return;\n\n this.renderLoopId = requestIdleCallback(\n async () => {\n await this.renderTick();\n this.scheduleNextRender();\n },\n { timeout: 100 }\n );\n }\n\n private async renderTick(): Promise<void> {\n if (!this._isRunning || !this.orchestrator.compositionModel) {\n return;\n }\n\n // In 3-Clip strategy, just ensure clips are cached\n // ClipFetchQueue handles the actual fetching\n await this.orchestrator.ensureClipCache(this._currentTimeUs);\n }\n}\n"],"names":[],"mappings":"AAUO,MAAM,iBAA8C;AAAA,EACjD;AAAA,EACA,aAAa;AAAA,EACb,eAA8B;AAAA,EAC9B,kBAAkB;AAAA,EAClB,iBAAyB;AAAA,EACzB,WAA2B;AAAA,IACjC,WAAW;AAAA,IACX,WAAW;AAAA,IACX,YAAY;AAAA,IACZ,eAAe;AAAA,EAAA;AAAA,EAGjB,YAAY,cAA4B,WAAgB;AACtD,SAAK,eAAe;AAAA,EACtB;AAAA,EAEA,QAAc;AACZ,QAAI,KAAK,WAAY;AACrB,SAAK,aAAa;AAClB,SAAK,mBAAA;AAAA,EACP;AAAA,EAEA,OAAa;AACX,SAAK,aAAa;AAElB,QAAI,KAAK,iBAAiB,MAAM;AAC9B,yBAAmB,KAAK,YAAY;AACpC,WAAK,eAAe;AAAA,IACtB;AAAA,EACF;AAAA,EAEA,QAAc;AACZ,SAAK,KAAA;AAAA,EACP;AAAA,EAEA,SAAe;AACb,SAAK,MAAA;AAAA,EACP;AAAA,EAEA,UAAU,MAAoB;AAC5B,SAAK,SAAS,YAAY;AAAA,EAC5B;AAAA,EAEA,YAAY,UAAyC;AACnD,SAAK,WAAW,EAAE,GAAG,KAAK,UAAU,GAAG,SAAA;AAAA,EACzC;AAAA,EAEA,YAAY,WAA4C;AAAA,EAExD;AAAA,EAEA,aAAmB;AAAA,EAEnB;AAAA,EAEA,WAAW,UAAkB,QAAgB,WAA0B;AAAA,EAEvE;AAAA,EAEA,mBAAmB,QAAsB;AACvC,SAAK,iBAAiB;AAAA,EACxB;AAAA,EAEA,IAAI,YAAqB;AACvB,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,IAAI,YAAoB;AACtB,WAAO;AAAA,EACT;AAAA,EAEA,IAAI,SAA0B;AAC5B,WAAO;AAAA,MACL,WAAW,KAAK;AAAA,MAChB,gBAAgB,KAAK;AAAA,MACrB,WAAW;AAAA,MACX,eAAe,KAAK;AAAA,IAAA;AAAA,EAExB;AAAA,EAEQ,qBAA2B;AACjC,QAAI,CAAC,KAAK,WAAY;AAEtB,SAAK,eAAe;AAAA,MAClB,YAAY;AACV,cAAM,KAAK,WAAA;AACX,aAAK,mBAAA;AAAA,MACP;AAAA,MACA,EAAE,SAAS,IAAA;AAAA,IAAI;AAAA,EAEnB;AAAA,EAEA,MAAc,aAA4B;AACxC,QAAI,CAAC,KAAK,cAAc,CAAC,KAAK,aAAa,kBAAkB;AAC3D;AAAA,IACF;AAIA,UAAM,KAAK,aAAa,gBAAgB,KAAK,cAAc;AAAA,EAC7D;AACF;"}
1
+ {"version":3,"file":"PreRenderService.js","sources":["../../src/controllers/PreRenderService.ts"],"sourcesContent":["import type { IPreRenderService, RenderStrategy, PreRenderStatus } from './types';\nimport type { TimeUs } from '../model/types';\nimport type { Orchestrator } from '../orchestrator';\n\n/**\n * PreRenderService: Background pre-render for filling L2 cache\n *\n * Dual-mode strategy:\n * 1. When playback active: Ensure 2-Clip window (Prev/Current/Next) for preview\n * 2. When idle: Continue rendering subsequent clips for L2 export cache\n *\n * Goals:\n * - Maintain smooth preview (2-Clip L1 cache)\n * - Build complete L2 cache for fast export\n * - Operate in background without blocking\n */\nexport class PreRenderService implements IPreRenderService {\n private orchestrator: Orchestrator;\n private _isRunning = false;\n private _isPaused = false;\n private renderLoopId: number | null = null;\n private _framesRendered = 0;\n private _currentTimeUs: TimeUs = 0;\n private processedClips = new Set<string>();\n private isPlaybackActive = false;\n private strategy: RenderStrategy = {\n direction: 'forward',\n lookahead: 3_000_000,\n lookbehind: 2_000_000,\n keyframesOnly: false,\n };\n\n private isRendering = false;\n private renderingPromises = new Map<\n string,\n { resolve: () => void; reject: (err: any) => void }\n >();\n\n constructor(orchestrator: Orchestrator, _eventBus: any) {\n this.orchestrator = orchestrator;\n }\n\n start(): void {\n if (this._isRunning) return;\n this._isRunning = true;\n this.scheduleNextRender();\n }\n\n async stop(): Promise<void> {\n this._isRunning = false;\n\n if (this.renderLoopId !== null) {\n cancelIdleCallback(this.renderLoopId);\n this.renderLoopId = null;\n }\n\n this.renderingPromises.clear();\n }\n\n pause(): void {\n this._isPaused = true;\n }\n\n resume(): void {\n this._isPaused = false;\n if (this._isRunning && !this.renderLoopId) {\n this.scheduleNextRender();\n }\n }\n\n setWindow(size: TimeUs): void {\n this.strategy.lookahead = size;\n }\n\n setStrategy(strategy: Partial<RenderStrategy>): void {\n this.strategy = { ...this.strategy, ...strategy };\n }\n\n setPriority(_priority: 'low' | 'normal' | 'high'): void {\n // Simplified - no-op for 2-Clip strategy\n }\n\n clearQueue(): void {\n // Simplified - no-op for 2-Clip strategy\n }\n\n queueRange(_startUs: TimeUs, _endUs: TimeUs, _priority?: number): void {\n // Simplified - no-op for 2-Clip strategy\n }\n\n updatePlaybackTime(timeUs: TimeUs): void {\n this._currentTimeUs = timeUs;\n }\n\n setPlaybackActive(active: boolean): void {\n this.isPlaybackActive = active;\n }\n\n get isRunning(): boolean {\n return this._isRunning;\n }\n\n get queueSize(): number {\n return 0;\n }\n\n get status(): PreRenderStatus {\n return {\n isRunning: this._isRunning,\n framesRendered: this._framesRendered,\n queueSize: 0,\n currentTimeUs: this._currentTimeUs,\n };\n }\n\n private scheduleNextRender(): void {\n if (!this._isRunning) return;\n\n this.renderLoopId = requestIdleCallback(\n async () => {\n await this.renderTick();\n this.scheduleNextRender();\n },\n { timeout: 100 }\n );\n }\n\n private async renderTick(): Promise<void> {\n if (!this._isRunning || this._isPaused || !this.orchestrator.compositionModel) {\n return;\n }\n\n const model = this.orchestrator.compositionModel;\n\n if (this.isPlaybackActive) {\n // Playback mode: Do nothing, PlaybackController manages 2-clip window\n return;\n }\n\n // If already rendering, skip this tick\n if (this.isRendering) {\n return;\n }\n\n // Idle mode: Continue rendering clips beyond 2-Clip window for L2 cache\n const videoTracks = model.tracks.filter((t) => t.kind === 'video');\n const allClips = videoTracks.flatMap((t) => t.clips);\n\n if (allClips.length === 0) {\n return;\n }\n\n // Find next clip to render (single pass, prioritized order)\n let clipToRender = null;\n for (const clip of allClips) {\n if (!this.processedClips.has(clip.id)) {\n const inL2 = await this.orchestrator.cacheManager.hasClipInL2(clip.id, 'video');\n if (!inL2) {\n clipToRender = clip;\n break;\n } else {\n this.processedClips.add(clip.id);\n }\n }\n }\n\n // All clips processed\n if (!clipToRender) {\n void this.stop();\n return;\n }\n\n // Render this clip completely with concurrency protection\n this.isRendering = true;\n try {\n await this.renderClipToL2(clipToRender.id);\n this.processedClips.add(clipToRender.id);\n } catch (error) {\n console.error(`[PreRenderService] Failed to render clip ${clipToRender.id}:`, error);\n } finally {\n this.isRendering = false;\n }\n }\n\n /**\n * Render a complete clip to L2 cache\n * Creates dedicated pipeline that bypasses L1 window management\n */\n private async renderClipToL2(clipId: string): Promise<void> {\n const model = this.orchestrator.compositionModel;\n if (!model) return;\n\n const clip = model.findClip(clipId);\n if (!clip) return;\n\n // Start L2 rendering\n await this.orchestrator.renderClipForL2(clipId);\n\n // Update counter\n const fps = model.fps || 30;\n const expectedFrames = Math.ceil((clip.durationUs / 1_000_000) * fps);\n this._framesRendered += expectedFrames;\n }\n}\n"],"names":[],"mappings":"AAgBO,MAAM,iBAA8C;AAAA,EACjD;AAAA,EACA,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,eAA8B;AAAA,EAC9B,kBAAkB;AAAA,EAClB,iBAAyB;AAAA,EACzB,qCAAqB,IAAA;AAAA,EACrB,mBAAmB;AAAA,EACnB,WAA2B;AAAA,IACjC,WAAW;AAAA,IACX,WAAW;AAAA,IACX,YAAY;AAAA,IACZ,eAAe;AAAA,EAAA;AAAA,EAGT,cAAc;AAAA,EACd,wCAAwB,IAAA;AAAA,EAKhC,YAAY,cAA4B,WAAgB;AACtD,SAAK,eAAe;AAAA,EACtB;AAAA,EAEA,QAAc;AACZ,QAAI,KAAK,WAAY;AACrB,SAAK,aAAa;AAClB,SAAK,mBAAA;AAAA,EACP;AAAA,EAEA,MAAM,OAAsB;AAC1B,SAAK,aAAa;AAElB,QAAI,KAAK,iBAAiB,MAAM;AAC9B,yBAAmB,KAAK,YAAY;AACpC,WAAK,eAAe;AAAA,IACtB;AAEA,SAAK,kBAAkB,MAAA;AAAA,EACzB;AAAA,EAEA,QAAc;AACZ,SAAK,YAAY;AAAA,EACnB;AAAA,EAEA,SAAe;AACb,SAAK,YAAY;AACjB,QAAI,KAAK,cAAc,CAAC,KAAK,cAAc;AACzC,WAAK,mBAAA;AAAA,IACP;AAAA,EACF;AAAA,EAEA,UAAU,MAAoB;AAC5B,SAAK,SAAS,YAAY;AAAA,EAC5B;AAAA,EAEA,YAAY,UAAyC;AACnD,SAAK,WAAW,EAAE,GAAG,KAAK,UAAU,GAAG,SAAA;AAAA,EACzC;AAAA,EAEA,YAAY,WAA4C;AAAA,EAExD;AAAA,EAEA,aAAmB;AAAA,EAEnB;AAAA,EAEA,WAAW,UAAkB,QAAgB,WAA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I,KAAK,EAAE;AAAA,QACjC;AAAA,MACF;AAAA,IACF;AAGA,QAAI,CAAC,cAAc;AACjB,WAAK,KAAK,KAAA;AACV;AAAA,IACF;AAGA,SAAK,cAAc;AACnB,QAAI;AACF,YAAM,KAAK,eAAe,aAAa,EAAE;AACzC,WAAK,eAAe,IAAI,aAAa,EAAE;AAAA,IACzC,SAAS,OAAO;AACd,cAAQ,MAAM,4CAA4C,aAAa,EAAE,KAAK,KAAK;AAAA,IACrF,UAAA;AACE,WAAK,cAAc;AAAA,IACrB;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAc,eAAe,QAA+B;AAC1D,UAAM,QAAQ,KAAK,aAAa;AAChC,QAAI,CAAC,MAAO;AAEZ,UAAM,OAAO,MAAM,SAAS,MAAM;AAClC,QAAI,CAAC,KAAM;AAGX,UAAM,KAAK,aAAa,gBAAgB,MAAM;AAG9C,UAAM,MAAM,MAAM,OAAO;AACzB,UAAM,iBAAiB,KAAK,KAAM,KAAK,aAAa,MAAa,GAAG;AACpE,SAAK,mBAAmB;AAAA,EAC1B;AACF;"}
@@ -34,7 +34,7 @@ export declare class CompositionModel {
34
34
  next?: string;
35
35
  };
36
36
  /**
37
- * Get all clip IDs that should be cached using 3-Clip strategy
37
+ * Get all clip IDs that should be cached using 2-Clip strategy
38
38
  * Returns array of unique clip IDs (Prev/Current/Next)
39
39
  */
40
40
  getClipsToCacheAtTime(timeUs: TimeUs): string[];
@@ -119,7 +119,7 @@ ${errors.map((e) => `${e.path}: ${e.message}`).join("\n")}`
119
119
  return result;
120
120
  }
121
121
  /**
122
- * Get all clip IDs that should be cached using 3-Clip strategy
122
+ * Get all clip IDs that should be cached using 2-Clip strategy
123
123
  * Returns array of unique clip IDs (Prev/Current/Next)
124
124
  */
125
125
  getClipsToCacheAtTime(timeUs) {
@@ -1 +1 @@
1
- {"version":3,"file":"CompositionModel.js","sources":["../../src/model/CompositionModel.ts"],"sourcesContent":["import { CompositionModelData, Track, Clip, Resource, TimeUs } from './types';\nimport { binarySearchRange, binarySearchOverlapping } from '../utils/binary-search';\nimport { validateCompositionStructure } from './validation';\n\nexport class CompositionModel {\n public readonly version = '1.0' as const;\n public readonly fps: 24 | 25 | 30 | 60;\n public durationUs: TimeUs;\n public readonly mainTrackId: string;\n public readonly tracks: Track[];\n public readonly resources: Map<string, Resource>;\n\n private readonly trackMap: Map<string, Track>;\n private readonly clipMap: Map<string, Clip>;\n private readonly resourceRefCount: Map<string, number>;\n\n public readonly renderConfig?: {\n width: number;\n height: number;\n backgroundColor?: string;\n };\n\n public readonly ext?: Record<string, unknown>;\n\n constructor(data: CompositionModelData) {\n const errors = validateCompositionStructure(data);\n if (errors.length > 0) {\n throw new Error(\n `Validation failed:\\n${errors.map((e) => `${e.path}: ${e.message}`).join('\\n')}`\n );\n }\n\n this.fps = data.fps;\n this.mainTrackId = data.mainTrackId ?? 'main';\n this.tracks = data.tracks;\n this.resources = new Map(Object.entries(data.resources));\n this.renderConfig = data.renderConfig;\n this.ext = data.ext;\n\n // Build indexes\n this.trackMap = new Map();\n this.clipMap = new Map();\n this.resourceRefCount = new Map();\n\n this.buildIndexes();\n this.durationUs = this.calculateDuration();\n }\n\n // Track operations\n findTrack(id: string): Track | null {\n return this.trackMap.get(id) || null;\n }\n\n getTracksByKind(kind: 'video' | 'audio' | 'caption' | 'fx'): Track[] {\n return this.tracks.filter((track) => track.kind === kind);\n }\n\n // Clip operations with binary search optimization\n findClip(id: string): Clip | null {\n return this.clipMap.get(id) || null;\n }\n\n getClipsAtTime(timeUs: TimeUs, trackId?: string): Clip[] {\n const tracks = trackId ? [this.findTrack(trackId)] : this.tracks;\n const clips: Clip[] = [];\n\n for (const track of tracks) {\n if (!track) continue;\n // Use binary search for single point lookup\n const clip = binarySearchRange(track.clips, timeUs, (entry) => ({\n start: entry.startUs,\n end: entry.startUs + entry.durationUs,\n }));\n\n if (clip) {\n clips.push(clip);\n }\n }\n\n return clips;\n }\n\n getActiveClips(startUs: TimeUs, endUs: TimeUs): Clip[] {\n const clips: Clip[] = [];\n\n for (const track of this.tracks) {\n // Use binary search for range overlap\n const overlappingClips = binarySearchOverlapping(track.clips, startUs, endUs, (clip) => ({\n start: clip.startUs,\n end: clip.startUs + clip.durationUs,\n }));\n\n clips.push(...overlappingClips);\n }\n\n return clips;\n }\n\n getClipIdsByResourceId(resourceId: string): string[] {\n const resource = this.resources.get(resourceId);\n return resource?.clipIds || [];\n }\n\n getClipIdAtTime(trackId: string, timeUs: TimeUs): string | undefined {\n const track = this.findTrack(trackId);\n if (!track) {\n return undefined;\n }\n\n const clip = binarySearchRange(track.clips, timeUs, (entry) => ({\n start: entry.startUs,\n end: entry.startUs + entry.durationUs,\n }));\n\n return clip?.id;\n }\n\n /**\n * Get neighboring clips (Prev/Current/Next) at a specific time for video tracks\n * Returns prev, current, and next clip IDs\n */\n getNeighboringClips(timeUs: TimeUs): { prev?: string; current?: string; next?: string } {\n const videoTracks = this.getTracksByKind('video');\n const result: { prev?: string; current?: string; next?: string } = {};\n\n for (const track of videoTracks) {\n const clips = track.clips;\n\n for (let i = 0; i < clips.length; i++) {\n const clip = clips[i];\n if (!clip) continue;\n\n const clipEndUs = clip.startUs + clip.durationUs;\n\n if (clip.startUs <= timeUs && timeUs < clipEndUs) {\n if (!result.current) {\n result.current = clip.id;\n }\n\n if (i > 0 && !result.prev) {\n const prevClip = clips[i - 1];\n if (prevClip) {\n result.prev = prevClip.id;\n }\n }\n\n if (i < clips.length - 1 && !result.next) {\n const nextClip = clips[i + 1];\n if (nextClip) {\n result.next = nextClip.id;\n }\n }\n }\n }\n }\n\n return result;\n }\n\n /**\n * Get all clip IDs that should be cached using 3-Clip strategy\n * Returns array of unique clip IDs (Prev/Current/Next)\n */\n getClipsToCacheAtTime(timeUs: TimeUs): string[] {\n const { current, next } = this.getNeighboringClips(timeUs);\n const clipIds: string[] = [];\n\n if (current) clipIds.push(current);\n if (next) clipIds.push(next);\n // if (prev) clipIds.push(prev);\n\n return Array.from(new Set(clipIds));\n }\n\n // Resource operations\n getResource(id: string): Resource | null {\n return this.resources.get(id) || null;\n }\n\n updateResourceState(id: string, state: 'pending' | 'loading' | 'ready' | 'error'): void {\n const resource = this.resources.get(id);\n if (resource) {\n resource.state = state;\n }\n }\n\n getUnusedResources(): Resource[] {\n const unused: Resource[] = [];\n\n for (const [id, resource] of this.resources) {\n if (!this.resourceRefCount.has(id) || this.resourceRefCount.get(id) === 0) {\n unused.push(resource);\n }\n }\n\n return unused;\n }\n\n // Time operations\n getDuration(): TimeUs {\n return this.durationUs;\n }\n\n getTrackDuration(trackId: string): TimeUs {\n const track = this.findTrack(trackId);\n if (!track || track.clips.length === 0) return 0;\n\n // Since clips are sorted, last clip determines duration\n const lastClip = track.clips[track.clips.length - 1];\n return (lastClip?.startUs ?? 0) + (lastClip?.durationUs ?? 0);\n }\n\n // Private methods\n private buildIndexes(): void {\n // Clear existing indexes\n this.trackMap.clear();\n this.clipMap.clear();\n this.resourceRefCount.clear();\n\n // Build track and clip indexes\n for (const track of this.tracks) {\n this.trackMap.set(track.id, track);\n\n for (const clip of track.clips) {\n (clip as Clip).trackId = track.id;\n (clip as Clip).trackKind = track.kind;\n this.clipMap.set(clip.id, clip);\n\n // Add clip id to resource\n const resource = this.resources.get(clip.resourceId);\n if (resource) {\n resource.clipIds = [...(resource.clipIds || []), clip.id];\n }\n // Count resource references\n const count = this.resourceRefCount.get(clip.resourceId) || 0;\n this.resourceRefCount.set(clip.resourceId, count + 1);\n }\n }\n\n // Sort clips by startUs within each track for binary search\n for (const track of this.tracks) {\n track.clips.sort((a, b) => a.startUs - b.startUs);\n }\n }\n\n private calculateDuration(): TimeUs {\n let maxEndUs = 0;\n\n for (const track of this.tracks) {\n const trackDuration = this.getTrackDuration(track.id);\n if (trackDuration > maxEndUs) {\n maxEndUs = trackDuration;\n }\n }\n\n return maxEndUs;\n }\n}\n"],"names":[],"mappings":";;AAIO,MAAM,iBAAiB;AAAA,EACZ,UAAU;AAAA,EACV;AA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O;AACpC,QAAI,CAAC,SAAS,MAAM,MAAM,WAAW,EAAG,QAAO;AAG/C,UAAM,WAAW,MAAM,MAAM,MAAM,MAAM,SAAS,CAAC;AACnD,YAAQ,UAAU,WAAW,MAAM,UAAU,cAAc;AAAA,EAC7D;AAAA;AAAA,EAGQ,eAAqB;AAE3B,SAAK,SAAS,MAAA;AACd,SAAK,QAAQ,MAAA;AACb,SAAK,iBAAiB,MAAA;AAGtB,eAAW,SAAS,KAAK,QAAQ;AAC/B,WAAK,SAAS,IAAI,MAAM,IAAI,KAAK;AAEjC,iBAAW,QAAQ,MAAM,OAAO;AAC7B,aAAc,UAAU,MAAM;AAC9B,aAAc,YAAY,MAAM;AACjC,aAAK,QAAQ,IAAI,KAAK,IAAI,IAAI;AAG9B,cAAM,WAAW,KAAK,UAAU,IAAI,KAAK,UAAU;AACnD,YAAI,UAAU;AACZ,mBAAS,UAAU,CAAC,GAAI,SAAS,WAAW,CAAA,GAAK,KAAK,EAAE;AAAA,QAC1D;AAEA,cAAM,QAAQ,KAAK,iBAAiB,IAAI,KAAK,UAAU,KAAK;AAC5D,aAAK,iBAAiB,IAAI,KAAK,YAAY,QAAQ,CAAC;AAAA,MACtD;AAAA,IACF;AAGA,eAAW,SAAS,KAAK,QAAQ;AAC/B,YAAM,MAAM,KAAK,CAAC,GAAG,MAAM,EAAE,UAAU,EAAE,OAAO;AAAA,IAClD;AAAA,EACF;AAAA,EAEQ,oBAA4B;AAClC,QAAI,WAAW;AAEf,eAAW,SAAS,KAAK,QAAQ;AAC/B,YAAM,gBAAgB,KAAK,iBAAiB,MAAM,EAAE;AACpD,UAAI,gBAAgB,UAAU;AAC5B,mBAAW;AAAA,MACb;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AACF;"}
1
+ {"version":3,"file":"CompositionModel.js","sources":["../../src/model/CompositionModel.ts"],"sourcesContent":["import { CompositionModelData, Track, Clip, Resource, TimeUs } from './types';\nimport { binarySearchRange, binarySearchOverlapping } from '../utils/binary-search';\nimport { validateCompositionStructure } from './validation';\n\nexport class CompositionModel {\n public readonly version = '1.0' as const;\n public readonly fps: 24 | 25 | 30 | 60;\n public durationUs: TimeUs;\n public readonly mainTrackId: string;\n public readonly tracks: Track[];\n public readonly resources: Map<string, Resource>;\n\n private readonly trackMap: Map<string, Track>;\n private readonly clipMap: Map<string, Clip>;\n private readonly resourceRefCount: Map<string, number>;\n\n public readonly renderConfig?: {\n width: number;\n height: number;\n backgroundColor?: string;\n };\n\n public readonly ext?: Record<string, unknown>;\n\n constructor(data: CompositionModelData) {\n const errors = validateCompositionStructure(data);\n if (errors.length > 0) {\n throw new Error(\n `Validation failed:\\n${errors.map((e) => `${e.path}: ${e.message}`).join('\\n')}`\n );\n }\n\n this.fps = data.fps;\n this.mainTrackId = data.mainTrackId ?? 'main';\n this.tracks = data.tracks;\n this.resources = new Map(Object.entries(data.resources));\n this.renderConfig = data.renderConfig;\n this.ext = data.ext;\n\n // Build indexes\n this.trackMap = new Map();\n this.clipMap = new Map();\n this.resourceRefCount = new Map();\n\n this.buildIndexes();\n this.durationUs = this.calculateDuration();\n }\n\n // Track operations\n findTrack(id: string): Track | null {\n return this.trackMap.get(id) || null;\n }\n\n getTracksByKind(kind: 'video' | 'audio' | 'caption' | 'fx'): Track[] {\n return this.tracks.filter((track) => track.kind === kind);\n }\n\n // Clip operations with binary search optimization\n findClip(id: string): Clip | null {\n return this.clipMap.get(id) || null;\n }\n\n getClipsAtTime(timeUs: TimeUs, trackId?: string): Clip[] {\n const tracks = trackId ? [this.findTrack(trackId)] : this.tracks;\n const clips: Clip[] = [];\n\n for (const track of tracks) {\n if (!track) continue;\n // Use binary search for single point lookup\n const clip = binarySearchRange(track.clips, timeUs, (entry) => ({\n start: entry.startUs,\n end: entry.startUs + entry.durationUs,\n }));\n\n if (clip) {\n clips.push(clip);\n }\n }\n\n return clips;\n }\n\n getActiveClips(startUs: TimeUs, endUs: TimeUs): Clip[] {\n const clips: Clip[] = [];\n\n for (const track of this.tracks) {\n // Use binary search for range overlap\n const overlappingClips = binarySearchOverlapping(track.clips, startUs, endUs, (clip) => ({\n start: clip.startUs,\n end: clip.startUs + clip.durationUs,\n }));\n\n clips.push(...overlappingClips);\n }\n\n return clips;\n }\n\n getClipIdsByResourceId(resourceId: string): string[] {\n const resource = this.resources.get(resourceId);\n return resource?.clipIds || [];\n }\n\n getClipIdAtTime(trackId: string, timeUs: TimeUs): string | undefined {\n const track = this.findTrack(trackId);\n if (!track) {\n return undefined;\n }\n\n const clip = binarySearchRange(track.clips, timeUs, (entry) => ({\n start: entry.startUs,\n end: entry.startUs + entry.durationUs,\n }));\n\n return clip?.id;\n }\n\n /**\n * Get neighboring clips (Prev/Current/Next) at a specific time for video tracks\n * Returns prev, current, and next clip IDs\n */\n getNeighboringClips(timeUs: TimeUs): { prev?: string; current?: string; next?: string } {\n const videoTracks = this.getTracksByKind('video');\n const result: { prev?: string; current?: string; next?: string } = {};\n\n for (const track of videoTracks) {\n const clips = track.clips;\n\n for (let i = 0; i < clips.length; i++) {\n const clip = clips[i];\n if (!clip) continue;\n\n const clipEndUs = clip.startUs + clip.durationUs;\n\n if (clip.startUs <= timeUs && timeUs < clipEndUs) {\n if (!result.current) {\n result.current = clip.id;\n }\n\n if (i > 0 && !result.prev) {\n const prevClip = clips[i - 1];\n if (prevClip) {\n result.prev = prevClip.id;\n }\n }\n\n if (i < clips.length - 1 && !result.next) {\n const nextClip = clips[i + 1];\n if (nextClip) {\n result.next = nextClip.id;\n }\n }\n }\n }\n }\n\n return result;\n }\n\n /**\n * Get all clip IDs that should be cached using 2-Clip strategy\n * Returns array of unique clip IDs (Prev/Current/Next)\n */\n getClipsToCacheAtTime(timeUs: TimeUs): string[] {\n const { current, next } = this.getNeighboringClips(timeUs);\n const clipIds: string[] = [];\n\n if (current) clipIds.push(current);\n if (next) clipIds.push(next);\n // if (prev) clipIds.push(prev);\n\n return Array.from(new Set(clipIds));\n }\n\n // Resource operations\n getResource(id: string): Resource | null {\n return this.resources.get(id) || null;\n }\n\n updateResourceState(id: string, state: 'pending' | 'loading' | 'ready' | 'error'): void {\n const resource = this.resources.get(id);\n if (resource) {\n resource.state = state;\n }\n }\n\n getUnusedResources(): Resource[] {\n const unused: Resource[] = [];\n\n for (const [id, resource] of this.resources) {\n if (!this.resourceRefCount.has(id) || this.resourceRefCount.get(id) === 0) {\n unused.push(resource);\n }\n }\n\n return unused;\n }\n\n // Time operations\n getDuration(): TimeUs {\n return this.durationUs;\n }\n\n getTrackDuration(trackId: string): TimeUs {\n const track = this.findTrack(trackId);\n if (!track || track.clips.length === 0) return 0;\n\n // Since clips are sorted, last clip determines duration\n const lastClip = track.clips[track.clips.length - 1];\n return (lastClip?.startUs ?? 0) + (lastClip?.durationUs ?? 0);\n }\n\n // Private methods\n private buildIndexes(): void {\n // Clear existing indexes\n this.trackMap.clear();\n this.clipMap.clear();\n this.resourceRefCount.clear();\n\n // Build track and clip indexes\n for (const track of this.tracks) {\n this.trackMap.set(track.id, track);\n\n for (const clip of track.clips) {\n (clip as Clip).trackId = track.id;\n (clip as Clip).trackKind = track.kind;\n this.clipMap.set(clip.id, clip);\n\n // Add clip id to resource\n const resource = this.resources.get(clip.resourceId);\n if (resource) {\n resource.clipIds = [...(resource.clipIds || []), clip.id];\n }\n // Count resource references\n const count = this.resourceRefCount.get(clip.resourceId) || 0;\n this.resourceRefCount.set(clip.resourceId, count + 1);\n }\n }\n\n // Sort clips by startUs within each track for binary search\n for (const track of this.tracks) {\n track.clips.sort((a, b) => a.startUs - b.startUs);\n }\n }\n\n private calculateDuration(): TimeUs {\n let maxEndUs = 0;\n\n for (const track of this.tracks) {\n const trackDuration = this.getTrackDuration(track.id);\n if (trackDuration > maxEndUs) {\n maxEndUs = trackDuration;\n }\n }\n\n return maxEndUs;\n }\n}\n"],"names":[],"mappings":";;AAIO,MAAM,iBAAiB;AAAA,EACZ,UAAU;AAAA,EACV;AAAA,EACT;AAAA,EACS;AAAA,EACA;AAAA,EACA;AAAA,EAEC;AAAA,E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/C,UAAM,WAAW,MAAM,MAAM,MAAM,MAAM,SAAS,CAAC;AACnD,YAAQ,UAAU,WAAW,MAAM,UAAU,cAAc;AAAA,EAC7D;AAAA;AAAA,EAGQ,eAAqB;AAE3B,SAAK,SAAS,MAAA;AACd,SAAK,QAAQ,MAAA;AACb,SAAK,iBAAiB,MAAA;AAGtB,eAAW,SAAS,KAAK,QAAQ;AAC/B,WAAK,SAAS,IAAI,MAAM,IAAI,KAAK;AAEjC,iBAAW,QAAQ,MAAM,OAAO;AAC7B,aAAc,UAAU,MAAM;AAC9B,aAAc,YAAY,MAAM;AACjC,aAAK,QAAQ,IAAI,KAAK,IAAI,IAAI;AAG9B,cAAM,WAAW,KAAK,UAAU,IAAI,KAAK,UAAU;AACnD,YAAI,UAAU;AACZ,mBAAS,UAAU,CAAC,GAAI,SAAS,WAAW,CAAA,GAAK,KAAK,EAAE;AAAA,QAC1D;AAEA,cAAM,QAAQ,KAAK,iBAAiB,IAAI,KAAK,UAAU,KAAK;AAC5D,aAAK,iBAAiB,IAAI,KAAK,YAAY,QAAQ,CAAC;AAAA,MACtD;AAAA,IACF;AAGA,eAAW,SAAS,KAAK,QAAQ;AAC/B,YAAM,MAAM,KAAK,CAAC,GAAG,MAAM,EAAE,UAAU,EAAE,OAAO;AAAA,IAClD;AAAA,EACF;AAAA,EAEQ,oBAA4B;AAClC,QAAI,WAAW;AAEf,eAAW,SAAS,KAAK,QAAQ;AAC/B,YAAM,gBAAgB,KAAK,iBAAiB,MAAM,EAAE;AACpD,UAAI,gBAAgB,UAAU;AAC5B,mBAAW;AAAA,MACb;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AACF;"}
@@ -3,7 +3,7 @@ import { CompositionPatch } from './types';
3
3
 
4
4
  /**
5
5
  * Apply patch to model and return affected clip IDs
6
- * Simplified for 3-Clip strategy - no complex time range calculation needed
6
+ * Simplified for 2-Clip strategy - no complex time range calculation needed
7
7
  */
8
8
  export declare function applyPatch(model: CompositionModel, patch: CompositionPatch): Set<string>;
9
9
  //# sourceMappingURL=patch.d.ts.map