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.
233 // Unsigned integer type.
234 typedef unsigned int uint
;
236 // Serialization types. The trailing digit indicates the number of bits.
237 typedef ALubyte uint8
;
240 typedef ALuint uint32
;
241 typedef ALuint64SOFT uint64
;
243 typedef enum ByteOrderT ByteOrderT
;
244 typedef enum SourceFormatT SourceFormatT
;
245 typedef enum ElementTypeT ElementTypeT
;
246 typedef enum HeadModelT HeadModelT
;
247 typedef enum OutputFormatT OutputFormatT
;
249 typedef struct TokenReaderT TokenReaderT
;
250 typedef struct SourceRefT SourceRefT
;
251 typedef struct HrirDataT HrirDataT
;
252 typedef struct ResamplerT ResamplerT
;
254 // Token reader state for parsing the data set definition.
255 struct TokenReaderT
{
260 char mRing
[TR_RING_SIZE
];
265 // Source reference state used when loading sources.
267 SourceFormatT mFormat
;
274 char mPath
[MAX_PATH_LEN
+ 1];
277 // The HRIR metrics and data set used when loading, processing, and storing
278 // the resulting HRTF.
287 mAzCount
[MAX_EV_COUNT
],
288 mEvOffset
[MAX_EV_COUNT
];
296 // The resampler metrics and FIR filter.
305 /* Token reader routines for parsing text files. Whitespace is not
306 * significant. It can process tokens as identifiers, numbers (integer and
307 * floating-point), strings, and operators. Strings must be encapsulated by
308 * double-quotes and cannot span multiple lines.
311 // Setup the reader on the given file. The filename can be NULL if no error
312 // output is desired.
313 static void TrSetup (FILE * fp
, const char * filename
, TokenReaderT
* tr
) {
314 const char * name
= NULL
;
319 // If a filename was given, store a pointer to the base name.
320 if (filename
!= NULL
) {
321 while ((ch
= (* filename
)) != '\0') {
322 if ((ch
== '/') || (ch
== '\\'))
334 // Prime the reader's ring buffer, and return a result indicating that there
335 // is text to process.
336 static int TrLoad (TokenReaderT
* tr
) {
337 size_t toLoad
, in
, count
;
339 toLoad
= TR_RING_SIZE
- (tr
-> mIn
- tr
-> mOut
);
340 if ((toLoad
>= TR_LOAD_SIZE
) && (! feof (tr
-> mFile
))) {
341 // Load TR_LOAD_SIZE (or less if at the end of the file) per read.
342 toLoad
= TR_LOAD_SIZE
;
343 in
= tr
-> mIn
& TR_RING_MASK
;
344 count
= TR_RING_SIZE
- in
;
345 if (count
< toLoad
) {
346 tr
-> mIn
+= fread (& tr
-> mRing
[in
], 1, count
, tr
-> mFile
);
347 tr
-> mIn
+= fread (& tr
-> mRing
[0], 1, toLoad
- count
, tr
-> mFile
);
349 tr
-> mIn
+= fread (& tr
-> mRing
[in
], 1, toLoad
, tr
-> mFile
);
351 if (tr
-> mOut
>= TR_RING_SIZE
) {
352 tr
-> mOut
-= TR_RING_SIZE
;
353 tr
-> mIn
-= TR_RING_SIZE
;
356 if (tr
-> mIn
> tr
-> mOut
)
361 // Error display routine. Only displays when the base name is not NULL.
362 static void TrErrorVA (const TokenReaderT
* tr
, uint line
, uint column
, const char * format
, va_list argPtr
) {
363 if (tr
-> mName
!= NULL
) {
364 fprintf (stderr
, "Error (%s:%u:%u): ", tr
-> mName
, line
, column
);
365 vfprintf (stderr
, format
, argPtr
);
369 // Used to display an error at a saved line/column.
370 static void TrErrorAt (const TokenReaderT
* tr
, uint line
, uint column
, const char * format
, ...) {
373 va_start (argPtr
, format
);
374 TrErrorVA (tr
, line
, column
, format
, argPtr
);
378 // Used to display an error at the current line/column.
379 static void TrError (const TokenReaderT
* tr
, const char * format
, ...) {
382 va_start (argPtr
, format
);
383 TrErrorVA (tr
, tr
-> mLine
, tr
-> mColumn
, format
, argPtr
);
387 // Skips to the next line.
388 static void TrSkipLine (TokenReaderT
* tr
) {
391 while (TrLoad (tr
)) {
392 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
403 // Skips to the next token.
404 static int TrSkipWhitespace (TokenReaderT
* tr
) {
407 while (TrLoad (tr
)) {
408 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
417 } else if (ch
== '#') {
426 // Get the line and/or column of the next token (or the end of input).
427 static void TrIndication (TokenReaderT
* tr
, uint
* line
, uint
* column
) {
428 TrSkipWhitespace (tr
);
430 (* line
) = tr
-> mLine
;
432 (* column
) = tr
-> mColumn
;
435 // Checks to see if a token is the given operator. It does not display any
436 // errors and will not proceed to the next token.
437 static int TrIsOperator (TokenReaderT
* tr
, const char * op
) {
441 if (! TrSkipWhitespace (tr
))
445 while ((op
[len
] != '\0') && (out
< tr
-> mIn
)) {
446 ch
= tr
-> mRing
[out
& TR_RING_MASK
];
452 if (op
[len
] == '\0')
457 /* The TrRead*() routines obtain the value of a matching token type. They
458 * display type, form, and boundary errors and will proceed to the next
462 // Reads and validates an identifier token.
463 static int TrReadIdent (TokenReaderT
* tr
, const uint maxLen
, char * ident
) {
468 if (TrSkipWhitespace (tr
)) {
470 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
471 if ((ch
== '_') || isalpha (ch
)) {
480 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
481 } while ((ch
== '_') || isdigit (ch
) || isalpha (ch
));
482 tr
-> mColumn
+= len
;
484 TrErrorAt (tr
, tr
-> mLine
, col
, "Identifier is too long.\n");
491 TrErrorAt (tr
, tr
-> mLine
, col
, "Expected an identifier.\n");
495 // Reads and validates (including bounds) an integer token.
496 static int TrReadInt (TokenReaderT
* tr
, const int loBound
, const int hiBound
, int * value
) {
497 uint col
, digis
, len
;
498 char ch
, temp
[64 + 1];
501 if (TrSkipWhitespace (tr
)) {
504 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
505 if ((ch
== '+') || (ch
== '-')) {
511 while (TrLoad (tr
)) {
512 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
521 tr
-> mColumn
+= len
;
522 if ((digis
> 0) && (ch
!= '.') && (! isalpha (ch
))) {
524 TrErrorAt (tr
, tr
-> mLine
, col
, "Integer is too long.");
528 (* value
) = strtol (temp
, NULL
, 10);
529 if (((* value
) < loBound
) || ((* value
) > hiBound
)) {
530 TrErrorAt (tr
, tr
-> mLine
, col
, "Expected a value from %d to %d.\n", loBound
, hiBound
);
536 TrErrorAt (tr
, tr
-> mLine
, col
, "Expected an integer.\n");
540 // Reads and validates (including bounds) a float token.
541 static int TrReadFloat (TokenReaderT
* tr
, const double loBound
, const double hiBound
, double * value
) {
542 uint col
, digis
, len
;
543 char ch
, temp
[64 + 1];
546 if (TrSkipWhitespace (tr
)) {
549 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
550 if ((ch
== '+') || (ch
== '-')) {
556 while (TrLoad (tr
)) {
557 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
572 while (TrLoad (tr
)) {
573 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
583 if ((ch
== 'E') || (ch
== 'e')) {
589 if ((ch
== '+') || (ch
== '-')) {
595 while (TrLoad (tr
)) {
596 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
606 tr
-> mColumn
+= len
;
607 if ((digis
> 0) && (ch
!= '.') && (! isalpha (ch
))) {
609 TrErrorAt (tr
, tr
-> mLine
, col
, "Float is too long.");
613 (* value
) = strtod (temp
, NULL
);
614 if (((* value
) < loBound
) || ((* value
) > hiBound
)) {
615 TrErrorAt (tr
, tr
-> mLine
, col
, "Expected a value from %f to %f.\n", loBound
, hiBound
);
621 tr
-> mColumn
+= len
;
624 TrErrorAt (tr
, tr
-> mLine
, col
, "Expected a float.\n");
628 // Reads and validates a string token.
629 static int TrReadString (TokenReaderT
* tr
, const uint maxLen
, char * text
) {
634 if (TrSkipWhitespace (tr
)) {
636 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
640 while (TrLoad (tr
)) {
641 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
646 TrErrorAt (tr
, tr
-> mLine
, col
, "Unterminated string at end of line.\n");
654 tr
-> mColumn
+= 1 + len
;
655 TrErrorAt (tr
, tr
-> mLine
, col
, "Unterminated string at end of input.\n");
658 tr
-> mColumn
+= 2 + len
;
660 TrErrorAt (tr
, tr
-> mLine
, col
, "String is too long.\n");
667 TrErrorAt (tr
, tr
-> mLine
, col
, "Expected a string.\n");
671 // Reads and validates the given operator.
672 static int TrReadOperator (TokenReaderT
* tr
, const char * op
) {
677 if (TrSkipWhitespace (tr
)) {
680 while ((op
[len
] != '\0') && TrLoad (tr
)) {
681 ch
= tr
-> mRing
[tr
-> mOut
& TR_RING_MASK
];
687 tr
-> mColumn
+= len
;
688 if (op
[len
] == '\0')
691 TrErrorAt (tr
, tr
-> mLine
, col
, "Expected '%s' operator.\n", op
);
695 /* Performs a string substitution. Any case-insensitive occurrences of the
696 * pattern string are replaced with the replacement string. The result is
697 * truncated if necessary.
699 static int StrSubst (const char * in
, const char * pat
, const char * rep
, const size_t maxLen
, char * out
) {
700 size_t inLen
, patLen
, repLen
;
705 patLen
= strlen (pat
);
706 repLen
= strlen (rep
);
710 while ((si
< inLen
) && (di
< maxLen
)) {
711 if (patLen
<= (inLen
- si
)) {
712 if (strncasecmp (& in
[si
], pat
, patLen
) == 0) {
713 if (repLen
> (maxLen
- di
)) {
714 repLen
= maxLen
- di
;
717 strncpy (& out
[di
], rep
, repLen
);
729 return (! truncated
);
732 // Provide missing math routines for MSVC versions < 1800 (Visual Studio 2013).
733 #if defined(_MSC_VER) && _MSC_VER < 1800
734 static double round (double val
) {
736 return (ceil (val
- 0.5));
737 return (floor (val
+ 0.5));
740 static double fmin (double a
, double b
) {
741 return ((a
< b
) ? a
: b
);
744 static double fmax (double a
, double b
) {
745 return ((a
> b
) ? a
: b
);
749 // Simple clamp routine.
750 static double Clamp (const double val
, const double lower
, const double upper
) {
751 return (fmin (fmax (val
, lower
), upper
));
754 // Performs linear interpolation.
755 static double Lerp (const double a
, const double b
, const double f
) {
756 return (a
+ (f
* (b
- a
)));
759 // Performs a high-passed triangular probability density function dither from
760 // a double to an integer. It assumes the input sample is already scaled.
761 static int HpTpdfDither (const double in
, int * hpHist
) {
762 const double PRNG_SCALE
= 1.0 / (RAND_MAX
+ 1.0);
767 out
= round (in
+ (PRNG_SCALE
* (prn
- (* hpHist
))));
772 // Allocates an array of doubles.
773 static double *CreateArray(size_t n
)
778 a
= calloc(n
, sizeof(double));
781 fprintf(stderr
, "Error: Out of memory.\n");
787 // Frees an array of doubles.
788 static void DestroyArray(double *a
)
791 // Complex number routines. All outputs must be non-NULL.
793 // Magnitude/absolute value.
794 static double ComplexAbs (const double r
, const double i
) {
795 return (sqrt ((r
* r
) + (i
* i
)));
799 static void ComplexMul (const double aR
, const double aI
, const double bR
, const double bI
, double * outR
, double * outI
) {
800 (* outR
) = (aR
* bR
) - (aI
* bI
);
801 (* outI
) = (aI
* bR
) + (aR
* bI
);
805 static void ComplexExp (const double inR
, const double inI
, double * outR
, double * outI
) {
809 (* outR
) = e
* cos (inI
);
810 (* outI
) = e
* sin (inI
);
813 /* Fast Fourier transform routines. The number of points must be a power of
814 * two. In-place operation is possible only if both the real and imaginary
815 * parts are in-place together.
818 // Performs bit-reversal ordering.
819 static void FftArrange (const uint n
, const double * inR
, const double * inI
, double * outR
, double * outI
) {
823 if ((inR
== outR
) && (inI
== outI
)) {
824 // Handle in-place arrangement.
826 for (k
= 0; k
< n
; k
++) {
836 while (rk
& (m
>>= 1))
841 // Handle copy arrangement.
843 for (k
= 0; k
< n
; k
++) {
847 while (rk
& (m
>>= 1))
854 // Performs the summation.
855 static void FftSummation (const uint n
, const double s
, double * re
, double * im
) {
858 double vR
, vI
, wR
, wI
;
863 for (m
= 1, m2
= 2; m
< n
; m
<<= 1, m2
<<= 1) {
864 // v = Complex (-2.0 * sin (0.5 * pi / m) * sin (0.5 * pi / m), -sin (pi / m))
865 vR
= sin (0.5 * pi
/ m
);
868 // w = Complex (1.0, 0.0)
871 for (i
= 0; i
< m
; i
++) {
872 for (k
= i
; k
< n
; k
+= m2
) {
874 // t = ComplexMul (w, out [km2])
875 tR
= (wR
* re
[mk
]) - (wI
* im
[mk
]);
876 tI
= (wR
* im
[mk
]) + (wI
* re
[mk
]);
877 // out [mk] = ComplexSub (out [k], t)
878 re
[mk
] = re
[k
] - tR
;
879 im
[mk
] = im
[k
] - tI
;
880 // out [k] = ComplexAdd (out [k], t)
884 // t = ComplexMul (v, w)
885 tR
= (vR
* wR
) - (vI
* wI
);
886 tI
= (vR
* wI
) + (vI
* wR
);
887 // w = ComplexAdd (w, t)
894 // Performs a forward FFT.
895 static void FftForward (const uint n
, const double * inR
, const double * inI
, double * outR
, double * outI
) {
896 FftArrange (n
, inR
, inI
, outR
, outI
);
897 FftSummation (n
, 1.0, outR
, outI
);
900 // Performs an inverse FFT.
901 static void FftInverse (const uint n
, const double * inR
, const double * inI
, double * outR
, double * outI
) {
905 FftArrange (n
, inR
, inI
, outR
, outI
);
906 FftSummation (n
, -1.0, outR
, outI
);
908 for (i
= 0; i
< n
; i
++) {
914 /* Calculate the complex helical sequence (or discrete-time analytical
915 * signal) of the given input using the Hilbert transform. Given the
916 * negative natural logarithm of a signal's magnitude response, the imaginary
917 * components can be used as the angles for minimum-phase reconstruction.
919 static void Hilbert (const uint n
, const double * in
, double * outR
, double * outI
) {
923 // Handle in-place operation.
924 for (i
= 0; i
< n
; i
++)
927 // Handle copy operation.
928 for (i
= 0; i
< n
; i
++) {
933 FftForward (n
, outR
, outI
, outR
, outI
);
934 /* Currently the Fourier routines operate only on point counts that are
935 * powers of two. If that changes and n is odd, the following conditional
936 * should be: i < (n + 1) / 2.
938 for (i
= 1; i
< (n
/ 2); i
++) {
942 // If n is odd, the following increment should be skipped.
944 for (; i
< n
; i
++) {
948 FftInverse (n
, outR
, outI
, outR
, outI
);
951 /* Calculate the magnitude response of the given input. This is used in
952 * place of phase decomposition, since the phase residuals are discarded for
953 * minimum phase reconstruction. The mirrored half of the response is also
956 static void MagnitudeResponse (const uint n
, const double * inR
, const double * inI
, double * out
) {
957 const uint m
= 1 + (n
/ 2);
960 for (i
= 0; i
< m
; i
++)
961 out
[i
] = fmax (ComplexAbs (inR
[i
], inI
[i
]), EPSILON
);
964 /* Apply a range limit (in dB) to the given magnitude response. This is used
965 * to adjust the effects of the diffuse-field average on the equalization
968 static void LimitMagnitudeResponse (const uint n
, const double limit
, const double * in
, double * out
) {
969 const uint m
= 1 + (n
/ 2);
971 uint i
, lower
, upper
;
974 halfLim
= limit
/ 2.0;
975 // Convert the response to dB.
976 for (i
= 0; i
< m
; i
++)
977 out
[i
] = 20.0 * log10 (in
[i
]);
978 // Use six octaves to calculate the average magnitude of the signal.
979 lower
= ((uint
) ceil (n
/ pow (2.0, 8.0))) - 1;
980 upper
= ((uint
) floor (n
/ pow (2.0, 2.0))) - 1;
982 for (i
= lower
; i
<= upper
; i
++)
984 ave
/= upper
- lower
+ 1;
985 // Keep the response within range of the average magnitude.
986 for (i
= 0; i
< m
; i
++)
987 out
[i
] = Clamp (out
[i
], ave
- halfLim
, ave
+ halfLim
);
988 // Convert the response back to linear magnitude.
989 for (i
= 0; i
< m
; i
++)
990 out
[i
] = pow (10.0, out
[i
] / 20.0);
993 /* Reconstructs the minimum-phase component for the given magnitude response
994 * of a signal. This is equivalent to phase recomposition, sans the missing
995 * residuals (which were discarded). The mirrored half of the response is
998 static void MinimumPhase (const uint n
, const double * in
, double * outR
, double * outI
) {
999 const uint m
= 1 + (n
/ 2);
1000 double * mags
= NULL
;
1004 mags
= CreateArray (n
);
1005 for (i
= 0; i
< m
; i
++) {
1006 mags
[i
] = fmax (in
[i
], EPSILON
);
1007 outR
[i
] = -log (mags
[i
]);
1009 for (; i
< n
; i
++) {
1010 mags
[i
] = mags
[n
- i
];
1011 outR
[i
] = outR
[n
- i
];
1013 Hilbert (n
, outR
, outR
, outI
);
1014 // Remove any DC offset the filter has.
1017 for (i
= 1; i
< n
; i
++) {
1018 ComplexExp (0.0, outI
[i
], & aR
, & aI
);
1019 ComplexMul (mags
[i
], 0.0, aR
, aI
, & outR
[i
], & outI
[i
]);
1021 DestroyArray (mags
);
1024 /* This is the normalized cardinal sine (sinc) function.
1026 * sinc(x) = { 1, x = 0
1027 * { sin(pi x) / (pi x), otherwise.
1029 static double Sinc (const double x
) {
1030 if (fabs (x
) < EPSILON
)
1032 return (sin (M_PI
* x
) / (M_PI
* x
));
1035 /* The zero-order modified Bessel function of the first kind, used for the
1038 * I_0(x) = sum_{k=0}^inf (1 / k!)^2 (x / 2)^(2 k)
1039 * = sum_{k=0}^inf ((x / 2)^k / k!)^2
1041 static double BesselI_0 (const double x
) {
1042 double term
, sum
, x2
, y
, last_sum
;
1045 // Start at k=1 since k=0 is trivial.
1050 // Let the integration converge until the term of the sum is no longer
1058 } while (sum
!= last_sum
);
1062 /* Calculate a Kaiser window from the given beta value and a normalized k
1065 * w(k) = { I_0(B sqrt(1 - k^2)) / I_0(B), -1 <= k <= 1
1068 * Where k can be calculated as:
1070 * k = i / l, where -l <= i <= l.
1074 * k = 2 i / M - 1, where 0 <= i <= M.
1076 static double Kaiser (const double b
, const double k
) {
1079 k2
= Clamp (k
, -1.0, 1.0);
1080 if ((k
< -1.0) || (k
> 1.0))
1083 return (BesselI_0 (b
* sqrt (1.0 - k2
)) / BesselI_0 (b
));
1086 // Calculates the greatest common divisor of a and b.
1087 static uint
Gcd (const uint a
, const uint b
) {
1100 /* Calculates the size (order) of the Kaiser window. Rejection is in dB and
1101 * the transition width is normalized frequency (0.5 is nyquist).
1103 * M = { ceil((r - 7.95) / (2.285 2 pi f_t)), r > 21
1104 * { ceil(5.79 / 2 pi f_t), r <= 21.
1107 static uint
CalcKaiserOrder (const double rejection
, const double transition
) {
1110 w_t
= 2.0 * M_PI
* transition
;
1111 if (rejection
> 21.0)
1112 return ((uint
) ceil ((rejection
- 7.95) / (2.285 * w_t
)));
1113 return ((uint
) ceil (5.79 / w_t
));
1116 // Calculates the beta value of the Kaiser window. Rejection is in dB.
1117 static double CalcKaiserBeta (const double rejection
) {
1118 if (rejection
> 50.0)
1119 return (0.1102 * (rejection
- 8.7));
1120 else if (rejection
>= 21.0)
1121 return ((0.5842 * pow (rejection
- 21.0, 0.4)) +
1122 (0.07886 * (rejection
- 21.0)));
1127 /* Calculates a point on the Kaiser-windowed sinc filter for the given half-
1128 * width, beta, gain, and cutoff. The point is specified in non-normalized
1129 * samples, from 0 to M, where M = (2 l + 1).
1131 * w(k) 2 p f_t sinc(2 f_t x)
1133 * x -- centered sample index (i - l)
1134 * k -- normalized and centered window index (x / l)
1135 * w(k) -- window function (Kaiser)
1136 * p -- gain compensation factor when sampling
1137 * f_t -- normalized center frequency (or cutoff; 0.5 is nyquist)
1139 static double SincFilter (const int l
, const double b
, const double gain
, const double cutoff
, const int i
) {
1140 return (Kaiser (b
, ((double) (i
- l
)) / l
) * 2.0 * gain
* cutoff
* Sinc (2.0 * cutoff
* (i
- l
)));
1143 /* This is a polyphase sinc-filtered resampler.
1145 * Upsample Downsample
1147 * p/q = 3/2 p/q = 3/5
1149 * M-+-+-+-> M-+-+-+->
1150 * -------------------+ ---------------------+
1151 * p s * f f f f|f| | p s * f f f f f |
1152 * | 0 * 0 0 0|0|0 | | 0 * 0 0 0 0|0| |
1153 * v 0 * 0 0|0|0 0 | v 0 * 0 0 0|0|0 |
1154 * s * f|f|f f f | s * f f|f|f f |
1155 * 0 * |0|0 0 0 0 | 0 * 0|0|0 0 0 |
1156 * --------+=+--------+ 0 * |0|0 0 0 0 |
1157 * d . d .|d|. d . d ----------+=+--------+
1158 * d . . . .|d|. . . .
1162 * P_f(i,j) = q i mod p + pj
1163 * P_s(i,j) = floor(q i / p) - j
1164 * d[i=0..N-1] = sum_{j=0}^{floor((M - 1) / p)} {
1165 * { f[P_f(i,j)] s[P_s(i,j)], P_f(i,j) < M
1166 * { 0, P_f(i,j) >= M. }
1169 // Calculate the resampling metrics and build the Kaiser-windowed sinc filter
1170 // that's used to cut frequencies above the destination nyquist.
1171 static void ResamplerSetup (ResamplerT
* rs
, const uint srcRate
, const uint dstRate
) {
1173 double cutoff
, width
, beta
;
1176 gcd
= Gcd (srcRate
, dstRate
);
1177 rs
-> mP
= dstRate
/ gcd
;
1178 rs
-> mQ
= srcRate
/ gcd
;
1179 /* The cutoff is adjusted by half the transition width, so the transition
1180 * ends before the nyquist (0.5). Both are scaled by the downsampling
1183 if (rs
-> mP
> rs
-> mQ
) {
1184 cutoff
= 0.45 / rs
-> mP
;
1185 width
= 0.1 / rs
-> mP
;
1187 cutoff
= 0.45 / rs
-> mQ
;
1188 width
= 0.1 / rs
-> mQ
;
1190 // A rejection of -180 dB is used for the stop band.
1191 l
= CalcKaiserOrder (180.0, width
) / 2;
1192 beta
= CalcKaiserBeta (180.0);
1193 rs
-> mM
= (2 * l
) + 1;
1195 rs
-> mF
= CreateArray (rs
-> mM
);
1196 for (i
= 0; i
< ((int) rs
-> mM
); i
++)
1197 rs
-> mF
[i
] = SincFilter ((int) l
, beta
, rs
-> mP
, cutoff
, i
);
1200 // Clean up after the resampler.
1201 static void ResamplerClear (ResamplerT
* rs
) {
1202 DestroyArray (rs
-> mF
);
1206 // Perform the upsample-filter-downsample resampling operation using a
1207 // polyphase filter implementation.
1208 static void ResamplerRun (ResamplerT
* rs
, const uint inN
, const double * in
, const uint outN
, double * out
) {
1209 const uint p
= rs
-> mP
, q
= rs
-> mQ
, m
= rs
-> mM
, l
= rs
-> mL
;
1210 const double * f
= rs
-> mF
;
1211 double * work
= NULL
;
1219 // Handle in-place operation.
1221 work
= CreateArray (outN
);
1224 // Resample the input.
1225 for (i
= 0; i
< outN
; i
++) {
1227 // Input starts at l to compensate for the filter delay. This will
1228 // drop any build-up from the first half of the filter.
1229 j_f
= (l
+ (q
* i
)) % p
;
1230 j_s
= (l
+ (q
* i
)) / p
;
1232 // Only take input when 0 <= j_s < inN. This single unsigned
1233 // comparison catches both cases.
1235 r
+= f
[j_f
] * in
[j_s
];
1241 // Clean up after in-place operation.
1243 for (i
= 0; i
< outN
; i
++)
1245 DestroyArray (work
);
1249 // Read a binary value of the specified byte order and byte size from a file,
1250 // storing it as a 32-bit unsigned integer.
1251 static int ReadBin4 (FILE * fp
, const char * filename
, const ByteOrderT order
, const uint bytes
, uint32
* out
) {
1256 if (fread (in
, 1, bytes
, fp
) != bytes
) {
1257 fprintf (stderr
, "Error: Bad read from file '%s'.\n", filename
);
1263 for (i
= 0; i
< bytes
; i
++)
1264 accum
= (accum
<< 8) | in
[bytes
- i
- 1];
1267 for (i
= 0; i
< bytes
; i
++)
1268 accum
= (accum
<< 8) | in
[i
];
1277 // Read a binary value of the specified byte order from a file, storing it as
1278 // a 64-bit unsigned integer.
1279 static int ReadBin8 (FILE * fp
, const char * filename
, const ByteOrderT order
, uint64
* out
) {
1284 if (fread (in
, 1, 8, fp
) != 8) {
1285 fprintf (stderr
, "Error: Bad read from file '%s'.\n", filename
);
1291 for (i
= 0; i
< 8; i
++)
1292 accum
= (accum
<< 8) | in
[8 - i
- 1];
1295 for (i
= 0; i
< 8; i
++)
1296 accum
= (accum
<< 8) | in
[i
];
1305 // Write an ASCII string to a file.
1306 static int WriteAscii (const char * out
, FILE * fp
, const char * filename
) {
1310 if (fwrite (out
, 1, len
, fp
) != len
) {
1312 fprintf (stderr
, "Error: Bad write to file '%s'.\n", filename
);
1318 // Write a binary value of the given byte order and byte size to a file,
1319 // loading it from a 32-bit unsigned integer.
1320 static int WriteBin4 (const ByteOrderT order
, const uint bytes
, const uint32 in
, FILE * fp
, const char * filename
) {
1326 for (i
= 0; i
< bytes
; i
++)
1327 out
[i
] = (in
>> (i
* 8)) & 0x000000FF;
1330 for (i
= 0; i
< bytes
; i
++)
1331 out
[bytes
- i
- 1] = (in
>> (i
* 8)) & 0x000000FF;
1336 if (fwrite (out
, 1, bytes
, fp
) != bytes
) {
1337 fprintf (stderr
, "Error: Bad write to file '%s'.\n", filename
);
1343 /* Read a binary value of the specified type, byte order, and byte size from
1344 * a file, converting it to a double. For integer types, the significant
1345 * bits are used to normalize the result. The sign of bits determines
1346 * whether they are padded toward the MSB (negative) or LSB (positive).
1347 * Floating-point types are not normalized.
1349 static int ReadBinAsDouble (FILE * fp
, const char * filename
, const ByteOrderT order
, const ElementTypeT type
, const uint bytes
, const int bits
, double * out
) {
1362 if (! ReadBin8 (fp
, filename
, order
, & v8
. ui
))
1367 if (! ReadBin4 (fp
, filename
, order
, bytes
, & v4
. ui
))
1369 if (type
== ET_FP
) {
1370 (* out
) = (double) v4
. f
;
1373 v4
. ui
>>= (8 * bytes
) - ((uint
) bits
);
1375 v4
. ui
&= (0xFFFFFFFF >> (32 + bits
));
1376 if (v4
. ui
& ((uint
) (1 << (abs (bits
) - 1))))
1377 v4
. ui
|= (0xFFFFFFFF << abs (bits
));
1378 (* out
) = v4
. i
/ ((double) (1 << (abs (bits
) - 1)));
1384 /* Read an ascii value of the specified type from a file, converting it to a
1385 * double. For integer types, the significant bits are used to normalize the
1386 * result. The sign of the bits should always be positive. This also skips
1387 * up to one separator character before the element itself.
1389 static int ReadAsciiAsDouble (TokenReaderT
* tr
, const char * filename
, const ElementTypeT type
, const uint bits
, double * out
) {
1392 if (TrIsOperator (tr
, ","))
1393 TrReadOperator (tr
, ",");
1394 else if (TrIsOperator (tr
, ":"))
1395 TrReadOperator (tr
, ":");
1396 else if (TrIsOperator (tr
, ";"))
1397 TrReadOperator (tr
, ";");
1398 else if (TrIsOperator (tr
, "|"))
1399 TrReadOperator (tr
, "|");
1400 if (type
== ET_FP
) {
1401 if (! TrReadFloat (tr
, -HUGE_VAL
, HUGE_VAL
, out
)) {
1402 fprintf (stderr
, "Error: Bad read from file '%s'.\n", filename
);
1406 if (! TrReadInt (tr
, -(1 << (bits
- 1)), (1 << (bits
- 1)) - 1, & v
)) {
1407 fprintf (stderr
, "Error: Bad read from file '%s'.\n", filename
);
1410 (* out
) = v
/ ((double) ((1 << (bits
- 1)) - 1));
1415 // Read the RIFF/RIFX WAVE format chunk from a file, validating it against
1416 // the source parameters and data set metrics.
1417 static int ReadWaveFormat (FILE * fp
, const ByteOrderT order
, const uint hrirRate
, SourceRefT
* src
) {
1418 uint32 fourCC
, chunkSize
;
1419 uint32 format
, channels
, rate
, dummy
, block
, size
, bits
;
1424 fseek (fp
, (long) chunkSize
, SEEK_CUR
);
1425 if ((! ReadBin4 (fp
, src
-> mPath
, BO_LITTLE
, 4, & fourCC
)) ||
1426 (! ReadBin4 (fp
, src
-> mPath
, order
, 4, & chunkSize
)))
1428 } while (fourCC
!= FOURCC_FMT
);
1429 if ((! ReadBin4 (fp
, src
-> mPath
, order
, 2, & format
)) ||
1430 (! ReadBin4 (fp
, src
-> mPath
, order
, 2, & channels
)) ||
1431 (! ReadBin4 (fp
, src
-> mPath
, order
, 4, & rate
)) ||
1432 (! ReadBin4 (fp
, src
-> mPath
, order
, 4, & dummy
)) ||
1433 (! ReadBin4 (fp
, src
-> mPath
, order
, 2, & block
)))
1436 if (chunkSize
> 14) {
1437 if (! ReadBin4 (fp
, src
-> mPath
, order
, 2, & size
))
1445 if (format
== WAVE_FORMAT_EXTENSIBLE
) {
1446 fseek (fp
, 2, SEEK_CUR
);
1447 if (! ReadBin4 (fp
, src
-> mPath
, order
, 2, & bits
))
1451 fseek (fp
, 4, SEEK_CUR
);
1452 if (! ReadBin4 (fp
, src
-> mPath
, order
, 2, & format
))
1454 fseek (fp
, (long) (chunkSize
- 26), SEEK_CUR
);
1458 fseek (fp
, (long) (chunkSize
- 16), SEEK_CUR
);
1460 fseek (fp
, (long) (chunkSize
- 14), SEEK_CUR
);
1462 if ((format
!= WAVE_FORMAT_PCM
) && (format
!= WAVE_FORMAT_IEEE_FLOAT
)) {
1463 fprintf (stderr
, "Error: Unsupported WAVE format in file '%s'.\n", src
-> mPath
);
1466 if (src
-> mChannel
>= channels
) {
1467 fprintf (stderr
, "Error: Missing source channel in WAVE file '%s'.\n", src
-> mPath
);
1470 if (rate
!= hrirRate
) {
1471 fprintf (stderr
, "Error: Mismatched source sample rate in WAVE file '%s'.\n", src
-> mPath
);
1474 if (format
== WAVE_FORMAT_PCM
) {
1475 if ((size
< 2) || (size
> 4)) {
1476 fprintf (stderr
, "Error: Unsupported sample size in WAVE file '%s'.\n", src
-> mPath
);
1479 if ((bits
< 16) || (bits
> (8 * size
))) {
1480 fprintf (stderr
, "Error: Bad significant bits in WAVE file '%s'.\n", src
-> mPath
);
1483 src
-> mType
= ET_INT
;
1485 if ((size
!= 4) && (size
!= 8)) {
1486 fprintf (stderr
, "Error: Unsupported sample size in WAVE file '%s'.\n", src
-> mPath
);
1489 src
-> mType
= ET_FP
;
1491 src
-> mSize
= size
;
1492 src
-> mBits
= (int) bits
;
1493 src
-> mSkip
= channels
;
1497 // Read a RIFF/RIFX WAVE data chunk, converting all elements to doubles.
1498 static int ReadWaveData (FILE * fp
, const SourceRefT
* src
, const ByteOrderT order
, const uint n
, double * hrir
) {
1499 int pre
, post
, skip
;
1502 pre
= (int) (src
-> mSize
* src
-> mChannel
);
1503 post
= (int) (src
-> mSize
* (src
-> mSkip
- src
-> mChannel
- 1));
1505 for (i
= 0; i
< n
; i
++) {
1508 fseek (fp
, skip
, SEEK_CUR
);
1509 if (! ReadBinAsDouble (fp
, src
-> mPath
, order
, src
-> mType
, src
-> mSize
, src
-> mBits
, & hrir
[i
]))
1514 fseek (fp
, skip
, SEEK_CUR
);
1518 // Read the RIFF/RIFX WAVE list or data chunk, converting all elements to
1520 static int ReadWaveList (FILE * fp
, const SourceRefT
* src
, const ByteOrderT order
, const uint n
, double * hrir
) {
1521 uint32 fourCC
, chunkSize
, listSize
, count
;
1522 uint block
, skip
, offset
, i
;
1526 if ((! ReadBin4 (fp
, src
-> mPath
, BO_LITTLE
, 4, & fourCC
)) ||
1527 (! ReadBin4 (fp
, src
-> mPath
, order
, 4, & chunkSize
)))
1529 if (fourCC
== FOURCC_DATA
) {
1530 block
= src
-> mSize
* src
-> mSkip
;
1531 count
= chunkSize
/ block
;
1532 if (count
< (src
-> mOffset
+ n
)) {
1533 fprintf (stderr
, "Error: Bad read from file '%s'.\n", src
-> mPath
);
1536 fseek (fp
, (long) (src
-> mOffset
* block
), SEEK_CUR
);
1537 if (! ReadWaveData (fp
, src
, order
, n
, & hrir
[0]))
1540 } else if (fourCC
== FOURCC_LIST
) {
1541 if (! ReadBin4 (fp
, src
-> mPath
, BO_LITTLE
, 4, & fourCC
))
1544 if (fourCC
== FOURCC_WAVL
)
1548 fseek (fp
, (long) chunkSize
, SEEK_CUR
);
1550 listSize
= chunkSize
;
1551 block
= src
-> mSize
* src
-> mSkip
;
1552 skip
= src
-> mOffset
;
1555 while ((offset
< n
) && (listSize
> 8)) {
1556 if ((! ReadBin4 (fp
, src
-> mPath
, BO_LITTLE
, 4, & fourCC
)) ||
1557 (! ReadBin4 (fp
, src
-> mPath
, order
, 4, & chunkSize
)))
1559 listSize
-= 8 + chunkSize
;
1560 if (fourCC
== FOURCC_DATA
) {
1561 count
= chunkSize
/ block
;
1563 fseek (fp
, (long) (skip
* block
), SEEK_CUR
);
1564 chunkSize
-= skip
* block
;
1567 if (count
> (n
- offset
))
1569 if (! ReadWaveData (fp
, src
, order
, count
, & hrir
[offset
]))
1571 chunkSize
-= count
* block
;
1573 lastSample
= hrir
[offset
- 1];
1578 } else if (fourCC
== FOURCC_SLNT
) {
1579 if (! ReadBin4 (fp
, src
-> mPath
, order
, 4, & count
))
1585 if (count
> (n
- offset
))
1587 for (i
= 0; i
< count
; i
++)
1588 hrir
[offset
+ i
] = lastSample
;
1596 fseek (fp
, (long) chunkSize
, SEEK_CUR
);
1599 fprintf (stderr
, "Error: Bad read from file '%s'.\n", src
-> mPath
);
1605 // Load a source HRIR from a RIFF/RIFX WAVE file.
1606 static int LoadWaveSource (FILE * fp
, SourceRefT
* src
, const uint hrirRate
, const uint n
, double * hrir
) {
1607 uint32 fourCC
, dummy
;
1610 if ((! ReadBin4 (fp
, src
-> mPath
, BO_LITTLE
, 4, & fourCC
)) ||
1611 (! ReadBin4 (fp
, src
-> mPath
, BO_LITTLE
, 4, & dummy
)))
1613 if (fourCC
== FOURCC_RIFF
) {
1615 } else if (fourCC
== FOURCC_RIFX
) {
1618 fprintf (stderr
, "Error: No RIFF/RIFX chunk in file '%s'.\n", src
-> mPath
);
1621 if (! ReadBin4 (fp
, src
-> mPath
, BO_LITTLE
, 4, & fourCC
))
1623 if (fourCC
!= FOURCC_WAVE
) {
1624 fprintf (stderr
, "Error: Not a RIFF/RIFX WAVE file '%s'.\n", src
-> mPath
);
1627 if (! ReadWaveFormat (fp
, order
, hrirRate
, src
))
1629 if (! ReadWaveList (fp
, src
, order
, n
, hrir
))
1634 // Load a source HRIR from a binary file.
1635 static int LoadBinarySource (FILE * fp
, const SourceRefT
* src
, const ByteOrderT order
, const uint n
, double * hrir
) {
1638 fseek (fp
, (long) src
-> mOffset
, SEEK_SET
);
1639 for (i
= 0; i
< n
; i
++) {
1640 if (! ReadBinAsDouble (fp
, src
-> mPath
, order
, src
-> mType
, src
-> mSize
, src
-> mBits
, & hrir
[i
]))
1642 if (src
-> mSkip
> 0)
1643 fseek (fp
, (long) src
-> mSkip
, SEEK_CUR
);
1648 // Load a source HRIR from an ASCII text file containing a list of elements
1649 // separated by whitespace or common list operators (',', ';', ':', '|').
1650 static int LoadAsciiSource (FILE * fp
, const SourceRefT
* src
, const uint n
, double * hrir
) {
1655 TrSetup (fp
, NULL
, & tr
);
1656 for (i
= 0; i
< src
-> mOffset
; i
++) {
1657 if (! ReadAsciiAsDouble (& tr
, src
-> mPath
, src
-> mType
, (uint
) src
-> mBits
, & dummy
))
1660 for (i
= 0; i
< n
; i
++) {
1661 if (! ReadAsciiAsDouble (& tr
, src
-> mPath
, src
-> mType
, (uint
) src
-> mBits
, & hrir
[i
]))
1663 for (j
= 0; j
< src
-> mSkip
; j
++) {
1664 if (! ReadAsciiAsDouble (& tr
, src
-> mPath
, src
-> mType
, (uint
) src
-> mBits
, & dummy
))
1671 // Load a source HRIR from a supported file type.
1672 static int LoadSource (SourceRefT
* src
, const uint hrirRate
, const uint n
, double * hrir
) {
1676 if (src
-> mFormat
== SF_ASCII
)
1677 fp
= fopen (src
-> mPath
, "r");
1679 fp
= fopen (src
-> mPath
, "rb");
1681 fprintf (stderr
, "Error: Could not open source file '%s'.\n", src
-> mPath
);
1684 if (src
-> mFormat
== SF_WAVE
)
1685 result
= LoadWaveSource (fp
, src
, hrirRate
, n
, hrir
);
1686 else if (src
-> mFormat
== SF_BIN_LE
)
1687 result
= LoadBinarySource (fp
, src
, BO_LITTLE
, n
, hrir
);
1688 else if (src
-> mFormat
== SF_BIN_BE
)
1689 result
= LoadBinarySource (fp
, src
, BO_BIG
, n
, hrir
);
1691 result
= LoadAsciiSource (fp
, src
, n
, hrir
);
1696 // Calculate the onset time of an HRIR and average it with any existing
1697 // timing for its elevation and azimuth.
1698 static void AverageHrirOnset (const double * hrir
, const double f
, const uint ei
, const uint ai
, const HrirDataT
* hData
) {
1703 n
= hData
-> mIrPoints
;
1704 for (i
= 0; i
< n
; i
++)
1705 mag
= fmax (fabs (hrir
[i
]), mag
);
1707 for (i
= 0; i
< n
; i
++) {
1708 if (fabs (hrir
[i
]) >= mag
)
1711 j
= hData
-> mEvOffset
[ei
] + ai
;
1712 hData
-> mHrtds
[j
] = Lerp (hData
-> mHrtds
[j
], ((double) i
) / hData
-> mIrRate
, f
);
1715 // Calculate the magnitude response of an HRIR and average it with any
1716 // existing responses for its elevation and azimuth.
1717 static void AverageHrirMagnitude (const double * hrir
, const double f
, const uint ei
, const uint ai
, const HrirDataT
* hData
) {
1718 double * re
= NULL
, * im
= NULL
;
1721 n
= hData
-> mFftSize
;
1722 re
= CreateArray (n
);
1723 im
= CreateArray (n
);
1724 for (i
= 0; i
< hData
-> mIrPoints
; i
++) {
1728 for (; i
< n
; i
++) {
1732 FftForward (n
, re
, im
, re
, im
);
1733 MagnitudeResponse (n
, re
, im
, re
);
1735 j
= (hData
-> mEvOffset
[ei
] + ai
) * hData
-> mIrSize
;
1736 for (i
= 0; i
< m
; i
++)
1737 hData
-> mHrirs
[j
+ i
] = Lerp (hData
-> mHrirs
[j
+ i
], re
[i
], f
);
1742 /* Calculate the contribution of each HRIR to the diffuse-field average based
1743 * on the area of its surface patch. All patches are centered at the HRIR
1744 * coordinates on the unit sphere and are measured by solid angle.
1746 static void CalculateDfWeights (const HrirDataT
* hData
, double * weights
) {
1748 double evs
, sum
, ev
, up_ev
, down_ev
, solidAngle
;
1750 evs
= 90.0 / (hData
-> mEvCount
- 1);
1752 for (ei
= hData
-> mEvStart
; ei
< hData
-> mEvCount
; ei
++) {
1753 // For each elevation, calculate the upper and lower limits of the
1755 ev
= -90.0 + (ei
* 2.0 * evs
);
1756 if (ei
< (hData
-> mEvCount
- 1))
1757 up_ev
= (ev
+ evs
) * M_PI
/ 180.0;
1761 down_ev
= (ev
- evs
) * M_PI
/ 180.0;
1763 down_ev
= -M_PI
/ 2.0;
1764 // Calculate the area of the patch band.
1765 solidAngle
= 2.0 * M_PI
* (sin (up_ev
) - sin (down_ev
));
1766 // Each weight is the area of one patch.
1767 weights
[ei
] = solidAngle
/ hData
-> mAzCount
[ei
];
1768 // Sum the total surface area covered by the HRIRs.
1771 // Normalize the weights given the total surface coverage.
1772 for (ei
= hData
-> mEvStart
; ei
< hData
-> mEvCount
; ei
++)
1773 weights
[ei
] /= sum
;
1776 /* Calculate the diffuse-field average from the given magnitude responses of
1777 * the HRIR set. Weighting can be applied to compensate for the varying
1778 * surface area covered by each HRIR. The final average can then be limited
1779 * by the specified magnitude range (in positive dB; 0.0 to skip).
1781 static void CalculateDiffuseFieldAverage (const HrirDataT
* hData
, const int weighted
, const double limit
, double * dfa
) {
1782 double * weights
= NULL
;
1783 uint ei
, ai
, count
, step
, start
, end
, m
, j
, i
;
1786 weights
= CreateArray (hData
-> mEvCount
);
1788 // Use coverage weighting to calculate the average.
1789 CalculateDfWeights (hData
, weights
);
1791 // If coverage weighting is not used, the weights still need to be
1792 // averaged by the number of HRIRs.
1794 for (ei
= hData
-> mEvStart
; ei
< hData
-> mEvCount
; ei
++)
1795 count
+= hData
-> mAzCount
[ei
];
1796 for (ei
= hData
-> mEvStart
; ei
< hData
-> mEvCount
; ei
++)
1797 weights
[ei
] = 1.0 / count
;
1799 ei
= hData
-> mEvStart
;
1801 step
= hData
-> mIrSize
;
1802 start
= hData
-> mEvOffset
[ei
] * step
;
1803 end
= hData
-> mIrCount
* step
;
1804 m
= 1 + (hData
-> mFftSize
/ 2);
1805 for (i
= 0; i
< m
; i
++)
1807 for (j
= start
; j
< end
; j
+= step
) {
1808 // Get the weight for this HRIR's contribution.
1809 weight
= weights
[ei
];
1810 // Add this HRIR's weighted power average to the total.
1811 for (i
= 0; i
< m
; i
++)
1812 dfa
[i
] += weight
* hData
-> mHrirs
[j
+ i
] * hData
-> mHrirs
[j
+ i
];
1813 // Determine the next weight to use.
1815 if (ai
>= hData
-> mAzCount
[ei
]) {
1820 // Finish the average calculation and keep it from being too small.
1821 for (i
= 0; i
< m
; i
++)
1822 dfa
[i
] = fmax (sqrt (dfa
[i
]), EPSILON
);
1823 // Apply a limit to the magnitude range of the diffuse-field average if
1826 LimitMagnitudeResponse (hData
-> mFftSize
, limit
, dfa
, dfa
);
1827 DestroyArray (weights
);
1830 // Perform diffuse-field equalization on the magnitude responses of the HRIR
1831 // set using the given average response.
1832 static void DiffuseFieldEqualize (const double * dfa
, const HrirDataT
* hData
) {
1833 uint step
, start
, end
, m
, j
, i
;
1835 step
= hData
-> mIrSize
;
1836 start
= hData
-> mEvOffset
[hData
-> mEvStart
] * step
;
1837 end
= hData
-> mIrCount
* step
;
1838 m
= 1 + (hData
-> mFftSize
/ 2);
1839 for (j
= start
; j
< end
; j
+= step
) {
1840 for (i
= 0; i
< m
; i
++)
1841 hData
-> mHrirs
[j
+ i
] /= dfa
[i
];
1845 // Perform minimum-phase reconstruction using the magnitude responses of the
1847 static void ReconstructHrirs (const HrirDataT
* hData
) {
1848 double * re
= NULL
, * im
= NULL
;
1849 uint step
, start
, end
, n
, j
, i
;
1851 step
= hData
-> mIrSize
;
1852 start
= hData
-> mEvOffset
[hData
-> mEvStart
] * step
;
1853 end
= hData
-> mIrCount
* step
;
1854 n
= hData
-> mFftSize
;
1855 re
= CreateArray (n
);
1856 im
= CreateArray (n
);
1857 for (j
= start
; j
< end
; j
+= step
) {
1858 MinimumPhase (n
, & hData
-> mHrirs
[j
], re
, im
);
1859 FftInverse (n
, re
, im
, re
, im
);
1860 for (i
= 0; i
< hData
-> mIrPoints
; i
++)
1861 hData
-> mHrirs
[j
+ i
] = re
[i
];
1867 // Resamples the HRIRs for use at the given sampling rate.
1868 static void ResampleHrirs (const uint rate
, HrirDataT
* hData
) {
1870 uint n
, step
, start
, end
, j
;
1872 ResamplerSetup (& rs
, hData
-> mIrRate
, rate
);
1873 n
= hData
-> mIrPoints
;
1874 step
= hData
-> mIrSize
;
1875 start
= hData
-> mEvOffset
[hData
-> mEvStart
] * step
;
1876 end
= hData
-> mIrCount
* step
;
1877 for (j
= start
; j
< end
; j
+= step
)
1878 ResamplerRun (& rs
, n
, & hData
-> mHrirs
[j
], n
, & hData
-> mHrirs
[j
]);
1879 ResamplerClear (& rs
);
1880 hData
-> mIrRate
= rate
;
1883 /* Given an elevation index and an azimuth, calculate the indices of the two
1884 * HRIRs that bound the coordinate along with a factor for calculating the
1885 * continous HRIR using interpolation.
1887 static void CalcAzIndices (const HrirDataT
* hData
, const uint ei
, const double az
, uint
* j0
, uint
* j1
, double * jf
) {
1891 af
= ((2.0 * M_PI
) + az
) * hData
-> mAzCount
[ei
] / (2.0 * M_PI
);
1892 ai
= ((uint
) af
) % hData
-> mAzCount
[ei
];
1894 (* j0
) = hData
-> mEvOffset
[ei
] + ai
;
1895 (* j1
) = hData
-> mEvOffset
[ei
] + ((ai
+ 1) % hData
-> mAzCount
[ei
]);
1899 // Synthesize any missing onset timings at the bottom elevations. This just
1900 // blends between slightly exaggerated known onsets. Not an accurate model.
1901 static void SynthesizeOnsets (HrirDataT
* hData
) {
1902 uint oi
, e
, a
, j0
, j1
;
1905 oi
= hData
-> mEvStart
;
1907 for (a
= 0; a
< hData
-> mAzCount
[oi
]; a
++)
1908 t
+= hData
-> mHrtds
[hData
-> mEvOffset
[oi
] + a
];
1909 hData
-> mHrtds
[0] = 1.32e-4 + (t
/ hData
-> mAzCount
[oi
]);
1910 for (e
= 1; e
< hData
-> mEvStart
; e
++) {
1911 of
= ((double) e
) / hData
-> mEvStart
;
1912 for (a
= 0; a
< hData
-> mAzCount
[e
]; a
++) {
1913 CalcAzIndices (hData
, oi
, a
* 2.0 * M_PI
/ hData
-> mAzCount
[e
], & j0
, & j1
, & jf
);
1914 hData
-> mHrtds
[hData
-> mEvOffset
[e
] + a
] = Lerp (hData
-> mHrtds
[0], Lerp (hData
-> mHrtds
[j0
], hData
-> mHrtds
[j1
], jf
), of
);
1919 /* Attempt to synthesize any missing HRIRs at the bottom elevations. Right
1920 * now this just blends the lowest elevation HRIRs together and applies some
1921 * attenuation and high frequency damping. It is a simple, if inaccurate
1924 static void SynthesizeHrirs (HrirDataT
* hData
) {
1925 uint oi
, a
, e
, step
, n
, i
, j
;
1929 double lp
[4], s0
, s1
;
1931 if (hData
-> mEvStart
<= 0)
1933 step
= hData
-> mIrSize
;
1934 oi
= hData
-> mEvStart
;
1935 n
= hData
-> mIrPoints
;
1936 for (i
= 0; i
< n
; i
++)
1937 hData
-> mHrirs
[i
] = 0.0;
1938 for (a
= 0; a
< hData
-> mAzCount
[oi
]; a
++) {
1939 j
= (hData
-> mEvOffset
[oi
] + a
) * step
;
1940 for (i
= 0; i
< n
; i
++)
1941 hData
-> mHrirs
[i
] += hData
-> mHrirs
[j
+ i
] / hData
-> mAzCount
[oi
];
1943 for (e
= 1; e
< hData
-> mEvStart
; e
++) {
1944 of
= ((double) e
) / hData
-> mEvStart
;
1945 b
= (1.0 - of
) * (3.5e-6 * hData
-> mIrRate
);
1946 for (a
= 0; a
< hData
-> mAzCount
[e
]; a
++) {
1947 j
= (hData
-> mEvOffset
[e
] + a
) * step
;
1948 CalcAzIndices (hData
, oi
, a
* 2.0 * M_PI
/ hData
-> mAzCount
[e
], & j0
, & j1
, & jf
);
1955 for (i
= 0; i
< n
; i
++) {
1956 s0
= hData
-> mHrirs
[i
];
1957 s1
= Lerp (hData
-> mHrirs
[j0
+ i
], hData
-> mHrirs
[j1
+ i
], jf
);
1958 s0
= Lerp (s0
, s1
, of
);
1959 lp
[0] = Lerp (s0
, lp
[0], b
);
1960 lp
[1] = Lerp (lp
[0], lp
[1], b
);
1961 lp
[2] = Lerp (lp
[1], lp
[2], b
);
1962 lp
[3] = Lerp (lp
[2], lp
[3], b
);
1963 hData
-> mHrirs
[j
+ i
] = lp
[3];
1967 b
= 3.5e-6 * hData
-> mIrRate
;
1972 for (i
= 0; i
< n
; i
++) {
1973 s0
= hData
-> mHrirs
[i
];
1974 lp
[0] = Lerp (s0
, lp
[0], b
);
1975 lp
[1] = Lerp (lp
[0], lp
[1], b
);
1976 lp
[2] = Lerp (lp
[1], lp
[2], b
);
1977 lp
[3] = Lerp (lp
[2], lp
[3], b
);
1978 hData
-> mHrirs
[i
] = lp
[3];
1980 hData
-> mEvStart
= 0;
1983 // The following routines assume a full set of HRIRs for all elevations.
1985 // Normalize the HRIR set and slightly attenuate the result.
1986 static void NormalizeHrirs (const HrirDataT
* hData
) {
1987 uint step
, end
, n
, j
, i
;
1990 step
= hData
-> mIrSize
;
1991 end
= hData
-> mIrCount
* step
;
1992 n
= hData
-> mIrPoints
;
1994 for (j
= 0; j
< end
; j
+= step
) {
1995 for (i
= 0; i
< n
; i
++)
1996 maxLevel
= fmax (fabs (hData
-> mHrirs
[j
+ i
]), maxLevel
);
1998 maxLevel
= 1.01 * maxLevel
;
1999 for (j
= 0; j
< end
; j
+= step
) {
2000 for (i
= 0; i
< n
; i
++)
2001 hData
-> mHrirs
[j
+ i
] /= maxLevel
;
2005 // Calculate the left-ear time delay using a spherical head model.
2006 static double CalcLTD (const double ev
, const double az
, const double rad
, const double dist
) {
2007 double azp
, dlp
, l
, al
;
2009 azp
= asin (cos (ev
) * sin (az
));
2010 dlp
= sqrt ((dist
* dist
) + (rad
* rad
) + (2.0 * dist
* rad
* sin (azp
)));
2011 l
= sqrt ((dist
* dist
) - (rad
* rad
));
2012 al
= (0.5 * M_PI
) + azp
;
2014 dlp
= l
+ (rad
* (al
- acos (rad
/ dist
)));
2015 return (dlp
/ 343.3);
2018 // Calculate the effective head-related time delays for each minimum-phase
2020 static void CalculateHrtds (const HeadModelT model
, const double radius
, HrirDataT
* hData
) {
2021 double minHrtd
, maxHrtd
;
2027 for (e
= 0; e
< hData
-> mEvCount
; e
++) {
2028 for (a
= 0; a
< hData
-> mAzCount
[e
]; a
++) {
2029 j
= hData
-> mEvOffset
[e
] + a
;
2030 if (model
== HM_DATASET
) {
2031 t
= hData
-> mHrtds
[j
] * radius
/ hData
-> mRadius
;
2033 t
= CalcLTD ((-90.0 + (e
* 180.0 / (hData
-> mEvCount
- 1))) * M_PI
/ 180.0,
2034 (a
* 360.0 / hData
-> mAzCount
[e
]) * M_PI
/ 180.0,
2035 radius
, hData
-> mDistance
);
2037 hData
-> mHrtds
[j
] = t
;
2038 maxHrtd
= fmax (t
, maxHrtd
);
2039 minHrtd
= fmin (t
, minHrtd
);
2043 for (j
= 0; j
< hData
-> mIrCount
; j
++)
2044 hData
-> mHrtds
[j
] -= minHrtd
;
2045 hData
-> mMaxHrtd
= maxHrtd
;
2048 // Store the OpenAL Soft HRTF data set.
2049 static int StoreMhr (const HrirDataT
* hData
, const char * filename
) {
2051 uint e
, step
, end
, n
, j
, i
;
2054 if ((fp
= fopen (filename
, "wb")) == NULL
) {
2055 fprintf (stderr
, "Error: Could not open MHR file '%s'.\n", filename
);
2058 if (! WriteAscii (MHR_FORMAT
, fp
, filename
))
2060 if (! WriteBin4 (BO_LITTLE
, 4, (uint32
) hData
-> mIrRate
, fp
, filename
))
2062 if (! WriteBin4 (BO_LITTLE
, 1, (uint32
) hData
-> mIrPoints
, fp
, filename
))
2064 if (! WriteBin4 (BO_LITTLE
, 1, (uint32
) hData
-> mEvCount
, fp
, filename
))
2066 for (e
= 0; e
< hData
-> mEvCount
; e
++) {
2067 if (! WriteBin4 (BO_LITTLE
, 1, (uint32
) hData
-> mAzCount
[e
], fp
, filename
))
2070 step
= hData
-> mIrSize
;
2071 end
= hData
-> mIrCount
* step
;
2072 n
= hData
-> mIrPoints
;
2074 for (j
= 0; j
< end
; j
+= step
) {
2076 for (i
= 0; i
< n
; i
++) {
2077 v
= HpTpdfDither (32767.0 * hData
-> mHrirs
[j
+ i
], & hpHist
);
2078 if (! WriteBin4 (BO_LITTLE
, 2, (uint32
) v
, fp
, filename
))
2082 for (j
= 0; j
< hData
-> mIrCount
; j
++) {
2083 v
= (int) fmin (round (hData
-> mIrRate
* hData
-> mHrtds
[j
]), MAX_HRTD
);
2084 if (! WriteBin4 (BO_LITTLE
, 1, (uint32
) v
, fp
, filename
))
2091 // Process the data set definition to read and validate the data set metrics.
2092 static int ProcessMetrics (TokenReaderT
* tr
, const uint fftSize
, const uint truncSize
, HrirDataT
* hData
) {
2093 char ident
[MAX_IDENT_LEN
+ 1];
2098 int hasRate
= 0, hasPoints
= 0, hasAzimuths
= 0;
2099 int hasRadius
= 0, hasDistance
= 0;
2101 while (! (hasRate
&& hasPoints
&& hasAzimuths
&& hasRadius
&& hasDistance
)) {
2102 TrIndication (tr
, & line
, & col
);
2103 if (! TrReadIdent (tr
, MAX_IDENT_LEN
, ident
))
2105 if (strcasecmp (ident
, "rate") == 0) {
2107 TrErrorAt (tr
, line
, col
, "Redefinition of 'rate'.\n");
2110 if (! TrReadOperator (tr
, "="))
2112 if (! TrReadInt (tr
, MIN_RATE
, MAX_RATE
, & intVal
))
2114 hData
-> mIrRate
= (uint
) intVal
;
2116 } else if (strcasecmp (ident
, "points") == 0) {
2118 TrErrorAt (tr
, line
, col
, "Redefinition of 'points'.\n");
2121 if (! TrReadOperator (tr
, "="))
2123 TrIndication (tr
, & line
, & col
);
2124 if (! TrReadInt (tr
, MIN_POINTS
, MAX_POINTS
, & intVal
))
2126 points
= (uint
) intVal
;
2127 if ((fftSize
> 0) && (points
> fftSize
)) {
2128 TrErrorAt (tr
, line
, col
, "Value exceeds the overridden FFT size.\n");
2131 if (points
< truncSize
) {
2132 TrErrorAt (tr
, line
, col
, "Value is below the truncation size.\n");
2135 hData
-> mIrPoints
= points
;
2136 hData
-> mFftSize
= fftSize
;
2139 while (points
< (4 * hData
-> mIrPoints
))
2141 hData
-> mFftSize
= points
;
2142 hData
-> mIrSize
= 1 + (points
/ 2);
2144 hData
-> mFftSize
= fftSize
;
2145 hData
-> mIrSize
= 1 + (fftSize
/ 2);
2146 if (points
> hData
-> mIrSize
)
2147 hData
-> mIrSize
= points
;
2150 } else if (strcasecmp (ident
, "azimuths") == 0) {
2152 TrErrorAt (tr
, line
, col
, "Redefinition of 'azimuths'.\n");
2155 if (! TrReadOperator (tr
, "="))
2157 hData
-> mIrCount
= 0;
2158 hData
-> mEvCount
= 0;
2159 hData
-> mEvOffset
[0] = 0;
2161 if (! TrReadInt (tr
, MIN_AZ_COUNT
, MAX_AZ_COUNT
, & intVal
))
2163 hData
-> mAzCount
[hData
-> mEvCount
] = (uint
) intVal
;
2164 hData
-> mIrCount
+= (uint
) intVal
;
2165 hData
-> mEvCount
++;
2166 if (! TrIsOperator (tr
, ","))
2168 if (hData
-> mEvCount
>= MAX_EV_COUNT
) {
2169 TrError (tr
, "Exceeded the maximum of %d elevations.\n", MAX_EV_COUNT
);
2172 hData
-> mEvOffset
[hData
-> mEvCount
] = hData
-> mEvOffset
[hData
-> mEvCount
- 1] + ((uint
) intVal
);
2173 TrReadOperator (tr
, ",");
2175 if (hData
-> mEvCount
< MIN_EV_COUNT
) {
2176 TrErrorAt (tr
, line
, col
, "Did not reach the minimum of %d azimuth counts.\n", MIN_EV_COUNT
);
2180 } else if (strcasecmp (ident
, "radius") == 0) {
2182 TrErrorAt (tr
, line
, col
, "Redefinition of 'radius'.\n");
2185 if (! TrReadOperator (tr
, "="))
2187 if (! TrReadFloat (tr
, MIN_RADIUS
, MAX_RADIUS
, & fpVal
))
2189 hData
-> mRadius
= fpVal
;
2191 } else if (strcasecmp (ident
, "distance") == 0) {
2193 TrErrorAt (tr
, line
, col
, "Redefinition of 'distance'.\n");
2196 if (! TrReadOperator (tr
, "="))
2198 if (! TrReadFloat (tr
, MIN_DISTANCE
, MAX_DISTANCE
, & fpVal
))
2200 hData
-> mDistance
= fpVal
;
2203 TrErrorAt (tr
, line
, col
, "Expected a metric name.\n");
2206 TrSkipWhitespace (tr
);
2211 // Parse an index pair from the data set definition.
2212 static int ReadIndexPair (TokenReaderT
* tr
, const HrirDataT
* hData
, uint
* ei
, uint
* ai
) {
2215 if (! TrReadInt (tr
, 0, (int) hData
-> mEvCount
, & intVal
))
2217 (* ei
) = (uint
) intVal
;
2218 if (! TrReadOperator (tr
, ","))
2220 if (! TrReadInt (tr
, 0, (int) hData
-> mAzCount
[(* ei
)], & intVal
))
2222 (* ai
) = (uint
) intVal
;
2226 // Match the source format from a given identifier.
2227 static SourceFormatT
MatchSourceFormat (const char * ident
) {
2228 if (strcasecmp (ident
, "wave") == 0)
2230 else if (strcasecmp (ident
, "bin_le") == 0)
2232 else if (strcasecmp (ident
, "bin_be") == 0)
2234 else if (strcasecmp (ident
, "ascii") == 0)
2239 // Match the source element type from a given identifier.
2240 static ElementTypeT
MatchElementType (const char * ident
) {
2241 if (strcasecmp (ident
, "int") == 0)
2243 else if (strcasecmp (ident
, "fp") == 0)
2248 // Parse and validate a source reference from the data set definition.
2249 static int ReadSourceRef (TokenReaderT
* tr
, SourceRefT
* src
) {
2251 char ident
[MAX_IDENT_LEN
+ 1];
2254 TrIndication (tr
, & line
, & col
);
2255 if (! TrReadIdent (tr
, MAX_IDENT_LEN
, ident
))
2257 src
-> mFormat
= MatchSourceFormat (ident
);
2258 if (src
-> mFormat
== SF_NONE
) {
2259 TrErrorAt (tr
, line
, col
, "Expected a source format.\n");
2262 if (! TrReadOperator (tr
, "("))
2264 if (src
-> mFormat
== SF_WAVE
) {
2265 if (! TrReadInt (tr
, 0, MAX_WAVE_CHANNELS
, & intVal
))
2267 src
-> mType
= ET_NONE
;
2270 src
-> mChannel
= (uint
) intVal
;
2273 TrIndication (tr
, & line
, & col
);
2274 if (! TrReadIdent (tr
, MAX_IDENT_LEN
, ident
))
2276 src
-> mType
= MatchElementType (ident
);
2277 if (src
-> mType
== ET_NONE
) {
2278 TrErrorAt (tr
, line
, col
, "Expected a source element type.\n");
2281 if ((src
-> mFormat
== SF_BIN_LE
) || (src
-> mFormat
== SF_BIN_BE
)) {
2282 if (! TrReadOperator (tr
, ","))
2284 if (src
-> mType
== ET_INT
) {
2285 if (! TrReadInt (tr
, MIN_BIN_SIZE
, MAX_BIN_SIZE
, & intVal
))
2287 src
-> mSize
= (uint
) intVal
;
2288 if (TrIsOperator (tr
, ",")) {
2289 TrReadOperator (tr
, ",");
2290 TrIndication (tr
, & line
, & col
);
2291 if (! TrReadInt (tr
, -2147483647 - 1, 2147483647, & intVal
))
2293 if ((abs (intVal
) < MIN_BIN_BITS
) || (((uint
) abs (intVal
)) > (8 * src
-> mSize
))) {
2294 TrErrorAt (tr
, line
, col
, "Expected a value of (+/-) %d to %d.\n", MIN_BIN_BITS
, 8 * src
-> mSize
);
2297 src
-> mBits
= intVal
;
2299 src
-> mBits
= (int) (8 * src
-> mSize
);
2302 TrIndication (tr
, & line
, & col
);
2303 if (! TrReadInt (tr
, -2147483647 - 1, 2147483647, & intVal
))
2305 if ((intVal
!= 4) && (intVal
!= 8)) {
2306 TrErrorAt (tr
, line
, col
, "Expected a value of 4 or 8.\n");
2309 src
-> mSize
= (uint
) intVal
;
2312 } else if ((src
-> mFormat
== SF_ASCII
) && (src
-> mType
== ET_INT
)) {
2313 if (! TrReadOperator (tr
, ","))
2315 if (! TrReadInt (tr
, MIN_ASCII_BITS
, MAX_ASCII_BITS
, & intVal
))
2318 src
-> mBits
= intVal
;
2323 if (TrIsOperator (tr
, ";")) {
2324 TrReadOperator (tr
, ";");
2325 if (! TrReadInt (tr
, 0, 0x7FFFFFFF, & intVal
))
2327 src
-> mSkip
= (uint
) intVal
;
2332 if (! TrReadOperator (tr
, ")"))
2334 if (TrIsOperator (tr
, "@")) {
2335 TrReadOperator (tr
, "@");
2336 if (! TrReadInt (tr
, 0, 0x7FFFFFFF, & intVal
))
2338 src
-> mOffset
= (uint
) intVal
;
2342 if (! TrReadOperator (tr
, ":"))
2344 if (! TrReadString (tr
, MAX_PATH_LEN
, src
-> mPath
))
2349 // Process the list of sources in the data set definition.
2350 static int ProcessSources (const HeadModelT model
, TokenReaderT
* tr
, HrirDataT
* hData
) {
2351 uint
* setCount
= NULL
, * setFlag
= NULL
;
2352 double * hrir
= NULL
;
2353 uint line
, col
, ei
, ai
;
2357 setCount
= (uint
*) calloc (hData
-> mEvCount
, sizeof (uint
));
2358 setFlag
= (uint
*) calloc (hData
-> mIrCount
, sizeof (uint
));
2359 hrir
= CreateArray (hData
-> mIrPoints
);
2360 while (TrIsOperator (tr
, "[")) {
2361 TrIndication (tr
, & line
, & col
);
2362 TrReadOperator (tr
, "[");
2363 if (ReadIndexPair (tr
, hData
, & ei
, & ai
)) {
2364 if (TrReadOperator (tr
, "]")) {
2365 if (! setFlag
[hData
-> mEvOffset
[ei
] + ai
]) {
2366 if (TrReadOperator (tr
, "=")) {
2369 if (ReadSourceRef (tr
, & src
)) {
2370 if (LoadSource (& src
, hData
-> mIrRate
, hData
-> mIrPoints
, hrir
)) {
2371 if (model
== HM_DATASET
)
2372 AverageHrirOnset (hrir
, 1.0 / factor
, ei
, ai
, hData
);
2373 AverageHrirMagnitude (hrir
, 1.0 / factor
, ei
, ai
, hData
);
2375 if (! TrIsOperator (tr
, "+"))
2377 TrReadOperator (tr
, "+");
2381 DestroyArray (hrir
);
2386 setFlag
[hData
-> mEvOffset
[ei
] + ai
] = 1;
2391 TrErrorAt (tr
, line
, col
, "Redefinition of source.\n");
2395 DestroyArray (hrir
);
2401 while ((ei
< hData
-> mEvCount
) && (setCount
[ei
] < 1))
2403 if (ei
< hData
-> mEvCount
) {
2404 hData
-> mEvStart
= ei
;
2405 while ((ei
< hData
-> mEvCount
) && (setCount
[ei
] == hData
-> mAzCount
[ei
]))
2407 if (ei
>= hData
-> mEvCount
) {
2408 if (! TrLoad (tr
)) {
2409 DestroyArray (hrir
);
2414 TrError (tr
, "Errant data at end of source list.\n");
2417 TrError (tr
, "Missing sources for elevation index %d.\n", ei
);
2420 TrError (tr
, "Missing source references.\n");
2422 DestroyArray (hrir
);
2428 /* Parse the data set definition and process the source data, storing the
2429 * resulting data set as desired. If the input name is NULL it will read
2430 * from standard input.
2432 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
) {
2436 double * dfa
= NULL
;
2437 char rateStr
[8 + 1], expName
[MAX_PATH_LEN
];
2439 hData
. mIrRate
= 0;
2440 hData
. mIrPoints
= 0;
2441 hData
. mFftSize
= 0;
2442 hData
. mIrSize
= 0;
2443 hData
. mIrCount
= 0;
2444 hData
. mEvCount
= 0;
2445 hData
. mRadius
= 0;
2446 hData
. mDistance
= 0;
2447 fprintf (stdout
, "Reading HRIR definition...\n");
2448 if (inName
!= NULL
) {
2449 fp
= fopen (inName
, "r");
2451 fprintf (stderr
, "Error: Could not open definition file '%s'\n", inName
);
2454 TrSetup (fp
, inName
, & tr
);
2457 TrSetup (fp
, "<stdin>", & tr
);
2459 if (! ProcessMetrics (& tr
, fftSize
, truncSize
, & hData
)) {
2464 hData
. mHrirs
= CreateArray (hData
. mIrCount
* hData
. mIrSize
);
2465 hData
. mHrtds
= CreateArray (hData
. mIrCount
);
2466 if (! ProcessSources (model
, & tr
, & hData
)) {
2467 DestroyArray (hData
. mHrtds
);
2468 DestroyArray (hData
. mHrirs
);
2476 dfa
= CreateArray (1 + (hData
. mFftSize
/ 2));
2477 fprintf (stdout
, "Calculating diffuse-field average...\n");
2478 CalculateDiffuseFieldAverage (& hData
, surface
, limit
, dfa
);
2479 fprintf (stdout
, "Performing diffuse-field equalization...\n");
2480 DiffuseFieldEqualize (dfa
, & hData
);
2483 fprintf (stdout
, "Performing minimum phase reconstruction...\n");
2484 ReconstructHrirs (& hData
);
2485 if ((outRate
!= 0) && (outRate
!= hData
. mIrRate
)) {
2486 fprintf (stdout
, "Resampling HRIRs...\n");
2487 ResampleHrirs (outRate
, & hData
);
2489 fprintf (stdout
, "Truncating minimum-phase HRIRs...\n");
2490 hData
. mIrPoints
= truncSize
;
2491 fprintf (stdout
, "Synthesizing missing elevations...\n");
2492 if (model
== HM_DATASET
)
2493 SynthesizeOnsets (& hData
);
2494 SynthesizeHrirs (& hData
);
2495 fprintf (stdout
, "Normalizing final HRIRs...\n");
2496 NormalizeHrirs (& hData
);
2497 fprintf (stdout
, "Calculating impulse delays...\n");
2498 CalculateHrtds (model
, (radius
> DEFAULT_CUSTOM_RADIUS
) ? radius
: hData
. mRadius
, & hData
);
2499 snprintf (rateStr
, 8, "%u", hData
. mIrRate
);
2500 StrSubst (outName
, "%r", rateStr
, MAX_PATH_LEN
, expName
);
2501 switch (outFormat
) {
2503 fprintf (stdout
, "Creating MHR data set file...\n");
2504 if (! StoreMhr (& hData
, expName
))
2510 DestroyArray (hData
. mHrtds
);
2511 DestroyArray (hData
. mHrirs
);
2515 // Standard command line dispatch.
2516 int main (const int argc
, const char * argv
[]) {
2517 const char * inName
= NULL
, * outName
= NULL
;
2518 OutputFormatT outFormat
;
2520 uint outRate
, fftSize
;
2521 int equalize
, surface
;
2529 fprintf (stderr
, "Error: No command specified. See '%s -h' for help.\n", argv
[0]);
2532 if ((strcmp (argv
[1], "--help") == 0) || (strcmp (argv
[1], "-h") == 0)) {
2533 fprintf (stdout
, "HRTF Processing and Composition Utility\n\n");
2534 fprintf (stdout
, "Usage: %s <command> [<option>...]\n\n", argv
[0]);
2535 fprintf (stdout
, "Commands:\n");
2536 fprintf (stdout
, " -m, --make-mhr Makes an OpenAL Soft compatible HRTF data set.\n");
2537 fprintf (stdout
, " Defaults output to: ./oalsoft_hrtf_%%r.mhr\n");
2538 fprintf (stdout
, " -h, --help Displays this help information.\n\n");
2539 fprintf (stdout
, "Options:\n");
2540 fprintf (stdout
, " -r=<rate> Change the data set sample rate to the specified value and\n");
2541 fprintf (stdout
, " resample the HRIRs accordingly.\n");
2542 fprintf (stdout
, " -f=<points> Override the FFT window size (defaults to the first power-\n");
2543 fprintf (stdout
, " of-two that fits four times the number of HRIR points).\n");
2544 fprintf (stdout
, " -e={on|off} Toggle diffuse-field equalization (default: %s).\n", (DEFAULT_EQUALIZE
? "on" : "off"));
2545 fprintf (stdout
, " -s={on|off} Toggle surface-weighted diffuse-field average (default: %s).\n", (DEFAULT_SURFACE
? "on" : "off"));
2546 fprintf (stdout
, " -l={<dB>|none} Specify a limit to the magnitude range of the diffuse-field\n");
2547 fprintf (stdout
, " average (default: %.2f).\n", DEFAULT_LIMIT
);
2548 fprintf (stdout
, " -w=<points> Specify the size of the truncation window that's applied\n");
2549 fprintf (stdout
, " after minimum-phase reconstruction (default: %u).\n", DEFAULT_TRUNCSIZE
);
2550 fprintf (stdout
, " -d={dataset| Specify the model used for calculating the head-delay timing\n");
2551 fprintf (stdout
, " sphere} values (default: %s).\n", ((DEFAULT_HEAD_MODEL
== HM_DATASET
) ? "dataset" : "sphere"));
2552 fprintf (stdout
, " -c=<size> Use a customized head radius measured ear-to-ear in meters.\n");
2553 fprintf (stdout
, " -i=<filename> Specify an HRIR definition file to use (defaults to stdin).\n");
2554 fprintf (stdout
, " -o=<filename> Specify an output file. Overrides command-selected default.\n");
2555 fprintf (stdout
, " Use of '%%r' will be substituted with the data set sample rate.\n");
2558 if ((strcmp (argv
[1], "--make-mhr") == 0) || (strcmp (argv
[1], "-m") == 0)) {
2562 outName
= "./oalsoft_hrtf_%r.mhr";
2565 fprintf (stderr
, "Error: Invalid command '%s'.\n", argv
[1]);
2571 equalize
= DEFAULT_EQUALIZE
;
2572 surface
= DEFAULT_SURFACE
;
2573 limit
= DEFAULT_LIMIT
;
2574 truncSize
= DEFAULT_TRUNCSIZE
;
2575 model
= DEFAULT_HEAD_MODEL
;
2576 radius
= DEFAULT_CUSTOM_RADIUS
;
2577 while (argi
< argc
) {
2578 if (strncmp (argv
[argi
], "-r=", 3) == 0) {
2579 outRate
= strtoul (& argv
[argi
] [3], & end
, 10);
2580 if ((end
[0] != '\0') || (outRate
< MIN_RATE
) || (outRate
> MAX_RATE
)) {
2581 fprintf (stderr
, "Error: Expected a value from %u to %u for '-r'.\n", MIN_RATE
, MAX_RATE
);
2584 } else if (strncmp (argv
[argi
], "-f=", 3) == 0) {
2585 fftSize
= strtoul (& argv
[argi
] [3], & end
, 10);
2586 if ((end
[0] != '\0') || (fftSize
& (fftSize
- 1)) || (fftSize
< MIN_FFTSIZE
) || (fftSize
> MAX_FFTSIZE
)) {
2587 fprintf (stderr
, "Error: Expected a power-of-two value from %u to %u for '-f'.\n", MIN_FFTSIZE
, MAX_FFTSIZE
);
2590 } else if (strncmp (argv
[argi
], "-e=", 3) == 0) {
2591 if (strcmp (& argv
[argi
] [3], "on") == 0) {
2593 } else if (strcmp (& argv
[argi
] [3], "off") == 0) {
2596 fprintf (stderr
, "Error: Expected 'on' or 'off' for '-e'.\n");
2599 } else if (strncmp (argv
[argi
], "-s=", 3) == 0) {
2600 if (strcmp (& argv
[argi
] [3], "on") == 0) {
2602 } else if (strcmp (& argv
[argi
] [3], "off") == 0) {
2605 fprintf (stderr
, "Error: Expected 'on' or 'off' for '-s'.\n");
2608 } else if (strncmp (argv
[argi
], "-l=", 3) == 0) {
2609 if (strcmp (& argv
[argi
] [3], "none") == 0) {
2612 limit
= strtod (& argv
[argi
] [3], & end
);
2613 if ((end
[0] != '\0') || (limit
< MIN_LIMIT
) || (limit
> MAX_LIMIT
)) {
2614 fprintf (stderr
, "Error: Expected 'none' or a value from %.2f to %.2f for '-l'.\n", MIN_LIMIT
, MAX_LIMIT
);
2618 } else if (strncmp (argv
[argi
], "-w=", 3) == 0) {
2619 truncSize
= strtoul (& argv
[argi
] [3], & end
, 10);
2620 if ((end
[0] != '\0') || (truncSize
< MIN_TRUNCSIZE
) || (truncSize
> MAX_TRUNCSIZE
) || (truncSize
% MOD_TRUNCSIZE
)) {
2621 fprintf (stderr
, "Error: Expected a value from %u to %u in multiples of %u for '-w'.\n", MIN_TRUNCSIZE
, MAX_TRUNCSIZE
, MOD_TRUNCSIZE
);
2624 } else if (strncmp (argv
[argi
], "-d=", 3) == 0) {
2625 if (strcmp (& argv
[argi
] [3], "dataset") == 0) {
2627 } else if (strcmp (& argv
[argi
] [3], "sphere") == 0) {
2630 fprintf (stderr
, "Error: Expected 'dataset' or 'sphere' for '-d'.\n");
2633 } else if (strncmp (argv
[argi
], "-c=", 3) == 0) {
2634 radius
= strtod (& argv
[argi
] [3], & end
);
2635 if ((end
[0] != '\0') || (radius
< MIN_CUSTOM_RADIUS
) || (radius
> MAX_CUSTOM_RADIUS
)) {
2636 fprintf (stderr
, "Error: Expected a value from %.2f to %.2f for '-c'.\n", MIN_CUSTOM_RADIUS
, MAX_CUSTOM_RADIUS
);
2639 } else if (strncmp (argv
[argi
], "-i=", 3) == 0) {
2640 inName
= & argv
[argi
] [3];
2641 } else if (strncmp (argv
[argi
], "-o=", 3) == 0) {
2642 outName
= & argv
[argi
] [3];
2644 fprintf (stderr
, "Error: Invalid option '%s'.\n", argv
[argi
]);
2649 if (! ProcessDefinition (inName
, outRate
, fftSize
, equalize
, surface
, limit
, truncSize
, model
, radius
, outFormat
, outName
))
2651 fprintf (stdout
, "Operation completed.\n");