// 固定容量的 PCM 环形缓冲。它只保留最新 4 秒数据，供 streaming pre-roll、
// 分段回看和 overload reset 使用；不会累积 AudioFrame 或 Promise 队列。
export class AudioRingBuffer {
    capacitySamples;
    values;
    writeIndex = 0;
    length = 0;
    constructor(capacitySamples) {
        this.capacitySamples = capacitySamples;
        if (!Number.isInteger(capacitySamples) || capacitySamples <= 0)
            throw new Error("invalid_audio_ring_capacity");
        this.values = new Int16Array(capacitySamples);
    }
    push(samples) {
        if (samples.length === 0)
            return;
        const retained = samples.length > this.capacitySamples ? samples.subarray(samples.length - this.capacitySamples) : samples;
        const first = Math.min(retained.length, this.capacitySamples - this.writeIndex);
        this.values.set(retained.subarray(0, first), this.writeIndex);
        if (first < retained.length)
            this.values.set(retained.subarray(first), 0);
        this.writeIndex = (this.writeIndex + retained.length) % this.capacitySamples;
        this.length = Math.min(this.capacitySamples, this.length + retained.length);
    }
    latest(maxSamples = this.length) {
        const count = Math.max(0, Math.min(this.length, Math.floor(maxSamples)));
        const output = new Int16Array(count);
        if (count === 0)
            return output;
        const start = (this.writeIndex - count + this.capacitySamples) % this.capacitySamples;
        const first = Math.min(count, this.capacitySamples - start);
        output.set(this.values.subarray(start, start + first));
        if (first < count)
            output.set(this.values.subarray(0, count - first), first);
        return output;
    }
    clear() { this.writeIndex = 0; this.length = 0; }
    get size() { return this.length; }
    get capacity() { return this.capacitySamples; }
}
