audio/internal/convert: Reduce allocations of float32 slices

This commit is contained in:
Hajime Hoshi 2021-01-15 00:37:21 +09:00
parent 612676cb19
commit ad218eae2d

View File

@ -30,6 +30,7 @@ type f32Reader struct {
r Float32Reader r Float32Reader
eof bool eof bool
buf *byte buf *byte
fbuf []float32
} }
func max(a, b int) int { func max(a, b int) int {
@ -52,9 +53,17 @@ func (f *f32Reader) Read(buf []byte) (int, error) {
return 1, nil return 1, nil
} }
bf := make([]float32, max(len(buf)/2, 1)) l := max(len(buf)/2, 1)
ll := len(f.fbuf)
if ll < 16 {
ll = 16
}
for ll < l {
ll *= 2
}
f.fbuf = make([]float32, ll)
n, err := f.r.Read(bf) n, err := f.r.Read(f.fbuf[:l])
if err != nil && err != io.EOF { if err != nil && err != io.EOF {
return 0, err return 0, err
} }
@ -67,7 +76,7 @@ func (f *f32Reader) Read(buf []byte) (int, error) {
b = make([]byte, 2) b = make([]byte, 2)
} }
for i := 0; i < n; i++ { for i := 0; i < n; i++ {
f := bf[i] f := f.fbuf[i]
s := int16(f * (1<<15 - 1)) s := int16(f * (1<<15 - 1))
b[2*i] = uint8(s) b[2*i] = uint8(s)
b[2*i+1] = uint8(s >> 8) b[2*i+1] = uint8(s >> 8)