Skip to content

Commit

Permalink
Replace the implementation of Mix with Mixer
Browse files Browse the repository at this point in the history
  • Loading branch information
MarkKremer committed Jan 3, 2024
1 parent 746bf70 commit 2858cbe
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 41 deletions.
42 changes: 4 additions & 38 deletions compositors.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,44 +98,10 @@ func Seq(s ...Streamer) Streamer {
//
// Mix does not propagate errors from the Streamers.
func Mix(s ...Streamer) Streamer {
return StreamerFunc(func(samples [][2]float64) (n int, ok bool) {
var tmp [512][2]float64

for len(samples) > 0 {
toStream := len(tmp)
if toStream > len(samples) {
toStream = len(samples)
}

// clear the samples
for i := range samples[:toStream] {
samples[i] = [2]float64{}
}

snMax := 0 // max number of streamed samples in this iteration
for _, st := range s {
// mix the stream
sn, sok := st.Stream(tmp[:toStream])
if sn > snMax {
snMax = sn
}
ok = ok || sok

for i := range tmp[:sn] {
samples[i][0] += tmp[i][0]
samples[i][1] += tmp[i][1]
}
}

n += snMax
if snMax < len(tmp) {
break
}
samples = samples[snMax:]
}

return n, ok
})
return &Mixer{
streamers: s,
stopWhenEmpty: true,
}
}

// Dup returns two Streamers which both stream the same data as the original s. The two Streamers
Expand Down
4 changes: 1 addition & 3 deletions compositors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,7 @@ func TestMix(t *testing.T) {

got := testtools.Collect(beep.Mix(s...))

if !reflect.DeepEqual(want, got) {
t.Error("Mix not working correctly")
}
testtools.AssertSamplesEqual(t, want, got)
}

func TestDup(t *testing.T) {
Expand Down
22 changes: 22 additions & 0 deletions internal/testtools/asserts.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,25 @@ func AssertStreamerHasCorrectReturnBehaviour(t *testing.T, s beep.Streamer, expe
assert.Equal(t, 0, n)
assert.NoError(t, s.Err())
}

func AssertSamplesEqual(t *testing.T, expected, actual [][2]float64) {
t.Helper()

if len(expected) != len(actual) {
t.Errorf("expected sample data length to be %d, got %d", len(expected), len(actual))
return
}

const epsilon = 1e-9
equals := true
for i := range expected {
if actual[i][0] < expected[i][0]-epsilon || actual[i][0] > expected[i][0]+epsilon ||
actual[i][1] < expected[i][1]-epsilon || actual[i][1] > expected[i][1]+epsilon {
equals = false
break
}
}
if !equals {
t.Errorf("the sample data isn't equal to the expected data")
}
}

0 comments on commit 2858cbe

Please sign in to comment.