stream.go | 23 ++++++++++++++++------- stream_test.go | 19 +++++++++++++++++++ diff --git a/stream.go b/stream.go index 5e0c8636bf166d827b83fb949041507d6d067c41..de8dbaef8360dae6187d3984f77cf134276f4824 100644 --- a/stream.go +++ b/stream.go @@ -63,8 +63,9 @@ if s.oggfile != nil { 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 @@ s.buf = make([]byte, maxEncodedFrameSize) 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 0000000000000000000000000000000000000000..08c07fde8c4eb31f5cae58b84799498328cf54f6 --- /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") + } +}