Deluge Firmware 1.3.0
Build date: 2026.11.28
Loading...
Searching...
No Matches
delay_buffer.h
1/*
2 * Copyright © 2015-2023 Synthstrom Audible Limited
3 *
4 * This file is part of The Synthstrom Audible Deluge Firmware.
5 *
6 * The Synthstrom Audible Deluge Firmware is free software: you can redistribute it and/or modify it under the
7 * terms of the GNU General Public License as published by the Free Software Foundation,
8 * either version 3 of the License, or (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
11 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12 * See the GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License along with this program.
15 * If not, see <https://www.gnu.org/licenses/>.
16 */
17
18#pragma once
19
20#include "definitions_cxx.hpp"
21#include "dsp/stereo_sample.h"
22#include <cstdint>
23#include <expected>
24#include <optional>
25#include <span>
26
27class StereoSample;
28
29constexpr ptrdiff_t delaySpaceBetweenReadAndWrite = 20;
30
31class DelayBuffer {
32public:
33 constexpr static size_t kMaxSize = 88200;
34 constexpr static size_t kMinSize = 1;
35 constexpr static size_t kNeutralSize = 16384;
36
37 DelayBuffer() = default;
38 ~DelayBuffer() { discard(); }
39 Error init(uint32_t newRate, uint32_t failIfThisSize = 0, bool includeExtraSpace = true);
40
41 // Prevent the delaybuffer from deallocing the Sample array on destruction
42 // TODO (Kate): investigate a shared_ptr for start_
43 constexpr void invalidate() { start_ = nullptr; }
44
45 void makeNativeRatePrecise();
46 void makeNativeRatePreciseRelativeToOtherBuffer(const DelayBuffer& otherBuffer);
47
48 void discard();
49
50 template <typename C>
51 [[gnu::always_inline]] constexpr int32_t advance(C callback) {
52 longPos += resample_config_.value().actualSpinRate;
53 uint8_t newShortPos = longPos >> 24;
54 uint8_t shortPosDiff = newShortPos - lastShortPos;
55 lastShortPos = newShortPos;
56
57 while (shortPosDiff > 0) {
58 callback();
59 shortPosDiff--;
60 }
61 return (longPos >> 8) & 65535;
62 }
63 template <typename C>
64 [[gnu::always_inline]] constexpr int32_t retreat(C callback) {
65 longPos -= resample_config_.value().actualSpinRate;
66 uint8_t newShortPos = longPos >> 24;
67 uint8_t shortPosDiff = lastShortPos - newShortPos; // backward diff
68 lastShortPos = newShortPos;
69
70 while (shortPosDiff > 0) {
71 callback();
72 shortPosDiff--;
73 }
74 return (longPos >> 8) & 65535; // return pos
75 }
76
77 void setupForRender(int32_t rate);
78
79 static std::pair<int32_t, bool> getIdealBufferSizeFromRate(uint32_t rate);
80
81 [[nodiscard]] constexpr bool isActive() const { return (start_ != nullptr); }
82
83 inline bool clearAndMoveOn() {
84 current_->l = 0;
85 current_->r = 0;
86 return moveOn();
87 }
88
91 bool clearAndReadNative(std::span<StereoSample> output);
92
93 inline bool moveOn() {
94 ++current_;
95 bool wrapped = (current_ == end_);
96 if (wrapped) {
97 current_ = start_;
98 }
99 return wrapped;
100 }
101
102 inline bool moveBack() {
103 if (current_ == start_) {
104 current_ = end_ - 1; // wrap around to last element
105 return true;
106 }
107 else {
108 --current_; // move back
109 return false; // no wrap
110 }
111 }
112
113 inline void writeNative(StereoSample toDelay) {
114 StereoSample* writePos = current_ - delaySpaceBetweenReadAndWrite;
115 if (writePos < start_) {
116 writePos += sizeIncludingExtra;
117 }
118 writePos->l = toDelay.l;
119 writePos->r = toDelay.r;
120 }
121
122 inline void writeNativeAndMoveOn(StereoSample toDelay, StereoSample** writePos) {
123 (*writePos)->l = toDelay.l;
124 (*writePos)->r = toDelay.r;
125
126 (*writePos)++;
127 if (*writePos == end_) {
128 *writePos = start_;
129 }
130 }
131
132 [[gnu::always_inline]] void write(StereoSample toDelay, int32_t strength1, int32_t strength2) {
133 // If no speed adjustment
134 if (isNative()) {
135 StereoSample* writePos = current_ - delaySpaceBetweenReadAndWrite;
136 if (writePos < start_) {
137 writePos += sizeIncludingExtra;
138 }
139 writePos->l = toDelay.l;
140 writePos->r = toDelay.r;
141 return;
142 }
143
144 writeResampled(toDelay, strength1, strength2);
145 }
146
147 [[gnu::always_inline]] void writeResampled(StereoSample toDelay, int32_t strength1, int32_t strength2) {
148 if (!resample_config_) {
149 return;
150 }
151 // If delay buffer spinning above sample rate...
152 if (resample_config_->actualSpinRate >= kMaxSampleValue) {
153
154 // An improvement on that could be to only do the triangle-widening when we're down near the native rate -
155 // i.e. set a minimum width of double the native rate rather than always doubling the width. The difficulty
156 // would be ensuring that we compensate perfectly the strength of each write so that the volume remains the
157 // same. It could totally be done. The only real advantage would be that the number of memory writes would
158 // be halved at high speeds.
159
160 // For efficiency, we start far-right, then traverse to far-left.
161
162 // I rearranged some algebra to get this from the strengthThisWrite equation
163 int32_t howFarRightToStart = (strength2 + (resample_config_->spinRateForSpedUpWriting >> 8)) >> 16;
164
165 // This variable represents one "step" of the delay buffer as 65536.
166 // Always positive - absolute distance
167 int32_t distanceFromMainWrite = (int32_t)howFarRightToStart << 16;
168
169 // Initially is the far-right right pos, not the central "main" one
170 StereoSample* writePos = current_ - delaySpaceBetweenReadAndWrite + howFarRightToStart;
171 while (writePos < start_) {
172 writePos += sizeIncludingExtra;
173 }
174 while (writePos >= end_) {
175 writePos -= sizeIncludingExtra;
176 }
177
178 // Do all writes to the right of the main write pos
179 while (distanceFromMainWrite != 0) { // For as long as we haven't reached the "main" pos...
180 // Check my notebook for a rudimentary diagram
181 int32_t strengthThisWrite =
182 (0xFFFFFFFF >> 4) - (((distanceFromMainWrite - strength2) >> 4) * resample_config_->divideByRate);
183
184 writePos->l += multiply_32x32_rshift32(toDelay.l, strengthThisWrite) << 3;
185 writePos->r += multiply_32x32_rshift32(toDelay.r, strengthThisWrite) << 3;
186
187 if (--writePos < start_) {
188 writePos = end_ - 1;
189 }
190 // writePos = (writePos == start_) ? end_ - 1 : writePos - 1;
191 distanceFromMainWrite -= 65536;
192 }
193
194 // Do all writes to the left of (and including) the main write pos
195 while (true) {
196 int32_t strengthThisWrite =
197 (0xFFFFFFFF >> 4) - (((distanceFromMainWrite + strength2) >> 4) * resample_config_->divideByRate);
198 if (strengthThisWrite <= 0) {
199 break; // And stop when we've got far enough left that we shouldn't be squirting any more juice here
200 }
201
202 writePos->l += multiply_32x32_rshift32(toDelay.l, strengthThisWrite) << 3;
203 writePos->r += multiply_32x32_rshift32(toDelay.r, strengthThisWrite) << 3;
204
205 --writePos;
206
207 // loop around
208 if (writePos < start_) {
209 writePos = end_ - 1;
210 }
211 distanceFromMainWrite += 65536;
212 }
213 }
214
215 // Or if delay buffer spinning below sample rate...
216 else {
217 // The most basic version of this would be to write to the "main" pos with strength1 and the "main + 1" pos
218 // with strength 2. But this isn't immune to aliasing, so we instead "squirt" things a little bit wider -
219 // wide enough that our "triangle" is always at least as wide as 1 step / sample in the delay buffer. This
220 // means we potentially need a further 1 write in each direction.
221
222 // And because we're "arbitrarily" increasing the width and height (height is more a side-effect of the
223 // simple algorithm) of our squirt, and also how spaced out the squirts are, the value written at each step
224 // needs to be resized. See delayWriteSizeAdjustment, which is calculated above.
225
226 // We've also had to make sure that the "triangles"' corners exactly meet up. Unfortunately this means even
227 // a tiny slow-down causes half the bandwidth to be lost
228
229 // The furthest right we need to write is 2 steps right from the "main" write
230 StereoSample* writePos = current_ - delaySpaceBetweenReadAndWrite + 2;
231
232 while (writePos < start_) {
233 writePos += sizeIncludingExtra;
234 }
235
236 // Not needed - but be careful! Leave this here as a reminder
237 // while (writePos >= end_) writePos -= sizeIncludingExtra;
238
239 int32_t strength[4];
240
241 strength[1] = strength1 + resample_config_->rateMultiple - 65536; // For the "main" pos
242 strength[2] = strength2 + resample_config_->rateMultiple - 65536; // For the "main + 1" pos
243
244 // Strengths for the further 1 write in each direction
245 strength[0] = strength[1] - 65536;
246 strength[3] = strength[2] - 65536;
247
248 int8_t i = 3;
249 while (true) {
250 if (strength[i] > 0) {
251 writePos->l +=
252 multiply_32x32_rshift32(toDelay.l, (strength[i] >> 2) * resample_config_->writeSizeAdjustment)
253 << 2;
254 writePos->r +=
255 multiply_32x32_rshift32(toDelay.r, (strength[i] >> 2) * resample_config_->writeSizeAdjustment)
256 << 2;
257 }
258 if (--i < 0) {
259 break;
260 }
261
262 --writePos;
263
264 // loop around
265 if (writePos < start_) {
266 writePos = end_ - 1;
267 }
268 }
269 }
270 }
271
272 [[nodiscard]] constexpr bool isNative() const { return !resample_config_.has_value(); }
273 [[nodiscard]] constexpr bool resampling() const { return resample_config_.has_value(); }
274 [[nodiscard]] constexpr uint32_t nativeRate() const { return native_rate_; }
275
276 // Iterator access
277 [[nodiscard]] constexpr StereoSample& current() const { return *current_; }
278 [[nodiscard]] constexpr StereoSample* begin() const { return start_; }
279 [[nodiscard]] constexpr StereoSample* end() const { return end_; }
280 [[nodiscard]] constexpr size_t size() const { return size_; }
281
282 void clear();
283
284 constexpr void setCurrent(StereoSample* sample) { current_ = sample; }
285
286 // TODO (Kate): Make it so the ModControllableFX stuff isn't touching these.
287 // That behavior should either be contained in this class or Delay or a new Stutterer class
288 uint32_t longPos;
289 uint8_t lastShortPos;
290
291 size_t sizeIncludingExtra;
292
293private:
295 uint32_t actualSpinRate; // 1 is represented as 16777216
296 uint32_t spinRateForSpedUpWriting; // Normally the same as actualSpinRate, but subject to some limits for safety
297 uint32_t divideByRate; // 1 is represented as 65536
298 uint32_t rateMultiple;
299 uint32_t writeSizeAdjustment;
300 };
301
302 void setupResample();
303
304 uint32_t native_rate_ = 0;
305
306 StereoSample* start_ = nullptr;
307 StereoSample* end_;
308 StereoSample* current_;
309
310 size_t size_;
311
312public:
313 std::optional<ResampleConfig> resample_config_{};
314};
bool clearAndReadNative(std::span< StereoSample > output)
Definition delay_buffer.cpp:194
Definition delay_buffer.h:294
Definition stereo_sample.h:25