package main

import (
	"encoding/binary"
	"math"
	"os"
)

// The instrument. One byte is one sample.
const (
	FS = 44100 // samples a second
	N  = 400   // loop delay; with the two point average the loop is N + 0.5
	G  = 0.98  // loop gain
	R  = 0.997 // pole of the AC coupling, about 21 Hz

	ringOut   = 4 * FS // samples of zero input after the last difference
	silentMax = 2 * FS // longest recording of identical files
	headroom  = -3.0   // dBFS of the loudest sample
	frameLen  = 1102   // samples per frame when counting rings
	ringGap   = 20     // frames of quiet that still belong to one ring
)

// tuning is the pitch the string actually has: FS / (N + 0.5).
func tuning() (hz, cents float64) {
	hz = FS / (N + 0.5)
	return hz, 1200 * math.Log2(hz/110)
}

// result is everything one comparison produces.
type result struct {
	v       verdict
	w, e, t int       // recording start and end in file positions, samples rendered
	r       []float64 // sA - sB
	pcm     []int16
	peak    float64 // P, the largest |r|
	rings   int
	longest float64 // seconds
}

func measure(a, b file, seconds int) result {
	res := result{v: compare(a, b, seconds)}
	if res.v.identical() {
		res.e = min(res.v.lmax+1, silentMax)
		res.t = res.e
	} else {
		res.w = recordingStart(res.v.first)
		res.e = res.v.lastW + 1
		res.t = res.e - res.w + ringOut
	}
	res.r = sound(input(a, res.w, res.e), res.t)
	sB := sound(input(b, res.w, res.e), res.t)
	for j := range res.r {
		res.r[j] -= sB[j]
	}
	res.pcm, res.peak = quantize(res.r)
	res.rings, res.longest = rings(res.pcm)
	return res
}

// input feeds the string the file from position w, scaled by 1/256, until
// position e, then zeros for the ring-out.
func input(f file, w, e int) func(int) float64 {
	return func(j int) float64 {
		if j < e-w {
			return float64(f.val(w+j)) / 256
		}
		return 0
	}
}

// sound drives the string with x for t samples: a one pole AC coupling,
// then a Karplus-Strong loop of z^-N and a two point average. It is linear,
// so the string of A minus the string of B is the string of A minus B.
func sound(x func(int) float64, t int) []float64 {
	s := make([]float64, t)
	var xPrev, h float64
	for j := range t {
		xj := x(j)
		h = xj - xPrev + R*h
		xPrev = xj
		var s1, s2 float64
		if j >= N {
			s1 = s[j-N]
		}
		if j >= N+1 {
			s2 = s[j-N-1]
		}
		s[j] = h + 0.5*G*(s1+s2)
	}
	return s
}

// quantize normalises r so the loudest sample sits at -3 dBFS. A zero r
// stays all zero.
func quantize(r []float64) ([]int16, float64) {
	peak := 0.0
	for _, v := range r {
		peak = max(peak, math.Abs(v))
	}
	pcm := make([]int16, len(r))
	if peak == 0 {
		return pcm, 0
	}
	gain := math.Pow(10, headroom/20)
	for j, v := range r {
		pcm[j] = int16(math.Round(v * gain / peak * 32767))
	}
	return pcm, peak
}

// rings counts stretches of sound in the final samples: frames whose peak is
// within 60 dB of the file's peak, joined across gaps of up to ringGap frames.
func rings(pcm []int16) (count int, longest float64) {
	top := 0
	for _, v := range pcm {
		top = max(top, abs(int(v)))
	}
	if top == 0 {
		return 0, 0
	}
	first, last := -1, -1
	closeRing := func() {
		if first >= 0 {
			longest = max(longest, float64((last-first+1)*frameLen)/FS)
		}
	}
	for f := 0; (f+1)*frameLen <= len(pcm); f++ {
		fp := 0
		for _, v := range pcm[f*frameLen : (f+1)*frameLen] {
			fp = max(fp, abs(int(v)))
		}
		if float64(fp) < 0.001*float64(top) {
			continue
		}
		if last >= 0 && f-last <= ringGap {
			last = f
			continue
		}
		closeRing()
		first, last = f, f
		count++
	}
	closeRing()
	return count, longest
}

func abs(v int) int {
	if v < 0 {
		return -v
	}
	return v
}

// wav is the canonical 44 byte header and the samples, little endian.
func wav(pcm []int16) []byte {
	n := 2 * len(pcm)
	b := make([]byte, 44+n)
	le := binary.LittleEndian
	copy(b[0:], "RIFF")
	le.PutUint32(b[4:], uint32(36+n))
	copy(b[8:], "WAVEfmt ")
	le.PutUint32(b[16:], 16)
	le.PutUint16(b[20:], 1) // PCM
	le.PutUint16(b[22:], 1) // mono
	le.PutUint32(b[24:], FS)
	le.PutUint32(b[28:], 2*FS)
	le.PutUint16(b[32:], 2)
	le.PutUint16(b[34:], 16)
	copy(b[36:], "data")
	le.PutUint32(b[40:], uint32(n))
	for j, v := range pcm {
		le.PutUint16(b[44+2*j:], uint16(v))
	}
	return b
}

func writeWAV(path string, pcm []int16) error { return os.WriteFile(path, wav(pcm), 0o644) }
