audio/mp3: Bug fix: Close source when needed

This commit is contained in:
Hajime Hoshi 2019-03-31 22:58:22 +09:00
parent aa042980ee
commit 49c0b64b60

View File

@ -21,6 +21,7 @@
package mp3 package mp3
import ( import (
"io"
"runtime" "runtime"
"github.com/hajimehoshi/go-mp3" "github.com/hajimehoshi/go-mp3"
@ -33,6 +34,7 @@ import (
type Stream struct { type Stream struct {
orig *mp3.Decoder orig *mp3.Decoder
resampling *convert.Resampling resampling *convert.Resampling
toClose io.Closer
} }
// Read is implementation of io.Reader's Read. // Read is implementation of io.Reader's Read.
@ -54,10 +56,7 @@ func (s *Stream) Seek(offset int64, whence int) (int64, error) {
// Close is implementation of io.Closer's Close. // Close is implementation of io.Closer's Close.
func (s *Stream) Close() error { func (s *Stream) Close() error {
runtime.SetFinalizer(s, nil) runtime.SetFinalizer(s, nil)
if s.resampling != nil { return s.toClose.Close()
return s.resampling.Close()
}
return nil
} }
// Length returns the size of decoded stream in bytes. // Length returns the size of decoded stream in bytes.
@ -83,13 +82,17 @@ func Decode(context *audio.Context, src audio.ReadSeekCloser) (*Stream, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
var toClose io.Closer = src
var r *convert.Resampling var r *convert.Resampling
if d.SampleRate() != context.SampleRate() { if d.SampleRate() != context.SampleRate() {
r = convert.NewResampling(d, d.Length(), d.SampleRate(), context.SampleRate()) r = convert.NewResampling(d, d.Length(), d.SampleRate(), context.SampleRate())
toClose = r
} }
s := &Stream{ s := &Stream{
orig: d, orig: d,
resampling: r, resampling: r,
toClose: toClose,
} }
runtime.SetFinalizer(s, (*Stream).Close) runtime.SetFinalizer(s, (*Stream).Close)
return s, nil return s, nil