@meframe/core 0.6.11 → 0.6.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/orchestrator/AudioWindowPreparer.d.ts +3 -0
- package/dist/orchestrator/AudioWindowPreparer.d.ts.map +1 -1
- package/dist/orchestrator/AudioWindowPreparer.js +34 -2
- package/dist/orchestrator/AudioWindowPreparer.js.map +1 -1
- package/dist/orchestrator/aac-window-timeline.d.ts +12 -0
- package/dist/orchestrator/aac-window-timeline.d.ts.map +1 -0
- package/dist/orchestrator/aac-window-timeline.js +75 -0
- package/dist/orchestrator/aac-window-timeline.js.map +1 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.6.12] - 2026-10-15
|
|
11
|
+
|
|
12
|
+
### Fixed
|
|
13
|
+
|
|
14
|
+
- Measure anomalously stretched AAC prefix duration and select bounded audio windows on the decoded PCM timeline. Fragmented MP4 audio now covers a two-second export and cold seeks retain synthesis preroll; missing interior packets still fail the PCM coverage guard (issue #30).
|
|
15
|
+
|
|
10
16
|
## [0.6.11] - 2026-10-13
|
|
11
17
|
|
|
12
18
|
### Added
|
package/dist/index.d.ts
CHANGED
|
@@ -16,5 +16,5 @@ export { ResourceNotCachedError, ResourceCorruptedError, ResourceSupersededError
|
|
|
16
16
|
export type { EnsureResourceCachedContext, EnsureResourceCachedHandler, ResourceCacheAdapters, ResourceNetworkPolicy, VideoParseStreamHandler, } from './stages/load/types';
|
|
17
17
|
export { BrowserCompatibilityError } from './utils/errors';
|
|
18
18
|
export type { MeframeOpfsGateway } from './cache/storage/opfs/gateway';
|
|
19
|
-
export declare const VERSION = "0.
|
|
19
|
+
export declare const VERSION = "0.6.12";
|
|
20
20
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,YAAY,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAC3D,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAG9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC5D,YAAY,EACV,oBAAoB,EACpB,gBAAgB,EAChB,UAAU,EACV,MAAM,EACN,KAAK,EACL,IAAI,EACJ,SAAS,EACT,SAAS,EACT,WAAW,EACX,QAAQ,EACR,MAAM,EACN,UAAU,EACV,UAAU,EACV,eAAe,EACf,iBAAiB,EACjB,WAAW,GACZ,MAAM,eAAe,CAAC;AAGvB,YAAY,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAG7D,YAAY,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAG1D,OAAO,EAAE,oBAAoB,EAAE,MAAM,4CAA4C,CAAC;AAClF,YAAY,EACV,kBAAkB,EAClB,aAAa,EACb,WAAW,EACX,WAAW,EACX,YAAY,EACZ,gBAAgB,GACjB,MAAM,4CAA4C,CAAC;AAGpD,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACzF,OAAO,EACL,sBAAsB,EACtB,sBAAsB,EACtB,uBAAuB,GACxB,MAAM,gBAAgB,CAAC;AACxB,YAAY,EACV,2BAA2B,EAC3B,2BAA2B,EAC3B,qBAAqB,EACrB,qBAAqB,EACrB,uBAAuB,GACxB,MAAM,qBAAqB,CAAC;AAE7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E,yBAAyB,EAAE,MAAM,gBAAgB,CAAC;AAC3D,YAAY,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAGvE,eAAO,MAAM,OAAO,WAAW,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -4,7 +4,7 @@ import { CompositionModel } from "./model/CompositionModel.js";
|
|
|
4
4
|
import { computeCaptionLayout } from "./stages/compose/text-utils/caption-layout.js";
|
|
5
5
|
import { checkCanvasDPI, createHiDPICanvas, setupCanvasDPI } from "./utils/canvas-utils.js";
|
|
6
6
|
import { BrowserCompatibilityError, ResourceCorruptedError, ResourceNotCachedError, ResourceSupersededError } from "./utils/errors.js";
|
|
7
|
-
const VERSION = "0.
|
|
7
|
+
const VERSION = "0.6.12";
|
|
8
8
|
export {
|
|
9
9
|
BrowserCompatibilityError,
|
|
10
10
|
CompositionModel,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["/**\n * @meframe/core - Next generation media processing framework\n * Based on WebCodecs API for high-performance video/audio processing\n */\n\n// Core exports\nexport { Meframe } from './Meframe';\nexport type { MeframeConfig, MeframeState } from './types';\nexport { MeframeEvent } from './event/events';\n\n// Model exports\nexport { CompositionModel } from './model/CompositionModel';\nexport type {\n CompositionModelData,\n CompositionPatch,\n DirtyRange,\n TimeUs,\n Track,\n Clip,\n VideoClip,\n AudioClip,\n CaptionClip,\n Resource,\n Effect,\n Transition,\n Attachment,\n AnimationEffect,\n AnimationKeyframe,\n Transform2D,\n} from './model/types';\n\n// Cache exports\nexport type { CacheConfig, CacheStats } from './cache/types';\n\n// Plugin exports\nexport type { Plugin, PluginHook } from './plugins/types';\n\n// Caption layout exports\nexport { computeCaptionLayout } from './stages/compose/text-utils/caption-layout';\nexport type {\n CaptionLayoutInput,\n CaptionLayout,\n CaptionLine,\n CaptionWord,\n CaptionStyle,\n CaptionContainer,\n} from './stages/compose/text-utils/caption-layout';\n\n// Utility exports\nexport { setupCanvasDPI, createHiDPICanvas, checkCanvasDPI } from './utils/canvas-utils';\nexport {\n ResourceNotCachedError,\n ResourceCorruptedError,\n ResourceSupersededError,\n} from './utils/errors';\nexport type {\n EnsureResourceCachedContext,\n EnsureResourceCachedHandler,\n ResourceCacheAdapters,\n ResourceNetworkPolicy,\n VideoParseStreamHandler,\n} from './stages/load/types';\n\nexport { BrowserCompatibilityError } from './utils/errors';\nexport type { MeframeOpfsGateway } from './cache/storage/opfs/gateway';\n\n// Re-export version\nexport const VERSION = '0.
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["/**\n * @meframe/core - Next generation media processing framework\n * Based on WebCodecs API for high-performance video/audio processing\n */\n\n// Core exports\nexport { Meframe } from './Meframe';\nexport type { MeframeConfig, MeframeState } from './types';\nexport { MeframeEvent } from './event/events';\n\n// Model exports\nexport { CompositionModel } from './model/CompositionModel';\nexport type {\n CompositionModelData,\n CompositionPatch,\n DirtyRange,\n TimeUs,\n Track,\n Clip,\n VideoClip,\n AudioClip,\n CaptionClip,\n Resource,\n Effect,\n Transition,\n Attachment,\n AnimationEffect,\n AnimationKeyframe,\n Transform2D,\n} from './model/types';\n\n// Cache exports\nexport type { CacheConfig, CacheStats } from './cache/types';\n\n// Plugin exports\nexport type { Plugin, PluginHook } from './plugins/types';\n\n// Caption layout exports\nexport { computeCaptionLayout } from './stages/compose/text-utils/caption-layout';\nexport type {\n CaptionLayoutInput,\n CaptionLayout,\n CaptionLine,\n CaptionWord,\n CaptionStyle,\n CaptionContainer,\n} from './stages/compose/text-utils/caption-layout';\n\n// Utility exports\nexport { setupCanvasDPI, createHiDPICanvas, checkCanvasDPI } from './utils/canvas-utils';\nexport {\n ResourceNotCachedError,\n ResourceCorruptedError,\n ResourceSupersededError,\n} from './utils/errors';\nexport type {\n EnsureResourceCachedContext,\n EnsureResourceCachedHandler,\n ResourceCacheAdapters,\n ResourceNetworkPolicy,\n VideoParseStreamHandler,\n} from './stages/load/types';\n\nexport { BrowserCompatibilityError } from './utils/errors';\nexport type { MeframeOpfsGateway } from './cache/storage/opfs/gateway';\n\n// Re-export version\nexport const VERSION = '0.6.12';\n"],"names":[],"mappings":";;;;;;AAmEO,MAAM,UAAU;"}
|
|
@@ -6,6 +6,7 @@ import { EventPayloadMap } from '../event/events';
|
|
|
6
6
|
import { CacheManager } from '../cache/CacheManager';
|
|
7
7
|
import { AudioSampleRecord } from '../cache/resource/AudioSampleCache';
|
|
8
8
|
import { RequestMode } from './types';
|
|
9
|
+
import { AACWindowTimeline } from './aac-window-timeline';
|
|
9
10
|
|
|
10
11
|
interface AudioWindowPreparerDeps {
|
|
11
12
|
cacheManager: CacheManager;
|
|
@@ -21,6 +22,7 @@ export interface AudioSourceSnapshot {
|
|
|
21
22
|
export interface PreparedAudioSource extends AudioSourceSnapshot {
|
|
22
23
|
record: AudioSampleRecord;
|
|
23
24
|
cacheKey: string;
|
|
25
|
+
aacTimeline?: AACWindowTimeline;
|
|
24
26
|
}
|
|
25
27
|
export type AudioPCM = {
|
|
26
28
|
planes: Float32Array[];
|
|
@@ -39,6 +41,7 @@ export declare class AudioWindowPreparer {
|
|
|
39
41
|
private decoding;
|
|
40
42
|
private recordIds;
|
|
41
43
|
private nextRecordId;
|
|
44
|
+
private aacTimelines;
|
|
42
45
|
private lifecycle;
|
|
43
46
|
get generation(): number;
|
|
44
47
|
getStats(): {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AudioWindowPreparer.d.ts","sourceRoot":"","sources":["../../src/orchestrator/AudioWindowPreparer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAC7D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AACjD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AACpE,OAAO,KAAK,EAAE,QAAQ,EAAE,M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C;IAqEP,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;gBAIhB,IAAI,EAAE,uBAAuB;IAIzC,QAAQ,CAAC,KAAK,EAAE,gBAAgB,GAAG,IAAI,GAAG,IAAI;IAK9C,QAAQ,IAAI,gBAAgB,GAAG,IAAI;IAInC,KAAK,IAAI,IAAI;IAMb,6CAA6C;IAC7C,oBAAoB,IAAI,WAAW,CAAC,MAAM,CAAC;IAI3C;;;;;;;OAOG;IACH,0BAA0B,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO;IAmB7D,qBAAqB,IAAI,OAAO,CAAC,IAAI,CAAC;IAwDtC,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IASnD;;OAEG;IACG,uBAAuB,CAC3B,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,MAAM,EACb,OAAO,EAAE;QAAE,IAAI,CAAC,EAAE,WAAW,CAAC;QAAC,YAAY,CAAC,EAAE,OAAO,CAAC;QAAC,UAAU,CAAC,EAAE,OAAO,CAAA;KAAE,GAC5E,OAAO,CAAC,IAAI,CAAC;IAiIhB;;OAEG;IACG,iBAAiB,CACrB,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,MAAM,EACb,UAAU,GAAE,OAAe,GAC1B,OAAO,CAAC,IAAI,CAAC;IAiBhB;;OAEG;YACW,iBAAiB;YAgIjB,eAAe;IAqF7B,mFAAmF;IACnF,OAAO,CAAC,eAAe;IAgBvB;;;OAGG;YACW,mBAAmB;IAgBjC;;OAEG;YACW,kBAAkB;IA2GhC;;;;OAIG;IACH,OAAO,CAAC,gBAAgB;CAqBzB"}
|
|
@@ -4,6 +4,7 @@ import { decodeWavPCM } from "../stages/demux/WAVIndexParser.js";
|
|
|
4
4
|
import { hasResourceId, isAudioClip, clipPlaybackRate } from "../model/types.js";
|
|
5
5
|
import { buildLoopedResourceSegments } from "../utils/loop-utils.js";
|
|
6
6
|
import { isTerminalMediaResourceError } from "../utils/errors.js";
|
|
7
|
+
import { prepareAACTimeline, getAACWindow } from "./aac-window-timeline.js";
|
|
7
8
|
class AudioWindowPreparer {
|
|
8
9
|
activeClips = /* @__PURE__ */ new Set();
|
|
9
10
|
/** 解码确定失败的 clip(坏包等):本会话不再重试,避免重试风暴;reset 清空 */
|
|
@@ -16,6 +17,7 @@ class AudioWindowPreparer {
|
|
|
16
17
|
decoding = 0;
|
|
17
18
|
recordIds = /* @__PURE__ */ new WeakMap();
|
|
18
19
|
nextRecordId = 0;
|
|
20
|
+
aacTimelines = /* @__PURE__ */ new WeakMap();
|
|
19
21
|
lifecycle = new AbortController();
|
|
20
22
|
get generation() {
|
|
21
23
|
return this.revision;
|
|
@@ -77,7 +79,37 @@ class AudioWindowPreparer {
|
|
|
77
79
|
}
|
|
78
80
|
const cacheKey = JSON.stringify([resource.id, resource.uri, recordId]);
|
|
79
81
|
this.deps.cacheManager.setAudioSource(clip.id, cacheKey);
|
|
80
|
-
|
|
82
|
+
let pendingTimeline = this.aacTimelines.get(record);
|
|
83
|
+
if (!pendingTimeline) {
|
|
84
|
+
pendingTimeline = this.decodeQueue.then(async () => {
|
|
85
|
+
this.decoding++;
|
|
86
|
+
try {
|
|
87
|
+
return await prepareAACTimeline(record);
|
|
88
|
+
} finally {
|
|
89
|
+
this.decoding--;
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
this.decodeQueue = pendingTimeline.then(
|
|
93
|
+
() => void 0,
|
|
94
|
+
() => void 0
|
|
95
|
+
);
|
|
96
|
+
this.aacTimelines.set(record, pendingTimeline);
|
|
97
|
+
}
|
|
98
|
+
let aacTimeline;
|
|
99
|
+
try {
|
|
100
|
+
aacTimeline = await pendingTimeline;
|
|
101
|
+
} catch (error) {
|
|
102
|
+
this.checkCurrent(source);
|
|
103
|
+
await this.handleDecodeFailure(clip.id, error, strictMode);
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
this.checkCurrent(source);
|
|
107
|
+
return {
|
|
108
|
+
...source,
|
|
109
|
+
record: aacTimeline ? { ...record, durationUs: aacTimeline.durationUs } : record,
|
|
110
|
+
cacheKey,
|
|
111
|
+
aacTimeline
|
|
112
|
+
};
|
|
81
113
|
}
|
|
82
114
|
maxReadDurationUs(source) {
|
|
83
115
|
const bytesPerSecond = source.record.metadata.sampleRate * source.record.metadata.numberOfChannels * 4;
|
|
@@ -435,7 +467,7 @@ class AudioWindowPreparer {
|
|
|
435
467
|
);
|
|
436
468
|
return;
|
|
437
469
|
}
|
|
438
|
-
const windowChunks = audioRecord.samples.filter((s) => {
|
|
470
|
+
const windowChunks = source?.aacTimeline ? getAACWindow(audioRecord.samples, source.aacTimeline, startUs, endUs) : audioRecord.samples.filter((s) => {
|
|
439
471
|
const sampleEndUs = s.timestamp + (s.duration ?? 0);
|
|
440
472
|
return s.timestamp < endUs && sampleEndUs > startUs;
|
|
441
473
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AudioWindowPreparer.js","sources":["../../src/orchestrator/AudioWindowPreparer.ts"],"sourcesContent":["import type { Clip, Resource, TimeUs } from '../model/types';\nimport type { CompositionModel } from '../model';\nimport type { ResourceLoader } from '../stages/load/ResourceLoader';\nimport type { EventBus } from '../event/EventBus';\nimport type { EventPayloadMap } from '../event/events';\nimport { MeframeEvent } from '../event/events';\nimport type { CacheManager } from '../cache/CacheManager';\nimport type { AudioSampleRecord } from '../cache/resource/AudioSampleCache';\nimport { AudioChunkDecoder } from '../stages/decode/AudioChunkDecoder';\nimport { decodeWavPCM } from '../stages/demux/WAVIndexParser';\nimport { clipPlaybackRate, isAudioClip, hasResourceId } from '../model/types';\nimport type { RequestMode } from './types';\nimport { buildLoopedResourceSegments } from '../utils/loop-utils';\nimport { isTerminalMediaResourceError } from '../utils/errors';\n\ninterface AudioWindowPreparerDeps {\n cacheManager: CacheManager;\n resourceLoader: ResourceLoader;\n eventBus: EventBus<EventPayloadMap>;\n}\n\nexport interface AudioSourceSnapshot {\n clip: Clip;\n resource: Resource;\n revision: number;\n cacheGeneration: number;\n}\n\nexport interface PreparedAudioSource extends AudioSourceSnapshot {\n record: AudioSampleRecord;\n cacheKey: string;\n}\n\nexport type AudioPCM = { planes: Float32Array[]; sampleRate: number; numberOfChannels: number };\n\nexport class AudioWindowPreparer {\n private activeClips = new Set<string>();\n /** 解码确定失败的 clip(坏包等):本会话不再重试,避免重试风暴;reset 清空 */\n private failedDecodeClips = new Set<string>();\n private deps: AudioWindowPreparerDeps;\n private model: CompositionModel | null = null;\n private revision = 0;\n private decodeQueue: Promise<unknown> = Promise.resolve();\n private pendingReads = 0;\n private decoding = 0;\n private recordIds = new WeakMap<AudioSampleRecord, number>();\n private nextRecordId = 0;\n private lifecycle = new AbortController();\n\n get generation(): number {\n return this.revision;\n }\n\n getStats() {\n return { decoding: this.decoding, pendingReads: this.pendingReads };\n }\n\n invalidate(abortLoads = true): void {\n this.revision++;\n if (abortLoads) {\n this.lifecycle.abort();\n this.lifecycle = new AbortController();\n }\n this.failedDecodeClips.clear();\n this.activeClips.clear();\n }\n\n snapshot(clip: Clip): AudioSourceSnapshot {\n const resource = hasResourceId(clip) ? this.model?.getResource(clip.resourceId) : null;\n if (!resource) throw new Error(`Audio resource missing for clip ${clip.id}`);\n return {\n clip: { ...clip },\n resource: { ...resource },\n revision: this.revision,\n cacheGeneration: this.deps.cacheManager.audioCacheGeneration,\n };\n }\n\n private checkCurrent(source: AudioSourceSnapshot): void {\n if (\n source.revision !== this.revision ||\n source.cacheGeneration !== this.deps.cacheManager.audioCacheGeneration\n ) {\n throw new DOMException('Audio request superseded', 'AbortError');\n }\n }\n\n async prepareSource(\n source: AudioSourceSnapshot,\n strictMode = false\n ): Promise<PreparedAudioSource | null> {\n this.checkCurrent(source);\n const { clip, resource } = source;\n if (resource.state === 'error' && resource.error?.terminal) {\n if (strictMode) throw new Error(`Resource ${resource.id} is in error state`);\n return null;\n }\n if (!this.deps.cacheManager.audioSampleCache.has(resource.id) && resource.state !== 'ready') {\n await this.deps.resourceLoader.load(resource.id, {\n clipId: clip.id,\n trackId: clip.trackId,\n signal: this.lifecycle.signal,\n isPreload: false,\n });\n this.checkCurrent(source);\n }\n const record = this.deps.cacheManager.audioSampleCache.get(resource.id);\n // A parsed video without an audio track is intentionally silent.\n if (!record) {\n if (this.model?.getResource(resource.id)?.state !== 'ready')\n throw new Error(`Audio resource ${resource.id} is not ready`);\n if (resource.type === 'audio') throw new Error(`Audio samples missing for ${resource.id}`);\n return null;\n }\n let recordId = this.recordIds.get(record);\n if (recordId === undefined) {\n recordId = ++this.nextRecordId;\n this.recordIds.set(record, recordId);\n }\n const cacheKey = JSON.stringify([resource.id, resource.uri, recordId]);\n this.deps.cacheManager.setAudioSource(clip.id, cacheKey);\n return { ...source, record, cacheKey };\n }\n\n maxReadDurationUs(source: PreparedAudioSource): number {\n const bytesPerSecond =\n source.record.metadata.sampleRate * source.record.metadata.numberOfChannels * 4;\n // Leave room for whole decoded edge frames plus the contiguous read copy.\n return Math.max(\n 1,\n Math.floor(\n (this.deps.cacheManager.getAudioCacheStats().maxBytes / (3 * bytesPerSecond)) * 1_000_000\n )\n );\n }\n\n /** Decode and consume under one lease. Other readers cannot evict these slots between awaits. */\n async withPCM<T>(\n source: PreparedAudioSource,\n startUs: TimeUs,\n endUs: TimeUs,\n consume: (pcm: AudioPCM | null) => T,\n strictMode = false\n ): Promise<T> {\n this.pendingReads++;\n const run = async () => {\n this.checkCurrent(source);\n const firstUs = source.record.gapless ? 0 : (source.record.samples[0]?.timestamp ?? 0);\n const readStartUs = Math.max(firstUs, startUs);\n const readEndUs = Math.min(endUs, source.record.durationUs);\n if (readEndUs <= readStartUs) return consume(null);\n const bytes =\n Math.ceil(((endUs - startUs) * source.record.metadata.sampleRate) / 1_000_000) *\n source.record.metadata.numberOfChannels *\n 4;\n const lease = this.deps.cacheManager.pinAudioRange(\n source.cacheKey,\n readStartUs,\n readEndUs,\n bytes\n );\n this.decoding++;\n try {\n await this.decodeAudioWindow(source.clip.id, readStartUs, readEndUs, strictMode, source);\n this.checkCurrent(source);\n if (this.failedDecodeClips.has(source.clip.id) && !strictMode) return consume(null);\n const threshold = Math.max(\n 0.5,\n 1 - 1_000_000 / source.record.metadata.sampleRate / (readEndUs - readStartUs)\n );\n if (\n !this.deps.cacheManager.getAudioRangeCoverage(\n source.cacheKey,\n readStartUs,\n readEndUs,\n threshold\n ).covered\n ) {\n throw new Error(\n `Audio PCM unavailable for ${source.clip.id} [${readStartUs}, ${readEndUs})`\n );\n }\n const pcm = lease.read();\n if (!pcm) throw new Error(`Audio PCM unavailable for ${source.clip.id}`);\n // Padding outside the physical audio range is intentional silence.\n if (readStartUs !== startUs || readEndUs !== endUs) {\n const frames = Math.ceil(((endUs - startUs) * pcm.sampleRate) / 1_000_000);\n const offset = Math.round(((readStartUs - startUs) * pcm.sampleRate) / 1_000_000);\n pcm.planes = pcm.planes.map((plane) => {\n const out = new Float32Array(frames);\n out.set(plane.subarray(0, frames - offset), offset);\n return out;\n });\n }\n return consume(pcm);\n } finally {\n this.decoding--;\n lease.release();\n }\n };\n const task = this.decodeQueue.then(run, run);\n this.decodeQueue = task.then(\n () => undefined,\n () => undefined\n );\n try {\n return await task;\n } finally {\n this.pendingReads--;\n }\n }\n\n async drain(): Promise<void> {\n await this.decodeQueue;\n }\n\n constructor(deps: AudioWindowPreparerDeps) {\n this.deps = deps;\n }\n\n setModel(model: CompositionModel | null): void {\n this.invalidate();\n this.model = model;\n }\n\n getModel(): CompositionModel | null {\n return this.model;\n }\n\n reset(): void {\n this.invalidate();\n this.deps.cacheManager.clearAudioCache();\n this.activeClips.clear();\n }\n\n /** 本会话解码确定失败、被静音跳过的 clip 集合(宿主可用于导出报告/提示) */\n getFailedDecodeClips(): ReadonlySet<string> {\n return this.failedDecodeClips;\n }\n\n /**\n * Fast readiness probe for preview playback.\n *\n * This is intentionally synchronous and lightweight:\n * - Only checks resource-level readiness (download + MP4 index parsing).\n * - If any relevant resource isn't ready yet, return false.\n * - Does NOT require audio samples / PCM window coverage (probe is resource-level only).\n */\n isAudioResourceWindowReady(startUs: TimeUs, endUs: TimeUs): boolean {\n const model = this.model;\n if (!model) return true;\n\n const activeClips = model.getActiveClips(startUs, endUs);\n\n for (const clip of activeClips) {\n if (clip.trackKind !== 'audio' && clip.trackKind !== 'video') continue;\n if (!hasResourceId(clip)) continue;\n\n const resource = model.getResource(clip.resourceId);\n if (resource?.state !== 'ready') {\n return false;\n }\n }\n\n return true;\n }\n\n async activateAllAudioClips(): Promise<void> {\n const model = this.model;\n const revision = this.revision;\n if (!model) {\n return;\n }\n\n const audioTracks = model.tracks.filter((track) => track.kind === 'audio');\n if (audioTracks.length === 0) return;\n\n // Find maximum clip count across all audio tracks\n const maxClipCount = Math.max(...audioTracks.map((track) => track.clips.length));\n\n // Horizontal loading: activate clip[0] from all tracks, then clip[1], etc.\n for (let clipIndex = 0; clipIndex < maxClipCount; clipIndex++) {\n for (const track of audioTracks) {\n if (revision !== this.revision) return;\n const clip = track.clips[clipIndex];\n if (!clip || this.activeClips.has(clip.id)) continue;\n\n if (!isAudioClip(clip)) {\n throw new Error(`Clip ${clip.id} in audio track is not an audio clip`);\n }\n\n // Preview: Use main-thread parsing → AudioSampleCache → on-demand decode\n // Check if we have cached samples (already parsed in ResourceLoader)\n if (this.deps.cacheManager.audioSampleCache.has(clip.resourceId)) {\n // Already parsed, mark as active\n this.activeClips.add(clip.id);\n this.deps.eventBus.emit(MeframeEvent.ClipActivated, { clipId: clip.id });\n continue;\n }\n\n // Ensure resource is loaded (will be parsed and cached in main thread)\n try {\n await this.deps.resourceLoader.load(clip.resourceId, {\n isPreload: false,\n clipId: clip.id,\n trackId: track.id,\n });\n } catch (error) {\n // Preview should not be blocked by a single bad audio resource.\n if (isTerminalMediaResourceError(error)) {\n continue;\n }\n throw error;\n }\n\n if (revision !== this.revision) return;\n // Mark as active\n this.activeClips.add(clip.id);\n this.deps.eventBus.emit(MeframeEvent.ClipActivated, { clipId: clip.id });\n }\n }\n }\n\n async deactivateClip(clipId: string): Promise<void> {\n if (!this.activeClips.has(clipId)) {\n return;\n }\n\n this.activeClips.delete(clipId);\n this.deps.cacheManager.clearClipAudioData(clipId);\n }\n\n /**\n * Core method to ensure audio for all clips in a time range\n */\n async ensureAudioForTimeRange(\n startUs: TimeUs,\n endUs: TimeUs,\n options: { mode?: RequestMode; loadResource?: boolean; strictMode?: boolean }\n ): Promise<void> {\n const model = this.model;\n if (!model) return;\n\n const revision = this.revision;\n const cacheGeneration = this.deps.cacheManager.audioCacheGeneration;\n const { mode = 'blocking', loadResource = true, strictMode = false } = options;\n\n // Find all clips that overlap with [startUs, endUs]\n const activeClips = model.getActiveClips(startUs, endUs);\n\n const ensurePromises = activeClips.map(async (clip) => {\n // Only process audio and video clips.\n // Note: video clips may carry an embedded audio track; preview should include them as well.\n if (clip.trackKind !== 'audio' && clip.trackKind !== 'video') return;\n if (!hasResourceId(clip)) return;\n\n // Skip muted/zero-volume clips early; they should not block preview or export.\n const muted = clip.audioConfig?.muted ?? false;\n const volume = clip.audioConfig?.volume ?? 1.0;\n if (muted || volume <= 0) {\n return;\n }\n\n const resource = model.getResource(clip.resourceId);\n\n // Terminal error state: for preview (strictMode=false) skip; for export (strictMode=true) fail fast.\n if (resource?.state === 'error' && resource.error?.terminal === true) {\n if (strictMode) {\n throw new Error(`Resource ${clip.resourceId} is in error state`);\n }\n return;\n }\n\n // Skip clips without audio track (performance optimization)\n // If AudioSampleCache doesn't have this resource, and resource is ready,\n // it means the resource has no audio track (e.g., video-only or image)\n if (\n resource?.state === 'ready' &&\n !this.deps.cacheManager.audioSampleCache.has(clip.resourceId)\n ) {\n // Resource is ready but has no audio samples - skip\n return;\n }\n\n // Ensure AudioSampleCache has data\n if (!this.deps.cacheManager.audioSampleCache.has(clip.resourceId)) {\n if (!loadResource) {\n // Export mode: skip clips without cached samples\n return;\n }\n\n if (resource?.state !== 'ready') {\n // Resource not yet loaded - wait for it\n try {\n await this.deps.resourceLoader.load(clip.resourceId, {\n isPreload: false,\n clipId: clip.id,\n trackId: clip.trackId,\n });\n } catch (error) {\n if (isTerminalMediaResourceError(error)) {\n if (strictMode) {\n throw error;\n }\n return;\n }\n throw error;\n }\n }\n }\n\n if (\n revision !== this.revision ||\n cacheGeneration !== this.deps.cacheManager.audioCacheGeneration\n )\n return;\n\n // Calculate clip-relative time range\n const clipRelativeStartUs = Math.max(0, startUs - clip.startUs);\n const clipRelativeEndUs = Math.min(clip.durationUs, endUs - clip.startUs);\n\n // Convert to resource time (aligned with video architecture)\n const trimStartUs = clip.trimStartUs ?? 0;\n const loop = clip.trackKind === 'audio' && clip.loop === true;\n const playbackRate = clipPlaybackRate(clip);\n const audioRecord = this.deps.cacheManager.audioSampleCache.get(clip.resourceId) as {\n durationUs: TimeUs;\n } | null;\n const resourceDurationUs = audioRecord?.durationUs ?? 0;\n\n let segments = buildLoopedResourceSegments({\n clipRelativeStartUs,\n clipRelativeEndUs,\n trimStartUs,\n resourceDurationUs,\n loop,\n playbackRate,\n });\n if (segments.length === 0 && clipRelativeEndUs > clipRelativeStartUs) {\n // Fallback to non-loop mapping when resource duration isn't available yet.\n segments = buildLoopedResourceSegments({\n clipRelativeStartUs,\n clipRelativeEndUs,\n trimStartUs,\n resourceDurationUs,\n loop: false,\n playbackRate,\n });\n }\n\n // Ensure audio window using resource time coordinates\n for (const seg of segments) {\n if (\n revision !== this.revision ||\n cacheGeneration !== this.deps.cacheManager.audioCacheGeneration\n )\n return;\n await this.ensureAudioWindow(clip.id, seg.resourceStartUs, seg.resourceEndUs, strictMode);\n }\n });\n\n if (mode === 'probe') {\n void Promise.all(ensurePromises).catch(() => {});\n return;\n }\n await Promise.all(ensurePromises);\n }\n\n /**\n * Ensure audio window for a clip\n */\n async ensureAudioWindow(\n clipId: string,\n startUs: TimeUs,\n endUs: TimeUs,\n strictMode: boolean = false\n ): Promise<void> {\n const clip = this.model?.findClip(clipId);\n if (!clip || !hasResourceId(clip)) return;\n const source = await this.prepareSource(this.snapshot(clip), strictMode);\n if (!source) return;\n const step = this.maxReadDurationUs(source);\n for (let cursor = startUs; cursor < endUs; cursor += step) {\n await this.withPCM(\n source,\n cursor,\n Math.min(endUs, cursor + step),\n () => undefined,\n strictMode\n );\n }\n }\n\n /**\n * Decode audio window for a clip\n */\n private async decodeAudioWindow(\n clipId: string,\n startUs: TimeUs,\n endUs: TimeUs,\n strictMode: boolean = false,\n source?: PreparedAudioSource\n ): Promise<void> {\n if (source) this.checkCurrent(source);\n if (this.failedDecodeClips.has(clipId)) {\n // deterministic decode failure earlier this session - don't retry.\n // 导出模式同样必须失败:不能带着\"已知坏了的音频\"继续出片。\n if (strictMode) {\n throw new Error(\n `Audio decode failed earlier for clip ${clipId}; export refused to ship silent audio`\n );\n }\n return;\n }\n if (source) {\n const threshold = Math.max(\n 0.5,\n 1 - 1_000_000 / source.record.metadata.sampleRate / Math.max(1, endUs - startUs)\n );\n if (\n this.deps.cacheManager.getAudioRangeCoverage(source.cacheKey, startUs, endUs, threshold)\n .covered\n )\n return;\n }\n const clip = source?.clip ?? this.model?.findClip(clipId);\n if (!clip || !hasResourceId(clip)) {\n return;\n }\n\n // Get audio samples from AudioSampleCache\n const audioRecord =\n source?.record ?? this.deps.cacheManager.audioSampleCache.get(clip.resourceId);\n if (!audioRecord) {\n // Resource has no audio track (common for some video files)\n return;\n }\n\n if (audioRecord.pcm) {\n try {\n await this.decodeWavWindow(\n clipId,\n audioRecord,\n startUs,\n endUs,\n clip.durationUs,\n clip.startUs,\n source\n );\n } catch (error) {\n if (source) this.checkCurrent(source);\n if (error instanceof RangeError) throw error;\n await this.handleDecodeFailure(clipId, error, strictMode);\n }\n return;\n }\n\n if (audioRecord.gapless) {\n // MP3 windows must stay contiguous, including cached chunks: reservoir and\n // synthesis state cannot survive holes in an incremental decode stream.\n const { skipSamples, trimEndSamples, samplesPerFrame } = audioRecord.gapless;\n const sampleRate = audioRecord.metadata.sampleRate;\n const validStart = Math.max(\n skipSamples,\n Math.ceil((startUs * sampleRate) / 1_000_000) + skipSamples\n );\n const validEnd = Math.min(\n audioRecord.samples.length * samplesPerFrame - trimEndSamples,\n Math.ceil((endUs * sampleRate) / 1_000_000) + skipSamples\n );\n if (validEnd <= validStart) return;\n const first = Math.floor(validStart / samplesPerFrame);\n const last = Math.ceil(validEnd / samplesPerFrame);\n const decodeStart = this.mp3PrerollStart(audioRecord, first);\n await this.decodeAudioSamples(\n clipId,\n audioRecord.samples.slice(decodeStart, last),\n audioRecord.metadata,\n clip.durationUs,\n clip.startUs,\n strictMode,\n {\n skipSamples,\n sampleRate,\n // Cache stable whole-frame slots so overlapping requests cannot leave partial holes.\n validStart: Math.max(skipSamples, first * samplesPerFrame),\n validEnd: Math.min(\n audioRecord.samples.length * samplesPerFrame - trimEndSamples,\n last * samplesPerFrame\n ),\n physicalStart: decodeStart * samplesPerFrame,\n },\n source\n );\n return;\n }\n\n // Filter chunks within window (aligned with video GOP filtering)\n const windowChunks = audioRecord.samples.filter((s) => {\n const sampleEndUs = s.timestamp + (s.duration ?? 0);\n return s.timestamp < endUs && sampleEndUs > startUs;\n });\n\n if (windowChunks.length === 0) {\n return;\n }\n\n // AAC decoders maintain a continuous output clock within one stream. Skipping\n // cached chunks can move later outputs onto earlier PTS and leave cache holes.\n // Decode the bounded window contiguously; the cache deduplicates existing slots.\n await this.decodeAudioSamples(\n clipId,\n windowChunks,\n audioRecord.metadata,\n clip.durationUs,\n clip.startUs,\n strictMode,\n undefined,\n source\n );\n }\n\n private async decodeWavWindow(\n clipId: string,\n record: AudioSampleRecord,\n startUs: TimeUs,\n endUs: TimeUs,\n clipDurationUs: TimeUs,\n clipStartUs: TimeUs,\n source?: PreparedAudioSource\n ): Promise<void> {\n const index = record.pcm!;\n const first = Math.max(0, Math.floor((startUs * index.sampleRate) / 1_000_000));\n const last = Math.min(index.numberOfFrames, Math.ceil((endUs * index.sampleRate) / 1_000_000));\n // Stable slots avoid overlapping seek windows pinning duplicate PCM. Edge\n // slots consume at most 1/8 of the budget, alongside the reserved read copy.\n const blockFrames = Math.max(\n 1,\n Math.min(\n 2048,\n Math.floor(\n this.deps.cacheManager.getAudioCacheStats().maxBytes / (16 * index.numberOfChannels * 4)\n )\n )\n );\n // Coalesce adjacent misses, retaining a bounded raw read in addition to L1.\n const maxReadBytes = Math.max(\n blockFrames * index.blockAlign,\n Math.min(256 * 1024, Math.floor(this.deps.cacheManager.getAudioCacheStats().maxBytes / 8))\n );\n const batchFrames =\n blockFrames * Math.max(1, Math.floor(maxReadBytes / (blockFrames * index.blockAlign)));\n const cacheKey = source?.cacheKey ?? clipId;\n const covered = (frame: number) =>\n this.deps.cacheManager.getAudioRangeCoverage(\n cacheKey,\n Math.round((frame * 1_000_000) / index.sampleRate),\n Math.round(\n (Math.min(index.numberOfFrames, frame + blockFrames) * 1_000_000) / index.sampleRate\n ),\n 0.99\n ).covered;\n for (let frame = Math.floor(first / blockFrames) * blockFrames; frame < last;) {\n if (source) this.checkCurrent(source);\n if (covered(frame)) {\n frame += blockFrames;\n continue;\n }\n let batchEnd = Math.min(index.numberOfFrames, frame + blockFrames);\n while (batchEnd < last && batchEnd - frame < batchFrames && !covered(batchEnd))\n batchEnd = Math.min(index.numberOfFrames, batchEnd + blockFrames);\n const bytes = await this.deps.cacheManager.resourceCache.readAudioRange(\n record.resourceId,\n index.dataOffset + frame * index.blockAlign,\n index.dataOffset + batchEnd * index.blockAlign\n );\n if (source) this.checkCurrent(source);\n if (bytes.byteLength !== (batchEnd - frame) * index.blockAlign)\n throw new Error('Truncated WAV PCM range');\n for (let slot = frame; slot < batchEnd; slot += blockFrames) {\n if (source) this.checkCurrent(source);\n const end = Math.min(batchEnd, slot + blockFrames);\n const timestamp = Math.round((slot * 1_000_000) / index.sampleRate);\n const range = new Uint8Array(\n bytes,\n (slot - frame) * index.blockAlign,\n (end - slot) * index.blockAlign\n );\n const data = new AudioData({\n format: 'f32-planar',\n sampleRate: index.sampleRate,\n numberOfChannels: index.numberOfChannels,\n numberOfFrames: end - slot,\n timestamp,\n data: decodeWavPCM(index, range).buffer as ArrayBuffer,\n });\n this.deps.cacheManager.putClipAudioData(\n cacheKey,\n data,\n clipDurationUs,\n clipStartUs + timestamp\n );\n }\n frame = batchEnd;\n }\n }\n\n /** Restore two synthesis frames plus their maximum bit reservoir before a seek. */\n private mp3PrerollStart(record: AudioSampleRecord, first: number): number {\n let start = Math.max(0, first - 2);\n let reservoirBytes = 0;\n while (start > 0 && reservoirBytes < 511) {\n const chunk = record.samples[--start]!;\n const bytes = new Uint8Array(chunk.byteLength);\n chunk.copyTo(bytes);\n const mpeg1 = ((bytes[1]! >> 3) & 3) === 3;\n const mono = bytes[3]! >> 6 === 3;\n const sideInfoBytes = mpeg1 ? (mono ? 17 : 32) : mono ? 9 : 17;\n const crcBytes = (bytes[1]! & 1) === 0 ? 2 : 0;\n reservoirBytes += Math.max(0, chunk.byteLength - 4 - crcBytes - sideInfoBytes);\n }\n return start;\n }\n\n /**\n * 统一的解码失败出口:广播 DecodeError(宿主据此中止导出/提示用户),\n * 导出模式响亮抛错,预览模式降级跳过并记入失败名单(不再重试)。\n */\n private async handleDecodeFailure(\n clipId: string,\n error: unknown,\n strictMode: boolean\n ): Promise<void> {\n console.error(`[AudioWindowPreparer] Decoder error for clip ${clipId}:`, error);\n this.failedDecodeClips.add(clipId);\n this.deps.eventBus.emit(MeframeEvent.DecodeError, {\n clipId,\n error: error instanceof Error ? error : new Error(String(error)),\n });\n if (strictMode) {\n throw error;\n }\n }\n\n /**\n * Decode audio samples to PCM and cache\n */\n private async decodeAudioSamples(\n clipId: string,\n samples: EncodedAudioChunk[],\n config: AudioDecoderConfig,\n clipDurationUs: number,\n clipStartUs: TimeUs,\n strictMode: boolean = false,\n gapless?: GaplessContext,\n source?: PreparedAudioSource\n ): Promise<void> {\n // Convert description to ArrayBuffer if needed for type compatibility\n let description: ArrayBuffer | undefined;\n if (config.description) {\n if (config.description instanceof ArrayBuffer) {\n description = config.description;\n } else if (ArrayBuffer.isView(config.description)) {\n const view = config.description as Uint8Array;\n const newBuffer = new ArrayBuffer(view.byteLength);\n new Uint8Array(newBuffer).set(\n new Uint8Array(view.buffer, view.byteOffset, view.byteLength)\n );\n description = newBuffer;\n }\n }\n\n const decoderConfig = {\n codec: config.codec,\n sampleRate: config.sampleRate,\n numberOfChannels: config.numberOfChannels,\n description,\n };\n\n // 解码器构造/配置/解码任何一步失败都走同一条失败路径(事件+降级/抛错),\n // 不能让构造错误绕过 catch 直接炸出去。\n let decoder: AudioChunkDecoder;\n try {\n decoder = new AudioChunkDecoder(`audio-${clipId}`, decoderConfig);\n } catch (error) {\n if (source) this.checkCurrent(source);\n await this.handleDecodeFailure(clipId, error, strictMode);\n return;\n }\n\n try {\n // Create chunk stream\n const chunkStream = new ReadableStream<EncodedAudioChunk>({\n start(controller) {\n for (const sample of samples) {\n controller.enqueue(sample);\n }\n controller.close();\n },\n });\n\n // Decode through stream\n const audioDataStream = chunkStream.pipeThrough(decoder.createStream());\n const reader = audioDataStream.getReader();\n\n // The contiguous input's absolute origin, independent of browser timestamp rewriting.\n let physicalStart = gapless?.physicalStart ?? 0;\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n if (value) {\n if (source) {\n try {\n this.checkCurrent(source);\n } catch (error) {\n value.close();\n await reader.cancel(error);\n throw error;\n }\n }\n const trimmed = this.applyGaplessTrim(value, gapless, physicalStart);\n physicalStart += value.numberOfFrames;\n if (!trimmed) {\n value.close();\n continue;\n }\n try {\n const globalTimeUs = clipStartUs + trimmed.timestamp;\n this.deps.cacheManager.putClipAudioData(\n source?.cacheKey ?? clipId,\n trimmed,\n clipDurationUs,\n globalTimeUs\n );\n } finally {\n if (trimmed !== value) value.close();\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n } catch (error) {\n if (source) this.checkCurrent(source);\n if (error instanceof RangeError) throw error;\n await this.handleDecodeFailure(clipId, error, strictMode);\n return;\n } finally {\n await decoder.close();\n }\n }\n\n /**\n * gapless 裁剪(issue #22):按解码帧在流内的样本位置计算首尾裁剪量。\n * 返回 null 表示整帧都在裁剪区间内(纯预填充静音),调用方丢弃。\n * 返回原对象表示无需裁剪;否则返回裁剪后的新 AudioData(时间戳前移)。\n */\n private applyGaplessTrim(\n data: AudioData,\n gapless: GaplessContext | undefined,\n physicalStart: number\n ): AudioData | null {\n if (!gapless) {\n return data;\n }\n const n = data.numberOfFrames;\n const frameStart = physicalStart;\n const headCut = Math.min(Math.max(gapless.validStart - frameStart, 0), n);\n const validEnd = gapless.validEnd;\n const tailCut = Math.min(Math.max(frameStart + n - validEnd, 0), n - headCut);\n if (headCut + tailCut >= n) {\n return null;\n }\n const timestamp = Math.round(\n ((frameStart + headCut - gapless.skipSamples) * 1_000_000) / gapless.sampleRate\n );\n return sliceAudioData(data, headCut, tailCut, timestamp);\n }\n}\n\ninterface GaplessContext {\n skipSamples: number;\n sampleRate: number;\n physicalStart: number;\n validStart: number;\n validEnd: number;\n}\n\n/** Copy the retained PCM and explicitly place it on the gapless resource timeline. */\nfunction sliceAudioData(\n src: AudioData,\n headFrames: number,\n tailFrames: number,\n timestamp: number\n): AudioData {\n const keep = src.numberOfFrames - headFrames - tailFrames;\n const format = src.format!;\n const planar = format.endsWith('-planar');\n const planes = planar ? src.numberOfChannels : 1;\n const planeSize = src.allocationSize({\n planeIndex: 0,\n format,\n frameOffset: headFrames,\n frameLength: keep,\n } as unknown as Parameters<AudioData['allocationSize']>[0]);\n const buffer = new ArrayBuffer(planeSize * planes);\n for (let plane = 0; plane < planes; plane++) {\n // frameOffset/frameLength 在 WebCodecs 规范与 Chrome 运行时均支持,\n // 当前 TS DOM lib 的 AudioDataCopyToOptions 定义滞后未收录,按实际签名断言\n src.copyTo(new Uint8Array(buffer, plane * planeSize, planeSize), {\n planeIndex: plane,\n format,\n frameOffset: headFrames,\n frameLength: keep,\n } as unknown as Parameters<AudioData['copyTo']>[1]);\n }\n return new AudioData({\n format,\n sampleRate: src.sampleRate,\n numberOfFrames: keep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M,SAAS,OAAO,SAAS,SAAS;AACxC,QAAM,SAAS,SAAS,IAAI,mBAAmB;AAC/C,QAAM,YAAY,IAAI,eAAe;AAAA,IACnC,YAAY;AAAA,IACZ;AAAA,IACA,aAAa;AAAA,IACb,aAAa;AAAA,EAAA,CAC2C;AAC1D,QAAM,SAAS,IAAI,YAAY,YAAY,MAAM;AACjD,WAAS,QAAQ,GAAG,QAAQ,QAAQ,SAAS;AAG3C,QAAI,OAAO,IAAI,WAAW,QAAQ,QAAQ,WAAW,SAAS,GAAG;AAAA,MAC/D,YAAY;AAAA,MACZ;AAAA,MACA,aAAa;AAAA,MACb,aAAa;AAAA,IAAA,CACmC;AAAA,EACpD;AACA,SAAO,IAAI,UAAU;AAAA,IACnB;AAAA,IACA,YAAY,IAAI;AAAA,IAChB,gBAAgB;AAAA,IAChB,kBAAkB,IAAI;AAAA,IACtB;AAAA,IACA,MAAM;AAAA,EAAA,CACP;AACH;"}
|
|
1
|
+
{"version":3,"file":"AudioWindowPreparer.js","sources":["../../src/orchestrator/AudioWindowPreparer.ts"],"sourcesContent":["import type { Clip, Resource, TimeUs } from '../model/types';\nimport type { CompositionModel } from '../model';\nimport type { ResourceLoader } from '../stages/load/ResourceLoader';\nimport type { EventBus } from '../event/EventBus';\nimport type { EventPayloadMap } from '../event/events';\nimport { MeframeEvent } from '../event/events';\nimport type { CacheManager } from '../cache/CacheManager';\nimport type { AudioSampleRecord } from '../cache/resource/AudioSampleCache';\nimport { AudioChunkDecoder } from '../stages/decode/AudioChunkDecoder';\nimport { decodeWavPCM } from '../stages/demux/WAVIndexParser';\nimport { clipPlaybackRate, isAudioClip, hasResourceId } from '../model/types';\nimport type { RequestMode } from './types';\nimport { buildLoopedResourceSegments } from '../utils/loop-utils';\nimport { isTerminalMediaResourceError } from '../utils/errors';\nimport { getAACWindow, prepareAACTimeline, type AACWindowTimeline } from './aac-window-timeline';\n\ninterface AudioWindowPreparerDeps {\n cacheManager: CacheManager;\n resourceLoader: ResourceLoader;\n eventBus: EventBus<EventPayloadMap>;\n}\n\nexport interface AudioSourceSnapshot {\n clip: Clip;\n resource: Resource;\n revision: number;\n cacheGeneration: number;\n}\n\nexport interface PreparedAudioSource extends AudioSourceSnapshot {\n record: AudioSampleRecord;\n cacheKey: string;\n aacTimeline?: AACWindowTimeline;\n}\n\nexport type AudioPCM = { planes: Float32Array[]; sampleRate: number; numberOfChannels: number };\n\nexport class AudioWindowPreparer {\n private activeClips = new Set<string>();\n /** 解码确定失败的 clip(坏包等):本会话不再重试,避免重试风暴;reset 清空 */\n private failedDecodeClips = new Set<string>();\n private deps: AudioWindowPreparerDeps;\n private model: CompositionModel | null = null;\n private revision = 0;\n private decodeQueue: Promise<unknown> = Promise.resolve();\n private pendingReads = 0;\n private decoding = 0;\n private recordIds = new WeakMap<AudioSampleRecord, number>();\n private nextRecordId = 0;\n private aacTimelines = new WeakMap<AudioSampleRecord, Promise<AACWindowTimeline | undefined>>();\n private lifecycle = new AbortController();\n\n get generation(): number {\n return this.revision;\n }\n\n getStats() {\n return { decoding: this.decoding, pendingReads: this.pendingReads };\n }\n\n invalidate(abortLoads = true): void {\n this.revision++;\n if (abortLoads) {\n this.lifecycle.abort();\n this.lifecycle = new AbortController();\n }\n this.failedDecodeClips.clear();\n this.activeClips.clear();\n }\n\n snapshot(clip: Clip): AudioSourceSnapshot {\n const resource = hasResourceId(clip) ? this.model?.getResource(clip.resourceId) : null;\n if (!resource) throw new Error(`Audio resource missing for clip ${clip.id}`);\n return {\n clip: { ...clip },\n resource: { ...resource },\n revision: this.revision,\n cacheGeneration: this.deps.cacheManager.audioCacheGeneration,\n };\n }\n\n private checkCurrent(source: AudioSourceSnapshot): void {\n if (\n source.revision !== this.revision ||\n source.cacheGeneration !== this.deps.cacheManager.audioCacheGeneration\n ) {\n throw new DOMException('Audio request superseded', 'AbortError');\n }\n }\n\n async prepareSource(\n source: AudioSourceSnapshot,\n strictMode = false\n ): Promise<PreparedAudioSource | null> {\n this.checkCurrent(source);\n const { clip, resource } = source;\n if (resource.state === 'error' && resource.error?.terminal) {\n if (strictMode) throw new Error(`Resource ${resource.id} is in error state`);\n return null;\n }\n if (!this.deps.cacheManager.audioSampleCache.has(resource.id) && resource.state !== 'ready') {\n await this.deps.resourceLoader.load(resource.id, {\n clipId: clip.id,\n trackId: clip.trackId,\n signal: this.lifecycle.signal,\n isPreload: false,\n });\n this.checkCurrent(source);\n }\n const record = this.deps.cacheManager.audioSampleCache.get(resource.id);\n // A parsed video without an audio track is intentionally silent.\n if (!record) {\n if (this.model?.getResource(resource.id)?.state !== 'ready')\n throw new Error(`Audio resource ${resource.id} is not ready`);\n if (resource.type === 'audio') throw new Error(`Audio samples missing for ${resource.id}`);\n return null;\n }\n let recordId = this.recordIds.get(record);\n if (recordId === undefined) {\n recordId = ++this.nextRecordId;\n this.recordIds.set(record, recordId);\n }\n const cacheKey = JSON.stringify([resource.id, resource.uri, recordId]);\n this.deps.cacheManager.setAudioSource(clip.id, cacheKey);\n let pendingTimeline = this.aacTimelines.get(record);\n if (!pendingTimeline) {\n // Share one probe per byte delivery and drain it with the other owned decodes.\n pendingTimeline = this.decodeQueue.then(async () => {\n this.decoding++;\n try {\n return await prepareAACTimeline(record);\n } finally {\n this.decoding--;\n }\n });\n this.decodeQueue = pendingTimeline.then(\n () => undefined,\n () => undefined\n );\n this.aacTimelines.set(record, pendingTimeline);\n }\n let aacTimeline: AACWindowTimeline | undefined;\n try {\n aacTimeline = await pendingTimeline;\n } catch (error) {\n this.checkCurrent(source);\n await this.handleDecodeFailure(clip.id, error, strictMode);\n return null;\n }\n this.checkCurrent(source);\n return {\n ...source,\n record: aacTimeline ? { ...record, durationUs: aacTimeline.durationUs } : record,\n cacheKey,\n aacTimeline,\n };\n }\n\n maxReadDurationUs(source: PreparedAudioSource): number {\n const bytesPerSecond =\n source.record.metadata.sampleRate * source.record.metadata.numberOfChannels * 4;\n // Leave room for whole decoded edge frames plus the contiguous read copy.\n return Math.max(\n 1,\n Math.floor(\n (this.deps.cacheManager.getAudioCacheStats().maxBytes / (3 * bytesPerSecond)) * 1_000_000\n )\n );\n }\n\n /** Decode and consume under one lease. Other readers cannot evict these slots between awaits. */\n async withPCM<T>(\n source: PreparedAudioSource,\n startUs: TimeUs,\n endUs: TimeUs,\n consume: (pcm: AudioPCM | null) => T,\n strictMode = false\n ): Promise<T> {\n this.pendingReads++;\n const run = async () => {\n this.checkCurrent(source);\n const firstUs = source.record.gapless ? 0 : (source.record.samples[0]?.timestamp ?? 0);\n const readStartUs = Math.max(firstUs, startUs);\n const readEndUs = Math.min(endUs, source.record.durationUs);\n if (readEndUs <= readStartUs) return consume(null);\n const bytes =\n Math.ceil(((endUs - startUs) * source.record.metadata.sampleRate) / 1_000_000) *\n source.record.metadata.numberOfChannels *\n 4;\n const lease = this.deps.cacheManager.pinAudioRange(\n source.cacheKey,\n readStartUs,\n readEndUs,\n bytes\n );\n this.decoding++;\n try {\n await this.decodeAudioWindow(source.clip.id, readStartUs, readEndUs, strictMode, source);\n this.checkCurrent(source);\n if (this.failedDecodeClips.has(source.clip.id) && !strictMode) return consume(null);\n const threshold = Math.max(\n 0.5,\n 1 - 1_000_000 / source.record.metadata.sampleRate / (readEndUs - readStartUs)\n );\n if (\n !this.deps.cacheManager.getAudioRangeCoverage(\n source.cacheKey,\n readStartUs,\n readEndUs,\n threshold\n ).covered\n ) {\n throw new Error(\n `Audio PCM unavailable for ${source.clip.id} [${readStartUs}, ${readEndUs})`\n );\n }\n const pcm = lease.read();\n if (!pcm) throw new Error(`Audio PCM unavailable for ${source.clip.id}`);\n // Padding outside the physical audio range is intentional silence.\n if (readStartUs !== startUs || readEndUs !== endUs) {\n const frames = Math.ceil(((endUs - startUs) * pcm.sampleRate) / 1_000_000);\n const offset = Math.round(((readStartUs - startUs) * pcm.sampleRate) / 1_000_000);\n pcm.planes = pcm.planes.map((plane) => {\n const out = new Float32Array(frames);\n out.set(plane.subarray(0, frames - offset), offset);\n return out;\n });\n }\n return consume(pcm);\n } finally {\n this.decoding--;\n lease.release();\n }\n };\n const task = this.decodeQueue.then(run, run);\n this.decodeQueue = task.then(\n () => undefined,\n () => undefined\n );\n try {\n return await task;\n } finally {\n this.pendingReads--;\n }\n }\n\n async drain(): Promise<void> {\n await this.decodeQueue;\n }\n\n constructor(deps: AudioWindowPreparerDeps) {\n this.deps = deps;\n }\n\n setModel(model: CompositionModel | null): void {\n this.invalidate();\n this.model = model;\n }\n\n getModel(): CompositionModel | null {\n return this.model;\n }\n\n reset(): void {\n this.invalidate();\n this.deps.cacheManager.clearAudioCache();\n this.activeClips.clear();\n }\n\n /** 本会话解码确定失败、被静音跳过的 clip 集合(宿主可用于导出报告/提示) */\n getFailedDecodeClips(): ReadonlySet<string> {\n return this.failedDecodeClips;\n }\n\n /**\n * Fast readiness probe for preview playback.\n *\n * This is intentionally synchronous and lightweight:\n * - Only checks resource-level readiness (download + MP4 index parsing).\n * - If any relevant resource isn't ready yet, return false.\n * - Does NOT require audio samples / PCM window coverage (probe is resource-level only).\n */\n isAudioResourceWindowReady(startUs: TimeUs, endUs: TimeUs): boolean {\n const model = this.model;\n if (!model) return true;\n\n const activeClips = model.getActiveClips(startUs, endUs);\n\n for (const clip of activeClips) {\n if (clip.trackKind !== 'audio' && clip.trackKind !== 'video') continue;\n if (!hasResourceId(clip)) continue;\n\n const resource = model.getResource(clip.resourceId);\n if (resource?.state !== 'ready') {\n return false;\n }\n }\n\n return true;\n }\n\n async activateAllAudioClips(): Promise<void> {\n const model = this.model;\n const revision = this.revision;\n if (!model) {\n return;\n }\n\n const audioTracks = model.tracks.filter((track) => track.kind === 'audio');\n if (audioTracks.length === 0) return;\n\n // Find maximum clip count across all audio tracks\n const maxClipCount = Math.max(...audioTracks.map((track) => track.clips.length));\n\n // Horizontal loading: activate clip[0] from all tracks, then clip[1], etc.\n for (let clipIndex = 0; clipIndex < maxClipCount; clipIndex++) {\n for (const track of audioTracks) {\n if (revision !== this.revision) return;\n const clip = track.clips[clipIndex];\n if (!clip || this.activeClips.has(clip.id)) continue;\n\n if (!isAudioClip(clip)) {\n throw new Error(`Clip ${clip.id} in audio track is not an audio clip`);\n }\n\n // Preview: Use main-thread parsing → AudioSampleCache → on-demand decode\n // Check if we have cached samples (already parsed in ResourceLoader)\n if (this.deps.cacheManager.audioSampleCache.has(clip.resourceId)) {\n // Already parsed, mark as active\n this.activeClips.add(clip.id);\n this.deps.eventBus.emit(MeframeEvent.ClipActivated, { clipId: clip.id });\n continue;\n }\n\n // Ensure resource is loaded (will be parsed and cached in main thread)\n try {\n await this.deps.resourceLoader.load(clip.resourceId, {\n isPreload: false,\n clipId: clip.id,\n trackId: track.id,\n });\n } catch (error) {\n // Preview should not be blocked by a single bad audio resource.\n if (isTerminalMediaResourceError(error)) {\n continue;\n }\n throw error;\n }\n\n if (revision !== this.revision) return;\n // Mark as active\n this.activeClips.add(clip.id);\n this.deps.eventBus.emit(MeframeEvent.ClipActivated, { clipId: clip.id });\n }\n }\n }\n\n async deactivateClip(clipId: string): Promise<void> {\n if (!this.activeClips.has(clipId)) {\n return;\n }\n\n this.activeClips.delete(clipId);\n this.deps.cacheManager.clearClipAudioData(clipId);\n }\n\n /**\n * Core method to ensure audio for all clips in a time range\n */\n async ensureAudioForTimeRange(\n startUs: TimeUs,\n endUs: TimeUs,\n options: { mode?: RequestMode; loadResource?: boolean; strictMode?: boolean }\n ): Promise<void> {\n const model = this.model;\n if (!model) return;\n\n const revision = this.revision;\n const cacheGeneration = this.deps.cacheManager.audioCacheGeneration;\n const { mode = 'blocking', loadResource = true, strictMode = false } = options;\n\n // Find all clips that overlap with [startUs, endUs]\n const activeClips = model.getActiveClips(startUs, endUs);\n\n const ensurePromises = activeClips.map(async (clip) => {\n // Only process audio and video clips.\n // Note: video clips may carry an embedded audio track; preview should include them as well.\n if (clip.trackKind !== 'audio' && clip.trackKind !== 'video') return;\n if (!hasResourceId(clip)) return;\n\n // Skip muted/zero-volume clips early; they should not block preview or export.\n const muted = clip.audioConfig?.muted ?? false;\n const volume = clip.audioConfig?.volume ?? 1.0;\n if (muted || volume <= 0) {\n return;\n }\n\n const resource = model.getResource(clip.resourceId);\n\n // Terminal error state: for preview (strictMode=false) skip; for export (strictMode=true) fail fast.\n if (resource?.state === 'error' && resource.error?.terminal === true) {\n if (strictMode) {\n throw new Error(`Resource ${clip.resourceId} is in error state`);\n }\n return;\n }\n\n // Skip clips without audio track (performance optimization)\n // If AudioSampleCache doesn't have this resource, and resource is ready,\n // it means the resource has no audio track (e.g., video-only or image)\n if (\n resource?.state === 'ready' &&\n !this.deps.cacheManager.audioSampleCache.has(clip.resourceId)\n ) {\n // Resource is ready but has no audio samples - skip\n return;\n }\n\n // Ensure AudioSampleCache has data\n if (!this.deps.cacheManager.audioSampleCache.has(clip.resourceId)) {\n if (!loadResource) {\n // Export mode: skip clips without cached samples\n return;\n }\n\n if (resource?.state !== 'ready') {\n // Resource not yet loaded - wait for it\n try {\n await this.deps.resourceLoader.load(clip.resourceId, {\n isPreload: false,\n clipId: clip.id,\n trackId: clip.trackId,\n });\n } catch (error) {\n if (isTerminalMediaResourceError(error)) {\n if (strictMode) {\n throw error;\n }\n return;\n }\n throw error;\n }\n }\n }\n\n if (\n revision !== this.revision ||\n cacheGeneration !== this.deps.cacheManager.audioCacheGeneration\n )\n return;\n\n // Calculate clip-relative time range\n const clipRelativeStartUs = Math.max(0, startUs - clip.startUs);\n const clipRelativeEndUs = Math.min(clip.durationUs, endUs - clip.startUs);\n\n // Convert to resource time (aligned with video architecture)\n const trimStartUs = clip.trimStartUs ?? 0;\n const loop = clip.trackKind === 'audio' && clip.loop === true;\n const playbackRate = clipPlaybackRate(clip);\n const audioRecord = this.deps.cacheManager.audioSampleCache.get(clip.resourceId) as {\n durationUs: TimeUs;\n } | null;\n const resourceDurationUs = audioRecord?.durationUs ?? 0;\n\n let segments = buildLoopedResourceSegments({\n clipRelativeStartUs,\n clipRelativeEndUs,\n trimStartUs,\n resourceDurationUs,\n loop,\n playbackRate,\n });\n if (segments.length === 0 && clipRelativeEndUs > clipRelativeStartUs) {\n // Fallback to non-loop mapping when resource duration isn't available yet.\n segments = buildLoopedResourceSegments({\n clipRelativeStartUs,\n clipRelativeEndUs,\n trimStartUs,\n resourceDurationUs,\n loop: false,\n playbackRate,\n });\n }\n\n // Ensure audio window using resource time coordinates\n for (const seg of segments) {\n if (\n revision !== this.revision ||\n cacheGeneration !== this.deps.cacheManager.audioCacheGeneration\n )\n return;\n await this.ensureAudioWindow(clip.id, seg.resourceStartUs, seg.resourceEndUs, strictMode);\n }\n });\n\n if (mode === 'probe') {\n void Promise.all(ensurePromises).catch(() => {});\n return;\n }\n await Promise.all(ensurePromises);\n }\n\n /**\n * Ensure audio window for a clip\n */\n async ensureAudioWindow(\n clipId: string,\n startUs: TimeUs,\n endUs: TimeUs,\n strictMode: boolean = false\n ): Promise<void> {\n const clip = this.model?.findClip(clipId);\n if (!clip || !hasResourceId(clip)) return;\n const source = await this.prepareSource(this.snapshot(clip), strictMode);\n if (!source) return;\n const step = this.maxReadDurationUs(source);\n for (let cursor = startUs; cursor < endUs; cursor += step) {\n await this.withPCM(\n source,\n cursor,\n Math.min(endUs, cursor + step),\n () => undefined,\n strictMode\n );\n }\n }\n\n /**\n * Decode audio window for a clip\n */\n private async decodeAudioWindow(\n clipId: string,\n startUs: TimeUs,\n endUs: TimeUs,\n strictMode: boolean = false,\n source?: PreparedAudioSource\n ): Promise<void> {\n if (source) this.checkCurrent(source);\n if (this.failedDecodeClips.has(clipId)) {\n // deterministic decode failure earlier this session - don't retry.\n // 导出模式同样必须失败:不能带着\"已知坏了的音频\"继续出片。\n if (strictMode) {\n throw new Error(\n `Audio decode failed earlier for clip ${clipId}; export refused to ship silent audio`\n );\n }\n return;\n }\n if (source) {\n const threshold = Math.max(\n 0.5,\n 1 - 1_000_000 / source.record.metadata.sampleRate / Math.max(1, endUs - startUs)\n );\n if (\n this.deps.cacheManager.getAudioRangeCoverage(source.cacheKey, startUs, endUs, threshold)\n .covered\n )\n return;\n }\n const clip = source?.clip ?? this.model?.findClip(clipId);\n if (!clip || !hasResourceId(clip)) {\n return;\n }\n\n // Get audio samples from AudioSampleCache\n const audioRecord =\n source?.record ?? this.deps.cacheManager.audioSampleCache.get(clip.resourceId);\n if (!audioRecord) {\n // Resource has no audio track (common for some video files)\n return;\n }\n\n if (audioRecord.pcm) {\n try {\n await this.decodeWavWindow(\n clipId,\n audioRecord,\n startUs,\n endUs,\n clip.durationUs,\n clip.startUs,\n source\n );\n } catch (error) {\n if (source) this.checkCurrent(source);\n if (error instanceof RangeError) throw error;\n await this.handleDecodeFailure(clipId, error, strictMode);\n }\n return;\n }\n\n if (audioRecord.gapless) {\n // MP3 windows must stay contiguous, including cached chunks: reservoir and\n // synthesis state cannot survive holes in an incremental decode stream.\n const { skipSamples, trimEndSamples, samplesPerFrame } = audioRecord.gapless;\n const sampleRate = audioRecord.metadata.sampleRate;\n const validStart = Math.max(\n skipSamples,\n Math.ceil((startUs * sampleRate) / 1_000_000) + skipSamples\n );\n const validEnd = Math.min(\n audioRecord.samples.length * samplesPerFrame - trimEndSamples,\n Math.ceil((endUs * sampleRate) / 1_000_000) + skipSamples\n );\n if (validEnd <= validStart) return;\n const first = Math.floor(validStart / samplesPerFrame);\n const last = Math.ceil(validEnd / samplesPerFrame);\n const decodeStart = this.mp3PrerollStart(audioRecord, first);\n await this.decodeAudioSamples(\n clipId,\n audioRecord.samples.slice(decodeStart, last),\n audioRecord.metadata,\n clip.durationUs,\n clip.startUs,\n strictMode,\n {\n skipSamples,\n sampleRate,\n // Cache stable whole-frame slots so overlapping requests cannot leave partial holes.\n validStart: Math.max(skipSamples, first * samplesPerFrame),\n validEnd: Math.min(\n audioRecord.samples.length * samplesPerFrame - trimEndSamples,\n last * samplesPerFrame\n ),\n physicalStart: decodeStart * samplesPerFrame,\n },\n source\n );\n return;\n }\n\n // Filter chunks within window (aligned with video GOP filtering)\n const windowChunks = source?.aacTimeline\n ? getAACWindow(audioRecord.samples, source.aacTimeline, startUs, endUs)\n : audioRecord.samples.filter((s) => {\n const sampleEndUs = s.timestamp + (s.duration ?? 0);\n return s.timestamp < endUs && sampleEndUs > startUs;\n });\n\n if (windowChunks.length === 0) {\n return;\n }\n\n // AAC decoders maintain a continuous output clock within one stream. Skipping\n // cached chunks can move later outputs onto earlier PTS and leave cache holes.\n // Decode the bounded window contiguously; the cache deduplicates existing slots.\n await this.decodeAudioSamples(\n clipId,\n windowChunks,\n audioRecord.metadata,\n clip.durationUs,\n clip.startUs,\n strictMode,\n undefined,\n source\n );\n }\n\n private async decodeWavWindow(\n clipId: string,\n record: AudioSampleRecord,\n startUs: TimeUs,\n endUs: TimeUs,\n clipDurationUs: TimeUs,\n clipStartUs: TimeUs,\n source?: PreparedAudioSource\n ): Promise<void> {\n const index = record.pcm!;\n const first = Math.max(0, Math.floor((startUs * index.sampleRate) / 1_000_000));\n const last = Math.min(index.numberOfFrames, Math.ceil((endUs * index.sampleRate) / 1_000_000));\n // Stable slots avoid overlapping seek windows pinning duplicate PCM. Edge\n // slots consume at most 1/8 of the budget, alongside the reserved read copy.\n const blockFrames = Math.max(\n 1,\n Math.min(\n 2048,\n Math.floor(\n this.deps.cacheManager.getAudioCacheStats().maxBytes / (16 * index.numberOfChannels * 4)\n )\n )\n );\n // Coalesce adjacent misses, retaining a bounded raw read in addition to L1.\n const maxReadBytes = Math.max(\n blockFrames * index.blockAlign,\n Math.min(256 * 1024, Math.floor(this.deps.cacheManager.getAudioCacheStats().maxBytes / 8))\n );\n const batchFrames =\n blockFrames * Math.max(1, Math.floor(maxReadBytes / (blockFrames * index.blockAlign)));\n const cacheKey = source?.cacheKey ?? clipId;\n const covered = (frame: number) =>\n this.deps.cacheManager.getAudioRangeCoverage(\n cacheKey,\n Math.round((frame * 1_000_000) / index.sampleRate),\n Math.round(\n (Math.min(index.numberOfFrames, frame + blockFrames) * 1_000_000) / index.sampleRate\n ),\n 0.99\n ).covered;\n for (let frame = Math.floor(first / blockFrames) * blockFrames; frame < last;) {\n if (source) this.checkCurrent(source);\n if (covered(frame)) {\n frame += blockFrames;\n continue;\n }\n let batchEnd = Math.min(index.numberOfFrames, frame + blockFrames);\n while (batchEnd < last && batchEnd - frame < batchFrames && !covered(batchEnd))\n batchEnd = Math.min(index.numberOfFrames, batchEnd + blockFrames);\n const bytes = await this.deps.cacheManager.resourceCache.readAudioRange(\n record.resourceId,\n index.dataOffset + frame * index.blockAlign,\n index.dataOffset + batchEnd * index.blockAlign\n );\n if (source) this.checkCurrent(source);\n if (bytes.byteLength !== (batchEnd - frame) * index.blockAlign)\n throw new Error('Truncated WAV PCM range');\n for (let slot = frame; slot < batchEnd; slot += blockFrames) {\n if (source) this.checkCurrent(source);\n const end = Math.min(batchEnd, slot + blockFrames);\n const timestamp = Math.round((slot * 1_000_000) / index.sampleRate);\n const range = new Uint8Array(\n bytes,\n (slot - frame) * index.blockAlign,\n (end - slot) * index.blockAlign\n );\n const data = new AudioData({\n format: 'f32-planar',\n sampleRate: index.sampleRate,\n numberOfChannels: index.numberOfChannels,\n numberOfFrames: end - slot,\n timestamp,\n data: decodeWavPCM(index, range).buffer as ArrayBuffer,\n });\n this.deps.cacheManager.putClipAudioData(\n cacheKey,\n data,\n clipDurationUs,\n clipStartUs + timestamp\n );\n }\n frame = batchEnd;\n }\n }\n\n /** Restore two synthesis frames plus their maximum bit reservoir before a seek. */\n private mp3PrerollStart(record: AudioSampleRecord, first: number): number {\n let start = Math.max(0, first - 2);\n let reservoirBytes = 0;\n while (start > 0 && reservoirBytes < 511) {\n const chunk = record.samples[--start]!;\n const bytes = new Uint8Array(chunk.byteLength);\n chunk.copyTo(bytes);\n const mpeg1 = ((bytes[1]! >> 3) & 3) === 3;\n const mono = bytes[3]! >> 6 === 3;\n const sideInfoBytes = mpeg1 ? (mono ? 17 : 32) : mono ? 9 : 17;\n const crcBytes = (bytes[1]! & 1) === 0 ? 2 : 0;\n reservoirBytes += Math.max(0, chunk.byteLength - 4 - crcBytes - sideInfoBytes);\n }\n return start;\n }\n\n /**\n * 统一的解码失败出口:广播 DecodeError(宿主据此中止导出/提示用户),\n * 导出模式响亮抛错,预览模式降级跳过并记入失败名单(不再重试)。\n */\n private async handleDecodeFailure(\n clipId: string,\n error: unknown,\n strictMode: boolean\n ): Promise<void> {\n console.error(`[AudioWindowPreparer] Decoder error for clip ${clipId}:`, error);\n this.failedDecodeClips.add(clipId);\n this.deps.eventBus.emit(MeframeEvent.DecodeError, {\n clipId,\n error: error instanceof Error ? error : new Error(String(error)),\n });\n if (strictMode) {\n throw error;\n }\n }\n\n /**\n * Decode audio samples to PCM and cache\n */\n private async decodeAudioSamples(\n clipId: string,\n samples: EncodedAudioChunk[],\n config: AudioDecoderConfig,\n clipDurationUs: number,\n clipStartUs: TimeUs,\n strictMode: boolean = false,\n gapless?: GaplessContext,\n source?: PreparedAudioSource\n ): Promise<void> {\n // Convert description to ArrayBuffer if needed for type compatibility\n let description: ArrayBuffer | undefined;\n if (config.description) {\n if (config.description instanceof ArrayBuffer) {\n description = config.description;\n } else if (ArrayBuffer.isView(config.description)) {\n const view = config.description as Uint8Array;\n const newBuffer = new ArrayBuffer(view.byteLength);\n new Uint8Array(newBuffer).set(\n new Uint8Array(view.buffer, view.byteOffset, view.byteLength)\n );\n description = newBuffer;\n }\n }\n\n const decoderConfig = {\n codec: config.codec,\n sampleRate: config.sampleRate,\n numberOfChannels: config.numberOfChannels,\n description,\n };\n\n // 解码器构造/配置/解码任何一步失败都走同一条失败路径(事件+降级/抛错),\n // 不能让构造错误绕过 catch 直接炸出去。\n let decoder: AudioChunkDecoder;\n try {\n decoder = new AudioChunkDecoder(`audio-${clipId}`, decoderConfig);\n } catch (error) {\n if (source) this.checkCurrent(source);\n await this.handleDecodeFailure(clipId, error, strictMode);\n return;\n }\n\n try {\n // Create chunk stream\n const chunkStream = new ReadableStream<EncodedAudioChunk>({\n start(controller) {\n for (const sample of samples) {\n controller.enqueue(sample);\n }\n controller.close();\n },\n });\n\n // Decode through stream\n const audioDataStream = chunkStream.pipeThrough(decoder.createStream());\n const reader = audioDataStream.getReader();\n\n // The contiguous input's absolute origin, independent of browser timestamp rewriting.\n let physicalStart = gapless?.physicalStart ?? 0;\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n if (value) {\n if (source) {\n try {\n this.checkCurrent(source);\n } catch (error) {\n value.close();\n await reader.cancel(error);\n throw error;\n }\n }\n const trimmed = this.applyGaplessTrim(value, gapless, physicalStart);\n physicalStart += value.numberOfFrames;\n if (!trimmed) {\n value.close();\n continue;\n }\n try {\n const globalTimeUs = clipStartUs + trimmed.timestamp;\n this.deps.cacheManager.putClipAudioData(\n source?.cacheKey ?? clipId,\n trimmed,\n clipDurationUs,\n globalTimeUs\n );\n } finally {\n if (trimmed !== value) value.close();\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n } catch (error) {\n if (source) this.checkCurrent(source);\n if (error instanceof RangeError) throw error;\n await this.handleDecodeFailure(clipId, error, strictMode);\n return;\n } finally {\n await decoder.close();\n }\n }\n\n /**\n * gapless 裁剪(issue #22):按解码帧在流内的样本位置计算首尾裁剪量。\n * 返回 null 表示整帧都在裁剪区间内(纯预填充静音),调用方丢弃。\n * 返回原对象表示无需裁剪;否则返回裁剪后的新 AudioData(时间戳前移)。\n */\n private applyGaplessTrim(\n data: AudioData,\n gapless: GaplessContext | undefined,\n physicalStart: number\n ): AudioData | null {\n if (!gapless) {\n return data;\n }\n const n = data.numberOfFrames;\n const frameStart = physicalStart;\n const headCut = Math.min(Math.max(gapless.validStart - frameStart, 0), n);\n const validEnd = gapless.validEnd;\n const tailCut = Math.min(Math.max(frameStart + n - validEnd, 0), n - headCut);\n if (headCut + tailCut >= n) {\n return null;\n }\n const timestamp = Math.round(\n ((frameStart + headCut - gapless.skipSamples) * 1_000_000) / gapless.sampleRate\n );\n return sliceAudioData(data, headCut, tailCut, timestamp);\n }\n}\n\ninterface GaplessContext {\n skipSamples: number;\n sampleRate: number;\n physicalStart: number;\n validStart: number;\n validEnd: number;\n}\n\n/** Copy the retained PCM and explicitly place it on the gapless resource timeline. */\nfunction sliceAudioData(\n src: AudioData,\n headFrames: number,\n tailFrames: number,\n timestamp: number\n): AudioData {\n const keep = src.numberOfFrames - headFrames - tailFrames;\n const format = src.format!;\n const planar = format.endsWith('-planar');\n const planes = planar ? src.numberOfChannels : 1;\n const planeSize = src.allocationSize({\n planeIndex: 0,\n format,\n frameOffset: headFrames,\n frameLength: keep,\n } as unknown as Parameters<AudioData['allocationSize']>[0]);\n const buffer = new ArrayBuffer(planeSize * planes);\n for (let plane = 0; plane < planes; plane++) {\n // frameOffset/frameLength 在 WebCodecs 规范与 Chrome 运行时均支持,\n // 当前 TS DOM lib 的 AudioDataCopyToOptions 定义滞后未收录,按实际签名断言\n src.copyTo(new Uint8Array(buffer, plane * planeSize, planeSize), {\n planeIndex: plane,\n format,\n frameOffset: headFrames,\n frameLength: keep,\n } as unknown as Parameters<AudioData['copyTo']>[1]);\n }\n return new AudioData({\n format,\n sampleRate: src.sampleRate,\n numberOfFrames: keep,\n numberOfChannels: src.numberOfChannels,\n timestamp,\n data: buffer,\n });\n}\n"],"names":[],"mappings":";;;;;;;AAqCO,MAAM,oBAAoB;AAAA,EACvB,kCAAkB,IAAA;AAAA;AAAA,EAElB,wCAAwB,IAAA;AAAA,EACxB;AAAA,EACA,QAAiC;AAAA,EACjC,WAAW;AAAA,EACX,cAAgC,QAAQ,QAAA;AAAA,EACxC,eAAe;AAAA,EACf,WAAW;AAAA,EACX,gCAAgB,QAAA;AAAA,EAChB,eAAe;AAAA,EACf,mCAAmB,QAAA;AAAA,EACnB,YAAY,IAAI,gBAAA;AAAA,EAExB,IAAI,aAAqB;AACvB,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,WAAW;AACT,WAAO,EAAE,UAAU,KAAK,UAAU,cAAc,KAAK,aAAA;AAAA,EACvD;AAAA,EAEA,WAAW,aAAa,MAAY;AAClC,SAAK;AACL,QAAI,YAAY;AACd,WAAK,UAAU,MAAA;AACf,WAAK,YAAY,IAAI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A,YACA,YACA,WACW;AACX,QAAM,OAAO,IAAI,iBAAiB,aAAa;AAC/C,QAAM,SAAS,IAAI;AACnB,QAAM,SAAS,OAAO,SAAS,SAAS;AACxC,QAAM,SAAS,SAAS,IAAI,mBAAmB;AAC/C,QAAM,YAAY,IAAI,eAAe;AAAA,IACnC,YAAY;AAAA,IACZ;AAAA,IACA,aAAa;AAAA,IACb,aAAa;AAAA,EAAA,CAC2C;AAC1D,QAAM,SAAS,IAAI,YAAY,YAAY,MAAM;AACjD,WAAS,QAAQ,GAAG,QAAQ,QAAQ,SAAS;AAG3C,QAAI,OAAO,IAAI,WAAW,QAAQ,QAAQ,WAAW,SAAS,GAAG;AAAA,MAC/D,YAAY;AAAA,MACZ;AAAA,MACA,aAAa;AAAA,MACb,aAAa;AAAA,IAAA,CACmC;AAAA,EACpD;AACA,SAAO,IAAI,UAAU;AAAA,IACnB;AAAA,IACA,YAAY,IAAI;AAAA,IAChB,gBAAgB;AAAA,IAChB,kBAAkB,IAAI;AAAA,IACtB;AAAA,IACA,MAAM;AAAA,EAAA,CACP;AACH;"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { AudioSampleRecord } from '../cache/resource/AudioSampleCache';
|
|
2
|
+
|
|
3
|
+
export interface AACWindowTimeline {
|
|
4
|
+
firstDurationUs: number;
|
|
5
|
+
shiftUs: number;
|
|
6
|
+
durationUs: number;
|
|
7
|
+
}
|
|
8
|
+
/** Measure anomalous AAC prefixes instead of treating container duration as PCM length. */
|
|
9
|
+
export declare function prepareAACTimeline(record: AudioSampleRecord): Promise<AACWindowTimeline | undefined>;
|
|
10
|
+
/** Only copy the requested encoded window; keep the resource's compressed samples shared. */
|
|
11
|
+
export declare function getAACWindow(samples: EncodedAudioChunk[], timeline: AACWindowTimeline, startUs: number, endUs: number): EncodedAudioChunk[];
|
|
12
|
+
//# sourceMappingURL=aac-window-timeline.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"aac-window-timeline.d.ts","sourceRoot":"","sources":["../../src/orchestrator/aac-window-timeline.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oCAAoC,CAAC;AAG5E,MAAM,WAAW,iBAAiB;IAChC,eAAe,EAAE,MAAM,CAAC;IACxB,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,2FAA2F;AAC3F,wBAAsB,kBAAkB,CACtC,MAAM,EAAE,iBAAiB,GACxB,OAAO,CAAC,iBAAiB,GAAG,SAAS,CAAC,CA2CxC;AAED,6FAA6F;AAC7F,wBAAgB,YAAY,CAC1B,OAAO,EAAE,iBAAiB,EAAE,EAC5B,QAAQ,EAAE,iBAAiB,EAC3B,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,MAAM,GACZ,iBAAiB,EAAE,CA8BrB"}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { AudioChunkDecoder } from "../stages/decode/AudioChunkDecoder.js";
|
|
2
|
+
async function prepareAACTimeline(record) {
|
|
3
|
+
const { samples, metadata } = record;
|
|
4
|
+
const first = samples[0];
|
|
5
|
+
if (!metadata.codec.startsWith("mp4a") || !first || samples.length < 2) return void 0;
|
|
6
|
+
const toleranceUs = 1e6 / metadata.sampleRate;
|
|
7
|
+
const followingDuration = samples[1].duration ?? 0;
|
|
8
|
+
if (followingDuration <= 0 || (first.duration ?? 0) <= followingDuration + toleranceUs)
|
|
9
|
+
return void 0;
|
|
10
|
+
const description = metadata.description;
|
|
11
|
+
const decoder = new AudioChunkDecoder("aac-prefix", {
|
|
12
|
+
...metadata,
|
|
13
|
+
description: description ? new Uint8Array(
|
|
14
|
+
ArrayBuffer.isView(description) ? new Uint8Array(description.buffer, description.byteOffset, description.byteLength) : new Uint8Array(description)
|
|
15
|
+
).buffer : void 0
|
|
16
|
+
});
|
|
17
|
+
const input = new ReadableStream({
|
|
18
|
+
start(controller) {
|
|
19
|
+
controller.enqueue(first);
|
|
20
|
+
controller.close();
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
const reader = input.pipeThrough(decoder.createStream()).getReader();
|
|
24
|
+
let durationUs = 0;
|
|
25
|
+
try {
|
|
26
|
+
while (true) {
|
|
27
|
+
const { value, done } = await reader.read();
|
|
28
|
+
if (done) break;
|
|
29
|
+
durationUs += value.numberOfFrames * 1e6 / value.sampleRate;
|
|
30
|
+
value.close();
|
|
31
|
+
}
|
|
32
|
+
} finally {
|
|
33
|
+
reader.releaseLock();
|
|
34
|
+
await decoder.close();
|
|
35
|
+
}
|
|
36
|
+
if (durationUs <= 0) throw new Error("AAC prefix produced no PCM");
|
|
37
|
+
const shiftUs = (first.duration ?? 0) - durationUs;
|
|
38
|
+
if (shiftUs <= toleranceUs) return void 0;
|
|
39
|
+
return { firstDurationUs: durationUs, shiftUs, durationUs: record.durationUs - shiftUs };
|
|
40
|
+
}
|
|
41
|
+
function getAACWindow(samples, timeline, startUs, endUs) {
|
|
42
|
+
const chunks = [];
|
|
43
|
+
let first = -1;
|
|
44
|
+
let last = 0;
|
|
45
|
+
for (let i = 0; i < samples.length; i++) {
|
|
46
|
+
const sample = samples[i];
|
|
47
|
+
const timestamp = sample.timestamp - (i === 0 ? 0 : timeline.shiftUs);
|
|
48
|
+
const duration = i === 0 ? timeline.firstDurationUs : sample.duration ?? 0;
|
|
49
|
+
if (timestamp >= endUs || timestamp + duration <= startUs) continue;
|
|
50
|
+
if (first === -1) first = i;
|
|
51
|
+
last = i + 1;
|
|
52
|
+
}
|
|
53
|
+
if (first === -1) return chunks;
|
|
54
|
+
for (let i = Math.max(0, first - 2); i < last; i++) {
|
|
55
|
+
const sample = samples[i];
|
|
56
|
+
const timestamp = sample.timestamp - (i === 0 ? 0 : timeline.shiftUs);
|
|
57
|
+
const duration = i === 0 ? timeline.firstDurationUs : sample.duration ?? 0;
|
|
58
|
+
const data = new Uint8Array(sample.byteLength);
|
|
59
|
+
sample.copyTo(data);
|
|
60
|
+
chunks.push(
|
|
61
|
+
new EncodedAudioChunk({
|
|
62
|
+
type: sample.type,
|
|
63
|
+
timestamp: Math.round(timestamp),
|
|
64
|
+
duration: Math.round(duration),
|
|
65
|
+
data
|
|
66
|
+
})
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
return chunks;
|
|
70
|
+
}
|
|
71
|
+
export {
|
|
72
|
+
getAACWindow,
|
|
73
|
+
prepareAACTimeline
|
|
74
|
+
};
|
|
75
|
+
//# sourceMappingURL=aac-window-timeline.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"aac-window-timeline.js","sources":["../../src/orchestrator/aac-window-timeline.ts"],"sourcesContent":["import type { AudioSampleRecord } from '../cache/resource/AudioSampleCache';\nimport { AudioChunkDecoder } from '../stages/decode/AudioChunkDecoder';\n\nexport interface AACWindowTimeline {\n firstDurationUs: number;\n shiftUs: number;\n durationUs: number;\n}\n\n/** Measure anomalous AAC prefixes instead of treating container duration as PCM length. */\nexport async function prepareAACTimeline(\n record: AudioSampleRecord\n): Promise<AACWindowTimeline | undefined> {\n const { samples, metadata } = record;\n const first = samples[0];\n if (!metadata.codec.startsWith('mp4a') || !first || samples.length < 2) return undefined;\n const toleranceUs = 1_000_000 / metadata.sampleRate;\n const followingDuration = samples[1]!.duration ?? 0;\n if (followingDuration <= 0 || (first.duration ?? 0) <= followingDuration + toleranceUs)\n return undefined;\n\n const description = metadata.description;\n const decoder = new AudioChunkDecoder('aac-prefix', {\n ...metadata,\n description: description\n ? new Uint8Array(\n ArrayBuffer.isView(description)\n ? new Uint8Array(description.buffer, description.byteOffset, description.byteLength)\n : new Uint8Array(description)\n ).buffer\n : undefined,\n });\n const input = new ReadableStream<EncodedAudioChunk>({\n start(controller) {\n controller.enqueue(first);\n controller.close();\n },\n });\n const reader = input.pipeThrough(decoder.createStream()).getReader();\n let durationUs = 0;\n try {\n while (true) {\n const { value, done } = await reader.read();\n if (done) break;\n durationUs += (value.numberOfFrames * 1_000_000) / value.sampleRate;\n value.close();\n }\n } finally {\n reader.releaseLock();\n await decoder.close();\n }\n if (durationUs <= 0) throw new Error('AAC prefix produced no PCM');\n const shiftUs = (first.duration ?? 0) - durationUs;\n if (shiftUs <= toleranceUs) return undefined;\n return { firstDurationUs: durationUs, shiftUs, durationUs: record.durationUs - shiftUs };\n}\n\n/** Only copy the requested encoded window; keep the resource's compressed samples shared. */\nexport function getAACWindow(\n samples: EncodedAudioChunk[],\n timeline: AACWindowTimeline,\n startUs: number,\n endUs: number\n): EncodedAudioChunk[] {\n const chunks: EncodedAudioChunk[] = [];\n let first = -1;\n let last = 0;\n for (let i = 0; i < samples.length; i++) {\n const sample = samples[i]!;\n const timestamp = sample.timestamp - (i === 0 ? 0 : timeline.shiftUs);\n const duration = i === 0 ? timeline.firstDurationUs : (sample.duration ?? 0);\n if (timestamp >= endUs || timestamp + duration <= startUs) continue;\n if (first === -1) first = i;\n last = i + 1;\n }\n if (first === -1) return chunks;\n // Restore AAC synthesis state for cold seeks without decoding the whole prefix.\n for (let i = Math.max(0, first - 2); i < last; i++) {\n const sample = samples[i]!;\n const timestamp = sample.timestamp - (i === 0 ? 0 : timeline.shiftUs);\n const duration = i === 0 ? timeline.firstDurationUs : (sample.duration ?? 0);\n const data = new Uint8Array(sample.byteLength);\n sample.copyTo(data);\n chunks.push(\n new EncodedAudioChunk({\n type: sample.type,\n timestamp: Math.round(timestamp),\n duration: Math.round(duration),\n data,\n })\n );\n }\n return chunks;\n}\n"],"names":[],"mappings":";AAUA,eAAsB,mBACpB,QACwC;AACxC,QAAM,EAAE,SAAS,SAAA,IAAa;AAC9B,QAAM,QAAQ,QAAQ,CAAC;AACvB,MAAI,CAAC,SAAS,MAAM,WAAW,MAAM,KAAK,CAAC,SAAS,QAAQ,SAAS,EAAG,QAAO;AAC/E,QAAM,cAAc,MAAY,SAAS;AACzC,QAAM,oBAAoB,QAAQ,CAAC,EAAG,YAAY;AAClD,MAAI,qBAAqB,MAAM,MAAM,YAAY,MAAM,oBA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