audio: Block all the players when suspended

This avoid to write 0 bytes when the app is in background. This
should reduce CPU usage.

Updates #931
This commit is contained in:
Hajime Hoshi 2019-09-07 01:59:36 +09:00
parent c982e00bb0
commit dbb8a5e873

View File

@ -62,12 +62,12 @@ type Context struct {
sampleRate int
err error
suspended bool
ready bool
players map[*playerImpl]struct{}
m sync.Mutex
m sync.Mutex
semaphore chan struct{}
}
var (
@ -99,19 +99,16 @@ func NewContext(sampleRate int) (*Context, error) {
c: newContext(sampleRate),
players: map[*playerImpl]struct{}{},
inited: make(chan struct{}),
semaphore: make(chan struct{}, 1),
}
theContext = c
h := getHook()
h.OnSuspendAudio(func() {
c.m.Lock()
c.suspended = true
c.m.Unlock()
c.semaphore <- struct{}{}
})
h.OnResumeAudio(func() {
c.m.Lock()
c.suspended = false
c.m.Unlock()
<-c.semaphore
})
h.AppendHookOnBeforeUpdate(func() error {
@ -141,13 +138,6 @@ func CurrentContext() *Context {
return c
}
func (c *Context) playable() bool {
c.m.Lock()
s := c.suspended
c.m.Unlock()
return !s
}
func (c *Context) hasError() bool {
c.m.Lock()
r := c.err != nil
@ -447,11 +437,10 @@ func (p *playerImpl) read() ([]byte, bool) {
const bufSize = 2048
if !p.context.playable() {
// Fill zero values, or the driver can block forever as trying to proceed.
buf := make([]byte, bufSize)
return buf, true
}
p.context.semaphore <- struct{}{}
defer func() {
<-p.context.semaphore
}()
newBuf := make([]byte, bufSize-len(p.buf))
n, err := p.src.Read(newBuf)