Debian Codegraph @

fon/Sound_to_Formant.cpp

raw symbols SCIP
1 /* Sound_to_Formant.cpp
2 *
3 * Copyright (C) 1992-2008,2010-2012,2014-2021,2024-2026 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 3 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 /*
20 * pb 2002/07/16 GPL
21 * pb 2003/05/15 replaced memcof with NUMburg
22 * pb 2003/09/18 default time step is 4 times oversampling
23 * pb 2006/05/10 better handling of interruption in Sound_to_Formant
24 * pb 2006/05/10 better handling of NULL from Polynomial_to_Roots
25 * pb 2007/01/26 made compatible with stereo Sounds
26 * pb 2007/03/30 changed float to double (against compiler warnings)
27 * pb 2010/12/13 removed some style bugs
28 * pb 2011/06/08 C++
29 */
30
31 #include "Sound_to_Formant.h"
32 #include "NUM2.h"
33 #include "Polynomial.h"
34 #include "Roots.h"
35
36 static void burg (constVEC samples, VEC coefficients,
37 Formant_Frame frame, double nyquistFrequency, double safetyMargin)
38 {
39 double a0 = VECburg (coefficients, samples);
40 (void) a0;
41 /*
42 Convert LP coefficients to polynomial.
43 */
44 autoPolynomial polynomial = Polynomial_create (-1, 1, coefficients.size);
45 for (integer i = 1; i <= coefficients.size; i ++)
46 polynomial -> coefficients [i] = - coefficients [coefficients.size - i + 1];
47 polynomial -> coefficients [coefficients.size + 1] = 1.0;
48
49 /*
50 Find the roots of the polynomial.
51 */
52 autoRoots roots = Polynomial_to_Roots (polynomial.get());
53 Roots_fixIntoUnitCircle (roots.get());
54
55 Melder_assert (frame -> numberOfFormants == 0 && NUMisEmpty (frame -> formant.get()));
56
57 /*
58 First pass: count the formants.
59 The roots come in conjugate pairs, so we need only count those above the real axis.
60 */
61 for (integer iroot = 1; iroot <= roots -> numberOfRoots; iroot ++)
62 if (roots -> roots [iroot].imag() >= 0.0) {
63 const double f = fabs (atan2 (roots -> roots [iroot].imag(), roots -> roots [iroot].real())) * nyquistFrequency / NUMpi;
64 if (f >= safetyMargin && f <= nyquistFrequency - safetyMargin)
65 frame -> numberOfFormants ++;
66 }
67
68 /*
69 Create space for formant data.
70 */
71 if (frame -> numberOfFormants > 0)
72 frame -> formant = newvectorzero <structFormant_Formant> (frame -> numberOfFormants);
73
74 /*
75 Second pass: fill in the formants.
76 */
77 int iformant = 0;
78 for (integer iroot = 1; iroot <= roots -> numberOfRoots; iroot ++)
79 if (roots -> roots [iroot].imag() >= 0.0) {
80 const double f = fabs (atan2 (roots -> roots [iroot].imag(), roots -> roots [iroot].real())) * nyquistFrequency / NUMpi;
81 if (f >= safetyMargin && f <= nyquistFrequency - safetyMargin) {
82 Formant_Formant formant = & frame -> formant [++ iformant];
83 formant -> frequency = f;
84 formant -> bandwidth = -
85 log (norm (roots -> roots [iroot])) * nyquistFrequency / NUMpi;
86 }
87 }
88 Melder_assert (iformant == frame -> numberOfFormants); // may fail if some frequency is NaN
89 }
90
91 static int findOneZero (integer ijt, double vcx [], double a, double b, double *zero) {
92 double fa = 0.0, fb = 0.0;
93 for (integer k = ijt; k >= 0; k --) {
94 fa = vcx [k] + a * fa;
95 fb = vcx [k] + b * fb;
96 }
97 if (fa * fb >= 0.0) { // there should be a zero between a and b
98 Melder_casual (
99 U"There is no zero between ,", Melder_single (a),
100 U" and ", Melder_single (b),
101 U".\n The function values are ", Melder_single (fa),
102 U" and ", Melder_single (fb),
103 U", respectively."
104 );
105 return 0;
106 }
107 double x, fx;
108 do {
109 //x = fa == fb ? 0.5 * (a + b) : a + fa * (a - b) / (fb - fa); // interpolation
110 x = 0.5 * (a + b); // simple bisection
111 fx = 0.0;
112 for (integer k = ijt; k >= 0; k --)
113 fx = vcx [k] + x * fx;
114 if (fa * fx > 0.0) {
115 a = x;
116 fa = fx;
117 } else {
118 b = x;
119 //fb = fx; // comment out if simple bisection
120 }
121 } while (fabs (fx) > 1e-5);
122 *zero = x;
123 return 1; // OK
124 }
125
126 static int findNewZeroes (integer ijt, double ppORIG [], integer degree,
127 double zeroes []) // In / out
128 {
129 static double cosa [7] [7] = {
130 { 1, 0, 0, 0, 0, 0, 0 },
131 { 0, 2, 0, 0, 0, 0, 0 },
132 { -2, 0, 4, 0, 0, 0, 0 },
133 { 0, -6, 0, 8, 0, 0, 0 },
134 { 2, 0, -16, 0, 16, 0, 0 },
135 { 0, 10, 0, -40, 0, 32, 0 },
136 { -2, 0, 36, 0, -96, 0, 64 } };
137 double pp [33], newZeroes [33], px [33];
138 integer const half_degree = (degree + 1) / 2;
139 for (integer vt = 0; vt <= half_degree; vt ++)
140 pp [vt] = ppORIG [vt];
141 if (! (degree & 1))
142 for (integer vt = 1; vt <= half_degree; vt ++)
143 pp [vt] -= pp [vt - 1];
144 for (integer i = 0; i <= half_degree; i ++)
145 px [i] = cosa [half_degree] [i];
146 for (integer pt = half_degree - 1; pt >= 0; pt --)
147 for (integer vt = 0; vt <= half_degree; vt ++)
148 px [vt] += pp [half_degree - pt] * cosa [pt] [vt];
149 /* Fill an array with the new zeroes, which lie between the old zeroes. */
150 newZeroes [0] = 1.0;
151 for (integer i = 1; i <= half_degree; i ++) {
152 if (! findOneZero (ijt, px, zeroes [i - 1], zeroes [i], & newZeroes [i])) {
153 Melder_casual (
154 U"Degree ", degree,
155 U" not completed."
156 );
157 return 0;
158 }
159 }
160 newZeroes [half_degree + 1] = -1.0;
161 /*
162 Grow older.
163 */
164 for (integer i = 0; i <= half_degree + 1; i ++)
165 zeroes [i] = newZeroes [i];
166 return 1;
167 }
168
169 static int splitLevinson (
170 constVEC samples, // the windowed signal xw [1..nx]
171 integer ncof, // the coefficients cof [1..ncof]
172 Formant_Frame frame, double nyquistFrequency) // put the results here
173 {
174 int result = 1;
175 double rx [100], zeroes [33];
176 for (integer i = 0; i <= 32; i ++)
177 zeroes [i] = 0.0;
178 /*
179 Compute the autocorrelation of the windowed signal.
180 */
181 for (integer i = 0; i < ncof; i ++) {
182 rx [i] = 0.0;
183 for (integer j = 1; j <= samples.size - i; j ++)
184 rx [i] += samples [j] * samples [j + i];
185 }
186 /*
187 Normalize autocorrelation;
188 (should we also divide by the autocorrelation of the window?).
189 */
190 for (integer i = 1; i < ncof; i ++)
191 rx [i] /= rx [0]; rx [0] = 1.0;
192
193 /*
194 Compute zeroes.
195 */
196 {
197 double tau = 0.5 * rx [0];
198 double pnu [33], pk [33], pkz [33];
199 for (integer i = 0; i <= 32; i ++)
200 pkz [i] = pk [i] = 0.0;
201 pkz [0] = 1.0;
202 pk [0] = 1.0;
203 pk [1] = 1.0;
204 for (integer degree = 1; degree < ncof; degree ++) {
205 integer t = degree / 2;
206 double tauk = rx [0] + rx [degree], alfak;
207 for (integer it = 1; it <= t; it ++)
208 tauk += pk [it] * ( 2 * it == degree ? rx [it] : rx [it] + rx [degree - it] );
209 alfak = tauk / tau;
210 tau = tauk;
211 pnu [0] = 1.0;
212 integer ijt = (degree + 1) / 2;
213 for (integer it = ijt; it > 0; it --)
214 pnu [it] = pk [it] + pk [it - 1] - alfak * pkz [it - 1];
215 if (2 * ijt == degree)
216 pnu [ijt + 1] = pnu [ijt];
217 if (degree == 1) {
218 (void) 0;
219 } else if (degree == 2) {
220 zeroes [0] = 1.0; // starting values
221 zeroes [1] = 0.5 - 0.5 * pnu [1];
222 zeroes [2] = -1.0;
223 }
224 else
225 if (! findNewZeroes (ijt, pnu, degree, zeroes)) {
226 result = 0;
227 goto loopEnd;
228 }
229 /*
230 Grow older.
231 */
232 for (integer i = 0; i <= 32; i ++) {
233 pkz [i] = pk [i];
234 pk [i] = pnu [i];
235 }
236 }
237 }
238 loopEnd:
239 /*
240 First pass: count the poles.
241 */
242 for (integer i = 1; i <= ncof / 2; i ++) {
243 if (zeroes [i] == 0.0 || zeroes [i] == -1.0)
244 break;
245 frame -> numberOfFormants ++;
246 }
247 /*
248 Create space for formant data.
249 */
250 if (frame -> numberOfFormants > 0)
251 frame -> formant = newvectorzero <structFormant_Formant> (frame -> numberOfFormants);
252 /*
253 Second pass: fill in the poles.
254 */
255 integer iformant = 0;
256 for (integer i = 1; i <= ncof / 2; i ++) {
257 Formant_Formant formant = & frame -> formant [++ iformant];
258 if (zeroes [i] == 0.0 || zeroes [i] == -1.0)
259 break;
260 formant -> frequency = acos (zeroes [i]) * nyquistFrequency / NUMpi;
261 formant -> bandwidth = 50.0;
262 }
263
264 return result;
265 }
266
267 void Formant_sort (Formant me) {
268 for (integer iframe = 1; iframe <= my nx; iframe ++) {
269 Formant_Frame frame = & my frames [iframe];
270 integer n = frame -> numberOfFormants;
271 for (integer i = 1; i < n; i ++) {
272 double min = frame -> formant [i]. frequency;
273 integer imin = i;
274 for (integer j = i + 1; j <= n; j ++)
275 if (frame -> formant [j]. frequency < min) {
276 min = frame -> formant [j]. frequency;
277 imin = j;
278 }
279 if (imin != i) {
280 const double min_bandwidth = frame -> formant [imin]. bandwidth;
281 frame -> formant [imin]. frequency = frame -> formant [i]. frequency;
282 frame -> formant [imin]. bandwidth = frame -> formant [i]. bandwidth;
283 frame -> formant [i]. frequency = min;
284 frame -> formant [i]. bandwidth = min_bandwidth;
285 }
286 }
287 }
288 }
289
290 static autoFormant Sound_to_Formant_any_inplace (Sound me, double dt_in, integer numberOfPoles,
291 double halfdt_window, int which, double preemphasisFrequency, double safetyMargin)
292 {
293 const double dt = ( dt_in > 0.0 ? dt_in : halfdt_window / 4.0 );
294 const double physicalDuration = my nx * my dx;
295 double dt_window = 2.0 * halfdt_window;
296 integer numberOfFrames = 1 + Melder_ifloor ((physicalDuration - dt_window) / dt);
297 integer nsamp_window = Melder_ifloor (dt_window / my dx), halfnsamp_window = nsamp_window / 2;
298
299 if (nsamp_window < numberOfPoles + 1)
300 Melder_throw (U"Window too short.");
301 double t1 = my x1 + 0.5 * (physicalDuration - my dx - (numberOfFrames - 1) * dt); // centre of first frame
302 if (numberOfFrames < 1) {
303 numberOfFrames = 1;
304 t1 = my x1 + 0.5 * physicalDuration;
305 dt_window = physicalDuration;
306 nsamp_window = my nx;
307 }
308 autoFormant thee = Formant_create (my xmin, my xmax, numberOfFrames, dt, t1, (numberOfPoles + 1) / 2); // e.g. 11 poles -> maximally 6 formants
309
310 autoMelderProgress progress (U"Sound to Formant...");
311
312 /* Pre-emphasis. */
313 Sound_preEmphasize_inplace (me, preemphasisFrequency);
314
315 /* Gaussian window. */
316 autoVEC window = raw_VEC (nsamp_window);
317 for (integer i = 1; i <= nsamp_window; i ++) {
318 const double imid = 0.5 * (nsamp_window + 1), edge = exp (-12.0);
319 window [i] = (exp (-48.0 * (i - imid) * (i - imid) / (nsamp_window + 1) / (nsamp_window + 1)) - edge) / (1.0 - edge);
320 }
321
322 integer maximumFrameLength = nsamp_window;
323
324 MelderThread_PARALLEL (numberOfFrames, 3) {
325 auto frameBuffer = raw_VEC (maximumFrameLength);
326 auto coefficients = raw_VEC (numberOfPoles); // superfluous if which==2, but nobody uses that anyway
327 MelderThread_FOR (iframe) {
328 const double t = Sampled_indexToX (thee.get(), iframe);
329 const integer leftSample = Sampled_xToLowIndex (me, t);
330 const integer rightSample = leftSample + 1;
331 integer startSample = rightSample - halfnsamp_window;
332 integer endSample = leftSample + halfnsamp_window;
333 double maximumIntensity = 0.0;
334 Melder_clipLeft (1_integer, & startSample); // this should not be more than a rounding problem
335 Melder_clipRight (& endSample, my nx); // this should not be more than a rounding problem
336 for (integer i = startSample; i <= endSample; i ++) {
337 const double value = Sampled_getValueAtSample (me, i, Sound_LEVEL_MONO, 0);
338 if (value * value > maximumIntensity)
339 maximumIntensity = value * value;
340 }
341 thy frames [iframe]. intensity = maximumIntensity;
342 if (maximumIntensity == 0.0)
343 continue; // Burg cannot stand all zeroes
344
345 /* Copy a pre-emphasized window to a frame. */
346 const integer actualFrameLength = endSample - startSample + 1; // should rarely be less than nsamp_window
347 VEC frame = frameBuffer.part (1, actualFrameLength);
348 const integer offset = startSample - 1;
349 for (integer isamp = 1; isamp <= actualFrameLength; isamp ++)
350 frame [isamp] = Sampled_getValueAtSample (me, offset + isamp, Sound_LEVEL_MONO, 0) * window [isamp];
351
352 if (which == 1) {
353 burg (frame, coefficients.get(), & thy frames [iframe], 0.5 / my dx, safetyMargin);
354 } else if (which == 2) {
355 if (! splitLevinson (frame, numberOfPoles, & thy frames [iframe], 0.5 / my dx)) {
356 Melder_clearError ();
357 Melder_casual (U"(Sound_to_Formant:)"
358 U" Analysis results of frame ", iframe,
359 U" will be wrong."
360 );
361 }
362 }
363 if (MelderThread_IS_MASTER) { // then we can interact with the GUI
364 const double estimatedProgress = MelderThread_ESTIMATED_PROGRESS;
365 Melder_progress (0.1 + 0.8 * estimatedProgress,
366 U"Sound to Formant: analysed approximately ", Melder_iround (numberOfFrames * estimatedProgress),
367 U" out of ", numberOfFrames, U" frames"
368 );
369 }
370 }
371 } MelderThread_ENDPARALLEL
372
373 Formant_sort (thee.get());
374 return thee;
375 }
376
377 autoFormant Sound_to_Formant_any (Sound me, double dt, integer numberOfPoles, double maximumFrequency,
378 double halfdt_window, int which, double preemphasisFrequency, double safetyMargin)
379 {
380 const double nyquist = 0.5 / my dx;
381 autoSound sound;
382 if (maximumFrequency <= 0.0 || fabs (maximumFrequency / nyquist - 1) < 1.0e-12) {
383 sound = Data_copy (me); // will be modified
384 } else {
385 sound = Sound_resample (me, maximumFrequency * 2, 50);
386 }
387 return Sound_to_Formant_any_inplace (sound.get(), dt, numberOfPoles, halfdt_window, which, preemphasisFrequency, safetyMargin);
388 }
389
390 autoFormant Sound_to_Formant_burg (Sound me, double dt, double nFormants, double maximumFrequency, double halfdt_window, double preemphasisFrequency) {
391 try {
392 return Sound_to_Formant_any (me, dt, Melder_iround (2.0 * nFormants), maximumFrequency, halfdt_window, 1, preemphasisFrequency, 50.0);
393 } catch (MelderError) {
394 Melder_throw (me, U": formant analysis (Burg) not performed.");
395 }
396 }
397
398 autoFormant Sound_to_Formant_keepAll (Sound me, double dt, double nFormants, double maximumFrequency, double halfdt_window, double preemphasisFrequency) {
399 try {
400 return Sound_to_Formant_any (me, dt, Melder_iround (2.0 * nFormants), maximumFrequency, halfdt_window, 1, preemphasisFrequency, 0.0);
401 } catch (MelderError) {
402 Melder_throw (me, U": formant analysis (keep all) not performed.");
403 }
404 }
405
406 autoFormant Sound_to_Formant_willems (Sound me, double dt, double nFormants, double maximumFrequency, double halfdt_window, double preemphasisFrequency) {
407 try {
408 return Sound_to_Formant_any (me, dt, Melder_iround (2.0 * nFormants), maximumFrequency, halfdt_window, 2, preemphasisFrequency, 50.0);
409 } catch (MelderError) {
410 Melder_throw (me, U": formant analysis (Willems) not performed.");
411 }
412 }
413
414 /* End of file Sound_to_Formant.cpp */