speaker: improve concurrency, only lock when and what necessary

This commit is contained in:
faiface 2017-07-06 22:11:03 +02:00
parent cb4bb4c3ef
commit 0737b86059
1 changed files with 14 additions and 16 deletions

View File

@ -11,10 +11,12 @@ import (
) )
var ( var (
mu sync.Mutex streamerMu sync.Mutex
streamer audio.Streamer streamer audio.Streamer
samples [][2]float64 samples [][2]float64
buf []byte buf []byte
playerMu sync.Mutex
player *oto.Player player *oto.Player
) )
@ -26,8 +28,8 @@ var (
// bufferSize means lower CPU usage and more reliable playback. Lower bufferSize means better // bufferSize means lower CPU usage and more reliable playback. Lower bufferSize means better
// responsiveness and less delay. // responsiveness and less delay.
func Init(bufferSize time.Duration) error { func Init(bufferSize time.Duration) error {
mu.Lock() playerMu.Lock()
defer mu.Unlock() defer playerMu.Unlock()
if player != nil { if player != nil {
player.Close() player.Close()
@ -51,10 +53,9 @@ func Init(bufferSize time.Duration) error {
// Play starts playing the provided Streamer through the speaker. // Play starts playing the provided Streamer through the speaker.
func Play(s audio.Streamer) { func Play(s audio.Streamer) {
mu.Lock() streamerMu.Lock()
defer mu.Unlock()
streamer = s streamer = s
streamerMu.Unlock()
} }
// Update pulls new data from the playing Streamers and sends it to the speaker. Blocks until the // Update pulls new data from the playing Streamers and sends it to the speaker. Blocks until the
@ -63,23 +64,18 @@ func Play(s audio.Streamer) {
// This function should be called at least once the duration of bufferSize given in Init, but it's // This function should be called at least once the duration of bufferSize given in Init, but it's
// recommended to call it more frequently to avoid glitches. // recommended to call it more frequently to avoid glitches.
func Update() error { func Update() error {
mu.Lock()
defer mu.Unlock()
if player == nil {
panic("didn't call speaker.Init")
}
// pull data from the streamer, if any // pull data from the streamer, if any
streamerMu.Lock()
n := 0 n := 0
if streamer != nil { if streamer != nil {
var ok bool var ok bool
n, ok = streamer.Stream(samples) n, ok = streamer.Stream(samples)
if !ok { if !ok {
streamer = nil streamer = nil
return nil
} }
} }
streamerMu.Unlock()
// convert samples to bytes // convert samples to bytes
for i := range samples[:n] { for i := range samples[:n] {
@ -104,7 +100,9 @@ func Update() error {
buf[i] = 0 buf[i] = 0
} }
playerMu.Lock()
player.Write(buf) player.Write(buf)
playerMu.Unlock()
return nil return nil
} }