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
81 #include "win_main_utf8.h"
83 /* Define int64_t and uint64_t types */
84 #if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
86 #elif defined(_WIN32) && defined(__GNUC__)
89 typedef __int64
int64_t;
90 typedef unsigned __int64
uint64_t;
92 /* Fallback if nothing above works */
97 #define M_PI (3.14159265358979323846)
101 #define HUGE_VAL (1.0 / 0.0)
105 // The epsilon used to maintain signal stability.
106 #define EPSILON (1e-9)
108 // Constants for accessing the token reader's ring buffer.
109 #define TR_RING_BITS (16)
110 #define TR_RING_SIZE (1 << TR_RING_BITS)
111 #define TR_RING_MASK (TR_RING_SIZE - 1)
113 // The token reader's load interval in bytes.
114 #define TR_LOAD_SIZE (TR_RING_SIZE >> 2)
116 // The maximum identifier length used when processing the data set
118 #define MAX_IDENT_LEN (16)
120 // The maximum path length used when processing filenames.
121 #define MAX_PATH_LEN (256)
123 // The limits for the sample 'rate' metric in the data set definition and for
125 #define MIN_RATE (32000)
126 #define MAX_RATE (96000)
128 // The limits for the HRIR 'points' metric in the data set definition.
129 #define MIN_POINTS (16)
130 #define MAX_POINTS (8192)
132 // The limit to the number of 'distances' listed in the data set definition.
133 #define MAX_FD_COUNT (16)
135 // The limits to the number of 'azimuths' listed in the data set definition.
136 #define MIN_EV_COUNT (5)
137 #define MAX_EV_COUNT (128)
139 // The limits for each of the 'azimuths' listed in the data set definition.
140 #define MIN_AZ_COUNT (1)
141 #define MAX_AZ_COUNT (128)
143 // The limits for the listener's head 'radius' in the data set definition.
144 #define MIN_RADIUS (0.05)
145 #define MAX_RADIUS (0.15)
147 // The limits for the 'distance' from source to listener for each field in
148 // the definition file.
149 #define MIN_DISTANCE (0.05)
150 #define MAX_DISTANCE (2.50)
152 // The maximum number of channels that can be addressed for a WAVE file
153 // source listed in the data set definition.
154 #define MAX_WAVE_CHANNELS (65535)
156 // The limits to the byte size for a binary source listed in the definition
158 #define MIN_BIN_SIZE (2)
159 #define MAX_BIN_SIZE (4)
161 // The minimum number of significant bits for binary sources listed in the
162 // data set definition. The maximum is calculated from the byte size.
163 #define MIN_BIN_BITS (16)
165 // The limits to the number of significant bits for an ASCII source listed in
166 // the data set definition.
167 #define MIN_ASCII_BITS (16)
168 #define MAX_ASCII_BITS (32)
170 // The limits to the FFT window size override on the command line.
171 #define MIN_FFTSIZE (65536)
172 #define MAX_FFTSIZE (131072)
174 // The limits to the equalization range limit on the command line.
175 #define MIN_LIMIT (2.0)
176 #define MAX_LIMIT (120.0)
178 // The limits to the truncation window size on the command line.
179 #define MIN_TRUNCSIZE (16)
180 #define MAX_TRUNCSIZE (512)
182 // The limits to the custom head radius on the command line.
183 #define MIN_CUSTOM_RADIUS (0.05)
184 #define MAX_CUSTOM_RADIUS (0.15)
186 // The truncation window size must be a multiple of the below value to allow
187 // for vectorized convolution.
188 #define MOD_TRUNCSIZE (8)
190 // The defaults for the command line options.
191 #define DEFAULT_FFTSIZE (65536)
192 #define DEFAULT_EQUALIZE (1)
193 #define DEFAULT_SURFACE (1)
194 #define DEFAULT_LIMIT (24.0)
195 #define DEFAULT_TRUNCSIZE (32)
196 #define DEFAULT_HEAD_MODEL (HM_DATASET)
197 #define DEFAULT_CUSTOM_RADIUS (0.0)
199 // The four-character-codes for RIFF/RIFX WAVE file chunks.
200 #define FOURCC_RIFF (0x46464952) // 'RIFF'
201 #define FOURCC_RIFX (0x58464952) // 'RIFX'
202 #define FOURCC_WAVE (0x45564157) // 'WAVE'
203 #define FOURCC_FMT (0x20746D66) // 'fmt '
204 #define FOURCC_DATA (0x61746164) // 'data'
205 #define FOURCC_LIST (0x5453494C) // 'LIST'
206 #define FOURCC_WAVL (0x6C766177) // 'wavl'
207 #define FOURCC_SLNT (0x746E6C73) // 'slnt'
209 // The supported wave formats.
210 #define WAVE_FORMAT_PCM (0x0001)
211 #define WAVE_FORMAT_IEEE_FLOAT (0x0003)
212 #define WAVE_FORMAT_EXTENSIBLE (0xFFFE)
214 // The maximum propagation delay value supported by OpenAL Soft.
215 #define MAX_HRTD (63.0)
217 // The OpenAL Soft HRTF format marker. It stands for minimum-phase head
218 // response protocol 02.
219 #define MHR_FORMAT ("MinPHR02")
221 // Sample and channel type enum values.
222 typedef enum SampleTypeT
{
227 // Certain iterations rely on these integer enum values.
228 typedef enum ChannelTypeT
{
234 // Byte order for the serialization routines.
235 typedef enum ByteOrderT
{
241 // Source format for the references listed in the data set definition.
242 typedef enum SourceFormatT
{
244 SF_WAVE
, // RIFF/RIFX WAVE file.
245 SF_BIN_LE
, // Little-endian binary file.
246 SF_BIN_BE
, // Big-endian binary file.
247 SF_ASCII
// ASCII text file.
250 // Element types for the references listed in the data set definition.
251 typedef enum ElementTypeT
{
253 ET_INT
, // Integer elements.
254 ET_FP
// Floating-point elements.
257 // Head model used for calculating the impulse delays.
258 typedef enum HeadModelT
{
260 HM_DATASET
, // Measure the onset from the dataset.
261 HM_SPHERE
// Calculate the onset using a spherical head model.
264 // Unsigned integer type.
265 typedef unsigned int uint
;
267 // Serialization types. The trailing digit indicates the number of bits.
268 typedef unsigned char uint8
;
270 typedef unsigned int uint32
;
271 typedef uint64_t uint64
;
273 // Token reader state for parsing the data set definition.
274 typedef struct TokenReaderT
{
279 char mRing
[TR_RING_SIZE
];
284 // Source reference state used when loading sources.
285 typedef struct SourceRefT
{
286 SourceFormatT mFormat
;
293 char mPath
[MAX_PATH_LEN
+1];
296 // Structured HRIR storage for stereo azimuth pairs, elevations, and fields.
297 typedef struct HrirAzT
{
304 typedef struct HrirEvT
{
311 typedef struct HrirFdT
{
319 // The HRIR metrics and data set used when loading, processing, and storing
320 // the resulting HRTF.
321 typedef struct HrirDataT
{
323 SampleTypeT mSampleType
;
324 ChannelTypeT mChannelType
;
334 // The resampler metrics and FIR filter.
335 typedef struct ResamplerT
{
341 /****************************************
342 *** Complex number type and routines ***
343 ****************************************/
349 static Complex
MakeComplex(double r
, double i
)
351 Complex c
= { r
, i
};
355 static Complex
c_add(Complex a
, Complex b
)
358 r
.Real
= a
.Real
+ b
.Real
;
359 r
.Imag
= a
.Imag
+ b
.Imag
;
363 static Complex
c_sub(Complex a
, Complex b
)
366 r
.Real
= a
.Real
- b
.Real
;
367 r
.Imag
= a
.Imag
- b
.Imag
;
371 static Complex
c_mul(Complex a
, Complex b
)
374 r
.Real
= a
.Real
*b
.Real
- a
.Imag
*b
.Imag
;
375 r
.Imag
= a
.Imag
*b
.Real
+ a
.Real
*b
.Imag
;
379 static Complex
c_muls(Complex a
, double s
)
387 static double c_abs(Complex a
)
389 return sqrt(a
.Real
*a
.Real
+ a
.Imag
*a
.Imag
);
392 static Complex
c_exp(Complex a
)
395 double e
= exp(a
.Real
);
396 r
.Real
= e
* cos(a
.Imag
);
397 r
.Imag
= e
* sin(a
.Imag
);
401 /*****************************
402 *** Token reader routines ***
403 *****************************/
405 /* Whitespace is not significant. It can process tokens as identifiers, numbers
406 * (integer and floating-point), strings, and operators. Strings must be
407 * encapsulated by double-quotes and cannot span multiple lines.
410 // Setup the reader on the given file. The filename can be NULL if no error
411 // output is desired.
412 static void TrSetup(FILE *fp
, const char *filename
, TokenReaderT
*tr
)
414 const char *name
= NULL
;
418 const char *slash
= strrchr(filename
, '/');
421 const char *bslash
= strrchr(slash
+1, '\\');
422 if(bslash
) name
= bslash
+1;
427 const char *bslash
= strrchr(filename
, '\\');
428 if(bslash
) name
= bslash
+1;
429 else name
= filename
;
441 // Prime the reader's ring buffer, and return a result indicating that there
442 // is text to process.
443 static int TrLoad(TokenReaderT
*tr
)
445 size_t toLoad
, in
, count
;
447 toLoad
= TR_RING_SIZE
- (tr
->mIn
- tr
->mOut
);
448 if(toLoad
>= TR_LOAD_SIZE
&& !feof(tr
->mFile
))
450 // Load TR_LOAD_SIZE (or less if at the end of the file) per read.
451 toLoad
= TR_LOAD_SIZE
;
452 in
= tr
->mIn
&TR_RING_MASK
;
453 count
= TR_RING_SIZE
- in
;
456 tr
->mIn
+= fread(&tr
->mRing
[in
], 1, count
, tr
->mFile
);
457 tr
->mIn
+= fread(&tr
->mRing
[0], 1, toLoad
-count
, tr
->mFile
);
460 tr
->mIn
+= fread(&tr
->mRing
[in
], 1, toLoad
, tr
->mFile
);
462 if(tr
->mOut
>= TR_RING_SIZE
)
464 tr
->mOut
-= TR_RING_SIZE
;
465 tr
->mIn
-= TR_RING_SIZE
;
468 if(tr
->mIn
> tr
->mOut
)
473 // Error display routine. Only displays when the base name is not NULL.
474 static void TrErrorVA(const TokenReaderT
*tr
, uint line
, uint column
, const char *format
, va_list argPtr
)
478 fprintf(stderr
, "Error (%s:%u:%u): ", tr
->mName
, line
, column
);
479 vfprintf(stderr
, format
, argPtr
);
482 // Used to display an error at a saved line/column.
483 static void TrErrorAt(const TokenReaderT
*tr
, uint line
, uint column
, const char *format
, ...)
487 va_start(argPtr
, format
);
488 TrErrorVA(tr
, line
, column
, format
, argPtr
);
492 // Used to display an error at the current line/column.
493 static void TrError(const TokenReaderT
*tr
, const char *format
, ...)
497 va_start(argPtr
, format
);
498 TrErrorVA(tr
, tr
->mLine
, tr
->mColumn
, format
, argPtr
);
502 // Skips to the next line.
503 static void TrSkipLine(TokenReaderT
*tr
)
509 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
521 // Skips to the next token.
522 static int TrSkipWhitespace(TokenReaderT
*tr
)
528 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
548 // Get the line and/or column of the next token (or the end of input).
549 static void TrIndication(TokenReaderT
*tr
, uint
*line
, uint
*column
)
551 TrSkipWhitespace(tr
);
552 if(line
) *line
= tr
->mLine
;
553 if(column
) *column
= tr
->mColumn
;
556 // Checks to see if a token is (likely to be) an identifier. It does not
557 // display any errors and will not proceed to the next token.
558 static int TrIsIdent(TokenReaderT
*tr
)
562 if(!TrSkipWhitespace(tr
))
564 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
565 return ch
== '_' || isalpha(ch
);
569 // Checks to see if a token is the given operator. It does not display any
570 // errors and will not proceed to the next token.
571 static int TrIsOperator(TokenReaderT
*tr
, const char *op
)
576 if(!TrSkipWhitespace(tr
))
580 while(op
[len
] != '\0' && out
< tr
->mIn
)
582 ch
= tr
->mRing
[out
&TR_RING_MASK
];
583 if(ch
!= op
[len
]) break;
592 /* The TrRead*() routines obtain the value of a matching token type. They
593 * display type, form, and boundary errors and will proceed to the next
597 // Reads and validates an identifier token.
598 static int TrReadIdent(TokenReaderT
*tr
, const uint maxLen
, char *ident
)
604 if(TrSkipWhitespace(tr
))
607 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
608 if(ch
== '_' || isalpha(ch
))
618 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
619 } while(ch
== '_' || isdigit(ch
) || isalpha(ch
));
627 TrErrorAt(tr
, tr
->mLine
, col
, "Identifier is too long.\n");
631 TrErrorAt(tr
, tr
->mLine
, col
, "Expected an identifier.\n");
635 // Reads and validates (including bounds) an integer token.
636 static int TrReadInt(TokenReaderT
*tr
, const int loBound
, const int hiBound
, int *value
)
638 uint col
, digis
, len
;
642 if(TrSkipWhitespace(tr
))
646 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
647 if(ch
== '+' || ch
== '-')
656 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
657 if(!isdigit(ch
)) break;
665 if(digis
> 0 && ch
!= '.' && !isalpha(ch
))
669 TrErrorAt(tr
, tr
->mLine
, col
, "Integer is too long.");
673 *value
= strtol(temp
, NULL
, 10);
674 if(*value
< loBound
|| *value
> hiBound
)
676 TrErrorAt(tr
, tr
->mLine
, col
, "Expected a value from %d to %d.\n", loBound
, hiBound
);
682 TrErrorAt(tr
, tr
->mLine
, col
, "Expected an integer.\n");
686 // Reads and validates (including bounds) a float token.
687 static int TrReadFloat(TokenReaderT
*tr
, const double loBound
, const double hiBound
, double *value
)
689 uint col
, digis
, len
;
693 if(TrSkipWhitespace(tr
))
697 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
698 if(ch
== '+' || ch
== '-')
708 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
709 if(!isdigit(ch
)) break;
725 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
726 if(!isdigit(ch
)) break;
735 if(ch
== 'E' || ch
== 'e')
742 if(ch
== '+' || ch
== '-')
751 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
752 if(!isdigit(ch
)) break;
761 if(digis
> 0 && ch
!= '.' && !isalpha(ch
))
765 TrErrorAt(tr
, tr
->mLine
, col
, "Float is too long.");
769 *value
= strtod(temp
, NULL
);
770 if(*value
< loBound
|| *value
> hiBound
)
772 TrErrorAt(tr
, tr
->mLine
, col
, "Expected a value from %f to %f.\n", loBound
, hiBound
);
781 TrErrorAt(tr
, tr
->mLine
, col
, "Expected a float.\n");
785 // Reads and validates a string token.
786 static int TrReadString(TokenReaderT
*tr
, const uint maxLen
, char *text
)
792 if(TrSkipWhitespace(tr
))
795 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
802 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
808 TrErrorAt(tr
, tr
->mLine
, col
, "Unterminated string at end of line.\n");
817 tr
->mColumn
+= 1 + len
;
818 TrErrorAt(tr
, tr
->mLine
, col
, "Unterminated string at end of input.\n");
821 tr
->mColumn
+= 2 + len
;
824 TrErrorAt(tr
, tr
->mLine
, col
, "String is too long.\n");
831 TrErrorAt(tr
, tr
->mLine
, col
, "Expected a string.\n");
835 // Reads and validates the given operator.
836 static int TrReadOperator(TokenReaderT
*tr
, const char *op
)
842 if(TrSkipWhitespace(tr
))
846 while(op
[len
] != '\0' && TrLoad(tr
))
848 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
849 if(ch
!= op
[len
]) break;
857 TrErrorAt(tr
, tr
->mLine
, col
, "Expected '%s' operator.\n", op
);
861 /* Performs a string substitution. Any case-insensitive occurrences of the
862 * pattern string are replaced with the replacement string. The result is
863 * truncated if necessary.
865 static int StrSubst(const char *in
, const char *pat
, const char *rep
, const size_t maxLen
, char *out
)
867 size_t inLen
, patLen
, repLen
;
872 patLen
= strlen(pat
);
873 repLen
= strlen(rep
);
877 while(si
< inLen
&& di
< maxLen
)
879 if(patLen
<= inLen
-si
)
881 if(strncasecmp(&in
[si
], pat
, patLen
) == 0)
883 if(repLen
> maxLen
-di
)
885 repLen
= maxLen
- di
;
888 strncpy(&out
[di
], rep
, repLen
);
904 /*********************
905 *** Math routines ***
906 *********************/
908 // Provide missing math routines for MSVC versions < 1800 (Visual Studio 2013).
909 #if defined(_MSC_VER) && _MSC_VER < 1800
910 static double round(double val
)
913 return ceil(val
-0.5);
914 return floor(val
+0.5);
917 static double fmin(double a
, double b
)
919 return (a
<b
) ? a
: b
;
922 static double fmax(double a
, double b
)
924 return (a
>b
) ? a
: b
;
928 // Simple clamp routine.
929 static double Clamp(const double val
, const double lower
, const double upper
)
931 return fmin(fmax(val
, lower
), upper
);
934 // Performs linear interpolation.
935 static double Lerp(const double a
, const double b
, const double f
)
937 return a
+ f
* (b
- a
);
940 static inline uint
dither_rng(uint
*seed
)
942 *seed
= *seed
* 96314165 + 907633515;
946 // Performs a triangular probability density function dither. The input samples
947 // should be normalized (-1 to +1).
948 static void TpdfDither(double *restrict out
, const double *restrict in
, const double scale
,
949 const int count
, const int step
, uint
*seed
)
951 static const double PRNG_SCALE
= 1.0 / UINT_MAX
;
955 for(i
= 0;i
< count
;i
++)
957 prn0
= dither_rng(seed
);
958 prn1
= dither_rng(seed
);
959 out
[i
*step
] = round(in
[i
]*scale
+ (prn0
*PRNG_SCALE
- prn1
*PRNG_SCALE
));
963 // Allocates an array of doubles.
964 static double *CreateDoubles(size_t n
)
968 a
= calloc(n
?n
:1, sizeof(*a
));
971 fprintf(stderr
, "Error: Out of memory.\n");
977 // Allocates an array of complex numbers.
978 static Complex
*CreateComplexes(size_t n
)
982 a
= calloc(n
?n
:1, sizeof(*a
));
985 fprintf(stderr
, "Error: Out of memory.\n");
991 /* Fast Fourier transform routines. The number of points must be a power of
995 // Performs bit-reversal ordering.
996 static void FftArrange(const uint n
, Complex
*inout
)
1000 // Handle in-place arrangement.
1002 for(k
= 0;k
< n
;k
++)
1006 Complex temp
= inout
[rk
];
1007 inout
[rk
] = inout
[k
];
1018 // Performs the summation.
1019 static void FftSummation(const int n
, const double s
, Complex
*cplx
)
1026 for(m
= 1, m2
= 2;m
< n
; m
<<= 1, m2
<<= 1)
1028 // v = Complex (-2.0 * sin (0.5 * pi / m) * sin (0.5 * pi / m), -sin (pi / m))
1029 double sm
= sin(0.5 * pi
/ m
);
1030 Complex v
= MakeComplex(-2.0*sm
*sm
, -sin(pi
/ m
));
1031 Complex w
= MakeComplex(1.0, 0.0);
1032 for(i
= 0;i
< m
;i
++)
1034 for(k
= i
;k
< n
;k
+= m2
)
1038 t
= c_mul(w
, cplx
[mk
]);
1039 cplx
[mk
] = c_sub(cplx
[k
], t
);
1040 cplx
[k
] = c_add(cplx
[k
], t
);
1042 w
= c_add(w
, c_mul(v
, w
));
1047 // Performs a forward FFT.
1048 static void FftForward(const uint n
, Complex
*inout
)
1050 FftArrange(n
, inout
);
1051 FftSummation(n
, 1.0, inout
);
1054 // Performs an inverse FFT.
1055 static void FftInverse(const uint n
, Complex
*inout
)
1060 FftArrange(n
, inout
);
1061 FftSummation(n
, -1.0, inout
);
1063 for(i
= 0;i
< n
;i
++)
1064 inout
[i
] = c_muls(inout
[i
], f
);
1067 /* Calculate the complex helical sequence (or discrete-time analytical signal)
1068 * of the given input using the Hilbert transform. Given the natural logarithm
1069 * of a signal's magnitude response, the imaginary components can be used as
1070 * the angles for minimum-phase reconstruction.
1072 static void Hilbert(const uint n
, Complex
*inout
)
1076 // Handle in-place operation.
1077 for(i
= 0;i
< n
;i
++)
1078 inout
[i
].Imag
= 0.0;
1080 FftInverse(n
, inout
);
1081 for(i
= 1;i
< (n
+1)/2;i
++)
1082 inout
[i
] = c_muls(inout
[i
], 2.0);
1083 /* Increment i if n is even. */
1086 inout
[i
] = MakeComplex(0.0, 0.0);
1087 FftForward(n
, inout
);
1090 /* Calculate the magnitude response of the given input. This is used in
1091 * place of phase decomposition, since the phase residuals are discarded for
1092 * minimum phase reconstruction. The mirrored half of the response is also
1095 static void MagnitudeResponse(const uint n
, const Complex
*in
, double *out
)
1097 const uint m
= 1 + (n
/ 2);
1099 for(i
= 0;i
< m
;i
++)
1100 out
[i
] = fmax(c_abs(in
[i
]), EPSILON
);
1103 /* Apply a range limit (in dB) to the given magnitude response. This is used
1104 * to adjust the effects of the diffuse-field average on the equalization
1107 static void LimitMagnitudeResponse(const uint n
, const uint m
, const double limit
, const double *in
, double *out
)
1110 uint i
, lower
, upper
;
1113 halfLim
= limit
/ 2.0;
1114 // Convert the response to dB.
1115 for(i
= 0;i
< m
;i
++)
1116 out
[i
] = 20.0 * log10(in
[i
]);
1117 // Use six octaves to calculate the average magnitude of the signal.
1118 lower
= ((uint
)ceil(n
/ pow(2.0, 8.0))) - 1;
1119 upper
= ((uint
)floor(n
/ pow(2.0, 2.0))) - 1;
1121 for(i
= lower
;i
<= upper
;i
++)
1123 ave
/= upper
- lower
+ 1;
1124 // Keep the response within range of the average magnitude.
1125 for(i
= 0;i
< m
;i
++)
1126 out
[i
] = Clamp(out
[i
], ave
- halfLim
, ave
+ halfLim
);
1127 // Convert the response back to linear magnitude.
1128 for(i
= 0;i
< m
;i
++)
1129 out
[i
] = pow(10.0, out
[i
] / 20.0);
1132 /* Reconstructs the minimum-phase component for the given magnitude response
1133 * of a signal. This is equivalent to phase recomposition, sans the missing
1134 * residuals (which were discarded). The mirrored half of the response is
1137 static void MinimumPhase(const uint n
, const double *in
, Complex
*out
)
1139 const uint m
= 1 + (n
/ 2);
1143 mags
= CreateDoubles(n
);
1144 for(i
= 0;i
< m
;i
++)
1146 mags
[i
] = fmax(EPSILON
, in
[i
]);
1147 out
[i
] = MakeComplex(log(mags
[i
]), 0.0);
1151 mags
[i
] = mags
[n
- i
];
1152 out
[i
] = out
[n
- i
];
1155 // Remove any DC offset the filter has.
1157 for(i
= 0;i
< n
;i
++)
1159 Complex a
= c_exp(MakeComplex(0.0, out
[i
].Imag
));
1160 out
[i
] = c_mul(MakeComplex(mags
[i
], 0.0), a
);
1166 /***************************
1167 *** Resampler functions ***
1168 ***************************/
1170 /* This is the normalized cardinal sine (sinc) function.
1172 * sinc(x) = { 1, x = 0
1173 * { sin(pi x) / (pi x), otherwise.
1175 static double Sinc(const double x
)
1177 if(fabs(x
) < EPSILON
)
1179 return sin(M_PI
* x
) / (M_PI
* x
);
1182 /* The zero-order modified Bessel function of the first kind, used for the
1185 * I_0(x) = sum_{k=0}^inf (1 / k!)^2 (x / 2)^(2 k)
1186 * = sum_{k=0}^inf ((x / 2)^k / k!)^2
1188 static double BesselI_0(const double x
)
1190 double term
, sum
, x2
, y
, last_sum
;
1193 // Start at k=1 since k=0 is trivial.
1199 // Let the integration converge until the term of the sum is no longer
1207 } while(sum
!= last_sum
);
1211 /* Calculate a Kaiser window from the given beta value and a normalized k
1214 * w(k) = { I_0(B sqrt(1 - k^2)) / I_0(B), -1 <= k <= 1
1217 * Where k can be calculated as:
1219 * k = i / l, where -l <= i <= l.
1223 * k = 2 i / M - 1, where 0 <= i <= M.
1225 static double Kaiser(const double b
, const double k
)
1227 if(!(k
>= -1.0 && k
<= 1.0))
1229 return BesselI_0(b
* sqrt(1.0 - k
*k
)) / BesselI_0(b
);
1232 // Calculates the greatest common divisor of a and b.
1233 static uint
Gcd(uint x
, uint y
)
1244 /* Calculates the size (order) of the Kaiser window. Rejection is in dB and
1245 * the transition width is normalized frequency (0.5 is nyquist).
1247 * M = { ceil((r - 7.95) / (2.285 2 pi f_t)), r > 21
1248 * { ceil(5.79 / 2 pi f_t), r <= 21.
1251 static uint
CalcKaiserOrder(const double rejection
, const double transition
)
1253 double w_t
= 2.0 * M_PI
* transition
;
1254 if(rejection
> 21.0)
1255 return (uint
)ceil((rejection
- 7.95) / (2.285 * w_t
));
1256 return (uint
)ceil(5.79 / w_t
);
1259 // Calculates the beta value of the Kaiser window. Rejection is in dB.
1260 static double CalcKaiserBeta(const double rejection
)
1262 if(rejection
> 50.0)
1263 return 0.1102 * (rejection
- 8.7);
1264 if(rejection
>= 21.0)
1265 return (0.5842 * pow(rejection
- 21.0, 0.4)) +
1266 (0.07886 * (rejection
- 21.0));
1270 /* Calculates a point on the Kaiser-windowed sinc filter for the given half-
1271 * width, beta, gain, and cutoff. The point is specified in non-normalized
1272 * samples, from 0 to M, where M = (2 l + 1).
1274 * w(k) 2 p f_t sinc(2 f_t x)
1276 * x -- centered sample index (i - l)
1277 * k -- normalized and centered window index (x / l)
1278 * w(k) -- window function (Kaiser)
1279 * p -- gain compensation factor when sampling
1280 * f_t -- normalized center frequency (or cutoff; 0.5 is nyquist)
1282 static double SincFilter(const int l
, const double b
, const double gain
, const double cutoff
, const int i
)
1284 return Kaiser(b
, (double)(i
- l
) / l
) * 2.0 * gain
* cutoff
* Sinc(2.0 * cutoff
* (i
- l
));
1287 /* This is a polyphase sinc-filtered resampler.
1289 * Upsample Downsample
1291 * p/q = 3/2 p/q = 3/5
1293 * M-+-+-+-> M-+-+-+->
1294 * -------------------+ ---------------------+
1295 * p s * f f f f|f| | p s * f f f f f |
1296 * | 0 * 0 0 0|0|0 | | 0 * 0 0 0 0|0| |
1297 * v 0 * 0 0|0|0 0 | v 0 * 0 0 0|0|0 |
1298 * s * f|f|f f f | s * f f|f|f f |
1299 * 0 * |0|0 0 0 0 | 0 * 0|0|0 0 0 |
1300 * --------+=+--------+ 0 * |0|0 0 0 0 |
1301 * d . d .|d|. d . d ----------+=+--------+
1302 * d . . . .|d|. . . .
1306 * P_f(i,j) = q i mod p + pj
1307 * P_s(i,j) = floor(q i / p) - j
1308 * d[i=0..N-1] = sum_{j=0}^{floor((M - 1) / p)} {
1309 * { f[P_f(i,j)] s[P_s(i,j)], P_f(i,j) < M
1310 * { 0, P_f(i,j) >= M. }
1313 // Calculate the resampling metrics and build the Kaiser-windowed sinc filter
1314 // that's used to cut frequencies above the destination nyquist.
1315 static void ResamplerSetup(ResamplerT
*rs
, const uint srcRate
, const uint dstRate
)
1317 double cutoff
, width
, beta
;
1321 gcd
= Gcd(srcRate
, dstRate
);
1322 rs
->mP
= dstRate
/ gcd
;
1323 rs
->mQ
= srcRate
/ gcd
;
1324 /* The cutoff is adjusted by half the transition width, so the transition
1325 * ends before the nyquist (0.5). Both are scaled by the downsampling
1330 cutoff
= 0.475 / rs
->mP
;
1331 width
= 0.05 / rs
->mP
;
1335 cutoff
= 0.475 / rs
->mQ
;
1336 width
= 0.05 / rs
->mQ
;
1338 // A rejection of -180 dB is used for the stop band. Round up when
1339 // calculating the left offset to avoid increasing the transition width.
1340 l
= (CalcKaiserOrder(180.0, width
)+1) / 2;
1341 beta
= CalcKaiserBeta(180.0);
1344 rs
->mF
= CreateDoubles(rs
->mM
);
1345 for(i
= 0;i
< ((int)rs
->mM
);i
++)
1346 rs
->mF
[i
] = SincFilter((int)l
, beta
, rs
->mP
, cutoff
, i
);
1349 // Clean up after the resampler.
1350 static void ResamplerClear(ResamplerT
*rs
)
1356 // Perform the upsample-filter-downsample resampling operation using a
1357 // polyphase filter implementation.
1358 static void ResamplerRun(ResamplerT
*rs
, const uint inN
, const double *in
, const uint outN
, double *out
)
1360 const uint p
= rs
->mP
, q
= rs
->mQ
, m
= rs
->mM
, l
= rs
->mL
;
1361 const double *f
= rs
->mF
;
1369 // Handle in-place operation.
1371 work
= CreateDoubles(outN
);
1374 // Resample the input.
1375 for(i
= 0;i
< outN
;i
++)
1378 // Input starts at l to compensate for the filter delay. This will
1379 // drop any build-up from the first half of the filter.
1380 j_f
= (l
+ (q
* i
)) % p
;
1381 j_s
= (l
+ (q
* i
)) / p
;
1384 // Only take input when 0 <= j_s < inN. This single unsigned
1385 // comparison catches both cases.
1387 r
+= f
[j_f
] * in
[j_s
];
1393 // Clean up after in-place operation.
1396 for(i
= 0;i
< outN
;i
++)
1402 /*************************
1403 *** File source input ***
1404 *************************/
1406 // Read a binary value of the specified byte order and byte size from a file,
1407 // storing it as a 32-bit unsigned integer.
1408 static int ReadBin4(FILE *fp
, const char *filename
, const ByteOrderT order
, const uint bytes
, uint32
*out
)
1414 if(fread(in
, 1, bytes
, fp
) != bytes
)
1416 fprintf(stderr
, "Error: Bad read from file '%s'.\n", filename
);
1423 for(i
= 0;i
< bytes
;i
++)
1424 accum
= (accum
<<8) | in
[bytes
- i
- 1];
1427 for(i
= 0;i
< bytes
;i
++)
1428 accum
= (accum
<<8) | in
[i
];
1437 // Read a binary value of the specified byte order from a file, storing it as
1438 // a 64-bit unsigned integer.
1439 static int ReadBin8(FILE *fp
, const char *filename
, const ByteOrderT order
, uint64
*out
)
1445 if(fread(in
, 1, 8, fp
) != 8)
1447 fprintf(stderr
, "Error: Bad read from file '%s'.\n", filename
);
1454 for(i
= 0;i
< 8;i
++)
1455 accum
= (accum
<<8) | in
[8 - i
- 1];
1458 for(i
= 0;i
< 8;i
++)
1459 accum
= (accum
<<8) | in
[i
];
1468 /* Read a binary value of the specified type, byte order, and byte size from
1469 * a file, converting it to a double. For integer types, the significant
1470 * bits are used to normalize the result. The sign of bits determines
1471 * whether they are padded toward the MSB (negative) or LSB (positive).
1472 * Floating-point types are not normalized.
1474 static int ReadBinAsDouble(FILE *fp
, const char *filename
, const ByteOrderT order
, const ElementTypeT type
, const uint bytes
, const int bits
, double *out
)
1489 if(!ReadBin8(fp
, filename
, order
, &v8
.ui
))
1496 if(!ReadBin4(fp
, filename
, order
, bytes
, &v4
.ui
))
1503 v4
.ui
>>= (8*bytes
) - ((uint
)bits
);
1505 v4
.ui
&= (0xFFFFFFFF >> (32+bits
));
1507 if(v4
.ui
&(uint
)(1<<(abs(bits
)-1)))
1508 v4
.ui
|= (0xFFFFFFFF << abs (bits
));
1509 *out
= v4
.i
/ (double)(1<<(abs(bits
)-1));
1515 /* Read an ascii value of the specified type from a file, converting it to a
1516 * double. For integer types, the significant bits are used to normalize the
1517 * result. The sign of the bits should always be positive. This also skips
1518 * up to one separator character before the element itself.
1520 static int ReadAsciiAsDouble(TokenReaderT
*tr
, const char *filename
, const ElementTypeT type
, const uint bits
, double *out
)
1522 if(TrIsOperator(tr
, ","))
1523 TrReadOperator(tr
, ",");
1524 else if(TrIsOperator(tr
, ":"))
1525 TrReadOperator(tr
, ":");
1526 else if(TrIsOperator(tr
, ";"))
1527 TrReadOperator(tr
, ";");
1528 else if(TrIsOperator(tr
, "|"))
1529 TrReadOperator(tr
, "|");
1533 if(!TrReadFloat(tr
, -HUGE_VAL
, HUGE_VAL
, out
))
1535 fprintf(stderr
, "Error: Bad read from file '%s'.\n", filename
);
1542 if(!TrReadInt(tr
, -(1<<(bits
-1)), (1<<(bits
-1))-1, &v
))
1544 fprintf(stderr
, "Error: Bad read from file '%s'.\n", filename
);
1547 *out
= v
/ (double)((1<<(bits
-1))-1);
1552 // Read the RIFF/RIFX WAVE format chunk from a file, validating it against
1553 // the source parameters and data set metrics.
1554 static int ReadWaveFormat(FILE *fp
, const ByteOrderT order
, const uint hrirRate
, SourceRefT
*src
)
1556 uint32 fourCC
, chunkSize
;
1557 uint32 format
, channels
, rate
, dummy
, block
, size
, bits
;
1562 fseek (fp
, (long) chunkSize
, SEEK_CUR
);
1563 if(!ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, &fourCC
) ||
1564 !ReadBin4(fp
, src
->mPath
, order
, 4, &chunkSize
))
1566 } while(fourCC
!= FOURCC_FMT
);
1567 if(!ReadBin4(fp
, src
->mPath
, order
, 2, &format
) ||
1568 !ReadBin4(fp
, src
->mPath
, order
, 2, &channels
) ||
1569 !ReadBin4(fp
, src
->mPath
, order
, 4, &rate
) ||
1570 !ReadBin4(fp
, src
->mPath
, order
, 4, &dummy
) ||
1571 !ReadBin4(fp
, src
->mPath
, order
, 2, &block
))
1576 if(!ReadBin4(fp
, src
->mPath
, order
, 2, &size
))
1584 if(format
== WAVE_FORMAT_EXTENSIBLE
)
1586 fseek(fp
, 2, SEEK_CUR
);
1587 if(!ReadBin4(fp
, src
->mPath
, order
, 2, &bits
))
1591 fseek(fp
, 4, SEEK_CUR
);
1592 if(!ReadBin4(fp
, src
->mPath
, order
, 2, &format
))
1594 fseek(fp
, (long)(chunkSize
- 26), SEEK_CUR
);
1600 fseek(fp
, (long)(chunkSize
- 16), SEEK_CUR
);
1602 fseek(fp
, (long)(chunkSize
- 14), SEEK_CUR
);
1604 if(format
!= WAVE_FORMAT_PCM
&& format
!= WAVE_FORMAT_IEEE_FLOAT
)
1606 fprintf(stderr
, "Error: Unsupported WAVE format in file '%s'.\n", src
->mPath
);
1609 if(src
->mChannel
>= channels
)
1611 fprintf(stderr
, "Error: Missing source channel in WAVE file '%s'.\n", src
->mPath
);
1614 if(rate
!= hrirRate
)
1616 fprintf(stderr
, "Error: Mismatched source sample rate in WAVE file '%s'.\n", src
->mPath
);
1619 if(format
== WAVE_FORMAT_PCM
)
1621 if(size
< 2 || size
> 4)
1623 fprintf(stderr
, "Error: Unsupported sample size in WAVE file '%s'.\n", src
->mPath
);
1626 if(bits
< 16 || bits
> (8*size
))
1628 fprintf (stderr
, "Error: Bad significant bits in WAVE file '%s'.\n", src
->mPath
);
1631 src
->mType
= ET_INT
;
1635 if(size
!= 4 && size
!= 8)
1637 fprintf(stderr
, "Error: Unsupported sample size in WAVE file '%s'.\n", src
->mPath
);
1643 src
->mBits
= (int)bits
;
1644 src
->mSkip
= channels
;
1648 // Read a RIFF/RIFX WAVE data chunk, converting all elements to doubles.
1649 static int ReadWaveData(FILE *fp
, const SourceRefT
*src
, const ByteOrderT order
, const uint n
, double *hrir
)
1651 int pre
, post
, skip
;
1654 pre
= (int)(src
->mSize
* src
->mChannel
);
1655 post
= (int)(src
->mSize
* (src
->mSkip
- src
->mChannel
- 1));
1657 for(i
= 0;i
< n
;i
++)
1661 fseek(fp
, skip
, SEEK_CUR
);
1662 if(!ReadBinAsDouble(fp
, src
->mPath
, order
, src
->mType
, src
->mSize
, src
->mBits
, &hrir
[i
]))
1667 fseek(fp
, skip
, SEEK_CUR
);
1671 // Read the RIFF/RIFX WAVE list or data chunk, converting all elements to
1673 static int ReadWaveList(FILE *fp
, const SourceRefT
*src
, const ByteOrderT order
, const uint n
, double *hrir
)
1675 uint32 fourCC
, chunkSize
, listSize
, count
;
1676 uint block
, skip
, offset
, i
;
1681 if(!ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, &fourCC
) ||
1682 !ReadBin4(fp
, src
->mPath
, order
, 4, &chunkSize
))
1685 if(fourCC
== FOURCC_DATA
)
1687 block
= src
->mSize
* src
->mSkip
;
1688 count
= chunkSize
/ block
;
1689 if(count
< (src
->mOffset
+ n
))
1691 fprintf(stderr
, "Error: Bad read from file '%s'.\n", src
->mPath
);
1694 fseek(fp
, (long)(src
->mOffset
* block
), SEEK_CUR
);
1695 if(!ReadWaveData(fp
, src
, order
, n
, &hrir
[0]))
1699 else if(fourCC
== FOURCC_LIST
)
1701 if(!ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, &fourCC
))
1704 if(fourCC
== FOURCC_WAVL
)
1708 fseek(fp
, (long)chunkSize
, SEEK_CUR
);
1710 listSize
= chunkSize
;
1711 block
= src
->mSize
* src
->mSkip
;
1712 skip
= src
->mOffset
;
1715 while(offset
< n
&& listSize
> 8)
1717 if(!ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, &fourCC
) ||
1718 !ReadBin4(fp
, src
->mPath
, order
, 4, &chunkSize
))
1720 listSize
-= 8 + chunkSize
;
1721 if(fourCC
== FOURCC_DATA
)
1723 count
= chunkSize
/ block
;
1726 fseek(fp
, (long)(skip
* block
), SEEK_CUR
);
1727 chunkSize
-= skip
* block
;
1730 if(count
> (n
- offset
))
1732 if(!ReadWaveData(fp
, src
, order
, count
, &hrir
[offset
]))
1734 chunkSize
-= count
* block
;
1736 lastSample
= hrir
[offset
- 1];
1744 else if(fourCC
== FOURCC_SLNT
)
1746 if(!ReadBin4(fp
, src
->mPath
, order
, 4, &count
))
1753 if(count
> (n
- offset
))
1755 for(i
= 0; i
< count
; i
++)
1756 hrir
[offset
+ i
] = lastSample
;
1766 fseek(fp
, (long)chunkSize
, SEEK_CUR
);
1770 fprintf(stderr
, "Error: Bad read from file '%s'.\n", src
->mPath
);
1776 // Load a source HRIR from a RIFF/RIFX WAVE file.
1777 static int LoadWaveSource(FILE *fp
, SourceRefT
*src
, const uint hrirRate
, const uint n
, double *hrir
)
1779 uint32 fourCC
, dummy
;
1782 if(!ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, &fourCC
) ||
1783 !ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, &dummy
))
1785 if(fourCC
== FOURCC_RIFF
)
1787 else if(fourCC
== FOURCC_RIFX
)
1791 fprintf(stderr
, "Error: No RIFF/RIFX chunk in file '%s'.\n", src
->mPath
);
1795 if(!ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, &fourCC
))
1797 if(fourCC
!= FOURCC_WAVE
)
1799 fprintf(stderr
, "Error: Not a RIFF/RIFX WAVE file '%s'.\n", src
->mPath
);
1802 if(!ReadWaveFormat(fp
, order
, hrirRate
, src
))
1804 if(!ReadWaveList(fp
, src
, order
, n
, hrir
))
1809 // Load a source HRIR from a binary file.
1810 static int LoadBinarySource(FILE *fp
, const SourceRefT
*src
, const ByteOrderT order
, const uint n
, double *hrir
)
1814 fseek(fp
, (long)src
->mOffset
, SEEK_SET
);
1815 for(i
= 0;i
< n
;i
++)
1817 if(!ReadBinAsDouble(fp
, src
->mPath
, order
, src
->mType
, src
->mSize
, src
->mBits
, &hrir
[i
]))
1820 fseek(fp
, (long)src
->mSkip
, SEEK_CUR
);
1825 // Load a source HRIR from an ASCII text file containing a list of elements
1826 // separated by whitespace or common list operators (',', ';', ':', '|').
1827 static int LoadAsciiSource(FILE *fp
, const SourceRefT
*src
, const uint n
, double *hrir
)
1833 TrSetup(fp
, NULL
, &tr
);
1834 for(i
= 0;i
< src
->mOffset
;i
++)
1836 if(!ReadAsciiAsDouble(&tr
, src
->mPath
, src
->mType
, (uint
)src
->mBits
, &dummy
))
1839 for(i
= 0;i
< n
;i
++)
1841 if(!ReadAsciiAsDouble(&tr
, src
->mPath
, src
->mType
, (uint
)src
->mBits
, &hrir
[i
]))
1843 for(j
= 0;j
< src
->mSkip
;j
++)
1845 if(!ReadAsciiAsDouble(&tr
, src
->mPath
, src
->mType
, (uint
)src
->mBits
, &dummy
))
1852 // Load a source HRIR from a supported file type.
1853 static int LoadSource(SourceRefT
*src
, const uint hrirRate
, const uint n
, double *hrir
)
1858 if(src
->mFormat
== SF_ASCII
)
1859 fp
= fopen(src
->mPath
, "r");
1861 fp
= fopen(src
->mPath
, "rb");
1864 fprintf(stderr
, "Error: Could not open source file '%s'.\n", src
->mPath
);
1867 if(src
->mFormat
== SF_WAVE
)
1868 result
= LoadWaveSource(fp
, src
, hrirRate
, n
, hrir
);
1869 else if(src
->mFormat
== SF_BIN_LE
)
1870 result
= LoadBinarySource(fp
, src
, BO_LITTLE
, n
, hrir
);
1871 else if(src
->mFormat
== SF_BIN_BE
)
1872 result
= LoadBinarySource(fp
, src
, BO_BIG
, n
, hrir
);
1874 result
= LoadAsciiSource(fp
, src
, n
, hrir
);
1880 /***************************
1881 *** File storage output ***
1882 ***************************/
1884 // Write an ASCII string to a file.
1885 static int WriteAscii(const char *out
, FILE *fp
, const char *filename
)
1890 if(fwrite(out
, 1, len
, fp
) != len
)
1893 fprintf(stderr
, "Error: Bad write to file '%s'.\n", filename
);
1899 // Write a binary value of the given byte order and byte size to a file,
1900 // loading it from a 32-bit unsigned integer.
1901 static int WriteBin4(const ByteOrderT order
, const uint bytes
, const uint32 in
, FILE *fp
, const char *filename
)
1909 for(i
= 0;i
< bytes
;i
++)
1910 out
[i
] = (in
>>(i
*8)) & 0x000000FF;
1913 for(i
= 0;i
< bytes
;i
++)
1914 out
[bytes
- i
- 1] = (in
>>(i
*8)) & 0x000000FF;
1919 if(fwrite(out
, 1, bytes
, fp
) != bytes
)
1921 fprintf(stderr
, "Error: Bad write to file '%s'.\n", filename
);
1927 // Store the OpenAL Soft HRTF data set.
1928 static int StoreMhr(const HrirDataT
*hData
, const char *filename
)
1930 uint channels
= (hData
->mChannelType
== CT_STEREO
) ? 2 : 1;
1931 uint n
= hData
->mIrPoints
;
1934 uint dither_seed
= 22222;
1936 if((fp
=fopen(filename
, "wb")) == NULL
)
1938 fprintf(stderr
, "Error: Could not open MHR file '%s'.\n", filename
);
1941 if(!WriteAscii(MHR_FORMAT
, fp
, filename
))
1943 if(!WriteBin4(BO_LITTLE
, 4, (uint32
)hData
->mIrRate
, fp
, filename
))
1945 if(!WriteBin4(BO_LITTLE
, 1, (uint32
)hData
->mSampleType
, fp
, filename
))
1947 if(!WriteBin4(BO_LITTLE
, 1, (uint32
)hData
->mChannelType
, fp
, filename
))
1949 if(!WriteBin4(BO_LITTLE
, 1, (uint32
)hData
->mIrPoints
, fp
, filename
))
1951 if(!WriteBin4(BO_LITTLE
, 1, (uint32
)hData
->mFdCount
, fp
, filename
))
1953 for(fi
= 0;fi
< hData
->mFdCount
;fi
++)
1955 if(!WriteBin4(BO_LITTLE
, 2, (uint32
)(1000.0 * hData
->mFds
[fi
].mDistance
), fp
, filename
))
1957 if(!WriteBin4(BO_LITTLE
, 1, (uint32
)hData
->mFds
[fi
].mEvCount
, fp
, filename
))
1959 for(ei
= 0;ei
< hData
->mFds
[fi
].mEvCount
;ei
++)
1961 if(!WriteBin4(BO_LITTLE
, 1, (uint32
)hData
->mFds
[fi
].mEvs
[ei
].mAzCount
, fp
, filename
))
1966 for(fi
= 0;fi
< hData
->mFdCount
;fi
++)
1968 const double scale
= (hData
->mSampleType
== ST_S16
) ? 32767.0 :
1969 ((hData
->mSampleType
== ST_S24
) ? 8388607.0 : 0.0);
1970 const int bps
= (hData
->mSampleType
== ST_S16
) ? 2 :
1971 ((hData
->mSampleType
== ST_S24
) ? 3 : 0);
1973 for(ei
= 0;ei
< hData
->mFds
[fi
].mEvCount
;ei
++)
1975 for(ai
= 0;ai
< hData
->mFds
[fi
].mEvs
[ei
].mAzCount
;ai
++)
1977 HrirAzT
*azd
= &hData
->mFds
[fi
].mEvs
[ei
].mAzs
[ai
];
1978 double out
[2 * MAX_TRUNCSIZE
];
1980 TpdfDither(out
, azd
->mIrs
[0], scale
, n
, channels
, &dither_seed
);
1981 if(hData
->mChannelType
== CT_STEREO
)
1982 TpdfDither(out
+1, azd
->mIrs
[1], scale
, n
, channels
, &dither_seed
);
1983 for(i
= 0;i
< (channels
* n
);i
++)
1985 int v
= (int)Clamp(out
[i
], -scale
-1.0, scale
);
1986 if(!WriteBin4(BO_LITTLE
, bps
, (uint32
)v
, fp
, filename
))
1992 for(fi
= 0;fi
< hData
->mFdCount
;fi
++)
1994 for(ei
= 0;ei
< hData
->mFds
[fi
].mEvCount
;ei
++)
1996 for(ai
= 0;ai
< hData
->mFds
[fi
].mEvs
[ei
].mAzCount
;ai
++)
1998 HrirAzT
*azd
= &hData
->mFds
[fi
].mEvs
[ei
].mAzs
[ai
];
1999 int v
= (int)fmin(round(hData
->mIrRate
* azd
->mDelays
[0]), MAX_HRTD
);
2001 if(!WriteBin4(BO_LITTLE
, 1, (uint32
)v
, fp
, filename
))
2003 if(hData
->mChannelType
== CT_STEREO
)
2005 v
= (int)fmin(round(hData
->mIrRate
* azd
->mDelays
[1]), MAX_HRTD
);
2007 if(!WriteBin4(BO_LITTLE
, 1, (uint32
)v
, fp
, filename
))
2018 /***********************
2019 *** HRTF processing ***
2020 ***********************/
2022 // Calculate the onset time of an HRIR and average it with any existing
2023 // timing for its field, elevation, azimuth, and ear.
2024 static double AverageHrirOnset(const uint rate
, const uint n
, const double *hrir
, const double f
, const double onset
)
2029 for(i
= 0;i
< n
;i
++)
2030 mag
= fmax(fabs(hrir
[i
]), mag
);
2032 for(i
= 0;i
< n
;i
++)
2034 if(fabs(hrir
[i
]) >= mag
)
2037 return Lerp(onset
, (double)i
/ rate
, f
);
2040 // Calculate the magnitude response of an HRIR and average it with any
2041 // existing responses for its field, elevation, azimuth, and ear.
2042 static void AverageHrirMagnitude(const uint points
, const uint n
, const double *hrir
, const double f
, double *mag
)
2044 uint m
= 1 + (n
/ 2), i
;
2045 Complex
*h
= CreateComplexes(n
);
2046 double *r
= CreateDoubles(n
);
2048 for(i
= 0;i
< points
;i
++)
2049 h
[i
] = MakeComplex(hrir
[i
], 0.0);
2051 h
[i
] = MakeComplex(0.0, 0.0);
2053 MagnitudeResponse(n
, h
, r
);
2054 for(i
= 0;i
< m
;i
++)
2055 mag
[i
] = Lerp(mag
[i
], r
[i
], f
);
2060 /* Calculate the contribution of each HRIR to the diffuse-field average based
2061 * on the area of its surface patch. All patches are centered at the HRIR
2062 * coordinates on the unit sphere and are measured by solid angle.
2064 static void CalculateDfWeights(const HrirDataT
*hData
, double *weights
)
2066 double sum
, evs
, ev
, upperEv
, lowerEv
, solidAngle
;
2070 for(fi
= 0;fi
< hData
->mFdCount
;fi
++)
2072 evs
= M_PI
/ 2.0 / (hData
->mFds
[fi
].mEvCount
- 1);
2073 for(ei
= hData
->mFds
[fi
].mEvStart
;ei
< hData
->mFds
[fi
].mEvCount
;ei
++)
2075 // For each elevation, calculate the upper and lower limits of
2077 ev
= hData
->mFds
[fi
].mEvs
[ei
].mElevation
;
2078 lowerEv
= fmax(-M_PI
/ 2.0, ev
- evs
);
2079 upperEv
= fmin(M_PI
/ 2.0, ev
+ evs
);
2080 // Calculate the area of the patch band.
2081 solidAngle
= 2.0 * M_PI
* (sin(upperEv
) - sin(lowerEv
));
2082 // Each weight is the area of one patch.
2083 weights
[(fi
* MAX_EV_COUNT
) + ei
] = solidAngle
/ hData
->mFds
[fi
].mEvs
[ei
].mAzCount
;
2084 // Sum the total surface area covered by the HRIRs of all fields.
2088 /* TODO: It may be interesting to experiment with how a volume-based
2089 weighting performs compared to the existing distance-indepenent
2092 for(fi
= 0;fi
< hData
->mFdCount
;fi
++)
2094 // Normalize the weights given the total surface coverage for all
2096 for(ei
= hData
->mFds
[fi
].mEvStart
;ei
< hData
->mFds
[fi
].mEvCount
;ei
++)
2097 weights
[(fi
* MAX_EV_COUNT
) + ei
] /= sum
;
2101 /* Calculate the diffuse-field average from the given magnitude responses of
2102 * the HRIR set. Weighting can be applied to compensate for the varying
2103 * surface area covered by each HRIR. The final average can then be limited
2104 * by the specified magnitude range (in positive dB; 0.0 to skip).
2106 static void CalculateDiffuseFieldAverage(const HrirDataT
*hData
, const uint channels
, const uint m
, const int weighted
, const double limit
, double *dfa
)
2108 double *weights
= CreateDoubles(hData
->mFdCount
* MAX_EV_COUNT
);
2109 uint count
, ti
, fi
, ei
, i
, ai
;
2113 // Use coverage weighting to calculate the average.
2114 CalculateDfWeights(hData
, weights
);
2120 // If coverage weighting is not used, the weights still need to be
2121 // averaged by the number of existing HRIRs.
2122 count
= hData
->mIrCount
;
2123 for(fi
= 0;fi
< hData
->mFdCount
;fi
++)
2125 for(ei
= 0;ei
< hData
->mFds
[fi
].mEvStart
;ei
++)
2126 count
-= hData
->mFds
[fi
].mEvs
[ei
].mAzCount
;
2128 weight
= 1.0 / count
;
2130 for(fi
= 0;fi
< hData
->mFdCount
;fi
++)
2132 for(ei
= hData
->mFds
[fi
].mEvStart
;ei
< hData
->mFds
[fi
].mEvCount
;ei
++)
2133 weights
[(fi
* MAX_EV_COUNT
) + ei
] = weight
;
2136 for(ti
= 0;ti
< channels
;ti
++)
2138 for(i
= 0;i
< m
;i
++)
2139 dfa
[(ti
* m
) + i
] = 0.0;
2140 for(fi
= 0;fi
< hData
->mFdCount
;fi
++)
2142 for(ei
= hData
->mFds
[fi
].mEvStart
;ei
< hData
->mFds
[fi
].mEvCount
;ei
++)
2144 for(ai
= 0;ai
< hData
->mFds
[fi
].mEvs
[ei
].mAzCount
;ai
++)
2146 HrirAzT
*azd
= &hData
->mFds
[fi
].mEvs
[ei
].mAzs
[ai
];
2147 // Get the weight for this HRIR's contribution.
2148 double weight
= weights
[(fi
* MAX_EV_COUNT
) + ei
];
2150 // Add this HRIR's weighted power average to the total.
2151 for(i
= 0;i
< m
;i
++)
2152 dfa
[(ti
* m
) + i
] += weight
* azd
->mIrs
[ti
][i
] * azd
->mIrs
[ti
][i
];
2156 // Finish the average calculation and keep it from being too small.
2157 for(i
= 0;i
< m
;i
++)
2158 dfa
[(ti
* m
) + i
] = fmax(sqrt(dfa
[(ti
* m
) + i
]), EPSILON
);
2159 // Apply a limit to the magnitude range of the diffuse-field average
2162 LimitMagnitudeResponse(hData
->mFftSize
, m
, limit
, &dfa
[ti
* m
], &dfa
[ti
* m
]);
2167 // Perform diffuse-field equalization on the magnitude responses of the HRIR
2168 // set using the given average response.
2169 static void DiffuseFieldEqualize(const uint channels
, const uint m
, const double *dfa
, const HrirDataT
*hData
)
2171 uint ti
, fi
, ei
, ai
, i
;
2173 for(fi
= 0;fi
< hData
->mFdCount
;fi
++)
2175 for(ei
= hData
->mFds
[fi
].mEvStart
;ei
< hData
->mFds
[fi
].mEvCount
;ei
++)
2177 for(ai
= 0;ai
< hData
->mFds
[fi
].mEvs
[ei
].mAzCount
;ai
++)
2179 HrirAzT
*azd
= &hData
->mFds
[fi
].mEvs
[ei
].mAzs
[ai
];
2181 for(ti
= 0;ti
< channels
;ti
++)
2183 for(i
= 0;i
< m
;i
++)
2184 azd
->mIrs
[ti
][i
] /= dfa
[(ti
* m
) + i
];
2191 // Perform minimum-phase reconstruction using the magnitude responses of the
2193 static void ReconstructHrirs(const HrirDataT
*hData
)
2195 uint channels
= (hData
->mChannelType
== CT_STEREO
) ? 2 : 1;
2196 uint n
= hData
->mFftSize
;
2197 uint ti
, fi
, ei
, ai
, i
;
2198 Complex
*h
= CreateComplexes(n
);
2199 uint total
, count
, pcdone
, lastpc
;
2201 total
= hData
->mIrCount
;
2202 for(fi
= 0;fi
< hData
->mFdCount
;fi
++)
2204 for(ei
= 0;ei
< hData
->mFds
[fi
].mEvStart
;ei
++)
2205 total
-= hData
->mFds
[fi
].mEvs
[ei
].mAzCount
;
2208 count
= pcdone
= lastpc
= 0;
2209 printf("%3d%% done.", pcdone
);
2211 for(fi
= 0;fi
< hData
->mFdCount
;fi
++)
2213 for(ei
= hData
->mFds
[fi
].mEvStart
;ei
< hData
->mFds
[fi
].mEvCount
;ei
++)
2215 for(ai
= 0;ai
< hData
->mFds
[fi
].mEvs
[ei
].mAzCount
;ai
++)
2217 HrirAzT
*azd
= &hData
->mFds
[fi
].mEvs
[ei
].mAzs
[ai
];
2219 for(ti
= 0;ti
< channels
;ti
++)
2221 MinimumPhase(n
, azd
->mIrs
[ti
], h
);
2223 for(i
= 0;i
< hData
->mIrPoints
;i
++)
2224 azd
->mIrs
[ti
][i
] = h
[i
].Real
;
2225 pcdone
= ++count
* 100 / total
;
2226 if(pcdone
!= lastpc
)
2229 printf("\r%3d%% done.", pcdone
);
2240 // Resamples the HRIRs for use at the given sampling rate.
2241 static void ResampleHrirs(const uint rate
, HrirDataT
*hData
)
2243 uint channels
= (hData
->mChannelType
== CT_STEREO
) ? 2 : 1;
2244 uint n
= hData
->mIrPoints
;
2245 uint ti
, fi
, ei
, ai
;
2248 ResamplerSetup(&rs
, hData
->mIrRate
, rate
);
2249 for(fi
= 0;fi
< hData
->mFdCount
;fi
++)
2251 for(ei
= hData
->mFds
[fi
].mEvStart
;ei
< hData
->mFds
[fi
].mEvCount
;ei
++)
2253 for(ai
= 0;ai
< hData
->mFds
[fi
].mEvs
[ei
].mAzCount
;ai
++)
2255 HrirAzT
*azd
= &hData
->mFds
[fi
].mEvs
[ei
].mAzs
[ai
];
2257 for(ti
= 0;ti
< channels
;ti
++)
2258 ResamplerRun(&rs
, n
, azd
->mIrs
[ti
], n
, azd
->mIrs
[ti
]);
2262 hData
->mIrRate
= rate
;
2263 ResamplerClear(&rs
);
2266 /* Given field and elevation indices and an azimuth, calculate the indices of
2267 * the two HRIRs that bound the coordinate along with a factor for
2268 * calculating the continuous HRIR using interpolation.
2270 static void CalcAzIndices(const HrirDataT
*hData
, const uint fi
, const uint ei
, const double az
, uint
*a0
, uint
*a1
, double *af
)
2272 double f
= (2.0*M_PI
+ az
) * hData
->mFds
[fi
].mEvs
[ei
].mAzCount
/ (2.0*M_PI
);
2273 uint i
= (uint
)f
% hData
->mFds
[fi
].mEvs
[ei
].mAzCount
;
2277 *a1
= (i
+ 1) % hData
->mFds
[fi
].mEvs
[ei
].mAzCount
;
2281 // Synthesize any missing onset timings at the bottom elevations of each
2282 // field. This just blends between slightly exaggerated known onsets (not
2283 // an accurate model).
2284 static void SynthesizeOnsets(HrirDataT
*hData
)
2286 uint channels
= (hData
->mChannelType
== CT_STEREO
) ? 2 : 1;
2287 uint ti
, fi
, oi
, ai
, ei
, a0
, a1
;
2290 for(fi
= 0;fi
< hData
->mFdCount
;fi
++)
2292 if(hData
->mFds
[fi
].mEvStart
<= 0)
2294 oi
= hData
->mFds
[fi
].mEvStart
;
2296 for(ti
= 0;ti
< channels
;ti
++)
2299 for(ai
= 0;ai
< hData
->mFds
[fi
].mEvs
[oi
].mAzCount
;ai
++)
2300 t
+= hData
->mFds
[fi
].mEvs
[oi
].mAzs
[ai
].mDelays
[ti
];
2301 hData
->mFds
[fi
].mEvs
[0].mAzs
[0].mDelays
[ti
] = 1.32e-4 + (t
/ hData
->mFds
[fi
].mEvs
[oi
].mAzCount
);
2302 for(ei
= 1;ei
< hData
->mFds
[fi
].mEvStart
;ei
++)
2304 of
= (double)ei
/ hData
->mFds
[fi
].mEvStart
;
2305 for(ai
= 0;ai
< hData
->mFds
[fi
].mEvs
[ei
].mAzCount
;ai
++)
2307 CalcAzIndices(hData
, fi
, oi
, hData
->mFds
[fi
].mEvs
[ei
].mAzs
[ai
].mAzimuth
, &a0
, &a1
, &af
);
2308 hData
->mFds
[fi
].mEvs
[ei
].mAzs
[ai
].mDelays
[ti
] = Lerp(
2309 hData
->mFds
[fi
].mEvs
[0].mAzs
[0].mDelays
[ti
],
2310 Lerp(hData
->mFds
[fi
].mEvs
[oi
].mAzs
[a0
].mDelays
[ti
],
2311 hData
->mFds
[fi
].mEvs
[oi
].mAzs
[a1
].mDelays
[ti
], af
),
2320 /* Attempt to synthesize any missing HRIRs at the bottom elevations of each
2321 * field. Right now this just blends the lowest elevation HRIRs together and
2322 * applies some attenuation and high frequency damping. It is a simple, if
2325 static void SynthesizeHrirs(HrirDataT
*hData
)
2327 uint channels
= (hData
->mChannelType
== CT_STEREO
) ? 2 : 1;
2328 uint n
= hData
->mIrPoints
;
2329 uint ti
, fi
, ai
, ei
, i
;
2330 double lp
[4], s0
, s1
;
2335 for(fi
= 0;fi
< hData
->mFdCount
;fi
++)
2337 const uint oi
= hData
->mFds
[fi
].mEvStart
;
2338 if(oi
<= 0) continue;
2340 for(ti
= 0;ti
< channels
;ti
++)
2342 for(i
= 0;i
< n
;i
++)
2343 hData
->mFds
[fi
].mEvs
[0].mAzs
[0].mIrs
[ti
][i
] = 0.0;
2344 for(ai
= 0;ai
< hData
->mFds
[fi
].mEvs
[oi
].mAzCount
;ai
++)
2346 for(i
= 0;i
< n
;i
++)
2347 hData
->mFds
[fi
].mEvs
[0].mAzs
[0].mIrs
[ti
][i
] += hData
->mFds
[fi
].mEvs
[oi
].mAzs
[ai
].mIrs
[ti
][i
] /
2348 hData
->mFds
[fi
].mEvs
[oi
].mAzCount
;
2350 for(ei
= 1;ei
< hData
->mFds
[fi
].mEvStart
;ei
++)
2352 of
= (double)ei
/ hData
->mFds
[fi
].mEvStart
;
2353 b
= (1.0 - of
) * (3.5e-6 * hData
->mIrRate
);
2354 for(ai
= 0;ai
< hData
->mFds
[fi
].mEvs
[ei
].mAzCount
;ai
++)
2356 CalcAzIndices(hData
, fi
, oi
, hData
->mFds
[fi
].mEvs
[ei
].mAzs
[ai
].mAzimuth
, &a0
, &a1
, &af
);
2361 for(i
= 0;i
< n
;i
++)
2363 s0
= hData
->mFds
[fi
].mEvs
[0].mAzs
[0].mIrs
[ti
][i
];
2364 s1
= Lerp(hData
->mFds
[fi
].mEvs
[oi
].mAzs
[a0
].mIrs
[ti
][i
],
2365 hData
->mFds
[fi
].mEvs
[oi
].mAzs
[a1
].mIrs
[ti
][i
], af
);
2366 s0
= Lerp(s0
, s1
, of
);
2367 lp
[0] = Lerp(s0
, lp
[0], b
);
2368 lp
[1] = Lerp(lp
[0], lp
[1], b
);
2369 lp
[2] = Lerp(lp
[1], lp
[2], b
);
2370 lp
[3] = Lerp(lp
[2], lp
[3], b
);
2371 hData
->mFds
[fi
].mEvs
[ei
].mAzs
[ai
].mIrs
[ti
][i
] = lp
[3];
2375 b
= 3.5e-6 * hData
->mIrRate
;
2380 for(i
= 0;i
< n
;i
++)
2382 s0
= hData
->mFds
[fi
].mEvs
[0].mAzs
[0].mIrs
[ti
][i
];
2383 lp
[0] = Lerp(s0
, lp
[0], b
);
2384 lp
[1] = Lerp(lp
[0], lp
[1], b
);
2385 lp
[2] = Lerp(lp
[1], lp
[2], b
);
2386 lp
[3] = Lerp(lp
[2], lp
[3], b
);
2387 hData
->mFds
[fi
].mEvs
[0].mAzs
[0].mIrs
[ti
][i
] = lp
[3];
2390 hData
->mFds
[fi
].mEvStart
= 0;
2394 // The following routines assume a full set of HRIRs for all elevations.
2396 // Normalize the HRIR set and slightly attenuate the result.
2397 static void NormalizeHrirs(const HrirDataT
*hData
)
2399 uint channels
= (hData
->mChannelType
== CT_STEREO
) ? 2 : 1;
2400 uint n
= hData
->mIrPoints
;
2401 uint ti
, fi
, ei
, ai
, i
;
2402 double maxLevel
= 0.0;
2404 for(fi
= 0;fi
< hData
->mFdCount
;fi
++)
2406 for(ei
= 0;ei
< hData
->mFds
[fi
].mEvCount
;ei
++)
2408 for(ai
= 0;ai
< hData
->mFds
[fi
].mEvs
[ei
].mAzCount
;ai
++)
2410 HrirAzT
*azd
= &hData
->mFds
[fi
].mEvs
[ei
].mAzs
[ai
];
2412 for(ti
= 0;ti
< channels
;ti
++)
2414 for(i
= 0;i
< n
;i
++)
2415 maxLevel
= fmax(fabs(azd
->mIrs
[ti
][i
]), maxLevel
);
2420 maxLevel
= 1.01 * maxLevel
;
2421 for(fi
= 0;fi
< hData
->mFdCount
;fi
++)
2423 for(ei
= 0;ei
< hData
->mFds
[fi
].mEvCount
;ei
++)
2425 for(ai
= 0;ai
< hData
->mFds
[fi
].mEvs
[ei
].mAzCount
;ai
++)
2427 HrirAzT
*azd
= &hData
->mFds
[fi
].mEvs
[ei
].mAzs
[ai
];
2429 for(ti
= 0;ti
< channels
;ti
++)
2431 for(i
= 0;i
< n
;i
++)
2432 azd
->mIrs
[ti
][i
] /= maxLevel
;
2439 // Calculate the left-ear time delay using a spherical head model.
2440 static double CalcLTD(const double ev
, const double az
, const double rad
, const double dist
)
2442 double azp
, dlp
, l
, al
;
2444 azp
= asin(cos(ev
) * sin(az
));
2445 dlp
= sqrt((dist
*dist
) + (rad
*rad
) + (2.0*dist
*rad
*sin(azp
)));
2446 l
= sqrt((dist
*dist
) - (rad
*rad
));
2447 al
= (0.5 * M_PI
) + azp
;
2449 dlp
= l
+ (rad
* (al
- acos(rad
/ dist
)));
2453 // Calculate the effective head-related time delays for each minimum-phase
2455 static void CalculateHrtds(const HeadModelT model
, const double radius
, HrirDataT
*hData
)
2457 uint channels
= (hData
->mChannelType
== CT_STEREO
) ? 2 : 1;
2458 double minHrtd
= INFINITY
, maxHrtd
= -INFINITY
;
2459 uint ti
, fi
, ei
, ai
;
2462 if(model
== HM_DATASET
)
2464 for(fi
= 0;fi
< hData
->mFdCount
;fi
++)
2466 for(ei
= 0;ei
< hData
->mFds
[fi
].mEvCount
;ei
++)
2468 for(ai
= 0;ai
< hData
->mFds
[fi
].mEvs
[ei
].mAzCount
;ai
++)
2470 HrirAzT
*azd
= &hData
->mFds
[fi
].mEvs
[ei
].mAzs
[ai
];
2472 for(ti
= 0;ti
< channels
;ti
++)
2474 t
= azd
->mDelays
[ti
] * radius
/ hData
->mRadius
;
2475 azd
->mDelays
[ti
] = t
;
2476 maxHrtd
= fmax(t
, maxHrtd
);
2477 minHrtd
= fmin(t
, minHrtd
);
2485 for(fi
= 0;fi
< hData
->mFdCount
;fi
++)
2487 for(ei
= 0;ei
< hData
->mFds
[fi
].mEvCount
;ei
++)
2489 HrirEvT
*evd
= &hData
->mFds
[fi
].mEvs
[ei
];
2491 for(ai
= 0;ai
< evd
->mAzCount
;ai
++)
2493 HrirAzT
*azd
= &evd
->mAzs
[ai
];
2495 for(ti
= 0;ti
< channels
;ti
++)
2497 t
= CalcLTD(evd
->mElevation
, azd
->mAzimuth
, radius
, hData
->mFds
[fi
].mDistance
);
2498 azd
->mDelays
[ti
] = t
;
2499 maxHrtd
= fmax(t
, maxHrtd
);
2500 minHrtd
= fmin(t
, minHrtd
);
2506 for(fi
= 0;fi
< hData
->mFdCount
;fi
++)
2508 for(ei
= 0;ei
< hData
->mFds
[fi
].mEvCount
;ei
++)
2510 for(ti
= 0;ti
< channels
;ti
++)
2512 for(ai
= 0;ai
< hData
->mFds
[fi
].mEvs
[ei
].mAzCount
;ai
++)
2513 hData
->mFds
[fi
].mEvs
[ei
].mAzs
[ai
].mDelays
[ti
] -= minHrtd
;
2519 // Clear the initial HRIR data state.
2520 static void ResetHrirData(HrirDataT
*hData
)
2523 hData
->mSampleType
= ST_S24
;
2524 hData
->mChannelType
= CT_NONE
;
2525 hData
->mIrPoints
= 0;
2526 hData
->mFftSize
= 0;
2528 hData
->mRadius
= 0.0;
2529 hData
->mIrCount
= 0;
2530 hData
->mFdCount
= 0;
2534 // Allocate and configure dynamic HRIR structures.
2535 static int PrepareHrirData(const uint fdCount
, const double distances
[MAX_FD_COUNT
], const uint evCounts
[MAX_FD_COUNT
], const uint azCounts
[MAX_FD_COUNT
* MAX_EV_COUNT
], HrirDataT
*hData
)
2537 uint evTotal
= 0, azTotal
= 0, fi
, ei
, ai
;
2539 for(fi
= 0;fi
< fdCount
;fi
++)
2541 evTotal
+= evCounts
[fi
];
2542 for(ei
= 0;ei
< evCounts
[fi
];ei
++)
2543 azTotal
+= azCounts
[(fi
* MAX_EV_COUNT
) + ei
];
2545 if(!fdCount
|| !evTotal
|| !azTotal
)
2548 hData
->mFds
= calloc(fdCount
, sizeof(*hData
->mFds
));
2549 if(hData
->mFds
== NULL
)
2551 hData
->mFds
[0].mEvs
= calloc(evTotal
, sizeof(*hData
->mFds
[0].mEvs
));
2552 if(hData
->mFds
[0].mEvs
== NULL
)
2554 hData
->mFds
[0].mEvs
[0].mAzs
= calloc(azTotal
, sizeof(*hData
->mFds
[0].mEvs
[0].mAzs
));
2555 if(hData
->mFds
[0].mEvs
[0].mAzs
== NULL
)
2557 hData
->mIrCount
= azTotal
;
2558 hData
->mFdCount
= fdCount
;
2561 for(fi
= 0;fi
< fdCount
;fi
++)
2563 hData
->mFds
[fi
].mDistance
= distances
[fi
];
2564 hData
->mFds
[fi
].mEvCount
= evCounts
[fi
];
2565 hData
->mFds
[fi
].mEvStart
= 0;
2566 hData
->mFds
[fi
].mEvs
= &hData
->mFds
[0].mEvs
[evTotal
];
2567 evTotal
+= evCounts
[fi
];
2568 for(ei
= 0;ei
< evCounts
[fi
];ei
++)
2570 uint azCount
= azCounts
[(fi
* MAX_EV_COUNT
) + ei
];
2572 hData
->mFds
[fi
].mIrCount
+= azCount
;
2573 hData
->mFds
[fi
].mEvs
[ei
].mElevation
= -M_PI
/ 2.0 + M_PI
* ei
/ (evCounts
[fi
] - 1);
2574 hData
->mFds
[fi
].mEvs
[ei
].mIrCount
+= azCount
;
2575 hData
->mFds
[fi
].mEvs
[ei
].mAzCount
= azCount
;
2576 hData
->mFds
[fi
].mEvs
[ei
].mAzs
= &hData
->mFds
[0].mEvs
[0].mAzs
[azTotal
];
2577 for(ai
= 0;ai
< azCount
;ai
++)
2579 hData
->mFds
[fi
].mEvs
[ei
].mAzs
[ai
].mAzimuth
= 2.0 * M_PI
* ai
/ azCount
;
2580 hData
->mFds
[fi
].mEvs
[ei
].mAzs
[ai
].mIndex
= azTotal
+ ai
;
2581 hData
->mFds
[fi
].mEvs
[ei
].mAzs
[ai
].mDelays
[0] = 0.0;
2582 hData
->mFds
[fi
].mEvs
[ei
].mAzs
[ai
].mDelays
[1] = 0.0;
2583 hData
->mFds
[fi
].mEvs
[ei
].mAzs
[ai
].mIrs
[0] = NULL
;
2584 hData
->mFds
[fi
].mEvs
[ei
].mAzs
[ai
].mIrs
[1] = NULL
;
2592 // Clean up HRIR data.
2593 static void FreeHrirData(HrirDataT
*hData
)
2595 if(hData
->mFds
!= NULL
)
2597 if(hData
->mFds
[0].mEvs
!= NULL
)
2599 if(hData
->mFds
[0].mEvs
[0].mAzs
)
2601 free(hData
->mFds
[0].mEvs
[0].mAzs
[0].mIrs
[0]);
2602 free(hData
->mFds
[0].mEvs
[0].mAzs
);
2604 free(hData
->mFds
[0].mEvs
);
2611 // Match the channel type from a given identifier.
2612 static ChannelTypeT
MatchChannelType(const char *ident
)
2614 if(strcasecmp(ident
, "mono") == 0)
2616 if(strcasecmp(ident
, "stereo") == 0)
2621 // Process the data set definition to read and validate the data set metrics.
2622 static int ProcessMetrics(TokenReaderT
*tr
, const uint fftSize
, const uint truncSize
, HrirDataT
*hData
)
2624 int hasRate
= 0, hasType
= 0, hasPoints
= 0, hasRadius
= 0;
2625 int hasDistance
= 0, hasAzimuths
= 0;
2626 char ident
[MAX_IDENT_LEN
+1];
2631 double distances
[MAX_FD_COUNT
];
2633 uint evCounts
[MAX_FD_COUNT
];
2634 uint
*azCounts
= calloc(MAX_FD_COUNT
* MAX_EV_COUNT
, sizeof(*azCounts
));
2636 if(azCounts
== NULL
)
2638 fprintf(stderr
, "Error: Out of memory.\n");
2641 TrIndication(tr
, &line
, &col
);
2642 while(TrIsIdent(tr
))
2644 TrIndication(tr
, &line
, &col
);
2645 if(!TrReadIdent(tr
, MAX_IDENT_LEN
, ident
))
2647 if(strcasecmp(ident
, "rate") == 0)
2651 TrErrorAt(tr
, line
, col
, "Redefinition of 'rate'.\n");
2654 if(!TrReadOperator(tr
, "="))
2656 if(!TrReadInt(tr
, MIN_RATE
, MAX_RATE
, &intVal
))
2658 hData
->mIrRate
= (uint
)intVal
;
2661 else if(strcasecmp(ident
, "type") == 0)
2663 char type
[MAX_IDENT_LEN
+1];
2667 TrErrorAt(tr
, line
, col
, "Redefinition of 'type'.\n");
2670 if(!TrReadOperator(tr
, "="))
2673 if(!TrReadIdent(tr
, MAX_IDENT_LEN
, type
))
2675 hData
->mChannelType
= MatchChannelType(type
);
2676 if(hData
->mChannelType
== CT_NONE
)
2678 TrErrorAt(tr
, line
, col
, "Expected a channel type.\n");
2683 else if(strcasecmp(ident
, "points") == 0)
2687 TrErrorAt(tr
, line
, col
, "Redefinition of 'points'.\n");
2690 if(!TrReadOperator(tr
, "="))
2692 TrIndication(tr
, &line
, &col
);
2693 if(!TrReadInt(tr
, MIN_POINTS
, MAX_POINTS
, &intVal
))
2695 points
= (uint
)intVal
;
2696 if(fftSize
> 0 && points
> fftSize
)
2698 TrErrorAt(tr
, line
, col
, "Value exceeds the overridden FFT size.\n");
2701 if(points
< truncSize
)
2703 TrErrorAt(tr
, line
, col
, "Value is below the truncation size.\n");
2706 hData
->mIrPoints
= points
;
2709 hData
->mFftSize
= DEFAULT_FFTSIZE
;
2710 hData
->mIrSize
= 1 + (DEFAULT_FFTSIZE
/ 2);
2714 hData
->mFftSize
= fftSize
;
2715 hData
->mIrSize
= 1 + (fftSize
/ 2);
2716 if(points
> hData
->mIrSize
)
2717 hData
->mIrSize
= points
;
2721 else if(strcasecmp(ident
, "radius") == 0)
2725 TrErrorAt(tr
, line
, col
, "Redefinition of 'radius'.\n");
2728 if(!TrReadOperator(tr
, "="))
2730 if(!TrReadFloat(tr
, MIN_RADIUS
, MAX_RADIUS
, &fpVal
))
2732 hData
->mRadius
= fpVal
;
2735 else if(strcasecmp(ident
, "distance") == 0)
2741 TrErrorAt(tr
, line
, col
, "Redefinition of 'distance'.\n");
2744 if(!TrReadOperator(tr
, "="))
2749 if(!TrReadFloat(tr
, MIN_DISTANCE
, MAX_DISTANCE
, &fpVal
))
2751 if(count
> 0 && fpVal
<= distances
[count
- 1])
2753 TrError(tr
, "Distances are not ascending.\n");
2756 distances
[count
++] = fpVal
;
2757 if(!TrIsOperator(tr
, ","))
2759 if(count
>= MAX_FD_COUNT
)
2761 TrError(tr
, "Exceeded the maximum of %d fields.\n", MAX_FD_COUNT
);
2764 TrReadOperator(tr
, ",");
2766 if(fdCount
!= 0 && count
!= fdCount
)
2768 TrError(tr
, "Did not match the specified number of %d fields.\n", fdCount
);
2774 else if(strcasecmp(ident
, "azimuths") == 0)
2780 TrErrorAt(tr
, line
, col
, "Redefinition of 'azimuths'.\n");
2783 if(!TrReadOperator(tr
, "="))
2789 if(!TrReadInt(tr
, MIN_AZ_COUNT
, MAX_AZ_COUNT
, &intVal
))
2791 azCounts
[(count
* MAX_EV_COUNT
) + evCounts
[count
]++] = (uint
)intVal
;
2792 if(TrIsOperator(tr
, ","))
2794 if(evCounts
[count
] >= MAX_EV_COUNT
)
2796 TrError(tr
, "Exceeded the maximum of %d elevations.\n", MAX_EV_COUNT
);
2799 TrReadOperator(tr
, ",");
2803 if(evCounts
[count
] < MIN_EV_COUNT
)
2805 TrErrorAt(tr
, line
, col
, "Did not reach the minimum of %d azimuth counts.\n", MIN_EV_COUNT
);
2808 if(azCounts
[count
* MAX_EV_COUNT
] != 1 || azCounts
[(count
* MAX_EV_COUNT
) + evCounts
[count
] - 1] != 1)
2810 TrError(tr
, "Poles are not singular for field %d.\n", count
- 1);
2814 if(TrIsOperator(tr
, ";"))
2816 if(count
>= MAX_FD_COUNT
)
2818 TrError(tr
, "Exceeded the maximum number of %d fields.\n", MAX_FD_COUNT
);
2821 evCounts
[count
] = 0;
2822 TrReadOperator(tr
, ";");
2830 if(fdCount
!= 0 && count
!= fdCount
)
2832 TrError(tr
, "Did not match the specified number of %d fields.\n", fdCount
);
2840 TrErrorAt(tr
, line
, col
, "Expected a metric name.\n");
2843 TrSkipWhitespace(tr
);
2845 if(!(hasRate
&& hasPoints
&& hasRadius
&& hasDistance
&& hasAzimuths
))
2847 TrErrorAt(tr
, line
, col
, "Expected a metric name.\n");
2850 if(distances
[0] < hData
->mRadius
)
2852 TrError(tr
, "Distance cannot start below head radius.\n");
2855 if(hData
->mChannelType
== CT_NONE
)
2856 hData
->mChannelType
= CT_MONO
;
2857 if(!PrepareHrirData(fdCount
, distances
, evCounts
, azCounts
, hData
))
2859 fprintf(stderr
, "Error: Out of memory.\n");
2870 // Parse an index triplet from the data set definition.
2871 static int ReadIndexTriplet(TokenReaderT
*tr
, const HrirDataT
*hData
, uint
*fi
, uint
*ei
, uint
*ai
)
2875 if(hData
->mFdCount
> 1)
2877 if(!TrReadInt(tr
, 0, (int)hData
->mFdCount
- 1, &intVal
))
2880 if(!TrReadOperator(tr
, ","))
2887 if(!TrReadInt(tr
, 0, (int)hData
->mFds
[*fi
].mEvCount
- 1, &intVal
))
2890 if(!TrReadOperator(tr
, ","))
2892 if(!TrReadInt(tr
, 0, (int)hData
->mFds
[*fi
].mEvs
[*ei
].mAzCount
- 1, &intVal
))
2898 // Match the source format from a given identifier.
2899 static SourceFormatT
MatchSourceFormat(const char *ident
)
2901 if(strcasecmp(ident
, "wave") == 0)
2903 if(strcasecmp(ident
, "bin_le") == 0)
2905 if(strcasecmp(ident
, "bin_be") == 0)
2907 if(strcasecmp(ident
, "ascii") == 0)
2912 // Match the source element type from a given identifier.
2913 static ElementTypeT
MatchElementType(const char *ident
)
2915 if(strcasecmp(ident
, "int") == 0)
2917 if(strcasecmp(ident
, "fp") == 0)
2922 // Parse and validate a source reference from the data set definition.
2923 static int ReadSourceRef(TokenReaderT
*tr
, SourceRefT
*src
)
2925 char ident
[MAX_IDENT_LEN
+1];
2929 TrIndication(tr
, &line
, &col
);
2930 if(!TrReadIdent(tr
, MAX_IDENT_LEN
, ident
))
2932 src
->mFormat
= MatchSourceFormat(ident
);
2933 if(src
->mFormat
== SF_NONE
)
2935 TrErrorAt(tr
, line
, col
, "Expected a source format.\n");
2938 if(!TrReadOperator(tr
, "("))
2940 if(src
->mFormat
== SF_WAVE
)
2942 if(!TrReadInt(tr
, 0, MAX_WAVE_CHANNELS
, &intVal
))
2944 src
->mType
= ET_NONE
;
2947 src
->mChannel
= (uint
)intVal
;
2952 TrIndication(tr
, &line
, &col
);
2953 if(!TrReadIdent(tr
, MAX_IDENT_LEN
, ident
))
2955 src
->mType
= MatchElementType(ident
);
2956 if(src
->mType
== ET_NONE
)
2958 TrErrorAt(tr
, line
, col
, "Expected a source element type.\n");
2961 if(src
->mFormat
== SF_BIN_LE
|| src
->mFormat
== SF_BIN_BE
)
2963 if(!TrReadOperator(tr
, ","))
2965 if(src
->mType
== ET_INT
)
2967 if(!TrReadInt(tr
, MIN_BIN_SIZE
, MAX_BIN_SIZE
, &intVal
))
2969 src
->mSize
= (uint
)intVal
;
2970 if(!TrIsOperator(tr
, ","))
2971 src
->mBits
= (int)(8*src
->mSize
);
2974 TrReadOperator(tr
, ",");
2975 TrIndication(tr
, &line
, &col
);
2976 if(!TrReadInt(tr
, -2147483647-1, 2147483647, &intVal
))
2978 if(abs(intVal
) < MIN_BIN_BITS
|| (uint
)abs(intVal
) > (8*src
->mSize
))
2980 TrErrorAt(tr
, line
, col
, "Expected a value of (+/-) %d to %d.\n", MIN_BIN_BITS
, 8*src
->mSize
);
2983 src
->mBits
= intVal
;
2988 TrIndication(tr
, &line
, &col
);
2989 if(!TrReadInt(tr
, -2147483647-1, 2147483647, &intVal
))
2991 if(intVal
!= 4 && intVal
!= 8)
2993 TrErrorAt(tr
, line
, col
, "Expected a value of 4 or 8.\n");
2996 src
->mSize
= (uint
)intVal
;
3000 else if(src
->mFormat
== SF_ASCII
&& src
->mType
== ET_INT
)
3002 if(!TrReadOperator(tr
, ","))
3004 if(!TrReadInt(tr
, MIN_ASCII_BITS
, MAX_ASCII_BITS
, &intVal
))
3007 src
->mBits
= intVal
;
3015 if(!TrIsOperator(tr
, ";"))
3019 TrReadOperator(tr
, ";");
3020 if(!TrReadInt(tr
, 0, 0x7FFFFFFF, &intVal
))
3022 src
->mSkip
= (uint
)intVal
;
3025 if(!TrReadOperator(tr
, ")"))
3027 if(TrIsOperator(tr
, "@"))
3029 TrReadOperator(tr
, "@");
3030 if(!TrReadInt(tr
, 0, 0x7FFFFFFF, &intVal
))
3032 src
->mOffset
= (uint
)intVal
;
3036 if(!TrReadOperator(tr
, ":"))
3038 if(!TrReadString(tr
, MAX_PATH_LEN
, src
->mPath
))
3043 // Match the target ear (index) from a given identifier.
3044 static int MatchTargetEar(const char *ident
)
3046 if(strcasecmp(ident
, "left") == 0)
3048 if(strcasecmp(ident
, "right") == 0)
3053 // Process the list of sources in the data set definition.
3054 static int ProcessSources(const HeadModelT model
, TokenReaderT
*tr
, HrirDataT
*hData
)
3056 uint channels
= (hData
->mChannelType
== CT_STEREO
) ? 2 : 1;
3057 double *hrirs
= CreateDoubles(channels
* hData
->mIrCount
* hData
->mIrSize
);
3058 double *hrir
= CreateDoubles(hData
->mIrPoints
);
3059 uint line
, col
, fi
, ei
, ai
, ti
;
3062 printf("Loading sources...");
3065 while(TrIsOperator(tr
, "["))
3067 double factor
[2] = { 1.0, 1.0 };
3069 TrIndication(tr
, &line
, &col
);
3070 TrReadOperator(tr
, "[");
3071 if(!ReadIndexTriplet(tr
, hData
, &fi
, &ei
, &ai
))
3073 if(!TrReadOperator(tr
, "]"))
3075 HrirAzT
*azd
= &hData
->mFds
[fi
].mEvs
[ei
].mAzs
[ai
];
3077 if(azd
->mIrs
[0] != NULL
)
3079 TrErrorAt(tr
, line
, col
, "Redefinition of source.\n");
3082 if(!TrReadOperator(tr
, "="))
3090 if(!ReadSourceRef(tr
, &src
))
3093 // TODO: Would be nice to display 'x of y files', but that would
3094 // require preparing the source refs first to get a total count
3095 // before loading them.
3097 printf("\rLoading sources... %d file%s", count
, (count
==1)?"":"s");
3100 if(!LoadSource(&src
, hData
->mIrRate
, hData
->mIrPoints
, hrir
))
3103 if(hData
->mChannelType
== CT_STEREO
)
3105 char ident
[MAX_IDENT_LEN
+1];
3107 if(!TrReadIdent(tr
, MAX_IDENT_LEN
, ident
))
3109 ti
= MatchTargetEar(ident
);
3112 TrErrorAt(tr
, line
, col
, "Expected a target ear.\n");
3116 azd
->mIrs
[ti
] = &hrirs
[hData
->mIrSize
* (ti
* hData
->mIrCount
+ azd
->mIndex
)];
3117 if(model
== HM_DATASET
)
3118 azd
->mDelays
[ti
] = AverageHrirOnset(hData
->mIrRate
, hData
->mIrPoints
, hrir
, 1.0 / factor
[ti
], azd
->mDelays
[ti
]);
3119 AverageHrirMagnitude(hData
->mIrPoints
, hData
->mFftSize
, hrir
, 1.0 / factor
[ti
], azd
->mIrs
[ti
]);
3121 if(!TrIsOperator(tr
, "+"))
3123 TrReadOperator(tr
, "+");
3125 if(hData
->mChannelType
== CT_STEREO
)
3127 if(azd
->mIrs
[0] == NULL
)
3129 TrErrorAt(tr
, line
, col
, "Missing left ear source reference(s).\n");
3132 else if(azd
->mIrs
[1] == NULL
)
3134 TrErrorAt(tr
, line
, col
, "Missing right ear source reference(s).\n");
3140 for(fi
= 0;fi
< hData
->mFdCount
;fi
++)
3142 for(ei
= 0;ei
< hData
->mFds
[fi
].mEvCount
;ei
++)
3144 for(ai
= 0;ai
< hData
->mFds
[fi
].mEvs
[ei
].mAzCount
;ai
++)
3146 HrirAzT
*azd
= &hData
->mFds
[fi
].mEvs
[ei
].mAzs
[ai
];
3148 if(azd
->mIrs
[0] != NULL
)
3151 if(ai
< hData
->mFds
[fi
].mEvs
[ei
].mAzCount
)
3154 if(ei
>= hData
->mFds
[fi
].mEvCount
)
3156 TrError(tr
, "Missing source references [ %d, *, * ].\n", fi
);
3159 hData
->mFds
[fi
].mEvStart
= ei
;
3160 for(;ei
< hData
->mFds
[fi
].mEvCount
;ei
++)
3162 for(ai
= 0;ai
< hData
->mFds
[fi
].mEvs
[ei
].mAzCount
;ai
++)
3164 HrirAzT
*azd
= &hData
->mFds
[fi
].mEvs
[ei
].mAzs
[ai
];
3166 if(azd
->mIrs
[0] == NULL
)
3168 TrError(tr
, "Missing source reference [ %d, %d, %d ].\n", fi
, ei
, ai
);
3174 for(ti
= 0;ti
< channels
;ti
++)
3176 for(fi
= 0;fi
< hData
->mFdCount
;fi
++)
3178 for(ei
= 0;ei
< hData
->mFds
[fi
].mEvCount
;ei
++)
3180 for(ai
= 0;ai
< hData
->mFds
[fi
].mEvs
[ei
].mAzCount
;ai
++)
3182 HrirAzT
*azd
= &hData
->mFds
[fi
].mEvs
[ei
].mAzs
[ai
];
3184 azd
->mIrs
[ti
] = &hrirs
[hData
->mIrSize
* (ti
* hData
->mIrCount
+ azd
->mIndex
)];
3194 TrError(tr
, "Errant data at end of source list.\n");
3201 /* Parse the data set definition and process the source data, storing the
3202 * resulting data set as desired. If the input name is NULL it will read
3203 * from standard input.
3205 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 char *outName
)
3207 char rateStr
[8+1], expName
[MAX_PATH_LEN
];
3213 ResetHrirData(&hData
);
3214 fprintf(stdout
, "Reading HRIR definition from %s...\n", inName
?inName
:"stdin");
3217 fp
= fopen(inName
, "r");
3220 fprintf(stderr
, "Error: Could not open definition file '%s'\n", inName
);
3223 TrSetup(fp
, inName
, &tr
);
3228 TrSetup(fp
, "<stdin>", &tr
);
3230 if(!ProcessMetrics(&tr
, fftSize
, truncSize
, &hData
))
3236 if(!ProcessSources(model
, &tr
, &hData
))
3238 FreeHrirData(&hData
);
3247 uint c
= (hData
.mChannelType
== CT_STEREO
) ? 2 : 1;
3248 uint m
= 1 + hData
.mFftSize
/ 2;
3249 double *dfa
= CreateDoubles(c
* m
);
3251 fprintf(stdout
, "Calculating diffuse-field average...\n");
3252 CalculateDiffuseFieldAverage(&hData
, c
, m
, surface
, limit
, dfa
);
3253 fprintf(stdout
, "Performing diffuse-field equalization...\n");
3254 DiffuseFieldEqualize(c
, m
, dfa
, &hData
);
3257 fprintf(stdout
, "Performing minimum phase reconstruction...\n");
3258 ReconstructHrirs(&hData
);
3259 if(outRate
!= 0 && outRate
!= hData
.mIrRate
)
3261 fprintf(stdout
, "Resampling HRIRs...\n");
3262 ResampleHrirs(outRate
, &hData
);
3264 fprintf(stdout
, "Truncating minimum-phase HRIRs...\n");
3265 hData
.mIrPoints
= truncSize
;
3266 fprintf(stdout
, "Synthesizing missing elevations...\n");
3267 if(model
== HM_DATASET
)
3268 SynthesizeOnsets(&hData
);
3269 SynthesizeHrirs(&hData
);
3270 fprintf(stdout
, "Normalizing final HRIRs...\n");
3271 NormalizeHrirs(&hData
);
3272 fprintf(stdout
, "Calculating impulse delays...\n");
3273 CalculateHrtds(model
, (radius
> DEFAULT_CUSTOM_RADIUS
) ? radius
: hData
.mRadius
, &hData
);
3274 snprintf(rateStr
, 8, "%u", hData
.mIrRate
);
3275 StrSubst(outName
, "%r", rateStr
, MAX_PATH_LEN
, expName
);
3276 fprintf(stdout
, "Creating MHR data set %s...\n", expName
);
3277 ret
= StoreMhr(&hData
, expName
);
3279 FreeHrirData(&hData
);
3283 static void PrintHelp(const char *argv0
, FILE *ofile
)
3285 fprintf(ofile
, "Usage: %s [<option>...]\n\n", argv0
);
3286 fprintf(ofile
, "Options:\n");
3287 fprintf(ofile
, " -m Ignored for compatibility.\n");
3288 fprintf(ofile
, " -r <rate> Change the data set sample rate to the specified value and\n");
3289 fprintf(ofile
, " resample the HRIRs accordingly.\n");
3290 fprintf(ofile
, " -f <points> Override the FFT window size (default: %u).\n", DEFAULT_FFTSIZE
);
3291 fprintf(ofile
, " -e {on|off} Toggle diffuse-field equalization (default: %s).\n", (DEFAULT_EQUALIZE
? "on" : "off"));
3292 fprintf(ofile
, " -s {on|off} Toggle surface-weighted diffuse-field average (default: %s).\n", (DEFAULT_SURFACE
? "on" : "off"));
3293 fprintf(ofile
, " -l {<dB>|none} Specify a limit to the magnitude range of the diffuse-field\n");
3294 fprintf(ofile
, " average (default: %.2f).\n", DEFAULT_LIMIT
);
3295 fprintf(ofile
, " -w <points> Specify the size of the truncation window that's applied\n");
3296 fprintf(ofile
, " after minimum-phase reconstruction (default: %u).\n", DEFAULT_TRUNCSIZE
);
3297 fprintf(ofile
, " -d {dataset| Specify the model used for calculating the head-delay timing\n");
3298 fprintf(ofile
, " sphere} values (default: %s).\n", ((DEFAULT_HEAD_MODEL
== HM_DATASET
) ? "dataset" : "sphere"));
3299 fprintf(ofile
, " -c <size> Use a customized head radius measured ear-to-ear in meters.\n");
3300 fprintf(ofile
, " -i <filename> Specify an HRIR definition file to use (defaults to stdin).\n");
3301 fprintf(ofile
, " -o <filename> Specify an output file. Use of '%%r' will be substituted with\n");
3302 fprintf(ofile
, " the data set sample rate.\n");
3305 // Standard command line dispatch.
3306 int main(int argc
, char *argv
[])
3308 const char *inName
= NULL
, *outName
= NULL
;
3309 uint outRate
, fftSize
;
3310 int equalize
, surface
;
3318 GET_UNICODE_ARGS(&argc
, &argv
);
3322 fprintf(stdout
, "HRTF Processing and Composition Utility\n\n");
3323 PrintHelp(argv
[0], stdout
);
3327 outName
= "./oalsoft_hrtf_%r.mhr";
3330 equalize
= DEFAULT_EQUALIZE
;
3331 surface
= DEFAULT_SURFACE
;
3332 limit
= DEFAULT_LIMIT
;
3333 truncSize
= DEFAULT_TRUNCSIZE
;
3334 model
= DEFAULT_HEAD_MODEL
;
3335 radius
= DEFAULT_CUSTOM_RADIUS
;
3337 while((opt
=getopt(argc
, argv
, "mr:f:e:s:l:w:d:c:e:i:o:h")) != -1)
3342 fprintf(stderr
, "Ignoring unused command '-m'.\n");
3346 outRate
= strtoul(optarg
, &end
, 10);
3347 if(end
[0] != '\0' || outRate
< MIN_RATE
|| outRate
> MAX_RATE
)
3349 fprintf(stderr
, "Error: Got unexpected value \"%s\" for option -%c, expected between %u to %u.\n", optarg
, opt
, MIN_RATE
, MAX_RATE
);
3355 fftSize
= strtoul(optarg
, &end
, 10);
3356 if(end
[0] != '\0' || (fftSize
&(fftSize
-1)) || fftSize
< MIN_FFTSIZE
|| fftSize
> MAX_FFTSIZE
)
3358 fprintf(stderr
, "Error: Got unexpected value \"%s\" for option -%c, expected a power-of-two between %u to %u.\n", optarg
, opt
, MIN_FFTSIZE
, MAX_FFTSIZE
);
3364 if(strcmp(optarg
, "on") == 0)
3366 else if(strcmp(optarg
, "off") == 0)
3370 fprintf(stderr
, "Error: Got unexpected value \"%s\" for option -%c, expected on or off.\n", optarg
, opt
);
3376 if(strcmp(optarg
, "on") == 0)
3378 else if(strcmp(optarg
, "off") == 0)
3382 fprintf(stderr
, "Error: Got unexpected value \"%s\" for option -%c, expected on or off.\n", optarg
, opt
);
3388 if(strcmp(optarg
, "none") == 0)
3392 limit
= strtod(optarg
, &end
);
3393 if(end
[0] != '\0' || limit
< MIN_LIMIT
|| limit
> MAX_LIMIT
)
3395 fprintf(stderr
, "Error: Got unexpected value \"%s\" for option -%c, expected between %.0f to %.0f.\n", optarg
, opt
, MIN_LIMIT
, MAX_LIMIT
);
3402 truncSize
= strtoul(optarg
, &end
, 10);
3403 if(end
[0] != '\0' || truncSize
< MIN_TRUNCSIZE
|| truncSize
> MAX_TRUNCSIZE
|| (truncSize
%MOD_TRUNCSIZE
))
3405 fprintf(stderr
, "Error: Got unexpected value \"%s\" for option -%c, expected multiple of %u between %u to %u.\n", optarg
, opt
, MOD_TRUNCSIZE
, MIN_TRUNCSIZE
, MAX_TRUNCSIZE
);
3411 if(strcmp(optarg
, "dataset") == 0)
3413 else if(strcmp(optarg
, "sphere") == 0)
3417 fprintf(stderr
, "Error: Got unexpected value \"%s\" for option -%c, expected dataset or sphere.\n", optarg
, opt
);
3423 radius
= strtod(optarg
, &end
);
3424 if(end
[0] != '\0' || radius
< MIN_CUSTOM_RADIUS
|| radius
> MAX_CUSTOM_RADIUS
)
3426 fprintf(stderr
, "Error: Got unexpected value \"%s\" for option -%c, expected between %.2f to %.2f.\n", optarg
, opt
, MIN_CUSTOM_RADIUS
, MAX_CUSTOM_RADIUS
);
3440 PrintHelp(argv
[0], stdout
);
3444 PrintHelp(argv
[0], stderr
);
3449 if(!ProcessDefinition(inName
, outRate
, fftSize
, equalize
, surface
, limit
,
3450 truncSize
, model
, radius
, outName
))
3452 fprintf(stdout
, "Operation completed.\n");
3454 return EXIT_SUCCESS
;