Debian Codegraph @

fon/Sound_and_Spectrogram.cpp

raw symbols SCIP
1 /* Sound_and_Spectrogram.cpp
2 *
3 * Copyright (C) 1992-2011,2014-2020,2023,2025 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 #include "Sound_and_Spectrogram.h"
20 #include "NUM2.h"
21
22 #include "enums_getText.h"
23 #include "Sound_and_Spectrogram_enums.h"
24 #include "enums_getValue.h"
25 #include "Sound_and_Spectrogram_enums.h"
26
27 autoSpectrogram Sound_to_Spectrogram_e (
28 const constSound me,
29 const double effectiveAnalysisWidth,
30 /* mutable clip */ double fmax,
31 const double minimumTimeStep1,
32 const double minimumFreqStep1,
33 const kSound_to_Spectrogram_windowShape windowType,
34 const double maximumTimeOversampling,
35 const double maximumFreqOversampling
36 ) {
37 try {
38 const double nyquist = 0.5 / my dx;
39 const double physicalAnalysisWidth =
40 ( windowType == kSound_to_Spectrogram_windowShape::GAUSSIAN ? 2.0 * effectiveAnalysisWidth : effectiveAnalysisWidth );
41 const double effectiveTimeWidth = effectiveAnalysisWidth / sqrt (NUMpi);
42 const double effectiveFreqWidth = 1.0 / effectiveTimeWidth;
43 const double minimumTimeStep2 = effectiveTimeWidth / maximumTimeOversampling;
44 const double minimumFreqStep2 = effectiveFreqWidth / maximumFreqOversampling;
45 const double timeStep = std::max (minimumTimeStep1, minimumTimeStep2);
46 double freqStep = std::max (minimumFreqStep1, minimumFreqStep2);
47 volatile const double physicalDuration = my dx * my nx; // volatile, because we need to truncate to 64 bits
48
49 /*
50 Compute the time sampling.
51 */
52 const integer approximateNumberOfSamplesPerWindow = Melder_ifloor (physicalAnalysisWidth / my dx);
53 const integer halfnsamp_window = approximateNumberOfSamplesPerWindow / 2 - 1;
54 const integer nsamp_window = halfnsamp_window * 2;
55 if (nsamp_window < 1)
56 Melder_throw (U"Your analysis window is too short: less than two samples.");
57 if (physicalAnalysisWidth > physicalDuration)
58 Melder_throw (U"Your sound is too short:\n"
59 U"it should be at least as long as ",
60 windowType == kSound_to_Spectrogram_windowShape::GAUSSIAN ? U"two window lengths." : U"one window length.");
61 const integer numberOfTimes = 1 + Melder_ifloor ((physicalDuration - physicalAnalysisWidth) / timeStep); // >= 1
62 const double t1 = my x1 + 0.5 * ((my nx - 1) * my dx - (numberOfTimes - 1) * timeStep); // centre of first frame
63
64 /*
65 Compute the frequency sampling of the FFT spectrum.
66 */
67 if (fmax <= 0.0 || fmax > nyquist)
68 fmax = nyquist;
69 integer numberOfFreqs = Melder_ifloor (fmax / freqStep);
70 if (numberOfFreqs < 1)
71 Melder_throw (U"No frequency bins in spectrogram analysis. "
72 U"Raise the maximum frequency, or raise the window length. (Or lower the frequency step, if you have that.)");
73 integer nsampFFT = 1;
74 while (nsampFFT < nsamp_window || nsampFFT < 2 * numberOfFreqs * (nyquist / fmax))
75 nsampFFT *= 2;
76 const integer half_nsampFFT = nsampFFT / 2;
77
78 /*
79 Compute the frequency sampling of the spectrogram.
80 */
81 const integer binWidth_samples = std::max (1_integer, Melder_ifloor (freqStep * my dx * nsampFFT));
82 double binWidth_hertz = 1.0 / (my dx * nsampFFT);
83 freqStep = binWidth_samples * binWidth_hertz;
84 numberOfFreqs = Melder_ifloor (fmax / freqStep);
85 //Melder_assert (numberOfFreqs >= 1);
86 if (numberOfFreqs < 1)
87 Melder_throw (U"No frequency bins in spectrogram analysis. "
88 U"Raise the maximum frequency, or raise the window length. (Or lower the frequency step, if you have that.)");
89
90 autoSpectrogram thee = Spectrogram_create (my xmin, my xmax, numberOfTimes, timeStep, t1,
91 0.0, fmax, numberOfFreqs, freqStep, 0.5 * (freqStep - binWidth_hertz));
92
93 autoVEC window = zero_VEC (nsamp_window);
94 longdouble windowssq = 0.0;
95 for (integer i = 1; i <= nsamp_window; i ++) {
96 const double nSamplesPerWindow_f = physicalAnalysisWidth / my dx;
97 switch (windowType) {
98 case kSound_to_Spectrogram_windowShape::SQUARE: {
99 window [i] = 1.0;
100 } break;
101 case kSound_to_Spectrogram_windowShape::HAMMING: {
102 const double phase = (double) i / nSamplesPerWindow_f; // 0 .. 1
103 window [i] = 0.54 - 0.46 * cos (2.0 * NUMpi * phase);
104 } break;
105 case kSound_to_Spectrogram_windowShape::BARTLETT: {
106 const double phase = (double) i / nSamplesPerWindow_f; // 0 .. 1
107 window [i] = 1.0 - fabs ((2.0 * phase - 1.0));
108 } break;
109 case kSound_to_Spectrogram_windowShape::WELCH: {
110 const double phase = (double) i / nSamplesPerWindow_f; // 0 .. 1
111 window [i] = 1.0 - (2.0 * phase - 1.0) * (2.0 * phase - 1.0);
112 } break;
113 case kSound_to_Spectrogram_windowShape::HANNING: {
114 const double phase = (double) i / nSamplesPerWindow_f; // 0 .. 1
115 window [i] = 0.5 * (1.0 - cos (2.0 * NUMpi * phase));
116 } break;
117 case kSound_to_Spectrogram_windowShape::GAUSSIAN: {
118 const double imid = 0.5 * (double) (nsamp_window + 1), edge = exp (-12.0);
119 const double phase = ((double) i - imid) / nSamplesPerWindow_f; // -0.5 .. +0.5
120 window [i] = (exp (-48.0 * phase * phase) - edge) / (1.0 - edge);
121 break;
122 }
123 break; default:
124 window [i] = 1.0;
125 }
126 windowssq += window [i] * window [i];
127 }
128 const double oneByBinWidth = 1.0 / double (windowssq) / binWidth_samples;
129
130 autoMelderProgress progress (U"Sound to Spectrogram...");
131
132 MelderThread_PARALLEL (numberOfTimes, 15) {
133 autoVEC data = zero_VEC (nsampFFT);
134 autoVEC spectrum = zero_VEC (half_nsampFFT + 1);
135 autoNUMFourierTable fftTable = NUMFourierTable_create (nsampFFT);
136 MelderThread_FOR (iframe) {
137 const double t = Sampled_indexToX (thee.get(), iframe);
138 const integer leftSample = Sampled_xToLowIndex (me, t), rightSample = leftSample + 1;
139 const integer startSample = rightSample - halfnsamp_window;
140 const integer endSample = leftSample + halfnsamp_window;
141 Melder_assert (startSample >= 1);
142 Melder_assert (endSample <= my nx);
143
144 spectrum.all() <<= 0.0;
145 /*
146 For multichannel sounds, the power spectrogram should represent the
147 average power in the channels,
148 so that the result for a stereo sound in which the
149 left channel has the same waveform as the right channel,
150 is identical to the result for the corresponding mono (= averaged) sound.
151 Averaging starts by adding up the powers of the channels.
152 */
153 for (integer channel = 1; channel <= my ny; channel ++) {
154 for (integer j = 1, i = startSample; j <= nsamp_window; j ++)
155 data [j] = my z [channel] [i ++] * window [j];
156 for (integer j = nsamp_window + 1; j <= nsampFFT; j ++)
157 data [j] = 0.0;
158
159 if (MelderThread_IS_MASTER) { // then we can interact with the GUI
160 const double estimatedProgress = MelderThread_ESTIMATED_PROGRESS;
161 Melder_progress (estimatedProgress,
162 U"Sound to Spectrogram: analysed approximately ", Melder_iround (numberOfTimes * estimatedProgress),
163 U" out of ", numberOfTimes, U" frames"
164 );
165 }
166
167 /*
168 Compute the Fast Fourier Transform of the frame.
169 */
170 NUMfft_forward (fftTable.get(), data.get()); // data := complex spectrum
171
172 /*
173 Convert from complex to power spectrum,
174 accumulating the power spectra of the channels.
175 */
176 spectrum [1] += data [1] * data [1]; // DC component
177 for (integer i = 2; i <= half_nsampFFT; i ++)
178 spectrum [i] += data [i + i - 2] * data [i + i - 2] + data [i + i - 1] * data [i + i - 1];
179 spectrum [half_nsampFFT + 1] += data [nsampFFT] * data [nsampFFT]; // Nyquist frequency. Correct??
180 }
181 /*
182 Power averaging ends by dividing the summed power by the number of channels,
183 */
184 if (my ny > 1 )
185 spectrum.all() /= my ny;
186
187 /*
188 Binning.
189 */
190 for (integer iband = 1; iband <= numberOfFreqs; iband ++) {
191 const integer lowerSample = (iband - 1) * binWidth_samples + 1;
192 const integer higherSample = lowerSample + binWidth_samples;
193 const double power = NUMsum (spectrum.part (lowerSample, higherSample - 1));
194 thy z [iband] [iframe] = power * oneByBinWidth;
195 }
196 }
197 } MelderThread_ENDPARALLEL
198 return thee;
199 } catch (MelderError) {
200 Melder_throw (me, U": spectrogram analysis not performed.");
201 }
202 }
203
204 autoSound Spectrogram_to_Sound (Spectrogram me, double fsamp) {
205 try {
206 const double dt = 1.0 / fsamp;
207 const integer n = Melder_ifloor ((my xmax - my xmin) / dt);
208 if (n < 0)
209 return autoSound ();
210 autoSound you = Sound_create (1, my xmin, my xmax, n, dt, 0.5 * dt);
211 for (integer i = 1; i <= n; i ++) {
212 const double t = Sampled_indexToX (you.get(), i);
213 const double rframe = Sampled_xToIndex (me, t);
214 if (rframe < 1 || rframe >= my nx)
215 continue;
216 const integer leftFrame = Melder_ifloor (rframe);
217 const integer rightFrame = leftFrame + 1;
218 const double phase = rframe - leftFrame;
219 longdouble value = 0.0;
220 for (integer j = 1; j <= my ny; j ++) {
221 const double f = Matrix_rowToY (me, j);
222 const double power = my z [j] [leftFrame] * (1.0 - phase) + my z [j] [rightFrame] * phase;
223 value += sqrt (power) * sin (2 * NUMpi * f * t);
224 }
225 your z [1] [i] = double (value);
226 }
227 return you;
228 } catch (MelderError) {
229 Melder_throw (me, U": not converted to Sound.");
230 }
231 }
232
233 /* End of file Sound_and_Spectrogram.cpp */