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
use crate::strategies::lpf::LpfBeatDetector;
use crate::strategies::spectrum::SABeatDetector;
use crate::strategies::window_stats::WindowStats;
use crate::strategies::AnalysisState;
pub mod record;
mod strategies;
#[derive(Debug)]
pub struct BeatInfo {
relative_ms: u32,
}
impl BeatInfo {
#[inline(always)]
pub fn new(relative_ms: u32) -> Self {
Self { relative_ms }
}
#[inline(always)]
pub fn relative_ms(&self) -> u32 {
self.relative_ms
}
}
pub trait Strategy {
fn is_beat(&self, samples: &[i16]) -> Option<BeatInfo>;
fn kind(&self) -> StrategyKind;
fn name() -> &'static str
where
Self: Sized;
fn description() -> &'static str
where
Self: Sized;
fn min_duration_between_beats_ms() -> u32
where
Self: Sized;
#[inline(always)]
fn last_beat_beyond_threshold(&self, state: &AnalysisState) -> bool
where
Self: Sized,
{
if state.beat_time_ms() > 0 {
let threshold = state.last_beat_timestamp() + Self::min_duration_between_beats_ms();
if state.beat_time_ms() < threshold {
return false;
}
}
true
}
#[inline(always)]
fn amplitude_high_enough(&self, w_stats: &WindowStats) -> bool {
const MIN_AMPLITUDE_THRESHOLD: i16 = (i16::MAX as f32 * 0.3) as i16;
w_stats.max() >= MIN_AMPLITUDE_THRESHOLD as u16
}
}
#[derive(Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum StrategyKind {
LPF,
Spectrum,
}
impl StrategyKind {
#[inline(always)]
fn detector(&self, sampling_rate: u32) -> Box<dyn Strategy + Send> {
match self {
StrategyKind::LPF => Box::new(LpfBeatDetector::new(sampling_rate)),
StrategyKind::Spectrum => Box::new(SABeatDetector::new(sampling_rate)),
_ => panic!("Unknown Strategy"),
}
}
pub fn name(&self) -> &'static str {
match self {
StrategyKind::LPF => LpfBeatDetector::name(),
StrategyKind::Spectrum => SABeatDetector::name(),
_ => panic!("Unknown Strategy"),
}
}
pub fn description(&self) -> &'static str {
match self {
StrategyKind::LPF => LpfBeatDetector::description(),
StrategyKind::Spectrum => SABeatDetector::description(),
_ => panic!("Unknown Strategy"),
}
}
pub fn values() -> Vec<StrategyKind> {
vec![Self::LPF, Self::Spectrum]
}
}
#[cfg(test)]
mod tests {
use super::*;
use minimp3::{Decoder as Mp3Decoder, Error as Mp3Error, Frame as Mp3Frame};
use std::collections::HashMap;
use std::fs::File;
const SAMPLE_1_EXPECTED_BEATS_MS: [u32; 6] = [300, 2131, 2297, 4303, 6143, 6310];
#[test]
fn test_sample_1_print_beats() {
let (sample_1_audio_data, sampling_rate) = read_mp3_to_mono("res/sample_1.mp3");
assert_eq!(
sampling_rate, 44100,
"The sampling rate of the MP3 examples must be 44100Hz."
);
let window_length = 1024;
let map =
apply_samples_to_all_strategies(window_length, &sample_1_audio_data, sampling_rate);
for (strategy, beats) in map {
println!("Strategy {:?} found beats at:", strategy);
for beat in beats {
println!(" {}ms", beat.relative_ms());
}
}
}
#[test]
#[ignore]
fn test_sample_1_beat_detection() {
let (sample_1_audio_data, sampling_rate) = read_mp3_to_mono("res/sample_1.mp3");
assert_eq!(
sampling_rate, 44100,
"The sampling rate of the MP3 examples must be 44100Hz."
);
let window_length = 1024;
let map =
apply_samples_to_all_strategies(window_length, &sample_1_audio_data, sampling_rate);
const DIFF_WARN_MS: u32 = 30;
const DIFF_ERROR_MS: u32 = 60;
for (strategy, beats) in map {
assert_eq!(
SAMPLE_1_EXPECTED_BEATS_MS.len(),
beats.len(),
"Strategy {:?} must detect {} beats in sample 1!",
strategy,
SAMPLE_1_EXPECTED_BEATS_MS.len()
);
for (i, beat) in beats.iter().enumerate() {
let abs_diff =
(SAMPLE_1_EXPECTED_BEATS_MS[i] as i64 - beat.relative_ms() as i64).abs() as u32;
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);
if abs_diff >= DIFF_WARN_MS {
eprintln!("[{:?}]: WARN: Recognized beat[{}] should is less than {}ms away from the actual value; is: {}ms", strategy, i, DIFF_WARN_MS, abs_diff);
};
}
}
}
fn apply_samples_to_all_strategies(
window_length: usize,
samples: &[i16],
_sampling_rate: u32,
) -> HashMap<StrategyKind, Vec<BeatInfo>> {
let mut samples = Vec::from(samples);
let remainder = samples.len() % window_length;
if remainder != 0 {
samples.extend_from_slice(&vec![0; remainder])
}
let window_count = samples.len() / window_length;
let strategies = vec![StrategyKind::LPF, StrategyKind::Spectrum];
let mut map = HashMap::new();
for strategy in strategies {
let detector = strategy.detector(44100);
let mut beats = Vec::new();
for i in 0..window_count {
let window = &samples[i * window_length..(i + 1) * window_length];
let beat = detector.is_beat(window);
if let Some(beat) = beat {
beats.push(beat);
}
}
map.insert(strategy, beats);
}
map
}
fn read_mp3_to_mono(file: &str) -> (Vec<i16>, u32) {
let mut decoder = Mp3Decoder::new(File::open(file).unwrap());
let mut sampling_rate = 0;
let mut mono_samples = vec![];
loop {
match decoder.next_frame() {
Ok(Mp3Frame {
data: samples_of_frame,
sample_rate,
channels,
..
}) => {
sampling_rate = sample_rate;
if channels == 2 {
for (i, sample) in samples_of_frame.iter().enumerate().step_by(2) {
let sample = *sample as i32;
let next_sample = samples_of_frame[i + 1] as i32;
mono_samples.push(((sample + next_sample) as f32 / 2.0) as i16);
}
} else if channels == 1 {
mono_samples.extend_from_slice(&samples_of_frame);
} else {
panic!("Unsupported number of channels={}", channels);
}
}
Err(Mp3Error::Eof) => break,
Err(e) => panic!("{:?}", e),
}
}
(mono_samples, sampling_rate as u32)
}
}