Debian Codegraph @

fon/Spectrum_to_Formant.cpp

raw
1 /* Spectrum_to_Formant.cpp
2 *
3 * Copyright (C) 1992-2011,2015-2017,2019,2020,2023 Paul Boersma
4 *
5 * This code is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or (at
8 * your option) any later version.
9 *
10 * This code is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 * See the GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this work. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #include "Spectrum_to_Formant.h"
20
21 autoFormant Spectrum_to_Formant (Spectrum me, const integer maxnFormants) {
22 try {
23 integer nfreq = my nx;
24 autoVEC power = zero_VEC (nfreq);
25 constexpr double fakeDuration = 1.0;
26 constexpr double fakeTimeStep = 1.0;
27 autoFormant thee = Formant_create (0.0, fakeDuration, 1, fakeTimeStep, 0.5 * fakeDuration, maxnFormants);
28 for (integer i = 1; i <= nfreq; i ++)
29 power [i] = my z [1] [i] * my z [1] [i] + my z [2] [i] * my z [2] [i];
30 for (integer i = 2; i < nfreq; i ++)
31 if (power [i] > power [i - 1] && power [i] >= power [i + 1]) {
32 const double firstDerivative = power [i + 1] - power [i - 1];
33 const double secondDerivative = 2.0 * power [i] - power [i - 1] - power [i + 1];
34 const Formant_Formant formant = thy frames [1]. formant. append();
35 formant -> frequency = my dx * (i - 1 + 0.5 * firstDerivative / secondDerivative);
36 const double min3dB = 0.5 * (power [i] + 0.125 * firstDerivative * firstDerivative / secondDerivative);
37 /*
38 Search to the left.
39 */
40 integer j = i - 1;
41 while (power [j] > min3dB && j > 1)
42 j --;
43 if (power [j] > min3dB)
44 formant -> bandwidth = formant -> frequency;
45 else
46 formant -> bandwidth =
47 formant -> frequency -
48 my dx * (j - 1 + (min3dB - power [j]) / (power [j + 1] - power [j]));
49 /*
50 Search to the right.
51 */
52 j = i + 1;
53 while (power [j] > min3dB && j < nfreq)
54 j ++;
55 if (power [j] > min3dB)
56 formant -> bandwidth += my xmax - formant -> frequency;
57 else
58 formant -> bandwidth +=
59 my dx * (j - 1 - (min3dB - power [j]) / (power [j - 1] - power [j])) -
60 formant -> frequency;
61 if (thy frames [1]. formant.size == maxnFormants)
62 break;
63 }
64 thy frames [1]. numberOfFormants = thy frames [1]. formant.size; // maintain invariant
65 return thee;
66 } catch (MelderError) {
67 Melder_throw (me, U": not converted to Formant.");
68 }
69 }
70
71 /* End of file Spectrum_to_Formant.cpp */