-
Notifications
You must be signed in to change notification settings - Fork 1
/
AudioFile.h
1083 lines (910 loc) · 37.3 KB
/
AudioFile.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//=======================================================================
/** @file AudioFile.h
* @author Adam Stark
* @copyright Copyright (C) 2017 Adam Stark
*
* This file is part of the 'AudioFile' library
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//=======================================================================
#ifndef _AS_AudioFile_h
#define _AS_AudioFile_h
#include <iostream>
#include <vector>
#include <assert.h>
#include <string>
#include <fstream>
#include <unordered_map>
#include <iterator>
#include <algorithm>
//=============================================================
/** The different types of audio file, plus some other types to
* indicate a failure to load a file, or that one hasn't been
* loaded yet
*/
enum class AudioFileFormat
{
Error,
NotLoaded,
Wave,
Aiff
};
//=============================================================
template <class T>
class AudioFile
{
public:
//=============================================================
typedef std::vector<std::vector<T> > AudioBuffer;
//=============================================================
/** Constructor */
AudioFile();
//=============================================================
/** Loads an audio file from a given file path.
* @Returns true if the file was successfully loaded
*/
bool load (std::string filePath);
/** Saves an audio file to a given file path.
* @Returns true if the file was successfully saved
*/
bool save (std::string filePath, AudioFileFormat format = AudioFileFormat::Wave);
//=============================================================
/** @Returns the sample rate */
uint32_t getSampleRate() const;
/** @Returns the number of audio channels in the buffer */
int getNumChannels() const;
/** @Returns true if the audio file is mono */
bool isMono() const;
/** @Returns true if the audio file is stereo */
bool isStereo() const;
/** @Returns the bit depth of each sample */
int getBitDepth() const;
/** @Returns the number of samples per channel */
int getNumSamplesPerChannel() const;
/** @Returns the length in seconds of the audio file based on the number of samples and sample rate */
double getLengthInSeconds() const;
/** Prints a summary of the audio file to the console */
void printSummary() const;
//=============================================================
/** Set the audio buffer for this AudioFile by copying samples from another buffer.
* @Returns true if the buffer was copied successfully.
*/
bool setAudioBuffer (AudioBuffer& newBuffer);
/** Sets the audio buffer to a given number of channels and number of samples per channel. This will try to preserve
* the existing audio, adding zeros to any new channels or new samples in a given channel.
*/
void setAudioBufferSize (int numChannels, int numSamples);
/** Sets the number of samples per channel in the audio buffer. This will try to preserve
* the existing audio, adding zeros to new samples in a given channel if the number of samples is increased.
*/
void setNumSamplesPerChannel (int numSamples);
/** Sets the number of channels. New channels will have the correct number of samples and be initialised to zero */
void setNumChannels (int numChannels);
/** Sets the bit depth for the audio file. If you use the save() function, this bit depth rate will be used */
void setBitDepth (int numBitsPerSample);
/** Sets the sample rate for the audio file. If you use the save() function, this sample rate will be used */
void setSampleRate (uint32_t newSampleRate);
//=============================================================
/** Sets whether the library should log error messages to the console. By default this is true */
void shouldLogErrorsToConsole (bool logErrors);
//=============================================================
/** A vector of vectors holding the audio samples for the AudioFile. You can
* access the samples by channel and then by sample index, i.e:
*
* samples[channel][sampleIndex]
*/
AudioBuffer samples;
private:
//=============================================================
enum class Endianness
{
LittleEndian,
BigEndian
};
//=============================================================
AudioFileFormat determineAudioFileFormat (std::vector<uint8_t>& fileData);
bool decodeWaveFile (std::vector<uint8_t>& fileData);
bool decodeAiffFile (std::vector<uint8_t>& fileData);
//=============================================================
bool saveToWaveFile (std::string filePath);
bool saveToAiffFile (std::string filePath);
//=============================================================
void clearAudioBuffer();
//=============================================================
int32_t fourBytesToInt (std::vector<uint8_t>& source, int startIndex, Endianness endianness = Endianness::LittleEndian);
int16_t twoBytesToInt (std::vector<uint8_t>& source, int startIndex, Endianness endianness = Endianness::LittleEndian);
int getIndexOfString (std::vector<uint8_t>& source, std::string s);
//=============================================================
T sixteenBitIntToSample (int16_t sample);
int16_t sampleToSixteenBitInt (T sample);
//=============================================================
uint8_t sampleToSingleByte (T sample);
T singleByteToSample (uint8_t sample);
uint32_t getAiffSampleRate (std::vector<uint8_t>& fileData, int sampleRateStartIndex);
bool tenByteMatch (std::vector<uint8_t>& v1, int startIndex1, std::vector<uint8_t>& v2, int startIndex2);
void addSampleRateToAiffData (std::vector<uint8_t>& fileData, uint32_t sampleRate);
T clamp (T v1, T minValue, T maxValue);
//=============================================================
void addStringToFileData (std::vector<uint8_t>& fileData, std::string s);
void addInt32ToFileData (std::vector<uint8_t>& fileData, int32_t i, Endianness endianness = Endianness::LittleEndian);
void addInt16ToFileData (std::vector<uint8_t>& fileData, int16_t i, Endianness endianness = Endianness::LittleEndian);
//=============================================================
bool writeDataToFile (std::vector<uint8_t>& fileData, std::string filePath);
//=============================================================
void reportError (std::string errorMessage);
//=============================================================
AudioFileFormat audioFileFormat;
uint32_t sampleRate;
int bitDepth;
bool logErrorsToConsole {true};
};
//=============================================================
// Pre-defined 10-byte representations of common sample rates
static std::unordered_map <uint32_t, std::vector<uint8_t>> aiffSampleRateTable = {
{8000, {64, 11, 250, 0, 0, 0, 0, 0, 0, 0}},
{11025, {64, 12, 172, 68, 0, 0, 0, 0, 0, 0}},
{16000, {64, 12, 250, 0, 0, 0, 0, 0, 0, 0}},
{22050, {64, 13, 172, 68, 0, 0, 0, 0, 0, 0}},
{32000, {64, 13, 250, 0, 0, 0, 0, 0, 0, 0}},
{37800, {64, 14, 147, 168, 0, 0, 0, 0, 0, 0}},
{44056, {64, 14, 172, 24, 0, 0, 0, 0, 0, 0}},
{44100, {64, 14, 172, 68, 0, 0, 0, 0, 0, 0}},
{47250, {64, 14, 184, 146, 0, 0, 0, 0, 0, 0}},
{48000, {64, 14, 187, 128, 0, 0, 0, 0, 0, 0}},
{50000, {64, 14, 195, 80, 0, 0, 0, 0, 0, 0}},
{50400, {64, 14, 196, 224, 0, 0, 0, 0, 0, 0}},
{88200, {64, 15, 172, 68, 0, 0, 0, 0, 0, 0}},
{96000, {64, 15, 187, 128, 0, 0, 0, 0, 0, 0}},
{176400, {64, 16, 172, 68, 0, 0, 0, 0, 0, 0}},
{192000, {64, 16, 187, 128, 0, 0, 0, 0, 0, 0}},
{352800, {64, 17, 172, 68, 0, 0, 0, 0, 0, 0}},
{2822400, {64, 20, 172, 68, 0, 0, 0, 0, 0, 0}},
{5644800, {64, 21, 172, 68, 0, 0, 0, 0, 0, 0}}
};
//=============================================================
/* IMPLEMENTATION */
//=============================================================
//=============================================================
template <class T>
AudioFile<T>::AudioFile()
{
bitDepth = 16;
sampleRate = 44100;
samples.resize (1);
samples[0].resize (0);
audioFileFormat = AudioFileFormat::NotLoaded;
}
//=============================================================
template <class T>
uint32_t AudioFile<T>::getSampleRate() const
{
return sampleRate;
}
//=============================================================
template <class T>
int AudioFile<T>::getNumChannels() const
{
return (int)samples.size();
}
//=============================================================
template <class T>
bool AudioFile<T>::isMono() const
{
return getNumChannels() == 1;
}
//=============================================================
template <class T>
bool AudioFile<T>::isStereo() const
{
return getNumChannels() == 2;
}
//=============================================================
template <class T>
int AudioFile<T>::getBitDepth() const
{
return bitDepth;
}
//=============================================================
template <class T>
int AudioFile<T>::getNumSamplesPerChannel() const
{
if (samples.size() > 0)
return (int) samples[0].size();
else
return 0;
}
//=============================================================
template <class T>
double AudioFile<T>::getLengthInSeconds() const
{
return (double)getNumSamplesPerChannel() / (double)sampleRate;
}
//=============================================================
template <class T>
void AudioFile<T>::printSummary() const
{
std::cout << "|======================================|" << std::endl;
std::cout << "Num Channels: " << getNumChannels() << std::endl;
std::cout << "Num Samples Per Channel: " << getNumSamplesPerChannel() << std::endl;
std::cout << "Sample Rate: " << sampleRate << std::endl;
std::cout << "Bit Depth: " << bitDepth << std::endl;
std::cout << "Length in Seconds: " << getLengthInSeconds() << std::endl;
std::cout << "|======================================|" << std::endl;
}
//=============================================================
template <class T>
bool AudioFile<T>::setAudioBuffer (AudioBuffer& newBuffer)
{
int numChannels = (int)newBuffer.size();
if (numChannels <= 0)
{
assert (false && "The buffer your are trying to use has no channels");
return false;
}
size_t numSamples = newBuffer[0].size();
// set the number of channels
samples.resize (newBuffer.size());
for (int k = 0; k < getNumChannels(); k++)
{
assert (newBuffer[k].size() == numSamples);
samples[k].resize (numSamples);
for (size_t i = 0; i < numSamples; i++)
{
samples[k][i] = newBuffer[k][i];
}
}
return true;
}
//=============================================================
template <class T>
void AudioFile<T>::setAudioBufferSize (int numChannels, int numSamples)
{
samples.resize (numChannels);
setNumSamplesPerChannel (numSamples);
}
//=============================================================
template <class T>
void AudioFile<T>::setNumSamplesPerChannel (int numSamples)
{
int originalSize = getNumSamplesPerChannel();
for (int i = 0; i < getNumChannels();i++)
{
samples[i].resize (numSamples);
// set any new samples to zero
if (numSamples > originalSize)
std::fill (samples[i].begin() + originalSize, samples[i].end(), (T)0.);
}
}
//=============================================================
template <class T>
void AudioFile<T>::setNumChannels (int numChannels)
{
int originalNumChannels = getNumChannels();
int originalNumSamplesPerChannel = getNumSamplesPerChannel();
samples.resize (numChannels);
// make sure any new channels are set to the right size
// and filled with zeros
if (numChannels > originalNumChannels)
{
for (int i = originalNumChannels; i < numChannels; i++)
{
samples[i].resize (originalNumSamplesPerChannel);
std::fill (samples[i].begin(), samples[i].end(), (T)0.);
}
}
}
//=============================================================
template <class T>
void AudioFile<T>::setBitDepth (int numBitsPerSample)
{
bitDepth = numBitsPerSample;
}
//=============================================================
template <class T>
void AudioFile<T>::setSampleRate (uint32_t newSampleRate)
{
sampleRate = newSampleRate;
}
//=============================================================
template <class T>
void AudioFile<T>::shouldLogErrorsToConsole (bool logErrors)
{
logErrorsToConsole = logErrors;
}
//=============================================================
template <class T>
bool AudioFile<T>::load (std::string filePath)
{
std::ifstream file (filePath, std::ios::binary);
// check the file exists
if (! file.good())
{
reportError ("ERROR: File doesn't exist or otherwise can't load file\n" + filePath);
return false;
}
file.unsetf (std::ios::skipws);
std::istream_iterator<uint8_t> begin (file), end;
std::vector<uint8_t> fileData (begin, end);
// get audio file format
audioFileFormat = determineAudioFileFormat (fileData);
if (audioFileFormat == AudioFileFormat::Wave)
{
return decodeWaveFile (fileData);
}
else if (audioFileFormat == AudioFileFormat::Aiff)
{
return decodeAiffFile (fileData);
}
else
{
reportError ("Audio File Type: Error");
return false;
}
}
//=============================================================
template <class T>
bool AudioFile<T>::decodeWaveFile (std::vector<uint8_t>& fileData)
{
// -----------------------------------------------------------
// HEADER CHUNK
std::string headerChunkID (fileData.begin(), fileData.begin() + 4);
//int32_t fileSizeInBytes = fourBytesToInt (fileData, 4) + 8;
std::string format (fileData.begin() + 8, fileData.begin() + 12);
// -----------------------------------------------------------
// try and find the start points of key chunks
int indexOfDataChunk = getIndexOfString (fileData, "data");
int indexOfFormatChunk = getIndexOfString (fileData, "fmt");
// if we can't find the data or format chunks, or the IDs/formats don't seem to be as expected
// then it is unlikely we'll able to read this file, so abort
if (indexOfDataChunk == -1 || indexOfFormatChunk == -1 || headerChunkID != "RIFF" || format != "WAVE")
{
reportError ("ERROR: this doesn't seem to be a valid .WAV file");
return false;
}
// -----------------------------------------------------------
// FORMAT CHUNK
int f = indexOfFormatChunk;
std::string formatChunkID (fileData.begin() + f, fileData.begin() + f + 4);
//int32_t formatChunkSize = fourBytesToInt (fileData, f + 4);
int16_t audioFormat = twoBytesToInt (fileData, f + 8);
int16_t numChannels = twoBytesToInt (fileData, f + 10);
sampleRate = (uint32_t) fourBytesToInt (fileData, f + 12);
int32_t numBytesPerSecond = fourBytesToInt (fileData, f + 16);
int16_t numBytesPerBlock = twoBytesToInt (fileData, f + 20);
bitDepth = (int) twoBytesToInt (fileData, f + 22);
int numBytesPerSample = bitDepth / 8;
// check that the audio format is PCM
if (audioFormat != 1)
{
reportError ("ERROR: this is a compressed .WAV file and this library does not support decoding them at present");
return false;
}
// check the number of channels is mono or stereo
if (numChannels < 1 ||numChannels > 2)
{
reportError ("ERROR: this WAV file seems to be neither mono nor stereo (perhaps multi-track, or corrupted?)");
return false;
}
// check header data is consistent
if ((numBytesPerSecond != (numChannels * sampleRate * bitDepth) / 8) || (numBytesPerBlock != (numChannels * numBytesPerSample)))
{
reportError ("ERROR: the header data in this WAV file seems to be inconsistent");
return false;
}
// check bit depth is either 8, 16 or 24 bit
if (bitDepth != 8 && bitDepth != 16 && bitDepth != 24)
{
reportError ("ERROR: this file has a bit depth that is not 8, 16 or 24 bits");
return false;
}
// -----------------------------------------------------------
// DATA CHUNK
int d = indexOfDataChunk;
std::string dataChunkID (fileData.begin() + d, fileData.begin() + d + 4);
int32_t dataChunkSize = fourBytesToInt (fileData, d + 4);
int numSamples = dataChunkSize / (numChannels * bitDepth / 8);
int samplesStartIndex = indexOfDataChunk + 8;
clearAudioBuffer();
samples.resize (numChannels);
for (int i = 0; i < numSamples; i++)
{
for (int channel = 0; channel < numChannels; channel++)
{
int sampleIndex = samplesStartIndex + (numBytesPerBlock * i) + channel * numBytesPerSample;
if (bitDepth == 8)
{
T sample = singleByteToSample (fileData[sampleIndex]);
samples[channel].push_back (sample);
}
else if (bitDepth == 16)
{
int16_t sampleAsInt = twoBytesToInt (fileData, sampleIndex);
T sample = sixteenBitIntToSample (sampleAsInt);
samples[channel].push_back (sample);
}
else if (bitDepth == 24)
{
int32_t sampleAsInt = 0;
sampleAsInt = (fileData[sampleIndex + 2] << 16) | (fileData[sampleIndex + 1] << 8) | fileData[sampleIndex];
if (sampleAsInt & 0x800000) // if the 24th bit is set, this is a negative number in 24-bit world
sampleAsInt = sampleAsInt | ~0xFFFFFF; // so make sure sign is extended to the 32 bit float
T sample = (T)sampleAsInt / (T)8388608.;
samples[channel].push_back (sample);
}
else
{
assert (false);
}
}
}
return true;
}
//=============================================================
template <class T>
bool AudioFile<T>::decodeAiffFile (std::vector<uint8_t>& fileData)
{
// -----------------------------------------------------------
// HEADER CHUNK
std::string headerChunkID (fileData.begin(), fileData.begin() + 4);
//int32_t fileSizeInBytes = fourBytesToInt (fileData, 4, Endianness::BigEndian) + 8;
std::string format (fileData.begin() + 8, fileData.begin() + 12);
// -----------------------------------------------------------
// try and find the start points of key chunks
int indexOfCommChunk = getIndexOfString (fileData, "COMM");
int indexOfSoundDataChunk = getIndexOfString (fileData, "SSND");
// if we can't find the data or format chunks, or the IDs/formats don't seem to be as expected
// then it is unlikely we'll able to read this file, so abort
if (indexOfSoundDataChunk == -1 || indexOfCommChunk == -1 || headerChunkID != "FORM" || format != "AIFF")
{
reportError ("ERROR: this doesn't seem to be a valid AIFF file");
return false;
}
// -----------------------------------------------------------
// COMM CHUNK
int p = indexOfCommChunk;
std::string commChunkID (fileData.begin() + p, fileData.begin() + p + 4);
//int32_t commChunkSize = fourBytesToInt (fileData, p + 4, Endianness::BigEndian);
int16_t numChannels = twoBytesToInt (fileData, p + 8, Endianness::BigEndian);
int32_t numSamplesPerChannel = fourBytesToInt (fileData, p + 10, Endianness::BigEndian);
bitDepth = (int) twoBytesToInt (fileData, p + 14, Endianness::BigEndian);
sampleRate = getAiffSampleRate (fileData, p + 16);
// check the sample rate was properly decoded
if (sampleRate == 0)
{
reportError ("ERROR: this AIFF file has an unsupported sample rate");
return false;
}
// check the number of channels is mono or stereo
if (numChannels < 1 ||numChannels > 2)
{
reportError ("ERROR: this AIFF file seems to be neither mono nor stereo (perhaps multi-track, or corrupted?)");
return false;
}
// check bit depth is either 8, 16 or 24 bit
if (bitDepth != 8 && bitDepth != 16 && bitDepth != 24)
{
reportError ("ERROR: this file has a bit depth that is not 8, 16 or 24 bits");
return false;
}
// -----------------------------------------------------------
// SSND CHUNK
int s = indexOfSoundDataChunk;
std::string soundDataChunkID (fileData.begin() + s, fileData.begin() + s + 4);
int32_t soundDataChunkSize = fourBytesToInt (fileData, s + 4, Endianness::BigEndian);
int32_t offset = fourBytesToInt (fileData, s + 8, Endianness::BigEndian);
//int32_t blockSize = fourBytesToInt (fileData, s + 12, Endianness::BigEndian);
int numBytesPerSample = bitDepth / 8;
int numBytesPerFrame = numBytesPerSample * numChannels;
int totalNumAudioSampleBytes = numSamplesPerChannel * numBytesPerFrame;
int samplesStartIndex = s + 16 + (int)offset;
// sanity check the data
if ((soundDataChunkSize - 8) != totalNumAudioSampleBytes || totalNumAudioSampleBytes > static_cast<long>(fileData.size() - samplesStartIndex))
{
reportError ("ERROR: the metadatafor this file doesn't seem right");
return false;
}
clearAudioBuffer();
samples.resize (numChannels);
for (int i = 0; i < numSamplesPerChannel; i++)
{
for (int channel = 0; channel < numChannels; channel++)
{
int sampleIndex = samplesStartIndex + (numBytesPerFrame * i) + channel * numBytesPerSample;
if (bitDepth == 8)
{
int8_t sampleAsSigned8Bit = (int8_t)fileData[sampleIndex];
T sample = (T)sampleAsSigned8Bit / (T)128.;
samples[channel].push_back (sample);
}
else if (bitDepth == 16)
{
int16_t sampleAsInt = twoBytesToInt (fileData, sampleIndex, Endianness::BigEndian);
T sample = sixteenBitIntToSample (sampleAsInt);
samples[channel].push_back (sample);
}
else if (bitDepth == 24)
{
int32_t sampleAsInt = 0;
sampleAsInt = (fileData[sampleIndex] << 16) | (fileData[sampleIndex + 1] << 8) | fileData[sampleIndex + 2];
if (sampleAsInt & 0x800000) // if the 24th bit is set, this is a negative number in 24-bit world
sampleAsInt = sampleAsInt | ~0xFFFFFF; // so make sure sign is extended to the 32 bit float
T sample = (T)sampleAsInt / (T)8388608.;
samples[channel].push_back (sample);
}
else
{
assert (false);
}
}
}
return true;
}
//=============================================================
template <class T>
uint32_t AudioFile<T>::getAiffSampleRate (std::vector<uint8_t>& fileData, int sampleRateStartIndex)
{
for (auto it : aiffSampleRateTable)
{
if (tenByteMatch (fileData, sampleRateStartIndex, it.second, 0))
return it.first;
}
return 0;
}
//=============================================================
template <class T>
bool AudioFile<T>::tenByteMatch (std::vector<uint8_t>& v1, int startIndex1, std::vector<uint8_t>& v2, int startIndex2)
{
for (int i = 0; i < 10; i++)
{
if (v1[startIndex1 + i] != v2[startIndex2 + i])
return false;
}
return true;
}
//=============================================================
template <class T>
void AudioFile<T>::addSampleRateToAiffData (std::vector<uint8_t>& fileData, uint32_t sampleRate)
{
if (aiffSampleRateTable.count (sampleRate) > 0)
{
for (int i = 0; i < 10; i++)
fileData.push_back (aiffSampleRateTable[sampleRate][i]);
}
}
//=============================================================
template <class T>
bool AudioFile<T>::save (std::string filePath, AudioFileFormat format)
{
if (format == AudioFileFormat::Wave)
{
return saveToWaveFile (filePath);
}
else if (format == AudioFileFormat::Aiff)
{
return saveToAiffFile (filePath);
}
return false;
}
//=============================================================
template <class T>
bool AudioFile<T>::saveToWaveFile (std::string filePath)
{
std::vector<uint8_t> fileData;
int32_t dataChunkSize = getNumSamplesPerChannel() * (getNumChannels() * bitDepth / 8);
// -----------------------------------------------------------
// HEADER CHUNK
addStringToFileData (fileData, "RIFF");
// The file size in bytes is the header chunk size (4, not counting RIFF and WAVE) + the format
// chunk size (24) + the metadata part of the data chunk plus the actual data chunk size
int32_t fileSizeInBytes = 4 + 24 + 8 + dataChunkSize;
addInt32ToFileData (fileData, fileSizeInBytes);
addStringToFileData (fileData, "WAVE");
// -----------------------------------------------------------
// FORMAT CHUNK
addStringToFileData (fileData, "fmt ");
addInt32ToFileData (fileData, 16); // format chunk size (16 for PCM)
addInt16ToFileData (fileData, 1); // audio format = 1
addInt16ToFileData (fileData, (int16_t)getNumChannels()); // num channels
addInt32ToFileData (fileData, (int32_t)sampleRate); // sample rate
int32_t numBytesPerSecond = (int32_t) ((getNumChannels() * sampleRate * bitDepth) / 8);
addInt32ToFileData (fileData, numBytesPerSecond);
int16_t numBytesPerBlock = getNumChannels() * (bitDepth / 8);
addInt16ToFileData (fileData, numBytesPerBlock);
addInt16ToFileData (fileData, (int16_t)bitDepth);
// -----------------------------------------------------------
// DATA CHUNK
addStringToFileData (fileData, "data");
addInt32ToFileData (fileData, dataChunkSize);
for (int i = 0; i < getNumSamplesPerChannel(); i++)
{
for (int channel = 0; channel < getNumChannels(); channel++)
{
if (bitDepth == 8)
{
uint8_t byte = sampleToSingleByte (samples[channel][i]);
fileData.push_back (byte);
}
else if (bitDepth == 16)
{
int16_t sampleAsInt = sampleToSixteenBitInt (samples[channel][i]);
addInt16ToFileData (fileData, sampleAsInt);
}
else if (bitDepth == 24)
{
int32_t sampleAsIntAgain = (int32_t) (samples[channel][i] * (T)8388608.);
uint8_t bytes[3];
bytes[2] = (uint8_t) (sampleAsIntAgain >> 16) & 0xFF;
bytes[1] = (uint8_t) (sampleAsIntAgain >> 8) & 0xFF;
bytes[0] = (uint8_t) sampleAsIntAgain & 0xFF;
fileData.push_back (bytes[0]);
fileData.push_back (bytes[1]);
fileData.push_back (bytes[2]);
}
else
{
assert (false && "Trying to write a file with unsupported bit depth");
return false;
}
}
}
// check that the various sizes we put in the metadata are correct
if (fileSizeInBytes != static_cast<int32_t> (fileData.size() - 8) || dataChunkSize != (getNumSamplesPerChannel() * getNumChannels() * (bitDepth / 8)))
{
reportError ("ERROR: couldn't save file to " + filePath);
return false;
}
// try to write the file
return writeDataToFile (fileData, filePath);
}
//=============================================================
template <class T>
bool AudioFile<T>::saveToAiffFile (std::string filePath)
{
std::vector<uint8_t> fileData;
int32_t numBytesPerSample = bitDepth / 8;
int32_t numBytesPerFrame = numBytesPerSample * getNumChannels();
int32_t totalNumAudioSampleBytes = getNumSamplesPerChannel() * numBytesPerFrame;
int32_t soundDataChunkSize = totalNumAudioSampleBytes + 8;
// -----------------------------------------------------------
// HEADER CHUNK
addStringToFileData (fileData, "FORM");
// The file size in bytes is the header chunk size (4, not counting FORM and AIFF) + the COMM
// chunk size (26) + the metadata part of the SSND chunk plus the actual data chunk size
int32_t fileSizeInBytes = 4 + 26 + 16 + totalNumAudioSampleBytes;
addInt32ToFileData (fileData, fileSizeInBytes, Endianness::BigEndian);
addStringToFileData (fileData, "AIFF");
// -----------------------------------------------------------
// COMM CHUNK
addStringToFileData (fileData, "COMM");
addInt32ToFileData (fileData, 18, Endianness::BigEndian); // commChunkSize
addInt16ToFileData (fileData, getNumChannels(), Endianness::BigEndian); // num channels
addInt32ToFileData (fileData, getNumSamplesPerChannel(), Endianness::BigEndian); // num samples per channel
addInt16ToFileData (fileData, bitDepth, Endianness::BigEndian); // bit depth
addSampleRateToAiffData (fileData, sampleRate);
// -----------------------------------------------------------
// SSND CHUNK
addStringToFileData (fileData, "SSND");
addInt32ToFileData (fileData, soundDataChunkSize, Endianness::BigEndian);
addInt32ToFileData (fileData, 0, Endianness::BigEndian); // offset
addInt32ToFileData (fileData, 0, Endianness::BigEndian); // block size
for (int i = 0; i < getNumSamplesPerChannel(); i++)
{
for (int channel = 0; channel < getNumChannels(); channel++)
{
if (bitDepth == 8)
{
uint8_t byte = sampleToSingleByte (samples[channel][i]);
fileData.push_back (byte);
}
else if (bitDepth == 16)
{
int16_t sampleAsInt = sampleToSixteenBitInt (samples[channel][i]);
addInt16ToFileData (fileData, sampleAsInt, Endianness::BigEndian);
}
else if (bitDepth == 24)
{
int32_t sampleAsIntAgain = (int32_t) (samples[channel][i] * (T)8388608.);
uint8_t bytes[3];
bytes[0] = (uint8_t) (sampleAsIntAgain >> 16) & 0xFF;
bytes[1] = (uint8_t) (sampleAsIntAgain >> 8) & 0xFF;
bytes[2] = (uint8_t) sampleAsIntAgain & 0xFF;
fileData.push_back (bytes[0]);
fileData.push_back (bytes[1]);
fileData.push_back (bytes[2]);
}
else
{
assert (false && "Trying to write a file with unsupported bit depth");
return false;
}
}
}
// check that the various sizes we put in the metadata are correct
if (fileSizeInBytes != static_cast<int32_t> (fileData.size() - 8) || soundDataChunkSize != getNumSamplesPerChannel() * numBytesPerFrame + 8)
{
reportError ("ERROR: couldn't save file to " + filePath);
return false;
}
// try to write the file
return writeDataToFile (fileData, filePath);
}
//=============================================================
template <class T>
bool AudioFile<T>::writeDataToFile (std::vector<uint8_t>& fileData, std::string filePath)
{
std::ofstream outputFile (filePath, std::ios::binary);
if (outputFile.is_open())
{
for (size_t i = 0; i < fileData.size(); i++)
{
char value = (char) fileData[i];
outputFile.write (&value, sizeof (char));
}
outputFile.close();
return true;
}
return false;
}
//=============================================================
template <class T>
void AudioFile<T>::addStringToFileData (std::vector<uint8_t>& fileData, std::string s)
{
for (size_t i = 0; i < s.length();i++)
fileData.push_back ((uint8_t) s[i]);
}
//=============================================================
template <class T>
void AudioFile<T>::addInt32ToFileData (std::vector<uint8_t>& fileData, int32_t i, Endianness endianness)
{
uint8_t bytes[4];
if (endianness == Endianness::LittleEndian)
{
bytes[3] = (i >> 24) & 0xFF;
bytes[2] = (i >> 16) & 0xFF;
bytes[1] = (i >> 8) & 0xFF;
bytes[0] = i & 0xFF;
}
else
{
bytes[0] = (i >> 24) & 0xFF;
bytes[1] = (i >> 16) & 0xFF;
bytes[2] = (i >> 8) & 0xFF;
bytes[3] = i & 0xFF;
}
for (int i = 0; i < 4; i++)
fileData.push_back (bytes[i]);
}
//=============================================================
template <class T>
void AudioFile<T>::addInt16ToFileData (std::vector<uint8_t>& fileData, int16_t i, Endianness endianness)
{
uint8_t bytes[2];
if (endianness == Endianness::LittleEndian)
{
bytes[1] = (i >> 8) & 0xFF;
bytes[0] = i & 0xFF;
}
else
{
bytes[0] = (i >> 8) & 0xFF;
bytes[1] = i & 0xFF;
}
fileData.push_back (bytes[0]);
fileData.push_back (bytes[1]);
}
//=============================================================
template <class T>
void AudioFile<T>::clearAudioBuffer()
{
for (size_t i = 0; i < samples.size();i++)
{
samples[i].clear();
}
samples.clear();
}
//=============================================================
template <class T>
AudioFileFormat AudioFile<T>::determineAudioFileFormat (std::vector<uint8_t>& fileData)
{
std::string header (fileData.begin(), fileData.begin() + 4);
if (header == "RIFF")
return AudioFileFormat::Wave;
else if (header == "FORM")
return AudioFileFormat::Aiff;
else
return AudioFileFormat::Error;
}
//=============================================================
template <class T>
int32_t AudioFile<T>::fourBytesToInt (std::vector<uint8_t>& source, int startIndex, Endianness endianness)
{
int32_t result;
if (endianness == Endianness::LittleEndian)
result = (source[startIndex + 3] << 24) | (source[startIndex + 2] << 16) | (source[startIndex + 1] << 8) | source[startIndex];
else
result = (source[startIndex] << 24) | (source[startIndex + 1] << 16) | (source[startIndex + 2] << 8) | source[startIndex + 3];
return result;
}
//=============================================================