From dbb8a5e873e273869cd8b441afcb9f677a9c36c7 Mon Sep 17 00:00:00 2001 From: Hajime Hoshi Date: Sat, 7 Sep 2019 01:59:36 +0900 Subject: [PATCH] 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 --- audio/audio.go | 29 +++++++++-------------------- 1 file changed, 9 insertions(+), 20 deletions(-) diff --git a/audio/audio.go b/audio/audio.go index 97621ccd2..d7ec2e79e 100644 --- a/audio/audio.go +++ b/audio/audio.go @@ -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)