| 1 | /* LongSound.cpp |
| 2 | * |
| 3 | * Copyright (C) 1992-2008,2010-2019,2021-2025 Paul Boersma, 2007 Erez Volk (for FLAC and MP3) |
| 4 | * |
| 5 | * This code is free software; you can redistribute it and/or modify |
| 6 | * it under the terms of the GNU General Public License as published by |
| 7 | * the Free Software Foundation; either version 3 of the License, or (at |
| 8 | * your option) any later version. |
| 9 | * |
| 10 | * This code is distributed in the hope that it will be useful, but |
| 11 | * WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| 13 | * See the GNU General Public License for more details. |
| 14 | * |
| 15 | * You should have received a copy of the GNU General Public License |
| 16 | * along with this work. If not, see <http://www.gnu.org/licenses/>. |
| 17 | */ |
| 18 | |
| 19 | /* |
| 20 | * pb 2002/05/28 |
| 21 | * pb 2002/07/16 GPL |
| 22 | * pb 2003/09/12 changed 5 to Melder_NUMBER_OF_AUDIO_FILE_TYPES |
| 23 | * pb 2004/05/14 support for reading 24-bit and 32-bit audio files |
| 24 | * pb 2004/11/24 made buffer length settable |
| 25 | * pb 2006/12/10 MelderInfo |
| 26 | * pb 2006/12/13 support for IEEE float 32-bit audio files |
| 27 | * pb 2007/01/01 compatible with stereo sounds |
| 28 | * pb 2007/01/27 more compatible with stereo sounds |
| 29 | * pb 2007/03/17 domain quantity |
| 30 | * Erez Volk 2007/03 FLAC reading |
| 31 | * Erez Volk 2007/05/14 FLAC writing |
| 32 | * Erez Volk 2007/06/04 MP3 reading |
| 33 | * pb 2007/12/05 prefs |
| 34 | * pb 2008/01/19 double |
| 35 | * pb 2010/01/10 MP3 precision warning |
| 36 | * fb 2010/02/25 corrected a bug that could cause LongSound_playPart to crash with an assertion on error |
| 37 | * pb 2010/11/07 no longer do an assertion on thy resampledBuffer |
| 38 | * pb 2010/12/20 support for more than 2 channels |
| 39 | * pb 2011/06/02 C++ |
| 40 | * pb 2011/07/05 C++ |
| 41 | * pb 2014/06/16 more support for more than 2 channels |
| 42 | */ |
| 43 | |
| 44 | #include "LongSound.h" |
| 45 | #include "Preferences.h" |
| 46 | #define FLAC__NO_DLL |
| 47 | #include "../external/flac/flac_FLAC_stream_decoder.h" |
| 48 | #include "../external/mp3/mp3.h" |
| 49 | |
| 50 | Thing_implement (LongSound, SampledXY, 0); |
| 51 | Thing_implement (SoundAndLongSoundList, Ordered, 0); |
| 52 | |
| 53 | #define MARGIN 0.01 |
| 54 | #define USE_MEMMOVE 1 |
| 55 | |
| 56 | constexpr integer minimumBufferDuration = 10; // seconds |
| 57 | constexpr integer defaultBufferDuration = 600; // seconds |
| 58 | constexpr integer maximumBufferDuration = 10000; // seconds |
| 59 | |
| 60 | static integer prefs_bufferLength; |
| 61 | |
| 62 | void LongSound_preferences () { |
| 63 | Preferences_addInteger (U"LongSound.bufferLength2", & prefs_bufferLength, defaultBufferDuration); |
| 64 | } |
| 65 | |
| 66 | integer LongSound_getBufferSizePref_seconds () { |
| 67 | return prefs_bufferLength; |
| 68 | } |
| 69 | |
| 70 | void LongSound_setBufferSizePref_seconds (const integer size) { |
| 71 | prefs_bufferLength = Melder_clipped (minimumBufferDuration, size, maximumBufferDuration); |
| 72 | } |
| 73 | |
| 74 | void structLongSound :: v9_destroy () noexcept { |
| 75 | /* |
| 76 | The play callback may contain a pointer to my buffer. |
| 77 | That pointer is about to dangle, so kill the playback. |
| 78 | */ |
| 79 | MelderAudio_stopPlaying (MelderAudio_IMPLICIT); |
| 80 | if (mp3f) |
| 81 | mp3f_delete (mp3f); |
| 82 | if (flacDecoder) { |
| 83 | FLAC__stream_decoder_finish (flacDecoder); // closes f |
| 84 | FLAC__stream_decoder_delete (flacDecoder); |
| 85 | } else if (f) { |
| 86 | fclose (f); |
| 87 | } |
| 88 | LongSound_Parent :: v9_destroy (); |
| 89 | } |
| 90 | |
| 91 | void structLongSound :: v1_info () { |
| 92 | structDaata :: v1_info (); |
| 93 | static const conststring32 encodingStrings [1+22] = { U"none", |
| 94 | U"linear 8 bit signed", U"linear 8 bit unsigned", |
| 95 | U"linear 16 bit big-endian", U"linear 16 bit little-endian", |
| 96 | U"linear 24 bit big-endian", U"linear 24 bit little-endian", |
| 97 | U"linear 32 bit big-endian", U"linear 32 bit little-endian", |
| 98 | U"mu-law", U"A-law", U"shorten", U"polyphone", |
| 99 | U"IEEE float 32 bit big-endian", U"IEEE float 32 bit little-endian", |
| 100 | U"IEEE float 64 bit big-endian", U"IEEE float 64 bit little-endian", |
| 101 | U"FLAC", U"FLAC", U"FLAC", U"MP3", U"MP3", U"MP3" }; |
| 102 | MelderInfo_writeLine (U"Duration: ", xmax - xmin, U" seconds"); |
| 103 | MelderInfo_writeLine (U"File name: ", MelderFile_peekPath (& file)); |
| 104 | MelderInfo_writeLine (U"File type: ", audioFileType > Melder_NUMBER_OF_AUDIO_FILE_TYPES ? U"unknown" : Melder_audioFileTypeString (audioFileType)); |
| 105 | MelderInfo_writeLine (U"Number of channels: ", numberOfChannels); |
| 106 | MelderInfo_writeLine (U"Encoding: ", encoding > 20 ? U"unknown" : encodingStrings [encoding]); |
| 107 | MelderInfo_writeLine (U"Sampling frequency: ", sampleRate, U" Hz"); |
| 108 | MelderInfo_writeLine (U"Size: ", nx, U" samples"); |
| 109 | MelderInfo_writeLine (U"Start of sample data: ", startOfData, U" bytes from the start of the file"); |
| 110 | } |
| 111 | |
| 112 | static void _LongSound_FLAC_convertFloats (LongSound me, const int32 *const samples[], const integer bitsPerSample, const integer numberOfSamples) { |
| 113 | double multiplier; |
| 114 | switch (bitsPerSample) { |
| 115 | case 8: multiplier = (1.0 / 128.0); break; |
| 116 | case 16: multiplier = (1.0 / 32768.0); break; |
| 117 | case 24: multiplier = (1.0 / 8388608.0); break; |
| 118 | case 32: multiplier = (1.0 / 32768.0 / 65536.0); break; |
| 119 | default: multiplier = 0.0; |
| 120 | } |
| 121 | for (integer i = 0; i < 2; ++i) { |
| 122 | const int32 *input = samples [i]; |
| 123 | double *output = my compressedFloats [i]; |
| 124 | if (! output ) continue; |
| 125 | for (integer j = 0; j < numberOfSamples; ++j) |
| 126 | output [j] = (double) input [j] * multiplier; |
| 127 | my compressedFloats [i] += numberOfSamples; |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | static void _LongSound_FLAC_convertShorts (LongSound me, const int32 *const samples[], const integer bitsPerSample, const integer numberOfSamples) { |
| 132 | for (integer channel = 0; channel < my numberOfChannels; ++ channel) { |
| 133 | int16 *output = my compressedShorts + channel; |
| 134 | const int32 *input = samples [channel]; |
| 135 | for (integer j = 0; j < numberOfSamples; ++ j, output += my numberOfChannels) { |
| 136 | int32 sample = * (input ++); |
| 137 | switch (bitsPerSample) { |
| 138 | case 8: sample *= 256; break; |
| 139 | case 16: break; |
| 140 | case 24: sample /= 256; break; |
| 141 | case 32: sample /= 65536; break; |
| 142 | default: sample = 0; break; |
| 143 | } |
| 144 | *output = (int16) sample; |
| 145 | } |
| 146 | } |
| 147 | my compressedShorts += numberOfSamples * my numberOfChannels; |
| 148 | } |
| 149 | |
| 150 | static FLAC__StreamDecoderWriteStatus _LongSound_FLAC_write (const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 *const buffer[], void *void_me) { |
| 151 | iam (LongSound); |
| 152 | const FLAC__FrameHeader *header = & frame -> header; |
| 153 | integer numberOfSamples = header -> blocksize; |
| 154 | const integer bitsPerSample = header -> bits_per_sample; |
| 155 | (void) decoder; |
| 156 | if (numberOfSamples > my compressedSamplesLeft) |
| 157 | numberOfSamples = my compressedSamplesLeft; |
| 158 | if (numberOfSamples == 0) |
| 159 | return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE; |
| 160 | if (my compressedMode == COMPRESSED_MODE_READ_FLOAT) |
| 161 | _LongSound_FLAC_convertFloats (me, buffer, bitsPerSample, numberOfSamples); |
| 162 | else |
| 163 | _LongSound_FLAC_convertShorts (me, buffer, bitsPerSample, numberOfSamples); |
| 164 | my compressedSamplesLeft -= numberOfSamples; |
| 165 | return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE; |
| 166 | } |
| 167 | |
| 168 | static void _LongSound_FLAC_error (const FLAC__StreamDecoder * /* decoder */, FLAC__StreamDecoderErrorStatus /* status */, void * /* longSound */) { |
| 169 | } |
| 170 | |
| 171 | static void _LongSound_MP3_convertFloats (LongSound me, const MP3F_SAMPLE *channels [MP3F_MAX_CHANNELS], const integer numberOfSamples) { |
| 172 | for (integer i = 0; i < 2; ++i) { |
| 173 | const MP3F_SAMPLE *input = channels [i]; |
| 174 | double *output = my compressedFloats [i]; |
| 175 | if (! output ) |
| 176 | continue; |
| 177 | for (integer j = 0; j < numberOfSamples; ++j) |
| 178 | output [j] = mp3f_sample_to_float (input [j]); |
| 179 | my compressedFloats [i] += numberOfSamples; |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | static void _LongSound_MP3_convertShorts (LongSound me, const MP3F_SAMPLE *channels [MP3F_MAX_CHANNELS], const integer numberOfSamples) { |
| 184 | for (integer i = 0; i < my numberOfChannels; ++ i) { |
| 185 | const MP3F_SAMPLE *input = channels [i]; |
| 186 | int16 *output = my compressedShorts + i; |
| 187 | for (integer j = 0; j < numberOfSamples; ++j, output += my numberOfChannels) { |
| 188 | const int sample = *input++; |
| 189 | *output = mp3f_sample_to_short (sample); |
| 190 | } |
| 191 | } |
| 192 | my compressedShorts += numberOfSamples * my numberOfChannels; |
| 193 | } |
| 194 | |
| 195 | static void _LongSound_MP3_convert (const MP3F_SAMPLE *channels [MP3F_MAX_CHANNELS], integer numberOfSamples, void *void_me) { |
| 196 | iam (LongSound); |
| 197 | if (numberOfSamples > my compressedSamplesLeft) |
| 198 | numberOfSamples = my compressedSamplesLeft; |
| 199 | if (numberOfSamples == 0) |
| 200 | return; |
| 201 | if (my compressedMode == COMPRESSED_MODE_READ_FLOAT) |
| 202 | _LongSound_MP3_convertFloats (me, channels, numberOfSamples); |
| 203 | else |
| 204 | _LongSound_MP3_convertShorts (me, channels, numberOfSamples); |
| 205 | my compressedSamplesLeft -= numberOfSamples; |
| 206 | } |
| 207 | |
| 208 | static void LongSound_init (LongSound me, constMelderFile file) { |
| 209 | MelderFile_copy (file, & my file); |
| 210 | MelderFile_open (& my file); |
| 211 | my f = my file. filePointer; |
| 212 | my audioFileType = MelderFile_checkSoundFile (& my file, & my numberOfChannels, & my encoding, & my sampleRate, & my startOfData, & my nx); |
| 213 | if (my audioFileType == 0) |
| 214 | Melder_throw (U"File not recognized (LongSound only supports AIFF, AIFC, WAV, NeXT/Sun, NIST and FLAC)."); |
| 215 | if (my encoding == Melder_SHORTEN || my encoding == Melder_POLYPHONE) |
| 216 | Melder_throw (U"LongSound does not support sound files compressed with \"shorten\"."); |
| 217 | if (my nx < 1) |
| 218 | Melder_throw (U"Audio file contains 0 samples."); |
| 219 | my xmin = 0.0; |
| 220 | my dx = 1.0 / my sampleRate; |
| 221 | my xmax = my nx * my dx; |
| 222 | my x1 = 0.5 * my dx; |
| 223 | my ymin = 1.0; |
| 224 | my ymax = my numberOfChannels; // TODO: rid numberOfChannels |
| 225 | my ny = my numberOfChannels; |
| 226 | my dy = 1.0; |
| 227 | my y1 = 1.0; |
| 228 | my numberOfBytesPerSamplePoint = Melder_bytesPerSamplePoint (my encoding); |
| 229 | my bufferLength = prefs_bufferLength; |
| 230 | for (;;) { |
| 231 | my nmax = my bufferLength * my sampleRate * (1 + 3 * MARGIN); |
| 232 | try { |
| 233 | my buffer = newvectorzero <int16> (my nmax * my numberOfChannels + 1); |
| 234 | break; |
| 235 | } catch (MelderError) { |
| 236 | my bufferLength *= 0.5; // try 30, 15, or 7.5 seconds |
| 237 | if (my bufferLength < 5.0) // too short to be good |
| 238 | throw; |
| 239 | Melder_clearError (); // delete out-of-memory message |
| 240 | } |
| 241 | } |
| 242 | my imin = 1; |
| 243 | my imax = 0; |
| 244 | my flacDecoder = nullptr; |
| 245 | if (my audioFileType == Melder_FLAC) { |
| 246 | my flacDecoder = FLAC__stream_decoder_new (); |
| 247 | FLAC__stream_decoder_init_FILE (my flacDecoder, my f, _LongSound_FLAC_write, nullptr, _LongSound_FLAC_error, me); |
| 248 | } |
| 249 | my mp3f = nullptr; |
| 250 | if (my audioFileType == Melder_MP3) { |
| 251 | my mp3f = mp3f_new (); |
| 252 | mp3f_set_file (my mp3f, my f); |
| 253 | mp3f_set_callback (my mp3f, _LongSound_MP3_convert, me); |
| 254 | if (! mp3f_analyze (my mp3f)) |
| 255 | Melder_throw (U"Unable to analyze MP3 file."); |
| 256 | Melder_warning (U"Time measurements in MP3 files can be off by several tens of milliseconds. " |
| 257 | U"Please convert to WAV file if you need time precision or annotation."); |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | void structLongSound :: v1_copy (Daata thee_Daata) const { |
| 262 | LongSound thee = static_cast <LongSound> (thee_Daata); |
| 263 | thy f = nullptr; |
| 264 | thy buffer.releaseToAmbiguousOwner(); // this may have been shallow-copied, so undangle and nullify |
| 265 | LongSound_init (thee, & our file); // this recreates a new buffer |
| 266 | } |
| 267 | |
| 268 | autoLongSound LongSound_open (MelderFile file) { |
| 269 | try { |
| 270 | autoLongSound me = Thing_new (LongSound); |
| 271 | LongSound_init (me.get(), file); |
| 272 | return me; |
| 273 | } catch (MelderError) { |
| 274 | Melder_throw (U"LongSound not created."); |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | static void _LongSound_FLAC_process (LongSound me, const integer firstSample, const integer numberOfSamples) { |
| 279 | my compressedSamplesLeft = numberOfSamples - 1; |
| 280 | if (! FLAC__stream_decoder_seek_absolute (my flacDecoder, firstSample)) |
| 281 | Melder_throw (U"Cannot seek in FLAC file ", & my file, U"."); |
| 282 | while (my compressedSamplesLeft > 0) { |
| 283 | if (FLAC__stream_decoder_get_state (my flacDecoder) == FLAC__STREAM_DECODER_END_OF_STREAM) |
| 284 | Melder_throw (U"FLAC file ", & my file, U" too short."); |
| 285 | if (! FLAC__stream_decoder_process_single (my flacDecoder)) |
| 286 | Melder_throw (U"Error decoding FLAC file ", & my file, U"."); |
| 287 | } |
| 288 | } |
| 289 | |
| 290 | static void _LongSound_FILE_seekSample (LongSound me, const integer firstSample) { |
| 291 | if (fseek (my f, my startOfData + (firstSample - 1) * my numberOfChannels * my numberOfBytesPerSamplePoint, SEEK_SET)) |
| 292 | Melder_throw (U"Cannot seek in file ", & my file, U"."); |
| 293 | } |
| 294 | |
| 295 | static void _LongSound_FLAC_readAudioToShort (LongSound me, int16 *buffer, const integer firstSample, const integer numberOfSamples) { |
| 296 | my compressedMode = COMPRESSED_MODE_READ_SHORT; |
| 297 | my compressedShorts = buffer + 1; |
| 298 | _LongSound_FLAC_process (me, firstSample, numberOfSamples); |
| 299 | } |
| 300 | |
| 301 | static void _LongSound_MP3_process (LongSound me, const integer firstSample, const integer numberOfSamples) { |
| 302 | if (! mp3f_seek (my mp3f, firstSample)) |
| 303 | Melder_throw (U"Cannot seek in MP3 file ", & my file, U"."); |
| 304 | my compressedSamplesLeft = numberOfSamples; |
| 305 | if (! mp3f_read (my mp3f, numberOfSamples)) |
| 306 | Melder_throw (U"Error decoding MP3 file ", & my file, U"."); |
| 307 | } |
| 308 | |
| 309 | static void _LongSound_MP3_readAudioToShort (LongSound me, int16 *buffer, const integer firstSample, const integer numberOfSamples) { |
| 310 | my compressedMode = COMPRESSED_MODE_READ_SHORT; |
| 311 | my compressedShorts = buffer + 1; |
| 312 | _LongSound_MP3_process (me, firstSample, numberOfSamples - 1); |
| 313 | } |
| 314 | |
| 315 | void LongSound_readAudioToFloat (LongSound me, const MAT buffer, const integer firstSample) { |
| 316 | Melder_assert (buffer.nrow == my numberOfChannels); |
| 317 | if (my encoding == Melder_FLAC_COMPRESSION_16) { |
| 318 | my compressedMode = COMPRESSED_MODE_READ_FLOAT; |
| 319 | for (int ichan = 1; ichan <= my numberOfChannels; ichan ++) { |
| 320 | my compressedFloats [ichan - 1] = & buffer [ichan] [1]; |
| 321 | } |
| 322 | _LongSound_FLAC_process (me, firstSample, buffer.ncol); |
| 323 | } else if (my encoding == Melder_MPEG_COMPRESSION_16) { |
| 324 | my compressedMode = COMPRESSED_MODE_READ_FLOAT; |
| 325 | for (int ichan = 1; ichan <= my numberOfChannels; ichan ++) { |
| 326 | my compressedFloats [ichan - 1] = & buffer [ichan] [1]; |
| 327 | } |
| 328 | _LongSound_MP3_process (me, firstSample, buffer.ncol); |
| 329 | } else { |
| 330 | _LongSound_FILE_seekSample (me, firstSample); |
| 331 | Melder_readAudioToFloat (& my file, my encoding, buffer); |
| 332 | } |
| 333 | } |
| 334 | |
| 335 | void LongSound_readAudioToShort (LongSound me, int16 *buffer, const integer firstSample, const integer numberOfSamples) { |
| 336 | if (my encoding == Melder_FLAC_COMPRESSION_16) { |
| 337 | _LongSound_FLAC_readAudioToShort (me, buffer, firstSample, numberOfSamples); |
| 338 | } else if (my encoding == Melder_MPEG_COMPRESSION_16) { |
| 339 | _LongSound_MP3_readAudioToShort (me, buffer, firstSample, numberOfSamples); |
| 340 | } else { |
| 341 | _LongSound_FILE_seekSample (me, firstSample); |
| 342 | Melder_readAudioToShort (& my file, my numberOfChannels, my encoding, buffer, numberOfSamples); |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | autoSound LongSound_extractPart (LongSound me, double tmin, double tmax, const bool preserveTimes) { |
| 347 | try { |
| 348 | Function_unidirectionalAutowindow (me, & tmin, & tmax); |
| 349 | if (tmin < my xmin) |
| 350 | tmin = my xmin; |
| 351 | if (tmax > my xmax) |
| 352 | tmax = my xmax; |
| 353 | integer firstSample, lastSample; |
| 354 | const integer numberOfSamples = Sampled_getWindowSamples (me, tmin, tmax, & firstSample, & lastSample); |
| 355 | if (numberOfSamples < 1) |
| 356 | Melder_throw (U"Less than 1 sample in window."); |
| 357 | autoSound thee = Sound_create (my numberOfChannels, |
| 358 | tmin, tmax, numberOfSamples, my dx, Sampled_indexToX (me, firstSample)); |
| 359 | if (! preserveTimes) { |
| 360 | thy xmin = 0.0; |
| 361 | thy xmax -= tmin; |
| 362 | thy x1 -= tmin; |
| 363 | } |
| 364 | LongSound_readAudioToFloat (me, thy z.get(), firstSample); |
| 365 | return thee; |
| 366 | } catch (MelderError) { |
| 367 | Melder_throw (me, U": Sound not extracted."); |
| 368 | } |
| 369 | } |
| 370 | |
| 371 | static void _LongSound_readSamples (LongSound me, int16 *buffer, const integer imin, const integer imax) { |
| 372 | LongSound_readAudioToShort (me, buffer, imin, imax - imin + 1); |
| 373 | } |
| 374 | |
| 375 | static void writePartToOpenFile (LongSound me, int audioFileType, const integer imin, const integer n, |
| 376 | MelderFile file, const int numberOfChannels_override, const int numberOfBitsPerSamplePoint) |
| 377 | { |
| 378 | if (! file -> filePointer) |
| 379 | return; |
| 380 | const integer numberOfBuffers = (n - 1) / my nmax + 1; |
| 381 | const integer numberOfSamplesInLastBuffer = (n - 1) % my nmax + 1; |
| 382 | for (integer ibuffer = 1, offset = imin; ibuffer <= numberOfBuffers; ibuffer ++) { |
| 383 | const integer numberOfSamplesToCopy = ( ibuffer < numberOfBuffers ? my nmax : numberOfSamplesInLastBuffer ); |
| 384 | my invalidateBuffer(); |
| 385 | LongSound_readAudioToShort (me, my buffer.asArgumentToFunctionThatExpectsZeroBasedArray(), offset, numberOfSamplesToCopy); |
| 386 | offset += numberOfSamplesToCopy; |
| 387 | MelderFile_writeShortToAudio (file, numberOfChannels_override ? numberOfChannels_override : my numberOfChannels, Melder_defaultAudioFileEncoding (audioFileType, numberOfBitsPerSamplePoint), my buffer.asArgumentToFunctionThatExpectsZeroBasedArray(), numberOfSamplesToCopy); |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | void LongSound_savePartAsAudioFile (LongSound me, int audioFileType, double tmin, double tmax, MelderFile file, int numberOfBitsPerSamplePoint) { |
| 392 | try { |
| 393 | Function_unidirectionalAutowindow (me, & tmin, & tmax); |
| 394 | Melder_clipLeft (my xmin, & tmin); |
| 395 | Melder_clipRight (& tmax, my xmax); |
| 396 | integer imin, imax; |
| 397 | const integer n = Sampled_getWindowSamples (me, tmin, tmax, & imin, & imax); |
| 398 | if (n < 1) |
| 399 | Melder_throw (U"Less than 1 sample selected."); |
| 400 | autoMelderFile mfile = MelderFile_create (file); |
| 401 | MelderFile_writeAudioFileHeader (file, audioFileType, my sampleRate, n, my numberOfChannels, numberOfBitsPerSamplePoint); |
| 402 | writePartToOpenFile (me, audioFileType, imin, n, file, 0, numberOfBitsPerSamplePoint); |
| 403 | MelderFile_writeAudioFileTrailer (file, audioFileType, my sampleRate, n, my numberOfChannels, numberOfBitsPerSamplePoint); |
| 404 | mfile.close (); |
| 405 | } catch (MelderError) { |
| 406 | Melder_throw (me, U": not written to sound file ", file, U"."); |
| 407 | } |
| 408 | } |
| 409 | |
| 410 | void LongSound_saveChannelAsAudioFile (LongSound me, int audioFileType, integer channel, MelderFile file) { |
| 411 | try { |
| 412 | if (my numberOfChannels != 2) |
| 413 | Melder_throw (U"This audio file is not a stereo file. It does not have a ", channel == 0 ? U"left" : U"right", U" channel."); |
| 414 | autoMelderFile mfile = MelderFile_create (file); |
| 415 | if (file -> filePointer) |
| 416 | MelderFile_writeAudioFileHeader (file, audioFileType, my sampleRate, my nx, 1, 8 * my numberOfBytesPerSamplePoint); |
| 417 | writePartToOpenFile (me, audioFileType, 1, my nx, file, channel == 0 ? -1 : -2, 8 * my numberOfBytesPerSamplePoint); |
| 418 | MelderFile_writeAudioFileTrailer (file, audioFileType, my sampleRate, my nx, 1, 8 * my numberOfBytesPerSamplePoint); |
| 419 | mfile.close (); |
| 420 | } catch (MelderError) { |
| 421 | Melder_throw (U"Channel ", channel, U" of ", me, U": not written to sound file ", file, U"."); |
| 422 | } |
| 423 | } |
| 424 | |
| 425 | static void _LongSound_haveSamples (LongSound me, integer imin, integer imax) { |
| 426 | TRACE |
| 427 | trace (0); |
| 428 | integer n = imax - imin + 1; |
| 429 | Melder_assert (n <= my nmax); |
| 430 | /* |
| 431 | Included? |
| 432 | */ |
| 433 | if (imin >= my imin && imax <= my imax) |
| 434 | return; |
| 435 | /* |
| 436 | Extendable? |
| 437 | */ |
| 438 | if (imin >= my imin && imax - my imin + 1 <= my nmax) { |
| 439 | _LongSound_readSamples (me, my buffer.asArgumentToFunctionThatExpectsZeroBasedArray() + (my imax - my imin + 1) * my numberOfChannels, my imax + 1, imax); |
| 440 | my imax = imax; |
| 441 | return; |
| 442 | } |
| 443 | /* |
| 444 | Determine the loadable imin..imax. |
| 445 | Add margins on both sides. |
| 446 | */ |
| 447 | imin -= MARGIN * n; |
| 448 | if (imin < 1) |
| 449 | imin = 1; |
| 450 | imax = imin + Melder_ifloor ((1.0 + 2.0 * MARGIN) * n); |
| 451 | if (imax > my nx) |
| 452 | imax = my nx; |
| 453 | imin = imax - Melder_ifloor ((1.0 + 2.0 * MARGIN) * n); |
| 454 | if (imin < 1) |
| 455 | imin = 1; |
| 456 | Melder_assert (imax - imin + 1 <= my nmax); |
| 457 | trace (1); |
| 458 | /* |
| 459 | Overlap? |
| 460 | */ |
| 461 | if (imax < my imin || imin > my imax) { |
| 462 | /* |
| 463 | No overlap. |
| 464 | */ |
| 465 | _LongSound_readSamples (me, my buffer.asArgumentToFunctionThatExpectsZeroBasedArray(), imin, imax); |
| 466 | } else if (imin < my imin) { |
| 467 | /* |
| 468 | Left overlap. |
| 469 | */ |
| 470 | if (imax <= my imax) { |
| 471 | /* |
| 472 | Only left overlap (e.g. scrolling up). |
| 473 | */ |
| 474 | const integer nshift = (imax - my imin + 1) * my numberOfChannels, shift = (my imin - imin) * my numberOfChannels; |
| 475 | #if USE_MEMMOVE |
| 476 | memmove (my buffer.asArgumentToFunctionThatExpectsZeroBasedArray() + shift, my buffer.asArgumentToFunctionThatExpectsZeroBasedArray(), nshift * sizeof (int16)); |
| 477 | #else |
| 478 | for (i = nshift; i >= 1; i --) |
| 479 | my buffer [i + shift] = my buffer [i]; |
| 480 | #endif |
| 481 | _LongSound_readSamples (me, my buffer.asArgumentToFunctionThatExpectsZeroBasedArray(), imin, my imin - 1); |
| 482 | } else { |
| 483 | /* |
| 484 | Left and right overlap (e.g. zooming out). |
| 485 | */ |
| 486 | const integer nshift = (my imax - my imin + 1) * my numberOfChannels, shift = (my imin - imin) * my numberOfChannels; |
| 487 | #if USE_MEMMOVE |
| 488 | memmove (my buffer.asArgumentToFunctionThatExpectsZeroBasedArray() + shift, my buffer.asArgumentToFunctionThatExpectsZeroBasedArray(), nshift * sizeof (int16)); |
| 489 | #else |
| 490 | for (i = nshift; i >= 1; i --) |
| 491 | my buffer [i + shift] = my buffer [i]; |
| 492 | #endif |
| 493 | _LongSound_readSamples (me, my buffer.asArgumentToFunctionThatExpectsZeroBasedArray(), imin, my imin - 1); |
| 494 | _LongSound_readSamples (me, my buffer.asArgumentToFunctionThatExpectsZeroBasedArray() + (my imax - imin + 1) * my numberOfChannels, my imax + 1, imax); |
| 495 | } |
| 496 | } else { |
| 497 | /* |
| 498 | Only right overlap (e.g. scrolling down). |
| 499 | */ |
| 500 | const integer nshift = (my imax - imin + 1) * my numberOfChannels, shift = (imin - my imin) * my numberOfChannels; |
| 501 | #if USE_MEMMOVE |
| 502 | memmove (my buffer.asArgumentToFunctionThatExpectsZeroBasedArray(), my buffer.asArgumentToFunctionThatExpectsZeroBasedArray() + shift, nshift * sizeof (int16)); |
| 503 | #else |
| 504 | for (i = 1; i <= nshift; i ++) |
| 505 | my buffer [i] = my buffer [i + shift]; |
| 506 | #endif |
| 507 | _LongSound_readSamples (me, my buffer.asArgumentToFunctionThatExpectsZeroBasedArray() + (my imax - imin + 1) * my numberOfChannels, my imax + 1, imax); |
| 508 | } |
| 509 | my imin = imin; |
| 510 | my imax = imax; |
| 511 | trace (2); |
| 512 | } |
| 513 | |
| 514 | bool LongSound_haveWindow (LongSound me, double tmin, double tmax) { |
| 515 | integer imin, imax; |
| 516 | const integer n = Sampled_getWindowSamples (me, tmin, tmax, & imin, & imax); |
| 517 | if ((1.0 + 2 * MARGIN) * n + 1 > my nmax) |
| 518 | return false; |
| 519 | _LongSound_haveSamples (me, imin, imax); |
| 520 | return true; |
| 521 | } |
| 522 | |
| 523 | void LongSound_getWindowExtrema (LongSound me, double tmin, double tmax, const integer channel, double *minimum, double *maximum) { |
| 524 | integer imin, imax; |
| 525 | (void) Sampled_getWindowSamples (me, tmin, tmax, & imin, & imax); |
| 526 | *minimum = 1.0; |
| 527 | *maximum = -1.0; |
| 528 | try { |
| 529 | LongSound_haveWindow (me, tmin, tmax); |
| 530 | } catch (MelderError) { |
| 531 | Melder_clearError (); |
| 532 | return; |
| 533 | } |
| 534 | integer minimum_int = 32767, maximum_int = -32768; |
| 535 | for (integer i = imin; i <= imax; i ++) { |
| 536 | const integer value = my buffer [(i - my imin) * my numberOfChannels + channel]; |
| 537 | if (value < minimum_int) |
| 538 | minimum_int = value; |
| 539 | if (value > maximum_int) |
| 540 | maximum_int = value; |
| 541 | } |
| 542 | *minimum = minimum_int / 32768.0; |
| 543 | *maximum = maximum_int / 32768.0; |
| 544 | } |
| 545 | |
| 546 | static struct LongSoundPlay { |
| 547 | integer numberOfSamples, i1, i2, silenceBefore, silenceAfter; |
| 548 | double startTime, endTime, dt, t1; |
| 549 | int16 *resampledBuffer; |
| 550 | Sound_PlayCallback playCallback; |
| 551 | Thing playBoss; |
| 552 | } thePlayingLongSound; |
| 553 | |
| 554 | static bool melderPlayCallback (void *closure, const integer samplesPlayed) { |
| 555 | struct LongSoundPlay *me = (struct LongSoundPlay *) closure; |
| 556 | int phase = 2; |
| 557 | const double t = samplesPlayed <= my silenceBefore ? my startTime : |
| 558 | samplesPlayed >= my silenceBefore + my numberOfSamples ? my endTime : |
| 559 | my t1 + (my i1 - 1.5 + samplesPlayed - my silenceBefore) * my dt; |
| 560 | if (! MelderAudio_isPlaying) { |
| 561 | phase = 3; |
| 562 | Melder_free (my resampledBuffer); |
| 563 | } |
| 564 | if (my playCallback) |
| 565 | return my playCallback (my playBoss, phase, my startTime, my endTime, t); |
| 566 | return true; |
| 567 | } |
| 568 | |
| 569 | void LongSound_playPart (LongSound me, double startTime, double endTime, Sound_PlayCallback playCallback, Thing playBoss) { |
| 570 | struct LongSoundPlay *thee = (struct LongSoundPlay *) & thePlayingLongSound; |
| 571 | MelderAudio_stopPlaying (MelderAudio_IMPLICIT); |
| 572 | Melder_free (thy resampledBuffer); // just in case, and after playing has stopped |
| 573 | try { |
| 574 | const bool fits = LongSound_haveWindow (me, startTime, endTime); |
| 575 | if (! fits) |
| 576 | Melder_throw (U"Sound too long (", endTime - startTime, U" seconds)."); |
| 577 | /* |
| 578 | Assign to *thee only after stopping the playing sound. |
| 579 | */ |
| 580 | thy startTime = startTime; |
| 581 | thy endTime = endTime; |
| 582 | thy playCallback = playCallback; |
| 583 | thy playBoss = playBoss; |
| 584 | integer i1, i2; |
| 585 | const integer n = Sampled_getWindowSamples (me, startTime, endTime, & i1, & i2); |
| 586 | if (n < 2) |
| 587 | return; |
| 588 | const integer bestSampleRate = MelderAudio_getOutputBestSampleRate (my sampleRate); |
| 589 | if (bestSampleRate == my sampleRate) { |
| 590 | thy numberOfSamples = n; |
| 591 | thy dt = 1.0 / my sampleRate; |
| 592 | thy t1 = my x1; |
| 593 | thy i1 = i1; |
| 594 | thy i2 = i2; |
| 595 | thy silenceBefore = Melder_iroundTowardsZero (my sampleRate * MelderAudio_getOutputSilenceBefore ()); |
| 596 | thy silenceAfter = Melder_iroundTowardsZero (my sampleRate * MelderAudio_getOutputSilenceAfter ()); |
| 597 | if (thy playCallback) |
| 598 | thy playCallback (thy playBoss, 1, startTime, endTime, startTime); |
| 599 | if (thy silenceBefore > 0 || thy silenceAfter > 0 || 1) { |
| 600 | thy resampledBuffer = Melder_calloc (int16, (thy silenceBefore + thy numberOfSamples + thy silenceAfter) * my numberOfChannels); |
| 601 | memcpy (& thy resampledBuffer [thy silenceBefore * my numberOfChannels], |
| 602 | my buffer.asArgumentToFunctionThatExpectsZeroBasedArray() + (i1 - my imin) * my numberOfChannels, |
| 603 | thy numberOfSamples * sizeof (int16) * my numberOfChannels); |
| 604 | MelderAudio_play16 (thy resampledBuffer, my sampleRate, thy silenceBefore + thy numberOfSamples + thy silenceAfter, |
| 605 | my numberOfChannels, melderPlayCallback, thee); |
| 606 | } else { |
| 607 | MelderAudio_play16 (my buffer.asArgumentToFunctionThatExpectsZeroBasedArray() + (i1 - my imin) * my numberOfChannels, my sampleRate, |
| 608 | thy numberOfSamples, my numberOfChannels, melderPlayCallback, thee); |
| 609 | } |
| 610 | } else { |
| 611 | const integer newSampleRate = bestSampleRate; |
| 612 | const integer newN = ((double) n * newSampleRate) / my sampleRate - 1; |
| 613 | const integer silenceBefore = Melder_iroundTowardsZero (newSampleRate * MelderAudio_getOutputSilenceBefore ()); |
| 614 | const integer silenceAfter = Melder_iroundTowardsZero (newSampleRate * MelderAudio_getOutputSilenceAfter ()); |
| 615 | int16 *resampledBuffer = Melder_calloc (int16, (silenceBefore + newN + silenceAfter) * my numberOfChannels); |
| 616 | int16 *from = my buffer.asArgumentToFunctionThatExpectsZeroBasedArray() + (i1 - my imin) * my numberOfChannels; // guaranteed: from [0 .. (my imax - my imin + 1) * nchan] |
| 617 | const double t1 = my x1, dt = 1.0 / newSampleRate; |
| 618 | thy numberOfSamples = newN; |
| 619 | thy dt = dt; |
| 620 | thy t1 = t1 + i1 / my sampleRate; |
| 621 | thy i1 = 0; |
| 622 | thy i2 = newN - 1; |
| 623 | thy silenceBefore = silenceBefore; |
| 624 | thy silenceAfter = silenceAfter; |
| 625 | thy resampledBuffer = resampledBuffer; |
| 626 | if (my numberOfChannels == 1) { |
| 627 | for (integer i = 0; i < newN; i ++) { |
| 628 | const double t = t1 + i * dt; // from t1 to t1 + (newN-1) * dt |
| 629 | const double index = (t - t1) * my sampleRate; // from 0 |
| 630 | const integer flore = Melder_iroundTowardsZero (index); |
| 631 | const double fraction = index - flore; |
| 632 | resampledBuffer [i + silenceBefore] = (1.0 - fraction) * from [flore] + fraction * from [flore + 1]; |
| 633 | } |
| 634 | } else if (my numberOfChannels == 2) { |
| 635 | for (integer i = 0; i < newN; i ++) { |
| 636 | const double t = t1 + i * dt; |
| 637 | const double index = (t - t1) * my sampleRate; |
| 638 | const integer flore = Melder_iroundTowardsZero (index); |
| 639 | const double fraction = index - flore; |
| 640 | const integer ii = i + silenceBefore; |
| 641 | resampledBuffer [ii + ii] = (1.0 - fraction) * from [flore + flore] + fraction * from [flore + flore + 2]; |
| 642 | resampledBuffer [ii + ii + 1] = (1.0 - fraction) * from [flore + flore + 1] + fraction * from [flore + flore + 3]; |
| 643 | } |
| 644 | } else { |
| 645 | for (integer i = 0; i < newN; i ++) { |
| 646 | const double t = t1 + i * dt; |
| 647 | const double index = (t - t1) * my sampleRate; |
| 648 | const integer flore = Melder_iroundTowardsZero (index); |
| 649 | const double fraction = index - flore; |
| 650 | const integer ii = (i + silenceBefore) * my numberOfChannels; |
| 651 | for (integer chan = 0; chan < my numberOfChannels; chan ++) { |
| 652 | resampledBuffer [ii + chan] = |
| 653 | (1.0 - fraction) * from [flore * my numberOfChannels + chan] + |
| 654 | fraction * from [(flore + 1) * my numberOfChannels + chan]; |
| 655 | } |
| 656 | } |
| 657 | } |
| 658 | if (thy playCallback) |
| 659 | thy playCallback (thy playBoss, 1, startTime, endTime, startTime); |
| 660 | MelderAudio_play16 (resampledBuffer, newSampleRate, silenceBefore + newN + silenceAfter, my numberOfChannels, melderPlayCallback, thee); |
| 661 | } |
| 662 | //Melder_free (thy resampledBuffer); // cannot do that, because MelderAudio_play16 isn't necessarily synchronous |
| 663 | } catch (MelderError) { |
| 664 | Melder_free (thy resampledBuffer); |
| 665 | Melder_throw (me, U": not played."); |
| 666 | } |
| 667 | } |
| 668 | |
| 669 | void LongSound_concatenate (SoundAndLongSoundList me, MelderFile file, const int audioFileType, const int numberOfBitsPerSamplePoint) { |
| 670 | try { |
| 671 | integer sampleRate, n; // integer sampling frequencies only, because of possible rounding errors |
| 672 | integer numberOfChannels; |
| 673 | if (my size < 1) |
| 674 | Melder_throw (U"No Sound or LongSound objects to concatenate."); |
| 675 | /* |
| 676 | The sampling frequencies and numbers of channels must be equal for all (long)sounds. |
| 677 | */ |
| 678 | SampledXY data = my at [1]; |
| 679 | if (data -> classInfo == classSound) { |
| 680 | Sound sound = (Sound) data; |
| 681 | sampleRate = Melder_iround (1.0 / sound -> dx); |
| 682 | numberOfChannels = sound -> ny; |
| 683 | n = sound -> nx; |
| 684 | } else { |
| 685 | LongSound longSound = (LongSound) data; |
| 686 | sampleRate = Melder_iroundTowardsZero (longSound -> sampleRate); |
| 687 | numberOfChannels = longSound -> numberOfChannels; |
| 688 | n = longSound -> nx; |
| 689 | } |
| 690 | /* |
| 691 | Check whether all the sampling frequencies and channels match. |
| 692 | */ |
| 693 | for (integer i = 2; i <= my size; i ++) { |
| 694 | bool sampleRatesMatch, numbersOfChannelsMatch; |
| 695 | data = my at [i]; |
| 696 | if (data -> classInfo == classSound) { |
| 697 | Sound sound = (Sound) data; |
| 698 | sampleRatesMatch = ( Melder_iround (1.0 / sound -> dx) == sampleRate ); |
| 699 | numbersOfChannelsMatch = sound -> ny == numberOfChannels; |
| 700 | n += sound -> nx; |
| 701 | } else { |
| 702 | LongSound longSound = (LongSound) data; |
| 703 | sampleRatesMatch = ( longSound -> sampleRate == sampleRate ); |
| 704 | numbersOfChannelsMatch = longSound -> numberOfChannels == numberOfChannels; |
| 705 | n += longSound -> nx; |
| 706 | } |
| 707 | if (! sampleRatesMatch) |
| 708 | Melder_throw (U"Sampling frequencies are not equal."); |
| 709 | if (! numbersOfChannelsMatch) |
| 710 | Melder_throw (U"Cannot mix stereo and mono."); |
| 711 | } |
| 712 | /* |
| 713 | Create output file and write header. |
| 714 | */ |
| 715 | autoMelderFile mfile = MelderFile_create (file); |
| 716 | if (file -> filePointer) |
| 717 | MelderFile_writeAudioFileHeader (file, audioFileType, sampleRate, n, numberOfChannels, numberOfBitsPerSamplePoint); |
| 718 | for (integer i = 1; i <= my size; i ++) { |
| 719 | data = my at [i]; |
| 720 | if (data -> classInfo == classSound) { |
| 721 | Sound sound = (Sound) data; |
| 722 | if (file -> filePointer) { |
| 723 | MelderFile_writeFloatToAudio (file, sound -> z.get(), |
| 724 | Melder_defaultAudioFileEncoding (audioFileType, numberOfBitsPerSamplePoint), true); |
| 725 | } |
| 726 | } else { |
| 727 | LongSound longSound = (LongSound) data; |
| 728 | writePartToOpenFile (longSound, audioFileType, 1, longSound -> nx, file, 0, numberOfBitsPerSamplePoint); |
| 729 | } |
| 730 | } |
| 731 | MelderFile_writeAudioFileTrailer (file, audioFileType, sampleRate, n, numberOfChannels, numberOfBitsPerSamplePoint); |
| 732 | mfile.close (); |
| 733 | } catch (MelderError) { |
| 734 | Melder_throw (U"Sounds not concatenated and not saved to ", file, U"."); |
| 735 | } |
| 736 | } |
| 737 | |
| 738 | /* End of file LongSound.cpp */ |