/*! * Copyright (c) 2026-present, Vanilagy and contributors * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. * * Modified by the operator of The Video Translator, 2026-11-08, from * @mediabunny/aac-encoder@1.65.0 src/encoder.ts: the worker is loaded from a fixed URL * (AAC_WORKER_URL) instead of an inlined Blob, so the LGPL FFmpeg code is a separate, * replaceable file; ADTS output removed (we only write MP4). The source of this file is * published at /vendor/ffmpeg-aac/1.65.0/aac-encoder-adapter.ts.txt (see /licenses). */ // The encoder class registers into the same mediabunny instance the app imports, which is // what makes the custom encoder visible to Output / AudioBufferSource. import { CustomAudioEncoder, EncodedPacket, registerEncoder, type AudioCodec, type AudioSample } from "mediabunny"; export const AAC_ENCODER_VERSION = "1.65.0"; export const AAC_WORKER_URL = `/vendor/ffmpeg-aac/${AAC_ENCODER_VERSION}/aac-encoder.worker.js`; // Message protocol of the worker (src/shared.ts of @mediabunny/aac-encoder). A replacement // worker must answer these three commands. type WorkerCommand = | { type: "init"; data: { numberOfChannels: number; sampleRate: number; bitrate: number } } | { type: "encode"; data: { ctx: number; audioData: ArrayBuffer; timestamp: number } } | { type: "flush"; data: { ctx: number } }; type PacketInfo = { encodedData: ArrayBuffer; pts: number; duration: number }; type WorkerResponseData = | { type: "init"; ctx: number; frameSize: number; extradata: ArrayBuffer } | { type: "encode"; packets: PacketInfo[] } | { type: "flush"; packets: PacketInfo[] }; type WorkerResponse = { id: number } & ({ success: true; data: WorkerResponseData } | { success: false; error: unknown }); const AAC_SAMPLE_RATES = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]; class AacEncoder extends CustomAudioEncoder { private worker: Worker | null = null; private workerError: Error | null = null; private nextMessageId = 0; private pendingMessages = new Map void; reject: (reason?: unknown) => void }>(); private ctx = 0; private encoderFrameSize = 0; private sampleRate = 0; private numberOfChannels = 0; private chunkMetadata: EncodedAudioChunkMetadata = {}; private description: Uint8Array | null = null; // Accumulate interleaved f32 samples until we have a full frame private pendingBuffer = new Float32Array(2 ** 16); private pendingFrames = 0; private nextSampleTimestampInSamples: number | null = null; static override supports(codec: AudioCodec, config: AudioEncoderConfig): boolean { const format = (config as { aac?: { format?: string } }).aac?.format; return ( codec === "aac" && format !== "adts" && config.numberOfChannels >= 1 && config.numberOfChannels <= 8 && AAC_SAMPLE_RATES.includes(config.sampleRate) && config.bitrate !== undefined ); } async init() { this.worker = new Worker(AAC_WORKER_URL); const onMessage = (data: WorkerResponse) => { const pending = this.pendingMessages.get(data.id); assert(pending !== undefined); this.pendingMessages.delete(data.id); if (data.success) pending.resolve(data.data); else pending.reject(data.error); }; // Treats any worker error (like a failed load) as fatal, rejecting pending and future commands const onError = (error: Error) => { this.workerError = error; for (const pending of this.pendingMessages.values()) pending.reject(error); this.pendingMessages.clear(); this.worker?.terminate(); this.worker = null; }; this.worker.addEventListener("message", (event) => onMessage(event.data as WorkerResponse)); this.worker.addEventListener("error", (event) => { onError(new Error(event.message || `AAC encoder worker failed to load or crashed (${AAC_WORKER_URL}).`)); }); assert(this.config.bitrate !== undefined); this.sampleRate = this.config.sampleRate; this.numberOfChannels = this.config.numberOfChannels; const result = await this.sendCommand({ type: "init", data: { numberOfChannels: this.config.numberOfChannels, sampleRate: this.config.sampleRate, bitrate: this.config.bitrate }, }); this.ctx = result.ctx; this.encoderFrameSize = result.frameSize; // The ffmpeg encoder provides an AudioSpecificConfig as extradata after init this.description = new Uint8Array(result.extradata); this.resetInternalState(); } private resetInternalState() { this.pendingFrames = 0; this.nextSampleTimestampInSamples = null; this.chunkMetadata = { decoderConfig: { codec: "mp4a.40.2", numberOfChannels: this.config.numberOfChannels, sampleRate: this.config.sampleRate, ...(this.description ? { description: this.description } : {}), }, }; } async encode(audioSample: AudioSample) { if (this.nextSampleTimestampInSamples === null) { this.nextSampleTimestampInSamples = Math.round(audioSample.timestamp * this.sampleRate); } const channels = this.numberOfChannels; const incomingFrames = audioSample.numberOfFrames; // Extract interleaved f32 data const totalBytes = audioSample.allocationSize({ format: "f32", planeIndex: 0 }); const audioBytes = new Uint8Array(totalBytes); audioSample.copyTo(audioBytes, { format: "f32", planeIndex: 0 }); const incomingData = new Float32Array(audioBytes.buffer); const requiredSamples = (this.pendingFrames + incomingFrames) * channels; if (requiredSamples > this.pendingBuffer.length) { let newSize = this.pendingBuffer.length; while (newSize < requiredSamples) newSize *= 2; const newBuffer = new Float32Array(newSize); newBuffer.set(this.pendingBuffer.subarray(0, this.pendingFrames * channels)); this.pendingBuffer = newBuffer; } this.pendingBuffer.set(incomingData, this.pendingFrames * channels); this.pendingFrames += incomingFrames; while (this.pendingFrames >= this.encoderFrameSize) await this.encodeOneFrame(); } async flush() { // Pad remaining samples with silence to fill a full frame if (this.pendingFrames > 0) { const channels = this.numberOfChannels; const frameSize = this.encoderFrameSize; this.pendingBuffer.fill(0, this.pendingFrames * channels, frameSize * channels); this.pendingFrames = frameSize; await this.encodeOneFrame(); } const result = await this.sendCommand({ type: "flush", data: { ctx: this.ctx } }); this.emitPackets(result.packets); this.resetInternalState(); } close() { this.worker?.terminate(); } private async encodeOneFrame() { assert(this.nextSampleTimestampInSamples !== null); const channels = this.numberOfChannels; const frameSize = this.encoderFrameSize; const frameSamples = frameSize * channels; const frameData = this.pendingBuffer.slice(0, frameSamples); // Shift remaining using copyWithin this.pendingFrames -= frameSize; if (this.pendingFrames > 0) { this.pendingBuffer.copyWithin(0, frameSamples, frameSamples + this.pendingFrames * channels); } const audioData = frameData.buffer; const result = await this.sendCommand( { type: "encode", data: { ctx: this.ctx, audioData, timestamp: this.nextSampleTimestampInSamples } }, [audioData], ); this.nextSampleTimestampInSamples += frameSize; this.emitPackets(result.packets); } private emitPackets(packets: PacketInfo[]) { for (const p of packets) { const packet = new EncodedPacket(new Uint8Array(p.encodedData), "key", p.pts / this.sampleRate, p.duration / this.sampleRate); this.onPacket(packet, this.chunkMetadata); this.chunkMetadata = {}; } } private sendCommand(command: WorkerCommand & { type: T }, transferables?: Transferable[]) { return new Promise((resolve, reject) => { if (this.workerError) { reject(this.workerError); return; } const id = this.nextMessageId++; this.pendingMessages.set(id, { resolve: resolve as (value: WorkerResponseData) => void, reject }); assert(this.worker); this.worker.postMessage({ id, command }, transferables ?? []); }); } } let registered = false; /** Registers the wasm AAC encoder with mediabunny. Call only when WebCodecs has no AAC. */ export const registerAacEncoder = () => { if (registered) return; registered = true; registerEncoder(AacEncoder); }; function assert(x: unknown): asserts x { if (!x) throw new Error("Assertion failed."); }