-
Notifications
You must be signed in to change notification settings - Fork 513
/
loaddef.cpp
2061 lines (1911 loc) · 64.1 KB
/
loaddef.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
/*
* HRTF utility for producing and demonstrating the process of creating an
* OpenAL Soft compatible HRIR data set.
*
* Copyright (C) 2011-2019 Christopher Fitzgerald
*
* 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 2 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, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Or visit: http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*/
#include "loaddef.h"
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <iterator>
#include <limits>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
#include "albit.h"
#include "almalloc.h"
#include "alnumeric.h"
#include "alspan.h"
#include "alstring.h"
#include "makemhr.h"
#include "polyphase_resampler.h"
#include "mysofa.h"
namespace {
// Constants for accessing the token reader's ring buffer.
constexpr uint TRRingBits{16};
constexpr uint TRRingSize{1 << TRRingBits};
constexpr uint TRRingMask{TRRingSize - 1};
// The token reader's load interval in bytes.
constexpr uint TRLoadSize{TRRingSize >> 2};
// Token reader state for parsing the data set definition.
struct TokenReaderT {
std::istream &mIStream;
std::string mName{};
uint mLine{};
uint mColumn{};
std::array<char,TRRingSize> mRing{};
std::streamsize mIn{};
std::streamsize mOut{};
TokenReaderT(std::istream &istream) noexcept : mIStream{istream} { }
TokenReaderT(const TokenReaderT&) = default;
};
// The maximum identifier length used when processing the data set
// definition.
constexpr uint MaxIdentLen{16};
// The limits for the listener's head 'radius' in the data set definition.
constexpr double MinRadius{0.05};
constexpr double MaxRadius{0.15};
// The maximum number of channels that can be addressed for a WAVE file
// source listed in the data set definition.
constexpr uint MaxWaveChannels{65535};
// The limits to the byte size for a binary source listed in the definition
// file.
enum : uint {
MinBinSize = 2,
MaxBinSize = 4
};
// The limits to the number of significant bits for an ASCII source listed in
// the data set definition.
enum : uint {
MinASCIIBits = 16,
MaxASCIIBits = 32
};
// The four-character-codes for RIFF/RIFX WAVE file chunks.
enum : uint {
FOURCC_RIFF = 0x46464952, // 'RIFF'
FOURCC_RIFX = 0x58464952, // 'RIFX'
FOURCC_WAVE = 0x45564157, // 'WAVE'
FOURCC_FMT = 0x20746D66, // 'fmt '
FOURCC_DATA = 0x61746164, // 'data'
FOURCC_LIST = 0x5453494C, // 'LIST'
FOURCC_WAVL = 0x6C766177, // 'wavl'
FOURCC_SLNT = 0x746E6C73, // 'slnt'
};
// The supported wave formats.
enum : uint {
WAVE_FORMAT_PCM = 0x0001,
WAVE_FORMAT_IEEE_FLOAT = 0x0003,
WAVE_FORMAT_EXTENSIBLE = 0xFFFE,
};
enum ByteOrderT {
BO_NONE,
BO_LITTLE,
BO_BIG
};
// Source format for the references listed in the data set definition.
enum SourceFormatT {
SF_NONE,
SF_ASCII, // ASCII text file.
SF_BIN_LE, // Little-endian binary file.
SF_BIN_BE, // Big-endian binary file.
SF_WAVE, // RIFF/RIFX WAVE file.
SF_SOFA // Spatially Oriented Format for Accoustics (SOFA) file.
};
// Element types for the references listed in the data set definition.
enum ElementTypeT {
ET_NONE,
ET_INT, // Integer elements.
ET_FP // Floating-point elements.
};
// Source reference state used when loading sources.
struct SourceRefT {
SourceFormatT mFormat;
ElementTypeT mType;
uint mSize;
int mBits;
uint mChannel;
double mAzimuth;
double mElevation;
double mRadius;
uint mSkip;
uint mOffset;
std::array<char,MAX_PATH_LEN+1> mPath;
};
/* Whitespace is not significant. It can process tokens as identifiers, numbers
* (integer and floating-point), strings, and operators. Strings must be
* encapsulated by double-quotes and cannot span multiple lines.
*/
// Setup the reader on the given file. The filename can be NULL if no error
// output is desired.
void TrSetup(const al::span<const char> startbytes, const std::string_view filename,
TokenReaderT *tr)
{
std::string_view namepart;
if(!filename.empty())
{
const auto fslashpos = filename.rfind('/');
const auto bslashpos = filename.rfind('\\');
const auto slashpos = (bslashpos >= filename.size()) ? fslashpos :
(fslashpos >= filename.size()) ? bslashpos :
std::max(fslashpos, bslashpos);
if(slashpos < filename.size())
namepart = filename.substr(slashpos+1);
}
tr->mName = namepart;
tr->mLine = 1;
tr->mColumn = 1;
tr->mIn = 0;
tr->mOut = 0;
if(!startbytes.empty())
{
assert(startbytes.size() <= tr->mRing.size());
std::copy(startbytes.cbegin(), startbytes.cend(), tr->mRing.begin());
tr->mIn += std::streamsize(startbytes.size());
}
}
// Prime the reader's ring buffer, and return a result indicating that there
// is text to process.
auto TrLoad(TokenReaderT *tr) -> int
{
std::istream &istream = tr->mIStream;
std::streamsize toLoad{TRRingSize - static_cast<std::streamsize>(tr->mIn - tr->mOut)};
if(toLoad >= TRLoadSize && istream.good())
{
// Load TRLoadSize (or less if at the end of the file) per read.
toLoad = TRLoadSize;
const auto in = tr->mIn&TRRingMask;
std::streamsize count{TRRingSize - in};
if(count < toLoad)
{
istream.read(al::to_address(tr->mRing.begin() + in), count);
tr->mIn += istream.gcount();
istream.read(tr->mRing.data(), toLoad-count);
tr->mIn += istream.gcount();
}
else
{
istream.read(al::to_address(tr->mRing.begin() + in), toLoad);
tr->mIn += istream.gcount();
}
if(tr->mOut >= TRRingSize)
{
tr->mOut -= TRRingSize;
tr->mIn -= TRRingSize;
}
}
if(tr->mIn > tr->mOut)
return 1;
return 0;
}
// Error display routine. Only displays when the base name is not NULL.
void TrErrorVA(const TokenReaderT *tr, uint line, uint column, const char *format, va_list argPtr)
{
if(tr->mName.empty())
return;
fprintf(stderr, "\nError (%s:%u:%u): ", tr->mName.c_str(), line, column);
vfprintf(stderr, format, argPtr);
}
// Used to display an error at a saved line/column.
void TrErrorAt(const TokenReaderT *tr, uint line, uint column, const char *format, ...)
{
/* NOLINTBEGIN(*-array-to-pointer-decay) */
va_list argPtr;
va_start(argPtr, format);
TrErrorVA(tr, line, column, format, argPtr);
va_end(argPtr);
/* NOLINTEND(*-array-to-pointer-decay) */
}
// Used to display an error at the current line/column.
void TrError(const TokenReaderT *tr, const char *format, ...)
{
/* NOLINTBEGIN(*-array-to-pointer-decay) */
va_list argPtr;
va_start(argPtr, format);
TrErrorVA(tr, tr->mLine, tr->mColumn, format, argPtr);
va_end(argPtr);
/* NOLINTEND(*-array-to-pointer-decay) */
}
// Skips to the next line.
void TrSkipLine(TokenReaderT *tr)
{
char ch;
while(TrLoad(tr))
{
ch = tr->mRing[tr->mOut&TRRingMask];
tr->mOut++;
if(ch == '\n')
{
tr->mLine++;
tr->mColumn = 1;
break;
}
tr->mColumn ++;
}
}
// Skips to the next token.
auto TrSkipWhitespace(TokenReaderT *tr) -> int
{
while(TrLoad(tr))
{
char ch{tr->mRing[tr->mOut&TRRingMask]};
if(isspace(ch))
{
tr->mOut++;
if(ch == '\n')
{
tr->mLine++;
tr->mColumn = 1;
}
else
tr->mColumn++;
}
else if(ch == '#')
TrSkipLine(tr);
else
return 1;
}
return 0;
}
// Get the line and/or column of the next token (or the end of input).
void TrIndication(TokenReaderT *tr, uint *line, uint *column)
{
TrSkipWhitespace(tr);
if(line) *line = tr->mLine;
if(column) *column = tr->mColumn;
}
// Checks to see if a token is (likely to be) an identifier. It does not
// display any errors and will not proceed to the next token.
auto TrIsIdent(TokenReaderT *tr) -> int
{
if(!TrSkipWhitespace(tr))
return 0;
char ch{tr->mRing[tr->mOut&TRRingMask]};
return ch == '_' || isalpha(ch);
}
// Checks to see if a token is the given operator. It does not display any
// errors and will not proceed to the next token.
auto TrIsOperator(TokenReaderT *tr, const std::string_view op) -> int
{
if(!TrSkipWhitespace(tr))
return 0;
auto out = tr->mOut;
size_t len{0};
while(len < op.size() && out < tr->mIn)
{
if(tr->mRing[out&TRRingMask] != op[len])
break;
++len;
++out;
}
if(len == op.size())
return 1;
return 0;
}
/* The TrRead*() routines obtain the value of a matching token type. They
* display type, form, and boundary errors and will proceed to the next
* token.
*/
// Reads and validates an identifier token.
auto TrReadIdent(TokenReaderT *tr, const al::span<char> ident) -> int
{
assert(!ident.empty());
const size_t maxLen{ident.size()-1};
uint col{tr->mColumn};
if(TrSkipWhitespace(tr))
{
col = tr->mColumn;
char ch{tr->mRing[tr->mOut&TRRingMask]};
if(ch == '_' || isalpha(ch))
{
size_t len{0};
do {
if(len < maxLen)
ident[len] = ch;
++len;
tr->mOut++;
if(!TrLoad(tr))
break;
ch = tr->mRing[tr->mOut&TRRingMask];
} while(ch == '_' || isdigit(ch) || isalpha(ch));
tr->mColumn += static_cast<uint>(len);
if(len < maxLen)
{
ident[len] = '\0';
return 1;
}
TrErrorAt(tr, tr->mLine, col, "Identifier is too long.\n");
return 0;
}
}
TrErrorAt(tr, tr->mLine, col, "Expected an identifier.\n");
return 0;
}
// Reads and validates (including bounds) an integer token.
auto TrReadInt(TokenReaderT *tr, const int loBound, const int hiBound, int *value) -> int
{
uint col{tr->mColumn};
if(TrSkipWhitespace(tr))
{
col = tr->mColumn;
uint len{0};
std::array<char,64+1> temp{};
char ch{tr->mRing[tr->mOut&TRRingMask]};
if(ch == '+' || ch == '-')
{
temp[len] = ch;
len++;
tr->mOut++;
}
uint digis{0};
while(TrLoad(tr))
{
ch = tr->mRing[tr->mOut&TRRingMask];
if(!isdigit(ch)) break;
if(len < 64)
temp[len] = ch;
len++;
digis++;
tr->mOut++;
}
tr->mColumn += len;
if(digis > 0 && ch != '.' && !isalpha(ch))
{
if(len > 64)
{
TrErrorAt(tr, tr->mLine, col, "Integer is too long.");
return 0;
}
temp[len] = '\0';
*value = static_cast<int>(strtol(temp.data(), nullptr, 10));
if(*value < loBound || *value > hiBound)
{
TrErrorAt(tr, tr->mLine, col, "Expected a value from %d to %d.\n", loBound, hiBound);
return 0;
}
return 1;
}
}
TrErrorAt(tr, tr->mLine, col, "Expected an integer.\n");
return 0;
}
// Reads and validates (including bounds) a float token.
auto TrReadFloat(TokenReaderT *tr, const double loBound, const double hiBound, double *value) -> int
{
uint col{tr->mColumn};
if(TrSkipWhitespace(tr))
{
col = tr->mColumn;
std::array<char,64+1> temp{};
uint len{0};
char ch{tr->mRing[tr->mOut&TRRingMask]};
if(ch == '+' || ch == '-')
{
temp[len] = ch;
len++;
tr->mOut++;
}
uint digis{0};
while(TrLoad(tr))
{
ch = tr->mRing[tr->mOut&TRRingMask];
if(!isdigit(ch)) break;
if(len < 64)
temp[len] = ch;
len++;
digis++;
tr->mOut++;
}
if(ch == '.')
{
if(len < 64)
temp[len] = ch;
len++;
tr->mOut++;
}
while(TrLoad(tr))
{
ch = tr->mRing[tr->mOut&TRRingMask];
if(!isdigit(ch)) break;
if(len < 64)
temp[len] = ch;
len++;
digis++;
tr->mOut++;
}
if(digis > 0)
{
if(ch == 'E' || ch == 'e')
{
if(len < 64)
temp[len] = ch;
len++;
digis = 0;
tr->mOut++;
if(ch == '+' || ch == '-')
{
if(len < 64)
temp[len] = ch;
len++;
tr->mOut++;
}
while(TrLoad(tr))
{
ch = tr->mRing[tr->mOut&TRRingMask];
if(!isdigit(ch)) break;
if(len < 64)
temp[len] = ch;
len++;
digis++;
tr->mOut++;
}
}
tr->mColumn += len;
if(digis > 0 && ch != '.' && !isalpha(ch))
{
if(len > 64)
{
TrErrorAt(tr, tr->mLine, col, "Float is too long.");
return 0;
}
temp[len] = '\0';
*value = strtod(temp.data(), nullptr);
if(*value < loBound || *value > hiBound)
{
TrErrorAt(tr, tr->mLine, col, "Expected a value from %f to %f.\n", loBound, hiBound);
return 0;
}
return 1;
}
}
else
tr->mColumn += len;
}
TrErrorAt(tr, tr->mLine, col, "Expected a float.\n");
return 0;
}
// Reads and validates a string token.
auto TrReadString(TokenReaderT *tr, const al::span<char> text) -> int
{
assert(!text.empty());
const size_t maxLen{text.size()-1};
uint col{tr->mColumn};
if(TrSkipWhitespace(tr))
{
col = tr->mColumn;
if(char ch{tr->mRing[tr->mOut&TRRingMask]}; ch == '\"')
{
tr->mOut++;
size_t len{0};
while(TrLoad(tr))
{
ch = tr->mRing[tr->mOut&TRRingMask];
tr->mOut++;
if(ch == '\"')
break;
if(ch == '\n')
{
TrErrorAt(tr, tr->mLine, col, "Unterminated string at end of line.\n");
return 0;
}
if(len < maxLen)
text[len] = ch;
len++;
}
if(ch != '\"')
{
tr->mColumn += static_cast<uint>(1 + len);
TrErrorAt(tr, tr->mLine, col, "Unterminated string at end of input.\n");
return 0;
}
tr->mColumn += static_cast<uint>(2 + len);
if(len > maxLen)
{
TrErrorAt(tr, tr->mLine, col, "String is too long.\n");
return 0;
}
text[len] = '\0';
return 1;
}
}
TrErrorAt(tr, tr->mLine, col, "Expected a string.\n");
return 0;
}
// Reads and validates the given operator.
auto TrReadOperator(TokenReaderT *tr, const std::string_view op) -> int
{
uint col{tr->mColumn};
if(TrSkipWhitespace(tr))
{
col = tr->mColumn;
size_t len{0};
while(len < op.size() && TrLoad(tr))
{
if(tr->mRing[tr->mOut&TRRingMask] != op[len])
break;
++len;
tr->mOut += 1;
}
tr->mColumn += static_cast<uint>(len);
if(len == op.size())
return 1;
}
TrErrorAt(tr, tr->mLine, col, "Expected '%s' operator.\n", op);
return 0;
}
/*************************
*** File source input ***
*************************/
// Read a binary value of the specified byte order and byte size from a file,
// storing it as a 32-bit unsigned integer.
auto ReadBin4(std::istream &istream, const char *filename, const ByteOrderT order,
const uint bytes, uint32_t *out) -> int
{
std::array<uint8_t,4> in{};
istream.read(reinterpret_cast<char*>(in.data()), static_cast<int>(bytes));
if(istream.gcount() != bytes)
{
fprintf(stderr, "\nError: Bad read from file '%s'.\n", filename);
return 0;
}
uint32_t accum{0};
switch(order)
{
case BO_LITTLE:
for(uint i = 0;i < bytes;i++)
accum = (accum<<8) | in[bytes - i - 1];
break;
case BO_BIG:
for(uint i = 0;i < bytes;i++)
accum = (accum<<8) | in[i];
break;
default:
break;
}
*out = accum;
return 1;
}
// Read a binary value of the specified byte order from a file, storing it as
// a 64-bit unsigned integer.
auto ReadBin8(std::istream &istream, const char *filename, const ByteOrderT order, uint64_t *out) -> int
{
std::array<uint8_t,8> in{};
istream.read(reinterpret_cast<char*>(in.data()), 8);
if(istream.gcount() != 8)
{
fprintf(stderr, "\nError: Bad read from file '%s'.\n", filename);
return 0;
}
uint64_t accum{};
switch(order)
{
case BO_LITTLE:
for(uint i{0};i < 8;++i)
accum = (accum<<8) | in[8 - i - 1];
break;
case BO_BIG:
for(uint i{0};i < 8;++i)
accum = (accum<<8) | in[i];
break;
default:
break;
}
*out = accum;
return 1;
}
/* Read a binary value of the specified type, byte order, and byte size from
* a file, converting it to a double. For integer types, the significant
* bits are used to normalize the result. The sign of bits determines
* whether they are padded toward the MSB (negative) or LSB (positive).
* Floating-point types are not normalized.
*/
auto ReadBinAsDouble(std::istream &istream, const char *filename, const ByteOrderT order,
const ElementTypeT type, const uint bytes, const int bits, double *out) -> int
{
*out = 0.0;
if(bytes > 4)
{
uint64_t val{};
if(!ReadBin8(istream, filename, order, &val))
return 0;
if(type == ET_FP)
*out = al::bit_cast<double>(val);
}
else
{
uint32_t val{};
if(!ReadBin4(istream, filename, order, bytes, &val))
return 0;
if(type == ET_FP)
*out = al::bit_cast<float>(val);
else
{
if(bits > 0)
val >>= (8*bytes) - (static_cast<uint>(bits));
else
val &= (0xFFFFFFFF >> (32+bits));
if(val&static_cast<uint>(1<<(std::abs(bits)-1)))
val |= (0xFFFFFFFF << std::abs(bits));
*out = static_cast<int32_t>(val) / static_cast<double>(1<<(std::abs(bits)-1));
}
}
return 1;
}
/* Read an ascii value of the specified type from a file, converting it to a
* double. For integer types, the significant bits are used to normalize the
* result. The sign of the bits should always be positive. This also skips
* up to one separator character before the element itself.
*/
auto ReadAsciiAsDouble(TokenReaderT *tr, const char *filename, const ElementTypeT type,
const uint bits, double *out) -> int
{
if(TrIsOperator(tr, ","))
TrReadOperator(tr, ",");
else if(TrIsOperator(tr, ":"))
TrReadOperator(tr, ":");
else if(TrIsOperator(tr, ";"))
TrReadOperator(tr, ";");
else if(TrIsOperator(tr, "|"))
TrReadOperator(tr, "|");
if(type == ET_FP)
{
if(!TrReadFloat(tr, -std::numeric_limits<double>::infinity(),
std::numeric_limits<double>::infinity(), out))
{
fprintf(stderr, "\nError: Bad read from file '%s'.\n", filename);
return 0;
}
}
else
{
int v;
if(!TrReadInt(tr, -(1<<(bits-1)), (1<<(bits-1))-1, &v))
{
fprintf(stderr, "\nError: Bad read from file '%s'.\n", filename);
return 0;
}
*out = v / static_cast<double>((1<<(bits-1))-1);
}
return 1;
}
// Read the RIFF/RIFX WAVE format chunk from a file, validating it against
// the source parameters and data set metrics.
auto ReadWaveFormat(std::istream &istream, const ByteOrderT order, const uint hrirRate,
SourceRefT *src) -> int
{
uint32_t fourCC, chunkSize;
uint32_t format, channels, rate, dummy, block, size, bits;
chunkSize = 0;
do {
if(chunkSize > 0)
istream.seekg(static_cast<int>(chunkSize), std::ios::cur);
if(!ReadBin4(istream, src->mPath.data(), BO_LITTLE, 4, &fourCC)
|| !ReadBin4(istream, src->mPath.data(), order, 4, &chunkSize))
return 0;
} while(fourCC != FOURCC_FMT);
if(!ReadBin4(istream, src->mPath.data(), order, 2, &format)
|| !ReadBin4(istream, src->mPath.data(), order, 2, &channels)
|| !ReadBin4(istream, src->mPath.data(), order, 4, &rate)
|| !ReadBin4(istream, src->mPath.data(), order, 4, &dummy)
|| !ReadBin4(istream, src->mPath.data(), order, 2, &block))
return 0;
block /= channels;
if(chunkSize > 14)
{
if(!ReadBin4(istream, src->mPath.data(), order, 2, &size))
return 0;
size /= 8;
if(block > size)
size = block;
}
else
size = block;
if(format == WAVE_FORMAT_EXTENSIBLE)
{
istream.seekg(2, std::ios::cur);
if(!ReadBin4(istream, src->mPath.data(), order, 2, &bits))
return 0;
if(bits == 0)
bits = 8 * size;
istream.seekg(4, std::ios::cur);
if(!ReadBin4(istream, src->mPath.data(), order, 2, &format))
return 0;
istream.seekg(static_cast<int>(chunkSize - 26), std::ios::cur);
}
else
{
bits = 8 * size;
if(chunkSize > 14)
istream.seekg(static_cast<int>(chunkSize - 16), std::ios::cur);
else
istream.seekg(static_cast<int>(chunkSize - 14), std::ios::cur);
}
if(format != WAVE_FORMAT_PCM && format != WAVE_FORMAT_IEEE_FLOAT)
{
fprintf(stderr, "\nError: Unsupported WAVE format in file '%s'.\n", src->mPath.data());
return 0;
}
if(src->mChannel >= channels)
{
fprintf(stderr, "\nError: Missing source channel in WAVE file '%s'.\n", src->mPath.data());
return 0;
}
if(rate != hrirRate)
{
fprintf(stderr, "\nError: Mismatched source sample rate in WAVE file '%s'.\n",
src->mPath.data());
return 0;
}
if(format == WAVE_FORMAT_PCM)
{
if(size < 2 || size > 4)
{
fprintf(stderr, "\nError: Unsupported sample size in WAVE file '%s'.\n",
src->mPath.data());
return 0;
}
if(bits < 16 || bits > (8*size))
{
fprintf(stderr, "\nError: Bad significant bits in WAVE file '%s'.\n",
src->mPath.data());
return 0;
}
src->mType = ET_INT;
}
else
{
if(size != 4 && size != 8)
{
fprintf(stderr, "\nError: Unsupported sample size in WAVE file '%s'.\n",
src->mPath.data());
return 0;
}
src->mType = ET_FP;
}
src->mSize = size;
src->mBits = static_cast<int>(bits);
src->mSkip = channels;
return 1;
}
// Read a RIFF/RIFX WAVE data chunk, converting all elements to doubles.
auto ReadWaveData(std::istream &istream, const SourceRefT *src, const ByteOrderT order,
const al::span<double> hrir) -> int
{
auto pre = static_cast<int>(src->mSize * src->mChannel);
auto post = static_cast<int>(src->mSize * (src->mSkip - src->mChannel - 1));
auto skip = int{0};
for(size_t i{0};i < hrir.size();++i)
{
skip += pre;
if(skip > 0)
istream.seekg(skip, std::ios::cur);
if(!ReadBinAsDouble(istream, src->mPath.data(), order, src->mType, src->mSize, src->mBits,
&hrir[i]))
return 0;
skip = post;
}
if(skip > 0)
istream.seekg(skip, std::ios::cur);
return 1;
}
// Read the RIFF/RIFX WAVE list or data chunk, converting all elements to
// doubles.
auto ReadWaveList(std::istream &istream, const SourceRefT *src, const ByteOrderT order,
const al::span<double> hrir) -> int
{
uint32_t fourCC, chunkSize, listSize, count;
uint block, skip, offset, i;
double lastSample;
for(;;)
{
if(!ReadBin4(istream, src->mPath.data(), BO_LITTLE, 4, &fourCC)
|| !ReadBin4(istream, src->mPath.data(), order, 4, &chunkSize))
return 0;
if(fourCC == FOURCC_DATA)
{
block = src->mSize * src->mSkip;
count = chunkSize / block;
if(count < (src->mOffset + hrir.size()))
{
fprintf(stderr, "\nError: Bad read from file '%s'.\n", src->mPath.data());
return 0;
}
using off_type = std::istream::off_type;
istream.seekg(off_type(src->mOffset) * off_type(block), std::ios::cur);
if(!ReadWaveData(istream, src, order, hrir))
return 0;
return 1;
}
if(fourCC == FOURCC_LIST)
{
if(!ReadBin4(istream, src->mPath.data(), BO_LITTLE, 4, &fourCC))
return 0;
chunkSize -= 4;
if(fourCC == FOURCC_WAVL)
break;
}
if(chunkSize > 0)
istream.seekg(static_cast<long>(chunkSize), std::ios::cur);
}
listSize = chunkSize;
block = src->mSize * src->mSkip;
skip = src->mOffset;
offset = 0;
lastSample = 0.0;
while(offset < hrir.size() && listSize > 8)
{
if(!ReadBin4(istream, src->mPath.data(), BO_LITTLE, 4, &fourCC)
|| !ReadBin4(istream, src->mPath.data(), order, 4, &chunkSize))
return 0;
listSize -= 8 + chunkSize;
if(fourCC == FOURCC_DATA)
{
count = chunkSize / block;
if(count > skip)
{
using off_type = std::istream::off_type;
istream.seekg(off_type(skip) * off_type(block), std::ios::cur);
chunkSize -= skip * block;
count -= skip;
skip = 0;
if(count > (hrir.size() - offset))
count = static_cast<uint>(hrir.size() - offset);
if(!ReadWaveData(istream, src, order, hrir.subspan(offset, count)))
return 0;
chunkSize -= count * block;
offset += count;
lastSample = hrir[offset - 1];
}
else
{
skip -= count;
count = 0;
}
}
else if(fourCC == FOURCC_SLNT)
{
if(!ReadBin4(istream, src->mPath.data(), order, 4, &count))
return 0;
chunkSize -= 4;
if(count > skip)
{
count -= skip;
skip = 0;
if(count > (hrir.size() - offset))
count = static_cast<uint>(hrir.size() - offset);
for(i = 0; i < count; i ++)
hrir[offset + i] = lastSample;
offset += count;
}
else
{
skip -= count;
count = 0;
}
}
if(chunkSize > 0)
istream.seekg(static_cast<long>(chunkSize), std::ios::cur);
}
if(offset < hrir.size())
{
fprintf(stderr, "\nError: Bad read from file '%s'.\n", src->mPath.data());
return 0;
}
return 1;
}
// Load a source HRIR from an ASCII text file containing a list of elements
// separated by whitespace or common list operators (',', ';', ':', '|').
auto LoadAsciiSource(std::istream &istream, const SourceRefT *src, const al::span<double> hrir) -> int
{
TokenReaderT tr{istream};
TrSetup({}, {}, &tr);
for(uint i{0};i < src->mOffset;++i)
{
double dummy{};
if(!ReadAsciiAsDouble(&tr, src->mPath.data(), src->mType, static_cast<uint>(src->mBits),
&dummy))
return 0;
}