package main

import (
	"io"
	"math"
	"sort"
)

// The recording has no room tone to measure against when its quietest
// un-gated tenth is louder than this.
const floorCeilingDBFS = -30.0

const fullScale = 32768.0

// window is 20 ms of the recording, all channels together.
type window struct {
	sumsq uint64 // sum of squared samples, in LSB
	n     uint32 // samples (frames times channels)
	peak  uint16 // largest absolute sample
}

func (w window) rms() float64 { return math.Sqrt(float64(w.sumsq) / float64(w.n)) }

// gated is digital silence: a muted line, or one LSB of flicker.
func (w window) gated() bool { return w.peak <= 1 }

func winFrames(rate int) int { return max(1, int(math.Round(float64(rate)*0.02))) }

// measure reads the whole recording once, in 20 ms windows, the last partial
// one kept.
func measure(in *wavIn) ([]window, int64, error) {
	wf := winFrames(in.rate)
	buf := make([]int16, wf*in.ch)
	var wins []window
	var frames int64
	for {
		n, err := in.read(buf)
		if n > 0 {
			var w window
			for _, s := range buf[:n*in.ch] {
				a := int64(s)
				w.sumsq += uint64(a * a)
				if a < 0 {
					a = -a
				}
				w.peak = max(w.peak, uint16(a))
			}
			w.n = uint32(n * in.ch)
			wins = append(wins, w)
			frames += int64(n)
		}
		if err == io.EOF {
			return wins, frames, nil
		}
		if err != nil {
			return nil, 0, err
		}
	}
}

// floorLSB is the 10th percentile RMS of the windows that are not gated,
// never below 1 LSB.
func floorLSB(wins []window) float64 {
	var r []float64
	for _, w := range wins {
		if !w.gated() {
			r = append(r, w.rms())
		}
	}
	if len(r) == 0 {
		return 1
	}
	sort.Float64s(r)
	return math.Max(r[int(math.Floor(0.10*float64(len(r)-1)))], 1)
}

func dbfs(lsb float64) float64 { return 20 * math.Log10(lsb/fullScale) }

type pause struct {
	startFrame int64
	frames     int64
	level      float64 // dBFS, -Inf when every sample is zero
	tone       int     // percent of windows that hold tone, rounded
	copied     bool
}

type result struct {
	floorDB     float64
	quietDB     float64
	digitalOnly bool
	pauses      []pause
}

// analyze applies the rule to the windows.
func analyze(wins []window, rate, ch int, minSec, above float64) result {
	fl := floorLSB(wins)
	res := result{floorDB: dbfs(fl)}
	threshold := fl * math.Pow(10, above/20)
	res.quietDB = dbfs(threshold)
	res.digitalOnly = res.floorDB > floorCeilingDBFS
	quiet := func(w window) bool {
		return w.gated() || (!res.digitalOnly && w.rms() <= threshold)
	}
	need := int(math.Ceil(minSec/0.02 - 1e-9))
	wf := int64(winFrames(rate))
	for i := 0; i < len(wins); {
		if !quiet(wins[i]) {
			i++
			continue
		}
		j := i
		for j < len(wins) && quiet(wins[j]) {
			j++
		}
		if j-i >= need {
			res.pauses = append(res.pauses, measurePause(wins[i:j], int64(i)*wf, ch))
		}
		i = j
	}
	return res
}

func measurePause(run []window, start int64, ch int) pause {
	var sumsq float64
	var n int64
	tone := 0
	for _, w := range run {
		sumsq += float64(w.sumsq)
		n += int64(w.n)
		if !w.gated() {
			tone++
		}
	}
	p := pause{startFrame: start, frames: n / int64(ch), level: math.Inf(-1)}
	if sumsq > 0 {
		p.level = dbfs(math.Sqrt(sumsq / float64(n)))
	}
	p.tone = int(math.Round(100 * float64(tone) / float64(len(run))))
	p.copied = p.tone >= 90
	return p
}
