@meframe/core 0.6.12 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +55 -0
- package/README.md +17 -5
- package/dist/Meframe.d.ts +14 -3
- package/dist/Meframe.d.ts.map +1 -1
- package/dist/Meframe.js +22 -12
- package/dist/Meframe.js.map +1 -1
- package/dist/cache/CacheManager.d.ts +2 -0
- package/dist/cache/CacheManager.d.ts.map +1 -1
- package/dist/cache/CacheManager.js +5 -0
- package/dist/cache/CacheManager.js.map +1 -1
- package/dist/cache/l1/VideoL1Cache.d.ts +2 -0
- package/dist/cache/l1/VideoL1Cache.d.ts.map +1 -1
- package/dist/cache/l1/VideoL1Cache.js +13 -7
- package/dist/cache/l1/VideoL1Cache.js.map +1 -1
- package/dist/cache/resource/ResourceCache.d.ts +0 -12
- package/dist/cache/resource/ResourceCache.d.ts.map +1 -1
- package/dist/cache/resource/ResourceCache.js +0 -24
- package/dist/cache/resource/ResourceCache.js.map +1 -1
- package/dist/config/defaults.d.ts.map +1 -1
- package/dist/config/defaults.js +4 -1
- package/dist/config/defaults.js.map +1 -1
- package/dist/config/index.d.ts +1 -1
- package/dist/config/index.d.ts.map +1 -1
- package/dist/config/types.d.ts +29 -0
- package/dist/config/types.d.ts.map +1 -1
- package/dist/config/validation.d.ts.map +1 -1
- package/dist/config/validation.js +3 -0
- package/dist/config/validation.js.map +1 -1
- package/dist/controllers/PlaybackController.d.ts +38 -9
- package/dist/controllers/PlaybackController.d.ts.map +1 -1
- package/dist/controllers/PlaybackController.js +269 -154
- package/dist/controllers/PlaybackController.js.map +1 -1
- package/dist/controllers/PlaybackStateMachine.d.ts.map +1 -1
- package/dist/controllers/PlaybackStateMachine.js +2 -1
- package/dist/controllers/PlaybackStateMachine.js.map +1 -1
- package/dist/controllers/types.d.ts +10 -2
- package/dist/controllers/types.d.ts.map +1 -1
- package/dist/controllers/types.js.map +1 -1
- package/dist/event/events.d.ts +2 -0
- package/dist/event/events.d.ts.map +1 -1
- package/dist/event/events.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/model/CompositionModel.d.ts +0 -1
- package/dist/model/CompositionModel.d.ts.map +1 -1
- package/dist/model/CompositionModel.js +0 -6
- package/dist/model/CompositionModel.js.map +1 -1
- package/dist/model/patch.js +12 -12
- package/dist/model/patch.js.map +1 -1
- package/dist/node_modules/.pnpm/{mp4-muxer@5.2.2 → mp4-muxer@5.2.2_patch_hash_452653ac44da4ef32d244694e500e34d084eaa3c4232515ddec962eacc5f30ea}/node_modules/mp4-muxer/build/mp4-muxer.js +17 -3
- package/dist/node_modules/.pnpm/mp4-muxer@5.2.2_patch_hash_452653ac44da4ef32d244694e500e34d084eaa3c4232515ddec962eacc5f30ea/node_modules/mp4-muxer/build/mp4-muxer.js.map +1 -0
- package/dist/node_modules/.pnpm/mp4box@0.5.4/node_modules/mp4box/dist/mp4box.all.js +36 -12
- package/dist/node_modules/.pnpm/mp4box@0.5.4/node_modules/mp4box/dist/mp4box.all.js.map +1 -1
- package/dist/orchestrator/AudioExportSession.d.ts +28 -3
- package/dist/orchestrator/AudioExportSession.d.ts.map +1 -1
- package/dist/orchestrator/AudioExportSession.js +131 -15
- package/dist/orchestrator/AudioExportSession.js.map +1 -1
- package/dist/orchestrator/AudioPreviewSession.d.ts +6 -1
- package/dist/orchestrator/AudioPreviewSession.d.ts.map +1 -1
- package/dist/orchestrator/AudioPreviewSession.js +57 -18
- package/dist/orchestrator/AudioPreviewSession.js.map +1 -1
- package/dist/orchestrator/AudioWindowPreparer.d.ts +9 -7
- package/dist/orchestrator/AudioWindowPreparer.d.ts.map +1 -1
- package/dist/orchestrator/AudioWindowPreparer.js +111 -36
- package/dist/orchestrator/AudioWindowPreparer.js.map +1 -1
- package/dist/orchestrator/CompositionPlanner.d.ts +5 -2
- package/dist/orchestrator/CompositionPlanner.d.ts.map +1 -1
- package/dist/orchestrator/CompositionPlanner.js +8 -3
- package/dist/orchestrator/CompositionPlanner.js.map +1 -1
- package/dist/orchestrator/ExportScheduler.d.ts +1 -0
- package/dist/orchestrator/ExportScheduler.d.ts.map +1 -1
- package/dist/orchestrator/ExportScheduler.js +177 -106
- package/dist/orchestrator/ExportScheduler.js.map +1 -1
- package/dist/orchestrator/Orchestrator.d.ts +30 -4
- package/dist/orchestrator/Orchestrator.d.ts.map +1 -1
- package/dist/orchestrator/Orchestrator.js +264 -111
- package/dist/orchestrator/Orchestrator.js.map +1 -1
- package/dist/orchestrator/PreviewFrameScheduler.d.ts +21 -1
- package/dist/orchestrator/PreviewFrameScheduler.d.ts.map +1 -1
- package/dist/orchestrator/PreviewFrameScheduler.js +129 -30
- package/dist/orchestrator/PreviewFrameScheduler.js.map +1 -1
- package/dist/orchestrator/VideoWindowDecodeSession.d.ts +22 -1
- package/dist/orchestrator/VideoWindowDecodeSession.d.ts.map +1 -1
- package/dist/orchestrator/VideoWindowDecodeSession.js +426 -198
- package/dist/orchestrator/VideoWindowDecodeSession.js.map +1 -1
- package/dist/orchestrator/aac-window-timeline.d.ts +7 -2
- package/dist/orchestrator/aac-window-timeline.d.ts.map +1 -1
- package/dist/orchestrator/aac-window-timeline.js +19 -9
- package/dist/orchestrator/aac-window-timeline.js.map +1 -1
- package/dist/orchestrator/types.d.ts +5 -1
- package/dist/orchestrator/types.d.ts.map +1 -1
- package/dist/stages/compose/FrameRateConverter.d.ts +2 -1
- package/dist/stages/compose/FrameRateConverter.d.ts.map +1 -1
- package/dist/stages/compose/LayerRenderPolicy.d.ts +14 -0
- package/dist/stages/compose/LayerRenderPolicy.d.ts.map +1 -0
- package/dist/stages/compose/LayerRenderPolicy.js +18 -0
- package/dist/stages/compose/LayerRenderPolicy.js.map +1 -0
- package/dist/stages/compose/OfflineAudioMixer.d.ts +2 -0
- package/dist/stages/compose/OfflineAudioMixer.d.ts.map +1 -1
- package/dist/stages/compose/OfflineAudioMixer.js +14 -2
- package/dist/stages/compose/OfflineAudioMixer.js.map +1 -1
- package/dist/stages/compose/OwnedFrameTransform.d.ts +52 -0
- package/dist/stages/compose/OwnedFrameTransform.d.ts.map +1 -0
- package/dist/stages/compose/OwnedFrameTransform.js +154 -0
- package/dist/stages/compose/OwnedFrameTransform.js.map +1 -0
- package/dist/stages/compose/TransitionProcessor.js +0 -1
- package/dist/stages/compose/TransitionProcessor.js.map +1 -1
- package/dist/stages/compose/VideoComposer.d.ts +12 -2
- package/dist/stages/compose/VideoComposer.d.ts.map +1 -1
- package/dist/stages/compose/VideoComposer.js +100 -92
- package/dist/stages/compose/VideoComposer.js.map +1 -1
- package/dist/stages/compose/text-renderers/basic-text-renderer.d.ts.map +1 -1
- package/dist/stages/compose/text-renderers/basic-text-renderer.js +24 -21
- package/dist/stages/compose/text-renderers/basic-text-renderer.js.map +1 -1
- package/dist/stages/compose/text-renderers/caption-stagger-entrance-renderer.d.ts.map +1 -1
- package/dist/stages/compose/text-renderers/caption-stagger-entrance-renderer.js +110 -99
- package/dist/stages/compose/text-renderers/caption-stagger-entrance-renderer.js.map +1 -1
- package/dist/stages/compose/text-renderers/character-ktv-renderer.d.ts.map +1 -1
- package/dist/stages/compose/text-renderers/character-ktv-renderer.js +41 -38
- package/dist/stages/compose/text-renderers/character-ktv-renderer.js.map +1 -1
- package/dist/stages/compose/text-renderers/word-by-word-renderer.d.ts.map +1 -1
- package/dist/stages/compose/text-renderers/word-by-word-renderer.js +47 -39
- package/dist/stages/compose/text-renderers/word-by-word-renderer.js.map +1 -1
- package/dist/stages/compose/text-renderers/word-fancy-renderer.d.ts.map +1 -1
- package/dist/stages/compose/text-renderers/word-fancy-renderer.js +54 -48
- package/dist/stages/compose/text-renderers/word-fancy-renderer.js.map +1 -1
- package/dist/stages/compose/text-utils/text-metrics.d.ts.map +1 -1
- package/dist/stages/compose/text-utils/text-metrics.js +6 -4
- package/dist/stages/compose/text-utils/text-metrics.js.map +1 -1
- package/dist/stages/compose/types.d.ts +12 -0
- package/dist/stages/compose/types.d.ts.map +1 -1
- package/dist/stages/decode/AudioChunkDecoder.d.ts.map +1 -1
- package/dist/stages/decode/AudioChunkDecoder.js +2 -1
- package/dist/stages/decode/AudioChunkDecoder.js.map +1 -1
- package/dist/stages/decode/BaseDecoder.d.ts +5 -0
- package/dist/stages/decode/BaseDecoder.d.ts.map +1 -1
- package/dist/stages/decode/BaseDecoder.js +52 -10
- package/dist/stages/decode/BaseDecoder.js.map +1 -1
- package/dist/stages/decode/preview-video-decoder.d.ts +48 -2
- package/dist/stages/decode/preview-video-decoder.d.ts.map +1 -1
- package/dist/stages/decode/preview-video-decoder.js +241 -71
- package/dist/stages/decode/preview-video-decoder.js.map +1 -1
- package/dist/stages/decode/video-decoder.d.ts +2 -11
- package/dist/stages/decode/video-decoder.d.ts.map +1 -1
- package/dist/stages/decode/video-decoder.js +60 -61
- package/dist/stages/decode/video-decoder.js.map +1 -1
- package/dist/stages/demux/MP4Demuxer.d.ts +1 -0
- package/dist/stages/demux/MP4Demuxer.d.ts.map +1 -1
- package/dist/stages/demux/MP4Demuxer.js +4 -1
- package/dist/stages/demux/MP4Demuxer.js.map +1 -1
- package/dist/stages/demux/MP4IndexParser.d.ts.map +1 -1
- package/dist/stages/demux/MP4IndexParser.js +11 -3
- package/dist/stages/demux/MP4IndexParser.js.map +1 -1
- package/dist/stages/encode/BaseEncoder.d.ts +9 -2
- package/dist/stages/encode/BaseEncoder.d.ts.map +1 -1
- package/dist/stages/encode/BaseEncoder.js +90 -59
- package/dist/stages/encode/BaseEncoder.js.map +1 -1
- package/dist/stages/load/ResourceLoader.d.ts +69 -8
- package/dist/stages/load/ResourceLoader.d.ts.map +1 -1
- package/dist/stages/load/ResourceLoader.js +248 -67
- package/dist/stages/load/ResourceLoader.js.map +1 -1
- package/dist/stages/load/TaskManager.d.ts.map +1 -1
- package/dist/stages/load/TaskManager.js +9 -3
- package/dist/stages/load/TaskManager.js.map +1 -1
- package/dist/stages/load/types.d.ts +2 -2
- package/dist/stages/load/types.d.ts.map +1 -1
- package/dist/stages/mux/MP4Muxer.d.ts +7 -1
- package/dist/stages/mux/MP4Muxer.d.ts.map +1 -1
- package/dist/stages/mux/MP4Muxer.js +8 -10
- package/dist/stages/mux/MP4Muxer.js.map +1 -1
- package/dist/stages/mux/MuxManager.d.ts +7 -0
- package/dist/stages/mux/MuxManager.d.ts.map +1 -1
- package/dist/stages/mux/MuxManager.js +9 -0
- package/dist/stages/mux/MuxManager.js.map +1 -1
- package/dist/types.d.ts +1 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/utils/errors.d.ts +2 -0
- package/dist/utils/errors.d.ts.map +1 -1
- package/dist/utils/errors.js +10 -1
- package/dist/utils/errors.js.map +1 -1
- package/dist/utils/mp4box.js +2 -2
- package/dist/utils/mp4box.js.map +1 -1
- package/dist/utils/until-aborted.d.ts +8 -0
- package/dist/utils/until-aborted.d.ts.map +1 -0
- package/dist/utils/until-aborted.js +33 -0
- package/dist/utils/until-aborted.js.map +1 -0
- package/dist/worker/WorkerChannel.d.ts.map +1 -1
- package/dist/worker/WorkerChannel.js +45 -10
- package/dist/worker/WorkerChannel.js.map +1 -1
- package/dist/worker/worker-manifest.js +1 -1
- package/dist/worker/worker-manifest.js.map +1 -1
- package/dist/workers/stages/export/{export.worker.BepPfuIx.js → export.worker.BG8HA7dY.js} +745 -450
- package/dist/workers/stages/export/export.worker.BG8HA7dY.js.map +1 -0
- package/dist/workers/worker-manifest.json +1 -1
- package/package.json +22 -23
- package/dist/node_modules/.pnpm/mp4-muxer@5.2.2/node_modules/mp4-muxer/build/mp4-muxer.js.map +0 -1
- package/dist/workers/stages/export/export.worker.BepPfuIx.js.map +0 -1
|
@@ -1,88 +1,258 @@
|
|
|
1
1
|
import { getRecommendedHardwareAcceleration } from "../../utils/platform-utils.js";
|
|
2
2
|
import { playbackDiagnostic } from "../../utils/playback-diagnostics.js";
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
settled = true;
|
|
18
|
-
clearTimeout(timer);
|
|
19
|
-
clearInterval(abortTimer);
|
|
20
|
-
if (decoder.state !== "closed") decoder.close();
|
|
21
|
-
if (error) reject(error);
|
|
22
|
-
else resolve();
|
|
3
|
+
const MAX_DECODE_QUEUE_SIZE = 4;
|
|
4
|
+
const YIELD_EVERY_CHUNKS = 4;
|
|
5
|
+
const DECODE_STALL_TIMEOUT_MS = 5e3;
|
|
6
|
+
const MAX_PENDING_FRAMES = 24;
|
|
7
|
+
function yieldToMain() {
|
|
8
|
+
if (typeof MessageChannel === "undefined") {
|
|
9
|
+
return new Promise((resolve) => setTimeout(resolve, 0));
|
|
10
|
+
}
|
|
11
|
+
return new Promise((resolve) => {
|
|
12
|
+
const channel = new MessageChannel();
|
|
13
|
+
channel.port1.onmessage = () => {
|
|
14
|
+
channel.port1.close();
|
|
15
|
+
channel.port2.close();
|
|
16
|
+
resolve();
|
|
23
17
|
};
|
|
18
|
+
channel.port2.postMessage(void 0);
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
class PersistentPreviewVideoDecoder {
|
|
22
|
+
constructor(config, hardwareAcceleration = config.hardwareAcceleration ?? getRecommendedHardwareAcceleration()) {
|
|
23
|
+
this.config = config;
|
|
24
|
+
this.hardwareAcceleration = hardwareAcceleration;
|
|
25
|
+
}
|
|
26
|
+
decoder = null;
|
|
27
|
+
pendingFrames = [];
|
|
28
|
+
pendingChunk = null;
|
|
29
|
+
closed = false;
|
|
30
|
+
flushed = false;
|
|
31
|
+
droppedPending = false;
|
|
32
|
+
fatalError = null;
|
|
33
|
+
activeRun = null;
|
|
34
|
+
targetReached = false;
|
|
35
|
+
get isOpen() {
|
|
36
|
+
return !this.closed && !this.flushed && !this.droppedPending && this.fatalError === null && this.decoder !== null && this.decoder.state === "configured";
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* A later window can continue here: the decoder takes more input, or it reached the end of the
|
|
40
|
+
* stream and still holds frames past the previous window's end.
|
|
41
|
+
*/
|
|
42
|
+
get canContinue() {
|
|
43
|
+
return this.isOpen || this.flushedIntact && this.pendingFrames.length > 0;
|
|
44
|
+
}
|
|
45
|
+
/** The stream was read to its end and every frame was handed out: there is nothing left to decode. */
|
|
46
|
+
get isExhausted() {
|
|
47
|
+
return this.flushedIntact && this.pendingFrames.length === 0;
|
|
48
|
+
}
|
|
49
|
+
get flushedIntact() {
|
|
50
|
+
return this.flushed && !this.closed && !this.droppedPending && this.fatalError === null;
|
|
51
|
+
}
|
|
52
|
+
get earliestPendingPtsUs() {
|
|
53
|
+
return this.pendingFrames.length > 0 ? this.pendingFrames[0].timestamp : Infinity;
|
|
54
|
+
}
|
|
55
|
+
open() {
|
|
56
|
+
if (this.closed) throw new Error("Preview decoder already closed");
|
|
57
|
+
if (this.decoder) return;
|
|
24
58
|
const decoder = new VideoDecoder({
|
|
25
|
-
output(frame)
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
59
|
+
output: (frame) => this.handleOutput(frame),
|
|
60
|
+
error: (error) => this.handleError(error)
|
|
61
|
+
});
|
|
62
|
+
decoder.ondequeue = () => this.activeRun?.wake();
|
|
63
|
+
decoder.configure({
|
|
64
|
+
codec: this.config.codec,
|
|
65
|
+
codedWidth: this.config.width,
|
|
66
|
+
codedHeight: this.config.height,
|
|
67
|
+
description: this.config.description,
|
|
68
|
+
hardwareAcceleration: this.hardwareAcceleration,
|
|
69
|
+
// Low latency turns off FFmpeg's frame threads: a software decoder would run on one core.
|
|
70
|
+
optimizeForLatency: this.hardwareAcceleration !== "prefer-software"
|
|
71
|
+
});
|
|
72
|
+
this.decoder = decoder;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Drain held frames first, then pull and decode chunks via `nextChunk` until `onFrame`
|
|
76
|
+
* returns `'hold'` (target end reached), `nextChunk` returns `null` (end of stream -> flush),
|
|
77
|
+
* or `shouldAbort()` becomes true.
|
|
78
|
+
*/
|
|
79
|
+
async decodeUntil(nextChunk, onFrame, shouldAbort) {
|
|
80
|
+
if (this.closed || shouldAbort()) return { reachedTarget: false, flushed: this.flushed };
|
|
81
|
+
if (this.fatalError !== null) throw this.fatalError;
|
|
82
|
+
while (this.pendingFrames.length > 0) {
|
|
83
|
+
if (this.closed || shouldAbort()) return { reachedTarget: false, flushed: this.flushed };
|
|
84
|
+
const frame = this.pendingFrames.shift();
|
|
85
|
+
if (this.deliver(frame, onFrame) === "hold") {
|
|
86
|
+
this.pendingFrames.unshift(frame);
|
|
87
|
+
return { reachedTarget: true, flushed: this.flushed };
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (this.flushed) return { reachedTarget: false, flushed: true };
|
|
91
|
+
this.open();
|
|
92
|
+
const decoder = this.decoder;
|
|
93
|
+
this.targetReached = false;
|
|
94
|
+
let wakeResolver = null;
|
|
95
|
+
let abortFailure = null;
|
|
96
|
+
let abandonFlush = null;
|
|
97
|
+
let settledError = null;
|
|
98
|
+
let stallTimer = null;
|
|
99
|
+
const wake = () => {
|
|
100
|
+
const resolve = wakeResolver;
|
|
101
|
+
wakeResolver = null;
|
|
102
|
+
resolve?.();
|
|
103
|
+
};
|
|
104
|
+
const fail = (error) => {
|
|
105
|
+
settledError = error;
|
|
106
|
+
const reject = abortFailure;
|
|
107
|
+
abortFailure = null;
|
|
108
|
+
wake();
|
|
109
|
+
reject?.(error);
|
|
110
|
+
};
|
|
111
|
+
const resetStallTimer = () => {
|
|
112
|
+
if (stallTimer) clearTimeout(stallTimer);
|
|
113
|
+
stallTimer = setTimeout(() => {
|
|
114
|
+
fail(new Error("Preview decode timed out"));
|
|
115
|
+
}, DECODE_STALL_TIMEOUT_MS);
|
|
116
|
+
};
|
|
117
|
+
const abortTimer = setInterval(() => {
|
|
118
|
+
if (!shouldAbort()) return;
|
|
119
|
+
wake();
|
|
120
|
+
abandonFlush?.();
|
|
121
|
+
}, 10);
|
|
122
|
+
this.activeRun = {
|
|
123
|
+
onFrame: (frame) => {
|
|
124
|
+
resetStallTimer();
|
|
125
|
+
return onFrame(frame);
|
|
126
|
+
},
|
|
127
|
+
onTargetReached: () => {
|
|
128
|
+
this.targetReached = true;
|
|
129
|
+
wake();
|
|
130
|
+
},
|
|
131
|
+
wake,
|
|
132
|
+
fail
|
|
133
|
+
};
|
|
134
|
+
resetStallTimer();
|
|
135
|
+
try {
|
|
136
|
+
let fedCount = 0;
|
|
137
|
+
let hitEof = false;
|
|
138
|
+
while (!this.closed && !shouldAbort() && !this.targetReached && settledError === null) {
|
|
139
|
+
if (fedCount > 0 && fedCount % YIELD_EVERY_CHUNKS === 0) {
|
|
140
|
+
await yieldToMain();
|
|
29
141
|
}
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
duration: frame.duration
|
|
142
|
+
while (!this.closed && !shouldAbort() && !this.targetReached && settledError === null && decoder.decodeQueueSize >= MAX_DECODE_QUEUE_SIZE) {
|
|
143
|
+
await new Promise((resolve) => {
|
|
144
|
+
wakeResolver = resolve;
|
|
34
145
|
});
|
|
35
|
-
if (onFrame(frame) === true) finish();
|
|
36
|
-
} catch (error) {
|
|
37
|
-
frame.close();
|
|
38
|
-
finish(error);
|
|
39
146
|
}
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
}, 10);
|
|
47
|
-
const feed = async () => {
|
|
48
|
-
decoder.configure({
|
|
49
|
-
codec: config.codec,
|
|
50
|
-
codedWidth: config.width,
|
|
51
|
-
codedHeight: config.height,
|
|
52
|
-
description: config.description,
|
|
53
|
-
hardwareAcceleration,
|
|
54
|
-
optimizeForLatency: true
|
|
55
|
-
});
|
|
56
|
-
for (let i = 0; i < chunks.length; i++) {
|
|
57
|
-
if (i % 4 === 0) await new Promise((r) => setTimeout(r, 0));
|
|
58
|
-
while (!settled && !shouldAbort() && decoder.decodeQueueSize >= 4) {
|
|
59
|
-
await new Promise((r) => setTimeout(r, 0));
|
|
147
|
+
if (this.closed || shouldAbort() || this.targetReached || settledError !== null) break;
|
|
148
|
+
this.pendingChunk ??= await nextChunk();
|
|
149
|
+
if (this.closed || shouldAbort() || this.targetReached || settledError !== null) break;
|
|
150
|
+
if (!this.pendingChunk) {
|
|
151
|
+
hitEof = true;
|
|
152
|
+
break;
|
|
60
153
|
}
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
154
|
+
resetStallTimer();
|
|
155
|
+
decoder.decode(this.pendingChunk);
|
|
156
|
+
this.pendingChunk = null;
|
|
157
|
+
fedCount++;
|
|
158
|
+
}
|
|
159
|
+
if (settledError !== null) throw settledError;
|
|
160
|
+
if (hitEof && !this.closed && !shouldAbort() && !this.targetReached) {
|
|
161
|
+
const flushed = await Promise.race([
|
|
162
|
+
decoder.flush().then(() => true),
|
|
163
|
+
new Promise((resolve, reject) => {
|
|
164
|
+
abortFailure = reject;
|
|
165
|
+
abandonFlush = () => resolve(false);
|
|
166
|
+
})
|
|
167
|
+
]);
|
|
168
|
+
if (flushed) {
|
|
169
|
+
this.flushed = true;
|
|
170
|
+
this.closeDecoderOnly();
|
|
171
|
+
playbackDiagnostic("decoder.flush-complete", { chunks: fedCount });
|
|
65
172
|
}
|
|
66
|
-
decoder.decode(chunks[i]);
|
|
67
173
|
}
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
174
|
+
if (settledError !== null) throw settledError;
|
|
175
|
+
return { reachedTarget: this.targetReached, flushed: this.flushed };
|
|
176
|
+
} finally {
|
|
177
|
+
if (stallTimer) clearTimeout(stallTimer);
|
|
178
|
+
clearInterval(abortTimer);
|
|
179
|
+
this.activeRun = null;
|
|
180
|
+
abortFailure = null;
|
|
181
|
+
abandonFlush = null;
|
|
182
|
+
wakeResolver = null;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
close() {
|
|
186
|
+
if (this.closed) return;
|
|
187
|
+
this.closed = true;
|
|
188
|
+
const run = this.activeRun;
|
|
189
|
+
this.activeRun = null;
|
|
190
|
+
run?.wake();
|
|
191
|
+
this.closeDecoderOnly();
|
|
192
|
+
this.pendingChunk = null;
|
|
193
|
+
for (const frame of this.pendingFrames.splice(0)) {
|
|
194
|
+
frame.close();
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
closeDecoderOnly() {
|
|
198
|
+
const decoder = this.decoder;
|
|
199
|
+
this.decoder = null;
|
|
200
|
+
if (decoder && decoder.state !== "closed") {
|
|
201
|
+
decoder.ondequeue = null;
|
|
202
|
+
decoder.close();
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
handleOutput(frame) {
|
|
206
|
+
if (this.closed) {
|
|
207
|
+
frame.close();
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
playbackDiagnostic("decoder.frame", {
|
|
211
|
+
timestamp: frame.timestamp,
|
|
212
|
+
duration: frame.duration
|
|
213
|
+
});
|
|
214
|
+
const run = this.activeRun;
|
|
215
|
+
if (!run || this.targetReached) {
|
|
216
|
+
this.holdFrame(frame);
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
try {
|
|
220
|
+
if (this.deliver(frame, run.onFrame) === "hold") {
|
|
221
|
+
this.holdFrame(frame);
|
|
222
|
+
run.onTargetReached();
|
|
223
|
+
} else {
|
|
224
|
+
run.wake();
|
|
225
|
+
}
|
|
226
|
+
} catch (error) {
|
|
227
|
+
run.fail(error);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
/** A frame whose callback throws is closed here, and the decoder does not continue past it. */
|
|
231
|
+
deliver(frame, onFrame) {
|
|
232
|
+
try {
|
|
233
|
+
return onFrame(frame);
|
|
234
|
+
} catch (error) {
|
|
235
|
+
frame.close();
|
|
236
|
+
this.fatalError = error;
|
|
81
237
|
throw error;
|
|
82
238
|
}
|
|
83
239
|
}
|
|
240
|
+
holdFrame(frame) {
|
|
241
|
+
if (this.pendingFrames.length >= MAX_PENDING_FRAMES) {
|
|
242
|
+
this.droppedPending = true;
|
|
243
|
+
this.pendingFrames.shift()?.close();
|
|
244
|
+
}
|
|
245
|
+
this.pendingFrames.push(frame);
|
|
246
|
+
}
|
|
247
|
+
handleError(error) {
|
|
248
|
+
this.fatalError = error;
|
|
249
|
+
const run = this.activeRun;
|
|
250
|
+
this.closeDecoderOnly();
|
|
251
|
+
run?.fail(error);
|
|
252
|
+
}
|
|
84
253
|
}
|
|
85
254
|
export {
|
|
86
|
-
|
|
255
|
+
PersistentPreviewVideoDecoder,
|
|
256
|
+
yieldToMain
|
|
87
257
|
};
|
|
88
258
|
//# sourceMappingURL=preview-video-decoder.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"preview-video-decoder.js","sources":["../../../src/stages/decode/preview-video-decoder.ts"],"sourcesContent":["import type { VideoDecoderConfig } from './video-decoder';\nimport { getRecommendedHardwareAcceleration } from '../../utils/platform-utils';\nimport { playbackDiagnostic } from '../../utils/playback-diagnostics';\n\n/** Stream output directly to the cache; never retain a whole window of native frames. */\nexport async function decodePreviewChunks(\n chunks: EncodedVideoChunk[],\n config: VideoDecoderConfig,\n onFrame: (frame: VideoFrame) => boolean | void,\n shouldAbort: () => boolean\n): Promise<void> {\n if (chunks.length === 0 || shouldAbort()) return;\n playbackDiagnostic('decoder.start', {\n chunks: chunks.length,\n codec: config.codec,\n width: config.width,\n height: config.height,\n });\n const run = (hardwareAcceleration: HardwareAcceleration) =>\n new Promise<void>((resolve, reject) => {\n let settled = false;\n let timer: ReturnType<typeof setTimeout>;\n let abortTimer: ReturnType<typeof setInterval>;\n const finish = (error?: unknown) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n clearInterval(abortTimer);\n if (decoder.state !== 'closed') decoder.close();\n if (error) reject(error);\n else resolve();\n };\n const decoder = new VideoDecoder({\n output(frame) {\n if (settled || shouldAbort()) {\n frame.close();\n return;\n }\n try {\n playbackDiagnostic('decoder.frame', {\n timestamp: frame.timestamp,\n duration: frame.duration,\n });\n if (onFrame(frame) === true) finish();\n } catch (error) {\n frame.close();\n finish(error);\n }\n },\n error: finish,\n });\n timer = setTimeout(() => finish(new Error('Preview decode timed out')), 5000);\n abortTimer = setInterval(() => {\n if (shouldAbort()) finish();\n }, 10);\n const feed = async () => {\n decoder.configure({\n codec: config.codec,\n codedWidth: config.width,\n codedHeight: config.height,\n description: config.description,\n hardwareAcceleration,\n optimizeForLatency: true,\n });\n for (let i = 0; i < chunks.length; i++) {\n // Yield even when decodeQueueSize drains synchronously, so large GOPs cannot\n // monopolize the event loop. A bounded queue also limits native surfaces.\n if (i % 4 === 0) await new Promise((r) => setTimeout(r, 0));\n while (!settled && !shouldAbort() && decoder.decodeQueueSize >= 4) {\n await new Promise((r) => setTimeout(r, 0));\n }\n if (settled) return;\n if (shouldAbort()) {\n finish();\n return;\n }\n decoder.decode(chunks[i]!);\n }\n // Queue size reaching zero does not mean reordered HEVC output is complete.\n await decoder.flush();\n playbackDiagnostic('decoder.flush-complete', { chunks: chunks.length });\n finish();\n };\n void feed().catch(finish);\n });\n const acceleration = config.hardwareAcceleration ?? getRecommendedHardwareAcceleration();\n try {\n await run(acceleration);\n } catch (error) {\n if (\n !shouldAbort() &&\n acceleration !== 'prefer-software' &&\n error instanceof Error &&\n error.message === 'Decoding error.'\n ) {\n await run('prefer-software');\n } else if (!shouldAbort()) {\n throw error;\n }\n }\n}\n"],"names":[],"mappings":";;AAKA,eAAsB,oBACpB,QACA,QACA,SACA,aACe;AACf,MAAI,OAAO,WAAW,KAAK,YAAA,EAAe;AAC1C,qBAAmB,iBAAiB;AAAA,IAClC,QAAQ,OAAO;AAAA,IACf,OAAO,OAAO;AAA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iBAAiB,QAAQ,mBAAmB,GAAG;AACjE,gBAAM,IAAI,QAAQ,CAAC,MAAM,WAAW,GAAG,CAAC,CAAC;AAAA,QAC3C;AACA,YAAI,QAAS;AACb,YAAI,eAAe;AACjB,iBAAA;AACA;AAAA,QACF;AACA,gBAAQ,OAAO,OAAO,CAAC,CAAE;AAAA,MAC3B;AAEA,YAAM,QAAQ,MAAA;AACd,yBAAmB,0BAA0B,EAAE,QAAQ,OAAO,QAAQ;AACtE,aAAA;AAAA,IACF;AACA,SAAK,KAAA,EAAO,MAAM,MAAM;AAAA,EAC1B,CAAC;AACH,QAAM,eAAe,OAAO,wBAAwB,mCAAA;AACpD,MAAI;AACF,UAAM,IAAI,YAAY;AAAA,EACxB,SAAS,OAAO;AACd,QACE,CAAC,iBACD,iBAAiB,qBACjB,iBAAiB,SACjB,MAAM,YAAY,mBAClB;AACA,YAAM,IAAI,iBAAiB;AAAA,IAC7B,WAAW,CAAC,eAAe;AACzB,YAAM;AAAA,IACR;AAAA,EACF;AACF;"}
|
|
1
|
+
{"version":3,"file":"preview-video-decoder.js","sources":["../../../src/stages/decode/preview-video-decoder.ts"],"sourcesContent":["import type { VideoDecoderConfig } from './video-decoder';\nimport { getRecommendedHardwareAcceleration } from '../../utils/platform-utils';\nimport { playbackDiagnostic } from '../../utils/playback-diagnostics';\n\nconst MAX_DECODE_QUEUE_SIZE = 4;\nconst YIELD_EVERY_CHUNKS = 4;\nconst DECODE_STALL_TIMEOUT_MS = 5000;\nconst MAX_PENDING_FRAMES = 24;\n\n/** Yield one macrotask without triggering Chromium's >=4ms nested setTimeout clamp. */\nexport function yieldToMain(): Promise<void> {\n if (typeof MessageChannel === 'undefined') {\n return new Promise((resolve) => setTimeout(resolve, 0));\n }\n return new Promise((resolve) => {\n const channel = new MessageChannel();\n channel.port1.onmessage = () => {\n channel.port1.close();\n channel.port2.close();\n resolve();\n };\n channel.port2.postMessage(undefined);\n });\n}\n\nexport type PreviewFrameDisposition = 'consumed' | 'hold';\n\n/**\n * Stateful preview decoder that stays open across consecutive forward preheat windows.\n * Avoids tearing down VideoDecoder and re-decoding from the GOP keyframe every 250ms.\n */\nexport class PersistentPreviewVideoDecoder {\n private decoder: VideoDecoder | null = null;\n private pendingFrames: VideoFrame[] = [];\n private pendingChunk: EncodedVideoChunk | null = null;\n private closed = false;\n private flushed = false;\n private droppedPending = false;\n private fatalError: unknown = null;\n private activeRun: {\n onFrame: (frame: VideoFrame) => PreviewFrameDisposition;\n onTargetReached: () => void;\n wake: () => void;\n fail: (error: unknown) => void;\n } | null = null;\n private targetReached = false;\n\n constructor(\n private readonly config: VideoDecoderConfig,\n readonly hardwareAcceleration: HardwareAcceleration = config.hardwareAcceleration ??\n getRecommendedHardwareAcceleration()\n ) {}\n\n get isOpen(): boolean {\n return (\n !this.closed &&\n !this.flushed &&\n !this.droppedPending &&\n this.fatalError === null &&\n this.decoder !== null &&\n this.decoder.state === 'configured'\n );\n }\n\n /**\n * A later window can continue here: the decoder takes more input, or it reached the end of the\n * stream and still holds frames past the previous window's end.\n */\n get canContinue(): boolean {\n return this.isOpen || (this.flushedIntact && this.pendingFrames.length > 0);\n }\n\n /** The stream was read to its end and every frame was handed out: there is nothing left to decode. */\n get isExhausted(): boolean {\n return this.flushedIntact && this.pendingFrames.length === 0;\n }\n\n private get flushedIntact(): boolean {\n return this.flushed && !this.closed && !this.droppedPending && this.fatalError === null;\n }\n\n get earliestPendingPtsUs(): number {\n return this.pendingFrames.length > 0 ? this.pendingFrames[0]!.timestamp : Infinity;\n }\n\n open(): void {\n if (this.closed) throw new Error('Preview decoder already closed');\n if (this.decoder) return;\n const decoder = new VideoDecoder({\n output: (frame) => this.handleOutput(frame),\n error: (error) => this.handleError(error),\n });\n decoder.ondequeue = () => this.activeRun?.wake();\n decoder.configure({\n codec: this.config.codec,\n codedWidth: this.config.width,\n codedHeight: this.config.height,\n description: this.config.description,\n hardwareAcceleration: this.hardwareAcceleration,\n // Low latency turns off FFmpeg's frame threads: a software decoder would run on one core.\n optimizeForLatency: this.hardwareAcceleration !== 'prefer-software',\n });\n this.decoder = decoder;\n }\n\n /**\n * Drain held frames first, then pull and decode chunks via `nextChunk` until `onFrame`\n * returns `'hold'` (target end reached), `nextChunk` returns `null` (end of stream -> flush),\n * or `shouldAbort()` becomes true.\n */\n async decodeUntil(\n nextChunk: () => Promise<EncodedVideoChunk | null>,\n onFrame: (frame: VideoFrame) => PreviewFrameDisposition,\n shouldAbort: () => boolean\n ): Promise<{ reachedTarget: boolean; flushed: boolean }> {\n if (this.closed || shouldAbort()) return { reachedTarget: false, flushed: this.flushed };\n if (this.fatalError !== null) throw this.fatalError;\n\n // 1. Drain frames that were already decoded past the previous window's end.\n while (this.pendingFrames.length > 0) {\n if (this.closed || shouldAbort()) return { reachedTarget: false, flushed: this.flushed };\n const frame = this.pendingFrames.shift()!;\n if (this.deliver(frame, onFrame) === 'hold') {\n this.pendingFrames.unshift(frame);\n return { reachedTarget: true, flushed: this.flushed };\n }\n }\n\n if (this.flushed) return { reachedTarget: false, flushed: true };\n\n this.open();\n const decoder = this.decoder!;\n this.targetReached = false;\n let wakeResolver: (() => void) | null = null;\n let abortFailure: ((error: unknown) => void) | null = null;\n let abandonFlush: (() => void) | null = null;\n let settledError: unknown = null;\n let stallTimer: ReturnType<typeof setTimeout> | null = null;\n\n const wake = () => {\n const resolve = wakeResolver;\n wakeResolver = null;\n resolve?.();\n };\n\n const fail = (error: unknown) => {\n settledError = error;\n const reject = abortFailure;\n abortFailure = null;\n wake();\n reject?.(error);\n };\n\n const resetStallTimer = () => {\n if (stallTimer) clearTimeout(stallTimer);\n stallTimer = setTimeout(() => {\n fail(new Error('Preview decode timed out'));\n }, DECODE_STALL_TIMEOUT_MS);\n };\n\n const abortTimer = setInterval(() => {\n if (!shouldAbort()) return;\n wake();\n abandonFlush?.();\n }, 10);\n\n this.activeRun = {\n onFrame: (frame) => {\n resetStallTimer();\n return onFrame(frame);\n },\n onTargetReached: () => {\n this.targetReached = true;\n wake();\n },\n wake,\n fail,\n };\n\n resetStallTimer();\n\n try {\n let fedCount = 0;\n let hitEof = false;\n\n while (!this.closed && !shouldAbort() && !this.targetReached && settledError === null) {\n if (fedCount > 0 && fedCount % YIELD_EVERY_CHUNKS === 0) {\n await yieldToMain();\n }\n while (\n !this.closed &&\n !shouldAbort() &&\n !this.targetReached &&\n settledError === null &&\n decoder.decodeQueueSize >= MAX_DECODE_QUEUE_SIZE\n ) {\n await new Promise<void>((resolve) => {\n wakeResolver = resolve;\n });\n }\n if (this.closed || shouldAbort() || this.targetReached || settledError !== null) break;\n\n // `nextChunk` may wait for a read. When output reaches the target meanwhile, the chunk stays\n // pending: the caller has already moved past it, and the next window must feed it first.\n this.pendingChunk ??= await nextChunk();\n if (this.closed || shouldAbort() || this.targetReached || settledError !== null) break;\n if (!this.pendingChunk) {\n hitEof = true;\n break;\n }\n resetStallTimer();\n decoder.decode(this.pendingChunk);\n this.pendingChunk = null;\n fedCount++;\n }\n\n if (settledError !== null) throw settledError;\n\n if (hitEof && !this.closed && !shouldAbort() && !this.targetReached) {\n const flushed = await Promise.race([\n decoder.flush().then(() => true),\n new Promise<false>((resolve, reject) => {\n abortFailure = reject;\n abandonFlush = () => resolve(false);\n }),\n ]);\n if (flushed) {\n this.flushed = true;\n this.closeDecoderOnly();\n playbackDiagnostic('decoder.flush-complete', { chunks: fedCount });\n }\n }\n\n if (settledError !== null) throw settledError;\n return { reachedTarget: this.targetReached, flushed: this.flushed };\n } finally {\n if (stallTimer) clearTimeout(stallTimer);\n clearInterval(abortTimer);\n this.activeRun = null;\n abortFailure = null;\n abandonFlush = null;\n wakeResolver = null;\n }\n }\n\n close(): void {\n if (this.closed) return;\n this.closed = true;\n const run = this.activeRun;\n this.activeRun = null;\n run?.wake();\n this.closeDecoderOnly();\n this.pendingChunk = null;\n for (const frame of this.pendingFrames.splice(0)) {\n frame.close();\n }\n }\n\n private closeDecoderOnly(): void {\n const decoder = this.decoder;\n this.decoder = null;\n if (decoder && decoder.state !== 'closed') {\n decoder.ondequeue = null;\n decoder.close();\n }\n }\n\n private handleOutput(frame: VideoFrame): void {\n if (this.closed) {\n frame.close();\n return;\n }\n playbackDiagnostic('decoder.frame', {\n timestamp: frame.timestamp,\n duration: frame.duration,\n });\n\n const run = this.activeRun;\n if (!run || this.targetReached) {\n this.holdFrame(frame);\n return;\n }\n\n try {\n if (this.deliver(frame, run.onFrame) === 'hold') {\n this.holdFrame(frame);\n run.onTargetReached();\n } else {\n run.wake();\n }\n } catch (error) {\n run.fail(error);\n }\n }\n\n /** A frame whose callback throws is closed here, and the decoder does not continue past it. */\n private deliver(\n frame: VideoFrame,\n onFrame: (frame: VideoFrame) => PreviewFrameDisposition\n ): PreviewFrameDisposition {\n try {\n return onFrame(frame);\n } catch (error) {\n frame.close();\n this.fatalError = error;\n throw error;\n }\n }\n\n private holdFrame(frame: VideoFrame): void {\n if (this.pendingFrames.length >= MAX_PENDING_FRAMES) {\n this.droppedPending = true;\n this.pendingFrames.shift()?.close();\n }\n this.pendingFrames.push(frame);\n }\n\n private handleError(error: unknown): void {\n this.fatalError = error;\n const run = this.activeRun;\n this.closeDecoderOnly();\n run?.fail(error);\n }\n}\n"],"names":[],"mappings":";;AAIA,MAAM,wBAAwB;AAC9B,MAAM,qBAAqB;AAC3B,MAAM,0BAA0B;AAChC,MAAM,qBAAqB;AAGpB,SAAS,cAA6B;AAC3C,MAAI,OAAO,mBAAmB,aAAa;AACzC,WAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,CAAC,CAAC;AAAA,EACxD;AACA,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,UAAM,UAAU,IAAI,eAAA;AACpB,YAAQ,MAAM,YAAY,MAAM;AAC9B,cAAQ,MAAM,MAAA;AACd,cAAQ,MAAM,MAAA;AACd,cAAA;AAAA,IACF;AACA,YAAQ,MAAM,YAAY,MAAS;AAAA,EACrC,CAAC;AACH;AAQO,MAAM,8BAA8B;AAAA,EAgBzC,YACmB,QACR,uBAA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,MACN;AAAA,IACF,SAAS,OAAO;AACd,UAAI,KAAK,KAAK;AAAA,IAChB;AAAA,EACF;AAAA;AAAA,EAGQ,QACN,OACA,SACyB;AACzB,QAAI;AACF,aAAO,QAAQ,KAAK;AAAA,IACtB,SAAS,OAAO;AACd,YAAM,MAAA;AACN,WAAK,aAAa;AAClB,YAAM;AAAA,IACR;AAAA,EACF;AAAA,EAEQ,UAAU,OAAyB;AACzC,QAAI,KAAK,cAAc,UAAU,oBAAoB;AACnD,WAAK,iBAAiB;AACtB,WAAK,cAAc,MAAA,GAAS,MAAA;AAAA,IAC9B;AACA,SAAK,cAAc,KAAK,KAAK;AAAA,EAC/B;AAAA,EAEQ,YAAY,OAAsB;AACxC,SAAK,aAAa;AAClB,UAAM,MAAM,KAAK;AACjB,SAAK,iBAAA;AACL,SAAK,KAAK,KAAK;AAAA,EACjB;AACF;"}
|
|
@@ -14,8 +14,8 @@ export interface VideoDecoderConfig {
|
|
|
14
14
|
hardwareAcceleration?: HardwareAcceleration;
|
|
15
15
|
}
|
|
16
16
|
export interface DecodeOptions {
|
|
17
|
+
signal?: AbortSignal;
|
|
17
18
|
timeoutMs?: number;
|
|
18
|
-
pollIntervalMs?: number;
|
|
19
19
|
}
|
|
20
20
|
export interface DecodeScrubResult {
|
|
21
21
|
before: VideoFrame | null;
|
|
@@ -45,15 +45,6 @@ export interface DecodeScrubOptions {
|
|
|
45
45
|
* - Keep on-demand session focused on IO/demux/cache, not decode control flow
|
|
46
46
|
*/
|
|
47
47
|
export declare function decodeChunksForScrub(chunks: EncodedVideoChunk[], config: VideoDecoderConfig, targetTimeUs: number, options?: DecodeScrubOptions): Promise<DecodeScrubResult>;
|
|
48
|
-
/**
|
|
49
|
-
* Decode chunks using native VideoDecoder without awaiting flush
|
|
50
|
-
* This avoids Windows hardware acceleration flush hang bug
|
|
51
|
-
*
|
|
52
|
-
* Strategy:
|
|
53
|
-
* - Feed all chunks to decoder
|
|
54
|
-
* - Call flush() but don't await (may hang on Windows HW)
|
|
55
|
-
* - Poll decodeQueueSize to detect completion
|
|
56
|
-
* - Timeout fallback ensures no infinite hang
|
|
57
|
-
*/
|
|
48
|
+
/** Decode a complete batch: await native flush, or reject and close on abort/timeout. */
|
|
58
49
|
export declare function decodeChunksWithoutFlush(chunks: EncodedVideoChunk[], config: VideoDecoderConfig, options?: DecodeOptions): Promise<DecodeResult>;
|
|
59
50
|
//# sourceMappingURL=video-decoder.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"video-decoder.d.ts","sourceRoot":"","sources":["../../../src/stages/decode/video-decoder.ts"],"names":[],"mappings":"AAMA,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,UAAU,EAAE,CAAC;IACrB,KAAK,EAAE;QACL,WAAW,EAAE,MAAM,CAAC;QACpB,YAAY,EAAE,MAAM,CAAC;QACrB,UAAU,EAAE,MAAM,CAAC;KACpB,CAAC;CACH;AAED,MAAM,WAAW,kBAAkB;IACjC,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,CAAC,EAAE,WAAW,CAAC;IAC1B,oBAAoB,CAAC,EAAE,oBAAoB,CAAC;CAC7C;AAED,MAAM,WAAW,aAAa;IAC5B,
|
|
1
|
+
{"version":3,"file":"video-decoder.d.ts","sourceRoot":"","sources":["../../../src/stages/decode/video-decoder.ts"],"names":[],"mappings":"AAMA,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,UAAU,EAAE,CAAC;IACrB,KAAK,EAAE;QACL,WAAW,EAAE,MAAM,CAAC;QACpB,YAAY,EAAE,MAAM,CAAC;QACrB,UAAU,EAAE,MAAM,CAAC;KACpB,CAAC;CACH;AAED,MAAM,WAAW,kBAAkB;IACjC,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,CAAC,EAAE,WAAW,CAAC;IAC1B,oBAAoB,CAAC,EAAE,oBAAoB,CAAC;CAC7C;AAED,MAAM,WAAW,aAAa;IAC5B,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,iBAAiB;IAChC,MAAM,EAAE,UAAU,GAAG,IAAI,CAAC;IAC1B,KAAK,EAAE,UAAU,GAAG,IAAI,CAAC;IACzB,KAAK,EAAE;QACL,WAAW,EAAE,MAAM,CAAC;QACpB,YAAY,EAAE,MAAM,CAAC;QACrB,UAAU,EAAE,MAAM,CAAC;KACpB,CAAC;CACH;AAED,MAAM,WAAW,kBAAkB;IACjC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;OAEG;IACH,WAAW,CAAC,EAAE,MAAM,OAAO,CAAC;CAC7B;AAED;;;;;;GAMG;AACH,wBAAsB,oBAAoB,CACxC,MAAM,EAAE,iBAAiB,EAAE,EAC3B,MAAM,EAAE,kBAAkB,EAC1B,YAAY,EAAE,MAAM,EACpB,OAAO,GAAE,kBAAuB,GAC/B,OAAO,CAAC,iBAAiB,CAAC,CAsB5B;AA6LD,yFAAyF;AACzF,wBAAsB,wBAAwB,CAC5C,MAAM,EAAE,iBAAiB,EAAE,EAC3B,MAAM,EAAE,kBAAkB,EAC1B,OAAO,GAAE,aAAkB,GAC1B,OAAO,CAAC,YAAY,CAAC,CA6DvB"}
|
|
@@ -140,8 +140,27 @@ async function _decodeForScrub(chunks, config, targetTimeUs, options, hwAccel) {
|
|
|
140
140
|
settle(false, new Error("Scrub decode aborted"));
|
|
141
141
|
return;
|
|
142
142
|
}
|
|
143
|
-
decoder.flush().
|
|
144
|
-
|
|
143
|
+
decoder.flush().then(
|
|
144
|
+
() => {
|
|
145
|
+
if (settled) return;
|
|
146
|
+
try {
|
|
147
|
+
decoder.close();
|
|
148
|
+
} catch {
|
|
149
|
+
}
|
|
150
|
+
if (shouldAbort?.())
|
|
151
|
+
settle(false, new DOMException("Scrub decode aborted", "AbortError"));
|
|
152
|
+
else if (before || after) settle(true);
|
|
153
|
+
else settle(false, new Error("Scrub decoder produced no frames"));
|
|
154
|
+
},
|
|
155
|
+
(error) => {
|
|
156
|
+
if (settled) return;
|
|
157
|
+
try {
|
|
158
|
+
decoder.close();
|
|
159
|
+
} catch {
|
|
160
|
+
}
|
|
161
|
+
settle(false, error);
|
|
162
|
+
}
|
|
163
|
+
);
|
|
145
164
|
} catch (e) {
|
|
146
165
|
settle(false, e);
|
|
147
166
|
}
|
|
@@ -204,56 +223,46 @@ async function decodeChunksWithoutFlush(chunks, config, options = {}) {
|
|
|
204
223
|
}
|
|
205
224
|
}
|
|
206
225
|
function _decodeWithoutFlush(chunks, config, options, hwAccel) {
|
|
207
|
-
const { timeoutMs = 2e3,
|
|
226
|
+
const { timeoutMs = 2e3, signal } = options;
|
|
208
227
|
const startTime = performance.now();
|
|
209
228
|
const frames = [];
|
|
210
229
|
return new Promise((resolve, reject) => {
|
|
211
|
-
let
|
|
212
|
-
let
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
if (
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
}
|
|
223
|
-
};
|
|
224
|
-
const settle = (success, errorMsg) => {
|
|
225
|
-
if (isSettled) return;
|
|
226
|
-
isSettled = true;
|
|
227
|
-
cleanup();
|
|
228
|
-
const stats = {
|
|
229
|
-
inputChunks: chunks.length,
|
|
230
|
-
outputFrames: frames.length,
|
|
231
|
-
durationMs: performance.now() - startTime
|
|
232
|
-
};
|
|
233
|
-
if (success && frames.length > 0) {
|
|
234
|
-
resolve({ frames, stats });
|
|
230
|
+
let settled = false;
|
|
231
|
+
let timer;
|
|
232
|
+
const finish = (error) => {
|
|
233
|
+
if (settled) return;
|
|
234
|
+
settled = true;
|
|
235
|
+
clearTimeout(timer);
|
|
236
|
+
signal?.removeEventListener("abort", abort);
|
|
237
|
+
if (decoder.state !== "closed") decoder.close();
|
|
238
|
+
if (error) {
|
|
239
|
+
for (const frame of frames) frame.close();
|
|
240
|
+
reject(error);
|
|
235
241
|
} else {
|
|
236
|
-
|
|
242
|
+
resolve({
|
|
243
|
+
frames,
|
|
244
|
+
stats: {
|
|
245
|
+
inputChunks: chunks.length,
|
|
246
|
+
outputFrames: frames.length,
|
|
247
|
+
durationMs: performance.now() - startTime
|
|
248
|
+
}
|
|
249
|
+
});
|
|
237
250
|
}
|
|
238
251
|
};
|
|
252
|
+
const abort = () => finish(signal?.reason ?? new DOMException("Decode aborted", "AbortError"));
|
|
239
253
|
const decoder = new VideoDecoder({
|
|
240
254
|
output: (frame) => {
|
|
241
|
-
|
|
255
|
+
if (settled) frame.close();
|
|
256
|
+
else frames.push(frame);
|
|
242
257
|
},
|
|
243
|
-
error:
|
|
244
|
-
for (const f of frames) {
|
|
245
|
-
try {
|
|
246
|
-
f.close();
|
|
247
|
-
} catch {
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
try {
|
|
251
|
-
decoder.close();
|
|
252
|
-
} catch {
|
|
253
|
-
}
|
|
254
|
-
settle(false, error.message);
|
|
255
|
-
}
|
|
258
|
+
error: finish
|
|
256
259
|
});
|
|
260
|
+
if (signal?.aborted) {
|
|
261
|
+
abort();
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
265
|
+
timer = setTimeout(() => finish(new Error(`Decode timeout after ${timeoutMs}ms`)), timeoutMs);
|
|
257
266
|
try {
|
|
258
267
|
decoder.configure({
|
|
259
268
|
codec: config.codec,
|
|
@@ -263,26 +272,16 @@ function _decodeWithoutFlush(chunks, config, options, hwAccel) {
|
|
|
263
272
|
optimizeForLatency: true,
|
|
264
273
|
...config.description && { description: config.description }
|
|
265
274
|
});
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
275
|
+
for (const chunk of chunks) decoder.decode(chunk);
|
|
276
|
+
decoder.flush().then(
|
|
277
|
+
() => finish(
|
|
278
|
+
frames.length > 0 ? void 0 : new Error(`Decode failed: flush produced no frames from ${chunks.length} chunks`)
|
|
279
|
+
),
|
|
280
|
+
finish
|
|
281
|
+
);
|
|
282
|
+
} catch (error) {
|
|
283
|
+
finish(error);
|
|
273
284
|
}
|
|
274
|
-
decoder.flush().catch(() => {
|
|
275
|
-
});
|
|
276
|
-
pollTimer = setInterval(() => {
|
|
277
|
-
if (decoder.decodeQueueSize === 0 && frames.length > 0) {
|
|
278
|
-
decoder.close();
|
|
279
|
-
settle(true);
|
|
280
|
-
}
|
|
281
|
-
}, pollIntervalMs);
|
|
282
|
-
timeoutTimer = setTimeout(() => {
|
|
283
|
-
decoder.close();
|
|
284
|
-
settle(frames.length > 0, `Decode timeout after ${timeoutMs}ms`);
|
|
285
|
-
}, timeoutMs);
|
|
286
285
|
});
|
|
287
286
|
}
|
|
288
287
|
export {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"video-decoder.js","sources":["../../../src/stages/decode/video-decoder.ts"],"sourcesContent":["import { detectPlatform, getRecommendedHardwareAcceleration } from '../../utils/platform-utils';\n\nfunction isDecodeError(error: unknown): boolean {\n return error instanceof Error && error.message === 'Decoding error.';\n}\n\nexport interface DecodeResult {\n frames: VideoFrame[];\n stats: {\n inputChunks: number;\n outputFrames: number;\n durationMs: number;\n };\n}\n\nexport interface VideoDecoderConfig {\n codec: string;\n width: number;\n height: number;\n description?: ArrayBuffer;\n hardwareAcceleration?: HardwareAcceleration;\n}\n\nexport interface DecodeOptions {\n timeoutMs?: number;\n pollIntervalMs?: number;\n}\n\nexport interface DecodeScrubResult {\n before: VideoFrame | null;\n after: VideoFrame | null;\n stats: {\n inputChunks: number;\n outputFrames: number;\n durationMs: number;\n };\n}\n\nexport interface DecodeScrubOptions {\n timeoutMs?: number;\n /**\n * Backpressure: keep decodeQueueSize small so we don't decode far past target.\n */\n maxQueueSize?: number;\n /**\n * Optional cooperative abort hook (e.g., session cancelled by a newer seek).\n */\n shouldAbort?: () => boolean;\n}\n\n/**\n * Scrub decode: feed chunks in order, stop as soon as output crosses targetTimeUs.\n *\n * Why this lives in helpers:\n * - Centralize VideoDecoder quirks (no-await flush, HW accel defaults)\n * - Keep on-demand session focused on IO/demux/cache, not decode control flow\n */\nexport async function decodeChunksForScrub(\n chunks: EncodedVideoChunk[],\n config: VideoDecoderConfig,\n targetTimeUs: number,\n options: DecodeScrubOptions = {}\n): Promise<DecodeScrubResult> {\n const hwAccel = config.hardwareAcceleration ?? getRecommendedHardwareAcceleration();\n\n const platformInfo = detectPlatform();\n\n try {\n return await _decodeForScrub(chunks, config, targetTimeUs, options, hwAccel);\n } catch (error) {\n console.warn(\n '[decodeChunksForScrub] decode error:',\n error,\n 'hwAccel:',\n hwAccel,\n 'platform:',\n platformInfo.platform\n );\n if (hwAccel !== 'prefer-software' && isDecodeError(error)) {\n console.warn('[VideoDecoder] Hardware decode failed, falling back to software decode');\n return _decodeForScrub(chunks, config, targetTimeUs, options, 'prefer-software');\n }\n throw error;\n }\n}\n\nasync function _decodeForScrub(\n chunks: EncodedVideoChunk[],\n config: VideoDecoderConfig,\n targetTimeUs: number,\n options: DecodeScrubOptions,\n hwAccel: HardwareAcceleration\n): Promise<DecodeScrubResult> {\n const { timeoutMs = 2000, maxQueueSize = 2, shouldAbort } = options;\n const startTime = performance.now();\n let outputFrames = 0;\n\n // Keep at most two frames: last <= target and first > target.\n let before: VideoFrame | null = null;\n let after: VideoFrame | null = null;\n\n return await new Promise<DecodeScrubResult>((resolve, reject) => {\n let settled = false;\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n const cleanup = () => {\n if (timeoutId !== null) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n };\n\n const settle = (ok: boolean, err?: unknown) => {\n if (settled) return;\n settled = true;\n cleanup();\n\n const stats = {\n inputChunks: chunks.length,\n outputFrames,\n durationMs: performance.now() - startTime,\n };\n\n if (!ok) {\n if (before) before.close();\n if (after) after.close();\n reject(err instanceof Error ? err : new Error(String(err ?? 'Scrub decode failed')));\n return;\n }\n\n resolve({ before, after, stats });\n };\n\n const decoder = new VideoDecoder({\n output: (frame) => {\n outputFrames += 1;\n\n if (settled) {\n frame.close();\n return;\n }\n\n const ts = frame.timestamp ?? 0;\n if (ts <= targetTimeUs) {\n if (before) before.close();\n before = frame;\n return;\n }\n\n if (!after) {\n after = frame;\n // We have both sides (or at least the first after); stop as soon as possible.\n try {\n decoder.close();\n } catch {\n // ignore\n }\n settle(true);\n return;\n }\n\n frame.close();\n },\n error: (e) => {\n try {\n decoder.close();\n } catch {\n /* noop */\n }\n settle(false, e);\n },\n });\n\n try {\n decoder.configure({\n codec: config.codec,\n codedWidth: config.width,\n codedHeight: config.height,\n hardwareAcceleration: hwAccel,\n optimizeForLatency: true,\n ...(config.description && { description: config.description }),\n });\n } catch (e) {\n settle(false, e);\n return;\n }\n\n timeoutId = setTimeout(() => {\n try {\n decoder.close();\n } catch {\n // ignore\n }\n // Best-effort: if we got at least one frame, still treat as success.\n if (before || after) {\n settle(true);\n } else {\n settle(false, new Error(`Scrub decode timeout after ${timeoutMs}ms`));\n }\n }, timeoutMs);\n\n const feed = async () => {\n try {\n for (const chunk of chunks) {\n if (settled) break;\n if (shouldAbort?.()) break;\n\n // Backpressure: keep queue small so we don't decode far past target.\n while (!settled && !shouldAbort?.() && decoder.decodeQueueSize > maxQueueSize) {\n await new Promise((r) => setTimeout(r, 0));\n }\n\n if (settled) break;\n if (shouldAbort?.()) break;\n decoder.decode(chunk);\n }\n\n // If we already settled (found target), we're done.\n if (settled) return;\n if (shouldAbort?.()) {\n // If cancelled, resolve best-effort if any output exists; otherwise fail.\n if (before || after) {\n try {\n decoder.close();\n } catch {\n // ignore\n }\n settle(true);\n return;\n }\n try {\n decoder.close();\n } catch {\n // ignore\n }\n settle(false, new Error('Scrub decode aborted'));\n return;\n }\n\n // We may have hit end-of-input without seeing a frame after target (e.g., target at end).\n // Trigger flush (do not await) and give output a chance before timeout.\n decoder.flush().catch(() => {});\n } catch (e) {\n settle(false, e);\n }\n };\n\n void feed();\n });\n}\n\n/**\n * Decode chunks using native VideoDecoder without awaiting flush\n * This avoids Windows hardware acceleration flush hang bug\n *\n * Strategy:\n * - Feed all chunks to decoder\n * - Call flush() but don't await (may hang on Windows HW)\n * - Poll decodeQueueSize to detect completion\n * - Timeout fallback ensures no infinite hang\n */\nexport async function decodeChunksWithoutFlush(\n chunks: EncodedVideoChunk[],\n config: VideoDecoderConfig,\n options: DecodeOptions = {}\n): Promise<DecodeResult> {\n const hwAccel = config.hardwareAcceleration ?? getRecommendedHardwareAcceleration();\n\n const platformInfo = detectPlatform();\n\n try {\n return await _decodeWithoutFlush(chunks, config, options, hwAccel);\n } catch (error) {\n // 用字符串字段暴露被 Puppeteer JSHandle@error 吞掉的真实错误 + 触发失败的 config。\n const err = error as Error;\n const cfgDesc = {\n codec: config.codec,\n width: config.width,\n height: config.height,\n hasDescription: !!config.description,\n descriptionBytes: config.description ? config.description.byteLength : 0,\n };\n console.warn(\n `[DECODE-DIAG] decode error name=${err?.name} message=${err?.message} ` +\n `hwAccel=${hwAccel} platform=${platformInfo.platform} config=${JSON.stringify(cfgDesc)}`\n );\n // 探测:用与实际 configure 完全一致的 config(含 hwAccel/optimizeForLatency),\n // 否则可能漏掉真正不被支持的字段。同时探一个纯软解、去掉可选字段的最小 config 做对比。\n const fullConfig = {\n codec: config.codec,\n codedWidth: config.width,\n codedHeight: config.height,\n hardwareAcceleration: hwAccel,\n optimizeForLatency: true,\n ...(config.description && { description: config.description }),\n };\n try {\n const probeFull = await VideoDecoder.isConfigSupported(fullConfig);\n console.warn(\n `[DECODE-DIAG] isConfigSupported(full)=${probeFull.supported} ` +\n `resolvedConfig=${JSON.stringify(probeFull.config ?? null)}`\n );\n const probeSw = await VideoDecoder.isConfigSupported({\n codec: config.codec,\n codedWidth: config.width,\n codedHeight: config.height,\n hardwareAcceleration: 'prefer-software',\n ...(config.description && { description: config.description }),\n });\n console.warn(`[DECODE-DIAG] isConfigSupported(prefer-software)=${probeSw.supported}`);\n } catch (probeErr) {\n console.warn(\n `[DECODE-DIAG] isConfigSupported threw name=${(probeErr as Error)?.name} ` +\n `message=${(probeErr as Error)?.message}`\n );\n }\n const willFallback = hwAccel !== 'prefer-software' && isDecodeError(error);\n console.warn(\n `[DECODE-DIAG] fallbackToSoftware=${willFallback} isDecodeError=${isDecodeError(error)} hwAccel=${hwAccel}`\n );\n if (willFallback) {\n console.warn('[VideoDecoder] Hardware decode failed, falling back to software decode');\n return _decodeWithoutFlush(chunks, config, options, 'prefer-software');\n }\n throw error;\n }\n}\n\nfunction _decodeWithoutFlush(\n chunks: EncodedVideoChunk[],\n config: VideoDecoderConfig,\n options: DecodeOptions,\n hwAccel: HardwareAcceleration\n): Promise<DecodeResult> {\n const { timeoutMs = 2000, pollIntervalMs = 10 } = options;\n const startTime = performance.now();\n const frames: VideoFrame[] = [];\n\n return new Promise((resolve, reject) => {\n let isSettled = false;\n let pollTimer: ReturnType<typeof setInterval> | null = null;\n let timeoutTimer: ReturnType<typeof setTimeout> | null = null;\n\n const cleanup = () => {\n if (pollTimer !== null) {\n clearInterval(pollTimer);\n pollTimer = null;\n }\n if (timeoutTimer !== null) {\n clearTimeout(timeoutTimer);\n timeoutTimer = null;\n }\n };\n\n const settle = (success: boolean, errorMsg?: string) => {\n if (isSettled) return;\n isSettled = true;\n cleanup();\n\n const stats = {\n inputChunks: chunks.length,\n outputFrames: frames.length,\n durationMs: performance.now() - startTime,\n };\n\n if (success && frames.length > 0) {\n resolve({ frames, stats });\n } else {\n reject(new Error(errorMsg || 'Decode failed'));\n }\n };\n\n const decoder = new VideoDecoder({\n output: (frame) => {\n frames.push(frame);\n },\n error: (error) => {\n for (const f of frames) {\n try {\n f.close();\n } catch {\n /* noop */\n }\n }\n try {\n decoder.close();\n } catch {\n /* noop */\n }\n settle(false, error.message);\n },\n });\n\n try {\n decoder.configure({\n codec: config.codec,\n codedWidth: config.width,\n codedHeight: config.height,\n hardwareAcceleration: hwAccel,\n optimizeForLatency: true,\n ...(config.description && { description: config.description }),\n });\n } catch (e) {\n const err = e as Error;\n // 标记 configure 阶段失败,区分于 decode 过程错误\n reject(new Error(`[configure] ${err?.name}: ${err?.message}`));\n return;\n }\n\n // Feed all chunks\n for (const chunk of chunks) {\n decoder.decode(chunk);\n }\n\n // Call flush but don't await (may hang on Windows HW acceleration)\n decoder.flush().catch(() => {\n // Flush errors are non-critical\n });\n\n // Poll decode queue to detect completion\n pollTimer = setInterval(() => {\n if (decoder.decodeQueueSize === 0 && frames.length > 0) {\n decoder.close();\n settle(true);\n }\n }, pollIntervalMs);\n\n // Timeout fallback\n timeoutTimer = setTimeout(() => {\n decoder.close();\n settle(frames.length > 0, `Decode timeout after ${timeoutMs}ms`);\n }, timeoutMs);\n });\n}\n"],"names":[],"mappings":";AAEA,SAAS,cAAc,OAAyB;AAC9C,SAAO,iBAAiB,SAAS,MAAM,YAAY;AACrD;AAqDA,eAAsB,qBACpB,QACA,QACA,cACA,UAA8B,CAAA,GACF;AAC5B,QAAM,UAAU,OAAO,wBAAwB,mCAAA;AAE/C,QAAM,eAAe,eAAA;AAErB,MAAI;AACF,WAAO,MAAM,gBAAgB,QAAQ,QAAQ,cAAc,SAAS,OAAO;AAAA,EAC7E,SAAS,OAAO;AACd,YAAQ;AAAA,MACN;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,aAAa;AAAA,IAAA;AAEf,QAAI,YAAY,qBAAqB,cAAc,KAAK,GAAG;AACzD,cAAQ,KAAK,wEAAwE;AACrF,aAAO,gBAAgB,QAAQ,QAAQ,cAAc,SAAS,iBAAiB;AAAA,IACjF;AACA,UAAM;AAAA,EACR;AACF;AAEA,eAAe,gBACb,QACA,QACA,cACA,SACA,SAC4B;AAC5B,QAAM,EAAE,YAAY,KAAM,eAA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AAW,KAAK,QAAQ;AACtB,cAAI;AACF,cAAE,MAAA;AAAA,UACJ,QAAQ;AAAA,UAER;AAAA,QACF;AACA,YAAI;AACF,kBAAQ,MAAA;AAAA,QACV,QAAQ;AAAA,QAER;AACA,eAAO,OAAO,MAAM,OAAO;AAAA,MAC7B;AAAA,IAAA,CACD;AAED,QAAI;AACF,cAAQ,UAAU;AAAA,QAChB,OAAO,OAAO;AAAA,QACd,YAAY,OAAO;AAAA,QACnB,aAAa,OAAO;AAAA,QACpB,sBAAsB;AAAA,QACtB,oBAAoB;AAAA,QACpB,GAAI,OAAO,eAAe,EAAE,aAAa,OAAO,YAAA;AAAA,MAAY,CAC7D;AAAA,IACH,SAAS,GAAG;AACV,YAAM,MAAM;AAEZ,aAAO,IAAI,MAAM,eAAe,KAAK,IAAI,KAAK,KAAK,OAAO,EAAE,CAAC;AAC7D;AAAA,IACF;AAGA,eAAW,SAAS,QAAQ;AAC1B,cAAQ,OAAO,KAAK;AAAA,IACtB;AAGA,YAAQ,QAAQ,MAAM,MAAM;AAAA,IAE5B,CAAC;AAGD,gBAAY,YAAY,MAAM;AAC5B,UAAI,QAAQ,oBAAoB,KAAK,OAAO,SAAS,GAAG;AACtD,gBAAQ,MAAA;AACR,eAAO,IAAI;AAAA,MACb;AAAA,IACF,GAAG,cAAc;AAGjB,mBAAe,WAAW,MAAM;AAC9B,cAAQ,MAAA;AACR,aAAO,OAAO,SAAS,GAAG,wBAAwB,SAAS,IAAI;AAAA,IACjE,GAAG,SAAS;AAAA,EACd,CAAC;AACH;"}
|
|
1
|
+
{"version":3,"file":"video-decoder.js","sources":["../../../src/stages/decode/video-decoder.ts"],"sourcesContent":["import { detectPlatform, getRecommendedHardwareAcceleration } from '../../utils/platform-utils';\n\nfunction isDecodeError(error: unknown): boolean {\n return error instanceof Error && error.message === 'Decoding error.';\n}\n\nexport interface DecodeResult {\n frames: VideoFrame[];\n stats: {\n inputChunks: number;\n outputFrames: number;\n durationMs: number;\n };\n}\n\nexport interface VideoDecoderConfig {\n codec: string;\n width: number;\n height: number;\n description?: ArrayBuffer;\n hardwareAcceleration?: HardwareAcceleration;\n}\n\nexport interface DecodeOptions {\n signal?: AbortSignal;\n timeoutMs?: number;\n}\n\nexport interface DecodeScrubResult {\n before: VideoFrame | null;\n after: VideoFrame | null;\n stats: {\n inputChunks: number;\n outputFrames: number;\n durationMs: number;\n };\n}\n\nexport interface DecodeScrubOptions {\n timeoutMs?: number;\n /**\n * Backpressure: keep decodeQueueSize small so we don't decode far past target.\n */\n maxQueueSize?: number;\n /**\n * Optional cooperative abort hook (e.g., session cancelled by a newer seek).\n */\n shouldAbort?: () => boolean;\n}\n\n/**\n * Scrub decode: feed chunks in order, stop as soon as output crosses targetTimeUs.\n *\n * Why this lives in helpers:\n * - Centralize VideoDecoder quirks (no-await flush, HW accel defaults)\n * - Keep on-demand session focused on IO/demux/cache, not decode control flow\n */\nexport async function decodeChunksForScrub(\n chunks: EncodedVideoChunk[],\n config: VideoDecoderConfig,\n targetTimeUs: number,\n options: DecodeScrubOptions = {}\n): Promise<DecodeScrubResult> {\n const hwAccel = config.hardwareAcceleration ?? getRecommendedHardwareAcceleration();\n\n const platformInfo = detectPlatform();\n\n try {\n return await _decodeForScrub(chunks, config, targetTimeUs, options, hwAccel);\n } catch (error) {\n console.warn(\n '[decodeChunksForScrub] decode error:',\n error,\n 'hwAccel:',\n hwAccel,\n 'platform:',\n platformInfo.platform\n );\n if (hwAccel !== 'prefer-software' && isDecodeError(error)) {\n console.warn('[VideoDecoder] Hardware decode failed, falling back to software decode');\n return _decodeForScrub(chunks, config, targetTimeUs, options, 'prefer-software');\n }\n throw error;\n }\n}\n\nasync function _decodeForScrub(\n chunks: EncodedVideoChunk[],\n config: VideoDecoderConfig,\n targetTimeUs: number,\n options: DecodeScrubOptions,\n hwAccel: HardwareAcceleration\n): Promise<DecodeScrubResult> {\n const { timeoutMs = 2000, maxQueueSize = 2, shouldAbort } = options;\n const startTime = performance.now();\n let outputFrames = 0;\n\n // Keep at most two frames: last <= target and first > target.\n let before: VideoFrame | null = null;\n let after: VideoFrame | null = null;\n\n return await new Promise<DecodeScrubResult>((resolve, reject) => {\n let settled = false;\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n const cleanup = () => {\n if (timeoutId !== null) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n };\n\n const settle = (ok: boolean, err?: unknown) => {\n if (settled) return;\n settled = true;\n cleanup();\n\n const stats = {\n inputChunks: chunks.length,\n outputFrames,\n durationMs: performance.now() - startTime,\n };\n\n if (!ok) {\n if (before) before.close();\n if (after) after.close();\n reject(err instanceof Error ? err : new Error(String(err ?? 'Scrub decode failed')));\n return;\n }\n\n resolve({ before, after, stats });\n };\n\n const decoder = new VideoDecoder({\n output: (frame) => {\n outputFrames += 1;\n\n if (settled) {\n frame.close();\n return;\n }\n\n const ts = frame.timestamp ?? 0;\n if (ts <= targetTimeUs) {\n if (before) before.close();\n before = frame;\n return;\n }\n\n if (!after) {\n after = frame;\n // We have both sides (or at least the first after); stop as soon as possible.\n try {\n decoder.close();\n } catch {\n // ignore\n }\n settle(true);\n return;\n }\n\n frame.close();\n },\n error: (e) => {\n try {\n decoder.close();\n } catch {\n /* noop */\n }\n settle(false, e);\n },\n });\n\n try {\n decoder.configure({\n codec: config.codec,\n codedWidth: config.width,\n codedHeight: config.height,\n hardwareAcceleration: hwAccel,\n optimizeForLatency: true,\n ...(config.description && { description: config.description }),\n });\n } catch (e) {\n settle(false, e);\n return;\n }\n\n timeoutId = setTimeout(() => {\n try {\n decoder.close();\n } catch {\n // ignore\n }\n // Best-effort: if we got at least one frame, still treat as success.\n if (before || after) {\n settle(true);\n } else {\n settle(false, new Error(`Scrub decode timeout after ${timeoutMs}ms`));\n }\n }, timeoutMs);\n\n const feed = async () => {\n try {\n for (const chunk of chunks) {\n if (settled) break;\n if (shouldAbort?.()) break;\n\n // Backpressure: keep queue small so we don't decode far past target.\n while (!settled && !shouldAbort?.() && decoder.decodeQueueSize > maxQueueSize) {\n await new Promise((r) => setTimeout(r, 0));\n }\n\n if (settled) break;\n if (shouldAbort?.()) break;\n decoder.decode(chunk);\n }\n\n // If we already settled (found target), we're done.\n if (settled) return;\n if (shouldAbort?.()) {\n // If cancelled, resolve best-effort if any output exists; otherwise fail.\n if (before || after) {\n try {\n decoder.close();\n } catch {\n // ignore\n }\n settle(true);\n return;\n }\n try {\n decoder.close();\n } catch {\n // ignore\n }\n settle(false, new Error('Scrub decode aborted'));\n return;\n }\n\n // A GOP/file can end before the next frame after the target. Flush\n // completion owns that result; the watchdog is only for a stuck decoder.\n decoder.flush().then(\n () => {\n if (settled) return;\n try {\n decoder.close();\n } catch {\n // ignore\n }\n if (shouldAbort?.())\n settle(false, new DOMException('Scrub decode aborted', 'AbortError'));\n else if (before || after) settle(true);\n else settle(false, new Error('Scrub decoder produced no frames'));\n },\n (error) => {\n if (settled) return;\n try {\n decoder.close();\n } catch {\n // ignore\n }\n settle(false, error);\n }\n );\n } catch (e) {\n settle(false, e);\n }\n };\n\n void feed();\n });\n}\n\n/** Decode a complete batch: await native flush, or reject and close on abort/timeout. */\nexport async function decodeChunksWithoutFlush(\n chunks: EncodedVideoChunk[],\n config: VideoDecoderConfig,\n options: DecodeOptions = {}\n): Promise<DecodeResult> {\n const hwAccel = config.hardwareAcceleration ?? getRecommendedHardwareAcceleration();\n\n const platformInfo = detectPlatform();\n\n try {\n return await _decodeWithoutFlush(chunks, config, options, hwAccel);\n } catch (error) {\n // 用字符串字段暴露被 Puppeteer JSHandle@error 吞掉的真实错误 + 触发失败的 config。\n const err = error as Error;\n const cfgDesc = {\n codec: config.codec,\n width: config.width,\n height: config.height,\n hasDescription: !!config.description,\n descriptionBytes: config.description ? config.description.byteLength : 0,\n };\n console.warn(\n `[DECODE-DIAG] decode error name=${err?.name} message=${err?.message} ` +\n `hwAccel=${hwAccel} platform=${platformInfo.platform} config=${JSON.stringify(cfgDesc)}`\n );\n // 探测:用与实际 configure 完全一致的 config(含 hwAccel/optimizeForLatency),\n // 否则可能漏掉真正不被支持的字段。同时探一个纯软解、去掉可选字段的最小 config 做对比。\n const fullConfig = {\n codec: config.codec,\n codedWidth: config.width,\n codedHeight: config.height,\n hardwareAcceleration: hwAccel,\n optimizeForLatency: true,\n ...(config.description && { description: config.description }),\n };\n try {\n const probeFull = await VideoDecoder.isConfigSupported(fullConfig);\n console.warn(\n `[DECODE-DIAG] isConfigSupported(full)=${probeFull.supported} ` +\n `resolvedConfig=${JSON.stringify(probeFull.config ?? null)}`\n );\n const probeSw = await VideoDecoder.isConfigSupported({\n codec: config.codec,\n codedWidth: config.width,\n codedHeight: config.height,\n hardwareAcceleration: 'prefer-software',\n ...(config.description && { description: config.description }),\n });\n console.warn(`[DECODE-DIAG] isConfigSupported(prefer-software)=${probeSw.supported}`);\n } catch (probeErr) {\n console.warn(\n `[DECODE-DIAG] isConfigSupported threw name=${(probeErr as Error)?.name} ` +\n `message=${(probeErr as Error)?.message}`\n );\n }\n const willFallback = hwAccel !== 'prefer-software' && isDecodeError(error);\n console.warn(\n `[DECODE-DIAG] fallbackToSoftware=${willFallback} isDecodeError=${isDecodeError(error)} hwAccel=${hwAccel}`\n );\n if (willFallback) {\n console.warn('[VideoDecoder] Hardware decode failed, falling back to software decode');\n return _decodeWithoutFlush(chunks, config, options, 'prefer-software');\n }\n throw error;\n }\n}\n\nfunction _decodeWithoutFlush(\n chunks: EncodedVideoChunk[],\n config: VideoDecoderConfig,\n options: DecodeOptions,\n hwAccel: HardwareAcceleration\n): Promise<DecodeResult> {\n const { timeoutMs = 2000, signal } = options;\n const startTime = performance.now();\n const frames: VideoFrame[] = [];\n\n return new Promise((resolve, reject) => {\n let settled = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n const finish = (error?: unknown) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n signal?.removeEventListener('abort', abort);\n if (decoder.state !== 'closed') decoder.close();\n if (error) {\n for (const frame of frames) frame.close();\n reject(error);\n } else {\n resolve({\n frames,\n stats: {\n inputChunks: chunks.length,\n outputFrames: frames.length,\n durationMs: performance.now() - startTime,\n },\n });\n }\n };\n const abort = () => finish(signal?.reason ?? new DOMException('Decode aborted', 'AbortError'));\n\n const decoder = new VideoDecoder({\n output: (frame) => {\n if (settled) frame.close();\n else frames.push(frame);\n },\n error: finish,\n });\n\n if (signal?.aborted) {\n abort();\n return;\n }\n signal?.addEventListener('abort', abort, { once: true });\n timer = setTimeout(() => finish(new Error(`Decode timeout after ${timeoutMs}ms`)), timeoutMs);\n\n try {\n decoder.configure({\n codec: config.codec,\n codedWidth: config.width,\n codedHeight: config.height,\n hardwareAcceleration: hwAccel,\n optimizeForLatency: true,\n ...(config.description && { description: config.description }),\n });\n for (const chunk of chunks) decoder.decode(chunk);\n // Queue consumption is not an output-completion fence. Only flush owns that contract.\n // A batch that flushes without a single frame decoded nothing usable; it fails like it did before flush was awaited.\n decoder\n .flush()\n .then(\n () =>\n finish(\n frames.length > 0\n ? undefined\n : new Error(`Decode failed: flush produced no frames from ${chunks.length} chunks`)\n ),\n finish\n );\n } catch (error) {\n finish(error);\n }\n });\n}\n"],"names":[],"mappings":";AAEA,SAAS,cAAc,OAAyB;AAC9C,SAAO,iBAAiB,SAAS,MAAM,YAAY;AACrD;AAqDA,eAAsB,qBACpB,QACA,QACA,cACA,UAA8B,CAAA,GACF;AAC5B,QAAM,UAAU,OAAO,wBAAwB,mCAAA;AAE/C,QAAM,eAAe,eAAA;AAErB,MAAI;AACF,WAAO,MAAM,gBAAgB,QAAQ,QAAQ,cAAc,SAAS,OAAO;AAAA,EAC7E,SAAS,OAAO;AACd,YAAQ;AAAA,MACN;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,aAAa;AAAA,IAAA;AAEf,QAAI,YAAY,qBAAqB,cAAc,KAAK,GAAG;AACzD,cAAQ,KAAK,wEAAwE;AACrF,aAAO,gBAAgB,QAAQ,QAAQ,cAAc,SAAS,iBAAiB;AAAA,IACjF;AACA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