Sound Byte Libs 29c5ff3
C++ firmware library for audio applications on 32-bit ARM Cortex-M processors
Loading...
Searching...
No Matches
delay_line.hpp
Go to the documentation of this file.
1// sbl/dsp/delay_line.hpp — Circular buffer delay line
2//
3// Fixed-size delay line with caller-provided storage. Supports integer
4// and fractional delay reads with linear interpolation.
5//
6// Usage:
7// float buf[1024];
8// sbl::dsp::DelayLine delay(buf, 1024);
9// delay.write(sample);
10// float out = delay.read(480); // 10ms delay at 48kHz
11
12#pragma once
13
14#include <cstdint>
15
16namespace sbl::dsp {
17
18class DelayLine {
19public:
20 /// @note All public methods are ISR-safe — bounded computation, no I/O.
21
22 /**
23 * @brief Construct with caller-provided buffer
24 * @param buffer Float buffer (must outlive the DelayLine)
25 * @param max_delay Maximum delay in samples (buffer size)
26 */
27 DelayLine(float* buffer, uint32_t max_delay)
28 : buffer_(buffer), max_delay_(max_delay), write_pos_(0) {}
29
30 /** @brief Write a sample to the delay line */
31 void write(float sample) {
32 buffer_[write_pos_] = sample;
33 ++write_pos_;
34 if (write_pos_ >= max_delay_) {
35 write_pos_ = 0;
36 }
37 }
38
39 /**
40 * @brief Read a sample at integer delay
41 * @param delay Delay in samples (0 = most recent write)
42 * @return Delayed sample
43 */
44 float read(uint32_t delay) const {
45 if (delay >= max_delay_) delay = max_delay_ - 1;
46 uint32_t pos = (write_pos_ + max_delay_ - delay - 1) % max_delay_;
47 return buffer_[pos];
48 }
49
50 /**
51 * @brief Read with fractional delay (float)
52 *
53 * Linear interpolation between adjacent samples.
54 *
55 * @param delay Fractional delay in samples (e.g. 10.5f)
56 * @return Linearly interpolated sample
57 */
58 float read_fractional(float delay) const {
59 uint32_t int_delay = static_cast<uint32_t>(delay);
60 float frac = delay - static_cast<float>(int_delay);
61
62 float a = read(int_delay);
63 float b = read(int_delay + 1);
64
65 return a + frac * (b - a);
66 }
67
68 /** @brief Zero all samples in the buffer */
69 void clear() {
70 for (uint32_t i = 0; i < max_delay_; ++i) {
71 buffer_[i] = 0.0f;
72 }
73 write_pos_ = 0;
74 }
75
76 /** @brief Maximum delay in samples */
77 uint32_t max_delay() const { return max_delay_; }
78
79private:
80 float* buffer_;
81 uint32_t max_delay_;
82 uint32_t write_pos_;
83};
84
85} // namespace sbl::dsp
float read_fractional(float delay) const
Read with fractional delay (float)
void clear()
Zero all samples in the buffer.
uint32_t max_delay() const
Maximum delay in samples.
void write(float sample)
Write a sample to the delay line.
DelayLine(float *buffer, uint32_t max_delay)
Construct with caller-provided buffer.
float read(uint32_t delay) const
Read a sample at integer delay.
DSP atoms for audio signal processing.
Definition allpass.hpp:22