Skip to content

Commit

Permalink
[bugfix] ebitenPlayerSource fails when run concurrently
Browse files Browse the repository at this point in the history
Read method executed not synchronized audioSystem.ReadSamples.
  • Loading branch information
elgopher committed Aug 28, 2023
1 parent 5cfbbce commit ebf0021
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
2 changes: 1 addition & 1 deletion ebitengine/audio.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ func (e *ebitenPlayerSource) Read(p []byte) (int, error) {

bytesRead := 0

e.audioSystem.ReadSamples(e.floatBuffer[:samples])
e.ReadSamples(e.floatBuffer[:samples])
for i := 0; i < samples; i++ {
floatSample := pi.Mid(e.floatBuffer[i], -1, 1)
sample := int16(floatSample * 0x7FFF) // actually the full int16 range is -0x8000 to 0x7FFF (therefore -0x8000 will never be returned)
Expand Down
35 changes: 35 additions & 0 deletions ebitengine/audio_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
package ebitengine //nolint

import (
"sync"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -119,6 +120,40 @@ func TestEbitenPlayerSource_Read(t *testing.T) {
})
}

func TestEbitenPlayerSource_ThreadSafety(t *testing.T) {
t.Run("should not fail when run with -race flag", func(t *testing.T) {
reader := &ebitenPlayerSource{
audioSystem: &audio.Synthesizer{},
}

const goroutines = 100

var group sync.WaitGroup
group.Add(goroutines)

for i := 0; i < goroutines; i++ {
go func() {
defer group.Done()

_, err := reader.Read(make([]byte, 128))
require.NoError(t, err)
reader.Sfx(0, 0, 0, 0)
reader.Music(0, 0, 0)
reader.Stat()
reader.SetSfx(0, audio.SoundEffect{})
reader.GetSfx(0)
reader.SetMusic(0, audio.Pattern{})
reader.GetMusic(0)
_, err = reader.Save()
require.NoError(t, err)
_ = reader.Load(make([]byte, 128))
}()
}

group.Wait()
})
}

type audioSystemMock struct {
buffer []float64
}
Expand Down

0 comments on commit ebf0021

Please sign in to comment.