2 * HRTF utility for producing and demonstrating the process of creating an
3 * OpenAL Soft compatible HRIR data set.
5 * Copyright (C) 2011-2012 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
61 /* Needed for 64-bit unsigned integer. */
71 // Rely (if naively) on OpenAL's header for the types used for serialization.
75 #define M_PI (3.14159265358979323846)
79 #define HUGE_VAL (1.0 / 0.0)
82 // The epsilon used to maintain signal stability.
83 #define EPSILON (1e-15)
85 // Constants for accessing the token reader's ring buffer.
86 #define TR_RING_BITS (16)
87 #define TR_RING_SIZE (1 << TR_RING_BITS)
88 #define TR_RING_MASK (TR_RING_SIZE - 1)
90 // The token reader's load interval in bytes.
91 #define TR_LOAD_SIZE (TR_RING_SIZE >> 2)
93 // The maximum identifier length used when processing the data set
95 #define MAX_IDENT_LEN (16)
97 // The maximum path length used when processing filenames.
98 #define MAX_PATH_LEN (256)
100 // The limits for the sample 'rate' metric in the data set definition and for
102 #define MIN_RATE (32000)
103 #define MAX_RATE (96000)
105 // The limits for the HRIR 'points' metric in the data set definition.
106 #define MIN_POINTS (16)
107 #define MAX_POINTS (8192)
109 // The limits to the number of 'azimuths' listed in the data set definition.
110 #define MIN_EV_COUNT (5)
111 #define MAX_EV_COUNT (128)
113 // The limits for each of the 'azimuths' listed in the data set definition.
114 #define MIN_AZ_COUNT (1)
115 #define MAX_AZ_COUNT (128)
117 // The limits for the listener's head 'radius' in the data set definition.
118 #define MIN_RADIUS (0.05)
119 #define MAX_RADIUS (0.15)
121 // The limits for the 'distance' from source to listener in the definition
123 #define MIN_DISTANCE (0.5)
124 #define MAX_DISTANCE (2.5)
126 // The maximum number of channels that can be addressed for a WAVE file
127 // source listed in the data set definition.
128 #define MAX_WAVE_CHANNELS (65535)
130 // The limits to the byte size for a binary source listed in the definition
132 #define MIN_BIN_SIZE (2)
133 #define MAX_BIN_SIZE (4)
135 // The minimum number of significant bits for binary sources listed in the
136 // data set definition. The maximum is calculated from the byte size.
137 #define MIN_BIN_BITS (16)
139 // The limits to the number of significant bits for an ASCII source listed in
140 // the data set definition.
141 #define MIN_ASCII_BITS (16)
142 #define MAX_ASCII_BITS (32)
144 // The limits to the FFT window size override on the command line.
145 #define MIN_FFTSIZE (512)
146 #define MAX_FFTSIZE (16384)
148 // The limits to the equalization range limit on the command line.
149 #define MIN_LIMIT (2.0)
150 #define MAX_LIMIT (120.0)
152 // The limits to the truncation window size on the command line.
153 #define MIN_TRUNCSIZE (8)
154 #define MAX_TRUNCSIZE (128)
156 // The truncation window size must be a multiple of the below value to allow
157 // for vectorized convolution.
158 #define MOD_TRUNCSIZE (8)
160 // The defaults for the command line options.
161 #define DEFAULT_EQUALIZE (1)
162 #define DEFAULT_SURFACE (1)
163 #define DEFAULT_LIMIT (24.0)
164 #define DEFAULT_TRUNCSIZE (32)
166 // The four-character-codes for RIFF/RIFX WAVE file chunks.
167 #define FOURCC_RIFF (0x46464952) // 'RIFF'
168 #define FOURCC_RIFX (0x58464952) // 'RIFX'
169 #define FOURCC_WAVE (0x45564157) // 'WAVE'
170 #define FOURCC_FMT (0x20746D66) // 'fmt '
171 #define FOURCC_DATA (0x61746164) // 'data'
172 #define FOURCC_LIST (0x5453494C) // 'LIST'
173 #define FOURCC_WAVL (0x6C766177) // 'wavl'
174 #define FOURCC_SLNT (0x746E6C73) // 'slnt'
176 // The supported wave formats.
177 #define WAVE_FORMAT_PCM (0x0001)
178 #define WAVE_FORMAT_IEEE_FLOAT (0x0003)
179 #define WAVE_FORMAT_EXTENSIBLE (0xFFFE)
181 // The maximum propagation delay value supported by OpenAL Soft.
182 #define MAX_HRTD (63.0)
184 // The OpenAL Soft HRTF format marker. It stands for minimum-phase head
185 // response protocol 01.
186 #define MHR_FORMAT ("MinPHR01")
188 // Byte order for the serialization routines.
195 // Source format for the references listed in the data set definition.
198 SF_WAVE
, // RIFF/RIFX WAVE file.
199 SF_BIN_LE
, // Little-endian binary file.
200 SF_BIN_BE
, // Big-endian binary file.
201 SF_ASCII
// ASCII text file.
204 // Element types for the references listed in the data set definition.
207 ET_INT
, // Integer elements.
208 ET_FP
// Floating-point elements.
211 // Desired output format from the command line.
214 OF_MHR
, // OpenAL Soft MHR data set file.
215 OF_TABLE
// OpenAL Soft built-in table file (used when compiling).
218 // Unsigned integer type.
219 typedef unsigned int uint
;
221 // Serialization types. The trailing digit indicates the number of bytes.
222 typedef ALubyte uint1
;
225 typedef ALuint uint4
;
227 #if defined (HAVE_STDINT_H)
230 typedef uint64_t uint8
;
231 #elif defined (HAVE___INT64)
232 typedef unsigned __int64 uint8
;
233 #elif (SIZEOF_LONG == 8)
234 typedef unsigned long uint8
;
235 #elif (SIZEOF_LONG_LONG == 8)
236 typedef unsigned long long uint8
;
239 typedef enum ByteOrderT ByteOrderT
;
240 typedef enum SourceFormatT SourceFormatT
;
241 typedef enum ElementTypeT ElementTypeT
;
242 typedef enum OutputFormatT OutputFormatT
;
244 typedef struct TokenReaderT TokenReaderT
;
245 typedef struct SourceRefT SourceRefT
;
246 typedef struct HrirDataT HrirDataT
;
247 typedef struct ResamplerT ResamplerT
;
249 // Token reader state for parsing the data set definition.
250 struct TokenReaderT
{
255 char mRing
[TR_RING_SIZE
];
260 // Source reference state used when loading sources.
262 SourceFormatT mFormat
;
269 char mPath
[MAX_PATH_LEN
+ 1];
272 // The HRIR metrics and data set used when loading, processing, and storing
273 // the resulting HRTF.
282 mAzCount
[MAX_EV_COUNT
],
283 mEvOffset
[MAX_EV_COUNT
];
291 // The resampler metrics and FIR filter.
300 /* Token reader routines for parsing text files. Whitespace is not
301 * significant. It can process tokens as identifiers, numbers (integer and
302 * floating-point), strings, and operators. Strings must be encapsulated by
303 * double-quotes and cannot span multiple lines.
306 // Setup the reader on the given file. The filename can be NULL if no error
307 // output is desired.
308 static void TrSetup (FILE * fp
, const char * filename
, TokenReaderT
* tr
) {
309 const char * name
= NULL
;
314 // If a filename was given, store a pointer to the base name.
315 if (filename
!= NULL
) {
316 while ((ch
= (* filename
)) != '\0') {
317 if ((ch
== '/') || (ch
== '\\'))
329 // Prime the reader's ring buffer, and return a result indicating that there
330 // is text to process.
331 static int TrLoad (TokenReaderT
* tr
) {
332 size_t toLoad
, in
, count
;
334 toLoad
= TR_RING_SIZE
- (tr
-> mIn
- tr
-> mOut
);
335 if ((toLoad
>= TR_LOAD_SIZE
) && (! feof (tr
-> mFile
))) {
336 // Load TR_LOAD_SIZE (or less if at the end of the file) per read.
337 toLoad
= TR_LOAD_SIZE
;
338 in
= tr
-> mIn
& TR_RING_MASK
;
339 count
= TR_RING_SIZE
- in
;
340 if (count
< toLoad
) {
341 tr
-> mIn
+= fread (& tr
-> mRing
[in
], 1, count
, tr
-> mFile
);
342 tr
-> mIn
+= fread (& tr
-> mRing
[0], 1, toLoad
- count
, tr
-> mFile
);
344 tr
-> mIn
+= fread (& tr
-> mRing
[in
], 1, toLoad
, tr
-> mFile
);
346 if (tr
-> mOut
>= TR_RING_SIZE
) {
347 tr
-> mOut
-= TR_RING_SIZE
;
348 tr
-> mIn
-= TR_RING_SIZE
;
351 if (tr
-> mIn
> tr
-> mOut
)
356 // Error display routine. Only displays when the base name is not NULL.
357 static void TrErrorVA (const TokenReaderT
* tr
, uint line
, uint column
, const char * format
, va_list argPtr
) {
358 if (tr
-> mName
!= NULL
) {
359 fprintf (stderr
, "Error (%s:%u:%u): ", tr
-> mName
, line
, column
);
360 vfprintf (stderr
, format
, argPtr
);
364 // Used to display an error at a saved line/column.
365 static void TrErrorAt (const TokenReaderT
* tr
, uint line
, uint column
, const char * format
, ...) {
368 va_start (argPtr
, format
);
369 TrErrorVA (tr
, line
, column
, format
, argPtr
);
373 // Used to display an error at the current line/column.
374 static void TrError (const TokenReaderT
* tr
, const char * format
, ...) {
377 va_start (argPtr
, format
);
378 TrErrorVA (tr
, tr
-> mLine
, tr
-> mColumn
, format
, argPtr
);
382 // Skips to the next line.
383 static void TrSkipLine (TokenReaderT
* tr
) {
386 while (TrLoad (tr
)) {
387 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
398 // Skips to the next token.
399 static int TrSkipWhitespace (TokenReaderT
* tr
) {
402 while (TrLoad (tr
)) {
403 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
412 } else if (ch
== '#') {
421 // Get the line and/or column of the next token (or the end of input).
422 static void TrIndication (TokenReaderT
* tr
, uint
* line
, uint
* column
) {
423 TrSkipWhitespace (tr
);
425 (* line
) = tr
-> mLine
;
427 (* column
) = tr
-> mColumn
;
430 // Checks to see if a token is the given operator. It does not display any
431 // errors and will not proceed to the next token.
432 static int TrIsOperator (TokenReaderT
* tr
, const char * op
) {
436 if (! TrSkipWhitespace (tr
))
440 while ((op
[len
] != '\0') && (out
< tr
-> mIn
)) {
441 ch
= tr
-> mRing
[out
& TR_RING_MASK
];
447 if (op
[len
] == '\0')
452 /* The TrRead*() routines obtain the value of a matching token type. They
453 * display type, form, and boundary errors and will proceed to the next
457 // Reads and validates an identifier token.
458 static int TrReadIdent (TokenReaderT
* tr
, const uint maxLen
, char * ident
) {
463 if (TrSkipWhitespace (tr
)) {
465 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
466 if ((ch
== '_') || isalpha (ch
)) {
475 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
476 } while ((ch
== '_') || isdigit (ch
) || isalpha (ch
));
477 tr
-> mColumn
+= len
;
479 TrErrorAt (tr
, tr
-> mLine
, col
, "Identifier is too long.\n");
486 TrErrorAt (tr
, tr
-> mLine
, col
, "Expected an identifier.\n");
490 // Reads and validates (including bounds) an integer token.
491 static int TrReadInt (TokenReaderT
* tr
, const int loBound
, const int hiBound
, int * value
) {
492 uint col
, digis
, len
;
493 char ch
, temp
[64 + 1];
496 if (TrSkipWhitespace (tr
)) {
499 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
500 if ((ch
== '+') || (ch
== '-')) {
506 while (TrLoad (tr
)) {
507 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
516 tr
-> mColumn
+= len
;
517 if ((digis
> 0) && (ch
!= '.') && (! isalpha (ch
))) {
519 TrErrorAt (tr
, tr
-> mLine
, col
, "Integer is too long.");
523 (* value
) = strtol (temp
, NULL
, 10);
524 if (((* value
) < loBound
) || ((* value
) > hiBound
)) {
525 TrErrorAt (tr
, tr
-> mLine
, col
, "Expected a value from %d to %d.\n", loBound
, hiBound
);
531 TrErrorAt (tr
, tr
-> mLine
, col
, "Expected an integer.\n");
535 // Reads and validates (including bounds) a float token.
536 static int TrReadFloat (TokenReaderT
* tr
, const double loBound
, const double hiBound
, double * value
) {
537 uint col
, digis
, len
;
538 char ch
, temp
[64 + 1];
541 if (TrSkipWhitespace (tr
)) {
544 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
545 if ((ch
== '+') || (ch
== '-')) {
551 while (TrLoad (tr
)) {
552 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
567 while (TrLoad (tr
)) {
568 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
578 if ((ch
== 'E') || (ch
== 'e')) {
584 if ((ch
== '+') || (ch
== '-')) {
590 while (TrLoad (tr
)) {
591 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
601 tr
-> mColumn
+= len
;
602 if ((digis
> 0) && (ch
!= '.') && (! isalpha (ch
))) {
604 TrErrorAt (tr
, tr
-> mLine
, col
, "Float is too long.");
608 (* value
) = strtod (temp
, NULL
);
609 if (((* value
) < loBound
) || ((* value
) > hiBound
)) {
610 TrErrorAt (tr
, tr
-> mLine
, col
, "Expected a value from %f to %f.\n", loBound
, hiBound
);
616 tr
-> mColumn
+= len
;
619 TrErrorAt (tr
, tr
-> mLine
, col
, "Expected a float.\n");
623 // Reads and validates a string token.
624 static int TrReadString (TokenReaderT
* tr
, const uint maxLen
, char * text
) {
629 if (TrSkipWhitespace (tr
)) {
631 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
635 while (TrLoad (tr
)) {
636 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
641 TrErrorAt (tr
, tr
-> mLine
, col
, "Unterminated string at end of line.\n");
649 tr
-> mColumn
+= 1 + len
;
650 TrErrorAt (tr
, tr
-> mLine
, col
, "Unterminated string at end of input.\n");
653 tr
-> mColumn
+= 2 + len
;
655 TrErrorAt (tr
, tr
-> mLine
, col
, "String is too long.\n");
662 TrErrorAt (tr
, tr
-> mLine
, col
, "Expected a string.\n");
666 // Reads and validates the given operator.
667 static int TrReadOperator (TokenReaderT
* tr
, const char * op
) {
672 if (TrSkipWhitespace (tr
)) {
675 while ((op
[len
] != '\0') && TrLoad (tr
)) {
676 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
682 tr
-> mColumn
+= len
;
683 if (op
[len
] == '\0')
686 TrErrorAt (tr
, tr
-> mLine
, col
, "Expected '%s' operator.\n", op
);
690 /* Performs a string substitution. Any case-insensitive occurrences of the
691 * pattern string are replaced with the replacement string. The result is
692 * truncated if necessary.
694 static int StrSubst (const char * in
, const char * pat
, const char * rep
, const size_t maxLen
, char * out
) {
695 size_t inLen
, patLen
, repLen
;
700 patLen
= strlen (pat
);
701 repLen
= strlen (rep
);
705 while ((si
< inLen
) && (di
< maxLen
)) {
706 if (patLen
<= (inLen
- si
)) {
707 if (strncasecmp (& in
[si
], pat
, patLen
) == 0) {
708 if (repLen
> (maxLen
- di
)) {
709 repLen
= maxLen
- di
;
712 strncpy (& out
[di
], rep
, repLen
);
724 return (! truncated
);
727 // Provide missing math routines for MSVC.
729 static double round (double val
) {
731 return (ceil (val
- 0.5));
732 return (floor (val
+ 0.5));
735 static double fmin (double a
, double b
) {
736 return ((a
< b
) ? a
: b
);
739 static double fmax (double a
, double b
) {
740 return ((a
> b
) ? a
: b
);
744 // Simple clamp routine.
745 static double Clamp (const double val
, const double lower
, const double upper
) {
746 return (fmin (fmax (val
, lower
), upper
));
749 // Performs linear interpolation.
750 static double Lerp (const double a
, const double b
, const double f
) {
751 return (a
+ (f
* (b
- a
)));
754 // Performs a high-passed triangular probability density function dither from
755 // a double to an integer. It assumes the input sample is already scaled.
756 static int HpTpdfDither (const double in
, int * hpHist
) {
757 const double PRNG_SCALE
= 1.0 / (RAND_MAX
+ 1.0);
762 out
= round (in
+ (PRNG_SCALE
* (prn
- (* hpHist
))));
767 // Allocates an array of doubles.
768 static double * CreateArray (const size_t n
) {
771 a
= (double *) calloc (n
, sizeof (double));
773 fprintf (stderr
, "Error: Out of memory.\n");
779 // Frees an array of doubles.
780 static void DestroyArray (const double * a
) {
784 // Complex number routines. All outputs must be non-NULL.
786 // Magnitude/absolute value.
787 static double ComplexAbs (const double r
, const double i
) {
788 return (sqrt ((r
* r
) + (i
* i
)));
792 static void ComplexMul (const double aR
, const double aI
, const double bR
, const double bI
, double * outR
, double * outI
) {
793 (* outR
) = (aR
* bR
) - (aI
* bI
);
794 (* outI
) = (aI
* bR
) + (aR
* bI
);
798 static void ComplexExp (const double inR
, const double inI
, double * outR
, double * outI
) {
802 (* outR
) = e
* cos (inI
);
803 (* outI
) = e
* sin (inI
);
806 /* Fast Fourier transform routines. The number of points must be a power of
807 * two. In-place operation is possible only if both the real and imaginary
808 * parts are in-place together.
811 // Performs bit-reversal ordering.
812 static void FftArrange (const uint n
, const double * inR
, const double * inI
, double * outR
, double * outI
) {
816 if ((inR
== outR
) && (inI
== outI
)) {
817 // Handle in-place arrangement.
819 for (k
= 0; k
< n
; k
++) {
829 while (rk
& (m
>>= 1))
834 // Handle copy arrangement.
836 for (k
= 0; k
< n
; k
++) {
840 while (rk
& (m
>>= 1))
847 // Performs the summation.
848 static void FftSummation (const uint n
, const double s
, double * re
, double * im
) {
851 double vR
, vI
, wR
, wI
;
856 for (m
= 1, m2
= 2; m
< n
; m
<<= 1, m2
<<= 1) {
857 // v = Complex (-2.0 * sin (0.5 * pi / m) * sin (0.5 * pi / m), -sin (pi / m))
858 vR
= sin (0.5 * pi
/ m
);
861 // w = Complex (1.0, 0.0)
864 for (i
= 0; i
< m
; i
++) {
865 for (k
= i
; k
< n
; k
+= m2
) {
867 // t = ComplexMul (w, out [km2])
868 tR
= (wR
* re
[mk
]) - (wI
* im
[mk
]);
869 tI
= (wR
* im
[mk
]) + (wI
* re
[mk
]);
870 // out [mk] = ComplexSub (out [k], t)
871 re
[mk
] = re
[k
] - tR
;
872 im
[mk
] = im
[k
] - tI
;
873 // out [k] = ComplexAdd (out [k], t)
877 // t = ComplexMul (v, w)
878 tR
= (vR
* wR
) - (vI
* wI
);
879 tI
= (vR
* wI
) + (vI
* wR
);
880 // w = ComplexAdd (w, t)
887 // Performs a forward FFT.
888 static void FftForward (const uint n
, const double * inR
, const double * inI
, double * outR
, double * outI
) {
889 FftArrange (n
, inR
, inI
, outR
, outI
);
890 FftSummation (n
, 1.0, outR
, outI
);
893 // Performs an inverse FFT.
894 static void FftInverse (const uint n
, const double * inR
, const double * inI
, double * outR
, double * outI
) {
898 FftArrange (n
, inR
, inI
, outR
, outI
);
899 FftSummation (n
, -1.0, outR
, outI
);
901 for (i
= 0; i
< n
; i
++) {
907 /* Calculate the complex helical sequence (or discrete-time analytical
908 * signal) of the given input using the Hilbert transform. Given the
909 * negative natural logarithm of a signal's magnitude response, the imaginary
910 * components can be used as the angles for minimum-phase reconstruction.
912 static void Hilbert (const uint n
, const double * in
, double * outR
, double * outI
) {
916 // Handle in-place operation.
917 for (i
= 0; i
< n
; i
++)
920 // Handle copy operation.
921 for (i
= 0; i
< n
; i
++) {
926 FftForward (n
, outR
, outI
, outR
, outI
);
927 /* Currently the Fourier routines operate only on point counts that are
928 * powers of two. If that changes and n is odd, the following conditional
929 * should be: i < (n + 1) / 2.
931 for (i
= 1; i
< (n
/ 2); i
++) {
935 // If n is odd, the following increment should be skipped.
937 for (; i
< n
; i
++) {
941 FftInverse (n
, outR
, outI
, outR
, outI
);
944 /* Calculate the magnitude response of the given input. This is used in
945 * place of phase decomposition, since the phase residuals are discarded for
946 * minimum phase reconstruction. The mirrored half of the response is also
949 static void MagnitudeResponse (const uint n
, const double * inR
, const double * inI
, double * out
) {
950 const uint m
= 1 + (n
/ 2);
953 for (i
= 0; i
< m
; i
++)
954 out
[i
] = fmax (ComplexAbs (inR
[i
], inI
[i
]), EPSILON
);
957 /* Apply a range limit (in dB) to the given magnitude response. This is used
958 * to adjust the effects of the diffuse-field average on the equalization
961 static void LimitMagnitudeResponse (const uint n
, const double limit
, const double * in
, double * out
) {
962 const uint m
= 1 + (n
/ 2);
964 uint i
, lower
, upper
;
967 halfLim
= limit
/ 2.0;
968 // Convert the response to dB.
969 for (i
= 0; i
< m
; i
++)
970 out
[i
] = 20.0 * log10 (in
[i
]);
971 // Use six octaves to calculate the average magnitude of the signal.
972 lower
= ((uint
) ceil (n
/ pow (2.0, 8.0))) - 1;
973 upper
= ((uint
) floor (n
/ pow (2.0, 2.0))) - 1;
975 for (i
= lower
; i
<= upper
; i
++)
977 ave
/= upper
- lower
+ 1;
978 // Keep the response within range of the average magnitude.
979 for (i
= 0; i
< m
; i
++)
980 out
[i
] = Clamp (out
[i
], ave
- halfLim
, ave
+ halfLim
);
981 // Convert the response back to linear magnitude.
982 for (i
= 0; i
< m
; i
++)
983 out
[i
] = pow (10.0, out
[i
] / 20.0);
986 /* Reconstructs the minimum-phase component for the given magnitude response
987 * of a signal. This is equivalent to phase recomposition, sans the missing
988 * residuals (which were discarded). The mirrored half of the response is
991 static void MinimumPhase (const uint n
, const double * in
, double * outR
, double * outI
) {
992 const uint m
= 1 + (n
/ 2);
993 double * mags
= NULL
;
997 mags
= CreateArray (n
);
998 for (i
= 0; i
< m
; i
++) {
999 mags
[i
] = fmax (in
[i
], EPSILON
);
1000 outR
[i
] = -log (mags
[i
]);
1002 for (; i
< n
; i
++) {
1003 mags
[i
] = mags
[n
- i
];
1004 outR
[i
] = outR
[n
- i
];
1006 Hilbert (n
, outR
, outR
, outI
);
1007 // Remove any DC offset the filter has.
1010 for (i
= 1; i
< n
; i
++) {
1011 ComplexExp (0.0, outI
[i
], & aR
, & aI
);
1012 ComplexMul (mags
[i
], 0.0, aR
, aI
, & outR
[i
], & outI
[i
]);
1014 DestroyArray (mags
);
1017 /* This is the normalized cardinal sine (sinc) function.
1019 * sinc(x) = { 1, x = 0
1020 * { sin(pi x) / (pi x), otherwise.
1022 static double Sinc (const double x
) {
1023 if (fabs (x
) < EPSILON
)
1025 return (sin (M_PI
* x
) / (M_PI
* x
));
1028 /* The zero-order modified Bessel function of the first kind, used for the
1031 * I_0(x) = sum_{k=0}^inf (1 / k!)^2 (x / 2)^(2 k)
1032 * = sum_{k=0}^inf ((x / 2)^k / k!)^2
1034 static double BesselI_0 (const double x
) {
1035 double term
, sum
, x2
, y
, last_sum
;
1038 // Start at k=1 since k=0 is trivial.
1043 // Let the integration converge until the term of the sum is no longer
1051 } while (sum
!= last_sum
);
1055 /* Calculate a Kaiser window from the given beta value and a normalized k
1058 * w(k) = { I_0(B sqrt(1 - k^2)) / I_0(B), -1 <= k <= 1
1061 * Where k can be calculated as:
1063 * k = i / l, where -l <= i <= l.
1067 * k = 2 i / M - 1, where 0 <= i <= M.
1069 static double Kaiser (const double b
, const double k
) {
1072 k2
= Clamp (k
, -1.0, 1.0);
1073 if ((k
< -1.0) || (k
> 1.0))
1076 return (BesselI_0 (b
* sqrt (1.0 - k2
)) / BesselI_0 (b
));
1079 // Calculates the greatest common divisor of a and b.
1080 static uint
Gcd (const uint a
, const uint b
) {
1093 /* Calculates the size (order) of the Kaiser window. Rejection is in dB and
1094 * the transition width is normalized frequency (0.5 is nyquist).
1096 * M = { ceil((r - 7.95) / (2.285 2 pi f_t)), r > 21
1097 * { ceil(5.79 / 2 pi f_t), r <= 21.
1100 static uint
CalcKaiserOrder (const double rejection
, const double transition
) {
1103 w_t
= 2.0 * M_PI
* transition
;
1104 if (rejection
> 21.0)
1105 return ((uint
) ceil ((rejection
- 7.95) / (2.285 * w_t
)));
1106 return ((uint
) ceil (5.79 / w_t
));
1109 // Calculates the beta value of the Kaiser window. Rejection is in dB.
1110 static double CalcKaiserBeta (const double rejection
) {
1111 if (rejection
> 50.0)
1112 return (0.1102 * (rejection
- 8.7));
1113 else if (rejection
>= 21.0)
1114 return ((0.5842 * pow (rejection
- 21.0, 0.4)) +
1115 (0.07886 * (rejection
- 21.0)));
1120 /* Calculates a point on the Kaiser-windowed sinc filter for the given half-
1121 * width, beta, gain, and cutoff. The point is specified in non-normalized
1122 * samples, from 0 to M, where M = (2 l + 1).
1124 * w(k) 2 p f_t sinc(2 f_t x)
1126 * x -- centered sample index (i - l)
1127 * k -- normalized and centered window index (x / l)
1128 * w(k) -- window function (Kaiser)
1129 * p -- gain compensation factor when sampling
1130 * f_t -- normalized center frequency (or cutoff; 0.5 is nyquist)
1132 static double SincFilter (const int l
, const double b
, const double gain
, const double cutoff
, const int i
) {
1133 return (Kaiser (b
, ((double) (i
- l
)) / l
) * 2.0 * gain
* cutoff
* Sinc (2.0 * cutoff
* (i
- l
)));
1136 /* This is a polyphase sinc-filtered resampler.
1138 * Upsample Downsample
1140 * p/q = 3/2 p/q = 3/5
1142 * M-+-+-+-> M-+-+-+->
1143 * -------------------+ ---------------------+
1144 * p s * f f f f|f| | p s * f f f f f |
1145 * | 0 * 0 0 0|0|0 | | 0 * 0 0 0 0|0| |
1146 * v 0 * 0 0|0|0 0 | v 0 * 0 0 0|0|0 |
1147 * s * f|f|f f f | s * f f|f|f f |
1148 * 0 * |0|0 0 0 0 | 0 * 0|0|0 0 0 |
1149 * --------+=+--------+ 0 * |0|0 0 0 0 |
1150 * d . d .|d|. d . d ----------+=+--------+
1151 * d . . . .|d|. . . .
1155 * P_f(i,j) = q i mod p + pj
1156 * P_s(i,j) = floor(q i / p) - j
1157 * d[i=0..N-1] = sum_{j=0}^{floor((M - 1) / p)} {
1158 * { f[P_f(i,j)] s[P_s(i,j)], P_f(i,j) < M
1159 * { 0, P_f(i,j) >= M. }
1162 // Calculate the resampling metrics and build the Kaiser-windowed sinc filter
1163 // that's used to cut frequencies above the destination nyquist.
1164 static void ResamplerSetup (ResamplerT
* rs
, const uint srcRate
, const uint dstRate
) {
1166 double cutoff
, width
, beta
;
1169 gcd
= Gcd (srcRate
, dstRate
);
1170 rs
-> mP
= dstRate
/ gcd
;
1171 rs
-> mQ
= srcRate
/ gcd
;
1172 /* The cutoff is adjusted by half the transition width, so the transition
1173 * ends before the nyquist (0.5). Both are scaled by the downsampling
1176 if (rs
-> mP
> rs
-> mQ
) {
1177 cutoff
= 0.45 / rs
-> mP
;
1178 width
= 0.1 / rs
-> mP
;
1180 cutoff
= 0.45 / rs
-> mQ
;
1181 width
= 0.1 / rs
-> mQ
;
1183 // A rejection of -180 dB is used for the stop band.
1184 l
= CalcKaiserOrder (180.0, width
) / 2;
1185 beta
= CalcKaiserBeta (180.0);
1186 rs
-> mM
= (2 * l
) + 1;
1188 rs
-> mF
= CreateArray (rs
-> mM
);
1189 for (i
= 0; i
< ((int) rs
-> mM
); i
++)
1190 rs
-> mF
[i
] = SincFilter ((int) l
, beta
, rs
-> mP
, cutoff
, i
);
1193 // Clean up after the resampler.
1194 static void ResamplerClear (ResamplerT
* rs
) {
1195 DestroyArray (rs
-> mF
);
1199 // Perform the upsample-filter-downsample resampling operation using a
1200 // polyphase filter implementation.
1201 static void ResamplerRun (ResamplerT
* rs
, const uint inN
, const double * in
, const uint outN
, double * out
) {
1202 const uint p
= rs
-> mP
, q
= rs
-> mQ
, m
= rs
-> mM
, l
= rs
-> mL
;
1203 const double * f
= rs
-> mF
;
1204 double * work
= NULL
;
1209 // Handle in-place operation.
1211 work
= CreateArray (outN
);
1214 // Resample the input.
1215 for (i
= 0; i
< outN
; i
++) {
1217 // Input starts at l to compensate for the filter delay. This will
1218 // drop any build-up from the first half of the filter.
1219 j_f
= (l
+ (q
* i
)) % p
;
1220 j_s
= (l
+ (q
* i
)) / p
;
1222 // Only take input when 0 <= j_s < inN. This single unsigned
1223 // comparison catches both cases.
1225 r
+= f
[j_f
] * in
[j_s
];
1231 // Clean up after in-place operation.
1233 for (i
= 0; i
< outN
; i
++)
1235 DestroyArray (work
);
1239 // Read a binary value of the specified byte order and byte size from a file,
1240 // storing it as a 32-bit unsigned integer.
1241 static int ReadBin4 (FILE * fp
, const char * filename
, const ByteOrderT order
, const uint bytes
, uint4
* out
) {
1246 if (fread (in
, 1, bytes
, fp
) != bytes
) {
1247 fprintf (stderr
, "Error: Bad read from file '%s'.\n", filename
);
1253 for (i
= 0; i
< bytes
; i
++)
1254 accum
= (accum
<< 8) | in
[bytes
- i
- 1];
1257 for (i
= 0; i
< bytes
; i
++)
1258 accum
= (accum
<< 8) | in
[i
];
1267 // Read a binary value of the specified byte order from a file, storing it as
1268 // a 64-bit unsigned integer.
1269 static int ReadBin8 (FILE * fp
, const char * filename
, const ByteOrderT order
, uint8
* out
) {
1274 if (fread (in
, 1, 8, fp
) != 8) {
1275 fprintf (stderr
, "Error: Bad read from file '%s'.\n", filename
);
1281 for (i
= 0; i
< 8; i
++)
1282 accum
= (accum
<< 8) | in
[8 - i
- 1];
1285 for (i
= 0; i
< 8; i
++)
1286 accum
= (accum
<< 8) | in
[i
];
1295 // Write an ASCII string to a file.
1296 static int WriteAscii (const char * out
, FILE * fp
, const char * filename
) {
1300 if (fwrite (out
, 1, len
, fp
) != len
) {
1302 fprintf (stderr
, "Error: Bad write to file '%s'.\n", filename
);
1308 // Write a binary value of the given byte order and byte size to a file,
1309 // loading it from a 32-bit unsigned integer.
1310 static int WriteBin4 (const ByteOrderT order
, const uint bytes
, const uint4 in
, FILE * fp
, const char * filename
) {
1316 for (i
= 0; i
< bytes
; i
++)
1317 out
[i
] = (in
>> (i
* 8)) & 0x000000FF;
1320 for (i
= 0; i
< bytes
; i
++)
1321 out
[bytes
- i
- 1] = (in
>> (i
* 8)) & 0x000000FF;
1326 if (fwrite (out
, 1, bytes
, fp
) != bytes
) {
1327 fprintf (stderr
, "Error: Bad write to file '%s'.\n", filename
);
1333 /* Read a binary value of the specified type, byte order, and byte size from
1334 * a file, converting it to a double. For integer types, the significant
1335 * bits are used to normalize the result. The sign of bits determines
1336 * whether they are padded toward the MSB (negative) or LSB (positive).
1337 * Floating-point types are not normalized.
1339 static int ReadBinAsDouble (FILE * fp
, const char * filename
, const ByteOrderT order
, const ElementTypeT type
, const uint bytes
, const int bits
, double * out
) {
1352 if (! ReadBin8 (fp
, filename
, order
, & v8
. ui
))
1357 if (! ReadBin4 (fp
, filename
, order
, bytes
, & v4
. ui
))
1359 if (type
== ET_FP
) {
1360 (* out
) = (double) v4
. f
;
1363 v4
. ui
>>= (8 * bytes
) - ((uint
) bits
);
1365 v4
. ui
&= (0xFFFFFFFF >> (32 + bits
));
1366 if (v4
. ui
& ((uint
) (1 << (abs (bits
) - 1))))
1367 v4
. ui
|= (0xFFFFFFFF << abs (bits
));
1368 (* out
) = v4
. i
/ ((double) (1 << (abs (bits
) - 1)));
1374 /* Read an ascii value of the specified type from a file, converting it to a
1375 * double. For integer types, the significant bits are used to normalize the
1376 * result. The sign of the bits should always be positive. This also skips
1377 * up to one separator character before the element itself.
1379 static int ReadAsciiAsDouble (TokenReaderT
* tr
, const char * filename
, const ElementTypeT type
, const uint bits
, double * out
) {
1382 if (TrIsOperator (tr
, ","))
1383 TrReadOperator (tr
, ",");
1384 else if (TrIsOperator (tr
, ":"))
1385 TrReadOperator (tr
, ":");
1386 else if (TrIsOperator (tr
, ";"))
1387 TrReadOperator (tr
, ";");
1388 else if (TrIsOperator (tr
, "|"))
1389 TrReadOperator (tr
, "|");
1390 if (type
== ET_FP
) {
1391 if (! TrReadFloat (tr
, -HUGE_VAL
, HUGE_VAL
, out
)) {
1392 fprintf (stderr
, "Error: Bad read from file '%s'.\n", filename
);
1396 if (! TrReadInt (tr
, -(1 << (bits
- 1)), (1 << (bits
- 1)) - 1, & v
)) {
1397 fprintf (stderr
, "Error: Bad read from file '%s'.\n", filename
);
1400 (* out
) = v
/ ((double) ((1 << (bits
- 1)) - 1));
1405 // Read the RIFF/RIFX WAVE format chunk from a file, validating it against
1406 // the source parameters and data set metrics.
1407 static int ReadWaveFormat (FILE * fp
, const ByteOrderT order
, const uint hrirRate
, SourceRefT
* src
) {
1408 uint4 fourCC
, chunkSize
;
1409 uint4 format
, channels
, rate
, dummy
, block
, size
, bits
;
1414 fseek (fp
, (long) chunkSize
, SEEK_CUR
);
1415 if ((! ReadBin4 (fp
, src
-> mPath
, BO_LITTLE
, 4, & fourCC
)) ||
1416 (! ReadBin4 (fp
, src
-> mPath
, order
, 4, & chunkSize
)))
1418 } while (fourCC
!= FOURCC_FMT
);
1419 if ((! ReadBin4 (fp
, src
-> mPath
, order
, 2, & format
)) ||
1420 (! ReadBin4 (fp
, src
-> mPath
, order
, 2, & channels
)) ||
1421 (! ReadBin4 (fp
, src
-> mPath
, order
, 4, & rate
)) ||
1422 (! ReadBin4 (fp
, src
-> mPath
, order
, 4, & dummy
)) ||
1423 (! ReadBin4 (fp
, src
-> mPath
, order
, 2, & block
)))
1426 if (chunkSize
> 14) {
1427 if (! ReadBin4 (fp
, src
-> mPath
, order
, 2, & size
))
1435 if (format
== WAVE_FORMAT_EXTENSIBLE
) {
1436 fseek (fp
, 2, SEEK_CUR
);
1437 if (! ReadBin4 (fp
, src
-> mPath
, order
, 2, & bits
))
1441 fseek (fp
, 4, SEEK_CUR
);
1442 if (! ReadBin4 (fp
, src
-> mPath
, order
, 2, & format
))
1444 fseek (fp
, (long) (chunkSize
- 26), SEEK_CUR
);
1448 fseek (fp
, (long) (chunkSize
- 16), SEEK_CUR
);
1450 fseek (fp
, (long) (chunkSize
- 14), SEEK_CUR
);
1452 if ((format
!= WAVE_FORMAT_PCM
) && (format
!= WAVE_FORMAT_IEEE_FLOAT
)) {
1453 fprintf (stderr
, "Error: Unsupported WAVE format in file '%s'.\n", src
-> mPath
);
1456 if (src
-> mChannel
>= channels
) {
1457 fprintf (stderr
, "Error: Missing source channel in WAVE file '%s'.\n", src
-> mPath
);
1460 if (rate
!= hrirRate
) {
1461 fprintf (stderr
, "Error: Mismatched source sample rate in WAVE file '%s'.\n", src
-> mPath
);
1464 if (format
== WAVE_FORMAT_PCM
) {
1465 if ((size
< 2) || (size
> 4)) {
1466 fprintf (stderr
, "Error: Unsupported sample size in WAVE file '%s'.\n", src
-> mPath
);
1469 if ((bits
< 16) || (bits
> (8 * size
))) {
1470 fprintf (stderr
, "Error: Bad significant bits in WAVE file '%s'.\n", src
-> mPath
);
1473 src
-> mType
= ET_INT
;
1475 if ((size
!= 4) && (size
!= 8)) {
1476 fprintf (stderr
, "Error: Unsupported sample size in WAVE file '%s'.\n", src
-> mPath
);
1479 src
-> mType
= ET_FP
;
1481 src
-> mSize
= size
;
1482 src
-> mBits
= (int) bits
;
1483 src
-> mSkip
= channels
;
1487 // Read a RIFF/RIFX WAVE data chunk, converting all elements to doubles.
1488 static int ReadWaveData (FILE * fp
, const SourceRefT
* src
, const ByteOrderT order
, const uint n
, double * hrir
) {
1489 int pre
, post
, skip
;
1492 pre
= (int) (src
-> mSize
* src
-> mChannel
);
1493 post
= (int) (src
-> mSize
* (src
-> mSkip
- src
-> mChannel
- 1));
1495 for (i
= 0; i
< n
; i
++) {
1498 fseek (fp
, skip
, SEEK_CUR
);
1499 if (! ReadBinAsDouble (fp
, src
-> mPath
, order
, src
-> mType
, src
-> mSize
, src
-> mBits
, & hrir
[i
]))
1504 fseek (fp
, skip
, SEEK_CUR
);
1508 // Read the RIFF/RIFX WAVE list or data chunk, converting all elements to
1510 static int ReadWaveList (FILE * fp
, const SourceRefT
* src
, const ByteOrderT order
, const uint n
, double * hrir
) {
1511 uint4 fourCC
, chunkSize
, listSize
, count
;
1512 uint block
, skip
, offset
, i
;
1516 if ((! ReadBin4 (fp
, src
-> mPath
, BO_LITTLE
, 4, & fourCC
)) ||
1517 (! ReadBin4 (fp
, src
-> mPath
, order
, 4, & chunkSize
)))
1519 if (fourCC
== FOURCC_DATA
) {
1520 block
= src
-> mSize
* src
-> mSkip
;
1521 count
= chunkSize
/ block
;
1522 if (count
< (src
-> mOffset
+ n
)) {
1523 fprintf (stderr
, "Error: Bad read from file '%s'.\n", src
-> mPath
);
1526 fseek (fp
, (long) (src
-> mOffset
* block
), SEEK_CUR
);
1527 if (! ReadWaveData (fp
, src
, order
, n
, & hrir
[0]))
1530 } else if (fourCC
== FOURCC_LIST
) {
1531 if (! ReadBin4 (fp
, src
-> mPath
, BO_LITTLE
, 4, & fourCC
))
1534 if (fourCC
== FOURCC_WAVL
)
1538 fseek (fp
, (long) chunkSize
, SEEK_CUR
);
1540 listSize
= chunkSize
;
1541 block
= src
-> mSize
* src
-> mSkip
;
1542 skip
= src
-> mOffset
;
1545 while ((offset
< n
) && (listSize
> 8)) {
1546 if ((! ReadBin4 (fp
, src
-> mPath
, BO_LITTLE
, 4, & fourCC
)) ||
1547 (! ReadBin4 (fp
, src
-> mPath
, order
, 4, & chunkSize
)))
1549 listSize
-= 8 + chunkSize
;
1550 if (fourCC
== FOURCC_DATA
) {
1551 count
= chunkSize
/ block
;
1553 fseek (fp
, (long) (skip
* block
), SEEK_CUR
);
1554 chunkSize
-= skip
* block
;
1557 if (count
> (n
- offset
))
1559 if (! ReadWaveData (fp
, src
, order
, count
, & hrir
[offset
]))
1561 chunkSize
-= count
* block
;
1563 lastSample
= hrir
[offset
- 1];
1568 } else if (fourCC
== FOURCC_SLNT
) {
1569 if (! ReadBin4 (fp
, src
-> mPath
, order
, 4, & count
))
1575 if (count
> (n
- offset
))
1577 for (i
= 0; i
< count
; i
++)
1578 hrir
[offset
+ i
] = lastSample
;
1586 fseek (fp
, (long) chunkSize
, SEEK_CUR
);
1589 fprintf (stderr
, "Error: Bad read from file '%s'.\n", src
-> mPath
);
1595 // Load a source HRIR from a RIFF/RIFX WAVE file.
1596 static int LoadWaveSource (FILE * fp
, SourceRefT
* src
, const uint hrirRate
, const uint n
, double * hrir
) {
1597 uint4 fourCC
, dummy
;
1600 if ((! ReadBin4 (fp
, src
-> mPath
, BO_LITTLE
, 4, & fourCC
)) ||
1601 (! ReadBin4 (fp
, src
-> mPath
, BO_LITTLE
, 4, & dummy
)))
1603 if (fourCC
== FOURCC_RIFF
) {
1605 } else if (fourCC
== FOURCC_RIFX
) {
1608 fprintf (stderr
, "Error: No RIFF/RIFX chunk in file '%s'.\n", src
-> mPath
);
1611 if (! ReadBin4 (fp
, src
-> mPath
, BO_LITTLE
, 4, & fourCC
))
1613 if (fourCC
!= FOURCC_WAVE
) {
1614 fprintf (stderr
, "Error: Not a RIFF/RIFX WAVE file '%s'.\n", src
-> mPath
);
1617 if (! ReadWaveFormat (fp
, order
, hrirRate
, src
))
1619 if (! ReadWaveList (fp
, src
, order
, n
, hrir
))
1624 // Load a source HRIR from a binary file.
1625 static int LoadBinarySource (FILE * fp
, const SourceRefT
* src
, const ByteOrderT order
, const uint n
, double * hrir
) {
1628 fseek (fp
, (long) src
-> mOffset
, SEEK_SET
);
1629 for (i
= 0; i
< n
; i
++) {
1630 if (! ReadBinAsDouble (fp
, src
-> mPath
, order
, src
-> mType
, src
-> mSize
, src
-> mBits
, & hrir
[i
]))
1632 if (src
-> mSkip
> 0)
1633 fseek (fp
, (long) src
-> mSkip
, SEEK_CUR
);
1638 // Load a source HRIR from an ASCII text file containing a list of elements
1639 // separated by whitespace or common list operators (',', ';', ':', '|').
1640 static int LoadAsciiSource (FILE * fp
, const SourceRefT
* src
, const uint n
, double * hrir
) {
1645 TrSetup (fp
, NULL
, & tr
);
1646 for (i
= 0; i
< src
-> mOffset
; i
++) {
1647 if (! ReadAsciiAsDouble (& tr
, src
-> mPath
, src
-> mType
, (uint
) src
-> mBits
, & dummy
))
1650 for (i
= 0; i
< n
; i
++) {
1651 if (! ReadAsciiAsDouble (& tr
, src
-> mPath
, src
-> mType
, (uint
) src
-> mBits
, & hrir
[i
]))
1653 for (j
= 0; j
< src
-> mSkip
; j
++) {
1654 if (! ReadAsciiAsDouble (& tr
, src
-> mPath
, src
-> mType
, (uint
) src
-> mBits
, & dummy
))
1661 // Load a source HRIR from a supported file type.
1662 static int LoadSource (SourceRefT
* src
, const uint hrirRate
, const uint n
, double * hrir
) {
1666 if (src
-> mFormat
== SF_ASCII
)
1667 fp
= fopen (src
-> mPath
, "r");
1669 fp
= fopen (src
-> mPath
, "rb");
1671 fprintf (stderr
, "Error: Could not open source file '%s'.\n", src
-> mPath
);
1674 if (src
-> mFormat
== SF_WAVE
)
1675 result
= LoadWaveSource (fp
, src
, hrirRate
, n
, hrir
);
1676 else if (src
-> mFormat
== SF_BIN_LE
)
1677 result
= LoadBinarySource (fp
, src
, BO_LITTLE
, n
, hrir
);
1678 else if (src
-> mFormat
== SF_BIN_BE
)
1679 result
= LoadBinarySource (fp
, src
, BO_BIG
, n
, hrir
);
1681 result
= LoadAsciiSource (fp
, src
, n
, hrir
);
1686 // Calculate the magnitude response of an HRIR and average it with any
1687 // existing responses for its elevation and azimuth.
1688 static void AverageHrirMagnitude (const double * hrir
, const double f
, const uint ei
, const uint ai
, const HrirDataT
* hData
) {
1689 double * re
= NULL
, * im
= NULL
;
1692 n
= hData
-> mFftSize
;
1693 re
= CreateArray (n
);
1694 im
= CreateArray (n
);
1695 for (i
= 0; i
< hData
-> mIrPoints
; i
++) {
1699 for (; i
< n
; i
++) {
1703 FftForward (n
, re
, im
, re
, im
);
1704 MagnitudeResponse (n
, re
, im
, re
);
1706 j
= (hData
-> mEvOffset
[ei
] + ai
) * hData
-> mIrSize
;
1707 for (i
= 0; i
< m
; i
++)
1708 hData
-> mHrirs
[j
+ i
] = Lerp (hData
-> mHrirs
[j
+ i
], re
[i
], f
);
1713 /* Calculate the contribution of each HRIR to the diffuse-field average based
1714 * on the area of its surface patch. All patches are centered at the HRIR
1715 * coordinates on the unit sphere and are measured by solid angle.
1717 static void CalculateDfWeights (const HrirDataT
* hData
, double * weights
) {
1719 double evs
, sum
, ev
, up_ev
, down_ev
, solidAngle
;
1721 evs
= 90.0 / (hData
-> mEvCount
- 1);
1723 for (ei
= hData
-> mEvStart
; ei
< hData
-> mEvCount
; ei
++) {
1724 // For each elevation, calculate the upper and lower limits of the
1726 ev
= -90.0 + (ei
* 2.0 * evs
);
1727 if (ei
< (hData
-> mEvCount
- 1))
1728 up_ev
= (ev
+ evs
) * M_PI
/ 180.0;
1732 down_ev
= (ev
- evs
) * M_PI
/ 180.0;
1734 down_ev
= -M_PI
/ 2.0;
1735 // Calculate the area of the patch band.
1736 solidAngle
= 2.0 * M_PI
* (sin (up_ev
) - sin (down_ev
));
1737 // Each weight is the area of one patch.
1738 weights
[ei
] = solidAngle
/ hData
-> mAzCount
[ei
];
1739 // Sum the total surface area covered by the HRIRs.
1742 // Normalize the weights given the total surface coverage.
1743 for (ei
= hData
-> mEvStart
; ei
< hData
-> mEvCount
; ei
++)
1744 weights
[ei
] /= sum
;
1747 /* Calculate the diffuse-field average from the given magnitude responses of
1748 * the HRIR set. Weighting can be applied to compensate for the varying
1749 * surface area covered by each HRIR. The final average can then be limited
1750 * by the specified magnitude range (in positive dB; 0.0 to skip).
1752 static void CalculateDiffuseFieldAverage (const HrirDataT
* hData
, const int weighted
, const double limit
, double * dfa
) {
1753 double * weights
= NULL
;
1754 uint ei
, ai
, count
, step
, start
, end
, m
, j
, i
;
1757 weights
= CreateArray (hData
-> mEvCount
);
1759 // Use coverage weighting to calculate the average.
1760 CalculateDfWeights (hData
, weights
);
1762 // If coverage weighting is not used, the weights still need to be
1763 // averaged by the number of HRIRs.
1765 for (ei
= hData
-> mEvStart
; ei
< hData
-> mEvCount
; ei
++)
1766 count
+= hData
-> mAzCount
[ei
];
1767 for (ei
= hData
-> mEvStart
; ei
< hData
-> mEvCount
; ei
++)
1768 weights
[ei
] = 1.0 / count
;
1770 ei
= hData
-> mEvStart
;
1772 step
= hData
-> mIrSize
;
1773 start
= hData
-> mEvOffset
[ei
] * step
;
1774 end
= hData
-> mIrCount
* step
;
1775 m
= 1 + (hData
-> mFftSize
/ 2);
1776 for (i
= 0; i
< m
; i
++)
1778 for (j
= start
; j
< end
; j
+= step
) {
1779 // Get the weight for this HRIR's contribution.
1780 weight
= weights
[ei
];
1781 // Add this HRIR's weighted power average to the total.
1782 for (i
= 0; i
< m
; i
++)
1783 dfa
[i
] += weight
* hData
-> mHrirs
[j
+ i
] * hData
-> mHrirs
[j
+ i
];
1784 // Determine the next weight to use.
1786 if (ai
>= hData
-> mAzCount
[ei
]) {
1791 // Finish the average calculation and keep it from being too small.
1792 for (i
= 0; i
< m
; i
++)
1793 dfa
[i
] = fmax (sqrt (dfa
[i
]), EPSILON
);
1794 // Apply a limit to the magnitude range of the diffuse-field average if
1797 LimitMagnitudeResponse (hData
-> mFftSize
, limit
, dfa
, dfa
);
1798 DestroyArray (weights
);
1801 // Perform diffuse-field equalization on the magnitude responses of the HRIR
1802 // set using the given average response.
1803 static void DiffuseFieldEqualize (const double * dfa
, const HrirDataT
* hData
) {
1804 uint step
, start
, end
, m
, j
, i
;
1806 step
= hData
-> mIrSize
;
1807 start
= hData
-> mEvOffset
[hData
-> mEvStart
] * step
;
1808 end
= hData
-> mIrCount
* step
;
1809 m
= 1 + (hData
-> mFftSize
/ 2);
1810 for (j
= start
; j
< end
; j
+= step
) {
1811 for (i
= 0; i
< m
; i
++)
1812 hData
-> mHrirs
[j
+ i
] /= dfa
[i
];
1816 // Perform minimum-phase reconstruction using the magnitude responses of the
1818 static void ReconstructHrirs (const HrirDataT
* hData
) {
1819 double * re
= NULL
, * im
= NULL
;
1820 uint step
, start
, end
, n
, j
, i
;
1822 step
= hData
-> mIrSize
;
1823 start
= hData
-> mEvOffset
[hData
-> mEvStart
] * step
;
1824 end
= hData
-> mIrCount
* step
;
1825 n
= hData
-> mFftSize
;
1826 re
= CreateArray (n
);
1827 im
= CreateArray (n
);
1828 for (j
= start
; j
< end
; j
+= step
) {
1829 MinimumPhase (n
, & hData
-> mHrirs
[j
], re
, im
);
1830 FftInverse (n
, re
, im
, re
, im
);
1831 for (i
= 0; i
< hData
-> mIrPoints
; i
++)
1832 hData
-> mHrirs
[j
+ i
] = re
[i
];
1838 // Resamples the HRIRs for use at the given sampling rate.
1839 static void ResampleHrirs (const uint rate
, HrirDataT
* hData
) {
1841 uint n
, step
, start
, end
, j
;
1843 ResamplerSetup (& rs
, hData
-> mIrRate
, rate
);
1844 n
= hData
-> mIrPoints
;
1845 step
= hData
-> mIrSize
;
1846 start
= hData
-> mEvOffset
[hData
-> mEvStart
] * step
;
1847 end
= hData
-> mIrCount
* step
;
1848 for (j
= start
; j
< end
; j
+= step
)
1849 ResamplerRun (& rs
, n
, & hData
-> mHrirs
[j
], n
, & hData
-> mHrirs
[j
]);
1850 ResamplerClear (& rs
);
1851 hData
-> mIrRate
= rate
;
1854 /* Given an elevation index and an azimuth, calculate the indices of the two
1855 * HRIRs that bound the coordinate along with a factor for calculating the
1856 * continous HRIR using interpolation.
1858 static void CalcAzIndices (const HrirDataT
* hData
, const uint ei
, const double az
, uint
* j0
, uint
* j1
, double * jf
) {
1862 af
= ((2.0 * M_PI
) + az
) * hData
-> mAzCount
[ei
] / (2.0 * M_PI
);
1863 ai
= ((uint
) af
) % hData
-> mAzCount
[ei
];
1865 (* j0
) = hData
-> mEvOffset
[ei
] + ai
;
1866 (* j1
) = hData
-> mEvOffset
[ei
] + ((ai
+ 1) % hData
-> mAzCount
[ei
]);
1870 /* Attempt to synthesize any missing HRIRs at the bottom elevations. Right
1871 * now this just blends the lowest elevation HRIRs together and applies some
1872 * attenuation and high frequency damping. It is a simple, if inaccurate
1875 static void SynthesizeHrirs (HrirDataT
* hData
) {
1876 uint oi
, a
, e
, step
, n
, i
, j
;
1880 double lp
[4], s0
, s1
;
1882 if (hData
-> mEvStart
<= 0)
1884 step
= hData
-> mIrSize
;
1885 oi
= hData
-> mEvStart
;
1886 n
= hData
-> mIrPoints
;
1887 for (i
= 0; i
< n
; i
++)
1888 hData
-> mHrirs
[i
] = 0.0;
1889 for (a
= 0; a
< hData
-> mAzCount
[oi
]; a
++) {
1890 j
= (hData
-> mEvOffset
[oi
] + a
) * step
;
1891 for (i
= 0; i
< n
; i
++)
1892 hData
-> mHrirs
[i
] += hData
-> mHrirs
[j
+ i
] / hData
-> mAzCount
[oi
];
1894 for (e
= 1; e
< hData
-> mEvStart
; e
++) {
1895 of
= ((double) e
) / hData
-> mEvStart
;
1896 b
= (1.0 - of
) * (3.5e-6 * hData
-> mIrRate
);
1897 for (a
= 0; a
< hData
-> mAzCount
[e
]; a
++) {
1898 j
= (hData
-> mEvOffset
[e
] + a
) * step
;
1899 CalcAzIndices (hData
, oi
, a
* 2.0 * M_PI
/ hData
-> mAzCount
[e
], & j0
, & j1
, & jf
);
1906 for (i
= 0; i
< n
; i
++) {
1907 s0
= hData
-> mHrirs
[i
];
1908 s1
= Lerp (hData
-> mHrirs
[j0
+ i
], hData
-> mHrirs
[j1
+ i
], jf
);
1909 s0
= Lerp (s0
, s1
, of
);
1910 lp
[0] = Lerp (s0
, lp
[0], b
);
1911 lp
[1] = Lerp (lp
[0], lp
[1], b
);
1912 lp
[2] = Lerp (lp
[1], lp
[2], b
);
1913 lp
[3] = Lerp (lp
[2], lp
[3], b
);
1914 hData
-> mHrirs
[j
+ i
] = lp
[3];
1918 b
= 3.5e-6 * hData
-> mIrRate
;
1923 for (i
= 0; i
< n
; i
++) {
1924 s0
= hData
-> mHrirs
[i
];
1925 lp
[0] = Lerp (s0
, lp
[0], b
);
1926 lp
[1] = Lerp (lp
[0], lp
[1], b
);
1927 lp
[2] = Lerp (lp
[1], lp
[2], b
);
1928 lp
[3] = Lerp (lp
[2], lp
[3], b
);
1929 hData
-> mHrirs
[i
] = lp
[3];
1931 hData
-> mEvStart
= 0;
1934 // The following routines assume a full set of HRIRs for all elevations.
1936 // Normalize the HRIR set and slightly attenuate the result.
1937 static void NormalizeHrirs (const HrirDataT
* hData
) {
1938 uint step
, end
, n
, j
, i
;
1941 step
= hData
-> mIrSize
;
1942 end
= hData
-> mIrCount
* step
;
1943 n
= hData
-> mIrPoints
;
1945 for (j
= 0; j
< end
; j
+= step
) {
1946 for (i
= 0; i
< n
; i
++)
1947 maxLevel
= fmax (fabs (hData
-> mHrirs
[j
+ i
]), maxLevel
);
1949 maxLevel
= 1.01 * maxLevel
;
1950 for (j
= 0; j
< end
; j
+= step
) {
1951 for (i
= 0; i
< n
; i
++)
1952 hData
-> mHrirs
[j
+ i
] /= maxLevel
;
1956 // Calculate the left-ear time delay using a spherical head model.
1957 static double CalcLTD (const double ev
, const double az
, const double rad
, const double dist
) {
1958 double azp
, dlp
, l
, al
;
1960 azp
= asin (cos (ev
) * sin (az
));
1961 dlp
= sqrt ((dist
* dist
) + (rad
* rad
) + (2.0 * dist
* rad
* sin (azp
)));
1962 l
= sqrt ((dist
* dist
) - (rad
* rad
));
1963 al
= (0.5 * M_PI
) + azp
;
1965 dlp
= l
+ (rad
* (al
- acos (rad
/ dist
)));
1966 return (dlp
/ 343.3);
1969 // Calculate the effective head-related time delays for the each HRIR, now
1970 // that they are minimum-phase.
1971 static void CalculateHrtds (HrirDataT
* hData
) {
1972 double minHrtd
, maxHrtd
;
1978 for (e
= 0; e
< hData
-> mEvCount
; e
++) {
1979 for (a
= 0; a
< hData
-> mAzCount
[e
]; a
++) {
1980 j
= hData
-> mEvOffset
[e
] + a
;
1981 t
= CalcLTD ((-90.0 + (e
* 180.0 / (hData
-> mEvCount
- 1))) * M_PI
/ 180.0,
1982 (a
* 360.0 / hData
-> mAzCount
[e
]) * M_PI
/ 180.0,
1983 hData
-> mRadius
, hData
-> mDistance
);
1984 hData
-> mHrtds
[j
] = t
;
1985 maxHrtd
= fmax (t
, maxHrtd
);
1986 minHrtd
= fmin (t
, minHrtd
);
1990 for (j
= 0; j
< hData
-> mIrCount
; j
++)
1991 hData
-> mHrtds
[j
] -= minHrtd
;
1992 hData
-> mMaxHrtd
= maxHrtd
;
1995 // Store the OpenAL Soft HRTF data set.
1996 static int StoreMhr (const HrirDataT
* hData
, const char * filename
) {
1998 uint e
, step
, end
, n
, j
, i
;
2001 if ((fp
= fopen (filename
, "wb")) == NULL
) {
2002 fprintf (stderr
, "Error: Could not open MHR file '%s'.\n", filename
);
2005 if (! WriteAscii (MHR_FORMAT
, fp
, filename
))
2007 if (! WriteBin4 (BO_LITTLE
, 4, (uint4
) hData
-> mIrRate
, fp
, filename
))
2009 if (! WriteBin4 (BO_LITTLE
, 1, (uint4
) hData
-> mIrPoints
, fp
, filename
))
2011 if (! WriteBin4 (BO_LITTLE
, 1, (uint4
) hData
-> mEvCount
, fp
, filename
))
2013 for (e
= 0; e
< hData
-> mEvCount
; e
++) {
2014 if (! WriteBin4 (BO_LITTLE
, 1, (uint4
) hData
-> mAzCount
[e
], fp
, filename
))
2017 step
= hData
-> mIrSize
;
2018 end
= hData
-> mIrCount
* step
;
2019 n
= hData
-> mIrPoints
;
2021 for (j
= 0; j
< end
; j
+= step
) {
2023 for (i
= 0; i
< n
; i
++) {
2024 v
= HpTpdfDither (32767.0 * hData
-> mHrirs
[j
+ i
], & hpHist
);
2025 if (! WriteBin4 (BO_LITTLE
, 2, (uint4
) v
, fp
, filename
))
2029 for (j
= 0; j
< hData
-> mIrCount
; j
++) {
2030 v
= (int) fmin (round (hData
-> mIrRate
* hData
-> mHrtds
[j
]), MAX_HRTD
);
2031 if (! WriteBin4 (BO_LITTLE
, 1, (uint4
) v
, fp
, filename
))
2038 // Store the OpenAL Soft built-in table.
2039 static int StoreTable (const HrirDataT
* hData
, const char * filename
) {
2041 uint step
, end
, n
, j
, i
;
2043 char text
[128 + 1];
2045 if ((fp
= fopen (filename
, "wb")) == NULL
) {
2046 fprintf (stderr
, "Error: Could not open table file '%s'.\n", filename
);
2049 snprintf (text
, 128, "/* Elevation metrics */\n"
2050 "static const ALubyte defaultAzCount[%u] = { ", hData
-> mEvCount
);
2051 if (! WriteAscii (text
, fp
, filename
))
2053 for (i
= 0; i
< hData
-> mEvCount
; i
++) {
2054 snprintf (text
, 128, "%u, ", hData
-> mAzCount
[i
]);
2055 if (! WriteAscii (text
, fp
, filename
))
2058 snprintf (text
, 128, "};\n"
2059 "static const ALushort defaultEvOffset[%u] = { ", hData
-> mEvCount
);
2060 if (! WriteAscii (text
, fp
, filename
))
2062 for (i
= 0; i
< hData
-> mEvCount
; i
++) {
2063 snprintf (text
, 128, "%u, ", hData
-> mEvOffset
[i
]);
2064 if (! WriteAscii (text
, fp
, filename
))
2067 step
= hData
-> mIrSize
;
2068 end
= hData
-> mIrCount
* step
;
2069 n
= hData
-> mIrPoints
;
2070 snprintf (text
, 128, "};\n\n"
2071 "/* HRIR Coefficients */\n"
2072 "static const ALshort defaultCoeffs[%u] =\n{\n", hData
-> mIrCount
* n
);
2073 if (! WriteAscii (text
, fp
, filename
))
2076 for (j
= 0; j
< end
; j
+= step
) {
2077 if (! WriteAscii (" ", fp
, filename
))
2080 for (i
= 0; i
< n
; i
++) {
2081 v
= HpTpdfDither (32767.0 * hData
-> mHrirs
[j
+ i
], & hpHist
);
2082 snprintf (text
, 128, " %+d,", v
);
2083 if (! WriteAscii (text
, fp
, filename
))
2086 if (! WriteAscii ("\n", fp
, filename
))
2089 snprintf (text
, 128, "};\n\n"
2090 "/* HRIR Delays */\n"
2091 "static const ALubyte defaultDelays[%u] =\n{\n"
2092 " ", hData
-> mIrCount
);
2093 if (! WriteAscii (text
, fp
, filename
))
2095 for (j
= 0; j
< hData
-> mIrCount
; j
++) {
2096 v
= (int) fmin (round (hData
-> mIrRate
* hData
-> mHrtds
[j
]), MAX_HRTD
);
2097 snprintf (text
, 128, " %d,", v
);
2098 if (! WriteAscii (text
, fp
, filename
))
2101 if (! WriteAscii ("\n};\n\n"
2102 "/* Default HRTF Definition */\n", fp
, filename
))
2104 snprintf (text
, 128, "static const struct Hrtf DefaultHrtf = {\n"
2105 " %u, %u, %u, defaultAzCount, defaultEvOffset,\n",
2106 hData
-> mIrRate
, hData
-> mIrPoints
, hData
-> mEvCount
);
2107 if (! WriteAscii (text
, fp
, filename
))
2109 if (! WriteAscii (" defaultCoeffs, defaultDelays, NULL\n"
2110 "};\n", fp
, filename
))
2116 // Process the data set definition to read and validate the data set metrics.
2117 static int ProcessMetrics (TokenReaderT
* tr
, const uint fftSize
, const uint truncSize
, HrirDataT
* hData
) {
2118 char ident
[MAX_IDENT_LEN
+ 1];
2123 int hasRate
= 0, hasPoints
= 0, hasAzimuths
= 0;
2124 int hasRadius
= 0, hasDistance
= 0;
2126 while (! (hasRate
&& hasPoints
&& hasAzimuths
&& hasRadius
&& hasDistance
)) {
2127 TrIndication (tr
, & line
, & col
);
2128 if (! TrReadIdent (tr
, MAX_IDENT_LEN
, ident
))
2130 if (strcasecmp (ident
, "rate") == 0) {
2132 TrErrorAt (tr
, line
, col
, "Redefinition of 'rate'.\n");
2135 if (! TrReadOperator (tr
, "="))
2137 if (! TrReadInt (tr
, MIN_RATE
, MAX_RATE
, & intVal
))
2139 hData
-> mIrRate
= (uint
) intVal
;
2141 } else if (strcasecmp (ident
, "points") == 0) {
2143 TrErrorAt (tr
, line
, col
, "Redefinition of 'points'.\n");
2146 if (! TrReadOperator (tr
, "="))
2148 TrIndication (tr
, & line
, & col
);
2149 if (! TrReadInt (tr
, MIN_POINTS
, MAX_POINTS
, & intVal
))
2151 points
= (uint
) intVal
;
2152 if ((fftSize
> 0) && (points
> fftSize
)) {
2153 TrErrorAt (tr
, line
, col
, "Value exceeds the overriden FFT size.\n");
2156 if (points
< truncSize
) {
2157 TrErrorAt (tr
, line
, col
, "Value is below the truncation size.\n");
2160 hData
-> mIrPoints
= points
;
2161 hData
-> mFftSize
= fftSize
;
2164 while (points
< (4 * hData
-> mIrPoints
))
2166 hData
-> mFftSize
= points
;
2167 hData
-> mIrSize
= 1 + (points
/ 2);
2169 hData
-> mFftSize
= fftSize
;
2170 hData
-> mIrSize
= 1 + (fftSize
/ 2);
2171 if (points
> hData
-> mIrSize
)
2172 hData
-> mIrSize
= points
;
2175 } else if (strcasecmp (ident
, "azimuths") == 0) {
2177 TrErrorAt (tr
, line
, col
, "Redefinition of 'azimuths'.\n");
2180 if (! TrReadOperator (tr
, "="))
2182 hData
-> mIrCount
= 0;
2183 hData
-> mEvCount
= 0;
2184 hData
-> mEvOffset
[0] = 0;
2186 if (! TrReadInt (tr
, MIN_AZ_COUNT
, MAX_AZ_COUNT
, & intVal
))
2188 hData
-> mAzCount
[hData
-> mEvCount
] = (uint
) intVal
;
2189 hData
-> mIrCount
+= (uint
) intVal
;
2190 hData
-> mEvCount
++;
2191 if (! TrIsOperator (tr
, ","))
2193 if (hData
-> mEvCount
>= MAX_EV_COUNT
) {
2194 TrError (tr
, "Exceeded the maximum of %d elevations.\n", MAX_EV_COUNT
);
2197 hData
-> mEvOffset
[hData
-> mEvCount
] = hData
-> mEvOffset
[hData
-> mEvCount
- 1] + ((uint
) intVal
);
2198 TrReadOperator (tr
, ",");
2200 if (hData
-> mEvCount
< MIN_EV_COUNT
) {
2201 TrErrorAt (tr
, line
, col
, "Did not reach the minimum of %d azimuth counts.\n", MIN_EV_COUNT
);
2205 } else if (strcasecmp (ident
, "radius") == 0) {
2207 TrErrorAt (tr
, line
, col
, "Redefinition of 'radius'.\n");
2210 if (! TrReadOperator (tr
, "="))
2212 if (! TrReadFloat (tr
, MIN_RADIUS
, MAX_RADIUS
, & fpVal
))
2214 hData
-> mRadius
= fpVal
;
2216 } else if (strcasecmp (ident
, "distance") == 0) {
2218 TrErrorAt (tr
, line
, col
, "Redefinition of 'distance'.\n");
2221 if (! TrReadOperator (tr
, "="))
2223 if (! TrReadFloat (tr
, MIN_DISTANCE
, MAX_DISTANCE
, & fpVal
))
2225 hData
-> mDistance
= fpVal
;
2228 TrErrorAt (tr
, line
, col
, "Expected a metric name.\n");
2231 TrSkipWhitespace (tr
);
2236 // Parse an index pair from the data set definition.
2237 static int ReadIndexPair (TokenReaderT
* tr
, const HrirDataT
* hData
, uint
* ei
, uint
* ai
) {
2240 if (! TrReadInt (tr
, 0, (int) hData
-> mEvCount
, & intVal
))
2242 (* ei
) = (uint
) intVal
;
2243 if (! TrReadOperator (tr
, ","))
2245 if (! TrReadInt (tr
, 0, (int) hData
-> mAzCount
[(* ei
)], & intVal
))
2247 (* ai
) = (uint
) intVal
;
2251 // Match the source format from a given identifier.
2252 static SourceFormatT
MatchSourceFormat (const char * ident
) {
2253 if (strcasecmp (ident
, "wave") == 0)
2255 else if (strcasecmp (ident
, "bin_le") == 0)
2257 else if (strcasecmp (ident
, "bin_be") == 0)
2259 else if (strcasecmp (ident
, "ascii") == 0)
2264 // Match the source element type from a given identifier.
2265 static ElementTypeT
MatchElementType (const char * ident
) {
2266 if (strcasecmp (ident
, "int") == 0)
2268 else if (strcasecmp (ident
, "fp") == 0)
2273 // Parse and validate a source reference from the data set definition.
2274 static int ReadSourceRef (TokenReaderT
* tr
, SourceRefT
* src
) {
2276 char ident
[MAX_IDENT_LEN
+ 1];
2279 TrIndication (tr
, & line
, & col
);
2280 if (! TrReadIdent (tr
, MAX_IDENT_LEN
, ident
))
2282 src
-> mFormat
= MatchSourceFormat (ident
);
2283 if (src
-> mFormat
== SF_NONE
) {
2284 TrErrorAt (tr
, line
, col
, "Expected a source format.\n");
2287 if (! TrReadOperator (tr
, "("))
2289 if (src
-> mFormat
== SF_WAVE
) {
2290 if (! TrReadInt (tr
, 0, MAX_WAVE_CHANNELS
, & intVal
))
2292 src
-> mType
= ET_NONE
;
2295 src
-> mChannel
= (uint
) intVal
;
2298 TrIndication (tr
, & line
, & col
);
2299 if (! TrReadIdent (tr
, MAX_IDENT_LEN
, ident
))
2301 src
-> mType
= MatchElementType (ident
);
2302 if (src
-> mType
== ET_NONE
) {
2303 TrErrorAt (tr
, line
, col
, "Expected a source element type.\n");
2306 if ((src
-> mFormat
== SF_BIN_LE
) || (src
-> mFormat
== SF_BIN_BE
)) {
2307 if (! TrReadOperator (tr
, ","))
2309 if (src
-> mType
== ET_INT
) {
2310 if (! TrReadInt (tr
, MIN_BIN_SIZE
, MAX_BIN_SIZE
, & intVal
))
2312 src
-> mSize
= (uint
) intVal
;
2313 if (TrIsOperator (tr
, ",")) {
2314 TrReadOperator (tr
, ",");
2315 TrIndication (tr
, & line
, & col
);
2316 if (! TrReadInt (tr
, -2147483647 - 1, 2147483647, & intVal
))
2318 if ((abs (intVal
) < MIN_BIN_BITS
) || (((uint
) abs (intVal
)) > (8 * src
-> mSize
))) {
2319 TrErrorAt (tr
, line
, col
, "Expected a value of (+/-) %d to %d.\n", MIN_BIN_BITS
, 8 * src
-> mSize
);
2322 src
-> mBits
= intVal
;
2324 src
-> mBits
= (int) (8 * src
-> mSize
);
2327 TrIndication (tr
, & line
, & col
);
2328 if (! TrReadInt (tr
, -2147483647 - 1, 2147483647, & intVal
))
2330 if ((intVal
!= 4) && (intVal
!= 8)) {
2331 TrErrorAt (tr
, line
, col
, "Expected a value of 4 or 8.\n");
2334 src
-> mSize
= (uint
) intVal
;
2337 } else if ((src
-> mFormat
== SF_ASCII
) && (src
-> mType
== ET_INT
)) {
2338 if (! TrReadOperator (tr
, ","))
2340 if (! TrReadInt (tr
, MIN_ASCII_BITS
, MAX_ASCII_BITS
, & intVal
))
2343 src
-> mBits
= intVal
;
2348 if (TrIsOperator (tr
, ";")) {
2349 TrReadOperator (tr
, ";");
2350 if (! TrReadInt (tr
, 0, 0x7FFFFFFF, & intVal
))
2352 src
-> mSkip
= (uint
) intVal
;
2357 if (! TrReadOperator (tr
, ")"))
2359 if (TrIsOperator (tr
, "@")) {
2360 TrReadOperator (tr
, "@");
2361 if (! TrReadInt (tr
, 0, 0x7FFFFFFF, & intVal
))
2363 src
-> mOffset
= (uint
) intVal
;
2367 if (! TrReadOperator (tr
, ":"))
2369 if (! TrReadString (tr
, MAX_PATH_LEN
, src
-> mPath
))
2374 // Process the list of sources in the data set definition.
2375 static int ProcessSources (TokenReaderT
* tr
, HrirDataT
* hData
) {
2376 uint
* setCount
= NULL
, * setFlag
= NULL
;
2377 double * hrir
= NULL
;
2378 uint line
, col
, ei
, ai
;
2382 setCount
= (uint
*) calloc (hData
-> mEvCount
, sizeof (uint
));
2383 setFlag
= (uint
*) calloc (hData
-> mIrCount
, sizeof (uint
));
2384 hrir
= CreateArray (hData
-> mIrPoints
);
2385 while (TrIsOperator (tr
, "[")) {
2386 TrIndication (tr
, & line
, & col
);
2387 TrReadOperator (tr
, "[");
2388 if (ReadIndexPair (tr
, hData
, & ei
, & ai
)) {
2389 if (TrReadOperator (tr
, "]")) {
2390 if (! setFlag
[hData
-> mEvOffset
[ei
] + ai
]) {
2391 if (TrReadOperator (tr
, "=")) {
2394 if (ReadSourceRef (tr
, & src
)) {
2395 if (LoadSource (& src
, hData
-> mIrRate
, hData
-> mIrPoints
, hrir
)) {
2396 AverageHrirMagnitude (hrir
, 1.0 / factor
, ei
, ai
, hData
);
2398 if (! TrIsOperator (tr
, "+"))
2400 TrReadOperator (tr
, "+");
2404 DestroyArray (hrir
);
2409 setFlag
[hData
-> mEvOffset
[ei
] + ai
] = 1;
2414 TrErrorAt (tr
, line
, col
, "Redefinition of source.\n");
2418 DestroyArray (hrir
);
2424 while ((ei
< hData
-> mEvCount
) && (setCount
[ei
] < 1))
2426 if (ei
< hData
-> mEvCount
) {
2427 hData
-> mEvStart
= ei
;
2428 while ((ei
< hData
-> mEvCount
) && (setCount
[ei
] == hData
-> mAzCount
[ei
]))
2430 if (ei
>= hData
-> mEvCount
) {
2431 if (! TrLoad (tr
)) {
2432 DestroyArray (hrir
);
2437 TrError (tr
, "Errant data at end of source list.\n");
2440 TrError (tr
, "Missing sources for elevation index %d.\n", ei
);
2443 TrError (tr
, "Missing source references.\n");
2445 DestroyArray (hrir
);
2451 /* Parse the data set definition and process the source data, storing the
2452 * resulting data set as desired. If the input name is NULL it will read
2453 * from standard input.
2455 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 OutputFormatT outFormat
, const char * outName
) {
2459 double * dfa
= NULL
;
2460 char rateStr
[8 + 1], expName
[MAX_PATH_LEN
];
2462 hData
. mIrRate
= 0;
2463 hData
. mIrPoints
= 0;
2464 hData
. mFftSize
= 0;
2465 hData
. mIrSize
= 0;
2466 hData
. mIrCount
= 0;
2467 hData
. mEvCount
= 0;
2468 hData
. mRadius
= 0;
2469 hData
. mDistance
= 0;
2470 fprintf (stdout
, "Reading HRIR definition...\n");
2471 if (inName
!= NULL
) {
2472 fp
= fopen (inName
, "r");
2474 fprintf (stderr
, "Error: Could not open definition file '%s'\n", inName
);
2477 TrSetup (fp
, inName
, & tr
);
2480 TrSetup (fp
, "<stdin>", & tr
);
2482 if (! ProcessMetrics (& tr
, fftSize
, truncSize
, & hData
)) {
2487 hData
. mHrirs
= CreateArray (hData
. mIrCount
* hData
. mIrSize
);
2488 hData
. mHrtds
= CreateArray (hData
. mIrCount
);
2489 if (! ProcessSources (& tr
, & hData
)) {
2490 DestroyArray (hData
. mHrtds
);
2491 DestroyArray (hData
. mHrirs
);
2499 dfa
= CreateArray (1 + (hData
. mFftSize
/ 2));
2500 fprintf (stdout
, "Calculating diffuse-field average...\n");
2501 CalculateDiffuseFieldAverage (& hData
, surface
, limit
, dfa
);
2502 fprintf (stdout
, "Performing diffuse-field equalization...\n");
2503 DiffuseFieldEqualize (dfa
, & hData
);
2506 fprintf (stdout
, "Performing minimum phase reconstruction...\n");
2507 ReconstructHrirs (& hData
);
2508 if ((outRate
!= 0) && (outRate
!= hData
. mIrRate
)) {
2509 fprintf (stdout
, "Resampling HRIRs...\n");
2510 ResampleHrirs (outRate
, & hData
);
2512 fprintf (stdout
, "Truncating minimum-phase HRIRs...\n");
2513 hData
. mIrPoints
= truncSize
;
2514 fprintf (stdout
, "Synthesizing missing elevations...\n");
2515 SynthesizeHrirs (& hData
);
2516 fprintf (stdout
, "Normalizing final HRIRs...\n");
2517 NormalizeHrirs (& hData
);
2518 fprintf (stdout
, "Calculating impulse delays...\n");
2519 CalculateHrtds (& hData
);
2520 snprintf (rateStr
, 8, "%u", hData
. mIrRate
);
2521 StrSubst (outName
, "%r", rateStr
, MAX_PATH_LEN
, expName
);
2522 switch (outFormat
) {
2524 fprintf (stdout
, "Creating MHR data set file...\n");
2525 if (! StoreMhr (& hData
, expName
))
2529 fprintf (stderr
, "Creating OpenAL Soft table file...\n");
2530 if (! StoreTable (& hData
, expName
))
2536 DestroyArray (hData
. mHrtds
);
2537 DestroyArray (hData
. mHrirs
);
2541 // Standard command line dispatch.
2542 int main (const int argc
, const char * argv
[]) {
2543 const char * inName
= NULL
, * outName
= NULL
;
2544 OutputFormatT outFormat
;
2546 uint outRate
, fftSize
;
2547 int equalize
, surface
;
2553 fprintf (stderr
, "Error: No command specified. See '%s -h' for help.\n", argv
[0]);
2556 if ((strcmp (argv
[1], "--help") == 0) || (strcmp (argv
[1], "-h") == 0)) {
2557 fprintf (stdout
, "HRTF Processing and Composition Utility\n\n");
2558 fprintf (stdout
, "Usage: %s <command> [<option>...]\n\n", argv
[0]);
2559 fprintf (stdout
, "Commands:\n");
2560 fprintf (stdout
, " -m, --make-mhr Makes an OpenAL Soft compatible HRTF data set.\n");
2561 fprintf (stdout
, " Defaults output to: ./oalsoft_hrtf_%%r.mhr\n");
2562 fprintf (stdout
, " -t, --make-tab Makes the built-in table used when compiling OpenAL Soft.\n");
2563 fprintf (stdout
, " Defaults output to: ./hrtf_tables.inc\n");
2564 fprintf (stdout
, " -h, --help Displays this help information.\n\n");
2565 fprintf (stdout
, "Options:\n");
2566 fprintf (stdout
, " -r=<rate> Change the data set sample rate to the specified value and\n");
2567 fprintf (stdout
, " resample the HRIRs accordingly.\n");
2568 fprintf (stdout
, " -f=<points> Override the FFT window size (defaults to the first power-\n");
2569 fprintf (stdout
, " of-two that fits four times the number of HRIR points).\n");
2570 fprintf (stdout
, " -e={on|off} Toggle diffuse-field equalization (default: %s).\n", (DEFAULT_EQUALIZE
? "on" : "off"));
2571 fprintf (stdout
, " -s={on|off} Toggle surface-weighted diffuse-field average (default: %s).\n", (DEFAULT_SURFACE
? "on" : "off"));
2572 fprintf (stdout
, " -l={<dB>|none} Specify a limit to the magnitude range of the diffuse-field\n");
2573 fprintf (stdout
, " average (default: %.2f).\n", DEFAULT_LIMIT
);
2574 fprintf (stdout
, " -w=<points> Specify the size of the truncation window that's applied\n");
2575 fprintf (stdout
, " after minimum-phase reconstruction (default: %u).\n", DEFAULT_TRUNCSIZE
);
2576 fprintf (stdout
, " -i=<filename> Specify an HRIR definition file to use (defaults to stdin).\n");
2577 fprintf (stdout
, " -o=<filename> Specify an output file. Overrides command-selected default.\n");
2578 fprintf (stdout
, " Use of '%%r' will be substituted with the data set sample rate.\n");
2581 if ((strcmp (argv
[1], "--make-mhr") == 0) || (strcmp (argv
[1], "-m") == 0)) {
2585 outName
= "./oalsoft_hrtf_%r.mhr";
2587 } else if ((strcmp (argv
[1], "--make-tab") == 0) || (strcmp (argv
[1], "-t") == 0)) {
2591 outName
= "./hrtf_tables.inc";
2592 outFormat
= OF_TABLE
;
2594 fprintf (stderr
, "Error: Invalid command '%s'.\n", argv
[1]);
2600 equalize
= DEFAULT_EQUALIZE
;
2601 surface
= DEFAULT_SURFACE
;
2602 limit
= DEFAULT_LIMIT
;
2603 truncSize
= DEFAULT_TRUNCSIZE
;
2604 while (argi
< argc
) {
2605 if (strncmp (argv
[argi
], "-r=", 3) == 0) {
2606 outRate
= strtoul (& argv
[argi
] [3], & end
, 10);
2607 if ((end
[0] != '\0') || (outRate
< MIN_RATE
) || (outRate
> MAX_RATE
)) {
2608 fprintf (stderr
, "Error: Expected a value from %u to %u for '-r'.\n", MIN_RATE
, MAX_RATE
);
2611 } else if (strncmp (argv
[argi
], "-f=", 3) == 0) {
2612 fftSize
= strtoul (& argv
[argi
] [3], & end
, 10);
2613 if ((end
[0] != '\0') || (fftSize
& (fftSize
- 1)) || (fftSize
< MIN_FFTSIZE
) || (fftSize
> MAX_FFTSIZE
)) {
2614 fprintf (stderr
, "Error: Expected a power-of-two value from %u to %u for '-f'.\n", MIN_FFTSIZE
, MAX_FFTSIZE
);
2617 } else if (strncmp (argv
[argi
], "-e=", 3) == 0) {
2618 if (strcmp (& argv
[argi
] [3], "on") == 0) {
2620 } else if (strcmp (& argv
[argi
] [3], "off") == 0) {
2623 fprintf (stderr
, "Error: Expected 'on' or 'off' for '-e'.\n");
2626 } else if (strncmp (argv
[argi
], "-s=", 3) == 0) {
2627 if (strcmp (& argv
[argi
] [3], "on") == 0) {
2629 } else if (strcmp (& argv
[argi
] [3], "off") == 0) {
2632 fprintf (stderr
, "Error: Expected 'on' or 'off' for '-s'.\n");
2635 } else if (strncmp (argv
[argi
], "-l=", 3) == 0) {
2636 if (strcmp (& argv
[argi
] [3], "none") == 0) {
2639 limit
= strtod (& argv
[argi
] [3], & end
);
2640 if ((end
[0] != '\0') || (limit
< MIN_LIMIT
) || (limit
> MAX_LIMIT
)) {
2641 fprintf (stderr
, "Error: Expected 'none' or a value from %.2f to %.2f for '-l'.\n", MIN_LIMIT
, MAX_LIMIT
);
2645 } else if (strncmp (argv
[argi
], "-w=", 3) == 0) {
2646 truncSize
= strtoul (& argv
[argi
] [3], & end
, 10);
2647 if ((end
[0] != '\0') || (truncSize
< MIN_TRUNCSIZE
) || (truncSize
> MAX_TRUNCSIZE
) || (truncSize
% MOD_TRUNCSIZE
)) {
2648 fprintf (stderr
, "Error: Expected a value from %u to %u in multiples of %u for '-w'.\n", MIN_TRUNCSIZE
, MAX_TRUNCSIZE
, MOD_TRUNCSIZE
);
2651 } else if (strncmp (argv
[argi
], "-i=", 3) == 0) {
2652 inName
= & argv
[argi
] [3];
2653 } else if (strncmp (argv
[argi
], "-o=", 3) == 0) {
2654 outName
= & argv
[argi
] [3];
2656 fprintf (stderr
, "Error: Invalid option '%s'.\n", argv
[argi
]);
2661 if (! ProcessDefinition (inName
, outRate
, fftSize
, equalize
, surface
, limit
, truncSize
, outFormat
, outName
))
2663 fprintf (stdout
, "Operation completed.\n");