audio_processor_analysis/peak_detector.rs
1use rustfft::num_traits::Float;
2
3// Augmented Audio: Audio libraries and applications
4// Copyright (c) 2022 Pedro Tacla Yamada
5//
6// The MIT License (MIT)
7//
8// Permission is hereby granted, free of charge, to any person obtaining a copy
9// of this software and associated documentation files (the "Software"), to deal
10// in the Software without restriction, including without limitation the rights
11// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12// copies of the Software, and to permit persons to whom the Software is
13// furnished to do so, subject to the following conditions:
14//
15// The above copyright notice and this permission notice shall be included in
16// all copies or substantial portions of the Software.
17//
18// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24// THE SOFTWARE.
25
26#[numeric_literals::replace_float_literals(F::from(literal).unwrap())]
27pub fn calculate_multiplier<F>(sample_rate: F, duration_ms: F) -> F
28where
29 F: Float,
30{
31 let attack_secs = duration_ms * 0.001;
32 let attack_samples = sample_rate * attack_secs;
33 F::exp2(-1.0 / attack_samples)
34}
35
36pub type PeakDetector = PeakDetectorImpl<f32>;
37
38pub struct PeakDetectorImpl<F> {
39 value: F,
40}
41
42impl<F: Float> Default for PeakDetectorImpl<F> {
43 #[numeric_literals::replace_float_literals(F::from(literal).unwrap())]
44 fn default() -> Self {
45 Self { value: 0.0 }
46 }
47}
48
49impl<F: Float + std::iter::Sum> PeakDetectorImpl<F> {
50 pub fn value(&self) -> F {
51 self.value
52 }
53
54 #[numeric_literals::replace_float_literals(F::from(literal).unwrap())]
55 pub fn accept_frame(&mut self, attack_mult: F, release_mult: F, frame: &[F]) {
56 let frame_len = F::from(frame.len()).unwrap();
57 let new: F = frame.iter().map(|f| F::abs(*f)).sum::<F>() / frame_len;
58 let curr_slope = if self.value > new {
59 release_mult
60 } else {
61 attack_mult
62 };
63 self.value = (self.value * curr_slope) + ((1.0 - curr_slope) * new);
64 }
65}