From c5395ca98ad8644bd73166b75a88ac79121211ca Mon Sep 17 00:00:00 2001 From: Hraban Luyat Date: Sun, 5 Jul 2015 21:03:21 +0100 Subject: [PATCH] Change stream reader API to look like io.Reader --- stream.go | 23 ++++++++++++++++------- stream_test.go | 19 +++++++++++++++++++ 2 files changed, 35 insertions(+), 7 deletions(-) create mode 100644 stream_test.go diff --git a/stream.go b/stream.go index 5e0c863..de8dbae 100644 --- a/stream.go +++ b/stream.go @@ -63,8 +63,9 @@ func (s *Stream) Init(read io.Reader) error { return fmt.Errorf("opus stream is already initialized") } if read == nil { - return fmt.Errorf("Reader function must be non-nil") + return fmt.Errorf("Reader must be non-nil") } + s.read = read var errno C.int oggfile := C.op_open_callbacks( unsafe.Pointer(s), @@ -80,20 +81,28 @@ func (s *Stream) Init(read io.Reader) error { return nil } -func (s *Stream) Read() ([]int16, error) { +// Read a chunk of raw opus data from the stream and decode it. Returns the +// number of decoded samples per channel. This means that a dual channel +// (stereo) feed will have twice as many samples as the value returned. +func (s *Stream) Read(pcm []int16) (int, error) { if s.oggfile == nil { - return nil, fmt.Errorf("opus stream is uninitialized or already closed") + return 0, fmt.Errorf("opus stream is uninitialized or already closed") + } + if len(pcm) == 0 { + return 0, nil } - pcm := make([]int16, xMAX_FRAME_SIZE) n := C.op_read( s.oggfile, (*C.opus_int16)(&pcm[0]), - C.int(cap(pcm)), + C.int(len(pcm)), nil) if n < 0 { - return nil, opusfileerr(n) + return 0, opusfileerr(n) + } + if n == 0 { + return 0, io.EOF } - return pcm[:n], nil + return int(n), nil } func (s *Stream) Close() error { diff --git a/stream_test.go b/stream_test.go new file mode 100644 index 0000000..08c07fd --- /dev/null +++ b/stream_test.go @@ -0,0 +1,19 @@ +// Copyright © 2015 Hraban Luyat +// +// License for use of this code is detailed in the LICENSE file + +package opus + +import ( + "strings" + "testing" +) + +func Test(t *testing.T) { + // Simple testing, no actual decoding + reader := strings.NewReader("hello") + _, err := NewStream(reader) + if err == nil { + t.Fatalf("Expected error while initializing illegal opus stream") + } +} -- 2.48.1