-
Notifications
You must be signed in to change notification settings - Fork 26
/
ReSampler.cpp
1626 lines (1364 loc) · 54.2 KB
/
ReSampler.cpp
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
/*
* Copyright (C) 2016 - 2024 Judd Niemann - All Rights Reserved.
* You may use, distribute and modify this code under the
* terms of the GNU Lesser General Public License, version 2.1
*
* You should have received a copy of GNU Lesser General Public License v2.1
* with this file. If not, please refer to: https://github.com/jniemann66/ReSampler
*/
// ReSampler.cpp : Audio Sample Rate Converter by Judd Niemann.
#include "ReSampler.h"
#include "csv.h"
#include "ctpl/ctpl_stl.h"
#include "raiitimer.h"
#include "fraction.h"
#include "srconvert.h"
#include "ditherer.h"
#include "iqdemodulator.h"
#include "mpxdecode.h"
#include "stereoimager.h"
#include "fadeeffect.h"
#include "effectchain.h"
#include "dsf.h"
#include "dff.h"
#include <cstdio>
#include <string>
#include <iostream>
#include <vector>
#include <iomanip>
#include <regex>
////////////////////////////////////////////////////////////////////////////////////////
// This program uses the following libraries:
// 1:
// libsndfile
// available at http://www.mega-nerd.com/libsndfile/
//
// (copy of entire package included in $(ProjectDir)\libsbdfile)
//
// 2:
// fftw
// http://www.fftw.org/
//
// //
////////////////////////////////////////////////////////////////////////////////////////
namespace ReSampler {
// parseGlobalOptions() - result indicates whether to terminate.
bool parseGlobalOptions(int argc, char * argv[]) {
// help switch:
if (getCmdlineParam(argv, argv + argc, "--help") || getCmdlineParam(argv, argv + argc, "-h")) {
std::cout << strUsage << std::endl;
std::cout << "Additional options:\n\n" << strExtraOptions << std::endl;
return true;
}
// version switch:
if (getCmdlineParam(argv, argv + argc, "--version")) {
std::cout << strVersion << std::endl;
return true;
}
// compiler switch:
if (getCmdlineParam(argv, argv + argc, "--compiler")) {
showCompiler();
return true;
}
// sndfile-version switch:
if (getCmdlineParam(argv, argv + argc, "--sndfile-version")) {
char s[128];
sf_command(nullptr, SFC_GET_LIB_VERSION, s, sizeof(s));
std::cout << s << std::endl;
return true;
}
// listsubformats
if (getCmdlineParam(argv, argv + argc, "--listsubformats")) {
std::string filetype;
getCmdlineParam(argv, argv + argc, "--listsubformats", filetype);
listSubFormats(filetype);
return true;
}
// showDitherProfiles
if (getCmdlineParam(argv, argv + argc, "--showDitherProfiles")) {
showDitherProfiles();
return true;
}
// generate
if (getCmdlineParam(argv, argv + argc, "--generate")) {
std::string filename;
getCmdlineParam(argv, argv + argc, "--generate", filename);
generateExpSweep(filename);
return true;
}
return false;
}
// determineBestBitFormat() : determines the most appropriate bit format for the output file, through the following process:
// 1. Try to use infile's format and if that isn't valid for outfile, then:
// 2. use the default subformat for outfile.
// store best bit format as a string in BitFormat
bool determineBestBitFormat(std::string& bitFormat, const ConversionInfo& ci)
{
// get infile's extension from filename:
std::string inFileExt;
if (ci.inputFilename.find_last_of('.') != std::string::npos) {
inFileExt = ci.inputFilename.substr(ci.inputFilename.find_last_of('.') + 1);
}
bool dsfInput = false;
bool dffInput = false;
int inFileFormat = 0;
if (inFileExt == "dsf") {
dsfInput = true;
} else if (inFileExt == "dff") {
dffInput = true;
}
else { // libsndfile-openable file
if (ci.bRawInput) {
inFileFormat = SF_FORMAT_RAW | subFormats.at(ci.rawInputBitFormat);
} else {
// Inspect input file for format:
SndfileHandle infile(ci.inputFilename, SFM_READ);
inFileFormat = infile.format();
if (int e = infile.error())
{
std::cout << "Couldn't Open Input File (" << sf_error_number(e) << ")" << std::endl;
return false;
}
}
// get BitFormat of inFile as a string:
for (auto& subformat : subFormats) {
if (subformat.second == (inFileFormat & SF_FORMAT_SUBMASK)) {
bitFormat = subformat.first;
break;
}
}
// retrieve infile's TRUE extension (from the file contents), and if retrieval is successful, override extension derived from filename:
SF_FORMAT_INFO infileFormatInfo;
infileFormatInfo.format = inFileFormat & SF_FORMAT_TYPEMASK;
if (sf_command(nullptr, SFC_GET_FORMAT_INFO, &infileFormatInfo, sizeof(SF_FORMAT_INFO)) == 0) {
inFileExt = std::string(infileFormatInfo.extension);
}
}
// get outfile's extension:
std::string outFileExt;
if (ci.outputFilename.find_last_of('.') != std::string::npos)
outFileExt = ci.outputFilename.substr(ci.outputFilename.find_last_of('.') + 1);
// when the input file is dsf/dff, use default output subformat:
if (dsfInput || dffInput) { // choose default output subformat for chosen output file format
bitFormat = defaultSubFormats.find(outFileExt)->second;
std::cout << "defaulting to " << bitFormat << std::endl;
return true;
}
if(SF_FORMAT_INFO formatinfo; getMajorFormatFromFileExt(&formatinfo, outFileExt)) {
SF_INFO sfinfo;
memset(&sfinfo, 0, sizeof(sfinfo));
sfinfo.channels = 1;
sfinfo.format = formatinfo.format;
if (!sf_format_check(&sfinfo)) {
// infile's subformat is not valid for outfile's format; use outfile's default subformat
std::cout << "Output file format " << outFileExt << " and subformat " << bitFormat << " combination not valid ... ";
bitFormat.clear();
bitFormat = defaultSubFormats.find(outFileExt)->second;
std::cout << "defaulting to " << bitFormat << std::endl;
}
}
return true;
}
bool getMajorFormatFromFileExt(SF_FORMAT_INFO *info, const std::string& ext)
{
bool found = false;
if(info != nullptr) {
static const std::map<std::string, std::string> fileExtMap
{
#ifdef HAVE_MPEG
foo;
#endif
#ifdef ENABLE_MPEG_CAPABILITY
{"mp3", "m1a"},
{"mp2", "m1a"}
#endif
};
const auto it = fileExtMap.find(ext);
const std::string _ext = (it == fileExtMap.end() ? ext : it->second);
int major_count;
sf_command(nullptr, SFC_GET_FORMAT_MAJOR_COUNT, &major_count, sizeof(int));
// Loop through all major formats to find match for outFileExt:
for (int m = 0; m < major_count; ++m) {
memset(info, 0, sizeof(SF_FORMAT_INFO));
info->format = m;
sf_command(nullptr, SFC_GET_FORMAT_MAJOR, info, sizeof(SF_FORMAT_INFO));
if (stricmp(info->extension, _ext.c_str()) == 0) {
found = true;
break;
}
}
}
return found;
}
// determineOutputFormat() : returns an integer representing a libsndfile output format:
int determineOutputFormat(const std::string& outFileExt, const std::string& bitFormat)
{
SF_FORMAT_INFO info;
int format = 0;
if (getMajorFormatFromFileExt(&info, outFileExt)) {
// Check if subformat is recognized:
auto sf = subFormats.find(bitFormat);
if (sf != subFormats.end()) {
format = info.format | sf->second;
} else {
std::cout << "Warning: bit format " << bitFormat << " not recognised !" << std::endl;
}
}
// Special cases:
if (bitFormat == "8") {
// user specified 8-bit. Determine whether it must be unsigned or signed, based on major type:
// These formats always use unsigned 8-bit when they use 8-bit: mat rf64 voc w64 wav
if ((outFileExt == "mat") || (outFileExt == "rf64") || (outFileExt == "voc") || (outFileExt == "w64") || (outFileExt == "wav"))
format = info.format | SF_FORMAT_PCM_U8;
else
format = info.format | SF_FORMAT_PCM_S8;
}
return format;
}
// listSubFormats() - lists all valid subformats for a given file extension (without "." or "*."):
void listSubFormats(const std::string& f)
{
if (SF_FORMAT_INFO info; getMajorFormatFromFileExt(&info, f)) {
SF_INFO sfinfo;
memset(&sfinfo, 0, sizeof(sfinfo));
sfinfo.channels = 1;
// loop through all subformats and find which ones are valid for file type:
for (auto& subformat : subFormats) {
sfinfo.format = (info.format & SF_FORMAT_TYPEMASK) | subformat.second;
if (sf_format_check(&sfinfo)) {
std::cout << subformat.first << std::endl;
}
}
} else {
std::cout << "File extension " << f << " unknown" << std::endl;
}
}
// explicit instantiations - generate all required flavors of convert()
bool convert_DffFile_Float(ConversionInfo & ci) {
return convert<DffFile, float>(ci);
}
bool convert_DffFile_Double(ConversionInfo & ci) {
return convert<DffFile, double>(ci);
}
bool convert_DsfFile_Float(ConversionInfo & ci) {
return convert<DsfFile, float>(ci);
}
bool convert_DsfFile_Double(ConversionInfo & ci) {
return convert<DsfFile, double>(ci);
}
bool convert_SndfileHandle_Float(ConversionInfo & ci) {
return convert<SndfileHandle, float>(ci);
}
bool convert_SndfileHandle_Double(ConversionInfo & ci) {
return convert<SndfileHandle, double>(ci);
}
bool convert_IQFile_Float(ConversionInfo& ci) {
return convert<IQFile, float>(ci);
}
bool convert_IQFile_Double(ConversionInfo& ci) {
return convert<IQFile, double>(ci);
}
// convert()
/* Note: type 'FileReader' MUST implement the following methods:
constructor(const std::string& fileName)
constructor(const std::string& fileName, int infileMode, int infileFormat, int infileChannels, int infileRate)
bool error() // or int error()
unsigned int channels()
unsigned int samplerate()
uint64_t frames()
int format()
read(inbuffer, count)
seek(position, whence)
*/
template<typename FileReader, typename FloatType>
bool convert(ConversionInfo& ci)
{
const bool multiThreaded = ci.bMultiThreaded;
// pointer for temp file;
SndfileHandle* tmpSndfileHandle = nullptr;
// filename for temp file;
std::string tmpFilename;
// Prepare input file opening parameters
int infileMode;
int infileFormat = 0; // leave these zero for normal operation. (Only set for RAW input)
int infileChannels = 0;
int infileRate = 0;
if(ci.dsfInput) {
infileMode = Dsf_read;
} else if(ci.dffInput) {
infileMode = Dff_read;
} else {
infileMode = SFM_READ;
if(ci.bRawInput) {
auto it = subFormats.find(ci.rawInputBitFormat);
int infileSubFormat = (it != subFormats.end()) ? it->second : SF_FORMAT_PCM_16;
infileFormat = SF_FORMAT_RAW | infileSubFormat;
infileChannels = ci.rawInputChannels;
infileRate = ci.rawInputSampleRate;
std::cout << "raw input" << std::endl;
}
if(ci.bDemodulateIQ) {
infileFormat |= ((ci.IQModulationType | ci.IQDeEmphasisType) << 8);
ModulationType modulationType = ci.IQModulationType;
if (modulationType == WFM_NO_LOWPASS) {
modulationType = WFM;
}
// stuff the modulation type into the second-least-significant byte
auto k = std::find_if(std::begin(modulationTypeMap), std::end(modulationTypeMap), [modulationType](const std::pair<std::string, ModulationType> pair){
return pair.second == modulationType;
});
std::string s;
if(k != std::end(modulationTypeMap)) {
s = k->first;
}
std::cout << "IQ demodulation " << s << " ";
if(ci.IQDeEmphasisType != NoDeEmphasis) {
auto k1 = std::find_if(std::begin(deEmphasisTypeMap), std::end(deEmphasisTypeMap), [&](const std::pair<std::string, DeEmphasisType> pair){
return pair.second == ci.IQDeEmphasisType;
});
if(k1 != std::end(deEmphasisTypeMap)) {
std::cout << k1->first << "us de-emphasis";
}
}
std::cout << std::endl;
}
}
// Open input file
FileReader infile(ci.inputFilename, infileMode, infileFormat, infileChannels, infileRate);
const int e = infile.error();
if (e != SF_ERR_NO_ERROR) {
if(e == ERROR_IQFILE_WFM_SAMPLERATE_TOO_LOW) {
std::cout << "Sample Rate not high enough for WFM" << std::endl;
} else if (e == ERROR_IQFILE_TWO_CHANNELS_EXPECTED) {
std::cout << "2 channels expected for an I/Q input file !" << std::endl;
} else {
std::cout << "Error: Couldn't Open Input File (" << sf_error_number(e) << ")" << std::endl;
}
return false;
}
// read input file metadata:
MetaData m;
getMetaData(m, infile);
// read input file properties:
const int nChannels = static_cast<int>(infile.channels());
ci.inputSampleRate = infile.samplerate();
const sf_count_t inputFrames = infile.frames();
const sf_count_t inputSampleCount = inputFrames * nChannels;
const double inputDuration = 1000.0 * inputFrames / ci.inputSampleRate; // ms
// determine conversion ratio:
Fraction fraction = getFractionFromSamplerates(ci.inputSampleRate, ci.outputSampleRate);
// set buffer sizes:
const auto inputChannelBufferSize = static_cast<size_t>(BUFFERSIZE);
const auto inputBlockSize = static_cast<size_t>(BUFFERSIZE * nChannels);
const auto outputChannelBufferSize = static_cast<size_t>(1 + std::ceil(BUFFERSIZE * static_cast<double>(fraction.numerator) / static_cast<double>(fraction.denominator)));
const auto outputBlockSize = static_cast<size_t>(nChannels * (1 + outputChannelBufferSize));
// allocate buffers:
std::vector<FloatType> inputBlock(inputBlockSize, 0); // input buffer for storing interleaved samples from input file
std::vector<FloatType> outputBlock(outputBlockSize, 0); // output buffer for storing interleaved samples to be saved to output file
std::vector<std::vector<FloatType>> inputChannelBuffers; // input buffer for each channel to store deinterleaved samples
std::vector<std::vector<FloatType>> outputChannelBuffers; // output buffer for each channel to store converted deinterleaved samples
for (int n = 0; n < nChannels; n++) {
inputChannelBuffers.emplace_back(std::vector<FloatType>(inputChannelBufferSize, 0));
outputChannelBuffers.emplace_back(std::vector<FloatType>(outputChannelBufferSize, 0));
}
const int inputFileFormat = infile.format();
if (inputFileFormat != DFF_FORMAT && inputFileFormat != DSF_FORMAT) { // this block only relevant to libsndfile ...
// detect if input format is a floating-point format:
bool bFloat = false;
bool bDouble = false;
switch (inputFileFormat & SF_FORMAT_SUBMASK) {
case SF_FORMAT_FLOAT:
bFloat = true;
break;
case SF_FORMAT_DOUBLE:
bDouble = true;
break;
}
for (auto& subformat : subFormats) { // scan subformats for a match:
if (subformat.second == (inputFileFormat & SF_FORMAT_SUBMASK)) {
std::cout << "input bit format: " << subformat.first;
break;
}
}
if (bFloat) {
std::cout << " (float)";
}
if (bDouble) {
std::cout << " (double precision)";
}
std::cout << std::endl;
}
std::cout << "source file channels: " << nChannels << std::endl;
std::cout << "input sample rate: " << ci.inputSampleRate << "\noutput sample rate: " << ci.outputSampleRate << std::endl;
FloatType peakInputSample;
sf_count_t peakInputPosition = 0LL;
sf_count_t samplesRead = 0LL;
sf_count_t totalSamplesRead = 0LL;
if (ci.bEnablePeakDetection) {
peakInputSample = 0.0;
std::cout << "Scanning input file for peaks ...";
do {
samplesRead = infile.read(inputBlock.data(), inputBlockSize);
for (unsigned int s = 0; s < samplesRead; ++s) { // read all samples, without caring which channel they belong to
if (std::abs(inputBlock[s]) > peakInputSample) {
peakInputSample = std::abs(inputBlock[s]);
peakInputPosition = totalSamplesRead + s;
}
}
totalSamplesRead += samplesRead;
} while (samplesRead > 0);
std::cout << "Done\n";
std::cout << "Peak input sample: " << std::fixed << peakInputSample << " (" << 20 * log10(peakInputSample) << " dBFS) at ";
printSamplePosAsTime(peakInputPosition, ci.inputSampleRate);
std::cout << std::endl;
infile.seek(0, SEEK_SET); // rewind back to start of file
}
else { // no peak detection
peakInputSample = ci.bNormalize ?
0.5 /* ... a guess, since we haven't actually measured the peak (in the case of DSD, it is a good guess.) */ :
1.0;
}
if (ci.bNormalize) { // echo Normalization settings to user
const auto prec = std::cout.precision();
std::cout << "Normalizing to " << std::setprecision(2) << ci.limit << std::endl;
std::cout.precision(prec);
}
// echo filter settings to user:
double targetNyquist = std::min(ci.inputSampleRate, ci.outputSampleRate) / 2.0;
double ft = (ci.lpfCutoff / 100.0) * targetNyquist;
const auto prec = std::cout.precision();
std::cout << "LPF transition frequency: " << std::fixed << std::setprecision(2) << ft << " Hz (" << 100 * ft / targetNyquist << " %)" << std::endl;
std::cout.precision(prec);
if (ci.bMinPhase) {
std::cout << "Using Minimum-Phase LPF" << std::endl;
}
// echo conversion ratio to user:
const FloatType resamplingFactor = static_cast<FloatType>(ci.outputSampleRate) / ci.inputSampleRate;
std::cout << "Conversion ratio: " << resamplingFactor
<< " (" << fraction.numerator << ":" << fraction.denominator << ")" << std::endl;
// if the outputFormat is zero, it means "No change to file format"
// if output file format has changed, use outputFormat. Otherwise, use same format as infile:
int outputFileFormat = ci.outputFormat ? ci.outputFormat : inputFileFormat;
// if the minor (sub) format of outputFileFormat is not set, attempt to use minor format of input file (as a last resort)
if ((outputFileFormat & SF_FORMAT_SUBMASK) == 0) {
outputFileFormat |= (inputFileFormat & SF_FORMAT_SUBMASK); // may not be valid subformat for new file format.
}
// for wav files, determine whether to switch to rf64 mode:
if ((outputFileFormat & SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV || (outputFileFormat & SF_FORMAT_TYPEMASK) == SF_FORMAT_WAVEX) {
if (ci.bRf64 ||
checkWarnOutputSize(inputSampleCount, getSfBytesPerSample(outputFileFormat), fraction.numerator, fraction.denominator)) {
std::cout << "Switching to rf64 format !" << std::endl;
outputFileFormat &= ~SF_FORMAT_TYPEMASK; // clear file type
outputFileFormat |= SF_FORMAT_RF64;
}
}
// note: libsndfile has an rf64 auto-downgrade mode:
// http://www.mega-nerd.com/libsndfile/command.html#SFC_RF64_AUTO_DOWNGRADE
// However, rf64 auto-downgrade is more appropriate for recording applications
// (where the final file size cannot be known until the recording has stopped)
// In the case of sample-rate conversions, the output file size (and therefore the decision to promote to rf64)
// can be determined at the outset.
// Determine the value of outputSignalBits, based on outputFileFormat.
// outputSignalsBits is used to set the level of the LSB for dithering
int outputSignalBits;
switch (outputFileFormat & SF_FORMAT_SUBMASK) {
case SF_FORMAT_PCM_24:
outputSignalBits = 24;
break;
case SF_FORMAT_PCM_S8:
case SF_FORMAT_PCM_U8:
outputSignalBits = 8;
break;
case SF_FORMAT_DOUBLE:
outputSignalBits = 53;
break;
case SF_FORMAT_FLOAT:
outputSignalBits = 21;
break;
default:
outputSignalBits = 16;
}
if (ci.quantize) {
outputSignalBits = std::max(1, std::min(ci.quantizeBits, outputSignalBits));
}
// confirm dithering options for user:
if (ci.bDither) {
auto prec = std::cout.precision();
std::cout << "Generating " << std::setprecision(2) << ci.ditherAmount << " bits of " << ditherProfileList[ci.ditherProfileID].name << " dither for " << outputSignalBits << "-bit output format";
std::cout.precision(prec);
if (ci.bAutoBlankingEnabled)
std::cout << ", with auto-blanking";
std::cout << std::endl;
}
// make a vector of ditherers (one ditherer for each channel):
std::vector<Ditherer<FloatType>> ditherers;
ditherers.reserve(static_cast<size_t>(nChannels));
const auto seed = static_cast<int>(ci.bUseSeed ? ci.seed : time(nullptr));
for (int n = 0; n < nChannels; n++) {
ditherers.emplace_back(outputSignalBits, ci.ditherAmount, ci.bAutoBlankingEnabled, n + seed, static_cast<DitherProfileID>(ci.ditherProfileID));
}
// make a vector of Resamplers
std::vector<Converter<FloatType>> converters;
converters.reserve(static_cast<size_t>(nChannels));
for (int n = 0; n < nChannels; n++) {
converters.emplace_back(ci);
}
// Calculate initial gain:
FloatType gain = static_cast<FloatType>(ci.gain) * static_cast<FloatType>(converters[0].getGain()) *
static_cast<FloatType>(ci.bNormalize ? fraction.numerator * (ci.limit / static_cast<double>(peakInputSample)) : fraction.numerator * ci.limit);
// todo: more testing with very low bit depths (eg 4 bits)
if (ci.bDither) { // allow headroom for dithering:
FloatType ditherCompensation =
(pow(2, outputSignalBits - 1) - pow(2, ci.ditherAmount - 1)) / pow(2, outputSignalBits - 1); // eg 32767/32768 = 0.999969 (-0.00027 dB)
gain *= ditherCompensation;
}
const int groupDelay = static_cast<int>(converters[0].getGroupDelay());
const auto tailSize = nChannels * std::ceil(std::max<size_t>(0, groupDelay) / resamplingFactor);
FloatType peakOutputSample;
bool bClippingDetected;
RaiiTimer timer(inputDuration);
int clippingProtectionAttempts = 0;
do { // clipping detection loop (repeats if clipping detected AND not using a temp file)
infile.seek(0, SEEK_SET);
peakInputSample = 0.0;
bClippingDetected = false;
std::unique_ptr<SndfileHandle> outFile;
std::unique_ptr<CsvFile> csvFile;
if (ci.csvOutput) { // csv output
csvFile.reset(new CsvFile(ci.outputFilename));
csvFile->setNumChannels(nChannels);
// defaults
csvFile->setNumericBase(Decimal);
csvFile->setIntegerWriteScalingStyle(ci.integerWriteScalingStyle);
csvFile->setSignedness(Signed);
csvFile->setNumericFormat(Integer);
if (ci.outBitFormat.empty()) { // default = 16-bit, unsigned, integer (decimal)
csvFile->setNumBits(16);
} else {
std::regex rgx("([us]?)(\\d+)([fiox]?)"); // [u|s]<numBits>[f|i|o|x]
std::smatch matchResults;
std::regex_search(ci.outBitFormat, matchResults, rgx);
int numBits = 16;
if (matchResults.length() >= 1 && matchResults[1].compare("u") == 0) {
csvFile->setSignedness(Unsigned);
}
if (matchResults.length() >= 2 && std::stoi(matchResults[2]) != 0) {
numBits = std::min(std::max(1, std::stoi(matchResults[2])), 64); // 1-64 bits
}
if (matchResults.length() >= 3 && !matchResults[3].str().empty()) {
if (matchResults[3].compare("f") == 0) {
csvFile->setNumericFormat(FloatingPoint);
}
else if (matchResults[3].compare("o") == 0) {
csvFile->setNumericBase(Octal);
}
else if (matchResults[3].compare("x") == 0) {
csvFile->setNumericBase(Hexadecimal);
}
}
csvFile->setNumBits(numBits);
// todo: precision, other params
}
} else { // libSndFile output
try {
// output file may need to be overwriten on subsequent passes,
// and the only way to close the file is to destroy the SndfileHandle.
outFile.reset(new SndfileHandle(ci.outputFilename, SFM_WRITE, outputFileFormat, nChannels, ci.outputSampleRate));
if (int e = outFile->error()) {
std::cout << "Error: Couldn't Open Output File (" << sf_error_number(e) << ")" << std::endl;
return false;
}
if (ci.bNoPeakChunk) {
outFile->command(SFC_SET_ADD_PEAK_CHUNK, nullptr, SF_FALSE);
}
if (ci.bWriteMetaData) {
if (!setMetaData(m, *outFile)) {
std::cout << "Warning: problem writing metadata to output file ( " << outFile->strError() << " )" << std::endl;
}
}
// if the minor (sub) format of outputFileFormat is flac, and user has requested a specific compression level, set compression level:
if (((outputFileFormat & SF_FORMAT_FLAC) == SF_FORMAT_FLAC) && ci.bSetFlacCompression) {
std::cout << "setting flac compression level to " << ci.flacCompressionLevel << std::endl;
double cl = ci.flacCompressionLevel / 8.0; // there are 9 flac compression levels from 0-8. Normalize to 0-1.0
outFile->command(SFC_SET_COMPRESSION_LEVEL, &cl, sizeof(cl));
}
// if the minor (sub) format of outputFileFormat is vorbis, and user has requested a specific quality level, set quality level:
if (((outputFileFormat & SF_FORMAT_VORBIS) == SF_FORMAT_VORBIS) && ci.bSetVorbisQuality) {
auto prec = std::cout.precision();
std::cout.precision(1);
std::cout << "setting vorbis quality level to " << ci.vorbisQuality << std::endl;
std::cout.precision(prec);
double cl = (1.0 - ci.vorbisQuality) / 11.0; // Normalize from (-1 to 10), to (1.0 to 0) ... why is it backwards ?
outFile->command(SFC_SET_COMPRESSION_LEVEL, &cl, sizeof(cl));
}
}
catch (std::exception& e) {
std::cout << "Error: Couldn't Open Output File " << e.what() << std::endl;
return false;
}
}
// conditionally open a temp file:
if (ci.bTmpFile) {
tmpSndfileHandle = getTempFile<FloatType>(inputFileFormat, nChannels, ci, tmpFilename);
if (tmpSndfileHandle == nullptr) {
ci.bTmpFile = false;
}
} // ends opening of temp file
// echo conversion mode to user (multi-stage/single-stage, multi-threaded/single-threaded)
const std::string stageness(ci.bMultiStage ? "multi-stage" : "single-stage");
const std::string threadedness(ci.bMultiThreaded ? ", multi-threaded" : "");
std::cout << "Converting (" << stageness << threadedness << ") ..." << std::endl;
peakOutputSample = 0.0;
totalSamplesRead = 0;
const sf_count_t incrementalProgressThreshold = (ci.progressUpdates > 0 ) ? inputSampleCount / ci.progressUpdates : inputSampleCount + 1;
sf_count_t nextProgressThreshold = incrementalProgressThreshold;
int outStartOffset = std::min(groupDelay * nChannels, static_cast<int>(outputBlockSize) - nChannels);
// initialise output (post-conversion) processing
EffectChain<FloatType> outputChain;
outputChain.setOutputBufferSize(outputBlockSize);
outputChain.setChannelCount(nChannels);
outputChain.setTakeOwnership(true);
if(ci.bAdjustStereoWidth && nChannels == 2) {
auto stereoImager = new StereoImager<FloatType>;
std::cout << "adjusting stereo width" << std::endl;
stereoImager->setStereoWidth(ci.stereoWidth);
outputChain.add(stereoImager);
}
if(ci.bFadeIn || ci.bFadeOut) {
auto fadeEffect = new FadeEffect<FloatType>;
fadeEffect->setSampleRate(ci.outputSampleRate);
fadeEffect->setTotalFrames(inputFrames * ci.outputSampleRate / ci.inputSampleRate);
const double shortestPossibleFade = 2.0 / ci.outputSampleRate;
if(ci.bFadeIn && ci.fadeInTime >= shortestPossibleFade) {
std::cout << "fade-in " << ci.fadeInTime << " seconds" << std::endl;
fadeEffect->setFadeIn(ci.fadeInTime);
}
if(ci.bFadeOut && ci.fadeOutTime >= shortestPossibleFade) {
std::cout << "fade-out " << ci.fadeOutTime << " seconds" << std::endl;
fadeEffect->setFadeOut(ci.fadeOutTime);
}
outputChain.add(fadeEffect);
}
const bool hasOutputFX = !outputChain.empty();
// ---
// construct thread pool
ctpl::thread_pool threadPool(nChannels);
struct Result {
size_t outBlockindex;
FloatType peak;
};
std::vector<std::future<Result>> results(nChannels);
bool eof = false;
do { // central conversion loop (the heart of the matter ...)
// Grab a block of interleaved samples from file:
samplesRead = infile.read(inputBlock.data(), inputBlockSize);
if(samplesRead == 0) {
eof = true;
samplesRead = std::min<size_t>(tailSize, inputBlockSize);
std::fill_n(inputBlock.begin(), samplesRead, static_cast<FloatType>(0.0));
}
totalSamplesRead += samplesRead;
// de-interleave into channel buffers
size_t i = 0;
for (size_t s = 0; s < samplesRead; s += nChannels) {
for (int ch = 0; ch < nChannels; ++ch) {
inputChannelBuffers[ch][i] = inputBlock[s + ch];
}
++i;
}
size_t outputBlockIndex = 0;
for (int ch = 0; ch < nChannels; ++ch) { // run convert stage for each channel (concurrently)
auto processingFunc = [&, ch](int) {
FloatType* iBuf = inputChannelBuffers[ch].data();
FloatType* oBuf = outputChannelBuffers[ch].data();
size_t o = 0;
FloatType localPeak = 0.0;
size_t localOutputBlockIndex = 0;
converters[ch].convert(oBuf, o, iBuf, i);
for (size_t f = 0; f < o; ++f) {
// note: disable dither for temp files (dithering to be done in post)
FloatType outputSample = (ci.bDither && !ci.bTmpFile) ? ditherers[ch].dither(gain * oBuf[f]) : gain * oBuf[f]; // gain, dither
localPeak = std::max(localPeak, std::abs(outputSample)); // peak
outputBlock[localOutputBlockIndex + ch] = outputSample; // interleave
localOutputBlockIndex += nChannels;
}
Result res{};
res.outBlockindex = localOutputBlockIndex;
res.peak = localPeak;
return res;
};
if (multiThreaded) {
results[ch] = threadPool.push(processingFunc);
} else {
Result res = processingFunc(0);
peakOutputSample = std::max(peakOutputSample, res.peak);
outputBlockIndex = res.outBlockindex;
}
}
if (multiThreaded) { // collect results:
for (int ch = 0; ch < nChannels; ++ch) {
Result res = results[ch].get();
peakOutputSample = std::max(peakOutputSample, res.peak);
outputBlockIndex = res.outBlockindex;
}
}
// process output (with Group Delay Compensation):
sf_count_t outputSampleCount = outputBlockIndex - outStartOffset;
const FloatType* outputData = hasOutputFX ?
outputChain.process(outputBlock.data(), outputSampleCount) + outStartOffset :
outputBlock.data() + outStartOffset;
// write out to either temp file or outfile
if (ci.bTmpFile) {
tmpSndfileHandle->write(outputData, outputSampleCount);
}
else {
if (ci.csvOutput) {
csvFile->write(outputData, outputSampleCount);
}
else {
outFile->write(outputData, outputSampleCount);
}
}
outStartOffset = 0; // reset after first use
// conditionally send progress update:
if (totalSamplesRead > nextProgressThreshold) {
int progressPercentage = std::min(static_cast<int>(99), static_cast<int>(100 * totalSamplesRead / inputSampleCount));
OutputManager::callProgressFunc(progressPercentage);
nextProgressThreshold += incrementalProgressThreshold;
}
} while (!eof); // ends central conversion loop
if (ci.bTmpFile) {
gain = 1.0; // output file must start with unity gain relative to temp file
} else {
// notify user:
std::cout << "Done" << std::endl;
auto prec = std::cout.precision();
std::cout << "Peak output sample: " << std::setprecision(6) << peakOutputSample << " (" << 20 * log10(peakOutputSample) << " dBFS)" << std::endl;
std::cout.precision(prec);
}
do {
// test for clipping:
if (!ci.disableClippingProtection && peakOutputSample > ci.limit) {
std::cout << "\nClipping detected !" << std::endl;
// calculate gain adjustment
FloatType gainAdjustment = static_cast<FloatType>(clippingTrim) * ci.limit / peakOutputSample;
gain *= gainAdjustment;
// echo gain adjustment to user - use slightly different message if using temp file:
if (ci.bTmpFile) {
std::cout << "Adjusting gain by " << 20 * log10(gainAdjustment) << " dB" << std::endl;
}
else {
std::cout << "Re-doing with " << 20 * log10(gainAdjustment) << " dB gain adjustment" << std::endl;
}
// reset the ditherers
if (ci.bDither) {
for (auto &ditherer : ditherers) {
ditherer.adjustGain(gainAdjustment);
ditherer.reset();
}
}
// reset the converters
for (auto &converter : converters) {
converter.reset();
}
} // ends test for clipping
// if using temp file, write to outFile
if (ci.bTmpFile) {
std::cout << "Writing to output file ...\n";
std::vector<FloatType> outBuf(inputBlockSize, 0);
peakOutputSample = 0.0;
totalSamplesRead = 0;
nextProgressThreshold = incrementalProgressThreshold;
tmpSndfileHandle->seek(0, SEEK_SET);
if (!ci.csvOutput) {
outFile->seek(0, SEEK_SET);
}
do { // Grab a block of interleaved samples from temp file:
samplesRead = tmpSndfileHandle->read(inputBlock.data(), inputBlockSize);
totalSamplesRead += samplesRead;
// de-interleave into channels, apply gain, add dither, and save to output buffer
size_t i = 0;
for (int s = 0; s < samplesRead; s += nChannels) {
for (int ch = 0; ch < nChannels; ++ch) {
FloatType smpl = ci.bDither ? ditherers[ch].dither(gain * inputBlock[i]) :
gain * inputBlock[i];
peakOutputSample = std::max(std::abs(smpl), peakOutputSample);
outBuf[i++] = smpl;
}
}
// write output buffer to outfile
if (ci.csvOutput) {
csvFile->write(outBuf.data(), i);
}
else {
outFile->write(outBuf.data(), i);
}
// conditionally send progress update:
if (totalSamplesRead > nextProgressThreshold) {
int progressPercentage = std::min(static_cast<int>(99),
static_cast<int>(100 * totalSamplesRead / inputSampleCount));
OutputManager::callProgressFunc(progressPercentage);
nextProgressThreshold += incrementalProgressThreshold;
}
} while (samplesRead > 0);
std::cout << "Done" << std::endl;
auto prec = std::cout.precision();
std::cout << "Peak output sample: " << std::setprecision(6) << peakOutputSample << " (" << 20 * log10(peakOutputSample) << " dBFS)" << std::endl;
std::cout.precision(prec);
} // ends if (ci.bTmpFile)
bClippingDetected = peakOutputSample > ci.limit;
if (bClippingDetected)
clippingProtectionAttempts++;
// explanation of 'while' loops:
// 1. when clipping is detected and temp file is in use, go back to re-adjusting gain, resetting ditherers etc and repeat
// 2. when clipping is detected and temp file NOT used, go all the way back to reading the input file, and running the whole conversion again
// (This whole control structure might be better served with good old gotos ...)
} while (ci.bTmpFile && !ci.disableClippingProtection && bClippingDetected && clippingProtectionAttempts < maxClippingProtectionAttempts); // if using temp file, do another round if clipping detected
} while (!ci.bTmpFile && !ci.disableClippingProtection && bClippingDetected && clippingProtectionAttempts < maxClippingProtectionAttempts); // if NOT using temp file, do another round if clipping detected
// clean-up temp file:
delete tmpSndfileHandle; // dealllocate SndFileHandle
#if defined (TEMPFILE_OPEN_METHOD_STD_TMPNAM) || defined (TEMPFILE_OPEN_METHOD_WINAPI)
std::remove(tmpFilename.c_str()); // actually remove the temp file from disk
#endif
return true;
} // ends convert()
// getTempFile() : opens a temp file (wav/rf64 file in floating-point format).
// Double- or single- precision is determined by FloatType.
// Dynamically allocates a SndfileHandle.
// Returns SndfileHandle pointer, which is the caller's responsibility to delete.
// Returns nullptr if unsuccessful.
template<typename FloatType>
SndfileHandle* getTempFile(int inputFileFormat, int nChannels, const ConversionInfo& ci, std::string& tmpFilename) {
SndfileHandle* tmpSndfileHandle = nullptr;
bool tmpFileError;
int outputFileFormat = ci.outputFormat ? ci.outputFormat : inputFileFormat;
// set major format of temp file (inherit rf64-ness from output file):
int tmpFileFormat = (outputFileFormat & SF_FORMAT_RF64) ? SF_FORMAT_RF64 : SF_FORMAT_WAV;