Sound_to_Formant.cpp 14 KB

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