DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
FrequencyShifter.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
33#include "../Core/AudioBuffer.h"
34#include "../Core/AudioSpec.h"
35#include "../Core/DenormalGuard.h"
36#include "../Core/DspMath.h"
37#include "../Core/Hilbert.h"
38#include "../Core/StateBlob.h"
39
40#include <algorithm>
41#include <atomic>
42#include <cmath>
43#include <cstddef>
44#include <cstdint>
45#include <numbers>
46#include <vector>
47
48namespace dspark {
49
64template <FloatType T>
66{
67public:
77 void prepare(const AudioSpec& spec)
78 {
79 if (!spec.isValid()) return; // release-safe: keep previous state
80
81 sampleRate_ = spec.sampleRate;
82 mixMaxStep_ = static_cast<T>(1.0 / (spec.sampleRate * 0.02));
83 numChannels_ = spec.numChannels;
84
85 // Zero-allocations on audio thread: allocate all Hilberts during prepare.
86 // The network is rate independent (designed in normalised frequency).
87 hilberts_.resize(numChannels_);
88
89 currentMix_ = mix_.load(std::memory_order_relaxed);
90 reset();
91 }
92
97 void processBlock(AudioBufferView<T> buffer) noexcept
98 {
99 const int numCh = std::min(buffer.getNumChannels(), numChannels_);
100 const int numSamples = buffer.getNumSamples();
101 if (numSamples == 0 || numCh == 0) return;
102
103 // The Hilbert network is a cascade of recursive allpass sections with
104 // poles near the unit circle: its decaying state reaches denormals in
105 // silence, and the framework convention is that per-sample Hilbert
106 // callers install their own guard (see Hilbert.h and Compressor.h).
107 DenormalGuard guard;
108
109 const T targetMix = mix_.load(std::memory_order_relaxed);
110 const T shiftHz = shift_.load(std::memory_order_relaxed);
111
112 // The mix is rate limited to full scale per 20 ms: an unsmoothed step
113 // would jump the dry/wet crossfade audibly, and a per-block ramp
114 // landed in 0.7 ms with 32-sample blocks. The shift needs no
115 // smoothing - it only changes the speed of the quadrature carrier,
116 // whose phase stays continuous across blocks.
117 const T mixStart = currentMix_;
118
119 // 1. Compute rotation matrix coefficients once per block
120 const double w = (shiftHz * 2.0 * std::numbers::pi) / sampleRate_;
121 const T cos_w = static_cast<T>(std::cos(w));
122 const T sin_w = static_cast<T>(std::sin(w));
123
124 // Cache the starting phase components for this block
125 const T startCos = static_cast<T>(std::cos(phase_));
126 const T startSin = static_cast<T>(std::sin(phase_));
127
128 // 2. Process planar channels to maximize cache locality
129 for (int ch = 0; ch < numCh; ++ch)
130 {
131 T* data = buffer.getChannel(ch);
132 auto& hilbert = hilberts_[ch];
133
134 // Local quadrature oscillator state (identical carrier and mix
135 // ramp on every channel)
136 T u = startCos;
137 T v = startSin;
138
139 for (int i = 0; i < numSamples; ++i)
140 {
141 const T smoothMix = moveTowards(mixStart, targetMix,
142 mixMaxStep_ * static_cast<T>(i + 1));
143
144 // Hilbert processing (I + jQ)
145 auto h = hilbert.process(data[i]);
146
147 // Modulate analytic signal: real part of (I+jQ) * (u+jv)
148 T shifted = h.real * u - h.imag * v;
149
150 // Mix correctly: Use h.real as the phase-aligned dry signal
151 data[i] = h.real + (shifted - h.real) * smoothMix;
152
153 // Advance quadrature oscillator: rotation matrix
154 T next_u = u * cos_w - v * sin_w;
155 T next_v = u * sin_w + v * cos_w;
156 u = next_u;
157 v = next_v;
158 }
159 }
160
161 currentMix_ = moveTowards(mixStart, targetMix, mixMaxStep_ * static_cast<T>(numSamples));
162
163 // 3. Advance absolute phase once per block to prevent float drift
164 phase_ += w * numSamples;
165
166 // Wrap phase precisely
167 constexpr double kTwoPi = 2.0 * std::numbers::pi;
168 phase_ = std::fmod(phase_, kTwoPi);
169 if (phase_ < 0.0) phase_ += kTwoPi;
170 }
171
175 void reset() noexcept
176 {
177 phase_ = 0.0;
178 for (auto& h : hilberts_) {
179 h.reset();
180 }
181 }
182
190 void setShift(T hz) noexcept
191 {
192 if (!std::isfinite(hz)) return;
193 shift_.store(hz, std::memory_order_relaxed);
194 }
195
201 void setMix(T mix) noexcept
202 {
203 if (!std::isfinite(mix)) return;
204 mix_.store(std::clamp(mix, T(0), T(1)), std::memory_order_relaxed);
205 }
206
208 [[nodiscard]] T getShift() const noexcept { return shift_.load(std::memory_order_relaxed); }
209
211 [[nodiscard]] T getMix() const noexcept { return mix_.load(std::memory_order_relaxed); }
212
220 [[nodiscard]] static constexpr int getLatency() noexcept
221 {
222 return 0;
223 }
224
226 [[nodiscard]] std::vector<uint8_t> getState() const
227 {
228 // The blob stores float (setState reads float back); the explicit
229 // casts also keep this overload resolvable when T is double.
230 StateWriter w(stateId("FSHF"), 1);
231 w.write("shift", static_cast<float>(shift_.load(std::memory_order_relaxed)));
232 w.write("mix", static_cast<float>(mix_.load(std::memory_order_relaxed)));
233 return w.blob();
234 }
235
237 bool setState(const uint8_t* data, size_t size)
238 {
239 StateReader r(data, size);
240 if (!r.isValid() || r.processorId() != stateId("FSHF")) return false;
241 setShift(static_cast<T>(r.read("shift", 0.0f)));
242 setMix(static_cast<T>(r.read("mix", 1.0f)));
243 return true;
244 }
245
246private:
247 double sampleRate_ = 44100.0;
248 int numChannels_ = 0;
249
250 // Using double for phase accumulation to prevent drift over long sessions
251 double phase_ = 0.0;
252
253 std::atomic<T> shift_{ T(0) };
254 std::atomic<T> mix_{ T(1) };
255
256 // Smoothed state for the audio thread
257 T currentMix_{ T(1) };
258 T mixMaxStep_{ T(1.0 / 960.0) };
259
260 std::vector<HilbertIIR<T>> hilberts_;
261};
262
263} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
Constant-Hz frequency shift optimized via Quadrature Oscillator.
static constexpr int getLatency() noexcept
Reports the processing latency in samples: none.
std::vector< uint8_t > getState() const
Serializes the parameter state (setup/UI threads; allocates).
void setMix(T mix) noexcept
Sets the dry/wet mix. Smoothed internally.
T getShift() const noexcept
void reset() noexcept
Resets internal filter states and phase accumulator.
void prepare(const AudioSpec &spec)
Prepares the frequency shifter state and allocates internal buffers.
T getMix() const noexcept
bool setState(const uint8_t *data, size_t size)
Restores parameters from a blob (tolerant; rejects foreign ids).
void setShift(T hz) noexcept
Sets the frequency shift amount in Hz.
void processBlock(AudioBufferView< T > buffer) noexcept
Processes audio in-place applying the frequency shift.
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.
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
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
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45