Skip to main content

beat_detector/
lib.rs

1/*
2MIT License
3
4Copyright (c) 2021 Philipp Schuster
5
6Permission is hereby granted, free of charge, to any person obtaining a copy
7of this software and associated documentation files (the "Software"), to deal
8in the Software without restriction, including without limitation the rights
9to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10copies of the Software, and to permit persons to whom the Software is
11furnished to do so, subject to the following conditions:
12
13The above copyright notice and this permission notice shall be included in all
14copies or substantial portions of the Software.
15
16THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22SOFTWARE.
23*/
24
25#![deny(
26clippy::all,
27clippy::cargo,
28clippy::nursery,
29// clippy::restriction,
30// clippy::pedantic
31)]
32// now allow a few rules which are denied by the above statement
33// --> they are ridiculous and not necessary
34#![allow(
35    clippy::suboptimal_flops,
36    clippy::redundant_pub_crate,
37    clippy::fallible_impl_from
38)]
39#![deny(missing_debug_implementations)]
40#![deny(rustdoc::all)]
41
42use crate::strategies::lpf::LpfBeatDetector;
43use crate::strategies::spectrum::SABeatDetector;
44use crate::strategies::window_stats::WindowStats;
45use crate::strategies::AnalysisState;
46
47pub mod record;
48mod strategies;
49
50/// Struct that holds information about a detected beat.
51#[derive(Debug)]
52pub struct BeatInfo {
53    relative_ms: u32,
54    // todo intensity
55}
56impl BeatInfo {
57    #[inline(always)]
58    pub const fn new(relative_ms: u32) -> Self {
59        Self { relative_ms }
60    }
61
62    #[inline(always)]
63    pub const fn relative_ms(&self) -> u32 {
64        self.relative_ms
65    }
66}
67
68/// Common abstraction over a beat detection strategy. Each strategy keeps ongoing
69/// audio samples, for example from microphone. Strategies should have an internal
70/// mutable state via interior mutability to compare sample windows (and analysis)
71/// against previous values.
72pub trait Strategy {
73    /// Checks if inside the samples window a new beat was recognized.
74    /// If so, it returns `Some` with [`BeatInfo`] as payload.
75    ///
76    /// Implementations may buffer previous samples and combine them with the latest,
77    /// i.e. make a sliding window.
78    fn is_beat(&self, samples: &[i16]) -> Option<BeatInfo>;
79
80    /// Convenient getter to get the [`StrategyKind`] of a strategy.
81    /// This is a 1:1 mapping.
82    fn kind(&self) -> StrategyKind;
83
84    /// A nice name for the algorithm, displayable in user interfaces.
85    // "where Self: Sized" => compiler gave me this hint
86    // => prevents "`Strategy` cannot be made into an object"
87    fn name() -> &'static str
88    where
89        Self: Sized;
90
91    /// A textual description of the algorithm to help the user to select
92    /// the right one.
93    // "where Self: Sized" => compiler gave me this hint
94    // => prevents "`Strategy` cannot be made into an object"
95    fn description() -> &'static str
96    where
97        Self: Sized;
98
99    /// Duration in ms after each beat. Useful do prevent the same beat to be
100    /// detected as two beats. This is a constant per strategy, because more
101    /// advanced strategies can cope with small durations (50ms) whereas
102    /// "stupid"/basic strategies may need 400ms.
103    /// This is a function instead of an associated constant, because
104    /// otherwise the build fails with "`Strategy` cannot be made into an object"
105    // "where Self: Sized" => compiler gave me this hint
106    // => prevents "`Strategy` cannot be made into an object"
107    fn min_duration_between_beats_ms() -> u32
108    where
109        Self: Sized;
110
111    /// Common implementation for all strategies which checks if
112    /// the last beat is beyond the threshold. Of not, we can return early
113    /// and do not need to check if a beat is in the given sample.
114    #[inline(always)]
115    fn last_beat_beyond_threshold(&self, state: &AnalysisState) -> bool
116    where
117        Self: Sized,
118    {
119        // only check this if at least a single beat was recognized
120        if state.beat_time_ms() > 0 {
121            let threshold = state.last_beat_timestamp() + Self::min_duration_between_beats_ms();
122            if state.beat_time_ms() < threshold {
123                return false;
124            }
125        }
126        true
127    }
128
129    /// Common implementation for all strategies which checks if
130    /// the current windows/frames max amplitude (i16) is above a value where
131    /// a beat could happen in theory (discard noise/silence/break between songs)
132    #[inline(always)]
133    fn amplitude_high_enough(&self, w_stats: &WindowStats) -> bool {
134        const MIN_AMPLITUDE_THRESHOLD: i16 = (i16::MAX as f32 * 0.3) as i16;
135        w_stats.max() >= MIN_AMPLITUDE_THRESHOLD as u16
136    }
137}
138
139/// Enum that conveniently and easily makes all [`Strategy`]s provided by this crate accessible.
140/// This enum provides the bare minimum functionality to access the strategies. All deeper
141/// functionality must be defined inside the implementations.
142#[derive(Debug, PartialEq, Eq, Hash)]
143#[non_exhaustive] // more will come in the future
144pub enum StrategyKind {
145    /// Corresponds to [`strategies::lpf::LpfBeatDetector`].
146    LPF,
147    /// Corresponds to [`strategies::spectrum::SABeatDetector`]
148    Spectrum,
149}
150
151impl StrategyKind {
152    /// Creates a concrete detector object, i.e. a struct that implements
153    /// [`Strategy`] on that you can continuously analyze your input audio data.
154    #[inline(always)]
155    fn detector(&self, sampling_rate: u32) -> Box<dyn Strategy + Send> {
156        match self {
157            StrategyKind::LPF => Box::new(LpfBeatDetector::new(sampling_rate)),
158            StrategyKind::Spectrum => Box::new(SABeatDetector::new(sampling_rate)),
159            // _ => panic!("Unknown Strategy"),
160        }
161    }
162
163    /// Convenient wrapper for ['Strategy::name'].
164    pub fn name(&self) -> &'static str {
165        match self {
166            StrategyKind::LPF => LpfBeatDetector::name(),
167            StrategyKind::Spectrum => SABeatDetector::name(),
168            // _ => panic!("Unknown Strategy"),
169        }
170    }
171
172    /// Convenient wrapper for ['Strategy::description'].
173    pub fn description(&self) -> &'static str {
174        match self {
175            StrategyKind::LPF => LpfBeatDetector::description(),
176            StrategyKind::Spectrum => SABeatDetector::description(),
177            // _ => panic!("Unknown Strategy"),
178        }
179    }
180
181    /// Returns a vector with all strategy kinds to iterate over them.
182    pub fn values() -> Vec<Self> {
183        vec![Self::LPF, Self::Spectrum]
184    }
185}
186
187#[cfg(test)]
188mod tests {
189    use super::*;
190    use minimp3::{Decoder as Mp3Decoder, Error as Mp3Error, Frame as Mp3Frame};
191    use std::collections::HashMap;
192    use std::fs::File;
193
194    // opened the file in Audacity and looked where the
195    // beats are
196    const SAMPLE_1_EXPECTED_BEATS_MS: [u32; 6] = [300, 2131, 2297, 4303, 6143, 6310];
197
198    #[test]
199    fn test_sample_1_print_beats() {
200        let (sample_1_audio_data, sampling_rate) = read_mp3_to_mono("res/sample_1.mp3");
201        // assert 44,1kHz because it makes things easier
202        assert_eq!(
203            sampling_rate, 44100,
204            "The sampling rate of the MP3 examples must be 44100Hz."
205        );
206
207        // 1/44100 * 1024 == 1024/44100 == 0.046439s == 23,2ms
208        let window_length = 1024;
209
210        let map =
211            apply_samples_to_all_strategies(window_length, &sample_1_audio_data, sampling_rate);
212
213        for (strategy, beats) in map {
214            println!("Strategy {:?} found beats at:", strategy);
215            for beat in beats {
216                println!("  {}ms", beat.relative_ms());
217            }
218        }
219    }
220
221    /// TODO this test only works for a "pretty good" beat detection algorithm, because
222    ///  beats are close together. This doesn't work for the two existing ones.
223    ///  Make this test more tolerant, i.e. only for the "good algorithms" that
224    ///  hopefully come in the future.
225    #[test]
226    #[ignore]
227    fn test_sample_1_beat_detection() {
228        let (sample_1_audio_data, sampling_rate) = read_mp3_to_mono("res/sample_1.mp3");
229        // assert 44,1kHz because it makes things easier
230        assert_eq!(
231            sampling_rate, 44100,
232            "The sampling rate of the MP3 examples must be 44100Hz."
233        );
234
235        // 1/44100 * 1024 == 1024/44100 == 0.046439s == 23,2ms
236        let window_length = 1024;
237
238        let map =
239            apply_samples_to_all_strategies(window_length, &sample_1_audio_data, sampling_rate);
240
241        const DIFF_WARN_MS: u32 = 30;
242        const DIFF_ERROR_MS: u32 = 60;
243
244        for (strategy, beats) in map {
245            assert_eq!(
246                SAMPLE_1_EXPECTED_BEATS_MS.len(),
247                beats.len(),
248                "Strategy {:?} must detect {} beats in sample 1!",
249                strategy,
250                SAMPLE_1_EXPECTED_BEATS_MS.len()
251            );
252            for (i, beat) in beats.iter().enumerate() {
253                let abs_diff =
254                    (SAMPLE_1_EXPECTED_BEATS_MS[i] as i64 - beat.relative_ms() as i64).abs() as u32;
255                assert!(abs_diff < DIFF_ERROR_MS, "[{:?}]: Recognized beat[{}] should not be more than {} ms away from the actual value; is {}ms", strategy, i, DIFF_ERROR_MS, abs_diff);
256                if abs_diff >= DIFF_WARN_MS {
257                    eprintln!("[{:?}]: WARN: Recognized beat[{}] should is less than {}ms away from the actual value; is: {}ms", strategy, i, DIFF_WARN_MS, abs_diff);
258                };
259            }
260        }
261    }
262
263    fn apply_samples_to_all_strategies(
264        window_length: usize,
265        samples: &[i16],
266        _sampling_rate: u32,
267    ) -> HashMap<StrategyKind, Vec<BeatInfo>> {
268        // we pad with zeroes until the audio data length is a multiple
269        // of the window length
270        let mut samples = Vec::from(samples);
271        let remainder = samples.len() % window_length;
272        if remainder != 0 {
273            samples.extend_from_slice(&vec![0; remainder])
274        }
275
276        let window_count = samples.len() / window_length;
277
278        // all strategies
279        let strategies = vec![StrategyKind::LPF, StrategyKind::Spectrum];
280
281        let mut map = HashMap::new();
282
283        for strategy in strategies {
284            let detector = strategy.detector(44100);
285            let mut beats = Vec::new();
286            for i in 0..window_count {
287                let window = &samples[i * window_length..(i + 1) * window_length];
288                let beat = detector.is_beat(window);
289                if let Some(beat) = beat {
290                    beats.push(beat);
291                }
292            }
293            map.insert(strategy, beats);
294        }
295
296        map
297    }
298
299    /// Reads an MP3 and returns the audio data as mono channel + the sampling rate in Hertz.
300    fn read_mp3_to_mono(file: &str) -> (Vec<i16>, u32) {
301        let mut decoder = Mp3Decoder::new(File::open(file).unwrap());
302
303        let mut sampling_rate = 0;
304        let mut mono_samples = vec![];
305        loop {
306            match decoder.next_frame() {
307                Ok(Mp3Frame {
308                    data: samples_of_frame,
309                    sample_rate,
310                    channels,
311                    ..
312                }) => {
313                    // that's a bird weird of the original API. Why should channels or sampling
314                    // rate change from frame to frame?
315
316                    // Should be constant throughout the MP3 file.
317                    sampling_rate = sample_rate;
318
319                    if channels == 2 {
320                        for (i, sample) in samples_of_frame.iter().enumerate().step_by(2) {
321                            let sample = *sample as i32;
322                            let next_sample = samples_of_frame[i + 1] as i32;
323                            mono_samples.push(((sample + next_sample) as f32 / 2.0) as i16);
324                        }
325                    } else if channels == 1 {
326                        mono_samples.extend_from_slice(&samples_of_frame);
327                    } else {
328                        panic!("Unsupported number of channels={}", channels);
329                    }
330                }
331                Err(Mp3Error::Eof) => break,
332                Err(e) => panic!("{:?}", e),
333            }
334        }
335
336        (mono_samples, sampling_rate as u32)
337    }
338}