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.
198 typedef enum ByteOrderT
{
204 // Source format for the references listed in the data set definition.
205 typedef enum SourceFormatT
{
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.
214 typedef enum ElementTypeT
{
216 ET_INT
, // Integer elements.
217 ET_FP
// Floating-point elements.
220 // Head model used for calculating the impulse delays.
221 typedef enum HeadModelT
{
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.
228 typedef enum OutputFormatT
{
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
;
239 typedef ALuint uint32
;
240 typedef ALuint64SOFT uint64
;
242 // Token reader state for parsing the data set definition.
243 typedef struct TokenReaderT
{
248 char mRing
[TR_RING_SIZE
];
253 // Source reference state used when loading sources.
254 typedef struct SourceRefT
{
255 SourceFormatT mFormat
;
262 char mPath
[MAX_PATH_LEN
+1];
265 // The HRIR metrics and data set used when loading, processing, and storing
266 // the resulting HRTF.
267 typedef struct HrirDataT
{
275 uint mAzCount
[MAX_EV_COUNT
];
276 uint mEvOffset
[MAX_EV_COUNT
];
284 // The resampler metrics and FIR filter.
285 typedef struct ResamplerT
{
290 /*****************************
291 *** Token reader routines ***
292 *****************************/
293 /* Whitespace is not significant. It can process tokens as identifiers, numbers
294 * (integer and floating-point), strings, and operators. Strings must be
295 * encapsulated by double-quotes and cannot span multiple lines.
298 // Setup the reader on the given file. The filename can be NULL if no error
299 // output is desired.
300 static void TrSetup(FILE *fp
, const char *filename
, TokenReaderT
*tr
)
302 const char *name
= NULL
;
306 const char *slash
= strrchr(filename
, '/');
309 const char *bslash
= strrchr(slash
+1, '\\');
310 if(bslash
) name
= bslash
+1;
315 const char *bslash
= strrchr(filename
, '\\');
316 if(bslash
) name
= bslash
+1;
317 else name
= filename
;
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
)
333 size_t toLoad
, in
, count
;
335 toLoad
= TR_RING_SIZE
- (tr
->mIn
- tr
->mOut
);
336 if(toLoad
>= TR_LOAD_SIZE
&& !feof(tr
->mFile
))
338 // Load TR_LOAD_SIZE (or less if at the end of the file) per read.
339 toLoad
= TR_LOAD_SIZE
;
340 in
= tr
->mIn
&TR_RING_MASK
;
341 count
= TR_RING_SIZE
- in
;
344 tr
->mIn
+= fread(&tr
->mRing
[in
], 1, count
, tr
->mFile
);
345 tr
->mIn
+= fread(&tr
->mRing
[0], 1, toLoad
-count
, tr
->mFile
);
348 tr
->mIn
+= fread(&tr
->mRing
[in
], 1, toLoad
, tr
->mFile
);
350 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
)
366 fprintf(stderr
, "Error (%s:%u:%u): ", tr
->mName
, line
, column
);
367 vfprintf(stderr
, format
, argPtr
);
370 // Used to display an error at a saved line/column.
371 static void TrErrorAt(const TokenReaderT
*tr
, uint line
, uint column
, const char *format
, ...)
375 va_start(argPtr
, format
);
376 TrErrorVA(tr
, line
, column
, format
, argPtr
);
380 // Used to display an error at the current line/column.
381 static void TrError(const TokenReaderT
*tr
, const char *format
, ...)
385 va_start(argPtr
, format
);
386 TrErrorVA(tr
, tr
->mLine
, tr
->mColumn
, format
, argPtr
);
390 // Skips to the next line.
391 static void TrSkipLine(TokenReaderT
*tr
)
397 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
409 // Skips to the next token.
410 static int TrSkipWhitespace(TokenReaderT
*tr
)
416 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
436 // Get the line and/or column of the next token (or the end of input).
437 static void TrIndication(TokenReaderT
*tr
, uint
*line
, uint
*column
)
439 TrSkipWhitespace(tr
);
440 if(line
) *line
= tr
->mLine
;
441 if(column
) *column
= tr
->mColumn
;
444 // Checks to see if a token is the given operator. It does not display any
445 // errors and will not proceed to the next token.
446 static int TrIsOperator(TokenReaderT
*tr
, const char *op
)
451 if(!TrSkipWhitespace(tr
))
455 while(op
[len
] != '\0' && out
< tr
->mIn
)
457 ch
= tr
->mRing
[out
&TR_RING_MASK
];
458 if(ch
!= op
[len
]) break;
467 /* The TrRead*() routines obtain the value of a matching token type. They
468 * display type, form, and boundary errors and will proceed to the next
472 // Reads and validates an identifier token.
473 static int TrReadIdent(TokenReaderT
*tr
, const uint maxLen
, char *ident
)
479 if(TrSkipWhitespace(tr
))
482 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
483 if(ch
== '_' || isalpha(ch
))
493 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
494 } while(ch
== '_' || isdigit(ch
) || isalpha(ch
));
502 TrErrorAt(tr
, tr
->mLine
, col
, "Identifier is too long.\n");
506 TrErrorAt(tr
, tr
->mLine
, col
, "Expected an identifier.\n");
510 // Reads and validates (including bounds) an integer token.
511 static int TrReadInt(TokenReaderT
*tr
, const int loBound
, const int hiBound
, int *value
)
513 uint col
, digis
, len
;
517 if(TrSkipWhitespace(tr
))
521 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
522 if(ch
== '+' || ch
== '-')
531 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
532 if(!isdigit(ch
)) break;
540 if(digis
> 0 && ch
!= '.' && !isalpha(ch
))
544 TrErrorAt(tr
, tr
->mLine
, col
, "Integer is too long.");
548 *value
= strtol(temp
, NULL
, 10);
549 if(*value
< loBound
|| *value
> hiBound
)
551 TrErrorAt(tr
, tr
->mLine
, col
, "Expected a value from %d to %d.\n", loBound
, hiBound
);
557 TrErrorAt(tr
, tr
->mLine
, col
, "Expected an integer.\n");
561 // Reads and validates (including bounds) a float token.
562 static int TrReadFloat(TokenReaderT
*tr
, const double loBound
, const double hiBound
, double *value
)
564 uint col
, digis
, len
;
568 if(TrSkipWhitespace(tr
))
572 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
573 if(ch
== '+' || ch
== '-')
583 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
584 if(!isdigit(ch
)) break;
600 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
601 if(!isdigit(ch
)) break;
610 if(ch
== 'E' || ch
== 'e')
617 if(ch
== '+' || ch
== '-')
626 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
627 if(!isdigit(ch
)) break;
636 if(digis
> 0 && ch
!= '.' && !isalpha(ch
))
640 TrErrorAt(tr
, tr
->mLine
, col
, "Float is too long.");
644 *value
= strtod(temp
, NULL
);
645 if(*value
< loBound
|| *value
> hiBound
)
647 TrErrorAt (tr
, tr
->mLine
, col
, "Expected a value from %f to %f.\n", loBound
, hiBound
);
656 TrErrorAt(tr
, tr
->mLine
, col
, "Expected a float.\n");
660 // Reads and validates a string token.
661 static int TrReadString(TokenReaderT
*tr
, const uint maxLen
, char *text
)
667 if(TrSkipWhitespace(tr
))
670 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
677 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
683 TrErrorAt (tr
, tr
->mLine
, col
, "Unterminated string at end of line.\n");
692 tr
->mColumn
+= 1 + len
;
693 TrErrorAt(tr
, tr
->mLine
, col
, "Unterminated string at end of input.\n");
696 tr
->mColumn
+= 2 + len
;
699 TrErrorAt (tr
, tr
->mLine
, col
, "String is too long.\n");
706 TrErrorAt(tr
, tr
->mLine
, col
, "Expected a string.\n");
710 // Reads and validates the given operator.
711 static int TrReadOperator(TokenReaderT
*tr
, const char *op
)
717 if(TrSkipWhitespace(tr
))
721 while(op
[len
] != '\0' && TrLoad(tr
))
723 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
724 if(ch
!= op
[len
]) break;
732 TrErrorAt(tr
, tr
->mLine
, col
, "Expected '%s' operator.\n", op
);
736 /* Performs a string substitution. Any case-insensitive occurrences of the
737 * pattern string are replaced with the replacement string. The result is
738 * truncated if necessary.
740 static int StrSubst(const char *in
, const char *pat
, const char *rep
, const size_t maxLen
, char *out
)
742 size_t inLen
, patLen
, repLen
;
747 patLen
= strlen(pat
);
748 repLen
= strlen(rep
);
752 while(si
< inLen
&& di
< maxLen
)
754 if(patLen
<= inLen
-si
)
756 if(strncasecmp(&in
[si
], pat
, patLen
) == 0)
758 if(repLen
> maxLen
-di
)
760 repLen
= maxLen
- di
;
763 strncpy(&out
[di
], rep
, repLen
);
779 /*********************
780 *** Math routines ***
781 *********************/
783 // Provide missing math routines for MSVC versions < 1800 (Visual Studio 2013).
784 #if defined(_MSC_VER) && _MSC_VER < 1800
785 static double round(double val
)
788 return ceil(val
-0.5);
789 return floor(val
+0.5);
792 static double fmin(double a
, double b
)
794 return (a
<b
) ? a
: b
;
797 static double fmax(double a
, double b
)
799 return (a
>b
) ? a
: b
;
803 // Simple clamp routine.
804 static double Clamp(const double val
, const double lower
, const double upper
)
806 return fmin(fmax(val
, lower
), upper
);
809 // Performs linear interpolation.
810 static double Lerp(const double a
, const double b
, const double f
)
812 return a
+ (f
* (b
- a
));
815 // Performs a high-passed triangular probability density function dither from
816 // a double to an integer. It assumes the input sample is already scaled.
817 static int HpTpdfDither(const double in
, int *hpHist
)
819 static const double PRNG_SCALE
= 1.0 / (RAND_MAX
+1.0);
824 out
= round(in
+ (PRNG_SCALE
* (prn
- *hpHist
)));
829 // Allocates an array of doubles.
830 static double *CreateArray(size_t n
)
835 a
= calloc(n
, sizeof(double));
838 fprintf(stderr
, "Error: Out of memory.\n");
844 // Frees an array of doubles.
845 static void DestroyArray(double *a
)
848 // Complex number routines. All outputs must be non-NULL.
850 // Magnitude/absolute value.
851 static double ComplexAbs(const double r
, const double i
)
853 return sqrt(r
*r
+ i
*i
);
857 static void ComplexMul(const double aR
, const double aI
, const double bR
, const double bI
, double *outR
, double *outI
)
859 *outR
= (aR
* bR
) - (aI
* bI
);
860 *outI
= (aI
* bR
) + (aR
* bI
);
864 static void ComplexExp(const double inR
, const double inI
, double *outR
, double *outI
)
867 *outR
= e
* cos(inI
);
868 *outI
= e
* sin(inI
);
871 /* Fast Fourier transform routines. The number of points must be a power of
872 * two. In-place operation is possible only if both the real and imaginary
873 * parts are in-place together.
876 // Performs bit-reversal ordering.
877 static void FftArrange(const uint n
, const double *inR
, const double *inI
, double *outR
, double *outI
)
882 if(inR
== outR
&& inI
== outI
)
884 // Handle in-place arrangement.
905 // Handle copy arrangement.
919 // Performs the summation.
920 static void FftSummation(const uint n
, const double s
, double *re
, double *im
)
924 double vR
, vI
, wR
, wI
;
929 for(m
= 1, m2
= 2;m
< n
; m
<<= 1, m2
<<= 1)
931 // v = Complex (-2.0 * sin (0.5 * pi / m) * sin (0.5 * pi / m), -sin (pi / m))
932 vR
= sin(0.5 * pi
/ m
);
935 // w = Complex (1.0, 0.0)
940 for(k
= i
;k
< n
;k
+= m2
)
943 // t = ComplexMul(w, out[km2])
944 tR
= (wR
* re
[mk
]) - (wI
* im
[mk
]);
945 tI
= (wR
* im
[mk
]) + (wI
* re
[mk
]);
946 // out[mk] = ComplexSub (out [k], t)
949 // out[k] = ComplexAdd (out [k], t)
953 // t = ComplexMul (v, w)
954 tR
= (vR
* wR
) - (vI
* wI
);
955 tI
= (vR
* wI
) + (vI
* wR
);
956 // w = ComplexAdd (w, t)
963 // Performs a forward FFT.
964 static void FftForward(const uint n
, const double *inR
, const double *inI
, double *outR
, double *outI
)
966 FftArrange(n
, inR
, inI
, outR
, outI
);
967 FftSummation(n
, 1.0, outR
, outI
);
970 // Performs an inverse FFT.
971 static void FftInverse(const uint n
, const double *inR
, const double *inI
, double *outR
, double *outI
)
976 FftArrange(n
, inR
, inI
, outR
, outI
);
977 FftSummation(n
, -1.0, outR
, outI
);
986 /* Calculate the complex helical sequence (or discrete-time analytical
987 * signal) of the given input using the Hilbert transform. Given the
988 * negative natural logarithm of a signal's magnitude response, the imaginary
989 * components can be used as the angles for minimum-phase reconstruction.
991 static void Hilbert(const uint n
, const double *in
, double *outR
, double *outI
)
997 // Handle in-place operation.
1003 // Handle copy operation.
1004 for(i
= 0;i
< n
;i
++)
1010 FftForward(n
, outR
, outI
, outR
, outI
);
1011 /* Currently the Fourier routines operate only on point counts that are
1012 * powers of two. If that changes and n is odd, the following conditional
1013 * should be: i < (n + 1) / 2.
1015 for(i
= 1;i
< (n
/2);i
++)
1020 // If n is odd, the following increment should be skipped.
1027 FftInverse(n
, outR
, outI
, outR
, outI
);
1030 /* Calculate the magnitude response of the given input. This is used in
1031 * place of phase decomposition, since the phase residuals are discarded for
1032 * minimum phase reconstruction. The mirrored half of the response is also
1035 static void MagnitudeResponse(const uint n
, const double *inR
, const double *inI
, double *out
)
1037 const uint m
= 1 + (n
/ 2);
1039 for(i
= 0;i
< m
;i
++)
1040 out
[i
] = fmax(ComplexAbs(inR
[i
], inI
[i
]), EPSILON
);
1043 /* Apply a range limit (in dB) to the given magnitude response. This is used
1044 * to adjust the effects of the diffuse-field average on the equalization
1047 static void LimitMagnitudeResponse(const uint n
, const double limit
, const double *in
, double *out
)
1049 const uint m
= 1 + (n
/ 2);
1051 uint i
, lower
, upper
;
1054 halfLim
= limit
/ 2.0;
1055 // Convert the response to dB.
1056 for(i
= 0;i
< m
;i
++)
1057 out
[i
] = 20.0 * log10(in
[i
]);
1058 // Use six octaves to calculate the average magnitude of the signal.
1059 lower
= ((uint
)ceil(n
/ pow(2.0, 8.0))) - 1;
1060 upper
= ((uint
)floor(n
/ pow(2.0, 2.0))) - 1;
1062 for(i
= lower
;i
<= upper
;i
++)
1064 ave
/= upper
- lower
+ 1;
1065 // Keep the response within range of the average magnitude.
1066 for(i
= 0;i
< m
;i
++)
1067 out
[i
] = Clamp(out
[i
], ave
- halfLim
, ave
+ halfLim
);
1068 // Convert the response back to linear magnitude.
1069 for(i
= 0;i
< m
;i
++)
1070 out
[i
] = pow(10.0, out
[i
] / 20.0);
1073 /* Reconstructs the minimum-phase component for the given magnitude response
1074 * of a signal. This is equivalent to phase recomposition, sans the missing
1075 * residuals (which were discarded). The mirrored half of the response is
1078 static void MinimumPhase(const uint n
, const double *in
, double *outR
, double *outI
)
1080 const uint m
= 1 + (n
/ 2);
1085 mags
= CreateArray(n
);
1086 for(i
= 0;i
< m
;i
++)
1088 mags
[i
] = fmax(in
[i
], EPSILON
);
1089 outR
[i
] = -log(mags
[i
]);
1093 mags
[i
] = mags
[n
- i
];
1094 outR
[i
] = outR
[n
- i
];
1096 Hilbert(n
, outR
, outR
, outI
);
1097 // Remove any DC offset the filter has.
1100 for(i
= 1;i
< n
;i
++)
1102 ComplexExp(0.0, outI
[i
], &aR
, &aI
);
1103 ComplexMul(mags
[i
], 0.0, aR
, aI
, &outR
[i
], &outI
[i
]);
1109 /***************************
1110 *** Resampler functions ***
1111 ***************************/
1113 /* This is the normalized cardinal sine (sinc) function.
1115 * sinc(x) = { 1, x = 0
1116 * { sin(pi x) / (pi x), otherwise.
1118 static double Sinc(const double x
)
1120 if(fabs(x
) < EPSILON
)
1122 return sin(M_PI
* x
) / (M_PI
* x
);
1125 /* The zero-order modified Bessel function of the first kind, used for the
1128 * I_0(x) = sum_{k=0}^inf (1 / k!)^2 (x / 2)^(2 k)
1129 * = sum_{k=0}^inf ((x / 2)^k / k!)^2
1131 static double BesselI_0(const double x
)
1133 double term
, sum
, x2
, y
, last_sum
;
1136 // Start at k=1 since k=0 is trivial.
1142 // Let the integration converge until the term of the sum is no longer
1150 } while(sum
!= last_sum
);
1154 /* Calculate a Kaiser window from the given beta value and a normalized k
1157 * w(k) = { I_0(B sqrt(1 - k^2)) / I_0(B), -1 <= k <= 1
1160 * Where k can be calculated as:
1162 * k = i / l, where -l <= i <= l.
1166 * k = 2 i / M - 1, where 0 <= i <= M.
1168 static double Kaiser(const double b
, const double k
)
1170 if(!(k
>= -1.0 && k
<= 1.0))
1172 return BesselI_0(b
* sqrt(1.0 - k
*k
)) / BesselI_0(b
);
1175 // Calculates the greatest common divisor of a and b.
1176 static uint
Gcd(uint x
, uint y
)
1187 /* Calculates the size (order) of the Kaiser window. Rejection is in dB and
1188 * the transition width is normalized frequency (0.5 is nyquist).
1190 * M = { ceil((r - 7.95) / (2.285 2 pi f_t)), r > 21
1191 * { ceil(5.79 / 2 pi f_t), r <= 21.
1194 static uint
CalcKaiserOrder(const double rejection
, const double transition
)
1196 double w_t
= 2.0 * M_PI
* transition
;
1197 if(rejection
> 21.0)
1198 return (uint
)ceil((rejection
- 7.95) / (2.285 * w_t
));
1199 return (uint
)ceil(5.79 / w_t
);
1202 // Calculates the beta value of the Kaiser window. Rejection is in dB.
1203 static double CalcKaiserBeta(const double rejection
)
1205 if(rejection
> 50.0)
1206 return 0.1102 * (rejection
- 8.7);
1207 if(rejection
>= 21.0)
1208 return (0.5842 * pow(rejection
- 21.0, 0.4)) +
1209 (0.07886 * (rejection
- 21.0));
1213 /* Calculates a point on the Kaiser-windowed sinc filter for the given half-
1214 * width, beta, gain, and cutoff. The point is specified in non-normalized
1215 * samples, from 0 to M, where M = (2 l + 1).
1217 * w(k) 2 p f_t sinc(2 f_t x)
1219 * x -- centered sample index (i - l)
1220 * k -- normalized and centered window index (x / l)
1221 * w(k) -- window function (Kaiser)
1222 * p -- gain compensation factor when sampling
1223 * f_t -- normalized center frequency (or cutoff; 0.5 is nyquist)
1225 static double SincFilter(const int l
, const double b
, const double gain
, const double cutoff
, const int i
)
1227 return Kaiser(b
, (double)(i
- l
) / l
) * 2.0 * gain
* cutoff
* Sinc(2.0 * cutoff
* (i
- l
));
1230 /* This is a polyphase sinc-filtered resampler.
1232 * Upsample Downsample
1234 * p/q = 3/2 p/q = 3/5
1236 * M-+-+-+-> M-+-+-+->
1237 * -------------------+ ---------------------+
1238 * p s * f f f f|f| | p s * f f f f f |
1239 * | 0 * 0 0 0|0|0 | | 0 * 0 0 0 0|0| |
1240 * v 0 * 0 0|0|0 0 | v 0 * 0 0 0|0|0 |
1241 * s * f|f|f f f | s * f f|f|f f |
1242 * 0 * |0|0 0 0 0 | 0 * 0|0|0 0 0 |
1243 * --------+=+--------+ 0 * |0|0 0 0 0 |
1244 * d . d .|d|. d . d ----------+=+--------+
1245 * d . . . .|d|. . . .
1249 * P_f(i,j) = q i mod p + pj
1250 * P_s(i,j) = floor(q i / p) - j
1251 * d[i=0..N-1] = sum_{j=0}^{floor((M - 1) / p)} {
1252 * { f[P_f(i,j)] s[P_s(i,j)], P_f(i,j) < M
1253 * { 0, P_f(i,j) >= M. }
1256 // Calculate the resampling metrics and build the Kaiser-windowed sinc filter
1257 // that's used to cut frequencies above the destination nyquist.
1258 static void ResamplerSetup(ResamplerT
*rs
, const uint srcRate
, const uint dstRate
)
1260 double cutoff
, width
, beta
;
1264 gcd
= Gcd(srcRate
, dstRate
);
1265 rs
->mP
= dstRate
/ gcd
;
1266 rs
->mQ
= srcRate
/ gcd
;
1267 /* The cutoff is adjusted by half the transition width, so the transition
1268 * ends before the nyquist (0.5). Both are scaled by the downsampling
1273 cutoff
= 0.45 / rs
->mP
;
1274 width
= 0.1 / rs
->mP
;
1278 cutoff
= 0.45 / rs
->mQ
;
1279 width
= 0.1 / rs
->mQ
;
1281 // A rejection of -180 dB is used for the stop band.
1282 l
= CalcKaiserOrder(180.0, width
) / 2;
1283 beta
= CalcKaiserBeta(180.0);
1284 rs
->mM
= (2 * l
) + 1;
1286 rs
->mF
= CreateArray(rs
->mM
);
1287 for(i
= 0;i
< ((int)rs
->mM
);i
++)
1288 rs
->mF
[i
] = SincFilter((int)l
, beta
, rs
->mP
, cutoff
, i
);
1291 // Clean up after the resampler.
1292 static void ResamplerClear(ResamplerT
*rs
)
1294 DestroyArray(rs
->mF
);
1298 // Perform the upsample-filter-downsample resampling operation using a
1299 // polyphase filter implementation.
1300 static void ResamplerRun(ResamplerT
*rs
, const uint inN
, const double *in
, const uint outN
, double *out
)
1302 const uint p
= rs
->mP
, q
= rs
->mQ
, m
= rs
->mM
, l
= rs
->mL
;
1303 const double *f
= rs
->mF
;
1311 // Handle in-place operation.
1313 work
= CreateArray(outN
);
1316 // Resample the input.
1317 for(i
= 0;i
< outN
;i
++)
1320 // Input starts at l to compensate for the filter delay. This will
1321 // drop any build-up from the first half of the filter.
1322 j_f
= (l
+ (q
* i
)) % p
;
1323 j_s
= (l
+ (q
* i
)) / p
;
1326 // Only take input when 0 <= j_s < inN. This single unsigned
1327 // comparison catches both cases.
1329 r
+= f
[j_f
] * in
[j_s
];
1335 // Clean up after in-place operation.
1338 for(i
= 0;i
< outN
;i
++)
1344 // Read a binary value of the specified byte order and byte size from a file,
1345 // storing it as a 32-bit unsigned integer.
1346 static int ReadBin4(FILE *fp
, const char *filename
, const ByteOrderT order
, const uint bytes
, uint32
*out
)
1352 if(fread(in
, 1, bytes
, fp
) != bytes
)
1354 fprintf(stderr
, "Error: Bad read from file '%s'.\n", filename
);
1361 for(i
= 0;i
< bytes
;i
++)
1362 accum
= (accum
<<8) | in
[bytes
- i
- 1];
1365 for(i
= 0;i
< bytes
;i
++)
1366 accum
= (accum
<<8) | in
[i
];
1375 // Read a binary value of the specified byte order from a file, storing it as
1376 // a 64-bit unsigned integer.
1377 static int ReadBin8(FILE *fp
, const char *filename
, const ByteOrderT order
, uint64
*out
)
1383 if(fread(in
, 1, 8, fp
) != 8)
1385 fprintf(stderr
, "Error: Bad read from file '%s'.\n", filename
);
1392 for(i
= 0;i
< 8;i
++)
1393 accum
= (accum
<<8) | in
[8 - i
- 1];
1396 for(i
= 0;i
< 8;i
++)
1397 accum
= (accum
<<8) | in
[i
];
1406 // Write an ASCII string to a file.
1407 static int WriteAscii(const char *out
, FILE *fp
, const char *filename
)
1412 if(fwrite(out
, 1, len
, fp
) != len
)
1415 fprintf(stderr
, "Error: Bad write to file '%s'.\n", filename
);
1421 // Write a binary value of the given byte order and byte size to a file,
1422 // loading it from a 32-bit unsigned integer.
1423 static int WriteBin4(const ByteOrderT order
, const uint bytes
, const uint32 in
, FILE *fp
, const char *filename
)
1431 for(i
= 0;i
< bytes
;i
++)
1432 out
[i
] = (in
>>(i
*8)) & 0x000000FF;
1435 for(i
= 0;i
< bytes
;i
++)
1436 out
[bytes
- i
- 1] = (in
>>(i
*8)) & 0x000000FF;
1441 if(fwrite(out
, 1, bytes
, fp
) != bytes
)
1443 fprintf(stderr
, "Error: Bad write to file '%s'.\n", filename
);
1449 /* Read a binary value of the specified type, byte order, and byte size from
1450 * a file, converting it to a double. For integer types, the significant
1451 * bits are used to normalize the result. The sign of bits determines
1452 * whether they are padded toward the MSB (negative) or LSB (positive).
1453 * Floating-point types are not normalized.
1455 static int ReadBinAsDouble(FILE *fp
, const char *filename
, const ByteOrderT order
, const ElementTypeT type
, const uint bytes
, const int bits
, double *out
)
1470 if(!ReadBin8(fp
, filename
, order
, &v8
.ui
))
1477 if(!ReadBin4(fp
, filename
, order
, bytes
, &v4
.ui
))
1484 v4
.ui
>>= (8*bytes
) - ((uint
)bits
);
1486 v4
.ui
&= (0xFFFFFFFF >> (32+bits
));
1488 if(v4
.ui
&(uint
)(1<<(abs(bits
)-1)))
1489 v4
.ui
|= (0xFFFFFFFF << abs (bits
));
1490 *out
= v4
.i
/ (double)(1<<(abs(bits
)-1));
1496 /* Read an ascii value of the specified type from a file, converting it to a
1497 * double. For integer types, the significant bits are used to normalize the
1498 * result. The sign of the bits should always be positive. This also skips
1499 * up to one separator character before the element itself.
1501 static int ReadAsciiAsDouble(TokenReaderT
*tr
, const char *filename
, const ElementTypeT type
, const uint bits
, double *out
)
1503 if(TrIsOperator(tr
, ","))
1504 TrReadOperator(tr
, ",");
1505 else if(TrIsOperator(tr
, ":"))
1506 TrReadOperator(tr
, ":");
1507 else if(TrIsOperator(tr
, ";"))
1508 TrReadOperator(tr
, ";");
1509 else if(TrIsOperator(tr
, "|"))
1510 TrReadOperator(tr
, "|");
1514 if(!TrReadFloat(tr
, -HUGE_VAL
, HUGE_VAL
, out
))
1516 fprintf(stderr
, "Error: Bad read from file '%s'.\n", filename
);
1523 if(!TrReadInt(tr
, -(1<<(bits
-1)), (1<<(bits
-1))-1, &v
))
1525 fprintf(stderr
, "Error: Bad read from file '%s'.\n", filename
);
1528 *out
= v
/ (double)((1<<(bits
-1))-1);
1533 // Read the RIFF/RIFX WAVE format chunk from a file, validating it against
1534 // the source parameters and data set metrics.
1535 static int ReadWaveFormat(FILE *fp
, const ByteOrderT order
, const uint hrirRate
, SourceRefT
*src
)
1537 uint32 fourCC
, chunkSize
;
1538 uint32 format
, channels
, rate
, dummy
, block
, size
, bits
;
1543 fseek (fp
, (long) chunkSize
, SEEK_CUR
);
1544 if(!ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, &fourCC
) ||
1545 !ReadBin4(fp
, src
->mPath
, order
, 4, &chunkSize
))
1547 } while(fourCC
!= FOURCC_FMT
);
1548 if(!ReadBin4(fp
, src
->mPath
, order
, 2, & format
) ||
1549 !ReadBin4(fp
, src
->mPath
, order
, 2, & channels
) ||
1550 !ReadBin4(fp
, src
->mPath
, order
, 4, & rate
) ||
1551 !ReadBin4(fp
, src
->mPath
, order
, 4, & dummy
) ||
1552 !ReadBin4(fp
, src
->mPath
, order
, 2, & block
))
1557 if(!ReadBin4(fp
, src
->mPath
, order
, 2, &size
))
1565 if(format
== WAVE_FORMAT_EXTENSIBLE
)
1567 fseek(fp
, 2, SEEK_CUR
);
1568 if(!ReadBin4(fp
, src
->mPath
, order
, 2, &bits
))
1572 fseek(fp
, 4, SEEK_CUR
);
1573 if(!ReadBin4(fp
, src
->mPath
, order
, 2, &format
))
1575 fseek(fp
, (long)(chunkSize
- 26), SEEK_CUR
);
1581 fseek(fp
, (long)(chunkSize
- 16), SEEK_CUR
);
1583 fseek(fp
, (long)(chunkSize
- 14), SEEK_CUR
);
1585 if(format
!= WAVE_FORMAT_PCM
&& format
!= WAVE_FORMAT_IEEE_FLOAT
)
1587 fprintf(stderr
, "Error: Unsupported WAVE format in file '%s'.\n", src
->mPath
);
1590 if(src
->mChannel
>= channels
)
1592 fprintf(stderr
, "Error: Missing source channel in WAVE file '%s'.\n", src
->mPath
);
1595 if(rate
!= hrirRate
)
1597 fprintf(stderr
, "Error: Mismatched source sample rate in WAVE file '%s'.\n", src
->mPath
);
1600 if(format
== WAVE_FORMAT_PCM
)
1602 if(size
< 2 || size
> 4)
1604 fprintf(stderr
, "Error: Unsupported sample size in WAVE file '%s'.\n", src
->mPath
);
1607 if(bits
< 16 || bits
> (8*size
))
1609 fprintf (stderr
, "Error: Bad significant bits in WAVE file '%s'.\n", src
->mPath
);
1612 src
->mType
= ET_INT
;
1616 if(size
!= 4 && size
!= 8)
1618 fprintf(stderr
, "Error: Unsupported sample size in WAVE file '%s'.\n", src
->mPath
);
1624 src
->mBits
= (int)bits
;
1625 src
->mSkip
= channels
;
1629 // Read a RIFF/RIFX WAVE data chunk, converting all elements to doubles.
1630 static int ReadWaveData(FILE *fp
, const SourceRefT
*src
, const ByteOrderT order
, const uint n
, double *hrir
)
1632 int pre
, post
, skip
;
1635 pre
= (int)(src
->mSize
* src
->mChannel
);
1636 post
= (int)(src
->mSize
* (src
->mSkip
- src
->mChannel
- 1));
1638 for(i
= 0;i
< n
;i
++)
1642 fseek(fp
, skip
, SEEK_CUR
);
1643 if(!ReadBinAsDouble(fp
, src
->mPath
, order
, src
->mType
, src
->mSize
, src
->mBits
, &hrir
[i
]))
1648 fseek(fp
, skip
, SEEK_CUR
);
1652 // Read the RIFF/RIFX WAVE list or data chunk, converting all elements to
1654 static int ReadWaveList(FILE *fp
, const SourceRefT
*src
, const ByteOrderT order
, const uint n
, double *hrir
)
1656 uint32 fourCC
, chunkSize
, listSize
, count
;
1657 uint block
, skip
, offset
, i
;
1661 if(!ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, & fourCC
) ||
1662 !ReadBin4(fp
, src
->mPath
, order
, 4, & chunkSize
))
1665 if(fourCC
== FOURCC_DATA
)
1667 block
= src
->mSize
* src
->mSkip
;
1668 count
= chunkSize
/ block
;
1669 if(count
< (src
->mOffset
+ n
))
1671 fprintf(stderr
, "Error: Bad read from file '%s'.\n", src
->mPath
);
1674 fseek(fp
, (long)(src
->mOffset
* block
), SEEK_CUR
);
1675 if(!ReadWaveData(fp
, src
, order
, n
, &hrir
[0]))
1679 else if(fourCC
== FOURCC_LIST
)
1681 if(!ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, &fourCC
))
1684 if(fourCC
== FOURCC_WAVL
)
1688 fseek(fp
, (long)chunkSize
, SEEK_CUR
);
1690 listSize
= chunkSize
;
1691 block
= src
->mSize
* src
->mSkip
;
1692 skip
= src
->mOffset
;
1695 while(offset
< n
&& listSize
> 8)
1697 if(!ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, &fourCC
) ||
1698 !ReadBin4(fp
, src
->mPath
, order
, 4, &chunkSize
))
1700 listSize
-= 8 + chunkSize
;
1701 if(fourCC
== FOURCC_DATA
)
1703 count
= chunkSize
/ block
;
1706 fseek(fp
, (long)(skip
* block
), SEEK_CUR
);
1707 chunkSize
-= skip
* block
;
1710 if(count
> (n
- offset
))
1712 if(!ReadWaveData(fp
, src
, order
, count
, &hrir
[offset
]))
1714 chunkSize
-= count
* block
;
1716 lastSample
= hrir
[offset
- 1];
1724 else if(fourCC
== FOURCC_SLNT
)
1726 if(!ReadBin4(fp
, src
->mPath
, order
, 4, &count
))
1733 if(count
> (n
- offset
))
1735 for(i
= 0; i
< count
; i
++)
1736 hrir
[offset
+ i
] = lastSample
;
1746 fseek(fp
, (long)chunkSize
, SEEK_CUR
);
1750 fprintf(stderr
, "Error: Bad read from file '%s'.\n", src
->mPath
);
1756 // Load a source HRIR from a RIFF/RIFX WAVE file.
1757 static int LoadWaveSource(FILE *fp
, SourceRefT
*src
, const uint hrirRate
, const uint n
, double *hrir
)
1759 uint32 fourCC
, dummy
;
1762 if(!ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, &fourCC
) ||
1763 !ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, &dummy
))
1765 if(fourCC
== FOURCC_RIFF
)
1767 else if(fourCC
== FOURCC_RIFX
)
1771 fprintf(stderr
, "Error: No RIFF/RIFX chunk in file '%s'.\n", src
->mPath
);
1775 if(!ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, &fourCC
))
1777 if(fourCC
!= FOURCC_WAVE
)
1779 fprintf(stderr
, "Error: Not a RIFF/RIFX WAVE file '%s'.\n", src
->mPath
);
1782 if(!ReadWaveFormat(fp
, order
, hrirRate
, src
))
1784 if(!ReadWaveList(fp
, src
, order
, n
, hrir
))
1789 // Load a source HRIR from a binary file.
1790 static int LoadBinarySource(FILE *fp
, const SourceRefT
*src
, const ByteOrderT order
, const uint n
, double *hrir
)
1794 fseek(fp
, (long)src
->mOffset
, SEEK_SET
);
1795 for(i
= 0;i
< n
;i
++)
1797 if(!ReadBinAsDouble(fp
, src
->mPath
, order
, src
->mType
, src
->mSize
, src
->mBits
, &hrir
[i
]))
1800 fseek(fp
, (long)src
->mSkip
, SEEK_CUR
);
1805 // Load a source HRIR from an ASCII text file containing a list of elements
1806 // separated by whitespace or common list operators (',', ';', ':', '|').
1807 static int LoadAsciiSource(FILE *fp
, const SourceRefT
*src
, const uint n
, double *hrir
)
1813 TrSetup(fp
, NULL
, &tr
);
1814 for(i
= 0;i
< src
->mOffset
;i
++)
1816 if(!ReadAsciiAsDouble(&tr
, src
->mPath
, src
->mType
, (uint
)src
->mBits
, &dummy
))
1819 for(i
= 0;i
< n
;i
++)
1821 if(!ReadAsciiAsDouble(&tr
, src
->mPath
, src
->mType
, (uint
)src
->mBits
, &hrir
[i
]))
1823 for(j
= 0;j
< src
->mSkip
;j
++)
1825 if(!ReadAsciiAsDouble(&tr
, src
->mPath
, src
->mType
, (uint
)src
->mBits
, &dummy
))
1832 // Load a source HRIR from a supported file type.
1833 static int LoadSource(SourceRefT
*src
, const uint hrirRate
, const uint n
, double *hrir
)
1838 if (src
->mFormat
== SF_ASCII
)
1839 fp
= fopen(src
->mPath
, "r");
1841 fp
= fopen(src
->mPath
, "rb");
1844 fprintf(stderr
, "Error: Could not open source file '%s'.\n", src
->mPath
);
1847 if(src
->mFormat
== SF_WAVE
)
1848 result
= LoadWaveSource(fp
, src
, hrirRate
, n
, hrir
);
1849 else if(src
->mFormat
== SF_BIN_LE
)
1850 result
= LoadBinarySource(fp
, src
, BO_LITTLE
, n
, hrir
);
1851 else if(src
->mFormat
== SF_BIN_BE
)
1852 result
= LoadBinarySource(fp
, src
, BO_BIG
, n
, hrir
);
1854 result
= LoadAsciiSource(fp
, src
, n
, hrir
);
1859 // Calculate the onset time of an HRIR and average it with any existing
1860 // timing for its elevation and azimuth.
1861 static void AverageHrirOnset(const double *hrir
, const double f
, const uint ei
, const uint ai
, const HrirDataT
*hData
)
1867 n
= hData
->mIrPoints
;
1868 for(i
= 0;i
< n
;i
++)
1869 mag
= fmax(fabs(hrir
[i
]), mag
);
1871 for(i
= 0;i
< n
;i
++)
1873 if(fabs(hrir
[i
]) >= mag
)
1876 j
= hData
->mEvOffset
[ei
] + ai
;
1877 hData
->mHrtds
[j
] = Lerp(hData
->mHrtds
[j
], ((double)i
) / hData
->mIrRate
, f
);
1880 // Calculate the magnitude response of an HRIR and average it with any
1881 // existing responses for its elevation and azimuth.
1882 static void AverageHrirMagnitude(const double *hrir
, const double f
, const uint ei
, const uint ai
, const HrirDataT
*hData
)
1887 n
= hData
->mFftSize
;
1888 re
= CreateArray(n
);
1889 im
= CreateArray(n
);
1890 for(i
= 0;i
< hData
->mIrPoints
;i
++)
1900 FftForward(n
, re
, im
, re
, im
);
1901 MagnitudeResponse(n
, re
, im
, re
);
1903 j
= (hData
->mEvOffset
[ei
] + ai
) * hData
->mIrSize
;
1904 for(i
= 0;i
< m
;i
++)
1905 hData
->mHrirs
[j
+i
] = Lerp(hData
->mHrirs
[j
+i
], re
[i
], f
);
1910 /* Calculate the contribution of each HRIR to the diffuse-field average based
1911 * on the area of its surface patch. All patches are centered at the HRIR
1912 * coordinates on the unit sphere and are measured by solid angle.
1914 static void CalculateDfWeights(const HrirDataT
*hData
, double *weights
)
1916 double evs
, sum
, ev
, up_ev
, down_ev
, solidAngle
;
1919 evs
= 90.0 / (hData
->mEvCount
- 1);
1921 for(ei
= hData
->mEvStart
;ei
< hData
->mEvCount
;ei
++)
1923 // For each elevation, calculate the upper and lower limits of the
1925 ev
= -90.0 + (ei
* 2.0 * evs
);
1926 if(ei
< (hData
->mEvCount
- 1))
1927 up_ev
= (ev
+ evs
) * M_PI
/ 180.0;
1931 down_ev
= (ev
- evs
) * M_PI
/ 180.0;
1933 down_ev
= -M_PI
/ 2.0;
1934 // Calculate the area of the patch band.
1935 solidAngle
= 2.0 * M_PI
* (sin(up_ev
) - sin(down_ev
));
1936 // Each weight is the area of one patch.
1937 weights
[ei
] = solidAngle
/ hData
->mAzCount
[ei
];
1938 // Sum the total surface area covered by the HRIRs.
1941 // Normalize the weights given the total surface coverage.
1942 for(ei
= hData
->mEvStart
;ei
< hData
->mEvCount
;ei
++)
1946 /* Calculate the diffuse-field average from the given magnitude responses of
1947 * the HRIR set. Weighting can be applied to compensate for the varying
1948 * surface area covered by each HRIR. The final average can then be limited
1949 * by the specified magnitude range (in positive dB; 0.0 to skip).
1951 static void CalculateDiffuseFieldAverage(const HrirDataT
*hData
, const int weighted
, const double limit
, double *dfa
)
1953 uint ei
, ai
, count
, step
, start
, end
, m
, j
, i
;
1956 weights
= CreateArray(hData
->mEvCount
);
1959 // Use coverage weighting to calculate the average.
1960 CalculateDfWeights(hData
, weights
);
1964 // If coverage weighting is not used, the weights still need to be
1965 // averaged by the number of HRIRs.
1967 for(ei
= hData
->mEvStart
;ei
< hData
->mEvCount
;ei
++)
1968 count
+= hData
->mAzCount
[ei
];
1969 for(ei
= hData
->mEvStart
;ei
< hData
->mEvCount
;ei
++)
1970 weights
[ei
] = 1.0 / count
;
1972 ei
= hData
->mEvStart
;
1974 step
= hData
->mIrSize
;
1975 start
= hData
->mEvOffset
[ei
] * step
;
1976 end
= hData
->mIrCount
* step
;
1977 m
= 1 + (hData
->mFftSize
/ 2);
1978 for(i
= 0;i
< m
;i
++)
1980 for(j
= start
;j
< end
;j
+= step
)
1982 // Get the weight for this HRIR's contribution.
1983 double weight
= weights
[ei
];
1984 // Add this HRIR's weighted power average to the total.
1985 for(i
= 0;i
< m
;i
++)
1986 dfa
[i
] += weight
* hData
->mHrirs
[j
+i
] * hData
->mHrirs
[j
+i
];
1987 // Determine the next weight to use.
1989 if(ai
>= hData
->mAzCount
[ei
])
1995 // Finish the average calculation and keep it from being too small.
1996 for(i
= 0;i
< m
;i
++)
1997 dfa
[i
] = fmax(sqrt(dfa
[i
]), EPSILON
);
1998 // Apply a limit to the magnitude range of the diffuse-field average if
2001 LimitMagnitudeResponse(hData
->mFftSize
, limit
, dfa
, dfa
);
2002 DestroyArray(weights
);
2005 // Perform diffuse-field equalization on the magnitude responses of the HRIR
2006 // set using the given average response.
2007 static void DiffuseFieldEqualize(const double *dfa
, const HrirDataT
*hData
)
2009 uint step
, start
, end
, m
, j
, i
;
2011 step
= hData
->mIrSize
;
2012 start
= hData
->mEvOffset
[hData
->mEvStart
] * step
;
2013 end
= hData
->mIrCount
* step
;
2014 m
= 1 + (hData
->mFftSize
/ 2);
2015 for(j
= start
;j
< end
;j
+= step
)
2017 for(i
= 0;i
< m
;i
++)
2018 hData
->mHrirs
[j
+i
] /= dfa
[i
];
2022 // Perform minimum-phase reconstruction using the magnitude responses of the
2024 static void ReconstructHrirs(const HrirDataT
*hData
)
2026 uint step
, start
, end
, n
, j
, i
;
2029 step
= hData
->mIrSize
;
2030 start
= hData
->mEvOffset
[hData
->mEvStart
] * step
;
2031 end
= hData
->mIrCount
* step
;
2032 n
= hData
->mFftSize
;
2033 re
= CreateArray(n
);
2034 im
= CreateArray(n
);
2035 for(j
= start
;j
< end
;j
+= step
)
2037 MinimumPhase(n
, &hData
->mHrirs
[j
], re
, im
);
2038 FftInverse(n
, re
, im
, re
, im
);
2039 for(i
= 0;i
< hData
->mIrPoints
;i
++)
2040 hData
->mHrirs
[j
+i
] = re
[i
];
2046 // Resamples the HRIRs for use at the given sampling rate.
2047 static void ResampleHrirs(const uint rate
, HrirDataT
*hData
)
2049 uint n
, step
, start
, end
, j
;
2052 ResamplerSetup(&rs
, hData
->mIrRate
, rate
);
2053 n
= hData
->mIrPoints
;
2054 step
= hData
->mIrSize
;
2055 start
= hData
->mEvOffset
[hData
->mEvStart
] * step
;
2056 end
= hData
->mIrCount
* step
;
2057 for(j
= start
;j
< end
;j
+= step
)
2058 ResamplerRun(&rs
, n
, &hData
->mHrirs
[j
], n
, &hData
->mHrirs
[j
]);
2059 ResamplerClear(&rs
);
2060 hData
->mIrRate
= rate
;
2063 /* Given an elevation index and an azimuth, calculate the indices of the two
2064 * HRIRs that bound the coordinate along with a factor for calculating the
2065 * continous HRIR using interpolation.
2067 static void CalcAzIndices(const HrirDataT
*hData
, const uint ei
, const double az
, uint
*j0
, uint
*j1
, double *jf
)
2072 af
= ((2.0*M_PI
) + az
) * hData
->mAzCount
[ei
] / (2.0*M_PI
);
2073 ai
= ((uint
)af
) % hData
->mAzCount
[ei
];
2076 *j0
= hData
->mEvOffset
[ei
] + ai
;
2077 *j1
= hData
->mEvOffset
[ei
] + ((ai
+1) % hData
->mAzCount
[ei
]);
2081 // Synthesize any missing onset timings at the bottom elevations. This just
2082 // blends between slightly exaggerated known onsets. Not an accurate model.
2083 static void SynthesizeOnsets(HrirDataT
*hData
)
2085 uint oi
, e
, a
, j0
, j1
;
2088 oi
= hData
->mEvStart
;
2090 for(a
= 0;a
< hData
->mAzCount
[oi
];a
++)
2091 t
+= hData
->mHrtds
[hData
->mEvOffset
[oi
] + a
];
2092 hData
->mHrtds
[0] = 1.32e-4 + (t
/ hData
->mAzCount
[oi
]);
2093 for(e
= 1;e
< hData
->mEvStart
;e
++)
2095 of
= ((double)e
) / hData
->mEvStart
;
2096 for(a
= 0;a
< hData
->mAzCount
[e
];a
++)
2098 CalcAzIndices(hData
, oi
, a
* 2.0 * M_PI
/ hData
->mAzCount
[e
], &j0
, &j1
, &jf
);
2099 hData
->mHrtds
[hData
->mEvOffset
[e
] + a
] = Lerp(hData
->mHrtds
[0], Lerp(hData
->mHrtds
[j0
], hData
->mHrtds
[j1
], jf
), of
);
2104 /* Attempt to synthesize any missing HRIRs at the bottom elevations. Right
2105 * now this just blends the lowest elevation HRIRs together and applies some
2106 * attenuation and high frequency damping. It is a simple, if inaccurate
2109 static void SynthesizeHrirs (HrirDataT
*hData
)
2111 uint oi
, a
, e
, step
, n
, i
, j
;
2112 double lp
[4], s0
, s1
;
2117 if(hData
->mEvStart
<= 0)
2119 step
= hData
->mIrSize
;
2120 oi
= hData
->mEvStart
;
2121 n
= hData
->mIrPoints
;
2122 for(i
= 0;i
< n
;i
++)
2123 hData
->mHrirs
[i
] = 0.0;
2124 for(a
= 0;a
< hData
->mAzCount
[oi
];a
++)
2126 j
= (hData
->mEvOffset
[oi
] + a
) * step
;
2127 for(i
= 0;i
< n
;i
++)
2128 hData
->mHrirs
[i
] += hData
->mHrirs
[j
+i
] / hData
->mAzCount
[oi
];
2130 for(e
= 1;e
< hData
->mEvStart
;e
++)
2132 of
= ((double)e
) / hData
->mEvStart
;
2133 b
= (1.0 - of
) * (3.5e-6 * hData
->mIrRate
);
2134 for(a
= 0;a
< hData
->mAzCount
[e
];a
++)
2136 j
= (hData
->mEvOffset
[e
] + a
) * step
;
2137 CalcAzIndices(hData
, oi
, a
* 2.0 * M_PI
/ hData
->mAzCount
[e
], &j0
, &j1
, &jf
);
2144 for(i
= 0;i
< n
;i
++)
2146 s0
= hData
->mHrirs
[i
];
2147 s1
= Lerp(hData
->mHrirs
[j0
+i
], hData
->mHrirs
[j1
+i
], jf
);
2148 s0
= Lerp(s0
, s1
, of
);
2149 lp
[0] = Lerp(s0
, lp
[0], b
);
2150 lp
[1] = Lerp(lp
[0], lp
[1], b
);
2151 lp
[2] = Lerp(lp
[1], lp
[2], b
);
2152 lp
[3] = Lerp(lp
[2], lp
[3], b
);
2153 hData
->mHrirs
[j
+i
] = lp
[3];
2157 b
= 3.5e-6 * hData
->mIrRate
;
2162 for(i
= 0;i
< n
;i
++)
2164 s0
= hData
->mHrirs
[i
];
2165 lp
[0] = Lerp(s0
, lp
[0], b
);
2166 lp
[1] = Lerp(lp
[0], lp
[1], b
);
2167 lp
[2] = Lerp(lp
[1], lp
[2], b
);
2168 lp
[3] = Lerp(lp
[2], lp
[3], b
);
2169 hData
->mHrirs
[i
] = lp
[3];
2171 hData
->mEvStart
= 0;
2174 // The following routines assume a full set of HRIRs for all elevations.
2176 // Normalize the HRIR set and slightly attenuate the result.
2177 static void NormalizeHrirs (const HrirDataT
*hData
)
2179 uint step
, end
, n
, j
, i
;
2182 step
= hData
->mIrSize
;
2183 end
= hData
->mIrCount
* step
;
2184 n
= hData
->mIrPoints
;
2186 for(j
= 0;j
< end
;j
+= step
)
2188 for(i
= 0;i
< n
;i
++)
2189 maxLevel
= fmax(fabs(hData
->mHrirs
[j
+i
]), maxLevel
);
2191 maxLevel
= 1.01 * maxLevel
;
2192 for(j
= 0;j
< end
;j
+= step
)
2194 for(i
= 0;i
< n
;i
++)
2195 hData
->mHrirs
[j
+i
] /= maxLevel
;
2199 // Calculate the left-ear time delay using a spherical head model.
2200 static double CalcLTD(const double ev
, const double az
, const double rad
, const double dist
)
2202 double azp
, dlp
, l
, al
;
2204 azp
= asin(cos(ev
) * sin(az
));
2205 dlp
= sqrt((dist
*dist
) + (rad
*rad
) + (2.0*dist
*rad
*sin(azp
)));
2206 l
= sqrt((dist
*dist
) - (rad
*rad
));
2207 al
= (0.5 * M_PI
) + azp
;
2209 dlp
= l
+ (rad
* (al
- acos(rad
/ dist
)));
2210 return (dlp
/ 343.3);
2213 // Calculate the effective head-related time delays for each minimum-phase
2215 static void CalculateHrtds (const HeadModelT model
, const double radius
, HrirDataT
*hData
)
2217 double minHrtd
, maxHrtd
;
2223 for(e
= 0;e
< hData
->mEvCount
;e
++)
2225 for(a
= 0;a
< hData
->mAzCount
[e
];a
++)
2227 j
= hData
->mEvOffset
[e
] + a
;
2228 if(model
== HM_DATASET
)
2229 t
= hData
->mHrtds
[j
] * radius
/ hData
->mRadius
;
2231 t
= CalcLTD((-90.0 + (e
* 180.0 / (hData
->mEvCount
- 1))) * M_PI
/ 180.0,
2232 (a
* 360.0 / hData
->mAzCount
[e
]) * M_PI
/ 180.0,
2233 radius
, hData
->mDistance
);
2234 hData
->mHrtds
[j
] = t
;
2235 maxHrtd
= fmax(t
, maxHrtd
);
2236 minHrtd
= fmin(t
, minHrtd
);
2240 for(j
= 0;j
< hData
->mIrCount
;j
++)
2241 hData
->mHrtds
[j
] -= minHrtd
;
2242 hData
->mMaxHrtd
= maxHrtd
;
2245 // Store the OpenAL Soft HRTF data set.
2246 static int StoreMhr(const HrirDataT
*hData
, const char *filename
)
2248 uint e
, step
, end
, n
, j
, i
;
2252 if((fp
=fopen(filename
, "wb")) == NULL
)
2254 fprintf(stderr
, "Error: Could not open MHR file '%s'.\n", filename
);
2257 if(!WriteAscii(MHR_FORMAT
, fp
, filename
))
2259 if(!WriteBin4(BO_LITTLE
, 4, (uint32
)hData
->mIrRate
, fp
, filename
))
2261 if(!WriteBin4(BO_LITTLE
, 1, (uint32
)hData
->mIrPoints
, fp
, filename
))
2263 if(!WriteBin4(BO_LITTLE
, 1, (uint32
)hData
->mEvCount
, fp
, filename
))
2265 for(e
= 0;e
< hData
->mEvCount
;e
++)
2267 if(!WriteBin4(BO_LITTLE
, 1, (uint32
)hData
->mAzCount
[e
], fp
, filename
))
2270 step
= hData
->mIrSize
;
2271 end
= hData
->mIrCount
* step
;
2272 n
= hData
->mIrPoints
;
2274 for(j
= 0;j
< end
;j
+= step
)
2277 for(i
= 0;i
< n
;i
++)
2279 v
= HpTpdfDither(32767.0 * hData
->mHrirs
[j
+i
], &hpHist
);
2280 if(!WriteBin4(BO_LITTLE
, 2, (uint32
)v
, fp
, filename
))
2284 for(j
= 0;j
< hData
->mIrCount
;j
++)
2286 v
= (int)fmin(round(hData
->mIrRate
* hData
->mHrtds
[j
]), MAX_HRTD
);
2287 if(!WriteBin4(BO_LITTLE
, 1, (uint32
)v
, fp
, filename
))
2294 // Process the data set definition to read and validate the data set metrics.
2295 static int ProcessMetrics(TokenReaderT
*tr
, const uint fftSize
, const uint truncSize
, HrirDataT
*hData
)
2297 int hasRate
= 0, hasPoints
= 0, hasAzimuths
= 0;
2298 int hasRadius
= 0, hasDistance
= 0;
2299 char ident
[MAX_IDENT_LEN
+1];
2305 while(!(hasRate
&& hasPoints
&& hasAzimuths
&& hasRadius
&& hasDistance
))
2307 TrIndication(tr
, & line
, & col
);
2308 if(!TrReadIdent(tr
, MAX_IDENT_LEN
, ident
))
2310 if(strcasecmp(ident
, "rate") == 0)
2314 TrErrorAt(tr
, line
, col
, "Redefinition of 'rate'.\n");
2317 if(!TrReadOperator(tr
, "="))
2319 if(!TrReadInt(tr
, MIN_RATE
, MAX_RATE
, &intVal
))
2321 hData
->mIrRate
= (uint
)intVal
;
2324 else if(strcasecmp(ident
, "points") == 0)
2327 TrErrorAt(tr
, line
, col
, "Redefinition of 'points'.\n");
2330 if(!TrReadOperator(tr
, "="))
2332 TrIndication(tr
, &line
, &col
);
2333 if(!TrReadInt(tr
, MIN_POINTS
, MAX_POINTS
, &intVal
))
2335 points
= (uint
)intVal
;
2336 if(fftSize
> 0 && points
> fftSize
)
2338 TrErrorAt(tr
, line
, col
, "Value exceeds the overridden FFT size.\n");
2341 if(points
< truncSize
)
2343 TrErrorAt(tr
, line
, col
, "Value is below the truncation size.\n");
2346 hData
->mIrPoints
= points
;
2347 hData
->mFftSize
= fftSize
;
2351 while(points
< (4 * hData
->mIrPoints
))
2353 hData
->mFftSize
= points
;
2354 hData
->mIrSize
= 1 + (points
/ 2);
2358 hData
->mFftSize
= fftSize
;
2359 hData
->mIrSize
= 1 + (fftSize
/ 2);
2360 if(points
> hData
->mIrSize
)
2361 hData
->mIrSize
= points
;
2365 else if(strcasecmp(ident
, "azimuths") == 0)
2369 TrErrorAt(tr
, line
, col
, "Redefinition of 'azimuths'.\n");
2372 if(!TrReadOperator(tr
, "="))
2374 hData
->mIrCount
= 0;
2375 hData
->mEvCount
= 0;
2376 hData
->mEvOffset
[0] = 0;
2379 if(!TrReadInt(tr
, MIN_AZ_COUNT
, MAX_AZ_COUNT
, &intVal
))
2381 hData
->mAzCount
[hData
->mEvCount
] = (uint
)intVal
;
2382 hData
->mIrCount
+= (uint
)intVal
;
2384 if(!TrIsOperator(tr
, ","))
2386 if(hData
->mEvCount
>= MAX_EV_COUNT
)
2388 TrError(tr
, "Exceeded the maximum of %d elevations.\n", MAX_EV_COUNT
);
2391 hData
->mEvOffset
[hData
->mEvCount
] = hData
->mEvOffset
[hData
->mEvCount
- 1] + ((uint
)intVal
);
2392 TrReadOperator(tr
, ",");
2394 if(hData
->mEvCount
< MIN_EV_COUNT
)
2396 TrErrorAt(tr
, line
, col
, "Did not reach the minimum of %d azimuth counts.\n", MIN_EV_COUNT
);
2401 else if(strcasecmp(ident
, "radius") == 0)
2405 TrErrorAt(tr
, line
, col
, "Redefinition of 'radius'.\n");
2408 if(!TrReadOperator(tr
, "="))
2410 if(!TrReadFloat(tr
, MIN_RADIUS
, MAX_RADIUS
, &fpVal
))
2412 hData
->mRadius
= fpVal
;
2415 else if(strcasecmp(ident
, "distance") == 0)
2419 TrErrorAt(tr
, line
, col
, "Redefinition of 'distance'.\n");
2422 if(!TrReadOperator(tr
, "="))
2424 if(!TrReadFloat(tr
, MIN_DISTANCE
, MAX_DISTANCE
, & fpVal
))
2426 hData
->mDistance
= fpVal
;
2431 TrErrorAt(tr
, line
, col
, "Expected a metric name.\n");
2434 TrSkipWhitespace (tr
);
2439 // Parse an index pair from the data set definition.
2440 static int ReadIndexPair(TokenReaderT
*tr
, const HrirDataT
*hData
, uint
*ei
, uint
*ai
)
2443 if(!TrReadInt(tr
, 0, (int)hData
->mEvCount
, &intVal
))
2446 if(!TrReadOperator(tr
, ","))
2448 if(!TrReadInt(tr
, 0, (int)hData
->mAzCount
[*ei
], &intVal
))
2454 // Match the source format from a given identifier.
2455 static SourceFormatT
MatchSourceFormat(const char *ident
)
2457 if(strcasecmp(ident
, "wave") == 0)
2459 if(strcasecmp(ident
, "bin_le") == 0)
2461 if(strcasecmp(ident
, "bin_be") == 0)
2463 if(strcasecmp(ident
, "ascii") == 0)
2468 // Match the source element type from a given identifier.
2469 static ElementTypeT
MatchElementType(const char *ident
)
2471 if(strcasecmp(ident
, "int") == 0)
2473 if(strcasecmp(ident
, "fp") == 0)
2478 // Parse and validate a source reference from the data set definition.
2479 static int ReadSourceRef(TokenReaderT
*tr
, SourceRefT
*src
)
2481 char ident
[MAX_IDENT_LEN
+1];
2485 TrIndication(tr
, &line
, &col
);
2486 if(!TrReadIdent(tr
, MAX_IDENT_LEN
, ident
))
2488 src
->mFormat
= MatchSourceFormat(ident
);
2489 if(src
->mFormat
== SF_NONE
)
2491 TrErrorAt(tr
, line
, col
, "Expected a source format.\n");
2494 if(!TrReadOperator(tr
, "("))
2496 if(src
->mFormat
== SF_WAVE
)
2498 if(!TrReadInt(tr
, 0, MAX_WAVE_CHANNELS
, &intVal
))
2500 src
->mType
= ET_NONE
;
2503 src
->mChannel
= (uint
)intVal
;
2508 TrIndication(tr
, &line
, &col
);
2509 if(!TrReadIdent(tr
, MAX_IDENT_LEN
, ident
))
2511 src
->mType
= MatchElementType(ident
);
2512 if(src
->mType
== ET_NONE
)
2514 TrErrorAt(tr
, line
, col
, "Expected a source element type.\n");
2517 if(src
->mFormat
== SF_BIN_LE
|| src
->mFormat
== SF_BIN_BE
)
2519 if(!TrReadOperator(tr
, ","))
2521 if(src
->mType
== ET_INT
)
2523 if(!TrReadInt(tr
, MIN_BIN_SIZE
, MAX_BIN_SIZE
, &intVal
))
2525 src
->mSize
= (uint
)intVal
;
2526 if(!TrIsOperator(tr
, ","))
2527 src
->mBits
= (int)(8*src
->mSize
);
2530 TrReadOperator(tr
, ",");
2531 TrIndication(tr
, &line
, &col
);
2532 if(!TrReadInt(tr
, -2147483647-1, 2147483647, &intVal
))
2534 if(abs(intVal
) < MIN_BIN_BITS
|| ((uint
)abs(intVal
)) > (8*src
->mSize
))
2536 TrErrorAt(tr
, line
, col
, "Expected a value of (+/-) %d to %d.\n", MIN_BIN_BITS
, 8*src
->mSize
);
2539 src
->mBits
= intVal
;
2544 TrIndication(tr
, &line
, &col
);
2545 if(!TrReadInt(tr
, -2147483647-1, 2147483647, &intVal
))
2547 if(intVal
!= 4 && intVal
!= 8)
2549 TrErrorAt(tr
, line
, col
, "Expected a value of 4 or 8.\n");
2552 src
->mSize
= (uint
)intVal
;
2556 else if(src
->mFormat
== SF_ASCII
&& src
->mType
== ET_INT
)
2558 if(!TrReadOperator(tr
, ","))
2560 if(!TrReadInt(tr
, MIN_ASCII_BITS
, MAX_ASCII_BITS
, &intVal
))
2563 src
->mBits
= intVal
;
2571 if(!TrIsOperator(tr
, ";"))
2575 TrReadOperator(tr
, ";");
2576 if(!TrReadInt (tr
, 0, 0x7FFFFFFF, &intVal
))
2578 src
->mSkip
= (uint
)intVal
;
2581 if(!TrReadOperator(tr
, ")"))
2583 if(TrIsOperator(tr
, "@"))
2585 TrReadOperator(tr
, "@");
2586 if(!TrReadInt(tr
, 0, 0x7FFFFFFF, &intVal
))
2588 src
->mOffset
= (uint
)intVal
;
2592 if(!TrReadOperator(tr
, ":"))
2594 if(!TrReadString(tr
, MAX_PATH_LEN
, src
->mPath
))
2599 // Process the list of sources in the data set definition.
2600 static int ProcessSources(const HeadModelT model
, TokenReaderT
*tr
, HrirDataT
*hData
)
2602 uint
*setCount
, *setFlag
;
2603 uint line
, col
, ei
, ai
;
2608 setCount
= (uint
*)calloc(hData
->mEvCount
, sizeof(uint
));
2609 setFlag
= (uint
*)calloc(hData
->mIrCount
, sizeof(uint
));
2610 hrir
= CreateArray(hData
->mIrPoints
);
2611 while(TrIsOperator(tr
, "["))
2613 TrIndication(tr
, & line
, & col
);
2614 TrReadOperator(tr
, "[");
2615 if(!ReadIndexPair(tr
, hData
, &ei
, &ai
))
2617 if(!TrReadOperator(tr
, "]"))
2619 if(setFlag
[hData
->mEvOffset
[ei
] + ai
])
2621 TrErrorAt(tr
, line
, col
, "Redefinition of source.\n");
2624 if(!TrReadOperator(tr
, "="))
2630 if(!ReadSourceRef(tr
, &src
))
2632 if(!LoadSource(&src
, hData
->mIrRate
, hData
->mIrPoints
, hrir
))
2635 if(model
== HM_DATASET
)
2636 AverageHrirOnset(hrir
, 1.0 / factor
, ei
, ai
, hData
);
2637 AverageHrirMagnitude(hrir
, 1.0 / factor
, ei
, ai
, hData
);
2639 if(!TrIsOperator(tr
, "+"))
2641 TrReadOperator(tr
, "+");
2643 setFlag
[hData
->mEvOffset
[ei
] + ai
] = 1;
2648 while(ei
< hData
->mEvCount
&& setCount
[ei
] < 1)
2650 if(ei
< hData
->mEvCount
)
2652 hData
->mEvStart
= ei
;
2653 while(ei
< hData
->mEvCount
&& setCount
[ei
] == hData
->mAzCount
[ei
])
2655 if(ei
>= hData
->mEvCount
)
2664 TrError(tr
, "Errant data at end of source list.\n");
2667 TrError(tr
, "Missing sources for elevation index %d.\n", ei
);
2670 TrError(tr
, "Missing source references.\n");
2679 /* Parse the data set definition and process the source data, storing the
2680 * resulting data set as desired. If the input name is NULL it will read
2681 * from standard input.
2683 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
)
2685 char rateStr
[8+1], expName
[MAX_PATH_LEN
];
2692 hData
.mIrPoints
= 0;
2698 hData
.mDistance
= 0;
2699 fprintf(stdout
, "Reading HRIR definition...\n");
2702 fp
= fopen(inName
, "r");
2705 fprintf(stderr
, "Error: Could not open definition file '%s'\n", inName
);
2708 TrSetup(fp
, inName
, &tr
);
2713 TrSetup(fp
, "<stdin>", &tr
);
2715 if(!ProcessMetrics(&tr
, fftSize
, truncSize
, &hData
))
2721 hData
.mHrirs
= CreateArray(hData
.mIrCount
* hData
. mIrSize
);
2722 hData
.mHrtds
= CreateArray(hData
.mIrCount
);
2723 if(!ProcessSources(model
, &tr
, &hData
))
2725 DestroyArray(hData
.mHrtds
);
2726 DestroyArray(hData
.mHrirs
);
2735 dfa
= CreateArray(1 + (hData
.mFftSize
/2));
2736 fprintf(stdout
, "Calculating diffuse-field average...\n");
2737 CalculateDiffuseFieldAverage(&hData
, surface
, limit
, dfa
);
2738 fprintf(stdout
, "Performing diffuse-field equalization...\n");
2739 DiffuseFieldEqualize(dfa
, &hData
);
2742 fprintf(stdout
, "Performing minimum phase reconstruction...\n");
2743 ReconstructHrirs(&hData
);
2744 if(outRate
!= 0 && outRate
!= hData
.mIrRate
)
2746 fprintf(stdout
, "Resampling HRIRs...\n");
2747 ResampleHrirs(outRate
, &hData
);
2749 fprintf(stdout
, "Truncating minimum-phase HRIRs...\n");
2750 hData
.mIrPoints
= truncSize
;
2751 fprintf(stdout
, "Synthesizing missing elevations...\n");
2752 if(model
== HM_DATASET
)
2753 SynthesizeOnsets(&hData
);
2754 SynthesizeHrirs(&hData
);
2755 fprintf(stdout
, "Normalizing final HRIRs...\n");
2756 NormalizeHrirs(&hData
);
2757 fprintf(stdout
, "Calculating impulse delays...\n");
2758 CalculateHrtds(model
, (radius
> DEFAULT_CUSTOM_RADIUS
) ? radius
: hData
.mRadius
, &hData
);
2759 snprintf(rateStr
, 8, "%u", hData
.mIrRate
);
2760 StrSubst(outName
, "%r", rateStr
, MAX_PATH_LEN
, expName
);
2764 fprintf(stdout
, "Creating MHR data set file...\n");
2765 if(!StoreMhr(&hData
, expName
))
2767 DestroyArray(hData
.mHrtds
);
2768 DestroyArray(hData
.mHrirs
);
2775 DestroyArray(hData
.mHrtds
);
2776 DestroyArray(hData
.mHrirs
);
2780 static void PrintHelp(const char *argv0
, FILE *ofile
)
2782 fprintf(ofile
, "Usage: %s <command> [<option>...]\n\n", argv0
);
2783 fprintf(ofile
, "Commands:\n");
2784 fprintf(ofile
, " -m, --make-mhr Makes an OpenAL Soft compatible HRTF data set.\n");
2785 fprintf(ofile
, " Defaults output to: ./oalsoft_hrtf_%%r.mhr\n");
2786 fprintf(ofile
, " -h, --help Displays this help information.\n\n");
2787 fprintf(ofile
, "Options:\n");
2788 fprintf(ofile
, " -r=<rate> Change the data set sample rate to the specified value and\n");
2789 fprintf(ofile
, " resample the HRIRs accordingly.\n");
2790 fprintf(ofile
, " -f=<points> Override the FFT window size (defaults to the first power-\n");
2791 fprintf(ofile
, " of-two that fits four times the number of HRIR points).\n");
2792 fprintf(ofile
, " -e={on|off} Toggle diffuse-field equalization (default: %s).\n", (DEFAULT_EQUALIZE
? "on" : "off"));
2793 fprintf(ofile
, " -s={on|off} Toggle surface-weighted diffuse-field average (default: %s).\n", (DEFAULT_SURFACE
? "on" : "off"));
2794 fprintf(ofile
, " -l={<dB>|none} Specify a limit to the magnitude range of the diffuse-field\n");
2795 fprintf(ofile
, " average (default: %.2f).\n", DEFAULT_LIMIT
);
2796 fprintf(ofile
, " -w=<points> Specify the size of the truncation window that's applied\n");
2797 fprintf(ofile
, " after minimum-phase reconstruction (default: %u).\n", DEFAULT_TRUNCSIZE
);
2798 fprintf(ofile
, " -d={dataset| Specify the model used for calculating the head-delay timing\n");
2799 fprintf(ofile
, " sphere} values (default: %s).\n", ((DEFAULT_HEAD_MODEL
== HM_DATASET
) ? "dataset" : "sphere"));
2800 fprintf(ofile
, " -c=<size> Use a customized head radius measured ear-to-ear in meters.\n");
2801 fprintf(ofile
, " -i=<filename> Specify an HRIR definition file to use (defaults to stdin).\n");
2802 fprintf(ofile
, " -o=<filename> Specify an output file. Overrides command-selected default.\n");
2803 fprintf(ofile
, " Use of '%%r' will be substituted with the data set sample rate.\n");
2806 // Standard command line dispatch.
2807 int main(const int argc
, const char *argv
[])
2809 const char *inName
= NULL
, *outName
= NULL
;
2810 OutputFormatT outFormat
;
2811 uint outRate
, fftSize
;
2812 int equalize
, surface
;
2820 if(argc
< 2 || strcmp(argv
[1], "--help") == 0 || strcmp(argv
[1], "-h") == 0)
2822 fprintf(stdout
, "HRTF Processing and Composition Utility\n\n");
2823 PrintHelp(argv
[0], stdout
);
2827 if(strcmp(argv
[1], "--make-mhr") == 0 || strcmp(argv
[1], "-m") == 0)
2829 outName
= "./oalsoft_hrtf_%r.mhr";
2834 fprintf(stderr
, "Error: Invalid command '%s'.\n\n", argv
[1]);
2835 PrintHelp(argv
[0], stderr
);
2841 equalize
= DEFAULT_EQUALIZE
;
2842 surface
= DEFAULT_SURFACE
;
2843 limit
= DEFAULT_LIMIT
;
2844 truncSize
= DEFAULT_TRUNCSIZE
;
2845 model
= DEFAULT_HEAD_MODEL
;
2846 radius
= DEFAULT_CUSTOM_RADIUS
;
2851 if(strncmp(argv
[argi
], "-r=", 3) == 0)
2853 outRate
= strtoul(&argv
[argi
][3], &end
, 10);
2854 if(end
[0] != '\0' || outRate
< MIN_RATE
|| outRate
> MAX_RATE
)
2856 fprintf(stderr
, "Error: Expected a value from %u to %u for '-r'.\n", MIN_RATE
, MAX_RATE
);
2860 else if(strncmp(argv
[argi
], "-f=", 3) == 0)
2862 fftSize
= strtoul(&argv
[argi
][3], &end
, 10);
2863 if(end
[0] != '\0' || (fftSize
&(fftSize
-1)) || fftSize
< MIN_FFTSIZE
|| fftSize
> MAX_FFTSIZE
)
2865 fprintf(stderr
, "Error: Expected a power-of-two value from %u to %u for '-f'.\n", MIN_FFTSIZE
, MAX_FFTSIZE
);
2869 else if(strncmp(argv
[argi
], "-e=", 3) == 0)
2871 if(strcmp(&argv
[argi
][3], "on") == 0)
2873 else if(strcmp(&argv
[argi
][3], "off") == 0)
2877 fprintf(stderr
, "Error: Expected 'on' or 'off' for '-e'.\n");
2881 else if(strncmp(argv
[argi
], "-s=", 3) == 0)
2883 if(strcmp(&argv
[argi
][3], "on") == 0)
2885 else if(strcmp(&argv
[argi
][3], "off") == 0)
2889 fprintf(stderr
, "Error: Expected 'on' or 'off' for '-s'.\n");
2893 else if(strncmp(argv
[argi
], "-l=", 3) == 0)
2895 if(strcmp(&argv
[argi
][3], "none") == 0)
2899 limit
= strtod(&argv
[argi
] [3], &end
);
2900 if(end
[0] != '\0' || limit
< MIN_LIMIT
|| limit
> MAX_LIMIT
)
2902 fprintf(stderr
, "Error: Expected 'none' or a value from %.2f to %.2f for '-l'.\n", MIN_LIMIT
, MAX_LIMIT
);
2907 else if(strncmp(argv
[argi
], "-w=", 3) == 0)
2909 truncSize
= strtoul(&argv
[argi
][3], &end
, 10);
2910 if(end
[0] != '\0' || truncSize
< MIN_TRUNCSIZE
|| truncSize
> MAX_TRUNCSIZE
|| (truncSize
%MOD_TRUNCSIZE
))
2912 fprintf(stderr
, "Error: Expected a value from %u to %u in multiples of %u for '-w'.\n", MIN_TRUNCSIZE
, MAX_TRUNCSIZE
, MOD_TRUNCSIZE
);
2916 else if(strncmp(argv
[argi
], "-d=", 3) == 0)
2918 if(strcmp(&argv
[argi
][3], "dataset") == 0)
2920 else if(strcmp(&argv
[argi
][3], "sphere") == 0)
2924 fprintf(stderr
, "Error: Expected 'dataset' or 'sphere' for '-d'.\n");
2928 else if(strncmp(argv
[argi
], "-c=", 3) == 0)
2930 radius
= strtod(&argv
[argi
][3], &end
);
2931 if(end
[0] != '\0' || radius
< MIN_CUSTOM_RADIUS
|| radius
> MAX_CUSTOM_RADIUS
)
2933 fprintf(stderr
, "Error: Expected a value from %.2f to %.2f for '-c'.\n", MIN_CUSTOM_RADIUS
, MAX_CUSTOM_RADIUS
);
2937 else if(strncmp(argv
[argi
], "-i=", 3) == 0)
2938 inName
= &argv
[argi
][3];
2939 else if(strncmp(argv
[argi
], "-o=", 3) == 0)
2940 outName
= &argv
[argi
][3];
2943 fprintf(stderr
, "Error: Invalid option '%s'.\n", argv
[argi
]);
2948 if(!ProcessDefinition(inName
, outRate
, fftSize
, equalize
, surface
, limit
, truncSize
, model
, radius
, outFormat
, outName
))
2950 fprintf(stdout
, "Operation completed.\n");