package audio import "math" // Float is all floating point number types (and Samples). type Float interface { ~float32 | ~float64 } // Clamp a sample in [-1..+1]. func Clamp[T Float](sample T) T { if sample < -1 { return -1 } if sample > +1 { return +1 } return sample } // Abs a slice of values. func Abs[T Float](values []T) { for i, v := range values { values[i] = T(math.Abs(float64(v))) } } // Mean of values. func Mean[T Float](values []T) T { if len(values) == 0 { return 0 } // an algorithm that attempts to retain accuracy // with widely different values. var parts []float64 for _, v := range values { var ( x = float64(v) i int ) for _, p := range parts { sum := p + x var err float64 switch ax, ap := math.Abs(x), math.Abs(p); { case ax < ap: err = x - (sum - p) case ap < ax: err = p - (sum - x) } if err != 0 { parts[i] = err i++ } x = sum } parts = append(parts[:i], x) } var sum float64 for _, x := range parts { sum += x } return T(sum / float64(len(values))) } // RMS calculates the root mean square of values. func RMS[T Float](values []T) T { if len(values) == 0 { return 0 } var squares float64 for _, v := range values { squares += float64(v) * float64(v) } return T(math.Sqrt(squares / float64(len(values)))) } // Sum of values. func Sum[T Float](values []T) T { if len(values) == 0 { return 0 } var sum T for _, v := range values { sum += v } return sum } // SQNR is the signal-to-quantization-noise ratio. func SQNR(bits int) float64 { return 20 * math.Log10(math.Pow(2, float64(bits))) }