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
{
291 /*****************************
292 *** Token reader routines ***
293 *****************************/
295 /* Whitespace is not significant. It can process tokens as identifiers, numbers
296 * (integer and floating-point), strings, and operators. Strings must be
297 * encapsulated by double-quotes and cannot span multiple lines.
300 // Setup the reader on the given file. The filename can be NULL if no error
301 // output is desired.
302 static void TrSetup(FILE *fp
, const char *filename
, TokenReaderT
*tr
)
304 const char *name
= NULL
;
308 const char *slash
= strrchr(filename
, '/');
311 const char *bslash
= strrchr(slash
+1, '\\');
312 if(bslash
) name
= bslash
+1;
317 const char *bslash
= strrchr(filename
, '\\');
318 if(bslash
) name
= bslash
+1;
319 else name
= filename
;
331 // Prime the reader's ring buffer, and return a result indicating that there
332 // is text to process.
333 static int TrLoad(TokenReaderT
*tr
)
335 size_t toLoad
, in
, count
;
337 toLoad
= TR_RING_SIZE
- (tr
->mIn
- tr
->mOut
);
338 if(toLoad
>= TR_LOAD_SIZE
&& !feof(tr
->mFile
))
340 // Load TR_LOAD_SIZE (or less if at the end of the file) per read.
341 toLoad
= TR_LOAD_SIZE
;
342 in
= tr
->mIn
&TR_RING_MASK
;
343 count
= TR_RING_SIZE
- in
;
346 tr
->mIn
+= fread(&tr
->mRing
[in
], 1, count
, tr
->mFile
);
347 tr
->mIn
+= fread(&tr
->mRing
[0], 1, toLoad
-count
, tr
->mFile
);
350 tr
->mIn
+= fread(&tr
->mRing
[in
], 1, toLoad
, tr
->mFile
);
352 if(tr
->mOut
>= TR_RING_SIZE
)
354 tr
->mOut
-= TR_RING_SIZE
;
355 tr
->mIn
-= TR_RING_SIZE
;
358 if(tr
->mIn
> tr
->mOut
)
363 // Error display routine. Only displays when the base name is not NULL.
364 static void TrErrorVA(const TokenReaderT
*tr
, uint line
, uint column
, const char *format
, va_list argPtr
)
368 fprintf(stderr
, "Error (%s:%u:%u): ", tr
->mName
, line
, column
);
369 vfprintf(stderr
, format
, argPtr
);
372 // Used to display an error at a saved line/column.
373 static void TrErrorAt(const TokenReaderT
*tr
, uint line
, uint column
, const char *format
, ...)
377 va_start(argPtr
, format
);
378 TrErrorVA(tr
, line
, column
, format
, argPtr
);
382 // Used to display an error at the current line/column.
383 static void TrError(const TokenReaderT
*tr
, const char *format
, ...)
387 va_start(argPtr
, format
);
388 TrErrorVA(tr
, tr
->mLine
, tr
->mColumn
, format
, argPtr
);
392 // Skips to the next line.
393 static void TrSkipLine(TokenReaderT
*tr
)
399 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
411 // Skips to the next token.
412 static int TrSkipWhitespace(TokenReaderT
*tr
)
418 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
438 // Get the line and/or column of the next token (or the end of input).
439 static void TrIndication(TokenReaderT
*tr
, uint
*line
, uint
*column
)
441 TrSkipWhitespace(tr
);
442 if(line
) *line
= tr
->mLine
;
443 if(column
) *column
= tr
->mColumn
;
446 // Checks to see if a token is the given operator. It does not display any
447 // errors and will not proceed to the next token.
448 static int TrIsOperator(TokenReaderT
*tr
, const char *op
)
453 if(!TrSkipWhitespace(tr
))
457 while(op
[len
] != '\0' && out
< tr
->mIn
)
459 ch
= tr
->mRing
[out
&TR_RING_MASK
];
460 if(ch
!= op
[len
]) break;
469 /* The TrRead*() routines obtain the value of a matching token type. They
470 * display type, form, and boundary errors and will proceed to the next
474 // Reads and validates an identifier token.
475 static int TrReadIdent(TokenReaderT
*tr
, const uint maxLen
, char *ident
)
481 if(TrSkipWhitespace(tr
))
484 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
485 if(ch
== '_' || isalpha(ch
))
495 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
496 } while(ch
== '_' || isdigit(ch
) || isalpha(ch
));
504 TrErrorAt(tr
, tr
->mLine
, col
, "Identifier is too long.\n");
508 TrErrorAt(tr
, tr
->mLine
, col
, "Expected an identifier.\n");
512 // Reads and validates (including bounds) an integer token.
513 static int TrReadInt(TokenReaderT
*tr
, const int loBound
, const int hiBound
, int *value
)
515 uint col
, digis
, len
;
519 if(TrSkipWhitespace(tr
))
523 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
524 if(ch
== '+' || ch
== '-')
533 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
534 if(!isdigit(ch
)) break;
542 if(digis
> 0 && ch
!= '.' && !isalpha(ch
))
546 TrErrorAt(tr
, tr
->mLine
, col
, "Integer is too long.");
550 *value
= strtol(temp
, NULL
, 10);
551 if(*value
< loBound
|| *value
> hiBound
)
553 TrErrorAt(tr
, tr
->mLine
, col
, "Expected a value from %d to %d.\n", loBound
, hiBound
);
559 TrErrorAt(tr
, tr
->mLine
, col
, "Expected an integer.\n");
563 // Reads and validates (including bounds) a float token.
564 static int TrReadFloat(TokenReaderT
*tr
, const double loBound
, const double hiBound
, double *value
)
566 uint col
, digis
, len
;
570 if(TrSkipWhitespace(tr
))
574 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
575 if(ch
== '+' || ch
== '-')
585 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
586 if(!isdigit(ch
)) break;
602 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
603 if(!isdigit(ch
)) break;
612 if(ch
== 'E' || ch
== 'e')
619 if(ch
== '+' || ch
== '-')
628 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
629 if(!isdigit(ch
)) break;
638 if(digis
> 0 && ch
!= '.' && !isalpha(ch
))
642 TrErrorAt(tr
, tr
->mLine
, col
, "Float is too long.");
646 *value
= strtod(temp
, NULL
);
647 if(*value
< loBound
|| *value
> hiBound
)
649 TrErrorAt (tr
, tr
->mLine
, col
, "Expected a value from %f to %f.\n", loBound
, hiBound
);
658 TrErrorAt(tr
, tr
->mLine
, col
, "Expected a float.\n");
662 // Reads and validates a string token.
663 static int TrReadString(TokenReaderT
*tr
, const uint maxLen
, char *text
)
669 if(TrSkipWhitespace(tr
))
672 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
679 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
685 TrErrorAt (tr
, tr
->mLine
, col
, "Unterminated string at end of line.\n");
694 tr
->mColumn
+= 1 + len
;
695 TrErrorAt(tr
, tr
->mLine
, col
, "Unterminated string at end of input.\n");
698 tr
->mColumn
+= 2 + len
;
701 TrErrorAt (tr
, tr
->mLine
, col
, "String is too long.\n");
708 TrErrorAt(tr
, tr
->mLine
, col
, "Expected a string.\n");
712 // Reads and validates the given operator.
713 static int TrReadOperator(TokenReaderT
*tr
, const char *op
)
719 if(TrSkipWhitespace(tr
))
723 while(op
[len
] != '\0' && TrLoad(tr
))
725 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
726 if(ch
!= op
[len
]) break;
734 TrErrorAt(tr
, tr
->mLine
, col
, "Expected '%s' operator.\n", op
);
738 /* Performs a string substitution. Any case-insensitive occurrences of the
739 * pattern string are replaced with the replacement string. The result is
740 * truncated if necessary.
742 static int StrSubst(const char *in
, const char *pat
, const char *rep
, const size_t maxLen
, char *out
)
744 size_t inLen
, patLen
, repLen
;
749 patLen
= strlen(pat
);
750 repLen
= strlen(rep
);
754 while(si
< inLen
&& di
< maxLen
)
756 if(patLen
<= inLen
-si
)
758 if(strncasecmp(&in
[si
], pat
, patLen
) == 0)
760 if(repLen
> maxLen
-di
)
762 repLen
= maxLen
- di
;
765 strncpy(&out
[di
], rep
, repLen
);
781 /*********************
782 *** Math routines ***
783 *********************/
785 // Provide missing math routines for MSVC versions < 1800 (Visual Studio 2013).
786 #if defined(_MSC_VER) && _MSC_VER < 1800
787 static double round(double val
)
790 return ceil(val
-0.5);
791 return floor(val
+0.5);
794 static double fmin(double a
, double b
)
796 return (a
<b
) ? a
: b
;
799 static double fmax(double a
, double b
)
801 return (a
>b
) ? a
: b
;
805 // Simple clamp routine.
806 static double Clamp(const double val
, const double lower
, const double upper
)
808 return fmin(fmax(val
, lower
), upper
);
811 // Performs linear interpolation.
812 static double Lerp(const double a
, const double b
, const double f
)
814 return a
+ (f
* (b
- a
));
817 // Performs a high-passed triangular probability density function dither from
818 // a double to an integer. It assumes the input sample is already scaled.
819 static int HpTpdfDither(const double in
, int *hpHist
)
821 static const double PRNG_SCALE
= 1.0 / (RAND_MAX
+1.0);
826 out
= round(in
+ (PRNG_SCALE
* (prn
- *hpHist
)));
831 // Allocates an array of doubles.
832 static double *CreateArray(size_t n
)
837 a
= calloc(n
, sizeof(double));
840 fprintf(stderr
, "Error: Out of memory.\n");
846 // Frees an array of doubles.
847 static void DestroyArray(double *a
)
850 // Complex number routines. All outputs must be non-NULL.
852 // Magnitude/absolute value.
853 static double ComplexAbs(const double r
, const double i
)
855 return sqrt(r
*r
+ i
*i
);
859 static void ComplexMul(const double aR
, const double aI
, const double bR
, const double bI
, double *outR
, double *outI
)
861 *outR
= (aR
* bR
) - (aI
* bI
);
862 *outI
= (aI
* bR
) + (aR
* bI
);
866 static void ComplexExp(const double inR
, const double inI
, double *outR
, double *outI
)
869 *outR
= e
* cos(inI
);
870 *outI
= e
* sin(inI
);
873 /* Fast Fourier transform routines. The number of points must be a power of
874 * two. In-place operation is possible only if both the real and imaginary
875 * parts are in-place together.
878 // Performs bit-reversal ordering.
879 static void FftArrange(const uint n
, const double *inR
, const double *inI
, double *outR
, double *outI
)
884 if(inR
== outR
&& inI
== outI
)
886 // Handle in-place arrangement.
907 // Handle copy arrangement.
921 // Performs the summation.
922 static void FftSummation(const uint n
, const double s
, double *re
, double *im
)
926 double vR
, vI
, wR
, wI
;
931 for(m
= 1, m2
= 2;m
< n
; m
<<= 1, m2
<<= 1)
933 // v = Complex (-2.0 * sin (0.5 * pi / m) * sin (0.5 * pi / m), -sin (pi / m))
934 vR
= sin(0.5 * pi
/ m
);
937 // w = Complex (1.0, 0.0)
942 for(k
= i
;k
< n
;k
+= m2
)
945 // t = ComplexMul(w, out[km2])
946 tR
= (wR
* re
[mk
]) - (wI
* im
[mk
]);
947 tI
= (wR
* im
[mk
]) + (wI
* re
[mk
]);
948 // out[mk] = ComplexSub (out [k], t)
951 // out[k] = ComplexAdd (out [k], t)
955 // t = ComplexMul (v, w)
956 tR
= (vR
* wR
) - (vI
* wI
);
957 tI
= (vR
* wI
) + (vI
* wR
);
958 // w = ComplexAdd (w, t)
965 // Performs a forward FFT.
966 static void FftForward(const uint n
, const double *inR
, const double *inI
, double *outR
, double *outI
)
968 FftArrange(n
, inR
, inI
, outR
, outI
);
969 FftSummation(n
, 1.0, outR
, outI
);
972 // Performs an inverse FFT.
973 static void FftInverse(const uint n
, const double *inR
, const double *inI
, double *outR
, double *outI
)
978 FftArrange(n
, inR
, inI
, outR
, outI
);
979 FftSummation(n
, -1.0, outR
, outI
);
988 /* Calculate the complex helical sequence (or discrete-time analytical
989 * signal) of the given input using the Hilbert transform. Given the
990 * negative natural logarithm of a signal's magnitude response, the imaginary
991 * components can be used as the angles for minimum-phase reconstruction.
993 static void Hilbert(const uint n
, const double *in
, double *outR
, double *outI
)
999 // Handle in-place operation.
1000 for(i
= 0;i
< n
;i
++)
1005 // Handle copy operation.
1006 for(i
= 0;i
< n
;i
++)
1012 FftForward(n
, outR
, outI
, outR
, outI
);
1013 /* Currently the Fourier routines operate only on point counts that are
1014 * powers of two. If that changes and n is odd, the following conditional
1015 * should be: i < (n + 1) / 2.
1017 for(i
= 1;i
< (n
/2);i
++)
1022 // If n is odd, the following increment should be skipped.
1029 FftInverse(n
, outR
, outI
, outR
, outI
);
1032 /* Calculate the magnitude response of the given input. This is used in
1033 * place of phase decomposition, since the phase residuals are discarded for
1034 * minimum phase reconstruction. The mirrored half of the response is also
1037 static void MagnitudeResponse(const uint n
, const double *inR
, const double *inI
, double *out
)
1039 const uint m
= 1 + (n
/ 2);
1041 for(i
= 0;i
< m
;i
++)
1042 out
[i
] = fmax(ComplexAbs(inR
[i
], inI
[i
]), EPSILON
);
1045 /* Apply a range limit (in dB) to the given magnitude response. This is used
1046 * to adjust the effects of the diffuse-field average on the equalization
1049 static void LimitMagnitudeResponse(const uint n
, const double limit
, const double *in
, double *out
)
1051 const uint m
= 1 + (n
/ 2);
1053 uint i
, lower
, upper
;
1056 halfLim
= limit
/ 2.0;
1057 // Convert the response to dB.
1058 for(i
= 0;i
< m
;i
++)
1059 out
[i
] = 20.0 * log10(in
[i
]);
1060 // Use six octaves to calculate the average magnitude of the signal.
1061 lower
= ((uint
)ceil(n
/ pow(2.0, 8.0))) - 1;
1062 upper
= ((uint
)floor(n
/ pow(2.0, 2.0))) - 1;
1064 for(i
= lower
;i
<= upper
;i
++)
1066 ave
/= upper
- lower
+ 1;
1067 // Keep the response within range of the average magnitude.
1068 for(i
= 0;i
< m
;i
++)
1069 out
[i
] = Clamp(out
[i
], ave
- halfLim
, ave
+ halfLim
);
1070 // Convert the response back to linear magnitude.
1071 for(i
= 0;i
< m
;i
++)
1072 out
[i
] = pow(10.0, out
[i
] / 20.0);
1075 /* Reconstructs the minimum-phase component for the given magnitude response
1076 * of a signal. This is equivalent to phase recomposition, sans the missing
1077 * residuals (which were discarded). The mirrored half of the response is
1080 static void MinimumPhase(const uint n
, const double *in
, double *outR
, double *outI
)
1082 const uint m
= 1 + (n
/ 2);
1087 mags
= CreateArray(n
);
1088 for(i
= 0;i
< m
;i
++)
1090 mags
[i
] = fmax(in
[i
], EPSILON
);
1091 outR
[i
] = -log(mags
[i
]);
1095 mags
[i
] = mags
[n
- i
];
1096 outR
[i
] = outR
[n
- i
];
1098 Hilbert(n
, outR
, outR
, outI
);
1099 // Remove any DC offset the filter has.
1102 for(i
= 1;i
< n
;i
++)
1104 ComplexExp(0.0, outI
[i
], &aR
, &aI
);
1105 ComplexMul(mags
[i
], 0.0, aR
, aI
, &outR
[i
], &outI
[i
]);
1111 /***************************
1112 *** Resampler functions ***
1113 ***************************/
1115 /* This is the normalized cardinal sine (sinc) function.
1117 * sinc(x) = { 1, x = 0
1118 * { sin(pi x) / (pi x), otherwise.
1120 static double Sinc(const double x
)
1122 if(fabs(x
) < EPSILON
)
1124 return sin(M_PI
* x
) / (M_PI
* x
);
1127 /* The zero-order modified Bessel function of the first kind, used for the
1130 * I_0(x) = sum_{k=0}^inf (1 / k!)^2 (x / 2)^(2 k)
1131 * = sum_{k=0}^inf ((x / 2)^k / k!)^2
1133 static double BesselI_0(const double x
)
1135 double term
, sum
, x2
, y
, last_sum
;
1138 // Start at k=1 since k=0 is trivial.
1144 // Let the integration converge until the term of the sum is no longer
1152 } while(sum
!= last_sum
);
1156 /* Calculate a Kaiser window from the given beta value and a normalized k
1159 * w(k) = { I_0(B sqrt(1 - k^2)) / I_0(B), -1 <= k <= 1
1162 * Where k can be calculated as:
1164 * k = i / l, where -l <= i <= l.
1168 * k = 2 i / M - 1, where 0 <= i <= M.
1170 static double Kaiser(const double b
, const double k
)
1172 if(!(k
>= -1.0 && k
<= 1.0))
1174 return BesselI_0(b
* sqrt(1.0 - k
*k
)) / BesselI_0(b
);
1177 // Calculates the greatest common divisor of a and b.
1178 static uint
Gcd(uint x
, uint y
)
1189 /* Calculates the size (order) of the Kaiser window. Rejection is in dB and
1190 * the transition width is normalized frequency (0.5 is nyquist).
1192 * M = { ceil((r - 7.95) / (2.285 2 pi f_t)), r > 21
1193 * { ceil(5.79 / 2 pi f_t), r <= 21.
1196 static uint
CalcKaiserOrder(const double rejection
, const double transition
)
1198 double w_t
= 2.0 * M_PI
* transition
;
1199 if(rejection
> 21.0)
1200 return (uint
)ceil((rejection
- 7.95) / (2.285 * w_t
));
1201 return (uint
)ceil(5.79 / w_t
);
1204 // Calculates the beta value of the Kaiser window. Rejection is in dB.
1205 static double CalcKaiserBeta(const double rejection
)
1207 if(rejection
> 50.0)
1208 return 0.1102 * (rejection
- 8.7);
1209 if(rejection
>= 21.0)
1210 return (0.5842 * pow(rejection
- 21.0, 0.4)) +
1211 (0.07886 * (rejection
- 21.0));
1215 /* Calculates a point on the Kaiser-windowed sinc filter for the given half-
1216 * width, beta, gain, and cutoff. The point is specified in non-normalized
1217 * samples, from 0 to M, where M = (2 l + 1).
1219 * w(k) 2 p f_t sinc(2 f_t x)
1221 * x -- centered sample index (i - l)
1222 * k -- normalized and centered window index (x / l)
1223 * w(k) -- window function (Kaiser)
1224 * p -- gain compensation factor when sampling
1225 * f_t -- normalized center frequency (or cutoff; 0.5 is nyquist)
1227 static double SincFilter(const int l
, const double b
, const double gain
, const double cutoff
, const int i
)
1229 return Kaiser(b
, (double)(i
- l
) / l
) * 2.0 * gain
* cutoff
* Sinc(2.0 * cutoff
* (i
- l
));
1232 /* This is a polyphase sinc-filtered resampler.
1234 * Upsample Downsample
1236 * p/q = 3/2 p/q = 3/5
1238 * M-+-+-+-> M-+-+-+->
1239 * -------------------+ ---------------------+
1240 * p s * f f f f|f| | p s * f f f f f |
1241 * | 0 * 0 0 0|0|0 | | 0 * 0 0 0 0|0| |
1242 * v 0 * 0 0|0|0 0 | v 0 * 0 0 0|0|0 |
1243 * s * f|f|f f f | s * f f|f|f f |
1244 * 0 * |0|0 0 0 0 | 0 * 0|0|0 0 0 |
1245 * --------+=+--------+ 0 * |0|0 0 0 0 |
1246 * d . d .|d|. d . d ----------+=+--------+
1247 * d . . . .|d|. . . .
1251 * P_f(i,j) = q i mod p + pj
1252 * P_s(i,j) = floor(q i / p) - j
1253 * d[i=0..N-1] = sum_{j=0}^{floor((M - 1) / p)} {
1254 * { f[P_f(i,j)] s[P_s(i,j)], P_f(i,j) < M
1255 * { 0, P_f(i,j) >= M. }
1258 // Calculate the resampling metrics and build the Kaiser-windowed sinc filter
1259 // that's used to cut frequencies above the destination nyquist.
1260 static void ResamplerSetup(ResamplerT
*rs
, const uint srcRate
, const uint dstRate
)
1262 double cutoff
, width
, beta
;
1266 gcd
= Gcd(srcRate
, dstRate
);
1267 rs
->mP
= dstRate
/ gcd
;
1268 rs
->mQ
= srcRate
/ gcd
;
1269 /* The cutoff is adjusted by half the transition width, so the transition
1270 * ends before the nyquist (0.5). Both are scaled by the downsampling
1275 cutoff
= 0.45 / rs
->mP
;
1276 width
= 0.1 / rs
->mP
;
1280 cutoff
= 0.45 / rs
->mQ
;
1281 width
= 0.1 / rs
->mQ
;
1283 // A rejection of -180 dB is used for the stop band.
1284 l
= CalcKaiserOrder(180.0, width
) / 2;
1285 beta
= CalcKaiserBeta(180.0);
1286 rs
->mM
= (2 * l
) + 1;
1288 rs
->mF
= CreateArray(rs
->mM
);
1289 for(i
= 0;i
< ((int)rs
->mM
);i
++)
1290 rs
->mF
[i
] = SincFilter((int)l
, beta
, rs
->mP
, cutoff
, i
);
1293 // Clean up after the resampler.
1294 static void ResamplerClear(ResamplerT
*rs
)
1296 DestroyArray(rs
->mF
);
1300 // Perform the upsample-filter-downsample resampling operation using a
1301 // polyphase filter implementation.
1302 static void ResamplerRun(ResamplerT
*rs
, const uint inN
, const double *in
, const uint outN
, double *out
)
1304 const uint p
= rs
->mP
, q
= rs
->mQ
, m
= rs
->mM
, l
= rs
->mL
;
1305 const double *f
= rs
->mF
;
1313 // Handle in-place operation.
1315 work
= CreateArray(outN
);
1318 // Resample the input.
1319 for(i
= 0;i
< outN
;i
++)
1322 // Input starts at l to compensate for the filter delay. This will
1323 // drop any build-up from the first half of the filter.
1324 j_f
= (l
+ (q
* i
)) % p
;
1325 j_s
= (l
+ (q
* i
)) / p
;
1328 // Only take input when 0 <= j_s < inN. This single unsigned
1329 // comparison catches both cases.
1331 r
+= f
[j_f
] * in
[j_s
];
1337 // Clean up after in-place operation.
1340 for(i
= 0;i
< outN
;i
++)
1346 /*************************
1347 *** File source input ***
1348 *************************/
1350 // Read a binary value of the specified byte order and byte size from a file,
1351 // storing it as a 32-bit unsigned integer.
1352 static int ReadBin4(FILE *fp
, const char *filename
, const ByteOrderT order
, const uint bytes
, uint32
*out
)
1358 if(fread(in
, 1, bytes
, fp
) != bytes
)
1360 fprintf(stderr
, "Error: Bad read from file '%s'.\n", filename
);
1367 for(i
= 0;i
< bytes
;i
++)
1368 accum
= (accum
<<8) | in
[bytes
- i
- 1];
1371 for(i
= 0;i
< bytes
;i
++)
1372 accum
= (accum
<<8) | in
[i
];
1381 // Read a binary value of the specified byte order from a file, storing it as
1382 // a 64-bit unsigned integer.
1383 static int ReadBin8(FILE *fp
, const char *filename
, const ByteOrderT order
, uint64
*out
)
1389 if(fread(in
, 1, 8, fp
) != 8)
1391 fprintf(stderr
, "Error: Bad read from file '%s'.\n", filename
);
1398 for(i
= 0;i
< 8;i
++)
1399 accum
= (accum
<<8) | in
[8 - i
- 1];
1402 for(i
= 0;i
< 8;i
++)
1403 accum
= (accum
<<8) | in
[i
];
1412 /* Read a binary value of the specified type, byte order, and byte size from
1413 * a file, converting it to a double. For integer types, the significant
1414 * bits are used to normalize the result. The sign of bits determines
1415 * whether they are padded toward the MSB (negative) or LSB (positive).
1416 * Floating-point types are not normalized.
1418 static int ReadBinAsDouble(FILE *fp
, const char *filename
, const ByteOrderT order
, const ElementTypeT type
, const uint bytes
, const int bits
, double *out
)
1433 if(!ReadBin8(fp
, filename
, order
, &v8
.ui
))
1440 if(!ReadBin4(fp
, filename
, order
, bytes
, &v4
.ui
))
1447 v4
.ui
>>= (8*bytes
) - ((uint
)bits
);
1449 v4
.ui
&= (0xFFFFFFFF >> (32+bits
));
1451 if(v4
.ui
&(uint
)(1<<(abs(bits
)-1)))
1452 v4
.ui
|= (0xFFFFFFFF << abs (bits
));
1453 *out
= v4
.i
/ (double)(1<<(abs(bits
)-1));
1459 /* Read an ascii value of the specified type from a file, converting it to a
1460 * double. For integer types, the significant bits are used to normalize the
1461 * result. The sign of the bits should always be positive. This also skips
1462 * up to one separator character before the element itself.
1464 static int ReadAsciiAsDouble(TokenReaderT
*tr
, const char *filename
, const ElementTypeT type
, const uint bits
, double *out
)
1466 if(TrIsOperator(tr
, ","))
1467 TrReadOperator(tr
, ",");
1468 else if(TrIsOperator(tr
, ":"))
1469 TrReadOperator(tr
, ":");
1470 else if(TrIsOperator(tr
, ";"))
1471 TrReadOperator(tr
, ";");
1472 else if(TrIsOperator(tr
, "|"))
1473 TrReadOperator(tr
, "|");
1477 if(!TrReadFloat(tr
, -HUGE_VAL
, HUGE_VAL
, out
))
1479 fprintf(stderr
, "Error: Bad read from file '%s'.\n", filename
);
1486 if(!TrReadInt(tr
, -(1<<(bits
-1)), (1<<(bits
-1))-1, &v
))
1488 fprintf(stderr
, "Error: Bad read from file '%s'.\n", filename
);
1491 *out
= v
/ (double)((1<<(bits
-1))-1);
1496 // Read the RIFF/RIFX WAVE format chunk from a file, validating it against
1497 // the source parameters and data set metrics.
1498 static int ReadWaveFormat(FILE *fp
, const ByteOrderT order
, const uint hrirRate
, SourceRefT
*src
)
1500 uint32 fourCC
, chunkSize
;
1501 uint32 format
, channels
, rate
, dummy
, block
, size
, bits
;
1506 fseek (fp
, (long) chunkSize
, SEEK_CUR
);
1507 if(!ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, &fourCC
) ||
1508 !ReadBin4(fp
, src
->mPath
, order
, 4, &chunkSize
))
1510 } while(fourCC
!= FOURCC_FMT
);
1511 if(!ReadBin4(fp
, src
->mPath
, order
, 2, & format
) ||
1512 !ReadBin4(fp
, src
->mPath
, order
, 2, & channels
) ||
1513 !ReadBin4(fp
, src
->mPath
, order
, 4, & rate
) ||
1514 !ReadBin4(fp
, src
->mPath
, order
, 4, & dummy
) ||
1515 !ReadBin4(fp
, src
->mPath
, order
, 2, & block
))
1520 if(!ReadBin4(fp
, src
->mPath
, order
, 2, &size
))
1528 if(format
== WAVE_FORMAT_EXTENSIBLE
)
1530 fseek(fp
, 2, SEEK_CUR
);
1531 if(!ReadBin4(fp
, src
->mPath
, order
, 2, &bits
))
1535 fseek(fp
, 4, SEEK_CUR
);
1536 if(!ReadBin4(fp
, src
->mPath
, order
, 2, &format
))
1538 fseek(fp
, (long)(chunkSize
- 26), SEEK_CUR
);
1544 fseek(fp
, (long)(chunkSize
- 16), SEEK_CUR
);
1546 fseek(fp
, (long)(chunkSize
- 14), SEEK_CUR
);
1548 if(format
!= WAVE_FORMAT_PCM
&& format
!= WAVE_FORMAT_IEEE_FLOAT
)
1550 fprintf(stderr
, "Error: Unsupported WAVE format in file '%s'.\n", src
->mPath
);
1553 if(src
->mChannel
>= channels
)
1555 fprintf(stderr
, "Error: Missing source channel in WAVE file '%s'.\n", src
->mPath
);
1558 if(rate
!= hrirRate
)
1560 fprintf(stderr
, "Error: Mismatched source sample rate in WAVE file '%s'.\n", src
->mPath
);
1563 if(format
== WAVE_FORMAT_PCM
)
1565 if(size
< 2 || size
> 4)
1567 fprintf(stderr
, "Error: Unsupported sample size in WAVE file '%s'.\n", src
->mPath
);
1570 if(bits
< 16 || bits
> (8*size
))
1572 fprintf (stderr
, "Error: Bad significant bits in WAVE file '%s'.\n", src
->mPath
);
1575 src
->mType
= ET_INT
;
1579 if(size
!= 4 && size
!= 8)
1581 fprintf(stderr
, "Error: Unsupported sample size in WAVE file '%s'.\n", src
->mPath
);
1587 src
->mBits
= (int)bits
;
1588 src
->mSkip
= channels
;
1592 // Read a RIFF/RIFX WAVE data chunk, converting all elements to doubles.
1593 static int ReadWaveData(FILE *fp
, const SourceRefT
*src
, const ByteOrderT order
, const uint n
, double *hrir
)
1595 int pre
, post
, skip
;
1598 pre
= (int)(src
->mSize
* src
->mChannel
);
1599 post
= (int)(src
->mSize
* (src
->mSkip
- src
->mChannel
- 1));
1601 for(i
= 0;i
< n
;i
++)
1605 fseek(fp
, skip
, SEEK_CUR
);
1606 if(!ReadBinAsDouble(fp
, src
->mPath
, order
, src
->mType
, src
->mSize
, src
->mBits
, &hrir
[i
]))
1611 fseek(fp
, skip
, SEEK_CUR
);
1615 // Read the RIFF/RIFX WAVE list or data chunk, converting all elements to
1617 static int ReadWaveList(FILE *fp
, const SourceRefT
*src
, const ByteOrderT order
, const uint n
, double *hrir
)
1619 uint32 fourCC
, chunkSize
, listSize
, count
;
1620 uint block
, skip
, offset
, i
;
1624 if(!ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, & fourCC
) ||
1625 !ReadBin4(fp
, src
->mPath
, order
, 4, & chunkSize
))
1628 if(fourCC
== FOURCC_DATA
)
1630 block
= src
->mSize
* src
->mSkip
;
1631 count
= chunkSize
/ block
;
1632 if(count
< (src
->mOffset
+ n
))
1634 fprintf(stderr
, "Error: Bad read from file '%s'.\n", src
->mPath
);
1637 fseek(fp
, (long)(src
->mOffset
* block
), SEEK_CUR
);
1638 if(!ReadWaveData(fp
, src
, order
, n
, &hrir
[0]))
1642 else if(fourCC
== FOURCC_LIST
)
1644 if(!ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, &fourCC
))
1647 if(fourCC
== FOURCC_WAVL
)
1651 fseek(fp
, (long)chunkSize
, SEEK_CUR
);
1653 listSize
= chunkSize
;
1654 block
= src
->mSize
* src
->mSkip
;
1655 skip
= src
->mOffset
;
1658 while(offset
< n
&& listSize
> 8)
1660 if(!ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, &fourCC
) ||
1661 !ReadBin4(fp
, src
->mPath
, order
, 4, &chunkSize
))
1663 listSize
-= 8 + chunkSize
;
1664 if(fourCC
== FOURCC_DATA
)
1666 count
= chunkSize
/ block
;
1669 fseek(fp
, (long)(skip
* block
), SEEK_CUR
);
1670 chunkSize
-= skip
* block
;
1673 if(count
> (n
- offset
))
1675 if(!ReadWaveData(fp
, src
, order
, count
, &hrir
[offset
]))
1677 chunkSize
-= count
* block
;
1679 lastSample
= hrir
[offset
- 1];
1687 else if(fourCC
== FOURCC_SLNT
)
1689 if(!ReadBin4(fp
, src
->mPath
, order
, 4, &count
))
1696 if(count
> (n
- offset
))
1698 for(i
= 0; i
< count
; i
++)
1699 hrir
[offset
+ i
] = lastSample
;
1709 fseek(fp
, (long)chunkSize
, SEEK_CUR
);
1713 fprintf(stderr
, "Error: Bad read from file '%s'.\n", src
->mPath
);
1719 // Load a source HRIR from a RIFF/RIFX WAVE file.
1720 static int LoadWaveSource(FILE *fp
, SourceRefT
*src
, const uint hrirRate
, const uint n
, double *hrir
)
1722 uint32 fourCC
, dummy
;
1725 if(!ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, &fourCC
) ||
1726 !ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, &dummy
))
1728 if(fourCC
== FOURCC_RIFF
)
1730 else if(fourCC
== FOURCC_RIFX
)
1734 fprintf(stderr
, "Error: No RIFF/RIFX chunk in file '%s'.\n", src
->mPath
);
1738 if(!ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, &fourCC
))
1740 if(fourCC
!= FOURCC_WAVE
)
1742 fprintf(stderr
, "Error: Not a RIFF/RIFX WAVE file '%s'.\n", src
->mPath
);
1745 if(!ReadWaveFormat(fp
, order
, hrirRate
, src
))
1747 if(!ReadWaveList(fp
, src
, order
, n
, hrir
))
1752 // Load a source HRIR from a binary file.
1753 static int LoadBinarySource(FILE *fp
, const SourceRefT
*src
, const ByteOrderT order
, const uint n
, double *hrir
)
1757 fseek(fp
, (long)src
->mOffset
, SEEK_SET
);
1758 for(i
= 0;i
< n
;i
++)
1760 if(!ReadBinAsDouble(fp
, src
->mPath
, order
, src
->mType
, src
->mSize
, src
->mBits
, &hrir
[i
]))
1763 fseek(fp
, (long)src
->mSkip
, SEEK_CUR
);
1768 // Load a source HRIR from an ASCII text file containing a list of elements
1769 // separated by whitespace or common list operators (',', ';', ':', '|').
1770 static int LoadAsciiSource(FILE *fp
, const SourceRefT
*src
, const uint n
, double *hrir
)
1776 TrSetup(fp
, NULL
, &tr
);
1777 for(i
= 0;i
< src
->mOffset
;i
++)
1779 if(!ReadAsciiAsDouble(&tr
, src
->mPath
, src
->mType
, (uint
)src
->mBits
, &dummy
))
1782 for(i
= 0;i
< n
;i
++)
1784 if(!ReadAsciiAsDouble(&tr
, src
->mPath
, src
->mType
, (uint
)src
->mBits
, &hrir
[i
]))
1786 for(j
= 0;j
< src
->mSkip
;j
++)
1788 if(!ReadAsciiAsDouble(&tr
, src
->mPath
, src
->mType
, (uint
)src
->mBits
, &dummy
))
1795 // Load a source HRIR from a supported file type.
1796 static int LoadSource(SourceRefT
*src
, const uint hrirRate
, const uint n
, double *hrir
)
1801 if (src
->mFormat
== SF_ASCII
)
1802 fp
= fopen(src
->mPath
, "r");
1804 fp
= fopen(src
->mPath
, "rb");
1807 fprintf(stderr
, "Error: Could not open source file '%s'.\n", src
->mPath
);
1810 if(src
->mFormat
== SF_WAVE
)
1811 result
= LoadWaveSource(fp
, src
, hrirRate
, n
, hrir
);
1812 else if(src
->mFormat
== SF_BIN_LE
)
1813 result
= LoadBinarySource(fp
, src
, BO_LITTLE
, n
, hrir
);
1814 else if(src
->mFormat
== SF_BIN_BE
)
1815 result
= LoadBinarySource(fp
, src
, BO_BIG
, n
, hrir
);
1817 result
= LoadAsciiSource(fp
, src
, n
, hrir
);
1823 /***************************
1824 *** File storage output ***
1825 ***************************/
1827 // Write an ASCII string to a file.
1828 static int WriteAscii(const char *out
, FILE *fp
, const char *filename
)
1833 if(fwrite(out
, 1, len
, fp
) != len
)
1836 fprintf(stderr
, "Error: Bad write to file '%s'.\n", filename
);
1842 // Write a binary value of the given byte order and byte size to a file,
1843 // loading it from a 32-bit unsigned integer.
1844 static int WriteBin4(const ByteOrderT order
, const uint bytes
, const uint32 in
, FILE *fp
, const char *filename
)
1852 for(i
= 0;i
< bytes
;i
++)
1853 out
[i
] = (in
>>(i
*8)) & 0x000000FF;
1856 for(i
= 0;i
< bytes
;i
++)
1857 out
[bytes
- i
- 1] = (in
>>(i
*8)) & 0x000000FF;
1862 if(fwrite(out
, 1, bytes
, fp
) != bytes
)
1864 fprintf(stderr
, "Error: Bad write to file '%s'.\n", filename
);
1870 // Store the OpenAL Soft HRTF data set.
1871 static int StoreMhr(const HrirDataT
*hData
, const char *filename
)
1873 uint e
, step
, end
, n
, j
, i
;
1877 if((fp
=fopen(filename
, "wb")) == NULL
)
1879 fprintf(stderr
, "Error: Could not open MHR file '%s'.\n", filename
);
1882 if(!WriteAscii(MHR_FORMAT
, fp
, filename
))
1884 if(!WriteBin4(BO_LITTLE
, 4, (uint32
)hData
->mIrRate
, fp
, filename
))
1886 if(!WriteBin4(BO_LITTLE
, 1, (uint32
)hData
->mIrPoints
, fp
, filename
))
1888 if(!WriteBin4(BO_LITTLE
, 1, (uint32
)hData
->mEvCount
, fp
, filename
))
1890 for(e
= 0;e
< hData
->mEvCount
;e
++)
1892 if(!WriteBin4(BO_LITTLE
, 1, (uint32
)hData
->mAzCount
[e
], fp
, filename
))
1895 step
= hData
->mIrSize
;
1896 end
= hData
->mIrCount
* step
;
1897 n
= hData
->mIrPoints
;
1899 for(j
= 0;j
< end
;j
+= step
)
1902 for(i
= 0;i
< n
;i
++)
1904 v
= HpTpdfDither(32767.0 * hData
->mHrirs
[j
+i
], &hpHist
);
1905 if(!WriteBin4(BO_LITTLE
, 2, (uint32
)v
, fp
, filename
))
1909 for(j
= 0;j
< hData
->mIrCount
;j
++)
1911 v
= (int)fmin(round(hData
->mIrRate
* hData
->mHrtds
[j
]), MAX_HRTD
);
1912 if(!WriteBin4(BO_LITTLE
, 1, (uint32
)v
, fp
, filename
))
1920 /***********************
1921 *** HRTF processing ***
1922 ***********************/
1924 // Calculate the onset time of an HRIR and average it with any existing
1925 // timing for its elevation and azimuth.
1926 static void AverageHrirOnset(const double *hrir
, const uint n
, const double f
, const uint ei
, const uint ai
, const HrirDataT
*hData
)
1932 for(i
= 0;i
< n
;i
++)
1933 mag
= fmax(fabs(hrir
[i
]), mag
);
1935 for(i
= 0;i
< n
;i
++)
1937 if(fabs(hrir
[i
]) >= mag
)
1940 j
= hData
->mEvOffset
[ei
] + ai
;
1941 hData
->mHrtds
[j
] = Lerp(hData
->mHrtds
[j
], ((double)i
) / hData
->mIrRate
, f
);
1944 // Calculate the magnitude response of an HRIR and average it with any
1945 // existing responses for its elevation and azimuth.
1946 static void AverageHrirMagnitude(const double *hrir
, const uint npoints
, const double f
, const uint ei
, const uint ai
, const HrirDataT
*hData
)
1951 n
= hData
->mFftSize
;
1952 re
= CreateArray(n
);
1953 im
= CreateArray(n
);
1954 for(i
= 0;i
< npoints
;i
++)
1964 FftForward(n
, re
, im
, re
, im
);
1965 MagnitudeResponse(n
, re
, im
, re
);
1967 j
= (hData
->mEvOffset
[ei
] + ai
) * hData
->mIrSize
;
1968 for(i
= 0;i
< m
;i
++)
1969 hData
->mHrirs
[j
+i
] = Lerp(hData
->mHrirs
[j
+i
], re
[i
], f
);
1974 /* Calculate the contribution of each HRIR to the diffuse-field average based
1975 * on the area of its surface patch. All patches are centered at the HRIR
1976 * coordinates on the unit sphere and are measured by solid angle.
1978 static void CalculateDfWeights(const HrirDataT
*hData
, double *weights
)
1980 double evs
, sum
, ev
, up_ev
, down_ev
, solidAngle
;
1983 evs
= 90.0 / (hData
->mEvCount
- 1);
1985 for(ei
= hData
->mEvStart
;ei
< hData
->mEvCount
;ei
++)
1987 // For each elevation, calculate the upper and lower limits of the
1989 ev
= -90.0 + (ei
* 2.0 * evs
);
1990 if(ei
< (hData
->mEvCount
- 1))
1991 up_ev
= (ev
+ evs
) * M_PI
/ 180.0;
1995 down_ev
= (ev
- evs
) * M_PI
/ 180.0;
1997 down_ev
= -M_PI
/ 2.0;
1998 // Calculate the area of the patch band.
1999 solidAngle
= 2.0 * M_PI
* (sin(up_ev
) - sin(down_ev
));
2000 // Each weight is the area of one patch.
2001 weights
[ei
] = solidAngle
/ hData
->mAzCount
[ei
];
2002 // Sum the total surface area covered by the HRIRs.
2005 // Normalize the weights given the total surface coverage.
2006 for(ei
= hData
->mEvStart
;ei
< hData
->mEvCount
;ei
++)
2010 /* Calculate the diffuse-field average from the given magnitude responses of
2011 * the HRIR set. Weighting can be applied to compensate for the varying
2012 * surface area covered by each HRIR. The final average can then be limited
2013 * by the specified magnitude range (in positive dB; 0.0 to skip).
2015 static void CalculateDiffuseFieldAverage(const HrirDataT
*hData
, const int weighted
, const double limit
, double *dfa
)
2017 uint ei
, ai
, count
, step
, start
, end
, m
, j
, i
;
2020 weights
= CreateArray(hData
->mEvCount
);
2023 // Use coverage weighting to calculate the average.
2024 CalculateDfWeights(hData
, weights
);
2028 // If coverage weighting is not used, the weights still need to be
2029 // averaged by the number of HRIRs.
2031 for(ei
= hData
->mEvStart
;ei
< hData
->mEvCount
;ei
++)
2032 count
+= hData
->mAzCount
[ei
];
2033 for(ei
= hData
->mEvStart
;ei
< hData
->mEvCount
;ei
++)
2034 weights
[ei
] = 1.0 / count
;
2036 ei
= hData
->mEvStart
;
2038 step
= hData
->mIrSize
;
2039 start
= hData
->mEvOffset
[ei
] * step
;
2040 end
= hData
->mIrCount
* step
;
2041 m
= 1 + (hData
->mFftSize
/ 2);
2042 for(i
= 0;i
< m
;i
++)
2044 for(j
= start
;j
< end
;j
+= step
)
2046 // Get the weight for this HRIR's contribution.
2047 double weight
= weights
[ei
];
2048 // Add this HRIR's weighted power average to the total.
2049 for(i
= 0;i
< m
;i
++)
2050 dfa
[i
] += weight
* hData
->mHrirs
[j
+i
] * hData
->mHrirs
[j
+i
];
2051 // Determine the next weight to use.
2053 if(ai
>= hData
->mAzCount
[ei
])
2059 // Finish the average calculation and keep it from being too small.
2060 for(i
= 0;i
< m
;i
++)
2061 dfa
[i
] = fmax(sqrt(dfa
[i
]), EPSILON
);
2062 // Apply a limit to the magnitude range of the diffuse-field average if
2065 LimitMagnitudeResponse(hData
->mFftSize
, limit
, dfa
, dfa
);
2066 DestroyArray(weights
);
2069 // Perform diffuse-field equalization on the magnitude responses of the HRIR
2070 // set using the given average response.
2071 static void DiffuseFieldEqualize(const double *dfa
, const HrirDataT
*hData
)
2073 uint step
, start
, end
, m
, j
, i
;
2075 step
= hData
->mIrSize
;
2076 start
= hData
->mEvOffset
[hData
->mEvStart
] * step
;
2077 end
= hData
->mIrCount
* step
;
2078 m
= 1 + (hData
->mFftSize
/ 2);
2079 for(j
= start
;j
< end
;j
+= step
)
2081 for(i
= 0;i
< m
;i
++)
2082 hData
->mHrirs
[j
+i
] /= dfa
[i
];
2086 // Perform minimum-phase reconstruction using the magnitude responses of the
2088 static void ReconstructHrirs(const HrirDataT
*hData
)
2090 uint step
, start
, end
, n
, j
, i
;
2093 step
= hData
->mIrSize
;
2094 start
= hData
->mEvOffset
[hData
->mEvStart
] * step
;
2095 end
= hData
->mIrCount
* step
;
2096 n
= hData
->mFftSize
;
2097 re
= CreateArray(n
);
2098 im
= CreateArray(n
);
2099 for(j
= start
;j
< end
;j
+= step
)
2101 MinimumPhase(n
, &hData
->mHrirs
[j
], re
, im
);
2102 FftInverse(n
, re
, im
, re
, im
);
2103 for(i
= 0;i
< hData
->mIrPoints
;i
++)
2104 hData
->mHrirs
[j
+i
] = re
[i
];
2110 /* Given an elevation index and an azimuth, calculate the indices of the two
2111 * HRIRs that bound the coordinate along with a factor for calculating the
2112 * continous HRIR using interpolation.
2114 static void CalcAzIndices(const HrirDataT
*hData
, const uint ei
, const double az
, uint
*j0
, uint
*j1
, double *jf
)
2119 af
= ((2.0*M_PI
) + az
) * hData
->mAzCount
[ei
] / (2.0*M_PI
);
2120 ai
= ((uint
)af
) % hData
->mAzCount
[ei
];
2123 *j0
= hData
->mEvOffset
[ei
] + ai
;
2124 *j1
= hData
->mEvOffset
[ei
] + ((ai
+1) % hData
->mAzCount
[ei
]);
2128 // Synthesize any missing onset timings at the bottom elevations. This just
2129 // blends between slightly exaggerated known onsets. Not an accurate model.
2130 static void SynthesizeOnsets(HrirDataT
*hData
)
2132 uint oi
, e
, a
, j0
, j1
;
2135 oi
= hData
->mEvStart
;
2137 for(a
= 0;a
< hData
->mAzCount
[oi
];a
++)
2138 t
+= hData
->mHrtds
[hData
->mEvOffset
[oi
] + a
];
2139 hData
->mHrtds
[0] = 1.32e-4 + (t
/ hData
->mAzCount
[oi
]);
2140 for(e
= 1;e
< hData
->mEvStart
;e
++)
2142 of
= ((double)e
) / hData
->mEvStart
;
2143 for(a
= 0;a
< hData
->mAzCount
[e
];a
++)
2145 CalcAzIndices(hData
, oi
, a
* 2.0 * M_PI
/ hData
->mAzCount
[e
], &j0
, &j1
, &jf
);
2146 hData
->mHrtds
[hData
->mEvOffset
[e
] + a
] = Lerp(hData
->mHrtds
[0], Lerp(hData
->mHrtds
[j0
], hData
->mHrtds
[j1
], jf
), of
);
2151 /* Attempt to synthesize any missing HRIRs at the bottom elevations. Right
2152 * now this just blends the lowest elevation HRIRs together and applies some
2153 * attenuation and high frequency damping. It is a simple, if inaccurate
2156 static void SynthesizeHrirs (HrirDataT
*hData
)
2158 uint oi
, a
, e
, step
, n
, i
, j
;
2159 double lp
[4], s0
, s1
;
2164 if(hData
->mEvStart
<= 0)
2166 step
= hData
->mIrSize
;
2167 oi
= hData
->mEvStart
;
2168 n
= hData
->mIrPoints
;
2169 for(i
= 0;i
< n
;i
++)
2170 hData
->mHrirs
[i
] = 0.0;
2171 for(a
= 0;a
< hData
->mAzCount
[oi
];a
++)
2173 j
= (hData
->mEvOffset
[oi
] + a
) * step
;
2174 for(i
= 0;i
< n
;i
++)
2175 hData
->mHrirs
[i
] += hData
->mHrirs
[j
+i
] / hData
->mAzCount
[oi
];
2177 for(e
= 1;e
< hData
->mEvStart
;e
++)
2179 of
= ((double)e
) / hData
->mEvStart
;
2180 b
= (1.0 - of
) * (3.5e-6 * hData
->mIrRate
);
2181 for(a
= 0;a
< hData
->mAzCount
[e
];a
++)
2183 j
= (hData
->mEvOffset
[e
] + a
) * step
;
2184 CalcAzIndices(hData
, oi
, a
* 2.0 * M_PI
/ hData
->mAzCount
[e
], &j0
, &j1
, &jf
);
2191 for(i
= 0;i
< n
;i
++)
2193 s0
= hData
->mHrirs
[i
];
2194 s1
= Lerp(hData
->mHrirs
[j0
+i
], hData
->mHrirs
[j1
+i
], jf
);
2195 s0
= Lerp(s0
, s1
, of
);
2196 lp
[0] = Lerp(s0
, lp
[0], b
);
2197 lp
[1] = Lerp(lp
[0], lp
[1], b
);
2198 lp
[2] = Lerp(lp
[1], lp
[2], b
);
2199 lp
[3] = Lerp(lp
[2], lp
[3], b
);
2200 hData
->mHrirs
[j
+i
] = lp
[3];
2204 b
= 3.5e-6 * hData
->mIrRate
;
2209 for(i
= 0;i
< n
;i
++)
2211 s0
= hData
->mHrirs
[i
];
2212 lp
[0] = Lerp(s0
, lp
[0], b
);
2213 lp
[1] = Lerp(lp
[0], lp
[1], b
);
2214 lp
[2] = Lerp(lp
[1], lp
[2], b
);
2215 lp
[3] = Lerp(lp
[2], lp
[3], b
);
2216 hData
->mHrirs
[i
] = lp
[3];
2218 hData
->mEvStart
= 0;
2221 // The following routines assume a full set of HRIRs for all elevations.
2223 // Normalize the HRIR set and slightly attenuate the result.
2224 static void NormalizeHrirs (const HrirDataT
*hData
)
2226 uint step
, end
, n
, j
, i
;
2229 step
= hData
->mIrSize
;
2230 end
= hData
->mIrCount
* step
;
2231 n
= hData
->mIrPoints
;
2233 for(j
= 0;j
< end
;j
+= step
)
2235 for(i
= 0;i
< n
;i
++)
2236 maxLevel
= fmax(fabs(hData
->mHrirs
[j
+i
]), maxLevel
);
2238 maxLevel
= 1.01 * maxLevel
;
2239 for(j
= 0;j
< end
;j
+= step
)
2241 for(i
= 0;i
< n
;i
++)
2242 hData
->mHrirs
[j
+i
] /= maxLevel
;
2246 // Calculate the left-ear time delay using a spherical head model.
2247 static double CalcLTD(const double ev
, const double az
, const double rad
, const double dist
)
2249 double azp
, dlp
, l
, al
;
2251 azp
= asin(cos(ev
) * sin(az
));
2252 dlp
= sqrt((dist
*dist
) + (rad
*rad
) + (2.0*dist
*rad
*sin(azp
)));
2253 l
= sqrt((dist
*dist
) - (rad
*rad
));
2254 al
= (0.5 * M_PI
) + azp
;
2256 dlp
= l
+ (rad
* (al
- acos(rad
/ dist
)));
2257 return (dlp
/ 343.3);
2260 // Calculate the effective head-related time delays for each minimum-phase
2262 static void CalculateHrtds (const HeadModelT model
, const double radius
, HrirDataT
*hData
)
2264 double minHrtd
, maxHrtd
;
2270 for(e
= 0;e
< hData
->mEvCount
;e
++)
2272 for(a
= 0;a
< hData
->mAzCount
[e
];a
++)
2274 j
= hData
->mEvOffset
[e
] + a
;
2275 if(model
== HM_DATASET
)
2276 t
= hData
->mHrtds
[j
] * radius
/ hData
->mRadius
;
2278 t
= CalcLTD((-90.0 + (e
* 180.0 / (hData
->mEvCount
- 1))) * M_PI
/ 180.0,
2279 (a
* 360.0 / hData
->mAzCount
[e
]) * M_PI
/ 180.0,
2280 radius
, hData
->mDistance
);
2281 hData
->mHrtds
[j
] = t
;
2282 maxHrtd
= fmax(t
, maxHrtd
);
2283 minHrtd
= fmin(t
, minHrtd
);
2287 for(j
= 0;j
< hData
->mIrCount
;j
++)
2288 hData
->mHrtds
[j
] -= minHrtd
;
2289 hData
->mMaxHrtd
= maxHrtd
;
2293 // Process the data set definition to read and validate the data set metrics.
2294 static int ProcessMetrics(TokenReaderT
*tr
, const uint fftSize
, const uint truncSize
, HrirDataT
*hData
)
2296 int hasRate
= 0, hasPoints
= 0, hasAzimuths
= 0;
2297 int hasRadius
= 0, hasDistance
= 0;
2298 char ident
[MAX_IDENT_LEN
+1];
2304 while(!(hasRate
&& hasPoints
&& hasAzimuths
&& hasRadius
&& hasDistance
))
2306 TrIndication(tr
, & line
, & col
);
2307 if(!TrReadIdent(tr
, MAX_IDENT_LEN
, ident
))
2309 if(strcasecmp(ident
, "rate") == 0)
2313 TrErrorAt(tr
, line
, col
, "Redefinition of 'rate'.\n");
2316 if(!TrReadOperator(tr
, "="))
2318 if(!TrReadInt(tr
, MIN_RATE
, MAX_RATE
, &intVal
))
2320 hData
->mIrRate
= (uint
)intVal
;
2323 else if(strcasecmp(ident
, "points") == 0)
2326 TrErrorAt(tr
, line
, col
, "Redefinition of 'points'.\n");
2329 if(!TrReadOperator(tr
, "="))
2331 TrIndication(tr
, &line
, &col
);
2332 if(!TrReadInt(tr
, MIN_POINTS
, MAX_POINTS
, &intVal
))
2334 points
= (uint
)intVal
;
2335 if(fftSize
> 0 && points
> fftSize
)
2337 TrErrorAt(tr
, line
, col
, "Value exceeds the overridden FFT size.\n");
2340 if(points
< truncSize
)
2342 TrErrorAt(tr
, line
, col
, "Value is below the truncation size.\n");
2345 hData
->mIrPoints
= points
;
2346 hData
->mFftSize
= fftSize
;
2350 while(points
< (4 * hData
->mIrPoints
))
2352 hData
->mFftSize
= points
;
2353 hData
->mIrSize
= 1 + (points
/ 2);
2357 hData
->mFftSize
= fftSize
;
2358 hData
->mIrSize
= 1 + (fftSize
/ 2);
2359 if(points
> hData
->mIrSize
)
2360 hData
->mIrSize
= points
;
2364 else if(strcasecmp(ident
, "azimuths") == 0)
2368 TrErrorAt(tr
, line
, col
, "Redefinition of 'azimuths'.\n");
2371 if(!TrReadOperator(tr
, "="))
2373 hData
->mIrCount
= 0;
2374 hData
->mEvCount
= 0;
2375 hData
->mEvOffset
[0] = 0;
2378 if(!TrReadInt(tr
, MIN_AZ_COUNT
, MAX_AZ_COUNT
, &intVal
))
2380 hData
->mAzCount
[hData
->mEvCount
] = (uint
)intVal
;
2381 hData
->mIrCount
+= (uint
)intVal
;
2383 if(!TrIsOperator(tr
, ","))
2385 if(hData
->mEvCount
>= MAX_EV_COUNT
)
2387 TrError(tr
, "Exceeded the maximum of %d elevations.\n", MAX_EV_COUNT
);
2390 hData
->mEvOffset
[hData
->mEvCount
] = hData
->mEvOffset
[hData
->mEvCount
- 1] + ((uint
)intVal
);
2391 TrReadOperator(tr
, ",");
2393 if(hData
->mEvCount
< MIN_EV_COUNT
)
2395 TrErrorAt(tr
, line
, col
, "Did not reach the minimum of %d azimuth counts.\n", MIN_EV_COUNT
);
2400 else if(strcasecmp(ident
, "radius") == 0)
2404 TrErrorAt(tr
, line
, col
, "Redefinition of 'radius'.\n");
2407 if(!TrReadOperator(tr
, "="))
2409 if(!TrReadFloat(tr
, MIN_RADIUS
, MAX_RADIUS
, &fpVal
))
2411 hData
->mRadius
= fpVal
;
2414 else if(strcasecmp(ident
, "distance") == 0)
2418 TrErrorAt(tr
, line
, col
, "Redefinition of 'distance'.\n");
2421 if(!TrReadOperator(tr
, "="))
2423 if(!TrReadFloat(tr
, MIN_DISTANCE
, MAX_DISTANCE
, & fpVal
))
2425 hData
->mDistance
= fpVal
;
2430 TrErrorAt(tr
, line
, col
, "Expected a metric name.\n");
2433 TrSkipWhitespace (tr
);
2438 // Parse an index pair from the data set definition.
2439 static int ReadIndexPair(TokenReaderT
*tr
, const HrirDataT
*hData
, uint
*ei
, uint
*ai
)
2442 if(!TrReadInt(tr
, 0, (int)hData
->mEvCount
, &intVal
))
2445 if(!TrReadOperator(tr
, ","))
2447 if(!TrReadInt(tr
, 0, (int)hData
->mAzCount
[*ei
], &intVal
))
2453 // Match the source format from a given identifier.
2454 static SourceFormatT
MatchSourceFormat(const char *ident
)
2456 if(strcasecmp(ident
, "wave") == 0)
2458 if(strcasecmp(ident
, "bin_le") == 0)
2460 if(strcasecmp(ident
, "bin_be") == 0)
2462 if(strcasecmp(ident
, "ascii") == 0)
2467 // Match the source element type from a given identifier.
2468 static ElementTypeT
MatchElementType(const char *ident
)
2470 if(strcasecmp(ident
, "int") == 0)
2472 if(strcasecmp(ident
, "fp") == 0)
2477 // Parse and validate a source reference from the data set definition.
2478 static int ReadSourceRef(TokenReaderT
*tr
, SourceRefT
*src
)
2480 char ident
[MAX_IDENT_LEN
+1];
2484 TrIndication(tr
, &line
, &col
);
2485 if(!TrReadIdent(tr
, MAX_IDENT_LEN
, ident
))
2487 src
->mFormat
= MatchSourceFormat(ident
);
2488 if(src
->mFormat
== SF_NONE
)
2490 TrErrorAt(tr
, line
, col
, "Expected a source format.\n");
2493 if(!TrReadOperator(tr
, "("))
2495 if(src
->mFormat
== SF_WAVE
)
2497 if(!TrReadInt(tr
, 0, MAX_WAVE_CHANNELS
, &intVal
))
2499 src
->mType
= ET_NONE
;
2502 src
->mChannel
= (uint
)intVal
;
2507 TrIndication(tr
, &line
, &col
);
2508 if(!TrReadIdent(tr
, MAX_IDENT_LEN
, ident
))
2510 src
->mType
= MatchElementType(ident
);
2511 if(src
->mType
== ET_NONE
)
2513 TrErrorAt(tr
, line
, col
, "Expected a source element type.\n");
2516 if(src
->mFormat
== SF_BIN_LE
|| src
->mFormat
== SF_BIN_BE
)
2518 if(!TrReadOperator(tr
, ","))
2520 if(src
->mType
== ET_INT
)
2522 if(!TrReadInt(tr
, MIN_BIN_SIZE
, MAX_BIN_SIZE
, &intVal
))
2524 src
->mSize
= (uint
)intVal
;
2525 if(!TrIsOperator(tr
, ","))
2526 src
->mBits
= (int)(8*src
->mSize
);
2529 TrReadOperator(tr
, ",");
2530 TrIndication(tr
, &line
, &col
);
2531 if(!TrReadInt(tr
, -2147483647-1, 2147483647, &intVal
))
2533 if(abs(intVal
) < MIN_BIN_BITS
|| ((uint
)abs(intVal
)) > (8*src
->mSize
))
2535 TrErrorAt(tr
, line
, col
, "Expected a value of (+/-) %d to %d.\n", MIN_BIN_BITS
, 8*src
->mSize
);
2538 src
->mBits
= intVal
;
2543 TrIndication(tr
, &line
, &col
);
2544 if(!TrReadInt(tr
, -2147483647-1, 2147483647, &intVal
))
2546 if(intVal
!= 4 && intVal
!= 8)
2548 TrErrorAt(tr
, line
, col
, "Expected a value of 4 or 8.\n");
2551 src
->mSize
= (uint
)intVal
;
2555 else if(src
->mFormat
== SF_ASCII
&& src
->mType
== ET_INT
)
2557 if(!TrReadOperator(tr
, ","))
2559 if(!TrReadInt(tr
, MIN_ASCII_BITS
, MAX_ASCII_BITS
, &intVal
))
2562 src
->mBits
= intVal
;
2570 if(!TrIsOperator(tr
, ";"))
2574 TrReadOperator(tr
, ";");
2575 if(!TrReadInt (tr
, 0, 0x7FFFFFFF, &intVal
))
2577 src
->mSkip
= (uint
)intVal
;
2580 if(!TrReadOperator(tr
, ")"))
2582 if(TrIsOperator(tr
, "@"))
2584 TrReadOperator(tr
, "@");
2585 if(!TrReadInt(tr
, 0, 0x7FFFFFFF, &intVal
))
2587 src
->mOffset
= (uint
)intVal
;
2591 if(!TrReadOperator(tr
, ":"))
2593 if(!TrReadString(tr
, MAX_PATH_LEN
, src
->mPath
))
2598 // Process the list of sources in the data set definition.
2599 static int ProcessSources(const HeadModelT model
, const uint dstRate
, TokenReaderT
*tr
, HrirDataT
*hData
)
2601 uint
*setCount
, *setFlag
;
2602 uint line
, col
, ei
, ai
;
2609 ResamplerSetup(&rs
, hData
->mIrRate
, dstRate
);
2610 /* Scale the number of IR points for resampling. This could be improved by
2611 * also including space for the resampler build-up and fall-off (rs.mL*2),
2612 * instead of clipping them off, but that could affect the HRTDs. It's not
2613 * a big deal to exclude them for sources that aren't already minimum-
2616 res_points
= (uint
)(((uint64
)hData
->mIrPoints
*dstRate
+ hData
->mIrRate
-1) /
2618 /* Clamp to the IR size to prevent overflow, and don't go less than the
2619 * original point count.
2621 if(res_points
> hData
->mIrSize
)
2622 res_points
= hData
->mIrSize
;
2623 else if(res_points
< hData
->mIrPoints
)
2624 res_points
= hData
->mIrPoints
;
2626 setCount
= (uint
*)calloc(hData
->mEvCount
, sizeof(uint
));
2627 setFlag
= (uint
*)calloc(hData
->mIrCount
, sizeof(uint
));
2628 hrir
= CreateArray(res_points
);
2630 while(TrIsOperator(tr
, "["))
2632 TrIndication(tr
, & line
, & col
);
2633 TrReadOperator(tr
, "[");
2634 if(!ReadIndexPair(tr
, hData
, &ei
, &ai
))
2636 if(!TrReadOperator(tr
, "]"))
2638 if(setFlag
[hData
->mEvOffset
[ei
] + ai
])
2640 TrErrorAt(tr
, line
, col
, "Redefinition of source.\n");
2643 if(!TrReadOperator(tr
, "="))
2649 if(!ReadSourceRef(tr
, &src
))
2651 if(!LoadSource(&src
, hData
->mIrRate
, hData
->mIrPoints
, hrir
))
2654 if(hData
->mIrRate
!= dstRate
)
2655 ResamplerRun(&rs
, hData
->mIrPoints
, hrir
,
2658 if(model
== HM_DATASET
)
2659 AverageHrirOnset(hrir
, res_points
, 1.0 / factor
, ei
, ai
, hData
);
2660 AverageHrirMagnitude(hrir
, res_points
, 1.0 / factor
, ei
, ai
, hData
);
2662 if(!TrIsOperator(tr
, "+"))
2664 TrReadOperator(tr
, "+");
2666 setFlag
[hData
->mEvOffset
[ei
] + ai
] = 1;
2669 hData
->mIrPoints
= res_points
;
2670 hData
->mIrRate
= dstRate
;
2673 while(ei
< hData
->mEvCount
&& setCount
[ei
] < 1)
2675 if(ei
< hData
->mEvCount
)
2677 hData
->mEvStart
= ei
;
2678 while(ei
< hData
->mEvCount
&& setCount
[ei
] == hData
->mAzCount
[ei
])
2680 if(ei
>= hData
->mEvCount
)
2684 ResamplerClear(&rs
);
2690 TrError(tr
, "Errant data at end of source list.\n");
2693 TrError(tr
, "Missing sources for elevation index %d.\n", ei
);
2696 TrError(tr
, "Missing source references.\n");
2699 ResamplerClear(&rs
);
2706 /* Parse the data set definition and process the source data, storing the
2707 * resulting data set as desired. If the input name is NULL it will read
2708 * from standard input.
2710 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
)
2712 char rateStr
[8+1], expName
[MAX_PATH_LEN
];
2719 hData
.mIrPoints
= 0;
2725 hData
.mDistance
= 0;
2726 fprintf(stdout
, "Reading HRIR definition...\n");
2729 fp
= fopen(inName
, "r");
2732 fprintf(stderr
, "Error: Could not open definition file '%s'\n", inName
);
2735 TrSetup(fp
, inName
, &tr
);
2740 TrSetup(fp
, "<stdin>", &tr
);
2742 if(!ProcessMetrics(&tr
, fftSize
, truncSize
, &hData
))
2748 hData
.mHrirs
= CreateArray(hData
.mIrCount
* hData
.mIrSize
);
2749 hData
.mHrtds
= CreateArray(hData
.mIrCount
);
2750 if(!ProcessSources(model
, outRate
? outRate
: hData
.mIrRate
, &tr
, &hData
))
2752 DestroyArray(hData
.mHrtds
);
2753 DestroyArray(hData
.mHrirs
);
2762 dfa
= CreateArray(1 + (hData
.mFftSize
/2));
2763 fprintf(stdout
, "Calculating diffuse-field average...\n");
2764 CalculateDiffuseFieldAverage(&hData
, surface
, limit
, dfa
);
2765 fprintf(stdout
, "Performing diffuse-field equalization...\n");
2766 DiffuseFieldEqualize(dfa
, &hData
);
2769 fprintf(stdout
, "Performing minimum phase reconstruction...\n");
2770 ReconstructHrirs(&hData
);
2771 fprintf(stdout
, "Truncating minimum-phase HRIRs...\n");
2772 hData
.mIrPoints
= truncSize
;
2773 fprintf(stdout
, "Synthesizing missing elevations...\n");
2774 if(model
== HM_DATASET
)
2775 SynthesizeOnsets(&hData
);
2776 SynthesizeHrirs(&hData
);
2777 fprintf(stdout
, "Normalizing final HRIRs...\n");
2778 NormalizeHrirs(&hData
);
2779 fprintf(stdout
, "Calculating impulse delays...\n");
2780 CalculateHrtds(model
, (radius
> DEFAULT_CUSTOM_RADIUS
) ? radius
: hData
.mRadius
, &hData
);
2781 snprintf(rateStr
, 8, "%u", hData
.mIrRate
);
2782 StrSubst(outName
, "%r", rateStr
, MAX_PATH_LEN
, expName
);
2786 fprintf(stdout
, "Creating MHR data set file...\n");
2787 if(!StoreMhr(&hData
, expName
))
2789 DestroyArray(hData
.mHrtds
);
2790 DestroyArray(hData
.mHrirs
);
2797 DestroyArray(hData
.mHrtds
);
2798 DestroyArray(hData
.mHrirs
);
2802 static void PrintHelp(const char *argv0
, FILE *ofile
)
2804 fprintf(ofile
, "Usage: %s <command> [<option>...]\n\n", argv0
);
2805 fprintf(ofile
, "Commands:\n");
2806 fprintf(ofile
, " -m, --make-mhr Makes an OpenAL Soft compatible HRTF data set.\n");
2807 fprintf(ofile
, " Defaults output to: ./oalsoft_hrtf_%%r.mhr\n");
2808 fprintf(ofile
, " -h, --help Displays this help information.\n\n");
2809 fprintf(ofile
, "Options:\n");
2810 fprintf(ofile
, " -r=<rate> Change the data set sample rate to the specified value and\n");
2811 fprintf(ofile
, " resample the HRIRs accordingly.\n");
2812 fprintf(ofile
, " -f=<points> Override the FFT window size (defaults to the first power-\n");
2813 fprintf(ofile
, " of-two that fits four times the number of HRIR points).\n");
2814 fprintf(ofile
, " -e={on|off} Toggle diffuse-field equalization (default: %s).\n", (DEFAULT_EQUALIZE
? "on" : "off"));
2815 fprintf(ofile
, " -s={on|off} Toggle surface-weighted diffuse-field average (default: %s).\n", (DEFAULT_SURFACE
? "on" : "off"));
2816 fprintf(ofile
, " -l={<dB>|none} Specify a limit to the magnitude range of the diffuse-field\n");
2817 fprintf(ofile
, " average (default: %.2f).\n", DEFAULT_LIMIT
);
2818 fprintf(ofile
, " -w=<points> Specify the size of the truncation window that's applied\n");
2819 fprintf(ofile
, " after minimum-phase reconstruction (default: %u).\n", DEFAULT_TRUNCSIZE
);
2820 fprintf(ofile
, " -d={dataset| Specify the model used for calculating the head-delay timing\n");
2821 fprintf(ofile
, " sphere} values (default: %s).\n", ((DEFAULT_HEAD_MODEL
== HM_DATASET
) ? "dataset" : "sphere"));
2822 fprintf(ofile
, " -c=<size> Use a customized head radius measured ear-to-ear in meters.\n");
2823 fprintf(ofile
, " -i=<filename> Specify an HRIR definition file to use (defaults to stdin).\n");
2824 fprintf(ofile
, " -o=<filename> Specify an output file. Overrides command-selected default.\n");
2825 fprintf(ofile
, " Use of '%%r' will be substituted with the data set sample rate.\n");
2828 // Standard command line dispatch.
2829 int main(const int argc
, const char *argv
[])
2831 const char *inName
= NULL
, *outName
= NULL
;
2832 OutputFormatT outFormat
;
2833 uint outRate
, fftSize
;
2834 int equalize
, surface
;
2842 if(argc
< 2 || strcmp(argv
[1], "--help") == 0 || strcmp(argv
[1], "-h") == 0)
2844 fprintf(stdout
, "HRTF Processing and Composition Utility\n\n");
2845 PrintHelp(argv
[0], stdout
);
2849 if(strcmp(argv
[1], "--make-mhr") == 0 || strcmp(argv
[1], "-m") == 0)
2851 outName
= "./oalsoft_hrtf_%r.mhr";
2856 fprintf(stderr
, "Error: Invalid command '%s'.\n\n", argv
[1]);
2857 PrintHelp(argv
[0], stderr
);
2863 equalize
= DEFAULT_EQUALIZE
;
2864 surface
= DEFAULT_SURFACE
;
2865 limit
= DEFAULT_LIMIT
;
2866 truncSize
= DEFAULT_TRUNCSIZE
;
2867 model
= DEFAULT_HEAD_MODEL
;
2868 radius
= DEFAULT_CUSTOM_RADIUS
;
2873 if(strncmp(argv
[argi
], "-r=", 3) == 0)
2875 outRate
= strtoul(&argv
[argi
][3], &end
, 10);
2876 if(end
[0] != '\0' || outRate
< MIN_RATE
|| outRate
> MAX_RATE
)
2878 fprintf(stderr
, "Error: Expected a value from %u to %u for '-r'.\n", MIN_RATE
, MAX_RATE
);
2882 else if(strncmp(argv
[argi
], "-f=", 3) == 0)
2884 fftSize
= strtoul(&argv
[argi
][3], &end
, 10);
2885 if(end
[0] != '\0' || (fftSize
&(fftSize
-1)) || fftSize
< MIN_FFTSIZE
|| fftSize
> MAX_FFTSIZE
)
2887 fprintf(stderr
, "Error: Expected a power-of-two value from %u to %u for '-f'.\n", MIN_FFTSIZE
, MAX_FFTSIZE
);
2891 else if(strncmp(argv
[argi
], "-e=", 3) == 0)
2893 if(strcmp(&argv
[argi
][3], "on") == 0)
2895 else if(strcmp(&argv
[argi
][3], "off") == 0)
2899 fprintf(stderr
, "Error: Expected 'on' or 'off' for '-e'.\n");
2903 else if(strncmp(argv
[argi
], "-s=", 3) == 0)
2905 if(strcmp(&argv
[argi
][3], "on") == 0)
2907 else if(strcmp(&argv
[argi
][3], "off") == 0)
2911 fprintf(stderr
, "Error: Expected 'on' or 'off' for '-s'.\n");
2915 else if(strncmp(argv
[argi
], "-l=", 3) == 0)
2917 if(strcmp(&argv
[argi
][3], "none") == 0)
2921 limit
= strtod(&argv
[argi
] [3], &end
);
2922 if(end
[0] != '\0' || limit
< MIN_LIMIT
|| limit
> MAX_LIMIT
)
2924 fprintf(stderr
, "Error: Expected 'none' or a value from %.2f to %.2f for '-l'.\n", MIN_LIMIT
, MAX_LIMIT
);
2929 else if(strncmp(argv
[argi
], "-w=", 3) == 0)
2931 truncSize
= strtoul(&argv
[argi
][3], &end
, 10);
2932 if(end
[0] != '\0' || truncSize
< MIN_TRUNCSIZE
|| truncSize
> MAX_TRUNCSIZE
|| (truncSize
%MOD_TRUNCSIZE
))
2934 fprintf(stderr
, "Error: Expected a value from %u to %u in multiples of %u for '-w'.\n", MIN_TRUNCSIZE
, MAX_TRUNCSIZE
, MOD_TRUNCSIZE
);
2938 else if(strncmp(argv
[argi
], "-d=", 3) == 0)
2940 if(strcmp(&argv
[argi
][3], "dataset") == 0)
2942 else if(strcmp(&argv
[argi
][3], "sphere") == 0)
2946 fprintf(stderr
, "Error: Expected 'dataset' or 'sphere' for '-d'.\n");
2950 else if(strncmp(argv
[argi
], "-c=", 3) == 0)
2952 radius
= strtod(&argv
[argi
][3], &end
);
2953 if(end
[0] != '\0' || radius
< MIN_CUSTOM_RADIUS
|| radius
> MAX_CUSTOM_RADIUS
)
2955 fprintf(stderr
, "Error: Expected a value from %.2f to %.2f for '-c'.\n", MIN_CUSTOM_RADIUS
, MAX_CUSTOM_RADIUS
);
2959 else if(strncmp(argv
[argi
], "-i=", 3) == 0)
2960 inName
= &argv
[argi
][3];
2961 else if(strncmp(argv
[argi
], "-o=", 3) == 0)
2962 outName
= &argv
[argi
][3];
2965 fprintf(stderr
, "Error: Invalid option '%s'.\n", argv
[argi
]);
2970 if(!ProcessDefinition(inName
, outRate
, fftSize
, equalize
, surface
, limit
, truncSize
, model
, radius
, outFormat
, outName
))
2972 fprintf(stdout
, "Operation completed.\n");