DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
StereoGenerator.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
9#include "../Core/AudioBuffer.h"
10#include "../Core/AudioSpec.h"
11#include "../Core/Convolver.h"
12#include "../Core/DenormalGuard.h"
13#include "../Core/DryWetMixer.h"
14#include "../Core/FIRFilter.h"
15#include "../Core/SmoothedValue.h"
16#include "../Core/StateBlob.h"
17#include "../Core/detail/StereoColor.h"
18#include "../Core/detail/TptSvf.h"
19#include <algorithm>
20#include <array>
21#include <atomic>
22#include <cmath>
23#include <cstdint>
24#include <limits>
25#include <memory>
26#include <span>
27#include <type_traits>
28#include <vector>
29
30namespace dspark
31{
64template <typename T> class StereoGenerator final
65{
66 static_assert(std::is_same_v<T, float> || std::is_same_v<T, double>);
67 static_assert(std::atomic<float>::is_always_lock_free && std::atomic<int>::is_always_lock_free);
68
69 public:
71 struct Options
72 {
73 int oversampling = 1;
74 float lowCutHz = 0;
75 bool operator==(const Options &) const noexcept = default;
76 };
77
79 enum class Status
80 {
81 Ok,
86 };
87
88 StereoGenerator() = default;
91
96 [[nodiscard]] static std::size_t getPrepareMemoryBound(const AudioSpec &spec,
97 Options options) noexcept
98 {
99 if (!validConfiguration(spec, options))
100 return 0;
102 const int source = State::sourceFactor(spec.sampleRate);
103 const int colorLatency = Color::latencyFor(options.oversampling, source);
104 const auto hp = highPassLayout(spec.sampleRate, options.lowCutHz);
105 const int totalLatency = colorLatency + hp.order / 2 + hp.block;
106 const auto buffer = [](std::size_t channels, std::size_t frames, std::size_t bytes) {
107 return channels * ((frames * bytes + 31) / 32 * 32) + 64;
108 };
109 auto bytes = sizeof(State) + 64 + 2 * Color::allocationBound(options.oversampling, source) +
110 buffer(2, 256, sizeof(double)) + buffer(1, 256, sizeof(double)) +
111 buffer(1, 256, sizeof(double)) + buffer(1, colorLatency, sizeof(double)) +
112 buffer(2, 256, sizeof(T)) + buffer(2, totalLatency, sizeof(T));
113 if (hp.block)
114 bytes += 3 * ((static_cast<std::size_t>(hp.order) + 1) * sizeof(double) + 64) +
116 return bytes;
117 }
118
123 bool prepare(const AudioSpec &spec)
124 {
125 return prepare(spec, options_);
126 }
127
129 bool prepare(const AudioSpec &spec, Options options)
130 {
131 if (!validConfiguration(spec, options))
132 return false;
133 auto next = std::make_unique<State>(spec, options, getWidth());
134 state_ = std::move(next);
135 options_ = options;
136 latency_.store(state_->latency, std::memory_order_relaxed);
137 publish(Status::Ok);
138 return true;
139 }
140
142 bool setWidth(float width) noexcept
143 {
144 if (!std::isfinite(width) || width < 0 || width > 1)
145 return false;
146 width_.store(width, std::memory_order_relaxed);
147 return true;
148 }
150 [[nodiscard]] float getWidth() const noexcept
151 {
152 return width_.load(std::memory_order_relaxed);
153 }
155 [[nodiscard]] Options getOptions() const noexcept
156 {
157 return options_;
158 }
160 [[nodiscard]] int getLatency() const noexcept
161 {
162 return latency_.load(std::memory_order_relaxed);
163 }
165 [[nodiscard]] Status getStatus() const noexcept
166 {
167 return static_cast<Status>(status_.load(std::memory_order_relaxed));
168 }
170 [[nodiscard]] std::uint64_t getSourceFrame() const noexcept
171 {
172 return state_ ? state_->frame : 0;
173 }
175 void reset() noexcept
176 {
177 resetAtFrame(0);
178 }
179
185 void resetAtFrame(std::uint64_t frame) noexcept
186 {
187 if (!state_)
188 return;
189 state_->reset(frame, getWidth());
190 publish(Status::Ok);
191 }
192
200 bool processBlock(AudioBufferView<T> buffer) noexcept
201 {
202 return processBlock(buffer, {});
203 }
204
212 bool processBlock(AudioBufferView<T> buffer, std::span<double> generatedDelta) noexcept
213 {
214 DenormalGuard denormalGuard;
215 if (!state_)
216 return publish(Status::NotPrepared);
217 const int count = buffer.getNumSamples();
218 if (buffer.getNumChannels() != 2 || count > state_->spec.maxBlockSize ||
219 (!generatedDelta.empty() && generatedDelta.size() != static_cast<std::size_t>(count)))
220 return publish(Status::InvalidInput);
221 if (static_cast<std::uint64_t>(count) >
222 std::numeric_limits<std::uint64_t>::max() - state_->frame)
223 return publish(Status::ClockOverflow);
224 if (count == 0)
225 return publish(state_->fault ? Status::NumericalFailure : Status::Ok);
226 auto *left = buffer.getChannel(0);
227 auto *right = buffer.getChannel(1);
228 if (!left || !right)
229 return publish(Status::InvalidInput);
230 if (!generatedDelta.empty() &&
231 (!generatedDelta.data() ||
232 overlaps(generatedDelta.data(),
233 static_cast<std::uint64_t>(generatedDelta.size()) * sizeof(double), left,
234 static_cast<std::uint64_t>(count) * sizeof(T)) ||
235 overlaps(generatedDelta.data(),
236 static_cast<std::uint64_t>(generatedDelta.size()) * sizeof(double), right,
237 static_cast<std::uint64_t>(count) * sizeof(T))))
238 return publish(Status::InvalidInput);
239 const auto a = reinterpret_cast<std::uintptr_t>(left);
240 const auto b = reinterpret_cast<std::uintptr_t>(right);
241 if (static_cast<std::uint64_t>(a > b ? a - b : b - a) <
242 static_cast<std::uint64_t>(count) * sizeof(T))
243 return publish(Status::InvalidInput);
244 for (int i = 0; i < count; ++i)
245 if (!std::isfinite(left[i]) || !std::isfinite(right[i]))
246 return publish(Status::InvalidInput);
247 state_->width.setTargetValue(getWidth());
248 for (int offset = 0; offset < count;)
249 {
250 const int size = std::min(256, count - offset);
251 state_->process(buffer.getSubView(offset, size),
252 generatedDelta.empty()
253 ? std::span<double>{}
254 : generatedDelta.subspan(static_cast<std::size_t>(offset),
255 static_cast<std::size_t>(size)));
256 offset += size;
257 }
258 return publish(state_->fault ? Status::NumericalFailure : Status::Ok);
259 }
260
262 [[nodiscard]] std::vector<std::uint8_t> getState() const
263 {
264 StateWriter writer(stateId("STGN"), 1);
265 writer.write("width", getWidth());
266 writer.write("oversampling", static_cast<std::int32_t>(options_.oversampling));
267 writer.write("lowCutHz", options_.lowCutHz);
268 return writer.blob();
269 }
270
275 bool setState(const std::uint8_t *data, std::size_t size)
276 {
277 StateReader reader(data, size);
278 if (!reader.isValid() || reader.processorId() != stateId("STGN") ||
279 reader.processorVersion() != 1)
280 return false;
281 std::array<bool, 3> seen{};
282 for (const auto &entry : reader.entries())
283 {
284 const int index = entry.key == "width" ? 0
285 : entry.key == "oversampling" ? 1
286 : entry.key == "lowCutHz" ? 2
287 : -1;
288 if (index < 0)
289 continue;
290 if (seen[index] || entry.type != (index == 1 ? 1 : 0))
291 return false;
292 seen[index] = true;
293 }
294 const float width = reader.read("width", getWidth());
295 const Options options{reader.read("oversampling", options_.oversampling),
296 reader.read("lowCutHz", options_.lowCutHz)};
297 if (!std::isfinite(width) || width < 0 || width > 1 || !validOptions(options))
298 return false;
299 options_ = options;
300 width_.store(width, std::memory_order_relaxed);
301 return true;
302 }
303
304 private:
305 struct HighPassLayout
306 {
307 int order = 0, block = 0;
308 bool allReject = false;
309 };
310 static HighPassLayout highPassLayout(double rate, double lowCut) noexcept
311 {
312 HighPassLayout result;
313 if (lowCut <= 0)
314 return result;
315 const double transition =
316 std::min(std::max(50., lowCut * .25), std::min(lowCut * 1.5, rate - 2 * lowCut));
317 if (lowCut >= rate * .5 || transition < 30)
318 result.allReject = true;
319 else
320 {
321 result.order =
322 static_cast<int>(std::ceil(94 / (2.285 * twoPi<double> * transition / rate)));
323 if (result.order & 1)
324 ++result.order;
325 result.block = 1;
326 while (result.block * 2 <= std::max(64, static_cast<int>(std::round(rate / 93.75))))
327 result.block *= 2;
328 }
329 return result;
330 }
331 static bool overlaps(const void *left, std::uint64_t leftBytes, const void *right,
332 std::uint64_t rightBytes) noexcept
333 {
334 const auto a = reinterpret_cast<std::uintptr_t>(left);
335 const auto b = reinterpret_cast<std::uintptr_t>(right);
336 return a <= b ? b - a < leftBytes : a - b < rightBytes;
337 }
338 struct Band
339 {
340 detail::TptSvfState<double> state{};
341 int index;
342 double rate, base, corridor, g = 0, gain = 0, dg = 0, dGain = 0;
343 int untilUpdate = 0;
344
345 void prepare(int i, double fs) noexcept
346 {
347 index = i;
348 rate = fs;
349 const double first = i < 16 ? 210 : 45;
350 const double last = i < 16 ? std::min(14000., fs * .35) : 165;
351 corridor = std::log(last / first) / (i < 16 ? 15 : 3);
352 base = first * std::exp((i < 16 ? i : i - 16) * corridor);
353 }
354 double coefficient(double t) const noexcept
355 {
356 const double f =
357 base *
358 std::exp(.22 * corridor *
359 std::sin(twoPi<double> * (.029 + index * .0017) * t + index * 2.399963));
360 return std::tan(pi<double> * f / rate);
361 }
362 double amplitude(double t) const noexcept
363 {
364 const double db = (((index / 2 + index % 2) & 1) == 0 ? 1 : -1) *
365 (2.6 + .4 * std::sin(twoPi<double> * (.037 + index * .0013) * t +
366 index * 1.618034));
367 return std::expm1(db * std::log(10.) / 20);
368 }
369 void position(std::uint64_t frame) noexcept
370 {
371 const auto offset = static_cast<int>(frame % 64);
372 const double t = static_cast<double>(frame - offset) / rate;
373 const double future = t + 64. / rate;
374 g = coefficient(t);
375 gain = amplitude(t);
376 dg = (coefficient(future) - g) / 64;
377 dGain = (amplitude(future) - gain) / 64;
378 for (int i = 0; i < offset; ++i)
379 {
380 g += dg;
381 gain += dGain;
382 }
383 untilUpdate = 64 - offset;
384 }
385 double process(double input, std::uint64_t frame) noexcept
386 {
387 if (untilUpdate == 0)
388 position(frame);
389 const double a1 = 1 / (1 + g * (g + .5));
390 const double a2 = g * a1;
391 const double a3 = g * a2;
392 const double y = gain * .5 * detail::tptSvfStep(input, state, a1, a2, a3).bandpass;
393 g += dg;
394 gain += dGain;
395 --untilUpdate;
396 return y;
397 }
398 };
399
400 struct State
401 {
402 AudioSpec spec;
403 std::array<Band, 20> bands{};
404 AudioBuffer<double> copy, delta;
405 DryWetMixer<T, 2> dry;
406 DryWetMixer<double, 1> linear;
407 Convolver<double> highPass;
408 detail::StereoColor<detail::ClipperCurve::AsymmetricKnee> tube;
409 detail::StereoColor<detail::ClipperCurve::SymmetricKnee> tape;
410 SmoothedValue<double> width;
411 std::uint64_t frame = 0;
412 int latency;
413 bool useHighPass = false, allReject = false, fault = false;
414
415 State(AudioSpec environment, Options options, float initialWidth)
416 : spec(environment), tube(options.oversampling, sourceFactor(spec.sampleRate)),
417 tape(options.oversampling, sourceFactor(spec.sampleRate)), latency(tube.latency())
418 {
419 for (int i = 0; i < 20; ++i)
420 bands[i].prepare(i, spec.sampleRate);
421 copy.resize(2, 256);
422 delta.resize(1, 256);
423 linear.prepare({spec.sampleRate, 256, 1});
424 linear.setLatencyCompensation(tube.latency());
425 const auto hp = highPassLayout(spec.sampleRate, options.lowCutHz);
426 allReject = hp.allReject;
427 if (hp.block)
428 {
429 const auto taps = FIRDesign<double>::highPass(spec.sampleRate, options.lowCutHz,
430 hp.order + 1, 10.2);
431 highPass.prepare(hp.block, taps.data(), static_cast<int>(taps.size()));
432 latency += hp.order / 2 + hp.block;
433 useHighPass = true;
434 }
435 dry.prepare({spec.sampleRate, 256, 2});
436 dry.setLatencyCompensation(latency);
437 width.prepare(spec.sampleRate, 5);
438 width.setSmoothingType(SmoothedValue<double>::SmoothingType::Linear);
439 reset(0, initialWidth);
440 }
441 static int sourceFactor(double rate) noexcept
442 {
443 return rate <= 48000 ? 8 : rate <= 96000 ? 4 : rate <= 192000 ? 2 : 1;
444 }
445 void reset(std::uint64_t position, float targetWidth) noexcept
446 {
447 frame = position;
448 for (auto &band : bands)
449 {
450 band.state = {};
451 band.position(position);
452 }
453 tube.reset();
454 tape.reset();
455 highPass.reset();
456 dry.reset();
457 linear.reset();
458 width.reset(targetWidth);
459 fault = false;
460 }
461 void process(AudioBufferView<T> input, std::span<double> generatedDelta) noexcept
462 {
463 const int count = input.getNumSamples();
464 dry.pushDry(input);
465 double *l = copy.getChannel(0), *r = copy.getChannel(1), *d = delta.getChannel(0);
466 if (!fault)
467 {
468 for (int i = 0; i < count; ++i)
469 {
470 l[i] = r[i] = 0;
471 for (int j = 0; j < 20; ++j)
472 (j & 1 ? r[i] : l[i]) +=
473 bands[j].process(input.getChannel(j & 1)[i], frame + i);
474 d[i] = .5 * (l[i] - r[i]);
475 if (!std::isfinite(l[i]) || !std::isfinite(r[i]) || !std::isfinite(d[i]))
476 fault = true;
477 }
478 if (!fault)
479 {
480 linear.pushDry(delta.toView().getSubView(0, count));
481 double *lc[]{l}, *rc[]{r};
482 tube.process({lc, 1, count});
483 tape.process({rc, 1, count});
484 const auto *aligned = linear.getDryChannel(0);
485 for (int i = 0; i < count; ++i)
486 d[i] = aligned[i] + .1 * (.5 * (l[i] - r[i]) - aligned[i]);
487 if (useHighPass)
488 highPass.processInPlace(d, count);
489 for (int i = 0; i < count; ++i)
490 if (!std::isfinite(d[i]))
491 fault = true;
492 if (allReject)
493 std::fill_n(d, count, 0.);
494 }
495 }
496 const auto *dl = dry.getDryChannel(0), *dr = dry.getDryChannel(1);
497 std::array<double, 256> changes{};
498 for (int i = 0; i < count; ++i)
499 {
500 const double w = width.getNextValue();
501 const double change = fault || w == 0 ? 0 : 8 * w * d[i];
502 const double outL = static_cast<double>(dl[i]) + change;
503 const double outR = static_cast<double>(dr[i]) - change;
504 if (!std::isfinite(outL) || !std::isfinite(outR) ||
505 std::abs(outL) > std::numeric_limits<T>::max() ||
506 std::abs(outR) > std::numeric_limits<T>::max())
507 fault = true;
508 changes[i] = change;
509 }
510 for (int i = 0; i < count; ++i)
511 {
512 if (!generatedDelta.empty())
513 generatedDelta[i] = fault ? 0 : changes[i];
514 // Assignment preserves signed zero and exact dry PCM at zero width.
515 input.getChannel(0)[i] =
516 fault || changes[i] == 0 ? dl[i] : static_cast<T>(dl[i] + changes[i]);
517 input.getChannel(1)[i] =
518 fault || changes[i] == 0 ? dr[i] : static_cast<T>(dr[i] - changes[i]);
519 }
520 frame += static_cast<std::uint64_t>(count);
521 }
522 };
523
524 static bool validConfiguration(const AudioSpec &spec, Options options) noexcept
525 {
526 return spec.isValid() && spec.numChannels == 2 && (spec.sampleRate >= 8000) &&
527 (spec.sampleRate <= 384000) && validOptions(options);
528 }
529 static bool validOptions(Options options) noexcept
530 {
531 return options.oversampling >= 1 && options.oversampling <= 16 &&
532 (options.oversampling & (options.oversampling - 1)) == 0 &&
533 std::isfinite(options.lowCutHz) &&
534 (options.lowCutHz == 0 || (options.lowCutHz >= 20 && options.lowCutHz <= 5000));
535 }
536 bool publish(Status status) noexcept
537 {
538 status_.store(static_cast<int>(status), std::memory_order_relaxed);
539 return status == Status::Ok;
540 }
541 std::unique_ptr<State> state_;
542 Options options_;
543 std::atomic<float> width_{0};
544 std::atomic<int> status_{static_cast<int>(Status::NotPrepared)}, latency_{0};
545};
546} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
static std::vector< T > highPass(double sampleRate, double cutoffHz, int numTaps, T beta=T(5))
Designs a high-pass FIR filter.
Definition FIRFilter.h:108
Tolerant reader: missing keys yield defaults, unknown keys are skipped.
Definition StateBlob.h:171
uint16_t processorVersion() const noexcept
Definition StateBlob.h:211
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
const std::vector< Entry > & entries() const noexcept
Definition StateBlob.h:257
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
A stereo generator that preserves the delayed original mid signal.
StereoGenerator(const StereoGenerator &)=delete
Status
Result of the last processing call (also readable by a UI).
Status getStatus() const noexcept
Returns the last processing status. Numerical failure latches until reset.
bool prepare(const AudioSpec &spec, Options options)
Prepares explicit options; on success clears all stream history.
void reset() noexcept
Clears history and restarts modulation at source frame zero.
bool setState(const std::uint8_t *data, std::size_t size)
Restores a validated preset. Factor/low cut apply at the next prepare. Missing keys retain their sett...
int getLatency() const noexcept
Exact active delay in source frames, including the optional FIR.
bool prepare(const AudioSpec &spec)
Prepares pending options for stereo at 8 to 384 kHz. Invalid settings return false,...
std::vector< std::uint8_t > getState() const
Serializes parameters only; filter history and source clock are excluded.
bool processBlock(AudioBufferView< T > buffer, std::span< double > generatedDelta) noexcept
Also captures the generated mono delta before rounded L/R add-back. An empty span disables capture....
bool setWidth(float width) noexcept
Publishes width in [0,1]. Invalid values return false unchanged.
float getWidth() const noexcept
Returns the published target, not the instantaneous ramp value.
Options getOptions() const noexcept
Returns options for the next prepare (including restored presets).
std::uint64_t getSourceFrame() const noexcept
Returns the next input frame on this stream's source clock.
static std::size_t getPrepareMemoryBound(const AudioSpec &spec, Options options) noexcept
Conservative cumulative setup allocation bound, or zero for invalid settings. Includes state,...
bool processBlock(AudioBufferView< T > buffer) noexcept
Processes writable, nonoverlapping stereo channels in place. Returns false without changing input or ...
void resetAtFrame(std::uint64_t frame) noexcept
Clears history and aligns modulation to an absolute source frame. This is not a seek restore: replay ...
StereoGenerator & operator=(const StereoGenerator &)=delete
static std::size_t convolutionAllocationBound(std::size_t block, std::size_t length) noexcept
TptSvfOutput< T > tptSvfStep(T input, TptSvfState< T > &state, T a1, T a2, T a3) noexcept
Advances the expanded Simper TPT recurrence by one sample.
Definition TptSvf.h:43
constexpr void copy(char *dst, std::string_view src, std::size_t dstCapacity) noexcept
Safe small string copy used only for compile-time-friendly name building.
Main namespace for the DSPark framework.
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
Configuration applied by prepare(), never by the audio callback.
int oversampling
Local color-branch factor: 1, 2, 4, 8 or 16.
bool operator==(const Options &) const noexcept=default
float lowCutHz
Generated delta only: off, or 20 to 5000 Hz.