"use strict";
/*!
 * 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/.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.registerAc3Decoder = void 0;
const mediabunny_1 = require("mediabunny");
const worker_client_1 = require("./worker-client");
class Ac3Decoder extends mediabunny_1.CustomAudioDecoder {
    constructor() {
        super(...arguments);
        this.ctx = 0;
    }
    static supports(codec) {
        return codec === 'ac3' || codec === 'eac3';
    }
    async init() {
        await (0, worker_client_1.refWorker)();
        const result = await (0, worker_client_1.sendCommand)({
            type: 'init-decoder',
            data: { codec: this.codec },
        });
        this.ctx = result.ctx;
    }
    async decode(packet) {
        const encodedData = packet.data.slice().buffer;
        const timestamp = Math.round(packet.timestamp * this.config.sampleRate);
        const result = await (0, worker_client_1.sendCommand)({
            type: 'decode',
            data: { ctx: this.ctx, encodedData, timestamp },
        }, [encodedData]);
        const sample = new mediabunny_1.AudioSample({
            data: result.pcmData,
            format: result.format,
            numberOfChannels: result.channels,
            sampleRate: result.sampleRate,
            timestamp: result.pts / result.sampleRate,
        });
        this.onSample(sample);
    }
    async flush() {
        await (0, worker_client_1.sendCommand)({ type: 'flush-decoder', data: { ctx: this.ctx } });
    }
    async close() {
        void (0, worker_client_1.sendCommand)({ type: 'close-decoder', data: { ctx: this.ctx } });
        await (0, worker_client_1.unrefWorker)();
    }
}
/**
 * Registers AC-3 and E-AC-3 decoders, which Mediabunny will then use automatically when applicable. Make sure to call
 * this function before starting any decoding task.
 *
 * @group \@mediabunny/ac3
 * @public
 */
const registerAc3Decoder = () => {
    (0, mediabunny_1.registerDecoder)(Ac3Decoder);
};
exports.registerAc3Decoder = registerAc3Decoder;
