refactor(oto): reuse temp buffers for repeated calls to convert buffer

This commit is contained in:
vsariola
2020-12-31 16:24:34 +02:00
parent 1d91603e36
commit c68d9d3bf5
3 changed files with 21 additions and 27 deletions

View File

@ -1,29 +1,25 @@
package oto
import (
"bytes"
"encoding/binary"
"fmt"
"math"
)
// FloatBufferTo16BitLE is a naive helper method to convert []float32 buffers to
// 16-bit little-endian integer buffers.
// TODO: optimize/refactor this, current is far from the best solution
func FloatBufferTo16BitLE(buff []float32) ([]byte, error) {
var buf bytes.Buffer
for i, v := range buff {
// 16-bit little-endian, but encoded in byte buffer
//
// Appends the encoded bytes into "to" slice, allowing you to preallocate the
// capacity or just use nil
func FloatBufferTo16BitLE(from []float32, to []byte) []byte {
for _, v := range from {
var uv int16
if v < -1.0 {
uv = -math.MaxInt16
uv = -math.MaxInt16 // we are a bit lazy: -1.0 is encoded as -32767, as this makes math easier, and -32768 is unused
} else if v > 1.0 {
uv = math.MaxInt16
} else {
uv = int16(v * math.MaxInt16)
}
if err := binary.Write(&buf, binary.LittleEndian, uv); err != nil {
return nil, fmt.Errorf("error converting buffer (@ %v, value %v) to bytes: %w", i, v, err)
}
to = append(to, byte(uv&255), byte(uv>>8))
}
return buf.Bytes(), nil
return to
}