go-pus/opus_test.go
DataHoarder 6cc027f24d
Some checks failed
continuous-integration/drone/push Build is failing
Use libopusenc to encode stream, WiP: tests
2022-02-27 18:56:08 +01:00

106 lines
2.8 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)
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?
n, err := dec.ReadFloat32(pcm)
if err != nil {
t.Fatalf("Couldn't decode data: %v", err)
}
if len(pcm) != n {
t.Fatalf("Length mismatch: %d samples in, %d out", len(pcm), n)
}
}