swadhinbiswas feat(transcoder,filters,recorder): add native hardware video/audio encoding, GPU video filters (chroma key), and canvas recorder · 7/23/2026
f3551af
60 lines · 1.6 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
import { VideoPacket, AudioPacket } from '@vidolib/core';

export interface TranscoderConfig {
  codec: string; // e.g. 'avc1.4d401f' or 'vp09.00.10.08'
  width: number;
  height: number;
  bitrate: number;
  frameRate?: number;
}

export class HardwareVideoEncoder {
  private encoder?: unknown;

  public async init(config: TranscoderConfig, onChunk: (packet: VideoPacket) => void): Promise<void> {
    if (typeof (globalThis as any).VideoEncoder === 'undefined') {
      throw new Error('WebCodecs VideoEncoder API is not supported in this browser environment.');
    }

    this.encoder = new (globalThis as any).VideoEncoder({
      output: (chunk: any, metadata: any) => {
        const buffer = new Uint8Array(chunk.byteLength);
        chunk.copyTo(buffer);
        onChunk({
          pts: chunk.timestamp / 1_000_000,
          dts: chunk.timestamp / 1_000_000,
          data: buffer,
          isKeyframe: chunk.type === 'key'
        });
      },
      error: (err: any) => console.error('VideoEncoder Error:', err)
    });

    (this.encoder as any).configure({
      codec: config.codec,
      width: config.width,
      height: config.height,
      bitrate: config.bitrate,
      framerate: config.frameRate || 30,
      hardwareAcceleration: 'prefer-hardware'
    });
  }

  public encodeFrame(frame: any, keyFrame: boolean = false): void {
    if (!this.encoder) return;
    (this.encoder as any).encode(frame, { keyFrame });
  }

  public async flush(): Promise<void> {
    if (this.encoder) {
      await (this.encoder as any).flush();
    }
  }

  public close(): void {
    if (this.encoder) {
      (this.encoder as any).close();
    }
  }
}