using System;
using System.IO;
using System.Text;
using OpenTK.Audio.OpenAL;

public class WavFile
{
    public byte[] Data;
    public ALFormat Format;      // Al.FORMAT_*
    public int SampleRate;

    private const short FORMAT_PCM        = 1;
    private const short FORMAT_FLOAT      = 3;
    private const short FORMAT_EXTENSIBLE = unchecked((short)0xFFFE);

    public static WavFile Load(string path)
    {
        using (var fs = File.OpenRead(path))
        using (var br = new BinaryReader(fs))
        {
            if (new string(br.ReadChars(4)) != "RIFF") throw new Exception("Not RIFF: " + path);
            br.ReadInt32();
            if (new string(br.ReadChars(4)) != "WAVE") throw new Exception("Not WAVE: " + path);

            short format = FORMAT_PCM, channels = 0, bits = 0;
            int rate = 0;
            byte[] data = null;

            while (fs.Position < fs.Length - 8)
            {
                string id  = new string(br.ReadChars(4));
                int    len = br.ReadInt32();

                if (id == "fmt ")
                {
                    format   = br.ReadInt16();          // 1 = PCM, 3 = float, 0xFFFE = extensible
                    channels = br.ReadInt16();
                    rate     = br.ReadInt32();
                    br.ReadInt32();                     // byte rate
                    br.ReadInt16();                     // block align
                    bits     = br.ReadInt16();
                    int rest = len - 16;

                    // WAVE_FORMAT_EXTENSIBLE: the real format is the first
                    // 2 bytes of the SubFormat GUID, 8 bytes further in.
                    if (format == FORMAT_EXTENSIBLE && rest >= 10)
                    {
                        br.ReadInt16();                 // cbSize
                        br.ReadInt16();                 // valid bits
                        br.ReadInt32();                 // channel mask
                        format = br.ReadInt16();        // SubFormat (first 2 bytes)
                        rest  -= 10;
                    }
                    if (rest > 0) br.ReadBytes(rest);
                }
                else if (id == "data")
                {
                    if (len < 0 || len > fs.Length - fs.Position) len = (int)(fs.Length - fs.Position);
                    data = br.ReadBytes(len);
                }
                else
                {
                    br.ReadBytes(len);                  // skip unknown chunk
                }

                if ((len & 1) == 1 && fs.Position < fs.Length) br.ReadByte();  // chunks are word-aligned
            }

            if (data == null) throw new Exception("No data chunk: " + path);
            if (channels != 1 && channels != 2)
                throw new Exception("Unsupported WAV: " + channels + " channels (" + path + ")");

            // OpenAL core only takes 8/16-bit. Convert anything wider to 16-bit.
            if (format == FORMAT_FLOAT && bits == 32)       { data = Float32To16(data); bits = 16; }
            else if (format == FORMAT_PCM && bits == 24)    { data = Int24To16(data);   bits = 16; }
            else if (format == FORMAT_PCM && bits == 32)    { data = Int32To16(data);   bits = 16; }
            else if (format != FORMAT_PCM)
                throw new Exception("Unsupported WAV encoding " + format + " (" + path + ")");

            ALFormat fmt;
            if      (channels == 1 && bits == 8)  fmt = ALFormat.Mono8;
            else if (channels == 1 && bits == 16) fmt = ALFormat.Mono16;
            else if (channels == 2 && bits == 8)  fmt = ALFormat.Stereo8;
            else if (channels == 2 && bits == 16) fmt = ALFormat.Stereo16;
            else throw new Exception("Unsupported WAV: " + channels + "ch " + bits + "bit");

            // a partial last frame makes alBufferData fail
            int frame = channels * bits / 8;
            if (data.Length % frame != 0)
                Array.Resize(ref data, data.Length - data.Length % frame);

            return new WavFile { Data = data, Format = fmt, SampleRate = rate };
        }
    }

    private static byte[] Int24To16(byte[] src)
    {
        int n = src.Length / 3;
        var dst = new byte[n * 2];
        for (int i = 0; i < n; i++)
        {
            dst[i * 2]     = src[i * 3 + 1];            // drop the lowest byte
            dst[i * 2 + 1] = src[i * 3 + 2];
        }
        return dst;
    }

    private static byte[] Int32To16(byte[] src)
    {
        int n = src.Length / 4;
        var dst = new byte[n * 2];
        for (int i = 0; i < n; i++)
        {
            dst[i * 2]     = src[i * 4 + 2];            // keep the top 16 bits
            dst[i * 2 + 1] = src[i * 4 + 3];
        }
        return dst;
    }

    private static byte[] Float32To16(byte[] src)
    {
        int n = src.Length / 4;
        var dst = new byte[n * 2];
        for (int i = 0; i < n; i++)
        {
            float f = BitConverter.ToSingle(src, i * 4);
            if (f > 1f) f = 1f; else if (f < -1f) f = -1f;
            short s = (short)Math.Round(f * 32767f);
            dst[i * 2]     = (byte)(s & 0xFF);
            dst[i * 2 + 1] = (byte)((s >> 8) & 0xFF);
        }
        return dst;
    }
}