Debian Codegraph @

dwtools/Sound_extensions.cpp

raw symbols SCIP
1 /* Sound_extensions.cpp
2 *
3 * Copyright (C) 1993-2023 David Weenink, 2017,2024-2026 Paul Boersma
4 *
5 * This code is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or (at
8 * your option) any later version.
9 *
10 * This code is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 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 #include "Formula.h"
20 #include "Intensity_extensions.h"
21 #include "Sound_extensions.h"
22 #include "Sound_and_Spectrum.h"
23 #include "Spectrum_extensions.h"
24 #include "Sound_and_Spectrogram.h"
25 #include "Sound_and_TextGrid_extensions.h"
26 #include "Spectrogram_extensions.h"
27 #include "Sound_to_Intensity.h"
28 #include "Sound_to_Pitch.h"
29 #include "Vector.h"
30 #include "Pitch_extensions.h"
31 #include "Pitch_to_PitchTier.h"
32 #include "Pitch_to_PointProcess.h"
33 #include "Polygon_extensions.h"
34 #include "TextGrid_extensions.h"
35 #include "DurationTier.h"
36 #include "Ltas.h"
37 #include "Manipulation.h"
38 #include "NUMcomplex.h"
39 #include "melder.h"
40 #include "../external/vorbis/vorbis_codec.h"
41 #include "../external/vorbis/vorbisfile.h"
42 #include "../external/opusfile/opusfile.h"
43 #include "../external/lame/lame.h"
44
45 #include "enums_getText.h"
46 #include "Sound_extensions_enums.h"
47 #include "enums_getValue.h"
48 #include "Sound_extensions_enums.h"
49
50 #define MAX_T 0.02000000001 /* Maximum interval between two voice pulses (otherwise voiceless). */
51
52 static void PitchTier_modifyExcursionRange (PitchTier me, double tmin, double tmax, double multiplier, double fref_Hz) {
53 if (fref_Hz <= 0)
54 return;
55 const double fref_st = 12.0 * log (fref_Hz / 100.0) / NUMln2;
56 for (integer i = 1; i <= my points.size; i ++) {
57 const RealPoint point = my points.at [i];
58 const double f = point -> value;
59 if (point -> number < tmin || point -> number > tmax)
60 continue;
61 if (f > 0.0) {
62 const double f_st = fref_st + 12.0 * log2 (f / fref_Hz) * multiplier;
63 point -> value = 100.0 * exp (f_st * (NUMln2 / 12.0));
64 }
65 }
66 }
67
68 static void Pitch_scaleDuration (Pitch me, double multiplier) {
69 if (multiplier != 1.0) {
70 // keep xmin at the same value
71 my dx *= multiplier;
72 my x1 = my xmin + (my x1 - my xmin) * multiplier;
73 my xmax = my xmin + (my xmax - my xmin) * multiplier;
74 }
75 }
76
77 static void Pitch_scalePitch (Pitch me, double multiplier) {
78 for (integer i = 1; i <= my nx; i ++) {
79 double f = my frames [i].candidates [1].frequency;
80 f *= multiplier;
81 if (f < my ceiling)
82 my frames [i].candidates [1].frequency = f;
83 }
84 }
85
86 static void i1write (Sound me, FILE *f, integer *nClip) {
87 const double min = -128.0, max = 127.0;
88 *nClip = 0;
89 for (integer i = 1; i <= my nx; i ++) {
90 double sample = round (my z [1] [i] * 128.0);
91 if (sample > max) {
92 sample = max;
93 (*nClip) ++;
94 } else if (sample < min) {
95 sample = min;
96 (*nClip) ++;
97 }
98 binputi8 ((int) sample, f);
99 }
100 }
101
102 static void i1read (Sound me, FILE *f) {
103 for (integer i = 1; i <= my nx; i ++)
104 my z [1] [i] = bingeti8 (f) / 128.0;
105 }
106
107 static void u1write (Sound me, FILE *f, integer *nClip) {
108 const double min = 0.0, max = 255.0;
109 *nClip = 0;
110 for (integer i = 1; i <= my nx; i ++) {
111 double sample = round ((my z [1] [i] + 1.0) * 255.0 / 2.0);
112 if (sample > max) {
113 sample = max;
114 (*nClip) ++;
115 } else if (sample < min) {
116 sample = min;
117 (*nClip) ++;
118 }
119 binputu8 ((unsigned int) sample, f);
120 }
121 }
122
123 static void u1read (Sound me, FILE *f) {
124 for (integer i = 1; i <= my nx; i ++)
125 my z [1] [i] = bingetu8 (f) / 128.0 - 1.0;
126 }
127
128 static void i2write (Sound me, FILE *f, bool littleEndian, integer *nClip) {
129 const double min = -32768.0, max = 32767.0;
130 void (*put) (int16, FILE *) = littleEndian ? binputi16LE : binputi16;
131 *nClip = 0;
132 for (integer i = 1; i <= my nx; i ++) {
133 double sample = round (my z [1] [i] * 32768.0);
134 if (sample > max) {
135 sample = max;
136 (*nClip) ++;
137 } else if (sample < min) {
138 sample = min;
139 (*nClip) ++;
140 }
141 put ((int16) sample, f);
142 }
143 }
144
145 static void i2read (Sound me, FILE *f, bool littleEndian) {
146 int16 (*get) (FILE *) = littleEndian ? bingeti16LE : bingeti16;
147 for (integer i = 1; i <= my nx; i ++)
148 my z [1] [i] = get (f) / 32768.0;
149 }
150
151 static void u2write (Sound me, FILE *f, bool littleEndian, integer *nClip) {
152 const double min = 0.0, max = 65535.0;
153 void (*put) (uint16, FILE *) = littleEndian ? binputu16LE : binputu16;
154 *nClip = 0;
155 for (integer i = 1; i <= my nx; i ++) {
156 double sample = round ((my z [1] [i] + 1.0) * 65535.0 / 2.0);
157 if (sample > max) {
158 sample = max;
159 (*nClip) ++;
160 } else if (sample < min) {
161 sample = min;
162 (*nClip) ++;
163 }
164 put ((uint16) sample, f);
165 }
166 }
167
168 static void u2read (Sound me, FILE *f, bool littleEndian) {
169 uint16 (*get) (FILE *) = littleEndian ? bingetu16LE : bingetu16;
170 for (integer i = 1; i <= my nx; i ++)
171 my z [1] [i] = get (f) / 32768.0 - 1.0;
172 }
173
174 static void i4write (Sound me, FILE *f, bool littleEndian, integer *nClip) {
175 const double min = -2147483648.0, max = 2147483647.0;
176 void (*put) (int32, FILE *) = littleEndian ? binputi32LE : binputi32;
177 *nClip = 0;
178 for (integer i = 1; i <= my nx; i ++) {
179 double sample = round (my z [1] [i] * 2147483648.0);
180 if (sample > max) {
181 sample = max;
182 (*nClip) ++;
183 } else if (sample < min) {
184 sample = min;
185 (*nClip) ++;
186 }
187 put ((int32) sample, f);
188 }
189 }
190
191 static void i4read (Sound me, FILE *f, bool littleEndian) {
192 int32 (*get) (FILE *) = littleEndian ? bingeti32LE : bingeti32;
193 for (integer i = 1; i <= my nx; i ++)
194 my z [1] [i] = get (f) / 2147483648.0;
195 }
196
197
198 static void u4write (Sound me, FILE *f, bool littleEndian, integer *nClip) {
199 const double min = 0.0, max = 4294967295.0;
200 void (*put) (uint32, FILE *) = littleEndian ? binputu32LE : binputu32;
201 *nClip = 0;
202 for (integer i = 1; i <= my nx; i ++) {
203 double sample = Melder_round_tieUp (my z [1] [i] * 4294967295.0);
204 if (sample > max) {
205 sample = max;
206 (*nClip) ++;
207 } else if (sample < min) {
208 sample = min;
209 (*nClip) ++;
210 }
211 put ((uint32) sample, f);
212 }
213 }
214
215 static void u4read (Sound me, FILE *f, bool littleEndian) {
216 int32 (*get) (FILE *) = littleEndian ? bingeti32LE : bingeti32;
217 for (integer i = 1; i <= my nx; i ++)
218 my z [1] [i] = get (f) / 2147483648.0 - 1.0;
219 }
220
221
222 static void r4write (Sound me, FILE *f) {
223 for (integer i = 1; i <= my nx; i ++)
224 binputr32 (my z [1] [i], f);
225 }
226
227 static void r4read (Sound me, FILE *f) {
228 for (integer i = 1; i <= my nx; i ++)
229 my z [1] [i] = bingetr32 (f);
230 }
231
232 /* Old TIMIT sound-file format */
233 autoSound Sound_readFromCmuAudioFile (MelderFile file) {
234 try {
235 constexpr bool littleEndian = true;
236 autofile f = Melder_fopen (file, "rb");
237 Melder_require (bingeti16LE (f) == 6,
238 U"Incorrect header size.");
239
240 bingeti16LE (f);
241 const short nChannels = bingeti16LE (f);
242 Melder_require (nChannels == 1,
243 U"Incorrect number of channels.");
244 Melder_require (bingeti16LE (f) > 0,
245 U"Incorrect sampling frequency.");
246
247 const integer nSamples = bingeti32LE (f);
248 Melder_require (nSamples > 0,
249 U"Incorrect number of samples.");
250
251 autoSound me = Sound_createSimple (1, nSamples / 16000.0, 16000);
252 i2read (me.get(), f, littleEndian);
253 f.close (file);
254 return me;
255 } catch (MelderError) {
256 Melder_throw (U"Sound not read from CMU audio file ", MelderFile_messageName (file), U".");
257 }
258 }
259
260 autoSound Sound_readFromRawFile (MelderFile file, const char *format, int nBitsCoding, bool littleEndian, bool unSigned, integer skipNBytes, double samplingFrequency) {
261 try {
262 autofile f = Melder_fopen (file, "rb");
263 if (! format)
264 format = "integer";
265 if (nBitsCoding <= 0)
266 nBitsCoding = 16;
267 integer nBytesPerSample = (nBitsCoding + 7) / 8;
268 if (strequ (format, "float"))
269 nBytesPerSample = 4;
270 Melder_require (! (nBytesPerSample == 3),
271 U"Number of bytes per sample should be 1, 2 or 4.");
272
273 if (skipNBytes <= 0)
274 skipNBytes = 0;
275 const integer nSamples = (MelderFile_length (file) - skipNBytes) / nBytesPerSample;
276 Melder_require (nSamples > 0,
277 U"No samples left to read.");
278
279 autoSound me = Sound_createSimple (1, nSamples / samplingFrequency, samplingFrequency);
280 fseek (f, skipNBytes, SEEK_SET);
281 if (nBytesPerSample == 1 && unSigned)
282 u1read (me.get(), f);
283 else if (nBytesPerSample == 1 && ! unSigned)
284 i1read (me.get(), f);
285 else if (nBytesPerSample == 2 && unSigned)
286 u2read (me.get(), f, littleEndian);
287 else if (nBytesPerSample == 2 && ! unSigned)
288 i2read (me.get(), f, littleEndian);
289 else if (nBytesPerSample == 4 && unSigned)
290 u4read (me.get(), f, littleEndian);
291 else if (nBytesPerSample == 4 && ! unSigned)
292 i4read (me.get(), f, littleEndian);
293 else if (nBytesPerSample == 4 && strequ (format, "float"))
294 r4read (me.get(), f);
295 f.close (file);
296 return me;
297 } catch (MelderError) {
298 Melder_throw (U"Sound not read from raw audio file ", MelderFile_messageName (file), U".");
299 }
300 }
301
302 void Sound_writeToRawFile (Sound me, MelderFile file, const char *format, bool littleEndian, int nBitsCoding, bool unSigned) {
303 try {
304 integer nClip = 0;
305 autofile f = Melder_fopen (file, "wb");
306 if (! format)
307 format = "integer";
308 if (nBitsCoding <= 0)
309 nBitsCoding = 16;
310 integer nBytesPerSample = (nBitsCoding + 7) / 8;
311 if (strequ (format, "float"))
312 nBytesPerSample = 4;
313 Melder_require (! (nBytesPerSample == 3),
314 U"number of bytes per sample should be 1, 2 or 4.");
315
316 if (nBytesPerSample == 1 && unSigned)
317 u1write (me, f, & nClip);
318 else if (nBytesPerSample == 1 && ! unSigned)
319 i1write (me, f, & nClip);
320 else if (nBytesPerSample == 2 && unSigned)
321 u2write (me, f, littleEndian, & nClip);
322 else if (nBytesPerSample == 2 && ! unSigned)
323 i2write (me, f, littleEndian, & nClip);
324 else if (nBytesPerSample == 4 && unSigned)
325 u4write (me, f, littleEndian, & nClip);
326 else if (nBytesPerSample == 4 && ! unSigned)
327 i4write (me, f, littleEndian, & nClip);
328 else if (nBytesPerSample == 4 && strequ (format, "float"))
329 r4write (me, f);
330 if (nClip > 0)
331 Melder_warning (nClip, U" from ", my nx, U" samples have been clipped.\nAdvice: you could scale the amplitudes or save as a binary file.");
332
333 Melder_require (feof ((FILE *) f) == 0 && ferror ((FILE *) f) == 0,
334 U"Sound_writeToRawFile: not completed");
335
336 f.close (file);
337 } catch (MelderError) {
338 Melder_throw (me, U": saving as raw file not performed.");
339 }
340 }
341
342 struct dialogic_adpcm {
343 char code;
344 short last, index;
345 short step_size [49];
346 short adjust [8];
347 };
348
349 static void dialogic_adpcm_init (struct dialogic_adpcm *adpcm) {
350 constexpr short step_size [49] = {
351 16, 17, 19, 21, 23, 25, 28, 31, 34, 37,
352 41, 45, 50, 55, 60, 66, 73, 80, 88, 97,
353 107, 118, 130, 143, 157, 173, 190, 209, 230, 253,
354 279, 307, 337, 371, 408, 449, 494, 544, 598, 658,
355 724, 796, 876, 963, 1060, 1166, 1282, 1411, 1552
356 };
357 constexpr short adjust [8] = { -1, -1, -1, -1, 2, 4, 6, 8 };
358
359 adpcm -> last = 0;
360 adpcm -> index = 0;
361 for (integer i = 0; i < 49; i ++)
362 adpcm -> step_size [i] = step_size [i];
363 for (integer i = 0; i < 8; i ++)
364 adpcm -> adjust [i] = adjust [i];
365 }
366
367 /*
368 The code is adapted from:
369 Bob Edgar (), "PC Telephony - The complete guide to designing,
370 building and programming systems using Dialogic and Related
371 Hardware", 272-276.
372 */
373 static float dialogic_adpcm_decode (struct dialogic_adpcm *adpcm) {
374 constexpr float scale = 32767.0 / 32768.0 / 2048.0;
375 /*
376 nibble = B3 B2 B1 B0 (4 lower bits)
377 d(n) = ss(n)*B2 + ss(n)/2 *B1 + ss(n)/4*B0 + ss(n)/8
378 */
379 const short ss = adpcm -> step_size [adpcm -> index];
380 short e = ss / 8;
381 if (adpcm -> code & 0x01)
382 e += ss / 4;
383 if (adpcm -> code & 0x02)
384 e += ss / 2;
385 if (adpcm -> code & 0x04)
386 e += ss;
387 /*
388 If B3==1 then d(n) = -d(n);
389 */
390 const short diff = (adpcm -> code & 0x08) ? -e : e;
391 /*
392 x(n) = x(n-1)+d(n)
393 */
394 short s = adpcm -> last + diff;
395 if (s > 2048)
396 s = 2048;
397 if (s < -2048)
398 s = -2048;
399 adpcm -> last = s;
400 /*
401 ss(n+1) = ss(n) * 1.1*M(L(n)) via lookup table
402 */
403 adpcm -> index += adpcm -> adjust [adpcm -> code & 0x07];
404 if (adpcm -> index < 0)
405 adpcm -> index = 0;
406 if (adpcm -> index > 48)
407 adpcm -> index = 48;
408 return scale * s;
409 }
410
411 autoSound Sound_readFromDialogicADPCMFile (MelderFile file, double sampleRate) {
412 try {
413 autofile f = Melder_fopen (file, "rb");
414
415 const integer filelength = MelderFile_length (file);
416
417 Melder_require (filelength > 0,
418 U"File should not be empty.");
419
420 const integer numberOfSamples = 2 * filelength; // Two samples in each byte
421
422 autoSound me = Sound_createSimple (1, numberOfSamples / sampleRate, sampleRate);
423 /*
424 Read all bytes and decode
425 */
426 struct dialogic_adpcm adpcm;
427 dialogic_adpcm_init (& adpcm);
428
429 integer n = 1;
430 for (integer i = 1; i <= filelength; i ++) {
431 unsigned char sc;
432 const integer nread = fread (& sc, 1, 1, f);
433 Melder_require (nread == 1,
434 U"Error: trying to read byte number ", i, U".");
435 adpcm.code = (char) ((sc >> 4) & 0x0f);
436 my z [1] [n ++] = dialogic_adpcm_decode (& adpcm);
437 adpcm.code = (char) (sc & 0x0f);
438 my z [1] [n ++] = dialogic_adpcm_decode (& adpcm);
439 }
440 f.close (file);
441 return me;
442 } catch (MelderError) {
443 Melder_throw (U"Sound not read from Dialogic ADPCM file ", MelderFile_messageName (file), U".");
444 }
445 }
446
447 /*
448 The code in this Ogg Vorbis file reader was modeled after code in vorbisfile.c and vorbis_decoder.c.
449 */
450 autoSound Sound_readFromOggVorbisFile (MelderFile file) {
451 try {
452 autofile f = Melder_fopen (file, "rb");
453
454 /*
455 We open the file as a vorbis file as was done in the vorbisfile_example.c in libvorbis-1.3.7/examples
456 and get the data necessary to create the Sound object.
457 Then we rewind the file and use code from decode_example.c because the code in the vorbisfile_example
458 does not read the file completely but skips some samples just after the start of the sound.
459 */
460 OggVorbis_File vorbisFile;
461 if (ov_open_callbacks (f, & vorbisFile, nullptr, 0, OV_CALLBACKS_NOCLOSE) < 0)
462 Melder_throw (U"Input does not appear to be an Ogg Vorbis bitstream.");
463 vorbis_info *vorbInfo = ov_info (& vorbisFile, -1);
464 const integer numberOfChannels = vorbInfo -> channels;
465 const long samplingFrequency_asLong = vorbInfo -> rate;
466 const double samplingFrequency = samplingFrequency_asLong;
467 const double samplingTime = 1.0 / samplingFrequency;
468 const integer numberOfSamples = ov_pcm_total (& vorbisFile, -1);
469 double xmin = 0.0; // the start time in the file can be > 0!!!
470 const double xmax = numberOfSamples * samplingTime;
471 autoSound me = Sound_create (numberOfChannels, xmin, xmax, numberOfSamples, samplingTime, 0.5 * samplingTime);
472
473 ov_clear (& vorbisFile);
474 rewind (f);
475
476 const long readBufferSize = 4096;
477 integer numberOfPCMValuesProcessed = 0;
478
479 ogg_sync_state oggSyncState; // sync and verify incoming physical bitstream
480 ogg_sync_init (& oggSyncState); // Now we can read pages
481
482 integer vorbisChainNumber = 0;
483 while (true) { // we repeat if the bitstream is chained
484 vorbisChainNumber ++;
485 /*
486 Grab some data at the head of the stream. We want the first page
487 (which is guaranteed to be small and only contain the Vorbis
488 stream initial header) We need the first page to get the stream
489 serialno.
490
491 Submit a 4k block to libvorbis' Ogg layer
492 */
493 char *readBuffer = ogg_sync_buffer (& oggSyncState, readBufferSize);
494 size_t bytesRead = fread (readBuffer, 1, readBufferSize, f);
495 ogg_sync_wrote (& oggSyncState, bytesRead);
496
497 /* Get the first page. */
498 ogg_page oggPage; // one Ogg bitstream page. Vorbis packets are inside
499 if (ogg_sync_pageout (& oggSyncState, & oggPage) != 1) {
500 if (bytesRead < readBufferSize) // have we simply run out of data? If so, we're done.
501 break;
502 Melder_throw (U"Input does not appear to be an Ogg Vorbis file.");
503 }
504 /*
505 Get the serial number and set up the rest of decode.
506 serialno first; use it to set up a logical stream
507 */
508 ogg_stream_state oggStream; // take physical pages, weld into a logical stream of packets
509 ogg_stream_init (& oggStream, ogg_page_serialno (& oggPage));
510 /*
511 Extract the initial header from the first page and verify that the
512 Ogg bitstream is in fact Vorbis data
513
514 I handle the initial header first instead of just having the code
515 read all three Vorbis headers at once because reading the initial
516 header is an easy way to identify a Vorbis bitstream and it's
517 useful to see that functionality separated out.
518 */
519 vorbis_info vorbisInfo; // struct that stores all the static vorbis bitstream settings
520 vorbis_info_init (& vorbisInfo);
521 vorbis_comment vorbisComment; // struct that stores all the bitstream user comments
522 vorbis_comment_init (& vorbisComment);
523 if (ogg_stream_pagein (& oggStream, & oggPage) < 0)
524 Melder_throw (U"Error reading first page of Ogg Vorbis bitstream data.");
525 ogg_packet oggPacket; // one raw packet of data for decode
526 if (ogg_stream_packetout (& oggStream, & oggPacket) != 1)
527 Melder_throw (U"Error reading initial header packet.");
528 if (vorbis_synthesis_headerin (& vorbisInfo, & vorbisComment, & oggPacket) < 0)
529 Melder_throw (U"This Ogg bitstream does not contain Vorbis audio data.");
530 /*
531 At this point, we're sure we're Vorbis. We've set up the logical
532 (Ogg) bitstream decoder. Get the comment and codebook headers and
533 set up the Vorbis decoder
534
535 The next two packets in order are the comment and codebook headers.
536 They're likely large and may span multiple pages. Thus we read
537 and submit data until we get our two packets, watching that no
538 pages are missing. If a page is missing, error out; losing a
539 header page is the only place where missing data is fatal.
540 */
541 integer i = 0;
542 bool eos = false;
543 while (i < 2) {
544 while(i < 2) {
545 int result = ogg_sync_pageout (& oggSyncState, & oggPage);
546 if (result == 0)
547 break; // Need more data
548 /*
549 Don't complain about missing or corrupt data yet.
550 We'll catch it at the packet output phase
551 */
552 if (result == 1) {
553 ogg_stream_pagein (& oggStream, & oggPage);
554 // we can ignore any errors here as they'll also become apparent at packetout
555 while (i < 2) {
556 result = ogg_stream_packetout (& oggStream, & oggPacket);
557 if (result == 0)
558 break;
559 if (result < 0)
560 Melder_throw (U"Corrupt secondary header.");
561 result = vorbis_synthesis_headerin (& vorbisInfo, & vorbisComment, & oggPacket);
562 if (result < 0)
563 Melder_throw (U"Corrupt secondary header.");
564 i ++;
565 }
566 }
567 }
568 readBuffer = ogg_sync_buffer (& oggSyncState, readBufferSize);
569 bytesRead = fread (readBuffer, 1, readBufferSize, f);
570 if (bytesRead == 0 && i < 2)
571 Melder_throw (U"End of file before finding all Vorbis headers");
572 ogg_sync_wrote (& oggSyncState, bytesRead);
573 }
574 Melder_require (vorbisInfo.channels == numberOfChannels,
575 U"The number of channels in all chains should be equal. It changed from ", numberOfChannels, U" to ",
576 vorbisInfo.channels, U" in chain ", vorbisChainNumber, U".");
577 Melder_require (samplingFrequency_asLong == vorbisInfo.rate,
578 U"The sampling frequency in all chains should be equal. It changed from ", samplingFrequency_asLong, U" to ",
579 vorbisInfo.rate, U" in chain ", vorbisChainNumber, U".");
580 /*
581 Parsed all three headers. Initialize the Vorbis packet->PCM decoder.
582 */
583 vorbis_dsp_state vorbisDspState; // central working state for the packet->PCM decoder
584 vorbis_block vorbisBlock; // local working space for packet->PCM decode
585 if (vorbis_synthesis_init (& vorbisDspState, & vorbisInfo) == 0) { // central decode state
586 vorbis_block_init (& vorbisDspState, & vorbisBlock);
587 /*
588 local state for most of the decode so multiple block decodes can proceed in parallel.
589 We could init multiple vorbis_block structures for vorbisDspState here
590
591 The rest is just a straight decode loop until end of stream
592 */
593 while (! eos) {
594 while (! eos) {
595 int result = ogg_sync_pageout (& oggSyncState, & oggPage);
596 if (result == 0)
597 break; // need more data
598 if (result < 0)
599 Melder_casual (U"Corrupt or missing data in Vorbis bitstream; continuing...");
600 else {
601 ogg_stream_pagein (& oggStream, & oggPage); // can safely ignore errors at this point
602 while (true) {
603 result = ogg_stream_packetout (& oggStream, & oggPacket);
604 if (result == 0)
605 break; // need more data
606 if (result < 0){
607 /*
608 missing or corrupt data at this page position
609 no reason to complain; already complained above
610 */
611 } else {
612 /*
613 we have a packet. Decode it
614 */
615 if (vorbis_synthesis (& vorbisBlock, & oggPacket) == 0)
616 vorbis_synthesis_blockin (& vorbisDspState, & vorbisBlock);
617 float **pcmOutFloats;
618 integer numberOfSamplesDecoded;
619 /*
620 The output from vorbis_synthesis_pcmout is a multichannel float vector. In stereo, for
621 example, pcmOutFloats [0] is the left channel, and pcmOutFloats [1] is the right.
622 The numberOfSamplesDecoded is the size of each channel, where all
623 floats are in the interval [-1.0, 1.0].
624 */
625 while ((numberOfSamplesDecoded = vorbis_synthesis_pcmout (& vorbisDspState, & pcmOutFloats)) > 0) {
626 Melder_require (numberOfPCMValuesProcessed + numberOfSamplesDecoded <= numberOfSamples,
627 U"The number of samples read is too large.");
628 for (integer ichan = 1; ichan <= vorbisInfo.channels; ichan ++){
629 float *oneChannelFloats = pcmOutFloats [ichan - 1];
630 for (integer j = 1; j <= numberOfSamplesDecoded; j ++)
631 my z [ichan] [numberOfPCMValuesProcessed + j] = oneChannelFloats [j - 1];
632 }
633 numberOfPCMValuesProcessed += numberOfSamplesDecoded;
634 /*
635 Tell libvorbis how many samples we actually consumed
636 */
637 vorbis_synthesis_read (& vorbisDspState, numberOfSamplesDecoded);
638 }
639 }
640 }
641 if (ogg_page_eos (& oggPage))
642 eos = true;
643 }
644 }
645 if (! eos) {
646 readBuffer = ogg_sync_buffer (& oggSyncState, readBufferSize);
647 bytesRead = fread (readBuffer, 1, readBufferSize, f);
648 ogg_sync_wrote (& oggSyncState, bytesRead);
649 if (bytesRead == 0)
650 eos = true;
651 }
652 }
653 /*
654 ogg_page and ogg_packet structs always point to storage in
655 libvorbis. They're never freed or manipulated directly
656 */
657 vorbis_block_clear (& vorbisBlock);
658 vorbis_dsp_clear (& vorbisDspState);
659 } else {
660 Melder_throw (U"Corrupt header during playback initialization");
661 }
662 /*
663 Clean up this logical bitstream; before exit we see if we're
664 followed by another [chained]
665 */
666 ogg_stream_clear (& oggStream);
667 vorbis_comment_clear (& vorbisComment);
668 vorbis_info_clear (& vorbisInfo); // must be called last
669 }
670 ogg_sync_clear (& oggSyncState);
671 return me;
672 } catch (MelderError) {
673 Melder_throw (U"Sound not read from Ogg Vorbis file ", MelderFile_messageName (file), U".");
674 }
675 }
676
677 autoSound Sound_readFromOggOpusFile (MelderFile file) {
678 try {
679 int error;
680 OggOpusFile *opusFile = op_open_file (MelderFile_peekPath8 (file), & error);
681 if (error != 0) {
682 if (error == OP_EREAD)
683 Melder_throw (U"Reading error.");
684 else if (error == OP_EFAULT)
685 Melder_throw (U"Memory error.");
686 else if (error == OP_EIMPL)
687 Melder_throw (U"Feature is not implemented.");
688 else if (error == OP_EINVAL)
689 Melder_throw (U"Seek function error.");
690 else if (error == OP_ENOTFORMAT)
691 Melder_throw (U"Link doea not have any logical Opus streams.");
692 else if (error == OP_EBADHEADER)
693 Melder_throw (U"Malformed header.");
694 else if (error == OP_EVERSION)
695 Melder_throw (U"Unrecognised version number.");
696 else if (error == OP_EBADLINK)
697 Melder_throw (U"Failed to find data.");
698 else if (error == OP_EBADTIMESTAMP)
699 Melder_throw (U"invalid time stamp.");
700 }
701 const OpusHead *head = op_head (opusFile, 0);
702 integer samplingFrequency_asLong = head -> input_sample_rate;
703 if (samplingFrequency_asLong == 0)
704 samplingFrequency_asLong = 44100;
705 const integer numberOfChannels = head -> channel_count;
706 const double samplingTime = 1.0 / 48000.0; // fixed decoding rate
707 const integer numberOfSamples = op_pcm_total (opusFile, -1);
708 double xmin = 0.0; // the start time in the file can be > 0!!!
709 const double xmax = numberOfSamples * samplingTime;
710 autoSound me = Sound_create (numberOfChannels, xmin, xmax, numberOfSamples, samplingTime, 0.5 * samplingTime);
711 const integer maximumBufferSize = 5760 * numberOfChannels; // 0.12 s at 48 kHz * numberOfChannels
712 autovector<float> multiChannelFloats = autovector<float> (maximumBufferSize, MelderArray::kInitializationType::RAW);
713 integer numberOfPCMValuesProcessed = 0;
714 int previousLinkIndex = -1;
715 integer opusChainNumber = 0;
716 while (true) {
717 int linkIndex;
718
719 integer numberOfSamplesDecoded = op_read_float (opusFile, multiChannelFloats.asArgumentToFunctionThatExpectsZeroBasedArray(), maximumBufferSize, & linkIndex);
720 if (numberOfSamplesDecoded < 0) {
721 if (numberOfSamplesDecoded == OP_HOLE) {
722 Melder_casual (U"Warning: Hole in data. Some samples may be skipped. "); // should we throw instead?
723 continue;
724 } else
725 Melder_throw (U"Decoding error.");
726 }
727 if (numberOfSamplesDecoded == 0)
728 break; // we're done
729
730 if (linkIndex != previousLinkIndex) {
731 opusChainNumber ++;
732
733 head = op_head (opusFile, linkIndex);
734 Melder_require (head -> channel_count == numberOfChannels,
735 U"The number of channels in all chains should be equal. It changed from ", numberOfChannels, U" to ",
736 head -> channel_count, U" in chain ", opusChainNumber, U".");
737 Melder_require (samplingFrequency_asLong == head -> input_sample_rate,
738 U"The sampling frequency in all chains should be equal. It changed from ", samplingFrequency_asLong, U" to ",
739 head -> input_sample_rate, U" in chain ", opusChainNumber, U".");
740 }
741 previousLinkIndex = linkIndex;
742 Melder_require (numberOfPCMValuesProcessed + numberOfSamplesDecoded <= numberOfSamples,
743 U"The number of samples read is too large.");
744 integer ifloat = 1;
745 for (integer j = 1; j <= numberOfSamplesDecoded; j ++)
746 for (integer ichan = 1; ichan <= numberOfChannels; ichan ++, ifloat ++){
747 my z [ichan] [numberOfPCMValuesProcessed + j] = multiChannelFloats [ifloat];
748 }
749 numberOfPCMValuesProcessed += numberOfSamplesDecoded;
750 }
751 if (samplingFrequency_asLong != 48000)
752 me = Sound_resample (me.get(), samplingFrequency_asLong, 50);
753 return me;
754 } catch (MelderError) {
755 Melder_throw (U"Sound not read from Ogg Opus file ", MelderFile_messageName (file), U".");
756 }
757 }
758
759 /*
760 The time derivative of a Sound can most easily be calculated in the spectral domain
761 in which a sound s(t) can represented as
762 s(t) = integral (S(f) exp(2*pi*i*f*t) * df), where S(f) is the complex spectrum.
763 The time derivative is:
764 d(s(t)/dt = integral (S(f)*2*pi*i*f * d/dt(exp(2*pi*f*t)) * df)
765 = integral (S(f)*2*pi*i*f * exp(2*pi*f*t) * df)
766 = (2*pi*f) * integral (i*S(f) * exp (2*pi*f*t) * df)
767 = (2*pi*f) * integral (-Im(S), Re (s)) * exp (2*pi*f*t) * df)
768 Transforming back to the time domain gives the desired result.
769 */
770 autoSound Sound_derivative (Sound me, double lowPassFrequency, double smoothing, double peakAmplitude) {
771 try {
772 autoSpectrum thee = Sound_to_Spectrum (me, false);
773 for (integer ifreq = 1; ifreq <= thy nx - 1; ifreq ++) {
774 const double frequency = Sampled_indexToX (thee.get(), ifreq);
775 const double im = thy z [2] [ifreq];
776 thy z [2] [ifreq] = NUM2pi * frequency * thy z [1] [ifreq]; // forget about scale factor 2*pi
777 thy z [1] [ifreq] = - NUM2pi * frequency * im;
778 }
779 thy z [2] [thy nx] = thy z [1] [thy nx] = 0.0;
780 Spectrum_passHannBand (thee.get(), 0.0, lowPassFrequency, smoothing);
781 autoSound him = Spectrum_to_Sound (thee.get());
782 if (peakAmplitude != 0.0)
783 Vector_scale (him.get(), peakAmplitude);
784 return him;
785 } catch (MelderError) {
786 Melder_throw (me, U": cannot create the derivative of the Sound.");
787 }
788 }
789
790 static autoSound Sound_derivative2 (Sound me, double lowPassFrequency, double smoothing, double peakAmplitude) {
791 try {
792 autoSpectrum thee = Sound_to_Spectrum (me, false);
793 for (integer ifreq = 1; ifreq <= thy nx; ifreq ++) {
794 const double frequency = Sampled_indexToX (thee.get(), ifreq);
795 const double im = thy z [2] [ifreq];
796 thy z [2] [ifreq] = NUM2pi * frequency * thy z [1] [ifreq]; // forget about scale factor 2*pi
797 thy z [1] [ifreq] = - NUM2pi * frequency * im;
798 }
799 const double nyquistFrequency = 0.5 / my dx;
800 if (lowPassFrequency < nyquistFrequency)
801 Spectrum_passHannBand (thee.get(), 0.0, lowPassFrequency, smoothing);
802 autoSound him = Spectrum_to_Sound (thee.get());
803 if (peakAmplitude != 0.0)
804 Vector_scale (him.get(), peakAmplitude);
805 return him;
806 } catch (MelderError) {
807 Melder_throw (me, U": cannot create the derivative of the Sound.");
808 }
809 }
810
811 autoSound Sound_createGaussian (double windowDuration, double samplingFrequency) {
812 try {
813 autoSound me = Sound_createSimple (1, windowDuration, samplingFrequency);
814 VEC s = my z.row (1);
815 const double imid = 0.5 * (my nx + 1), edge = exp (-12.0);
816 for (integer i = 1; i <= my nx; i ++) {
817 const double phase = (i - imid) / my nx; // conforms to standard
818 // const double phase = (i - imid) / (my nx + 1); // behaviour <= 6.4.23
819 s [i] = (exp (-48.0 * phase * phase) - edge) / (1 - edge);
820 }
821 return me;
822 } catch (MelderError) {
823 Melder_throw (U"Sound not created from Gaussian function.");
824 }
825 }
826
827 autoSound Sound_createHamming (double windowDuration, double samplingFrequency) {
828 try {
829 autoSound me = Sound_createSimple (1, windowDuration, samplingFrequency);
830 const double p = NUM2pi / (my nx - 1);
831 for (integer i = 1; i <= my nx; i ++)
832 my z [1] [i] = 0.54 - 0.46 * cos ((i - 1) * p);
833 return me;
834 } catch (MelderError) {
835 Melder_throw (U"Sound not created from Hamming function.");
836 };
837 }
838
839 static autoSound Sound_create2 (double minimumTime, double maximumTime, double samplingFrequency) {
840 return Sound_create (1, minimumTime, maximumTime, Melder_iround ((maximumTime - minimumTime) * samplingFrequency),
841 1.0 / samplingFrequency, minimumTime + 0.5 / samplingFrequency);
842 }
843
844 /*
845 Trig functions whose arguments form a linear sequence x = x1 + n.dx,
846 for n=0,1,2,... are efficiently calculated by the following recurrence:
847 cos(a+dx) = cos(a) - (alpha . cos(a) + beta . sin(a))
848 sin(a+dx) = sin(a) - (alpha . sin(a) - beta . sin(a))
849 where alpha and beta are precomputed coefficients
850 alpha = 2 sin^2(dx/2) and beta = sin(dx)
851 In this way alpha and beta do not lose significance if the increment
852 dx is small.
853 */
854
855 static autoSound Sound_createToneComplex (double minimumTime, double maximumTime, double samplingFrequency, double firstFrequency,
856 integer numberOfComponents, double frequencyDistance, integer mistunedComponent, double mistuningFraction, bool scaleAmplitudes)
857 {
858 try {
859 autoSound me = Sound_create2 (minimumTime, maximumTime, samplingFrequency);
860 for (integer j = 1; j <= numberOfComponents; j ++) {
861 const double fraction = ( j == mistunedComponent ? mistuningFraction : 0.0 );
862 const double w = NUM2pi * (firstFrequency + (j - 1 + fraction) * frequencyDistance);
863 const double delta = w * my dx;
864 const double alpha = 2.0 * sin (delta / 2.0) * sin (delta / 2.0);
865 const double beta = sin (delta);
866 double sint = sin (w * my x1);
867 double cost = cos (w * my x1);
868 my z [1] [1] += sint;
869 for (integer i = 2; i <= my nx; i ++) {
870 const double costd = cost - (alpha * cost + beta * sint);
871 const double sintd = sint - (alpha * sint - beta * cost);
872 my z [1] [i] += sintd;
873 cost = costd;
874 sint = sintd;
875 }
876 }
877 if (scaleAmplitudes)
878 Vector_scale (me.get(), 0.99996948);
879 return me;
880 } catch (MelderError) {
881 Melder_throw (U"Sound not created from tone complex.");
882 }
883 }
884
885
886 autoSound Sound_createSimpleToneComplex (double minimumTime, double maximumTime, double samplingFrequency, double firstFrequency,
887 integer numberOfComponents, double frequencyDistance, bool scaleAmplitudes)
888 {
889 if (firstFrequency + (numberOfComponents - 1) * frequencyDistance > samplingFrequency / 2) {
890 Melder_warning (U"Sound_createSimpleToneComplex: frequency of (some) components too high.");
891 numberOfComponents = Melder_ifloor (1.0 + (0.5 * samplingFrequency - firstFrequency) / frequencyDistance);
892 }
893 return Sound_createToneComplex (minimumTime, maximumTime, samplingFrequency,
894 firstFrequency, numberOfComponents, frequencyDistance, 0, 0, scaleAmplitudes);
895 }
896
897 autoSound Sound_createMistunedHarmonicComplex (double minimumTime, double maximumTime, double samplingFrequency, double firstFrequency,
898 integer numberOfComponents, integer mistunedComponent, double mistuningFraction, bool scaleAmplitudes)
899 {
900 if (firstFrequency + (numberOfComponents - 1) * firstFrequency > samplingFrequency / 2) {
901 Melder_warning (U"Sound_createMistunedHarmonicComplex: frequency of (some) components too high.");
902 numberOfComponents = Melder_ifloor (1.0 + (0.5 * samplingFrequency - firstFrequency) / firstFrequency);
903 }
904 if (mistunedComponent > numberOfComponents) {
905 Melder_warning (U"Sound_createMistunedHarmonicComplex: mistuned component too high.");
906 }
907 return Sound_createToneComplex (minimumTime, maximumTime, samplingFrequency, firstFrequency, numberOfComponents, firstFrequency, mistunedComponent, mistuningFraction, scaleAmplitudes);
908 }
909
910 /*
911 The gammachirp is a "chirp tone" with a gamma-function envelope:
912 f(t) = t^(n-1) exp (-2 pi b t) cos (2 pi f0 t + c ln (t) + p0)
913 = t^(n-1) exp (-2 pi b t) cos (phi(t))
914 Instantaneous frequency f is defined as f = d phi(t) / dt / (2 pi)
915 and so: f = f0 + c /(2 pi t)
916 Irino: bandwidth = (frequency * (6.23e-6 * frequency + 93.39e-3) + 28.52)
917 */
918 autoSound Sound_createGammaTone (double minimumTime, double maximumTime, double samplingFrequency, double gamma, double frequency, double bandwidth, double initialPhase, double addition, bool scaleAmplitudes) {
919 try {
920 autoSound me = Sound_create2 (minimumTime, maximumTime, samplingFrequency);
921 for (integer i = 1; i <= my nx; i ++) {
922 const double t = (i - 0.5) * my dx;
923 const double f = frequency + addition / (NUM2pi * t);
924 if (f > 0 && f < samplingFrequency / 2)
925 my z [1] [i] = pow (t, gamma - 1.0) * exp (- NUM2pi * bandwidth * t) *
926 cos (NUM2pi * frequency * t + addition * log (t) + initialPhase);
927 }
928 if (scaleAmplitudes)
929 Vector_scale (me.get(), 0.99996948);
930 return me;
931 } catch (MelderError) {
932 Melder_throw (U"Sound not created from gammatone function.");
933 }
934 }
935
936 #if 0
937 // This routine is unstable for small values of f and large b. Better to use cross-correlation of gammatone with sound.
938 static void NUMgammatoneFilter4 (double *x, double *y, integer n, double centre_frequency, double bandwidth, double samplingFrequency) {
939 double a [5], b [9], dt = 1.0 / samplingFrequency, wt = NUMpi * centre_frequency * dt;
940 double bt = 2 * NUMpi * bandwidth * dt, dt2 = dt * dt, dt4 = dt2 * dt2;
941
942 Melder_assert (n > 0 && centre_frequency > 0 && bandwidth >= 0 && samplingFrequency > 0);
943
944 /*
945 The filter function is:
946 H(z) = sum (i=0..4, a [i] z^-i) / sum (j=0..4, b [j] z^-j)
947 Coefficients a & b according to:
948 Slaney (1993), An efficient implementation of the Patterson-Holdsworth
949 auditory filterbank, Apple Computer Technical Report 35, 41 pages.
950 For the a's we have left out an overall scale factor of dt^4.
951 This makes a [0] = 1.
952 */
953
954 a [0] = dt4;
955 a [1] = -4 * dt4 * cos (2 * wt) * exp (- bt);
956 a [2] = 6 * dt4 * cos (4 * wt) * exp (-2 * bt);
957 a [3] = -4 * dt4 * cos (6 * wt) * exp (-3 * bt);
958 a [4] = dt4 * cos (8 * wt) * exp (-4 * bt);
959
960 b [0] = 1;
961 b [1] = -8 * cos (2 * wt) * exp (- bt);
962 b [2] = (16 + 12 * cos (4 * wt)) * exp (-2 * bt);
963 b [3] = (-48 * cos (2 * wt) - 8 * cos (6 * wt)) * exp (-3 * bt);
964 b [4] = (36 + 32 * cos (4 * wt) + 2 * cos (8 * wt)) * exp (-4 * bt);
965 b [5] = (-48 * cos (2 * wt) - 8 * cos (6 * wt)) * exp (-5 * bt);
966 b [6] = (16 + 12 * cos (4 * wt)) * exp (-6 * bt);
967 b [7] = -8 * cos (2 * wt) * exp (-7 * bt);
968 b [8] = exp (-8 * bt);
969
970 // Calculate gain (= Abs (H(z); f=fc) and scale a [0-4] with it.
971
972 double zr = cos (2 * wt), zi = -sin (2 * wt);
973 double dr = a [4], di = 0, tr, ti, nr, ni;
974
975 for (integer j = 1; j <= 4; j ++) {
976 tr = a [4 - j] + zr * dr - zi * di;
977 ti = zi * dr + zr * di;
978 dr = tr; di = ti;
979 }
980
981 dr = b [8];
982 di = 0;
983 for (integer j = 1; j <= 8; j ++) {
984 nr = b [8 - j] + zr * dr - zi * di;
985 ni = zi * dr + zr * di;
986 dr = nr; di = ni;
987 }
988
989 double n2 = nr * nr + ni * ni;
990 double gr = tr * nr + ti * ni;
991 double gi = ti * nr - tr * ni;
992 double gain = hypot (gr, gi) / n2;
993
994 for (integer j = 0; j <= 4; j ++) {
995 a [j] /= gain;
996 }
997
998 if (Melder_debug == -1) {
999 Melder_casual (
1000 U" --gammatonefilter4 --\nF = ", centre_frequency,
1001 U", B = ", bandwidth,
1002 U", T = ", dt,
1003 U"\nGain = ", gain
1004 );
1005 for (integer i = 0; i <= 4; i ++) {
1006 Melder_casual (U"a [", i, U"] = ", a [i]);
1007 }
1008 for (integer i = 0; i <= 8; i ++) {
1009 Melder_casual (U"b [", i, U"] = ", b [i]);
1010 }
1011 }
1012
1013 /* Perform the filtering. For the first 8 samples we must do some extra work.
1014 y [1] = a [0] * x [1];
1015 if (n > 1) {
1016 y [2] = a [0] * x [2];
1017 y [2] += a [1] * x [1] - b [1] * y [1];
1018 }
1019 if (n > 2) {
1020 y [2] = a [0] * x [2];
1021 y [2] += a [2] * x [i - 2] - b [2] * y [i - 2];
1022 }
1023 */
1024 integer n8 = n < 8 ? n : 8;
1025 for (integer i = 1; i <= n8; i ++) {
1026 y [i] = a [0] * x [i];
1027 if (i > 1) {
1028 y [i] += a [1] * x [i - 1] - b [1] * y [i - 1];
1029 } else {
1030 continue;
1031 }
1032 if (i > 2) {
1033 y [i] += a [2] * x [i - 2] - b [2] * y [i - 2];
1034 } else {
1035 continue;
1036 }
1037 if (i > 3) {
1038 y [i] += a [3] * x [i - 3] - b [3] * y [i - 3];
1039 } else {
1040 continue;
1041 }
1042 if (i > 4) {
1043 y [i] += a [4] * x [i - 4] - b [4] * y [i - 4];
1044 } else {
1045 continue;
1046 }
1047 if (i > 5) {
1048 y [i] -= b [5] * y [i - 5];
1049 } else {
1050 continue;
1051 }
1052 if (i > 6) {
1053 y [i] -= b [6] * y [i - 6];
1054 } else {
1055 continue;
1056 }
1057 if (i > 7) {
1058 y [i] -= b [7] * y [i - 7];
1059 }
1060 }
1061
1062 for (integer i = n8 + 1; i <= n; i ++) {
1063 // y [i] = a [0] * x [i];
1064 // y [i] += a [1] * x [i-1] + a [2] * x [i-2] + a [3] * x [i-3] + a [4] * x [i-4];
1065 // y [i] -= b [1] * y [i-1] + b [2] * y [i-2] + b [3] * y [i-3] + b [4] * y [i-4];
1066 // y [i] -= b [5] * y [i-5] + b [6] * y [i-6] + b [7] * y [i-7] + b [8] * y [i-8];
1067 y [i] = a [0] * x [i] + a [1] * x [i - 1] + a [2] * x [i - 2] + a [3] * x [i - 3] + a [4] * x [i - 4]
1068 - b [1] * y [i - 1] - b [2] * y [i - 2] - b [3] * y [i - 3] - b [4] * y [i - 4]
1069 - b [5] * y [i - 5] - b [6] * y [i - 6] - b [7] * y [i - 7] - b [8] * y [i - 8];
1070 }
1071 }
1072
1073 autoSound Sound_filterByGammaToneFilter4 (Sound me, double centre_frequency, double bandwidth) {
1074 try {
1075 Meldr_require (centre_frequency > 0,
1076 U"Centre frequency should be positive.");
1077 Melder_require (bandwidth > 0,
1078 U"Bandwidth should be positive.");
1079
1080 autoSound thee = Sound_create (my ny, my xmin, my xmax, my nx, my dx, my x1);
1081 autoVEC y = zero_VEC (my nx);
1082 autoVEC x = zero_VEC (my nx);
1083
1084 const double fs = 1.0 / my dx;
1085 for (integer channel = 1; channel <= my ny; channel ++) {
1086 for (integer i = 1; i <= my nx; i ++)
1087 x [i] = my z [channel] [i];
1088 NUMgammatoneFilter4 (x.asArgumentToFunctionThatExpectsOneBasedArray(), y.asArgumentToFunctionThatExpectsOneBasedArray(),
1089 my nx, centre_frequency, bandwidth, fs);
1090 for (integer i = 1; i <= my nx; i ++)
1091 thy z [channel] [i] = y [i];
1092 }
1093 return thee;
1094 } catch (MelderError) {
1095 Melder_throw (U"Sound not filtered by gammatone filter4.");
1096 }
1097 }
1098 #endif
1099
1100
1101 autoSound Sound_filterByGammaToneFilter4 (Sound me, double centre_frequency, double bandwidth) {
1102 return Sound_filterByGammaToneFilter (me, centre_frequency, bandwidth, 4.0, 0.0);
1103 }
1104
1105 autoSound Sound_filterByGammaToneFilter (Sound me, double centre_frequency, double bandwidth, double gamma, double initialPhase) {
1106 try {
1107 autoSound gammaTone = Sound_createGammaTone (my xmin, my xmax, 1.0 / my dx, gamma, centre_frequency, bandwidth, initialPhase, 0.0, 0);
1108 // kSounds_convolve_scaling_INTEGRAL, SUM, NORMALIZE, PEAK_099
1109 autoSound thee = Sounds_convolve (me, gammaTone.get(), kSounds_convolve_scaling::INTEGRAL, kSounds_convolve_signalOutsideTimeDomain::ZERO);
1110
1111 const dcomplex r = gammaToneFilterResponseAtCentreFrequency (centre_frequency, bandwidth, gamma, initialPhase, my xmax - my xmin);
1112
1113 const double scale = 1.0 / sqrt (r.real() * r.real() + r.imag() * r.imag());
1114 thy z.row (1) *= scale;
1115
1116 return thee;
1117 } catch (MelderError) {
1118 Melder_throw (U"Sound not filtered by gammatone filter4.");
1119 }
1120 }
1121
1122
1123 /*
1124 Sound Sound_createShepardTone (double minimumTime, double maximumTime, double samplingFrequency,
1125 double baseFrequency, double frequencyShiftFraction, double maximumFrequency, double amplitudeRange)
1126 {
1127 Sound me;
1128 integer i, j, nComponents = 1 + log2 (maximumFrequency / 2 / baseFrequency);
1129 double lmin = pow (10, - amplitudeRange / 10);
1130 double twoPi = NUM2pi, f = baseFrequency * (1 + frequencyShiftFraction);
1131 if (nComponents < 2)
1132 Melder_warning (U"Sound_createShepardTone: only 1 component.");
1133 Melder_casual (U"Sound_createShepardTone: ", nComponents, U" components.");
1134 if (! (me = Sound_create2 (minimumTime, maximumTime, samplingFrequency)))
1135 return nullptr; // BUG: pre-2014 error handling
1136
1137 for (j=1; j <= nComponents; j ++) {
1138 const double fj = f * pow (2, j-1), wj = twoPi * fj;
1139 const double amplitude = lmin + (1 - lmin) *
1140 (1 - cos (twoPi * log (fj + 1) / log (maximumFrequency + 1))) / 2;
1141 for (i = 1; i <= my nx; i ++)
1142 my z [1] [i] += amplitude * sin (wj * (i - 0.5) * my dx);
1143 }
1144 Vector_scale (me, 0.99996948);
1145 return me;
1146 }
1147 */
1148
1149 autoSound Sound_createShepardToneComplex (double minimumTime, double maximumTime, double samplingFrequency, double lowestFrequency, integer numberOfComponents, double frequencyChange_st, double amplitudeRange_dB, double octaveShiftFraction) {
1150 try {
1151 const double highestFrequency = lowestFrequency * pow (2, numberOfComponents);
1152 const double lmax_db = 0, lmin_db = lmax_db - fabs (amplitudeRange_dB);
1153
1154 Melder_require (highestFrequency <= samplingFrequency / 2.0,
1155 U"The highest frequency you want to generate is "
1156 U"above the Nyquist frequency. Choose a larger value for \"Sampling frequency\", or lower values for "
1157 U"\"Number of components\" or \"Lowest frequency\".");
1158 Melder_require (octaveShiftFraction >= 0.0 && octaveShiftFraction < 1.0,
1159 U"Octave offset fraction should be greater or equal zero and smaller than one.");
1160
1161 double octaveTime, sweeptime;
1162 if (frequencyChange_st != 0.0) {
1163 octaveTime = 12.0 / fabs (frequencyChange_st);
1164 sweeptime = numberOfComponents * octaveTime;
1165 } else {
1166 octaveTime = sweeptime = 1e308;
1167 }
1168 autoSound me = Sound_create2 (minimumTime, maximumTime, samplingFrequency);
1169
1170 const double a = frequencyChange_st / 12.0;
1171 for (integer ifreq = 1; ifreq <= numberOfComponents; ifreq ++) {
1172 double freqi = lowestFrequency * pow (2.0, ifreq - 1 + octaveShiftFraction);
1173 double b1, b2, tswitch;
1174 double phase1 = 0, phasejm1 = 0;
1175 /*
1176 The frequency is f(t) = lowestFrequency * 2^tone(t)
1177 The tone is parametrized with a straight line: tone(t) = a * t + b
1178 where a = frequencyChange_st / 12 and b depends on the component
1179 If frequencyChange_st >=0
1180 The tone rises until highest frequency at t=tswich, then falls to lowest and starts rising again.
1181 The slope is always the same. The offsets are b1 and b2 respectively.
1182 We count octaveShiftFraction as distance from tone base
1183 else if frequencyChange_st < 0
1184 The tone falls until the lowest frequency at t=tswich, then jumps to highest and starts falling again
1185 All tones start one octave higher as in rising case.
1186 We also count octaveShiftFraction down from this tone base.
1187 else
1188 No changes in frequency of the components.
1189 endif
1190 */
1191 if (frequencyChange_st >= 0) {
1192 b1 = ifreq - 1 + octaveShiftFraction;
1193 b2 = 0.0;
1194 tswitch = (numberOfComponents - b1) * octaveTime;
1195 } else {
1196 freqi *= 2.0;
1197 b1 = ifreq - octaveShiftFraction;
1198 b2 = numberOfComponents;
1199 tswitch = b1 * octaveTime;
1200 }
1201 for (integer j = 1; j <= my nx; j ++) {
1202 const double t = Sampled_indexToX (me.get(), j);
1203 const double tmod = fmod (t, sweeptime);
1204 const double tone = tmod <= tswitch ? b1 + a * tmod : b2 + a * (tmod - tswitch);
1205 const double f = lowestFrequency * pow (2, tone);
1206 /* double theta = 2 * NUMpi * log2 (f / lowestFrequency) / numberOfComponents; */
1207 const double theta = 2 * NUMpi * tone / numberOfComponents;
1208 const double level = pow (10.0, (lmin_db + (lmax_db - lmin_db) * (1.0 - cos (theta)) / 2.0) / 20.0);
1209 const double phasej = phasejm1 + 2.0 * NUMpi * f * my dx; /* Integrate 2*pi*f(t) */
1210
1211 if (j == 1)
1212 phase1 = phasej;
1213 my z [1] [j] += level * sin (phasej - phase1); // si
1214 phasejm1 = phasej;
1215 }
1216 }
1217 Vector_scale (me.get(), 0.99996948);
1218 return me;
1219 } catch (MelderError) {
1220 Melder_throw (U"Sound not created from Shepard tone complex.");
1221 }
1222 }
1223
1224 /* can be implemented more efficiently with sin recurrence? */
1225 /* amplitude(f) = min + (1-min)*(1-cos(2*pi*(ln(f/f1) / ln(fn/f1)))/2 */
1226 autoSound Sound_createShepardTone (double minimumTime, double maximumTime, double samplingFrequency, double lowestFrequency, integer numberOfComponents, double frequencyChange_st, double amplitudeRange) {
1227 try {
1228 const double scale = pow (2.0, numberOfComponents);
1229 const double maximumFrequency = lowestFrequency * scale;
1230 const double lmin = pow (10.0, - amplitudeRange / 10.0), twoPi = NUM2pi;
1231 const double ln2t0 = log (2.0) * frequencyChange_st / 12.0;
1232 const double lnf1 = log (lowestFrequency + 1.0);
1233 const double amplarg = twoPi / log ((maximumFrequency + 1.0) / (lowestFrequency + 1.0));
1234
1235 Melder_require (lowestFrequency <= 0.5 * samplingFrequency,
1236 U"Sound_createShepardTone: lowest frequency too high.");
1237 Melder_require (maximumFrequency <= 0.5 * samplingFrequency,
1238 U"Sound_createShepardTone: frequency of highest component too high.");
1239 autoSound me = Sound_create2 (minimumTime, maximumTime, samplingFrequency);
1240
1241 for (integer i = 1; i <= my nx; i ++) {
1242 const double t = (i - 0.5) * my dx;
1243 double argt, ft = lowestFrequency;
1244 if (frequencyChange_st != 0.0) {
1245 const double expt = exp (ln2t0 * t);
1246 argt = twoPi * lowestFrequency * (expt - 1.0) / ln2t0;
1247 ft *= expt;
1248 } else {
1249 argt = twoPi * ft * t;
1250 }
1251 for (integer j = 1; j <= numberOfComponents; j ++) {
1252 while (ft >= maximumFrequency) {
1253 ft /= scale;
1254 argt /= scale;
1255 }
1256 //amplitude = lmin + (1 - lmin) * (1 - cos (twoPi * log (ft + 1) / log (maximumFrequency + 1))) / 2;
1257 const double amplitude = lmin + (1 - lmin) * (1 - cos (amplarg * (log (ft + 1) - lnf1))) / 2.0;
1258 my z [1] [i] += amplitude * sin (argt);
1259 ft *= 2.0;
1260 argt *= 2.0;
1261 }
1262 }
1263 Vector_scale (me.get(), 0.99996948);
1264 return me;
1265 } catch (MelderError) {
1266 Melder_throw (U"Sound not created from Shepard tone.");
1267 }
1268 }
1269
1270 autoSound Sound_createPattersonWightmanTone (double minimumTime, double maximumTime, double samplingFrequency, double baseFrequency, double frequencyShiftRatio, integer numberOfComponents) {
1271 try {
1272 Melder_require ((numberOfComponents - 1 + frequencyShiftRatio) * baseFrequency <= samplingFrequency / 2.0,
1273 U"Frequency of one or more components too large.");
1274 autoSound me = Sound_create2 (minimumTime, maximumTime, samplingFrequency);
1275 const double w0 = NUM2pi * baseFrequency;
1276 for (integer i = 1; i <= my nx; i ++) {
1277 const double t = (i - 0.5) * my dx;
1278 double a = 0.0;
1279 for (integer j = 1; j <= numberOfComponents; j ++)
1280 a += sin ( (j + frequencyShiftRatio) * w0 * t);
1281 my z [1] [i] = a;
1282 }
1283 Vector_scale (me.get(), 0.99996948);
1284 return me;
1285 } catch (MelderError) {
1286 Melder_throw (U"Sound not created from Patterson Wightman tone.");
1287 }
1288 }
1289
1290 autoSound Sound_createPlompTone (double minimumTime, double maximumTime, double samplingFrequency, double baseFrequency, double frequencyFraction, integer m) {
1291 try {
1292 Melder_require (12.0 * (1.0 + frequencyFraction) * baseFrequency <= samplingFrequency / 2.0,
1293 U"Sound_createPlompTone: frequency of one or more components too large.");
1294
1295 const double w1 = NUM2pi * (1.0 - frequencyFraction) * baseFrequency;
1296 const double w2 = NUM2pi * (1.0 + frequencyFraction) * baseFrequency;
1297 autoSound me = Sound_create2 (minimumTime, maximumTime, samplingFrequency);
1298 for (integer i = 1; i <= my nx; i ++) {
1299 const double t = (i - 0.5) * my dx;
1300 double a = 0.0;
1301 for (integer j = 1; j <= m; j ++)
1302 a += sin (j * w1 * t);
1303 for (integer j = m + 1; j <= 12; j ++)
1304 a += sin (j * w2 * t);
1305 my z [1] [i] = a;
1306 }
1307 Vector_scale (me.get(), 0.99996948);
1308 return me;
1309 } catch (MelderError) {
1310 Melder_throw (U"Sound not created from Plomp tone.");
1311 }
1312 }
1313
1314 void Sounds_multiply (Sound me, Sound thee) {
1315 const integer n = std::min (my nx, thy nx );
1316 my z.row (1).part (1, n) *= thy z.row (1).part (1, n);
1317 }
1318
1319 double Sound_power (Sound me) {
1320 const double sumSq = NUMsum2 (my z.row (1));
1321 return sqrt (sumSq) * my dx / (my xmax - my xmin);
1322 }
1323
1324 double Sound_correlateParts (Sound me, double tx, double ty, double duration) {
1325 if (ty < tx)
1326 std::swap (tx, ty);
1327 const integer nbx = Sampled_xToNearestIndex (me, tx);
1328 const integer nby = Sampled_xToNearestIndex (me, ty);
1329 const integer ney = Sampled_xToNearestIndex (me, ty + duration);
1330 const integer increment = nbx < 1 ? 1 - nbx : 0;
1331 const integer decrement = ney > my nx ? ney - my nx : 0;
1332 const integer ns = Melder_ifloor (duration / my dx) - increment - decrement;
1333 if (ns < 1)
1334 return 0.0;
1335
1336 const double *x = & my z [1] [nbx + increment - 1];
1337 const double *y = & my z [1] [nby + increment - 1];
1338 double xm = 0.0, ym = 0.0;
1339 for (integer i = 1; i <= ns; i ++) {
1340 xm += x [i];
1341 ym += y [i];
1342 }
1343 xm /= ns;
1344 ym /= ns;
1345 double sxx = 0.0, syy = 0.0, sxy = 0.0;
1346 for (integer i = 1; i <= ns; i ++) {
1347 const double xt = x [i] - xm, yt = y [i] - ym;
1348 sxx += xt * xt;
1349 syy += yt * yt;
1350 sxy += xt * yt;
1351 }
1352 const double denum = sxx * syy;
1353 const double rxy = ( denum > 0.0 ? sxy / sqrt (denum) : 0.0 );
1354 return rxy;
1355 }
1356
1357 double Sound_localPeak (Sound me, double fromTime, double toTime, double reference) {
1358 integer n1 = Sampled_xToNearestIndex (me, fromTime);
1359 integer n2 = Sampled_xToNearestIndex (me, toTime);
1360 const double *s = & my z [1] [0];
1361 double peak = -1e308;
1362 if (fromTime <= toTime) {
1363 if (n1 < 1)
1364 n1 = 1;
1365 if (n2 > my nx)
1366 n2 = my nx;
1367 for (integer i = n1; i <= n2; i ++) {
1368 const double ds = fabs (s [i] - reference);
1369 if (ds > peak)
1370 peak = ds;
1371 }
1372 }
1373 return peak;
1374 }
1375
1376 void Sound_into_Sound (Sound me, Sound to, double startTime) {
1377 const integer index = Sampled_xToNearestIndex (me, startTime);
1378 for (integer i = 1; i <= to -> nx; i ++) {
1379 const integer j = index - 1 + i;
1380 to -> z [1] [i] = ( j < 1 || j > my nx ? 0.0 : my z [1] [j] );
1381 }
1382 }
1383
1384 /*
1385 IntervalTier Sound_PointProcess_to_IntervalTier (Sound me, PointProcess thee, double window);
1386 IntervalTier Sound_PointProcess_to_IntervalTier (Sound me, PointProcess thee, double window)
1387 {
1388 double window2 = window / 2;
1389 double t1 = thy t [1] - window2;
1390 if (t1 < my xmin) t1 = my xmin;
1391 double t2 = t1 + window2;
1392 if (t2 > my xmax) t2 = my xmax;
1393 autoIntervalTier him = IntervalTier_create (my xmin, my xmax);
1394 autoTextInterval interval = TextInterval_create (t1, t2, "yes");
1395 his intervals -> addItem_move (interval.move());
1396
1397 for (integer i = 2; i <= thy nt; i ++)
1398 {
1399 double t = thy t [i];
1400
1401 if (t <= t2)
1402 {
1403 integer index = his points.size;
1404 RealPoint point = his points->at [index];
1405 t2 = t + window2;
1406 if (t2 > my xmax) t2 = my xmax;
1407 point -> value = t2;
1408 }
1409 else
1410 {
1411 t2 = t + window2;
1412 if (t2 > my xmax) t2 = my xmax;
1413 RealTier_addPoint (him, t, t2);
1414 }
1415 }
1416 return him;
1417 }
1418 */
1419
1420
1421 /*
1422 First approximation on the basis of differences in the sampled signal.
1423 The underlying analog signal still could have jumps undetected by this algorithm.
1424 We could get a better approximation by first upsampling the signal.
1425 */
1426 autoPointProcess Sound_to_PointProcess_getJumps (Sound me, integer channel, double minimumJump, double maximumDuration) {
1427 try {
1428 Melder_require (channel >= 1 && channel <= my ny,
1429 U"The channel number should be in the interval from 1 to ", my ny, U".");
1430 autoPointProcess thee = PointProcess_create (my xmin, my xmax, 10);
1431 integer index = 1, intervalSize_samples = Melder_ifloor (maximumDuration / my dx);
1432 if (intervalSize_samples < 1)
1433 intervalSize_samples = 1;
1434 constVEC samples = my z.row (channel);
1435 while (index < my nx) {
1436 integer nextIndex = index + 1, step = 1;
1437 while (nextIndex <= index + intervalSize_samples && nextIndex <= my nx) {
1438 if (fabs (samples [index] - samples [nextIndex]) > minimumJump) {
1439 const double t = Sampled_indexToX (me, index);
1440 PointProcess_addPoint (thee.get(), t);
1441 step = nextIndex - index + 1;
1442 break;
1443 }
1444 nextIndex ++;
1445 }
1446 index += step;
1447 }
1448 return thee;
1449 } catch (MelderError) {
1450 Melder_throw (me, U": no PointProcess created.");
1451 }
1452 }
1453
1454 /* Internal pitch representation in semitones */
1455 autoSound Sound_Pitch_changeSpeaker (Sound me, Pitch him, double formantMultiplier, double pitchMultiplier, double pitchRangeMultiplier, double durationMultiplier) {
1456 try {
1457 const double samplingFrequency_old = 1.0 / my dx;
1458
1459 Melder_require (my xmin == his xmin && my xmax == his xmax,
1460 U"The Pitch and the Sound object should have the same domain.");
1461
1462 autoSound sound = Data_copy (me);
1463 Vector_subtractMean (sound.get());
1464
1465 if (formantMultiplier != 1.0) // Shift all frequencies (inclusive pitch!)
1466 Sound_overrideSamplingFrequency (sound.get(), samplingFrequency_old * formantMultiplier);
1467
1468 autoPitch pitch = Data_copy (him);
1469 Pitch_scaleDuration (pitch.get(), 1.0 / formantMultiplier); //
1470 Pitch_scalePitch (pitch.get(), formantMultiplier);
1471
1472 autoPointProcess pulses = Sound_Pitch_to_PointProcess_cc (sound.get(), pitch.get());
1473 autoPitchTier pitchTier = Pitch_to_PitchTier (pitch.get());
1474
1475 const double median = Pitch_getQuantile (pitch.get(), 0.0, 0.0, 0.5, kPitch_unit::HERTZ);
1476 if (isdefined (median) && median != 0.0) {
1477 /*
1478 Incorporate pitch shift from overriding the sampling frequency
1479 */
1480 PitchTier_multiplyFrequencies (pitchTier.get(), sound -> xmin, sound -> xmax, pitchMultiplier / formantMultiplier);
1481 PitchTier_modifyExcursionRange (pitchTier.get(), sound -> xmin, sound -> xmax, pitchRangeMultiplier, median);
1482 } else if (pitchMultiplier != 1) {
1483 Melder_warning (U"Pitch has not been changed because the sound was entirely voiceless.");
1484 }
1485 autoDurationTier duration = DurationTier_create (my xmin, my xmax);
1486 RealTier_addPoint (duration.get(), (my xmin + my xmax) / 2, formantMultiplier * durationMultiplier);
1487
1488 autoSound thee = Sound_Point_Pitch_Duration_to_Sound (sound.get(), pulses.get(), pitchTier.get(), duration.get(), MAX_T);
1489 /*
1490 Resample to the original sampling frequency
1491 */
1492 if (formantMultiplier != 1.0)
1493 thee = Sound_resample (thee.get(), samplingFrequency_old, 10);
1494
1495 return thee;
1496 } catch (MelderError) {
1497 Melder_throw (U"Sound not created from Pitch & Sound.");
1498 }
1499 }
1500
1501 autoSound Sound_changeSpeaker (Sound me, double pitchMin, double pitchMax, double formantMultiplier, double pitchMultiplier, double pitchRangeMultiplier, double durationMultiplier) { // > 0
1502 try {
1503 autoPitch pitch = Sound_to_Pitch (me, 0.8 / pitchMin, pitchMin, pitchMax);
1504 autoSound thee = Sound_Pitch_changeSpeaker (me, pitch.get(), formantMultiplier, pitchMultiplier, pitchRangeMultiplier, durationMultiplier);
1505 return thee;
1506 } catch (MelderError) {
1507 Melder_throw (me, U": speaker not changed.");
1508 }
1509 }
1510
1511 static void IntervalTier_addBoundaryUnsorted (IntervalTier me, integer iinterval, double time, conststring32 leftLabel) {
1512 Melder_require (time > my xmin && time <= my xmax,
1513 U"Time is outside interval.");
1514 /*
1515 Find interval to split.
1516 */
1517 if (iinterval <= 0)
1518 iinterval = IntervalTier_timeToLowIndex (me, time);
1519 /*
1520 Modify end time of left label.
1521 */
1522 const TextInterval ti = my intervals.at [iinterval];
1523 ti -> xmax = time;
1524 TextInterval_setText (ti, leftLabel);
1525 if (time != my xmax) {
1526 autoTextInterval ti_new = TextInterval_create (time, my xmax, U"");
1527 my intervals. addItem_unsorted_move (ti_new.move());
1528 }
1529 }
1530
1531 static autoIntensity Spectrogram_to_Intensity_silenceDetection (Spectrogram me) {
1532 try {
1533 autoIntensity thee = Intensity_create (my xmin, my xmax, my nx, my dx, my x1);
1534 VEC intensityBins = thy z.row (1);
1535 /*
1536 Add the values in the frequency bins, they are power (~amplitude squared)
1537 Don't use frequencies below 80 Hz and above 8000 Hz.
1538 */
1539 constexpr double fmin = 80.0, fmax = 8000.0;
1540 const integer iFreqFrom = std::max (1_integer, Melder_iroundDown (fmin / my dy));
1541 const integer iFreqTo = std::min (Melder_iroundUp (fmax / my dy), my ny);
1542 for (integer ifreq = iFreqFrom; ifreq <= iFreqTo; ifreq ++)
1543 intensityBins += my z.row (ifreq);
1544 /*
1545 Scale intensity.
1546 */
1547 intensityBins /= 4.0e-10; // threshold of hearing
1548 const double halfWindow = 3.2 * 0.01; // as if pitchFloor were 100 Hz
1549 autoIntensity him = Intensity_create (my xmin, my xmax, my nx, my dx, my x1);
1550 for (integer iframe = 1; iframe <= my nx; iframe ++) {
1551 const double xmid = Sampled_indexToX (thee.get(), iframe);
1552 const double intensity = Sampled_getMean (thee.get(), xmid - halfWindow, xmid + halfWindow, 1, 0, true);
1553 his z [1] [iframe] = ( intensity < 1.0e-30 ? -300.0 : 10.0 * log10 (intensity) );
1554 }
1555 return him;
1556 } catch (MelderError) {
1557 Melder_throw (me, U": could not determine Intensity.");
1558 }
1559 }
1560
1561 autoTextGrid Sound_to_TextGrid_speechActivity_ltsf (Sound me, double timeStep, double longTermWindow, double shorttimeWindow, double fmin, double fmax,
1562 double ltsfThreshold, double nonspeechThreshold_dB, double minNonspeechDuration, double minSpeechDuration,
1563 conststring32 nonspeechLabel, conststring32 speechLabel)
1564 {
1565 try {
1566 if (timeStep <= 0.0)
1567 timeStep = 0.01;
1568 Melder_require (fmin < fmax,
1569 U"The minimum frequency of the range should be smaller than the maximum frequency.");
1570 const double nyquistFrequency = 0.5 / my dx;
1571 Melder_clipRight (& fmax, nyquistFrequency);
1572 const double effectiveAnalysisWidth = std::max (0.02, 2.0 * timeStep);
1573 const double minimumFreqStep = 20.0;
1574 const double maximumTimeOversampling = 8.0, maximumFreqOversampling = 8.0;
1575 autoSpectrogram spectrogram = Sound_to_Spectrogram_e (me, effectiveAnalysisWidth, fmax, timeStep, minimumFreqStep,
1576 kSound_to_Spectrogram_windowShape::HANNING, maximumTimeOversampling, maximumFreqOversampling);
1577 autoMatrix ltsfMatrix = Spectrogram_getLongtermSpectralFlatness (spectrogram.get(), longTermWindow, shorttimeWindow, fmin, fmax);
1578 autoTextGrid thee = TextGrid_create (my xmin, my xmax, U"VAD", U"");
1579 const IntervalTier vadTier = (IntervalTier) thy tiers->at [1];
1580 TextInterval_setText (vadTier -> intervals.at [1], speechLabel);
1581 if (minNonspeechDuration > my xmax - my xmin)
1582 return thee;
1583 /*
1584 Step 1. Find activity intervals
1585 */
1586 VEC ltsf = ltsfMatrix -> z.row (1);
1587 conststring32 label;
1588 integer iinterval = 1;
1589 bool activityInterval = ( ltsf [1] < ltsfThreshold );
1590 for (integer index = 2; index <= ltsf.size; index ++) {
1591 bool addBoundary = false;
1592 if (ltsf [index] < ltsfThreshold) {
1593 if (! activityInterval) { // start of activity
1594 addBoundary = true;
1595 activityInterval = true;
1596 label = nonspeechLabel;
1597 }
1598 } else {
1599 if (activityInterval) { // end of activity
1600 addBoundary = true;
1601 activityInterval = false;
1602 label = speechLabel;
1603 }
1604 }
1605
1606 if (addBoundary) {
1607 const double time = Sampled_indexToX (ltsfMatrix.get(), index);
1608 IntervalTier_addBoundaryUnsorted (vadTier, iinterval, time, label);
1609 iinterval ++;
1610 }
1611 }
1612 /*
1613 Set the label of the last interval.
1614 */
1615 label = activityInterval ? speechLabel : nonspeechLabel;
1616 TextInterval_setText (vadTier -> intervals.at [iinterval], label);
1617 vadTier -> intervals. sort ();
1618 /*
1619 Step 2: remove intervals that are too short.
1620 First remove short activity intervals in-between noActivity intervals and
1621 then remove the remaining short silence intervals.
1622 This works much better than first removing short silence intervals and
1623 then short non-silence intervals.
1624 */
1625 if (minSpeechDuration > 0.0) {
1626 IntervalTier_cutIntervals_minimumDuration (vadTier, speechLabel, minSpeechDuration);
1627 IntervalTier_combineIntervalsOnLabelMatch (vadTier, nonspeechLabel);
1628 }
1629 if (minNonspeechDuration > 0.0) {
1630 IntervalTier_cutIntervals_minimumDuration (vadTier, nonspeechLabel, minNonspeechDuration);
1631 IntervalTier_combineIntervalsOnLabelMatch (vadTier, speechLabel);
1632 }
1633
1634 if (nonspeechThreshold_dB > -50.0) {
1635 /*
1636 Step 3: Find silences
1637 */
1638 autoIntensity intensity = Spectrogram_to_Intensity_silenceDetection (spectrogram.get());
1639 autoTextGrid silences = Intensity_to_TextGrid_detectSilences (intensity.get(), nonspeechThreshold_dB, minNonspeechDuration, minSpeechDuration, nonspeechLabel, speechLabel);
1640 /*
1641 Step 4: Union of the two VAD and the silences intervals.
1642 */
1643 autoTextGrid unionTextGrid = TextGrid_create (my xmin, my xmax, U"union", U"");
1644 integer unionIndex = 1;
1645 const double timeMargin = std::max (0.02, std::min (0.02, std::min (minNonspeechDuration, minSpeechDuration)));
1646 const IntervalTier silenceTier = (IntervalTier) silences -> tiers -> at [1];
1647 const IntervalTier unionTier = (IntervalTier) unionTextGrid -> tiers -> at [1];
1648 const integer silenceNumberOfIntervals = silenceTier -> intervals.size;
1649 const integer vadNumberOfIntervals = vadTier -> intervals.size;
1650 for (integer silenceIndex = 1; silenceIndex <= silenceNumberOfIntervals; silenceIndex ++) {
1651 const TextInterval silenceTextInterval = silenceTier -> intervals.at [silenceIndex];
1652 const double silenceStartTime = silenceTextInterval -> xmin;
1653 const conststring32 silenceLabel = silenceTextInterval -> text.get();
1654 const double silenceEndTime = silenceTextInterval -> xmax;
1655 if (Melder_stringMatchesCriterion (silenceLabel, kMelder_string::EQUAL_TO, nonspeechLabel, false)) {
1656 /*
1657 Silent interval. Simply add it.
1658 */
1659 IntervalTier_addBoundaryUnsorted (unionTier, unionIndex, silenceEndTime, nonspeechLabel);
1660 unionIndex ++;
1661 } else {
1662 /*
1663 Non silent interval. Do we have to split it into VAD intervals?
1664 */
1665 integer vadIndex = IntervalTier_timeToIndex (vadTier, silenceStartTime);
1666 bool unionContinues = true;
1667 while (unionContinues && vadIndex <= vadNumberOfIntervals) {
1668 const TextInterval vadTextInterval = vadTier -> intervals.at [vadIndex];
1669 const conststring32 vadLabel = vadTextInterval -> text.get();
1670 const double vadEndTime = vadTextInterval -> xmax;
1671 if (vadEndTime > silenceEndTime - timeMargin) {
1672 // extends beyond the end
1673 IntervalTier_addBoundaryUnsorted (unionTier, unionIndex, silenceEndTime, vadLabel);
1674 unionIndex ++;
1675 unionContinues = false;
1676 } else {
1677 IntervalTier_addBoundaryUnsorted (unionTier, unionIndex, vadEndTime, vadLabel);
1678 unionIndex ++;
1679 }
1680 vadIndex ++;
1681 }
1682 }
1683 }
1684 unionTier -> intervals. sort ();
1685 IntervalTier_combineIntervalsOnLabelMatch (unionTier, nonspeechLabel);
1686 TextGrid_addTier_copy (unionTextGrid.get(), silenceTier);
1687 TextGrid_addTier_copy (unionTextGrid.get(), vadTier);
1688 return unionTextGrid;
1689 }
1690 return thee;
1691 } catch (MelderError) {
1692 Melder_throw (me, U": could not detect speech activity.");
1693 }
1694 }
1695
1696 void Sound_getStartAndEndTimesOfSounding (Sound me, double minPitch, double timeStep, double silenceThreshold, double minSilenceDuration, double minSoundingDuration, double *out_t1, double *out_t2) {
1697 try {
1698 const conststring32 silentLabel = U"-", soundingLabel = U"+";
1699 autoTextGrid dbs = Sound_to_TextGrid_detectSilences (me, minPitch, timeStep, silenceThreshold, minSilenceDuration, minSoundingDuration, silentLabel, soundingLabel);
1700 const IntervalTier tier = (IntervalTier) dbs -> tiers->at [1];
1701 Melder_assert (tier -> intervals.size > 0);
1702 TextInterval interval = tier -> intervals.at [1];
1703 if (out_t1) {
1704 *out_t1 = my xmin;
1705 if (Melder_equ (interval -> text.get(), silentLabel))
1706 *out_t1 = interval -> xmax;
1707 }
1708 if (out_t2) {
1709 *out_t2 = my xmax;
1710 interval = tier -> intervals.at [tier -> intervals.size];
1711 if (Melder_equ (interval -> text.get(), silentLabel))
1712 *out_t2 = interval -> xmin;
1713 }
1714 } catch (MelderError) {
1715 Melder_throw (U"Sounding times not found.");
1716 }
1717 }
1718
1719 autoSound Sound_trimSilences (Sound me, double trimDuration, bool onlyAtStartAndEnd,
1720 double minPitch, double timeStep, double silenceThreshold,
1721 double minSilenceDuration, double minSoundingDuration,
1722 autoTextGrid *out_tg, conststring32 trimLabel
1723 ) {
1724 try {
1725 Melder_require (my ny == 1,
1726 U"The sound should be a mono sound.");
1727 /*
1728 The following guards against removing *all* of the sound.
1729 */
1730 Melder_require (trimLabel [0] != U'\0',
1731 U"The trim label should not be empty.");
1732
1733 const conststring32 silentLabel = U"silent", soundingLabel = U"sounding";
1734 const conststring32 copyLabel = U"";
1735 autoTextGrid tg = Sound_to_TextGrid_detectSilences (me, minPitch, timeStep, silenceThreshold, minSilenceDuration, minSoundingDuration, silentLabel, soundingLabel);
1736 autoIntervalTier itg = Data_copy ((IntervalTier) tg -> tiers->at [1]);
1737 IntervalTier tier = (IntervalTier) tg -> tiers->at [1];
1738 for (integer iint = 1; iint <= tier -> intervals.size; iint ++) {
1739 const TextInterval ti = tier -> intervals.at [iint];
1740 const TextInterval ati = itg -> intervals.at [iint];
1741 const double duration = ti -> xmax - ti -> xmin;
1742 if (duration > trimDuration && Melder_equ (ti -> text.get(), silentLabel)) { // silent
1743 conststring32 label = trimLabel;
1744 if (tier -> intervals.size == 1) { // current interval is both the first and the last: very special
1745 // all of the sound is silent: do nothing
1746 } else if (iint == 1) { // first is special
1747 const double trim_t = ti -> xmax - trimDuration;
1748 IntervalTier_moveRightBoundary (itg.get(), iint, trim_t);
1749 } else if (iint == tier -> intervals.size) { // last is special
1750 const double trim_t = ti -> xmin + trimDuration;
1751 IntervalTier_moveLeftBoundary (itg.get(), iint, trim_t);
1752 } else {
1753 if (onlyAtStartAndEnd) {
1754 label = ati -> text.get();
1755 } else {
1756 double trim_t = ti -> xmin + 0.5 * trimDuration;
1757 IntervalTier_moveLeftBoundary (itg.get(), iint, trim_t);
1758 trim_t = ti -> xmax - 0.5 * trimDuration;
1759 IntervalTier_moveRightBoundary (itg.get(), iint, trim_t);
1760 }
1761 }
1762 TextInterval_setText (ati, label);
1763 } else { // sounding
1764 TextInterval_setText (ati, copyLabel);
1765 }
1766 }
1767 autoSound thee = Sound_IntervalTier_cutPartsMatchingLabel (me, itg.get(), trimLabel);
1768 /*
1769 As a silent sound will lead to an error about the loudest and softest part being only 0 dB apart,
1770 the following assertion will normally not fire.
1771 However, this assumption is *brittle* and should be checked,
1772 because otherwise we may end up with a sound with duration 0.0 and without samples.
1773 */
1774 Melder_assert (thy nx > 0);
1775 if (out_tg) {
1776 TextGrid_addTier_copy (tg.get(), itg.get());
1777 *out_tg = tg.move();
1778 }
1779 return thee;
1780 } catch (MelderError) {
1781 Melder_throw (me, U": silences not trimmed.");
1782 }
1783 }
1784
1785 autoSound Sound_trimSilencesAtStartAndEnd (Sound me, double trimDuration, double minPitch, double timeStep,
1786 double silenceThreshold, double minSilenceDuration, double minSoundingDuration, double *startTimeOfSounding, double *endTimeOfSounding)
1787 {
1788 try {
1789 autoTextGrid tg;
1790 autoSound thee = Sound_trimSilences (me, trimDuration, true, minPitch, timeStep, silenceThreshold,
1791 minSilenceDuration, minSoundingDuration, & tg, U"trimmed");
1792 const IntervalTier trim = (IntervalTier) tg -> tiers->at [2];
1793 const TextInterval ti1 = trim -> intervals.at [1];
1794 if (startTimeOfSounding) {
1795 *startTimeOfSounding = my xmin;
1796 if (Melder_equ (ti1 -> text.get(), U"trimmed"))
1797 *startTimeOfSounding = ti1 -> xmax;
1798 }
1799 const TextInterval ti2 = trim -> intervals.at [trim -> intervals.size];
1800 if (endTimeOfSounding) {
1801 *endTimeOfSounding = my xmax;
1802 if (Melder_equ (ti2 -> text.get(), U"trimmed"))
1803 *endTimeOfSounding = ti2 -> xmin;
1804 }
1805 return thee;
1806 } catch (MelderError) {
1807 Melder_throw (me, U": silences at start and end not trimmed.");
1808 }
1809 }
1810
1811 /* Compatibility with old Sound(&pitch)_changeGender ***********************************/
1812
1813 static void PitchTier_modifyRange_old (PitchTier me, double tmin, double tmax, double factor, double fmid) {
1814 for (integer i = 1; i <= my points.size; i ++) {
1815 const RealPoint point = my points.at [i];
1816 const double f = point -> value;
1817 if (point -> number < tmin || point -> number > tmax)
1818 continue;
1819 point -> value = fmid + (f - fmid) * factor;
1820 /*
1821 This scaling could lead to a negative value.
1822 Negative pitch values have no meaning,
1823 and even a zero pitch value cannot be handled by Sound_Point_Pitch_Duration_to_Sound.
1824 So in such a case we bail out.
1825 */
1826 if (point -> value < 0.0)
1827 Melder_throw (U"Change gender: your pitch manipulation would lead to negative pitch values.");
1828 }
1829 }
1830
1831 static autoPitch Pitch_scaleTime_old (Pitch me, double scaleFactor) {
1832 try {
1833 double dx = my dx, x1 = my x1, xmax = my xmax;
1834 if (scaleFactor != 1.0) {
1835 dx = my dx * scaleFactor;
1836 x1 = my xmin + 0.5 * dx;
1837 xmax = my xmin + my nx * dx;
1838 }
1839 autoPitch thee = Pitch_create (my xmin, xmax, my nx, dx, x1, my ceiling, 2);
1840
1841 for (integer i = 1; i <= my nx; i ++) {
1842 double f = my frames [i].candidates [1].frequency;
1843 thy frames [i]. candidates [1].strength = my frames [i]. candidates [1].strength;
1844 f /= scaleFactor;
1845 if (f < my ceiling)
1846 thy frames [i]. candidates [1]. frequency = f;
1847 }
1848 return thee;
1849 } catch (MelderError) {
1850 Melder_throw (U"Pitch not scaled.");
1851 }
1852 }
1853
1854 autoSound Sound_Pitch_changeGender_old (Sound me, Pitch him, double formantRatio, double new_pitch, double pitchRangeFactor, double durationFactor) {
1855 try {
1856 const double samplingFrequency_old = 1.0 / my dx;
1857
1858 Melder_require (my ny == 1,
1859 U"Change Gender works only on mono sounds.");
1860 Melder_require (my xmin == his xmin && my xmax == his xmax,
1861 U"The Pitch and the Sound object should have the same domain.");
1862 Melder_require (new_pitch >= 0,
1863 U"The new pitch median should not be negative.");
1864
1865 autoSound sound = Data_copy (me);
1866 Vector_subtractMean (sound.get());
1867
1868 if (formantRatio != 1.0)
1869 // Shift all frequencies (including pitch!)
1870 Sound_overrideSamplingFrequency (sound.get(), samplingFrequency_old * formantRatio);
1871
1872 autoPitch pitch = Pitch_scaleTime_old (him, 1 / formantRatio);
1873 autoPointProcess pulses = Sound_Pitch_to_PointProcess_cc (sound.get(), pitch.get());
1874 autoPitchTier pitchTier = Pitch_to_PitchTier (pitch.get());
1875
1876 const double median = Pitch_getQuantile (pitch.get(), 0, 0, 0.5, kPitch_unit::HERTZ);
1877 if (isdefined (median) && median != 0.0) {
1878 // Incorporate pitch shift from overriding the sampling frequency
1879 if (new_pitch == 0.0)
1880 new_pitch = median / formantRatio;
1881 const double factor = new_pitch / median;
1882 PitchTier_multiplyFrequencies (pitchTier.get(), sound -> xmin, sound -> xmax, factor);
1883 PitchTier_modifyRange_old (pitchTier.get(), sound -> xmin, sound -> xmax, pitchRangeFactor, new_pitch);
1884 } else {
1885 Melder_warning (U"There were no voiced segments found.");
1886 }
1887 autoDurationTier duration = DurationTier_create (my xmin, my xmax);
1888 RealTier_addPoint (duration.get(), (my xmin + my xmax) / 2, formantRatio * durationFactor);
1889
1890 autoSound thee = Sound_Point_Pitch_Duration_to_Sound (sound.get(), pulses.get(), pitchTier.get(), duration.get(), 1.25 / Pitch_getMinimum (pitch.get(), 0.0, 0.0, kPitch_unit::HERTZ, false));
1891 /*
1892 Resample to the original sampling frequency
1893 */
1894 if (formantRatio != 1.0)
1895 thee = Sound_resample (thee.get(), samplingFrequency_old, 10);
1896 return thee;
1897 } catch (MelderError) {
1898 Melder_throw (U"Sound not created from Pitch & Sound.");
1899 }
1900 }
1901
1902 autoSound Sound_changeGender_old (Sound me, double fmin, double fmax, double formantRatio, double new_pitch, double pitchRangeFactor, double durationFactor) {
1903 try {
1904 autoPitch pitch = Sound_to_Pitch (me, 0.8 / fmin, fmin, fmax);
1905 autoSound thee = Sound_Pitch_changeGender_old (me, pitch.get(), formantRatio, new_pitch, pitchRangeFactor, durationFactor);
1906 return thee;
1907 } catch (MelderError) {
1908 Melder_throw (U"Sound not created for gender change.");
1909 }
1910 }
1911
1912 /* End of compatibility with Sound_changeGender and Sound_Pitch_changeGender ***********************************/
1913
1914 /* Draw a sound vertically, from bottom to top */
1915 void Sound_draw_btlr (Sound me, Graphics g, double tmin, double tmax, double amin, double amax, kSoundDrawingDirection drawingDirection, bool garnish) {
1916 double xmin, xmax, ymin, ymax;
1917
1918 if (tmin == tmax) {
1919 tmin = my xmin;
1920 tmax = my xmax;
1921 }
1922 integer itmin, itmax;
1923 Matrix_getWindowSamplesX (me, tmin, tmax, & itmin, & itmax);
1924 if (amin == amax) {
1925 Matrix_getWindowExtrema (me, itmin, itmax, 1, my ny, & amin, & amax);
1926 if (amin == amax) {
1927 amin -= 1.0;
1928 amax += 1.0;
1929 }
1930 }
1931 /*
1932 In bottom-to-top-drawing, the maximum amplitude is on the left, the minimum on the right.
1933 */
1934 if (drawingDirection == kSoundDrawingDirection::BOTTOM_TO_TOP) {
1935 xmin = amax;
1936 xmax = amin;
1937 ymin = tmin;
1938 ymax = tmax;
1939 } else if (drawingDirection == kSoundDrawingDirection::TOP_TO_BOTTOM) {
1940 xmin = amin;
1941 xmax = amax;
1942 ymin = tmax;
1943 ymax = tmin;
1944 } else if (drawingDirection == kSoundDrawingDirection::RIGHT_TO_LEFT) {
1945 xmin = tmax;
1946 xmax = tmin;
1947 ymin = amin;
1948 ymax = amax;
1949 } else { //if (drawingDirection == kSoundDrawingDirection::LEFT_TO_RIGHT)
1950 xmin = tmin;
1951 xmax = tmax;
1952 ymin = amin;
1953 ymax = amax;
1954 }
1955 Graphics_setWindow (g, xmin, xmax, ymin, ymax);
1956 double a1 = my z [1] [itmin];
1957 double t1 = Sampled_indexToX (me, itmin);
1958 for (integer it = itmin + 1; it <= itmax; it ++) {
1959 const double t2 = Sampled_indexToX (me, it);
1960 const double a2 = my z [1] [it];
1961 if (drawingDirection == kSoundDrawingDirection::BOTTOM_TO_TOP ||
1962 drawingDirection == kSoundDrawingDirection::TOP_TO_BOTTOM) {
1963 Graphics_line (g, a1, t1, a2, t2);
1964 } else {
1965 Graphics_line (g, t1, a1, t2, a2);
1966 }
1967 a1 = a2;
1968 t1 = t2;
1969 }
1970 if (garnish) {
1971 if (drawingDirection == kSoundDrawingDirection::BOTTOM_TO_TOP) {
1972 if (amin * amax < 0.0)
1973 Graphics_markBottom (g, 0.0, false, true, true, nullptr);
1974 } else if (drawingDirection == kSoundDrawingDirection::TOP_TO_BOTTOM) {
1975 if (amin * amax < 0.0)
1976 Graphics_markTop (g, 0.0, false, true, true, nullptr);
1977 } else if (drawingDirection == kSoundDrawingDirection::RIGHT_TO_LEFT) {
1978 if (amin * amax < 0.0)
1979 Graphics_markRight (g, 0.0, false, true, true, nullptr);
1980 } else { //if (drawingDirection == kSoundDrawingDirection::LEFT_TO_RIGHT)
1981 if (amin * amax < 0.0)
1982 Graphics_markLeft (g, 0.0, false, true, true, nullptr);
1983 }
1984 Graphics_rectangle (g, xmin, xmax, ymin, ymax);
1985 }
1986 }
1987
1988 void Sound_fade (Sound me, int channel, double t, double fadeTime, bool fadeOut, bool fadeGlobal) {
1989 integer numberOfSamples = Melder_ifloor (fabs (fadeTime) / my dx);
1990 double t1 = t, t2 = t1 + fadeTime;
1991 bool fadeIn = ! fadeOut;
1992 const conststring32 fade_string = ( fadeOut ? U"out" : U"in" );
1993
1994 Melder_require (channel >= 0 && channel <= my ny,
1995 U"Invalid channel number: ", channel, U".");
1996
1997 if (t > my xmax) {
1998 t = my xmax;
1999 if (fadeIn) {
2000 Melder_warning (U"The start time of the fade-in is after the end time of the sound. The fade-in will not happen.");
2001 return;
2002 }
2003 } else if (t < my xmin) {
2004 t = my xmin;
2005 if (fadeOut) {
2006 Melder_warning (U"The start time of the fade-out is before the start time of the sound. The fade-out will not happen.");
2007 return;
2008 }
2009 }
2010 if (fadeTime < 0.0) {
2011 t1 = t + fadeTime;
2012 t2 = t;
2013 } else if (fadeTime > 0.0) {
2014 t1 = t;
2015 t2 = t + fadeTime;
2016 } else {
2017 Melder_warning (U"You have given a \"Fade time\" of zero seconds. The fade-", fade_string, U" will not happen.");
2018 return;
2019 }
2020 integer i0 = 0, iystart, iyend;
2021 if (channel == 0) { // all
2022 iystart = 1;
2023 iyend = my ny;
2024 } else {
2025 iystart = iyend = channel;
2026 }
2027
2028 integer istart = Sampled_xToNearestIndex (me, t1);
2029 if (istart < 1)
2030 istart = 1;
2031 if (istart >= my nx) {
2032 Melder_warning (U"The part to fade ", fade_string, U" lies after the end time of the sound. The fade-", fade_string, U" will not happen.");
2033 return;
2034 }
2035 integer iend = Sampled_xToNearestIndex (me, t2);
2036 if (iend <= 1) {
2037 Melder_warning (U"The part to fade ", fade_string, U" lies before the start time of the sound. Fade-", fade_string, U" will be incomplete.");
2038 return;
2039 }
2040 if (iend > my nx)
2041 iend = my nx;
2042 if (iend - istart + 1 >= numberOfSamples) {
2043 numberOfSamples = iend - istart + 1;
2044 } else {
2045 /*
2046 If the start of the fade is before xmin, arrange starting phase.
2047 The end of the fade after xmax presents no problems (i0 = 0).
2048 */
2049 if (fadeTime < 0)
2050 i0 = numberOfSamples - (iend - istart + 1);
2051 Melder_warning (U"The fade time is larger than the part of the sound to fade ", fade_string, U". Fade-", fade_string, U" will be incomplete.");
2052 }
2053 for (integer ichannel = iystart; ichannel <= iyend; ichannel ++) {
2054 for (integer i = istart; i <= iend; i ++) {
2055 double cosp = cos (NUMpi * (i0 + i - istart) / (numberOfSamples - 1));
2056 if (fadeIn)
2057 cosp = -cosp; // fade-in
2058 my z [ichannel] [i] *= 0.5 * (1.0 + cosp);
2059 }
2060 if (fadeGlobal) {
2061 if (fadeIn) {
2062 if (istart > 1)
2063 my z [ichannel].part (1, istart - 1) <<= 0.0;
2064 } else {
2065 if (iend < my nx)
2066 my z [ichannel].part (iend, my nx) <<= 0.0;
2067 }
2068 }
2069 }
2070 }
2071
2072 /* 1; rect 2:hamming 3: bartlet 4: welch 5: hanning 6:gaussian */
2073 autoSound Sound_createFromWindowFunction (double windowDuration, double samplingFrequency, int windowType) {
2074 try {
2075 autoSound me = Sound_createSimple (1, windowDuration, samplingFrequency);
2076
2077 for (integer i = 1; i <= my nx; i ++) {
2078 double phase = (my x1 + (i - 1) * my dx) / windowDuration;
2079 double value = 1.0;
2080 switch (windowType) {
2081 case 1:
2082 value = 1.0;
2083 break;
2084 case 2: /* Hamming */
2085 value = 0.54 - 0.46 * cos (NUM2pi * phase);
2086 break;
2087 case 3: /* Bartlett */
2088 value = 1.0 - fabs ( (2.0 * phase - 1.0));
2089 break;
2090 case 4: /* Welch */
2091 value = 1.0 - (2.0 * phase - 1.0) * (2.0 * phase - 1.0);
2092 break;
2093 case 5: /* Hanning */
2094 value = 0.5 * (1.0 - cos (NUM2pi * phase));
2095 break;
2096 case 6: { /* Gaussian */
2097 const double edge = exp (-12.0);
2098 phase -= 0.5; /* -0.5 .. +0.5 */
2099 value = (exp (-48.0 * phase * phase) - edge) / (1.0 - edge);
2100 break;
2101 }
2102 break;
2103 }
2104 my z [1] [i] = value;
2105 }
2106 return me;
2107 } catch (MelderError) {
2108 Melder_throw (U"Sound not created from window function.");
2109 }
2110 }
2111
2112 /* y [n] = sum(i=-n, i=n, x [n+mi])/(2*n+1) */
2113 autoSound Sound_localAverage (Sound me, double averagingInterval, int windowType) {
2114 try {
2115 const double windowDuration = windowType == 6 ? 2 * averagingInterval : averagingInterval;
2116 autoSound thee = Data_copy (me);
2117 autoSound window = Sound_createFromWindowFunction (windowDuration, 1 / my dx, windowType);
2118
2119 const integer nswindow2 = window -> nx / 2;
2120 const integer nswindow2p = (window -> nx - 1) / 2; // nx is odd: one sample less in the forward direction
2121 if (nswindow2 < 1) {
2122 return thee;
2123 }
2124 const double *w = & window -> z [1] [0];
2125
2126 for (integer k = 1; k <= thy ny; k ++) {
2127 for (integer i = 1; i <= my nx; i ++) {
2128 longdouble sum = 0.0, wsum = 0.0;
2129 integer m = (nswindow2 + 1 - i + 1) < 1 ? 1 : (nswindow2 + 1 - i + 1);
2130 const integer jfrom = (i - nswindow2) < 1 ? 1 : (i - nswindow2);
2131 const integer jto = (i + nswindow2p) > my nx ? my nx : (i + nswindow2p);
2132 for (integer j = jfrom; j <= jto; j ++, m ++) {
2133 sum += my z [k] [j] * w [m];
2134 wsum += w [m];
2135 }
2136 thy z [k] [i] = double (sum / wsum);
2137 }
2138 }
2139 return thee;
2140 } catch (MelderError) {
2141 Melder_throw (me, U": no Sound (local average) created.");
2142 }
2143 }
2144
2145 static void _Sound_garnish (Sound me, Graphics g, double tmin, double tmax, double minimum, double maximum) {
2146 Graphics_drawInnerBox (g);
2147 Graphics_textBottom (g, true, U"Time (s)");
2148 Graphics_marksBottom (g, 2, true, true, false);
2149 Graphics_setWindow (g, tmin, tmax, minimum - (my ny - 1) * (maximum - minimum), maximum);
2150 Graphics_markLeft (g, minimum, true, true, false, nullptr);
2151 Graphics_markLeft (g, maximum, true, true, false, nullptr);
2152 if (minimum != 0.0 && maximum != 0.0 && (minimum > 0.0) != (maximum > 0.0))
2153 Graphics_markLeft (g, 0.0, true, true, true, nullptr);
2154 if (my ny == 2) {
2155 Graphics_setWindow (g, tmin, tmax, minimum, maximum + (my ny - 1) * (maximum - minimum));
2156 Graphics_markRight (g, minimum, true, true, false, nullptr);
2157 Graphics_markRight (g, maximum, true, true, false, nullptr);
2158 if (minimum != 0.0 && maximum != 0.0 && (minimum > 0.0) != (maximum > 0.0))
2159 Graphics_markRight (g, 0.0, true, true, true, nullptr);
2160 }
2161 }
2162
2163 static void autowindowAndGetWindowSamplesAndAutoscale (Sound me, double *tmin, double *tmax, double *minimum, double *maximum, integer *ixmin, integer *ixmax) {
2164 if (*tmin == *tmax) {
2165 *tmin = my xmin;
2166 *tmax = my xmax;
2167 }
2168
2169 Matrix_getWindowSamplesX (me, *tmin, *tmax, ixmin, ixmax);
2170
2171 if (*minimum == *maximum) {
2172 Matrix_getWindowExtrema (me, *ixmin, *ixmax, 1, my ny, minimum, maximum);
2173 if (*minimum == *maximum) {
2174 *minimum -= 1.0;
2175 *maximum += 1.0;
2176 }
2177 }
2178 }
2179
2180 /*
2181 Given sample numbers ileft and ileft+1, where the formula evaluates to the booleans left and right, respectively.
2182 We want to find the x value in this interval where the formula switches from true to false.
2183 The x-value of the best point is approximated by a number of bisections.
2184 It is essential that the intermediate interpolated y-values are always between the values at samples ileft and ileft+1.
2185 We cannot use a sinc-interpolation because at strong amplitude changes high-frequency oscillations may occur.
2186 */
2187 static void Sound_findIntermediatePoint_bs (Sound me, integer ichannel, integer ileft, bool left, bool right,
2188 conststring32 formula, Interpreter interpreter, integer numberOfBisections, double *x, double *y)
2189 {
2190 Melder_require (left != right,
2191 U"Invalid situation.");
2192
2193 if (left) {
2194 *x = Matrix_columnToX (me, ileft);
2195 *y = my z [ichannel] [ileft];
2196 } else {
2197 *x = Matrix_columnToX (me, ileft + 1);
2198 *y = my z [ichannel] [ileft + 1];
2199 }
2200
2201 if (numberOfBisections < 1)
2202 return;
2203 /*
2204 For the bisection we create a Sound with only 3 samples in it which is sufficient for doing linear interpolation.
2205 The domain needs to be the same as the sound otherwise the formula might give wrong answers because
2206 it might contains references to other matrix objects!
2207 We also need all the channels because the formula might involve relations between the
2208 sample values in these channels too!
2209 */
2210 double xleft = Matrix_columnToX (me, ileft);
2211 autoSound thee = Sound_create (my ny, my xmin, my xmax, 3, 0.5 * my dx, xleft);
2212
2213 for (integer channel = 1; channel <= my ny; channel ++) {
2214 thy z [channel] [1] = my z [channel] [ileft];
2215 thy z [channel] [3] = my z [channel] [ileft + 1];
2216 }
2217 integer istep = 1;
2218 double xright = xleft + my dx, xmid; // !!
2219 do {
2220 xmid = 0.5 * (xleft + xright); // the bisection
2221
2222 for (integer channel = 1; channel <= my ny; channel ++)
2223 thy z [channel] [2] = Vector_getValueAtX (me, xmid, channel, kVector_valueInterpolation :: LINEAR);
2224 Formula_compile (interpreter, thee.get(), formula, kFormula_EXPRESSION_TYPE_NUMERIC, true);
2225 Formula_Result result;
2226 Formula_run (ichannel, 2, & result);
2227 const bool mid = ( result. numericResult != 0.0 );
2228
2229 thy dx *= 0.5;
2230 if (left == mid) {
2231 xleft = xmid;
2232 for (integer channel = 1; channel <= my ny; channel ++)
2233 thy z [channel] [1] = thy z [channel] [2];
2234 thy x1 = xleft;
2235 } else {
2236 xright = xmid;
2237 for (integer channel = 1; channel <= my ny; channel ++)
2238 thy z [channel] [3] = thy z [channel] [2];
2239 }
2240 istep ++;
2241 } while (istep < numberOfBisections);
2242
2243 *x = xmid;
2244 *y = thy z [ichannel] [2];
2245 }
2246
2247 void Sound_drawWhere (Sound me, Graphics g, double tmin, double tmax, double minimum, double maximum,
2248 bool garnish, conststring32 method, integer numberOfBisections, conststring32 formula, Interpreter interpreter) {
2249
2250 Formula_compile (interpreter, me, formula, kFormula_EXPRESSION_TYPE_NUMERIC, true);
2251 Formula_Result result;
2252
2253 integer ixmin, ixmax;
2254 autowindowAndGetWindowSamplesAndAutoscale (me, & tmin, & tmax, & minimum, & maximum, & ixmin, & ixmax);
2255 /*
2256 Set coordinates for drawing.
2257 */
2258 Graphics_setInner (g);
2259 for (integer channel = 1; channel <= my ny; channel ++) {
2260 Graphics_setWindow (g, tmin, tmax, minimum - (my ny - channel) * (maximum - minimum), maximum + (channel - 1) * (maximum - minimum));
2261 if (str32str (method, U"bars") || str32str (method, U"Bars")) {
2262 for (integer ix = ixmin; ix <= ixmax; ix ++) {
2263 Formula_run (channel, ix, & result);
2264 if (result. numericResult != 0.0) {
2265 const double x = Sampled_indexToX (me, ix);
2266 double y = my z [channel] [ix];
2267 double left = x - 0.5 * my dx, right = x + 0.5 * my dx;
2268 if (y > maximum)
2269 y = maximum;
2270 if (left < tmin)
2271 left = tmin;
2272 if (right > tmax)
2273 right = tmax;
2274 Graphics_line (g, left, y, right, y);
2275 Graphics_line (g, left, y, left, minimum);
2276 Graphics_line (g, right, y, right, minimum);
2277 }
2278 }
2279 } else if (str32str (method, U"poles") || str32str (method, U"Poles")) {
2280 for (integer ix = ixmin; ix <= ixmax; ix ++) {
2281 Formula_run (channel, ix, & result);
2282 if (result. numericResult != 0.0) {
2283 const double x = Sampled_indexToX (me, ix);
2284 double y = my z [channel] [ix];
2285 if (y > maximum)
2286 y = maximum;
2287 if (y < minimum)
2288 y = minimum;
2289 Graphics_line (g, x, 0.0, x, y);
2290 }
2291 }
2292 } else if (str32str (method, U"speckles") || str32str (method, U"Speckles")) {
2293 for (integer ix = ixmin; ix <= ixmax; ix ++) {
2294 Formula_run (channel, ix, & result);
2295 if (result. numericResult != 0.0) {
2296 const double x = Sampled_indexToX (me, ix);
2297 Graphics_speckle (g, x, my z [channel] [ix]);
2298 }
2299 }
2300 } else {
2301 /*
2302 The default: draw as a curve.
2303 */
2304 Formula_run (channel, 1, & result);
2305 bool previous = (result. numericResult != 0.0); // numericResult == 0.0 means false!
2306 integer istart = ixmin; // first sample of segment to be drawn
2307 double xb, yb, xe, ye;
2308 for (integer ix = ixmin + 1; ix <= ixmax; ix ++) {
2309 Formula_run (channel, ix, & result);
2310 const bool current = (result. numericResult != 0.0); // numericResult == 0.0 means false!
2311 if (previous && not current) {
2312 /*
2313 T to F change: we are leaving a segment to be drawn
2314 1. Draw the curve between the sample numbers from istart to ix-1 (previous).
2315 2. Find the (x,y) in the interval between sample numbers ix-1 and ix (current) where the change from
2316 T to F occurs and draw the line between the previous point and (x,y).
2317 3. Compile the formula again because it has been changed during the interpolation
2318 */
2319 xb = Matrix_columnToX (me, ix - 1);
2320 yb = my z [channel] [ix - 1];
2321 if (ix - istart > 1) {
2322 const double x1 = Matrix_columnToX (me, istart);
2323 Graphics_function (g, & my z [channel] [0], istart, ix - 1, x1, xb);
2324 }
2325 Sound_findIntermediatePoint_bs (me, channel, ix - 1, previous, current, formula, interpreter, numberOfBisections, & xe, & ye);
2326 Graphics_line (g, xb, yb, xe, ye);
2327 Formula_compile (interpreter, me, formula, kFormula_EXPRESSION_TYPE_NUMERIC, true);
2328 } else if (not previous && current ) {
2329 /*
2330 F to T change: we are entering a segment to be drawn.
2331 1. Find the (x,y) where the F changes to T and then draw the line from that (x,y) to the current point.
2332 2. Compile the formula again
2333 */
2334 istart = ix;
2335 Sound_findIntermediatePoint_bs (me, channel, ix - 1, previous, current, formula, interpreter, numberOfBisections, & xb, & yb);
2336 xe = Sampled_indexToX (me, ix);
2337 ye = my z [channel] [ix];
2338 Graphics_line (g, xb, yb, xe, ye);
2339 Formula_compile (interpreter, me, formula, kFormula_EXPRESSION_TYPE_NUMERIC, true);
2340 }
2341 previous = current;
2342 }
2343 if (previous && ixmax - istart > 0) {
2344 xb = Matrix_columnToX (me, istart);
2345 xe = Matrix_columnToX (me, ixmax);
2346 Graphics_function (g, & my z [channel] [0], istart, ixmax, xb, xe);
2347 }
2348 }
2349 }
2350
2351 Graphics_setWindow (g, tmin, tmax, minimum, maximum);
2352 if (garnish && my ny == 2)
2353 Graphics_line (g, tmin, 0.5 * (minimum + maximum), tmax, 0.5 * (minimum + maximum));
2354 Graphics_unsetInner (g);
2355
2356 if (garnish)
2357 _Sound_garnish (me, g, tmin, tmax, minimum, maximum);
2358 }
2359
2360 void Sound_paintWhere (Sound me, Graphics g, MelderColour colour, double tmin, double tmax,
2361 double minimum, double maximum, double level, bool garnish,
2362 integer numberOfBisections, conststring32 formula, Interpreter interpreter)
2363 {
2364 try {
2365 Formula_compile (interpreter, me, formula, kFormula_EXPRESSION_TYPE_NUMERIC, true);
2366 Formula_Result result;
2367
2368 integer ixmin, ixmax;
2369 autowindowAndGetWindowSamplesAndAutoscale (me, & tmin, & tmax, & minimum, & maximum, & ixmin, & ixmax);
2370
2371 Graphics_setColour (g, colour);
2372 Graphics_setInner (g);
2373 for (integer channel = 1; channel <= my ny; channel ++) {
2374 Graphics_setWindow (g, tmin, tmax, minimum - (my ny - channel) * (maximum - minimum), maximum + (channel - 1) * (maximum - minimum));
2375 bool current, previous = true, fill = false; // fill only when leaving area
2376 double tmini = tmin, tmaxi = tmax, xe, ye;
2377 integer ix = ixmin;
2378 do {
2379 Formula_run (channel, ix, & result);
2380 current = ( result. numericResult != 0.0 );
2381 if (ix == ixmin)
2382 previous = current;
2383 if (previous != current) {
2384 Sound_findIntermediatePoint_bs (me, channel, ix - 1, previous, current, formula, interpreter, numberOfBisections, & xe, & ye);
2385 if (current) { // entering painting area
2386 tmini = xe;
2387 } else { //leaving painting area
2388 tmaxi = xe;
2389 fill = true;
2390 }
2391 Formula_compile (interpreter, me, formula, kFormula_EXPRESSION_TYPE_NUMERIC, true);
2392 }
2393 if (ix == ixmax && current) {
2394 tmaxi = tmax;
2395 fill = true;
2396 }
2397 if (fill) {
2398 autoPolygon him = Sound_to_Polygon (me, channel, tmini, tmaxi, minimum, maximum, level);
2399 Graphics_fillArea (g, his numberOfPoints, & his x [1], & his y [1]);
2400 fill = false;
2401 }
2402 previous = current;
2403 } while ( ++ix <= ixmax);
2404 }
2405 Graphics_setWindow (g, tmin, tmax, minimum, maximum);
2406 if (garnish && my ny == 2)
2407 Graphics_line (g, tmin, 0.5 * (minimum + maximum), tmax, 0.5 * (minimum + maximum));
2408 Graphics_unsetInner (g);
2409 if (garnish)
2410 _Sound_garnish (me, g, tmin, tmax, minimum, maximum);
2411 } catch (MelderError) {
2412 Melder_clearError ();
2413 }
2414 }
2415
2416 void Sounds_paintEnclosed (Sound me, Sound thee, Graphics g, MelderColour colour, double tmin, double tmax, double minimum, double maximum, bool garnish) {
2417 try {
2418 integer ixmin, ixmax;
2419 const integer numberOfChannels = std::max (my ny, thy ny);
2420 double min1 = minimum, max1 = maximum, tmin1 = tmin, tmax1 = tmax;
2421 double min2 = min1, max2 = max1, tmin2 = tmin1, tmax2 = tmax1;
2422 const double xmin = std::max (my xmin, thy xmin);
2423 const double xmax = std::min (my xmax, thy xmax);
2424 if (xmax <= xmin)
2425 return;
2426 if (tmin >= tmax) { // ppgb: why this, if autoscaling occurs anyway?
2427 tmin = xmin;
2428 tmax = xmax;
2429 }
2430 autowindowAndGetWindowSamplesAndAutoscale (thee, & tmin1, & tmax1, & min1, & max1, & ixmin, & ixmax);
2431 autowindowAndGetWindowSamplesAndAutoscale (me, & tmin2, & tmax2, & min2, & max2, & ixmin, & ixmax);
2432 minimum = std::min (min1, min2);
2433 maximum = std::max (max1, max2);
2434
2435 Graphics_setColour (g, colour);
2436 Graphics_setInner (g);
2437 for (integer channel = 1; channel <= numberOfChannels; channel ++) {
2438 autoPolygon him = Sounds_to_Polygon_enclosed (me, thee, channel, tmin, tmax, minimum, maximum);
2439 Graphics_setWindow (g, tmin, tmax, minimum - (numberOfChannels - channel) * (maximum - minimum), maximum + (channel - 1) * (maximum - minimum));
2440 Graphics_fillArea (g, his numberOfPoints, &his x [1], &his y [1]);
2441 }
2442 Graphics_setWindow (g, tmin, tmax, minimum, maximum);
2443 if (garnish && (my ny == 2 || thy ny == 2))
2444 Graphics_line (g, tmin, 0.5 * (minimum + maximum), tmax, 0.5 * (minimum + maximum));
2445 Graphics_unsetInner (g);
2446 if (garnish)
2447 _Sound_garnish (my ny == 2 ? me : thee, g, tmin, tmax, minimum, maximum);
2448 } catch (MelderError) {
2449 Melder_clearError ();
2450 }
2451 }
2452
2453 /* After a script by Ton Wempe */
2454 static autoSound Sound_reduceNoiseBySpectralSubtraction_mono (Sound me, Sound noise, double windowLength, double noiseReduction_dB) {
2455 try {
2456 Melder_require (my dx == noise -> dx,
2457 U"The sound and the noise should have the same sampling frequency.");
2458 Melder_require (my ny == 1 && noise -> ny == 1,
2459 U"The number of channels in the noise and the sound should equal 1.");
2460
2461 const double samplingFrequency = 1.0 / my dx, nyquistFrequency = 0.5 / my dx;
2462 autoSound denoised = Sound_create (1, my xmin, my xmax, my nx, my dx, my x1);
2463 autoSound const analysisWindow = Sound_createSimple (1, windowLength, samplingFrequency);
2464 const integer windowSamples = analysisWindow -> nx;
2465 const integer wantedNumberOfFrequencyBins = windowSamples / 2 + 1;
2466 autoSound const noise_copy = Data_copy (noise);
2467 Sound_multiplyByWindow (noise_copy.get(), kSound_windowShape::HANNING);
2468 /*
2469 The number of bands in the noise Ltas and the number of frequencies in the
2470 sound spectra preferably should to be equal.
2471 numberOfBands = Melder_iceiling (nyquistFrequency / bandwidth)
2472 wantedNumberOfFrequencyBins = windowSamples / 2 + 1;
2473 We can calculate the bandwidth to make numberOfBands == wantedNumberOfFrequencyBins by applying
2474 the following two conditions
2475 (1) nyquistFrequency / b > wantedNumberOfFrequencyBins - 1 && (2) nyquistFrequency / b < wantedNumberOfFrequencyBins
2476 (1) gives b1 < nyquistFrequency / (wantedNumberOfFrequencyBins - 1)
2477 (2) gives b2 > nyquistFrequency / wantedNumberOfFrequencyBins
2478 Take b = (b1 + b2) / 2
2479 */
2480 double bandwidth = nyquistFrequency * (wantedNumberOfFrequencyBins - 0.5) / (wantedNumberOfFrequencyBins * (wantedNumberOfFrequencyBins - 1));
2481 autoLtas const noiseLtas = Sound_to_Ltas (noise_copy.get(), bandwidth);
2482 Melder_assert (noiseLtas -> nx == wantedNumberOfFrequencyBins);
2483 autoVEC const noiseAmplitudes = raw_VEC (noiseLtas -> nx);
2484 for (integer iband = 1; iband <= noiseLtas -> nx; iband ++) {
2485 const double powerDensity = 4e-10 * pow (10.0, noiseLtas -> z [1] [iband] / 10.0);
2486 noiseAmplitudes [iband] = sqrt (0.5 * powerDensity);
2487 }
2488 autoMelderProgress progress (U"Remove noise");
2489
2490 const double noiseAmplitudeSubtractionScaleFactor = 1.0 - pow (10.0, noiseReduction_dB / 20.0);
2491 const integer stepSizeSamples = windowSamples / 4;
2492 const integer numberOfSteps = my nx / stepSizeSamples;
2493 for (integer istep = 1; istep <= numberOfSteps; istep ++) {
2494 const integer istart = (istep - 1) * stepSizeSamples + 1;
2495
2496 if (istart >= my nx)
2497 break; // finished
2498 const integer nsamples = std::min (my nx - istart + 1, windowSamples);
2499
2500 analysisWindow -> z.row (1).part (1, nsamples) <<= my z.row (1).part (istart, istart + nsamples - 1);
2501 if (nsamples < windowSamples)
2502 analysisWindow -> z.row (1).part (nsamples + 1, windowSamples) <<= 0.0;
2503
2504 // Sound_multiplyByWindow (analysisWindow.get(), kSound_windowShape::HANNING);
2505 autoSpectrum const analysisSpectrum = Sound_to_Spectrum (analysisWindow.get(), false);
2506 /*
2507 Suppress noise in the analysisSpectrum by subtracting the noise spectrum
2508 */
2509 VEC const re = analysisSpectrum -> z.row (1), im = analysisSpectrum -> z.row (2);
2510 for (integer ifreq = 1; ifreq <= analysisSpectrum -> nx; ifreq ++) {
2511 const double amp = hypot (re [ifreq], im [ifreq]);
2512 const double factor = std::max (1.0 - noiseAmplitudeSubtractionScaleFactor * noiseAmplitudes [ifreq] / amp, 1e-6);
2513 re [ifreq] *= factor;
2514 im [ifreq] *= factor;
2515 }
2516 autoSound const suppressed = Spectrum_to_Sound (analysisSpectrum.get());
2517 Sound_multiplyByWindow (suppressed.get(), kSound_windowShape::HANNING);
2518 denoised -> z.row (1).part (istart, istart + nsamples - 1) += 0.5 * suppressed -> z.row (1).part (1, nsamples); // 0.5 because of 2-fold
2519 if (istep % 10 == 1)
2520 Melder_progress (double (istep) / numberOfSteps,
2521 U"Remove noise: frame ", istep, U" out of ", numberOfSteps, U".");
2522 }
2523 return denoised;
2524 } catch (MelderError) {
2525 Melder_throw (me, U": noise not subtracted.");
2526 }
2527 }
2528
2529 //TODO improve?
2530 static void Sound_findNoise (Sound me, double minimumNoiseDuration, double *noiseStart, double *noiseEnd) {
2531 try {
2532 *noiseStart = undefined;
2533 *noiseEnd = undefined;
2534 autoIntensity const intensity = Sound_to_Intensity (me, 20.0, 0.005, true);
2535 double tmin = Vector_getXOfMinimum (intensity.get(), intensity -> xmin, intensity -> xmax, kVector_peakInterpolation :: PARABOLIC) - minimumNoiseDuration / 2.0;
2536 double tmax = tmin + minimumNoiseDuration;
2537 if (tmin < my xmin) {
2538 tmin = my xmin;
2539 tmax = tmin + minimumNoiseDuration;
2540 }
2541 if (tmax > my xmax) {
2542 tmax = my xmax;
2543 tmin = tmax - minimumNoiseDuration;
2544 }
2545 Melder_require (tmin >= my xmin,
2546 U"Sound too short, or window length too long.");
2547
2548 *noiseStart = tmin;
2549 *noiseEnd = tmax;
2550 } catch (MelderError) {
2551 Melder_throw (me, U": noise not found.");
2552 }
2553 }
2554
2555 autoSound Sound_removeNoise (Sound me, double noiseStart, double noiseEnd, double windowLength, double minBandFilterFrequency, double maxBandFilterFrequency, double smoothing, kSoundNoiseReductionMethod method) {
2556 return Sound_reduceNoise (me, noiseStart, noiseEnd, windowLength, minBandFilterFrequency, maxBandFilterFrequency, smoothing, 0.0, method);
2557 }
2558
2559 autoSound Sound_reduceNoise (Sound me, double noiseStart, double noiseEnd, double windowLength, double minBandFilterFrequency, double maxBandFilterFrequency, double smoothing, double noiseReduction_dB, kSoundNoiseReductionMethod method) {
2560 try {
2561 autoSound const filtered = Sound_filter_passHannBand (me, minBandFilterFrequency, maxBandFilterFrequency, smoothing);
2562 autoSound denoised = Sound_create (my ny, my xmin, my xmax, my nx, my dx, my x1);
2563 const bool findNoise = ( noiseEnd <= noiseStart );
2564 const double minimumNoiseDuration = 2.0 * windowLength;
2565 for (integer ichannel = 1; ichannel <= my ny; ichannel ++) {
2566 autoSound denoisedi, channeli = Sound_extractChannel (filtered.get(), ichannel);
2567 if (findNoise)
2568 Sound_findNoise (channeli.get(), minimumNoiseDuration, & noiseStart, & noiseEnd);
2569 autoSound noise = Sound_extractPart (channeli.get(), noiseStart, noiseEnd, kSound_windowShape::RECTANGULAR, 1.0, false);
2570 if (method == kSoundNoiseReductionMethod::SPECTRAL_SUBTRACTION) { // spectral subtraction
2571 denoisedi = Sound_reduceNoiseBySpectralSubtraction_mono (filtered.get(), noise.get(), windowLength, noiseReduction_dB);
2572 } else {
2573 Melder_crash (U"Unknown method in Sound_reduceNoise.");
2574 }
2575 denoised -> z.row (ichannel) <<= denoisedi -> z.row (1);
2576 }
2577 return denoised;
2578 } catch (MelderError) {
2579 Melder_throw (me, U": not denoised.");
2580 }
2581 }
2582
2583 void Sound_playAsFrequencyShifted (Sound me, double shiftBy, double newSamplingFrequency, integer precision) {
2584 try {
2585 autoSpectrum const spectrum = Sound_to_Spectrum (me, true);
2586 autoSpectrum const shifted = Spectrum_shiftFrequencies (spectrum.get(), shiftBy, newSamplingFrequency / 2, precision);
2587 autoSound const thee = Spectrum_to_Sound (shifted.get());
2588 Sound_playPart (thee.get(), my xmin, my xmax, nullptr, nullptr);
2589 } catch (MelderError) {
2590 Melder_throw (me, U" not played with frequencies shifted.");
2591 }
2592 }
2593
2594 void Sound_saveAsMP3File (Sound me, MelderFile file, kSoundToMP3Encoding mp3Encoding, integer kbitsPerSecond) {
2595 try {
2596 const integer samplingFrequency = 1.0 / my dx;
2597 Melder_require (kbitsPerSecond >= 8 && kbitsPerSecond <= 320,
2598 U"The number of kilo bits per second should be in the interval [8, 320].");
2599 Melder_require (my ny <= 2,
2600 U"Your sound should not have more than two channels.");
2601 lame_global_flags *encoderSettings = lame_init ();
2602 Melder_require (encoderSettings != nullptr,
2603 U"The L.A.M.E. encoder settings could not be initialised.");
2604
2605 lame_set_num_channels (encoderSettings, my ny);
2606 lame_set_in_samplerate (encoderSettings, samplingFrequency);
2607 lame_set_out_samplerate (encoderSettings, samplingFrequency);
2608 vbr_mode vbrMode = (mp3Encoding == kSoundToMP3Encoding::CBR ? vbr_off :
2609 (mp3Encoding == kSoundToMP3Encoding::ABR) ? vbr_abr : vbr_mtrh);
2610 Melder_require (lame_set_VBR (encoderSettings, vbrMode) == 0,
2611 U"Error setting bit rate mode.");
2612
2613 lame_set_VBR_max_bitrate_kbps (encoderSettings, kbitsPerSecond);
2614
2615 Melder_require (lame_init_params (encoderSettings) >= 0,
2616 U"Some of the parameter do not combine. ");
2617 /* encoding */
2618 const integer mp3bufferSize = 262144; // 2^18: large enough, we don't use album art pictures
2619 autoBYTEVEC mp3buffer = raw_BYTEVEC (mp3bufferSize);
2620 unsigned char *mp3buffer_p = mp3buffer.asArgumentToFunctionThatExpectsZeroBasedArray();
2621 file -> filePointer = Melder_fopen (file, "wb");
2622 /*
2623 We do not need to write an id3v2 tag
2624 */
2625 double *left = my z [1].asArgumentToFunctionThatExpectsZeroBasedArray();
2626 double *right = (my ny == 2) ? my z [2].asArgumentToFunctionThatExpectsZeroBasedArray() : nullptr;
2627 integer numberOfSamplesToEncode = my nx;
2628 integer numberOfSamplesPerEncodingStep = lame_get_maximum_number_of_samples (encoderSettings, mp3bufferSize);
2629 numberOfSamplesPerEncodingStep = std::min (numberOfSamplesPerEncodingStep, numberOfSamplesToEncode);
2630 do {
2631 integer numberOfBytesOutput = lame_encode_buffer_ieee_double (encoderSettings, left, right,
2632 numberOfSamplesPerEncodingStep, mp3buffer_p, mp3bufferSize);
2633 Melder_require (numberOfBytesOutput >= 0,
2634 U"MP3 internal error (", numberOfBytesOutput, U",).");
2635 if (numberOfBytesOutput > 0)
2636 fwrite (mp3buffer_p, 1, numberOfBytesOutput, file -> filePointer);
2637 numberOfSamplesToEncode -= numberOfSamplesPerEncodingStep;
2638 left += numberOfSamplesPerEncodingStep;
2639 if (my ny == 2)
2640 right += numberOfSamplesPerEncodingStep;
2641 } while (numberOfSamplesToEncode > 0);
2642 const integer numberOfBytesToFlush = lame_encode_flush (encoderSettings, mp3buffer_p, mp3bufferSize);
2643 if (numberOfBytesToFlush > 0)
2644 fwrite (mp3buffer_p, 1, numberOfBytesToFlush, file -> filePointer);
2645 lame_close (encoderSettings);
2646 Melder_fclose (file, file -> filePointer);
2647 } catch (MelderError) {
2648 Melder_throw (U"");
2649 }
2650 }
2651
2652 void Sound_saveAsMP3File_VBR (Sound me, MelderFile file, double inverseQuality) {
2653 try {
2654 const integer samplingFrequency = 1.0 / my dx;
2655 Melder_require (inverseQuality >= 0.0 && inverseQuality < 10.0,
2656 U"The quality should be in the interval [0, 10).");
2657 Melder_require (my ny <= 2,
2658 U"Your sound should not have more than two channels.");
2659 lame_global_flags *encoderSettings = lame_init ();
2660 Melder_require (encoderSettings != nullptr,
2661 U"The L.A.M.E. encoder settings could not be initialised.");
2662
2663 lame_set_num_channels (encoderSettings, my ny);
2664 lame_set_in_samplerate (encoderSettings, samplingFrequency);
2665 lame_set_out_samplerate (encoderSettings, samplingFrequency);
2666 lame_set_VBR_quality (encoderSettings, inverseQuality);
2667 Melder_require (lame_set_VBR (encoderSettings, vbr_mtrh) == 0,
2668 U"Error setting bit rate mode.");
2669
2670 Melder_require (lame_init_params (encoderSettings) >= 0,
2671 U"Some of the parameter do not combine. ");
2672
2673 const integer mp3bufferSize = 262144; // 2^18: large enough, we don't use album art pictures
2674 autoBYTEVEC mp3buffer = raw_BYTEVEC (mp3bufferSize);
2675 unsigned char *mp3buffer_p = mp3buffer.asArgumentToFunctionThatExpectsZeroBasedArray();
2676 file -> filePointer = Melder_fopen (file, "wb");
2677 /*
2678 We do not need to write an id3v2 tag
2679 */
2680 double *left = my z [1].asArgumentToFunctionThatExpectsZeroBasedArray();
2681 double *right = (my ny == 2) ? my z [2].asArgumentToFunctionThatExpectsZeroBasedArray() : nullptr;
2682 integer numberOfSamplesToEncode = my nx;
2683 integer numberOfSamplesPerEncodingStep = lame_get_maximum_number_of_samples (encoderSettings, mp3bufferSize);
2684 do {
2685 numberOfSamplesPerEncodingStep = std::min (numberOfSamplesPerEncodingStep, numberOfSamplesToEncode);
2686 const integer numberOfBytesOutput = lame_encode_buffer_ieee_double (encoderSettings, left, right,
2687 numberOfSamplesPerEncodingStep, mp3buffer_p, mp3bufferSize);
2688 Melder_require (numberOfBytesOutput >= 0,
2689 U"MP3 internal error (", numberOfBytesOutput, U",).");
2690 if (numberOfBytesOutput > 0)
2691 fwrite (mp3buffer_p, 1, numberOfBytesOutput, file -> filePointer);
2692 numberOfSamplesToEncode -= numberOfSamplesPerEncodingStep;
2693 left += numberOfSamplesPerEncodingStep;
2694 if (my ny == 2)
2695 right += numberOfSamplesPerEncodingStep;
2696 } while (numberOfSamplesToEncode > 0);
2697 const integer numberOfBytesToFlush = lame_encode_flush (encoderSettings, mp3buffer_p, mp3bufferSize);
2698 if (numberOfBytesToFlush > 0)
2699 fwrite (mp3buffer_p, 1, numberOfBytesToFlush, file -> filePointer);
2700 lame_close (encoderSettings);
2701 Melder_fclose (file, file -> filePointer);
2702 } catch (MelderError) {
2703 Melder_throw (U"");
2704 }
2705 }
2706
2707 void windowShape_into_VEC (kSound_windowShape windowShape, VEC inout_window) {
2708 const integer size = inout_window.size;
2709 const double imid = 0.5 * (double) (size + 1);
2710 double edge, onebyedge, factor;
2711 switch (windowShape) {
2712 case kSound_windowShape::RECTANGULAR:
2713 inout_window <<= 1.0;
2714 break;
2715 case kSound_windowShape::TRIANGULAR: // "Bartlett"
2716 for (integer i = 1; i <= size; i ++) {
2717 const double phase = (double) (i - 0.5) / size;
2718 inout_window [i] = 1.0 - fabs ((2.0 * phase - 1.0));
2719 }
2720 break;
2721 case kSound_windowShape::PARABOLIC: // "Welch"
2722 for (integer i = 1; i <= size; i ++) {
2723 const double phase = (double) (i - 0.5) / size;
2724 inout_window [i] = 1.0 - (2.0 * phase - 1.0) * (2.0 * phase - 1.0);
2725 }
2726 break;
2727 case kSound_windowShape::HANNING:
2728 for (integer i = 1; i <= size; i ++) {
2729 const double phase = (double) (i - 0.5) / size;
2730 inout_window [i] = 0.5 * (1.0 - cos (NUM2pi * phase));
2731 }
2732 break;
2733 case kSound_windowShape::HAMMING:
2734 for (integer i = 1; i <= size; i ++) {
2735 const double phase = (double) (i - 0.5) / size;
2736 inout_window [i] = 0.54 - 0.46 * cos (NUM2pi * phase);
2737 }
2738 break;
2739 case kSound_windowShape::GAUSSIAN_1:
2740 edge = exp (-3.0);
2741 onebyedge = 1.0 / (1.0 - edge); // -0.5..+0.5
2742 for (integer i = 1; i <= size; i ++) {
2743 const double phase = ((double) i - imid) / size;
2744 inout_window [i] = (exp (-12.0 * phase * phase) - edge) * onebyedge;
2745 }
2746 break;
2747 case kSound_windowShape::GAUSSIAN_2:
2748 edge = exp (-12.0);
2749 onebyedge = 1.0 / (1.0 - edge);
2750 for (integer i = 1; i <= size; i ++) {
2751 const double phase = ((double) i - imid) / size;
2752 inout_window [i] = (exp (-48.0 * phase * phase) - edge) * onebyedge;
2753 }
2754 break;
2755 case kSound_windowShape::GAUSSIAN_3:
2756 edge = exp (-27.0);
2757 onebyedge = 1.0 / (1.0 - edge);
2758 for (integer i = 1; i <= size; i ++) {
2759 const double phase = ((double) i - imid) / size;
2760 inout_window [i] = (exp (-108.0 * phase * phase) - edge) * onebyedge;
2761 }
2762 break;
2763 case kSound_windowShape::GAUSSIAN_4:
2764 edge = exp (-48.0);
2765 onebyedge = 1.0 / (1.0 - edge);
2766 for (integer i = 1; i <= size; i ++) {
2767 const double phase = ((double) i - imid) / size;
2768 inout_window [i] = (exp (-192.0 * phase * phase) - edge) * onebyedge;
2769 }
2770 break;
2771 case kSound_windowShape::GAUSSIAN_5:
2772 edge = exp (-75.0);
2773 onebyedge = 1.0 / (1.0 - edge);
2774 for (integer i = 1; i <= size; i ++) {
2775 const double phase = ((double) i - imid) / size;
2776 inout_window [i] = (exp (-300.0 * phase * phase) - edge) * onebyedge;
2777 }
2778 break;
2779 case kSound_windowShape::KAISER_1:
2780 factor = 1.0 / NUMbessel_i0_f (NUM2pi);
2781 for (integer i = 1; i <= size; i ++) {
2782 const double phase = 2.0 * ((double) i - imid) / size; // -1..+1
2783 const double root = 1.0 - phase * phase;
2784 inout_window [i] = ( root <= 0.0 ? 0.0 : factor * NUMbessel_i0_f (NUM2pi * sqrt (root)) );
2785 }
2786 break;
2787 case kSound_windowShape::KAISER_2:
2788 factor = 1.0 / NUMbessel_i0_f (NUM2pi * NUMpi + 0.5);
2789 for (integer i = 1; i <= size; i ++) {
2790 const double phase = 2.0 * ((double) i - imid) / size; // -1..+1
2791 const double root = 1.0 - phase * phase;
2792 inout_window [i] = ( root <= 0.0 ? 0.0 : factor * NUMbessel_i0_f ((NUM2pi * NUMpi + 0.5) * sqrt (root)) );
2793 }
2794 break;
2795 default:
2796 inout_window <<= 1.0;
2797 }
2798 }
2799
2800 autoSound Sound_resampleAndOrPreemphasize (constSound me, double maximumFrequency, integer depth, double preEmphasisFrequency) {
2801 try {
2802 const double nyquistFrequency = 0.5 / my dx;
2803 autoSound sound;
2804 if (maximumFrequency <= 0.0 || fabs (maximumFrequency / nyquistFrequency - 1.0) < 1.0e-12)
2805 sound = Data_copy (me);
2806 else
2807 sound = Sound_resample (me, maximumFrequency * 2.0, depth);
2808 Sound_preEmphasize_inplace (sound.get(), preEmphasisFrequency);
2809 return sound;
2810 } catch (MelderError) {
2811 Melder_throw (me, U": could not resample.");
2812 }
2813 }
2814
2815 /* End of file Sound_extensions.cpp */