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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
use rustfft::num_complex::Complex;
use audio_processor_traits::{AudioBuffer, SimpleAudioProcessor};
use dynamic_thresholds::{DynamicThresholds, DynamicThresholdsParams};
use power_change::{PowerOfChangeFrames, PowerOfChangeParams};
use crate::fft_processor::{FftDirection, FftProcessor, FftProcessorOptions};
use crate::window_functions::WindowFunctionType;
mod dynamic_thresholds;
mod frame_deltas;
mod power_change;
pub mod markers;
#[cfg(any(test, feature = "visualization"))]
pub mod visualization;
#[derive(Debug, Clone)]
pub struct IterativeTransientDetectionParams {
pub fft_size: usize,
pub fft_overlap_ratio: f32,
pub power_of_change_spectral_spread: usize,
pub threshold_time_spread: usize,
pub threshold_time_spread_factor: f32,
pub frequency_bin_change_threshold: usize,
pub iteration_magnitude_factor: f32,
pub iteration_count: usize,
}
impl Default for IterativeTransientDetectionParams {
fn default() -> Self {
let fft_size = 2048;
let frequency_bin_change_threshold = 2048 / 4;
Self {
fft_size,
fft_overlap_ratio: 0.75,
power_of_change_spectral_spread: 3,
threshold_time_spread: 2,
threshold_time_spread_factor: 2.0,
iteration_magnitude_factor: 0.05,
iteration_count: 20,
frequency_bin_change_threshold,
}
}
}
pub fn find_transients<BufferType: AudioBuffer<SampleType = f32>>(
params: IterativeTransientDetectionParams,
data: &mut BufferType,
) -> Vec<f32> {
let IterativeTransientDetectionParams {
fft_size,
fft_overlap_ratio,
power_of_change_spectral_spread,
threshold_time_spread,
threshold_time_spread_factor,
frequency_bin_change_threshold,
iteration_magnitude_factor,
iteration_count,
} = params;
log::info!("Performing FFT...");
let fft_frames = get_fft_frames(fft_size, fft_overlap_ratio, data);
log::info!("Finding base function values");
let mut magnitude_frames: Vec<Vec<f32>> = get_magnitudes(&fft_frames);
let mut transient_magnitude_frames: Vec<Vec<f32>> =
initialize_result_transient_magnitude_frames(&mut magnitude_frames);
for _iteration in 0..iteration_count {
let t_results = frame_deltas::calculate_deltas(&magnitude_frames);
let f_frames = power_change::calculate_power_of_change(
PowerOfChangeParams {
spectral_spread_bins: power_of_change_spectral_spread,
},
&t_results,
);
let threshold_frames = dynamic_thresholds::calculate_dynamic_thresholds(
DynamicThresholdsParams {
threshold_time_spread,
threshold_time_spread_factor,
},
&f_frames,
);
let num_changed_bins_frames: Vec<usize> =
count_changed_bins_per_frame(f_frames, threshold_frames);
update_output_and_magnitudes(
iteration_magnitude_factor,
frequency_bin_change_threshold,
num_changed_bins_frames,
&mut magnitude_frames,
&mut transient_magnitude_frames,
);
}
generate_output_frames(
fft_size,
fft_overlap_ratio,
data,
&fft_frames,
&mut transient_magnitude_frames,
)
}
fn update_output_and_magnitudes(
iteration_magnitude_factor: f32,
frequency_bin_change_threshold: usize,
num_changed_bins_frames: Vec<usize>,
magnitude_frames: &mut [Vec<f32>],
transient_magnitude_frames: &mut [Vec<f32>],
) {
for i in 0..transient_magnitude_frames.len() {
for j in 0..transient_magnitude_frames[i].len() {
if num_changed_bins_frames[i] >= frequency_bin_change_threshold {
transient_magnitude_frames[i][j] +=
iteration_magnitude_factor * magnitude_frames[i][j];
magnitude_frames[i][j] -=
(1.0 - iteration_magnitude_factor) * magnitude_frames[i][j];
}
}
}
}
fn count_changed_bins_per_frame(
f_frames: PowerOfChangeFrames,
threshold_frames: DynamicThresholds,
) -> Vec<usize> {
threshold_frames
.buffer
.iter()
.zip(f_frames.buffer)
.map(|(threshold_frame, f_frame)| {
threshold_frame
.iter()
.zip(f_frame)
.map(|(threshold, f)| if f > *threshold { 1 } else { 0 })
.sum()
})
.collect()
}
fn generate_output_frames<BufferType: AudioBuffer<SampleType = f32>>(
fft_size: usize,
fft_overlap_ratio: f32,
data: &mut BufferType,
fft_frames: &[Vec<Complex<f32>>],
transient_magnitude_frames: &mut [Vec<f32>],
) -> Vec<f32> {
let mut planner = rustfft::FftPlanner::new();
let fft = planner.plan_fft(fft_size, FftDirection::Inverse);
let scratch_size = fft.get_inplace_scratch_len();
let mut scratch = Vec::with_capacity(scratch_size);
scratch.resize(scratch_size, 0.0.into());
let mut output = vec![];
output.resize(data.num_samples(), 0.0);
let mut cursor = 0;
for i in 0..fft_frames.len() {
let frame = &fft_frames[i];
let mut buffer: Vec<Complex<f32>> = frame
.iter()
.zip(&transient_magnitude_frames[i])
.map(|(input_signal_complex, transient_magnitude)| {
Complex::from_polar(*transient_magnitude, input_signal_complex.arg())
})
.collect();
fft.process_with_scratch(&mut buffer, &mut scratch);
for j in 0..buffer.len() {
if cursor + j < output.len() {
output[cursor + j] += buffer[j].re;
}
}
cursor += (frame.len() as f32 * (1.0 - fft_overlap_ratio)) as usize;
}
let maximum_output = output
.iter()
.map(|f| f.abs())
.max_by(|f1, f2| f1.partial_cmp(f2).unwrap_or(std::cmp::Ordering::Equal))
.unwrap_or(0.0);
for sample in &mut output {
if sample.abs() > maximum_output * 0.05 {
*sample /= maximum_output;
} else {
*sample = 0.0;
}
}
output.iter().skip(fft_size).cloned().collect()
}
fn initialize_result_transient_magnitude_frames(magnitudes: &mut [Vec<f32>]) -> Vec<Vec<f32>> {
magnitudes
.iter()
.map(|frame| frame.iter().map(|_| 0.0).collect())
.collect()
}
fn get_magnitudes(fft_frames: &[Vec<Complex<f32>>]) -> Vec<Vec<f32>> {
fft_frames
.iter()
.map(|frame| {
frame
.iter()
.map(|frequency_bin| frequency_bin.norm())
.collect()
})
.collect()
}
fn get_fft_frames<BufferType: AudioBuffer<SampleType = f32>>(
fft_size: usize,
fft_overlap_ratio: f32,
data: &mut BufferType,
) -> Vec<Vec<Complex<f32>>> {
let mut fft = FftProcessor::new(FftProcessorOptions {
size: fft_size,
direction: FftDirection::Forward,
overlap_ratio: fft_overlap_ratio,
window_function: WindowFunctionType::Hann,
});
let mut fft_frames = vec![];
for frame in data.frames_mut() {
fft.s_process_frame(frame);
if fft.has_changed() {
fft_frames.push(fft.buffer().clone());
}
}
fft_frames
}
#[cfg(test)]
mod test {
use audio_processor_testing_helpers::relative_path;
use audio_processor_file::{AudioFileProcessor, OutputAudioFileProcessor};
use audio_processor_traits::{
AudioProcessor, AudioProcessorSettings, OwnedAudioBuffer, VecAudioBuffer,
};
use super::*;
fn read_input_file(input_file_path: &str) -> impl AudioBuffer<SampleType = f32> {
log::info!("Reading input file input_file={}", input_file_path);
let settings = AudioProcessorSettings::default();
let mut input = AudioFileProcessor::from_path(
audio_garbage_collector::handle(),
settings,
input_file_path,
)
.unwrap();
input.prepare(settings);
let input_buffer = input.buffer();
let mut buffer = VecAudioBuffer::new();
let max_len = (settings.sample_rate() * 10.0) as usize;
buffer.resize(1, input_buffer[0].len().min(max_len), 0.0);
for channel in input_buffer.iter() {
for (sample_index, sample) in channel.iter().enumerate().take(max_len) {
buffer.set(0, sample_index, *sample + buffer.get(0, sample_index));
}
}
buffer
}
#[test]
fn test_transient_detector() {
use visualization::draw;
wisual_logger::init_from_env();
let output_path = relative_path!("./src/transient_detection/stft.png");
let input_path = relative_path!("./hiphop-drum-loop.mp3");
let transients_file_path = format!("{}.transients.wav", input_path);
let mut input = read_input_file(&input_path);
let frames: Vec<f32> = input.frames().map(|frame| frame[0]).collect();
let max_input = frames
.iter()
.map(|f| f.abs())
.max_by(|f1, f2| f1.partial_cmp(f2).unwrap_or(std::cmp::Ordering::Equal))
.unwrap();
let transients = find_transients(
IterativeTransientDetectionParams {
iteration_count: 2,
..IterativeTransientDetectionParams::default()
},
&mut input,
);
assert_eq!(
frames.len() - IterativeTransientDetectionParams::default().fft_size,
transients.len()
);
draw(&output_path, &frames, &transients);
let settings = AudioProcessorSettings {
input_channels: 1,
output_channels: 1,
..AudioProcessorSettings::default()
};
let mut output_processor =
OutputAudioFileProcessor::from_path(settings, &transients_file_path);
output_processor.prepare(settings);
let mut transients: Vec<f32> = transients.iter().map(|f| f * max_input).collect();
output_processor.process(&mut transients);
}
}