refactor: use [][2] as audio buffers, instead of []float32

Throughout sointu, we assume stereo audiobuffers, but were passing
around []float32. This had several issues, including len(buf)/2 and
numSamples*2 type of length conversion in many places. Also, it
caused one bug in a test case, causing it to succeed when it should
have not (the test had +-1 when it should have had +-2). This
refactoring makes it impossible to have odd length buffer issues.
This commit is contained in:
5684185+vsariola@users.noreply.github.com
2023-10-18 13:51:02 +03:00
parent bb0d4d6800
commit 38e9007bf8
14 changed files with 106 additions and 82 deletions

View File

@ -2,6 +2,8 @@ package oto
import (
"math"
"github.com/vsariola/sointu"
)
// FloatBufferTo16BitLE is a naive helper method to convert []float32 buffers to
@ -9,17 +11,22 @@ import (
//
// Appends the encoded bytes into "to" slice, allowing you to preallocate the
// capacity or just use nil
func FloatBufferTo16BitLE(from []float32, to []byte) []byte {
func FloatBufferTo16BitLE(from sointu.AudioBuffer, to []byte) []byte {
for _, v := range from {
var uv int16
if v < -1.0 {
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)
}
to = append(to, byte(uv&255), byte(uv>>8))
left := to16BitSample(v[0])
right := to16BitSample(v[1])
to = append(to, byte(left&255), byte(left>>8), byte(right&255), byte(right>>8))
}
return to
}
// convert float32 to int16, clamping to min and max
func to16BitSample(v float32) int16 {
if v < -1.0 {
return -math.MaxInt16
}
if v > 1.0 {
return math.MaxInt16
}
return int16(v * math.MaxInt16)
}