DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
LoFi.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
46#include "GranularProcessor.h"
47#include "../Core/AudioBuffer.h"
48#include "../Core/AudioSpec.h"
49#include "../Core/BiquadCascade.h"
50#include "../Core/DspMath.h"
51#include "../Core/FilterDesign.h"
52#include "../Core/StateBlob.h"
53
54#include <algorithm>
55#include <array>
56#include <atomic>
57#include <cmath>
58#include <cstddef>
59#include <cstdint>
60#include <memory>
61#include <numbers>
62#include <vector>
63
64namespace dspark {
65
71template <FloatType T>
72class LoFi
73{
74public:
75 static constexpr int kMaxChannels = 16;
76
77 LoFi() : grains_(std::make_unique<GranularProcessor<T>>()) {}
78
80 void prepare(const AudioSpec& spec)
81 {
82 if (!spec.isValid()) return;
83 prepared_ = false;
84 spec_ = spec;
85 grains_->setGrainSize(T(30));
86 grains_->setDensity(T(60));
87 grains_->setSpread(T(0));
88 grains_->setPitchJitter(T(0));
89 grains_->setMix(T(1));
90 grains_->prepare(spec, 1.0);
91 if (!filter_) filter_ = std::make_unique<Filter>();
92 filter_->setNumSections(kFilterSections);
93 fit_.prepare(spec.sampleRate);
94 rampStep_ = 1.0 / std::max(1.0, 0.02 * spec.sampleRate);
95 dry_.resize(std::min(spec.numChannels, kMaxChannels), spec.maxBlockSize);
96 prepared_ = true;
97 reset();
98 }
99
101 void reset() noexcept
102 {
103 if (!prepared_) return;
104 grains_->reset();
105 filter_->reset();
106 designedRate_ = -1.0;
107 held_.fill(T(0));
108 phase_ = 1.0;
109 mixNow_ = static_cast<double>(mix_.load(std::memory_order_relaxed));
110 outputNow_ = std::pow(10.0, static_cast<double>(outputDb_.load(std::memory_order_relaxed)) / 20.0);
111 foldNow_ = foldGainFor(static_cast<double>(foldDb_.load(std::memory_order_relaxed)));
112 foldScaleNow_ = foldScaleFor(foldNow_);
113 rng_ = 0x9E3779B9u;
114 }
115
117 void processBlock(AudioBufferView<T> buffer) noexcept
118 {
119 if (!prepared_) return;
120 const int nS = buffer.getNumSamples();
121 const int maxBlock = dry_.getNumSamples();
122 for (int off = 0; off < nS; off += maxBlock)
123 processChunk(buffer.getSubView(off, std::min(maxBlock, nS - off)));
124 }
125
126 // -- Settings (any thread) ---------------------------------------------------
127
129 void setSmear(T amount) noexcept { store(smear_, amount, T(0), T(1)); }
131 void setPitch(T semitones) noexcept { store(pitch_, semitones, T(-24), T(12)); }
133 void setFold(T dB) noexcept { store(foldDb_, dB, T(0), T(36)); }
135 void setRate(T hz) noexcept
136 {
137 if (!std::isfinite(hz)) return;
138 rate_.store(std::max(hz, T(100)), std::memory_order_relaxed);
139 }
141 void setRateFilter(bool on) noexcept { rateFilter_.store(on, std::memory_order_relaxed); }
143 void setBits(T bits) noexcept { store(bits_, bits, T(1), T(24)); }
145 void setDither(bool on) noexcept { dither_.store(on, std::memory_order_relaxed); }
147 void setMix(T mix) noexcept { store(mix_, mix, T(0), T(1)); }
149 void setOutput(T dB) noexcept { store(outputDb_, dB, T(-24), T(12)); }
150
151 [[nodiscard]] T getSmear() const noexcept { return smear_.load(std::memory_order_relaxed); }
152 [[nodiscard]] T getPitch() const noexcept { return pitch_.load(std::memory_order_relaxed); }
153 [[nodiscard]] T getFold() const noexcept { return foldDb_.load(std::memory_order_relaxed); }
154 [[nodiscard]] T getRate() const noexcept { return rate_.load(std::memory_order_relaxed); }
155 [[nodiscard]] bool isRateFilter() const noexcept { return rateFilter_.load(std::memory_order_relaxed); }
156 [[nodiscard]] T getBits() const noexcept { return bits_.load(std::memory_order_relaxed); }
157 [[nodiscard]] bool isDither() const noexcept { return dither_.load(std::memory_order_relaxed); }
158 [[nodiscard]] T getMix() const noexcept { return mix_.load(std::memory_order_relaxed); }
159 [[nodiscard]] T getOutput() const noexcept { return outputDb_.load(std::memory_order_relaxed); }
160
162 [[nodiscard]] static constexpr int getLatency() noexcept { return 0; }
163
165 [[nodiscard]] std::vector<uint8_t> getState() const
166 {
167 StateWriter w(stateId("LOFI"), 1);
168 w.write("smear", static_cast<float>(getSmear()));
169 w.write("pitch", static_cast<float>(getPitch()));
170 w.write("fold", static_cast<float>(getFold()));
171 w.write("rate", static_cast<float>(getRate()));
172 w.write("rateFilter", isRateFilter());
173 w.write("bits", static_cast<float>(getBits()));
174 w.write("dither", isDither());
175 w.write("mix", static_cast<float>(getMix()));
176 w.write("output", static_cast<float>(getOutput()));
177 return w.blob();
178 }
179
181 bool setState(const uint8_t* data, size_t size)
182 {
183 StateReader r(data, size);
184 if (!r.isValid() || r.processorId() != stateId("LOFI")) return false;
185 setSmear(static_cast<T>(r.read("smear", 0.0f)));
186 setPitch(static_cast<T>(r.read("pitch", 0.0f)));
187 setFold(static_cast<T>(r.read("fold", 0.0f)));
188 setRate(static_cast<T>(r.read("rate", 1e9f)));
189 setRateFilter(r.read("rateFilter", false));
190 setBits(static_cast<T>(r.read("bits", 24.0f)));
191 setDither(r.read("dither", false));
192 setMix(static_cast<T>(r.read("mix", 1.0f)));
193 setOutput(static_cast<T>(r.read("output", 0.0f)));
194 return true;
195 }
196
197private:
198 static constexpr int kFilterSections = 4;
200
201 static void store(std::atomic<T>& field, T value, T lo, T hi) noexcept
202 {
203 if (std::isfinite(value)) field.store(std::clamp(value, lo, hi), std::memory_order_relaxed);
204 }
205
207 [[nodiscard]] static double foldGainFor(double dB) noexcept
208 {
209 return dB > 0.0 ? 0.5 * std::numbers::pi * std::pow(10.0, dB / 20.0) : 0.0;
210 }
211
218 [[nodiscard]] static double foldScaleFor(double g) noexcept
219 {
220 if (g <= 0.0) return 1.0;
221 constexpr double a = 0.25;
222 constexpr int n = 256;
223 double sum = 0.0;
224 for (int i = 0; i < n; ++i)
225 {
226 const double s = std::sin(g * a * std::sin(2.0 * std::numbers::pi * i / n));
227 sum += s * s;
228 }
229 const double out = sum / n;
230 return out > 1e-12 ? std::sqrt(0.5 * a * a / out) : 1.0;
231 }
232
234 [[nodiscard]] double triangular() noexcept
235 {
236 const auto uniform = [this]() noexcept {
237 rng_ ^= rng_ << 13;
238 rng_ ^= rng_ >> 17;
239 rng_ ^= rng_ << 5;
240 return static_cast<double>(rng_) * (1.0 / 4294967296.0);
241 };
242 return uniform() - uniform();
243 }
244
245 void processChunk(AudioBufferView<T> buffer) noexcept
246 {
247 const int nCh = std::min(buffer.getNumChannels(), kMaxChannels);
248 const int nS = std::min(buffer.getNumSamples(), dry_.getNumSamples());
249 if (nCh <= 0 || nS <= 0) return;
250 const int dryCh = std::min(nCh, dry_.getNumChannels());
251
252 const double mixTarget = static_cast<double>(mix_.load(std::memory_order_relaxed));
253 const double outputTarget = std::pow(10.0, static_cast<double>(outputDb_.load(std::memory_order_relaxed)) / 20.0);
254 const bool mixing = mixTarget < 1.0 || mixNow_ < 1.0;
255 if (mixing)
256 for (int ch = 0; ch < dryCh; ++ch)
257 std::copy_n(buffer.getChannel(ch), nS, dry_.getChannel(ch));
258
259 // Grains.
260 const T smear = smear_.load(std::memory_order_relaxed);
261 const T pitch = pitch_.load(std::memory_order_relaxed);
262 const bool grains = smear > T(0) || pitch != T(0);
263 if (grains)
264 {
265 if (!grainsOn_) grains_->reset();
266 grains_->setJitter(smear);
267 grains_->setPitch(pitch);
268 grains_->processBlock(buffer.getSubView(0, nS));
269 }
270 grainsOn_ = grains;
271
272 // Fold, with the gain and its scale on a ramp across the block.
273 const double foldTarget = foldGainFor(static_cast<double>(foldDb_.load(std::memory_order_relaxed)));
274 if (foldTarget > 0.0 || foldNow_ > 0.0)
275 {
276 const double scaleTarget = (foldTarget != foldNow_) ? foldScaleFor(foldTarget) : foldScaleNow_;
277 const double gStep = (foldTarget - foldNow_) / nS, sStep = (scaleTarget - foldScaleNow_) / nS;
278 for (int ch = 0; ch < nCh; ++ch)
279 {
280 T* x = buffer.getChannel(ch);
281 for (int i = 0; i < nS; ++i)
282 {
283 const double g = foldNow_ + gStep * (i + 1), s = foldScaleNow_ + sStep * (i + 1);
284 x[i] = static_cast<T>(g > 0.0 ? std::sin(g * static_cast<double>(x[i])) * s : static_cast<double>(x[i]));
285 }
286 }
287 foldNow_ = foldTarget;
288 foldScaleNow_ = scaleTarget;
289 }
290
291 // Rate: a held sample, with the low-pass in front when asked.
292 const double rate = static_cast<double>(rate_.load(std::memory_order_relaxed));
293 if (rate < spec_.sampleRate)
294 {
295 if (rateFilter_.load(std::memory_order_relaxed))
296 {
297 if (rate != designedRate_)
298 {
299 BiquadCoeffs sections[kFilterSections];
300 const int count = FilterDesign::digital(FilterDesign::highCut(std::min(0.45 * rate, 0.45 * spec_.sampleRate), 48.0),
301 fit_, sections, kFilterSections);
302 for (int s = 0; s < kFilterSections; ++s)
303 filter_->setCoeffs(s, s < count ? sections[s] : BiquadCoeffs {});
304 designedRate_ = rate;
305 }
306 filter_->processBlock(buffer.getSubView(0, nS));
307 }
308 const double step = rate / spec_.sampleRate;
309 for (int i = 0; i < nS; ++i)
310 {
311 phase_ += step;
312 const bool tick = phase_ >= 1.0;
313 if (tick) phase_ -= std::floor(phase_);
314 for (int ch = 0; ch < nCh; ++ch)
315 {
316 T& x = buffer.getChannel(ch)[i];
317 if (tick) held_[static_cast<size_t>(ch)] = x;
318 x = held_[static_cast<size_t>(ch)];
319 }
320 }
321 }
322
323 // Bits.
324 const double bits = static_cast<double>(bits_.load(std::memory_order_relaxed));
325 if (bits < 24.0)
326 {
327 const double steps = std::exp2(bits - 1.0);
328 const bool dither = dither_.load(std::memory_order_relaxed);
329 for (int i = 0; i < nS; ++i)
330 for (int ch = 0; ch < nCh; ++ch)
331 {
332 T& x = buffer.getChannel(ch)[i];
333 const double noise = dither ? triangular() : 0.0;
334 x = static_cast<T>(std::round(static_cast<double>(x) * steps + noise) / steps);
335 }
336 }
337
338 // Mix and output.
339 if (mixing || outputTarget != 1.0 || outputNow_ != 1.0)
340 {
341 double mix = mixNow_, gain = outputNow_;
342 for (int i = 0; i < nS; ++i)
343 {
344 mix += std::clamp(mixTarget - mix, -rampStep_, rampStep_);
345 gain += (outputTarget - gain) * rampStep_ * 4.0;
346 if (std::abs(outputTarget - gain) < 1e-9) gain = outputTarget;
347 for (int ch = 0; ch < nCh; ++ch)
348 {
349 T& x = buffer.getChannel(ch)[i];
350 const double wet = static_cast<double>(x);
351 const double dry = (mixing && ch < dryCh) ? static_cast<double>(dry_.getChannel(ch)[i]) : wet;
352 x = static_cast<T>((dry + mix * (wet - dry)) * gain);
353 }
354 }
355 mixNow_ = mix;
356 outputNow_ = gain;
357 }
358 }
359
360 std::unique_ptr<GranularProcessor<T>> grains_;
361 std::unique_ptr<Filter> filter_;
362 FilterDesign::Band fit_;
363 AudioSpec spec_ {};
364 AudioBuffer<T> dry_;
365 bool prepared_ = false;
366
367 std::atomic<T> smear_ { T(0) }, pitch_ { T(0) }, foldDb_ { T(0) }, rate_ { T(1e9) };
368 std::atomic<T> bits_ { T(24) }, mix_ { T(1) }, outputDb_ { T(0) };
369 std::atomic<bool> rateFilter_ { false }, dither_ { false };
370
371 // Audio thread.
372 bool grainsOn_ = false;
373 double designedRate_ = -1.0;
374 std::array<T, kMaxChannels> held_ {};
375 double phase_ = 1.0;
376 double mixNow_ = 1.0, outputNow_ = 1.0, foldNow_ = 0.0, foldScaleNow_ = 1.0, rampStep_ = 1.0 / 960.0;
377 uint32_t rng_ = 0x9E3779B9u;
378};
379
380} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
Up to MaxSections second-order sections in series, run in one pass.
void prepare(double sampleRate) noexcept
Sets the sample rate (an invalid one leaves 48 kHz).
static BiquadCoeffs digital(const AnalogSection &section, const Band &band) noexcept
The biquad whose magnitude follows an analog section up to Nyquist.
static AnalogCascade highCut(double hz, double slopeDbPerOctave, double q=kButterworthQ) noexcept
High cut (low-pass) of any slope from 0 to 96 dB per octave.
Granular clouds and spectral-freeze textures from live input.
Grains, fold, sample rate and bit depth, each off by default.
Definition LoFi.h:73
void reset() noexcept
Clears every stage's memory.
Definition LoFi.h:101
void setMix(T mix) noexcept
Dry/wet mix, 0 to 1 (default 1); glides over 20 ms.
Definition LoFi.h:147
T getOutput() const noexcept
Definition LoFi.h:159
T getMix() const noexcept
Definition LoFi.h:158
T getPitch() const noexcept
Definition LoFi.h:152
bool isDither() const noexcept
Definition LoFi.h:157
T getSmear() const noexcept
Definition LoFi.h:151
bool isRateFilter() const noexcept
Definition LoFi.h:155
std::vector< uint8_t > getState() const
Serializes the settings.
Definition LoFi.h:165
T getFold() const noexcept
Definition LoFi.h:153
T getRate() const noexcept
Definition LoFi.h:154
bool setState(const uint8_t *data, size_t size)
Restores what getState() wrote.
Definition LoFi.h:181
void setRateFilter(bool on) noexcept
A 48 dB per octave low-pass at 0.45 of the rate in front of the hold (off by default).
Definition LoFi.h:141
static constexpr int getLatency() noexcept
No latency at any setting.
Definition LoFi.h:162
void setDither(bool on) noexcept
Triangular dither of one step before the rounding (off by default).
Definition LoFi.h:145
void setBits(T bits) noexcept
Bit depth, 1 to 24 (fractional values too); 24, the default, is off.
Definition LoFi.h:143
void setSmear(T amount) noexcept
How far the grains' read position wanders, 0 to 1 (0, the default, with no pitch: no grains).
Definition LoFi.h:129
void prepare(const AudioSpec &spec)
Prepares every stage. Invalid specs are ignored; allocates (setup thread).
Definition LoFi.h:80
void setFold(T dB) noexcept
Fold gain in dB, 0 to 36; 0, the default, is off (see the file notes).
Definition LoFi.h:133
T getBits() const noexcept
Definition LoFi.h:156
void setOutput(T dB) noexcept
Output gain in dB, -24 to +12 (default 0); glides over 20 ms.
Definition LoFi.h:149
void setRate(T hz) noexcept
Sample rate of the hold in hertz, from 100; at or above the stream's rate, the default,...
Definition LoFi.h:135
void processBlock(AudioBufferView< T > buffer) noexcept
Processes a block in place. Pass-through until prepare() succeeds.
Definition LoFi.h:117
void setPitch(T semitones) noexcept
Pitch of the grains in semitones, -24 to +12 (0, the default, with no smear: no grains).
Definition LoFi.h:131
static constexpr int kMaxChannels
Definition LoFi.h:75
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
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
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