Debian Codegraph @

fon/Sound.cpp

raw
1 /* Sound.cpp
2 *
3 * Copyright (C) 1992-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 /*
20 * a selection of changes:
21 * pb 2006/12/31 stereo
22 * pb 2010/03/26 Sounds_convolve, Sounds_crossCorrelate, Sound_autocorrelate
23 */
24
25 #include "Sound.h"
26 #include "Sound_extensions.h"
27 #include "NUM2.h"
28
29 #include "enums_getText.h"
30 #include "Sound_enums.h"
31 #include "enums_getValue.h"
32 #include "Sound_enums.h"
33
34 Thing_implement (Sound, Vector, 2);
35
36 void structSound :: v1_info () {
37 structDaata :: v1_info ();
38 MelderInfo_writeLine (U"Number of channels: ", our ny, our ny == 1 ? U" (mono)" : our ny == 2 ? U" (stereo)" : U"");
39 MelderInfo_writeLine (U"Time domain:");
40 MelderInfo_writeLine (U" Start time: ", our xmin, U" seconds");
41 MelderInfo_writeLine (U" End time: ", our xmax, U" seconds");
42 MelderInfo_writeLine (U" Total duration: ", our xmax - our xmin, U" seconds");
43 MelderInfo_writeLine (U"Time sampling:");
44 MelderInfo_writeLine (U" Number of samples: ", our nx);
45 MelderInfo_writeLine (U" Sampling period: ", our dx, U" seconds");
46 MelderInfo_writeLine (U" Sampling frequency: ", Melder_single (1.0 / our dx), U" Hz");
47 MelderInfo_writeLine (U" First sample centred at: ", our x1, U" seconds");
48 integer numberOfCells = our nx * our ny;
49 bool thereAreEnoughObservationsToComputeFirstOrderOverallStatistics = ( numberOfCells >= 1 );
50 if (thereAreEnoughObservationsToComputeFirstOrderOverallStatistics) {
51 double minimum_Pa = our z [1] [1], maximum_Pa = minimum_Pa;
52 longdouble sum_Pa = 0.0, sumOfSquares_Pa2 = 0.0;
53 for (integer channel = 1; channel <= our ny; channel ++) {
54 constVEC const& waveform_Pa = our z [channel];
55 for (integer i = 1; i <= our nx; i ++) {
56 const double value_Pa = waveform_Pa [i];
57 sum_Pa += value_Pa;
58 sumOfSquares_Pa2 += value_Pa * value_Pa;
59 if (value_Pa < minimum_Pa)
60 minimum_Pa = value_Pa;
61 if (value_Pa > maximum_Pa)
62 maximum_Pa = value_Pa;
63 }
64 }
65 MelderInfo_writeLine (U"Amplitude:");
66 MelderInfo_writeLine (U" Minimum: ", Melder_single (minimum_Pa), U" Pascal");
67 MelderInfo_writeLine (U" Maximum: ", Melder_single (maximum_Pa), U" Pascal");
68 const double mean_Pa = (double) sum_Pa / numberOfCells;
69 MelderInfo_writeLine (U" Mean: ", Melder_single (mean_Pa), U" Pascal");
70 const double meanSquare_Pa2 = (double) sumOfSquares_Pa2 / numberOfCells;
71 const double rootMeanSquare_Pa = sqrt (meanSquare_Pa2);
72 MelderInfo_writeLine (U" Root-mean-square: ", Melder_single (rootMeanSquare_Pa), U" Pascal");
73 const double energy_Pa2s = (double) sumOfSquares_Pa2 * our dx / our ny; // Pa2 s = kg2 m-2 s-3
74 MelderInfo_write (U"Total energy: ", Melder_single (energy_Pa2s), U" Pascal\u00B2 sec");
75 const double rho_c = 400.0; // rho = 1.14 kg m-3; c = 353 m s-1; [rho c] = kg m-2 s-1
76 const double energy_J_m2 = energy_Pa2s / rho_c; // kg s-2 = Joule m-2
77 MelderInfo_writeLine (U" (energy in air: ", Melder_single (energy_J_m2), U" Joule/m\u00B2)");
78 const double physicalDuration_s = our dx * our nx;
79 const double power_W_m2 = energy_J_m2 / physicalDuration_s; // kg s-3 = Watt/m2
80 MelderInfo_write (U"Mean power (intensity) in air: ", Melder_single (power_W_m2), U" Watt/m\u00B2");
81 if (power_W_m2 != 0.0) {
82 const double referencePower_W_m2 = 1.0e-12; // this equals the square of 2.0e-5 Pa, divided by rho c
83 const double power_dB = 10.0 * log10 (power_W_m2 / referencePower_W_m2);
84 MelderInfo_writeLine (U" = ", Melder_half (power_dB), U" dB");
85 } else {
86 MelderInfo_writeLine (U"");
87 }
88 }
89 const bool thereAreEnoughObservationsToComputeSecondOrderChannelStatistics = ( our nx >= 2 );
90 if (thereAreEnoughObservationsToComputeSecondOrderChannelStatistics) {
91 for (integer channel = 1; channel <= our ny; channel ++) {
92 const double stdev = NUMstdev (our z [channel]);
93 MelderInfo_writeLine (U"Standard deviation in channel ", channel, U": ", Melder_single (stdev), U" Pascal");
94 }
95 }
96 }
97
98 double structSound :: v_getMatrix (const integer irow, const integer icol) const {
99 if (irow < 1 || irow > our ny) {
100 if (irow == 0) {
101 if (icol < 1 || icol > nx)
102 return 0.0;
103 if (our ny == 1)
104 return our z [1] [icol]; // optimization
105 if (our ny == 2)
106 return 0.5 * (our z [1] [icol] + our z [2] [icol]); // optimization
107 longdouble sum = 0.0;
108 for (integer channel = 1; channel <= ny; channel ++)
109 sum += our z [channel] [icol];
110 return (double) sum / our ny;
111 }
112 return 0.0;
113 }
114 if (icol < 1 || icol > nx)
115 return 0.0;
116 return our z [irow] [icol];
117 }
118
119 double structSound :: v_getFunction2 (const double x, const double y) const {
120 const integer channel = Melder_ifloor (y);
121 if (channel < 0 || channel > our ny || y != (double) channel)
122 return 0.0;
123 return v_getFunction1 (channel, x);
124 }
125
126 autoSound Sound_create (integer numberOfChannels, double xmin, double xmax, integer nx, double dx, double x1) {
127 try {
128 autoSound me = Thing_new (Sound);
129 Matrix_init (me.get(), xmin, xmax, nx, dx, x1, 1, numberOfChannels, numberOfChannels, 1, 1);
130 return me;
131 } catch (MelderError) {
132 Melder_throw (U"Sound not created.");
133 }
134 }
135
136 autoSound Sound_createSimple (integer numberOfChannels, double duration, double samplingFrequency) {
137 Melder_assert (duration >= 0.0);
138 Melder_assert (samplingFrequency > 0.0);
139 const double numberOfSamples_real = round (duration * samplingFrequency);
140 if (numberOfSamples_real > double (INT32_MAX))
141 Melder_throw (U"Cannot create sounds with more than ", Melder_bigInteger (INT32_MAX), U" samples, because they cannot be saved to disk.");
142 return Sound_create (numberOfChannels, 0.0, duration, (integer) (int32) numberOfSamples_real,
143 1.0 / samplingFrequency, 0.5 / samplingFrequency);
144 }
145
146 autoSound Sound_convertToMono (constSound me) {
147 if (my ny == 1)
148 return Data_copy (me); // optimization
149 try {
150 autoSound thee = Sound_create (1, my xmin, my xmax, my nx, my dx, my x1);
151 if (my ny == 2) { // optimization
152 for (integer i = 1; i <= my nx; i ++)
153 thy z [1] [i] = 0.5 * (my z [1] [i] + my z [2] [i]);
154 } else {
155 for (integer i = 1; i <= my nx; i ++) {
156 longdouble sum = my z [1] [i] + my z [2] [i] + my z [3] [i];
157 for (integer channel = 4; channel <= my ny; channel ++)
158 sum += my z [channel] [i];
159 thy z [1] [i] = double (sum / my ny);
160 }
161 }
162 return thee;
163 } catch (MelderError) {
164 Melder_throw (me, U": not converted to mono.");
165 }
166 }
167
168 autoSound Sound_convertToStereo (constSound me) {
169 if (my ny == 2)
170 return Data_copy (me);
171 try {
172 if (my ny > 2)
173 Melder_throw (U"The Sound has ", my ny, U" channels; don't know which to choose.");
174 Melder_assert (my ny == 1);
175 autoSound thee = Sound_create (2, my xmin, my xmax, my nx, my dx, my x1);
176 for (integer i = 1; i <= my nx; i ++)
177 thy z [1] [i] = thy z [2] [i] = my z [1] [i];
178 return thee;
179 } catch (MelderError) {
180 Melder_throw (me, U": not converted to stereo.");
181 }
182 }
183
184 autoSound Sounds_combineToStereo (OrderedOf<structSound>* me) {
185 try {
186 integer totalNumberOfChannels = 0;
187 double sharedSamplingPeriod = 0.0;
188 for (integer isound = 1; isound <= my size; isound ++) {
189 Sound sound = my at [isound];
190 totalNumberOfChannels += sound -> ny;
191 if (sharedSamplingPeriod == 0.0) {
192 sharedSamplingPeriod = sound -> dx;
193 } else if (sound -> dx != sharedSamplingPeriod) {
194 Melder_throw (U"To combine sounds, their sampling frequencies should be equal.\n"
195 U"You could resample one or more of the sounds before combining.");
196 }
197 }
198 Melder_assert (my size > 0);
199 double sharedMinimumTime = my at [1] -> xmin;
200 double sharedMaximumTime = my at [1] -> xmax;
201 for (integer isound = 2; isound <= my size; isound ++) {
202 Sound sound = my at [isound];
203 if (sound -> xmin < sharedMinimumTime)
204 sharedMinimumTime = sound -> xmin;
205 if (sound -> xmax > sharedMaximumTime)
206 sharedMaximumTime = sound -> xmax;
207 }
208 autoINTVEC numberOfInitialZeroes = zero_INTVEC (my size);
209 integer sharedNumberOfSamples = 0;
210 double sumOfFirstTimes = 0.0;
211 for (integer isound = 1; isound <= my size; isound ++) {
212 Sound sound = my at [isound];
213 numberOfInitialZeroes [isound] = Melder_ifloor ((sound -> xmin - sharedMinimumTime) / sharedSamplingPeriod);
214 const double newFirstTime = sound -> x1 - sound -> dx * numberOfInitialZeroes [isound];
215 sumOfFirstTimes += newFirstTime;
216 const integer newNumberOfSamplesThroughLastNonzero = sound -> nx + numberOfInitialZeroes [isound];
217 if (newNumberOfSamplesThroughLastNonzero > sharedNumberOfSamples)
218 sharedNumberOfSamples = newNumberOfSamplesThroughLastNonzero;
219 }
220 const double sharedTimeOfFirstSample = sumOfFirstTimes / my size; // this is an approximation
221 autoSound thee = Sound_create (totalNumberOfChannels, sharedMinimumTime, sharedMaximumTime,
222 sharedNumberOfSamples, sharedSamplingPeriod, sharedTimeOfFirstSample);
223 integer channelNumber = 0;
224 for (integer isound = 1; isound <= my size; isound ++) {
225 Sound sound = my at [isound];
226 const integer offset = numberOfInitialZeroes [isound];
227 for (integer ichan = 1; ichan <= sound -> ny; ichan ++) {
228 channelNumber ++;
229 for (integer isamp = 1; isamp <= sound -> nx; isamp ++)
230 thy z [channelNumber] [isamp + offset] = sound -> z [ichan] [isamp];
231 }
232 }
233 return thee;
234 } catch (MelderError) {
235 Melder_throw (U"Sounds not combined to stereo.");
236 }
237 }
238
239 static void Sound_checkChannelNumberWithinRange (constSound me, integer channel) {
240 Melder_require (channel > 0,
241 U"Your channel number is ", channel, U", but it should be positive.");
242 Melder_require (channel <= my ny,
243 U"Your channel number is ", channel,
244 U", but it should not be greater than my number of channels, which is ",
245 my ny, U"."
246 );
247 }
248
249 autoSound Sound_extractChannel (constSound me, integer channel) {
250 try {
251 Sound_checkChannelNumberWithinRange (me, channel);
252 autoSound you = Sound_create (1, my xmin, my xmax, my nx, my dx, my x1);
253 your z.row (1) <<= my z.row (channel);
254 return you;
255 } catch (MelderError) {
256 Melder_throw (me, U": channel ", channel, U" not extracted.");
257 }
258 }
259
260 autoSound Sound_extractChannels (constSound me, constINTVECVU const& channels) {
261 try {
262 Melder_require (channels.size > 0,
263 U"The number of channels should be greater than 0.");
264 autoSound you = Sound_create (channels.size, my xmin, my xmax, my nx, my dx, my x1);
265 for (integer ichan = 1; ichan <= channels.size; ichan ++) {
266 Sound_checkChannelNumberWithinRange (me, channels [ichan]);
267 your z.row (ichan) <<= my z.row (channels [ichan]);
268 }
269 return you;
270 } catch (MelderError) {
271 Melder_throw (me, U": channels not extracted.");
272 }
273 }
274
275 void Sound_shiftTimesToBetweenZeroAndPhysicalDuration (mutableSound me) {
276 my xmin = 0.0;
277 my x1 = 0.5 * my dx;
278 my xmax = my nx * my dx;
279 }
280
281 double Sound_getRootMeanSquare (constSound me, double tmin, double tmax) {
282 /* mutable accumulate */ double meanOfSquared = 0.0;
283 for (integer ichan = 1; ichan <= my ny; ichan ++)
284 meanOfSquared += Sampled_getMeanOfSquared (me, tmin, tmax, ichan, 0, false);
285 return isdefined (meanOfSquared) ? sqrt (meanOfSquared / my ny) : undefined;
286 }
287
288 double Sound_getEnergy (constSound me, double tmin, double tmax) {
289 /* mutable accumulate */ double integralOfSquared = 0.0;
290 for (integer ichan = 1; ichan <= my ny; ichan ++)
291 integralOfSquared += Sampled_getIntegralOfSquared (me, tmin, tmax, ichan, 0, false);
292 return isdefined (integralOfSquared) ? integralOfSquared / my ny : undefined;
293 }
294
295 double Sound_getPower (constSound me, double tmin, double tmax) {
296 /* mutable accumulate */ double meanOfSquared = 0.0;
297 for (integer ichan = 1; ichan <= my ny; ichan ++)
298 meanOfSquared += Sampled_getMeanOfSquared (me, tmin, tmax, ichan, 0, false);
299 return isdefined (meanOfSquared) ? meanOfSquared / my ny : undefined;
300 }
301
302 double Sound_getEnergyInAir (constSound me) {
303 /* mutable accumulate */ double integralOfSquared = 0.0;
304 for (integer ichan = 1; ichan <= my ny; ichan ++)
305 integralOfSquared += Sampled_getIntegralOfSquared (me, 0.0, 0.0, ichan, 0, false);
306 return isdefined (integralOfSquared) ? integralOfSquared / (400.0 * my ny) : undefined;
307 }
308
309 double Sound_getIntensity_dB (constSound me) {
310 /* mutable accumulate */ double meanOfSquared = 0.0;
311 for (integer ichan = 1; ichan <= my ny; ichan ++)
312 meanOfSquared += Sampled_getMeanOfSquared (me, 0.0, 0.0, ichan, 0, false);
313 return isdefined (meanOfSquared) && meanOfSquared != 0.0 ? 10.0 * log10 (meanOfSquared / (4.0e-10 * my ny)) : undefined;
314 }
315
316 double Sound_getPowerInAir (constSound me) {
317 /* mutable accumulate */ double meanOfSquared = 0.0;
318 for (integer ichan = 1; ichan <= my ny; ichan ++)
319 meanOfSquared += Sampled_getMeanOfSquared (me, 0.0, 0.0, ichan, 0, false);
320 return ( isdefined (meanOfSquared) ? meanOfSquared / (400.0 * my ny) : undefined );
321 }
322
323 autoSound Matrix_to_Sound_mono (constMatrix me, integer rowNumber) {
324 try {
325 autoSound thee = Sound_create (1, my xmin, my xmax, my nx, my dx, my x1);
326 if (rowNumber < 0)
327 rowNumber = my ny + 1 + rowNumber;
328 Melder_clip (1_integer, & rowNumber, my ny);
329 thy z.row (1) <<= my z.row (rowNumber);
330 return thee;
331 } catch (MelderError) {
332 Melder_throw (me, U": not converted to Sound.");
333 }
334 }
335
336 autoSound Matrix_to_Sound (constMatrix me) {
337 try {
338 autoSound thee = Thing_new (Sound);
339 my structMatrix :: v1_copy (thee.get());
340 return thee;
341 } catch (MelderError) {
342 Melder_throw (me, U": not converted to Sound.");
343 }
344 }
345
346 autoMatrix Sound_to_Matrix (constSound me) {
347 try {
348 autoMatrix thee = Thing_new (Matrix);
349 my structMatrix :: v1_copy (thee.get());
350 return thee;
351 } catch (MelderError) {
352 Melder_throw (me, U": not converted to Matrix.");
353 }
354 }
355
356 autoSound Sound_upsample (constSound me) {
357 try {
358 constexpr integer antiTurnAround = 1000;
359 constexpr integer sampleRateFactor = 2;
360 constexpr integer numberOfPaddingSides = 2; // namely beginning and end
361 const integer nfft = Melder_iroundUpToPowerOfTwo (my nx + antiTurnAround * numberOfPaddingSides);
362 const double newDx = my dx / sampleRateFactor;
363 /*
364 The computation of the new x1 relies on the idea that the left edge
365 of the old first sample should coincide with the left edge of the new first sample
366 (typically, e.g. if the old first sample starts at zero, which is usual,
367 then the new first sample should also start at zero):
368 old x1 - 0.5 * old dx == new x1 - 0.5 * new dx
369 ==>
370 new x1 == old x1 - 0.5 * (old dx - new dx)
371 */
372 autoSound thee = Sound_create (my ny, my xmin, my xmax, my nx * sampleRateFactor,
373 newDx, my x1 - 0.5 * (my dx - newDx));
374 for (integer ichan = 1; ichan <= my ny; ichan ++) {
375 autoVEC data = zero_VEC (sampleRateFactor * nfft); // zeroing is important...
376 data.part (antiTurnAround + 1, antiTurnAround + my nx) <<= my z.row (ichan); // ...because this fills only part of the sound
377 NUMrealft (data.part (1, nfft), 1);
378 const integer imin = (integer) (nfft * 0.95);
379 for (integer i = imin + 1; i <= nfft; i ++)
380 data [i] *= ((double) (nfft - i)) / (nfft - imin);
381 data [2] = 0.0;
382 NUMrealft (data.get(), -1);
383 const double factor = 1.0 / nfft;
384 for (integer i = 1; i <= thy nx; i ++)
385 thy z [ichan] [i] = data [i + sampleRateFactor * antiTurnAround] * factor;
386 }
387 return thee;
388 } catch (MelderError) {
389 Melder_throw (me, U": not upsampled.");
390 }
391 }
392
393 autoSound Sound_resample (constSound me, double samplingFrequency, integer precision) {
394 const double upfactor = samplingFrequency * my dx;
395 if (fabs (upfactor - 2.0) < 1e-6)
396 return Sound_upsample (me);
397 if (fabs (upfactor - 1.0) < 1e-6)
398 return Data_copy (me);
399 try {
400 const integer numberOfSamples = Melder_iround ((my xmax - my xmin) * samplingFrequency);
401 if (numberOfSamples < 1)
402 Melder_throw (U"The resampled Sound would have no samples.");
403 autoSound filtered;
404 const bool weNeedAnAntiAliasingFilter = ( upfactor < 1.0 );
405 if (weNeedAnAntiAliasingFilter) {
406 constexpr integer antiTurnAround = 1000;
407 constexpr integer numberOfPaddingSides = 2; // namely beginning and end
408 const integer nfft = Melder_iroundUpToPowerOfTwo (my nx + antiTurnAround * numberOfPaddingSides);
409 autoVEC data = raw_VEC (nfft); // will be zeroed in every turn of the loop
410 filtered = Sound_create (my ny, my xmin, my xmax, my nx, my dx, my x1);
411 for (integer ichan = 1; ichan <= my ny; ichan ++) {
412 for (integer i = 1; i <= nfft; i ++)
413 data [i] = 0.0;
414 data.part (antiTurnAround + 1, antiTurnAround + my nx) <<= my z.row (ichan);
415 NUMrealft (data.get(), 1); // go to the frequency domain
416 for (integer i = Melder_ifloor (upfactor * nfft); i <= nfft; i ++)
417 data [i] = 0.0; // filter away high frequencies
418 data [2] = 0.0;
419 NUMrealft (data.get(), -1); // return to the time domain
420 const double factor = 1.0 / nfft;
421 const VEC to = filtered -> z.row (ichan);
422 for (integer i = 1; i <= my nx; i ++)
423 to [i] = data [i + antiTurnAround] * factor;
424 }
425 me = filtered.get(); // reference copy; remove at end
426 }
427 autoSound thee = Sound_create (my ny, my xmin, my xmax, numberOfSamples, 1.0 / samplingFrequency,
428 0.5 * (my xmin + my xmax - (numberOfSamples - 1) / samplingFrequency));
429 for (integer ichan = 1; ichan <= my ny; ichan ++) {
430 if (precision <= 1) {
431 for (integer i = 1; i <= numberOfSamples; i ++) {
432 const double x = Sampled_indexToX (thee.get(), i);
433 const double index = Sampled_xToIndex (me, x);
434 const integer leftSample = Melder_ifloor (index);
435 const double fraction = index - leftSample;
436 thy z [ichan] [i] = ( leftSample < 1 || leftSample >= my nx ? 0.0 :
437 (1 - fraction) * my z [ichan] [leftSample] + fraction * my z [ichan] [leftSample + 1] );
438 }
439 } else {
440 for (integer i = 1; i <= numberOfSamples; i ++) {
441 const double x = Sampled_indexToX (thee.get(), i);
442 const double index = Sampled_xToIndex (me, x);
443 thy z [ichan] [i] = NUM_interpolate_sinc (my z.row (ichan), index, precision);
444 }
445 }
446 }
447 return thee;
448 } catch (MelderError) {
449 Melder_throw (me, U": not resampled.");
450 }
451 }
452
453 autoSound Sounds_append (constSound me, double silenceDuration, constSound thee) {
454 try {
455 const integer nx_silence = Melder_iround (silenceDuration / my dx), nx = my nx + nx_silence + thy nx;
456 if (my ny != thy ny)
457 Melder_throw (U"The numbers of channels are not equal (e.g. one is mono, the other stereo).");
458 if (my dx != thy dx)
459 Melder_throw (U"The sampling frequencies are not equal.");
460 autoSound him = Sound_create (my ny, 0.0, nx * my dx, nx, my dx, 0.5 * my dx);
461 his z.verticalBand (1, my nx) <<= my z.all();
462 his z.verticalBand (my nx + nx_silence + 1, nx) <<= thy z.all();
463 return him;
464 } catch (MelderError) {
465 Melder_throw (me, U" & ", thee, U": not appended.");
466 }
467 }
468
469 autoSound Sounds_concatenate (SoundList list, double overlapTime) {
470 try {
471 integer sharedNumberOfChannels = 0, totalNumberOfSamples = 0;
472 double sharedTimeStep = 0.0;
473 for (integer i = 1; i <= list->size; i ++) {
474 const Sound sound = list->at [i];
475 if (sharedNumberOfChannels == 0) {
476 sharedNumberOfChannels = sound -> ny;
477 } else if (sound -> ny != sharedNumberOfChannels) {
478 Melder_throw (U"To concatenate sounds, their numbers of channels (mono, stereo) should be equal.");
479 }
480 if (sharedTimeStep == 0.0) {
481 sharedTimeStep = sound -> dx;
482 } else if (sound -> dx != sharedTimeStep) {
483 Melder_throw (U"To concatenate sounds, their sampling frequencies should be equal.\n"
484 U"You could resample one or more of the sounds before concatenating.");
485 }
486 totalNumberOfSamples += sound -> nx;
487 }
488 const integer numberOfSmoothingSamples = Melder_iround (overlapTime / sharedTimeStep);
489 totalNumberOfSamples -= numberOfSmoothingSamples * (list->size - 1);
490 Melder_require (totalNumberOfSamples > 0,
491 U"The joint overlap should not exceed the total duration of the sounds.\nChoose a shorter overlap time.");
492 autoSound thee = Sound_create (sharedNumberOfChannels, 0.0, totalNumberOfSamples * sharedTimeStep,
493 totalNumberOfSamples, sharedTimeStep, 0.5 * sharedTimeStep);
494 autoVEC smoother;
495 if (numberOfSmoothingSamples > 0) {
496 smoother = raw_VEC (numberOfSmoothingSamples);
497 const double factor = NUMpi / numberOfSmoothingSamples;
498 for (integer i = 1; i <= numberOfSmoothingSamples; i ++)
499 smoother [i] = 0.5 - 0.5 * cos (factor * (i - 0.5));
500 }
501 integer sampleOffset = 0;
502 for (integer i = 1; i <= list->size; i ++) {
503 const Sound sound = list->at [i];
504 if (numberOfSmoothingSamples > 2 * sound -> nx)
505 Melder_throw (U"At least one of the sounds is shorter than twice the overlap time.\nChoose a shorter overlap time.");
506 const bool thisIsTheFirstSound = ( i == 1 );
507 const bool thisIsTheLastSound = ( i == list->size );
508 const bool weNeedSmoothingAtTheStartOfThisSound = ! thisIsTheFirstSound;
509 const bool weNeedSmoothingAtTheEndOfThisSound = ! thisIsTheLastSound;
510 const integer numberOfSmoothingSamplesAtTheStartOfThisSound = ( weNeedSmoothingAtTheStartOfThisSound ? numberOfSmoothingSamples : 0 );
511 const integer numberOfSmoothingSamplesAtTheEndOfThisSound = ( weNeedSmoothingAtTheEndOfThisSound ? numberOfSmoothingSamples : 0 );
512 for (integer channel = 1; channel <= sharedNumberOfChannels; channel ++) {
513 for (integer j = 1, mySample = 1, thySample = mySample + sampleOffset;
514 j <= numberOfSmoothingSamplesAtTheStartOfThisSound;
515 j ++, mySample ++, thySample ++)
516 {
517 thy z [channel] [thySample] += sound -> z [channel] [mySample] * smoother [j]; // add
518 }
519 thy z.row (channel).part (sampleOffset + 1 + numberOfSmoothingSamplesAtTheStartOfThisSound,
520 sampleOffset + sound -> nx - numberOfSmoothingSamplesAtTheEndOfThisSound) <<=
521 sound -> z.row (channel).part (1 + numberOfSmoothingSamplesAtTheStartOfThisSound,
522 sound -> nx - numberOfSmoothingSamplesAtTheEndOfThisSound);
523 for (integer j = 1, mySample = sound -> nx - numberOfSmoothingSamplesAtTheEndOfThisSound + 1, thySample = mySample + sampleOffset;
524 j <= numberOfSmoothingSamplesAtTheEndOfThisSound;
525 j ++, mySample ++, thySample ++)
526 {
527 thy z [channel] [thySample] = sound -> z [channel] [mySample] * smoother [numberOfSmoothingSamplesAtTheEndOfThisSound + 1 - j]; // replace (or add, which is the same since it's all zeroes to start with)
528 }
529 }
530 sampleOffset += sound -> nx - numberOfSmoothingSamplesAtTheEndOfThisSound;
531 }
532 Melder_assert (sampleOffset == totalNumberOfSamples);
533 return thee;
534 } catch (MelderError) {
535 Melder_throw (U"Sounds not concatenated.");
536 }
537 }
538
539 autoSound Sounds_convolve (constSound me, constSound thee, kSounds_convolve_scaling scaling, kSounds_convolve_signalOutsideTimeDomain signalOutsideTimeDomain) {
540 try {
541 if (my ny > 1 && thy ny > 1 && my ny != thy ny)
542 Melder_throw (U"The numbers of channels of the two sounds have to be equal or 1.");
543 if (my dx != thy dx)
544 Melder_throw (U"The sampling frequencies of the two sounds have to be equal.");
545 const integer n1 = my nx, n2 = thy nx;
546 const integer n3 = n1 + n2 - 1;
547 const integer nfft = Melder_iroundUpToPowerOfTwo (n3);
548 autoVEC data1 = raw_VEC (nfft);
549 autoVEC data2 = raw_VEC (nfft);
550 integer numberOfChannels = std::max (my ny, thy ny);
551 autoSound him = Sound_create (numberOfChannels, my xmin + thy xmin, my xmax + thy xmax, n3, my dx, my x1 + thy x1);
552 for (integer channel = 1; channel <= numberOfChannels; channel ++) {
553 VEC a = my z.row (my ny == 1 ? 1 : channel);
554 for (integer i = n1; i > 0; i --)
555 data1 [i] = a [i];
556 for (integer i = n1 + 1; i <= nfft; i ++)
557 data1 [i] = 0.0;
558 a = thy z.row (thy ny == 1 ? 1 : channel);
559 for (integer i = n2; i > 0; i --)
560 data2 [i] = a [i];
561 for (integer i = n2 + 1; i <= nfft; i ++)
562 data2 [i] = 0.0;
563 NUMrealft (data1.get(), 1);
564 NUMrealft (data2.get(), 1);
565 data2 [1] *= data1 [1];
566 data2 [2] *= data1 [2];
567 for (integer i = 3; i <= nfft; i += 2) {
568 const double temp = data1 [i] * data2 [i] - data1 [i + 1] * data2 [i + 1];
569 data2 [i + 1] = data1 [i] * data2 [i + 1] + data1 [i + 1] * data2 [i];
570 data2 [i] = temp;
571 }
572 NUMrealft (data2.get(), -1);
573 a = his z.row (channel);
574 for (integer i = 1; i <= n3; i ++)
575 a [i] = data2 [i];
576 }
577 switch (signalOutsideTimeDomain) {
578 case kSounds_convolve_signalOutsideTimeDomain::ZERO: {
579 // do nothing
580 } break;
581 case kSounds_convolve_signalOutsideTimeDomain::SIMILAR: {
582 for (integer channel = 1; channel <= numberOfChannels; channel ++) {
583 const VEC a = his z.row (channel);
584 const double edge = std::min (n1, n2);
585 for (integer i = 1; i < edge; i ++) {
586 const double factor = edge / i;
587 a [i] *= factor;
588 a [n3 + 1 - i] *= factor;
589 }
590 }
591 } break;
592 //case kSounds_convolve_signalOutsideTimeDomain_PERIODIC: {
593 // do nothing
594 //} break;
595 default: Melder_crash (U"Sounds_convolve: unimplemented outside-time-domain strategy ", (int) signalOutsideTimeDomain);
596 }
597 switch (scaling) {
598 case kSounds_convolve_scaling::INTEGRAL: {
599 Vector_multiplyByScalar (him.get(), my dx / nfft);
600 } break;
601 case kSounds_convolve_scaling::SUM: {
602 Vector_multiplyByScalar (him.get(), 1.0 / nfft);
603 } break;
604 case kSounds_convolve_scaling::NORMALIZE: {
605 double normalizationFactor = Matrix_getNorm (me) * Matrix_getNorm (thee);
606 if (normalizationFactor != 0.0)
607 Vector_multiplyByScalar (him.get(), 1.0 / nfft / normalizationFactor);
608 } break;
609 case kSounds_convolve_scaling::PEAK_099: {
610 Vector_scale (him.get(), 0.99);
611 } break;
612 default: Melder_crash (U"Sounds_convolve: unimplemented scaling ", (int) scaling);
613 }
614 return him;
615 } catch (MelderError) {
616 Melder_throw (me, U" & ", thee, U": not convolved.");
617 }
618 }
619
620 autoSound Sounds_crossCorrelate (constSound me, constSound thee, kSounds_convolve_scaling scaling, kSounds_convolve_signalOutsideTimeDomain signalOutsideTimeDomain) {
621 try {
622 Melder_require (my ny == 1 || thy ny == 1 || my ny == thy ny,
623 U"The numbers of channels of the two sounds have to be equal or 1.");
624 Melder_require (my dx == thy dx,
625 U"The sampling frequencies of the two sounds have to be equal.");
626 const integer numberOfChannels = std::max (my ny, thy ny);
627 const integer n1 = my nx, n2 = thy nx, n3 = n1 + n2 - 1;
628 const integer nfft = Melder_iroundUpToPowerOfTwo (n3);
629 autoVEC data1 = raw_VEC (nfft);
630 autoVEC data2 = raw_VEC (nfft);
631 const double my_xlast = my x1 + (n1 - 1) * my dx;
632 autoSound him = Sound_create (numberOfChannels, thy xmin - my xmax, thy xmax - my xmin, n3, my dx, thy x1 - my_xlast);
633 for (integer channel = 1; channel <= numberOfChannels; channel ++) {
634 VEC a = my z.row (my ny == 1 ? 1 : channel);
635 for (integer i = n1; i > 0; i --)
636 data1 [i] = a [i];
637 for (integer i = n1 + 1; i <= nfft; i ++)
638 data1 [i] = 0.0;
639 a = thy z.row (thy ny == 1 ? 1 : channel);
640 for (integer i = n2; i > 0; i --)
641 data2 [i] = a [i];
642 for (integer i = n2 + 1; i <= nfft; i ++)
643 data2 [i] = 0.0;
644 NUMrealft (data1.get(), 1);
645 NUMrealft (data2.get(), 1);
646 data2 [1] *= data1 [1];
647 data2 [2] *= data1 [2];
648 for (integer i = 3; i <= nfft; i += 2) {
649 const double temp = data1 [i] * data2 [i] + data1 [i + 1] * data2 [i + 1]; // reverse me by taking the conjugate of data1
650 data2 [i + 1] = data1 [i] * data2 [i + 1] - data1 [i + 1] * data2 [i]; // reverse me by taking the conjugate of data1
651 data2 [i] = temp;
652 }
653 NUMrealft (data2.get(), -1);
654 a = his z.row (channel);
655 for (integer i = 1; i < n1; i ++)
656 a [i] = data2 [i + (nfft - (n1 - 1))]; // data for the first part ("negative lags") is at the end of data2
657 for (integer i = 1; i <= n2; i ++)
658 a [i + (n1 - 1)] = data2 [i]; // data for the second part ("positive lags") is at the beginning of data2
659 }
660 switch (signalOutsideTimeDomain) {
661 case kSounds_convolve_signalOutsideTimeDomain::ZERO: {
662 // do nothing
663 } break;
664 case kSounds_convolve_signalOutsideTimeDomain::SIMILAR: {
665 for (integer channel = 1; channel <= numberOfChannels; channel ++) {
666 double *const a = & his z [channel] [0];
667 double const edge = std::min (n1, n2);
668 for (integer i = 1; i < edge; i ++) {
669 const double factor = edge / i;
670 a [i] *= factor;
671 a [n3 + 1 - i] *= factor;
672 }
673 }
674 } break;
675 //case kSounds_convolve_signalOutsideTimeDomain_PERIODIC: {
676 // do nothing
677 //} break;
678 default: Melder_crash (U"Sounds_crossCorrelate: unimplemented outside-time-domain strategy ", (int) signalOutsideTimeDomain);
679 }
680 switch (scaling) {
681 case kSounds_convolve_scaling::INTEGRAL: {
682 Vector_multiplyByScalar (him.get(), my dx / nfft);
683 } break;
684 case kSounds_convolve_scaling::SUM: {
685 Vector_multiplyByScalar (him.get(), 1.0 / nfft);
686 } break;
687 case kSounds_convolve_scaling::NORMALIZE: {
688 const double normalizationFactor = Matrix_getNorm (me) * Matrix_getNorm (thee);
689 if (normalizationFactor != 0.0)
690 Vector_multiplyByScalar (him.get(), 1.0 / nfft / normalizationFactor);
691 } break;
692 case kSounds_convolve_scaling::PEAK_099: {
693 Vector_scale (him.get(), 0.99);
694 } break;
695 default: Melder_crash (U"Sounds_crossCorrelate: unimplemented scaling ", (int) scaling);
696 }
697 return him;
698 } catch (MelderError) {
699 Melder_throw (me, U" & ", thee, U": not cross-correlated.");
700 }
701 }
702
703 autoSound Sound_autoCorrelate (constSound me, kSounds_convolve_scaling scaling, kSounds_convolve_signalOutsideTimeDomain signalOutsideTimeDomain) {
704 try {
705 const integer numberOfChannels = my ny, n1 = my nx, n2 = n1 + n1 - 1;
706 const integer nfft = Melder_iroundUpToPowerOfTwo (n2);
707 autoVEC data = raw_VEC (nfft);
708 const double my_xlast = my x1 + (n1 - 1) * my dx;
709 autoSound thee = Sound_create (numberOfChannels, my xmin - my xmax, my xmax - my xmin, n2, my dx, my x1 - my_xlast);
710 for (integer channel = 1; channel <= numberOfChannels; channel ++) {
711 VEC a = my z.row (channel);
712 for (integer i = n1; i > 0; i --)
713 data [i] = a [i];
714 for (integer i = n1 + 1; i <= nfft; i ++)
715 data [i] = 0.0;
716 NUMrealft (data.get(), 1);
717 data [1] *= data [1];
718 data [2] *= data [2];
719 for (integer i = 3; i <= nfft; i += 2) {
720 data [i] = data [i] * data [i] + data [i + 1] * data [i + 1];
721 data [i + 1] = 0.0; // reverse me by taking the conjugate of data1
722 }
723 NUMrealft (data.get(), -1);
724 a = thy z.row (channel);
725 for (integer i = 1; i < n1; i ++)
726 a [i] = data [i + (nfft - (n1 - 1))]; // data for the first part ("negative lags") is at the end of data
727 for (integer i = 1; i <= n1; i ++)
728 a [i + (n1 - 1)] = data [i]; // data for the second part ("positive lags") is at the beginning of data
729 }
730 switch (signalOutsideTimeDomain) {
731 case kSounds_convolve_signalOutsideTimeDomain::ZERO: {
732 // do nothing
733 } break;
734 case kSounds_convolve_signalOutsideTimeDomain::SIMILAR: {
735 for (integer channel = 1; channel <= numberOfChannels; channel ++) {
736 const VEC a = thy z.row (channel);
737 const double edge = n1;
738 for (integer i = 1; i < edge; i ++) {
739 const double factor = edge / i;
740 a [i] *= factor;
741 a [n2 + 1 - i] *= factor;
742 }
743 }
744 } break;
745 //case kSounds_convolve_signalOutsideTimeDomain_PERIODIC: {
746 // do nothing
747 //} break;
748 default: Melder_crash (U"Sounds_autoCorrelate: unimplemented outside-time-domain strategy ", (int) signalOutsideTimeDomain);
749 }
750 switch (scaling) {
751 case kSounds_convolve_scaling::INTEGRAL: {
752 Vector_multiplyByScalar (thee.get(), my dx / nfft);
753 } break;
754 case kSounds_convolve_scaling::SUM: {
755 Vector_multiplyByScalar (thee.get(), 1.0 / nfft);
756 } break;
757 case kSounds_convolve_scaling::NORMALIZE: {
758 const double normalizationFactor = Matrix_getNorm (me) * Matrix_getNorm (me);
759 if (normalizationFactor != 0.0)
760 Vector_multiplyByScalar (thee.get(), 1.0 / nfft / normalizationFactor);
761 } break;
762 case kSounds_convolve_scaling::PEAK_099: {
763 Vector_scale (thee.get(), 0.99);
764 } break;
765 default: Melder_crash (U"Sounds_autoCorrelate: unimplemented scaling ", (int) scaling);
766 }
767 return thee;
768 } catch (MelderError) {
769 Melder_throw (me, U": autocorrelation not computed.");
770 }
771 }
772
773 void Sound_draw (constSound me, Graphics g,
774 double tmin, double tmax, double minimum, double maximum, bool garnish, conststring32 method)
775 {
776 const bool timesAreReversed = ( tmin > tmax );
777 if (timesAreReversed)
778 std::swap (tmin, tmax);
779 Function_bidirectionalAutowindow (me, & tmin, & tmax);
780 /*
781 Domain expressed in sample numbers.
782 */
783 integer ixmin, ixmax;
784 const integer n = Matrix_getWindowSamplesX (me, tmin, tmax, & ixmin, & ixmax);
785 if (n < 1)
786 return;
787 /*
788 Automatic vertical range.
789 */
790 if (minimum == maximum) {
791 Matrix_getWindowExtrema (me, ixmin, ixmax, 1, my ny, & minimum, & maximum);
792 if (minimum == maximum) {
793 minimum -= 1.0;
794 maximum += 1.0;
795 }
796 }
797 /*
798 Set coordinates for drawing.
799 */
800 Graphics_setInner (g);
801 for (integer channel = 1; channel <= my ny; channel ++) {
802 Graphics_setWindow (g, timesAreReversed ? tmax : tmin, timesAreReversed ? tmin : tmax,
803 minimum - (my ny - channel) * (maximum - minimum),
804 maximum + (channel - 1) * (maximum - minimum)
805 );
806 if (str32str (method, U"bars") || str32str (method, U"Bars")) {
807 for (integer ix = ixmin; ix <= ixmax; ix ++) {
808 const double x = Sampled_indexToX (me, ix);
809 const double y = std::min (my z [channel] [ix], maximum);
810 const double left = std::max (x - 0.5 * my dx, tmin);
811 const double right = std::min (x + 0.5 * my dx, tmax);
812 Graphics_line (g, left, y, right, y);
813 Graphics_line (g, left, y, left, minimum);
814 Graphics_line (g, right, y, right, minimum);
815 }
816 } else if (str32str (method, U"poles") || str32str (method, U"Poles")) {
817 for (integer ix = ixmin; ix <= ixmax; ix ++) {
818 const double x = Sampled_indexToX (me, ix);
819 Graphics_line (g, x, 0, x, my z [channel] [ix]);
820 }
821 } else if (str32str (method, U"speckles") || str32str (method, U"Speckles")) {
822 for (integer ix = ixmin; ix <= ixmax; ix ++) {
823 const double x = Sampled_indexToX (me, ix);
824 Graphics_speckle (g, x, my z [channel] [ix]);
825 }
826 } else {
827 /*
828 The default: draw as a curve.
829 */
830 Graphics_function (g, & my z [channel] [0], ixmin, ixmax,
831 Matrix_columnToX (me, ixmin), Matrix_columnToX (me, ixmax));
832 }
833 }
834 Graphics_setWindow (g, timesAreReversed ? tmax : tmin, timesAreReversed ? tmin : tmax, minimum, maximum);
835 if (garnish && my ny == 2)
836 Graphics_line (g, tmin, 0.5 * (minimum + maximum), tmax, 0.5 * (minimum + maximum));
837 Graphics_unsetInner (g);
838 if (garnish) {
839 Graphics_drawInnerBox (g);
840 Graphics_textBottom (g, true, U"Time (s)");
841 Graphics_marksBottom (g, 2, true, true, false);
842 Graphics_setWindow (g, tmin, tmax, minimum - (my ny - 1) * (maximum - minimum), maximum);
843 Graphics_markLeft (g, minimum, true, true, false, nullptr);
844 Graphics_markLeft (g, maximum, true, true, false, nullptr);
845 if (minimum != 0.0 && maximum != 0.0 && (minimum > 0.0) != (maximum > 0.0))
846 Graphics_markLeft (g, 0.0, true, true, true, nullptr);
847 if (my ny == 2) {
848 Graphics_setWindow (g, timesAreReversed ? tmax : tmin, timesAreReversed ? tmin : tmax,
849 minimum, maximum + (my ny - 1) * (maximum - minimum));
850 Graphics_markRight (g, minimum, true, true, false, nullptr);
851 Graphics_markRight (g, maximum, true, true, false, nullptr);
852 if (minimum != 0.0 && maximum != 0.0 && (minimum > 0.0) != (maximum > 0.0))
853 Graphics_markRight (g, 0.0, true, true, true, nullptr);
854 }
855 }
856 }
857
858 static double interpolate (constSound me, integer i1, integer channel)
859 /* Precondition: my z [1] [i1] != my z [1] [i1 + 1]; */
860 {
861 const integer i2 = i1 + 1;
862 const double x1 = Sampled_indexToX (me, i1), x2 = Sampled_indexToX (me, i2);
863 const double y1 = my z [channel] [i1], y2 = my z [channel] [i2];
864 return x1 + (x2 - x1) * y1 / (y1 - y2); // linear
865 }
866 double Sound_getNearestZeroCrossing (constSound me, double position, integer channel) {
867 VEC amplitude = my z.row (channel);
868 const integer leftSample = Sampled_xToLowIndex (me, position);
869 const integer rightSample = leftSample + 1;
870 /* Are we already at a zero crossing? */
871 if (leftSample >= 1 && rightSample <= my nx &&
872 (amplitude [leftSample] >= 0.0) !=
873 (amplitude [rightSample] >= 0.0))
874 {
875 return interpolate (me, leftSample, channel);
876 }
877 integer ileft, iright;
878 double leftZero, rightZero;
879
880 /*
881 Search to the left.
882 */
883 if (leftSample > my nx)
884 return undefined;
885 for (ileft = leftSample - 1; ileft >= 1; ileft --)
886 if ((amplitude [ileft] >= 0.0) != (amplitude [ileft + 1] >= 0.0)) {
887 leftZero = interpolate (me, ileft, channel);
888 break;
889 }
890
891 /*
892 Search to the right.
893 */
894 if (rightSample < 1)
895 return undefined;
896 for (iright = rightSample + 1; iright <= my nx; iright ++)
897 if ((amplitude [iright] >= 0.0) != (amplitude [iright - 1] >= 0.0)) {
898 rightZero = interpolate (me, iright - 1, channel);
899 break;
900 }
901
902 if (ileft < 1 && iright > my nx)
903 return undefined;
904 return ileft < 1 ? rightZero : iright > my nx ? leftZero :
905 position - leftZero < rightZero - position ? leftZero : rightZero;
906 }
907
908 void Sound_setZero (mutableSound me, double tmin_in, double tmax_in, bool roundTimesToNearestZeroCrossing) {
909 Function_unidirectionalAutowindow (me, & tmin_in, & tmax_in);
910 Function_intersectRangeWithDomain (me, & tmin_in, & tmax_in);
911 for (integer channel = 1; channel <= my ny; channel ++) {
912 /* mutable */ double tmin = tmin_in, tmax = tmax_in;
913 if (roundTimesToNearestZeroCrossing) {
914 if (tmin > my xmin)
915 tmin = Sound_getNearestZeroCrossing (me, tmin_in, channel);
916 if (tmax < my xmax)
917 tmax = Sound_getNearestZeroCrossing (me, tmax_in, channel);
918 }
919 if (isundef (tmin))
920 tmin = my xmin;
921 if (isundef (tmax))
922 tmax = my xmax;
923 /* mutable */ integer imin, imax;
924 Sampled_getWindowSamples (me, tmin, tmax, & imin, & imax);
925 for (integer i = imin; i <= imax; i ++)
926 my z [channel] [i] = 0.0;
927 }
928 }
929
930 autoSound Sound_createAsPureTone (integer numberOfChannels, double startingTime, double endTime,
931 double sampleRate, double frequency, double amplitude, double fadeInDuration, double fadeOutDuration)
932 {
933 try {
934 Melder_require (numberOfChannels >= 1,
935 U"The number of channels should be at least 1.");
936 const double numberOfSamples_real = round ((endTime - startingTime) * sampleRate);
937 if (numberOfSamples_real > double (INT32_MAX))
938 Melder_throw (U"Cannot create sounds with more than ", Melder_bigInteger (INT32_MAX), U" samples, because they cannot be saved to disk.");
939 autoSound me = Sound_create (numberOfChannels, startingTime, endTime, (integer) (int32) numberOfSamples_real,
940 1.0 / sampleRate, startingTime + 0.5 / sampleRate);
941 for (integer isamp = 1; isamp <= my nx; isamp ++) {
942 const double time = my x1 + (isamp - 1) * my dx;
943 /* mutable */ double value = amplitude * sin (2.0 * NUMpi * frequency * time);
944 const double timeFromStart = time - startingTime;
945 if (timeFromStart < fadeInDuration)
946 value *= 0.5 - 0.5 * cos (NUMpi * timeFromStart / fadeInDuration);
947 const double timeFromEnd = endTime - time;
948 if (timeFromEnd < fadeOutDuration)
949 value *= 0.5 - 0.5 * cos (NUMpi * timeFromEnd / fadeOutDuration);
950 for (integer ichan = 1; ichan <= my ny; ichan ++)
951 my z [ichan] [isamp] = value;
952 }
953 return me;
954 } catch (MelderError) {
955 Melder_throw (U"Sound not created from tone complex.");
956 }
957 }
958
959 autoSound Sound_createAsToneComplex (double startTime, double endTime, double samplingFrequency,
960 int phase, double frequencyStep, double firstFrequency, double ceiling, integer numberOfComponents)
961 {
962 try {
963 if (frequencyStep == 0.0)
964 Melder_throw (U"The frequency step should not be zero.");
965 /*
966 Translate default firstFrequency.
967 */
968 if (firstFrequency <= 0.0)
969 firstFrequency = frequencyStep;
970 const double firstOmega = 2.0 * NUMpi * firstFrequency;
971 /*
972 Translate default ceiling.
973 */
974 const double omegaStep = 2.0 * NUMpi * frequencyStep;
975 const double nyquistFrequency = 0.5 * samplingFrequency;
976 if (ceiling <= 0.0 || ceiling > nyquistFrequency)
977 ceiling = nyquistFrequency;
978 /*
979 Translate number of components.
980 */
981 const integer maximumNumberOfComponents = Melder_ifloor ((ceiling - firstFrequency) / frequencyStep) + 1;
982 if (numberOfComponents <= 0 || numberOfComponents > maximumNumberOfComponents)
983 numberOfComponents = maximumNumberOfComponents;
984 if (numberOfComponents < 1)
985 Melder_throw (U"There would be zero sine waves.");
986 /*
987 Generate the Sound.
988 */
989 const double factor = 0.99 / numberOfComponents;
990 autoSound me = Sound_create (1, startTime, endTime, Melder_iround ((endTime - startTime) * samplingFrequency),
991 1.0 / samplingFrequency, startTime + 0.5 / samplingFrequency);
992 for (integer isamp = 1; isamp <= my nx; isamp ++) {
993 const double t = Sampled_indexToX (me.get(), isamp);
994 const double omegaStepT = omegaStep * t;
995 const double firstOmegaT = firstOmega * t;
996 longdouble value = 0.0;
997 if (phase == Sound_TONE_COMPLEX_SINE) {
998 for (integer icomp = 1; icomp <= numberOfComponents; icomp ++)
999 value += sin (firstOmegaT + (icomp - 1) * omegaStepT);
1000 } else {
1001 for (integer icomp = 1; icomp <= numberOfComponents; icomp ++)
1002 value += cos (firstOmegaT + (icomp - 1) * omegaStepT);
1003 }
1004 my z [1] [isamp] = double (value) * factor;
1005 }
1006 return me;
1007 } catch (MelderError) {
1008 Melder_throw (U"Sound not created as tone complex.");
1009 }
1010 }
1011
1012 void Sound_multiplyByWindow (mutableSound me, kSound_windowShape windowShape) {
1013 for (integer ichan = 1; ichan <= my ny; ichan ++) {
1014 const integer n = my nx;
1015 VEC channel = my z.row (ichan);
1016 switch (windowShape) {
1017 case kSound_windowShape::RECTANGULAR: {
1018 ;
1019 } break; case kSound_windowShape::TRIANGULAR: { // "Bartlett"
1020 for (integer i = 1; i <= n; i ++) {
1021 const double phase = double (i - 0.5) / n; // 0..1
1022 channel [i] *= 1.0 - fabs ((2.0 * phase - 1.0));
1023 }
1024 } break; case kSound_windowShape::PARABOLIC: { // "Welch"
1025 for (integer i = 1; i <= n; i ++) {
1026 const double phase = double (i - 0.5) / n;
1027 channel [i] *= 1.0 - (2.0 * phase - 1.0) * (2.0 * phase - 1.0);
1028 }
1029 } break; case kSound_windowShape::HANNING: {
1030 for (integer i = 1; i <= n; i ++) {
1031 const double phase = double (i - 0.5) / n;
1032 channel [i] *= 0.5 * (1.0 - cos (2.0 * NUMpi * phase));
1033 }
1034 } break; case kSound_windowShape::HAMMING: {
1035 for (integer i = 1; i <= n; i ++) {
1036 const double phase = double (i - 0.5) / n;
1037 channel [i] *= 0.54 - 0.46 * cos (2.0 * NUMpi * phase);
1038 }
1039 } break; case kSound_windowShape::GAUSSIAN_1: {
1040 const double imid = 0.5 * double (n + 1), edge = exp (-3.0), onebyedge1 = 1.0 / (1.0 - edge);
1041 for (integer i = 1; i <= n; i ++) {
1042 const double phase = ((double) i - imid) / n; // -0.5..+0.5
1043 channel [i] *= (exp (-12.0 * phase * phase) - edge) * onebyedge1;
1044 }
1045 } break; case kSound_windowShape::GAUSSIAN_2: {
1046 const double imid = 0.5 * double (n + 1), edge = exp (-12.0), onebyedge1 = 1.0 / (1.0 - edge);
1047 for (integer i = 1; i <= n; i ++) {
1048 const double phase = ((double) i - imid) / n;
1049 channel [i] *= (exp (-48.0 * phase * phase) - edge) * onebyedge1;
1050 }
1051 } break; case kSound_windowShape::GAUSSIAN_3: {
1052 const double imid = 0.5 * double (n + 1), edge = exp (-27.0), onebyedge1 = 1.0 / (1.0 - edge);
1053 for (integer i = 1; i <= n; i ++) {
1054 const double phase = ((double) i - imid) / n;
1055 channel [i] *= (exp (-108.0 * phase * phase) - edge) * onebyedge1;
1056 }
1057 } break; case kSound_windowShape::GAUSSIAN_4: {
1058 const double imid = 0.5 * double (n + 1), edge = exp (-48.0), onebyedge1 = 1.0 / (1.0 - edge);
1059 for (integer i = 1; i <= n; i ++) {
1060 const double phase = ((double) i - imid) / n;
1061 channel [i] *= (exp (-192.0 * phase * phase) - edge) * onebyedge1;
1062 }
1063 } break; case kSound_windowShape::GAUSSIAN_5: {
1064 const double imid = 0.5 * double (n + 1), edge = exp (-75.0), onebyedge1 = 1.0 / (1.0 - edge);
1065 for (integer i = 1; i <= n; i ++) {
1066 const double phase = ((double) i - imid) / n;
1067 channel [i] *= (exp (-300.0 * phase * phase) - edge) * onebyedge1;
1068 }
1069 } break; case kSound_windowShape::KAISER_1: {
1070 const double imid = 0.5 * double (n + 1);
1071 const double factor = 1.0 / NUMbessel_i0_f (2 * NUMpi);
1072 for (integer i = 1; i <= n; i ++) {
1073 const double phase = 2.0 * ((double) i - imid) / n; // -1..+1
1074 const double root = 1.0 - phase * phase;
1075 channel [i] *= root <= 0.0 ? 0.0 : factor * NUMbessel_i0_f (2.0 * NUMpi * sqrt (root));
1076 }
1077 } break; case kSound_windowShape::KAISER_2: {
1078 const double imid = 0.5 * double (n + 1);
1079 const double factor = 1.0 / NUMbessel_i0_f (2 * NUMpi * NUMpi + 0.5);
1080 for (integer i = 1; i <= n; i ++) {
1081 const double phase = 2.0 * ((double) i - imid) / n; // -1..+1
1082 const double root = 1.0 - phase * phase;
1083 channel [i] *= root <= 0.0 ? 0.0 : factor * NUMbessel_i0_f ((2.0 * NUMpi * NUMpi + 0.5) * sqrt (root));
1084 }
1085 } break; default: {
1086 }
1087 }
1088 }
1089 }
1090
1091 void Sound_scaleIntensity (mutableSound me, double newAverageIntensity) {
1092 const double currentIntensity = Sound_getIntensity_dB (me);
1093 if (isundef (currentIntensity))
1094 return;
1095 const double factor = pow (10.0, (newAverageIntensity - currentIntensity) / 20.0);
1096 my z.all() *= factor;
1097 }
1098
1099 void Sound_overrideSamplingFrequency (mutableSound me, double newSamplingFrequency) {
1100 my dx = 1.0 / newSamplingFrequency;
1101 my x1 = my xmin + 0.5 * my dx;
1102 my xmax = my xmin + my nx * my dx;
1103 }
1104
1105 autoSound Sound_extractPart (constSound me, double tmin, double tmax, kSound_windowShape windowShape, double relativeWidth, bool preserveTimes) {
1106 try {
1107 /*
1108 We do not clip to the Sound's time domain.
1109 Any samples outside it are taken to be zero.
1110 */
1111
1112 Function_unidirectionalAutowindow (me, & tmin, & tmax);
1113 /*
1114 Allow window tails outside specified domain.
1115 */
1116 if (relativeWidth != 1.0) {
1117 const double margin = 0.5 * (relativeWidth - 1) * (tmax - tmin);
1118 tmin -= margin;
1119 tmax += margin;
1120 }
1121 /*
1122 Determine index range. We use all the real or virtual samples that fit within [t1..t2].
1123 */
1124 const integer itmin = 1 + Melder_iceiling ((tmin - my x1) / my dx);
1125 const integer itmax = 1 + Melder_ifloor ((tmax - my x1) / my dx);
1126 Melder_require (itmax >= itmin,
1127 U"Extracted Sound would contain no samples.");
1128 /*
1129 Create sound, optionally shifted to [0..t2-t1].
1130 */
1131 autoSound thee = Sound_create (my ny, tmin, tmax, itmax - itmin + 1, my dx, my x1 + (itmin - 1) * my dx);
1132 if (! preserveTimes) {
1133 thy xmin = 0.0;
1134 thy xmax -= tmin;
1135 thy x1 -= tmin;
1136 }
1137 /*
1138 Copy only *real* samples into the new sound.
1139 The *virtual* samples will remain at zero.
1140 */
1141 for (integer ichan = 1; ichan <= my ny; ichan ++) {
1142 const integer itmin_clipped = Melder_clippedLeft (1_integer, itmin);
1143 const integer itmax_clipped = Melder_clippedRight (itmax, my nx);
1144 thy z.row (ichan).part (1 - itmin + itmin_clipped, 1 - itmin + itmax_clipped)
1145 <<= my z.row (ichan).part (itmin_clipped, itmax_clipped);
1146 }
1147 /*
1148 Multiply by a window that extends throughout the target domain.
1149 */
1150 Sound_multiplyByWindow (thee.get(), windowShape);
1151 return thee;
1152 } catch (MelderError) {
1153 Melder_throw (me, U": part not extracted.");
1154 }
1155 }
1156
1157 autoSound Sound_extractPartForOverlap (constSound me, double tmin, double tmax, double overlap) {
1158 try {
1159 Function_unidirectionalAutowindow (me, & tmin, & tmax);
1160 if (overlap > 0.0) {
1161 const double margin = 0.5 * overlap;
1162 tmin -= margin;
1163 tmax += margin;
1164 }
1165 Melder_clipLeft (my xmin, & tmin);
1166 Melder_clipRight (& tmax, my xmax);
1167 /*
1168 Determine index range. We use all the real or virtual samples that fit within [t1..t2].
1169 */
1170 const integer itmin = 1 + Melder_iceiling ((tmin - my x1) / my dx);
1171 const integer itmax = 1 + Melder_ifloor ((tmax - my x1) / my dx);
1172 Melder_require (itmax >= itmin,
1173 U"Extracted Sound would contain no samples.");
1174 /*
1175 Create sound.
1176 */
1177 autoSound thee = Sound_create (my ny, tmin, tmax, itmax - itmin + 1, my dx, my x1 + (itmin - 1) * my dx);
1178 thy xmin = 0.0;
1179 thy xmax -= tmin;
1180 thy x1 -= tmin;
1181 /*
1182 Copy only *real* samples into the new sound.
1183 The *virtual* samples will remain at zero.
1184 */
1185 for (integer ichan = 1; ichan <= my ny; ichan ++) {
1186 const integer itmin_clipped = Melder_clippedLeft (1_integer, itmin);
1187 const integer itmax_clipped = Melder_clippedRight (itmax, my nx);
1188 thy z.row (ichan).part (1 - itmin + itmin_clipped, 1 - itmin + itmax_clipped)
1189 <<= my z.row (ichan).part (itmin_clipped, itmax_clipped);
1190 }
1191 return thee;
1192 } catch (MelderError) {
1193 Melder_throw (me, U": part not extracted.");
1194 }
1195 }
1196
1197 void Sound_filterWithFormants (mutableSound me, double tmin, double tmax,
1198 int numberOfFormants, double formant [], double bandwidth [])
1199 {
1200 try {
1201 Function_unidirectionalAutowindow (me, & tmin, & tmax);
1202 integer itmin, itmax;
1203 integer n = Sampled_getWindowSamples (me, tmin, tmax, & itmin, & itmax);
1204 Melder_require (n >= 3,
1205 U"Sound too short.");
1206 for (integer ichan = 1; ichan <= my ny; ichan ++) {
1207 VECVU const& channel = my z.row (ichan);
1208 VECVU const& window = channel.part (itmin, itmax);
1209 VECdeemphasize_f_inplace (window, my dx, 50.0);
1210 for (int iformant = 1; iformant <= numberOfFormants; iformant ++)
1211 VECfilterSecondOrderSection_fb_inplace (window, my dx, formant [iformant], bandwidth [iformant]);
1212 }
1213 Matrix_scaleAbsoluteExtremum (me, 0.99);
1214 } catch (MelderError) {
1215 Melder_throw (me, U": not filtered.");
1216 }
1217 }
1218
1219 autoSound Sound_filter_oneFormant (constSound me, double frequency, double bandwidth) {
1220 try {
1221 autoSound thee = Data_copy (me);
1222 Sound_filterWithOneFormantInplace (thee.get(), frequency, bandwidth);
1223 return thee;
1224 } catch (MelderError) {
1225 Melder_throw (me, U": not filtered (one formant).");
1226 }
1227 }
1228
1229 void Sound_filterWithOneFormantInplace (mutableSound me, double frequency, double bandwidth) {
1230 for (integer ichan = 1; ichan <= my ny; ichan ++) {
1231 const VEC channel = my z.row (ichan);
1232 VECfilterSecondOrderSection_fb_inplace (channel, my dx, frequency, bandwidth);
1233 }
1234 Matrix_scaleAbsoluteExtremum (me, 0.99);
1235 }
1236
1237 double Sound_computeEmphasisFactor (constSound me, double cutoffFrequency) {
1238 return exp (- NUM2pi * cutoffFrequency * my dx);
1239 }
1240
1241 void Sound_preEmphasize_inplace (mutableSound me, double cutoffFrequency) {
1242 const double emphasisFactor = Sound_computeEmphasisFactor (me, cutoffFrequency);
1243 if (emphasisFactor != 0.0) // OPTIMIZE; will happen for cut-off frequencies above 119 times the sampling frequency
1244 for (integer channel = 1; channel <= my ny; channel ++) {
1245 const VEC s = my z.row (channel);
1246 for (integer i = my nx; i >= 2; i --)
1247 s [i] -= emphasisFactor * s [i - 1];
1248 }
1249 }
1250
1251 void Sound_deEmphasize_inplace (Sound me, double cutoffFrequency) {
1252 const double emphasisFactor = Sound_computeEmphasisFactor (me, cutoffFrequency);
1253 if (emphasisFactor != 0.0) // OPTIMIZE; will happen for cut-off frequencies above 119 times the sampling frequency
1254 for (integer channel = 1; channel <= my ny; channel ++) {
1255 const VEC s = my z.row (channel);
1256 for (integer i = 2; i <= my nx; i ++)
1257 s [i] += emphasisFactor * s [i - 1];
1258 }
1259 }
1260
1261 autoSound Sound_filter_preemphasis (constSound me, double frequency) {
1262 try {
1263 autoSound thee = Data_copy (me);
1264 Sound_preEmphasize_inplace (thee.get(), frequency);
1265 Matrix_scaleAbsoluteExtremum (thee.get(), 0.99);
1266 return thee;
1267 } catch (MelderError) {
1268 Melder_throw (me, U": not filtered (pre-emphasis).");
1269 }
1270 }
1271
1272 autoSound Sound_filter_deemphasis (constSound me, double frequency) {
1273 try {
1274 autoSound thee = Data_copy (me);
1275 Sound_deEmphasize_inplace (thee.get(), frequency);
1276 Matrix_scaleAbsoluteExtremum (thee.get(), 0.99);
1277 return thee;
1278 } catch (MelderError) {
1279 Melder_throw (me, U": not filtered (de-emphasis).");
1280 }
1281 }
1282
1283 void Sound_reverse (mutableSound me, double tmin, double tmax) {
1284 Function_unidirectionalAutowindow (me, & tmin, & tmax);
1285 integer itmin, itmax;
1286 const integer n = Sampled_getWindowSamples (me, tmin, tmax, & itmin, & itmax) / 2;
1287 for (integer channel = 1; channel <= my ny; channel ++) {
1288 double * const amp = & my z [channel] [0];
1289 for (integer i = 0; i < n; i ++)
1290 std::swap (amp [itmin + i], amp [itmax - i]);
1291 }
1292 }
1293
1294 autoSound Sounds_crossCorrelate_short (constSound me, constSound thee, double tmin, double tmax, bool normalize) {
1295 try {
1296 if (my dx != thy dx)
1297 Melder_throw (U"Sampling frequencies are not equal.");
1298 if (my ny != thy ny)
1299 Melder_throw (U"Numbers of channels are not equal.");
1300 const double dt = my dx;
1301 double dphase = (thy x1 - my x1) / dt;
1302 dphase -= Melder_roundDown (dphase); // a number between 0 and 1
1303 const integer i1 = Melder_iceiling (tmin / dt - dphase); // index of first sample if sample at dphase has index 0
1304 const integer i2 = Melder_ifloor (tmax / dt - dphase); // index of last sample if sample at dphase has index 0
1305 const integer nt = i2 - i1 + 1;
1306 if (nt < 1)
1307 Melder_throw (U"Window too small.");
1308 const double t1 = (dphase + i1) * dt;
1309 autoSound him = Sound_create (1, tmin, tmax, nt, dt, t1);
1310 for (integer i = 1; i <= nt; i ++) {
1311 const integer di = i - 1 + i1;
1312 for (integer ime = 1; ime <= my nx; ime ++) {
1313 if (ime + di < 1)
1314 continue;
1315 if (ime + di > thy nx)
1316 break;
1317 for (integer channel = 1; channel <= my ny; channel ++)
1318 his z [1] [i] += my z [channel] [ime] * thy z [channel] [ime + di];
1319 }
1320 }
1321 if (normalize) {
1322 longdouble mypower = 0.0, thypower = 0.0;
1323 for (integer channel = 1; channel <= my ny; channel ++) {
1324 for (integer i = 1; i <= my nx; i ++) {
1325 const double value = my z [channel] [i];
1326 mypower += value * value;
1327 }
1328 for (integer i = 1; i <= thy nx; i ++) {
1329 const double value = thy z [channel] [i];
1330 thypower += value * value;
1331 }
1332 }
1333 if (mypower != 0.0 && thypower != 0.0) {
1334 const double factor = 1.0 / (sqrt (double (mypower)) * sqrt (double (thypower)));
1335 for (integer i = 1; i <= nt; i ++) {
1336 his z [1] [i] *= factor;
1337 }
1338 }
1339 } else {
1340 const double factor = dt / my ny;
1341 for (integer i = 1; i <= nt; i ++) {
1342 his z [1] [i] *= factor;
1343 }
1344 }
1345 return him;
1346 } catch (MelderError) {
1347 Melder_throw (me, U": not cross-correlated.");
1348 }
1349 }
1350
1351 Thing_implement (SoundList, Ordered, 0);
1352
1353 /* End of file Sound.cpp */