Debian Codegraph @

libs/Music/FreqAnalysis.cpp

raw
1 // Copyright 2004-07 "Gilles Degottex"
2
3 // This file is part of "Music"
4
5 // "Music" is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU Lesser General Public License as published by
7 // the Free Software Foundation; either version 2.1 of the License, or
8 // (at your option) any later version.
9 //
10 // "Music" is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU Lesser General Public License for more details.
14 //
15 // You should have received a copy of the GNU Lesser General Public License
16 // along with this program; if not, write to the Free Software
17 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19
20 #include "FreqAnalysis.h"
21
22 #include <assert.h>
23 #include <iostream>
24 #include <algorithm>
25 using namespace std;
26 using namespace Math;
27 #include "Music.h"
28 #include <CppAddons/Fit.h>
29
30 namespace Music
31 {
32 double PeakRefinementLogParabola(const vector<std::complex<double> > spectrum, int peak_index)
33 {
34 assert(peak_index>0 && peak_index<int(spectrum.size()-1));
35
36 if(!(is_peak(spectrum, peak_index)))
37 {
38 if(peak_index+1<int(spectrum.size()-1) && is_peak(spectrum, peak_index+1))
39 peak_index++;
40 else if(peak_index-1>0 && is_peak(spectrum, peak_index-1))
41 peak_index--;
42 }
43
44 double a,b,c,xapex,yapex;
45 FitParabola(peak_index-1, log(mod(spectrum[peak_index-1])+numeric_limits<double>::min()),
46 peak_index, log(mod(spectrum[peak_index])+numeric_limits<double>::min()),
47 peak_index+1, log(mod(spectrum[peak_index+1])+numeric_limits<double>::min()),
48 a, b, c, xapex, yapex);
49
50 return xapex;
51 }
52
53 /*!
54 * M. Abe and J. O. Smith III
55 * “Design Criteria for Simple Sinusoidal Parameter Estimation based on Quadratic
56 * Interpolation of FFT Magnitude Peaks AM/FM Rate Estimation and Bias Correction
57 * for Time-Varying Sinusoidal Modeling,”
58 * Convention Paper Audio Engineering Society,
59 * Dept. of Music, Stanford University, August, (2004).
60 */
61 double PeakRefinementLogParabolaUnbiased(const vector<std::complex<double> > spectrum, int peak_index, double zp)
62 {
63 double f = PeakRefinementLogParabola(spectrum, peak_index);
64
65 double df = f - peak_index;
66
67 double c0 = 0.247560; // hann coefs
68 double c1 = 0.084372;
69
70 double xi_zp = c0/(zp*zp) + c1/(zp*zp*zp*zp);
71 double df2 = xi_zp*(df-0.5)*(df+0.5)*df;
72
73 // double c2 = −0.090608;
74 // double c3 = −0.055781;
75 // double nu_zp = c2/(zp*zp*zp*zp) + c3/(zp*zp*zp*zp*zp*zp);
76 // double da = nu_zp*df*df;
77
78 return f+df2;
79 }
80
81 vector<Harmonic> GetHarmonicStruct(const vector<complex<double> >& spectrum, double approx_f0, int nb_harm, double used_zp, double offset_tresh, bool pick_nonpeaks)
82 {
83 double approx_f0_rel = approx_f0*spectrum.size()/double(GetSamplingRate());
84 assert(approx_f0_rel>1 && approx_f0_rel<=spectrum.size()/2-1);
85
86 vector<Harmonic> harms;
87
88 for(int h=1; h<=nb_harm && int(h*approx_f0_rel)<int(spectrum.size()/2)-1; h++)
89 {
90 int c = int(h*approx_f0_rel);
91 int llimit = int((h-offset_tresh)*approx_f0_rel);
92 llimit = std::max(llimit, 1);
93 int rlimit = int((h+offset_tresh)*approx_f0_rel);
94 rlimit = std::min(rlimit, int(spectrum.size()/2)-1);
95 int peak_index = -1;
96
97 if(is_peak(spectrum, c))
98 peak_index = c;
99 else
100 {
101 int cl = c;
102 bool cl_is_peak = false;
103 while(!cl_is_peak && cl-1>llimit)
104 cl_is_peak = is_peak(spectrum, --cl);
105
106 int cr = c;
107 bool cr_is_peak = false;
108 while(!cr_is_peak && cr+1<rlimit)
109 cr_is_peak = is_peak(spectrum, ++cr);
110
111 if(cl_is_peak)
112 {
113 if(cr_is_peak)
114 peak_index = (c-cl<cr-c)?cl:cr;
115 else
116 peak_index = cl;
117 }
118 else if(cr_is_peak)
119 peak_index = cr;
120 }
121
122 if(peak_index>0)
123 {
124 Harmonic harm;
125 harm.mod = mod(spectrum[peak_index]);
126 harm.freq = PeakRefinementLogParabolaUnbiased(spectrum, peak_index, used_zp)*double(GetSamplingRate())/spectrum.size();
127 harm.harm_number = h;
128 harms.push_back(harm);
129 }
130 else if(pick_nonpeaks)
131 {
132 Harmonic harm;
133 harm.mod = mod(spectrum[c]);
134 harm.freq = c*double(GetSamplingRate())/spectrum.size();
135 harm.harm_number = h;
136 harms.push_back(harm);
137 }
138 }
139
140 return harms;
141 }
142
143 double FundFreqRefinementOfHarmonicStruct(const vector<complex<double> >& spectrum, double approx_f0, int nb_harm, double used_zp)
144 {
145 vector<Harmonic> harms = GetHarmonicStruct(spectrum, approx_f0, nb_harm, used_zp, 0.2);
146
147 if(harms.empty())
148 return 0.0;
149
150 double sum_f0 = 0.0;
151
152 for(size_t i=0; i<harms.size(); i++)
153 sum_f0 += harms[i].freq/harms[i].harm_number; // TODO mod weigthed ???
154
155 return sum_f0/harms.size();
156 }
157
158 #if 0
159 void SingleResConvolutionTransform::init()
160 {
161 if(GetSamplingRate()<=0) return;
162
163 for(size_t h=0; h<size(); h++)
164 if(m_convolutions[h]!=NULL)
165 delete m_convolutions[h];
166
167 m_components.resize(GetNbSemitones());
168 m_convolutions.resize(GetNbSemitones());
169 m_harmonics.resize(GetNbSemitones());
170 for(size_t h=0; h<size(); h++)
171 m_convolutions[h] = new Convolution(m_latency_factor, m_gauss_factor, int(h)+GetSemitoneMin());
172 }
173
174 SingleResConvolutionTransform::SingleResConvolutionTransform(double latency_factor, double gauss_factor)
175 : Transform(0.0, 0.0)
176 , m_latency_factor(latency_factor)
177 , m_gauss_factor(gauss_factor)
178 {
179 m_convolutions.resize(size());
180 m_harmonics.resize(size());
181 for(size_t h=0; h<size(); h++)
182 m_convolutions[h] = NULL;
183 init();
184 }
185 void SingleResConvolutionTransform::apply(const deque<double>& buff)
186 {
187 for(size_t h=0; h<size(); h++)
188 {
189 m_is_fondamental[h] = false;
190 m_convolutions[h]->apply(buff);
191 m_harmonics[h] = m_convolutions[h]->m_value;
192 m_components[h] = mod(m_harmonics[h]);
193 }
194 }
195 SingleResConvolutionTransform::~SingleResConvolutionTransform()
196 {
197 for(size_t i=0; i<m_convolutions.size(); i++)
198 delete m_convolutions[i];
199 }
200
201 // NeuralNetGaussAlgo
202 void NeuralNetGaussAlgo::init()
203 {
204 cout << "NeuralNetGaussAlgo::init" << endl;
205
206 SingleResConvolutionTransform::init();
207
208 // m_fwd_plan = rfftw_create_plan(m_size, FFTW_REAL_TO_COMPLEX, FFTW_ESTIMATE | FFTW_OUT_OF_PLACE | FFTW_USE_WISDOM);
209 }
210 NeuralNetGaussAlgo::NeuralNetGaussAlgo(double latency_factor, double gauss_factor)
211 : SingleResConvolutionTransform(latency_factor, gauss_factor)
212 {
213 init();
214 }
215
216 void NeuralNetGaussAlgo::apply(const deque<double>& buff)
217 {
218 // cout << "NeuralNetGaussAlgo::apply " << m_components_treshold << endl;
219
220 m_components_max = 0.0;
221 for(size_t h=0; h<size(); h++)
222 {
223 m_convolutions[h]->apply(buff);
224 m_harmonics[h] = m_convolutions[h]->m_value;
225 m_components[h] = mod(m_harmonics[h]);
226 m_components_max = max(m_components_max, m_components[h]);
227 }
228
229 m_first_fond = UNDEFINED_SEMITONE;
230 for(size_t h=0; h<size(); h++)
231 {
232 m_is_fondamental[h] = false;
233
234 if(m_components[h]/m_components_max>m_components_treshold && m_first_fond==UNDEFINED_SEMITONE)
235 {
236 m_first_fond = h;
237 m_is_fondamental[h] = true;
238 }
239 }
240 }
241
242 NeuralNetGaussAlgo::~NeuralNetGaussAlgo()
243 {
244 }
245
246 // MonophonicAlgo
247 MonophonicAlgo::MonophonicAlgo(double latency_factor, double gauss_factor)
248 : SingleResConvolutionTransform(latency_factor, gauss_factor)
249 {
250 init();
251 }
252 int MonophonicAlgo::getSampleAlgoLatency() const
253 {
254 return m_convolutions[0]->size();
255 }
256 void MonophonicAlgo::apply(const deque<double>& buff)
257 {
258 for(size_t h=0; h<m_is_fondamental.size(); h++)
259 m_is_fondamental[h] = false;
260
261 m_volume_max = 0.0;
262 m_components_max = 0.0;
263 m_first_fond = -1;
264
265 // cout << "buff size=" << buff.size() << " size=" << m_convolutions[m_convolutions.size()-1]->size() << endl;
266
267 int h;
268 for(h=size()-1; h>=0 && buff.size()>=m_convolutions[h]->size(); h--)
269 {
270 size_t i=0;
271 if(h!=int(size())-1) i=m_convolutions[h+1]->size();
272 for(; i<m_convolutions[h]->size(); i++)
273 m_volume_max = max(m_volume_max, abs(buff[i]));
274
275 if(m_volume_max > getVolumeTreshold())
276 {
277 m_convolutions[h]->apply(buff);
278
279 double formant_mod = mod(m_convolutions[h]->m_value);
280
281 // cout<<formant_mod<<" "<<getComponentsTreshold()<<endl;
282
283 // if(formant_mod > getComponentsTreshold())
284 {
285 // m_components[h] = min(formant_mod, max_value);
286 m_components[h] = formant_mod;
287 m_components_max = max(m_components_max, m_components[h]);
288 m_first_fond = h;
289 }
290 // else m_components[h] = 0.0;
291 }
292 else m_components[h] = 0.0;
293 }
294 for(;h>=0; h--)
295 m_components[h] = 0.0;
296
297 // smash all components below a treshold of the max component
298 // for(size_t h=0; h<size(); h++)
299 // if(m_components[h] < m_dominant_treshold*m_components_max)
300 // m_components[h] = 0.0;
301 //
302 // the note is the first resulting component
303 // for(size_t h=0; m_first_fond==-1 && h<size(); h++)
304 // if(m_components[h] > 0.0)
305 // m_first_fond = h;
306
307 // correction: the note is the nearest maximum of m_note
308 // if(m_first_fond!=-1)
309 // while(m_first_fond+1<int(size()) && m_components[m_first_fond+1] > m_components[m_first_fond])
310 // m_first_fond++;
311
312 // cout << "m_first_fond=" << m_first_fond << endl;
313 }
314
315 TwoVoiceMHT::TwoVoiceMHT(double AFreq, int dataBySecond, double rep, double win_factor, int minHT, int maxHT)
316 : m_mht(new MHT(AFreq, dataBySecond, rep, win_factor, minHT, maxHT))
317 , m_last_sol(m_mht->m_components.size())
318 {
319 int nbHT = maxHT - minHT + 1;
320 m_components.resize(nbHT);
321
322 for(size_t i=0; i<m_last_sol.size(); i++)
323 m_last_sol[i] = complex<double>(0.0,0.0);
324 }
325 void TwoVoiceMHT::apply(deque<double>& buff)
326 {
327 // cout << "TwoVoiceMHT::apply" << endl;
328
329 m_mht->apply(buff);
330
331 // double earingTreshold = 0.05;
332 // double modArgTreshold = 0.2;
333 // double modModTreshold = 0.2;
334 // ComputeDiffs(m_mht->m_components, fp, argpfp, modfp);
335
336 // int count = 0;
337 for(size_t h=0;h<m_components.size(); h++)
338 {
339 // if(m_mht->m_components[h]!=complex<double>(0.0,0.0) && count<2)
340 {
341 m_components[h] = m_mht->m_components[h];
342
343 // count++;
344 // if(fabs(argpfp[0][h])>modArgTreshold) count++;
345 }
346 // else m_components[h] = complex<double>(0.0,0.0);
347 }
348
349 // m_last_sol = m_mht->m_components;
350 }
351 TwoVoiceMHT::~TwoVoiceMHT()
352 {
353 delete m_mht;
354 }
355
356 RemoveSyncMHT::RemoveSyncMHT(double AFreq, int dataBySecond, double rep, double win_factor, int minHT, int maxHT)
357 : m_mht(new MHT(AFreq, dataBySecond, rep, win_factor, minHT, maxHT))
358 , m_last_sol(m_mht->m_components.size())
359 {
360 int nbHT = maxHT - minHT + 1;
361 m_components.resize(nbHT);
362
363 for(size_t i=0; i<m_last_sol.size(); i++)
364 m_last_sol[i] = complex<double>(0.0,0.0);
365 }
366 void RemoveSyncMHT::apply(deque<double>& buff)
367 {
368 m_mht->apply(buff);
369
370 double earingTreshold = 0.05;
371 double syncArgTreshold = 0.3; // 0.02 0.25 0.2
372 // double syncModTreshold = 0.2; // 0.05 0.1 0.3
373
374 double fourier_amplitude = 0.0;
375 for(size_t h=0; h<m_mht->m_components.size(); h++)
376 fourier_amplitude = max(fourier_amplitude, normm(m_mht->m_components[h]));
377 vector<int> notes;
378
379 for(size_t h=0; h<m_mht->m_components.size(); h++) // for each half tone
380 {
381 bool is_fond = false;
382
383 if(normm(m_mht->m_components[h])>earingTreshold*fourier_amplitude) // if we can ear it
384 {
385 is_fond = true;
386
387 // search for syncronisation with each discovered fondamentals
388 for(size_t i=0; i<notes.size() && is_fond; i++)
389 {
390 double rk = m_mht->m_convolutions[h]->m_freq/m_mht->m_convolutions[notes[i]]->m_freq;
391 int k = int(rk+0.5);
392 if(abs(k-rk)<0.05) // TODO // if k is nearly an integer, a potential harmonic
393 {
394 complex<double> ft = m_mht->m_components[notes[i]] / normm(m_mht->m_components[notes[i]]);
395 complex<double> ftm1 = m_last_sol[notes[i]] / normm(m_last_sol[notes[i]]);
396 complex<double> rpt = m_mht->m_components[h]/pow(ft, k);
397 complex<double> rptm1 = m_last_sol[h]/pow(ftm1, k);
398 // if(h==25 && k==4)
399 // cout << abs(log(normm(rpt))-log(normm(rptm1))) << " ";
400 // cout << k << "=(arg=" << abs(arg(rpt)-arg(rptm1)) << " mod=" << abs(log(normm(rpt))-log(normm(rptm1))) << ") ";
401 is_fond = abs(arg(rpt)-arg(rptm1)) > syncArgTreshold;
402 // is_fond = is_fond || abs(log(normm(rpt))-log(normm(rptm1))) > syncModTreshold;
403 }
404
405 // is_fond = false;
406 }
407
408 if(is_fond) notes.push_back(h); // it's a fondamentals
409 }
410
411 // cout << endl;
412
413 if(is_fond) m_components[h] = m_mht->m_components[h];
414 else m_components[h] = complex<double>(0.0,0.0);
415 }
416
417 m_last_sol = m_mht->m_sol;
418 }
419 RemoveSyncMHT::~RemoveSyncMHT()
420 {
421 delete m_mht;
422 }
423
424 #if 0
425 NeuralNetMHT::NeuralNetMHT(double AFreq, int dataBySecond, double rep, double win_factor, int minHT, int maxHT, const string& file_name)
426 : m_mht(new MHT(AFreq, dataBySecond, rep, win_factor, minHT, maxHT))
427 , m_nn(new LayeredNeuralNet<TypeNeuron>())
428 {
429 m_nbHT = maxHT - minHT + 1;
430 m_components.resize(m_nbHT);
431
432 m_nn->load(file_name.c_str());
433
434 assert(m_nbHT==m_nn->getInputLayer()->getNeurons().size());
435 assert(m_nbHT==m_nn->getOutputLayer()->getNeurons().size());
436
437 cout << "topology: " << m_nn->getInputLayer()->getNeurons().size();
438 for(LayeredNeuralNet<TypeNeuron>::LayerIterator it = ++(m_nn->m_layerList.begin()); it !=m_nn->m_layerList.end(); it++)
439 cout << " => " << (*it)->getNeurons().size();
440 cout << " [" << m_nn->getNbWeights() << " weights]" << endl;
441 }
442 void NeuralNetMHT::apply(deque<double>& buff)
443 {
444 // cout << "NeuralNetMHT::apply" << endl;
445
446 m_mht->apply(buff);
447
448 vector<double> inputs(m_nbHT);
449
450 for(int h=0; h<m_nbHT; h++)
451 inputs[h] = normm(m_mht->m_components[h]);
452
453 m_nn->computeOutputs(inputs);
454
455 for(int h=0; h<m_nbHT; h++)
456 m_components[h] = complex<double>(m_nn->getOutputLayer()->getNeurons()[h].o);
457 }
458 NeuralNetMHT::~NeuralNetMHT()
459 {
460 delete m_nn;
461 delete m_mht;
462 }
463 #endif
464
465 #endif
466 }