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
80 // Rely (if naively) on OpenAL's header for the types used for serialization.
85 #define M_PI (3.14159265358979323846)
89 #define HUGE_VAL (1.0 / 0.0)
94 #define WIN32_LEAN_AND_MEAN
97 static char *ToUTF8(const wchar_t *from
)
101 if((len
=WideCharToMultiByte(CP_UTF8
, 0, from
, -1, NULL
, 0, NULL
, NULL
)) > 0)
103 out
= calloc(sizeof(*out
), len
);
104 WideCharToMultiByte(CP_UTF8
, 0, from
, -1, out
, len
, NULL
, NULL
);
110 static WCHAR
*FromUTF8(const char *str
)
115 if((len
=MultiByteToWideChar(CP_UTF8
, 0, str
, -1, NULL
, 0)) > 0)
117 out
= calloc(sizeof(WCHAR
), len
);
118 MultiByteToWideChar(CP_UTF8
, 0, str
, -1, out
, len
);
125 static FILE *my_fopen(const char *fname
, const char *mode
)
127 WCHAR
*wname
=NULL
, *wmode
=NULL
;
130 wname
= FromUTF8(fname
);
131 wmode
= FromUTF8(mode
);
133 fprintf(stderr
, "Failed to convert UTF-8 filename: \"%s\"\n", fname
);
135 fprintf(stderr
, "Failed to convert UTF-8 mode: \"%s\"\n", mode
);
137 file
= _wfopen(wname
, wmode
);
144 #define fopen my_fopen
147 // The epsilon used to maintain signal stability.
148 #define EPSILON (1e-9)
150 // Constants for accessing the token reader's ring buffer.
151 #define TR_RING_BITS (16)
152 #define TR_RING_SIZE (1 << TR_RING_BITS)
153 #define TR_RING_MASK (TR_RING_SIZE - 1)
155 // The token reader's load interval in bytes.
156 #define TR_LOAD_SIZE (TR_RING_SIZE >> 2)
158 // The maximum identifier length used when processing the data set
160 #define MAX_IDENT_LEN (16)
162 // The maximum path length used when processing filenames.
163 #define MAX_PATH_LEN (256)
165 // The limits for the sample 'rate' metric in the data set definition and for
167 #define MIN_RATE (32000)
168 #define MAX_RATE (96000)
170 // The limits for the HRIR 'points' metric in the data set definition.
171 #define MIN_POINTS (16)
172 #define MAX_POINTS (8192)
174 // The limits to the number of 'azimuths' listed in the data set definition.
175 #define MIN_EV_COUNT (5)
176 #define MAX_EV_COUNT (128)
178 // The limits for each of the 'azimuths' listed in the data set definition.
179 #define MIN_AZ_COUNT (1)
180 #define MAX_AZ_COUNT (128)
182 // The limits for the listener's head 'radius' in the data set definition.
183 #define MIN_RADIUS (0.05)
184 #define MAX_RADIUS (0.15)
186 // The limits for the 'distance' from source to listener in the definition
188 #define MIN_DISTANCE (0.5)
189 #define MAX_DISTANCE (2.5)
191 // The maximum number of channels that can be addressed for a WAVE file
192 // source listed in the data set definition.
193 #define MAX_WAVE_CHANNELS (65535)
195 // The limits to the byte size for a binary source listed in the definition
197 #define MIN_BIN_SIZE (2)
198 #define MAX_BIN_SIZE (4)
200 // The minimum number of significant bits for binary sources listed in the
201 // data set definition. The maximum is calculated from the byte size.
202 #define MIN_BIN_BITS (16)
204 // The limits to the number of significant bits for an ASCII source listed in
205 // the data set definition.
206 #define MIN_ASCII_BITS (16)
207 #define MAX_ASCII_BITS (32)
209 // The limits to the FFT window size override on the command line.
210 #define MIN_FFTSIZE (65536)
211 #define MAX_FFTSIZE (131072)
213 // The limits to the equalization range limit on the command line.
214 #define MIN_LIMIT (2.0)
215 #define MAX_LIMIT (120.0)
217 // The limits to the truncation window size on the command line.
218 #define MIN_TRUNCSIZE (16)
219 #define MAX_TRUNCSIZE (512)
221 // The limits to the custom head radius on the command line.
222 #define MIN_CUSTOM_RADIUS (0.05)
223 #define MAX_CUSTOM_RADIUS (0.15)
225 // The truncation window size must be a multiple of the below value to allow
226 // for vectorized convolution.
227 #define MOD_TRUNCSIZE (8)
229 // The defaults for the command line options.
230 #define DEFAULT_FFTSIZE (65536)
231 #define DEFAULT_EQUALIZE (1)
232 #define DEFAULT_SURFACE (1)
233 #define DEFAULT_LIMIT (24.0)
234 #define DEFAULT_TRUNCSIZE (32)
235 #define DEFAULT_HEAD_MODEL (HM_DATASET)
236 #define DEFAULT_CUSTOM_RADIUS (0.0)
238 // The four-character-codes for RIFF/RIFX WAVE file chunks.
239 #define FOURCC_RIFF (0x46464952) // 'RIFF'
240 #define FOURCC_RIFX (0x58464952) // 'RIFX'
241 #define FOURCC_WAVE (0x45564157) // 'WAVE'
242 #define FOURCC_FMT (0x20746D66) // 'fmt '
243 #define FOURCC_DATA (0x61746164) // 'data'
244 #define FOURCC_LIST (0x5453494C) // 'LIST'
245 #define FOURCC_WAVL (0x6C766177) // 'wavl'
246 #define FOURCC_SLNT (0x746E6C73) // 'slnt'
248 // The supported wave formats.
249 #define WAVE_FORMAT_PCM (0x0001)
250 #define WAVE_FORMAT_IEEE_FLOAT (0x0003)
251 #define WAVE_FORMAT_EXTENSIBLE (0xFFFE)
253 // The maximum propagation delay value supported by OpenAL Soft.
254 #define MAX_HRTD (63.0)
256 // The OpenAL Soft HRTF format marker. It stands for minimum-phase head
257 // response protocol 01.
258 #define MHR_FORMAT ("MinPHR01")
260 #define MHR_FORMAT_EXPERIMENTAL ("MinPHRTEMPDONOTUSE")
262 // Sample and channel type enum values
263 typedef enum SampleTypeT
{
268 typedef enum ChannelTypeT
{
273 // Byte order for the serialization routines.
274 typedef enum ByteOrderT
{
280 // Source format for the references listed in the data set definition.
281 typedef enum SourceFormatT
{
283 SF_WAVE
, // RIFF/RIFX WAVE file.
284 SF_BIN_LE
, // Little-endian binary file.
285 SF_BIN_BE
, // Big-endian binary file.
286 SF_ASCII
// ASCII text file.
289 // Element types for the references listed in the data set definition.
290 typedef enum ElementTypeT
{
292 ET_INT
, // Integer elements.
293 ET_FP
// Floating-point elements.
296 // Head model used for calculating the impulse delays.
297 typedef enum HeadModelT
{
299 HM_DATASET
, // Measure the onset from the dataset.
300 HM_SPHERE
// Calculate the onset using a spherical head model.
303 // Unsigned integer type.
304 typedef unsigned int uint
;
306 // Serialization types. The trailing digit indicates the number of bits.
307 typedef ALubyte uint8
;
309 typedef ALuint uint32
;
310 typedef ALuint64SOFT uint64
;
312 // Token reader state for parsing the data set definition.
313 typedef struct TokenReaderT
{
318 char mRing
[TR_RING_SIZE
];
323 // Source reference state used when loading sources.
324 typedef struct SourceRefT
{
325 SourceFormatT mFormat
;
332 char mPath
[MAX_PATH_LEN
+1];
335 // The HRIR metrics and data set used when loading, processing, and storing
336 // the resulting HRTF.
337 typedef struct HrirDataT
{
339 SampleTypeT mSampleType
;
340 ChannelTypeT mChannelType
;
347 uint mAzCount
[MAX_EV_COUNT
];
348 uint mEvOffset
[MAX_EV_COUNT
];
356 // The resampler metrics and FIR filter.
357 typedef struct ResamplerT
{
363 /****************************************
364 *** Complex number type and routines ***
365 ****************************************/
371 static Complex
MakeComplex(double r
, double i
)
373 Complex c
= { r
, i
};
377 static Complex
c_add(Complex a
, Complex b
)
380 r
.Real
= a
.Real
+ b
.Real
;
381 r
.Imag
= a
.Imag
+ b
.Imag
;
385 static Complex
c_sub(Complex a
, Complex b
)
388 r
.Real
= a
.Real
- b
.Real
;
389 r
.Imag
= a
.Imag
- b
.Imag
;
393 static Complex
c_mul(Complex a
, Complex b
)
396 r
.Real
= a
.Real
*b
.Real
- a
.Imag
*b
.Imag
;
397 r
.Imag
= a
.Imag
*b
.Real
+ a
.Real
*b
.Imag
;
401 static Complex
c_muls(Complex a
, double s
)
409 static double c_abs(Complex a
)
411 return sqrt(a
.Real
*a
.Real
+ a
.Imag
*a
.Imag
);
414 static Complex
c_exp(Complex a
)
417 double e
= exp(a
.Real
);
418 r
.Real
= e
* cos(a
.Imag
);
419 r
.Imag
= e
* sin(a
.Imag
);
423 /*****************************
424 *** Token reader routines ***
425 *****************************/
427 /* Whitespace is not significant. It can process tokens as identifiers, numbers
428 * (integer and floating-point), strings, and operators. Strings must be
429 * encapsulated by double-quotes and cannot span multiple lines.
432 // Setup the reader on the given file. The filename can be NULL if no error
433 // output is desired.
434 static void TrSetup(FILE *fp
, const char *filename
, TokenReaderT
*tr
)
436 const char *name
= NULL
;
440 const char *slash
= strrchr(filename
, '/');
443 const char *bslash
= strrchr(slash
+1, '\\');
444 if(bslash
) name
= bslash
+1;
449 const char *bslash
= strrchr(filename
, '\\');
450 if(bslash
) name
= bslash
+1;
451 else name
= filename
;
463 // Prime the reader's ring buffer, and return a result indicating that there
464 // is text to process.
465 static int TrLoad(TokenReaderT
*tr
)
467 size_t toLoad
, in
, count
;
469 toLoad
= TR_RING_SIZE
- (tr
->mIn
- tr
->mOut
);
470 if(toLoad
>= TR_LOAD_SIZE
&& !feof(tr
->mFile
))
472 // Load TR_LOAD_SIZE (or less if at the end of the file) per read.
473 toLoad
= TR_LOAD_SIZE
;
474 in
= tr
->mIn
&TR_RING_MASK
;
475 count
= TR_RING_SIZE
- in
;
478 tr
->mIn
+= fread(&tr
->mRing
[in
], 1, count
, tr
->mFile
);
479 tr
->mIn
+= fread(&tr
->mRing
[0], 1, toLoad
-count
, tr
->mFile
);
482 tr
->mIn
+= fread(&tr
->mRing
[in
], 1, toLoad
, tr
->mFile
);
484 if(tr
->mOut
>= TR_RING_SIZE
)
486 tr
->mOut
-= TR_RING_SIZE
;
487 tr
->mIn
-= TR_RING_SIZE
;
490 if(tr
->mIn
> tr
->mOut
)
495 // Error display routine. Only displays when the base name is not NULL.
496 static void TrErrorVA(const TokenReaderT
*tr
, uint line
, uint column
, const char *format
, va_list argPtr
)
500 fprintf(stderr
, "Error (%s:%u:%u): ", tr
->mName
, line
, column
);
501 vfprintf(stderr
, format
, argPtr
);
504 // Used to display an error at a saved line/column.
505 static void TrErrorAt(const TokenReaderT
*tr
, uint line
, uint column
, const char *format
, ...)
509 va_start(argPtr
, format
);
510 TrErrorVA(tr
, line
, column
, format
, argPtr
);
514 // Used to display an error at the current line/column.
515 static void TrError(const TokenReaderT
*tr
, const char *format
, ...)
519 va_start(argPtr
, format
);
520 TrErrorVA(tr
, tr
->mLine
, tr
->mColumn
, format
, argPtr
);
524 // Skips to the next line.
525 static void TrSkipLine(TokenReaderT
*tr
)
531 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
543 // Skips to the next token.
544 static int TrSkipWhitespace(TokenReaderT
*tr
)
550 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
570 // Get the line and/or column of the next token (or the end of input).
571 static void TrIndication(TokenReaderT
*tr
, uint
*line
, uint
*column
)
573 TrSkipWhitespace(tr
);
574 if(line
) *line
= tr
->mLine
;
575 if(column
) *column
= tr
->mColumn
;
578 // Checks to see if a token is the given operator. It does not display any
579 // errors and will not proceed to the next token.
580 static int TrIsOperator(TokenReaderT
*tr
, const char *op
)
585 if(!TrSkipWhitespace(tr
))
589 while(op
[len
] != '\0' && out
< tr
->mIn
)
591 ch
= tr
->mRing
[out
&TR_RING_MASK
];
592 if(ch
!= op
[len
]) break;
601 /* The TrRead*() routines obtain the value of a matching token type. They
602 * display type, form, and boundary errors and will proceed to the next
606 // Reads and validates an identifier token.
607 static int TrReadIdent(TokenReaderT
*tr
, const uint maxLen
, char *ident
)
613 if(TrSkipWhitespace(tr
))
616 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
617 if(ch
== '_' || isalpha(ch
))
627 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
628 } while(ch
== '_' || isdigit(ch
) || isalpha(ch
));
636 TrErrorAt(tr
, tr
->mLine
, col
, "Identifier is too long.\n");
640 TrErrorAt(tr
, tr
->mLine
, col
, "Expected an identifier.\n");
644 // Reads and validates (including bounds) an integer token.
645 static int TrReadInt(TokenReaderT
*tr
, const int loBound
, const int hiBound
, int *value
)
647 uint col
, digis
, len
;
651 if(TrSkipWhitespace(tr
))
655 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
656 if(ch
== '+' || ch
== '-')
665 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
666 if(!isdigit(ch
)) break;
674 if(digis
> 0 && ch
!= '.' && !isalpha(ch
))
678 TrErrorAt(tr
, tr
->mLine
, col
, "Integer is too long.");
682 *value
= strtol(temp
, NULL
, 10);
683 if(*value
< loBound
|| *value
> hiBound
)
685 TrErrorAt(tr
, tr
->mLine
, col
, "Expected a value from %d to %d.\n", loBound
, hiBound
);
691 TrErrorAt(tr
, tr
->mLine
, col
, "Expected an integer.\n");
695 // Reads and validates (including bounds) a float token.
696 static int TrReadFloat(TokenReaderT
*tr
, const double loBound
, const double hiBound
, double *value
)
698 uint col
, digis
, len
;
702 if(TrSkipWhitespace(tr
))
706 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
707 if(ch
== '+' || ch
== '-')
717 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
718 if(!isdigit(ch
)) break;
734 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
735 if(!isdigit(ch
)) break;
744 if(ch
== 'E' || ch
== 'e')
751 if(ch
== '+' || ch
== '-')
760 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
761 if(!isdigit(ch
)) break;
770 if(digis
> 0 && ch
!= '.' && !isalpha(ch
))
774 TrErrorAt(tr
, tr
->mLine
, col
, "Float is too long.");
778 *value
= strtod(temp
, NULL
);
779 if(*value
< loBound
|| *value
> hiBound
)
781 TrErrorAt (tr
, tr
->mLine
, col
, "Expected a value from %f to %f.\n", loBound
, hiBound
);
790 TrErrorAt(tr
, tr
->mLine
, col
, "Expected a float.\n");
794 // Reads and validates a string token.
795 static int TrReadString(TokenReaderT
*tr
, const uint maxLen
, char *text
)
801 if(TrSkipWhitespace(tr
))
804 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
811 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
817 TrErrorAt (tr
, tr
->mLine
, col
, "Unterminated string at end of line.\n");
826 tr
->mColumn
+= 1 + len
;
827 TrErrorAt(tr
, tr
->mLine
, col
, "Unterminated string at end of input.\n");
830 tr
->mColumn
+= 2 + len
;
833 TrErrorAt (tr
, tr
->mLine
, col
, "String is too long.\n");
840 TrErrorAt(tr
, tr
->mLine
, col
, "Expected a string.\n");
844 // Reads and validates the given operator.
845 static int TrReadOperator(TokenReaderT
*tr
, const char *op
)
851 if(TrSkipWhitespace(tr
))
855 while(op
[len
] != '\0' && TrLoad(tr
))
857 ch
= tr
->mRing
[tr
->mOut
&TR_RING_MASK
];
858 if(ch
!= op
[len
]) break;
866 TrErrorAt(tr
, tr
->mLine
, col
, "Expected '%s' operator.\n", op
);
870 /* Performs a string substitution. Any case-insensitive occurrences of the
871 * pattern string are replaced with the replacement string. The result is
872 * truncated if necessary.
874 static int StrSubst(const char *in
, const char *pat
, const char *rep
, const size_t maxLen
, char *out
)
876 size_t inLen
, patLen
, repLen
;
881 patLen
= strlen(pat
);
882 repLen
= strlen(rep
);
886 while(si
< inLen
&& di
< maxLen
)
888 if(patLen
<= inLen
-si
)
890 if(strncasecmp(&in
[si
], pat
, patLen
) == 0)
892 if(repLen
> maxLen
-di
)
894 repLen
= maxLen
- di
;
897 strncpy(&out
[di
], rep
, repLen
);
913 /*********************
914 *** Math routines ***
915 *********************/
917 // Provide missing math routines for MSVC versions < 1800 (Visual Studio 2013).
918 #if defined(_MSC_VER) && _MSC_VER < 1800
919 static double round(double val
)
922 return ceil(val
-0.5);
923 return floor(val
+0.5);
926 static double fmin(double a
, double b
)
928 return (a
<b
) ? a
: b
;
931 static double fmax(double a
, double b
)
933 return (a
>b
) ? a
: b
;
937 // Simple clamp routine.
938 static double Clamp(const double val
, const double lower
, const double upper
)
940 return fmin(fmax(val
, lower
), upper
);
943 // Performs linear interpolation.
944 static double Lerp(const double a
, const double b
, const double f
)
946 return a
+ (f
* (b
- a
));
949 static inline uint
dither_rng(uint
*seed
)
951 *seed
= (*seed
* 96314165) + 907633515;
955 // Performs a triangular probability density function dither. It assumes the
956 // input sample is already scaled.
957 static inline double TpdfDither(const double in
, uint
*seed
)
959 static const double PRNG_SCALE
= 1.0 / UINT_MAX
;
962 prn0
= dither_rng(seed
);
963 prn1
= dither_rng(seed
);
964 return round(in
+ (prn0
*PRNG_SCALE
- prn1
*PRNG_SCALE
));
967 // Allocates an array of doubles.
968 static double *CreateArray(size_t n
)
973 a
= calloc(n
, sizeof(double));
976 fprintf(stderr
, "Error: Out of memory.\n");
982 // Frees an array of doubles.
983 static void DestroyArray(double *a
)
986 /* Fast Fourier transform routines. The number of points must be a power of
987 * two. In-place operation is possible only if both the real and imaginary
988 * parts are in-place together.
991 // Performs bit-reversal ordering.
992 static void FftArrange(const uint n
, const Complex
*in
, Complex
*out
)
998 // Handle in-place arrangement.
1000 for(k
= 0;k
< n
;k
++)
1004 Complex temp
= in
[rk
];
1016 // Handle copy arrangement.
1018 for(k
= 0;k
< n
;k
++)
1029 // Performs the summation.
1030 static void FftSummation(const int n
, const double s
, Complex
*cplx
)
1037 for(m
= 1, m2
= 2;m
< n
; m
<<= 1, m2
<<= 1)
1039 // v = Complex (-2.0 * sin (0.5 * pi / m) * sin (0.5 * pi / m), -sin (pi / m))
1040 double sm
= sin(0.5 * pi
/ m
);
1041 Complex v
= MakeComplex(-2.0*sm
*sm
, -sin(pi
/ m
));
1042 Complex w
= MakeComplex(1.0, 0.0);
1043 for(i
= 0;i
< m
;i
++)
1045 for(k
= i
;k
< n
;k
+= m2
)
1049 t
= c_mul(w
, cplx
[mk
]);
1050 cplx
[mk
] = c_sub(cplx
[k
], t
);
1051 cplx
[k
] = c_add(cplx
[k
], t
);
1053 w
= c_add(w
, c_mul(v
, w
));
1058 // Performs a forward FFT.
1059 static void FftForward(const uint n
, const Complex
*in
, Complex
*out
)
1061 FftArrange(n
, in
, out
);
1062 FftSummation(n
, 1.0, out
);
1065 // Performs an inverse FFT.
1066 static void FftInverse(const uint n
, const Complex
*in
, Complex
*out
)
1071 FftArrange(n
, in
, out
);
1072 FftSummation(n
, -1.0, out
);
1074 for(i
= 0;i
< n
;i
++)
1075 out
[i
] = c_muls(out
[i
], f
);
1078 /* Calculate the complex helical sequence (or discrete-time analytical signal)
1079 * of the given input using the Hilbert transform. Given the natural logarithm
1080 * of a signal's magnitude response, the imaginary components can be used as
1081 * the angles for minimum-phase reconstruction.
1083 static void Hilbert(const uint n
, const Complex
*in
, Complex
*out
)
1089 // Handle in-place operation.
1090 for(i
= 0;i
< n
;i
++)
1095 // Handle copy operation.
1096 for(i
= 0;i
< n
;i
++)
1097 out
[i
] = MakeComplex(in
[i
].Real
, 0.0);
1099 FftInverse(n
, out
, out
);
1100 for(i
= 1;i
< (n
+1)/2;i
++)
1101 out
[i
] = c_muls(out
[i
], 2.0);
1102 /* Increment i if n is even. */
1105 out
[i
] = MakeComplex(0.0, 0.0);
1106 FftForward(n
, out
, out
);
1109 /* Calculate the magnitude response of the given input. This is used in
1110 * place of phase decomposition, since the phase residuals are discarded for
1111 * minimum phase reconstruction. The mirrored half of the response is also
1114 static void MagnitudeResponse(const uint n
, const Complex
*in
, double *out
)
1116 const uint m
= 1 + (n
/ 2);
1118 for(i
= 0;i
< m
;i
++)
1119 out
[i
] = fmax(c_abs(in
[i
]), EPSILON
);
1122 /* Apply a range limit (in dB) to the given magnitude response. This is used
1123 * to adjust the effects of the diffuse-field average on the equalization
1126 static void LimitMagnitudeResponse(const uint n
, const double limit
, const double *in
, double *out
)
1128 const uint m
= 1 + (n
/ 2);
1130 uint i
, lower
, upper
;
1133 halfLim
= limit
/ 2.0;
1134 // Convert the response to dB.
1135 for(i
= 0;i
< m
;i
++)
1136 out
[i
] = 20.0 * log10(in
[i
]);
1137 // Use six octaves to calculate the average magnitude of the signal.
1138 lower
= ((uint
)ceil(n
/ pow(2.0, 8.0))) - 1;
1139 upper
= ((uint
)floor(n
/ pow(2.0, 2.0))) - 1;
1141 for(i
= lower
;i
<= upper
;i
++)
1143 ave
/= upper
- lower
+ 1;
1144 // Keep the response within range of the average magnitude.
1145 for(i
= 0;i
< m
;i
++)
1146 out
[i
] = Clamp(out
[i
], ave
- halfLim
, ave
+ halfLim
);
1147 // Convert the response back to linear magnitude.
1148 for(i
= 0;i
< m
;i
++)
1149 out
[i
] = pow(10.0, out
[i
] / 20.0);
1152 /* Reconstructs the minimum-phase component for the given magnitude response
1153 * of a signal. This is equivalent to phase recomposition, sans the missing
1154 * residuals (which were discarded). The mirrored half of the response is
1157 static void MinimumPhase(const uint n
, const double *in
, Complex
*out
)
1159 const uint m
= 1 + (n
/ 2);
1163 mags
= CreateArray(n
);
1164 for(i
= 0;i
< m
;i
++)
1166 mags
[i
] = fmax(EPSILON
, in
[i
]);
1167 out
[i
] = MakeComplex(log(mags
[i
]), 0.0);
1171 mags
[i
] = mags
[n
- i
];
1172 out
[i
] = out
[n
- i
];
1174 Hilbert(n
, out
, out
);
1175 // Remove any DC offset the filter has.
1177 for(i
= 0;i
< n
;i
++)
1179 Complex a
= c_exp(MakeComplex(0.0, out
[i
].Imag
));
1180 out
[i
] = c_mul(MakeComplex(mags
[i
], 0.0), a
);
1186 /***************************
1187 *** Resampler functions ***
1188 ***************************/
1190 /* This is the normalized cardinal sine (sinc) function.
1192 * sinc(x) = { 1, x = 0
1193 * { sin(pi x) / (pi x), otherwise.
1195 static double Sinc(const double x
)
1197 if(fabs(x
) < EPSILON
)
1199 return sin(M_PI
* x
) / (M_PI
* x
);
1202 /* The zero-order modified Bessel function of the first kind, used for the
1205 * I_0(x) = sum_{k=0}^inf (1 / k!)^2 (x / 2)^(2 k)
1206 * = sum_{k=0}^inf ((x / 2)^k / k!)^2
1208 static double BesselI_0(const double x
)
1210 double term
, sum
, x2
, y
, last_sum
;
1213 // Start at k=1 since k=0 is trivial.
1219 // Let the integration converge until the term of the sum is no longer
1227 } while(sum
!= last_sum
);
1231 /* Calculate a Kaiser window from the given beta value and a normalized k
1234 * w(k) = { I_0(B sqrt(1 - k^2)) / I_0(B), -1 <= k <= 1
1237 * Where k can be calculated as:
1239 * k = i / l, where -l <= i <= l.
1243 * k = 2 i / M - 1, where 0 <= i <= M.
1245 static double Kaiser(const double b
, const double k
)
1247 if(!(k
>= -1.0 && k
<= 1.0))
1249 return BesselI_0(b
* sqrt(1.0 - k
*k
)) / BesselI_0(b
);
1252 // Calculates the greatest common divisor of a and b.
1253 static uint
Gcd(uint x
, uint y
)
1264 /* Calculates the size (order) of the Kaiser window. Rejection is in dB and
1265 * the transition width is normalized frequency (0.5 is nyquist).
1267 * M = { ceil((r - 7.95) / (2.285 2 pi f_t)), r > 21
1268 * { ceil(5.79 / 2 pi f_t), r <= 21.
1271 static uint
CalcKaiserOrder(const double rejection
, const double transition
)
1273 double w_t
= 2.0 * M_PI
* transition
;
1274 if(rejection
> 21.0)
1275 return (uint
)ceil((rejection
- 7.95) / (2.285 * w_t
));
1276 return (uint
)ceil(5.79 / w_t
);
1279 // Calculates the beta value of the Kaiser window. Rejection is in dB.
1280 static double CalcKaiserBeta(const double rejection
)
1282 if(rejection
> 50.0)
1283 return 0.1102 * (rejection
- 8.7);
1284 if(rejection
>= 21.0)
1285 return (0.5842 * pow(rejection
- 21.0, 0.4)) +
1286 (0.07886 * (rejection
- 21.0));
1290 /* Calculates a point on the Kaiser-windowed sinc filter for the given half-
1291 * width, beta, gain, and cutoff. The point is specified in non-normalized
1292 * samples, from 0 to M, where M = (2 l + 1).
1294 * w(k) 2 p f_t sinc(2 f_t x)
1296 * x -- centered sample index (i - l)
1297 * k -- normalized and centered window index (x / l)
1298 * w(k) -- window function (Kaiser)
1299 * p -- gain compensation factor when sampling
1300 * f_t -- normalized center frequency (or cutoff; 0.5 is nyquist)
1302 static double SincFilter(const int l
, const double b
, const double gain
, const double cutoff
, const int i
)
1304 return Kaiser(b
, (double)(i
- l
) / l
) * 2.0 * gain
* cutoff
* Sinc(2.0 * cutoff
* (i
- l
));
1307 /* This is a polyphase sinc-filtered resampler.
1309 * Upsample Downsample
1311 * p/q = 3/2 p/q = 3/5
1313 * M-+-+-+-> M-+-+-+->
1314 * -------------------+ ---------------------+
1315 * p s * f f f f|f| | p s * f f f f f |
1316 * | 0 * 0 0 0|0|0 | | 0 * 0 0 0 0|0| |
1317 * v 0 * 0 0|0|0 0 | v 0 * 0 0 0|0|0 |
1318 * s * f|f|f f f | s * f f|f|f f |
1319 * 0 * |0|0 0 0 0 | 0 * 0|0|0 0 0 |
1320 * --------+=+--------+ 0 * |0|0 0 0 0 |
1321 * d . d .|d|. d . d ----------+=+--------+
1322 * d . . . .|d|. . . .
1326 * P_f(i,j) = q i mod p + pj
1327 * P_s(i,j) = floor(q i / p) - j
1328 * d[i=0..N-1] = sum_{j=0}^{floor((M - 1) / p)} {
1329 * { f[P_f(i,j)] s[P_s(i,j)], P_f(i,j) < M
1330 * { 0, P_f(i,j) >= M. }
1333 // Calculate the resampling metrics and build the Kaiser-windowed sinc filter
1334 // that's used to cut frequencies above the destination nyquist.
1335 static void ResamplerSetup(ResamplerT
*rs
, const uint srcRate
, const uint dstRate
)
1337 double cutoff
, width
, beta
;
1341 gcd
= Gcd(srcRate
, dstRate
);
1342 rs
->mP
= dstRate
/ gcd
;
1343 rs
->mQ
= srcRate
/ gcd
;
1344 /* The cutoff is adjusted by half the transition width, so the transition
1345 * ends before the nyquist (0.5). Both are scaled by the downsampling
1350 cutoff
= 0.475 / rs
->mP
;
1351 width
= 0.05 / rs
->mP
;
1355 cutoff
= 0.475 / rs
->mQ
;
1356 width
= 0.05 / rs
->mQ
;
1358 // A rejection of -180 dB is used for the stop band. Round up when
1359 // calculating the left offset to avoid increasing the transition width.
1360 l
= (CalcKaiserOrder(180.0, width
)+1) / 2;
1361 beta
= CalcKaiserBeta(180.0);
1364 rs
->mF
= CreateArray(rs
->mM
);
1365 for(i
= 0;i
< ((int)rs
->mM
);i
++)
1366 rs
->mF
[i
] = SincFilter((int)l
, beta
, rs
->mP
, cutoff
, i
);
1369 // Clean up after the resampler.
1370 static void ResamplerClear(ResamplerT
*rs
)
1372 DestroyArray(rs
->mF
);
1376 // Perform the upsample-filter-downsample resampling operation using a
1377 // polyphase filter implementation.
1378 static void ResamplerRun(ResamplerT
*rs
, const uint inN
, const double *in
, const uint outN
, double *out
)
1380 const uint p
= rs
->mP
, q
= rs
->mQ
, m
= rs
->mM
, l
= rs
->mL
;
1381 const double *f
= rs
->mF
;
1389 // Handle in-place operation.
1391 work
= CreateArray(outN
);
1394 // Resample the input.
1395 for(i
= 0;i
< outN
;i
++)
1398 // Input starts at l to compensate for the filter delay. This will
1399 // drop any build-up from the first half of the filter.
1400 j_f
= (l
+ (q
* i
)) % p
;
1401 j_s
= (l
+ (q
* i
)) / p
;
1404 // Only take input when 0 <= j_s < inN. This single unsigned
1405 // comparison catches both cases.
1407 r
+= f
[j_f
] * in
[j_s
];
1413 // Clean up after in-place operation.
1416 for(i
= 0;i
< outN
;i
++)
1422 /*************************
1423 *** File source input ***
1424 *************************/
1426 // Read a binary value of the specified byte order and byte size from a file,
1427 // storing it as a 32-bit unsigned integer.
1428 static int ReadBin4(FILE *fp
, const char *filename
, const ByteOrderT order
, const uint bytes
, uint32
*out
)
1434 if(fread(in
, 1, bytes
, fp
) != bytes
)
1436 fprintf(stderr
, "Error: Bad read from file '%s'.\n", filename
);
1443 for(i
= 0;i
< bytes
;i
++)
1444 accum
= (accum
<<8) | in
[bytes
- i
- 1];
1447 for(i
= 0;i
< bytes
;i
++)
1448 accum
= (accum
<<8) | in
[i
];
1457 // Read a binary value of the specified byte order from a file, storing it as
1458 // a 64-bit unsigned integer.
1459 static int ReadBin8(FILE *fp
, const char *filename
, const ByteOrderT order
, uint64
*out
)
1465 if(fread(in
, 1, 8, fp
) != 8)
1467 fprintf(stderr
, "Error: Bad read from file '%s'.\n", filename
);
1474 for(i
= 0;i
< 8;i
++)
1475 accum
= (accum
<<8) | in
[8 - i
- 1];
1478 for(i
= 0;i
< 8;i
++)
1479 accum
= (accum
<<8) | in
[i
];
1488 /* Read a binary value of the specified type, byte order, and byte size from
1489 * a file, converting it to a double. For integer types, the significant
1490 * bits are used to normalize the result. The sign of bits determines
1491 * whether they are padded toward the MSB (negative) or LSB (positive).
1492 * Floating-point types are not normalized.
1494 static int ReadBinAsDouble(FILE *fp
, const char *filename
, const ByteOrderT order
, const ElementTypeT type
, const uint bytes
, const int bits
, double *out
)
1509 if(!ReadBin8(fp
, filename
, order
, &v8
.ui
))
1516 if(!ReadBin4(fp
, filename
, order
, bytes
, &v4
.ui
))
1523 v4
.ui
>>= (8*bytes
) - ((uint
)bits
);
1525 v4
.ui
&= (0xFFFFFFFF >> (32+bits
));
1527 if(v4
.ui
&(uint
)(1<<(abs(bits
)-1)))
1528 v4
.ui
|= (0xFFFFFFFF << abs (bits
));
1529 *out
= v4
.i
/ (double)(1<<(abs(bits
)-1));
1535 /* Read an ascii value of the specified type from a file, converting it to a
1536 * double. For integer types, the significant bits are used to normalize the
1537 * result. The sign of the bits should always be positive. This also skips
1538 * up to one separator character before the element itself.
1540 static int ReadAsciiAsDouble(TokenReaderT
*tr
, const char *filename
, const ElementTypeT type
, const uint bits
, double *out
)
1542 if(TrIsOperator(tr
, ","))
1543 TrReadOperator(tr
, ",");
1544 else if(TrIsOperator(tr
, ":"))
1545 TrReadOperator(tr
, ":");
1546 else if(TrIsOperator(tr
, ";"))
1547 TrReadOperator(tr
, ";");
1548 else if(TrIsOperator(tr
, "|"))
1549 TrReadOperator(tr
, "|");
1553 if(!TrReadFloat(tr
, -HUGE_VAL
, HUGE_VAL
, out
))
1555 fprintf(stderr
, "Error: Bad read from file '%s'.\n", filename
);
1562 if(!TrReadInt(tr
, -(1<<(bits
-1)), (1<<(bits
-1))-1, &v
))
1564 fprintf(stderr
, "Error: Bad read from file '%s'.\n", filename
);
1567 *out
= v
/ (double)((1<<(bits
-1))-1);
1572 // Read the RIFF/RIFX WAVE format chunk from a file, validating it against
1573 // the source parameters and data set metrics.
1574 static int ReadWaveFormat(FILE *fp
, const ByteOrderT order
, const uint hrirRate
, SourceRefT
*src
)
1576 uint32 fourCC
, chunkSize
;
1577 uint32 format
, channels
, rate
, dummy
, block
, size
, bits
;
1582 fseek (fp
, (long) chunkSize
, SEEK_CUR
);
1583 if(!ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, &fourCC
) ||
1584 !ReadBin4(fp
, src
->mPath
, order
, 4, &chunkSize
))
1586 } while(fourCC
!= FOURCC_FMT
);
1587 if(!ReadBin4(fp
, src
->mPath
, order
, 2, & format
) ||
1588 !ReadBin4(fp
, src
->mPath
, order
, 2, & channels
) ||
1589 !ReadBin4(fp
, src
->mPath
, order
, 4, & rate
) ||
1590 !ReadBin4(fp
, src
->mPath
, order
, 4, & dummy
) ||
1591 !ReadBin4(fp
, src
->mPath
, order
, 2, & block
))
1596 if(!ReadBin4(fp
, src
->mPath
, order
, 2, &size
))
1604 if(format
== WAVE_FORMAT_EXTENSIBLE
)
1606 fseek(fp
, 2, SEEK_CUR
);
1607 if(!ReadBin4(fp
, src
->mPath
, order
, 2, &bits
))
1611 fseek(fp
, 4, SEEK_CUR
);
1612 if(!ReadBin4(fp
, src
->mPath
, order
, 2, &format
))
1614 fseek(fp
, (long)(chunkSize
- 26), SEEK_CUR
);
1620 fseek(fp
, (long)(chunkSize
- 16), SEEK_CUR
);
1622 fseek(fp
, (long)(chunkSize
- 14), SEEK_CUR
);
1624 if(format
!= WAVE_FORMAT_PCM
&& format
!= WAVE_FORMAT_IEEE_FLOAT
)
1626 fprintf(stderr
, "Error: Unsupported WAVE format in file '%s'.\n", src
->mPath
);
1629 if(src
->mChannel
>= channels
)
1631 fprintf(stderr
, "Error: Missing source channel in WAVE file '%s'.\n", src
->mPath
);
1634 if(rate
!= hrirRate
)
1636 fprintf(stderr
, "Error: Mismatched source sample rate in WAVE file '%s'.\n", src
->mPath
);
1639 if(format
== WAVE_FORMAT_PCM
)
1641 if(size
< 2 || size
> 4)
1643 fprintf(stderr
, "Error: Unsupported sample size in WAVE file '%s'.\n", src
->mPath
);
1646 if(bits
< 16 || bits
> (8*size
))
1648 fprintf (stderr
, "Error: Bad significant bits in WAVE file '%s'.\n", src
->mPath
);
1651 src
->mType
= ET_INT
;
1655 if(size
!= 4 && size
!= 8)
1657 fprintf(stderr
, "Error: Unsupported sample size in WAVE file '%s'.\n", src
->mPath
);
1663 src
->mBits
= (int)bits
;
1664 src
->mSkip
= channels
;
1668 // Read a RIFF/RIFX WAVE data chunk, converting all elements to doubles.
1669 static int ReadWaveData(FILE *fp
, const SourceRefT
*src
, const ByteOrderT order
, const uint n
, double *hrir
)
1671 int pre
, post
, skip
;
1674 pre
= (int)(src
->mSize
* src
->mChannel
);
1675 post
= (int)(src
->mSize
* (src
->mSkip
- src
->mChannel
- 1));
1677 for(i
= 0;i
< n
;i
++)
1681 fseek(fp
, skip
, SEEK_CUR
);
1682 if(!ReadBinAsDouble(fp
, src
->mPath
, order
, src
->mType
, src
->mSize
, src
->mBits
, &hrir
[i
]))
1687 fseek(fp
, skip
, SEEK_CUR
);
1691 // Read the RIFF/RIFX WAVE list or data chunk, converting all elements to
1693 static int ReadWaveList(FILE *fp
, const SourceRefT
*src
, const ByteOrderT order
, const uint n
, double *hrir
)
1695 uint32 fourCC
, chunkSize
, listSize
, count
;
1696 uint block
, skip
, offset
, i
;
1700 if(!ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, & fourCC
) ||
1701 !ReadBin4(fp
, src
->mPath
, order
, 4, & chunkSize
))
1704 if(fourCC
== FOURCC_DATA
)
1706 block
= src
->mSize
* src
->mSkip
;
1707 count
= chunkSize
/ block
;
1708 if(count
< (src
->mOffset
+ n
))
1710 fprintf(stderr
, "Error: Bad read from file '%s'.\n", src
->mPath
);
1713 fseek(fp
, (long)(src
->mOffset
* block
), SEEK_CUR
);
1714 if(!ReadWaveData(fp
, src
, order
, n
, &hrir
[0]))
1718 else if(fourCC
== FOURCC_LIST
)
1720 if(!ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, &fourCC
))
1723 if(fourCC
== FOURCC_WAVL
)
1727 fseek(fp
, (long)chunkSize
, SEEK_CUR
);
1729 listSize
= chunkSize
;
1730 block
= src
->mSize
* src
->mSkip
;
1731 skip
= src
->mOffset
;
1734 while(offset
< n
&& listSize
> 8)
1736 if(!ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, &fourCC
) ||
1737 !ReadBin4(fp
, src
->mPath
, order
, 4, &chunkSize
))
1739 listSize
-= 8 + chunkSize
;
1740 if(fourCC
== FOURCC_DATA
)
1742 count
= chunkSize
/ block
;
1745 fseek(fp
, (long)(skip
* block
), SEEK_CUR
);
1746 chunkSize
-= skip
* block
;
1749 if(count
> (n
- offset
))
1751 if(!ReadWaveData(fp
, src
, order
, count
, &hrir
[offset
]))
1753 chunkSize
-= count
* block
;
1755 lastSample
= hrir
[offset
- 1];
1763 else if(fourCC
== FOURCC_SLNT
)
1765 if(!ReadBin4(fp
, src
->mPath
, order
, 4, &count
))
1772 if(count
> (n
- offset
))
1774 for(i
= 0; i
< count
; i
++)
1775 hrir
[offset
+ i
] = lastSample
;
1785 fseek(fp
, (long)chunkSize
, SEEK_CUR
);
1789 fprintf(stderr
, "Error: Bad read from file '%s'.\n", src
->mPath
);
1795 // Load a source HRIR from a RIFF/RIFX WAVE file.
1796 static int LoadWaveSource(FILE *fp
, SourceRefT
*src
, const uint hrirRate
, const uint n
, double *hrir
)
1798 uint32 fourCC
, dummy
;
1801 if(!ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, &fourCC
) ||
1802 !ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, &dummy
))
1804 if(fourCC
== FOURCC_RIFF
)
1806 else if(fourCC
== FOURCC_RIFX
)
1810 fprintf(stderr
, "Error: No RIFF/RIFX chunk in file '%s'.\n", src
->mPath
);
1814 if(!ReadBin4(fp
, src
->mPath
, BO_LITTLE
, 4, &fourCC
))
1816 if(fourCC
!= FOURCC_WAVE
)
1818 fprintf(stderr
, "Error: Not a RIFF/RIFX WAVE file '%s'.\n", src
->mPath
);
1821 if(!ReadWaveFormat(fp
, order
, hrirRate
, src
))
1823 if(!ReadWaveList(fp
, src
, order
, n
, hrir
))
1828 // Load a source HRIR from a binary file.
1829 static int LoadBinarySource(FILE *fp
, const SourceRefT
*src
, const ByteOrderT order
, const uint n
, double *hrir
)
1833 fseek(fp
, (long)src
->mOffset
, SEEK_SET
);
1834 for(i
= 0;i
< n
;i
++)
1836 if(!ReadBinAsDouble(fp
, src
->mPath
, order
, src
->mType
, src
->mSize
, src
->mBits
, &hrir
[i
]))
1839 fseek(fp
, (long)src
->mSkip
, SEEK_CUR
);
1844 // Load a source HRIR from an ASCII text file containing a list of elements
1845 // separated by whitespace or common list operators (',', ';', ':', '|').
1846 static int LoadAsciiSource(FILE *fp
, const SourceRefT
*src
, const uint n
, double *hrir
)
1852 TrSetup(fp
, NULL
, &tr
);
1853 for(i
= 0;i
< src
->mOffset
;i
++)
1855 if(!ReadAsciiAsDouble(&tr
, src
->mPath
, src
->mType
, (uint
)src
->mBits
, &dummy
))
1858 for(i
= 0;i
< n
;i
++)
1860 if(!ReadAsciiAsDouble(&tr
, src
->mPath
, src
->mType
, (uint
)src
->mBits
, &hrir
[i
]))
1862 for(j
= 0;j
< src
->mSkip
;j
++)
1864 if(!ReadAsciiAsDouble(&tr
, src
->mPath
, src
->mType
, (uint
)src
->mBits
, &dummy
))
1871 // Load a source HRIR from a supported file type.
1872 static int LoadSource(SourceRefT
*src
, const uint hrirRate
, const uint n
, double *hrir
)
1877 if (src
->mFormat
== SF_ASCII
)
1878 fp
= fopen(src
->mPath
, "r");
1880 fp
= fopen(src
->mPath
, "rb");
1883 fprintf(stderr
, "Error: Could not open source file '%s'.\n", src
->mPath
);
1886 if(src
->mFormat
== SF_WAVE
)
1887 result
= LoadWaveSource(fp
, src
, hrirRate
, n
, hrir
);
1888 else if(src
->mFormat
== SF_BIN_LE
)
1889 result
= LoadBinarySource(fp
, src
, BO_LITTLE
, n
, hrir
);
1890 else if(src
->mFormat
== SF_BIN_BE
)
1891 result
= LoadBinarySource(fp
, src
, BO_BIG
, n
, hrir
);
1893 result
= LoadAsciiSource(fp
, src
, n
, hrir
);
1899 /***************************
1900 *** File storage output ***
1901 ***************************/
1903 // Write an ASCII string to a file.
1904 static int WriteAscii(const char *out
, FILE *fp
, const char *filename
)
1909 if(fwrite(out
, 1, len
, fp
) != len
)
1912 fprintf(stderr
, "Error: Bad write to file '%s'.\n", filename
);
1918 // Write a binary value of the given byte order and byte size to a file,
1919 // loading it from a 32-bit unsigned integer.
1920 static int WriteBin4(const ByteOrderT order
, const uint bytes
, const uint32 in
, FILE *fp
, const char *filename
)
1928 for(i
= 0;i
< bytes
;i
++)
1929 out
[i
] = (in
>>(i
*8)) & 0x000000FF;
1932 for(i
= 0;i
< bytes
;i
++)
1933 out
[bytes
- i
- 1] = (in
>>(i
*8)) & 0x000000FF;
1938 if(fwrite(out
, 1, bytes
, fp
) != bytes
)
1940 fprintf(stderr
, "Error: Bad write to file '%s'.\n", filename
);
1946 // Store the OpenAL Soft HRTF data set.
1947 static int StoreMhr(const HrirDataT
*hData
, const int experimental
, const char *filename
)
1949 uint e
, step
, end
, n
, j
, i
;
1954 if((fp
=fopen(filename
, "wb")) == NULL
)
1956 fprintf(stderr
, "Error: Could not open MHR file '%s'.\n", filename
);
1959 if(!WriteAscii(experimental
? MHR_FORMAT_EXPERIMENTAL
: MHR_FORMAT
, fp
, filename
))
1961 if(!WriteBin4(BO_LITTLE
, 4, (uint32
)hData
->mIrRate
, fp
, filename
))
1965 if(!WriteBin4(BO_LITTLE
, 1, (uint32
)hData
->mSampleType
, fp
, filename
))
1967 if(!WriteBin4(BO_LITTLE
, 1, (uint32
)hData
->mChannelType
, fp
, filename
))
1970 if(!WriteBin4(BO_LITTLE
, 1, (uint32
)hData
->mIrPoints
, fp
, filename
))
1972 if(!WriteBin4(BO_LITTLE
, 1, (uint32
)hData
->mEvCount
, fp
, filename
))
1974 for(e
= 0;e
< hData
->mEvCount
;e
++)
1976 if(!WriteBin4(BO_LITTLE
, 1, (uint32
)hData
->mAzCount
[e
], fp
, filename
))
1979 step
= hData
->mIrSize
;
1980 end
= hData
->mIrCount
* step
;
1981 n
= hData
->mIrPoints
;
1982 dither_seed
= 22222;
1983 for(j
= 0;j
< end
;j
+= step
)
1985 const double scale
= (!experimental
|| hData
->mSampleType
== ST_S16
) ? 32767.0 :
1986 ((hData
->mSampleType
== ST_S24
) ? 8388607.0 : 0.0);
1987 const int bps
= (!experimental
|| hData
->mSampleType
== ST_S16
) ? 2 :
1988 ((hData
->mSampleType
== ST_S24
) ? 3 : 0);
1989 double out
[MAX_TRUNCSIZE
];
1990 for(i
= 0;i
< n
;i
++)
1991 out
[i
] = TpdfDither(scale
* hData
->mHrirs
[j
+i
], &dither_seed
);
1992 for(i
= 0;i
< n
;i
++)
1994 v
= (int)Clamp(out
[i
], -scale
-1.0, scale
);
1995 if(!WriteBin4(BO_LITTLE
, bps
, (uint32
)v
, fp
, filename
))
1999 for(j
= 0;j
< hData
->mIrCount
;j
++)
2001 v
= (int)fmin(round(hData
->mIrRate
* hData
->mHrtds
[j
]), MAX_HRTD
);
2002 if(!WriteBin4(BO_LITTLE
, 1, (uint32
)v
, fp
, filename
))
2010 /***********************
2011 *** HRTF processing ***
2012 ***********************/
2014 // Calculate the onset time of an HRIR and average it with any existing
2015 // timing for its elevation and azimuth.
2016 static void AverageHrirOnset(const double *hrir
, const double f
, const uint ei
, const uint ai
, const HrirDataT
*hData
)
2022 n
= hData
->mIrPoints
;
2023 for(i
= 0;i
< n
;i
++)
2024 mag
= fmax(fabs(hrir
[i
]), mag
);
2026 for(i
= 0;i
< n
;i
++)
2028 if(fabs(hrir
[i
]) >= mag
)
2031 j
= hData
->mEvOffset
[ei
] + ai
;
2032 hData
->mHrtds
[j
] = Lerp(hData
->mHrtds
[j
], ((double)i
) / hData
->mIrRate
, f
);
2035 // Calculate the magnitude response of an HRIR and average it with any
2036 // existing responses for its elevation and azimuth.
2037 static void AverageHrirMagnitude(const double *hrir
, const double f
, const uint ei
, const uint ai
, const HrirDataT
*hData
)
2043 n
= hData
->mFftSize
;
2044 cplx
= calloc(sizeof(*cplx
), n
);
2045 mags
= calloc(sizeof(*mags
), n
);
2046 for(i
= 0;i
< hData
->mIrPoints
;i
++)
2047 cplx
[i
] = MakeComplex(hrir
[i
], 0.0);
2049 cplx
[i
] = MakeComplex(0.0, 0.0);
2050 FftForward(n
, cplx
, cplx
);
2051 MagnitudeResponse(n
, cplx
, mags
);
2053 j
= (hData
->mEvOffset
[ei
] + ai
) * hData
->mIrSize
;
2054 for(i
= 0;i
< m
;i
++)
2055 hData
->mHrirs
[j
+i
] = Lerp(hData
->mHrirs
[j
+i
], mags
[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 evs
, sum
, ev
, up_ev
, down_ev
, solidAngle
;
2069 evs
= 90.0 / (hData
->mEvCount
- 1);
2071 for(ei
= hData
->mEvStart
;ei
< hData
->mEvCount
;ei
++)
2073 // For each elevation, calculate the upper and lower limits of the
2075 ev
= -90.0 + (ei
* 2.0 * evs
);
2076 if(ei
< (hData
->mEvCount
- 1))
2077 up_ev
= (ev
+ evs
) * M_PI
/ 180.0;
2081 down_ev
= (ev
- evs
) * M_PI
/ 180.0;
2083 down_ev
= -M_PI
/ 2.0;
2084 // Calculate the area of the patch band.
2085 solidAngle
= 2.0 * M_PI
* (sin(up_ev
) - sin(down_ev
));
2086 // Each weight is the area of one patch.
2087 weights
[ei
] = solidAngle
/ hData
->mAzCount
[ei
];
2088 // Sum the total surface area covered by the HRIRs.
2091 // Normalize the weights given the total surface coverage.
2092 for(ei
= hData
->mEvStart
;ei
< hData
->mEvCount
;ei
++)
2096 /* Calculate the diffuse-field average from the given magnitude responses of
2097 * the HRIR set. Weighting can be applied to compensate for the varying
2098 * surface area covered by each HRIR. The final average can then be limited
2099 * by the specified magnitude range (in positive dB; 0.0 to skip).
2101 static void CalculateDiffuseFieldAverage(const HrirDataT
*hData
, const int weighted
, const double limit
, double *dfa
)
2103 uint ei
, ai
, count
, step
, start
, end
, m
, j
, i
;
2106 weights
= CreateArray(hData
->mEvCount
);
2109 // Use coverage weighting to calculate the average.
2110 CalculateDfWeights(hData
, weights
);
2114 // If coverage weighting is not used, the weights still need to be
2115 // averaged by the number of HRIRs.
2117 for(ei
= hData
->mEvStart
;ei
< hData
->mEvCount
;ei
++)
2118 count
+= hData
->mAzCount
[ei
];
2119 for(ei
= hData
->mEvStart
;ei
< hData
->mEvCount
;ei
++)
2120 weights
[ei
] = 1.0 / count
;
2122 ei
= hData
->mEvStart
;
2124 step
= hData
->mIrSize
;
2125 start
= hData
->mEvOffset
[ei
] * step
;
2126 end
= hData
->mIrCount
* step
;
2127 m
= 1 + (hData
->mFftSize
/ 2);
2128 for(i
= 0;i
< m
;i
++)
2130 for(j
= start
;j
< end
;j
+= step
)
2132 // Get the weight for this HRIR's contribution.
2133 double weight
= weights
[ei
];
2134 // Add this HRIR's weighted power average to the total.
2135 for(i
= 0;i
< m
;i
++)
2136 dfa
[i
] += weight
* hData
->mHrirs
[j
+i
] * hData
->mHrirs
[j
+i
];
2137 // Determine the next weight to use.
2139 if(ai
>= hData
->mAzCount
[ei
])
2145 // Finish the average calculation and keep it from being too small.
2146 for(i
= 0;i
< m
;i
++)
2147 dfa
[i
] = fmax(sqrt(dfa
[i
]), EPSILON
);
2148 // Apply a limit to the magnitude range of the diffuse-field average if
2151 LimitMagnitudeResponse(hData
->mFftSize
, limit
, dfa
, dfa
);
2152 DestroyArray(weights
);
2155 // Perform diffuse-field equalization on the magnitude responses of the HRIR
2156 // set using the given average response.
2157 static void DiffuseFieldEqualize(const double *dfa
, const HrirDataT
*hData
)
2159 uint step
, start
, end
, m
, j
, i
;
2161 step
= hData
->mIrSize
;
2162 start
= hData
->mEvOffset
[hData
->mEvStart
] * step
;
2163 end
= hData
->mIrCount
* step
;
2164 m
= 1 + (hData
->mFftSize
/ 2);
2165 for(j
= start
;j
< end
;j
+= step
)
2167 for(i
= 0;i
< m
;i
++)
2168 hData
->mHrirs
[j
+i
] /= dfa
[i
];
2172 // Perform minimum-phase reconstruction using the magnitude responses of the
2174 static void ReconstructHrirs(const HrirDataT
*hData
)
2176 uint step
, start
, end
, n
, j
, i
;
2177 uint pcdone
, lastpc
;
2180 pcdone
= lastpc
= 0;
2181 printf("%3d%% done.", pcdone
);
2184 step
= hData
->mIrSize
;
2185 start
= hData
->mEvOffset
[hData
->mEvStart
] * step
;
2186 end
= hData
->mIrCount
* step
;
2187 n
= hData
->mFftSize
;
2188 cplx
= calloc(sizeof(*cplx
), n
);
2189 for(j
= start
;j
< end
;j
+= step
)
2191 MinimumPhase(n
, &hData
->mHrirs
[j
], cplx
);
2192 FftInverse(n
, cplx
, cplx
);
2193 for(i
= 0;i
< hData
->mIrPoints
;i
++)
2194 hData
->mHrirs
[j
+i
] = cplx
[i
].Real
;
2195 pcdone
= (j
+step
-start
) * 100 / (end
-start
);
2196 if(pcdone
!= lastpc
)
2199 printf("\r%3d%% done.", pcdone
);
2207 // Resamples the HRIRs for use at the given sampling rate.
2208 static void ResampleHrirs(const uint rate
, HrirDataT
*hData
)
2210 uint n
, step
, start
, end
, j
;
2213 ResamplerSetup(&rs
, hData
->mIrRate
, rate
);
2214 n
= hData
->mIrPoints
;
2215 step
= hData
->mIrSize
;
2216 start
= hData
->mEvOffset
[hData
->mEvStart
] * step
;
2217 end
= hData
->mIrCount
* step
;
2218 for(j
= start
;j
< end
;j
+= step
)
2219 ResamplerRun(&rs
, n
, &hData
->mHrirs
[j
], n
, &hData
->mHrirs
[j
]);
2220 ResamplerClear(&rs
);
2221 hData
->mIrRate
= rate
;
2224 /* Given an elevation index and an azimuth, calculate the indices of the two
2225 * HRIRs that bound the coordinate along with a factor for calculating the
2226 * continous HRIR using interpolation.
2228 static void CalcAzIndices(const HrirDataT
*hData
, const uint ei
, const double az
, uint
*j0
, uint
*j1
, double *jf
)
2233 af
= ((2.0*M_PI
) + az
) * hData
->mAzCount
[ei
] / (2.0*M_PI
);
2234 ai
= ((uint
)af
) % hData
->mAzCount
[ei
];
2237 *j0
= hData
->mEvOffset
[ei
] + ai
;
2238 *j1
= hData
->mEvOffset
[ei
] + ((ai
+1) % hData
->mAzCount
[ei
]);
2242 // Synthesize any missing onset timings at the bottom elevations. This just
2243 // blends between slightly exaggerated known onsets. Not an accurate model.
2244 static void SynthesizeOnsets(HrirDataT
*hData
)
2246 uint oi
, e
, a
, j0
, j1
;
2249 oi
= hData
->mEvStart
;
2251 for(a
= 0;a
< hData
->mAzCount
[oi
];a
++)
2252 t
+= hData
->mHrtds
[hData
->mEvOffset
[oi
] + a
];
2253 hData
->mHrtds
[0] = 1.32e-4 + (t
/ hData
->mAzCount
[oi
]);
2254 for(e
= 1;e
< hData
->mEvStart
;e
++)
2256 of
= ((double)e
) / hData
->mEvStart
;
2257 for(a
= 0;a
< hData
->mAzCount
[e
];a
++)
2259 CalcAzIndices(hData
, oi
, a
* 2.0 * M_PI
/ hData
->mAzCount
[e
], &j0
, &j1
, &jf
);
2260 hData
->mHrtds
[hData
->mEvOffset
[e
] + a
] = Lerp(hData
->mHrtds
[0], Lerp(hData
->mHrtds
[j0
], hData
->mHrtds
[j1
], jf
), of
);
2265 /* Attempt to synthesize any missing HRIRs at the bottom elevations. Right
2266 * now this just blends the lowest elevation HRIRs together and applies some
2267 * attenuation and high frequency damping. It is a simple, if inaccurate
2270 static void SynthesizeHrirs (HrirDataT
*hData
)
2272 uint oi
, a
, e
, step
, n
, i
, j
;
2273 double lp
[4], s0
, s1
;
2278 if(hData
->mEvStart
<= 0)
2280 step
= hData
->mIrSize
;
2281 oi
= hData
->mEvStart
;
2282 n
= hData
->mIrPoints
;
2283 for(i
= 0;i
< n
;i
++)
2284 hData
->mHrirs
[i
] = 0.0;
2285 for(a
= 0;a
< hData
->mAzCount
[oi
];a
++)
2287 j
= (hData
->mEvOffset
[oi
] + a
) * step
;
2288 for(i
= 0;i
< n
;i
++)
2289 hData
->mHrirs
[i
] += hData
->mHrirs
[j
+i
] / hData
->mAzCount
[oi
];
2291 for(e
= 1;e
< hData
->mEvStart
;e
++)
2293 of
= ((double)e
) / hData
->mEvStart
;
2294 b
= (1.0 - of
) * (3.5e-6 * hData
->mIrRate
);
2295 for(a
= 0;a
< hData
->mAzCount
[e
];a
++)
2297 j
= (hData
->mEvOffset
[e
] + a
) * step
;
2298 CalcAzIndices(hData
, oi
, a
* 2.0 * M_PI
/ hData
->mAzCount
[e
], &j0
, &j1
, &jf
);
2305 for(i
= 0;i
< n
;i
++)
2307 s0
= hData
->mHrirs
[i
];
2308 s1
= Lerp(hData
->mHrirs
[j0
+i
], hData
->mHrirs
[j1
+i
], jf
);
2309 s0
= Lerp(s0
, s1
, of
);
2310 lp
[0] = Lerp(s0
, lp
[0], b
);
2311 lp
[1] = Lerp(lp
[0], lp
[1], b
);
2312 lp
[2] = Lerp(lp
[1], lp
[2], b
);
2313 lp
[3] = Lerp(lp
[2], lp
[3], b
);
2314 hData
->mHrirs
[j
+i
] = lp
[3];
2318 b
= 3.5e-6 * hData
->mIrRate
;
2323 for(i
= 0;i
< n
;i
++)
2325 s0
= hData
->mHrirs
[i
];
2326 lp
[0] = Lerp(s0
, lp
[0], b
);
2327 lp
[1] = Lerp(lp
[0], lp
[1], b
);
2328 lp
[2] = Lerp(lp
[1], lp
[2], b
);
2329 lp
[3] = Lerp(lp
[2], lp
[3], b
);
2330 hData
->mHrirs
[i
] = lp
[3];
2332 hData
->mEvStart
= 0;
2335 // The following routines assume a full set of HRIRs for all elevations.
2337 // Normalize the HRIR set and slightly attenuate the result.
2338 static void NormalizeHrirs (const HrirDataT
*hData
)
2340 uint step
, end
, n
, j
, i
;
2343 step
= hData
->mIrSize
;
2344 end
= hData
->mIrCount
* step
;
2345 n
= hData
->mIrPoints
;
2347 for(j
= 0;j
< end
;j
+= step
)
2349 for(i
= 0;i
< n
;i
++)
2350 maxLevel
= fmax(fabs(hData
->mHrirs
[j
+i
]), maxLevel
);
2352 maxLevel
= 1.01 * maxLevel
;
2353 for(j
= 0;j
< end
;j
+= step
)
2355 for(i
= 0;i
< n
;i
++)
2356 hData
->mHrirs
[j
+i
] /= maxLevel
;
2360 // Calculate the left-ear time delay using a spherical head model.
2361 static double CalcLTD(const double ev
, const double az
, const double rad
, const double dist
)
2363 double azp
, dlp
, l
, al
;
2365 azp
= asin(cos(ev
) * sin(az
));
2366 dlp
= sqrt((dist
*dist
) + (rad
*rad
) + (2.0*dist
*rad
*sin(azp
)));
2367 l
= sqrt((dist
*dist
) - (rad
*rad
));
2368 al
= (0.5 * M_PI
) + azp
;
2370 dlp
= l
+ (rad
* (al
- acos(rad
/ dist
)));
2371 return (dlp
/ 343.3);
2374 // Calculate the effective head-related time delays for each minimum-phase
2376 static void CalculateHrtds (const HeadModelT model
, const double radius
, HrirDataT
*hData
)
2378 double minHrtd
, maxHrtd
;
2384 for(e
= 0;e
< hData
->mEvCount
;e
++)
2386 for(a
= 0;a
< hData
->mAzCount
[e
];a
++)
2388 j
= hData
->mEvOffset
[e
] + a
;
2389 if(model
== HM_DATASET
)
2390 t
= hData
->mHrtds
[j
] * radius
/ hData
->mRadius
;
2392 t
= CalcLTD((-90.0 + (e
* 180.0 / (hData
->mEvCount
- 1))) * M_PI
/ 180.0,
2393 (a
* 360.0 / hData
->mAzCount
[e
]) * M_PI
/ 180.0,
2394 radius
, hData
->mDistance
);
2395 hData
->mHrtds
[j
] = t
;
2396 maxHrtd
= fmax(t
, maxHrtd
);
2397 minHrtd
= fmin(t
, minHrtd
);
2401 for(j
= 0;j
< hData
->mIrCount
;j
++)
2402 hData
->mHrtds
[j
] -= minHrtd
;
2403 hData
->mMaxHrtd
= maxHrtd
;
2407 // Process the data set definition to read and validate the data set metrics.
2408 static int ProcessMetrics(TokenReaderT
*tr
, const uint fftSize
, const uint truncSize
, HrirDataT
*hData
)
2410 int hasRate
= 0, hasPoints
= 0, hasAzimuths
= 0;
2411 int hasRadius
= 0, hasDistance
= 0;
2412 char ident
[MAX_IDENT_LEN
+1];
2418 while(!(hasRate
&& hasPoints
&& hasAzimuths
&& hasRadius
&& hasDistance
))
2420 TrIndication(tr
, & line
, & col
);
2421 if(!TrReadIdent(tr
, MAX_IDENT_LEN
, ident
))
2423 if(strcasecmp(ident
, "rate") == 0)
2427 TrErrorAt(tr
, line
, col
, "Redefinition of 'rate'.\n");
2430 if(!TrReadOperator(tr
, "="))
2432 if(!TrReadInt(tr
, MIN_RATE
, MAX_RATE
, &intVal
))
2434 hData
->mIrRate
= (uint
)intVal
;
2437 else if(strcasecmp(ident
, "points") == 0)
2440 TrErrorAt(tr
, line
, col
, "Redefinition of 'points'.\n");
2443 if(!TrReadOperator(tr
, "="))
2445 TrIndication(tr
, &line
, &col
);
2446 if(!TrReadInt(tr
, MIN_POINTS
, MAX_POINTS
, &intVal
))
2448 points
= (uint
)intVal
;
2449 if(fftSize
> 0 && points
> fftSize
)
2451 TrErrorAt(tr
, line
, col
, "Value exceeds the overridden FFT size.\n");
2454 if(points
< truncSize
)
2456 TrErrorAt(tr
, line
, col
, "Value is below the truncation size.\n");
2459 hData
->mIrPoints
= points
;
2462 hData
->mFftSize
= DEFAULT_FFTSIZE
;
2463 hData
->mIrSize
= 1 + (DEFAULT_FFTSIZE
/ 2);
2467 hData
->mFftSize
= fftSize
;
2468 hData
->mIrSize
= 1 + (fftSize
/ 2);
2469 if(points
> hData
->mIrSize
)
2470 hData
->mIrSize
= points
;
2474 else if(strcasecmp(ident
, "azimuths") == 0)
2478 TrErrorAt(tr
, line
, col
, "Redefinition of 'azimuths'.\n");
2481 if(!TrReadOperator(tr
, "="))
2483 hData
->mIrCount
= 0;
2484 hData
->mEvCount
= 0;
2485 hData
->mEvOffset
[0] = 0;
2488 if(!TrReadInt(tr
, MIN_AZ_COUNT
, MAX_AZ_COUNT
, &intVal
))
2490 hData
->mAzCount
[hData
->mEvCount
] = (uint
)intVal
;
2491 hData
->mIrCount
+= (uint
)intVal
;
2493 if(!TrIsOperator(tr
, ","))
2495 if(hData
->mEvCount
>= MAX_EV_COUNT
)
2497 TrError(tr
, "Exceeded the maximum of %d elevations.\n", MAX_EV_COUNT
);
2500 hData
->mEvOffset
[hData
->mEvCount
] = hData
->mEvOffset
[hData
->mEvCount
- 1] + ((uint
)intVal
);
2501 TrReadOperator(tr
, ",");
2503 if(hData
->mEvCount
< MIN_EV_COUNT
)
2505 TrErrorAt(tr
, line
, col
, "Did not reach the minimum of %d azimuth counts.\n", MIN_EV_COUNT
);
2510 else if(strcasecmp(ident
, "radius") == 0)
2514 TrErrorAt(tr
, line
, col
, "Redefinition of 'radius'.\n");
2517 if(!TrReadOperator(tr
, "="))
2519 if(!TrReadFloat(tr
, MIN_RADIUS
, MAX_RADIUS
, &fpVal
))
2521 hData
->mRadius
= fpVal
;
2524 else if(strcasecmp(ident
, "distance") == 0)
2528 TrErrorAt(tr
, line
, col
, "Redefinition of 'distance'.\n");
2531 if(!TrReadOperator(tr
, "="))
2533 if(!TrReadFloat(tr
, MIN_DISTANCE
, MAX_DISTANCE
, & fpVal
))
2535 hData
->mDistance
= fpVal
;
2540 TrErrorAt(tr
, line
, col
, "Expected a metric name.\n");
2543 TrSkipWhitespace (tr
);
2548 // Parse an index pair from the data set definition.
2549 static int ReadIndexPair(TokenReaderT
*tr
, const HrirDataT
*hData
, uint
*ei
, uint
*ai
)
2552 if(!TrReadInt(tr
, 0, (int)hData
->mEvCount
, &intVal
))
2555 if(!TrReadOperator(tr
, ","))
2557 if(!TrReadInt(tr
, 0, (int)hData
->mAzCount
[*ei
], &intVal
))
2563 // Match the source format from a given identifier.
2564 static SourceFormatT
MatchSourceFormat(const char *ident
)
2566 if(strcasecmp(ident
, "wave") == 0)
2568 if(strcasecmp(ident
, "bin_le") == 0)
2570 if(strcasecmp(ident
, "bin_be") == 0)
2572 if(strcasecmp(ident
, "ascii") == 0)
2577 // Match the source element type from a given identifier.
2578 static ElementTypeT
MatchElementType(const char *ident
)
2580 if(strcasecmp(ident
, "int") == 0)
2582 if(strcasecmp(ident
, "fp") == 0)
2587 // Parse and validate a source reference from the data set definition.
2588 static int ReadSourceRef(TokenReaderT
*tr
, SourceRefT
*src
)
2590 char ident
[MAX_IDENT_LEN
+1];
2594 TrIndication(tr
, &line
, &col
);
2595 if(!TrReadIdent(tr
, MAX_IDENT_LEN
, ident
))
2597 src
->mFormat
= MatchSourceFormat(ident
);
2598 if(src
->mFormat
== SF_NONE
)
2600 TrErrorAt(tr
, line
, col
, "Expected a source format.\n");
2603 if(!TrReadOperator(tr
, "("))
2605 if(src
->mFormat
== SF_WAVE
)
2607 if(!TrReadInt(tr
, 0, MAX_WAVE_CHANNELS
, &intVal
))
2609 src
->mType
= ET_NONE
;
2612 src
->mChannel
= (uint
)intVal
;
2617 TrIndication(tr
, &line
, &col
);
2618 if(!TrReadIdent(tr
, MAX_IDENT_LEN
, ident
))
2620 src
->mType
= MatchElementType(ident
);
2621 if(src
->mType
== ET_NONE
)
2623 TrErrorAt(tr
, line
, col
, "Expected a source element type.\n");
2626 if(src
->mFormat
== SF_BIN_LE
|| src
->mFormat
== SF_BIN_BE
)
2628 if(!TrReadOperator(tr
, ","))
2630 if(src
->mType
== ET_INT
)
2632 if(!TrReadInt(tr
, MIN_BIN_SIZE
, MAX_BIN_SIZE
, &intVal
))
2634 src
->mSize
= (uint
)intVal
;
2635 if(!TrIsOperator(tr
, ","))
2636 src
->mBits
= (int)(8*src
->mSize
);
2639 TrReadOperator(tr
, ",");
2640 TrIndication(tr
, &line
, &col
);
2641 if(!TrReadInt(tr
, -2147483647-1, 2147483647, &intVal
))
2643 if(abs(intVal
) < MIN_BIN_BITS
|| ((uint
)abs(intVal
)) > (8*src
->mSize
))
2645 TrErrorAt(tr
, line
, col
, "Expected a value of (+/-) %d to %d.\n", MIN_BIN_BITS
, 8*src
->mSize
);
2648 src
->mBits
= intVal
;
2653 TrIndication(tr
, &line
, &col
);
2654 if(!TrReadInt(tr
, -2147483647-1, 2147483647, &intVal
))
2656 if(intVal
!= 4 && intVal
!= 8)
2658 TrErrorAt(tr
, line
, col
, "Expected a value of 4 or 8.\n");
2661 src
->mSize
= (uint
)intVal
;
2665 else if(src
->mFormat
== SF_ASCII
&& src
->mType
== ET_INT
)
2667 if(!TrReadOperator(tr
, ","))
2669 if(!TrReadInt(tr
, MIN_ASCII_BITS
, MAX_ASCII_BITS
, &intVal
))
2672 src
->mBits
= intVal
;
2680 if(!TrIsOperator(tr
, ";"))
2684 TrReadOperator(tr
, ";");
2685 if(!TrReadInt (tr
, 0, 0x7FFFFFFF, &intVal
))
2687 src
->mSkip
= (uint
)intVal
;
2690 if(!TrReadOperator(tr
, ")"))
2692 if(TrIsOperator(tr
, "@"))
2694 TrReadOperator(tr
, "@");
2695 if(!TrReadInt(tr
, 0, 0x7FFFFFFF, &intVal
))
2697 src
->mOffset
= (uint
)intVal
;
2701 if(!TrReadOperator(tr
, ":"))
2703 if(!TrReadString(tr
, MAX_PATH_LEN
, src
->mPath
))
2708 // Process the list of sources in the data set definition.
2709 static int ProcessSources(const HeadModelT model
, TokenReaderT
*tr
, HrirDataT
*hData
)
2711 uint
*setCount
, *setFlag
;
2712 uint line
, col
, ei
, ai
;
2718 printf("Loading sources...");
2722 setCount
= (uint
*)calloc(hData
->mEvCount
, sizeof(uint
));
2723 setFlag
= (uint
*)calloc(hData
->mIrCount
, sizeof(uint
));
2724 hrir
= CreateArray(hData
->mIrPoints
);
2725 while(TrIsOperator(tr
, "["))
2727 TrIndication(tr
, & line
, & col
);
2728 TrReadOperator(tr
, "[");
2729 if(!ReadIndexPair(tr
, hData
, &ei
, &ai
))
2731 if(!TrReadOperator(tr
, "]"))
2733 if(setFlag
[hData
->mEvOffset
[ei
] + ai
])
2735 TrErrorAt(tr
, line
, col
, "Redefinition of source.\n");
2738 if(!TrReadOperator(tr
, "="))
2744 if(!ReadSourceRef(tr
, &src
))
2747 // TODO: Would be nice to display 'x of y files', but that would
2748 // require preparing the source refs first to get a total count
2749 // before loading them.
2751 printf("\rLoading sources... %d file%s", count
, (count
==1)?"":"s");
2754 if(!LoadSource(&src
, hData
->mIrRate
, hData
->mIrPoints
, hrir
))
2757 if(model
== HM_DATASET
)
2758 AverageHrirOnset(hrir
, 1.0 / factor
, ei
, ai
, hData
);
2759 AverageHrirMagnitude(hrir
, 1.0 / factor
, ei
, ai
, hData
);
2761 if(!TrIsOperator(tr
, "+"))
2763 TrReadOperator(tr
, "+");
2765 setFlag
[hData
->mEvOffset
[ei
] + ai
] = 1;
2771 while(ei
< hData
->mEvCount
&& setCount
[ei
] < 1)
2773 if(ei
< hData
->mEvCount
)
2775 hData
->mEvStart
= ei
;
2776 while(ei
< hData
->mEvCount
&& setCount
[ei
] == hData
->mAzCount
[ei
])
2778 if(ei
>= hData
->mEvCount
)
2787 TrError(tr
, "Errant data at end of source list.\n");
2790 TrError(tr
, "Missing sources for elevation index %d.\n", ei
);
2793 TrError(tr
, "Missing source references.\n");
2802 /* Parse the data set definition and process the source data, storing the
2803 * resulting data set as desired. If the input name is NULL it will read
2804 * from standard input.
2806 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 int experimental
, const char *outName
)
2808 char rateStr
[8+1], expName
[MAX_PATH_LEN
];
2815 hData
.mSampleType
= ST_S24
;
2816 hData
.mChannelType
= CT_LEFTONLY
;
2817 hData
.mIrPoints
= 0;
2823 hData
.mDistance
= 0;
2824 fprintf(stdout
, "Reading HRIR definition from %s...\n", inName
?inName
:"stdin");
2827 fp
= fopen(inName
, "r");
2830 fprintf(stderr
, "Error: Could not open definition file '%s'\n", inName
);
2833 TrSetup(fp
, inName
, &tr
);
2838 TrSetup(fp
, "<stdin>", &tr
);
2840 if(!ProcessMetrics(&tr
, fftSize
, truncSize
, &hData
))
2846 hData
.mHrirs
= CreateArray(hData
.mIrCount
* hData
.mIrSize
);
2847 hData
.mHrtds
= CreateArray(hData
.mIrCount
);
2848 if(!ProcessSources(model
, &tr
, &hData
))
2850 DestroyArray(hData
.mHrtds
);
2851 DestroyArray(hData
.mHrirs
);
2860 double *dfa
= CreateArray(1 + (hData
.mFftSize
/2));
2861 fprintf(stdout
, "Calculating diffuse-field average...\n");
2862 CalculateDiffuseFieldAverage(&hData
, surface
, limit
, dfa
);
2863 fprintf(stdout
, "Performing diffuse-field equalization...\n");
2864 DiffuseFieldEqualize(dfa
, &hData
);
2867 fprintf(stdout
, "Performing minimum phase reconstruction...\n");
2868 ReconstructHrirs(&hData
);
2869 if(outRate
!= 0 && outRate
!= hData
.mIrRate
)
2871 fprintf(stdout
, "Resampling HRIRs...\n");
2872 ResampleHrirs(outRate
, &hData
);
2874 fprintf(stdout
, "Truncating minimum-phase HRIRs...\n");
2875 hData
.mIrPoints
= truncSize
;
2876 fprintf(stdout
, "Synthesizing missing elevations...\n");
2877 if(model
== HM_DATASET
)
2878 SynthesizeOnsets(&hData
);
2879 SynthesizeHrirs(&hData
);
2880 fprintf(stdout
, "Normalizing final HRIRs...\n");
2881 NormalizeHrirs(&hData
);
2882 fprintf(stdout
, "Calculating impulse delays...\n");
2883 CalculateHrtds(model
, (radius
> DEFAULT_CUSTOM_RADIUS
) ? radius
: hData
.mRadius
, &hData
);
2884 snprintf(rateStr
, 8, "%u", hData
.mIrRate
);
2885 StrSubst(outName
, "%r", rateStr
, MAX_PATH_LEN
, expName
);
2886 fprintf(stdout
, "Creating MHR data set %s...\n", expName
);
2887 ret
= StoreMhr(&hData
, experimental
, expName
);
2889 DestroyArray(hData
.mHrtds
);
2890 DestroyArray(hData
.mHrirs
);
2894 static void PrintHelp(const char *argv0
, FILE *ofile
)
2896 fprintf(ofile
, "Usage: %s <command> [<option>...]\n\n", argv0
);
2897 fprintf(ofile
, "Options:\n");
2898 fprintf(ofile
, " -m Ignored for compatibility.\n");
2899 fprintf(ofile
, " -r <rate> Change the data set sample rate to the specified value and\n");
2900 fprintf(ofile
, " resample the HRIRs accordingly.\n");
2901 fprintf(ofile
, " -f <points> Override the FFT window size (default: %u).\n", DEFAULT_FFTSIZE
);
2902 fprintf(ofile
, " -e {on|off} Toggle diffuse-field equalization (default: %s).\n", (DEFAULT_EQUALIZE
? "on" : "off"));
2903 fprintf(ofile
, " -s {on|off} Toggle surface-weighted diffuse-field average (default: %s).\n", (DEFAULT_SURFACE
? "on" : "off"));
2904 fprintf(ofile
, " -l {<dB>|none} Specify a limit to the magnitude range of the diffuse-field\n");
2905 fprintf(ofile
, " average (default: %.2f).\n", DEFAULT_LIMIT
);
2906 fprintf(ofile
, " -w <points> Specify the size of the truncation window that's applied\n");
2907 fprintf(ofile
, " after minimum-phase reconstruction (default: %u).\n", DEFAULT_TRUNCSIZE
);
2908 fprintf(ofile
, " -d {dataset| Specify the model used for calculating the head-delay timing\n");
2909 fprintf(ofile
, " sphere} values (default: %s).\n", ((DEFAULT_HEAD_MODEL
== HM_DATASET
) ? "dataset" : "sphere"));
2910 fprintf(ofile
, " -c <size> Use a customized head radius measured ear-to-ear in meters.\n");
2911 fprintf(ofile
, " -i <filename> Specify an HRIR definition file to use (defaults to stdin).\n");
2912 fprintf(ofile
, " -o <filename> Specify an output file. Overrides command-selected default.\n");
2913 fprintf(ofile
, " Use of '%%r' will be substituted with the data set sample rate.\n");
2917 #define main my_main
2918 int main(int argc
, char *argv
[]);
2920 static char **arglist
;
2921 static void cleanup_arglist(void)
2924 for(i
= 0;arglist
[i
];i
++)
2929 int wmain(int argc
, const wchar_t *wargv
[])
2933 atexit(cleanup_arglist
);
2934 arglist
= calloc(sizeof(*arglist
), argc
+1);
2935 for(i
= 0;i
< argc
;i
++)
2936 arglist
[i
] = ToUTF8(wargv
[i
]);
2938 return main(argc
, arglist
);
2942 // Standard command line dispatch.
2943 int main(int argc
, char *argv
[])
2945 const char *inName
= NULL
, *outName
= NULL
;
2946 uint outRate
, fftSize
;
2947 int equalize
, surface
;
2958 fprintf(stdout
, "HRTF Processing and Composition Utility\n\n");
2959 PrintHelp(argv
[0], stdout
);
2963 outName
= "./oalsoft_hrtf_%r.mhr";
2966 equalize
= DEFAULT_EQUALIZE
;
2967 surface
= DEFAULT_SURFACE
;
2968 limit
= DEFAULT_LIMIT
;
2969 truncSize
= DEFAULT_TRUNCSIZE
;
2970 model
= DEFAULT_HEAD_MODEL
;
2971 radius
= DEFAULT_CUSTOM_RADIUS
;
2974 while((opt
=getopt(argc
, argv
, "mr:f:e:s:l:w:d:c:e:i:o:xh")) != -1)
2979 fprintf(stderr
, "Ignoring unused command '-m'.\n");
2983 outRate
= strtoul(optarg
, &end
, 10);
2984 if(end
[0] != '\0' || outRate
< MIN_RATE
|| outRate
> MAX_RATE
)
2986 fprintf(stderr
, "Error: Got unexpected value \"%s\" for option -%c, expected between %u to %u.\n", optarg
, opt
, MIN_RATE
, MAX_RATE
);
2992 fftSize
= strtoul(optarg
, &end
, 10);
2993 if(end
[0] != '\0' || (fftSize
&(fftSize
-1)) || fftSize
< MIN_FFTSIZE
|| fftSize
> MAX_FFTSIZE
)
2995 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
);
3001 if(strcmp(optarg
, "on") == 0)
3003 else if(strcmp(optarg
, "off") == 0)
3007 fprintf(stderr
, "Error: Got unexpected value \"%s\" for option -%c, expected on or off.\n", optarg
, opt
);
3013 if(strcmp(optarg
, "on") == 0)
3015 else if(strcmp(optarg
, "off") == 0)
3019 fprintf(stderr
, "Error: Got unexpected value \"%s\" for option -%c, expected on or off.\n", optarg
, opt
);
3025 if(strcmp(optarg
, "none") == 0)
3029 limit
= strtod(optarg
, &end
);
3030 if(end
[0] != '\0' || limit
< MIN_LIMIT
|| limit
> MAX_LIMIT
)
3032 fprintf(stderr
, "Error: Got unexpected value \"%s\" for option -%c, expected between %.0f to %.0f.\n", optarg
, opt
, MIN_LIMIT
, MAX_LIMIT
);
3039 truncSize
= strtoul(optarg
, &end
, 10);
3040 if(end
[0] != '\0' || truncSize
< MIN_TRUNCSIZE
|| truncSize
> MAX_TRUNCSIZE
|| (truncSize
%MOD_TRUNCSIZE
))
3042 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
);
3048 if(strcmp(optarg
, "dataset") == 0)
3050 else if(strcmp(optarg
, "sphere") == 0)
3054 fprintf(stderr
, "Error: Got unexpected value \"%s\" for option -%c, expected dataset or sphere.\n", optarg
, opt
);
3060 radius
= strtod(optarg
, &end
);
3061 if(end
[0] != '\0' || radius
< MIN_CUSTOM_RADIUS
|| radius
> MAX_CUSTOM_RADIUS
)
3063 fprintf(stderr
, "Error: Got unexpected value \"%s\" for option -%c, expected between %.2f to %.2f.\n", optarg
, opt
, MIN_CUSTOM_RADIUS
, MAX_CUSTOM_RADIUS
);
3081 PrintHelp(argv
[0], stdout
);
3085 PrintHelp(argv
[0], stderr
);
3090 if(!ProcessDefinition(inName
, outRate
, fftSize
, equalize
, surface
, limit
,
3091 truncSize
, model
, radius
, experimental
, outName
))
3093 fprintf(stdout
, "Operation completed.\n");
3095 return EXIT_SUCCESS
;