2 * HRTF utility for producing and demonstrating the process of creating an
3 * OpenAL Soft compatible HRIR data set.
5 * Copyright (C) 2011-2014 Christopher Fitzgerald
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 * Or visit: http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
23 * --------------------------------------------------------------------------
25 * A big thanks goes out to all those whose work done in the field of
26 * binaural sound synthesis using measured HRTFs makes this utility and the
27 * OpenAL Soft implementation possible.
29 * The algorithm for diffuse-field equalization was adapted from the work
30 * done by Rio Emmanuel and Larcher Veronique of IRCAM and Bill Gardner of
31 * MIT Media Laboratory. It operates as follows:
33 * 1. Take the FFT of each HRIR and only keep the magnitude responses.
34 * 2. Calculate the diffuse-field power-average of all HRIRs weighted by
35 * their contribution to the total surface area covered by their
37 * 3. Take the diffuse-field average and limit its magnitude range.
38 * 4. Equalize the responses by using the inverse of the diffuse-field
40 * 5. Reconstruct the minimum-phase responses.
41 * 5. Zero the DC component.
42 * 6. IFFT the result and truncate to the desired-length minimum-phase FIR.
44 * The spherical head algorithm for calculating propagation delay was adapted
47 * Modeling Interaural Time Difference Assuming a Spherical Head
49 * Music 150, Musical Acoustics, Stanford University
52 * The formulae for calculating the Kaiser window metrics are from the
55 * Discrete-Time Signal Processing
56 * Alan V. Oppenheim and Ronald W. Schafer
57 * Prentice-Hall Signal Processing Series
73 // Rely (if naively) on OpenAL's header for the types used for serialization.
78 #define M_PI (3.14159265358979323846)
82 #define HUGE_VAL (1.0 / 0.0)
85 // The epsilon used to maintain signal stability.
86 #define EPSILON (1e-15)
88 // Constants for accessing the token reader's ring buffer.
89 #define TR_RING_BITS (16)
90 #define TR_RING_SIZE (1 << TR_RING_BITS)
91 #define TR_RING_MASK (TR_RING_SIZE - 1)
93 // The token reader's load interval in bytes.
94 #define TR_LOAD_SIZE (TR_RING_SIZE >> 2)
96 // The maximum identifier length used when processing the data set
98 #define MAX_IDENT_LEN (16)
100 // The maximum path length used when processing filenames.
101 #define MAX_PATH_LEN (256)
103 // The limits for the sample 'rate' metric in the data set definition and for
105 #define MIN_RATE (32000)
106 #define MAX_RATE (96000)
108 // The limits for the HRIR 'points' metric in the data set definition.
109 #define MIN_POINTS (16)
110 #define MAX_POINTS (8192)
112 // The limits to the number of 'azimuths' listed in the data set definition.
113 #define MIN_EV_COUNT (5)
114 #define MAX_EV_COUNT (128)
116 // The limits for each of the 'azimuths' listed in the data set definition.
117 #define MIN_AZ_COUNT (1)
118 #define MAX_AZ_COUNT (128)
120 // The limits for the listener's head 'radius' in the data set definition.
121 #define MIN_RADIUS (0.05)
122 #define MAX_RADIUS (0.15)
124 // The limits for the 'distance' from source to listener in the definition
126 #define MIN_DISTANCE (0.5)
127 #define MAX_DISTANCE (2.5)
129 // The maximum number of channels that can be addressed for a WAVE file
130 // source listed in the data set definition.
131 #define MAX_WAVE_CHANNELS (65535)
133 // The limits to the byte size for a binary source listed in the definition
135 #define MIN_BIN_SIZE (2)
136 #define MAX_BIN_SIZE (4)
138 // The minimum number of significant bits for binary sources listed in the
139 // data set definition. The maximum is calculated from the byte size.
140 #define MIN_BIN_BITS (16)
142 // The limits to the number of significant bits for an ASCII source listed in
143 // the data set definition.
144 #define MIN_ASCII_BITS (16)
145 #define MAX_ASCII_BITS (32)
147 // The limits to the FFT window size override on the command line.
148 #define MIN_FFTSIZE (512)
149 #define MAX_FFTSIZE (16384)
151 // The limits to the equalization range limit on the command line.
152 #define MIN_LIMIT (2.0)
153 #define MAX_LIMIT (120.0)
155 // The limits to the truncation window size on the command line.
156 #define MIN_TRUNCSIZE (8)
157 #define MAX_TRUNCSIZE (128)
159 // The limits to the custom head radius on the command line.
160 #define MIN_CUSTOM_RADIUS (0.05)
161 #define MAX_CUSTOM_RADIUS (0.15)
163 // The truncation window size must be a multiple of the below value to allow
164 // for vectorized convolution.
165 #define MOD_TRUNCSIZE (8)
167 // The defaults for the command line options.
168 #define DEFAULT_EQUALIZE (1)
169 #define DEFAULT_SURFACE (1)
170 #define DEFAULT_LIMIT (24.0)
171 #define DEFAULT_TRUNCSIZE (32)
172 #define DEFAULT_HEAD_MODEL (HM_DATASET)
173 #define DEFAULT_CUSTOM_RADIUS (0.0)
175 // The four-character-codes for RIFF/RIFX WAVE file chunks.
176 #define FOURCC_RIFF (0x46464952) // 'RIFF'
177 #define FOURCC_RIFX (0x58464952) // 'RIFX'
178 #define FOURCC_WAVE (0x45564157) // 'WAVE'
179 #define FOURCC_FMT (0x20746D66) // 'fmt '
180 #define FOURCC_DATA (0x61746164) // 'data'
181 #define FOURCC_LIST (0x5453494C) // 'LIST'
182 #define FOURCC_WAVL (0x6C766177) // 'wavl'
183 #define FOURCC_SLNT (0x746E6C73) // 'slnt'
185 // The supported wave formats.
186 #define WAVE_FORMAT_PCM (0x0001)
187 #define WAVE_FORMAT_IEEE_FLOAT (0x0003)
188 #define WAVE_FORMAT_EXTENSIBLE (0xFFFE)
190 // The maximum propagation delay value supported by OpenAL Soft.
191 #define MAX_HRTD (63.0)
193 // The OpenAL Soft HRTF format marker. It stands for minimum-phase head
194 // response protocol 01.
195 #define MHR_FORMAT ("MinPHR01")
197 // Byte order for the serialization routines.
204 // Source format for the references listed in the data set definition.
207 SF_WAVE
, // RIFF/RIFX WAVE file.
208 SF_BIN_LE
, // Little-endian binary file.
209 SF_BIN_BE
, // Big-endian binary file.
210 SF_ASCII
// ASCII text file.
213 // Element types for the references listed in the data set definition.
216 ET_INT
, // Integer elements.
217 ET_FP
// Floating-point elements.
220 // Head model used for calculating the impulse delays.
223 HM_DATASET
, // Measure the onset from the dataset.
224 HM_SPHERE
// Calculate the onset using a spherical head model.
227 // Desired output format from the command line.
230 OF_MHR
, // OpenAL Soft MHR data set file.
231 OF_TABLE
// OpenAL Soft built-in table file (used when compiling).
234 // Unsigned integer type.
235 typedef unsigned int uint
;
237 // Serialization types. The trailing digit indicates the number of bits.
238 typedef ALubyte uint8
;
241 typedef ALuint uint32
;
242 typedef ALuint64SOFT uint64
;
244 typedef enum ByteOrderT ByteOrderT
;
245 typedef enum SourceFormatT SourceFormatT
;
246 typedef enum ElementTypeT ElementTypeT
;
247 typedef enum HeadModelT HeadModelT
;
248 typedef enum OutputFormatT OutputFormatT
;
250 typedef struct TokenReaderT TokenReaderT
;
251 typedef struct SourceRefT SourceRefT
;
252 typedef struct HrirDataT HrirDataT
;
253 typedef struct ResamplerT ResamplerT
;
255 // Token reader state for parsing the data set definition.
256 struct TokenReaderT
{
261 char mRing
[TR_RING_SIZE
];
266 // Source reference state used when loading sources.
268 SourceFormatT mFormat
;
275 char mPath
[MAX_PATH_LEN
+ 1];
278 // The HRIR metrics and data set used when loading, processing, and storing
279 // the resulting HRTF.
288 mAzCount
[MAX_EV_COUNT
],
289 mEvOffset
[MAX_EV_COUNT
];
297 // The resampler metrics and FIR filter.
306 /* Token reader routines for parsing text files. Whitespace is not
307 * significant. It can process tokens as identifiers, numbers (integer and
308 * floating-point), strings, and operators. Strings must be encapsulated by
309 * double-quotes and cannot span multiple lines.
312 // Setup the reader on the given file. The filename can be NULL if no error
313 // output is desired.
314 static void TrSetup (FILE * fp
, const char * filename
, TokenReaderT
* tr
) {
315 const char * name
= NULL
;
320 // If a filename was given, store a pointer to the base name.
321 if (filename
!= NULL
) {
322 while ((ch
= (* filename
)) != '\0') {
323 if ((ch
== '/') || (ch
== '\\'))
335 // Prime the reader's ring buffer, and return a result indicating that there
336 // is text to process.
337 static int TrLoad (TokenReaderT
* tr
) {
338 size_t toLoad
, in
, count
;
340 toLoad
= TR_RING_SIZE
- (tr
-> mIn
- tr
-> mOut
);
341 if ((toLoad
>= TR_LOAD_SIZE
) && (! feof (tr
-> mFile
))) {
342 // Load TR_LOAD_SIZE (or less if at the end of the file) per read.
343 toLoad
= TR_LOAD_SIZE
;
344 in
= tr
-> mIn
& TR_RING_MASK
;
345 count
= TR_RING_SIZE
- in
;
346 if (count
< toLoad
) {
347 tr
-> mIn
+= fread (& tr
-> mRing
[in
], 1, count
, tr
-> mFile
);
348 tr
-> mIn
+= fread (& tr
-> mRing
[0], 1, toLoad
- count
, tr
-> mFile
);
350 tr
-> mIn
+= fread (& tr
-> mRing
[in
], 1, toLoad
, tr
-> mFile
);
352 if (tr
-> mOut
>= TR_RING_SIZE
) {
353 tr
-> mOut
-= TR_RING_SIZE
;
354 tr
-> mIn
-= TR_RING_SIZE
;
357 if (tr
-> mIn
> tr
-> mOut
)
362 // Error display routine. Only displays when the base name is not NULL.
363 static void TrErrorVA (const TokenReaderT
* tr
, uint line
, uint column
, const char * format
, va_list argPtr
) {
364 if (tr
-> mName
!= NULL
) {
365 fprintf (stderr
, "Error (%s:%u:%u): ", tr
-> mName
, line
, column
);
366 vfprintf (stderr
, format
, argPtr
);
370 // Used to display an error at a saved line/column.
371 static void TrErrorAt (const TokenReaderT
* tr
, uint line
, uint column
, const char * format
, ...) {
374 va_start (argPtr
, format
);
375 TrErrorVA (tr
, line
, column
, format
, argPtr
);
379 // Used to display an error at the current line/column.
380 static void TrError (const TokenReaderT
* tr
, const char * format
, ...) {
383 va_start (argPtr
, format
);
384 TrErrorVA (tr
, tr
-> mLine
, tr
-> mColumn
, format
, argPtr
);
388 // Skips to the next line.
389 static void TrSkipLine (TokenReaderT
* tr
) {
392 while (TrLoad (tr
)) {
393 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
404 // Skips to the next token.
405 static int TrSkipWhitespace (TokenReaderT
* tr
) {
408 while (TrLoad (tr
)) {
409 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
418 } else if (ch
== '#') {
427 // Get the line and/or column of the next token (or the end of input).
428 static void TrIndication (TokenReaderT
* tr
, uint
* line
, uint
* column
) {
429 TrSkipWhitespace (tr
);
431 (* line
) = tr
-> mLine
;
433 (* column
) = tr
-> mColumn
;
436 // Checks to see if a token is the given operator. It does not display any
437 // errors and will not proceed to the next token.
438 static int TrIsOperator (TokenReaderT
* tr
, const char * op
) {
442 if (! TrSkipWhitespace (tr
))
446 while ((op
[len
] != '\0') && (out
< tr
-> mIn
)) {
447 ch
= tr
-> mRing
[out
& TR_RING_MASK
];
453 if (op
[len
] == '\0')
458 /* The TrRead*() routines obtain the value of a matching token type. They
459 * display type, form, and boundary errors and will proceed to the next
463 // Reads and validates an identifier token.
464 static int TrReadIdent (TokenReaderT
* tr
, const uint maxLen
, char * ident
) {
469 if (TrSkipWhitespace (tr
)) {
471 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
472 if ((ch
== '_') || isalpha (ch
)) {
481 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
482 } while ((ch
== '_') || isdigit (ch
) || isalpha (ch
));
483 tr
-> mColumn
+= len
;
485 TrErrorAt (tr
, tr
-> mLine
, col
, "Identifier is too long.\n");
492 TrErrorAt (tr
, tr
-> mLine
, col
, "Expected an identifier.\n");
496 // Reads and validates (including bounds) an integer token.
497 static int TrReadInt (TokenReaderT
* tr
, const int loBound
, const int hiBound
, int * value
) {
498 uint col
, digis
, len
;
499 char ch
, temp
[64 + 1];
502 if (TrSkipWhitespace (tr
)) {
505 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
506 if ((ch
== '+') || (ch
== '-')) {
512 while (TrLoad (tr
)) {
513 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
522 tr
-> mColumn
+= len
;
523 if ((digis
> 0) && (ch
!= '.') && (! isalpha (ch
))) {
525 TrErrorAt (tr
, tr
-> mLine
, col
, "Integer is too long.");
529 (* value
) = strtol (temp
, NULL
, 10);
530 if (((* value
) < loBound
) || ((* value
) > hiBound
)) {
531 TrErrorAt (tr
, tr
-> mLine
, col
, "Expected a value from %d to %d.\n", loBound
, hiBound
);
537 TrErrorAt (tr
, tr
-> mLine
, col
, "Expected an integer.\n");
541 // Reads and validates (including bounds) a float token.
542 static int TrReadFloat (TokenReaderT
* tr
, const double loBound
, const double hiBound
, double * value
) {
543 uint col
, digis
, len
;
544 char ch
, temp
[64 + 1];
547 if (TrSkipWhitespace (tr
)) {
550 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
551 if ((ch
== '+') || (ch
== '-')) {
557 while (TrLoad (tr
)) {
558 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
573 while (TrLoad (tr
)) {
574 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
584 if ((ch
== 'E') || (ch
== 'e')) {
590 if ((ch
== '+') || (ch
== '-')) {
596 while (TrLoad (tr
)) {
597 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
607 tr
-> mColumn
+= len
;
608 if ((digis
> 0) && (ch
!= '.') && (! isalpha (ch
))) {
610 TrErrorAt (tr
, tr
-> mLine
, col
, "Float is too long.");
614 (* value
) = strtod (temp
, NULL
);
615 if (((* value
) < loBound
) || ((* value
) > hiBound
)) {
616 TrErrorAt (tr
, tr
-> mLine
, col
, "Expected a value from %f to %f.\n", loBound
, hiBound
);
622 tr
-> mColumn
+= len
;
625 TrErrorAt (tr
, tr
-> mLine
, col
, "Expected a float.\n");
629 // Reads and validates a string token.
630 static int TrReadString (TokenReaderT
* tr
, const uint maxLen
, char * text
) {
635 if (TrSkipWhitespace (tr
)) {
637 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
641 while (TrLoad (tr
)) {
642 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
647 TrErrorAt (tr
, tr
-> mLine
, col
, "Unterminated string at end of line.\n");
655 tr
-> mColumn
+= 1 + len
;
656 TrErrorAt (tr
, tr
-> mLine
, col
, "Unterminated string at end of input.\n");
659 tr
-> mColumn
+= 2 + len
;
661 TrErrorAt (tr
, tr
-> mLine
, col
, "String is too long.\n");
668 TrErrorAt (tr
, tr
-> mLine
, col
, "Expected a string.\n");
672 // Reads and validates the given operator.
673 static int TrReadOperator (TokenReaderT
* tr
, const char * op
) {
678 if (TrSkipWhitespace (tr
)) {
681 while ((op
[len
] != '\0') && TrLoad (tr
)) {
682 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
688 tr
-> mColumn
+= len
;
689 if (op
[len
] == '\0')
692 TrErrorAt (tr
, tr
-> mLine
, col
, "Expected '%s' operator.\n", op
);
696 /* Performs a string substitution. Any case-insensitive occurrences of the
697 * pattern string are replaced with the replacement string. The result is
698 * truncated if necessary.
700 static int StrSubst (const char * in
, const char * pat
, const char * rep
, const size_t maxLen
, char * out
) {
701 size_t inLen
, patLen
, repLen
;
706 patLen
= strlen (pat
);
707 repLen
= strlen (rep
);
711 while ((si
< inLen
) && (di
< maxLen
)) {
712 if (patLen
<= (inLen
- si
)) {
713 if (strncasecmp (& in
[si
], pat
, patLen
) == 0) {
714 if (repLen
> (maxLen
- di
)) {
715 repLen
= maxLen
- di
;
718 strncpy (& out
[di
], rep
, repLen
);
730 return (! truncated
);
733 // Provide missing math routines for MSVC versions < 1800 (Visual Studio 2013).
734 #if defined(_MSC_VER) && _MSC_VER < 1800
735 static double round (double val
) {
737 return (ceil (val
- 0.5));
738 return (floor (val
+ 0.5));
741 static double fmin (double a
, double b
) {
742 return ((a
< b
) ? a
: b
);
745 static double fmax (double a
, double b
) {
746 return ((a
> b
) ? a
: b
);
750 // Simple clamp routine.
751 static double Clamp (const double val
, const double lower
, const double upper
) {
752 return (fmin (fmax (val
, lower
), upper
));
755 // Performs linear interpolation.
756 static double Lerp (const double a
, const double b
, const double f
) {
757 return (a
+ (f
* (b
- a
)));
760 // Performs a high-passed triangular probability density function dither from
761 // a double to an integer. It assumes the input sample is already scaled.
762 static int HpTpdfDither (const double in
, int * hpHist
) {
763 const double PRNG_SCALE
= 1.0 / (RAND_MAX
+ 1.0);
768 out
= round (in
+ (PRNG_SCALE
* (prn
- (* hpHist
))));
773 // Allocates an array of doubles.
774 static double *CreateArray(size_t n
)
779 a
= calloc(n
, sizeof(double));
782 fprintf(stderr
, "Error: Out of memory.\n");
788 // Frees an array of doubles.
789 static void DestroyArray(double *a
)
792 // Complex number routines. All outputs must be non-NULL.
794 // Magnitude/absolute value.
795 static double ComplexAbs (const double r
, const double i
) {
796 return (sqrt ((r
* r
) + (i
* i
)));
800 static void ComplexMul (const double aR
, const double aI
, const double bR
, const double bI
, double * outR
, double * outI
) {
801 (* outR
) = (aR
* bR
) - (aI
* bI
);
802 (* outI
) = (aI
* bR
) + (aR
* bI
);
806 static void ComplexExp (const double inR
, const double inI
, double * outR
, double * outI
) {
810 (* outR
) = e
* cos (inI
);
811 (* outI
) = e
* sin (inI
);
814 /* Fast Fourier transform routines. The number of points must be a power of
815 * two. In-place operation is possible only if both the real and imaginary
816 * parts are in-place together.
819 // Performs bit-reversal ordering.
820 static void FftArrange (const uint n
, const double * inR
, const double * inI
, double * outR
, double * outI
) {
824 if ((inR
== outR
) && (inI
== outI
)) {
825 // Handle in-place arrangement.
827 for (k
= 0; k
< n
; k
++) {
837 while (rk
& (m
>>= 1))
842 // Handle copy arrangement.
844 for (k
= 0; k
< n
; k
++) {
848 while (rk
& (m
>>= 1))
855 // Performs the summation.
856 static void FftSummation (const uint n
, const double s
, double * re
, double * im
) {
859 double vR
, vI
, wR
, wI
;
864 for (m
= 1, m2
= 2; m
< n
; m
<<= 1, m2
<<= 1) {
865 // v = Complex (-2.0 * sin (0.5 * pi / m) * sin (0.5 * pi / m), -sin (pi / m))
866 vR
= sin (0.5 * pi
/ m
);
869 // w = Complex (1.0, 0.0)
872 for (i
= 0; i
< m
; i
++) {
873 for (k
= i
; k
< n
; k
+= m2
) {
875 // t = ComplexMul (w, out [km2])
876 tR
= (wR
* re
[mk
]) - (wI
* im
[mk
]);
877 tI
= (wR
* im
[mk
]) + (wI
* re
[mk
]);
878 // out [mk] = ComplexSub (out [k], t)
879 re
[mk
] = re
[k
] - tR
;
880 im
[mk
] = im
[k
] - tI
;
881 // out [k] = ComplexAdd (out [k], t)
885 // t = ComplexMul (v, w)
886 tR
= (vR
* wR
) - (vI
* wI
);
887 tI
= (vR
* wI
) + (vI
* wR
);
888 // w = ComplexAdd (w, t)
895 // Performs a forward FFT.
896 static void FftForward (const uint n
, const double * inR
, const double * inI
, double * outR
, double * outI
) {
897 FftArrange (n
, inR
, inI
, outR
, outI
);
898 FftSummation (n
, 1.0, outR
, outI
);
901 // Performs an inverse FFT.
902 static void FftInverse (const uint n
, const double * inR
, const double * inI
, double * outR
, double * outI
) {
906 FftArrange (n
, inR
, inI
, outR
, outI
);
907 FftSummation (n
, -1.0, outR
, outI
);
909 for (i
= 0; i
< n
; i
++) {
915 /* Calculate the complex helical sequence (or discrete-time analytical
916 * signal) of the given input using the Hilbert transform. Given the
917 * negative natural logarithm of a signal's magnitude response, the imaginary
918 * components can be used as the angles for minimum-phase reconstruction.
920 static void Hilbert (const uint n
, const double * in
, double * outR
, double * outI
) {
924 // Handle in-place operation.
925 for (i
= 0; i
< n
; i
++)
928 // Handle copy operation.
929 for (i
= 0; i
< n
; i
++) {
934 FftForward (n
, outR
, outI
, outR
, outI
);
935 /* Currently the Fourier routines operate only on point counts that are
936 * powers of two. If that changes and n is odd, the following conditional
937 * should be: i < (n + 1) / 2.
939 for (i
= 1; i
< (n
/ 2); i
++) {
943 // If n is odd, the following increment should be skipped.
945 for (; i
< n
; i
++) {
949 FftInverse (n
, outR
, outI
, outR
, outI
);
952 /* Calculate the magnitude response of the given input. This is used in
953 * place of phase decomposition, since the phase residuals are discarded for
954 * minimum phase reconstruction. The mirrored half of the response is also
957 static void MagnitudeResponse (const uint n
, const double * inR
, const double * inI
, double * out
) {
958 const uint m
= 1 + (n
/ 2);
961 for (i
= 0; i
< m
; i
++)
962 out
[i
] = fmax (ComplexAbs (inR
[i
], inI
[i
]), EPSILON
);
965 /* Apply a range limit (in dB) to the given magnitude response. This is used
966 * to adjust the effects of the diffuse-field average on the equalization
969 static void LimitMagnitudeResponse (const uint n
, const double limit
, const double * in
, double * out
) {
970 const uint m
= 1 + (n
/ 2);
972 uint i
, lower
, upper
;
975 halfLim
= limit
/ 2.0;
976 // Convert the response to dB.
977 for (i
= 0; i
< m
; i
++)
978 out
[i
] = 20.0 * log10 (in
[i
]);
979 // Use six octaves to calculate the average magnitude of the signal.
980 lower
= ((uint
) ceil (n
/ pow (2.0, 8.0))) - 1;
981 upper
= ((uint
) floor (n
/ pow (2.0, 2.0))) - 1;
983 for (i
= lower
; i
<= upper
; i
++)
985 ave
/= upper
- lower
+ 1;
986 // Keep the response within range of the average magnitude.
987 for (i
= 0; i
< m
; i
++)
988 out
[i
] = Clamp (out
[i
], ave
- halfLim
, ave
+ halfLim
);
989 // Convert the response back to linear magnitude.
990 for (i
= 0; i
< m
; i
++)
991 out
[i
] = pow (10.0, out
[i
] / 20.0);
994 /* Reconstructs the minimum-phase component for the given magnitude response
995 * of a signal. This is equivalent to phase recomposition, sans the missing
996 * residuals (which were discarded). The mirrored half of the response is
999 static void MinimumPhase (const uint n
, const double * in
, double * outR
, double * outI
) {
1000 const uint m
= 1 + (n
/ 2);
1001 double * mags
= NULL
;
1005 mags
= CreateArray (n
);
1006 for (i
= 0; i
< m
; i
++) {
1007 mags
[i
] = fmax (in
[i
], EPSILON
);
1008 outR
[i
] = -log (mags
[i
]);
1010 for (; i
< n
; i
++) {
1011 mags
[i
] = mags
[n
- i
];
1012 outR
[i
] = outR
[n
- i
];
1014 Hilbert (n
, outR
, outR
, outI
);
1015 // Remove any DC offset the filter has.
1018 for (i
= 1; i
< n
; i
++) {
1019 ComplexExp (0.0, outI
[i
], & aR
, & aI
);
1020 ComplexMul (mags
[i
], 0.0, aR
, aI
, & outR
[i
], & outI
[i
]);
1022 DestroyArray (mags
);
1025 /* This is the normalized cardinal sine (sinc) function.
1027 * sinc(x) = { 1, x = 0
1028 * { sin(pi x) / (pi x), otherwise.
1030 static double Sinc (const double x
) {
1031 if (fabs (x
) < EPSILON
)
1033 return (sin (M_PI
* x
) / (M_PI
* x
));
1036 /* The zero-order modified Bessel function of the first kind, used for the
1039 * I_0(x) = sum_{k=0}^inf (1 / k!)^2 (x / 2)^(2 k)
1040 * = sum_{k=0}^inf ((x / 2)^k / k!)^2
1042 static double BesselI_0 (const double x
) {
1043 double term
, sum
, x2
, y
, last_sum
;
1046 // Start at k=1 since k=0 is trivial.
1051 // Let the integration converge until the term of the sum is no longer
1059 } while (sum
!= last_sum
);
1063 /* Calculate a Kaiser window from the given beta value and a normalized k
1066 * w(k) = { I_0(B sqrt(1 - k^2)) / I_0(B), -1 <= k <= 1
1069 * Where k can be calculated as:
1071 * k = i / l, where -l <= i <= l.
1075 * k = 2 i / M - 1, where 0 <= i <= M.
1077 static double Kaiser (const double b
, const double k
) {
1080 k2
= Clamp (k
, -1.0, 1.0);
1081 if ((k
< -1.0) || (k
> 1.0))
1084 return (BesselI_0 (b
* sqrt (1.0 - k2
)) / BesselI_0 (b
));
1087 // Calculates the greatest common divisor of a and b.
1088 static uint
Gcd (const uint a
, const uint b
) {
1101 /* Calculates the size (order) of the Kaiser window. Rejection is in dB and
1102 * the transition width is normalized frequency (0.5 is nyquist).
1104 * M = { ceil((r - 7.95) / (2.285 2 pi f_t)), r > 21
1105 * { ceil(5.79 / 2 pi f_t), r <= 21.
1108 static uint
CalcKaiserOrder (const double rejection
, const double transition
) {
1111 w_t
= 2.0 * M_PI
* transition
;
1112 if (rejection
> 21.0)
1113 return ((uint
) ceil ((rejection
- 7.95) / (2.285 * w_t
)));
1114 return ((uint
) ceil (5.79 / w_t
));
1117 // Calculates the beta value of the Kaiser window. Rejection is in dB.
1118 static double CalcKaiserBeta (const double rejection
) {
1119 if (rejection
> 50.0)
1120 return (0.1102 * (rejection
- 8.7));
1121 else if (rejection
>= 21.0)
1122 return ((0.5842 * pow (rejection
- 21.0, 0.4)) +
1123 (0.07886 * (rejection
- 21.0)));
1128 /* Calculates a point on the Kaiser-windowed sinc filter for the given half-
1129 * width, beta, gain, and cutoff. The point is specified in non-normalized
1130 * samples, from 0 to M, where M = (2 l + 1).
1132 * w(k) 2 p f_t sinc(2 f_t x)
1134 * x -- centered sample index (i - l)
1135 * k -- normalized and centered window index (x / l)
1136 * w(k) -- window function (Kaiser)
1137 * p -- gain compensation factor when sampling
1138 * f_t -- normalized center frequency (or cutoff; 0.5 is nyquist)
1140 static double SincFilter (const int l
, const double b
, const double gain
, const double cutoff
, const int i
) {
1141 return (Kaiser (b
, ((double) (i
- l
)) / l
) * 2.0 * gain
* cutoff
* Sinc (2.0 * cutoff
* (i
- l
)));
1144 /* This is a polyphase sinc-filtered resampler.
1146 * Upsample Downsample
1148 * p/q = 3/2 p/q = 3/5
1150 * M-+-+-+-> M-+-+-+->
1151 * -------------------+ ---------------------+
1152 * p s * f f f f|f| | p s * f f f f f |
1153 * | 0 * 0 0 0|0|0 | | 0 * 0 0 0 0|0| |
1154 * v 0 * 0 0|0|0 0 | v 0 * 0 0 0|0|0 |
1155 * s * f|f|f f f | s * f f|f|f f |
1156 * 0 * |0|0 0 0 0 | 0 * 0|0|0 0 0 |
1157 * --------+=+--------+ 0 * |0|0 0 0 0 |
1158 * d . d .|d|. d . d ----------+=+--------+
1159 * d . . . .|d|. . . .
1163 * P_f(i,j) = q i mod p + pj
1164 * P_s(i,j) = floor(q i / p) - j
1165 * d[i=0..N-1] = sum_{j=0}^{floor((M - 1) / p)} {
1166 * { f[P_f(i,j)] s[P_s(i,j)], P_f(i,j) < M
1167 * { 0, P_f(i,j) >= M. }
1170 // Calculate the resampling metrics and build the Kaiser-windowed sinc filter
1171 // that's used to cut frequencies above the destination nyquist.
1172 static void ResamplerSetup (ResamplerT
* rs
, const uint srcRate
, const uint dstRate
) {
1174 double cutoff
, width
, beta
;
1177 gcd
= Gcd (srcRate
, dstRate
);
1178 rs
-> mP
= dstRate
/ gcd
;
1179 rs
-> mQ
= srcRate
/ gcd
;
1180 /* The cutoff is adjusted by half the transition width, so the transition
1181 * ends before the nyquist (0.5). Both are scaled by the downsampling
1184 if (rs
-> mP
> rs
-> mQ
) {
1185 cutoff
= 0.45 / rs
-> mP
;
1186 width
= 0.1 / rs
-> mP
;
1188 cutoff
= 0.45 / rs
-> mQ
;
1189 width
= 0.1 / rs
-> mQ
;
1191 // A rejection of -180 dB is used for the stop band.
1192 l
= CalcKaiserOrder (180.0, width
) / 2;
1193 beta
= CalcKaiserBeta (180.0);
1194 rs
-> mM
= (2 * l
) + 1;
1196 rs
-> mF
= CreateArray (rs
-> mM
);
1197 for (i
= 0; i
< ((int) rs
-> mM
); i
++)
1198 rs
-> mF
[i
] = SincFilter ((int) l
, beta
, rs
-> mP
, cutoff
, i
);
1201 // Clean up after the resampler.
1202 static void ResamplerClear (ResamplerT
* rs
) {
1203 DestroyArray (rs
-> mF
);
1207 // Perform the upsample-filter-downsample resampling operation using a
1208 // polyphase filter implementation.
1209 static void ResamplerRun (ResamplerT
* rs
, const uint inN
, const double * in
, const uint outN
, double * out
) {
1210 const uint p
= rs
-> mP
, q
= rs
-> mQ
, m
= rs
-> mM
, l
= rs
-> mL
;
1211 const double * f
= rs
-> mF
;
1212 double * work
= NULL
;
1220 // Handle in-place operation.
1222 work
= CreateArray (outN
);
1225 // Resample the input.
1226 for (i
= 0; i
< outN
; i
++) {
1228 // Input starts at l to compensate for the filter delay. This will
1229 // drop any build-up from the first half of the filter.
1230 j_f
= (l
+ (q
* i
)) % p
;
1231 j_s
= (l
+ (q
* i
)) / p
;
1233 // Only take input when 0 <= j_s < inN. This single unsigned
1234 // comparison catches both cases.
1236 r
+= f
[j_f
] * in
[j_s
];
1242 // Clean up after in-place operation.
1244 for (i
= 0; i
< outN
; i
++)
1246 DestroyArray (work
);
1250 // Read a binary value of the specified byte order and byte size from a file,
1251 // storing it as a 32-bit unsigned integer.
1252 static int ReadBin4 (FILE * fp
, const char * filename
, const ByteOrderT order
, const uint bytes
, uint32
* out
) {
1257 if (fread (in
, 1, bytes
, fp
) != bytes
) {
1258 fprintf (stderr
, "Error: Bad read from file '%s'.\n", filename
);
1264 for (i
= 0; i
< bytes
; i
++)
1265 accum
= (accum
<< 8) | in
[bytes
- i
- 1];
1268 for (i
= 0; i
< bytes
; i
++)
1269 accum
= (accum
<< 8) | in
[i
];
1278 // Read a binary value of the specified byte order from a file, storing it as
1279 // a 64-bit unsigned integer.
1280 static int ReadBin8 (FILE * fp
, const char * filename
, const ByteOrderT order
, uint64
* out
) {
1285 if (fread (in
, 1, 8, fp
) != 8) {
1286 fprintf (stderr
, "Error: Bad read from file '%s'.\n", filename
);
1292 for (i
= 0; i
< 8; i
++)
1293 accum
= (accum
<< 8) | in
[8 - i
- 1];
1296 for (i
= 0; i
< 8; i
++)
1297 accum
= (accum
<< 8) | in
[i
];
1306 // Write an ASCII string to a file.
1307 static int WriteAscii (const char * out
, FILE * fp
, const char * filename
) {
1311 if (fwrite (out
, 1, len
, fp
) != len
) {
1313 fprintf (stderr
, "Error: Bad write to file '%s'.\n", filename
);
1319 // Write a binary value of the given byte order and byte size to a file,
1320 // loading it from a 32-bit unsigned integer.
1321 static int WriteBin4 (const ByteOrderT order
, const uint bytes
, const uint32 in
, FILE * fp
, const char * filename
) {
1327 for (i
= 0; i
< bytes
; i
++)
1328 out
[i
] = (in
>> (i
* 8)) & 0x000000FF;
1331 for (i
= 0; i
< bytes
; i
++)
1332 out
[bytes
- i
- 1] = (in
>> (i
* 8)) & 0x000000FF;
1337 if (fwrite (out
, 1, bytes
, fp
) != bytes
) {
1338 fprintf (stderr
, "Error: Bad write to file '%s'.\n", filename
);
1344 /* Read a binary value of the specified type, byte order, and byte size from
1345 * a file, converting it to a double. For integer types, the significant
1346 * bits are used to normalize the result. The sign of bits determines
1347 * whether they are padded toward the MSB (negative) or LSB (positive).
1348 * Floating-point types are not normalized.
1350 static int ReadBinAsDouble (FILE * fp
, const char * filename
, const ByteOrderT order
, const ElementTypeT type
, const uint bytes
, const int bits
, double * out
) {
1363 if (! ReadBin8 (fp
, filename
, order
, & v8
. ui
))
1368 if (! ReadBin4 (fp
, filename
, order
, bytes
, & v4
. ui
))
1370 if (type
== ET_FP
) {
1371 (* out
) = (double) v4
. f
;
1374 v4
. ui
>>= (8 * bytes
) - ((uint
) bits
);
1376 v4
. ui
&= (0xFFFFFFFF >> (32 + bits
));
1377 if (v4
. ui
& ((uint
) (1 << (abs (bits
) - 1))))
1378 v4
. ui
|= (0xFFFFFFFF << abs (bits
));
1379 (* out
) = v4
. i
/ ((double) (1 << (abs (bits
) - 1)));
1385 /* Read an ascii value of the specified type from a file, converting it to a
1386 * double. For integer types, the significant bits are used to normalize the
1387 * result. The sign of the bits should always be positive. This also skips
1388 * up to one separator character before the element itself.
1390 static int ReadAsciiAsDouble (TokenReaderT
* tr
, const char * filename
, const ElementTypeT type
, const uint bits
, double * out
) {
1393 if (TrIsOperator (tr
, ","))
1394 TrReadOperator (tr
, ",");
1395 else if (TrIsOperator (tr
, ":"))
1396 TrReadOperator (tr
, ":");
1397 else if (TrIsOperator (tr
, ";"))
1398 TrReadOperator (tr
, ";");
1399 else if (TrIsOperator (tr
, "|"))
1400 TrReadOperator (tr
, "|");
1401 if (type
== ET_FP
) {
1402 if (! TrReadFloat (tr
, -HUGE_VAL
, HUGE_VAL
, out
)) {
1403 fprintf (stderr
, "Error: Bad read from file '%s'.\n", filename
);
1407 if (! TrReadInt (tr
, -(1 << (bits
- 1)), (1 << (bits
- 1)) - 1, & v
)) {
1408 fprintf (stderr
, "Error: Bad read from file '%s'.\n", filename
);
1411 (* out
) = v
/ ((double) ((1 << (bits
- 1)) - 1));
1416 // Read the RIFF/RIFX WAVE format chunk from a file, validating it against
1417 // the source parameters and data set metrics.
1418 static int ReadWaveFormat (FILE * fp
, const ByteOrderT order
, const uint hrirRate
, SourceRefT
* src
) {
1419 uint32 fourCC
, chunkSize
;
1420 uint32 format
, channels
, rate
, dummy
, block
, size
, bits
;
1425 fseek (fp
, (long) chunkSize
, SEEK_CUR
);
1426 if ((! ReadBin4 (fp
, src
-> mPath
, BO_LITTLE
, 4, & fourCC
)) ||
1427 (! ReadBin4 (fp
, src
-> mPath
, order
, 4, & chunkSize
)))
1429 } while (fourCC
!= FOURCC_FMT
);
1430 if ((! ReadBin4 (fp
, src
-> mPath
, order
, 2, & format
)) ||
1431 (! ReadBin4 (fp
, src
-> mPath
, order
, 2, & channels
)) ||
1432 (! ReadBin4 (fp
, src
-> mPath
, order
, 4, & rate
)) ||
1433 (! ReadBin4 (fp
, src
-> mPath
, order
, 4, & dummy
)) ||
1434 (! ReadBin4 (fp
, src
-> mPath
, order
, 2, & block
)))
1437 if (chunkSize
> 14) {
1438 if (! ReadBin4 (fp
, src
-> mPath
, order
, 2, & size
))
1446 if (format
== WAVE_FORMAT_EXTENSIBLE
) {
1447 fseek (fp
, 2, SEEK_CUR
);
1448 if (! ReadBin4 (fp
, src
-> mPath
, order
, 2, & bits
))
1452 fseek (fp
, 4, SEEK_CUR
);
1453 if (! ReadBin4 (fp
, src
-> mPath
, order
, 2, & format
))
1455 fseek (fp
, (long) (chunkSize
- 26), SEEK_CUR
);
1459 fseek (fp
, (long) (chunkSize
- 16), SEEK_CUR
);
1461 fseek (fp
, (long) (chunkSize
- 14), SEEK_CUR
);
1463 if ((format
!= WAVE_FORMAT_PCM
) && (format
!= WAVE_FORMAT_IEEE_FLOAT
)) {
1464 fprintf (stderr
, "Error: Unsupported WAVE format in file '%s'.\n", src
-> mPath
);
1467 if (src
-> mChannel
>= channels
) {
1468 fprintf (stderr
, "Error: Missing source channel in WAVE file '%s'.\n", src
-> mPath
);
1471 if (rate
!= hrirRate
) {
1472 fprintf (stderr
, "Error: Mismatched source sample rate in WAVE file '%s'.\n", src
-> mPath
);
1475 if (format
== WAVE_FORMAT_PCM
) {
1476 if ((size
< 2) || (size
> 4)) {
1477 fprintf (stderr
, "Error: Unsupported sample size in WAVE file '%s'.\n", src
-> mPath
);
1480 if ((bits
< 16) || (bits
> (8 * size
))) {
1481 fprintf (stderr
, "Error: Bad significant bits in WAVE file '%s'.\n", src
-> mPath
);
1484 src
-> mType
= ET_INT
;
1486 if ((size
!= 4) && (size
!= 8)) {
1487 fprintf (stderr
, "Error: Unsupported sample size in WAVE file '%s'.\n", src
-> mPath
);
1490 src
-> mType
= ET_FP
;
1492 src
-> mSize
= size
;
1493 src
-> mBits
= (int) bits
;
1494 src
-> mSkip
= channels
;
1498 // Read a RIFF/RIFX WAVE data chunk, converting all elements to doubles.
1499 static int ReadWaveData (FILE * fp
, const SourceRefT
* src
, const ByteOrderT order
, const uint n
, double * hrir
) {
1500 int pre
, post
, skip
;
1503 pre
= (int) (src
-> mSize
* src
-> mChannel
);
1504 post
= (int) (src
-> mSize
* (src
-> mSkip
- src
-> mChannel
- 1));
1506 for (i
= 0; i
< n
; i
++) {
1509 fseek (fp
, skip
, SEEK_CUR
);
1510 if (! ReadBinAsDouble (fp
, src
-> mPath
, order
, src
-> mType
, src
-> mSize
, src
-> mBits
, & hrir
[i
]))
1515 fseek (fp
, skip
, SEEK_CUR
);
1519 // Read the RIFF/RIFX WAVE list or data chunk, converting all elements to
1521 static int ReadWaveList (FILE * fp
, const SourceRefT
* src
, const ByteOrderT order
, const uint n
, double * hrir
) {
1522 uint32 fourCC
, chunkSize
, listSize
, count
;
1523 uint block
, skip
, offset
, i
;
1527 if ((! ReadBin4 (fp
, src
-> mPath
, BO_LITTLE
, 4, & fourCC
)) ||
1528 (! ReadBin4 (fp
, src
-> mPath
, order
, 4, & chunkSize
)))
1530 if (fourCC
== FOURCC_DATA
) {
1531 block
= src
-> mSize
* src
-> mSkip
;
1532 count
= chunkSize
/ block
;
1533 if (count
< (src
-> mOffset
+ n
)) {
1534 fprintf (stderr
, "Error: Bad read from file '%s'.\n", src
-> mPath
);
1537 fseek (fp
, (long) (src
-> mOffset
* block
), SEEK_CUR
);
1538 if (! ReadWaveData (fp
, src
, order
, n
, & hrir
[0]))
1541 } else if (fourCC
== FOURCC_LIST
) {
1542 if (! ReadBin4 (fp
, src
-> mPath
, BO_LITTLE
, 4, & fourCC
))
1545 if (fourCC
== FOURCC_WAVL
)
1549 fseek (fp
, (long) chunkSize
, SEEK_CUR
);
1551 listSize
= chunkSize
;
1552 block
= src
-> mSize
* src
-> mSkip
;
1553 skip
= src
-> mOffset
;
1556 while ((offset
< n
) && (listSize
> 8)) {
1557 if ((! ReadBin4 (fp
, src
-> mPath
, BO_LITTLE
, 4, & fourCC
)) ||
1558 (! ReadBin4 (fp
, src
-> mPath
, order
, 4, & chunkSize
)))
1560 listSize
-= 8 + chunkSize
;
1561 if (fourCC
== FOURCC_DATA
) {
1562 count
= chunkSize
/ block
;
1564 fseek (fp
, (long) (skip
* block
), SEEK_CUR
);
1565 chunkSize
-= skip
* block
;
1568 if (count
> (n
- offset
))
1570 if (! ReadWaveData (fp
, src
, order
, count
, & hrir
[offset
]))
1572 chunkSize
-= count
* block
;
1574 lastSample
= hrir
[offset
- 1];
1579 } else if (fourCC
== FOURCC_SLNT
) {
1580 if (! ReadBin4 (fp
, src
-> mPath
, order
, 4, & count
))
1586 if (count
> (n
- offset
))
1588 for (i
= 0; i
< count
; i
++)
1589 hrir
[offset
+ i
] = lastSample
;
1597 fseek (fp
, (long) chunkSize
, SEEK_CUR
);
1600 fprintf (stderr
, "Error: Bad read from file '%s'.\n", src
-> mPath
);
1606 // Load a source HRIR from a RIFF/RIFX WAVE file.
1607 static int LoadWaveSource (FILE * fp
, SourceRefT
* src
, const uint hrirRate
, const uint n
, double * hrir
) {
1608 uint32 fourCC
, dummy
;
1611 if ((! ReadBin4 (fp
, src
-> mPath
, BO_LITTLE
, 4, & fourCC
)) ||
1612 (! ReadBin4 (fp
, src
-> mPath
, BO_LITTLE
, 4, & dummy
)))
1614 if (fourCC
== FOURCC_RIFF
) {
1616 } else if (fourCC
== FOURCC_RIFX
) {
1619 fprintf (stderr
, "Error: No RIFF/RIFX chunk in file '%s'.\n", src
-> mPath
);
1622 if (! ReadBin4 (fp
, src
-> mPath
, BO_LITTLE
, 4, & fourCC
))
1624 if (fourCC
!= FOURCC_WAVE
) {
1625 fprintf (stderr
, "Error: Not a RIFF/RIFX WAVE file '%s'.\n", src
-> mPath
);
1628 if (! ReadWaveFormat (fp
, order
, hrirRate
, src
))
1630 if (! ReadWaveList (fp
, src
, order
, n
, hrir
))
1635 // Load a source HRIR from a binary file.
1636 static int LoadBinarySource (FILE * fp
, const SourceRefT
* src
, const ByteOrderT order
, const uint n
, double * hrir
) {
1639 fseek (fp
, (long) src
-> mOffset
, SEEK_SET
);
1640 for (i
= 0; i
< n
; i
++) {
1641 if (! ReadBinAsDouble (fp
, src
-> mPath
, order
, src
-> mType
, src
-> mSize
, src
-> mBits
, & hrir
[i
]))
1643 if (src
-> mSkip
> 0)
1644 fseek (fp
, (long) src
-> mSkip
, SEEK_CUR
);
1649 // Load a source HRIR from an ASCII text file containing a list of elements
1650 // separated by whitespace or common list operators (',', ';', ':', '|').
1651 static int LoadAsciiSource (FILE * fp
, const SourceRefT
* src
, const uint n
, double * hrir
) {
1656 TrSetup (fp
, NULL
, & tr
);
1657 for (i
= 0; i
< src
-> mOffset
; i
++) {
1658 if (! ReadAsciiAsDouble (& tr
, src
-> mPath
, src
-> mType
, (uint
) src
-> mBits
, & dummy
))
1661 for (i
= 0; i
< n
; i
++) {
1662 if (! ReadAsciiAsDouble (& tr
, src
-> mPath
, src
-> mType
, (uint
) src
-> mBits
, & hrir
[i
]))
1664 for (j
= 0; j
< src
-> mSkip
; j
++) {
1665 if (! ReadAsciiAsDouble (& tr
, src
-> mPath
, src
-> mType
, (uint
) src
-> mBits
, & dummy
))
1672 // Load a source HRIR from a supported file type.
1673 static int LoadSource (SourceRefT
* src
, const uint hrirRate
, const uint n
, double * hrir
) {
1677 if (src
-> mFormat
== SF_ASCII
)
1678 fp
= fopen (src
-> mPath
, "r");
1680 fp
= fopen (src
-> mPath
, "rb");
1682 fprintf (stderr
, "Error: Could not open source file '%s'.\n", src
-> mPath
);
1685 if (src
-> mFormat
== SF_WAVE
)
1686 result
= LoadWaveSource (fp
, src
, hrirRate
, n
, hrir
);
1687 else if (src
-> mFormat
== SF_BIN_LE
)
1688 result
= LoadBinarySource (fp
, src
, BO_LITTLE
, n
, hrir
);
1689 else if (src
-> mFormat
== SF_BIN_BE
)
1690 result
= LoadBinarySource (fp
, src
, BO_BIG
, n
, hrir
);
1692 result
= LoadAsciiSource (fp
, src
, n
, hrir
);
1697 // Calculate the onset time of an HRIR and average it with any existing
1698 // timing for its elevation and azimuth.
1699 static void AverageHrirOnset (const double * hrir
, const double f
, const uint ei
, const uint ai
, const HrirDataT
* hData
) {
1704 n
= hData
-> mIrPoints
;
1705 for (i
= 0; i
< n
; i
++)
1706 mag
= fmax (fabs (hrir
[i
]), mag
);
1708 for (i
= 0; i
< n
; i
++) {
1709 if (fabs (hrir
[i
]) >= mag
)
1712 j
= hData
-> mEvOffset
[ei
] + ai
;
1713 hData
-> mHrtds
[j
] = Lerp (hData
-> mHrtds
[j
], ((double) i
) / hData
-> mIrRate
, f
);
1716 // Calculate the magnitude response of an HRIR and average it with any
1717 // existing responses for its elevation and azimuth.
1718 static void AverageHrirMagnitude (const double * hrir
, const double f
, const uint ei
, const uint ai
, const HrirDataT
* hData
) {
1719 double * re
= NULL
, * im
= NULL
;
1722 n
= hData
-> mFftSize
;
1723 re
= CreateArray (n
);
1724 im
= CreateArray (n
);
1725 for (i
= 0; i
< hData
-> mIrPoints
; i
++) {
1729 for (; i
< n
; i
++) {
1733 FftForward (n
, re
, im
, re
, im
);
1734 MagnitudeResponse (n
, re
, im
, re
);
1736 j
= (hData
-> mEvOffset
[ei
] + ai
) * hData
-> mIrSize
;
1737 for (i
= 0; i
< m
; i
++)
1738 hData
-> mHrirs
[j
+ i
] = Lerp (hData
-> mHrirs
[j
+ i
], re
[i
], f
);
1743 /* Calculate the contribution of each HRIR to the diffuse-field average based
1744 * on the area of its surface patch. All patches are centered at the HRIR
1745 * coordinates on the unit sphere and are measured by solid angle.
1747 static void CalculateDfWeights (const HrirDataT
* hData
, double * weights
) {
1749 double evs
, sum
, ev
, up_ev
, down_ev
, solidAngle
;
1751 evs
= 90.0 / (hData
-> mEvCount
- 1);
1753 for (ei
= hData
-> mEvStart
; ei
< hData
-> mEvCount
; ei
++) {
1754 // For each elevation, calculate the upper and lower limits of the
1756 ev
= -90.0 + (ei
* 2.0 * evs
);
1757 if (ei
< (hData
-> mEvCount
- 1))
1758 up_ev
= (ev
+ evs
) * M_PI
/ 180.0;
1762 down_ev
= (ev
- evs
) * M_PI
/ 180.0;
1764 down_ev
= -M_PI
/ 2.0;
1765 // Calculate the area of the patch band.
1766 solidAngle
= 2.0 * M_PI
* (sin (up_ev
) - sin (down_ev
));
1767 // Each weight is the area of one patch.
1768 weights
[ei
] = solidAngle
/ hData
-> mAzCount
[ei
];
1769 // Sum the total surface area covered by the HRIRs.
1772 // Normalize the weights given the total surface coverage.
1773 for (ei
= hData
-> mEvStart
; ei
< hData
-> mEvCount
; ei
++)
1774 weights
[ei
] /= sum
;
1777 /* Calculate the diffuse-field average from the given magnitude responses of
1778 * the HRIR set. Weighting can be applied to compensate for the varying
1779 * surface area covered by each HRIR. The final average can then be limited
1780 * by the specified magnitude range (in positive dB; 0.0 to skip).
1782 static void CalculateDiffuseFieldAverage (const HrirDataT
* hData
, const int weighted
, const double limit
, double * dfa
) {
1783 double * weights
= NULL
;
1784 uint ei
, ai
, count
, step
, start
, end
, m
, j
, i
;
1787 weights
= CreateArray (hData
-> mEvCount
);
1789 // Use coverage weighting to calculate the average.
1790 CalculateDfWeights (hData
, weights
);
1792 // If coverage weighting is not used, the weights still need to be
1793 // averaged by the number of HRIRs.
1795 for (ei
= hData
-> mEvStart
; ei
< hData
-> mEvCount
; ei
++)
1796 count
+= hData
-> mAzCount
[ei
];
1797 for (ei
= hData
-> mEvStart
; ei
< hData
-> mEvCount
; ei
++)
1798 weights
[ei
] = 1.0 / count
;
1800 ei
= hData
-> mEvStart
;
1802 step
= hData
-> mIrSize
;
1803 start
= hData
-> mEvOffset
[ei
] * step
;
1804 end
= hData
-> mIrCount
* step
;
1805 m
= 1 + (hData
-> mFftSize
/ 2);
1806 for (i
= 0; i
< m
; i
++)
1808 for (j
= start
; j
< end
; j
+= step
) {
1809 // Get the weight for this HRIR's contribution.
1810 weight
= weights
[ei
];
1811 // Add this HRIR's weighted power average to the total.
1812 for (i
= 0; i
< m
; i
++)
1813 dfa
[i
] += weight
* hData
-> mHrirs
[j
+ i
] * hData
-> mHrirs
[j
+ i
];
1814 // Determine the next weight to use.
1816 if (ai
>= hData
-> mAzCount
[ei
]) {
1821 // Finish the average calculation and keep it from being too small.
1822 for (i
= 0; i
< m
; i
++)
1823 dfa
[i
] = fmax (sqrt (dfa
[i
]), EPSILON
);
1824 // Apply a limit to the magnitude range of the diffuse-field average if
1827 LimitMagnitudeResponse (hData
-> mFftSize
, limit
, dfa
, dfa
);
1828 DestroyArray (weights
);
1831 // Perform diffuse-field equalization on the magnitude responses of the HRIR
1832 // set using the given average response.
1833 static void DiffuseFieldEqualize (const double * dfa
, const HrirDataT
* hData
) {
1834 uint step
, start
, end
, m
, j
, i
;
1836 step
= hData
-> mIrSize
;
1837 start
= hData
-> mEvOffset
[hData
-> mEvStart
] * step
;
1838 end
= hData
-> mIrCount
* step
;
1839 m
= 1 + (hData
-> mFftSize
/ 2);
1840 for (j
= start
; j
< end
; j
+= step
) {
1841 for (i
= 0; i
< m
; i
++)
1842 hData
-> mHrirs
[j
+ i
] /= dfa
[i
];
1846 // Perform minimum-phase reconstruction using the magnitude responses of the
1848 static void ReconstructHrirs (const HrirDataT
* hData
) {
1849 double * re
= NULL
, * im
= NULL
;
1850 uint step
, start
, end
, n
, j
, i
;
1852 step
= hData
-> mIrSize
;
1853 start
= hData
-> mEvOffset
[hData
-> mEvStart
] * step
;
1854 end
= hData
-> mIrCount
* step
;
1855 n
= hData
-> mFftSize
;
1856 re
= CreateArray (n
);
1857 im
= CreateArray (n
);
1858 for (j
= start
; j
< end
; j
+= step
) {
1859 MinimumPhase (n
, & hData
-> mHrirs
[j
], re
, im
);
1860 FftInverse (n
, re
, im
, re
, im
);
1861 for (i
= 0; i
< hData
-> mIrPoints
; i
++)
1862 hData
-> mHrirs
[j
+ i
] = re
[i
];
1868 // Resamples the HRIRs for use at the given sampling rate.
1869 static void ResampleHrirs (const uint rate
, HrirDataT
* hData
) {
1871 uint n
, step
, start
, end
, j
;
1873 ResamplerSetup (& rs
, hData
-> mIrRate
, rate
);
1874 n
= hData
-> mIrPoints
;
1875 step
= hData
-> mIrSize
;
1876 start
= hData
-> mEvOffset
[hData
-> mEvStart
] * step
;
1877 end
= hData
-> mIrCount
* step
;
1878 for (j
= start
; j
< end
; j
+= step
)
1879 ResamplerRun (& rs
, n
, & hData
-> mHrirs
[j
], n
, & hData
-> mHrirs
[j
]);
1880 ResamplerClear (& rs
);
1881 hData
-> mIrRate
= rate
;
1884 /* Given an elevation index and an azimuth, calculate the indices of the two
1885 * HRIRs that bound the coordinate along with a factor for calculating the
1886 * continous HRIR using interpolation.
1888 static void CalcAzIndices (const HrirDataT
* hData
, const uint ei
, const double az
, uint
* j0
, uint
* j1
, double * jf
) {
1892 af
= ((2.0 * M_PI
) + az
) * hData
-> mAzCount
[ei
] / (2.0 * M_PI
);
1893 ai
= ((uint
) af
) % hData
-> mAzCount
[ei
];
1895 (* j0
) = hData
-> mEvOffset
[ei
] + ai
;
1896 (* j1
) = hData
-> mEvOffset
[ei
] + ((ai
+ 1) % hData
-> mAzCount
[ei
]);
1900 // Synthesize any missing onset timings at the bottom elevations. This just
1901 // blends between slightly exaggerated known onsets. Not an accurate model.
1902 static void SynthesizeOnsets (HrirDataT
* hData
) {
1903 uint oi
, e
, a
, j0
, j1
;
1906 oi
= hData
-> mEvStart
;
1908 for (a
= 0; a
< hData
-> mAzCount
[oi
]; a
++)
1909 t
+= hData
-> mHrtds
[hData
-> mEvOffset
[oi
] + a
];
1910 hData
-> mHrtds
[0] = 1.32e-4 + (t
/ hData
-> mAzCount
[oi
]);
1911 for (e
= 1; e
< hData
-> mEvStart
; e
++) {
1912 of
= ((double) e
) / hData
-> mEvStart
;
1913 for (a
= 0; a
< hData
-> mAzCount
[e
]; a
++) {
1914 CalcAzIndices (hData
, oi
, a
* 2.0 * M_PI
/ hData
-> mAzCount
[e
], & j0
, & j1
, & jf
);
1915 hData
-> mHrtds
[hData
-> mEvOffset
[e
] + a
] = Lerp (hData
-> mHrtds
[0], Lerp (hData
-> mHrtds
[j0
], hData
-> mHrtds
[j1
], jf
), of
);
1920 /* Attempt to synthesize any missing HRIRs at the bottom elevations. Right
1921 * now this just blends the lowest elevation HRIRs together and applies some
1922 * attenuation and high frequency damping. It is a simple, if inaccurate
1925 static void SynthesizeHrirs (HrirDataT
* hData
) {
1926 uint oi
, a
, e
, step
, n
, i
, j
;
1930 double lp
[4], s0
, s1
;
1932 if (hData
-> mEvStart
<= 0)
1934 step
= hData
-> mIrSize
;
1935 oi
= hData
-> mEvStart
;
1936 n
= hData
-> mIrPoints
;
1937 for (i
= 0; i
< n
; i
++)
1938 hData
-> mHrirs
[i
] = 0.0;
1939 for (a
= 0; a
< hData
-> mAzCount
[oi
]; a
++) {
1940 j
= (hData
-> mEvOffset
[oi
] + a
) * step
;
1941 for (i
= 0; i
< n
; i
++)
1942 hData
-> mHrirs
[i
] += hData
-> mHrirs
[j
+ i
] / hData
-> mAzCount
[oi
];
1944 for (e
= 1; e
< hData
-> mEvStart
; e
++) {
1945 of
= ((double) e
) / hData
-> mEvStart
;
1946 b
= (1.0 - of
) * (3.5e-6 * hData
-> mIrRate
);
1947 for (a
= 0; a
< hData
-> mAzCount
[e
]; a
++) {
1948 j
= (hData
-> mEvOffset
[e
] + a
) * step
;
1949 CalcAzIndices (hData
, oi
, a
* 2.0 * M_PI
/ hData
-> mAzCount
[e
], & j0
, & j1
, & jf
);
1956 for (i
= 0; i
< n
; i
++) {
1957 s0
= hData
-> mHrirs
[i
];
1958 s1
= Lerp (hData
-> mHrirs
[j0
+ i
], hData
-> mHrirs
[j1
+ i
], jf
);
1959 s0
= Lerp (s0
, s1
, of
);
1960 lp
[0] = Lerp (s0
, lp
[0], b
);
1961 lp
[1] = Lerp (lp
[0], lp
[1], b
);
1962 lp
[2] = Lerp (lp
[1], lp
[2], b
);
1963 lp
[3] = Lerp (lp
[2], lp
[3], b
);
1964 hData
-> mHrirs
[j
+ i
] = lp
[3];
1968 b
= 3.5e-6 * hData
-> mIrRate
;
1973 for (i
= 0; i
< n
; i
++) {
1974 s0
= hData
-> mHrirs
[i
];
1975 lp
[0] = Lerp (s0
, lp
[0], b
);
1976 lp
[1] = Lerp (lp
[0], lp
[1], b
);
1977 lp
[2] = Lerp (lp
[1], lp
[2], b
);
1978 lp
[3] = Lerp (lp
[2], lp
[3], b
);
1979 hData
-> mHrirs
[i
] = lp
[3];
1981 hData
-> mEvStart
= 0;
1984 // The following routines assume a full set of HRIRs for all elevations.
1986 // Normalize the HRIR set and slightly attenuate the result.
1987 static void NormalizeHrirs (const HrirDataT
* hData
) {
1988 uint step
, end
, n
, j
, i
;
1991 step
= hData
-> mIrSize
;
1992 end
= hData
-> mIrCount
* step
;
1993 n
= hData
-> mIrPoints
;
1995 for (j
= 0; j
< end
; j
+= step
) {
1996 for (i
= 0; i
< n
; i
++)
1997 maxLevel
= fmax (fabs (hData
-> mHrirs
[j
+ i
]), maxLevel
);
1999 maxLevel
= 1.01 * maxLevel
;
2000 for (j
= 0; j
< end
; j
+= step
) {
2001 for (i
= 0; i
< n
; i
++)
2002 hData
-> mHrirs
[j
+ i
] /= maxLevel
;
2006 // Calculate the left-ear time delay using a spherical head model.
2007 static double CalcLTD (const double ev
, const double az
, const double rad
, const double dist
) {
2008 double azp
, dlp
, l
, al
;
2010 azp
= asin (cos (ev
) * sin (az
));
2011 dlp
= sqrt ((dist
* dist
) + (rad
* rad
) + (2.0 * dist
* rad
* sin (azp
)));
2012 l
= sqrt ((dist
* dist
) - (rad
* rad
));
2013 al
= (0.5 * M_PI
) + azp
;
2015 dlp
= l
+ (rad
* (al
- acos (rad
/ dist
)));
2016 return (dlp
/ 343.3);
2019 // Calculate the effective head-related time delays for each minimum-phase
2021 static void CalculateHrtds (const HeadModelT model
, const double radius
, HrirDataT
* hData
) {
2022 double minHrtd
, maxHrtd
;
2028 for (e
= 0; e
< hData
-> mEvCount
; e
++) {
2029 for (a
= 0; a
< hData
-> mAzCount
[e
]; a
++) {
2030 j
= hData
-> mEvOffset
[e
] + a
;
2031 if (model
== HM_DATASET
) {
2032 t
= hData
-> mHrtds
[j
] * radius
/ hData
-> mRadius
;
2034 t
= CalcLTD ((-90.0 + (e
* 180.0 / (hData
-> mEvCount
- 1))) * M_PI
/ 180.0,
2035 (a
* 360.0 / hData
-> mAzCount
[e
]) * M_PI
/ 180.0,
2036 radius
, hData
-> mDistance
);
2038 hData
-> mHrtds
[j
] = t
;
2039 maxHrtd
= fmax (t
, maxHrtd
);
2040 minHrtd
= fmin (t
, minHrtd
);
2044 for (j
= 0; j
< hData
-> mIrCount
; j
++)
2045 hData
-> mHrtds
[j
] -= minHrtd
;
2046 hData
-> mMaxHrtd
= maxHrtd
;
2049 // Store the OpenAL Soft HRTF data set.
2050 static int StoreMhr (const HrirDataT
* hData
, const char * filename
) {
2052 uint e
, step
, end
, n
, j
, i
;
2055 if ((fp
= fopen (filename
, "wb")) == NULL
) {
2056 fprintf (stderr
, "Error: Could not open MHR file '%s'.\n", filename
);
2059 if (! WriteAscii (MHR_FORMAT
, fp
, filename
))
2061 if (! WriteBin4 (BO_LITTLE
, 4, (uint32
) hData
-> mIrRate
, fp
, filename
))
2063 if (! WriteBin4 (BO_LITTLE
, 1, (uint32
) hData
-> mIrPoints
, fp
, filename
))
2065 if (! WriteBin4 (BO_LITTLE
, 1, (uint32
) hData
-> mEvCount
, fp
, filename
))
2067 for (e
= 0; e
< hData
-> mEvCount
; e
++) {
2068 if (! WriteBin4 (BO_LITTLE
, 1, (uint32
) hData
-> mAzCount
[e
], fp
, filename
))
2071 step
= hData
-> mIrSize
;
2072 end
= hData
-> mIrCount
* step
;
2073 n
= hData
-> mIrPoints
;
2075 for (j
= 0; j
< end
; j
+= step
) {
2077 for (i
= 0; i
< n
; i
++) {
2078 v
= HpTpdfDither (32767.0 * hData
-> mHrirs
[j
+ i
], & hpHist
);
2079 if (! WriteBin4 (BO_LITTLE
, 2, (uint32
) v
, fp
, filename
))
2083 for (j
= 0; j
< hData
-> mIrCount
; j
++) {
2084 v
= (int) fmin (round (hData
-> mIrRate
* hData
-> mHrtds
[j
]), MAX_HRTD
);
2085 if (! WriteBin4 (BO_LITTLE
, 1, (uint32
) v
, fp
, filename
))
2092 // Store the OpenAL Soft built-in table.
2093 static int StoreTable (const HrirDataT
* hData
, const char * filename
) {
2095 uint step
, end
, n
, j
, i
;
2097 char text
[128 + 1];
2099 if ((fp
= fopen (filename
, "wb")) == NULL
) {
2100 fprintf (stderr
, "Error: Could not open table file '%s'.\n", filename
);
2103 snprintf (text
, 128, "/* Elevation metrics */\n"
2104 "static const ALubyte defaultAzCount[%u] = { ", hData
-> mEvCount
);
2105 if (! WriteAscii (text
, fp
, filename
))
2107 for (i
= 0; i
< hData
-> mEvCount
; i
++) {
2108 snprintf (text
, 128, "%u, ", hData
-> mAzCount
[i
]);
2109 if (! WriteAscii (text
, fp
, filename
))
2112 snprintf (text
, 128, "};\n"
2113 "static const ALushort defaultEvOffset[%u] = { ", hData
-> mEvCount
);
2114 if (! WriteAscii (text
, fp
, filename
))
2116 for (i
= 0; i
< hData
-> mEvCount
; i
++) {
2117 snprintf (text
, 128, "%u, ", hData
-> mEvOffset
[i
]);
2118 if (! WriteAscii (text
, fp
, filename
))
2121 step
= hData
-> mIrSize
;
2122 end
= hData
-> mIrCount
* step
;
2123 n
= hData
-> mIrPoints
;
2124 snprintf (text
, 128, "};\n\n"
2125 "/* HRIR Coefficients */\n"
2126 "static const ALshort defaultCoeffs[%u] =\n{\n", hData
-> mIrCount
* n
);
2127 if (! WriteAscii (text
, fp
, filename
))
2130 for (j
= 0; j
< end
; j
+= step
) {
2131 if (! WriteAscii (" ", fp
, filename
))
2134 for (i
= 0; i
< n
; i
++) {
2135 v
= HpTpdfDither (32767.0 * hData
-> mHrirs
[j
+ i
], & hpHist
);
2136 snprintf (text
, 128, " %+d,", v
);
2137 if (! WriteAscii (text
, fp
, filename
))
2140 if (! WriteAscii ("\n", fp
, filename
))
2143 snprintf (text
, 128, "};\n\n"
2144 "/* HRIR Delays */\n"
2145 "static const ALubyte defaultDelays[%u] =\n{\n"
2146 " ", hData
-> mIrCount
);
2147 if (! WriteAscii (text
, fp
, filename
))
2149 for (j
= 0; j
< hData
-> mIrCount
; j
++) {
2150 v
= (int) fmin (round (hData
-> mIrRate
* hData
-> mHrtds
[j
]), MAX_HRTD
);
2151 snprintf (text
, 128, " %d,", v
);
2152 if (! WriteAscii (text
, fp
, filename
))
2155 if (! WriteAscii ("\n};\n\n"
2156 "/* Default HRTF Definition */\n", fp
, filename
))
2158 snprintf (text
, 128, "static const struct Hrtf DefaultHrtf = {\n"
2159 " %u, %u, %u, defaultAzCount, defaultEvOffset,\n",
2160 hData
-> mIrRate
, hData
-> mIrPoints
, hData
-> mEvCount
);
2161 if (! WriteAscii (text
, fp
, filename
))
2163 if (! WriteAscii (" defaultCoeffs, defaultDelays, NULL\n"
2164 "};\n", fp
, filename
))
2170 // Process the data set definition to read and validate the data set metrics.
2171 static int ProcessMetrics (TokenReaderT
* tr
, const uint fftSize
, const uint truncSize
, HrirDataT
* hData
) {
2172 char ident
[MAX_IDENT_LEN
+ 1];
2177 int hasRate
= 0, hasPoints
= 0, hasAzimuths
= 0;
2178 int hasRadius
= 0, hasDistance
= 0;
2180 while (! (hasRate
&& hasPoints
&& hasAzimuths
&& hasRadius
&& hasDistance
)) {
2181 TrIndication (tr
, & line
, & col
);
2182 if (! TrReadIdent (tr
, MAX_IDENT_LEN
, ident
))
2184 if (strcasecmp (ident
, "rate") == 0) {
2186 TrErrorAt (tr
, line
, col
, "Redefinition of 'rate'.\n");
2189 if (! TrReadOperator (tr
, "="))
2191 if (! TrReadInt (tr
, MIN_RATE
, MAX_RATE
, & intVal
))
2193 hData
-> mIrRate
= (uint
) intVal
;
2195 } else if (strcasecmp (ident
, "points") == 0) {
2197 TrErrorAt (tr
, line
, col
, "Redefinition of 'points'.\n");
2200 if (! TrReadOperator (tr
, "="))
2202 TrIndication (tr
, & line
, & col
);
2203 if (! TrReadInt (tr
, MIN_POINTS
, MAX_POINTS
, & intVal
))
2205 points
= (uint
) intVal
;
2206 if ((fftSize
> 0) && (points
> fftSize
)) {
2207 TrErrorAt (tr
, line
, col
, "Value exceeds the overridden FFT size.\n");
2210 if (points
< truncSize
) {
2211 TrErrorAt (tr
, line
, col
, "Value is below the truncation size.\n");
2214 hData
-> mIrPoints
= points
;
2215 hData
-> mFftSize
= fftSize
;
2218 while (points
< (4 * hData
-> mIrPoints
))
2220 hData
-> mFftSize
= points
;
2221 hData
-> mIrSize
= 1 + (points
/ 2);
2223 hData
-> mFftSize
= fftSize
;
2224 hData
-> mIrSize
= 1 + (fftSize
/ 2);
2225 if (points
> hData
-> mIrSize
)
2226 hData
-> mIrSize
= points
;
2229 } else if (strcasecmp (ident
, "azimuths") == 0) {
2231 TrErrorAt (tr
, line
, col
, "Redefinition of 'azimuths'.\n");
2234 if (! TrReadOperator (tr
, "="))
2236 hData
-> mIrCount
= 0;
2237 hData
-> mEvCount
= 0;
2238 hData
-> mEvOffset
[0] = 0;
2240 if (! TrReadInt (tr
, MIN_AZ_COUNT
, MAX_AZ_COUNT
, & intVal
))
2242 hData
-> mAzCount
[hData
-> mEvCount
] = (uint
) intVal
;
2243 hData
-> mIrCount
+= (uint
) intVal
;
2244 hData
-> mEvCount
++;
2245 if (! TrIsOperator (tr
, ","))
2247 if (hData
-> mEvCount
>= MAX_EV_COUNT
) {
2248 TrError (tr
, "Exceeded the maximum of %d elevations.\n", MAX_EV_COUNT
);
2251 hData
-> mEvOffset
[hData
-> mEvCount
] = hData
-> mEvOffset
[hData
-> mEvCount
- 1] + ((uint
) intVal
);
2252 TrReadOperator (tr
, ",");
2254 if (hData
-> mEvCount
< MIN_EV_COUNT
) {
2255 TrErrorAt (tr
, line
, col
, "Did not reach the minimum of %d azimuth counts.\n", MIN_EV_COUNT
);
2259 } else if (strcasecmp (ident
, "radius") == 0) {
2261 TrErrorAt (tr
, line
, col
, "Redefinition of 'radius'.\n");
2264 if (! TrReadOperator (tr
, "="))
2266 if (! TrReadFloat (tr
, MIN_RADIUS
, MAX_RADIUS
, & fpVal
))
2268 hData
-> mRadius
= fpVal
;
2270 } else if (strcasecmp (ident
, "distance") == 0) {
2272 TrErrorAt (tr
, line
, col
, "Redefinition of 'distance'.\n");
2275 if (! TrReadOperator (tr
, "="))
2277 if (! TrReadFloat (tr
, MIN_DISTANCE
, MAX_DISTANCE
, & fpVal
))
2279 hData
-> mDistance
= fpVal
;
2282 TrErrorAt (tr
, line
, col
, "Expected a metric name.\n");
2285 TrSkipWhitespace (tr
);
2290 // Parse an index pair from the data set definition.
2291 static int ReadIndexPair (TokenReaderT
* tr
, const HrirDataT
* hData
, uint
* ei
, uint
* ai
) {
2294 if (! TrReadInt (tr
, 0, (int) hData
-> mEvCount
, & intVal
))
2296 (* ei
) = (uint
) intVal
;
2297 if (! TrReadOperator (tr
, ","))
2299 if (! TrReadInt (tr
, 0, (int) hData
-> mAzCount
[(* ei
)], & intVal
))
2301 (* ai
) = (uint
) intVal
;
2305 // Match the source format from a given identifier.
2306 static SourceFormatT
MatchSourceFormat (const char * ident
) {
2307 if (strcasecmp (ident
, "wave") == 0)
2309 else if (strcasecmp (ident
, "bin_le") == 0)
2311 else if (strcasecmp (ident
, "bin_be") == 0)
2313 else if (strcasecmp (ident
, "ascii") == 0)
2318 // Match the source element type from a given identifier.
2319 static ElementTypeT
MatchElementType (const char * ident
) {
2320 if (strcasecmp (ident
, "int") == 0)
2322 else if (strcasecmp (ident
, "fp") == 0)
2327 // Parse and validate a source reference from the data set definition.
2328 static int ReadSourceRef (TokenReaderT
* tr
, SourceRefT
* src
) {
2330 char ident
[MAX_IDENT_LEN
+ 1];
2333 TrIndication (tr
, & line
, & col
);
2334 if (! TrReadIdent (tr
, MAX_IDENT_LEN
, ident
))
2336 src
-> mFormat
= MatchSourceFormat (ident
);
2337 if (src
-> mFormat
== SF_NONE
) {
2338 TrErrorAt (tr
, line
, col
, "Expected a source format.\n");
2341 if (! TrReadOperator (tr
, "("))
2343 if (src
-> mFormat
== SF_WAVE
) {
2344 if (! TrReadInt (tr
, 0, MAX_WAVE_CHANNELS
, & intVal
))
2346 src
-> mType
= ET_NONE
;
2349 src
-> mChannel
= (uint
) intVal
;
2352 TrIndication (tr
, & line
, & col
);
2353 if (! TrReadIdent (tr
, MAX_IDENT_LEN
, ident
))
2355 src
-> mType
= MatchElementType (ident
);
2356 if (src
-> mType
== ET_NONE
) {
2357 TrErrorAt (tr
, line
, col
, "Expected a source element type.\n");
2360 if ((src
-> mFormat
== SF_BIN_LE
) || (src
-> mFormat
== SF_BIN_BE
)) {
2361 if (! TrReadOperator (tr
, ","))
2363 if (src
-> mType
== ET_INT
) {
2364 if (! TrReadInt (tr
, MIN_BIN_SIZE
, MAX_BIN_SIZE
, & intVal
))
2366 src
-> mSize
= (uint
) intVal
;
2367 if (TrIsOperator (tr
, ",")) {
2368 TrReadOperator (tr
, ",");
2369 TrIndication (tr
, & line
, & col
);
2370 if (! TrReadInt (tr
, -2147483647 - 1, 2147483647, & intVal
))
2372 if ((abs (intVal
) < MIN_BIN_BITS
) || (((uint
) abs (intVal
)) > (8 * src
-> mSize
))) {
2373 TrErrorAt (tr
, line
, col
, "Expected a value of (+/-) %d to %d.\n", MIN_BIN_BITS
, 8 * src
-> mSize
);
2376 src
-> mBits
= intVal
;
2378 src
-> mBits
= (int) (8 * src
-> mSize
);
2381 TrIndication (tr
, & line
, & col
);
2382 if (! TrReadInt (tr
, -2147483647 - 1, 2147483647, & intVal
))
2384 if ((intVal
!= 4) && (intVal
!= 8)) {
2385 TrErrorAt (tr
, line
, col
, "Expected a value of 4 or 8.\n");
2388 src
-> mSize
= (uint
) intVal
;
2391 } else if ((src
-> mFormat
== SF_ASCII
) && (src
-> mType
== ET_INT
)) {
2392 if (! TrReadOperator (tr
, ","))
2394 if (! TrReadInt (tr
, MIN_ASCII_BITS
, MAX_ASCII_BITS
, & intVal
))
2397 src
-> mBits
= intVal
;
2402 if (TrIsOperator (tr
, ";")) {
2403 TrReadOperator (tr
, ";");
2404 if (! TrReadInt (tr
, 0, 0x7FFFFFFF, & intVal
))
2406 src
-> mSkip
= (uint
) intVal
;
2411 if (! TrReadOperator (tr
, ")"))
2413 if (TrIsOperator (tr
, "@")) {
2414 TrReadOperator (tr
, "@");
2415 if (! TrReadInt (tr
, 0, 0x7FFFFFFF, & intVal
))
2417 src
-> mOffset
= (uint
) intVal
;
2421 if (! TrReadOperator (tr
, ":"))
2423 if (! TrReadString (tr
, MAX_PATH_LEN
, src
-> mPath
))
2428 // Process the list of sources in the data set definition.
2429 static int ProcessSources (const HeadModelT model
, TokenReaderT
* tr
, HrirDataT
* hData
) {
2430 uint
* setCount
= NULL
, * setFlag
= NULL
;
2431 double * hrir
= NULL
;
2432 uint line
, col
, ei
, ai
;
2436 setCount
= (uint
*) calloc (hData
-> mEvCount
, sizeof (uint
));
2437 setFlag
= (uint
*) calloc (hData
-> mIrCount
, sizeof (uint
));
2438 hrir
= CreateArray (hData
-> mIrPoints
);
2439 while (TrIsOperator (tr
, "[")) {
2440 TrIndication (tr
, & line
, & col
);
2441 TrReadOperator (tr
, "[");
2442 if (ReadIndexPair (tr
, hData
, & ei
, & ai
)) {
2443 if (TrReadOperator (tr
, "]")) {
2444 if (! setFlag
[hData
-> mEvOffset
[ei
] + ai
]) {
2445 if (TrReadOperator (tr
, "=")) {
2448 if (ReadSourceRef (tr
, & src
)) {
2449 if (LoadSource (& src
, hData
-> mIrRate
, hData
-> mIrPoints
, hrir
)) {
2450 if (model
== HM_DATASET
)
2451 AverageHrirOnset (hrir
, 1.0 / factor
, ei
, ai
, hData
);
2452 AverageHrirMagnitude (hrir
, 1.0 / factor
, ei
, ai
, hData
);
2454 if (! TrIsOperator (tr
, "+"))
2456 TrReadOperator (tr
, "+");
2460 DestroyArray (hrir
);
2465 setFlag
[hData
-> mEvOffset
[ei
] + ai
] = 1;
2470 TrErrorAt (tr
, line
, col
, "Redefinition of source.\n");
2474 DestroyArray (hrir
);
2480 while ((ei
< hData
-> mEvCount
) && (setCount
[ei
] < 1))
2482 if (ei
< hData
-> mEvCount
) {
2483 hData
-> mEvStart
= ei
;
2484 while ((ei
< hData
-> mEvCount
) && (setCount
[ei
] == hData
-> mAzCount
[ei
]))
2486 if (ei
>= hData
-> mEvCount
) {
2487 if (! TrLoad (tr
)) {
2488 DestroyArray (hrir
);
2493 TrError (tr
, "Errant data at end of source list.\n");
2496 TrError (tr
, "Missing sources for elevation index %d.\n", ei
);
2499 TrError (tr
, "Missing source references.\n");
2501 DestroyArray (hrir
);
2507 /* Parse the data set definition and process the source data, storing the
2508 * resulting data set as desired. If the input name is NULL it will read
2509 * from standard input.
2511 static int ProcessDefinition (const char * inName
, const uint outRate
, const uint fftSize
, const int equalize
, const int surface
, const double limit
, const uint truncSize
, const HeadModelT model
, const double radius
, const OutputFormatT outFormat
, const char * outName
) {
2515 double * dfa
= NULL
;
2516 char rateStr
[8 + 1], expName
[MAX_PATH_LEN
];
2518 hData
. mIrRate
= 0;
2519 hData
. mIrPoints
= 0;
2520 hData
. mFftSize
= 0;
2521 hData
. mIrSize
= 0;
2522 hData
. mIrCount
= 0;
2523 hData
. mEvCount
= 0;
2524 hData
. mRadius
= 0;
2525 hData
. mDistance
= 0;
2526 fprintf (stdout
, "Reading HRIR definition...\n");
2527 if (inName
!= NULL
) {
2528 fp
= fopen (inName
, "r");
2530 fprintf (stderr
, "Error: Could not open definition file '%s'\n", inName
);
2533 TrSetup (fp
, inName
, & tr
);
2536 TrSetup (fp
, "<stdin>", & tr
);
2538 if (! ProcessMetrics (& tr
, fftSize
, truncSize
, & hData
)) {
2543 hData
. mHrirs
= CreateArray (hData
. mIrCount
* hData
. mIrSize
);
2544 hData
. mHrtds
= CreateArray (hData
. mIrCount
);
2545 if (! ProcessSources (model
, & tr
, & hData
)) {
2546 DestroyArray (hData
. mHrtds
);
2547 DestroyArray (hData
. mHrirs
);
2555 dfa
= CreateArray (1 + (hData
. mFftSize
/ 2));
2556 fprintf (stdout
, "Calculating diffuse-field average...\n");
2557 CalculateDiffuseFieldAverage (& hData
, surface
, limit
, dfa
);
2558 fprintf (stdout
, "Performing diffuse-field equalization...\n");
2559 DiffuseFieldEqualize (dfa
, & hData
);
2562 fprintf (stdout
, "Performing minimum phase reconstruction...\n");
2563 ReconstructHrirs (& hData
);
2564 if ((outRate
!= 0) && (outRate
!= hData
. mIrRate
)) {
2565 fprintf (stdout
, "Resampling HRIRs...\n");
2566 ResampleHrirs (outRate
, & hData
);
2568 fprintf (stdout
, "Truncating minimum-phase HRIRs...\n");
2569 hData
. mIrPoints
= truncSize
;
2570 fprintf (stdout
, "Synthesizing missing elevations...\n");
2571 if (model
== HM_DATASET
)
2572 SynthesizeOnsets (& hData
);
2573 SynthesizeHrirs (& hData
);
2574 fprintf (stdout
, "Normalizing final HRIRs...\n");
2575 NormalizeHrirs (& hData
);
2576 fprintf (stdout
, "Calculating impulse delays...\n");
2577 CalculateHrtds (model
, (radius
> DEFAULT_CUSTOM_RADIUS
) ? radius
: hData
. mRadius
, & hData
);
2578 snprintf (rateStr
, 8, "%u", hData
. mIrRate
);
2579 StrSubst (outName
, "%r", rateStr
, MAX_PATH_LEN
, expName
);
2580 switch (outFormat
) {
2582 fprintf (stdout
, "Creating MHR data set file...\n");
2583 if (! StoreMhr (& hData
, expName
))
2587 fprintf (stderr
, "Creating OpenAL Soft table file...\n");
2588 if (! StoreTable (& hData
, expName
))
2594 DestroyArray (hData
. mHrtds
);
2595 DestroyArray (hData
. mHrirs
);
2599 // Standard command line dispatch.
2600 int main (const int argc
, const char * argv
[]) {
2601 const char * inName
= NULL
, * outName
= NULL
;
2602 OutputFormatT outFormat
;
2604 uint outRate
, fftSize
;
2605 int equalize
, surface
;
2613 fprintf (stderr
, "Error: No command specified. See '%s -h' for help.\n", argv
[0]);
2616 if ((strcmp (argv
[1], "--help") == 0) || (strcmp (argv
[1], "-h") == 0)) {
2617 fprintf (stdout
, "HRTF Processing and Composition Utility\n\n");
2618 fprintf (stdout
, "Usage: %s <command> [<option>...]\n\n", argv
[0]);
2619 fprintf (stdout
, "Commands:\n");
2620 fprintf (stdout
, " -m, --make-mhr Makes an OpenAL Soft compatible HRTF data set.\n");
2621 fprintf (stdout
, " Defaults output to: ./oalsoft_hrtf_%%r.mhr\n");
2622 fprintf (stdout
, " -t, --make-tab Makes the built-in table used when compiling OpenAL Soft.\n");
2623 fprintf (stdout
, " Defaults output to: ./hrtf_tables.inc\n");
2624 fprintf (stdout
, " -h, --help Displays this help information.\n\n");
2625 fprintf (stdout
, "Options:\n");
2626 fprintf (stdout
, " -r=<rate> Change the data set sample rate to the specified value and\n");
2627 fprintf (stdout
, " resample the HRIRs accordingly.\n");
2628 fprintf (stdout
, " -f=<points> Override the FFT window size (defaults to the first power-\n");
2629 fprintf (stdout
, " of-two that fits four times the number of HRIR points).\n");
2630 fprintf (stdout
, " -e={on|off} Toggle diffuse-field equalization (default: %s).\n", (DEFAULT_EQUALIZE
? "on" : "off"));
2631 fprintf (stdout
, " -s={on|off} Toggle surface-weighted diffuse-field average (default: %s).\n", (DEFAULT_SURFACE
? "on" : "off"));
2632 fprintf (stdout
, " -l={<dB>|none} Specify a limit to the magnitude range of the diffuse-field\n");
2633 fprintf (stdout
, " average (default: %.2f).\n", DEFAULT_LIMIT
);
2634 fprintf (stdout
, " -w=<points> Specify the size of the truncation window that's applied\n");
2635 fprintf (stdout
, " after minimum-phase reconstruction (default: %u).\n", DEFAULT_TRUNCSIZE
);
2636 fprintf (stdout
, " -d={dataset| Specify the model used for calculating the head-delay timing\n");
2637 fprintf (stdout
, " sphere} values (default: %s).\n", ((DEFAULT_HEAD_MODEL
== HM_DATASET
) ? "dataset" : "sphere"));
2638 fprintf (stdout
, " -c=<size> Use a customized head radius measured ear-to-ear in meters.\n");
2639 fprintf (stdout
, " -i=<filename> Specify an HRIR definition file to use (defaults to stdin).\n");
2640 fprintf (stdout
, " -o=<filename> Specify an output file. Overrides command-selected default.\n");
2641 fprintf (stdout
, " Use of '%%r' will be substituted with the data set sample rate.\n");
2644 if ((strcmp (argv
[1], "--make-mhr") == 0) || (strcmp (argv
[1], "-m") == 0)) {
2648 outName
= "./oalsoft_hrtf_%r.mhr";
2650 } else if ((strcmp (argv
[1], "--make-tab") == 0) || (strcmp (argv
[1], "-t") == 0)) {
2654 outName
= "./hrtf_tables.inc";
2655 outFormat
= OF_TABLE
;
2657 fprintf (stderr
, "Error: Invalid command '%s'.\n", argv
[1]);
2663 equalize
= DEFAULT_EQUALIZE
;
2664 surface
= DEFAULT_SURFACE
;
2665 limit
= DEFAULT_LIMIT
;
2666 truncSize
= DEFAULT_TRUNCSIZE
;
2667 model
= DEFAULT_HEAD_MODEL
;
2668 radius
= DEFAULT_CUSTOM_RADIUS
;
2669 while (argi
< argc
) {
2670 if (strncmp (argv
[argi
], "-r=", 3) == 0) {
2671 outRate
= strtoul (& argv
[argi
] [3], & end
, 10);
2672 if ((end
[0] != '\0') || (outRate
< MIN_RATE
) || (outRate
> MAX_RATE
)) {
2673 fprintf (stderr
, "Error: Expected a value from %u to %u for '-r'.\n", MIN_RATE
, MAX_RATE
);
2676 } else if (strncmp (argv
[argi
], "-f=", 3) == 0) {
2677 fftSize
= strtoul (& argv
[argi
] [3], & end
, 10);
2678 if ((end
[0] != '\0') || (fftSize
& (fftSize
- 1)) || (fftSize
< MIN_FFTSIZE
) || (fftSize
> MAX_FFTSIZE
)) {
2679 fprintf (stderr
, "Error: Expected a power-of-two value from %u to %u for '-f'.\n", MIN_FFTSIZE
, MAX_FFTSIZE
);
2682 } else if (strncmp (argv
[argi
], "-e=", 3) == 0) {
2683 if (strcmp (& argv
[argi
] [3], "on") == 0) {
2685 } else if (strcmp (& argv
[argi
] [3], "off") == 0) {
2688 fprintf (stderr
, "Error: Expected 'on' or 'off' for '-e'.\n");
2691 } else if (strncmp (argv
[argi
], "-s=", 3) == 0) {
2692 if (strcmp (& argv
[argi
] [3], "on") == 0) {
2694 } else if (strcmp (& argv
[argi
] [3], "off") == 0) {
2697 fprintf (stderr
, "Error: Expected 'on' or 'off' for '-s'.\n");
2700 } else if (strncmp (argv
[argi
], "-l=", 3) == 0) {
2701 if (strcmp (& argv
[argi
] [3], "none") == 0) {
2704 limit
= strtod (& argv
[argi
] [3], & end
);
2705 if ((end
[0] != '\0') || (limit
< MIN_LIMIT
) || (limit
> MAX_LIMIT
)) {
2706 fprintf (stderr
, "Error: Expected 'none' or a value from %.2f to %.2f for '-l'.\n", MIN_LIMIT
, MAX_LIMIT
);
2710 } else if (strncmp (argv
[argi
], "-w=", 3) == 0) {
2711 truncSize
= strtoul (& argv
[argi
] [3], & end
, 10);
2712 if ((end
[0] != '\0') || (truncSize
< MIN_TRUNCSIZE
) || (truncSize
> MAX_TRUNCSIZE
) || (truncSize
% MOD_TRUNCSIZE
)) {
2713 fprintf (stderr
, "Error: Expected a value from %u to %u in multiples of %u for '-w'.\n", MIN_TRUNCSIZE
, MAX_TRUNCSIZE
, MOD_TRUNCSIZE
);
2716 } else if (strncmp (argv
[argi
], "-d=", 3) == 0) {
2717 if (strcmp (& argv
[argi
] [3], "dataset") == 0) {
2719 } else if (strcmp (& argv
[argi
] [3], "sphere") == 0) {
2722 fprintf (stderr
, "Error: Expected 'dataset' or 'sphere' for '-d'.\n");
2725 } else if (strncmp (argv
[argi
], "-c=", 3) == 0) {
2726 radius
= strtod (& argv
[argi
] [3], & end
);
2727 if ((end
[0] != '\0') || (radius
< MIN_CUSTOM_RADIUS
) || (radius
> MAX_CUSTOM_RADIUS
)) {
2728 fprintf (stderr
, "Error: Expected a value from %.2f to %.2f for '-c'.\n", MIN_CUSTOM_RADIUS
, MAX_CUSTOM_RADIUS
);
2731 } else if (strncmp (argv
[argi
], "-i=", 3) == 0) {
2732 inName
= & argv
[argi
] [3];
2733 } else if (strncmp (argv
[argi
], "-o=", 3) == 0) {
2734 outName
= & argv
[argi
] [3];
2736 fprintf (stderr
, "Error: Invalid option '%s'.\n", argv
[argi
]);
2741 if (! ProcessDefinition (inName
, outRate
, fftSize
, equalize
, surface
, limit
, truncSize
, model
, radius
, outFormat
, outName
))
2743 fprintf (stdout
, "Operation completed.\n");