audio/mp3: Flexible timeout

This commit is contained in:
Hajime Hoshi 2017-12-27 19:18:02 +09:00
parent e2a026138a
commit a98b03f738

View File

@ -21,6 +21,7 @@ import (
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
"math"
"time" "time"
"github.com/gopherjs/gopherjs/js" "github.com/gopherjs/gopherjs/js"
@ -129,8 +130,9 @@ func Decode(context *audio.Context, src audio.ReadSeekCloser) (*Stream, error) {
return nil, err return nil, err
} }
var s *Stream var s *Stream
try := 0
for { for {
s, err = decode(context, b) s, err = decode(context, b, try)
switch err { switch err {
case errTryAgain: case errTryAgain:
buf, ok := seekNextFrame(b) buf, ok := seekNextFrame(b)
@ -140,6 +142,7 @@ func Decode(context *audio.Context, src audio.ReadSeekCloser) (*Stream, error) {
b = buf b = buf
continue continue
case errTimeout: case errTimeout:
try++
continue continue
default: default:
if err != nil { if err != nil {
@ -164,7 +167,7 @@ func init() {
} }
} }
func decode(context *audio.Context, buf []byte) (*Stream, error) { func decode(context *audio.Context, buf []byte, try int) (*Stream, error) {
if offlineAudioContextClass == nil { if offlineAudioContextClass == nil {
return nil, errors.New("audio/mp3: OfflineAudioContext is not available") return nil, errors.New("audio/mp3: OfflineAudioContext is not available")
} }
@ -200,12 +203,14 @@ func decode(context *audio.Context, buf []byte) (*Stream, error) {
} }
}) })
timeout := time.Duration(math.Pow(2, float64(try))) * time.Second
select { select {
case err := <-ch: case err := <-ch:
if err != nil { if err != nil {
return nil, err return nil, err
} }
case <-time.After(3 * time.Second): case <-time.After(timeout):
// Sometimes decode fails without calling the callbacks (#464). // Sometimes decode fails without calling the callbacks (#464).
// Let's just try again in this case. // Let's just try again in this case.
return nil, errTimeout return nil, errTimeout