audio/internal/convert: Simplify f32Reader implementation

This commit is contained in:
Hajime Hoshi 2021-10-31 19:47:42 +09:00
parent 630df60894
commit a3eb8933e5

View File

@ -27,10 +27,11 @@ func NewReaderFromFloat32Reader(r Float32Reader) io.Reader {
} }
type f32Reader struct { type f32Reader struct {
r Float32Reader r Float32Reader
eof bool eof bool
buf *byte hasRemain bool
fbuf []float32 remain byte
fbuf []float32
} }
func max(a, b int) int { func max(a, b int) int {
@ -47,22 +48,15 @@ func (f *f32Reader) Read(buf []byte) (int, error) {
if len(buf) == 0 { if len(buf) == 0 {
return 0, nil return 0, nil
} }
if f.buf != nil { if f.hasRemain {
buf[0] = *f.buf buf[0] = f.remain
f.buf = nil f.hasRemain = false
return 1, nil return 1, nil
} }
l := max(len(buf)/2, 1) l := max(len(buf)/2, 1)
ll := len(f.fbuf) if cap(f.fbuf) < l {
if ll < 16 { f.fbuf = make([]float32, l)
ll = 16
}
for ll < l {
ll *= 2
}
if len(f.fbuf) < ll {
f.fbuf = make([]float32, ll)
} }
n, err := f.r.Read(f.fbuf[:l]) n, err := f.r.Read(f.fbuf[:l])
@ -86,7 +80,8 @@ func (f *f32Reader) Read(buf []byte) (int, error) {
if len(buf) == 1 && len(b) == 2 { if len(buf) == 1 && len(b) == 2 {
buf[0] = b[0] buf[0] = b[0]
f.buf = &b[1] f.remain = b[1]
f.hasRemain = true
return 1, err return 1, err
} }
return n * 2, err return n * 2, err