package com.foxx.androidcast.receiver.av;

/** Lightweight 16-bit PCM helpers for experimental receiver filters. */
final class PcmAudioFilters {
    private PcmAudioFilters() {}

    static float intensityGain(int intensity) {
        return Math.max(0f, Math.min(10, intensity)) / 10f;
    }

    static void process16Le(byte[] pcm, int bytes, int channels, SampleProcessor proc) {
        int frames = bytes / (2 * channels);
        int off = 0;
        for (int i = 0; i < frames; i++) {
            for (int ch = 0; ch < channels; ch++) {
                float s = readSample(pcm, off);
                s = proc.process(s, ch, i);
                writeSample(pcm, off, s);
                off += 2;
            }
        }
    }

    static float readSample(byte[] pcm, int off) {
        int lo = pcm[off] & 0xff;
        int hi = pcm[off + 1];
        int v = (hi << 8) | lo;
        if (v > 32767) {
            v -= 65536;
        }
        return v / 32768f;
    }

    static void writeSample(byte[] pcm, int off, float s) {
        int v = Math.round(Math.max(-1f, Math.min(1f, s)) * 32767f);
        pcm[off] = (byte) (v & 0xff);
        pcm[off + 1] = (byte) ((v >> 8) & 0xff);
    }

    interface SampleProcessor {
        float process(float sample, int channel, int frameIndex);
    }
}
