Debian Codegraph @

dwtools/Sound_to_Pitch2.cpp

raw
1 /* Sound_to_Pitch2.c
2 *
3 * Copyright (C) 1993-2019 David Weenink
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. See the GNU
13 * 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 djmw 20020813 GPL header
21 djmw 20021106 Latest modification
22 djmw 20041124 Changed call to Sound_to_Spectrum.
23 djmw 20070103 Sound interface changes
24 */
25
26 #include "Sound_to_Pitch2.h"
27 #include "Pitch_extensions.h"
28 #include "Sound_and_Spectrum.h"
29 #include "Sound_to_SPINET.h"
30 #include "SPINET_to_Pitch.h"
31 #include "NUM2.h"
32
33 static double Sound_approximateLocalSampleMean (Sound me, double fromTime, double toTime) {
34 const integer n1 = Melder_clippedLeft (1_integer, Sampled_xToNearestIndex (me, fromTime));
35 const integer n2 = Melder_clippedRight (Sampled_xToNearestIndex (me, toTime), my nx);
36 return n1 <= n2 ? NUMmean (my z [1].part (n1, n2)) : undefined;
37 }
38
39 static void spec_enhance_SHS (VEC const & a) {
40 Melder_assert (a.size >= 2);
41
42 autoINTVEC posmax = raw_INTVEC ((a.size + 1) / 2);
43 integer nmax = 0;
44 if (a [1] > a [2])
45 posmax [++ nmax] = 1;
46
47 for (integer i = 2; i <= a.size - 1; i ++)
48 if (a [i] > a [i - 1] && a [i] >= a [i + 1])
49 posmax [++ nmax] = i;
50
51 if (a [a.size] > a [a.size - 1])
52 posmax [++ nmax] = a.size;
53
54 if (nmax == 1) {
55 a.part (1, posmax [1] - 3) <<= 0.0;
56 a.part (posmax [1] + 3, a.size) <<= 0.0;
57 } else {
58 for (integer i = 2; i <= nmax; i ++)
59 a.part (posmax [i - 1] + 3, posmax [i] - 3) <<= 0.0;
60 }
61 }
62
63 static void spec_smoooth_SHS (VEC const& a) {
64 /*
65 Convolve in-place with the small symmetric moving-average
66 kernel { 0.25, 0.5, 0.25 }, aligned around its second element.
67 The basic equation for an output element a_new [i] is:
68 a_new [i] := 0.25 * (a [i - 1] + 2.0 * a [i] + a [i + 1])
69
70 The procedure is performed in place, i.e., the vector a_new []
71 appears as the new version of the vector a [], so that care has
72 to be taken to timely save elements that will be overwritten.
73 At the edges we perform "same" convolution, meaning that
74 the output vector has the same number of elements as the
75 input vector (this is a natural situation in case of in-place
76 filtering). The elements just beyond the edges of the vector,
77 namely a [0] and a [a.size + 1], are assumed to be zero.
78 */
79 double a_i_minus_1 = 0.0; // save a [i - 1], for i == 1
80 for (integer i = 1; i <= a.size - 1; i ++) {
81 const double a_i = a [i]; // save a [i]
82 a [i] = 0.25 * (a_i_minus_1 + 2.0 * a_i + a [i + 1]);
83 a_i_minus_1 = a_i;
84 }
85 a [a.size] = 0.25 * (a_i_minus_1 + 2.0 * a [a.size]);
86 }
87
88 autoPitch Sound_to_Pitch_shs (Sound me, double timeStep, double pitchFloor, double maximumFrequency,
89 double pitchCeiling, integer maxnSubharmonics, integer maxnCandidates, double compressionFactor, integer numberOfPointsPerOctave)
90 {
91 try {
92 const double newSamplingFrequency = 2.0 * maximumFrequency;
93 const double windowDuration = 2.0 / pitchFloor, halfWindow = 0.5 * windowDuration;
94 const double atans = numberOfPointsPerOctave * NUMlog2 (65.0 / 50.0) - 1.0;
95 /*
96 Number of speech samples in the downsampled signal in each frame:
97 100 for windowDuration == 0.04 and newSamplingFrequency == 2500
98 */
99 const integer numberOfSamples = Melder_iround (windowDuration * newSamplingFrequency);
100 const double frameDuration = numberOfSamples / newSamplingFrequency;
101
102 const integer nfft = Melder_clippedLeft (256_integer /* the minimum number of points for the FFT */, Melder_iroundUpToPowerOfTwo (numberOfSamples));
103 const integer nfft2 = nfft / 2 + 1;
104 const double fftframeDuration = nfft / newSamplingFrequency;
105 const double df = newSamplingFrequency / nfft;
106 /*
107 The number of points on the octave scale.
108 */
109 const double fminl2 = NUMlog2 (pitchFloor), fmaxl2 = NUMlog2 (maximumFrequency);
110 const integer numberOfFrequencyPoints = Melder_ifloor ((fmaxl2 - fminl2) * numberOfPointsPerOctave);
111 const double dfl2 = (fmaxl2 - fminl2) / (numberOfFrequencyPoints - 1);
112
113 autoSound sound = Sound_resample (me, newSamplingFrequency, 50);
114 integer numberOfFrames;
115 double firstTime;
116 Sampled_shortTermAnalysis (sound.get(), windowDuration, timeStep, & numberOfFrames, & firstTime);
117 autoSound fftframe = Sound_createSimple (1, fftframeDuration, newSamplingFrequency);
118 autoSound analysisframe = Sound_createSimple (1, frameDuration, newSamplingFrequency);
119 autoSound hamming = Sound_createHamming (frameDuration, newSamplingFrequency);
120 autoPitch thee = Pitch_create (my xmin, my xmax, numberOfFrames, timeStep, firstTime, pitchCeiling, maxnCandidates);
121 autoVEC cc = zero_VEC (numberOfFrames);
122 autoVEC specAmp = raw_VEC (nfft2);
123 autoVEC fl2 = raw_VEC (nfft2);
124 autoVEC yv2 = raw_VEC (nfft2);
125 autoVEC arctg = raw_VEC (numberOfFrequencyPoints);
126 autoVEC al2 = raw_VEC (numberOfFrequencyPoints);
127
128 Melder_assert (fftframe -> nx >= numberOfSamples);
129 Melder_assert (hamming -> nx == numberOfSamples);
130 Melder_assert (analysisframe -> nx == numberOfSamples);
131 /*
132 Compute the absolute value of the globally largest amplitude w.r.t. the global mean.
133 */
134 const double globalMean = Sound_approximateLocalSampleMean (sound.get(), sound -> xmin, sound -> xmax);
135 const double globalPeak = Sound_localPeak (sound.get(), sound -> xmin, sound -> xmax, globalMean);
136 /*
137 For the cubic spline interpolation we need the frequencies on an octave
138 scale, i.e., a log2 scale. All frequencies should be DIFFERENT, otherwise
139 the cubic spline interpolation will give corrupt results.
140 Because log2(f==0) is not defined, we use the heuristic: f [2] - f [1] == f [3] - f [2].
141 */
142 for (integer i = 2; i <= nfft2; i ++)
143 fl2 [i] = NUMlog2 ((i - 1) * df);
144 fl2 [1] = 2.0 * fl2 [2] - fl2 [3];
145 /*
146 Calculate frequencies regularly spaced on a log2-scale and the frequency weighting function.
147 */
148 for (integer i = 1; i <= numberOfFrequencyPoints; i ++)
149 arctg [i] = 0.5 + atan (3.0 * (i - atans) / numberOfPointsPerOctave) / NUMpi;
150 /*
151 Perform the analysis on all frames.
152 */
153 for (integer iframe = 1; iframe <= numberOfFrames; iframe ++) {
154 const Pitch_Frame pitchFrame = & thy frames [iframe];
155 const double tmid = Sampled_indexToX (thee.get(), iframe); // The center of this frame
156 /*
157 Copy a frame from the sound, apply a hamming window. Get local 'intensity'
158 */
159 Sound_into_Sound (sound.get(), analysisframe.get(), tmid - halfWindow);
160 Sounds_multiply (analysisframe.get(), hamming.get());
161 const double localMean = Sound_approximateLocalSampleMean (sound.get(), tmid - 3.0 * halfWindow, tmid + 3.0 * halfWindow);
162 const double localPeak = Sound_localPeak (sound.get(), tmid - halfWindow, tmid + halfWindow, localMean);
163 pitchFrame -> intensity = localPeak > globalPeak ? 1.0 : localPeak / globalPeak;
164 /*
165 Get the Fourier spectrum.
166 */
167 fftframe -> z [1].part (1, analysisframe -> nx) <<= analysisframe -> z [1]; //
168 autoSpectrum spec = Sound_to_Spectrum (fftframe.get(), true);
169 Melder_assert (spec -> nx == nfft2);
170 /*
171 From complex spectrum to amplitude spectrum.
172 */
173 for (integer j = 1; j <= nfft2; j ++) {
174 const double rs = spec -> z [1] [j], is = spec -> z [2] [j];
175 specAmp [j] = hypot (rs, is);
176 }
177 /*
178 Enhance the peaks in the spectrum.
179 */
180 spec_enhance_SHS (specAmp.get());
181 /*
182 Smooth the enhanced spectrum.
183 */
184 spec_smoooth_SHS (specAmp.get());
185 /*
186 Go to a logarithmic scale and perform cubic spline interpolation to get
187 spectral values for the increased number of frequency points.
188 */
189 NUMcubicSplineInterpolation_getSecondDerivatives (yv2.get(), fl2.get(), specAmp.get(), 1e30, 1e30);
190 for (integer j = 1; j <= numberOfFrequencyPoints; j ++) {
191 const double f = fminl2 + (j - 1) * dfl2;
192 al2 [j] = NUMcubicSplineInterpolation (fl2.get(), specAmp.get(), yv2.get(), f);
193 }
194 /*
195 Multiply by frequency selectivity of the auditory system.
196 */
197 for (integer j = 1; j <= numberOfFrequencyPoints; j ++)
198 al2 [j] = ( al2 [j] > 0.0 ? al2 [j] * arctg [j] : 0.0 );
199 /*
200 The subharmonic summation. Shift spectra in octaves and sum.
201 */
202 Pitch_Frame_init (pitchFrame, maxnCandidates);
203 autoVEC sumspec = zero_VEC (numberOfFrequencyPoints);
204 pitchFrame -> candidates. resize (pitchFrame -> nCandidates = 0); // !!!!!
205
206 double hm = 1.0;
207 for (integer m = 1; m <= maxnSubharmonics + 1; m ++) {
208 const integer kb = 1 + Melder_ifloor (numberOfPointsPerOctave * NUMlog2 (m));
209 for (integer k = kb; k <= numberOfFrequencyPoints; k ++)
210 sumspec [k - kb + 1] += al2 [k] * hm;
211 hm *= compressionFactor;
212 }
213 /*
214 First register the voiceless candidate (always present).
215 */
216 Pitch_Frame_addPitch (pitchFrame, 0.0, 0.0, maxnCandidates);
217 /*
218 Get the best local estimates for the pitch as the maxima of the
219 subharmonic sum spectrum by parabolic interpolation on three points:
220 The formula for a parabola with a maximum is:
221 y(x) = a - b (x - c)^2 with a, b, c >= 0
222 The three points are (-x, y1), (0, y2) and (x, y3).
223 The solution for a (the maximum) and c (the position) is:
224 a = (2 y1 (4 y2 + y3) - y1^2 - (y3 - 4 y2)^2)/( 8 (y1 - 2 y2 + y3)
225 c = dx (y1 - y3) / (2 (y1 - 2 y2 + y3))
226 (b = (2 y2 - y1 - y3) / (2 dx^2) )
227 */
228 for (integer k = 2; k <= numberOfFrequencyPoints - 1; k ++) {
229 const double y1 = sumspec [k - 1], y2 = sumspec [k], y3 = sumspec [k + 1];
230 if (y2 > y1 && y2 >= y3) {
231 const double denum = y1 - 2.0 * y2 + y3, tmp = y3 - 4.0 * y2;
232 const double x = dfl2 * (y1 - y3) / (2.0 * denum);
233 const double f = pow (2.0, fminl2 + (k - 1) * dfl2 + x);
234 const double strength = (2.0 * y1 * (4.0 * y2 + y3) - y1 * y1 - tmp * tmp) / (8.0 * denum);
235 Pitch_Frame_addPitch (pitchFrame, f, strength, maxnCandidates);
236 }
237 }
238 /*
239 Check whether f0 corresponds to an actual periodicity T = 1 / f0:
240 correlate two signal periods of duration T, one starting at the
241 middle of the interval and one starting T seconds before.
242 If there is periodicity the correlation coefficient should be high.
243
244 However, some sounds do not show any regularity, or very low
245 frequency and regularity, and nevertheless have a definite
246 pitch, e.g. Shepard sounds.
247 */
248 double pitch_strength, f0;
249 Pitch_Frame_getPitch (pitchFrame, & f0, & pitch_strength);
250 if (f0 > 0.0)
251 cc [iframe] = Sound_correlateParts (sound.get(), tmid - 1.0 / f0, tmid, 1.0 / f0);
252 }
253 /*
254 Base V/UV decision on correlation coefficients.
255 Resize the pitch strengths w.r.t. the cc.
256 */
257 constexpr double vuvCriterion = 0.52;
258 for (integer i = 1; i <= numberOfFrames; i ++)
259 Pitch_Frame_resizeStrengths (& thy frames [i], cc [i], vuvCriterion);
260
261 return thee;
262 } catch (MelderError) {
263 Melder_throw (me, U": no Pitch (shs) created.");
264 }
265 }
266
267 autoPitch Sound_to_Pitch_SPINET (Sound me, double timeStep, double windowDuration, double minimumFrequencyHz, double maximumFrequencyHz, integer nFilters, double ceiling, int maxnCandidates) {
268 try {
269 autoSPINET him = Sound_to_SPINET (me, timeStep, windowDuration, minimumFrequencyHz, maximumFrequencyHz, nFilters, 0.4, 0.6);
270 autoPitch thee = SPINET_to_Pitch (him.get(), 0.15, ceiling, maxnCandidates);
271 return thee;
272 } catch (MelderError) {
273 Melder_throw (me, U": no Pitch (SPINET) created.");
274 }
275 }
276
277 /* End of file Sound_to_Pitch2.cpp */