/*! * 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/. */ import { CustomAudioEncoder, AudioCodec, AudioSample, EncodedPacket, registerEncoder, } from 'mediabunny'; import { sendCommand, refWorker, unrefWorker } from './worker-client'; import { assert } from './shared'; import { clampDtsBitrate, DTS_CHANNEL_COUNTS, DTS_SAMPLE_RATES } from '../../../shared/dts-misc'; // FFmpeg's DTS encoder doesn't report it, but the decoded audio comes out this many samples late const CODEC_DELAY = 512; class DtsEncoder extends CustomAudioEncoder { private ctx: number | null = null; private encoderFrameSize = 0; private sampleRate = 0; private numberOfChannels = 0; private chunkMetadata: EncodedAudioChunkMetadata = {}; // Accumulate interleaved f32 samples until we have a full frame private pendingBuffer = new Float32Array(2 ** 16); private pendingFrames = 0; private nextSampleTimestampInSamples: number | null = null; private inFlightEncode: Promise | null = null; static override supports(codec: AudioCodec, config: AudioEncoderConfig): boolean { return codec === 'dts' && DTS_CHANNEL_COUNTS.includes(config.numberOfChannels) && DTS_SAMPLE_RATES.includes(config.sampleRate) && config.bitrate !== undefined; } async init() { await refWorker(); assert(this.config.bitrate !== undefined); this.sampleRate = this.config.sampleRate; this.numberOfChannels = this.config.numberOfChannels; const result = await sendCommand({ type: 'init-encoder', data: { numberOfChannels: this.config.numberOfChannels, sampleRate: this.config.sampleRate, bitrate: clampDtsBitrate(this.config.bitrate, this.config.sampleRate, this.config.numberOfChannels), }, }); this.ctx = result.ctx; this.encoderFrameSize = result.frameSize; this.resetInternalState(); } private resetInternalState() { this.pendingFrames = 0; this.nextSampleTimestampInSamples = null; this.chunkMetadata = { decoderConfig: { codec: 'dtsc', numberOfChannels: this.config.numberOfChannels, sampleRate: this.config.sampleRate, }, }; } 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; // Shift the remainder to the front only once at the end, as doing it per frame is quadratic for big samples let encodedFrames = 0; while (this.pendingFrames - encodedFrames >= this.encoderFrameSize) { await this.encodeOneFrame(encodedFrames); encodedFrames += this.encoderFrameSize; } this.pendingBuffer.copyWithin(0, encodedFrames * channels, this.pendingFrames * channels); this.pendingFrames -= encodedFrames; } async flush() { // Pad with enough silence to push the remaining samples through the codec delay and to fill up the last frame if (this.nextSampleTimestampInSamples !== null) { const channels = this.numberOfChannels; const frameSize = this.encoderFrameSize; const paddedFrames = Math.ceil((this.pendingFrames + CODEC_DELAY) / frameSize) * frameSize; this.pendingBuffer.fill(0, this.pendingFrames * channels, paddedFrames * channels); for (let startFrame = 0; startFrame < paddedFrames; startFrame += frameSize) { await this.encodeOneFrame(startFrame); } } // FFmpeg's DTS encoder doesn't hold back any frames, so there's nothing to flush out of it await this.inFlightEncode; this.inFlightEncode = null; this.resetInternalState(); } close() { // Close shouldn't throw if (this.ctx !== null) { sendCommand({ type: 'close-encoder', data: { ctx: this.ctx } }).catch(() => {}); } void unrefWorker(); } private async encodeOneFrame(startFrame: number) { assert(this.ctx !== null); assert(this.nextSampleTimestampInSamples !== null); const channels = this.numberOfChannels; const frameSize = this.encoderFrameSize; const frameData = this.pendingBuffer.slice(startFrame * channels, (startFrame + frameSize) * channels); const audioData = frameData.buffer; const encode = sendCommand({ type: 'encode', data: { ctx: this.ctx, audioData, // Shifted back by the codec delay so that the decoded audio lines up with the input timestamp: this.nextSampleTimestampInSamples - CODEC_DELAY, }, }, [audioData]).then((result) => { // We always get exactly one packet because we encode the correct frame size const packet = new EncodedPacket( new Uint8Array(result.encodedData), 'key', result.pts / this.sampleRate, result.duration / this.sampleRate, ); this.onPacket( packet, this.chunkMetadata, ); this.chunkMetadata = {}; }); encode.catch(() => {}); // Surfaces through whoever awaits it next this.nextSampleTimestampInSamples += frameSize; // Keep one frame in flight, so the worker already has the next frame by the time it's done with the current one const previousEncode = this.inFlightEncode; this.inFlightEncode = encode; await previousEncode; } } let registered = false; /** * Registers a DTS audio encoder, which Mediabunny will then use automatically when applicable. Make sure to call this * function before starting any encoding task. * * @group \@mediabunny/dts * @public */ export const registerDtsEncoder = () => { if (registered) { return; } registered = true; registerEncoder(DtsEncoder); };