audio/internal/convert: add a lazy-load getter for cosTable (#2404)

Closes #2286
This commit is contained in:
Nathan Levett 2022-10-23 02:24:51 +11:00 committed by GitHub
parent fc2f999ebf
commit 18123a6336
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -17,21 +17,32 @@ package convert
import (
"io"
"math"
"sync"
)
var cosTable = [65536]float64{}
var (
// cosTable contains values of cosine applied to the range [0, π/2).
// It must be initialised the first time it is referenced
// in a function via its lazy load wrapper getCosTable().
cosTable []float64
cosTableOnce sync.Once
)
func init() {
for i := range cosTable {
cosTable[i] = math.Cos(float64(i) * math.Pi / 2 / float64(len(cosTable)))
}
func getCosTable() []float64 {
cosTableOnce.Do(func() {
cosTable = make([]float64, 65536)
for i := range cosTable {
cosTable[i] = math.Cos(float64(i) * math.Pi / 2 / float64(len(cosTable)))
}
})
return cosTable
}
func fastCos01(x float64) float64 {
if x < 0 {
x = -x
}
i := int(4 * float64(len(cosTable)) * x)
i := int(4 * float64(len(getCosTable())) * x)
if 4*len(cosTable) < i {
i %= 4 * len(cosTable)
}