DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
StereoWidth.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
30#include "../Core/DspMath.h"
31#include "../Core/AudioSpec.h"
32#include "../Core/AudioBuffer.h"
33#include "../Core/StateBlob.h"
34
35#include <algorithm>
36#include <atomic>
37#include <cmath>
38#include <cstdint>
39#include <numbers>
40#include <vector>
41
42namespace dspark {
43
50template <FloatType T>
52{
53public:
54 StereoWidth() = default;
55 ~StereoWidth() = default; // Removed virtual to prevent vtable overhead
56
61 void prepare(double sampleRate) noexcept
62 {
63 if (!(sampleRate > 0.0) || !std::isfinite(sampleRate)) return;
64 sampleRate_ = sampleRate;
65 widthMaxStep_ = static_cast<T>(1.0 / (sampleRate * 0.02));
66 updateBassMonoCoeff(bassMonoCutoff_.load(std::memory_order_relaxed));
67 reset();
68 }
69
71 void prepare(const AudioSpec& spec) noexcept { prepare(spec.sampleRate); }
72
77 void processBlock(AudioBufferView<T> buffer) noexcept
78 {
79 if (buffer.getNumChannels() >= 2)
80 process(buffer.getChannel(0), buffer.getChannel(1), buffer.getNumSamples());
81 }
82
89 void setWidth(T width) noexcept
90 {
91 if (!std::isfinite(width)) return;
92 width_.store(std::max(T(0), width), std::memory_order_relaxed);
93 }
94
96 [[nodiscard]] T getWidth() const noexcept { return width_.load(std::memory_order_relaxed); }
97
106 void setBassMono(bool enabled, double cutoffHz = 100.0) noexcept
107 {
108 if (cutoffHz > 0.0 && std::isfinite(cutoffHz))
109 {
110 bassMonoCutoff_.store(cutoffHz, std::memory_order_relaxed);
111 updateBassMonoCoeff(cutoffHz);
112 }
113 bassMonoEnabled_.store(enabled, std::memory_order_release);
114 }
115
122 void process(T* left, T* right, int numSamples) noexcept
123 {
124 if (numSamples <= 0) return;
125
126 // Front-door non-finite guard: the bass-mono side filter is recursive,
127 // so one NaN/Inf sample would latch it (and both outputs) forever.
128 // No-op on finite input.
129 for (int i = 0; i < numSamples; ++i)
130 {
131 if (!std::isfinite(left[i])) left[i] = T(0);
132 if (!std::isfinite(right[i])) right[i] = T(0);
133 }
134
135 // Load atomics once per block to allow tight loop vectorization. The
136 // width ramp is closed form per sample (moveTowards), so the pure-width
137 // loop still vectorizes; settled, it reduces to the constant exactly.
138 const T widthTarget = width_.load(std::memory_order_relaxed);
139 if (snapWidth_)
140 {
141 currentWidth_ = widthTarget;
142 snapWidth_ = false;
143 }
144 const T widthStart = currentWidth_;
145 const T widthStep = widthMaxStep_;
146 const bool bassMono = bassMonoEnabled_.load(std::memory_order_acquire);
147
148 // The bass mono fades in and out over 20 ms with its filter running
149 // (switching it outright stepped the side by its low end); coming
150 // back from rest, the filter starts from silence under a fade that
151 // starts from zero. Settled, the arithmetic is the plain filter's.
152 const T bassTarget = bassMono ? T(1) : T(0);
153 if (snapBass_)
154 {
155 bassAmount_ = bassTarget;
156 snapBass_ = false;
157 }
158 if (bassMono && bassAmount_ == T(0)) sideState_ = T(0);
159 const T bassStart = bassAmount_;
160
161 if (bassMono || bassAmount_ > T(0))
162 {
163 const T coeff = bassMonoCoeff_.load(std::memory_order_relaxed);
164
165 // Bass-mono crossover: the side channel loses its lows through a
166 // one-pole high-pass; the mid passes UNTOUCHED. A one-pole split is
167 // complementary (LP + HP == 1 exactly), so no phase "compensation"
168 // of the mid is needed - the previously used first-order allpass
169 // rotated the mid by up to 180 degrees at HF, which swapped and
170 // inverted the channels above the transition band.
171 for (int i = 0; i < numSamples; ++i)
172 {
173 T l = left[i];
174 T r = right[i];
175
176 const T width = moveTowards(widthStart, widthTarget, widthStep * static_cast<T>(i + 1));
177 T mid = (l + r) * T(0.5);
178 T side = (l - r) * T(0.5) * width;
179
180 // Side processing (1-pole high-pass: side - LP(side))
181 T sideLpIn = side;
182 sideState_ += coeff * (sideLpIn - sideState_) + antiDenormal_;
183 sideState_ -= antiDenormal_; // Denormal flush
184 const T amount = moveTowards(bassStart, bassTarget, widthStep * static_cast<T>(i + 1));
185 side = sideLpIn - amount * sideState_;
186
187 left[i] = mid + side;
188 right[i] = mid - side;
189 }
190 }
191 else
192 {
193 // Fast-path branch: Pure Width control without filtering overhead
194 for (int i = 0; i < numSamples; ++i)
195 {
196 const T width = moveTowards(widthStart, widthTarget, widthStep * static_cast<T>(i + 1));
197 T mid = (left[i] + right[i]) * T(0.5);
198 T side = (left[i] - right[i]) * T(0.5) * width;
199
200 left[i] = mid + side;
201 right[i] = mid - side;
202 }
203 }
204 currentWidth_ = moveTowards(widthStart, widthTarget, widthStep * static_cast<T>(numSamples));
205 bassAmount_ = moveTowards(bassStart, bassTarget, widthStep * static_cast<T>(numSamples));
206 }
207
209 void reset() noexcept
210 {
211 sideState_ = T(0);
212 snapWidth_ = true; // the next block starts settled (no glide on start)
213 snapBass_ = true;
214 }
215
216
218 [[nodiscard]] std::vector<uint8_t> getState() const
219 {
220 // The blob stores float: the casts keep the double instantiation
221 // compiling (a double matches no StateWriter overload unambiguously).
222 StateWriter w(stateId("WIDE"), 1);
223 w.write("width", static_cast<float>(width_.load(std::memory_order_relaxed)));
224 w.write("bassMono", bassMonoEnabled_.load(std::memory_order_relaxed));
225 w.write("bassCutoff", static_cast<float>(bassMonoCutoff_.load(std::memory_order_relaxed)));
226 return w.blob();
227 }
228
230 bool setState(const uint8_t* data, size_t size)
231 {
232 StateReader r(data, size);
233 if (!r.isValid() || r.processorId() != stateId("WIDE")) return false;
234 setWidth(static_cast<T>(r.read("width", 1.0f)));
235 setBassMono(r.read("bassMono", false),
236 static_cast<double>(r.read("bassCutoff", 100.0f)));
237 return true;
238 }
239
240protected:
241 void updateBassMonoCoeff(double cutoff) noexcept
242 {
243 if (sampleRate_ > 0.0)
244 {
245 // Calculate 1-pole coeff. Stored atomically to prevent data races.
246 T coeff = static_cast<T>(1.0 - std::exp(-std::numbers::pi * 2.0 * cutoff / sampleRate_));
247 bassMonoCoeff_.store(coeff, std::memory_order_relaxed);
248 }
249 }
250
251private:
252 double sampleRate_ = 48000.0;
253
254 // Lock-free parameters
255 std::atomic<T> width_ { T(1) };
256 std::atomic<bool> bassMonoEnabled_ { false };
257 std::atomic<double> bassMonoCutoff_ { 100.0 };
258 std::atomic<T> bassMonoCoeff_ { T(0) };
259
260 // Filter states
261 T sideState_ = T(0);
262
263 // Width glide (audio thread)
264 T currentWidth_ = T(1);
265 T widthMaxStep_ = T(1.0 / 960.0);
266 bool snapWidth_ = true;
267 T bassAmount_ = T(0);
268 bool snapBass_ = true;
269
270 // Anti-denormal DC offset (type generic)
271 static constexpr T antiDenormal_ = static_cast<T>(1e-15);
272};
273
274} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
Tolerant reader: missing keys yield defaults, unknown keys are skipped.
Definition StateBlob.h:171
float read(const char *key, float defaultValue) const
Reads a float, or defaultValue when the key is absent.
Definition StateBlob.h:214
bool isValid() const noexcept
Definition StateBlob.h:209
uint32_t processorId() const noexcept
Definition StateBlob.h:210
Serializes key/value parameters into a versioned blob.
Definition StateBlob.h:53
std::vector< uint8_t > blob() const
Finalizes and returns the blob.
Definition StateBlob.h:112
void write(const char *key, float value)
Writes a float parameter.
Definition StateBlob.h:71
High-performance stereo image processor with phase-aligned bass mono.
Definition StereoWidth.h:52
void setWidth(T width) noexcept
Sets the overall stereo width factor.
Definition StereoWidth.h:89
void processBlock(AudioBufferView< T > buffer) noexcept
Processes an AudioBufferView in-place.
Definition StereoWidth.h:77
void process(T *left, T *right, int numSamples) noexcept
Process a full block of audio. Optimized for SIMD vectorization.
void prepare(const AudioSpec &spec) noexcept
Prepares from AudioSpec (unified API).
Definition StereoWidth.h:71
std::vector< uint8_t > getState() const
Serializes the parameter state (setup/UI threads; allocates).
T getWidth() const noexcept
Returns current width setting.
Definition StereoWidth.h:96
void prepare(double sampleRate) noexcept
Prepares the processor and resets internal states.
Definition StereoWidth.h:61
void setBassMono(bool enabled, double cutoffHz=100.0) noexcept
Toggles Bass Mono and updates the crossover frequency.
~StereoWidth()=default
void updateBassMonoCoeff(double cutoff) noexcept
bool setState(const uint8_t *data, size_t size)
Restores parameters from a blob (tolerant; rejects foreign ids).
void reset() noexcept
Clears the internal filter states to prevent artifact ringing.
Main namespace for the DSPark framework.
T moveTowards(T from, T to, T maxDelta) noexcept
Moves a value toward a target by at most a given distance.
Definition DspMath.h:137
constexpr uint32_t stateId(const char(&tag)[5]) noexcept
Builds a FOURCC processor id, e.g. dspark::stateId("COMP").
Definition StateBlob.h:672
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37