|
| 1 | +import { |
| 2 | + type AudioCodec, |
| 3 | + AudioSample, |
| 4 | + AudioSampleSource, |
| 5 | + CanvasSource, |
| 6 | + Mp4OutputFormat, |
| 7 | + Output, |
| 8 | + StreamTarget, |
| 9 | + type StreamTargetChunk, |
| 10 | +} from 'mediabunny'; |
| 11 | + |
| 12 | +import { ENCODER_AUDIO_BITRATE, ENCODER_VIDEO_BITRATE, KEYFRAME_INTERVAL_SEC } from './constants'; |
| 13 | +import type { AudioTapSamples } from './types'; |
| 14 | + |
| 15 | +const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)); |
| 16 | + |
| 17 | +const AUDIO_STALL_MS = 500; // audio silent this long → fall back to the wall clock |
| 18 | +const AUDIO_POLL_MS = 4; // re-check cadence while waiting for the clock to advance |
| 19 | + |
| 20 | +// Encodes the live OffscreenCanvas to a fragmented MP4 at constant frame rate: |
| 21 | +// evenly spaced timestamps (n / fps), duplicating the canvas on a missed slot. |
| 22 | +// The frame count follows the audio clock (wall-clock fallback when there's no |
| 23 | +// audio), so the video duration tracks the audio and can't drift from it. |
| 24 | +export class EncoderPipeline { |
| 25 | + private output: Output; |
| 26 | + private videoSource: CanvasSource; |
| 27 | + private audioSource: AudioSampleSource; |
| 28 | + private audioT0: number | null = null; |
| 29 | + private audioTail: Promise<void> = Promise.resolve(); |
| 30 | + private audioElapsed = 0; |
| 31 | + private audioUpdatedMs = 0; |
| 32 | + private hasAudio = false; |
| 33 | + private fps: number; |
| 34 | + private running = false; |
| 35 | + private startMs = 0; |
| 36 | + private emittedFrames = 0; |
| 37 | + private loopPromise: Promise<void> | null = null; |
| 38 | + private onError: (error: unknown) => void; |
| 39 | + |
| 40 | + constructor( |
| 41 | + canvas: OffscreenCanvas, |
| 42 | + fps: number, |
| 43 | + audioCodec: AudioCodec, |
| 44 | + onChunk: (data: Uint8Array<ArrayBuffer>, position: number) => void, |
| 45 | + onError: (error: unknown) => void |
| 46 | + ) { |
| 47 | + this.fps = fps; |
| 48 | + this.onError = onError; |
| 49 | + |
| 50 | + const writable = new WritableStream<StreamTargetChunk>({ |
| 51 | + write(chunk) { |
| 52 | + // Copy out of Mediabunny's buffer before handing ownership off. |
| 53 | + onChunk(chunk.data.slice(), chunk.position); |
| 54 | + }, |
| 55 | + }); |
| 56 | + |
| 57 | + this.output = new Output({ |
| 58 | + format: new Mp4OutputFormat({ fastStart: 'fragmented' }), |
| 59 | + target: new StreamTarget(writable), |
| 60 | + }); |
| 61 | + |
| 62 | + this.videoSource = new CanvasSource(canvas, { |
| 63 | + codec: 'avc', |
| 64 | + bitrate: ENCODER_VIDEO_BITRATE, |
| 65 | + keyFrameInterval: KEYFRAME_INTERVAL_SEC, |
| 66 | + }); |
| 67 | + this.output.addVideoTrack(this.videoSource); |
| 68 | + |
| 69 | + this.audioSource = new AudioSampleSource({ codec: audioCodec, bitrate: ENCODER_AUDIO_BITRATE }); |
| 70 | + this.output.addAudioTrack(this.audioSource); |
| 71 | + } |
| 72 | + |
| 73 | + public async start(): Promise<void> { |
| 74 | + await this.output.start(); |
| 75 | + this.running = true; |
| 76 | + this.startMs = performance.now(); |
| 77 | + this.loopPromise = this.captureLoop(); |
| 78 | + } |
| 79 | + |
| 80 | + private async captureLoop(): Promise<void> { |
| 81 | + const frameDuration = 1 / this.fps; |
| 82 | + while (this.running) { |
| 83 | + const nowMs = performance.now(); |
| 84 | + const wallElapsed = (nowMs - this.startMs) / 1000; |
| 85 | + const audioLive = this.hasAudio && nowMs - this.audioUpdatedMs < AUDIO_STALL_MS; |
| 86 | + const reference = audioLive ? Math.min(wallElapsed, this.audioElapsed) : wallElapsed; |
| 87 | + const dueFrames = Math.floor(reference * this.fps); |
| 88 | + if (this.emittedFrames <= dueFrames) { |
| 89 | + await this.videoSource.add(this.emittedFrames * frameDuration, frameDuration); |
| 90 | + this.emittedFrames += 1; |
| 91 | + } else { |
| 92 | + const nextSlotMs = this.startMs + (this.emittedFrames * 1000) / this.fps; |
| 93 | + await sleep(Math.max(AUDIO_POLL_MS, nextSlotMs - nowMs)); |
| 94 | + } |
| 95 | + } |
| 96 | + } |
| 97 | + |
| 98 | + public addAudioSamples({ channels, frame, sampleRate }: AudioTapSamples): void { |
| 99 | + if (!this.running || channels.length === 0) { |
| 100 | + return; |
| 101 | + } |
| 102 | + const numberOfChannels = channels.length; |
| 103 | + const numberOfFrames = channels[0].length; |
| 104 | + const timestamp = frame / sampleRate; |
| 105 | + if (this.audioT0 === null) { |
| 106 | + this.audioT0 = timestamp; |
| 107 | + } |
| 108 | + const rebasedTimestamp = timestamp - this.audioT0; |
| 109 | + |
| 110 | + this.audioElapsed = rebasedTimestamp + numberOfFrames / sampleRate; |
| 111 | + this.audioUpdatedMs = performance.now(); |
| 112 | + this.hasAudio = true; |
| 113 | + |
| 114 | + const data = new Float32Array(numberOfChannels * numberOfFrames); |
| 115 | + for (let c = 0; c < numberOfChannels; c++) { |
| 116 | + data.set(channels[c], c * numberOfFrames); |
| 117 | + } |
| 118 | + const sample = new AudioSample({ |
| 119 | + data, |
| 120 | + format: 'f32-planar', |
| 121 | + numberOfChannels, |
| 122 | + sampleRate, |
| 123 | + timestamp: rebasedTimestamp, |
| 124 | + }); |
| 125 | + // audioSource.add isn't concurrency-safe — keep these adds serialized. |
| 126 | + this.audioTail = this.audioTail.then(() => this.addAudioSample(sample)); |
| 127 | + } |
| 128 | + |
| 129 | + private async addAudioSample(sample: AudioSample): Promise<void> { |
| 130 | + try { |
| 131 | + await this.audioSource.add(sample); |
| 132 | + } catch (error) { |
| 133 | + if (this.running) { |
| 134 | + this.onError(error); |
| 135 | + } |
| 136 | + } |
| 137 | + sample.close(); |
| 138 | + } |
| 139 | + |
| 140 | + public async stop(): Promise<void> { |
| 141 | + this.running = false; |
| 142 | + await this.loopPromise; |
| 143 | + await this.audioTail; |
| 144 | + await this.output.finalize(); |
| 145 | + } |
| 146 | +} |
0 commit comments