-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlibpar.rs
246 lines (204 loc) · 6.32 KB
/
libpar.rs
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
use std::error::Error;
use std::path::PathBuf;
use std::sync::mpsc;
use std::sync::Arc;
use std::thread;
use std::time::Instant;
// perf note: instead of using Rust impl of lpca:
//use super::lpca_rs::lpca;
// use the C impl:
use crate::ecoz2_lib::lpca_c::lpca;
use crate::prd::Predictor;
use crate::sgn;
use crate::utl;
use super::lpc_rs::create_hamming;
pub fn lpc_par(
file: PathBuf,
output: Option<PathBuf>,
prediction_order: usize,
window_length_ms: usize,
offset_length_ms: usize,
) {
let filename: &str = file.to_str().unwrap();
let out_filename: &str = match output {
Some(ref fname) => fname.to_str().unwrap(),
None => "predictor_par.prd",
};
println!("Loading: {}", filename);
let s = sgn::load(filename);
s.show();
//sgn::save(&s, "output.wav");
let before = Instant::now();
let vectors = lpa_on_signal(prediction_order, window_length_ms, offset_length_ms, &s).unwrap();
let elapsed = before.elapsed();
if elapsed.as_secs() > 5 {
println!("processing took: {:.2?}", elapsed);
}
let class_name = "_".to_string();
let predictor = Predictor {
class_name,
prediction_order,
vectors,
};
utl::save_ser(&predictor, out_filename).unwrap();
println!(
"{} saved. Class: '{}': {} vectors",
out_filename,
&predictor.class_name,
&predictor.vectors.len()
);
}
struct LPAnalyzerPar {
pub prediction_order: usize,
#[allow(dead_code)] // TODO review
pub win_size: usize,
reflex: Vec<f64>,
pred: Vec<f64>,
frame: Vec<f64>,
}
impl LPAnalyzerPar {
fn new(prediction_order: usize, win_size: usize) -> LPAnalyzerPar {
let reflex = vec![0f64; prediction_order + 1]; // reflection coefficients
let pred = vec![0f64; prediction_order + 1]; // prediction coefficients
// perform linear prediction to each frame:
let frame = vec![0f64; win_size];
LPAnalyzerPar {
prediction_order,
win_size,
reflex,
pred,
frame,
}
}
#[inline]
pub fn process_frame(
&mut self,
samples: &[f64],
hamming: &[f64],
vector: &mut [f64],
) -> Result<(), Box<dyn Error>> {
self.fill_frame(samples);
self.remove_mean();
self.preemphasis();
self.apply_hamming(hamming);
let (res_lpca, err_pred) = lpca(
&self.frame,
self.prediction_order,
vector,
&mut self.reflex,
&mut self.pred,
);
if res_lpca == 0 {
// normalize autocorrelation sequence by gain:
if err_pred != 0. {
for elem in vector.iter_mut() {
*elem /= err_pred;
}
}
Ok(())
} else {
Err(format!(
"ERROR: lpa_on_signal: res_lpca = {}, err_pred = {}",
res_lpca, err_pred
)
.into())
}
}
#[inline]
fn fill_frame(&mut self, from: &[f64]) {
self.frame.copy_from_slice(from);
}
#[inline]
fn remove_mean(&mut self) {
let sum: f64 = self.frame.iter().sum();
let mean = sum / self.frame.len() as f64;
for elem in self.frame.iter_mut() {
*elem -= mean;
}
}
#[inline]
fn preemphasis(&mut self) {
for n in (1..self.frame.len()).rev() {
self.frame[n] -= 0.95 * self.frame[n - 1];
}
}
#[inline]
fn apply_hamming(&mut self, hamming: &[f64]) {
for (elem, h) in self.frame.iter_mut().zip(hamming) {
*elem *= *h
}
}
}
pub fn lpa_on_signal(
p: usize,
window_length_ms: usize,
offset_length_ms: usize,
s: &sgn::Sgn,
) -> Option<Vec<Vec<f64>>> {
let num_samples: usize = s.num_samples;
let sample_rate: usize = s.sample_rate;
let signal = Arc::new({
let mut x = vec![0f64; num_samples];
x.clone_from_slice(&s.samples[..num_samples]);
x
});
// number of samples corresponding to window_length_ms:
let win_size = (window_length_ms * sample_rate) / 1000;
// number of samples corresponding to offset_length_ms:
let offset = (offset_length_ms * sample_rate) / 1000;
if win_size > num_samples {
eprintln!("ERROR: lpa_on_signal: signal too short\n");
return None;
}
// total number of frames:
let mut num_frames = (num_samples - (win_size - offset)) / offset;
// discard last section if incomplete:
if (num_frames - 1) * offset + win_size > num_samples {
num_frames -= 1;
}
let cores: usize = num_cpus::get();
println!(
"lpa_on_signal: p={} numSamples={} sampleRate={} winSize={} offset={} num_frames={} (cores={})",
p, num_samples, sample_rate, win_size, offset, num_frames, cores
);
let hamming: Arc<Vec<_>> = Arc::new(create_hamming(win_size));
let (tx, rx) = mpsc::channel();
let mut children = vec![];
let frames_per_thread = num_frames / cores;
let extra_frames_last_thread = num_frames % cores;
for th in 0..cores {
let c_hamming = hamming.clone();
let c_tx = tx.clone();
let mut lpa = LPAnalyzerPar::new(p, win_size);
let signal = signal.clone();
let handle = thread::spawn(move || {
let frame_low = th * frames_per_thread;
let frame_upp = frame_low + frames_per_thread + {
if th == cores - 1 {
extra_frames_last_thread
} else {
0
}
};
for f in frame_low..frame_upp {
let signal_from = f * offset;
let signal_to = signal_from + win_size;
let samples = &signal[signal_from..signal_to];
let mut vector = vec![0f64; p + 1];
lpa.process_frame(samples, &c_hamming, &mut vector).unwrap();
c_tx.send((f, vector)).unwrap();
}
});
children.push(handle);
}
drop(tx);
for child in children {
child.join().unwrap();
}
let mut vectors = vec![vec![0f64; 0]; num_frames];
for (f, vector) in &rx {
vectors[f] = vector;
}
println!(" PAR lpa_on_signal complete: {} vectors", vectors.len());
Some(vectors)
}