Repository navigation
Expand file tree
/
Copy pathVideoDecoder.ts
More file actions
345 lines (295 loc) · 9.85 KB
/
Copy pathVideoDecoder.ts
File metadata and controls
345 lines (295 loc) · 9.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
/**
* VideoDecoder - Decodes encoded video data to VideoFrame
* Implements the W3C WebCodecs VideoDecoder interface
*/
import { VideoFrame } from './VideoFrame';
import { EncodedVideoChunk } from './EncodedVideoChunk';
import { isVideoCodecSupported, getFFmpegVideoDecoder, parseAvcCodecString } from './codec-registry';
import { CodecState, DOMException, BufferSource } from './types';
export interface VideoDecoderConfig {
codec: string;
codedWidth?: number;
codedHeight?: number;
displayAspectWidth?: number;
displayAspectHeight?: number;
colorSpace?: {
primaries?: string;
transfer?: string;
matrix?: string;
fullRange?: boolean;
};
hardwareAcceleration?: 'no-preference' | 'prefer-hardware' | 'prefer-software';
optimizeForLatency?: boolean;
description?: BufferSource; // Codec-specific data (e.g., AVCC for H.264)
/**
* Use async (non-blocking) decoder. Defaults to true.
* Set to false to use synchronous decoder (blocks event loop during decoding).
*/
useWorkerThread?: boolean;
}
export interface VideoDecoderInit {
output: (frame: VideoFrame) => void;
error: (error: DOMException) => void;
}
export interface VideoDecoderSupport {
supported: boolean;
config: VideoDecoderConfig;
}
// Load native addon
import { native } from './native';
export class VideoDecoder {
private _native: any;
private _state: CodecState = 'unconfigured';
private _outputCallback: (frame: VideoFrame) => void;
private _errorCallback: (error: DOMException) => void;
private _decodeQueueSize: number = 0;
private _pendingCallbacks: number = 0; // Track pending setImmediate callbacks
private _config: VideoDecoderConfig | null = null;
private _listeners: Map<string, Set<() => void>> = new Map();
private _useAsync: boolean = true;
private _nativeCreated: boolean = false;
private _ondequeue: ((event: Event) => void) | null = null;
static async isConfigSupported(config: VideoDecoderConfig): Promise<VideoDecoderSupport> {
// Basic validation first
if (!config.codec) {
return { supported: false, config };
}
// Check codec string format
if (!isVideoCodecSupported(config.codec)) {
return { supported: false, config };
}
// If native probing is available, use it to actually test codec support
if (native?.CapabilityProbe?.probeVideoDecoder) {
try {
const ffmpegCodec = getFFmpegVideoDecoder(config.codec);
const result = native.CapabilityProbe.probeVideoDecoder({
codec: ffmpegCodec,
width: config.codedWidth || 1920,
height: config.codedHeight || 1080,
hardwareAcceleration: config.hardwareAcceleration || 'no-preference',
});
return {
supported: result.supported,
config,
};
} catch {
// Fall back to basic check on error
}
}
// Fallback to basic string check
return { supported: true, config };
}
constructor(init: VideoDecoderInit) {
if (!init.output || typeof init.output !== 'function') {
throw new TypeError('output callback is required');
}
if (!init.error || typeof init.error !== 'function') {
throw new TypeError('error callback is required');
}
this._outputCallback = init.output;
this._errorCallback = init.error;
// Defer native creation to configure() so we know whether to use async or sync
}
get state(): CodecState {
return this._state;
}
get decodeQueueSize(): number {
return this._decodeQueueSize;
}
/**
* Event handler for dequeue events
*/
get ondequeue(): ((event: Event) => void) | null {
return this._ondequeue;
}
set ondequeue(handler: ((event: Event) => void) | null) {
this._ondequeue = handler;
}
/**
* Minimal EventTarget-style API for 'dequeue' events.
* Enables compatibility with MediaBunny and browser WebCodecs code.
*/
addEventListener(type: string, listener: () => void, options?: { once?: boolean }): void {
if (typeof listener !== 'function') return;
const once = !!(options && (options as any).once);
const wrapper = once
? () => {
this.removeEventListener(type, wrapper);
listener();
}
: listener;
let set = this._listeners.get(type);
if (!set) {
set = new Set();
this._listeners.set(type, set);
}
set.add(wrapper);
}
removeEventListener(type: string, listener: () => void): void {
const set = this._listeners.get(type);
if (!set) return;
if (set.has(listener)) {
set.delete(listener);
}
if (set.size === 0) {
this._listeners.delete(type);
}
}
private _dispatchEvent(type: string): void {
// Call the ondequeue handler if it exists
if (type === 'dequeue' && this._ondequeue) {
try {
this._ondequeue(new Event('dequeue'));
} catch {
// Swallow handler errors
}
}
const set = this._listeners.get(type);
if (!set) return;
for (const listener of Array.from(set)) {
try {
listener();
} catch {
// Swallow listener errors
}
}
}
configure(config: VideoDecoderConfig): void {
if (this._state === 'closed') {
throw new DOMException('Decoder is closed', 'InvalidStateError');
}
if (!isVideoCodecSupported(config.codec)) {
throw new DOMException(`Unsupported codec: ${config.codec}`, 'NotSupportedError');
}
if (!native) {
throw new DOMException('Native addon not available', 'NotSupportedError');
}
// Determine whether to use async (non-blocking) decoder
// Default to async unless explicitly disabled
this._useAsync = config.useWorkerThread !== false && !!native.VideoDecoderAsync;
// Create native decoder if not already created
if (!this._nativeCreated) {
if (this._useAsync) {
this._native = new native.VideoDecoderAsync(
this._onFrame.bind(this),
this._onError.bind(this)
);
} else {
this._native = new native.VideoDecoderNative(
this._onFrame.bind(this),
this._onError.bind(this)
);
}
this._nativeCreated = true;
}
const ffmpegCodec = getFFmpegVideoDecoder(config.codec);
const codecParams: any = { codec: ffmpegCodec };
// Parse H.264 codec string for profile/level
if (config.codec.startsWith('avc1.')) {
const avcInfo = parseAvcCodecString(config.codec);
if (avcInfo) {
codecParams.profile = avcInfo.profile;
codecParams.level = avcInfo.level;
}
}
if (config.codedWidth) codecParams.width = config.codedWidth;
if (config.codedHeight) codecParams.height = config.codedHeight;
if (config.optimizeForLatency) codecParams.optimizeForLatency = true;
if (config.description) {
// Convert BufferSource to Buffer
let desc: Uint8Array;
if (config.description instanceof ArrayBuffer) {
desc = new Uint8Array(config.description);
} else {
desc = new Uint8Array(
(config.description as ArrayBufferView).buffer,
(config.description as ArrayBufferView).byteOffset,
(config.description as ArrayBufferView).byteLength
);
}
codecParams.extradata = Buffer.from(desc);
}
this._native.configure(codecParams);
this._config = config;
this._state = 'configured';
}
decode(chunk: EncodedVideoChunk): void {
if (this._state !== 'configured') {
throw new DOMException('Decoder is not configured', 'InvalidStateError');
}
const data = new Uint8Array(chunk.byteLength);
chunk.copyTo(data);
this._decodeQueueSize++;
this._pendingCallbacks++;
this._native.decode(
Buffer.from(data),
chunk.type === 'key',
chunk.timestamp,
chunk.duration ?? 0
);
// Per WebCodecs spec, dequeue fires when input is consumed from queue
// Use setImmediate to ensure decodeQueueSize > 0 when decode() returns
setImmediate(() => {
this._pendingCallbacks--;
this._decodeQueueSize = Math.max(0, this._decodeQueueSize - 1);
this._dispatchEvent('dequeue');
});
}
async flush(): Promise<void> {
if (this._state !== 'configured') {
throw new DOMException('Decoder is not configured', 'InvalidStateError');
}
return new Promise((resolve, reject) => {
this._native.flush(async (err: Error | null) => {
if (err) {
reject(new DOMException(err.message, 'EncodingError'));
} else {
// Wait for any pending setImmediate callbacks to complete
while (this._pendingCallbacks > 0) {
await new Promise(r => setImmediate(r));
}
resolve();
}
});
});
}
reset(): void {
if (this._state === 'closed') {
throw new DOMException('Decoder is closed', 'InvalidStateError');
}
if (this._native) {
this._native.reset();
}
this._decodeQueueSize = 0;
this._state = 'unconfigured';
this._config = null;
}
close(): void {
if (this._state === 'closed') return;
if (this._native) {
this._native.close();
}
this._state = 'closed';
this._decodeQueueSize = 0;
this._config = null;
}
private _onFrame(nativeFrame: any, timestamp: number, duration: number): void {
// Output frames are delivered asynchronously
// Queue size management and dequeue events are handled in decode()
try {
// Each callback gets a freshly wrapped AVFrame, so adopt it zero-copy
const frame = VideoFrame._adopt(nativeFrame, timestamp, duration > 0 ? duration : undefined);
this._outputCallback(frame);
} catch (e) {
// Don't propagate callback errors, but report as error
console.error('VideoDecoder output callback error:', e);
}
}
private _onError(message: string): void {
try {
this._errorCallback(new DOMException(message, 'EncodingError') as any);
} catch (e) {
// Don't propagate callback errors
}
}
}