]> Sergey Matveev's repositories - go-opus.git/commitdiff
Change stream reader API to look like io.Reader
authorHraban Luyat <hraban@0brg.net>
Sun, 5 Jul 2015 20:03:21 +0000 (21:03 +0100)
committerHraban Luyat <hraban@0brg.net>
Sun, 5 Jul 2015 20:03:21 +0000 (21:03 +0100)
stream.go
stream_test.go [new file with mode: 0644]

index 5e0c8636bf166d827b83fb949041507d6d067c41..de8dbaef8360dae6187d3984f77cf134276f4824 100644 (file)
--- 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 (file)
index 0000000..08c07fd
--- /dev/null
@@ -0,0 +1,19 @@
+// Copyright © 2015 Hraban Luyat <hraban@0brg.net>
+//
+// 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")
+       }
+}