+
+ // Apply stereo width settings. Set stereo width w to a 0..1 range instead of
+ // -1..1, since it makes for much easier calculations (so 0.5 = completely mono).
+ // Then, what we want is
+ //
+ // L' = wL + (1-w)R = R + w(L-R)
+ // R' = wR + (1-w)L = L + w(R-L)
+ //
+ // This can be further simplified calculation-wise by defining the weighted
+ // difference signal D = w(R-L), so that:
+ //
+ // L' = R - D
+ // R' = L + D
+ float w = 0.5f * stereo_width + 0.5f;
+ if (bus.source_channel[0] == bus.source_channel[1]) {
+ // Mono anyway, so no need to bother.
+ w = 1.0f;
+ } else if (fabs(w) < 1e-3) {
+ // Perfect inverse.
+ swap(lsrc, rsrc);
+ swap(lstride, rstride);
+ w = 1.0f;
+ }
+ if (fabs(w - 1.0f) < 1e-3) {
+ // No calculations needed for stereo_width = 1.
+ for (unsigned i = 0; i < num_samples; ++i) {
+ *dptr++ = *lsrc;
+ *dptr++ = *rsrc;
+ lsrc += lstride;
+ rsrc += rstride;
+ }
+ } else {
+ // General case.
+ for (unsigned i = 0; i < num_samples; ++i) {
+ float left = *lsrc, right = *rsrc;
+ float diff = w * (right - left);
+ *dptr++ = right - diff;
+ *dptr++ = left + diff;
+ lsrc += lstride;
+ rsrc += rstride;
+ }