package com.foxx.androidcast.receiver.av;

/**
 * Boosts energy below ~150 Hz and gently reduces mids/highs at higher intensity.
 */
public final class BassBoostAudioFilter implements AudioFilter {
    private float[] lowL;
    private float[] lowR;
    private int channels;

    @Override
    public void reset(int sampleRate, int channels) {
        this.channels = Math.max(1, channels);
        lowL = new float[this.channels];
        lowR = new float[this.channels];
    }

    @Override
    public void process(byte[] pcm, int bytes, int sampleRate, int channels, int intensity) {
        if (intensity <= 0 || sampleRate <= 0) {
            return;
        }
        if (lowL == null || this.channels != channels) {
            reset(sampleRate, channels);
        }
        float g = PcmAudioFilters.intensityGain(intensity);
        float alpha = (float) (1.0 - Math.exp(-2.0 * Math.PI * 150.0 / sampleRate));
        float bassGain = 1f + 1.2f * g;
        float trebleCut = 1f - 0.35f * g;
        PcmAudioFilters.process16Le(pcm, bytes, channels, (sample, ch, frame) -> {
            float[] state = ch == 0 ? lowL : (ch == 1 ? lowR : lowL);
            int idx = Math.min(ch, state.length - 1);
            state[idx] += alpha * (sample - state[idx]);
            float low = state[idx];
            float high = sample - low;
            float out = sample + (bassGain - 1f) * low + (trebleCut - 1f) * high;
            return Math.max(-1f, Math.min(1f, out));
        });
    }
}
