go-pus/opus_test.go
DataHoarder 3d5460c48a
Some checks failed
continuous-integration/drone/push Build is failing
Fix TestCodecFloat32
2022-07-21 15:06:34 +02:00

113 lines
2.9 KiB
Go

// Copyright © Go Opus Authors (see AUTHORS file)
//
// License for use of this code is detailed in the LICENSE file
package opus
import (
"bytes"
"io"
"strings"
"testing"
)
func TestVersion(t *testing.T) {
if ver := Version(); !strings.HasPrefix(ver, "libopus") {
t.Errorf("Unexpected linked libopus version: " + ver)
}
}
func TestOpusErrstr(t *testing.T) {
// I scooped this -1 up from opus_defines.h, it's OPUS_BAD_ARG. Not pretty,
// but it's better than not testing at all. Again, accessing #defines from
// CGO is not possible.
if ErrBadArg.Error() != "opus: invalid argument" {
t.Errorf("Expected \"invalid argument\" error message for error code %d: %v",
ErrBadArg, ErrBadArg)
}
}
func TestCodec(t *testing.T) {
// Create bogus input sound
const G4 = 391.995
const SAMPLE_RATE = 48000
const FRAME_SIZE_MS = 60
const FRAME_SIZE = SAMPLE_RATE * FRAME_SIZE_MS / 1000
pcm := make([]int16, FRAME_SIZE)
data := new(bytes.Buffer)
enc, err := NewEncoder(SAMPLE_RATE, 1, AppVoIP, data)
if err != nil || enc == nil {
t.Fatalf("Error creating new encoder: %v", err)
}
addSine(pcm, SAMPLE_RATE, G4)
err = enc.Encode(pcm)
if err != nil {
t.Fatalf("Couldn't encode data: %v", err)
}
enc.Close()
dec, err := NewStream(bytes.NewReader(data.Bytes()))
if err != nil || dec == nil {
t.Fatalf("Error creating new decoder: %v", err)
}
toRead := len(pcm)
for toRead != 0 {
n, err := dec.Read(pcm)
if err == io.EOF {
break
} else if err != nil {
t.Fatalf("Couldn't decode data: %v", err)
}
toRead -= n
}
if toRead != 0 {
t.Fatalf("Length mismatch: %d samples in, %d out", len(pcm), len(pcm)-toRead)
}
// Checking the output programmatically is seriously not easy. I checked it
// by hand and by ear, it looks fine. I'll just assume the API faithfully
// passes error codes through, and that's that.
}
func TestCodecFloat32(t *testing.T) {
// Create bogus input sound
const G4 = 391.995
const SAMPLE_RATE = 48000
const FRAME_SIZE_MS = 60
const FRAME_SIZE = SAMPLE_RATE * FRAME_SIZE_MS / 1000
pcm := make([]float32, FRAME_SIZE)
data := new(bytes.Buffer)
enc, err := NewEncoder(SAMPLE_RATE, 1, AppVoIP, data)
if err != nil || enc == nil {
t.Fatalf("Error creating new encoder: %v", err)
}
addSineFloat32(pcm, SAMPLE_RATE, G4)
err = enc.EncodeFloat32(pcm)
enc.Close()
if err != nil {
t.Fatalf("Couldn't encode data: %v", err)
}
dec, err := NewStream(bytes.NewReader(data.Bytes()))
if err != nil || dec == nil {
t.Fatalf("Error creating new decoder: %v", err)
}
// TODO: Uh-oh.. it looks like I forgot to put a data = data[:n] here, yet
// the test is not failing. Why?
var out []float32
buf := make([]float32, 120*SAMPLE_RATE)
for {
n, err := dec.ReadFloat32(pcm)
if err != nil {
break
}
out = append(out, buf[:n]...)
}
if len(out) != len(pcm) {
t.Fatalf("Length mismatch: %d samples in, %d out", len(out), len(pcm))
}
}