mirror of
https://github.com/vsariola/sointu.git
synced 2025-07-18 13:04:25 -04:00
refactor(oto): reuse temp buffers for repeated calls to convert buffer
This commit is contained in:
@ -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
|
||||
}
|
||||
|
Reference in New Issue
Block a user