@meframe/core 0.5.19 → 0.5.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cache/resource/ResourceCache.d.ts +18 -6
- package/dist/cache/resource/ResourceCache.d.ts.map +1 -1
- package/dist/cache/resource/ResourceCache.js +52 -2
- package/dist/cache/resource/ResourceCache.js.map +1 -1
- package/dist/cache/storage/opfs/OPFSManager.d.ts +15 -0
- package/dist/cache/storage/opfs/OPFSManager.d.ts.map +1 -1
- package/dist/cache/storage/opfs/OPFSManager.js +31 -5
- package/dist/cache/storage/opfs/OPFSManager.js.map +1 -1
- package/dist/orchestrator/VideoWindowDecodeSession.d.ts.map +1 -1
- package/dist/orchestrator/VideoWindowDecodeSession.js +3 -2
- package/dist/orchestrator/VideoWindowDecodeSession.js.map +1 -1
- package/dist/stages/load/ResourceLoader.d.ts +10 -1
- package/dist/stages/load/ResourceLoader.d.ts.map +1 -1
- package/dist/stages/load/ResourceLoader.js +68 -26
- package/dist/stages/load/ResourceLoader.js.map +1 -1
- package/package.json +23 -22
|
@@ -1,11 +1,5 @@
|
|
|
1
1
|
import { OPFSManager } from '../storage/opfs/OPFSManager';
|
|
2
2
|
|
|
3
|
-
/**
|
|
4
|
-
* ResourceCache - Original video resource OPFS cache
|
|
5
|
-
*
|
|
6
|
-
* Stores original MP4/video files for on-demand decoding
|
|
7
|
-
* Project-level quota management handled by OPFSManager
|
|
8
|
-
*/
|
|
9
3
|
export declare class ResourceCache {
|
|
10
4
|
readonly opfsManager: OPFSManager;
|
|
11
5
|
readonly projectId: string;
|
|
@@ -37,5 +31,23 @@ export declare class ResourceCache {
|
|
|
37
31
|
*/
|
|
38
32
|
clear(): Promise<void>;
|
|
39
33
|
private getFileName;
|
|
34
|
+
private audioPath;
|
|
35
|
+
/**
|
|
36
|
+
* Write an audio resource (whole buffer) to OPFS.
|
|
37
|
+
* OPFSManager handles quota management automatically.
|
|
38
|
+
*/
|
|
39
|
+
writeAudioResource(resourceId: string, buffer: ArrayBuffer): Promise<void>;
|
|
40
|
+
/**
|
|
41
|
+
* Read a whole audio resource file from OPFS.
|
|
42
|
+
*/
|
|
43
|
+
readAudioResource(resourceId: string): Promise<ArrayBuffer>;
|
|
44
|
+
/**
|
|
45
|
+
* Check if an audio resource exists in OPFS and has content.
|
|
46
|
+
*/
|
|
47
|
+
hasAudioResource(resourceId: string): Promise<boolean>;
|
|
48
|
+
/**
|
|
49
|
+
* Delete an audio resource from OPFS.
|
|
50
|
+
*/
|
|
51
|
+
deleteAudioResource(resourceId: string): Promise<void>;
|
|
40
52
|
}
|
|
41
53
|
//# sourceMappingURL=ResourceCache.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ResourceCache.d.ts","sourceRoot":"","sources":["../../../src/cache/resource/ResourceCache.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;
|
|
1
|
+
{"version":3,"file":"ResourceCache.d.ts","sourceRoot":"","sources":["../../../src/cache/resource/ResourceCache.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAc1D,qBAAa,aAAa;IACxB,QAAQ,CAAC,WAAW,EAAE,WAAW,CAAC;IAClC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;gBAEf,WAAW,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM;IAKjD,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAI3B;;;OAGG;IACG,aAAa,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,cAAc,CAAC,UAAU,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;IAyB1F;;OAEG;IACG,SAAS,CAAC,UAAU,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC;IAWrF;;OAEG;IACG,WAAW,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAqBvD;;OAEG;IACG,eAAe,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAW1D;;OAEG;IACG,cAAc,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAWvD;;OAEG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAI5B,OAAO,CAAC,WAAW;IAQnB,OAAO,CAAC,SAAS;IAQjB;;;OAGG;IACG,kBAAkB,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC;IAWhF;;OAEG;IACG,iBAAiB,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC;IAIjE;;OAEG;IACG,gBAAgB,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAY5D;;OAEG;IACG,mBAAmB,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAG7D"}
|
|
@@ -97,8 +97,58 @@ class ResourceCache {
|
|
|
97
97
|
async clear() {
|
|
98
98
|
await this.opfsManager.deleteProjectDirectory(this.projectId, "resource");
|
|
99
99
|
}
|
|
100
|
-
getFileName(resourceId) {
|
|
101
|
-
return `${resourceId}
|
|
100
|
+
getFileName(resourceId, kind = "video") {
|
|
101
|
+
return `${resourceId}.${kind === "audio" ? "mp3" : "mp4"}`;
|
|
102
|
+
}
|
|
103
|
+
// ── Audio resource (standalone voiceover / BGM) ────────────────────────────
|
|
104
|
+
// Audio files are small and parsed as a whole, so we persist/read the entire
|
|
105
|
+
// file rather than byte ranges. Same `resource` prefix, distinct extension.
|
|
106
|
+
audioPath(resourceId) {
|
|
107
|
+
return {
|
|
108
|
+
projectId: this.projectId,
|
|
109
|
+
prefix: "resource",
|
|
110
|
+
fileName: this.getFileName(resourceId, "audio")
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Write an audio resource (whole buffer) to OPFS.
|
|
115
|
+
* OPFSManager handles quota management automatically.
|
|
116
|
+
*/
|
|
117
|
+
async writeAudioResource(resourceId, buffer) {
|
|
118
|
+
try {
|
|
119
|
+
await this.opfsManager.writeFile(this.audioPath(resourceId), buffer);
|
|
120
|
+
} catch (error) {
|
|
121
|
+
if (error instanceof OPFSQuotaExceededError) {
|
|
122
|
+
throw new Error(`Failed to write audio resource ${resourceId}: ${error.message}`);
|
|
123
|
+
}
|
|
124
|
+
throw error;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Read a whole audio resource file from OPFS.
|
|
129
|
+
*/
|
|
130
|
+
async readAudioResource(resourceId) {
|
|
131
|
+
return await this.opfsManager.readFile(this.audioPath(resourceId));
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Check if an audio resource exists in OPFS and has content.
|
|
135
|
+
*/
|
|
136
|
+
async hasAudioResource(resourceId) {
|
|
137
|
+
const path = this.audioPath(resourceId);
|
|
138
|
+
const exists = await this.opfsManager.exists(path);
|
|
139
|
+
if (!exists) return false;
|
|
140
|
+
try {
|
|
141
|
+
const size = await this.opfsManager.getFileSize(path);
|
|
142
|
+
return size > 0;
|
|
143
|
+
} catch {
|
|
144
|
+
return false;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Delete an audio resource from OPFS.
|
|
149
|
+
*/
|
|
150
|
+
async deleteAudioResource(resourceId) {
|
|
151
|
+
await this.opfsManager.deleteFile(this.audioPath(resourceId));
|
|
102
152
|
}
|
|
103
153
|
}
|
|
104
154
|
export {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ResourceCache.js","sources":["../../../src/cache/resource/ResourceCache.ts"],"sourcesContent":["import { OPFSManager } from '../storage/opfs/OPFSManager';\nimport type { OPFSPath } from '../storage/opfs/types';\nimport { OPFSQuotaExceededError } from '../../utils/errors';\n\n/**\n * ResourceCache - Original
|
|
1
|
+
{"version":3,"file":"ResourceCache.js","sources":["../../../src/cache/resource/ResourceCache.ts"],"sourcesContent":["import { OPFSManager } from '../storage/opfs/OPFSManager';\nimport type { OPFSPath } from '../storage/opfs/types';\nimport { OPFSQuotaExceededError } from '../../utils/errors';\n\n/**\n * ResourceCache - Original media resource OPFS cache\n *\n * Stores original media files for on-demand decoding:\n * - video: MP4 files, read by byte range (GOP-level)\n * - audio: standalone audio files (voiceover / BGM), read as whole file\n * Both share the same `resource` OPFS directory; the file extension keeps them apart.\n * Project-level quota management handled by OPFSManager\n */\ntype ResourceKind = 'video' | 'audio';\nexport class ResourceCache {\n readonly opfsManager: OPFSManager;\n readonly projectId: string;\n\n constructor(opfsManager: OPFSManager, projectId: string) {\n this.opfsManager = opfsManager;\n this.projectId = projectId;\n }\n\n async init(): Promise<void> {\n await this.opfsManager.init();\n }\n\n /**\n * Write resource to OPFS (streaming)\n * OPFSManager handles quota management automatically\n */\n async writeResource(resourceId: string, stream: ReadableStream<Uint8Array>): Promise<void> {\n const fileName = this.getFileName(resourceId);\n const path: OPFSPath = {\n projectId: this.projectId,\n prefix: 'resource',\n fileName,\n };\n\n try {\n await this.opfsManager.writeFile(path, stream);\n } catch (error) {\n if (error instanceof OPFSQuotaExceededError) {\n if (error.retryable) {\n throw new Error(\n `Failed to write resource ${resourceId}: ${error.message} Please retry with a fresh stream.`\n );\n }\n throw new Error(\n `Failed to write resource ${resourceId}: No space available and no old projects to evict.`\n );\n }\n throw error;\n }\n }\n\n /**\n * Read byte range from resource (for GOP-level access)\n */\n async readRange(resourceId: string, start: number, end: number): Promise<ArrayBuffer> {\n const fileName = this.getFileName(resourceId);\n const path: OPFSPath = {\n projectId: this.projectId,\n prefix: 'resource',\n fileName,\n };\n\n return await this.opfsManager.readRange(path, start, end);\n }\n\n /**\n * Check if resource exists in OPFS and has content\n */\n async hasResource(resourceId: string): Promise<boolean> {\n const fileName = this.getFileName(resourceId);\n const path: OPFSPath = {\n projectId: this.projectId,\n prefix: 'resource',\n fileName,\n };\n\n // Check if file exists\n const exists = await this.opfsManager.exists(path);\n if (!exists) return false;\n\n // Check file size to avoid empty files (race condition protection)\n try {\n const size = await this.opfsManager.getFileSize(path);\n return size > 0;\n } catch {\n return false;\n }\n }\n\n /**\n * Get resource file size\n */\n async getResourceSize(resourceId: string): Promise<number> {\n const fileName = this.getFileName(resourceId);\n const path: OPFSPath = {\n projectId: this.projectId,\n prefix: 'resource',\n fileName,\n };\n\n return await this.opfsManager.getFileSize(path);\n }\n\n /**\n * Delete a resource from OPFS\n */\n async deleteResource(resourceId: string): Promise<void> {\n const fileName = this.getFileName(resourceId);\n const path: OPFSPath = {\n projectId: this.projectId,\n prefix: 'resource',\n fileName,\n };\n\n await this.opfsManager.deleteFile(path);\n }\n\n /**\n * Clear all resources for current project\n */\n async clear(): Promise<void> {\n await this.opfsManager.deleteProjectDirectory(this.projectId, 'resource');\n }\n\n private getFileName(resourceId: string, kind: ResourceKind = 'video'): string {\n return `${resourceId}.${kind === 'audio' ? 'mp3' : 'mp4'}`;\n }\n\n // ── Audio resource (standalone voiceover / BGM) ────────────────────────────\n // Audio files are small and parsed as a whole, so we persist/read the entire\n // file rather than byte ranges. Same `resource` prefix, distinct extension.\n\n private audioPath(resourceId: string): OPFSPath {\n return {\n projectId: this.projectId,\n prefix: 'resource',\n fileName: this.getFileName(resourceId, 'audio'),\n };\n }\n\n /**\n * Write an audio resource (whole buffer) to OPFS.\n * OPFSManager handles quota management automatically.\n */\n async writeAudioResource(resourceId: string, buffer: ArrayBuffer): Promise<void> {\n try {\n await this.opfsManager.writeFile(this.audioPath(resourceId), buffer);\n } catch (error) {\n if (error instanceof OPFSQuotaExceededError) {\n throw new Error(`Failed to write audio resource ${resourceId}: ${error.message}`);\n }\n throw error;\n }\n }\n\n /**\n * Read a whole audio resource file from OPFS.\n */\n async readAudioResource(resourceId: string): Promise<ArrayBuffer> {\n return await this.opfsManager.readFile(this.audioPath(resourceId));\n }\n\n /**\n * Check if an audio resource exists in OPFS and has content.\n */\n async hasAudioResource(resourceId: string): Promise<boolean> {\n const path = this.audioPath(resourceId);\n const exists = await this.opfsManager.exists(path);\n if (!exists) return false;\n try {\n const size = await this.opfsManager.getFileSize(path);\n return size > 0;\n } catch {\n return false;\n }\n }\n\n /**\n * Delete an audio resource from OPFS.\n */\n async deleteAudioResource(resourceId: string): Promise<void> {\n await this.opfsManager.deleteFile(this.audioPath(resourceId));\n }\n}\n"],"names":[],"mappings":";AAcO,MAAM,cAAc;AAAA,EAChB;AAAA,EACA;AAAA,EAET,YAAY,aAA0B,WAAmB;AACvD,SAAK,cAAc;AACnB,SAAK,YAAY;AAAA,EACnB;AAAA,EAEA,MAAM,OAAsB;AAC1B,UAAM,KAAK,YAAY,KAAA;AAAA,EACzB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,cAAc,YAAoB,QAAmD;AACzF,UAAM,WAAW,KAAK,YAAY,UAAU;AAC5C,UAAM,OAAiB;AAAA,MACrB,WAAW,KAAK;AAAA,MAChB,QAAQ;AAAA,MACR;AAAA,IAAA;AAGF,QAAI;AACF,YAAM,KAAK,YAAY,UAAU,MAAM,MAAM;AAAA,IAC/C,SAAS,OAAO;AACd,UAAI,iBAAiB,wBAAwB;AAC3C,YAAI,MAAM,WAAW;AACnB,gBAAM,IAAI;AAAA,YACR,4BAA4B,UAAU,KAAK,MAAM,OAAO;AAAA,UAAA;AAAA,QAE5D;AACA,cAAM,IAAI;AAAA,UACR,4BAA4B,UAAU;AAAA,QAAA;AAAA,MAE1C;AACA,YAAM;AAAA,IACR;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,UAAU,YAAoB,OAAe,KAAmC;AACpF,UAAM,WAAW,KAAK,YAAY,UAAU;AAC5C,UAAM,OAAiB;AAAA,MACrB,WAAW,KAAK;AAAA,MAChB,QAAQ;AAAA,MACR;AAAA,IAAA;AAGF,WAAO,MAAM,KAAK,YAAY,UAAU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A;AAAA,EAElD;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,mBAAmB,YAAoB,QAAoC;AAC/E,QAAI;AACF,YAAM,KAAK,YAAY,UAAU,KAAK,UAAU,UAAU,GAAG,MAAM;AAAA,IACrE,SAAS,OAAO;AACd,UAAI,iBAAiB,wBAAwB;AAC3C,cAAM,IAAI,MAAM,kCAAkC,UAAU,KAAK,MAAM,OAAO,EAAE;AAAA,MAClF;AACA,YAAM;AAAA,IACR;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,kBAAkB,YAA0C;AAChE,WAAO,MAAM,KAAK,YAAY,SAAS,KAAK,UAAU,UAAU,CAAC;AAAA,EACnE;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,iBAAiB,YAAsC;AAC3D,UAAM,OAAO,KAAK,UAAU,UAAU;AACtC,UAAM,SAAS,MAAM,KAAK,YAAY,OAAO,IAAI;AACjD,QAAI,CAAC,OAAQ,QAAO;AACpB,QAAI;AACF,YAAM,OAAO,MAAM,KAAK,YAAY,YAAY,IAAI;AACpD,aAAO,OAAO;AAAA,IAChB,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,oBAAoB,YAAmC;AAC3D,UAAM,KAAK,YAAY,WAAW,KAAK,UAAU,UAAU,CAAC;AAAA,EAC9D;AACF;"}
|
|
@@ -40,6 +40,21 @@ export declare class OPFSManager {
|
|
|
40
40
|
*/
|
|
41
41
|
getTotalSize(prefix: OPFSPrefix): Promise<number>;
|
|
42
42
|
private writeFileInternal;
|
|
43
|
+
/**
|
|
44
|
+
* Read from an OPFS file handle with retry on transient InvalidStateError.
|
|
45
|
+
*
|
|
46
|
+
* `getFile()` returns a snapshot bound to the file's size/mtime at that moment.
|
|
47
|
+
* If the file is being written concurrently (createWritable swaps the backing
|
|
48
|
+
* file), that snapshot can go stale and reading it throws a DOMException
|
|
49
|
+
* `InvalidStateError` ("state had changed since it was read from disk").
|
|
50
|
+
* This is transient — re-taking the snapshot after the write settles succeeds.
|
|
51
|
+
* Observed on Windows (stricter FS semantics); rare/absent on macOS.
|
|
52
|
+
*
|
|
53
|
+
* Only InvalidStateError is retried; every other error is rethrown immediately,
|
|
54
|
+
* so existing behavior (NotFoundError, etc.) is unchanged. A successful first
|
|
55
|
+
* read takes the exact same path as before with no added cost.
|
|
56
|
+
*/
|
|
57
|
+
private readFromHandle;
|
|
43
58
|
/**
|
|
44
59
|
* Read entire file
|
|
45
60
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"OPFSManager.d.ts","sourceRoot":"","sources":["../../../../src/cache/storage/opfs/OPFSManager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAGrE;;;;;;;;GAQG;AACH,qBAAa,WAAW;IACtB,OAAO,CAAC,QAAQ,CAA0C;IAC1D,OAAO,CAAC,WAAW,CAA8B;IACjD,YAAY,EAAE,MAAM,CAAY;IAChC,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;gBAEpB,qBAAqB,GAAE,MAAa;IAI1C,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;YAOb,WAAW;IAWzB;;OAEG;IACG,aAAa,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,yBAAyB,CAAC;IAS9F;;;OAGG;IACG,SAAS,CAAC,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,WAAW,GAAG,cAAc,CAAC,UAAU,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;IAwB9F;;OAEG;YACW,eAAe;IAU7B;;;OAGG;YACW,WAAW;IAYzB;;OAEG;IACG,YAAY,CAAC,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC;YAKzC,iBAAiB;IAgC/B;;OAEG;IACG,QAAQ,CAAC,IAAI,EAAE,QAAQ,GA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AE,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC;IAa9C;;OAEG;IACG,WAAW,CAAC,IAAI,EAAE,QAAQ,GAAG,OAAO,CAAC,MAAM,CAAC;IAOlD;;OAEG;IACG,oBAAoB,CAAC,IAAI,EAAE,QAAQ,GAAG,OAAO,CAAC,4BAA4B,CAAC;IAMjF;;OAEG;IACG,sBAAsB,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC;IAalF;;;OAGG;IACG,wBAAwB,CAAC,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,eAAe,EAAE,CAAC;IA2C9E;;;OAGG;IACG,mBAAmB,CACvB,gBAAgB,EAAE,MAAM,EACxB,MAAM,EAAE,UAAU,EAClB,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC,MAAM,CAAC;CAiCnB"}
|
|
@@ -108,14 +108,42 @@ class OPFSManager {
|
|
|
108
108
|
}
|
|
109
109
|
await writable.close();
|
|
110
110
|
}
|
|
111
|
+
/**
|
|
112
|
+
* Read from an OPFS file handle with retry on transient InvalidStateError.
|
|
113
|
+
*
|
|
114
|
+
* `getFile()` returns a snapshot bound to the file's size/mtime at that moment.
|
|
115
|
+
* If the file is being written concurrently (createWritable swaps the backing
|
|
116
|
+
* file), that snapshot can go stale and reading it throws a DOMException
|
|
117
|
+
* `InvalidStateError` ("state had changed since it was read from disk").
|
|
118
|
+
* This is transient — re-taking the snapshot after the write settles succeeds.
|
|
119
|
+
* Observed on Windows (stricter FS semantics); rare/absent on macOS.
|
|
120
|
+
*
|
|
121
|
+
* Only InvalidStateError is retried; every other error is rethrown immediately,
|
|
122
|
+
* so existing behavior (NotFoundError, etc.) is unchanged. A successful first
|
|
123
|
+
* read takes the exact same path as before with no added cost.
|
|
124
|
+
*/
|
|
125
|
+
async readFromHandle(fileHandle, read) {
|
|
126
|
+
const MAX_RETRIES = 5;
|
|
127
|
+
for (let attempt = 0; ; attempt++) {
|
|
128
|
+
try {
|
|
129
|
+
const file = await fileHandle.getFile();
|
|
130
|
+
return await read(file);
|
|
131
|
+
} catch (error) {
|
|
132
|
+
if (isDOMException(error, "InvalidStateError") && attempt < MAX_RETRIES) {
|
|
133
|
+
await new Promise((resolve) => setTimeout(resolve, 30 * (attempt + 1)));
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
throw error;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
111
140
|
/**
|
|
112
141
|
* Read entire file
|
|
113
142
|
*/
|
|
114
143
|
async readFile(path) {
|
|
115
144
|
const projectDir = await this.getProjectDir(path.projectId, path.prefix);
|
|
116
145
|
const fileHandle = await projectDir.getFileHandle(path.fileName, { create: false });
|
|
117
|
-
|
|
118
|
-
return await file.arrayBuffer();
|
|
146
|
+
return await this.readFromHandle(fileHandle, (file) => file.arrayBuffer());
|
|
119
147
|
}
|
|
120
148
|
/**
|
|
121
149
|
* Read byte range from file (for on-demand decoding)
|
|
@@ -123,9 +151,7 @@ class OPFSManager {
|
|
|
123
151
|
async readRange(path, start, end) {
|
|
124
152
|
const projectDir = await this.getProjectDir(path.projectId, path.prefix);
|
|
125
153
|
const fileHandle = await projectDir.getFileHandle(path.fileName, { create: false });
|
|
126
|
-
|
|
127
|
-
const slice = file.slice(start, end);
|
|
128
|
-
return await slice.arrayBuffer();
|
|
154
|
+
return await this.readFromHandle(fileHandle, (file) => file.slice(start, end).arrayBuffer());
|
|
129
155
|
}
|
|
130
156
|
/**
|
|
131
157
|
* Delete file
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"OPFSManager.js","sources":["../../../../src/cache/storage/opfs/OPFSManager.ts"],"sourcesContent":["import type { OPFSPrefix, OPFSPath, ProjectMetadata } from './types';\nimport { OPFSQuotaExceededError, isDOMException } from '../../../utils/errors';\n\n/**\n * OPFSManager - Unified OPFS management infrastructure\n *\n * Supports:\n * - Directory isolation by prefix (l2/resource)\n * - Range reads for on-demand decoding\n * - Streaming writes with automatic quota management\n * - Project-level LRU eviction\n */\nexport class OPFSManager {\n private opfsRoot: FileSystemDirectoryHandle | null = null;\n private initPromise: Promise<void> | null = null;\n maxSizeBytes: number = Infinity;\n readonly quotaThreshold: number;\n\n constructor(quotaThresholdPercent: number = 0.85) {\n this.quotaThreshold = quotaThresholdPercent;\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 private async initStorage(): Promise<void> {\n this.opfsRoot = await navigator.storage.getDirectory();\n\n // Dynamic quota detection\n const estimate = await navigator.storage.estimate();\n const quota = estimate.quota || 5 * 1024 * 1024 * 1024;\n\n // Aggressive strategy: use 80% of browser quota\n this.maxSizeBytes = Math.floor(quota * 0.8);\n }\n\n /**\n * Get project directory by prefix\n */\n async getProjectDir(projectId: string, prefix: OPFSPrefix): Promise<FileSystemDirectoryHandle> {\n if (!this.opfsRoot) {\n throw new Error('[OPFSManager] Not initialized');\n }\n\n const dirName = `meframe-${prefix}-${projectId}`;\n return this.opfsRoot.getDirectoryHandle(dirName, { create: true });\n }\n\n /**\n * Write file with automatic quota management\n * Proactively checks quota before write; evicts old projects if threshold exceeded\n */\n async writeFile(path: OPFSPath, data: ArrayBuffer | ReadableStream<Uint8Array>): Promise<void> {\n await this.ensureQuota(path.projectId, path.prefix);\n\n try {\n await this.writeFileInternal(path, data);\n } catch (error) {\n if (isDOMException(error, 'QuotaExceededError')) {\n const evictedCount = await this.evictOldestProjects(path.projectId, path.prefix, 1);\n\n if (evictedCount === 0) {\n throw new OPFSQuotaExceededError(path.projectId, path.prefix, false);\n }\n\n if (data instanceof ReadableStream) {\n throw new OPFSQuotaExceededError(path.projectId, path.prefix, true);\n }\n\n await this.writeFileInternal(path, data);\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Check if project is locked by any tab (actively being used)\n */\n private async isProjectLocked(projectId: string, prefix: OPFSPrefix): Promise<boolean> {\n if (!navigator.locks) {\n return false;\n }\n\n const lockName = `meframe-${prefix}-${projectId}`;\n const locks = await navigator.locks.query();\n return locks.held?.some((lock) => lock.name === lockName) ?? false;\n }\n\n /**\n * Ensure quota is within threshold before write\n * Proactively evicts old projects if usage exceeds threshold\n */\n private async ensureQuota(currentProjectId: string, prefix: OPFSPrefix): Promise<void> {\n const totalSize = await this.getTotalSize(prefix);\n const usagePercent = totalSize / this.maxSizeBytes;\n\n if (usagePercent > this.quotaThreshold) {\n const needToFreeBytes = totalSize - this.maxSizeBytes * this.quotaThreshold;\n const projectsToEvict = Math.ceil(needToFreeBytes / (totalSize / 10));\n\n await this.evictOldestProjects(currentProjectId, prefix, Math.max(1, projectsToEvict));\n }\n }\n\n /**\n * Get total size of all projects for a prefix\n */\n async getTotalSize(prefix: OPFSPrefix): Promise<number> {\n const projects = await this.listProjectsWithMetadata(prefix);\n return projects.reduce((sum, p) => sum + p.size, 0);\n }\n\n private async writeFileInternal(\n path: OPFSPath,\n data: ArrayBuffer | ReadableStream<Uint8Array>\n ): Promise<void> {\n const projectDir = await this.getProjectDir(path.projectId, path.prefix);\n const fileHandle = await projectDir.getFileHandle(path.fileName, { create: true });\n const writable = await fileHandle.createWritable();\n\n if (data instanceof ArrayBuffer) {\n await writable.write(data);\n } else {\n const reader = data.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n if (value) {\n const buffer = value.buffer.slice(\n value.byteOffset,\n value.byteOffset + value.byteLength\n );\n await writable.write(buffer as ArrayBuffer);\n }\n }\n } finally {\n reader.releaseLock();\n }\n }\n\n await writable.close();\n }\n\n /**\n * Read entire file\n */\n async readFile(path: OPFSPath): Promise<ArrayBuffer> {\n const projectDir = await this.getProjectDir(path.projectId, path.prefix);\n const fileHandle = await projectDir.getFileHandle(path.fileName, { create: false });\n const file = await fileHandle.getFile();\n return await file.arrayBuffer();\n }\n\n /**\n * Read byte range from file (for on-demand decoding)\n */\n async readRange(path: OPFSPath, start: number, end: number): Promise<ArrayBuffer> {\n const projectDir = await this.getProjectDir(path.projectId, path.prefix);\n const fileHandle = await projectDir.getFileHandle(path.fileName, { create: false });\n const file = await fileHandle.getFile();\n const slice = file.slice(start, end);\n return await slice.arrayBuffer();\n }\n\n /**\n * Delete file\n */\n async deleteFile(path: OPFSPath): Promise<void> {\n try {\n const projectDir = await this.getProjectDir(path.projectId, path.prefix);\n await projectDir.removeEntry(path.fileName);\n } catch (error) {\n if (!isDOMException(error, 'NotFoundError')) {\n console.warn(`[OPFSManager] Failed to delete file ${path.fileName}:`, error);\n }\n }\n }\n\n /**\n * Check if file exists\n */\n async exists(path: OPFSPath): Promise<boolean> {\n try {\n const projectDir = await this.getProjectDir(path.projectId, path.prefix);\n await projectDir.getFileHandle(path.fileName, { create: false });\n return true;\n } catch (error) {\n if (isDOMException(error, 'NotFoundError')) {\n return false;\n }\n throw error;\n }\n }\n\n /**\n * Get file size\n */\n async getFileSize(path: OPFSPath): Promise<number> {\n const projectDir = await this.getProjectDir(path.projectId, path.prefix);\n const fileHandle = await projectDir.getFileHandle(path.fileName, { create: false });\n const file = await fileHandle.getFile();\n return file.size;\n }\n\n /**\n * Create writable stream for streaming writes\n */\n async createWritableStream(path: OPFSPath): Promise<FileSystemWritableFileStream> {\n const projectDir = await this.getProjectDir(path.projectId, path.prefix);\n const fileHandle = await projectDir.getFileHandle(path.fileName, { create: true });\n return await fileHandle.createWritable();\n }\n\n /**\n * Delete entire project directory\n */\n async deleteProjectDirectory(projectId: string, prefix: OPFSPrefix): Promise<void> {\n if (!this.opfsRoot) return;\n\n try {\n const dirName = `meframe-${prefix}-${projectId}`;\n await this.opfsRoot.removeEntry(dirName, { recursive: true });\n } catch (error) {\n if (!isDOMException(error, 'NotFoundError')) {\n console.warn(`[OPFSManager] Failed to remove directory ${prefix}-${projectId}:`, error);\n }\n }\n }\n\n /**\n * List all projects with size and lastModified metadata\n * Used for LRU eviction\n */\n async listProjectsWithMetadata(prefix: OPFSPrefix): Promise<ProjectMetadata[]> {\n if (!this.opfsRoot) {\n throw new Error('[OPFSManager] Not initialized');\n }\n\n const projects: ProjectMetadata[] = [];\n const searchPrefix = `meframe-${prefix}-`;\n\n // @ts-expect-error - AsyncIterator type not well-supported\n for await (const [name, handle] of this.opfsRoot.entries()) {\n if (handle.kind === 'directory' && name.startsWith(searchPrefix)) {\n const projectId = name.slice(searchPrefix.length);\n const projectDir = handle as FileSystemDirectoryHandle;\n let totalSize = 0;\n let maxLastModified = 0;\n\n // @ts-expect-error - AsyncIterator type not well-supported\n for await (const [_fileName, fileHandle] of projectDir.entries()) {\n if (fileHandle.kind === 'file') {\n try {\n const file = await (fileHandle as FileSystemFileHandle).getFile();\n totalSize += file.size;\n maxLastModified = Math.max(maxLastModified, file.lastModified);\n } catch (error) {\n // Race: file may be deleted/evicted between directory iteration and getFile().\n // Under CPU throttling this becomes much more likely; ignore and continue.\n if (isDOMException(error, 'NotFoundError')) {\n continue;\n }\n throw error;\n }\n }\n }\n\n if (totalSize > 0) {\n projects.push({ projectId, size: totalSize, lastModified: maxLastModified });\n }\n }\n }\n\n return projects;\n }\n\n /**\n * Evict oldest projects (by lastModified) excluding current project and locked projects\n * Returns number of projects evicted\n */\n async evictOldestProjects(\n currentProjectId: string,\n prefix: OPFSPrefix,\n count: number\n ): Promise<number> {\n const projects = await this.listProjectsWithMetadata(prefix);\n\n // Filter candidates: exclude current project and locked projects\n const candidates = [];\n for (const project of projects) {\n if (project.projectId === currentProjectId) continue;\n\n const isLocked = await this.isProjectLocked(project.projectId, prefix);\n if (isLocked) continue;\n\n candidates.push(project);\n }\n\n if (candidates.length === 0) {\n return 0;\n }\n\n candidates.sort((a, b) => a.lastModified - b.lastModified);\n const toEvict = candidates.slice(0, count);\n\n let freedBytes = 0;\n for (const project of toEvict) {\n await this.deleteProjectDirectory(project.projectId, prefix);\n freedBytes += project.size;\n }\n\n console.log(\n `[OPFSManager] Evicted ${toEvict.length} project(s), freed ${(freedBytes / 1024 / 1024).toFixed(0)}MB`\n );\n\n return toEvict.length;\n }\n}\n"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KAAK;AAEzC,QAAI,aAAa;AACjB,eAAW,WAAW,SAAS;AAC7B,YAAM,KAAK,uBAAuB,QAAQ,WAAW,MAAM;AAC3D,oBAAc,QAAQ;AAAA,IACxB;AAEA,YAAQ;AAAA,MACN,yBAAyB,QAAQ,MAAM,uBAAuB,aAAa,OAAO,MAAM,QAAQ,CAAC,CAAC;AAAA,IAAA;AAGpG,WAAO,QAAQ;AAAA,EACjB;AACF;"}
|
|
1
|
+
{"version":3,"file":"OPFSManager.js","sources":["../../../../src/cache/storage/opfs/OPFSManager.ts"],"sourcesContent":["import type { OPFSPrefix, OPFSPath, ProjectMetadata } from './types';\nimport { OPFSQuotaExceededError, isDOMException } from '../../../utils/errors';\n\n/**\n * OPFSManager - Unified OPFS management infrastructure\n *\n * Supports:\n * - Directory isolation by prefix (l2/resource)\n * - Range reads for on-demand decoding\n * - Streaming writes with automatic quota management\n * - Project-level LRU eviction\n */\nexport class OPFSManager {\n private opfsRoot: FileSystemDirectoryHandle | null = null;\n private initPromise: Promise<void> | null = null;\n maxSizeBytes: number = Infinity;\n readonly quotaThreshold: number;\n\n constructor(quotaThresholdPercent: number = 0.85) {\n this.quotaThreshold = quotaThresholdPercent;\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 private async initStorage(): Promise<void> {\n this.opfsRoot = await navigator.storage.getDirectory();\n\n // Dynamic quota detection\n const estimate = await navigator.storage.estimate();\n const quota = estimate.quota || 5 * 1024 * 1024 * 1024;\n\n // Aggressive strategy: use 80% of browser quota\n this.maxSizeBytes = Math.floor(quota * 0.8);\n }\n\n /**\n * Get project directory by prefix\n */\n async getProjectDir(projectId: string, prefix: OPFSPrefix): Promise<FileSystemDirectoryHandle> {\n if (!this.opfsRoot) {\n throw new Error('[OPFSManager] Not initialized');\n }\n\n const dirName = `meframe-${prefix}-${projectId}`;\n return this.opfsRoot.getDirectoryHandle(dirName, { create: true });\n }\n\n /**\n * Write file with automatic quota management\n * Proactively checks quota before write; evicts old projects if threshold exceeded\n */\n async writeFile(path: OPFSPath, data: ArrayBuffer | ReadableStream<Uint8Array>): Promise<void> {\n await this.ensureQuota(path.projectId, path.prefix);\n\n try {\n await this.writeFileInternal(path, data);\n } catch (error) {\n if (isDOMException(error, 'QuotaExceededError')) {\n const evictedCount = await this.evictOldestProjects(path.projectId, path.prefix, 1);\n\n if (evictedCount === 0) {\n throw new OPFSQuotaExceededError(path.projectId, path.prefix, false);\n }\n\n if (data instanceof ReadableStream) {\n throw new OPFSQuotaExceededError(path.projectId, path.prefix, true);\n }\n\n await this.writeFileInternal(path, data);\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Check if project is locked by any tab (actively being used)\n */\n private async isProjectLocked(projectId: string, prefix: OPFSPrefix): Promise<boolean> {\n if (!navigator.locks) {\n return false;\n }\n\n const lockName = `meframe-${prefix}-${projectId}`;\n const locks = await navigator.locks.query();\n return locks.held?.some((lock) => lock.name === lockName) ?? false;\n }\n\n /**\n * Ensure quota is within threshold before write\n * Proactively evicts old projects if usage exceeds threshold\n */\n private async ensureQuota(currentProjectId: string, prefix: OPFSPrefix): Promise<void> {\n const totalSize = await this.getTotalSize(prefix);\n const usagePercent = totalSize / this.maxSizeBytes;\n\n if (usagePercent > this.quotaThreshold) {\n const needToFreeBytes = totalSize - this.maxSizeBytes * this.quotaThreshold;\n const projectsToEvict = Math.ceil(needToFreeBytes / (totalSize / 10));\n\n await this.evictOldestProjects(currentProjectId, prefix, Math.max(1, projectsToEvict));\n }\n }\n\n /**\n * Get total size of all projects for a prefix\n */\n async getTotalSize(prefix: OPFSPrefix): Promise<number> {\n const projects = await this.listProjectsWithMetadata(prefix);\n return projects.reduce((sum, p) => sum + p.size, 0);\n }\n\n private async writeFileInternal(\n path: OPFSPath,\n data: ArrayBuffer | ReadableStream<Uint8Array>\n ): Promise<void> {\n const projectDir = await this.getProjectDir(path.projectId, path.prefix);\n const fileHandle = await projectDir.getFileHandle(path.fileName, { create: true });\n const writable = await fileHandle.createWritable();\n\n if (data instanceof ArrayBuffer) {\n await writable.write(data);\n } else {\n const reader = data.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n if (value) {\n const buffer = value.buffer.slice(\n value.byteOffset,\n value.byteOffset + value.byteLength\n );\n await writable.write(buffer as ArrayBuffer);\n }\n }\n } finally {\n reader.releaseLock();\n }\n }\n\n await writable.close();\n }\n\n /**\n * Read from an OPFS file handle with retry on transient InvalidStateError.\n *\n * `getFile()` returns a snapshot bound to the file's size/mtime at that moment.\n * If the file is being written concurrently (createWritable swaps the backing\n * file), that snapshot can go stale and reading it throws a DOMException\n * `InvalidStateError` (\"state had changed since it was read from disk\").\n * This is transient — re-taking the snapshot after the write settles succeeds.\n * Observed on Windows (stricter FS semantics); rare/absent on macOS.\n *\n * Only InvalidStateError is retried; every other error is rethrown immediately,\n * so existing behavior (NotFoundError, etc.) is unchanged. A successful first\n * read takes the exact same path as before with no added cost.\n */\n private async readFromHandle(\n fileHandle: FileSystemFileHandle,\n read: (file: File) => Promise<ArrayBuffer>\n ): Promise<ArrayBuffer> {\n const MAX_RETRIES = 5;\n for (let attempt = 0; ; attempt++) {\n try {\n const file = await fileHandle.getFile();\n return await read(file);\n } catch (error) {\n if (isDOMException(error, 'InvalidStateError') && attempt < MAX_RETRIES) {\n // Small backoff to let the concurrent write settle: 30/60/90/120/150ms.\n await new Promise((resolve) => setTimeout(resolve, 30 * (attempt + 1)));\n continue;\n }\n throw error;\n }\n }\n }\n\n /**\n * Read entire file\n */\n async readFile(path: OPFSPath): Promise<ArrayBuffer> {\n const projectDir = await this.getProjectDir(path.projectId, path.prefix);\n const fileHandle = await projectDir.getFileHandle(path.fileName, { create: false });\n return await this.readFromHandle(fileHandle, (file) => file.arrayBuffer());\n }\n\n /**\n * Read byte range from file (for on-demand decoding)\n */\n async readRange(path: OPFSPath, start: number, end: number): Promise<ArrayBuffer> {\n const projectDir = await this.getProjectDir(path.projectId, path.prefix);\n const fileHandle = await projectDir.getFileHandle(path.fileName, { create: false });\n return await this.readFromHandle(fileHandle, (file) => file.slice(start, end).arrayBuffer());\n }\n\n /**\n * Delete file\n */\n async deleteFile(path: OPFSPath): Promise<void> {\n try {\n const projectDir = await this.getProjectDir(path.projectId, path.prefix);\n await projectDir.removeEntry(path.fileName);\n } catch (error) {\n if (!isDOMException(error, 'NotFoundError')) {\n console.warn(`[OPFSManager] Failed to delete file ${path.fileName}:`, error);\n }\n }\n }\n\n /**\n * Check if file exists\n */\n async exists(path: OPFSPath): Promise<boolean> {\n try {\n const projectDir = await this.getProjectDir(path.projectId, path.prefix);\n await projectDir.getFileHandle(path.fileName, { create: false });\n return true;\n } catch (error) {\n if (isDOMException(error, 'NotFoundError')) {\n return false;\n }\n throw error;\n }\n }\n\n /**\n * Get file size\n */\n async getFileSize(path: OPFSPath): Promise<number> {\n const projectDir = await this.getProjectDir(path.projectId, path.prefix);\n const fileHandle = await projectDir.getFileHandle(path.fileName, { create: false });\n const file = await fileHandle.getFile();\n return file.size;\n }\n\n /**\n * Create writable stream for streaming writes\n */\n async createWritableStream(path: OPFSPath): Promise<FileSystemWritableFileStream> {\n const projectDir = await this.getProjectDir(path.projectId, path.prefix);\n const fileHandle = await projectDir.getFileHandle(path.fileName, { create: true });\n return await fileHandle.createWritable();\n }\n\n /**\n * Delete entire project directory\n */\n async deleteProjectDirectory(projectId: string, prefix: OPFSPrefix): Promise<void> {\n if (!this.opfsRoot) return;\n\n try {\n const dirName = `meframe-${prefix}-${projectId}`;\n await this.opfsRoot.removeEntry(dirName, { recursive: true });\n } catch (error) {\n if (!isDOMException(error, 'NotFoundError')) {\n console.warn(`[OPFSManager] Failed to remove directory ${prefix}-${projectId}:`, error);\n }\n }\n }\n\n /**\n * List all projects with size and lastModified metadata\n * Used for LRU eviction\n */\n async listProjectsWithMetadata(prefix: OPFSPrefix): Promise<ProjectMetadata[]> {\n if (!this.opfsRoot) {\n throw new Error('[OPFSManager] Not initialized');\n }\n\n const projects: ProjectMetadata[] = [];\n const searchPrefix = `meframe-${prefix}-`;\n\n // @ts-expect-error - AsyncIterator type not well-supported\n for await (const [name, handle] of this.opfsRoot.entries()) {\n if (handle.kind === 'directory' && name.startsWith(searchPrefix)) {\n const projectId = name.slice(searchPrefix.length);\n const projectDir = handle as FileSystemDirectoryHandle;\n let totalSize = 0;\n let maxLastModified = 0;\n\n // @ts-expect-error - AsyncIterator type not well-supported\n for await (const [_fileName, fileHandle] of projectDir.entries()) {\n if (fileHandle.kind === 'file') {\n try {\n const file = await (fileHandle as FileSystemFileHandle).getFile();\n totalSize += file.size;\n maxLastModified = Math.max(maxLastModified, file.lastModified);\n } catch (error) {\n // Race: file may be deleted/evicted between directory iteration and getFile().\n // Under CPU throttling this becomes much more likely; ignore and continue.\n if (isDOMException(error, 'NotFoundError')) {\n continue;\n }\n throw error;\n }\n }\n }\n\n if (totalSize > 0) {\n projects.push({ projectId, size: totalSize, lastModified: maxLastModified });\n }\n }\n }\n\n return projects;\n }\n\n /**\n * Evict oldest projects (by lastModified) excluding current project and locked projects\n * Returns number of projects evicted\n */\n async evictOldestProjects(\n currentProjectId: string,\n prefix: OPFSPrefix,\n count: number\n ): Promise<number> {\n const projects = await this.listProjectsWithMetadata(prefix);\n\n // Filter candidates: exclude current project and locked projects\n const candidates = [];\n for (const project of projects) {\n if (project.projectId === currentProjectId) continue;\n\n const isLocked = await this.isProjectLocked(project.projectId, prefix);\n if (isLocked) continue;\n\n candidates.push(project);\n }\n\n if (candidates.length === 0) {\n return 0;\n }\n\n candidates.sort((a, b) => a.lastModified - b.lastModified);\n const toEvict = candidates.slice(0, count);\n\n let freedBytes = 0;\n for (const project of toEvict) {\n await this.deleteProjectDirectory(project.projectId, prefix);\n freedBytes += project.size;\n }\n\n console.log(\n `[OPFSManager] Evicted ${toEvict.length} project(s), freed ${(freedBytes / 1024 / 1024).toFixed(0)}MB`\n );\n\n return toEvict.length;\n }\n}\n"],"names":[],"mappings":";AAYO,MAAM,Y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AmB;IAsBjC;;OAEG;YACW,mBAAmB;YA6CnB,wBAAwB;IAiFtC,OAAO,CAAC,6BAA6B;IAiCrC;;OAEG;IACH,OAAO,CAAC,oBAAoB;IAO5B,OAAO,CAAC,2BAA2B;IA8CnC;;;;;;OAMG;YACW,YAAY;YA0DZ,YAAY;IAsB1B;;OAEG;IACH,OAAO,CAAC,UAAU;YAsBJ,kBAAkB;IA8BhC;;;OAGG;IACG,mBAAmB,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,CAAC,UAAU,CAAC,CAAC;YA4HhF,6BAA6B;IAoBrC,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;CAU/B"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { isVideoClip, videoClipPlaybackRate } from "../model/types.js";
|
|
2
2
|
import { binarySearchRange, binarySearchOverlapping } from "../utils/binary-search.js";
|
|
3
3
|
import { decodeChunksWithoutFlush, decodeChunksForScrub } from "../stages/decode/video-decoder.js";
|
|
4
|
-
import { ResourceCorruptedError } from "../utils/errors.js";
|
|
4
|
+
import { ResourceCorruptedError, isDOMException } from "../utils/errors.js";
|
|
5
5
|
class VideoWindowDecodeSession {
|
|
6
6
|
/**
|
|
7
7
|
* Static method to decode and cache first frame from extracted GOP chunks
|
|
@@ -517,7 +517,8 @@ class VideoWindowDecodeSession {
|
|
|
517
517
|
try {
|
|
518
518
|
return await this.cacheManager.readResourceRange(this.resourceId, start, end);
|
|
519
519
|
} catch (error) {
|
|
520
|
-
|
|
520
|
+
const recoverable = error instanceof ResourceCorruptedError || isDOMException(error, "InvalidStateError");
|
|
521
|
+
if (!recoverable) throw error;
|
|
521
522
|
await this.cacheManager.resourceCache.deleteResource(this.resourceId);
|
|
522
523
|
this.cacheManager.mp4IndexCache.delete(this.resourceId);
|
|
523
524
|
await this.resourceLoader.load(this.resourceId, { isPreload: false, clipId: this.clipId });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"VideoWindowDecodeSession.js","sources":["../../src/orchestrator/VideoWindowDecodeSession.ts"],"sourcesContent":["import type { CacheManager } from '../cache/CacheManager';\nimport type { MP4IndexCache } from '../cache/resource/MP4IndexCache';\nimport type { MP4Index, GOP, Sample } from '../stages/demux/types';\nimport { type TimeUs, type Resource, isVideoClip, videoClipPlaybackRate } from '../model/types';\nimport type { CompositionModel, Clip } from '../model';\nimport { binarySearchOverlapping, binarySearchRange } from '../utils/binary-search';\nimport type { ResourceLoader } from '../stages/load/ResourceLoader';\nimport { decodeChunksForScrub, decodeChunksWithoutFlush } from '../stages/decode/video-decoder';\nimport { ResourceCorruptedError } from '../utils/errors';\n\ninterface GOPWindowResult {\n gops: GOP[];\n byteStart: number;\n byteEnd: number;\n}\n\ninterface VideoWindowDecodeSessionConfig {\n clipId: string;\n resourceId: string;\n resourceUri: string;\n targetTimeUs: TimeUs;\n globalTimeUs: TimeUs;\n mp4IndexCache: MP4IndexCache;\n cacheManager: CacheManager;\n compositionModel: CompositionModel;\n resourceLoader: ResourceLoader;\n fps: number;\n}\n\n/**\n * Strategy:\n * 1. Read GOP range from OPFS\n * 2. Demux using MP4Box (main thread)\n * 3. Decode using VideoDecoder (main thread)\n * 4. Write RAW VideoFrames (YUV) to L1 cache\n * 5. Dispose immediately after window completes\n *\n * Why main thread?\n * - Window is small (±2s, ~60-120 frames)\n * - Worker overhead (10-50ms) is significant for small workloads\n * - Decode is fast enough\n */\nexport class VideoWindowDecodeSession {\n /**\n * Static method to decode and cache first frame from extracted GOP chunks\n * Used by ResourceLoader during streaming download for fast cover rendering\n */\n static async decodeAndCacheFirstFrame(\n _resourceId: string,\n chunks: EncodedVideoChunk[],\n index: MP4Index,\n clip: Clip,\n cacheManager: CacheManager,\n fps: number\n ): Promise<void> {\n if (chunks.length === 0) return;\n\n const videoTrack = index.tracks.video;\n if (!videoTrack) return;\n\n // Verify first chunk is keyframe\n const firstChunk = chunks[0];\n if (!firstChunk || firstChunk.type !== 'key') {\n return;\n }\n\n try {\n const result = await decodeChunksWithoutFlush(chunks, {\n codec: videoTrack.codec,\n width: videoTrack.width,\n height: videoTrack.height,\n description: videoTrack.description,\n });\n\n // Cache all decoded frames\n const frameDuration = Math.round(1_000_000 / fps);\n for (const frame of result.frames) {\n const frameGlobalTime = clip.startUs + frame.timestamp;\n cacheManager.addFrame(\n frame,\n clip.id,\n frameDuration,\n clip.trackId ?? 'main',\n frameGlobalTime\n );\n }\n } catch {\n // Don't throw - this is a best-effort optimization\n }\n }\n private readonly clipId: string;\n private readonly resourceId: string;\n private readonly resourceUri: string;\n private readonly mp4IndexCache: MP4IndexCache;\n private readonly cacheManager: CacheManager;\n private readonly compositionModel: CompositionModel;\n private readonly resourceLoader: ResourceLoader;\n private readonly fps: number;\n private readonly globalTimeUs: TimeUs;\n private readonly targetTimeUs: TimeUs;\n\n isDisposed = false;\n private aborted = false;\n private decodedFrames: VideoFrame[] = [];\n private loggedDecodedStreamDimensions = false;\n\n private constructor(config: VideoWindowDecodeSessionConfig) {\n this.clipId = config.clipId;\n this.resourceId = config.resourceId;\n this.resourceUri = config.resourceUri;\n this.mp4IndexCache = config.mp4IndexCache;\n this.cacheManager = config.cacheManager;\n this.resourceLoader = config.resourceLoader;\n this.compositionModel = config.compositionModel;\n this.fps = config.fps;\n this.globalTimeUs = config.globalTimeUs;\n this.targetTimeUs = config.targetTimeUs;\n }\n\n static async create(config: VideoWindowDecodeSessionConfig): Promise<VideoWindowDecodeSession> {\n const session = new VideoWindowDecodeSession(config);\n await session.init();\n return session;\n }\n\n private async init(): Promise<void> {\n // No special initialization needed for now\n }\n\n /**\n * Decode a window range, write raw frames to L1 cache\n */\n async decodeWindow(startUs: TimeUs, endUs: TimeUs): Promise<void> {\n if (this.isDisposed) {\n throw new Error('Session already disposed');\n }\n\n const resource = this.compositionModel.getResource(this.resourceId);\n if (!resource) {\n console.warn('[VideoWindowDecodeSession] Resource not found in composition model:', {\n resourceId: this.resourceId,\n clipId: this.clipId,\n startUs,\n endUs,\n model: {\n fps: this.compositionModel.fps,\n durationUs: this.compositionModel.durationUs,\n mainTrackId: this.compositionModel.mainTrackId,\n trackCount: this.compositionModel.tracks.length,\n resourcesSize: this.compositionModel.resources.size,\n },\n });\n throw new Error(`Resource not found: ${this.resourceId}`);\n }\n\n if (resource.type === 'image') {\n await this.handleImageResource(resource, startUs, endUs);\n return;\n }\n\n await this.handleVideoResource(startUs, endUs);\n }\n\n /**\n * Scrub decode (timeline dragging):\n * Decode only the minimum frames needed to present a true frame near targetTimeUs.\n * This avoids the heavy 3s window decode used for playback preheating.\n */\n async decodeScrub(targetTimeUs: TimeUs): Promise<void> {\n if (this.isDisposed) {\n throw new Error('Session already disposed');\n }\n\n const resource = this.compositionModel.getResource(this.resourceId);\n if (!resource) {\n throw new Error(`Resource not found: ${this.resourceId}`);\n }\n\n if (resource.type === 'image') {\n const frameDuration = Math.max(1, Math.round(1_000_000 / this.fps));\n await this.handleImageResource(resource, targetTimeUs, targetTimeUs + frameDuration);\n return;\n }\n\n await this.handleVideoResourceScrub(targetTimeUs);\n }\n\n /**\n * Handle image resource by creating a VideoFrame from ImageBitmap\n */\n private async handleImageResource(\n resource: Resource,\n startUs: TimeUs,\n endUs: TimeUs\n ): Promise<void> {\n const image = await this.resourceLoader.loadImage(resource);\n if (!image) return;\n\n const frame = new VideoFrame(image, {\n timestamp: startUs,\n duration: endUs - startUs,\n });\n\n this.cacheManager.addFrame(\n frame,\n this.clipId,\n endUs - startUs,\n this.compositionModel.mainTrackId,\n this.globalTimeUs\n );\n }\n\n /**\n * Handle video resource by decoding from OPFS\n */\n private async handleVideoResource(startUs: TimeUs, endUs: TimeUs): Promise<void> {\n const index = this.mp4IndexCache.get(this.resourceId);\n if (!index) {\n throw new Error(`No index found for resource ${this.resourceId}`);\n }\n\n // Calculate GOP ranges needed\n const gopWindow = this.calculateGOPRangesForWindow(index, startUs, endUs);\n if (gopWindow.gops.length === 0) {\n console.warn('[VideoWindowDecodeSession] no GOPs found for window');\n return;\n }\n\n // Read GOP data from OPFS\n const gopData = await this.readResourceRangeWithRecovery(\n gopWindow.byteStart,\n gopWindow.byteEnd\n );\n\n if (this.aborted) {\n console.warn('[VideoWindowDecodeSession] aborted during readResourceRangeWithRecovery');\n return;\n }\n\n // Extract chunks from GOP data\n const chunks = await this.demuxGOPData(gopData, index, gopWindow);\n if (this.aborted) {\n console.warn('[VideoWindowDecodeSession] aborted during demuxGOPData');\n return;\n }\n\n // Decode chunks to frames\n await this.decodeChunks(chunks, index);\n\n // Check abort and cleanup if needed\n if (this.aborted) {\n console.warn('[VideoWindowDecodeSession] aborted during decodeWindow');\n this.releaseDecodedFrames();\n return;\n }\n\n // Write frames to L1 cache\n await this.cacheDecodedFrames(startUs, endUs);\n }\n\n private async handleVideoResourceScrub(targetTimeUs: TimeUs): Promise<void> {\n const index = this.mp4IndexCache.get(this.resourceId);\n if (!index?.tracks.video) {\n throw new Error(`No video index found for resource ${this.resourceId}`);\n }\n\n const videoTrack = index.tracks.video;\n const { gopIndex, samples } = videoTrack;\n\n const gop = binarySearchRange(gopIndex, targetTimeUs, (g, idx) => {\n const next = gopIndex[idx + 1];\n return { start: g.startTimeUs, end: next ? next.startTimeUs : Infinity };\n });\n if (!gop) {\n // Fallback: use a tiny window decode.\n const frameDuration = Math.max(1, Math.round(1_000_000 / this.fps));\n await this.handleVideoResource(targetTimeUs, targetTimeUs + frameDuration);\n return;\n }\n\n const startIdx = gop.keyframeSampleIndex;\n const endIdx = Math.min(samples.length, startIdx + gop.sampleCount);\n if (startIdx >= endIdx) return;\n\n // Compute byte range for the GOP (sample offsets are not guaranteed monotonic).\n let byteStart = Infinity;\n let byteEnd = 0;\n for (let i = startIdx; i < endIdx; i++) {\n const s = samples[i];\n if (!s) continue;\n byteStart = Math.min(byteStart, s.byteOffset);\n byteEnd = Math.max(byteEnd, s.byteOffset + s.byteLength);\n }\n if (!Number.isFinite(byteStart) || byteEnd <= byteStart) return;\n\n const gopData = await this.readResourceRangeWithRecovery(byteStart, byteEnd);\n if (this.aborted) return;\n\n const chunks = this.buildEncodedChunksFromSamples(\n gopData,\n byteStart,\n samples,\n startIdx,\n endIdx\n );\n if (chunks.length === 0) return;\n\n const timeoutMs = this.cacheManager.isExporting ? 15_000 : 2_000;\n const { before, after } = await decodeChunksForScrub(\n chunks,\n {\n codec: videoTrack.codec,\n width: videoTrack.width,\n height: videoTrack.height,\n description: videoTrack.description,\n },\n targetTimeUs,\n {\n timeoutMs,\n maxQueueSize: 2,\n shouldAbort: () => this.aborted,\n }\n );\n\n if (this.aborted) {\n before?.close();\n after?.close();\n return;\n }\n\n // Cache only the closest frames around target.\n for (const frame of [before, after]) {\n if (!frame) continue;\n try {\n this.cacheFrame(frame);\n } catch {\n frame.close();\n }\n }\n }\n\n private buildEncodedChunksFromSamples(\n data: ArrayBuffer,\n baseByteOffset: number,\n samples: Sample[],\n startIdx: number,\n endIdx: number\n ): EncodedVideoChunk[] {\n const chunks: EncodedVideoChunk[] = [];\n const dataView = new Uint8Array(data);\n\n for (let i = startIdx; i < endIdx; i++) {\n const sample = samples[i];\n if (!sample) continue;\n\n const relativeOffset = sample.byteOffset - baseByteOffset;\n if (relativeOffset < 0 || relativeOffset + sample.byteLength > data.byteLength) {\n continue;\n }\n\n const sampleData = dataView.slice(relativeOffset, relativeOffset + sample.byteLength);\n chunks.push(\n new EncodedVideoChunk({\n type: sample.isKeyframe ? 'key' : 'delta',\n timestamp: sample.timestamp,\n duration: sample.duration,\n data: sampleData,\n })\n );\n }\n\n return chunks;\n }\n\n /**\n * Release all decoded frames without caching\n */\n private releaseDecodedFrames(): void {\n for (const frame of this.decodedFrames) {\n frame.close();\n }\n this.decodedFrames = [];\n }\n\n private calculateGOPRangesForWindow(\n index: MP4Index,\n startUs: TimeUs,\n endUs: TimeUs\n ): GOPWindowResult {\n if (!index.tracks.video) {\n return { gops: [], byteStart: 0, byteEnd: 0 };\n }\n\n const { gopIndex, samples } = index.tracks.video;\n\n // Find GOP containing startUs (or the nearest keyframe before it)\n const nearestKeyframe = this.mp4IndexCache.getNearestKeyframe(this.resourceId, startUs);\n const decodeStartUs = nearestKeyframe?.timestamp ?? startUs;\n\n // Use binary search to find all overlapping GOPs\n const overlappingGOPs = binarySearchOverlapping(gopIndex, decodeStartUs, endUs, (gop, idx) => {\n const nextGOP = gopIndex[idx + 1];\n return {\n start: gop.startTimeUs,\n end: nextGOP ? nextGOP.startTimeUs : Infinity,\n };\n });\n\n if (overlappingGOPs.length === 0) {\n return { gops: [], byteStart: 0, byteEnd: 0 };\n }\n\n // Calculate merged byte range for OPFS read\n let byteStart = Infinity;\n let byteEnd = 0;\n\n for (const gop of overlappingGOPs) {\n const startSample = samples[gop.keyframeSampleIndex];\n const endSampleIndex = gop.keyframeSampleIndex + gop.sampleCount - 1;\n const endSample = samples[endSampleIndex];\n\n if (startSample && endSample) {\n byteStart = Math.min(byteStart, startSample.byteOffset);\n byteEnd = Math.max(byteEnd, endSample.byteOffset + endSample.byteLength);\n }\n }\n\n return { gops: overlappingGOPs, byteStart, byteEnd };\n }\n\n /**\n * Extract video chunks from GOP data\n *\n * Directly use GOP sample indices to slice the samples array.\n * This is O(k) where k is the number of samples in the window,\n * vs O(n×m) for the old approach (n=all samples, m=GOP count).\n */\n private async demuxGOPData(\n data: ArrayBuffer,\n index: MP4Index,\n gopWindow: GOPWindowResult\n ): Promise<EncodedVideoChunk[]> {\n const videoTrack = index.tracks.video;\n if (!videoTrack) {\n throw new Error('No video track in index');\n }\n\n const { samples } = videoTrack;\n const chunks: EncodedVideoChunk[] = [];\n const dataView = new Uint8Array(data);\n const baseByteOffset = gopWindow.byteStart;\n\n // Direct sample index slicing - iterate only samples in the window\n for (const gop of gopWindow.gops) {\n const startIdx = gop.keyframeSampleIndex;\n const endIdx = startIdx + gop.sampleCount;\n\n // Extract samples for this GOP (direct array slice)\n for (let i = startIdx; i < endIdx; i++) {\n const sample = samples[i];\n if (!sample) continue;\n\n // Calculate relative offset within the data buffer\n const relativeOffset = sample.byteOffset - baseByteOffset;\n\n // Validate offset is within buffer\n if (relativeOffset < 0 || relativeOffset + sample.byteLength > data.byteLength) {\n console.warn('[VideoWindowDecodeSession] Sample outside buffer:', {\n sampleOffset: sample.byteOffset,\n sampleLength: sample.byteLength,\n baseOffset: baseByteOffset,\n relativeOffset,\n bufferLength: data.byteLength,\n });\n continue;\n }\n\n // Extract sample data\n const sampleData = dataView.slice(relativeOffset, relativeOffset + sample.byteLength);\n\n // Create EncodedVideoChunk\n const chunk = new EncodedVideoChunk({\n type: sample.isKeyframe ? 'key' : 'delta',\n timestamp: sample.timestamp,\n duration: sample.duration,\n data: sampleData,\n });\n\n chunks.push(chunk);\n }\n }\n\n return chunks;\n }\n\n private async decodeChunks(chunks: EncodedVideoChunk[], index: MP4Index): Promise<void> {\n const videoTrack = index.tracks.video;\n if (!videoTrack) {\n throw new Error('No video track in index');\n }\n\n const timeoutMs = this.cacheManager.isExporting ? 15_000 : undefined;\n const result = await decodeChunksWithoutFlush(\n chunks,\n {\n codec: videoTrack.codec,\n width: videoTrack.width,\n height: videoTrack.height,\n description: videoTrack.description,\n },\n timeoutMs ? { timeoutMs } : undefined\n );\n\n // Store frames for caching\n this.decodedFrames = result.frames;\n }\n\n /**\n * Cache a single frame to L1 with proper timestamp calculations\n */\n private cacheFrame(frame: VideoFrame, globalTimeOffset: TimeUs = 0): void {\n const frameDuration = frame.duration ?? Math.round(1_000_000 / this.fps);\n const clip = this.compositionModel.findClip(this.clipId);\n let frameGlobalTime: TimeUs;\n if (clip && isVideoClip(clip)) {\n const trimStartUs = clip.trimStartUs ?? 0;\n const rate = videoClipPlaybackRate(clip);\n frameGlobalTime = clip.startUs + (frame.timestamp - trimStartUs) / rate + globalTimeOffset;\n } else {\n frameGlobalTime =\n this.globalTimeUs + (frame.timestamp - this.targetTimeUs) + globalTimeOffset;\n }\n\n this.cacheManager.addFrame(\n frame,\n this.clipId,\n frameDuration,\n this.compositionModel.mainTrackId,\n frameGlobalTime\n );\n }\n\n private async cacheDecodedFrames(startUs: TimeUs, endUs: TimeUs): Promise<void> {\n const framesToCache: VideoFrame[] = [];\n const framesToDiscard: VideoFrame[] = [];\n\n // Partition frames into cacheable and discardable\n for (const frame of this.decodedFrames) {\n if (frame.timestamp >= startUs && frame.timestamp < endUs) {\n framesToCache.push(frame);\n } else {\n framesToDiscard.push(frame);\n }\n }\n\n // Cache frames within window\n for (const frame of framesToCache) {\n try {\n this.cacheFrame(frame);\n } catch {\n frame.close();\n }\n }\n\n // Release frames outside window\n for (const frame of framesToDiscard) {\n frame.close();\n }\n\n this.decodedFrames = [];\n }\n\n /**\n * Decode entire time range to VideoFrame stream (for export)\n * Does NOT cache to L1 - outputs frames directly for Worker pipeline\n */\n async decodeRangeToStream(startUs: TimeUs, endUs: TimeUs): Promise<ReadableStream<VideoFrame>> {\n const index = this.mp4IndexCache.get(this.resourceId);\n if (!index?.tracks.video) {\n throw new Error(`[VideoWindowDecodeSession] No video track index for ${this.resourceId}`);\n }\n\n const videoTrack = index.tracks.video;\n const gopWindow = this.calculateGOPRangesForWindow(index, startUs, endUs);\n\n return new ReadableStream<VideoFrame>({\n start: async (controller) => {\n try {\n if (gopWindow.gops.length === 0) {\n console.warn('[VideoWindowDecodeSession] No GOPs found for range');\n controller.close();\n return;\n }\n\n // Process GOPs in batches (10 GOPs at a time for memory control)\n const batchSize = 10;\n for (let i = 0; i < gopWindow.gops.length; i += batchSize) {\n if (this.aborted) {\n controller.close();\n return;\n }\n\n const batchGOPs = gopWindow.gops.slice(\n i,\n Math.min(i + batchSize, gopWindow.gops.length)\n );\n\n // Calculate byte range for this batch\n let batchByteStart = Infinity;\n let batchByteEnd = 0;\n for (const gop of batchGOPs) {\n const startSample = videoTrack.samples[gop.keyframeSampleIndex];\n const endSampleIdx = gop.keyframeSampleIndex + gop.sampleCount - 1;\n const endSample = videoTrack.samples[endSampleIdx];\n if (startSample && endSample) {\n batchByteStart = Math.min(batchByteStart, startSample.byteOffset);\n batchByteEnd = Math.max(batchByteEnd, endSample.byteOffset + endSample.byteLength);\n }\n }\n\n // Read GOP batch data from OPFS\n const gopData = await this.readResourceRangeWithRecovery(batchByteStart, batchByteEnd);\n\n if (this.aborted) {\n controller.close();\n return;\n }\n\n // Extract chunks from GOP batch\n const batchChunks = await this.demuxGOPData(gopData, index, {\n gops: batchGOPs,\n byteStart: batchByteStart,\n byteEnd: batchByteEnd,\n });\n\n // Decode chunks to frames\n await this.decodeChunks(batchChunks, index);\n\n if (this.aborted) {\n this.releaseDecodedFrames();\n controller.close();\n return;\n }\n\n // Enqueue only frames within the requested range.\n // Leading GOP frames before startUs are reference-only; discard them\n // to prevent duplicate frames across sequential windows.\n for (const frame of this.decodedFrames) {\n if (frame.timestamp >= startUs && frame.timestamp < endUs) {\n if (!this.loggedDecodedStreamDimensions) {\n console.info(\n 'decodeRangeToStream:',\n 'Id:',\n this.resourceId,\n 'videoTrack:',\n videoTrack.width,\n 'x',\n videoTrack.height,\n 'displaySize:',\n frame.displayWidth,\n 'x',\n frame.displayHeight,\n 'codedSize:',\n frame.codedWidth,\n 'x',\n frame.codedHeight,\n 'startUs:',\n startUs,\n 'endUs:',\n endUs,\n 'duration:',\n frame.duration,\n 'Uri:',\n this.resourceUri\n );\n this.loggedDecodedStreamDimensions = true;\n }\n\n controller.enqueue(frame);\n } else {\n frame.close();\n }\n }\n this.decodedFrames = [];\n }\n\n controller.close();\n } catch (error) {\n console.error('[VideoWindowDecodeSession] decodeRangeToStream error:', error);\n this.releaseDecodedFrames();\n controller.error(error);\n }\n },\n cancel: () => {\n this.aborted = true;\n this.releaseDecodedFrames();\n },\n });\n }\n\n private async readResourceRangeWithRecovery(start: number, end: number): Promise<ArrayBuffer> {\n try {\n return await this.cacheManager.readResourceRange(this.resourceId, start, end);\n } catch (error) {\n if (!(error instanceof ResourceCorruptedError)) throw error;\n\n // Unify recovery behavior:\n // 1) Invalidate OPFS + index (ensure cache consistency)\n // 2) Reload to OPFS + rebuild index\n // 3) Retry the read once\n await this.cacheManager.resourceCache.deleteResource(this.resourceId);\n this.cacheManager.mp4IndexCache.delete(this.resourceId);\n\n await this.resourceLoader.load(this.resourceId, { isPreload: false, clipId: this.clipId });\n return await this.cacheManager.readResourceRange(this.resourceId, start, end);\n }\n }\n\n async dispose(): Promise<void> {\n if (this.isDisposed) return;\n\n this.aborted = true;\n\n // Release all decoded frames\n this.releaseDecodedFrames();\n\n this.isDisposed = true;\n }\n}\n"],"names":[],"mappings":";;;;AA0CO,MAAM,yBAAyB;AAAA;AAAA;AAAA;AAAA;AAAA,EAKpC,aAAa,yBACX,aACA,QACA,OACA,MACA,cACA,KACe;AACf,QAAI,OAAO,WAAW,EAAG;AAEzB,UAAM,aAAa,MAAM,OAAO;AAChC,QAAI,CAAC,WAAY;AAGjB,UAAM,aAAa,OAAO,CAAC;AAC3B,QAAI,CAAC,cAAc,WAAW,SAAS,OAAO;AAC5C;AAAA,IACF;AAEA,QAAI;AACF,YAAM,SAAS,MAAM,yBAAyB,QAAQ;AAAA,QACpD,OAAO,WAAW;AAAA,QAClB,OAAO,WAAW;AAAA,QAClB,QAAQ,WAAW;AAAA,QACnB,aAAa,WAAW;AAAA,MAAA,CACzB;AAGD,YAAM,gBAAgB,KAAK,MAAM,MAAY,GAAG;AAChD,iBAAW,SAAS,OAAO,QAAQ;AACjC,cAAM,kBAAkB,KAAK,UAAU,MAAM;AAC7C,qBAAa;AAAA,UACX;AAAA,UACA,KAAK;AAAA,UACL;AAAA,UACA,KAAK,WAAW;AAAA,UAChB;AAAA,QAAA;AAAA,MAEJ;AAAA,IACF,QAAQ;AAAA,IAER;AAAA,EACF;AAAA,EACiB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEjB,aAAa;AAAA,EACL,UAAU;AAAA,EACV,gBAA8B,CAAA;AAAA,EAC9B,gCAAgC;AAAA,EAEhC,YAAY,QAAwC;AAC1D,SAAK,SA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AAG;AAAA,IAC9E,SAAS,OAAO;AACd,UAAI,EAAE,iBAAiB,wBAAyB,OAAM;AAMtD,YAAM,KAAK,aAAa,cAAc,eAAe,KAAK,UAAU;AACpE,WAAK,aAAa,cAAc,OAAO,KAAK,UAAU;AAEtD,YAAM,KAAK,eAAe,KAAK,KAAK,YAAY,EAAE,WAAW,OAAO,QAAQ,KAAK,OAAA,CAAQ;AACzF,aAAO,MAAM,KAAK,aAAa,kBAAkB,KAAK,YAAY,OAAO,GAAG;AAAA,IAC9E;AAAA,EACF;AAAA,EAEA,MAAM,UAAyB;AAC7B,QAAI,KAAK,WAAY;AAErB,SAAK,UAAU;AAGf,SAAK,qBAAA;AAEL,SAAK,aAAa;AAAA,EACpB;AACF;"}
|
|
1
|
+
{"version":3,"file":"VideoWindowDecodeSession.js","sources":["../../src/orchestrator/VideoWindowDecodeSession.ts"],"sourcesContent":["import type { CacheManager } from '../cache/CacheManager';\nimport type { MP4IndexCache } from '../cache/resource/MP4IndexCache';\nimport type { MP4Index, GOP, Sample } from '../stages/demux/types';\nimport { type TimeUs, type Resource, isVideoClip, videoClipPlaybackRate } from '../model/types';\nimport type { CompositionModel, Clip } from '../model';\nimport { binarySearchOverlapping, binarySearchRange } from '../utils/binary-search';\nimport type { ResourceLoader } from '../stages/load/ResourceLoader';\nimport { decodeChunksForScrub, decodeChunksWithoutFlush } from '../stages/decode/video-decoder';\nimport { ResourceCorruptedError, isDOMException } from '../utils/errors';\n\ninterface GOPWindowResult {\n gops: GOP[];\n byteStart: number;\n byteEnd: number;\n}\n\ninterface VideoWindowDecodeSessionConfig {\n clipId: string;\n resourceId: string;\n resourceUri: string;\n targetTimeUs: TimeUs;\n globalTimeUs: TimeUs;\n mp4IndexCache: MP4IndexCache;\n cacheManager: CacheManager;\n compositionModel: CompositionModel;\n resourceLoader: ResourceLoader;\n fps: number;\n}\n\n/**\n * Strategy:\n * 1. Read GOP range from OPFS\n * 2. Demux using MP4Box (main thread)\n * 3. Decode using VideoDecoder (main thread)\n * 4. Write RAW VideoFrames (YUV) to L1 cache\n * 5. Dispose immediately after window completes\n *\n * Why main thread?\n * - Window is small (±2s, ~60-120 frames)\n * - Worker overhead (10-50ms) is significant for small workloads\n * - Decode is fast enough\n */\nexport class VideoWindowDecodeSession {\n /**\n * Static method to decode and cache first frame from extracted GOP chunks\n * Used by ResourceLoader during streaming download for fast cover rendering\n */\n static async decodeAndCacheFirstFrame(\n _resourceId: string,\n chunks: EncodedVideoChunk[],\n index: MP4Index,\n clip: Clip,\n cacheManager: CacheManager,\n fps: number\n ): Promise<void> {\n if (chunks.length === 0) return;\n\n const videoTrack = index.tracks.video;\n if (!videoTrack) return;\n\n // Verify first chunk is keyframe\n const firstChunk = chunks[0];\n if (!firstChunk || firstChunk.type !== 'key') {\n return;\n }\n\n try {\n const result = await decodeChunksWithoutFlush(chunks, {\n codec: videoTrack.codec,\n width: videoTrack.width,\n height: videoTrack.height,\n description: videoTrack.description,\n });\n\n // Cache all decoded frames\n const frameDuration = Math.round(1_000_000 / fps);\n for (const frame of result.frames) {\n const frameGlobalTime = clip.startUs + frame.timestamp;\n cacheManager.addFrame(\n frame,\n clip.id,\n frameDuration,\n clip.trackId ?? 'main',\n frameGlobalTime\n );\n }\n } catch {\n // Don't throw - this is a best-effort optimization\n }\n }\n private readonly clipId: string;\n private readonly resourceId: string;\n private readonly resourceUri: string;\n private readonly mp4IndexCache: MP4IndexCache;\n private readonly cacheManager: CacheManager;\n private readonly compositionModel: CompositionModel;\n private readonly resourceLoader: ResourceLoader;\n private readonly fps: number;\n private readonly globalTimeUs: TimeUs;\n private readonly targetTimeUs: TimeUs;\n\n isDisposed = false;\n private aborted = false;\n private decodedFrames: VideoFrame[] = [];\n private loggedDecodedStreamDimensions = false;\n\n private constructor(config: VideoWindowDecodeSessionConfig) {\n this.clipId = config.clipId;\n this.resourceId = config.resourceId;\n this.resourceUri = config.resourceUri;\n this.mp4IndexCache = config.mp4IndexCache;\n this.cacheManager = config.cacheManager;\n this.resourceLoader = config.resourceLoader;\n this.compositionModel = config.compositionModel;\n this.fps = config.fps;\n this.globalTimeUs = config.globalTimeUs;\n this.targetTimeUs = config.targetTimeUs;\n }\n\n static async create(config: VideoWindowDecodeSessionConfig): Promise<VideoWindowDecodeSession> {\n const session = new VideoWindowDecodeSession(config);\n await session.init();\n return session;\n }\n\n private async init(): Promise<void> {\n // No special initialization needed for now\n }\n\n /**\n * Decode a window range, write raw frames to L1 cache\n */\n async decodeWindow(startUs: TimeUs, endUs: TimeUs): Promise<void> {\n if (this.isDisposed) {\n throw new Error('Session already disposed');\n }\n\n const resource = this.compositionModel.getResource(this.resourceId);\n if (!resource) {\n console.warn('[VideoWindowDecodeSession] Resource not found in composition model:', {\n resourceId: this.resourceId,\n clipId: this.clipId,\n startUs,\n endUs,\n model: {\n fps: this.compositionModel.fps,\n durationUs: this.compositionModel.durationUs,\n mainTrackId: this.compositionModel.mainTrackId,\n trackCount: this.compositionModel.tracks.length,\n resourcesSize: this.compositionModel.resources.size,\n },\n });\n throw new Error(`Resource not found: ${this.resourceId}`);\n }\n\n if (resource.type === 'image') {\n await this.handleImageResource(resource, startUs, endUs);\n return;\n }\n\n await this.handleVideoResource(startUs, endUs);\n }\n\n /**\n * Scrub decode (timeline dragging):\n * Decode only the minimum frames needed to present a true frame near targetTimeUs.\n * This avoids the heavy 3s window decode used for playback preheating.\n */\n async decodeScrub(targetTimeUs: TimeUs): Promise<void> {\n if (this.isDisposed) {\n throw new Error('Session already disposed');\n }\n\n const resource = this.compositionModel.getResource(this.resourceId);\n if (!resource) {\n throw new Error(`Resource not found: ${this.resourceId}`);\n }\n\n if (resource.type === 'image') {\n const frameDuration = Math.max(1, Math.round(1_000_000 / this.fps));\n await this.handleImageResource(resource, targetTimeUs, targetTimeUs + frameDuration);\n return;\n }\n\n await this.handleVideoResourceScrub(targetTimeUs);\n }\n\n /**\n * Handle image resource by creating a VideoFrame from ImageBitmap\n */\n private async handleImageResource(\n resource: Resource,\n startUs: TimeUs,\n endUs: TimeUs\n ): Promise<void> {\n const image = await this.resourceLoader.loadImage(resource);\n if (!image) return;\n\n const frame = new VideoFrame(image, {\n timestamp: startUs,\n duration: endUs - startUs,\n });\n\n this.cacheManager.addFrame(\n frame,\n this.clipId,\n endUs - startUs,\n this.compositionModel.mainTrackId,\n this.globalTimeUs\n );\n }\n\n /**\n * Handle video resource by decoding from OPFS\n */\n private async handleVideoResource(startUs: TimeUs, endUs: TimeUs): Promise<void> {\n const index = this.mp4IndexCache.get(this.resourceId);\n if (!index) {\n throw new Error(`No index found for resource ${this.resourceId}`);\n }\n\n // Calculate GOP ranges needed\n const gopWindow = this.calculateGOPRangesForWindow(index, startUs, endUs);\n if (gopWindow.gops.length === 0) {\n console.warn('[VideoWindowDecodeSession] no GOPs found for window');\n return;\n }\n\n // Read GOP data from OPFS\n const gopData = await this.readResourceRangeWithRecovery(\n gopWindow.byteStart,\n gopWindow.byteEnd\n );\n\n if (this.aborted) {\n console.warn('[VideoWindowDecodeSession] aborted during readResourceRangeWithRecovery');\n return;\n }\n\n // Extract chunks from GOP data\n const chunks = await this.demuxGOPData(gopData, index, gopWindow);\n if (this.aborted) {\n console.warn('[VideoWindowDecodeSession] aborted during demuxGOPData');\n return;\n }\n\n // Decode chunks to frames\n await this.decodeChunks(chunks, index);\n\n // Check abort and cleanup if needed\n if (this.aborted) {\n console.warn('[VideoWindowDecodeSession] aborted during decodeWindow');\n this.releaseDecodedFrames();\n return;\n }\n\n // Write frames to L1 cache\n await this.cacheDecodedFrames(startUs, endUs);\n }\n\n private async handleVideoResourceScrub(targetTimeUs: TimeUs): Promise<void> {\n const index = this.mp4IndexCache.get(this.resourceId);\n if (!index?.tracks.video) {\n throw new Error(`No video index found for resource ${this.resourceId}`);\n }\n\n const videoTrack = index.tracks.video;\n const { gopIndex, samples } = videoTrack;\n\n const gop = binarySearchRange(gopIndex, targetTimeUs, (g, idx) => {\n const next = gopIndex[idx + 1];\n return { start: g.startTimeUs, end: next ? next.startTimeUs : Infinity };\n });\n if (!gop) {\n // Fallback: use a tiny window decode.\n const frameDuration = Math.max(1, Math.round(1_000_000 / this.fps));\n await this.handleVideoResource(targetTimeUs, targetTimeUs + frameDuration);\n return;\n }\n\n const startIdx = gop.keyframeSampleIndex;\n const endIdx = Math.min(samples.length, startIdx + gop.sampleCount);\n if (startIdx >= endIdx) return;\n\n // Compute byte range for the GOP (sample offsets are not guaranteed monotonic).\n let byteStart = Infinity;\n let byteEnd = 0;\n for (let i = startIdx; i < endIdx; i++) {\n const s = samples[i];\n if (!s) continue;\n byteStart = Math.min(byteStart, s.byteOffset);\n byteEnd = Math.max(byteEnd, s.byteOffset + s.byteLength);\n }\n if (!Number.isFinite(byteStart) || byteEnd <= byteStart) return;\n\n const gopData = await this.readResourceRangeWithRecovery(byteStart, byteEnd);\n if (this.aborted) return;\n\n const chunks = this.buildEncodedChunksFromSamples(\n gopData,\n byteStart,\n samples,\n startIdx,\n endIdx\n );\n if (chunks.length === 0) return;\n\n const timeoutMs = this.cacheManager.isExporting ? 15_000 : 2_000;\n const { before, after } = await decodeChunksForScrub(\n chunks,\n {\n codec: videoTrack.codec,\n width: videoTrack.width,\n height: videoTrack.height,\n description: videoTrack.description,\n },\n targetTimeUs,\n {\n timeoutMs,\n maxQueueSize: 2,\n shouldAbort: () => this.aborted,\n }\n );\n\n if (this.aborted) {\n before?.close();\n after?.close();\n return;\n }\n\n // Cache only the closest frames around target.\n for (const frame of [before, after]) {\n if (!frame) continue;\n try {\n this.cacheFrame(frame);\n } catch {\n frame.close();\n }\n }\n }\n\n private buildEncodedChunksFromSamples(\n data: ArrayBuffer,\n baseByteOffset: number,\n samples: Sample[],\n startIdx: number,\n endIdx: number\n ): EncodedVideoChunk[] {\n const chunks: EncodedVideoChunk[] = [];\n const dataView = new Uint8Array(data);\n\n for (let i = startIdx; i < endIdx; i++) {\n const sample = samples[i];\n if (!sample) continue;\n\n const relativeOffset = sample.byteOffset - baseByteOffset;\n if (relativeOffset < 0 || relativeOffset + sample.byteLength > data.byteLength) {\n continue;\n }\n\n const sampleData = dataView.slice(relativeOffset, relativeOffset + sample.byteLength);\n chunks.push(\n new EncodedVideoChunk({\n type: sample.isKeyframe ? 'key' : 'delta',\n timestamp: sample.timestamp,\n duration: sample.duration,\n data: sampleData,\n })\n );\n }\n\n return chunks;\n }\n\n /**\n * Release all decoded frames without caching\n */\n private releaseDecodedFrames(): void {\n for (const frame of this.decodedFrames) {\n frame.close();\n }\n this.decodedFrames = [];\n }\n\n private calculateGOPRangesForWindow(\n index: MP4Index,\n startUs: TimeUs,\n endUs: TimeUs\n ): GOPWindowResult {\n if (!index.tracks.video) {\n return { gops: [], byteStart: 0, byteEnd: 0 };\n }\n\n const { gopIndex, samples } = index.tracks.video;\n\n // Find GOP containing startUs (or the nearest keyframe before it)\n const nearestKeyframe = this.mp4IndexCache.getNearestKeyframe(this.resourceId, startUs);\n const decodeStartUs = nearestKeyframe?.timestamp ?? startUs;\n\n // Use binary search to find all overlapping GOPs\n const overlappingGOPs = binarySearchOverlapping(gopIndex, decodeStartUs, endUs, (gop, idx) => {\n const nextGOP = gopIndex[idx + 1];\n return {\n start: gop.startTimeUs,\n end: nextGOP ? nextGOP.startTimeUs : Infinity,\n };\n });\n\n if (overlappingGOPs.length === 0) {\n return { gops: [], byteStart: 0, byteEnd: 0 };\n }\n\n // Calculate merged byte range for OPFS read\n let byteStart = Infinity;\n let byteEnd = 0;\n\n for (const gop of overlappingGOPs) {\n const startSample = samples[gop.keyframeSampleIndex];\n const endSampleIndex = gop.keyframeSampleIndex + gop.sampleCount - 1;\n const endSample = samples[endSampleIndex];\n\n if (startSample && endSample) {\n byteStart = Math.min(byteStart, startSample.byteOffset);\n byteEnd = Math.max(byteEnd, endSample.byteOffset + endSample.byteLength);\n }\n }\n\n return { gops: overlappingGOPs, byteStart, byteEnd };\n }\n\n /**\n * Extract video chunks from GOP data\n *\n * Directly use GOP sample indices to slice the samples array.\n * This is O(k) where k is the number of samples in the window,\n * vs O(n×m) for the old approach (n=all samples, m=GOP count).\n */\n private async demuxGOPData(\n data: ArrayBuffer,\n index: MP4Index,\n gopWindow: GOPWindowResult\n ): Promise<EncodedVideoChunk[]> {\n const videoTrack = index.tracks.video;\n if (!videoTrack) {\n throw new Error('No video track in index');\n }\n\n const { samples } = videoTrack;\n const chunks: EncodedVideoChunk[] = [];\n const dataView = new Uint8Array(data);\n const baseByteOffset = gopWindow.byteStart;\n\n // Direct sample index slicing - iterate only samples in the window\n for (const gop of gopWindow.gops) {\n const startIdx = gop.keyframeSampleIndex;\n const endIdx = startIdx + gop.sampleCount;\n\n // Extract samples for this GOP (direct array slice)\n for (let i = startIdx; i < endIdx; i++) {\n const sample = samples[i];\n if (!sample) continue;\n\n // Calculate relative offset within the data buffer\n const relativeOffset = sample.byteOffset - baseByteOffset;\n\n // Validate offset is within buffer\n if (relativeOffset < 0 || relativeOffset + sample.byteLength > data.byteLength) {\n console.warn('[VideoWindowDecodeSession] Sample outside buffer:', {\n sampleOffset: sample.byteOffset,\n sampleLength: sample.byteLength,\n baseOffset: baseByteOffset,\n relativeOffset,\n bufferLength: data.byteLength,\n });\n continue;\n }\n\n // Extract sample data\n const sampleData = dataView.slice(relativeOffset, relativeOffset + sample.byteLength);\n\n // Create EncodedVideoChunk\n const chunk = new EncodedVideoChunk({\n type: sample.isKeyframe ? 'key' : 'delta',\n timestamp: sample.timestamp,\n duration: sample.duration,\n data: sampleData,\n });\n\n chunks.push(chunk);\n }\n }\n\n return chunks;\n }\n\n private async decodeChunks(chunks: EncodedVideoChunk[], index: MP4Index): Promise<void> {\n const videoTrack = index.tracks.video;\n if (!videoTrack) {\n throw new Error('No video track in index');\n }\n\n const timeoutMs = this.cacheManager.isExporting ? 15_000 : undefined;\n const result = await decodeChunksWithoutFlush(\n chunks,\n {\n codec: videoTrack.codec,\n width: videoTrack.width,\n height: videoTrack.height,\n description: videoTrack.description,\n },\n timeoutMs ? { timeoutMs } : undefined\n );\n\n // Store frames for caching\n this.decodedFrames = result.frames;\n }\n\n /**\n * Cache a single frame to L1 with proper timestamp calculations\n */\n private cacheFrame(frame: VideoFrame, globalTimeOffset: TimeUs = 0): void {\n const frameDuration = frame.duration ?? Math.round(1_000_000 / this.fps);\n const clip = this.compositionModel.findClip(this.clipId);\n let frameGlobalTime: TimeUs;\n if (clip && isVideoClip(clip)) {\n const trimStartUs = clip.trimStartUs ?? 0;\n const rate = videoClipPlaybackRate(clip);\n frameGlobalTime = clip.startUs + (frame.timestamp - trimStartUs) / rate + globalTimeOffset;\n } else {\n frameGlobalTime =\n this.globalTimeUs + (frame.timestamp - this.targetTimeUs) + globalTimeOffset;\n }\n\n this.cacheManager.addFrame(\n frame,\n this.clipId,\n frameDuration,\n this.compositionModel.mainTrackId,\n frameGlobalTime\n );\n }\n\n private async cacheDecodedFrames(startUs: TimeUs, endUs: TimeUs): Promise<void> {\n const framesToCache: VideoFrame[] = [];\n const framesToDiscard: VideoFrame[] = [];\n\n // Partition frames into cacheable and discardable\n for (const frame of this.decodedFrames) {\n if (frame.timestamp >= startUs && frame.timestamp < endUs) {\n framesToCache.push(frame);\n } else {\n framesToDiscard.push(frame);\n }\n }\n\n // Cache frames within window\n for (const frame of framesToCache) {\n try {\n this.cacheFrame(frame);\n } catch {\n frame.close();\n }\n }\n\n // Release frames outside window\n for (const frame of framesToDiscard) {\n frame.close();\n }\n\n this.decodedFrames = [];\n }\n\n /**\n * Decode entire time range to VideoFrame stream (for export)\n * Does NOT cache to L1 - outputs frames directly for Worker pipeline\n */\n async decodeRangeToStream(startUs: TimeUs, endUs: TimeUs): Promise<ReadableStream<VideoFrame>> {\n const index = this.mp4IndexCache.get(this.resourceId);\n if (!index?.tracks.video) {\n throw new Error(`[VideoWindowDecodeSession] No video track index for ${this.resourceId}`);\n }\n\n const videoTrack = index.tracks.video;\n const gopWindow = this.calculateGOPRangesForWindow(index, startUs, endUs);\n\n return new ReadableStream<VideoFrame>({\n start: async (controller) => {\n try {\n if (gopWindow.gops.length === 0) {\n console.warn('[VideoWindowDecodeSession] No GOPs found for range');\n controller.close();\n return;\n }\n\n // Process GOPs in batches (10 GOPs at a time for memory control)\n const batchSize = 10;\n for (let i = 0; i < gopWindow.gops.length; i += batchSize) {\n if (this.aborted) {\n controller.close();\n return;\n }\n\n const batchGOPs = gopWindow.gops.slice(\n i,\n Math.min(i + batchSize, gopWindow.gops.length)\n );\n\n // Calculate byte range for this batch\n let batchByteStart = Infinity;\n let batchByteEnd = 0;\n for (const gop of batchGOPs) {\n const startSample = videoTrack.samples[gop.keyframeSampleIndex];\n const endSampleIdx = gop.keyframeSampleIndex + gop.sampleCount - 1;\n const endSample = videoTrack.samples[endSampleIdx];\n if (startSample && endSample) {\n batchByteStart = Math.min(batchByteStart, startSample.byteOffset);\n batchByteEnd = Math.max(batchByteEnd, endSample.byteOffset + endSample.byteLength);\n }\n }\n\n // Read GOP batch data from OPFS\n const gopData = await this.readResourceRangeWithRecovery(batchByteStart, batchByteEnd);\n\n if (this.aborted) {\n controller.close();\n return;\n }\n\n // Extract chunks from GOP batch\n const batchChunks = await this.demuxGOPData(gopData, index, {\n gops: batchGOPs,\n byteStart: batchByteStart,\n byteEnd: batchByteEnd,\n });\n\n // Decode chunks to frames\n await this.decodeChunks(batchChunks, index);\n\n if (this.aborted) {\n this.releaseDecodedFrames();\n controller.close();\n return;\n }\n\n // Enqueue only frames within the requested range.\n // Leading GOP frames before startUs are reference-only; discard them\n // to prevent duplicate frames across sequential windows.\n for (const frame of this.decodedFrames) {\n if (frame.timestamp >= startUs && frame.timestamp < endUs) {\n if (!this.loggedDecodedStreamDimensions) {\n console.info(\n 'decodeRangeToStream:',\n 'Id:',\n this.resourceId,\n 'videoTrack:',\n videoTrack.width,\n 'x',\n videoTrack.height,\n 'displaySize:',\n frame.displayWidth,\n 'x',\n frame.displayHeight,\n 'codedSize:',\n frame.codedWidth,\n 'x',\n frame.codedHeight,\n 'startUs:',\n startUs,\n 'endUs:',\n endUs,\n 'duration:',\n frame.duration,\n 'Uri:',\n this.resourceUri\n );\n this.loggedDecodedStreamDimensions = true;\n }\n\n controller.enqueue(frame);\n } else {\n frame.close();\n }\n }\n this.decodedFrames = [];\n }\n\n controller.close();\n } catch (error) {\n console.error('[VideoWindowDecodeSession] decodeRangeToStream error:', error);\n this.releaseDecodedFrames();\n controller.error(error);\n }\n },\n cancel: () => {\n this.aborted = true;\n this.releaseDecodedFrames();\n },\n });\n }\n\n private async readResourceRangeWithRecovery(start: number, end: number): Promise<ArrayBuffer> {\n try {\n return await this.cacheManager.readResourceRange(this.resourceId, start, end);\n } catch (error) {\n // Recover from a truly corrupted/missing OPFS file, and — as a last resort —\n // from a persistent InvalidStateError (concurrent-write snapshot staleness that\n // OPFSManager.readRange's retries couldn't ride out; seen on Windows). Both are\n // healed the same way: drop the cache, re-download, rebuild index, read once more.\n const recoverable =\n error instanceof ResourceCorruptedError || isDOMException(error, 'InvalidStateError');\n if (!recoverable) throw error;\n\n await this.cacheManager.resourceCache.deleteResource(this.resourceId);\n this.cacheManager.mp4IndexCache.delete(this.resourceId);\n\n await this.resourceLoader.load(this.resourceId, { isPreload: false, clipId: this.clipId });\n return await this.cacheManager.readResourceRange(this.resourceId, start, end);\n }\n }\n\n async dispose(): Promise<void> {\n if (this.isDisposed) return;\n\n this.aborted = true;\n\n // Release all decoded frames\n this.releaseDecodedFrames();\n\n this.isDisposed = true;\n }\n}\n"],"names":[],"mappings":";;;;AA0CO,MAAM,yBAAyB;AAAA;AAAA;AAAA;AAAA;AAAA,EAKpC,aAAa,yBACX,aACA,QACA,OACA,MACA,cACA,KACe;AACf,QAAI,OAAO,WAAW,EAAG;AAEzB,UAAM,aAAa,MAAM,OAAO;AAChC,QAAI,CAAC,WAAY;AAGjB,UAAM,aAAa,OAAO,CAAC;AAC3B,QAAI,CAAC,cAAc,WAAW,SAAS,OAAO;AAC5C;AAAA,IACF;AAEA,QAAI;AACF,YAAM,SAAS,MAAM,yBAAyB,QAAQ;AAAA,QACpD,OAAO,WAAW;AAAA,QAClB,OA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A,oBACA;AAAA,oBACA,MAAM;AAAA,oBACN;AAAA,oBACA,KAAK;AAAA,kBAAA;AAEP,uBAAK,gCAAgC;AAAA,gBACvC;AAEA,2BAAW,QAAQ,KAAK;AAAA,cAC1B,OAAO;AACL,sBAAM,MAAA;AAAA,cACR;AAAA,YACF;AACA,iBAAK,gBAAgB,CAAA;AAAA,UACvB;AAEA,qBAAW,MAAA;AAAA,QACb,SAAS,OAAO;AACd,kBAAQ,MAAM,yDAAyD,KAAK;AAC5E,eAAK,qBAAA;AACL,qBAAW,MAAM,KAAK;AAAA,QACxB;AAAA,MACF;AAAA,MACA,QAAQ,MAAM;AACZ,aAAK,UAAU;AACf,aAAK,qBAAA;AAAA,MACP;AAAA,IAAA,CACD;AAAA,EACH;AAAA,EAEA,MAAc,8BAA8B,OAAe,KAAmC;AAC5F,QAAI;AACF,aAAO,MAAM,KAAK,aAAa,kBAAkB,KAAK,YAAY,OAAO,GAAG;AAAA,IAC9E,SAAS,OAAO;AAKd,YAAM,cACJ,iBAAiB,0BAA0B,eAAe,OAAO,mBAAmB;AACtF,UAAI,CAAC,YAAa,OAAM;AAExB,YAAM,KAAK,aAAa,cAAc,eAAe,KAAK,UAAU;AACpE,WAAK,aAAa,cAAc,OAAO,KAAK,UAAU;AAEtD,YAAM,KAAK,eAAe,KAAK,KAAK,YAAY,EAAE,WAAW,OAAO,QAAQ,KAAK,OAAA,CAAQ;AACzF,aAAO,MAAM,KAAK,aAAa,kBAAkB,KAAK,YAAY,OAAO,GAAG;AAAA,IAC9E;AAAA,EACF;AAAA,EAEA,MAAM,UAAyB;AAC7B,QAAI,KAAK,WAAY;AAErB,SAAK,UAAU;AAGf,SAAK,qBAAA;AAEL,SAAK,aAAa;AAAA,EACpB;AACF;"}
|
|
@@ -27,7 +27,11 @@ export declare class ResourceLoader {
|
|
|
27
27
|
*/
|
|
28
28
|
private loadVideoResource;
|
|
29
29
|
/**
|
|
30
|
-
* Load audio resource
|
|
30
|
+
* Load audio resource: memory -> OPFS -> network.
|
|
31
|
+
* - memory (audioSampleCache) hit: reuse, fastest path.
|
|
32
|
+
* - OPFS hit: read whole file back and parse (no re-download across reloads).
|
|
33
|
+
* If the OPFS file is corrupt/empty, self-heal by deleting it and re-downloading.
|
|
34
|
+
* - miss: download, parse, then persist the raw bytes to OPFS.
|
|
31
35
|
*/
|
|
32
36
|
private loadAudioResource;
|
|
33
37
|
/**
|
|
@@ -81,6 +85,11 @@ export declare class ResourceLoader {
|
|
|
81
85
|
* Aligned with video audio track extraction (unified architecture)
|
|
82
86
|
*/
|
|
83
87
|
private loadAndParseAudioFile;
|
|
88
|
+
/**
|
|
89
|
+
* Parse raw MP3 bytes into EncodedAudioChunks and store in AudioSampleCache.
|
|
90
|
+
* Shared by the download path and the OPFS-hit path.
|
|
91
|
+
*/
|
|
92
|
+
private parseAudioBuffer;
|
|
84
93
|
/**
|
|
85
94
|
* Parse moov from stream and cache index + audio samples + decode first frame
|
|
86
95
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ResourceLoader.d.ts","sourceRoot":"","sources":["../../../src/stages/load/ResourceLoader.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,QAAQ,EACb,KAAK,gBAAgB,EAItB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,mBAAmB,EAAE,QAAQ,EAAgB,qBAAqB,EAAE,MAAM,SAAS,CAAC;AAuBlG,qBAAa,qBAAsB,SAAQ,KAAK;gBAClC,OAAO,EAAE,MAAM;CAI5B;AAED,qBAAa,cAAc;IACzB,OAAO,CAAC,YAAY,CAAe;IACnC,OAAO,CAAC,KAAK,CAAC,CAAmB;IACjC,OAAO,CAAC,WAAW,CAAc;IACjC,OAAO,CAAC,aAAa,CAAgB;IACrC,OAAO,CAAC,QAAQ,CAAC,CAA4B;IAC7C,OAAO,CAAC,UAAU,CAAC,CAAmC;IACtD,OAAO,CAAC,aAAa,CAAC,CAAyD;IAC/E,OAAO,CAAC,SAAS,C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AI,SAAS,IAAI,QAAQ,EAAE,CAE1B;IAED,OAAO,IAAI,IAAI;IAKf;;;OAGG;IACH,OAAO,CAAC,kBAAkB;CAM3B"}
|
|
@@ -176,12 +176,35 @@ class ResourceLoader {
|
|
|
176
176
|
}
|
|
177
177
|
}
|
|
178
178
|
/**
|
|
179
|
-
* Load audio resource
|
|
179
|
+
* Load audio resource: memory -> OPFS -> network.
|
|
180
|
+
* - memory (audioSampleCache) hit: reuse, fastest path.
|
|
181
|
+
* - OPFS hit: read whole file back and parse (no re-download across reloads).
|
|
182
|
+
* If the OPFS file is corrupt/empty, self-heal by deleting it and re-downloading.
|
|
183
|
+
* - miss: download, parse, then persist the raw bytes to OPFS.
|
|
180
184
|
*/
|
|
181
185
|
async loadAudioResource(task) {
|
|
182
|
-
|
|
183
|
-
|
|
186
|
+
const { resourceId } = task;
|
|
187
|
+
if (this.cacheManager.audioSampleCache.has(resourceId)) {
|
|
188
|
+
console.info(`[ResourceLoader][audio-opfs] ${resourceId} memory-cache hit`);
|
|
189
|
+
return;
|
|
184
190
|
}
|
|
191
|
+
if (await this.cacheManager.resourceCache.hasAudioResource(resourceId)) {
|
|
192
|
+
try {
|
|
193
|
+
const buffer = await this.cacheManager.resourceCache.readAudioResource(resourceId);
|
|
194
|
+
this.parseAudioBuffer(resourceId, new Uint8Array(buffer));
|
|
195
|
+
console.info(
|
|
196
|
+
`[ResourceLoader][audio-opfs] ${resourceId} OPFS hit (${buffer.byteLength} bytes), skipped download`
|
|
197
|
+
);
|
|
198
|
+
return;
|
|
199
|
+
} catch (error) {
|
|
200
|
+
console.warn(
|
|
201
|
+
`[ResourceLoader][audio-opfs] ${resourceId} cached file unusable, re-downloading:`,
|
|
202
|
+
error
|
|
203
|
+
);
|
|
204
|
+
await this.cacheManager.resourceCache.deleteAudioResource(resourceId);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
await this.loadAndParseAudioFile(task);
|
|
185
208
|
}
|
|
186
209
|
/**
|
|
187
210
|
* Ensure image blob is cached (download + cache or reuse cache).
|
|
@@ -449,34 +472,53 @@ class ResourceLoader {
|
|
|
449
472
|
try {
|
|
450
473
|
const blob = await this.fetchBlob(task.resource.uri, task.controller.signal);
|
|
451
474
|
const arrayBuffer = await blob.arrayBuffer();
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
475
|
+
this.parseAudioBuffer(resourceId, new Uint8Array(arrayBuffer));
|
|
476
|
+
try {
|
|
477
|
+
await this.cacheManager.resourceCache.writeAudioResource(resourceId, arrayBuffer);
|
|
478
|
+
console.info(
|
|
479
|
+
`[ResourceLoader][audio-opfs] ${resourceId} downloaded & persisted to OPFS (${arrayBuffer.byteLength} bytes)`
|
|
480
|
+
);
|
|
481
|
+
} catch (error) {
|
|
482
|
+
console.warn(
|
|
483
|
+
`[ResourceLoader][audio-opfs] ${resourceId} failed to persist to OPFS:`,
|
|
484
|
+
error
|
|
485
|
+
);
|
|
459
486
|
}
|
|
460
|
-
const audioChunks = allFrames.map((frame) => {
|
|
461
|
-
return new EncodedAudioChunk({
|
|
462
|
-
type: "key",
|
|
463
|
-
// MP3 frames are all key frames
|
|
464
|
-
timestamp: frame.timestampUs,
|
|
465
|
-
duration: frame.durationUs,
|
|
466
|
-
data: frame.data
|
|
467
|
-
});
|
|
468
|
-
});
|
|
469
|
-
const audioConfig = {
|
|
470
|
-
codec: "mp3",
|
|
471
|
-
sampleRate: config.sampleRate,
|
|
472
|
-
numberOfChannels: config.channels
|
|
473
|
-
};
|
|
474
|
-
this.cacheManager.audioSampleCache.set(resourceId, audioChunks, audioConfig);
|
|
475
487
|
} catch (error) {
|
|
476
|
-
console.error(
|
|
488
|
+
console.error(
|
|
489
|
+
`[ResourceLoader][audio-opfs] ${resourceId} failed to parse audio file:`,
|
|
490
|
+
error
|
|
491
|
+
);
|
|
477
492
|
throw error;
|
|
478
493
|
}
|
|
479
494
|
}
|
|
495
|
+
/**
|
|
496
|
+
* Parse raw MP3 bytes into EncodedAudioChunks and store in AudioSampleCache.
|
|
497
|
+
* Shared by the download path and the OPFS-hit path.
|
|
498
|
+
*/
|
|
499
|
+
parseAudioBuffer(resourceId, uint8Array) {
|
|
500
|
+
const parser = new MP3FrameParser();
|
|
501
|
+
const { frames, config } = parser.push(uint8Array);
|
|
502
|
+
const remainingFrames = parser.flush();
|
|
503
|
+
const allFrames = [...frames, ...remainingFrames];
|
|
504
|
+
if (!config) {
|
|
505
|
+
throw new Error(`Failed to parse audio config for ${resourceId}`);
|
|
506
|
+
}
|
|
507
|
+
const audioChunks = allFrames.map(
|
|
508
|
+
(frame) => new EncodedAudioChunk({
|
|
509
|
+
type: "key",
|
|
510
|
+
timestamp: frame.timestampUs,
|
|
511
|
+
duration: frame.durationUs,
|
|
512
|
+
data: frame.data
|
|
513
|
+
})
|
|
514
|
+
);
|
|
515
|
+
const audioConfig = {
|
|
516
|
+
codec: "mp3",
|
|
517
|
+
sampleRate: config.sampleRate,
|
|
518
|
+
numberOfChannels: config.channels
|
|
519
|
+
};
|
|
520
|
+
this.cacheManager.audioSampleCache.set(resourceId, audioChunks, audioConfig);
|
|
521
|
+
}
|
|
480
522
|
/**
|
|
481
523
|
* Parse moov from stream and cache index + audio samples + decode first frame
|
|
482
524
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ResourceLoader.js","sources":["../../../src/stages/load/ResourceLoader.ts"],"sourcesContent":["import {\n type Resource,\n type CompositionModel,\n type VideoClip,\n type AudioClip,\n hasResourceId,\n} from '../../model';\nimport type { ResourceLoadOptions, LoadTask, LoadProgress, ResourceLoaderOptions } from './types';\nimport { TaskManager } from './TaskManager';\nimport { StreamFactory } from './StreamFactory';\nimport { EventPayloadMap, MeframeEvent } from '../../event/events';\nimport { EventBus } from '../../event/EventBus';\nimport { createImageBitmapFromBlob } from '../../utils/image-utils';\nimport { MP4IndexParser, type MP4ParseResult } from '../demux/MP4IndexParser';\nimport { MP3FrameParser } from '../demux/MP3FrameParser';\nimport type { CacheManager } from '../../cache/CacheManager';\n\nimport {\n MP4MoovNotFoundError,\n NotMP4Error,\n toResourceErrorInfo,\n isTerminalMediaResourceError,\n} from '../../utils/errors';\nimport {\n EmptyStreamError,\n ResourceCorruptedError,\n OPFSQuotaExceededError,\n isDOMException,\n} from '../../utils/errors';\n\nexport class ResourceConflictError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ResourceConflictError';\n }\n}\n\nexport class ResourceLoader {\n private cacheManager: CacheManager;\n private model?: CompositionModel;\n private taskManager: TaskManager;\n private streamFactory: StreamFactory;\n private eventBus?: EventBus<EventPayloadMap>;\n private onProgress?: (progress: LoadProgress) => void;\n private onStateChange?: (resourceId: string, state: Resource['state']) => void;\n private blobCache = new Map<string, Blob>();\n private parsingIndexes = new Set<string>(); // Track in-progress index parsing\n private writingResources = new Set<string>(); // Track in-progress OPFS writes\n\n // Preloading state\n private isPreloadingEnabled = true;\n\n constructor(options: ResourceLoaderOptions) {\n const config = options.config || {};\n const maxConcurrent = config.maxConcurrent ?? 4;\n const preloadConcurrency = config.preloadConcurrency ?? 1;\n\n this.taskManager = new TaskManager(maxConcurrent, preloadConcurrency);\n this.streamFactory = new StreamFactory(options.onProgress, config);\n this.eventBus = options.eventBus;\n this.onProgress = options.onProgress;\n this.onStateChange = options.onStateChange;\n this.cacheManager = options.cacheManager;\n }\n\n async setModel(model: CompositionModel): Promise<void> {\n // Resource IDs are globally stable across models (same id implies same uri/content),\n // so in-flight load tasks remain valid across model switching.\n this.model = model;\n const mainTrack = model.tracks.find(\n (track) => track.kind === 'video' && track.id === (model.mainTrackId || 'main')\n );\n if (mainTrack?.clips?.[0] && hasResourceId(mainTrack.clips[0])) {\n try {\n await this.load(mainTrack.clips[0].resourceId, {\n isPreload: false,\n clipId: mainTrack.clips[0].id,\n trackId: mainTrack.id,\n });\n } catch (error) {\n // Do not block model setup on permanent media/container mismatch.\n if (error instanceof NotMP4Error || error instanceof MP4MoovNotFoundError) {\n // Resource state is already set to 'error' in startLoad().\n } else {\n throw error;\n }\n }\n }\n\n // Ready (canplay) must wait until first video clip plus first clip on each audio track\n // voice as separate tracks) are downloaded and parsed — otherwise preview mix/audio\n // gates on resource state will keep buffering.\n const audioTracksSpeech = model.tracks.filter((t) => t.kind === 'audio' && t.id === 'speech');\n for (const track of audioTracksSpeech) {\n const speechClip = track.clips[0];\n if (!speechClip || !hasResourceId(speechClip)) {\n continue;\n }\n const muted = speechClip.audioConfig?.muted ?? false;\n const volume = speechClip.audioConfig?.volume ?? 1.0;\n if (muted || volume <= 0) continue;\n try {\n await this.load(speechClip.resourceId, {\n isPreload: false,\n clipId: speechClip.id,\n trackId: track.id,\n });\n } catch (error) {\n if (\n error instanceof NotMP4Error ||\n error instanceof MP4MoovNotFoundError ||\n isTerminalMediaResourceError(error)\n ) {\n // Resource state is already set to 'error' in startLoad(); preview can skip bad assets.\n } else {\n throw error;\n }\n }\n }\n\n // Ready (canplay) must wait until first video clip plus first clip on each audio track\n // BGM as separate tracks are downloaded and parsed — otherwise preview mix/audio\n // gates on resource state will keep buffering.\n const audioTracksBgm = model.tracks.filter((t) => t.kind === 'audio' && t.id === 'bgm');\n for (const track of audioTracksBgm) {\n const bgmClip = track.clips[0];\n if (!bgmClip || !hasResourceId(bgmClip)) {\n continue;\n }\n const muted = bgmClip.audioConfig?.muted ?? false;\n const volume = bgmClip.audioConfig?.volume ?? 1.0;\n if (muted || volume <= 0) continue;\n try {\n await this.load(bgmClip.resourceId, {\n isPreload: false,\n clipId: bgmClip.id,\n trackId: track.id,\n });\n } catch (error) {\n if (\n error instanceof NotMP4Error ||\n error instanceof MP4MoovNotFoundError ||\n isTerminalMediaResourceError(error)\n ) {\n // Resource state is already set to 'error' in startLoad(); preview can skip bad assets.\n } else {\n throw error;\n }\n }\n }\n\n console.info('[setModel] preloading is begin');\n this.startPreloading();\n console.info('[setModel] preloading is complete');\n }\n\n setPreloadingEnabled(enabled: boolean): void {\n this.isPreloadingEnabled = enabled;\n if (enabled) {\n this.startPreloading();\n }\n }\n\n startPreloading(): void {\n if (!this.model || !this.isPreloadingEnabled) return;\n\n // Collect all video/audio tracks for horizontal loading\n const tracks = this.model.tracks.filter(\n (track) => track.kind === 'video' || track.kind === 'audio'\n );\n if (tracks.length === 0) return;\n\n // Timeline-order preloading: preload clips by their timeline start time, so\n // the clips the user reaches first download first (instead of column-by-column\n // across tracks, which can starve the very first clip behind later tracks).\n const preloadItems: Array<{\n track: (typeof tracks)[number];\n clip: VideoClip | AudioClip;\n clipIndex: number;\n startUs: number;\n }> = [];\n\n for (const track of tracks) {\n for (let clipIndex = 0; clipIndex < track.clips.length; clipIndex++) {\n const clip = track.clips[clipIndex];\n if (!clip || !hasResourceId(clip)) continue;\n preloadItems.push({\n track,\n clip,\n clipIndex,\n startUs: Number.isFinite(clip.startUs) ? clip.startUs : 0,\n });\n }\n }\n\n preloadItems.sort((a, b) => a.startUs - b.startUs || a.clipIndex - b.clipIndex);\n\n for (const { track, clip } of preloadItems) {\n const resource = this.model.getResource(clip.resourceId);\n if (!resource) continue;\n\n // Skip if already ready, loading, or error\n if (\n resource.state === 'ready' ||\n resource.state === 'loading' ||\n resource.state === 'error'\n ) {\n continue;\n }\n\n // Preload is best-effort; always swallow errors to avoid unhandled promise rejections.\n void this.load(resource.id, {\n isPreload: true,\n clipId: clip.id,\n trackId: track.id,\n }).catch(() => {});\n }\n }\n\n private enqueueLoad(\n resource: Resource,\n isPreload: boolean = false,\n sessionId?: string,\n clipId?: string,\n trackId?: string\n ): LoadTask {\n // Check if task is already active\n const existingTask = this.taskManager.getActiveTask(resource.id);\n if (existingTask) {\n // Upgrade preload task to foreground if needed (go through TaskManager to keep counters correct)\n this.taskManager.enqueue(resource, isPreload, sessionId, clipId, trackId);\n return existingTask;\n }\n\n // Create new task and enqueue\n const task = this.taskManager.enqueue(resource, isPreload, sessionId, clipId, trackId);\n this.processQueue();\n return task;\n }\n\n private processQueue(): void {\n while (this.taskManager.canProcess) {\n const task = this.taskManager.getNextTask();\n if (!task) break;\n this.startLoad(task);\n }\n }\n\n /**\n * Load video resource (download + cache or read from cache)\n */\n private async loadVideoResource(task: LoadTask): Promise<void> {\n const cached = await this.cacheManager.hasResourceInCache(task.resourceId);\n\n if (cached) {\n // Resource already in OPFS - ensure index is parsed.\n // Important: OPFS files can disappear (browser eviction / manual clear / partial write).\n // If ensureIndexParsed fails with a corruption-related error, self-heal by re-downloading.\n try {\n await this.ensureIndexParsed(task.resourceId);\n } catch (error) {\n if (\n error instanceof ResourceCorruptedError ||\n error instanceof EmptyStreamError ||\n error instanceof MP4MoovNotFoundError\n ) {\n // ensureIndexParsed() already clears corrupted OPFS + mp4Index cache where applicable.\n // Re-download to OPFS and rebuild index cache.\n await this.loadWithOPFSCache(task);\n return;\n }\n throw error;\n }\n\n // Note: Export now uses IndexedVideoSource directly from OPFS\n // No need to transfer stream to worker anymore\n } else {\n // Not cached - download and cache to OPFS\n await this.loadWithOPFSCache(task);\n }\n }\n\n /**\n * Load audio resource (download + parse or reuse cache)\n */\n private async loadAudioResource(task: LoadTask): Promise<void> {\n if (!this.cacheManager.audioSampleCache.has(task.resourceId)) {\n // Not cached - download and parse\n await this.loadAndParseAudioFile(task);\n }\n // If already cached, do nothing (reuse existing cache)\n }\n\n /**\n * Ensure image blob is cached (download + cache or reuse cache).\n *\n * Important: preload should NOT decode ImageBitmap.\n * createImageBitmap can be slow / flaky under heavy main-thread load (playback + export),\n * and decoding isn't required for caching or for later loadImage()/getImageBitmap() calls.\n */\n private async ensureImageBlob(task: LoadTask): Promise<void> {\n // Check cache first\n let blob = this.blobCache.get(task.resourceId);\n\n if (!blob) {\n // Not cached: download and cache\n if (task.controller) {\n blob = await this.fetchBlob(task.resource.uri, task.controller.signal);\n this.blobCache.set(task.resourceId, blob);\n } else {\n return;\n }\n }\n }\n\n /**\n * Get cached ImageBitmap (for already loaded resources)\n * Used by VideoClipSession to batch transfer attachments\n */\n async getImageBitmap(resourceId: string): Promise<ImageBitmap | null> {\n const blob = this.blobCache.get(resourceId);\n if (!blob) return null;\n return await createImageBitmapFromBlob(blob);\n }\n\n /**\n * Load text resource (json/text)\n */\n private async loadTextResource(task: LoadTask): Promise<void> {\n if (task.controller) {\n await this.fetchBlob(task.resource.uri, task.controller.signal);\n }\n }\n\n /**\n * Start loading a resource\n * Handles state management (loading → ready/error) for all resource types\n */\n private async startLoad(task: LoadTask): Promise<void> {\n this.taskManager.activateTask(task);\n let loadError: Error | undefined;\n\n try {\n this.updateResourceState(task.resourceId, 'loading');\n this.updateLoadStage(task.resourceId, 'loading');\n\n task.controller = new AbortController();\n\n // Route to specific handlers based on resource type\n switch (task.resource.type) {\n case 'image': {\n // Preload path: only cache blob, avoid createImageBitmap during export/playback concurrency.\n this.onProgress?.({\n resourceId: task.resourceId,\n cached: true,\n bytesLoaded: 0,\n totalBytes: 0,\n percentage: 0,\n speed: 128000,\n estimatedTimeRemaining: 0,\n });\n await this.ensureImageBlob(task);\n this.onProgress?.({\n resourceId: task.resourceId,\n cached: true,\n bytesLoaded: 0,\n totalBytes: 0,\n percentage: 100,\n speed: 128000,\n estimatedTimeRemaining: 0,\n });\n break;\n }\n\n case 'video':\n await this.loadVideoResource(task);\n break;\n\n case 'audio':\n this.onProgress?.({\n resourceId: task.resourceId,\n cached: true,\n bytesLoaded: 0,\n totalBytes: 0,\n percentage: 0,\n speed: 256000,\n estimatedTimeRemaining: 0,\n });\n await this.loadAudioResource(task);\n this.onProgress?.({\n resourceId: task.resourceId,\n cached: true,\n bytesLoaded: 0,\n totalBytes: 0,\n percentage: 100,\n speed: 256000,\n estimatedTimeRemaining: 0,\n });\n break;\n\n case 'json':\n case 'text':\n await this.loadTextResource(task);\n break;\n }\n\n // Unified state update for all resource types\n this.updateResourceState(task.resourceId, 'ready');\n this.updateLoadStage(task.resourceId, 'ready');\n } catch (error) {\n task.error = error as Error;\n loadError = error as Error;\n this.updateResourceState(task.resourceId, 'error', toResourceErrorInfo(error));\n this.updateLoadStage(task.resourceId, 'error', toResourceErrorInfo(error));\n } finally {\n this.taskManager.completeTask(task.resourceId, loadError);\n this.processQueue();\n }\n }\n\n /**\n * Ensure MP4 index is parsed for a cached resource\n */\n async ensureIndexParsed(resourceId: string): Promise<void> {\n // Check if index already exists\n if (this.cacheManager.mp4IndexCache.has(resourceId)) {\n return;\n }\n\n // Wait for OPFS write to complete\n while (this.writingResources.has(resourceId)) {\n await new Promise((resolve) => setTimeout(resolve, 50));\n }\n\n // Check if already parsing (avoid duplicate parsing for same resource)\n if (this.parsingIndexes.has(resourceId)) {\n // Wait for the in-progress parsing to complete\n while (this.parsingIndexes.has(resourceId)) {\n await new Promise((resolve) => setTimeout(resolve, 50));\n }\n return;\n }\n\n // Mark as parsing\n this.parsingIndexes.add(resourceId);\n\n try {\n // Validate file exists and has content\n const cached = await this.cacheManager.hasResourceInCache(resourceId);\n if (!cached) {\n throw new ResourceCorruptedError(resourceId, 'File not found in OPFS or is empty');\n }\n\n this.onProgress?.({\n resourceId,\n cached: true,\n bytesLoaded: 0,\n totalBytes: 0,\n percentage: 0,\n speed: 512000,\n estimatedTimeRemaining: 0,\n });\n // Parse from OPFS file\n const stream = await this.createOPFSReadStream(resourceId);\n // Create minimal task for parsing (no clipId since this is a background index parse)\n const parseTask: LoadTask = {\n resourceId,\n resource: { id: resourceId, type: 'video', uri: '' },\n bytesLoaded: 0,\n totalBytes: 0,\n startTime: Date.now(),\n isPreload: false,\n };\n await this.parseIndexFromStream(parseTask, stream);\n\n this.onProgress?.({\n resourceId,\n cached: true,\n bytesLoaded: 0,\n totalBytes: 0,\n percentage: 100,\n speed: 512000,\n estimatedTimeRemaining: 0,\n });\n } catch (error) {\n // Handle empty stream error by clearing corrupted cache\n if (\n error instanceof EmptyStreamError ||\n error instanceof ResourceCorruptedError ||\n error instanceof MP4MoovNotFoundError\n ) {\n console.warn(`[ResourceLoader] Corrupted cache detected for ${resourceId}, clearing...`);\n try {\n await this.cacheManager.resourceCache.deleteResource(resourceId);\n this.cacheManager.mp4IndexCache.delete(resourceId);\n } catch (deleteError) {\n console.error(`[ResourceLoader] Failed to clear corrupted cache:`, deleteError);\n }\n }\n throw error;\n } finally {\n // Remove from parsing set\n this.parsingIndexes.delete(resourceId);\n }\n }\n\n /**\n * Create ReadableStream from OPFS file\n * Reuses OPFSManager's underlying file access\n */\n private async createOPFSReadStream(resourceId: string): Promise<ReadableStream<Uint8Array>> {\n const opfsManager = this.cacheManager.resourceCache.opfsManager;\n const projectId = this.cacheManager.resourceCache.projectId;\n\n try {\n // Get file handle from OPFS\n const dir = await opfsManager.getProjectDir(projectId, 'resource');\n const fileName = `${resourceId}.mp4`;\n const fileHandle = await dir.getFileHandle(fileName, { create: false });\n const file = await fileHandle.getFile();\n\n // Return native stream\n return file.stream();\n } catch (error) {\n if (isDOMException(error, 'NotFoundError')) {\n throw new ResourceCorruptedError(resourceId, 'File not found in OPFS');\n }\n throw error;\n }\n }\n\n /**\n * Load resource and cache to OPFS + parse moov + extract first frame\n *\n * Strategy: Parallel tee() approach for fast first frame\n * - One stream writes to OPFS (background)\n * - Another stream parses moov and extracts first GOP\n * - First frame is decoded and cached immediately\n */\n private async loadWithOPFSCache(task: LoadTask): Promise<void> {\n // Retry the whole download+parse a few times: a stalled stream (see\n // StreamFactory's stall/request timeout) surfaces here as an error. On retry\n // we drop any partial OPFS/index state and start with a fresh AbortController.\n let lastError: unknown;\n for (let attempt = 0; attempt < 3; attempt++) {\n try {\n task.controller = new AbortController();\n const stream = await this.streamFactory.createRegularStream(task);\n if (!stream) {\n throw new Error(`Failed to create stream for ${task.resourceId}`);\n }\n\n // Export mode: only 2-way split (OPFS + parsing)\n // IndexedVideoSource will read directly from OPFS later\n const [opfsStream, parseStream] = stream.tee();\n\n // Parallel execution: write to OPFS and parse index\n await Promise.all([\n this.writeToOPFS(task.resourceId, opfsStream, task),\n this.parseIndexFromStream(task, parseStream),\n ]);\n return;\n } catch (error) {\n lastError = error;\n // Clear partial state so the retry re-downloads cleanly\n try {\n await this.cacheManager.resourceCache.deleteResource(task.resourceId);\n this.cacheManager.mp4IndexCache.delete(task.resourceId);\n } catch {\n // best-effort cleanup\n }\n if (attempt >= 2) break;\n await new Promise((resolve) => setTimeout(resolve, 500 * (attempt + 1)));\n }\n }\n throw lastError ?? new Error(`Failed to load ${task.resourceId} after retries`);\n }\n\n /**\n * Write resource stream to OPFS with retry on quota exceeded\n * If quota is exceeded and old projects are evicted, fetches a fresh stream and retries\n */\n private async writeToOPFS(\n resourceId: string,\n stream: ReadableStream<Uint8Array>,\n task?: LoadTask\n ): Promise<void> {\n this.writingResources.add(resourceId);\n try {\n await this.cacheManager.resourceCache.writeResource(resourceId, stream);\n } catch (error) {\n if (error instanceof OPFSQuotaExceededError && error.retryable && task) {\n console.log(\n `[ResourceLoader] OPFS quota exceeded for ${resourceId}, retrying with fresh stream...`\n );\n\n // Create fresh stream for retry\n const retryStream = await this.streamFactory.createRegularStream(task);\n if (!retryStream) {\n throw new Error(`Failed to create retry stream for ${resourceId}`);\n }\n\n // Retry write with fresh stream\n await this.cacheManager.resourceCache.writeResource(resourceId, retryStream);\n } else {\n throw error;\n }\n } finally {\n this.writingResources.delete(resourceId);\n }\n }\n\n /**\n * Load and parse audio file (MP3/WAV) in main thread\n * Extract EncodedAudioChunk and cache to AudioSampleCache\n * Aligned with video audio track extraction (unified architecture)\n */\n private async loadAndParseAudioFile(task: LoadTask): Promise<void> {\n const { resourceId } = task;\n\n try {\n // TODO: Streaming download and parse?\n const blob = await this.fetchBlob(task.resource.uri, task.controller!.signal);\n\n // Convert blob to ArrayBuffer\n const arrayBuffer = await blob.arrayBuffer();\n const uint8Array = new Uint8Array(arrayBuffer);\n\n // Parse MP3 frames using MP3FrameParser\n const parser = new MP3FrameParser();\n const { frames, config } = parser.push(uint8Array);\n const remainingFrames = parser.flush();\n const allFrames = [...frames, ...remainingFrames];\n\n if (!config) {\n throw new Error(`Failed to parse audio config for ${resourceId}`);\n }\n\n // Convert MP3Frame to EncodedAudioChunk\n const audioChunks: EncodedAudioChunk[] = allFrames.map((frame) => {\n return new EncodedAudioChunk({\n type: 'key', // MP3 frames are all key frames\n timestamp: frame.timestampUs,\n duration: frame.durationUs,\n data: frame.data,\n });\n });\n\n // Build AudioDecoderConfig from MP3Config\n const audioConfig: AudioDecoderConfig = {\n codec: 'mp3',\n sampleRate: config.sampleRate,\n numberOfChannels: config.channels,\n };\n\n // Cache to AudioSampleCache\n this.cacheManager.audioSampleCache.set(resourceId, audioChunks, audioConfig);\n } catch (error) {\n console.error(`[ResourceLoader] Failed to parse audio file ${resourceId}:`, error);\n throw error;\n }\n }\n\n /**\n * Parse moov from stream and cache index + audio samples + decode first frame\n */\n private async parseIndexFromStream(\n task: LoadTask,\n stream: ReadableStream<Uint8Array>\n ): Promise<void> {\n const { resourceId, clipId } = task;\n\n try {\n const parser = new MP4IndexParser();\n\n // Only enable first GOP extraction for clips that start at time 0 (cover clips)\n const shouldExtractFirstGOP = clipId ? this.shouldExtractCover(clipId) : false;\n\n const result: MP4ParseResult = await parser.parseFromStream(stream, {\n resourceId: resourceId,\n onFirstFrameReady: shouldExtractFirstGOP\n ? async (index, chunks) => {\n // Set resourceId on index\n index.resourceId = resourceId;\n\n // Cache index immediately\n this.cacheManager.mp4IndexCache.set(resourceId, index);\n\n // Emit event with chunks for Orchestrator to handle\n this.eventBus?.emit(MeframeEvent.ResourceFirstFrameReady, {\n resourceId,\n clipId: clipId!,\n index,\n chunks,\n });\n }\n : undefined,\n });\n\n result.index.resourceId = resourceId;\n\n // Cache index (if not already cached by onFirstFrameReady)\n if (!this.cacheManager.mp4IndexCache.has(resourceId)) {\n this.cacheManager.mp4IndexCache.set(resourceId, result.index);\n }\n\n // Cache audio samples if present\n if (result.audioSamples && result.audioMetadata) {\n this.cacheManager.audioSampleCache.set(\n resourceId,\n result.audioSamples,\n result.audioMetadata\n );\n }\n } catch (error) {\n if (error instanceof NotMP4Error) {\n console.error(\n `[ResourceLoader] Resource ${resourceId} is not an MP4 file: ${error.detectedContainer}`\n );\n } else if (error instanceof MP4MoovNotFoundError) {\n console.error(\n `[ResourceLoader] MP4 moov box not found for ${resourceId} after reading ${error.bytesRead} bytes`\n );\n } else {\n console.error(`[ResourceLoader] Failed to parse MP4 index for ${resourceId}:`, error);\n }\n // Rethrow error to ensure resource is marked as failed\n // In the new architecture (Window Cache + AudioSampleCache), index parsing is critical.\n throw error;\n }\n }\n\n async loadImage(resource: Resource): Promise<ImageBitmap> {\n // If we already have the blob in memory, decoding to ImageBitmap is NOT resource loading.\n // Do not flip resource.state to 'loading' during playback; it will cause buffering oscillation\n // because PlaybackController gates on resource.state === 'ready'.\n const existingBlob = this.blobCache.get(resource.id);\n if (existingBlob) {\n const imageBitmap = await createImageBitmapFromBlob(existingBlob);\n return imageBitmap;\n }\n\n const task: LoadTask = {\n resourceId: resource.id,\n resource: resource,\n bytesLoaded: 0,\n totalBytes: 0,\n startTime: Date.now(),\n isPreload: false,\n controller: new AbortController(),\n };\n\n // loadImage() bypasses startLoad(), so it must manage resource state by itself.\n let loadError: Error | undefined;\n try {\n this.updateResourceState(resource.id, 'loading');\n // Ensure blob exists, then decode to ImageBitmap.\n await this.ensureImageBlob(task);\n const blob = this.blobCache.get(resource.id);\n if (!blob) throw new Error(`Failed to load image ${resource.id}`);\n const imageBitmap = await createImageBitmapFromBlob(blob);\n this.updateResourceState(resource.id, 'ready');\n return imageBitmap;\n } catch (error) {\n loadError = error as Error;\n this.updateResourceState(resource.id, 'error', toResourceErrorInfo(error));\n throw loadError;\n }\n }\n\n /**\n * Fetch resource as blob (for images, json, etc.)\n */\n private async fetchBlob(uri: string, signal: AbortSignal): Promise<Blob> {\n const response = await fetch(uri, { signal });\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n return response.blob();\n }\n\n private updateResourceState(\n resourceId: string,\n state: Resource['state'],\n error?: Resource['error']\n ): void {\n const resource = this.model?.resources.get(resourceId);\n if (resource) {\n const oldState = resource.state;\n resource.state = state;\n if (state === 'error') {\n resource.error = error;\n } else {\n // Clear stale error info on non-error transitions (new attempt / recovered)\n resource.error = undefined;\n }\n this.eventBus?.emit(MeframeEvent.ResourceStageChange, {\n type: MeframeEvent.ResourceStageChange,\n resourceId,\n oldState,\n newState: state,\n });\n }\n\n this.onStateChange?.(resourceId, state);\n }\n\n private updateLoadStage(\n resourceId: string,\n state: Resource['state'],\n error?: Resource['error']\n ): void {\n const resource = this.model?.resources.get(resourceId);\n console.info(\n '[updateLoadStage] state:',\n state,\n 'resourceId:',\n resourceId,\n 'uri:',\n resource?.uri || ''\n );\n if (state === 'loading') {\n this.eventBus?.emit(MeframeEvent.LoadStart, {\n resourceId,\n url: resource?.uri || '',\n size: 0,\n });\n } else if (state === 'ready') {\n this.eventBus?.emit(MeframeEvent.LoadComplete, {\n resourceId,\n bytes: 0,\n durationMs: 0,\n });\n } else if (state === 'error') {\n this.eventBus?.emit(MeframeEvent.LoadError, {\n resourceId,\n error: new Error(error?.message || 'Unknown error'),\n retry: false,\n });\n }\n }\n\n /**\n * Fetch a resource and wait for loading + parsing to complete\n *\n * Returns a Promise that resolves when:\n * - Resource is fully loaded, parsed, and cached (state='ready')\n * - Or rejects if loading/parsing fails\n *\n * Promise lifecycle:\n * 1. enqueueLoad() creates LoadTask with promise/resolve/reject (or reuses existing)\n * 2. processQueue() → startLoad() executes async in background\n * 3. startLoad() completes → finally → completeTask() → task.resolve()/reject()\n */\n async load(resourceId?: string, options?: ResourceLoadOptions): Promise<void> {\n if (!resourceId) {\n return;\n }\n\n const resource = this.model?.getResource(resourceId);\n if (!resource) {\n const m = this.model;\n console.warn('[ResourceLoader] Resource not found in model:', {\n resourceId,\n options: {\n isPreload: options?.isPreload ?? false,\n sessionId: options?.sessionId,\n clipId: options?.clipId,\n trackId: options?.trackId,\n isMainTrack: options?.isMainTrack,\n },\n model: m\n ? {\n fps: m.fps,\n durationUs: m.durationUs,\n mainTrackId: m.mainTrackId,\n trackCount: m.tracks.length,\n resourcesSize: m.resources.size,\n }\n : null,\n });\n return;\n }\n\n // Terminal error: do not retry automatically. Upstream can decide how to recover (e.g. replace URI).\n if (resource.state === 'error' && resource.error?.terminal === true) {\n return;\n }\n\n const isPreload = options?.isPreload ?? false;\n\n // First check: if resource is already ready, nothing to do\n if (resource.state === 'ready') {\n // NOTE: resource.state is runtime-only and can be stale relative to OPFS/index.\n // During export (or after browser storage eviction), the OPFS file may disappear while\n // the model still marks the resource as 'ready'. For video resources we must validate.\n if (resource.type === 'video') {\n const hasIndex = this.cacheManager.mp4IndexCache.has(resourceId);\n if (hasIndex) {\n const cached = await this.cacheManager.hasResourceInCache(resourceId);\n if (cached) {\n return;\n }\n }\n\n // Force a repair load (OPFS/index missing). Mark back to pending for correctness.\n this.updateResourceState(resourceId, 'pending');\n // Fall through to enqueue a load task.\n } else {\n return;\n }\n }\n\n // Second check: if resource is being loaded\n if (resource.state === 'loading') {\n const existingTask = this.taskManager.getActiveTask(resourceId);\n if (existingTask) {\n // Upgrade preload -> foreground through TaskManager to keep counters correct\n // (do NOT mutate existingTask.isPreload here).\n this.taskManager.enqueue(\n resource,\n isPreload,\n options?.sessionId,\n options?.clipId,\n options?.trackId\n );\n\n // If sessionId matches or no sessionId required, reuse existing task\n if (!options?.sessionId || existingTask.sessionId === options.sessionId) {\n return existingTask.promise;\n }\n }\n }\n\n // Third path: check if already has active task\n const existingTask = this.taskManager.getActiveTask(resourceId);\n if (existingTask) {\n // Upgrade preload -> foreground through TaskManager to keep counters correct\n // (do NOT mutate existingTask.isPreload here).\n this.taskManager.enqueue(\n resource,\n isPreload,\n options?.sessionId,\n options?.clipId,\n options?.trackId\n );\n\n // Reuse existing task\n return existingTask.promise;\n }\n\n // Create new task\n const task = this.enqueueLoad(\n resource,\n isPreload,\n options?.sessionId,\n options?.clipId,\n options?.trackId\n );\n\n // Wait for task completion\n return task.promise;\n }\n\n cancel(resourceId: string): void {\n this.taskManager.cancelTask(resourceId);\n this.processQueue();\n }\n\n /**\n * Check if a resource is currently being loaded\n */\n isResourceLoading(resourceId: string): boolean {\n return this.taskManager.hasActiveTask(resourceId);\n }\n\n pause(resourceId: string): void {\n const task = this.taskManager.getActiveTask(resourceId);\n if (task) {\n task.controller?.abort();\n }\n }\n\n async resume(resourceId: string, options?: ResourceLoadOptions): Promise<void> {\n const resource = this.model?.getResource(resourceId);\n if (!resource) {\n throw new Error(`Resource ${resourceId} not found`);\n }\n\n const pausedTask = this.taskManager.getActiveTask(resourceId);\n\n if (pausedTask?.pausedAt !== undefined) {\n this.enqueueLoad(\n resource,\n options?.isPreload ?? false,\n options?.sessionId,\n options?.clipId,\n options?.trackId\n );\n } else {\n await this.load(resourceId, options);\n }\n }\n\n get activeTasks(): Map<string, LoadTask> {\n return this.taskManager.activeTasks;\n }\n\n get taskQueue(): LoadTask[] {\n return this.taskManager.taskQueue;\n }\n\n dispose(): void {\n this.taskManager.clear();\n this.blobCache.clear();\n }\n\n /**\n * Check if a clip needs cover extraction (first GOP decode)\n * Only clips starting at time 0 need fast cover rendering\n */\n private shouldExtractCover(clipId: string): boolean {\n if (!this.model) return false;\n\n const clip = this.model.findClip(clipId);\n return clip?.startUs === 0;\n }\n}\n"],"names":["existingTask"],"mappings":";;;;;;;;AAqCO,MAAM,eAAe;AAAA,EAClB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,gCAAgB,IAAA;AAAA,EAChB,qCAAqB,IAAA;AAAA;AAAA,EACrB,uCAAuB,IAAA;AAAA;AAAA;AAAA,EAGvB,sBAAsB;AAAA,EAE9B,YAAY,SAAgC;AAC1C,UAAM,SAAS,QAAQ,UAAU,CAAA;AACjC,UAAM,gBAAgB,OAAO,iBAAiB;AAC9C,UAAM,qBAAqB,OAAO,sBAAsB;AAExD,SAAK,cAAc,IAAI,YAAY,eAAe,kBAAkB;AACpE,SAAK,gBAAgB,IAAI,cAAc,QAAQ,YAAY,MAAM;AACjE,SAAK,WAAW,QAAQ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AY;AAAA,IACpD;AAEA,UAAM,aAAa,KAAK,YAAY,cAAc,UAAU;AAE5D,QAAI,YAAY,aAAa,QAAW;AACtC,WAAK;AAAA,QACH;AAAA,QACA,SAAS,aAAa;AAAA,QACtB,SAAS;AAAA,QACT,SAAS;AAAA,QACT,SAAS;AAAA,MAAA;AAAA,IAEb,OAAO;AACL,YAAM,KAAK,KAAK,YAAY,OAAO;AAAA,IACrC;AAAA,EACF;AAAA,EAEA,IAAI,cAAqC;AACvC,WAAO,KAAK,YAAY;AAAA,EAC1B;AAAA,EAEA,IAAI,YAAwB;AAC1B,WAAO,KAAK,YAAY;AAAA,EAC1B;AAAA,EAEA,UAAgB;AACd,SAAK,YAAY,MAAA;AACjB,SAAK,UAAU,MAAA;AAAA,EACjB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMQ,mBAAmB,QAAyB;AAClD,QAAI,CAAC,KAAK,MAAO,QAAO;AAExB,UAAM,OAAO,KAAK,MAAM,SAAS,MAAM;AACvC,WAAO,MAAM,YAAY;AAAA,EAC3B;AACF;"}
|
|
1
|
+
{"version":3,"file":"ResourceLoader.js","sources":["../../../src/stages/load/ResourceLoader.ts"],"sourcesContent":["import {\n type Resource,\n type CompositionModel,\n type VideoClip,\n type AudioClip,\n hasResourceId,\n} from '../../model';\nimport type { ResourceLoadOptions, LoadTask, LoadProgress, ResourceLoaderOptions } from './types';\nimport { TaskManager } from './TaskManager';\nimport { StreamFactory } from './StreamFactory';\nimport { EventPayloadMap, MeframeEvent } from '../../event/events';\nimport { EventBus } from '../../event/EventBus';\nimport { createImageBitmapFromBlob } from '../../utils/image-utils';\nimport { MP4IndexParser, type MP4ParseResult } from '../demux/MP4IndexParser';\nimport { MP3FrameParser } from '../demux/MP3FrameParser';\nimport type { CacheManager } from '../../cache/CacheManager';\n\nimport {\n MP4MoovNotFoundError,\n NotMP4Error,\n toResourceErrorInfo,\n isTerminalMediaResourceError,\n} from '../../utils/errors';\nimport {\n EmptyStreamError,\n ResourceCorruptedError,\n OPFSQuotaExceededError,\n isDOMException,\n} from '../../utils/errors';\n\nexport class ResourceConflictError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ResourceConflictError';\n }\n}\n\nexport class ResourceLoader {\n private cacheManager: CacheManager;\n private model?: CompositionModel;\n private taskManager: TaskManager;\n private streamFactory: StreamFactory;\n private eventBus?: EventBus<EventPayloadMap>;\n private onProgress?: (progress: LoadProgress) => void;\n private onStateChange?: (resourceId: string, state: Resource['state']) => void;\n private blobCache = new Map<string, Blob>();\n private parsingIndexes = new Set<string>(); // Track in-progress index parsing\n private writingResources = new Set<string>(); // Track in-progress OPFS writes\n\n // Preloading state\n private isPreloadingEnabled = true;\n\n constructor(options: ResourceLoaderOptions) {\n const config = options.config || {};\n const maxConcurrent = config.maxConcurrent ?? 4;\n const preloadConcurrency = config.preloadConcurrency ?? 1;\n\n this.taskManager = new TaskManager(maxConcurrent, preloadConcurrency);\n this.streamFactory = new StreamFactory(options.onProgress, config);\n this.eventBus = options.eventBus;\n this.onProgress = options.onProgress;\n this.onStateChange = options.onStateChange;\n this.cacheManager = options.cacheManager;\n }\n\n async setModel(model: CompositionModel): Promise<void> {\n // Resource IDs are globally stable across models (same id implies same uri/content),\n // so in-flight load tasks remain valid across model switching.\n this.model = model;\n const mainTrack = model.tracks.find(\n (track) => track.kind === 'video' && track.id === (model.mainTrackId || 'main')\n );\n if (mainTrack?.clips?.[0] && hasResourceId(mainTrack.clips[0])) {\n try {\n await this.load(mainTrack.clips[0].resourceId, {\n isPreload: false,\n clipId: mainTrack.clips[0].id,\n trackId: mainTrack.id,\n });\n } catch (error) {\n // Do not block model setup on permanent media/container mismatch.\n if (error instanceof NotMP4Error || error instanceof MP4MoovNotFoundError) {\n // Resource state is already set to 'error' in startLoad().\n } else {\n throw error;\n }\n }\n }\n\n // Ready (canplay) must wait until first video clip plus first clip on each audio track\n // voice as separate tracks) are downloaded and parsed — otherwise preview mix/audio\n // gates on resource state will keep buffering.\n const audioTracksSpeech = model.tracks.filter((t) => t.kind === 'audio' && t.id === 'speech');\n for (const track of audioTracksSpeech) {\n const speechClip = track.clips[0];\n if (!speechClip || !hasResourceId(speechClip)) {\n continue;\n }\n const muted = speechClip.audioConfig?.muted ?? false;\n const volume = speechClip.audioConfig?.volume ?? 1.0;\n if (muted || volume <= 0) continue;\n try {\n await this.load(speechClip.resourceId, {\n isPreload: false,\n clipId: speechClip.id,\n trackId: track.id,\n });\n } catch (error) {\n if (\n error instanceof NotMP4Error ||\n error instanceof MP4MoovNotFoundError ||\n isTerminalMediaResourceError(error)\n ) {\n // Resource state is already set to 'error' in startLoad(); preview can skip bad assets.\n } else {\n throw error;\n }\n }\n }\n\n // Ready (canplay) must wait until first video clip plus first clip on each audio track\n // BGM as separate tracks are downloaded and parsed — otherwise preview mix/audio\n // gates on resource state will keep buffering.\n const audioTracksBgm = model.tracks.filter((t) => t.kind === 'audio' && t.id === 'bgm');\n for (const track of audioTracksBgm) {\n const bgmClip = track.clips[0];\n if (!bgmClip || !hasResourceId(bgmClip)) {\n continue;\n }\n const muted = bgmClip.audioConfig?.muted ?? false;\n const volume = bgmClip.audioConfig?.volume ?? 1.0;\n if (muted || volume <= 0) continue;\n try {\n await this.load(bgmClip.resourceId, {\n isPreload: false,\n clipId: bgmClip.id,\n trackId: track.id,\n });\n } catch (error) {\n if (\n error instanceof NotMP4Error ||\n error instanceof MP4MoovNotFoundError ||\n isTerminalMediaResourceError(error)\n ) {\n // Resource state is already set to 'error' in startLoad(); preview can skip bad assets.\n } else {\n throw error;\n }\n }\n }\n\n console.info('[setModel] preloading is begin');\n this.startPreloading();\n console.info('[setModel] preloading is complete');\n }\n\n setPreloadingEnabled(enabled: boolean): void {\n this.isPreloadingEnabled = enabled;\n if (enabled) {\n this.startPreloading();\n }\n }\n\n startPreloading(): void {\n if (!this.model || !this.isPreloadingEnabled) return;\n\n // Collect all video/audio tracks for horizontal loading\n const tracks = this.model.tracks.filter(\n (track) => track.kind === 'video' || track.kind === 'audio'\n );\n if (tracks.length === 0) return;\n\n // Timeline-order preloading: preload clips by their timeline start time, so\n // the clips the user reaches first download first (instead of column-by-column\n // across tracks, which can starve the very first clip behind later tracks).\n const preloadItems: Array<{\n track: (typeof tracks)[number];\n clip: VideoClip | AudioClip;\n clipIndex: number;\n startUs: number;\n }> = [];\n\n for (const track of tracks) {\n for (let clipIndex = 0; clipIndex < track.clips.length; clipIndex++) {\n const clip = track.clips[clipIndex];\n if (!clip || !hasResourceId(clip)) continue;\n preloadItems.push({\n track,\n clip,\n clipIndex,\n startUs: Number.isFinite(clip.startUs) ? clip.startUs : 0,\n });\n }\n }\n\n preloadItems.sort((a, b) => a.startUs - b.startUs || a.clipIndex - b.clipIndex);\n\n for (const { track, clip } of preloadItems) {\n const resource = this.model.getResource(clip.resourceId);\n if (!resource) continue;\n\n // Skip if already ready, loading, or error\n if (\n resource.state === 'ready' ||\n resource.state === 'loading' ||\n resource.state === 'error'\n ) {\n continue;\n }\n\n // Preload is best-effort; always swallow errors to avoid unhandled promise rejections.\n void this.load(resource.id, {\n isPreload: true,\n clipId: clip.id,\n trackId: track.id,\n }).catch(() => {});\n }\n }\n\n private enqueueLoad(\n resource: Resource,\n isPreload: boolean = false,\n sessionId?: string,\n clipId?: string,\n trackId?: string\n ): LoadTask {\n // Check if task is already active\n const existingTask = this.taskManager.getActiveTask(resource.id);\n if (existingTask) {\n // Upgrade preload task to foreground if needed (go through TaskManager to keep counters correct)\n this.taskManager.enqueue(resource, isPreload, sessionId, clipId, trackId);\n return existingTask;\n }\n\n // Create new task and enqueue\n const task = this.taskManager.enqueue(resource, isPreload, sessionId, clipId, trackId);\n this.processQueue();\n return task;\n }\n\n private processQueue(): void {\n while (this.taskManager.canProcess) {\n const task = this.taskManager.getNextTask();\n if (!task) break;\n this.startLoad(task);\n }\n }\n\n /**\n * Load video resource (download + cache or read from cache)\n */\n private async loadVideoResource(task: LoadTask): Promise<void> {\n const cached = await this.cacheManager.hasResourceInCache(task.resourceId);\n\n if (cached) {\n // Resource already in OPFS - ensure index is parsed.\n // Important: OPFS files can disappear (browser eviction / manual clear / partial write).\n // If ensureIndexParsed fails with a corruption-related error, self-heal by re-downloading.\n try {\n await this.ensureIndexParsed(task.resourceId);\n } catch (error) {\n if (\n error instanceof ResourceCorruptedError ||\n error instanceof EmptyStreamError ||\n error instanceof MP4MoovNotFoundError\n ) {\n // ensureIndexParsed() already clears corrupted OPFS + mp4Index cache where applicable.\n // Re-download to OPFS and rebuild index cache.\n await this.loadWithOPFSCache(task);\n return;\n }\n throw error;\n }\n\n // Note: Export now uses IndexedVideoSource directly from OPFS\n // No need to transfer stream to worker anymore\n } else {\n // Not cached - download and cache to OPFS\n await this.loadWithOPFSCache(task);\n }\n }\n\n /**\n * Load audio resource: memory -> OPFS -> network.\n * - memory (audioSampleCache) hit: reuse, fastest path.\n * - OPFS hit: read whole file back and parse (no re-download across reloads).\n * If the OPFS file is corrupt/empty, self-heal by deleting it and re-downloading.\n * - miss: download, parse, then persist the raw bytes to OPFS.\n */\n private async loadAudioResource(task: LoadTask): Promise<void> {\n const { resourceId } = task;\n\n // 1. Memory cache hit.\n if (this.cacheManager.audioSampleCache.has(resourceId)) {\n console.info(`[ResourceLoader][audio-opfs] ${resourceId} memory-cache hit`);\n return;\n }\n\n // 2. OPFS hit: read whole file and parse.\n if (await this.cacheManager.resourceCache.hasAudioResource(resourceId)) {\n try {\n const buffer = await this.cacheManager.resourceCache.readAudioResource(resourceId);\n this.parseAudioBuffer(resourceId, new Uint8Array(buffer));\n console.info(\n `[ResourceLoader][audio-opfs] ${resourceId} OPFS hit (${buffer.byteLength} bytes), skipped download`\n );\n return;\n } catch (error) {\n // OPFS file missing/corrupt: drop it and fall through to re-download.\n console.warn(\n `[ResourceLoader][audio-opfs] ${resourceId} cached file unusable, re-downloading:`,\n error\n );\n await this.cacheManager.resourceCache.deleteAudioResource(resourceId);\n }\n }\n\n // 3. Miss: download, parse, persist to OPFS.\n await this.loadAndParseAudioFile(task);\n }\n\n /**\n * Ensure image blob is cached (download + cache or reuse cache).\n *\n * Important: preload should NOT decode ImageBitmap.\n * createImageBitmap can be slow / flaky under heavy main-thread load (playback + export),\n * and decoding isn't required for caching or for later loadImage()/getImageBitmap() calls.\n */\n private async ensureImageBlob(task: LoadTask): Promise<void> {\n // Check cache first\n let blob = this.blobCache.get(task.resourceId);\n\n if (!blob) {\n // Not cached: download and cache\n if (task.controller) {\n blob = await this.fetchBlob(task.resource.uri, task.controller.signal);\n this.blobCache.set(task.resourceId, blob);\n } else {\n return;\n }\n }\n }\n\n /**\n * Get cached ImageBitmap (for already loaded resources)\n * Used by VideoClipSession to batch transfer attachments\n */\n async getImageBitmap(resourceId: string): Promise<ImageBitmap | null> {\n const blob = this.blobCache.get(resourceId);\n if (!blob) return null;\n return await createImageBitmapFromBlob(blob);\n }\n\n /**\n * Load text resource (json/text)\n */\n private async loadTextResource(task: LoadTask): Promise<void> {\n if (task.controller) {\n await this.fetchBlob(task.resource.uri, task.controller.signal);\n }\n }\n\n /**\n * Start loading a resource\n * Handles state management (loading → ready/error) for all resource types\n */\n private async startLoad(task: LoadTask): Promise<void> {\n this.taskManager.activateTask(task);\n let loadError: Error | undefined;\n\n try {\n this.updateResourceState(task.resourceId, 'loading');\n this.updateLoadStage(task.resourceId, 'loading');\n\n task.controller = new AbortController();\n\n // Route to specific handlers based on resource type\n switch (task.resource.type) {\n case 'image': {\n // Preload path: only cache blob, avoid createImageBitmap during export/playback concurrency.\n this.onProgress?.({\n resourceId: task.resourceId,\n cached: true,\n bytesLoaded: 0,\n totalBytes: 0,\n percentage: 0,\n speed: 128000,\n estimatedTimeRemaining: 0,\n });\n await this.ensureImageBlob(task);\n this.onProgress?.({\n resourceId: task.resourceId,\n cached: true,\n bytesLoaded: 0,\n totalBytes: 0,\n percentage: 100,\n speed: 128000,\n estimatedTimeRemaining: 0,\n });\n break;\n }\n\n case 'video':\n await this.loadVideoResource(task);\n break;\n\n case 'audio':\n this.onProgress?.({\n resourceId: task.resourceId,\n cached: true,\n bytesLoaded: 0,\n totalBytes: 0,\n percentage: 0,\n speed: 256000,\n estimatedTimeRemaining: 0,\n });\n await this.loadAudioResource(task);\n this.onProgress?.({\n resourceId: task.resourceId,\n cached: true,\n bytesLoaded: 0,\n totalBytes: 0,\n percentage: 100,\n speed: 256000,\n estimatedTimeRemaining: 0,\n });\n break;\n\n case 'json':\n case 'text':\n await this.loadTextResource(task);\n break;\n }\n\n // Unified state update for all resource types\n this.updateResourceState(task.resourceId, 'ready');\n this.updateLoadStage(task.resourceId, 'ready');\n } catch (error) {\n task.error = error as Error;\n loadError = error as Error;\n this.updateResourceState(task.resourceId, 'error', toResourceErrorInfo(error));\n this.updateLoadStage(task.resourceId, 'error', toResourceErrorInfo(error));\n } finally {\n this.taskManager.completeTask(task.resourceId, loadError);\n this.processQueue();\n }\n }\n\n /**\n * Ensure MP4 index is parsed for a cached resource\n */\n async ensureIndexParsed(resourceId: string): Promise<void> {\n // Check if index already exists\n if (this.cacheManager.mp4IndexCache.has(resourceId)) {\n return;\n }\n\n // Wait for OPFS write to complete\n while (this.writingResources.has(resourceId)) {\n await new Promise((resolve) => setTimeout(resolve, 50));\n }\n\n // Check if already parsing (avoid duplicate parsing for same resource)\n if (this.parsingIndexes.has(resourceId)) {\n // Wait for the in-progress parsing to complete\n while (this.parsingIndexes.has(resourceId)) {\n await new Promise((resolve) => setTimeout(resolve, 50));\n }\n return;\n }\n\n // Mark as parsing\n this.parsingIndexes.add(resourceId);\n\n try {\n // Validate file exists and has content\n const cached = await this.cacheManager.hasResourceInCache(resourceId);\n if (!cached) {\n throw new ResourceCorruptedError(resourceId, 'File not found in OPFS or is empty');\n }\n\n this.onProgress?.({\n resourceId,\n cached: true,\n bytesLoaded: 0,\n totalBytes: 0,\n percentage: 0,\n speed: 512000,\n estimatedTimeRemaining: 0,\n });\n // Parse from OPFS file\n const stream = await this.createOPFSReadStream(resourceId);\n // Create minimal task for parsing (no clipId since this is a background index parse)\n const parseTask: LoadTask = {\n resourceId,\n resource: { id: resourceId, type: 'video', uri: '' },\n bytesLoaded: 0,\n totalBytes: 0,\n startTime: Date.now(),\n isPreload: false,\n };\n await this.parseIndexFromStream(parseTask, stream);\n\n this.onProgress?.({\n resourceId,\n cached: true,\n bytesLoaded: 0,\n totalBytes: 0,\n percentage: 100,\n speed: 512000,\n estimatedTimeRemaining: 0,\n });\n } catch (error) {\n // Handle empty stream error by clearing corrupted cache\n if (\n error instanceof EmptyStreamError ||\n error instanceof ResourceCorruptedError ||\n error instanceof MP4MoovNotFoundError\n ) {\n console.warn(`[ResourceLoader] Corrupted cache detected for ${resourceId}, clearing...`);\n try {\n await this.cacheManager.resourceCache.deleteResource(resourceId);\n this.cacheManager.mp4IndexCache.delete(resourceId);\n } catch (deleteError) {\n console.error(`[ResourceLoader] Failed to clear corrupted cache:`, deleteError);\n }\n }\n throw error;\n } finally {\n // Remove from parsing set\n this.parsingIndexes.delete(resourceId);\n }\n }\n\n /**\n * Create ReadableStream from OPFS file\n * Reuses OPFSManager's underlying file access\n */\n private async createOPFSReadStream(resourceId: string): Promise<ReadableStream<Uint8Array>> {\n const opfsManager = this.cacheManager.resourceCache.opfsManager;\n const projectId = this.cacheManager.resourceCache.projectId;\n\n try {\n // Get file handle from OPFS\n const dir = await opfsManager.getProjectDir(projectId, 'resource');\n const fileName = `${resourceId}.mp4`;\n const fileHandle = await dir.getFileHandle(fileName, { create: false });\n const file = await fileHandle.getFile();\n\n // Return native stream\n return file.stream();\n } catch (error) {\n if (isDOMException(error, 'NotFoundError')) {\n throw new ResourceCorruptedError(resourceId, 'File not found in OPFS');\n }\n throw error;\n }\n }\n\n /**\n * Load resource and cache to OPFS + parse moov + extract first frame\n *\n * Strategy: Parallel tee() approach for fast first frame\n * - One stream writes to OPFS (background)\n * - Another stream parses moov and extracts first GOP\n * - First frame is decoded and cached immediately\n */\n private async loadWithOPFSCache(task: LoadTask): Promise<void> {\n // Retry the whole download+parse a few times: a stalled stream (see\n // StreamFactory's stall/request timeout) surfaces here as an error. On retry\n // we drop any partial OPFS/index state and start with a fresh AbortController.\n let lastError: unknown;\n for (let attempt = 0; attempt < 3; attempt++) {\n try {\n task.controller = new AbortController();\n const stream = await this.streamFactory.createRegularStream(task);\n if (!stream) {\n throw new Error(`Failed to create stream for ${task.resourceId}`);\n }\n\n // Export mode: only 2-way split (OPFS + parsing)\n // IndexedVideoSource will read directly from OPFS later\n const [opfsStream, parseStream] = stream.tee();\n\n // Parallel execution: write to OPFS and parse index\n await Promise.all([\n this.writeToOPFS(task.resourceId, opfsStream, task),\n this.parseIndexFromStream(task, parseStream),\n ]);\n return;\n } catch (error) {\n lastError = error;\n // Clear partial state so the retry re-downloads cleanly\n try {\n await this.cacheManager.resourceCache.deleteResource(task.resourceId);\n this.cacheManager.mp4IndexCache.delete(task.resourceId);\n } catch {\n // best-effort cleanup\n }\n if (attempt >= 2) break;\n await new Promise((resolve) => setTimeout(resolve, 500 * (attempt + 1)));\n }\n }\n throw lastError ?? new Error(`Failed to load ${task.resourceId} after retries`);\n }\n\n /**\n * Write resource stream to OPFS with retry on quota exceeded\n * If quota is exceeded and old projects are evicted, fetches a fresh stream and retries\n */\n private async writeToOPFS(\n resourceId: string,\n stream: ReadableStream<Uint8Array>,\n task?: LoadTask\n ): Promise<void> {\n this.writingResources.add(resourceId);\n try {\n await this.cacheManager.resourceCache.writeResource(resourceId, stream);\n } catch (error) {\n if (error instanceof OPFSQuotaExceededError && error.retryable && task) {\n console.log(\n `[ResourceLoader] OPFS quota exceeded for ${resourceId}, retrying with fresh stream...`\n );\n\n // Create fresh stream for retry\n const retryStream = await this.streamFactory.createRegularStream(task);\n if (!retryStream) {\n throw new Error(`Failed to create retry stream for ${resourceId}`);\n }\n\n // Retry write with fresh stream\n await this.cacheManager.resourceCache.writeResource(resourceId, retryStream);\n } else {\n throw error;\n }\n } finally {\n this.writingResources.delete(resourceId);\n }\n }\n\n /**\n * Load and parse audio file (MP3/WAV) in main thread\n * Extract EncodedAudioChunk and cache to AudioSampleCache\n * Aligned with video audio track extraction (unified architecture)\n */\n private async loadAndParseAudioFile(task: LoadTask): Promise<void> {\n const { resourceId } = task;\n\n try {\n // TODO: Streaming download and parse?\n const blob = await this.fetchBlob(task.resource.uri, task.controller!.signal);\n const arrayBuffer = await blob.arrayBuffer();\n\n // Parse into memory cache first so playback is ready even if OPFS write fails.\n this.parseAudioBuffer(resourceId, new Uint8Array(arrayBuffer));\n\n // Persist raw bytes to OPFS so future sessions skip the re-download.\n // Best-effort: a quota/write failure must not break playback.\n try {\n await this.cacheManager.resourceCache.writeAudioResource(resourceId, arrayBuffer);\n console.info(\n `[ResourceLoader][audio-opfs] ${resourceId} downloaded & persisted to OPFS (${arrayBuffer.byteLength} bytes)`\n );\n } catch (error) {\n console.warn(\n `[ResourceLoader][audio-opfs] ${resourceId} failed to persist to OPFS:`,\n error\n );\n }\n } catch (error) {\n console.error(\n `[ResourceLoader][audio-opfs] ${resourceId} failed to parse audio file:`,\n error\n );\n throw error;\n }\n }\n\n /**\n * Parse raw MP3 bytes into EncodedAudioChunks and store in AudioSampleCache.\n * Shared by the download path and the OPFS-hit path.\n */\n private parseAudioBuffer(resourceId: string, uint8Array: Uint8Array): void {\n const parser = new MP3FrameParser();\n const { frames, config } = parser.push(uint8Array);\n const remainingFrames = parser.flush();\n const allFrames = [...frames, ...remainingFrames];\n\n if (!config) {\n throw new Error(`Failed to parse audio config for ${resourceId}`);\n }\n\n // MP3 frames are all key frames.\n const audioChunks: EncodedAudioChunk[] = allFrames.map(\n (frame) =>\n new EncodedAudioChunk({\n type: 'key',\n timestamp: frame.timestampUs,\n duration: frame.durationUs,\n data: frame.data,\n })\n );\n\n const audioConfig: AudioDecoderConfig = {\n codec: 'mp3',\n sampleRate: config.sampleRate,\n numberOfChannels: config.channels,\n };\n\n this.cacheManager.audioSampleCache.set(resourceId, audioChunks, audioConfig);\n }\n\n /**\n * Parse moov from stream and cache index + audio samples + decode first frame\n */\n private async parseIndexFromStream(\n task: LoadTask,\n stream: ReadableStream<Uint8Array>\n ): Promise<void> {\n const { resourceId, clipId } = task;\n\n try {\n const parser = new MP4IndexParser();\n\n // Only enable first GOP extraction for clips that start at time 0 (cover clips)\n const shouldExtractFirstGOP = clipId ? this.shouldExtractCover(clipId) : false;\n\n const result: MP4ParseResult = await parser.parseFromStream(stream, {\n resourceId: resourceId,\n onFirstFrameReady: shouldExtractFirstGOP\n ? async (index, chunks) => {\n // Set resourceId on index\n index.resourceId = resourceId;\n\n // Cache index immediately\n this.cacheManager.mp4IndexCache.set(resourceId, index);\n\n // Emit event with chunks for Orchestrator to handle\n this.eventBus?.emit(MeframeEvent.ResourceFirstFrameReady, {\n resourceId,\n clipId: clipId!,\n index,\n chunks,\n });\n }\n : undefined,\n });\n\n result.index.resourceId = resourceId;\n\n // Cache index (if not already cached by onFirstFrameReady)\n if (!this.cacheManager.mp4IndexCache.has(resourceId)) {\n this.cacheManager.mp4IndexCache.set(resourceId, result.index);\n }\n\n // Cache audio samples if present\n if (result.audioSamples && result.audioMetadata) {\n this.cacheManager.audioSampleCache.set(\n resourceId,\n result.audioSamples,\n result.audioMetadata\n );\n }\n } catch (error) {\n if (error instanceof NotMP4Error) {\n console.error(\n `[ResourceLoader] Resource ${resourceId} is not an MP4 file: ${error.detectedContainer}`\n );\n } else if (error instanceof MP4MoovNotFoundError) {\n console.error(\n `[ResourceLoader] MP4 moov box not found for ${resourceId} after reading ${error.bytesRead} bytes`\n );\n } else {\n console.error(`[ResourceLoader] Failed to parse MP4 index for ${resourceId}:`, error);\n }\n // Rethrow error to ensure resource is marked as failed\n // In the new architecture (Window Cache + AudioSampleCache), index parsing is critical.\n throw error;\n }\n }\n\n async loadImage(resource: Resource): Promise<ImageBitmap> {\n // If we already have the blob in memory, decoding to ImageBitmap is NOT resource loading.\n // Do not flip resource.state to 'loading' during playback; it will cause buffering oscillation\n // because PlaybackController gates on resource.state === 'ready'.\n const existingBlob = this.blobCache.get(resource.id);\n if (existingBlob) {\n const imageBitmap = await createImageBitmapFromBlob(existingBlob);\n return imageBitmap;\n }\n\n const task: LoadTask = {\n resourceId: resource.id,\n resource: resource,\n bytesLoaded: 0,\n totalBytes: 0,\n startTime: Date.now(),\n isPreload: false,\n controller: new AbortController(),\n };\n\n // loadImage() bypasses startLoad(), so it must manage resource state by itself.\n let loadError: Error | undefined;\n try {\n this.updateResourceState(resource.id, 'loading');\n // Ensure blob exists, then decode to ImageBitmap.\n await this.ensureImageBlob(task);\n const blob = this.blobCache.get(resource.id);\n if (!blob) throw new Error(`Failed to load image ${resource.id}`);\n const imageBitmap = await createImageBitmapFromBlob(blob);\n this.updateResourceState(resource.id, 'ready');\n return imageBitmap;\n } catch (error) {\n loadError = error as Error;\n this.updateResourceState(resource.id, 'error', toResourceErrorInfo(error));\n throw loadError;\n }\n }\n\n /**\n * Fetch resource as blob (for images, json, etc.)\n */\n private async fetchBlob(uri: string, signal: AbortSignal): Promise<Blob> {\n const response = await fetch(uri, { signal });\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n return response.blob();\n }\n\n private updateResourceState(\n resourceId: string,\n state: Resource['state'],\n error?: Resource['error']\n ): void {\n const resource = this.model?.resources.get(resourceId);\n if (resource) {\n const oldState = resource.state;\n resource.state = state;\n if (state === 'error') {\n resource.error = error;\n } else {\n // Clear stale error info on non-error transitions (new attempt / recovered)\n resource.error = undefined;\n }\n this.eventBus?.emit(MeframeEvent.ResourceStageChange, {\n type: MeframeEvent.ResourceStageChange,\n resourceId,\n oldState,\n newState: state,\n });\n }\n\n this.onStateChange?.(resourceId, state);\n }\n\n private updateLoadStage(\n resourceId: string,\n state: Resource['state'],\n error?: Resource['error']\n ): void {\n const resource = this.model?.resources.get(resourceId);\n console.info(\n '[updateLoadStage] state:',\n state,\n 'resourceId:',\n resourceId,\n 'uri:',\n resource?.uri || ''\n );\n if (state === 'loading') {\n this.eventBus?.emit(MeframeEvent.LoadStart, {\n resourceId,\n url: resource?.uri || '',\n size: 0,\n });\n } else if (state === 'ready') {\n this.eventBus?.emit(MeframeEvent.LoadComplete, {\n resourceId,\n bytes: 0,\n durationMs: 0,\n });\n } else if (state === 'error') {\n this.eventBus?.emit(MeframeEvent.LoadError, {\n resourceId,\n error: new Error(error?.message || 'Unknown error'),\n retry: false,\n });\n }\n }\n\n /**\n * Fetch a resource and wait for loading + parsing to complete\n *\n * Returns a Promise that resolves when:\n * - Resource is fully loaded, parsed, and cached (state='ready')\n * - Or rejects if loading/parsing fails\n *\n * Promise lifecycle:\n * 1. enqueueLoad() creates LoadTask with promise/resolve/reject (or reuses existing)\n * 2. processQueue() → startLoad() executes async in background\n * 3. startLoad() completes → finally → completeTask() → task.resolve()/reject()\n */\n async load(resourceId?: string, options?: ResourceLoadOptions): Promise<void> {\n if (!resourceId) {\n return;\n }\n\n const resource = this.model?.getResource(resourceId);\n if (!resource) {\n const m = this.model;\n console.warn('[ResourceLoader] Resource not found in model:', {\n resourceId,\n options: {\n isPreload: options?.isPreload ?? false,\n sessionId: options?.sessionId,\n clipId: options?.clipId,\n trackId: options?.trackId,\n isMainTrack: options?.isMainTrack,\n },\n model: m\n ? {\n fps: m.fps,\n durationUs: m.durationUs,\n mainTrackId: m.mainTrackId,\n trackCount: m.tracks.length,\n resourcesSize: m.resources.size,\n }\n : null,\n });\n return;\n }\n\n // Terminal error: do not retry automatically. Upstream can decide how to recover (e.g. replace URI).\n if (resource.state === 'error' && resource.error?.terminal === true) {\n return;\n }\n\n const isPreload = options?.isPreload ?? false;\n\n // First check: if resource is already ready, nothing to do\n if (resource.state === 'ready') {\n // NOTE: resource.state is runtime-only and can be stale relative to OPFS/index.\n // During export (or after browser storage eviction), the OPFS file may disappear while\n // the model still marks the resource as 'ready'. For video resources we must validate.\n if (resource.type === 'video') {\n const hasIndex = this.cacheManager.mp4IndexCache.has(resourceId);\n if (hasIndex) {\n const cached = await this.cacheManager.hasResourceInCache(resourceId);\n if (cached) {\n return;\n }\n }\n\n // Force a repair load (OPFS/index missing). Mark back to pending for correctness.\n this.updateResourceState(resourceId, 'pending');\n // Fall through to enqueue a load task.\n } else {\n return;\n }\n }\n\n // Second check: if resource is being loaded\n if (resource.state === 'loading') {\n const existingTask = this.taskManager.getActiveTask(resourceId);\n if (existingTask) {\n // Upgrade preload -> foreground through TaskManager to keep counters correct\n // (do NOT mutate existingTask.isPreload here).\n this.taskManager.enqueue(\n resource,\n isPreload,\n options?.sessionId,\n options?.clipId,\n options?.trackId\n );\n\n // If sessionId matches or no sessionId required, reuse existing task\n if (!options?.sessionId || existingTask.sessionId === options.sessionId) {\n return existingTask.promise;\n }\n }\n }\n\n // Third path: check if already has active task\n const existingTask = this.taskManager.getActiveTask(resourceId);\n if (existingTask) {\n // Upgrade preload -> foreground through TaskManager to keep counters correct\n // (do NOT mutate existingTask.isPreload here).\n this.taskManager.enqueue(\n resource,\n isPreload,\n options?.sessionId,\n options?.clipId,\n options?.trackId\n );\n\n // Reuse existing task\n return existingTask.promise;\n }\n\n // Create new task\n const task = this.enqueueLoad(\n resource,\n isPreload,\n options?.sessionId,\n options?.clipId,\n options?.trackId\n );\n\n // Wait for task completion\n return task.promise;\n }\n\n cancel(resourceId: string): void {\n this.taskManager.cancelTask(resourceId);\n this.processQueue();\n }\n\n /**\n * Check if a resource is currently being loaded\n */\n isResourceLoading(resourceId: string): boolean {\n return this.taskManager.hasActiveTask(resourceId);\n }\n\n pause(resourceId: string): void {\n const task = this.taskManager.getActiveTask(resourceId);\n if (task) {\n task.controller?.abort();\n }\n }\n\n async resume(resourceId: string, options?: ResourceLoadOptions): Promise<void> {\n const resource = this.model?.getResource(resourceId);\n if (!resource) {\n throw new Error(`Resource ${resourceId} not found`);\n }\n\n const pausedTask = this.taskManager.getActiveTask(resourceId);\n\n if (pausedTask?.pausedAt !== undefined) {\n this.enqueueLoad(\n resource,\n options?.isPreload ?? false,\n options?.sessionId,\n options?.clipId,\n options?.trackId\n );\n } else {\n await this.load(resourceId, options);\n }\n }\n\n get activeTasks(): Map<string, LoadTask> {\n return this.taskManager.activeTasks;\n }\n\n get taskQueue(): LoadTask[] {\n return this.taskManager.taskQueue;\n }\n\n dispose(): void {\n this.taskManager.clear();\n this.blobCache.clear();\n }\n\n /**\n * Check if a clip needs cover extraction (first GOP decode)\n * Only clips starting at time 0 need fast cover rendering\n */\n private shouldExtractCover(clipId: string): boolean {\n if (!this.model) return false;\n\n const clip = this.model.findClip(clipId);\n return clip?.startUs === 0;\n }\n}\n"],"names":["existingTask"],"mappings":";;;;;;;;AAqCO,MAAM,eAAe;AAAA,EAClB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,gCAAgB,IAAA;AAAA,EAChB,qCAAqB,IAAA;AAAA;AAAA,EACrB,uCAAuB,IAAA;AAAA;AAAA;AAAA,EAGvB,sBAAsB;AAAA,EAE9B,YAAY,SAAgC;AAC1C,UAAM,SAAS,QAAQ,UAAU,CAAA;AACjC,UAAM,gBAAgB,OAAO,iBAAiB;AAC9C,UAAM,qBAAqB,OAAO,sBAAsB;AAExD,SAAK,cAAc,IAAI,YAAY,eAAe,kBAAkB;AACpE,SAAK,gBAAgB,IAAI,cAAc,QAAQ,YAAY,MAAM;AACjE,SAAK,WAAW,QAAQ;AACxB,SAAK,aAAa,QAAQ;AAC1B,SAAK,gBAAgB,QAAQ;AAC7B,SAAK,eAAe,QAAQ;AAAA,EAC9B;AAAA,EAEA,MAAM,SAAS,OAAwC;AAGrD,SAAK,QAAQ;AACb,UAAM,YAAY,MAAM,OAAO;AAAA,MAC7B,CAAC,UAAU,MAAM,SAAS,WAAW,MAAM,QAAQ,MAAM,eAAe;AAAA,IAAA;AAE1E,QAAI,WAAW,QAAQ,CAAC,KAAK,cAAc,UAAU,MAAM,CAAC,CAAC,GAAG;AAC9D,UAAI;AACF,cAAM,KAAK,KAAK,UAAU,MAAM,CAAC,EAAE,YAAY;AAAA,UAC7C,WAAW;AAAA,UACX,QAAQ,UAAU,MAAM,CAAC,EAAE;AAAA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KA,kBAAkB,YAA6B;AAC7C,WAAO,KAAK,YAAY,cAAc,UAAU;AAAA,EAClD;AAAA,EAEA,MAAM,YAA0B;AAC9B,UAAM,OAAO,KAAK,YAAY,cAAc,UAAU;AACtD,QAAI,MAAM;AACR,WAAK,YAAY,MAAA;AAAA,IACnB;AAAA,EACF;AAAA,EAEA,MAAM,OAAO,YAAoB,SAA8C;AAC7E,UAAM,WAAW,KAAK,OAAO,YAAY,UAAU;AACnD,QAAI,CAAC,UAAU;AACb,YAAM,IAAI,MAAM,YAAY,UAAU,YAAY;AAAA,IACpD;AAEA,UAAM,aAAa,KAAK,YAAY,cAAc,UAAU;AAE5D,QAAI,YAAY,aAAa,QAAW;AACtC,WAAK;AAAA,QACH;AAAA,QACA,SAAS,aAAa;AAAA,QACtB,SAAS;AAAA,QACT,SAAS;AAAA,QACT,SAAS;AAAA,MAAA;AAAA,IAEb,OAAO;AACL,YAAM,KAAK,KAAK,YAAY,OAAO;AAAA,IACrC;AAAA,EACF;AAAA,EAEA,IAAI,cAAqC;AACvC,WAAO,KAAK,YAAY;AAAA,EAC1B;AAAA,EAEA,IAAI,YAAwB;AAC1B,WAAO,KAAK,YAAY;AAAA,EAC1B;AAAA,EAEA,UAAgB;AACd,SAAK,YAAY,MAAA;AACjB,SAAK,UAAU,MAAA;AAAA,EACjB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMQ,mBAAmB,QAAyB;AAClD,QAAI,CAAC,KAAK,MAAO,QAAO;AAExB,UAAM,OAAO,KAAK,MAAM,SAAS,MAAM;AACvC,WAAO,MAAM,YAAY;AAAA,EAC3B;AACF;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@meframe/core",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.21",
|
|
4
4
|
"description": "Next generation media processing framework based on WebCodecs",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -43,6 +43,27 @@
|
|
|
43
43
|
"LICENSE",
|
|
44
44
|
"CHANGELOG.md"
|
|
45
45
|
],
|
|
46
|
+
"scripts": {
|
|
47
|
+
"dev": "vite",
|
|
48
|
+
"build": "tsc && vite build && pnpm build:workers && pnpm build:node-cjs",
|
|
49
|
+
"build:workers": "vite build --config vite.worker.config.ts && node scripts/generate-worker-manifest.js",
|
|
50
|
+
"build:node-cjs": "node scripts/generate-node-cjs.js",
|
|
51
|
+
"preview": "vite preview",
|
|
52
|
+
"prepublishOnly": "npm run lint && npm run type-check && npm run build",
|
|
53
|
+
"test": "vitest run",
|
|
54
|
+
"test:watch": "vitest",
|
|
55
|
+
"test:coverage": "vitest run --coverage",
|
|
56
|
+
"test:ui": "vitest --ui",
|
|
57
|
+
"test:integration": "vitest run --config vitest.integration.config.ts",
|
|
58
|
+
"test:e2e": "playwright test --project=chromium",
|
|
59
|
+
"test:e2e:ui": "playwright test --project=chromium --ui",
|
|
60
|
+
"test:e2e:debug": "playwright test --project=chromium --debug",
|
|
61
|
+
"lint": "eslint src --ignore-pattern '**/__tests__' --ignore-pattern '**/*.test.ts' --ignore-pattern '**/*.spec.ts' --ignore-pattern '**/*.worker.ts'",
|
|
62
|
+
"lint:fix": "eslint src --fix --ignore-pattern '**/__tests__' --ignore-pattern '**/*.test.ts' --ignore-pattern '**/*.spec.ts' --ignore-pattern '**/*.worker.ts'",
|
|
63
|
+
"type-check": "tsc --noEmit",
|
|
64
|
+
"clean": "rm -rf dist coverage",
|
|
65
|
+
"playwright:install": "playwright install chromium"
|
|
66
|
+
},
|
|
46
67
|
"dependencies": {
|
|
47
68
|
"mp4-muxer": "^5.2.2",
|
|
48
69
|
"mp4box": "^0.5.2",
|
|
@@ -95,25 +116,5 @@
|
|
|
95
116
|
"publishConfig": {
|
|
96
117
|
"access": "public",
|
|
97
118
|
"registry": "https://registry.npmjs.org/"
|
|
98
|
-
},
|
|
99
|
-
"scripts": {
|
|
100
|
-
"dev": "vite",
|
|
101
|
-
"build": "tsc && vite build && pnpm build:workers && pnpm build:node-cjs",
|
|
102
|
-
"build:workers": "vite build --config vite.worker.config.ts && node scripts/generate-worker-manifest.js",
|
|
103
|
-
"build:node-cjs": "node scripts/generate-node-cjs.js",
|
|
104
|
-
"preview": "vite preview",
|
|
105
|
-
"test": "vitest run",
|
|
106
|
-
"test:watch": "vitest",
|
|
107
|
-
"test:coverage": "vitest run --coverage",
|
|
108
|
-
"test:ui": "vitest --ui",
|
|
109
|
-
"test:integration": "vitest run --config vitest.integration.config.ts",
|
|
110
|
-
"test:e2e": "playwright test --project=chromium",
|
|
111
|
-
"test:e2e:ui": "playwright test --project=chromium --ui",
|
|
112
|
-
"test:e2e:debug": "playwright test --project=chromium --debug",
|
|
113
|
-
"lint": "eslint src --ignore-pattern '**/__tests__' --ignore-pattern '**/*.test.ts' --ignore-pattern '**/*.spec.ts' --ignore-pattern '**/*.worker.ts'",
|
|
114
|
-
"lint:fix": "eslint src --fix --ignore-pattern '**/__tests__' --ignore-pattern '**/*.test.ts' --ignore-pattern '**/*.spec.ts' --ignore-pattern '**/*.worker.ts'",
|
|
115
|
-
"type-check": "tsc --noEmit",
|
|
116
|
-
"clean": "rm -rf dist coverage",
|
|
117
|
-
"playwright:install": "playwright install chromium"
|
|
118
119
|
}
|
|
119
|
-
}
|
|
120
|
+
}
|