DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
DryWetMixer.h
1// DSPark -- Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi -- MIT License
3
4#pragma once
5
49#include "AudioBuffer.h"
50#include "AudioSpec.h"
51
52#include <algorithm>
53#include <array>
54#include <atomic>
55#include <cmath>
56#include <cstddef>
57#include <numbers>
58#include <vector>
59
60// DSPARK_RESTRICT is normally provided by SimdOps.h (pulled in via AudioBuffer.h).
61// Guard against redefinition so this header stays self-contained if included alone.
62#ifndef DSPARK_RESTRICT
63 #if defined(__clang__) || defined(__GNUC__)
64 #define DSPARK_RESTRICT __restrict__
65 #elif defined(_MSC_VER)
66 #define DSPARK_RESTRICT __restrict
67 #else
68 #define DSPARK_RESTRICT
69 #endif
70#endif
71
72namespace dspark {
73
81template <typename T, int MaxChannels = 16>
83{
84public:
86 enum class MixRule {
88 Linear,
94 };
95
96 DryWetMixer() noexcept = default;
97
98 // The atomic mix rule makes the implicit move operations vanish. Provide
99 // manual moves so the mixer keeps working inside movable owners; moves
100 // are single-threaded setup-time relocations, so plain relaxed transfers
101 // of the atomic are sufficient. Copying is deleted by the owned buffers.
102 DryWetMixer(DryWetMixer&& other) noexcept
103 : dryBuffer_(std::move(other.dryBuffer_)),
104 capturedSamples_(other.capturedSamples_),
105 delayHist_(std::move(other.delayHist_)),
106 latencySamples_(other.latencySamples_),
107 histPos_(other.histPos_),
108 mixRule_(other.mixRule_.load(std::memory_order_relaxed)),
109 currentMix_(other.currentMix_),
110 maxMixStep_(other.maxMixStep_)
111 {}
112
114 {
115 if (this == &other) return *this;
116 dryBuffer_ = std::move(other.dryBuffer_);
117 capturedSamples_ = other.capturedSamples_;
118 delayHist_ = std::move(other.delayHist_);
119 latencySamples_ = other.latencySamples_;
120 histPos_ = other.histPos_;
121 mixRule_.store(other.mixRule_.load(std::memory_order_relaxed),
122 std::memory_order_relaxed);
123 currentMix_ = other.currentMix_;
124 maxMixStep_ = other.maxMixStep_;
125 return *this;
126 }
127
128 DryWetMixer(const DryWetMixer&) = delete;
130
135 void prepare(const AudioSpec& spec)
136 {
137 dryBuffer_.resize(spec.numChannels, spec.maxBlockSize);
138
139 // Mix changes ramp over at least kMinRampSeconds for a full-scale
140 // move, whatever the host block size (an invalid rate keeps the
141 // one-block ramp).
142 maxMixStep_ = spec.isValid()
143 ? static_cast<T>(1.0 / std::max(1.0, spec.sampleRate * kMinRampSeconds))
144 : T(1);
145
146 // If latency compensation was configured before prepare(), the delay
147 // history was sized with 0 channels; rebuild it now that the channel
148 // count is known (otherwise pushDry would index a 0-channel buffer).
149 if (latencySamples_ > 0)
150 {
151 delayHist_.resize(spec.numChannels, latencySamples_);
152 histPos_ = 0;
153 }
154
155 reset();
156 }
157
159 void reset() noexcept
160 {
161 dryBuffer_.clear();
162 if (delayHist_.getNumSamples() > 0) delayHist_.clear();
163 histPos_ = 0;
164 capturedSamples_ = 0; // No valid dry snapshot until the next pushDry().
165 currentMix_ = T(-1); // Forces immediate jump on first use
166 }
167
176 void setMixRule(MixRule rule) noexcept
177 {
178 const int r = static_cast<int>(rule);
179 mixRule_.store(r >= 0 && r <= 2 ? rule : MixRule::Linear, std::memory_order_relaxed);
180 }
181
183 [[nodiscard]] MixRule getMixRule() const noexcept { return mixRule_.load(std::memory_order_relaxed); }
184
197 void setLatencyCompensation(int samples)
198 {
199 samples = std::max(0, samples);
200 if (samples == latencySamples_) return;
201 latencySamples_ = samples;
202 delayHist_.resize(dryBuffer_.getNumChannels(), samples);
203 histPos_ = 0;
204 }
205
207 [[nodiscard]] int getLatencyCompensation() const noexcept { return latencySamples_; }
208
219 void pushDry(const AudioBufferView<const T>& input) noexcept
220 {
221 if (dryBuffer_.getNumSamples() == 0) return; // Prevent ops if unprepared
222
223 const int chCount = std::min(input.getNumChannels(), dryBuffer_.getNumChannels());
224 const int nSamples = std::min(input.getNumSamples(), dryBuffer_.getNumSamples());
225
226 if (latencySamples_ <= 0)
227 {
228 for (int ch = 0; ch < chCount; ++ch)
229 {
230 const T* DSPARK_RESTRICT src = input.getChannel(ch);
231 T* DSPARK_RESTRICT dst = dryBuffer_.getChannel(ch);
232 std::copy_n(src, nSamples, dst);
233 }
234 }
235 else
236 {
237 // Latency-compensated capture: route the dry through a per-channel
238 // circular delay of exactly latencySamples_ so it stays time-aligned
239 // with a wet path that incurs the same delay.
240 const int D = latencySamples_;
241 for (int ch = 0; ch < chCount; ++ch)
242 {
243 const T* DSPARK_RESTRICT src = input.getChannel(ch);
244 T* DSPARK_RESTRICT dst = dryBuffer_.getChannel(ch);
245 T* DSPARK_RESTRICT hist = delayHist_.getChannel(ch);
246 int pos = histPos_;
247 for (int i = 0; i < nSamples; ++i)
248 {
249 dst[i] = hist[pos]; // sample written D steps ago
250 hist[pos] = src[i];
251 if (++pos == D) pos = 0;
252 }
253 }
254 histPos_ = (histPos_ + nSamples) % D;
255 }
256
257 capturedSamples_ = nSamples;
258 }
259
278 void mixWet(AudioBufferView<T> wetBuffer, T targetMix) noexcept
279 {
280 // Handle invalid floating point inputs (NaN) safely
281 if (std::isnan(targetMix)) targetMix = T(0);
282 targetMix = std::clamp(targetMix, T(0), T(1));
283
284 const int chCount = std::min(wetBuffer.getNumChannels(), dryBuffer_.getNumChannels());
285 const int nSamples = std::min(wetBuffer.getNumSamples(), capturedSamples_);
286
287 if (nSamples == 0 || chCount == 0) return;
288
289 // Initialize smoothing state on first run
290 if (currentMix_ < T(0)) currentMix_ = targetMix;
291
292 const bool needsSmoothing = std::abs(currentMix_ - targetMix) > T(1e-5);
293 T mixStep = T(0);
294 bool rateLimited = false;
295 if (needsSmoothing)
296 {
297 mixStep = (targetMix - currentMix_) / T(nSamples);
298 if (std::abs(mixStep) > maxMixStep_)
299 {
300 mixStep = mixStep > T(0) ? maxMixStep_ : -maxMixStep_;
301 rateLimited = true;
302 }
303 }
304 const MixRule rule = mixRule_.load(std::memory_order_relaxed);
305
306 // Every channel ramps from the same smoothed origin. The ramps below
307 // are indexed (mix0 + mixStep * i) rather than accumulated: one
308 // rounding per sample instead of a drift that grows with the block
309 // (a serial accumulator can overshoot the [0, 1] range on long
310 // blocks), and no loop-carried dependency in the way of the
311 // auto-vectoriser. A settled mix within the 1e-5 dead band renders
312 // at the target itself, so no residual offset is ever held.
313 const T mix0 = needsSmoothing ? currentMix_ : targetMix;
314
315 for (int ch = 0; ch < chCount; ++ch)
316 {
317 T* DSPARK_RESTRICT wetData = wetBuffer.getChannel(ch);
318 const T* DSPARK_RESTRICT dryData = dryBuffer_.getChannel(ch);
319
320 if (rule == MixRule::EqualPower)
321 {
322 if (!needsSmoothing)
323 {
324 // Static mix: hoist both square roots out of the loop;
325 // the body becomes a single FMA per sample (vectorizable).
326 const T w = std::sqrt(mix0);
327 const T d = std::sqrt(T(1) - mix0);
328 for (int i = 0; i < nSamples; ++i)
329 wetData[i] = dryData[i] * d + wetData[i] * w;
330 }
331 else
332 {
333 for (int i = 0; i < nSamples; ++i)
334 {
335 // Exact constant-power law: w^2 + d^2 = 1. The max()
336 // guards keep float rounding at the ramp ends from
337 // pushing a radicand a few ulp negative, where sqrt()
338 // would inject NaN into the output.
339 const T m = mix0 + mixStep * T(i);
340 const T w = std::sqrt(std::max(T(0), m));
341 const T d = std::sqrt(std::max(T(0), T(1) - m));
342 wetData[i] = dryData[i] * d + wetData[i] * w;
343 }
344 }
345 }
346 else if (rule == MixRule::FullDryToHalf)
347 {
348 // dry min(1, 2 (1 - m)), wet min(1, 2 m).
349 for (int i = 0; i < nSamples; ++i)
350 {
351 const T m = needsSmoothing ? mix0 + mixStep * T(i) : mix0;
352 const T w = std::min(T(1), T(2) * m);
353 const T d = std::min(T(1), T(2) * (T(1) - m));
354 wetData[i] = dryData[i] * d + wetData[i] * w;
355 }
356 }
357 else // MixRule::Linear
358 {
359 if (!needsSmoothing)
360 {
361 const T w = mix0;
362 const T d = T(1) - w;
363 for (int i = 0; i < nSamples; ++i)
364 wetData[i] = dryData[i] * d + wetData[i] * w;
365 }
366 else
367 {
368 for (int i = 0; i < nSamples; ++i)
369 {
370 const T w = mix0 + mixStep * T(i);
371 const T d = T(1) - w;
372 wetData[i] = dryData[i] * d + wetData[i] * w;
373 }
374 }
375 }
376 }
377
378 // Update the persistent state after the block is processed: a
379 // rate-limited ramp resumes from where this block left it.
380 currentMix_ = rateLimited
381 ? std::clamp(mix0 + mixStep * T(nSamples), T(0), T(1))
382 : targetMix;
383 }
384
390 [[nodiscard]] const T* getDryChannel(int ch) const noexcept
391 {
392 if (ch < 0 || ch >= dryBuffer_.getNumChannels()) return nullptr;
393 return dryBuffer_.getChannel(ch);
394 }
395
397 [[nodiscard]] int getDryNumChannels() const noexcept { return dryBuffer_.getNumChannels(); }
398
400 [[nodiscard]] int getDryCapturedSamples() const noexcept { return capturedSamples_; }
401
402private:
404 int capturedSamples_ = 0;
405
406 // Optional dry-path latency compensation (circular delay). Disabled (0) by default.
408 int latencySamples_ = 0;
409 int histPos_ = 0;
410
411 std::atomic<MixRule> mixRule_ { MixRule::Linear };
412 T currentMix_ = T(-1); // Internal state for parameter smoothing
413 T maxMixStep_ = T(1); // Per-sample mix slew limit (set in prepare())
414
415 static constexpr double kMinRampSeconds = 0.02;
416};
417
418namespace detail {
419
439{
440public:
442 static constexpr double kButterworthShare = 0.8;
443
449 void prepare(double sampleRate, int channels)
450 {
451 sampleRate_ = sampleRate;
452 step_ = 1.0 / std::max(1.0, sampleRate * 0.02);
453 state_.assign(static_cast<std::size_t>(std::max(channels, 0)), {});
454 corner_ = -1.0;
455 }
456
458 void reset() noexcept { std::fill(state_.begin(), state_.end(), std::array<double, 2> {}); }
459
464 void setCorner(double hz) noexcept
465 {
466 if (hz == corner_) return;
467 corner_ = hz;
468 const double t = std::tan(std::numbers::pi * std::clamp(hz / sampleRate_, 0.0, 0.45));
469 pole_ = (1.0 - t) / (1.0 + t);
470 }
471
476 void aim(bool on) noexcept { target_ = on ? 1.0 : 0.0; }
477
479 void land() noexcept { amount_ = target_; }
480
482 [[nodiscard]] double advance() noexcept
483 {
484 if (amount_ != target_)
485 amount_ = (amount_ < target_) ? std::min(target_, amount_ + step_) : std::max(target_, amount_ - step_);
486 return amount_;
487 }
488
495 template <typename T>
496 [[nodiscard]] T processSample(int channel, T x, double amount) noexcept
497 {
498 if (channel < 0 || static_cast<std::size_t>(channel) >= state_.size()) return x;
499 auto& s = state_[static_cast<std::size_t>(channel)];
500 const double in = static_cast<double>(x);
501 double y = pole_ * (in + s[1]) - s[0];
502 if (!std::isfinite(y))
503 {
504 s = {};
505 return x;
506 }
507 if (std::abs(y) < 1e-30) y = 0.0;
508 s[0] = in;
509 s[1] = y;
510 if (amount == 0.0) return x;
511 return static_cast<T>(amount == 1.0 ? y : in + amount * (y - in));
512 }
513
518 template <typename T>
519 void process(AudioBufferView<T> buffer) noexcept
520 {
521 const int channels = std::min(buffer.getNumChannels(), static_cast<int>(state_.size()));
522 const int samples = buffer.getNumSamples();
523 for (int i = 0; i < samples; ++i)
524 {
525 const double amount = advance();
526 for (int ch = 0; ch < channels; ++ch)
527 {
528 T* data = buffer.getChannel(ch);
529 data[i] = processSample(ch, data[i], amount);
530 }
531 }
532 }
533
534private:
535 std::vector<std::array<double, 2>> state_;
536 double sampleRate_ = 48000.0, step_ = 1.0 / 960.0;
537 double corner_ = -1.0, pole_ = 0.0;
538 double amount_ = 0.0, target_ = 0.0;
539};
540
541} // namespace detail
542
543} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
Owning audio buffer with contiguous, 32-byte aligned storage.
int getNumChannels() const noexcept
Returns the number of active channels.
T * getChannel(int ch) noexcept
Returns a pointer to the sample data.
int getNumSamples() const noexcept
Returns the number of samples per channel.
void resize(int numChannels, int numSamples)
Allocates the buffer for the given dimensions.
void clear() noexcept
Clears all channels, including SIMD alignment padding. Ensures any SIMD over-read will consume pure z...
Pre-allocated, SIMD-friendly dry/wet blender for real-time audio.
Definition DryWetMixer.h:83
void setLatencyCompensation(int samples)
Delays the captured dry signal to compensate for an effect's internal latency (e.g....
int getLatencyCompensation() const noexcept
Returns the configured dry-path latency compensation in samples.
MixRule
Defines the mathematical curve used for mixing.
Definition DryWetMixer.h:86
int getDryCapturedSamples() const noexcept
Returns the number of samples valid from the last pushDry() call.
void mixWet(AudioBufferView< T > wetBuffer, T targetMix) noexcept
Blends the stored dry signal with the current (wet) buffer in-place.
void reset() noexcept
Resets the internal buffer and smoothing states to zero.
int getDryNumChannels() const noexcept
Returns the internal capacity of channels in the dry buffer.
DryWetMixer() noexcept=default
MixRule getMixRule() const noexcept
DryWetMixer & operator=(DryWetMixer &&other) noexcept
void pushDry(const AudioBufferView< const T > &input) noexcept
Captures a snapshot of the dry (unprocessed) signal.
void setMixRule(MixRule rule) noexcept
Sets the mathematical curve to use during the mix phase.
void prepare(const AudioSpec &spec)
Allocates the internal dry buffer for the given audio spec.
DryWetMixer & operator=(const DryWetMixer &)=delete
const T * getDryChannel(int ch) const noexcept
Retrieves a read-only pointer to the captured dry channel data.
DryWetMixer(const DryWetMixer &)=delete
Gives the dry side of a mix the phase that a high-pass leaves in the wet side, and none of its magnit...
void reset() noexcept
Clears the memory (the amount stays).
T processSample(int channel, T x, double amount) noexcept
A sample of a channel, with the amount that advance() returned.
void process(AudioBufferView< T > buffer) noexcept
A stretch of a buffer, in place.
void prepare(double sampleRate, int channels)
Sizes the state (allocates).
void aim(bool on) noexcept
Where the amount goes.
double advance() noexcept
Moves the amount by a frame and returns it.
void land() noexcept
Puts the amount where it goes, without the fade.
void setCorner(double hz) noexcept
Moves the corner (a tangent, when it changes).
static constexpr double kButterworthShare
Main namespace for the DSPark framework.
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37
constexpr bool isValid() const noexcept
Checks if the specification contains valid, processable parameters.
Definition AudioSpec.h:71
int numChannels
Number of audio channels (e.g., 1 = mono, 2 = stereo).
Definition AudioSpec.h:58
int maxBlockSize
Maximum number of samples per processing block.
Definition AudioSpec.h:53
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45