package main

import (
	"bufio"
	"encoding/binary"
	"errors"
	"fmt"
	"io"
	"os"
)

// wavIn is one 16-bit PCM WAV file, read as a stream of whole frames.
type wavIn struct {
	f       *os.File
	rate    int
	ch      int
	dataOff int64
	dataLen int64 // -1: the data runs to the end of the file
	src     io.Reader
	raw     []byte
}

const bufSize = 1 << 20

// openWAV walks the RIFF chunks up to data. Every error it returns is a
// rejection message for the person, already worded.
func openWAV(path string) (*wavIn, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, fmt.Errorf("%s cannot be read (%v).", quote(path), errors.Unwrap(err))
	}
	w, err := parseWAV(f, path)
	if err != nil {
		f.Close()
		return nil, err
	}
	return w, w.rewind()
}

func parseWAV(f *os.File, path string) (*wavIn, error) {
	br := bufio.NewReaderSize(f, bufSize)
	var head [12]byte
	if _, err := io.ReadFull(br, head[:]); err != nil {
		return nil, notWAV(path)
	}
	switch id := string(head[0:4]); {
	case id == "RF64":
		return nil, fmt.Errorf("%s is an RF64 file. Only plain WAV is read.", quote(path))
	case id == "BW64":
		return nil, fmt.Errorf("%s is a BW64 file. Only plain WAV is read.", quote(path))
	case id != "RIFF" || string(head[8:12]) != "WAVE":
		return nil, notWAV(path)
	}
	w := &wavIn{f: f}
	pos := int64(12)
	haveFmt := false
	for {
		var ck [8]byte
		if _, err := io.ReadFull(br, ck[:]); err != nil {
			if haveFmt {
				return nil, fmt.Errorf("%s holds no audio.", quote(path))
			}
			return nil, notWAV(path)
		}
		id, size := string(ck[0:4]), int64(binary.LittleEndian.Uint32(ck[4:8]))
		pos += 8
		if id == "data" {
			if !haveFmt {
				return nil, notWAV(path)
			}
			w.dataOff = pos
			w.dataLen = size
			if size == 0 || size == 0xFFFFFFFF {
				w.dataLen = -1
			}
			return w, nil
		}
		skip := size + size&1
		if id == "fmt " {
			if size < 16 || size > 1024 {
				return nil, notWAV(path)
			}
			b := make([]byte, skip)
			if _, err := io.ReadFull(br, b); err != nil {
				return nil, notWAV(path)
			}
			if err := w.parseFmt(b[:size], path); err != nil {
				return nil, err
			}
			haveFmt = true
		} else if _, err := br.Discard(int(skip)); err != nil {
			return nil, notWAV(path)
		}
		pos += skip
	}
}

func (w *wavIn) parseFmt(b []byte, path string) error {
	tag := binary.LittleEndian.Uint16(b[0:2])
	ch := int(binary.LittleEndian.Uint16(b[2:4]))
	rate := int(binary.LittleEndian.Uint32(b[4:8]))
	bits := int(binary.LittleEndian.Uint16(b[14:16]))
	if tag == 0xFFFE {
		if len(b) < 40 {
			return notWAV(path)
		}
		tag = binary.LittleEndian.Uint16(b[24:26]) // the sub-format GUID starts with the plain tag
	}
	if tag != 1 || bits != 16 {
		q := quote(path)
		nw := quote(newName(path))
		return fmt.Errorf("%s is %s. Only 16-bit PCM is read. Convert: ffmpeg -i %s -c:a pcm_s16le %s (on a Mac: afconvert -f WAVE -d LEI16 %s %s) then: touch -r %s %s",
			q, describe(tag, bits), q, nw, q, nw, q, nw)
	}
	if ch < 1 || ch > 8 {
		return fmt.Errorf("%s has %d channels. Only 1 to 8 are read.", quote(path), ch)
	}
	if rate < 1 {
		return notWAV(path)
	}
	w.rate, w.ch = rate, ch
	return nil
}

func describe(tag uint16, bits int) string {
	switch tag {
	case 1:
		return fmt.Sprintf("%d-bit", bits)
	case 3:
		return fmt.Sprintf("%d-bit float", bits)
	case 2, 0x11:
		return "ADPCM"
	case 6:
		return "A-law"
	case 7:
		return "mu-law"
	case 0x55:
		return "MP3"
	}
	return fmt.Sprintf("format 0x%04X", tag)
}

func notWAV(path string) error {
	q, nw := quote(path), quote(newName(path))
	return fmt.Errorf("%s is not a WAV file. Convert it first: ffmpeg -i %s -c:a pcm_s16le %s (on a Mac: afconvert -f WAVE -d LEI16 %s %s) then: touch -r %s %s",
		q, q, nw, q, nw, q, nw)
}

// rewind puts the reader at the first frame.
func (w *wavIn) rewind() error {
	if _, err := w.f.Seek(w.dataOff, io.SeekStart); err != nil {
		return err
	}
	w.src = bufio.NewReaderSize(w.f, bufSize)
	if w.dataLen >= 0 {
		w.src = io.LimitReader(w.src, w.dataLen)
	}
	return nil
}

// read fills buf with whole frames. It returns fewer than len(buf)/ch frames
// only together with io.EOF; a trailing partial frame is dropped.
func (w *wavIn) read(buf []int16) (int, error) {
	fb := 2 * w.ch
	need := len(buf) / w.ch * fb
	if cap(w.raw) < need {
		w.raw = make([]byte, need)
	}
	raw := w.raw[:need]
	n, err := io.ReadFull(w.src, raw)
	frames := n / fb
	for i := 0; i < frames*w.ch; i++ {
		buf[i] = int16(binary.LittleEndian.Uint16(raw[2*i:]))
	}
	if err == io.ErrUnexpectedEOF {
		err = io.EOF
	}
	return frames, err
}

func (w *wavIn) skip(frames int64) error {
	_, err := io.CopyN(io.Discard, w.src, frames*int64(2*w.ch))
	return err
}

// wavHeader is the standard 44 byte header for 16-bit PCM.
func wavHeader(rate, ch int, frames int64) []byte {
	data := uint32(frames * int64(2*ch))
	h := make([]byte, 44)
	copy(h[0:], "RIFF")
	binary.LittleEndian.PutUint32(h[4:], 36+data)
	copy(h[8:], "WAVEfmt ")
	binary.LittleEndian.PutUint32(h[16:], 16)
	binary.LittleEndian.PutUint16(h[20:], 1)
	binary.LittleEndian.PutUint16(h[22:], uint16(ch))
	binary.LittleEndian.PutUint32(h[24:], uint32(rate))
	binary.LittleEndian.PutUint32(h[28:], uint32(rate*ch*2))
	binary.LittleEndian.PutUint16(h[32:], uint16(ch*2))
	binary.LittleEndian.PutUint16(h[34:], 16)
	copy(h[36:], "data")
	binary.LittleEndian.PutUint32(h[40:], data)
	return h
}
