2 * HRTF utility for producing and demonstrating the process of creating an
3 * OpenAL Soft compatible HRIR data set.
5 * Copyright (C) 2011-2017 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-9)
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 (65536)
149 #define MAX_FFTSIZE (131072)
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 (16)
157 #define MAX_TRUNCSIZE (512)
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_FFTSIZE (65536)
169 #define DEFAULT_EQUALIZE (1)
170 #define DEFAULT_SURFACE (1)
171 #define DEFAULT_LIMIT (24.0)
172 #define DEFAULT_TRUNCSIZE (32)
173 #define DEFAULT_HEAD_MODEL (HM_DATASET)
174 #define DEFAULT_CUSTOM_RADIUS (0.0)
176 // The four-character-codes for RIFF/RIFX WAVE file chunks.
177 #define FOURCC_RIFF (0x46464952) // 'RIFF'
178 #define FOURCC_RIFX (0x58464952) // 'RIFX'
179 #define FOURCC_WAVE (0x45564157) // 'WAVE'
180 #define FOURCC_FMT (0x20746D66) // 'fmt '
181 #define FOURCC_DATA (0x61746164) // 'data'
182 #define FOURCC_LIST (0x5453494C) // 'LIST'
183 #define FOURCC_WAVL (0x6C766177) // 'wavl'
184 #define FOURCC_SLNT (0x746E6C73) // 'slnt'
186 // The supported wave formats.
187 #define WAVE_FORMAT_PCM (0x0001)
188 #define WAVE_FORMAT_IEEE_FLOAT (0x0003)
189 #define WAVE_FORMAT_EXTENSIBLE (0xFFFE)
191 // The maximum propagation delay value supported by OpenAL Soft.
192 #define MAX_HRTD (63.0)
194 // The OpenAL Soft HRTF format marker. It stands for minimum-phase head
195 // response protocol 01.
196 #define MHR_FORMAT ("MinPHR01")
198 // Byte order for the serialization routines.
199 typedef enum ByteOrderT
{
205 // Source format for the references listed in the data set definition.
206 typedef enum SourceFormatT
{
208 SF_WAVE
, // RIFF/RIFX WAVE file.
209 SF_BIN_LE
, // Little-endian binary file.
210 SF_BIN_BE
, // Big-endian binary file.
211 SF_ASCII
// ASCII text file.
214 // Element types for the references listed in the data set definition.
215 typedef enum ElementTypeT
{
217 ET_INT
, // Integer elements.
218 ET_FP
// Floating-point elements.
221 // Head model used for calculating the impulse delays.
222 typedef enum HeadModelT
{
224 HM_DATASET
, // Measure the onset from the dataset.
225 HM_SPHERE
// Calculate the onset using a spherical head model.
228 // Desired output format from the command line.
229 typedef enum OutputFormatT
{
231 OF_MHR
// OpenAL Soft MHR data set file.
234 // Unsigned integer type.
235 typedef unsigned int uint
;
237 // Serialization types. The trailing digit indicates the number of bits.
238 typedef ALubyte uint8
;
240 typedef ALuint uint32
;
241 typedef ALuint64SOFT uint64
;
243 // Token reader state for parsing the data set definition.
244 typedef struct TokenReaderT
{
249 char mRing
[TR_RING_SIZE
];
254 // Source reference state used when loading sources.
255 typedef struct SourceRefT
{
256 SourceFormatT mFormat
;
263 char mPath
[MAX_PATH_LEN
+1];
266 // The HRIR metrics and data set used when loading, processing, and storing
267 // the resulting HRTF.
268 typedef struct HrirDataT
{
276 uint mAzCount
[MAX_EV_COUNT
];
277 uint mEvOffset
[MAX_EV_COUNT
];
285 // The resampler metrics and FIR filter.
286 typedef struct ResamplerT
{
292 /*****************************
293 *** Token reader routines ***
294 *****************************/
296 /* Whitespace is not significant. It can process tokens as identifiers, numbers
297 * (integer and floating-point), strings, and operators. Strings must be
298 * encapsulated by double-quotes and cannot span multiple lines.
301 // Setup the reader on the given file. The filename can be NULL if no error
302 // output is desired.
303 static void TrSetup(FILE *fp
, const char *filename
, TokenReaderT
*tr
)
305 const char *name
= NULL
;
309 const char *slash
= strrchr(filename
, '/');
312 const char *bslash
= strrchr(slash
+1, '\\');
313 if(bslash
) name
= bslash
+1;
318 const char *bslash
= strrchr(filename
, '\\');
319 if(bslash
) name
= bslash
+1;
320 else name
= filename
;
332 // Prime the reader's ring buffer, and return a result indicating that there
333 // is text to process.
334 static int TrLoad(TokenReaderT
*tr
)
336 size_t toLoad
, in
, count
;
338 toLoad
= TR_RING_SIZE
- (tr
->mIn
- tr
->mOut
);
339 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
;
347 tr
->mIn
+= fread(&tr
->mRing
[in
], 1, count
, tr
->mFile
);
348 tr
->mIn
+= fread(&tr
->mRing
[0], 1, toLoad
-count
, tr
->mFile
);
351 tr
->mIn
+= fread(&tr
->mRing
[in
], 1, toLoad
, tr
->mFile
);
353 if(tr
->mOut
>= TR_RING_SIZE
)
355 tr
->mOut
-= TR_RING_SIZE
;
356 tr
->mIn
-= TR_RING_SIZE
;
359 if(tr
->mIn
> tr
->mOut
)
364 // Error display routine. Only displays when the base name is not NULL.
365 static void TrErrorVA(const TokenReaderT
*tr
, uint line
, uint column
, const char *format
, va_list argPtr
)
369 fprintf(stderr
, "Error (%s:%u:%u): ", tr
->mName
, line
, column
);
370 vfprintf(stderr
, format
, argPtr
);
373 // Used to display an error at a saved line/column.
374 static void TrErrorAt(const TokenReaderT
*tr
, uint line
, uint column
, const char *format
, ...)
378 va_start(argPtr
, format
);
379 TrErrorVA(tr
, line
, column
, format
, argPtr
);
383 // Used to display an error at the current line/column.
384 static void TrError(const TokenReaderT
*tr
, const char *format
, ...)
388 va_start(argPtr
, format
);
389 TrErrorVA(tr
, tr
->mLine
, tr
->mColumn
, format
, argPtr
);
393 // Skips to the next line.
394 static void TrSkipLine(TokenReaderT
*tr
)
400 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
412 // Skips to the next token.
413 static int TrSkipWhitespace(TokenReaderT
*tr
)
419 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
439 // Get the line and/or column of the next token (or the end of input).
440 static void TrIndication(TokenReaderT
*tr
, uint
*line
, uint
*column
)
442 TrSkipWhitespace(tr
);
443 if(line
) *line
= tr
->mLine
;
444 if(column
) *column
= tr
->mColumn
;
447 // Checks to see if a token is the given operator. It does not display any
448 // errors and will not proceed to the next token.
449 static int TrIsOperator(TokenReaderT
*tr
, const char *op
)
454 if(!TrSkipWhitespace(tr
))
458 while(op
[len
] != '\0' && out
< tr
->mIn
)
460 ch
= tr
->mRing
[out
&TR_RING_MASK
];
461 if(ch
!= op
[len
]) break;
470 /* The TrRead*() routines obtain the value of a matching token type. They
471 * display type, form, and boundary errors and will proceed to the next
475 // Reads and validates an identifier token.
476 static int TrReadIdent(TokenReaderT
*tr
, const uint maxLen
, char *ident
)
482 if(TrSkipWhitespace(tr
))
485 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
486 if(ch
== '_' || isalpha(ch
))
496 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
497 } while(ch
== '_' || isdigit(ch
) || isalpha(ch
));
505 TrErrorAt(tr
, tr
->mLine
, col
, "Identifier is too long.\n");
509 TrErrorAt(tr
, tr
->mLine
, col
, "Expected an identifier.\n");
513 // Reads and validates (including bounds) an integer token.
514 static int TrReadInt(TokenReaderT
*tr
, const int loBound
, const int hiBound
, int *value
)
516 uint col
, digis
, len
;
520 if(TrSkipWhitespace(tr
))
524 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
525 if(ch
== '+' || ch
== '-')
534 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
535 if(!isdigit(ch
)) break;
543 if(digis
> 0 && ch
!= '.' && !isalpha(ch
))
547 TrErrorAt(tr
, tr
->mLine
, col
, "Integer is too long.");
551 *value
= strtol(temp
, NULL
, 10);
552 if(*value
< loBound
|| *value
> hiBound
)
554 TrErrorAt(tr
, tr
->mLine
, col
, "Expected a value from %d to %d.\n", loBound
, hiBound
);
560 TrErrorAt(tr
, tr
->mLine
, col
, "Expected an integer.\n");
564 // Reads and validates (including bounds) a float token.
565 static int TrReadFloat(TokenReaderT
*tr
, const double loBound
, const double hiBound
, double *value
)
567 uint col
, digis
, len
;
571 if(TrSkipWhitespace(tr
))
575 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
576 if(ch
== '+' || ch
== '-')
586 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
587 if(!isdigit(ch
)) break;
603 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
604 if(!isdigit(ch
)) break;
613 if(ch
== 'E' || ch
== 'e')
620 if(ch
== '+' || ch
== '-')
629 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
630 if(!isdigit(ch
)) break;
639 if(digis
> 0 && ch
!= '.' && !isalpha(ch
))
643 TrErrorAt(tr
, tr
->mLine
, col
, "Float is too long.");
647 *value
= strtod(temp
, NULL
);
648 if(*value
< loBound
|| *value
> hiBound
)
650 TrErrorAt (tr
, tr
->mLine
, col
, "Expected a value from %f to %f.\n", loBound
, hiBound
);
659 TrErrorAt(tr
, tr
->mLine
, col
, "Expected a float.\n");
663 // Reads and validates a string token.
664 static int TrReadString(TokenReaderT
*tr
, const uint maxLen
, char *text
)
670 if(TrSkipWhitespace(tr
))
673 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
680 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
686 TrErrorAt (tr
, tr
->mLine
, col
, "Unterminated string at end of line.\n");
695 tr
->mColumn
+= 1 + len
;
696 TrErrorAt(tr
, tr
->mLine
, col
, "Unterminated string at end of input.\n");
699 tr
->mColumn
+= 2 + len
;
702 TrErrorAt (tr
, tr
->mLine
, col
, "String is too long.\n");
709 TrErrorAt(tr
, tr
->mLine
, col
, "Expected a string.\n");
713 // Reads and validates the given operator.
714 static int TrReadOperator(TokenReaderT
*tr
, const char *op
)
720 if(TrSkipWhitespace(tr
))
724 while(op
[len
] != '\0' && TrLoad(tr
))
726 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
727 if(ch
!= op
[len
]) break;
735 TrErrorAt(tr
, tr
->mLine
, col
, "Expected '%s' operator.\n", op
);
739 /* Performs a string substitution. Any case-insensitive occurrences of the
740 * pattern string are replaced with the replacement string. The result is
741 * truncated if necessary.
743 static int StrSubst(const char *in
, const char *pat
, const char *rep
, const size_t maxLen
, char *out
)
745 size_t inLen
, patLen
, repLen
;
750 patLen
= strlen(pat
);
751 repLen
= strlen(rep
);
755 while(si
< inLen
&& di
< maxLen
)
757 if(patLen
<= inLen
-si
)
759 if(strncasecmp(&in
[si
], pat
, patLen
) == 0)
761 if(repLen
> maxLen
-di
)
763 repLen
= maxLen
- di
;
766 strncpy(&out
[di
], rep
, repLen
);
782 /*********************
783 *** Math routines ***
784 *********************/
786 // Provide missing math routines for MSVC versions < 1800 (Visual Studio 2013).
787 #if defined(_MSC_VER) && _MSC_VER < 1800
788 static double round(double val
)
791 return ceil(val
-0.5);
792 return floor(val
+0.5);
795 static double fmin(double a
, double b
)
797 return (a
<b
) ? a
: b
;
800 static double fmax(double a
, double b
)
802 return (a
>b
) ? a
: b
;
806 // Simple clamp routine.
807 static double Clamp(const double val
, const double lower
, const double upper
)
809 return fmin(fmax(val
, lower
), upper
);
812 // Performs linear interpolation.
813 static double Lerp(const double a
, const double b
, const double f
)
815 return a
+ (f
* (b
- a
));
818 // Performs a high-passed triangular probability density function dither from
819 // a double to an integer. It assumes the input sample is already scaled.
820 static int HpTpdfDither(const double in
, int *hpHist
)
822 static const double PRNG_SCALE
= 1.0 / (RAND_MAX
+1.0);
827 out
= round(in
+ (PRNG_SCALE
* (prn
- *hpHist
)));
832 // Allocates an array of doubles.
833 static double *CreateArray(size_t n
)
838 a
= calloc(n
, sizeof(double));
841 fprintf(stderr
, "Error: Out of memory.\n");
847 // Frees an array of doubles.
848 static void DestroyArray(double *a
)
851 // Complex number routines. All outputs must be non-NULL.
853 // Magnitude/absolute value.
854 static double ComplexAbs(const double r
, const double i
)
856 return sqrt(r
*r
+ i
*i
);
860 static void ComplexMul(const double aR
, const double aI
, const double bR
, const double bI
, double *outR
, double *outI
)
862 *outR
= (aR
* bR
) - (aI
* bI
);
863 *outI
= (aI
* bR
) + (aR
* bI
);
867 static void ComplexExp(const double inR
, const double inI
, double *outR
, double *outI
)
870 *outR
= e
* cos(inI
);
871 *outI
= e
* sin(inI
);
874 /* Fast Fourier transform routines. The number of points must be a power of
875 * two. In-place operation is possible only if both the real and imaginary
876 * parts are in-place together.
879 // Performs bit-reversal ordering.
880 static void FftArrange(const uint n
, const double *inR
, const double *inI
, double *outR
, double *outI
)
885 if(inR
== outR
&& inI
== outI
)
887 // Handle in-place arrangement.
908 // Handle copy arrangement.
922 // Performs the summation.
923 static void FftSummation(const uint n
, const double s
, double *re
, double *im
)
927 double vR
, vI
, wR
, wI
;
932 for(m
= 1, m2
= 2;m
< n
; m
<<= 1, m2
<<= 1)
934 // v = Complex (-2.0 * sin (0.5 * pi / m) * sin (0.5 * pi / m), -sin (pi / m))
935 vR
= sin(0.5 * pi
/ m
);
938 // w = Complex (1.0, 0.0)
943 for(k
= i
;k
< n
;k
+= m2
)
946 // t = ComplexMul(w, out[km2])
947 tR
= (wR
* re
[mk
]) - (wI
* im
[mk
]);
948 tI
= (wR
* im
[mk
]) + (wI
* re
[mk
]);
949 // out[mk] = ComplexSub (out [k], t)
952 // out[k] = ComplexAdd (out [k], t)
956 // t = ComplexMul (v, w)
957 tR
= (vR
* wR
) - (vI
* wI
);
958 tI
= (vR
* wI
) + (vI
* wR
);
959 // w = ComplexAdd (w, t)
966 // Performs a forward FFT.
967 static void FftForward(const uint n
, const double *inR
, const double *inI
, double *outR
, double *outI
)
969 FftArrange(n
, inR
, inI
, outR
, outI
);
970 FftSummation(n
, 1.0, outR
, outI
);
973 // Performs an inverse FFT.
974 static void FftInverse(const uint n
, const double *inR
, const double *inI
, double *outR
, double *outI
)
979 FftArrange(n
, inR
, inI
, outR
, outI
);
980 FftSummation(n
, -1.0, outR
, outI
);
989 /* Calculate the complex helical sequence (or discrete-time analytical signal)
990 * of the given input using the Hilbert transform. Given the natural logarithm
991 * of a signal's magnitude response, the imaginary components can be used as
992 * the angles for minimum-phase reconstruction.
994 static void Hilbert(const uint n
, const double *in
, double *outR
, double *outI
)
1000 // Handle in-place operation.
1001 for(i
= 0;i
< n
;i
++)
1006 // Handle copy operation.
1007 for(i
= 0;i
< n
;i
++)
1013 FftInverse(n
, outR
, outI
, outR
, outI
);
1014 for(i
= 1;i
< (n
+1)/2;i
++)
1019 /* Increment i if n is even. */
1026 FftForward(n
, outR
, outI
, outR
, outI
);
1029 /* Calculate the magnitude response of the given input. This is used in
1030 * place of phase decomposition, since the phase residuals are discarded for
1031 * minimum phase reconstruction. The mirrored half of the response is also
1034 static void MagnitudeResponse(const uint n
, const double *inR
, const double *inI
, double *out
)
1036 const uint m
= 1 + (n
/ 2);
1038 for(i
= 0;i
< m
;i
++)
1039 out
[i
] = fmax(ComplexAbs(inR
[i
], inI
[i
]), EPSILON
);
1042 /* Apply a range limit (in dB) to the given magnitude response. This is used
1043 * to adjust the effects of the diffuse-field average on the equalization
1046 static void LimitMagnitudeResponse(const uint n
, const double limit
, const double *in
, double *out
)
1048 const uint m
= 1 + (n
/ 2);
1050 uint i
, lower
, upper
;
1053 halfLim
= limit
/ 2.0;
1054 // Convert the response to dB.
1055 for(i
= 0;i
< m
;i
++)
1056 out
[i
] = 20.0 * log10(in
[i
]);
1057 // Use six octaves to calculate the average magnitude of the signal.
1058 lower
= ((uint
)ceil(n
/ pow(2.0, 8.0))) - 1;
1059 upper
= ((uint
)floor(n
/ pow(2.0, 2.0))) - 1;
1061 for(i
= lower
;i
<= upper
;i
++)
1063 ave
/= upper
- lower
+ 1;
1064 // Keep the response within range of the average magnitude.
1065 for(i
= 0;i
< m
;i
++)
1066 out
[i
] = Clamp(out
[i
], ave
- halfLim
, ave
+ halfLim
);
1067 // Convert the response back to linear magnitude.
1068 for(i
= 0;i
< m
;i
++)
1069 out
[i
] = pow(10.0, out
[i
] / 20.0);
1072 /* Reconstructs the minimum-phase component for the given magnitude response
1073 * of a signal. This is equivalent to phase recomposition, sans the missing
1074 * residuals (which were discarded). The mirrored half of the response is
1077 static void MinimumPhase(const uint n
, const double *in
, double *outR
, double *outI
)
1079 const uint m
= 1 + (n
/ 2);
1084 mags
= CreateArray(n
);
1085 for(i
= 0;i
< m
;i
++)
1087 mags
[i
] = fmax(EPSILON
, in
[i
]);
1088 outR
[i
] = log(mags
[i
]);
1092 mags
[i
] = mags
[n
- i
];
1093 outR
[i
] = outR
[n
- i
];
1095 Hilbert(n
, outR
, outR
, outI
);
1096 // Remove any DC offset the filter has.
1098 for(i
= 0;i
< n
;i
++)
1100 ComplexExp(0.0, outI
[i
], &aR
, &aI
);
1101 ComplexMul(mags
[i
], 0.0, aR
, aI
, &outR
[i
], &outI
[i
]);
1107 /***************************
1108 *** Resampler functions ***
1109 ***************************/
1111 /* This is the normalized cardinal sine (sinc) function.
1113 * sinc(x) = { 1, x = 0
1114 * { sin(pi x) / (pi x), otherwise.
1116 static double Sinc(const double x
)
1118 if(fabs(x
) < EPSILON
)
1120 return sin(M_PI
* x
) / (M_PI
* x
);
1123 /* The zero-order modified Bessel function of the first kind, used for the
1126 * I_0(x) = sum_{k=0}^inf (1 / k!)^2 (x / 2)^(2 k)
1127 * = sum_{k=0}^inf ((x / 2)^k / k!)^2
1129 static double BesselI_0(const double x
)
1131 double term
, sum
, x2
, y
, last_sum
;
1134 // Start at k=1 since k=0 is trivial.
1140 // Let the integration converge until the term of the sum is no longer
1148 } while(sum
!= last_sum
);
1152 /* Calculate a Kaiser window from the given beta value and a normalized k
1155 * w(k) = { I_0(B sqrt(1 - k^2)) / I_0(B), -1 <= k <= 1
1158 * Where k can be calculated as:
1160 * k = i / l, where -l <= i <= l.
1164 * k = 2 i / M - 1, where 0 <= i <= M.
1166 static double Kaiser(const double b
, const double k
)
1168 if(!(k
>= -1.0 && k
<= 1.0))
1170 return BesselI_0(b
* sqrt(1.0 - k
*k
)) / BesselI_0(b
);
1173 // Calculates the greatest common divisor of a and b.
1174 static uint
Gcd(uint x
, uint y
)
1185 /* Calculates the size (order) of the Kaiser window. Rejection is in dB and
1186 * the transition width is normalized frequency (0.5 is nyquist).
1188 * M = { ceil((r - 7.95) / (2.285 2 pi f_t)), r > 21
1189 * { ceil(5.79 / 2 pi f_t), r <= 21.
1192 static uint
CalcKaiserOrder(const double rejection
, const double transition
)
1194 double w_t
= 2.0 * M_PI
* transition
;
1195 if(rejection
> 21.0)
1196 return (uint
)ceil((rejection
- 7.95) / (2.285 * w_t
));
1197 return (uint
)ceil(5.79 / w_t
);
1200 // Calculates the beta value of the Kaiser window. Rejection is in dB.
1201 static double CalcKaiserBeta(const double rejection
)
1203 if(rejection
> 50.0)
1204 return 0.1102 * (rejection
- 8.7);
1205 if(rejection
>= 21.0)
1206 return (0.5842 * pow(rejection
- 21.0, 0.4)) +
1207 (0.07886 * (rejection
- 21.0));
1211 /* Calculates a point on the Kaiser-windowed sinc filter for the given half-
1212 * width, beta, gain, and cutoff. The point is specified in non-normalized
1213 * samples, from 0 to M, where M = (2 l + 1).
1215 * w(k) 2 p f_t sinc(2 f_t x)
1217 * x -- centered sample index (i - l)
1218 * k -- normalized and centered window index (x / l)
1219 * w(k) -- window function (Kaiser)
1220 * p -- gain compensation factor when sampling
1221 * f_t -- normalized center frequency (or cutoff; 0.5 is nyquist)
1223 static double SincFilter(const int l
, const double b
, const double gain
, const double cutoff
, const int i
)
1225 return Kaiser(b
, (double)(i
- l
) / l
) * 2.0 * gain
* cutoff
* Sinc(2.0 * cutoff
* (i
- l
));
1228 /* This is a polyphase sinc-filtered resampler.
1230 * Upsample Downsample
1232 * p/q = 3/2 p/q = 3/5
1234 * M-+-+-+-> M-+-+-+->
1235 * -------------------+ ---------------------+
1236 * p s * f f f f|f| | p s * f f f f f |
1237 * | 0 * 0 0 0|0|0 | | 0 * 0 0 0 0|0| |
1238 * v 0 * 0 0|0|0 0 | v 0 * 0 0 0|0|0 |
1239 * s * f|f|f f f | s * f f|f|f f |
1240 * 0 * |0|0 0 0 0 | 0 * 0|0|0 0 0 |
1241 * --------+=+--------+ 0 * |0|0 0 0 0 |
1242 * d . d .|d|. d . d ----------+=+--------+
1243 * d . . . .|d|. . . .
1247 * P_f(i,j) = q i mod p + pj
1248 * P_s(i,j) = floor(q i / p) - j
1249 * d[i=0..N-1] = sum_{j=0}^{floor((M - 1) / p)} {
1250 * { f[P_f(i,j)] s[P_s(i,j)], P_f(i,j) < M
1251 * { 0, P_f(i,j) >= M. }
1254 // Calculate the resampling metrics and build the Kaiser-windowed sinc filter
1255 // that's used to cut frequencies above the destination nyquist.
1256 static void ResamplerSetup(ResamplerT
*rs
, const uint srcRate
, const uint dstRate
)
1258 double cutoff
, width
, beta
;
1262 gcd
= Gcd(srcRate
, dstRate
);
1263 rs
->mP
= dstRate
/ gcd
;
1264 rs
->mQ
= srcRate
/ gcd
;
1265 /* The cutoff is adjusted by half the transition width, so the transition
1266 * ends before the nyquist (0.5). Both are scaled by the downsampling
1271 cutoff
= 0.475 / rs
->mP
;
1272 width
= 0.05 / rs
->mP
;
1276 cutoff
= 0.475 / rs
->mQ
;
1277 width
= 0.05 / rs
->mQ
;
1279 // A rejection of -180 dB is used for the stop band.
1280 l
= CalcKaiserOrder(180.0, width
) / 2;
1281 beta
= CalcKaiserBeta(180.0);
1282 rs
->mM
= (2 * l
) + 1;
1284 rs
->mF
= CreateArray(rs
->mM
);
1285 for(i
= 0;i
< ((int)rs
->mM
);i
++)
1286 rs
->mF
[i
] = SincFilter((int)l
, beta
, rs
->mP
, cutoff
, i
);
1289 // Clean up after the resampler.
1290 static void ResamplerClear(ResamplerT
*rs
)
1292 DestroyArray(rs
->mF
);
1296 // Perform the upsample-filter-downsample resampling operation using a
1297 // polyphase filter implementation.
1298 static void ResamplerRun(ResamplerT
*rs
, const uint inN
, const double *in
, const uint outN
, double *out
)
1300 const uint p
= rs
->mP
, q
= rs
->mQ
, m
= rs
->mM
, l
= rs
->mL
;
1301 const double *f
= rs
->mF
;
1309 // Handle in-place operation.
1311 work
= CreateArray(outN
);
1314 // Resample the input.
1315 for(i
= 0;i
< outN
;i
++)
1318 // Input starts at l to compensate for the filter delay. This will
1319 // drop any build-up from the first half of the filter.
1320 j_f
= (l
+ (q
* i
)) % p
;
1321 j_s
= (l
+ (q
* i
)) / p
;
1324 // Only take input when 0 <= j_s < inN. This single unsigned
1325 // comparison catches both cases.
1327 r
+= f
[j_f
] * in
[j_s
];
1333 // Clean up after in-place operation.
1336 for(i
= 0;i
< outN
;i
++)
1342 /*************************
1343 *** File source input ***
1344 *************************/
1346 // Read a binary value of the specified byte order and byte size from a file,
1347 // storing it as a 32-bit unsigned integer.
1348 static int ReadBin4(FILE *fp
, const char *filename
, const ByteOrderT order
, const uint bytes
, uint32
*out
)
1354 if(fread(in
, 1, bytes
, fp
) != bytes
)
1356 fprintf(stderr
, "Error: Bad read from file '%s'.\n", filename
);
1363 for(i
= 0;i
< bytes
;i
++)
1364 accum
= (accum
<<8) | in
[bytes
- i
- 1];
1367 for(i
= 0;i
< bytes
;i
++)
1368 accum
= (accum
<<8) | in
[i
];
1377 // Read a binary value of the specified byte order from a file, storing it as
1378 // a 64-bit unsigned integer.
1379 static int ReadBin8(FILE *fp
, const char *filename
, const ByteOrderT order
, uint64
*out
)
1385 if(fread(in
, 1, 8, fp
) != 8)
1387 fprintf(stderr
, "Error: Bad read from file '%s'.\n", filename
);
1394 for(i
= 0;i
< 8;i
++)
1395 accum
= (accum
<<8) | in
[8 - i
- 1];
1398 for(i
= 0;i
< 8;i
++)
1399 accum
= (accum
<<8) | in
[i
];
1408 /* Read a binary value of the specified type, byte order, and byte size from
1409 * a file, converting it to a double. For integer types, the significant
1410 * bits are used to normalize the result. The sign of bits determines
1411 * whether they are padded toward the MSB (negative) or LSB (positive).
1412 * Floating-point types are not normalized.
1414 static int ReadBinAsDouble(FILE *fp
, const char *filename
, const ByteOrderT order
, const ElementTypeT type
, const uint bytes
, const int bits
, double *out
)
1429 if(!ReadBin8(fp
, filename
, order
, &v8
.ui
))
1436 if(!ReadBin4(fp
, filename
, order
, bytes
, &v4
.ui
))
1443 v4
.ui
>>= (8*bytes
) - ((uint
)bits
);
1445 v4
.ui
&= (0xFFFFFFFF >> (32+bits
));
1447 if(v4
.ui
&(uint
)(1<<(abs(bits
)-1)))
1448 v4
.ui
|= (0xFFFFFFFF << abs (bits
));
1449 *out
= v4
.i
/ (double)(1<<(abs(bits
)-1));
1455 /* Read an ascii value of the specified type from a file, converting it to a
1456 * double. For integer types, the significant bits are used to normalize the
1457 * result. The sign of the bits should always be positive. This also skips
1458 * up to one separator character before the element itself.
1460 static int ReadAsciiAsDouble(TokenReaderT
*tr
, const char *filename
, const ElementTypeT type
, const uint bits
, double *out
)
1462 if(TrIsOperator(tr
, ","))
1463 TrReadOperator(tr
, ",");
1464 else if(TrIsOperator(tr
, ":"))
1465 TrReadOperator(tr
, ":");
1466 else if(TrIsOperator(tr
, ";"))
1467 TrReadOperator(tr
, ";");
1468 else if(TrIsOperator(tr
, "|"))
1469 TrReadOperator(tr
, "|");
1473 if(!TrReadFloat(tr
, -HUGE_VAL
, HUGE_VAL
, out
))
1475 fprintf(stderr
, "Error: Bad read from file '%s'.\n", filename
);
1482 if(!TrReadInt(tr
, -(1<<(bits
-1)), (1<<(bits
-1))-1, &v
))
1484 fprintf(stderr
, "Error: Bad read from file '%s'.\n", filename
);
1487 *out
= v
/ (double)((1<<(bits
-1))-1);
1492 // Read the RIFF/RIFX WAVE format chunk from a file, validating it against
1493 // the source parameters and data set metrics.
1494 static int ReadWaveFormat(FILE *fp
, const ByteOrderT order
, const uint hrirRate
, SourceRefT
*src
)
1496 uint32 fourCC
, chunkSize
;
1497 uint32 format
, channels
, rate
, dummy
, block
, size
, bits
;
1502 fseek (fp
, (long) chunkSize
, SEEK_CUR
);
1503 if(!ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, &fourCC
) ||
1504 !ReadBin4(fp
, src
->mPath
, order
, 4, &chunkSize
))
1506 } while(fourCC
!= FOURCC_FMT
);
1507 if(!ReadBin4(fp
, src
->mPath
, order
, 2, & format
) ||
1508 !ReadBin4(fp
, src
->mPath
, order
, 2, & channels
) ||
1509 !ReadBin4(fp
, src
->mPath
, order
, 4, & rate
) ||
1510 !ReadBin4(fp
, src
->mPath
, order
, 4, & dummy
) ||
1511 !ReadBin4(fp
, src
->mPath
, order
, 2, & block
))
1516 if(!ReadBin4(fp
, src
->mPath
, order
, 2, &size
))
1524 if(format
== WAVE_FORMAT_EXTENSIBLE
)
1526 fseek(fp
, 2, SEEK_CUR
);
1527 if(!ReadBin4(fp
, src
->mPath
, order
, 2, &bits
))
1531 fseek(fp
, 4, SEEK_CUR
);
1532 if(!ReadBin4(fp
, src
->mPath
, order
, 2, &format
))
1534 fseek(fp
, (long)(chunkSize
- 26), SEEK_CUR
);
1540 fseek(fp
, (long)(chunkSize
- 16), SEEK_CUR
);
1542 fseek(fp
, (long)(chunkSize
- 14), SEEK_CUR
);
1544 if(format
!= WAVE_FORMAT_PCM
&& format
!= WAVE_FORMAT_IEEE_FLOAT
)
1546 fprintf(stderr
, "Error: Unsupported WAVE format in file '%s'.\n", src
->mPath
);
1549 if(src
->mChannel
>= channels
)
1551 fprintf(stderr
, "Error: Missing source channel in WAVE file '%s'.\n", src
->mPath
);
1554 if(rate
!= hrirRate
)
1556 fprintf(stderr
, "Error: Mismatched source sample rate in WAVE file '%s'.\n", src
->mPath
);
1559 if(format
== WAVE_FORMAT_PCM
)
1561 if(size
< 2 || size
> 4)
1563 fprintf(stderr
, "Error: Unsupported sample size in WAVE file '%s'.\n", src
->mPath
);
1566 if(bits
< 16 || bits
> (8*size
))
1568 fprintf (stderr
, "Error: Bad significant bits in WAVE file '%s'.\n", src
->mPath
);
1571 src
->mType
= ET_INT
;
1575 if(size
!= 4 && size
!= 8)
1577 fprintf(stderr
, "Error: Unsupported sample size in WAVE file '%s'.\n", src
->mPath
);
1583 src
->mBits
= (int)bits
;
1584 src
->mSkip
= channels
;
1588 // Read a RIFF/RIFX WAVE data chunk, converting all elements to doubles.
1589 static int ReadWaveData(FILE *fp
, const SourceRefT
*src
, const ByteOrderT order
, const uint n
, double *hrir
)
1591 int pre
, post
, skip
;
1594 pre
= (int)(src
->mSize
* src
->mChannel
);
1595 post
= (int)(src
->mSize
* (src
->mSkip
- src
->mChannel
- 1));
1597 for(i
= 0;i
< n
;i
++)
1601 fseek(fp
, skip
, SEEK_CUR
);
1602 if(!ReadBinAsDouble(fp
, src
->mPath
, order
, src
->mType
, src
->mSize
, src
->mBits
, &hrir
[i
]))
1607 fseek(fp
, skip
, SEEK_CUR
);
1611 // Read the RIFF/RIFX WAVE list or data chunk, converting all elements to
1613 static int ReadWaveList(FILE *fp
, const SourceRefT
*src
, const ByteOrderT order
, const uint n
, double *hrir
)
1615 uint32 fourCC
, chunkSize
, listSize
, count
;
1616 uint block
, skip
, offset
, i
;
1620 if(!ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, & fourCC
) ||
1621 !ReadBin4(fp
, src
->mPath
, order
, 4, & chunkSize
))
1624 if(fourCC
== FOURCC_DATA
)
1626 block
= src
->mSize
* src
->mSkip
;
1627 count
= chunkSize
/ block
;
1628 if(count
< (src
->mOffset
+ n
))
1630 fprintf(stderr
, "Error: Bad read from file '%s'.\n", src
->mPath
);
1633 fseek(fp
, (long)(src
->mOffset
* block
), SEEK_CUR
);
1634 if(!ReadWaveData(fp
, src
, order
, n
, &hrir
[0]))
1638 else if(fourCC
== FOURCC_LIST
)
1640 if(!ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, &fourCC
))
1643 if(fourCC
== FOURCC_WAVL
)
1647 fseek(fp
, (long)chunkSize
, SEEK_CUR
);
1649 listSize
= chunkSize
;
1650 block
= src
->mSize
* src
->mSkip
;
1651 skip
= src
->mOffset
;
1654 while(offset
< n
&& listSize
> 8)
1656 if(!ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, &fourCC
) ||
1657 !ReadBin4(fp
, src
->mPath
, order
, 4, &chunkSize
))
1659 listSize
-= 8 + chunkSize
;
1660 if(fourCC
== FOURCC_DATA
)
1662 count
= chunkSize
/ block
;
1665 fseek(fp
, (long)(skip
* block
), SEEK_CUR
);
1666 chunkSize
-= skip
* block
;
1669 if(count
> (n
- offset
))
1671 if(!ReadWaveData(fp
, src
, order
, count
, &hrir
[offset
]))
1673 chunkSize
-= count
* block
;
1675 lastSample
= hrir
[offset
- 1];
1683 else if(fourCC
== FOURCC_SLNT
)
1685 if(!ReadBin4(fp
, src
->mPath
, order
, 4, &count
))
1692 if(count
> (n
- offset
))
1694 for(i
= 0; i
< count
; i
++)
1695 hrir
[offset
+ i
] = lastSample
;
1705 fseek(fp
, (long)chunkSize
, SEEK_CUR
);
1709 fprintf(stderr
, "Error: Bad read from file '%s'.\n", src
->mPath
);
1715 // Load a source HRIR from a RIFF/RIFX WAVE file.
1716 static int LoadWaveSource(FILE *fp
, SourceRefT
*src
, const uint hrirRate
, const uint n
, double *hrir
)
1718 uint32 fourCC
, dummy
;
1721 if(!ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, &fourCC
) ||
1722 !ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, &dummy
))
1724 if(fourCC
== FOURCC_RIFF
)
1726 else if(fourCC
== FOURCC_RIFX
)
1730 fprintf(stderr
, "Error: No RIFF/RIFX chunk in file '%s'.\n", src
->mPath
);
1734 if(!ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, &fourCC
))
1736 if(fourCC
!= FOURCC_WAVE
)
1738 fprintf(stderr
, "Error: Not a RIFF/RIFX WAVE file '%s'.\n", src
->mPath
);
1741 if(!ReadWaveFormat(fp
, order
, hrirRate
, src
))
1743 if(!ReadWaveList(fp
, src
, order
, n
, hrir
))
1748 // Load a source HRIR from a binary file.
1749 static int LoadBinarySource(FILE *fp
, const SourceRefT
*src
, const ByteOrderT order
, const uint n
, double *hrir
)
1753 fseek(fp
, (long)src
->mOffset
, SEEK_SET
);
1754 for(i
= 0;i
< n
;i
++)
1756 if(!ReadBinAsDouble(fp
, src
->mPath
, order
, src
->mType
, src
->mSize
, src
->mBits
, &hrir
[i
]))
1759 fseek(fp
, (long)src
->mSkip
, SEEK_CUR
);
1764 // Load a source HRIR from an ASCII text file containing a list of elements
1765 // separated by whitespace or common list operators (',', ';', ':', '|').
1766 static int LoadAsciiSource(FILE *fp
, const SourceRefT
*src
, const uint n
, double *hrir
)
1772 TrSetup(fp
, NULL
, &tr
);
1773 for(i
= 0;i
< src
->mOffset
;i
++)
1775 if(!ReadAsciiAsDouble(&tr
, src
->mPath
, src
->mType
, (uint
)src
->mBits
, &dummy
))
1778 for(i
= 0;i
< n
;i
++)
1780 if(!ReadAsciiAsDouble(&tr
, src
->mPath
, src
->mType
, (uint
)src
->mBits
, &hrir
[i
]))
1782 for(j
= 0;j
< src
->mSkip
;j
++)
1784 if(!ReadAsciiAsDouble(&tr
, src
->mPath
, src
->mType
, (uint
)src
->mBits
, &dummy
))
1791 // Load a source HRIR from a supported file type.
1792 static int LoadSource(SourceRefT
*src
, const uint hrirRate
, const uint n
, double *hrir
)
1797 if (src
->mFormat
== SF_ASCII
)
1798 fp
= fopen(src
->mPath
, "r");
1800 fp
= fopen(src
->mPath
, "rb");
1803 fprintf(stderr
, "Error: Could not open source file '%s'.\n", src
->mPath
);
1806 if(src
->mFormat
== SF_WAVE
)
1807 result
= LoadWaveSource(fp
, src
, hrirRate
, n
, hrir
);
1808 else if(src
->mFormat
== SF_BIN_LE
)
1809 result
= LoadBinarySource(fp
, src
, BO_LITTLE
, n
, hrir
);
1810 else if(src
->mFormat
== SF_BIN_BE
)
1811 result
= LoadBinarySource(fp
, src
, BO_BIG
, n
, hrir
);
1813 result
= LoadAsciiSource(fp
, src
, n
, hrir
);
1819 /***************************
1820 *** File storage output ***
1821 ***************************/
1823 // Write an ASCII string to a file.
1824 static int WriteAscii(const char *out
, FILE *fp
, const char *filename
)
1829 if(fwrite(out
, 1, len
, fp
) != len
)
1832 fprintf(stderr
, "Error: Bad write to file '%s'.\n", filename
);
1838 // Write a binary value of the given byte order and byte size to a file,
1839 // loading it from a 32-bit unsigned integer.
1840 static int WriteBin4(const ByteOrderT order
, const uint bytes
, const uint32 in
, FILE *fp
, const char *filename
)
1848 for(i
= 0;i
< bytes
;i
++)
1849 out
[i
] = (in
>>(i
*8)) & 0x000000FF;
1852 for(i
= 0;i
< bytes
;i
++)
1853 out
[bytes
- i
- 1] = (in
>>(i
*8)) & 0x000000FF;
1858 if(fwrite(out
, 1, bytes
, fp
) != bytes
)
1860 fprintf(stderr
, "Error: Bad write to file '%s'.\n", filename
);
1866 // Store the OpenAL Soft HRTF data set.
1867 static int StoreMhr(const HrirDataT
*hData
, const char *filename
)
1869 uint e
, step
, end
, n
, j
, i
;
1873 if((fp
=fopen(filename
, "wb")) == NULL
)
1875 fprintf(stderr
, "Error: Could not open MHR file '%s'.\n", filename
);
1878 if(!WriteAscii(MHR_FORMAT
, fp
, filename
))
1880 if(!WriteBin4(BO_LITTLE
, 4, (uint32
)hData
->mIrRate
, fp
, filename
))
1882 if(!WriteBin4(BO_LITTLE
, 1, (uint32
)hData
->mIrPoints
, fp
, filename
))
1884 if(!WriteBin4(BO_LITTLE
, 1, (uint32
)hData
->mEvCount
, fp
, filename
))
1886 for(e
= 0;e
< hData
->mEvCount
;e
++)
1888 if(!WriteBin4(BO_LITTLE
, 1, (uint32
)hData
->mAzCount
[e
], fp
, filename
))
1891 step
= hData
->mIrSize
;
1892 end
= hData
->mIrCount
* step
;
1893 n
= hData
->mIrPoints
;
1895 for(j
= 0;j
< end
;j
+= step
)
1898 for(i
= 0;i
< n
;i
++)
1900 v
= HpTpdfDither(32767.0 * hData
->mHrirs
[j
+i
], &hpHist
);
1901 if(!WriteBin4(BO_LITTLE
, 2, (uint32
)v
, fp
, filename
))
1905 for(j
= 0;j
< hData
->mIrCount
;j
++)
1907 v
= (int)fmin(round(hData
->mIrRate
* hData
->mHrtds
[j
]), MAX_HRTD
);
1908 if(!WriteBin4(BO_LITTLE
, 1, (uint32
)v
, fp
, filename
))
1916 /***********************
1917 *** HRTF processing ***
1918 ***********************/
1920 // Calculate the onset time of an HRIR and average it with any existing
1921 // timing for its elevation and azimuth.
1922 static void AverageHrirOnset(const double *hrir
, const double f
, const uint ei
, const uint ai
, const HrirDataT
*hData
)
1928 n
= hData
->mIrPoints
;
1929 for(i
= 0;i
< n
;i
++)
1930 mag
= fmax(fabs(hrir
[i
]), mag
);
1932 for(i
= 0;i
< n
;i
++)
1934 if(fabs(hrir
[i
]) >= mag
)
1937 j
= hData
->mEvOffset
[ei
] + ai
;
1938 hData
->mHrtds
[j
] = Lerp(hData
->mHrtds
[j
], ((double)i
) / hData
->mIrRate
, f
);
1941 // Calculate the magnitude response of an HRIR and average it with any
1942 // existing responses for its elevation and azimuth.
1943 static void AverageHrirMagnitude(const double *hrir
, const double f
, const uint ei
, const uint ai
, const HrirDataT
*hData
)
1948 n
= hData
->mFftSize
;
1949 re
= CreateArray(n
);
1950 im
= CreateArray(n
);
1951 for(i
= 0;i
< hData
->mIrPoints
;i
++)
1961 FftForward(n
, re
, im
, re
, im
);
1962 MagnitudeResponse(n
, re
, im
, re
);
1964 j
= (hData
->mEvOffset
[ei
] + ai
) * hData
->mIrSize
;
1965 for(i
= 0;i
< m
;i
++)
1966 hData
->mHrirs
[j
+i
] = Lerp(hData
->mHrirs
[j
+i
], re
[i
], f
);
1971 /* Calculate the contribution of each HRIR to the diffuse-field average based
1972 * on the area of its surface patch. All patches are centered at the HRIR
1973 * coordinates on the unit sphere and are measured by solid angle.
1975 static void CalculateDfWeights(const HrirDataT
*hData
, double *weights
)
1977 double evs
, sum
, ev
, up_ev
, down_ev
, solidAngle
;
1980 evs
= 90.0 / (hData
->mEvCount
- 1);
1982 for(ei
= hData
->mEvStart
;ei
< hData
->mEvCount
;ei
++)
1984 // For each elevation, calculate the upper and lower limits of the
1986 ev
= -90.0 + (ei
* 2.0 * evs
);
1987 if(ei
< (hData
->mEvCount
- 1))
1988 up_ev
= (ev
+ evs
) * M_PI
/ 180.0;
1992 down_ev
= (ev
- evs
) * M_PI
/ 180.0;
1994 down_ev
= -M_PI
/ 2.0;
1995 // Calculate the area of the patch band.
1996 solidAngle
= 2.0 * M_PI
* (sin(up_ev
) - sin(down_ev
));
1997 // Each weight is the area of one patch.
1998 weights
[ei
] = solidAngle
/ hData
->mAzCount
[ei
];
1999 // Sum the total surface area covered by the HRIRs.
2002 // Normalize the weights given the total surface coverage.
2003 for(ei
= hData
->mEvStart
;ei
< hData
->mEvCount
;ei
++)
2007 /* Calculate the diffuse-field average from the given magnitude responses of
2008 * the HRIR set. Weighting can be applied to compensate for the varying
2009 * surface area covered by each HRIR. The final average can then be limited
2010 * by the specified magnitude range (in positive dB; 0.0 to skip).
2012 static void CalculateDiffuseFieldAverage(const HrirDataT
*hData
, const int weighted
, const double limit
, double *dfa
)
2014 uint ei
, ai
, count
, step
, start
, end
, m
, j
, i
;
2017 weights
= CreateArray(hData
->mEvCount
);
2020 // Use coverage weighting to calculate the average.
2021 CalculateDfWeights(hData
, weights
);
2025 // If coverage weighting is not used, the weights still need to be
2026 // averaged by the number of HRIRs.
2028 for(ei
= hData
->mEvStart
;ei
< hData
->mEvCount
;ei
++)
2029 count
+= hData
->mAzCount
[ei
];
2030 for(ei
= hData
->mEvStart
;ei
< hData
->mEvCount
;ei
++)
2031 weights
[ei
] = 1.0 / count
;
2033 ei
= hData
->mEvStart
;
2035 step
= hData
->mIrSize
;
2036 start
= hData
->mEvOffset
[ei
] * step
;
2037 end
= hData
->mIrCount
* step
;
2038 m
= 1 + (hData
->mFftSize
/ 2);
2039 for(i
= 0;i
< m
;i
++)
2041 for(j
= start
;j
< end
;j
+= step
)
2043 // Get the weight for this HRIR's contribution.
2044 double weight
= weights
[ei
];
2045 // Add this HRIR's weighted power average to the total.
2046 for(i
= 0;i
< m
;i
++)
2047 dfa
[i
] += weight
* hData
->mHrirs
[j
+i
] * hData
->mHrirs
[j
+i
];
2048 // Determine the next weight to use.
2050 if(ai
>= hData
->mAzCount
[ei
])
2056 // Finish the average calculation and keep it from being too small.
2057 for(i
= 0;i
< m
;i
++)
2058 dfa
[i
] = fmax(sqrt(dfa
[i
]), EPSILON
);
2059 // Apply a limit to the magnitude range of the diffuse-field average if
2062 LimitMagnitudeResponse(hData
->mFftSize
, limit
, dfa
, dfa
);
2063 DestroyArray(weights
);
2066 // Perform diffuse-field equalization on the magnitude responses of the HRIR
2067 // set using the given average response.
2068 static void DiffuseFieldEqualize(const double *dfa
, const HrirDataT
*hData
)
2070 uint step
, start
, end
, m
, j
, i
;
2072 step
= hData
->mIrSize
;
2073 start
= hData
->mEvOffset
[hData
->mEvStart
] * step
;
2074 end
= hData
->mIrCount
* step
;
2075 m
= 1 + (hData
->mFftSize
/ 2);
2076 for(j
= start
;j
< end
;j
+= step
)
2078 for(i
= 0;i
< m
;i
++)
2079 hData
->mHrirs
[j
+i
] /= dfa
[i
];
2083 // Perform minimum-phase reconstruction using the magnitude responses of the
2085 static void ReconstructHrirs(const HrirDataT
*hData
)
2087 uint step
, start
, end
, n
, j
, i
;
2090 step
= hData
->mIrSize
;
2091 start
= hData
->mEvOffset
[hData
->mEvStart
] * step
;
2092 end
= hData
->mIrCount
* step
;
2093 n
= hData
->mFftSize
;
2094 re
= CreateArray(n
);
2095 im
= CreateArray(n
);
2096 for(j
= start
;j
< end
;j
+= step
)
2098 MinimumPhase(n
, &hData
->mHrirs
[j
], re
, im
);
2099 FftInverse(n
, re
, im
, re
, im
);
2100 for(i
= 0;i
< hData
->mIrPoints
;i
++)
2101 hData
->mHrirs
[j
+i
] = re
[i
];
2107 // Resamples the HRIRs for use at the given sampling rate.
2108 static void ResampleHrirs(const uint rate
, HrirDataT
*hData
)
2110 uint n
, step
, start
, end
, j
;
2113 ResamplerSetup(&rs
, hData
->mIrRate
, rate
);
2114 n
= hData
->mIrPoints
;
2115 step
= hData
->mIrSize
;
2116 start
= hData
->mEvOffset
[hData
->mEvStart
] * step
;
2117 end
= hData
->mIrCount
* step
;
2118 for(j
= start
;j
< end
;j
+= step
)
2119 ResamplerRun(&rs
, n
, &hData
->mHrirs
[j
], n
, &hData
->mHrirs
[j
]);
2120 ResamplerClear(&rs
);
2121 hData
->mIrRate
= rate
;
2124 /* Given an elevation index and an azimuth, calculate the indices of the two
2125 * HRIRs that bound the coordinate along with a factor for calculating the
2126 * continous HRIR using interpolation.
2128 static void CalcAzIndices(const HrirDataT
*hData
, const uint ei
, const double az
, uint
*j0
, uint
*j1
, double *jf
)
2133 af
= ((2.0*M_PI
) + az
) * hData
->mAzCount
[ei
] / (2.0*M_PI
);
2134 ai
= ((uint
)af
) % hData
->mAzCount
[ei
];
2137 *j0
= hData
->mEvOffset
[ei
] + ai
;
2138 *j1
= hData
->mEvOffset
[ei
] + ((ai
+1) % hData
->mAzCount
[ei
]);
2142 // Synthesize any missing onset timings at the bottom elevations. This just
2143 // blends between slightly exaggerated known onsets. Not an accurate model.
2144 static void SynthesizeOnsets(HrirDataT
*hData
)
2146 uint oi
, e
, a
, j0
, j1
;
2149 oi
= hData
->mEvStart
;
2151 for(a
= 0;a
< hData
->mAzCount
[oi
];a
++)
2152 t
+= hData
->mHrtds
[hData
->mEvOffset
[oi
] + a
];
2153 hData
->mHrtds
[0] = 1.32e-4 + (t
/ hData
->mAzCount
[oi
]);
2154 for(e
= 1;e
< hData
->mEvStart
;e
++)
2156 of
= ((double)e
) / hData
->mEvStart
;
2157 for(a
= 0;a
< hData
->mAzCount
[e
];a
++)
2159 CalcAzIndices(hData
, oi
, a
* 2.0 * M_PI
/ hData
->mAzCount
[e
], &j0
, &j1
, &jf
);
2160 hData
->mHrtds
[hData
->mEvOffset
[e
] + a
] = Lerp(hData
->mHrtds
[0], Lerp(hData
->mHrtds
[j0
], hData
->mHrtds
[j1
], jf
), of
);
2165 /* Attempt to synthesize any missing HRIRs at the bottom elevations. Right
2166 * now this just blends the lowest elevation HRIRs together and applies some
2167 * attenuation and high frequency damping. It is a simple, if inaccurate
2170 static void SynthesizeHrirs (HrirDataT
*hData
)
2172 uint oi
, a
, e
, step
, n
, i
, j
;
2173 double lp
[4], s0
, s1
;
2178 if(hData
->mEvStart
<= 0)
2180 step
= hData
->mIrSize
;
2181 oi
= hData
->mEvStart
;
2182 n
= hData
->mIrPoints
;
2183 for(i
= 0;i
< n
;i
++)
2184 hData
->mHrirs
[i
] = 0.0;
2185 for(a
= 0;a
< hData
->mAzCount
[oi
];a
++)
2187 j
= (hData
->mEvOffset
[oi
] + a
) * step
;
2188 for(i
= 0;i
< n
;i
++)
2189 hData
->mHrirs
[i
] += hData
->mHrirs
[j
+i
] / hData
->mAzCount
[oi
];
2191 for(e
= 1;e
< hData
->mEvStart
;e
++)
2193 of
= ((double)e
) / hData
->mEvStart
;
2194 b
= (1.0 - of
) * (3.5e-6 * hData
->mIrRate
);
2195 for(a
= 0;a
< hData
->mAzCount
[e
];a
++)
2197 j
= (hData
->mEvOffset
[e
] + a
) * step
;
2198 CalcAzIndices(hData
, oi
, a
* 2.0 * M_PI
/ hData
->mAzCount
[e
], &j0
, &j1
, &jf
);
2205 for(i
= 0;i
< n
;i
++)
2207 s0
= hData
->mHrirs
[i
];
2208 s1
= Lerp(hData
->mHrirs
[j0
+i
], hData
->mHrirs
[j1
+i
], jf
);
2209 s0
= Lerp(s0
, s1
, of
);
2210 lp
[0] = Lerp(s0
, lp
[0], b
);
2211 lp
[1] = Lerp(lp
[0], lp
[1], b
);
2212 lp
[2] = Lerp(lp
[1], lp
[2], b
);
2213 lp
[3] = Lerp(lp
[2], lp
[3], b
);
2214 hData
->mHrirs
[j
+i
] = lp
[3];
2218 b
= 3.5e-6 * hData
->mIrRate
;
2223 for(i
= 0;i
< n
;i
++)
2225 s0
= hData
->mHrirs
[i
];
2226 lp
[0] = Lerp(s0
, lp
[0], b
);
2227 lp
[1] = Lerp(lp
[0], lp
[1], b
);
2228 lp
[2] = Lerp(lp
[1], lp
[2], b
);
2229 lp
[3] = Lerp(lp
[2], lp
[3], b
);
2230 hData
->mHrirs
[i
] = lp
[3];
2232 hData
->mEvStart
= 0;
2235 // The following routines assume a full set of HRIRs for all elevations.
2237 // Normalize the HRIR set and slightly attenuate the result.
2238 static void NormalizeHrirs (const HrirDataT
*hData
)
2240 uint step
, end
, n
, j
, i
;
2243 step
= hData
->mIrSize
;
2244 end
= hData
->mIrCount
* step
;
2245 n
= hData
->mIrPoints
;
2247 for(j
= 0;j
< end
;j
+= step
)
2249 for(i
= 0;i
< n
;i
++)
2250 maxLevel
= fmax(fabs(hData
->mHrirs
[j
+i
]), maxLevel
);
2252 maxLevel
= 1.01 * maxLevel
;
2253 for(j
= 0;j
< end
;j
+= step
)
2255 for(i
= 0;i
< n
;i
++)
2256 hData
->mHrirs
[j
+i
] /= maxLevel
;
2260 // Calculate the left-ear time delay using a spherical head model.
2261 static double CalcLTD(const double ev
, const double az
, const double rad
, const double dist
)
2263 double azp
, dlp
, l
, al
;
2265 azp
= asin(cos(ev
) * sin(az
));
2266 dlp
= sqrt((dist
*dist
) + (rad
*rad
) + (2.0*dist
*rad
*sin(azp
)));
2267 l
= sqrt((dist
*dist
) - (rad
*rad
));
2268 al
= (0.5 * M_PI
) + azp
;
2270 dlp
= l
+ (rad
* (al
- acos(rad
/ dist
)));
2271 return (dlp
/ 343.3);
2274 // Calculate the effective head-related time delays for each minimum-phase
2276 static void CalculateHrtds (const HeadModelT model
, const double radius
, HrirDataT
*hData
)
2278 double minHrtd
, maxHrtd
;
2284 for(e
= 0;e
< hData
->mEvCount
;e
++)
2286 for(a
= 0;a
< hData
->mAzCount
[e
];a
++)
2288 j
= hData
->mEvOffset
[e
] + a
;
2289 if(model
== HM_DATASET
)
2290 t
= hData
->mHrtds
[j
] * radius
/ hData
->mRadius
;
2292 t
= CalcLTD((-90.0 + (e
* 180.0 / (hData
->mEvCount
- 1))) * M_PI
/ 180.0,
2293 (a
* 360.0 / hData
->mAzCount
[e
]) * M_PI
/ 180.0,
2294 radius
, hData
->mDistance
);
2295 hData
->mHrtds
[j
] = t
;
2296 maxHrtd
= fmax(t
, maxHrtd
);
2297 minHrtd
= fmin(t
, minHrtd
);
2301 for(j
= 0;j
< hData
->mIrCount
;j
++)
2302 hData
->mHrtds
[j
] -= minHrtd
;
2303 hData
->mMaxHrtd
= maxHrtd
;
2307 // Process the data set definition to read and validate the data set metrics.
2308 static int ProcessMetrics(TokenReaderT
*tr
, const uint fftSize
, const uint truncSize
, HrirDataT
*hData
)
2310 int hasRate
= 0, hasPoints
= 0, hasAzimuths
= 0;
2311 int hasRadius
= 0, hasDistance
= 0;
2312 char ident
[MAX_IDENT_LEN
+1];
2318 while(!(hasRate
&& hasPoints
&& hasAzimuths
&& hasRadius
&& hasDistance
))
2320 TrIndication(tr
, & line
, & col
);
2321 if(!TrReadIdent(tr
, MAX_IDENT_LEN
, ident
))
2323 if(strcasecmp(ident
, "rate") == 0)
2327 TrErrorAt(tr
, line
, col
, "Redefinition of 'rate'.\n");
2330 if(!TrReadOperator(tr
, "="))
2332 if(!TrReadInt(tr
, MIN_RATE
, MAX_RATE
, &intVal
))
2334 hData
->mIrRate
= (uint
)intVal
;
2337 else if(strcasecmp(ident
, "points") == 0)
2340 TrErrorAt(tr
, line
, col
, "Redefinition of 'points'.\n");
2343 if(!TrReadOperator(tr
, "="))
2345 TrIndication(tr
, &line
, &col
);
2346 if(!TrReadInt(tr
, MIN_POINTS
, MAX_POINTS
, &intVal
))
2348 points
= (uint
)intVal
;
2349 if(fftSize
> 0 && points
> fftSize
)
2351 TrErrorAt(tr
, line
, col
, "Value exceeds the overridden FFT size.\n");
2354 if(points
< truncSize
)
2356 TrErrorAt(tr
, line
, col
, "Value is below the truncation size.\n");
2359 hData
->mIrPoints
= points
;
2362 hData
->mFftSize
= DEFAULT_FFTSIZE
;
2363 hData
->mIrSize
= 1 + (DEFAULT_FFTSIZE
/ 2);
2367 hData
->mFftSize
= fftSize
;
2368 hData
->mIrSize
= 1 + (fftSize
/ 2);
2369 if(points
> hData
->mIrSize
)
2370 hData
->mIrSize
= points
;
2374 else if(strcasecmp(ident
, "azimuths") == 0)
2378 TrErrorAt(tr
, line
, col
, "Redefinition of 'azimuths'.\n");
2381 if(!TrReadOperator(tr
, "="))
2383 hData
->mIrCount
= 0;
2384 hData
->mEvCount
= 0;
2385 hData
->mEvOffset
[0] = 0;
2388 if(!TrReadInt(tr
, MIN_AZ_COUNT
, MAX_AZ_COUNT
, &intVal
))
2390 hData
->mAzCount
[hData
->mEvCount
] = (uint
)intVal
;
2391 hData
->mIrCount
+= (uint
)intVal
;
2393 if(!TrIsOperator(tr
, ","))
2395 if(hData
->mEvCount
>= MAX_EV_COUNT
)
2397 TrError(tr
, "Exceeded the maximum of %d elevations.\n", MAX_EV_COUNT
);
2400 hData
->mEvOffset
[hData
->mEvCount
] = hData
->mEvOffset
[hData
->mEvCount
- 1] + ((uint
)intVal
);
2401 TrReadOperator(tr
, ",");
2403 if(hData
->mEvCount
< MIN_EV_COUNT
)
2405 TrErrorAt(tr
, line
, col
, "Did not reach the minimum of %d azimuth counts.\n", MIN_EV_COUNT
);
2410 else if(strcasecmp(ident
, "radius") == 0)
2414 TrErrorAt(tr
, line
, col
, "Redefinition of 'radius'.\n");
2417 if(!TrReadOperator(tr
, "="))
2419 if(!TrReadFloat(tr
, MIN_RADIUS
, MAX_RADIUS
, &fpVal
))
2421 hData
->mRadius
= fpVal
;
2424 else if(strcasecmp(ident
, "distance") == 0)
2428 TrErrorAt(tr
, line
, col
, "Redefinition of 'distance'.\n");
2431 if(!TrReadOperator(tr
, "="))
2433 if(!TrReadFloat(tr
, MIN_DISTANCE
, MAX_DISTANCE
, & fpVal
))
2435 hData
->mDistance
= fpVal
;
2440 TrErrorAt(tr
, line
, col
, "Expected a metric name.\n");
2443 TrSkipWhitespace (tr
);
2448 // Parse an index pair from the data set definition.
2449 static int ReadIndexPair(TokenReaderT
*tr
, const HrirDataT
*hData
, uint
*ei
, uint
*ai
)
2452 if(!TrReadInt(tr
, 0, (int)hData
->mEvCount
, &intVal
))
2455 if(!TrReadOperator(tr
, ","))
2457 if(!TrReadInt(tr
, 0, (int)hData
->mAzCount
[*ei
], &intVal
))
2463 // Match the source format from a given identifier.
2464 static SourceFormatT
MatchSourceFormat(const char *ident
)
2466 if(strcasecmp(ident
, "wave") == 0)
2468 if(strcasecmp(ident
, "bin_le") == 0)
2470 if(strcasecmp(ident
, "bin_be") == 0)
2472 if(strcasecmp(ident
, "ascii") == 0)
2477 // Match the source element type from a given identifier.
2478 static ElementTypeT
MatchElementType(const char *ident
)
2480 if(strcasecmp(ident
, "int") == 0)
2482 if(strcasecmp(ident
, "fp") == 0)
2487 // Parse and validate a source reference from the data set definition.
2488 static int ReadSourceRef(TokenReaderT
*tr
, SourceRefT
*src
)
2490 char ident
[MAX_IDENT_LEN
+1];
2494 TrIndication(tr
, &line
, &col
);
2495 if(!TrReadIdent(tr
, MAX_IDENT_LEN
, ident
))
2497 src
->mFormat
= MatchSourceFormat(ident
);
2498 if(src
->mFormat
== SF_NONE
)
2500 TrErrorAt(tr
, line
, col
, "Expected a source format.\n");
2503 if(!TrReadOperator(tr
, "("))
2505 if(src
->mFormat
== SF_WAVE
)
2507 if(!TrReadInt(tr
, 0, MAX_WAVE_CHANNELS
, &intVal
))
2509 src
->mType
= ET_NONE
;
2512 src
->mChannel
= (uint
)intVal
;
2517 TrIndication(tr
, &line
, &col
);
2518 if(!TrReadIdent(tr
, MAX_IDENT_LEN
, ident
))
2520 src
->mType
= MatchElementType(ident
);
2521 if(src
->mType
== ET_NONE
)
2523 TrErrorAt(tr
, line
, col
, "Expected a source element type.\n");
2526 if(src
->mFormat
== SF_BIN_LE
|| src
->mFormat
== SF_BIN_BE
)
2528 if(!TrReadOperator(tr
, ","))
2530 if(src
->mType
== ET_INT
)
2532 if(!TrReadInt(tr
, MIN_BIN_SIZE
, MAX_BIN_SIZE
, &intVal
))
2534 src
->mSize
= (uint
)intVal
;
2535 if(!TrIsOperator(tr
, ","))
2536 src
->mBits
= (int)(8*src
->mSize
);
2539 TrReadOperator(tr
, ",");
2540 TrIndication(tr
, &line
, &col
);
2541 if(!TrReadInt(tr
, -2147483647-1, 2147483647, &intVal
))
2543 if(abs(intVal
) < MIN_BIN_BITS
|| ((uint
)abs(intVal
)) > (8*src
->mSize
))
2545 TrErrorAt(tr
, line
, col
, "Expected a value of (+/-) %d to %d.\n", MIN_BIN_BITS
, 8*src
->mSize
);
2548 src
->mBits
= intVal
;
2553 TrIndication(tr
, &line
, &col
);
2554 if(!TrReadInt(tr
, -2147483647-1, 2147483647, &intVal
))
2556 if(intVal
!= 4 && intVal
!= 8)
2558 TrErrorAt(tr
, line
, col
, "Expected a value of 4 or 8.\n");
2561 src
->mSize
= (uint
)intVal
;
2565 else if(src
->mFormat
== SF_ASCII
&& src
->mType
== ET_INT
)
2567 if(!TrReadOperator(tr
, ","))
2569 if(!TrReadInt(tr
, MIN_ASCII_BITS
, MAX_ASCII_BITS
, &intVal
))
2572 src
->mBits
= intVal
;
2580 if(!TrIsOperator(tr
, ";"))
2584 TrReadOperator(tr
, ";");
2585 if(!TrReadInt (tr
, 0, 0x7FFFFFFF, &intVal
))
2587 src
->mSkip
= (uint
)intVal
;
2590 if(!TrReadOperator(tr
, ")"))
2592 if(TrIsOperator(tr
, "@"))
2594 TrReadOperator(tr
, "@");
2595 if(!TrReadInt(tr
, 0, 0x7FFFFFFF, &intVal
))
2597 src
->mOffset
= (uint
)intVal
;
2601 if(!TrReadOperator(tr
, ":"))
2603 if(!TrReadString(tr
, MAX_PATH_LEN
, src
->mPath
))
2608 // Process the list of sources in the data set definition.
2609 static int ProcessSources(const HeadModelT model
, TokenReaderT
*tr
, HrirDataT
*hData
)
2611 uint
*setCount
, *setFlag
;
2612 uint line
, col
, ei
, ai
;
2617 setCount
= (uint
*)calloc(hData
->mEvCount
, sizeof(uint
));
2618 setFlag
= (uint
*)calloc(hData
->mIrCount
, sizeof(uint
));
2619 hrir
= CreateArray(hData
->mIrPoints
);
2620 while(TrIsOperator(tr
, "["))
2622 TrIndication(tr
, & line
, & col
);
2623 TrReadOperator(tr
, "[");
2624 if(!ReadIndexPair(tr
, hData
, &ei
, &ai
))
2626 if(!TrReadOperator(tr
, "]"))
2628 if(setFlag
[hData
->mEvOffset
[ei
] + ai
])
2630 TrErrorAt(tr
, line
, col
, "Redefinition of source.\n");
2633 if(!TrReadOperator(tr
, "="))
2639 if(!ReadSourceRef(tr
, &src
))
2641 if(!LoadSource(&src
, hData
->mIrRate
, hData
->mIrPoints
, hrir
))
2644 if(model
== HM_DATASET
)
2645 AverageHrirOnset(hrir
, 1.0 / factor
, ei
, ai
, hData
);
2646 AverageHrirMagnitude(hrir
, 1.0 / factor
, ei
, ai
, hData
);
2648 if(!TrIsOperator(tr
, "+"))
2650 TrReadOperator(tr
, "+");
2652 setFlag
[hData
->mEvOffset
[ei
] + ai
] = 1;
2657 while(ei
< hData
->mEvCount
&& setCount
[ei
] < 1)
2659 if(ei
< hData
->mEvCount
)
2661 hData
->mEvStart
= ei
;
2662 while(ei
< hData
->mEvCount
&& setCount
[ei
] == hData
->mAzCount
[ei
])
2664 if(ei
>= hData
->mEvCount
)
2673 TrError(tr
, "Errant data at end of source list.\n");
2676 TrError(tr
, "Missing sources for elevation index %d.\n", ei
);
2679 TrError(tr
, "Missing source references.\n");
2688 /* Parse the data set definition and process the source data, storing the
2689 * resulting data set as desired. If the input name is NULL it will read
2690 * from standard input.
2692 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
)
2694 char rateStr
[8+1], expName
[MAX_PATH_LEN
];
2701 hData
.mIrPoints
= 0;
2707 hData
.mDistance
= 0;
2708 fprintf(stdout
, "Reading HRIR definition...\n");
2711 fp
= fopen(inName
, "r");
2714 fprintf(stderr
, "Error: Could not open definition file '%s'\n", inName
);
2717 TrSetup(fp
, inName
, &tr
);
2722 TrSetup(fp
, "<stdin>", &tr
);
2724 if(!ProcessMetrics(&tr
, fftSize
, truncSize
, &hData
))
2730 hData
.mHrirs
= CreateArray(hData
.mIrCount
* hData
.mIrSize
);
2731 hData
.mHrtds
= CreateArray(hData
.mIrCount
);
2732 if(!ProcessSources(model
, &tr
, &hData
))
2734 DestroyArray(hData
.mHrtds
);
2735 DestroyArray(hData
.mHrirs
);
2744 dfa
= CreateArray(1 + (hData
.mFftSize
/2));
2745 fprintf(stdout
, "Calculating diffuse-field average...\n");
2746 CalculateDiffuseFieldAverage(&hData
, surface
, limit
, dfa
);
2747 fprintf(stdout
, "Performing diffuse-field equalization...\n");
2748 DiffuseFieldEqualize(dfa
, &hData
);
2751 fprintf(stdout
, "Performing minimum phase reconstruction...\n");
2752 ReconstructHrirs(&hData
);
2753 if(outRate
!= 0 && outRate
!= hData
.mIrRate
)
2755 fprintf(stdout
, "Resampling HRIRs...\n");
2756 ResampleHrirs(outRate
, &hData
);
2758 fprintf(stdout
, "Truncating minimum-phase HRIRs...\n");
2759 hData
.mIrPoints
= truncSize
;
2760 fprintf(stdout
, "Synthesizing missing elevations...\n");
2761 if(model
== HM_DATASET
)
2762 SynthesizeOnsets(&hData
);
2763 SynthesizeHrirs(&hData
);
2764 fprintf(stdout
, "Normalizing final HRIRs...\n");
2765 NormalizeHrirs(&hData
);
2766 fprintf(stdout
, "Calculating impulse delays...\n");
2767 CalculateHrtds(model
, (radius
> DEFAULT_CUSTOM_RADIUS
) ? radius
: hData
.mRadius
, &hData
);
2768 snprintf(rateStr
, 8, "%u", hData
.mIrRate
);
2769 StrSubst(outName
, "%r", rateStr
, MAX_PATH_LEN
, expName
);
2773 fprintf(stdout
, "Creating MHR data set file...\n");
2774 if(!StoreMhr(&hData
, expName
))
2776 DestroyArray(hData
.mHrtds
);
2777 DestroyArray(hData
.mHrirs
);
2784 DestroyArray(hData
.mHrtds
);
2785 DestroyArray(hData
.mHrirs
);
2789 static void PrintHelp(const char *argv0
, FILE *ofile
)
2791 fprintf(ofile
, "Usage: %s <command> [<option>...]\n\n", argv0
);
2792 fprintf(ofile
, "Commands:\n");
2793 fprintf(ofile
, " -m, --make-mhr Makes an OpenAL Soft compatible HRTF data set.\n");
2794 fprintf(ofile
, " Defaults output to: ./oalsoft_hrtf_%%r.mhr\n");
2795 fprintf(ofile
, " -h, --help Displays this help information.\n\n");
2796 fprintf(ofile
, "Options:\n");
2797 fprintf(ofile
, " -r=<rate> Change the data set sample rate to the specified value and\n");
2798 fprintf(ofile
, " resample the HRIRs accordingly.\n");
2799 fprintf(ofile
, " -f=<points> Override the FFT window size (default: %u).\n", DEFAULT_FFTSIZE
);
2800 fprintf(ofile
, " -e={on|off} Toggle diffuse-field equalization (default: %s).\n", (DEFAULT_EQUALIZE
? "on" : "off"));
2801 fprintf(ofile
, " -s={on|off} Toggle surface-weighted diffuse-field average (default: %s).\n", (DEFAULT_SURFACE
? "on" : "off"));
2802 fprintf(ofile
, " -l={<dB>|none} Specify a limit to the magnitude range of the diffuse-field\n");
2803 fprintf(ofile
, " average (default: %.2f).\n", DEFAULT_LIMIT
);
2804 fprintf(ofile
, " -w=<points> Specify the size of the truncation window that's applied\n");
2805 fprintf(ofile
, " after minimum-phase reconstruction (default: %u).\n", DEFAULT_TRUNCSIZE
);
2806 fprintf(ofile
, " -d={dataset| Specify the model used for calculating the head-delay timing\n");
2807 fprintf(ofile
, " sphere} values (default: %s).\n", ((DEFAULT_HEAD_MODEL
== HM_DATASET
) ? "dataset" : "sphere"));
2808 fprintf(ofile
, " -c=<size> Use a customized head radius measured ear-to-ear in meters.\n");
2809 fprintf(ofile
, " -i=<filename> Specify an HRIR definition file to use (defaults to stdin).\n");
2810 fprintf(ofile
, " -o=<filename> Specify an output file. Overrides command-selected default.\n");
2811 fprintf(ofile
, " Use of '%%r' will be substituted with the data set sample rate.\n");
2814 // Standard command line dispatch.
2815 int main(const int argc
, const char *argv
[])
2817 const char *inName
= NULL
, *outName
= NULL
;
2818 OutputFormatT outFormat
;
2819 uint outRate
, fftSize
;
2820 int equalize
, surface
;
2828 if(argc
< 2 || strcmp(argv
[1], "--help") == 0 || strcmp(argv
[1], "-h") == 0)
2830 fprintf(stdout
, "HRTF Processing and Composition Utility\n\n");
2831 PrintHelp(argv
[0], stdout
);
2835 if(strcmp(argv
[1], "--make-mhr") == 0 || strcmp(argv
[1], "-m") == 0)
2837 outName
= "./oalsoft_hrtf_%r.mhr";
2842 fprintf(stderr
, "Error: Invalid command '%s'.\n\n", argv
[1]);
2843 PrintHelp(argv
[0], stderr
);
2849 equalize
= DEFAULT_EQUALIZE
;
2850 surface
= DEFAULT_SURFACE
;
2851 limit
= DEFAULT_LIMIT
;
2852 truncSize
= DEFAULT_TRUNCSIZE
;
2853 model
= DEFAULT_HEAD_MODEL
;
2854 radius
= DEFAULT_CUSTOM_RADIUS
;
2859 if(strncmp(argv
[argi
], "-r=", 3) == 0)
2861 outRate
= strtoul(&argv
[argi
][3], &end
, 10);
2862 if(end
[0] != '\0' || outRate
< MIN_RATE
|| outRate
> MAX_RATE
)
2864 fprintf(stderr
, "Error: Expected a value from %u to %u for '-r'.\n", MIN_RATE
, MAX_RATE
);
2868 else if(strncmp(argv
[argi
], "-f=", 3) == 0)
2870 fftSize
= strtoul(&argv
[argi
][3], &end
, 10);
2871 if(end
[0] != '\0' || (fftSize
&(fftSize
-1)) || fftSize
< MIN_FFTSIZE
|| fftSize
> MAX_FFTSIZE
)
2873 fprintf(stderr
, "Error: Expected a power-of-two value from %u to %u for '-f'.\n", MIN_FFTSIZE
, MAX_FFTSIZE
);
2877 else if(strncmp(argv
[argi
], "-e=", 3) == 0)
2879 if(strcmp(&argv
[argi
][3], "on") == 0)
2881 else if(strcmp(&argv
[argi
][3], "off") == 0)
2885 fprintf(stderr
, "Error: Expected 'on' or 'off' for '-e'.\n");
2889 else if(strncmp(argv
[argi
], "-s=", 3) == 0)
2891 if(strcmp(&argv
[argi
][3], "on") == 0)
2893 else if(strcmp(&argv
[argi
][3], "off") == 0)
2897 fprintf(stderr
, "Error: Expected 'on' or 'off' for '-s'.\n");
2901 else if(strncmp(argv
[argi
], "-l=", 3) == 0)
2903 if(strcmp(&argv
[argi
][3], "none") == 0)
2907 limit
= strtod(&argv
[argi
] [3], &end
);
2908 if(end
[0] != '\0' || limit
< MIN_LIMIT
|| limit
> MAX_LIMIT
)
2910 fprintf(stderr
, "Error: Expected 'none' or a value from %.2f to %.2f for '-l'.\n", MIN_LIMIT
, MAX_LIMIT
);
2915 else if(strncmp(argv
[argi
], "-w=", 3) == 0)
2917 truncSize
= strtoul(&argv
[argi
][3], &end
, 10);
2918 if(end
[0] != '\0' || truncSize
< MIN_TRUNCSIZE
|| truncSize
> MAX_TRUNCSIZE
|| (truncSize
%MOD_TRUNCSIZE
))
2920 fprintf(stderr
, "Error: Expected a value from %u to %u in multiples of %u for '-w'.\n", MIN_TRUNCSIZE
, MAX_TRUNCSIZE
, MOD_TRUNCSIZE
);
2924 else if(strncmp(argv
[argi
], "-d=", 3) == 0)
2926 if(strcmp(&argv
[argi
][3], "dataset") == 0)
2928 else if(strcmp(&argv
[argi
][3], "sphere") == 0)
2932 fprintf(stderr
, "Error: Expected 'dataset' or 'sphere' for '-d'.\n");
2936 else if(strncmp(argv
[argi
], "-c=", 3) == 0)
2938 radius
= strtod(&argv
[argi
][3], &end
);
2939 if(end
[0] != '\0' || radius
< MIN_CUSTOM_RADIUS
|| radius
> MAX_CUSTOM_RADIUS
)
2941 fprintf(stderr
, "Error: Expected a value from %.2f to %.2f for '-c'.\n", MIN_CUSTOM_RADIUS
, MAX_CUSTOM_RADIUS
);
2945 else if(strncmp(argv
[argi
], "-i=", 3) == 0)
2946 inName
= &argv
[argi
][3];
2947 else if(strncmp(argv
[argi
], "-o=", 3) == 0)
2948 outName
= &argv
[argi
][3];
2951 fprintf(stderr
, "Error: Invalid option '%s'.\n", argv
[argi
]);
2956 if(!ProcessDefinition(inName
, outRate
, fftSize
, equalize
, surface
, limit
, truncSize
, model
, radius
, outFormat
, outName
))
2958 fprintf(stdout
, "Operation completed.\n");