package net.yak.kiwi;

public class Resampler {

    // gain is x1000.   1000 is unity.
    public void applyGain(short[] a, int gain) {
        for (int i = 0; i < a.length; i++) {
            int x = (gain * a[i]) / 1000;
            if (x > 0x7FFF) {
                x = 0x7FFF;
            }
            if (x < -0x7FFF) {
                x = -0x7FFF;
            }
            a[i] = (short) x;
        }
    }

    public short[] crudelyResample(int spsIn, int spsOut, short[] a) {
        if (spsIn != 12000) {
            throw new RuntimeException(String.format(
                    "Resampler: Input rate %d not supported", spsIn));
        }
        final int m = a.length;
        int n;
        short[] z;
        switch (spsOut) {
            case 8000:
                n = m * 2 / 3;
                z = new short[n];
                for (int i = 0; i < n; i++) {
                    z[i] = a[i * 3 / 2];
                }
                break;

            case 12000:
                z = a;
                break;

            case 24000:
                n = m * 2;
                z = new short[n];
                for (int i = 0; i < m; i++) {
                    z[2*i+0] = a[i];
                    z[2*i+1] = a[i];
                }
                break;

            case 48000:
                n = m * 4;
                z = new short[n];
                for (int i = 0; i < m; i++) {
                    z[4*i+0] = a[i];
                    z[4*i+1] = a[i];
                    z[4*i+2] = a[i];
                    z[4*i+3] = a[i];
                }
                break;

            default:
                throw new RuntimeException(String.format(
                    "Resampler: Output rate %d not supported", spsOut));
        }
        return z;
    }
}
