1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
macro_rules! impl_peak_hold_float {
($name:ident, $builder:ident, $ty:ty) => {
/// Peak hold with decay — instant attack, configurable hold, exponential decay.
///
/// Captures peaks instantly, holds them for a configurable number of
/// samples, then decays exponentially.
///
/// # Use Cases
/// - VU meter / level indicator behavior
/// - Peak envelope tracking
/// - "What was the recent peak?" with graceful decay
#[derive(Debug, Clone)]
pub struct $name {
peak: $ty,
hold_samples: u64,
decay_rate: $ty,
hold_remaining: u64,
count: u64,
}
/// Builder for [`
#[doc = stringify!($name)]
/// `].
#[derive(Debug, Clone)]
pub struct $builder {
hold_samples: u64,
decay_rate: Option<$ty>,
}
impl $name {
/// Creates a builder.
#[inline]
#[must_use]
pub fn builder() -> $builder {
$builder {
hold_samples: 0,
decay_rate: Option::None,
}
}
/// Feeds a sample. Returns the current envelope value.
///
/// New peaks are captured instantly. During the hold period, the
/// peak is maintained. After hold expires, the envelope decays
/// multiplicatively each sample.
#[inline]
#[must_use]
pub fn update(&mut self, sample: $ty) -> $ty {
self.count += 1;
// Instant attack — new peak
if sample >= self.peak {
self.peak = sample;
self.hold_remaining = self.hold_samples;
return self.peak;
}
// Hold period
if self.hold_remaining > 0 {
self.hold_remaining -= 1;
return self.peak;
}
// Decay
self.peak *= self.decay_rate;
// If sample is above decayed peak, capture it
if sample > self.peak {
self.peak = sample;
self.hold_remaining = self.hold_samples;
}
self.peak
}
/// Current envelope value.
#[inline]
#[must_use]
pub fn peak(&self) -> $ty {
self.peak
}
/// Number of samples processed.
#[inline]
#[must_use]
pub fn count(&self) -> u64 {
self.count
}
/// Resets the envelope.
#[inline]
pub fn reset(&mut self) {
self.peak = 0.0 as $ty;
self.hold_remaining = 0;
self.count = 0;
}
}
impl $builder {
/// Number of samples to hold the peak before decaying. Default: 0.
#[inline]
#[must_use]
pub fn hold_samples(mut self, n: u64) -> Self {
self.hold_samples = n;
self
}
/// Per-sample multiplicative decay rate (0 to 1). Default must be set.
///
/// 0.99 = slow decay, 0.9 = fast decay.
#[inline]
#[must_use]
pub fn decay_rate(mut self, rate: $ty) -> Self {
self.decay_rate = Option::Some(rate);
self
}
/// Builds the peak hold envelope.
///
/// # Errors
///
/// - decay_rate must have been set.
/// - decay_rate must be in (0, 1].
#[inline]
pub fn build(self) -> Result<$name, crate::ConfigError> {
let rate = self
.decay_rate
.ok_or(crate::ConfigError::Missing("decay_rate"))?;
if !(rate > 0.0 as $ty && rate <= 1.0 as $ty) {
return Err(crate::ConfigError::Invalid("decay_rate must be in (0, 1]"));
}
Ok($name {
peak: 0.0 as $ty,
hold_samples: self.hold_samples,
decay_rate: rate,
hold_remaining: 0,
count: 0,
})
}
}
};
}
macro_rules! impl_peak_hold_int {
($name:ident, $builder:ident, $ty:ty) => {
/// Peak hold (integer) — instant attack, configurable hold, no decay.
///
/// Integer variant tracks the peak during the hold window. After hold
/// expires, the peak resets to the current sample (no exponential decay
/// for integers — use the float variant for decay behavior).
#[derive(Debug, Clone)]
pub struct $name {
peak: $ty,
hold_samples: u64,
hold_remaining: u64,
count: u64,
}
/// Builder for [`
#[doc = stringify!($name)]
/// `].
#[derive(Debug, Clone)]
pub struct $builder {
hold_samples: u64,
}
impl $name {
/// Creates a builder.
#[inline]
#[must_use]
pub fn builder() -> $builder {
$builder { hold_samples: 0 }
}
/// Feeds a sample. Returns the current peak.
#[inline]
#[must_use]
pub fn update(&mut self, sample: $ty) -> $ty {
self.count += 1;
if sample >= self.peak || self.count == 1 {
self.peak = sample;
self.hold_remaining = self.hold_samples;
return self.peak;
}
if self.hold_remaining > 0 {
self.hold_remaining -= 1;
return self.peak;
}
// Hold expired — reset to current sample
self.peak = sample;
self.hold_remaining = self.hold_samples;
self.peak
}
/// Current peak value.
#[inline]
#[must_use]
pub fn peak(&self) -> $ty {
self.peak
}
/// Number of samples processed.
#[inline]
#[must_use]
pub fn count(&self) -> u64 {
self.count
}
/// Resets the peak.
#[inline]
pub fn reset(&mut self) {
self.peak = 0;
self.hold_remaining = 0;
self.count = 0;
}
}
impl $builder {
/// Number of samples to hold the peak. Default: 0.
#[inline]
#[must_use]
pub fn hold_samples(mut self, n: u64) -> Self {
self.hold_samples = n;
self
}
/// Builds the peak hold tracker.
#[inline]
pub fn build(self) -> Result<$name, crate::ConfigError> {
Ok($name {
peak: 0,
hold_samples: self.hold_samples,
hold_remaining: 0,
count: 0,
})
}
}
};
}
impl_peak_hold_float!(PeakHoldF64, PeakHoldF64Builder, f64);
impl_peak_hold_float!(PeakHoldF32, PeakHoldF32Builder, f32);
impl_peak_hold_int!(PeakHoldI64, PeakHoldI64Builder, i64);
impl_peak_hold_int!(PeakHoldI32, PeakHoldI32Builder, i32);
impl_peak_hold_int!(PeakHoldI128, PeakHoldI128Builder, i128);
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[allow(clippy::float_cmp)]
fn instant_attack() {
let mut ph = PeakHoldF64::builder()
.decay_rate(0.95)
.hold_samples(5)
.build()
.unwrap();
assert_eq!(ph.update(50.0), 50.0);
assert_eq!(ph.update(100.0), 100.0); // instant capture
}
#[test]
#[allow(clippy::float_cmp)]
fn hold_period() {
let mut ph = PeakHoldF64::builder()
.decay_rate(0.95)
.hold_samples(3)
.build()
.unwrap();
let _ = ph.update(100.0);
assert_eq!(ph.update(50.0), 100.0); // held
assert_eq!(ph.update(50.0), 100.0); // held
assert_eq!(ph.update(50.0), 100.0); // held (3rd hold sample)
}
#[test]
fn decay_after_hold() {
let mut ph = PeakHoldF64::builder()
.decay_rate(0.9)
.hold_samples(0)
.build()
.unwrap();
let _ = ph.update(100.0);
let v = ph.update(0.0); // decay immediately (no hold)
assert!(v < 100.0, "should have decayed, got {v}");
}
#[test]
#[allow(clippy::float_cmp)]
fn new_peak_during_hold() {
let mut ph = PeakHoldF64::builder()
.decay_rate(0.95)
.hold_samples(10)
.build()
.unwrap();
let _ = ph.update(100.0);
let _ = ph.update(50.0); // holding at 100
assert_eq!(ph.update(200.0), 200.0); // new peak resets hold
}
#[test]
fn i64_hold() {
let mut ph = PeakHoldI64::builder().hold_samples(3).build().unwrap();
let _ = ph.update(100);
assert_eq!(ph.update(50), 100); // held
assert_eq!(ph.update(50), 100); // held
assert_eq!(ph.update(50), 100); // held
assert_eq!(ph.update(50), 50); // hold expired, reset to current
}
#[test]
fn reset() {
let mut ph = PeakHoldF64::builder().decay_rate(0.95).build().unwrap();
let _ = ph.update(100.0);
ph.reset();
assert_eq!(ph.count(), 0);
}
#[test]
fn errors_without_decay_rate() {
let result = PeakHoldF64::builder().build();
assert!(matches!(
result,
Err(crate::ConfigError::Missing("decay_rate"))
));
}
#[test]
fn i128_basic() {
let mut ph = PeakHoldI128::builder().hold_samples(3).build().unwrap();
let _ = ph.update(100);
assert_eq!(ph.update(50), 100); // held
}
}