Fix some types
[openal-soft.git] / utils / makehrtf.c
blobd3917d5dbe4b2510865955c4ac4ff47026979470
1 /*
2 * HRTF utility for producing and demonstrating the process of creating an
3 * OpenAL Soft compatible HRIR data set.
5 * Copyright (C) 2011-2012 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
36 * measurement.
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
39 * average.
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
45 * from the paper:
47 * Modeling Interaural Time Difference Assuming a Spherical Head
48 * Joel David Miller
49 * Music 150, Musical Acoustics, Stanford University
50 * December 2, 2001
54 /* Needed for 64-bit unsigned integer. */
55 #include "config.h"
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <stdarg.h>
60 #include <string.h>
61 #include <ctype.h>
62 #include <math.h>
64 // Rely (if naively) on OpenAL's header for the types used for serialization.
65 #include "AL/al.h"
67 #ifndef M_PI
68 #define M_PI 3.14159265358979323846
69 #endif
71 #ifndef HUGE_VAL
72 #define HUGE_VAL (1.0/0.0)
73 #endif
75 // The epsilon used to maintain signal stability.
76 #define EPSILON (1e-15)
78 // Constants for accessing the token reader's ring buffer.
79 #define TR_RING_BITS (16)
80 #define TR_RING_SIZE (1 << TR_RING_BITS)
81 #define TR_RING_MASK (TR_RING_SIZE - 1)
83 // The token reader's load interval in bytes.
84 #define TR_LOAD_SIZE (TR_RING_SIZE >> 2)
86 // The maximum identifier length used when processing the data set
87 // definition.
88 #define MAX_IDENT_LEN (16)
90 // The maximum path length used when processing filenames.
91 #define MAX_PATH_LEN (256)
93 // The limits for the sample 'rate' metric in the data set definition.
94 #define MIN_RATE (32000)
95 #define MAX_RATE (96000)
97 // The limits for the HRIR 'points' metric in the data set definition.
98 #define MIN_POINTS (16)
99 #define MAX_POINTS (8192)
101 // The limits to the number of 'azimuths' listed in the data set definition.
102 #define MIN_EV_COUNT (5)
103 #define MAX_EV_COUNT (128)
105 // The limits for each of the 'azimuths' listed in the data set definition.
106 #define MIN_AZ_COUNT (1)
107 #define MAX_AZ_COUNT (128)
109 // The limits for the listener's head 'radius' in the data set definition.
110 #define MIN_RADIUS (0.05)
111 #define MAX_RADIUS (0.15)
113 // The limits for the 'distance' from source to listener in the definition
114 // file.
115 #define MIN_DISTANCE (0.5)
116 #define MAX_DISTANCE (2.5)
118 // The maximum number of channels that can be addressed for a WAVE file
119 // source listed in the data set definition.
120 #define MAX_WAVE_CHANNELS (65535)
122 // The limits to the byte size for a binary source listed in the definition
123 // file.
124 #define MIN_BIN_SIZE (2)
125 #define MAX_BIN_SIZE (4)
127 // The minimum number of significant bits for binary sources listed in the
128 // data set definition. The maximum is calculated from the byte size.
129 #define MIN_BIN_BITS (16)
131 // The limits to the number of significant bits for an ASCII source listed in
132 // the data set definition.
133 #define MIN_ASCII_BITS (16)
134 #define MAX_ASCII_BITS (32)
136 // The limits to the FFT window size override on the command line.
137 #define MIN_FFTSIZE (512)
138 #define MAX_FFTSIZE (16384)
140 // The limits to the equalization range limit on the command line.
141 #define MIN_LIMIT (2.0)
142 #define MAX_LIMIT (120.0)
144 // The limits to the truncation window size on the command line.
145 #define MIN_TRUNCSIZE (8)
146 #define MAX_TRUNCSIZE (128)
148 // The truncation window size must be a multiple of the below value to allow
149 // for vectorized convolution.
150 #define MOD_TRUNCSIZE (8)
152 // The defaults for the command line options.
153 #define DEFAULT_EQUALIZE (1)
154 #define DEFAULT_SURFACE (1)
155 #define DEFAULT_LIMIT (24.0)
156 #define DEFAULT_TRUNCSIZE (32)
158 // The four-character-codes for RIFF/RIFX WAVE file chunks.
159 #define FOURCC_RIFF (0x46464952) // 'RIFF'
160 #define FOURCC_RIFX (0x58464952) // 'RIFX'
161 #define FOURCC_WAVE (0x45564157) // 'WAVE'
162 #define FOURCC_FMT (0x20746D66) // 'fmt '
163 #define FOURCC_DATA (0x61746164) // 'data'
164 #define FOURCC_LIST (0x5453494C) // 'LIST'
165 #define FOURCC_WAVL (0x6C766177) // 'wavl'
166 #define FOURCC_SLNT (0x746E6C73) // 'slnt'
168 // The supported wave formats.
169 #define WAVE_FORMAT_PCM (0x0001)
170 #define WAVE_FORMAT_IEEE_FLOAT (0x0003)
171 #define WAVE_FORMAT_EXTENSIBLE (0xFFFE)
173 // The maximum propagation delay value supported by OpenAL Soft.
174 #define MAX_HRTD (63.0)
176 // The OpenAL Soft HRTF format marker. It stands for minimum-phase head
177 // response protocol 01.
178 #define MHR_FORMAT ("MinPHR01")
180 // Byte order for the serialization routines.
181 enum ByteOrderT {
182 BO_NONE = 0,
183 BO_LITTLE ,
184 BO_BIG
187 // Source format for the references listed in the data set definition.
188 enum SourceFormatT {
189 SF_NONE = 0,
190 SF_WAVE , // RIFF/RIFX WAVE file.
191 SF_BIN_LE , // Little-endian binary file.
192 SF_BIN_BE , // Big-endian binary file.
193 SF_ASCII // ASCII text file.
196 // Element types for the references listed in the data set definition.
197 enum ElementTypeT {
198 ET_NONE = 0,
199 ET_INT , // Integer elements.
200 ET_FP // Floating-point elements.
203 // Desired output format from the command line.
204 enum OutputFormatT {
205 OF_NONE = 0,
206 OF_MHR , // OpenAL Soft MHR data set file.
207 OF_TABLE // OpenAL Soft built-in table file (used when compiling).
210 // Unsigned integer type.
211 typedef unsigned int uint;
213 // Serialization types. The trailing digit indicates the number of bytes.
214 typedef ALubyte uint1;
216 typedef ALint int4;
217 typedef ALuint uint4;
219 #if defined (HAVE_STDINT_H)
220 #include <stdint.h>
222 typedef uint64_t uint8;
223 #elif defined (HAVE___INT64)
224 typedef unsigned __int64 uint8;
225 #elif (SIZEOF_LONG == 8)
226 typedef unsigned long uint8;
227 #elif (SIZEOF_LONG_LONG == 8)
228 typedef unsigned long long uint8;
229 #endif
231 typedef enum ByteOrderT ByteOrderT;
232 typedef enum SourceFormatT SourceFormatT;
233 typedef enum ElementTypeT ElementTypeT;
234 typedef enum OutputFormatT OutputFormatT;
236 typedef struct TokenReaderT TokenReaderT;
237 typedef struct SourceRefT SourceRefT;
238 typedef struct HrirDataT HrirDataT;
240 // Token reader state for parsing the data set definition.
241 struct TokenReaderT {
242 FILE * mFile;
243 const char * mName;
244 uint mLine,
245 mColumn;
246 char mRing [TR_RING_SIZE];
247 size_t mIn,
248 mOut;
251 // Source reference state used when loading sources.
252 struct SourceRefT {
253 SourceFormatT mFormat;
254 ElementTypeT mType;
255 uint mSize;
256 int mBits;
257 uint mChannel,
258 mSkip,
259 mOffset;
260 char mPath [MAX_PATH_LEN + 1];
263 // The HRIR metrics and data set used when loading, processing, and storing
264 // the resulting HRTF.
265 struct HrirDataT {
266 uint mIrRate,
267 mIrCount;
268 size_t mIrSize,
269 mIrPoints,
270 mFftSize;
271 uint mEvCount,
272 mEvStart,
273 mAzCount [MAX_EV_COUNT],
274 mEvOffset [MAX_EV_COUNT];
275 double mRadius,
276 mDistance,
277 * mHrirs,
278 * mHrtds,
279 mMaxHrtd;
282 /* Token reader routines for parsing text files. Whitespace is not
283 * significant. It can process tokens as identifiers, numbers (integer and
284 * floating-point), strings, and operators. Strings must be encapsulated by
285 * double-quotes and cannot span multiple lines.
288 // Setup the reader on the given file. The filename can be NULL if no error
289 // output is desired.
290 static void TrSetup (FILE * fp, const char * filename, TokenReaderT * tr) {
291 const char * name = NULL;
292 char ch;
294 tr -> mFile = fp;
295 name = filename;
296 // If a filename was given, store a pointer to the base name.
297 if (filename != NULL) {
298 while ((ch = (* filename)) != '\0') {
299 if ((ch == '/') || (ch == '\\'))
300 name = filename + 1;
301 filename ++;
304 tr -> mName = name;
305 tr -> mLine = 1;
306 tr -> mColumn = 1;
307 tr -> mIn = 0;
308 tr -> mOut = 0;
311 // Prime the reader's ring buffer, and return a result indicating that there
312 // is text to process.
313 static int TrLoad (TokenReaderT * tr) {
314 size_t toLoad, in, count;
316 toLoad = TR_RING_SIZE - (tr -> mIn - tr -> mOut);
317 if ((toLoad >= TR_LOAD_SIZE) && (! feof (tr -> mFile))) {
318 // Load TR_LOAD_SIZE (or less if at the end of the file) per read.
319 toLoad = TR_LOAD_SIZE;
320 in = tr -> mIn & TR_RING_MASK;
321 count = TR_RING_SIZE - in;
322 if (count < toLoad) {
323 tr -> mIn += fread (& tr -> mRing [in], 1, count, tr -> mFile);
324 tr -> mIn += fread (& tr -> mRing [0], 1, toLoad - count, tr -> mFile);
325 } else {
326 tr -> mIn += fread (& tr -> mRing [in], 1, toLoad, tr -> mFile);
328 if (tr -> mOut >= TR_RING_SIZE) {
329 tr -> mOut -= TR_RING_SIZE;
330 tr -> mIn -= TR_RING_SIZE;
333 if (tr -> mIn > tr -> mOut)
334 return (1);
335 return (0);
338 // Error display routine. Only displays when the base name is not NULL.
339 static void TrErrorVA (const TokenReaderT * tr, uint line, uint column, const char * format, va_list argPtr) {
340 if (tr -> mName != NULL) {
341 fprintf (stderr, "Error (%s:%d:%d): ", tr -> mName, line, column);
342 vfprintf (stderr, format, argPtr);
346 // Used to display an error at a saved line/column.
347 static void TrErrorAt (const TokenReaderT * tr, uint line, uint column, const char * format, ...) {
348 va_list argPtr;
350 va_start (argPtr, format);
351 TrErrorVA (tr, line, column, format, argPtr);
352 va_end (argPtr);
355 // Used to display an error at the current line/column.
356 static void TrError (const TokenReaderT * tr, const char * format, ...) {
357 va_list argPtr;
359 va_start (argPtr, format);
360 TrErrorVA (tr, tr -> mLine, tr -> mColumn, format, argPtr);
361 va_end (argPtr);
364 // Skips to the next line.
365 static void TrSkipLine (TokenReaderT * tr) {
366 char ch;
368 while (TrLoad (tr)) {
369 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
370 tr -> mOut ++;
371 if (ch == '\n') {
372 tr -> mLine ++;
373 tr -> mColumn = 1;
374 break;
376 tr -> mColumn ++;
380 // Skips to the next token.
381 static int TrSkipWhitespace (TokenReaderT * tr) {
382 char ch;
384 while (TrLoad (tr)) {
385 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
386 if (isspace (ch)) {
387 tr -> mOut ++;
388 if (ch == '\n') {
389 tr -> mLine ++;
390 tr -> mColumn = 1;
391 } else {
392 tr -> mColumn ++;
394 } else if (ch == '#') {
395 TrSkipLine (tr);
396 } else {
397 return (1);
400 return (0);
403 // Get the line and/or column of the next token (or the end of input).
404 static void TrIndication (TokenReaderT * tr, uint * line, uint * column) {
405 TrSkipWhitespace (tr);
406 if (line != NULL)
407 (* line) = tr -> mLine;
408 if (column != NULL)
409 (* column) = tr -> mColumn;
412 // Checks to see if a token is the given operator. It does not display any
413 // errors and will not proceed to the next token.
414 static int TrIsOperator (TokenReaderT * tr, const char * op) {
415 size_t out, len;
416 char ch;
418 if (! TrSkipWhitespace (tr))
419 return (0);
420 out = tr -> mOut;
421 len = 0;
422 while ((op [len] != '\0') && (out < tr -> mIn)) {
423 ch = tr -> mRing [out & TR_RING_MASK];
424 if (ch != op [len])
425 break;
426 len ++;
427 out ++;
429 if (op [len] == '\0')
430 return (1);
431 return (0);
434 /* The TrRead*() routines obtain the value of a matching token type. They
435 * display type, form, and boundary errors and will proceed to the next
436 * token.
439 // Reads and validates an identifier token.
440 static int TrReadIdent (TokenReaderT * tr, const size_t maxLen, char * ident) {
441 uint col;
442 size_t len;
443 char ch;
445 col = tr -> mColumn;
446 if (TrSkipWhitespace (tr)) {
447 col = tr -> mColumn;
448 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
449 if ((ch == '_') || isalpha (ch)) {
450 len = 0;
451 do {
452 if (len < maxLen)
453 ident [len] = ch;
454 len ++;
455 tr -> mOut ++;
456 if (! TrLoad (tr))
457 break;
458 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
459 } while ((ch == '_') || isdigit (ch) || isalpha (ch));
460 tr -> mColumn += len;
461 if (len > maxLen) {
462 TrErrorAt (tr, tr -> mLine, col, "Identifier is too long.\n");
463 return (0);
465 ident [len] = '\0';
466 return (1);
469 TrErrorAt (tr, tr -> mLine, col, "Expected an identifier.\n");
470 return (0);
473 // Reads and validates (including bounds) an integer token.
474 static int TrReadInt (TokenReaderT * tr, const int loBound, const int hiBound, int * value) {
475 uint col, digis;
476 size_t len;
477 char ch, temp [64 + 1];
479 col = tr -> mColumn;
480 if (TrSkipWhitespace (tr)) {
481 col = tr -> mColumn;
482 len = 0;
483 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
484 if ((ch == '+') || (ch == '-')) {
485 temp [len] = ch;
486 len ++;
487 tr -> mOut ++;
489 digis = 0;
490 while (TrLoad (tr)) {
491 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
492 if (! isdigit (ch))
493 break;
494 if (len < 64)
495 temp [len] = ch;
496 len ++;
497 digis ++;
498 tr -> mOut ++;
500 tr -> mColumn += len;
501 if ((digis > 0) && (ch != '.') && (! isalpha (ch))) {
502 if (len > 64) {
503 TrErrorAt (tr, tr -> mLine, col, "Integer is too long.");
504 return (0);
506 temp [len] = '\0';
507 (* value) = strtol (temp, NULL, 10);
508 if (((* value) < loBound) || ((* value) > hiBound)) {
509 TrErrorAt (tr, tr -> mLine, col, "Expected a value from %d to %d.\n", loBound, hiBound);
510 return (0);
512 return (1);
515 TrErrorAt (tr, tr -> mLine, col, "Expected an integer.\n");
516 return (0);
519 // Reads and validates (including bounds) a float token.
520 static int TrReadFloat (TokenReaderT * tr, const double loBound, const double hiBound, double * value) {
521 uint col, digis;
522 size_t len;
523 char ch, temp [64 + 1];
525 col = tr -> mColumn;
526 if (TrSkipWhitespace (tr)) {
527 col = tr -> mColumn;
528 len = 0;
529 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
530 if ((ch == '+') || (ch == '-')) {
531 temp [len] = ch;
532 len ++;
533 tr -> mOut ++;
535 digis = 0;
536 while (TrLoad (tr)) {
537 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
538 if (! isdigit (ch))
539 break;
540 if (len < 64)
541 temp [len] = ch;
542 len ++;
543 digis ++;
544 tr -> mOut ++;
546 if (ch == '.') {
547 if (len < 64)
548 temp [len] = ch;
549 len ++;
550 tr -> mOut ++;
552 while (TrLoad (tr)) {
553 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
554 if (! isdigit (ch))
555 break;
556 if (len < 64)
557 temp [len] = ch;
558 len ++;
559 digis ++;
560 tr -> mOut ++;
562 if (digis > 0) {
563 if ((ch == 'E') || (ch == 'e')) {
564 if (len < 64)
565 temp [len] = ch;
566 len ++;
567 digis = 0;
568 tr -> mOut ++;
569 if ((ch == '+') || (ch == '-')) {
570 if (len < 64)
571 temp [len] = ch;
572 len ++;
573 tr -> mOut ++;
575 while (TrLoad (tr)) {
576 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
577 if (! isdigit (ch))
578 break;
579 if (len < 64)
580 temp [len] = ch;
581 len ++;
582 digis ++;
583 tr -> mOut ++;
586 tr -> mColumn += len;
587 if ((digis > 0) && (ch != '.') && (! isalpha (ch))) {
588 if (len > 64) {
589 TrErrorAt (tr, tr -> mLine, col, "Float is too long.");
590 return (0);
592 temp [len] = '\0';
593 (* value) = strtod (temp, NULL);
594 if (((* value) < loBound) || ((* value) > hiBound)) {
595 TrErrorAt (tr, tr -> mLine, col, "Expected a value from %f to %f.\n", loBound, hiBound);
596 return (0);
598 return (1);
600 } else {
601 tr -> mColumn += len;
604 TrErrorAt (tr, tr -> mLine, col, "Expected a float.\n");
605 return (0);
608 // Reads and validates a string token.
609 static int TrReadString (TokenReaderT * tr, const size_t maxLen, char * text) {
610 uint col;
611 size_t len;
612 char ch;
614 col = tr -> mColumn;
615 if (TrSkipWhitespace (tr)) {
616 col = tr -> mColumn;
617 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
618 if (ch == '\"') {
619 tr -> mOut ++;
620 len = 0;
621 while (TrLoad (tr)) {
622 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
623 tr -> mOut ++;
624 if (ch == '\"')
625 break;
626 if (ch == '\n') {
627 TrErrorAt (tr, tr -> mLine, col, "Unterminated string at end of line.\n");
628 return (0);
630 if (len < maxLen)
631 text [len] = ch;
632 len ++;
634 if (ch != '\"') {
635 tr -> mColumn += 1 + len;
636 TrErrorAt (tr, tr -> mLine, col, "Unterminated string at end of input.\n");
637 return (0);
639 tr -> mColumn += 2 + len;
640 if (len > maxLen) {
641 TrErrorAt (tr, tr -> mLine, col, "String is too long.\n");
642 return (0);
644 text [len] = '\0';
645 return (1);
648 TrErrorAt (tr, tr -> mLine, col, "Expected a string.\n");
649 return (0);
652 // Reads and validates the given operator.
653 static int TrReadOperator (TokenReaderT * tr, const char * op) {
654 uint col;
655 size_t len;
656 char ch;
658 col = tr -> mColumn;
659 if (TrSkipWhitespace (tr)) {
660 col = tr -> mColumn;
661 len = 0;
662 while ((op [len] != '\0') && TrLoad (tr)) {
663 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
664 if (ch != op [len])
665 break;
666 len ++;
667 tr -> mOut ++;
669 tr -> mColumn += len;
670 if (op [len] == '\0')
671 return (1);
673 TrErrorAt (tr, tr -> mLine, col, "Expected '%s' operator.\n", op);
674 return (0);
677 /* Performs a string substitution. Any case-insensitive occurrences of the
678 * pattern string are replaced with the replacement string. The result is
679 * truncated if necessary.
681 static int StrSubst (const char * in, const char * pat, const char * rep, const size_t maxLen, char * out) {
682 size_t inLen, patLen, repLen;
683 size_t si, di;
684 int truncated;
686 inLen = strlen (in);
687 patLen = strlen (pat);
688 repLen = strlen (rep);
689 si = 0;
690 di = 0;
691 truncated = 0;
692 while ((si < inLen) && (di < maxLen)) {
693 if (patLen <= (inLen - si)) {
694 if (strncasecmp (& in [si], pat, patLen) == 0) {
695 if (repLen > (maxLen - di)) {
696 repLen = maxLen - di;
697 truncated = 1;
699 strncpy (& out [di], rep, repLen);
700 si += patLen;
701 di += repLen;
704 out [di] = in [si];
705 si ++;
706 di ++;
708 if (si < inLen)
709 truncated = 1;
710 out [di] = '\0';
711 return (! truncated);
714 // Provide missing math routines for MSVC.
715 #ifdef _MSC_VER
716 static double round (double val) {
717 if (val < 0.0)
718 return (ceil (val - 0.5));
719 return (floor (val + 0.5));
722 static double fmin (double a, double b) {
723 return ((a < b) ? a : b);
726 static double fmax (double a, double b) {
727 return ((a > b) ? a : b);
729 #endif
731 // Simple clamp routine.
732 static double Clamp (const double val, const double lower, const double upper) {
733 return (fmin (fmax (val, lower), upper));
736 // Performs linear interpolation.
737 static double Lerp (const double a, const double b, const double f) {
738 return (a + (f * (b - a)));
741 // Performs a high-passed triangular probability density function dither from
742 // a double to an integer. It assumes the input sample is already scaled.
743 static int HpTpdfDither (const double in, int * hpHist) {
744 const double PRNG_SCALE = 1.0 / RAND_MAX;
745 int prn;
746 double out;
748 prn = rand ();
749 out = round (in + (PRNG_SCALE * (prn - (* hpHist))));
750 (* hpHist) = prn;
751 return ((int) out);
754 // Allocates an array of doubles.
755 static double * CreateArray (const size_t n) {
756 double * a = NULL;
758 a = (double *) calloc (n, sizeof (double));
759 if (a == NULL) {
760 fprintf (stderr, "Error: Out of memory.\n");
761 exit (-1);
763 return (a);
766 // Frees an array of doubles.
767 static void DestroyArray (const double * a) {
768 free ((void *) a);
771 // Complex number routines. All outputs must be non-NULL.
773 // Magnitude/absolute value.
774 static double ComplexAbs (const double r, const double i) {
775 return (sqrt ((r * r) + (i * i)));
778 // Multiply.
779 static void ComplexMul (const double aR, const double aI, const double bR, const double bI, double * outR, double * outI) {
780 (* outR) = (aR * bR) - (aI * bI);
781 (* outI) = (aI * bR) + (aR * bI);
784 // Base-e exponent.
785 static void ComplexExp (const double inR, const double inI, double * outR, double * outI) {
786 double e;
788 e = exp (inR);
789 (* outR) = e * cos (inI);
790 (* outI) = e * sin (inI);
793 /* Fast Fourier transform routines. The number of points must be a power of
794 * two. In-place operation is possible only if both the real and imaginary
795 * parts are in-place together.
798 // Performs bit-reversal ordering.
799 static void FftArrange (const size_t n, const double * inR, const double * inI, double * outR, double * outI) {
800 size_t rk, k, m;
801 double tempR, tempI;
803 if ((inR == outR) && (inI == outI)) {
804 // Handle in-place arrangement.
805 rk = 0;
806 for (k = 0; k < n; k ++) {
807 if (rk > k) {
808 tempR = inR [rk];
809 tempI = inI [rk];
810 outR [rk] = inR [k];
811 outI [rk] = inI [k];
812 outR [k] = tempR;
813 outI [k] = tempI;
815 m = n;
816 while (rk & (m >>= 1))
817 rk &= ~m;
818 rk |= m;
820 } else {
821 // Handle copy arrangement.
822 rk = 0;
823 for (k = 0; k < n; k ++) {
824 outR [rk] = inR [k];
825 outI [rk] = inI [k];
826 m = n;
827 while (rk & (m >>= 1))
828 rk &= ~m;
829 rk |= m;
834 // Performs the summation.
835 static void FftSummation (const size_t n, const double s, double * re, double * im) {
836 double pi;
837 size_t m, m2;
838 double vR, vI, wR, wI;
839 size_t i, k, mk;
840 double tR, tI;
842 pi = s * M_PI;
843 for (m = 1, m2 = 2; m < n; m <<= 1, m2 <<= 1) {
844 // v = Complex (-2.0 * sin (0.5 * pi / m) * sin (0.5 * pi / m), -sin (pi / m))
845 vR = sin (0.5 * pi / m);
846 vR = -2.0 * vR * vR;
847 vI = -sin (pi / m);
848 // w = Complex (1.0, 0.0)
849 wR = 1.0;
850 wI = 0.0;
851 for (i = 0; i < m; i ++) {
852 for (k = i; k < n; k += m2) {
853 mk = k + m;
854 // t = ComplexMul (w, out [km2])
855 tR = (wR * re [mk]) - (wI * im [mk]);
856 tI = (wR * im [mk]) + (wI * re [mk]);
857 // out [mk] = ComplexSub (out [k], t)
858 re [mk] = re [k] - tR;
859 im [mk] = im [k] - tI;
860 // out [k] = ComplexAdd (out [k], t)
861 re [k] += tR;
862 im [k] += tI;
864 // t = ComplexMul (v, w)
865 tR = (vR * wR) - (vI * wI);
866 tI = (vR * wI) + (vI * wR);
867 // w = ComplexAdd (w, t)
868 wR += tR;
869 wI += tI;
874 // Performs a forward FFT.
875 static void FftForward (const size_t n, const double * inR, const double * inI, double * outR, double * outI) {
876 FftArrange (n, inR, inI, outR, outI);
877 FftSummation (n, 1.0, outR, outI);
880 // Performs an inverse FFT.
881 static void FftInverse (const size_t n, const double * inR, const double * inI, double * outR, double * outI) {
882 double f;
883 size_t i;
885 FftArrange (n, inR, inI, outR, outI);
886 FftSummation (n, -1.0, outR, outI);
887 f = 1.0 / n;
888 for (i = 0; i < n; i ++) {
889 outR [i] *= f;
890 outI [i] *= f;
894 /* Calculate the complex helical sequence (or discrete-time analytical
895 * signal) of the given input using the Hilbert transform. Given the
896 * negative natural logarithm of a signal's magnitude response, the imaginary
897 * components can be used as the angles for minimum-phase reconstruction.
899 static void Hilbert (const size_t n, const double * in, double * outR, double * outI) {
900 size_t i;
902 if (in == outR) {
903 // Handle in-place operation.
904 for (i = 0; i < n; i ++)
905 outI [i] = 0.0;
906 } else {
907 // Handle copy operation.
908 for (i = 0; i < n; i ++) {
909 outR [i] = in [i];
910 outI [i] = 0.0;
913 FftForward (n, outR, outI, outR, outI);
914 /* Currently the Fourier routines operate only on point counts that are
915 * powers of two. If that changes and n is odd, the following conditional
916 * should be: i < (n + 1) / 2.
918 for (i = 1; i < (n / 2); i ++) {
919 outR [i] *= 2.0;
920 outI [i] *= 2.0;
922 // If n is odd, the following increment should be skipped.
923 i ++;
924 for (; i < n; i ++) {
925 outR [i] = 0.0;
926 outI [i] = 0.0;
928 FftInverse (n, outR, outI, outR, outI);
931 /* Calculate the magnitude response of the given input. This is used in
932 * place of phase decomposition, since the phase residuals are discarded for
933 * minimum phase reconstruction. The mirrored half of the response is also
934 * discarded.
936 static void MagnitudeResponse (const size_t n, const double * inR, const double * inI, double * out) {
937 const size_t m = 1 + (n / 2);
938 size_t i;
940 for (i = 0; i < m; i ++)
941 out [i] = fmax (ComplexAbs (inR [i], inI [i]), EPSILON);
944 /* Apply a range limit (in dB) to the given magnitude response. This is used
945 * to adjust the effects of the diffuse-field average on the equalization
946 * process.
948 static void LimitMagnitudeResponse (const size_t n, const double limit, const double * in, double * out) {
949 const size_t m = 1 + (n / 2);
950 double halfLim;
951 size_t i, lower, upper;
952 double ave;
954 halfLim = limit / 2.0;
955 // Convert the response to dB.
956 for (i = 0; i < m; i ++)
957 out [i] = 20.0 * log10 (in [i]);
958 // Use six octaves to calculate the average magnitude of the signal.
959 lower = ((size_t) ceil (n / pow (2.0, 8.0))) - 1;
960 upper = ((size_t) floor (n / pow (2.0, 2.0))) - 1;
961 ave = 0.0;
962 for (i = lower; i <= upper; i ++)
963 ave += out [i];
964 ave /= upper - lower + 1;
965 // Keep the response within range of the average magnitude.
966 for (i = 0; i < m; i ++)
967 out [i] = Clamp (out [i], ave - halfLim, ave + halfLim);
968 // Convert the response back to linear magnitude.
969 for (i = 0; i < m; i ++)
970 out [i] = pow (10.0, out [i] / 20.0);
973 /* Reconstructs the minimum-phase component for the given magnitude response
974 * of a signal. This is equivalent to phase recomposition, sans the missing
975 * residuals (which were discarded). The mirrored half of the response is
976 * reconstructed.
978 static void MinimumPhase (const size_t n, const double * in, double * outR, double * outI) {
979 const size_t m = 1 + (n / 2);
980 double * mags = NULL;
981 size_t i;
982 double aR, aI;
984 mags = CreateArray (n);
985 for (i = 0; i < m; i ++) {
986 mags [i] = fmax (in [i], EPSILON);
987 outR [i] = -log (mags [i]);
989 for (; i < n; i ++) {
990 mags [i] = mags [n - i];
991 outR [i] = outR [n - i];
993 Hilbert (n, outR, outR, outI);
994 // Remove any DC offset the filter has.
995 outR [0] = 0.0;
996 outI [0] = 0.0;
997 for (i = 1; i < n; i ++) {
998 ComplexExp (0.0, outI [i], & aR, & aI);
999 ComplexMul (mags [i], 0.0, aR, aI, & outR [i], & outI [i]);
1001 DestroyArray (mags);
1004 // Read a binary value of the specified byte order and byte size from a file,
1005 // storing it as a 32-bit unsigned integer.
1006 static int ReadBin4 (FILE * fp, const char * filename, const ByteOrderT order, const uint bytes, uint4 * out) {
1007 uint1 in [4];
1008 uint4 accum;
1009 uint i;
1011 if (fread (in, 1, bytes, fp) != bytes) {
1012 fprintf (stderr, "Error: Bad read from file '%s'.\n", filename);
1013 return (0);
1015 accum = 0;
1016 switch (order) {
1017 case BO_LITTLE :
1018 for (i = 0; i < bytes; i ++)
1019 accum = (accum << 8) | in [bytes - i - 1];
1020 break;
1021 case BO_BIG :
1022 for (i = 0; i < bytes; i ++)
1023 accum = (accum << 8) | in [i];
1024 break;
1025 default :
1026 break;
1028 (* out) = accum;
1029 return (1);
1032 // Read a binary value of the specified byte order from a file, storing it as
1033 // a 64-bit unsigned integer.
1034 static int ReadBin8 (FILE * fp, const char * filename, const ByteOrderT order, uint8 * out) {
1035 uint1 in [8];
1036 uint8 accum;
1037 uint i;
1039 if (fread (in, 1, 8, fp) != 8) {
1040 fprintf (stderr, "Error: Bad read from file '%s'.\n", filename);
1041 return (0);
1043 accum = 0ULL;
1044 switch (order) {
1045 case BO_LITTLE :
1046 for (i = 0; i < 8; i ++)
1047 accum = (accum << 8) | in [8 - i - 1];
1048 break;
1049 case BO_BIG :
1050 for (i = 0; i < 8; i ++)
1051 accum = (accum << 8) | in [i];
1052 break;
1053 default :
1054 break;
1056 (* out) = accum;
1057 return (1);
1060 // Write an ASCII string to a file.
1061 static int WriteAscii (const char * out, FILE * fp, const char * filename) {
1062 size_t len;
1064 len = strlen (out);
1065 if (fwrite (out, 1, len, fp) != len) {
1066 fclose (fp);
1067 fprintf (stderr, "Error: Bad write to file '%s'.\n", filename);
1068 return (0);
1070 return (1);
1073 // Write a binary value of the given byte order and byte size to a file,
1074 // loading it from a 32-bit unsigned integer.
1075 static int WriteBin4 (const ByteOrderT order, const uint bytes, const uint4 in, FILE * fp, const char * filename) {
1076 uint1 out [4];
1077 uint i;
1079 switch (order) {
1080 case BO_LITTLE :
1081 for (i = 0; i < bytes; i ++)
1082 out [i] = (in >> (i * 8)) & 0x000000FF;
1083 break;
1084 case BO_BIG :
1085 for (i = 0; i < bytes; i ++)
1086 out [bytes - i - 1] = (in >> (i * 8)) & 0x000000FF;
1087 break;
1088 default :
1089 break;
1091 if (fwrite (out, 1, bytes, fp) != bytes) {
1092 fprintf (stderr, "Error: Bad write to file '%s'.\n", filename);
1093 return (0);
1095 return (1);
1098 /* Read a binary value of the specified type, byte order, and byte size from
1099 * a file, converting it to a double. For integer types, the significant
1100 * bits are used to normalize the result. The sign of bits determines
1101 * whether they are padded toward the MSB (negative) or LSB (positive).
1102 * Floating-point types are not normalized.
1104 static int ReadBinAsDouble (FILE * fp, const char * filename, const ByteOrderT order, const ElementTypeT type, const uint bytes, const int bits, double * out) {
1105 union {
1106 uint4 ui;
1107 int4 i;
1108 float f;
1109 } v4;
1110 union {
1111 uint8 ui;
1112 double f;
1113 } v8;
1115 (* out) = 0.0;
1116 if (bytes > 4) {
1117 if (! ReadBin8 (fp, filename, order, & v8 . ui))
1118 return (0);
1119 if (type == ET_FP)
1120 (* out) = v8 . f;
1121 } else {
1122 if (! ReadBin4 (fp, filename, order, bytes, & v4 . ui))
1123 return (0);
1124 if (type == ET_FP) {
1125 (* out) = (double) v4 . f;
1126 } else {
1127 if (bits > 0)
1128 v4 . ui >>= (8 * bytes) - bits;
1129 else
1130 v4 . ui &= (0xFFFFFFFF >> (32 + bits));
1131 if (v4 . ui & (1 << (abs (bits) - 1)))
1132 v4 . ui |= (0xFFFFFFFF << abs (bits));
1133 (* out) = v4 . i / ((double) (1 << (abs (bits) - 1)));
1136 return (1);
1139 /* Read an ascii value of the specified type from a file, converting it to a
1140 * double. For integer types, the significant bits are used to normalize the
1141 * result. The sign of the bits should always be positive. This also skips
1142 * up to one separator character before the element itself.
1144 static int ReadAsciiAsDouble (TokenReaderT * tr, const char * filename, const ElementTypeT type, const uint bits, double * out) {
1145 int v;
1147 if (TrIsOperator (tr, ","))
1148 TrReadOperator (tr, ",");
1149 else if (TrIsOperator (tr, ":"))
1150 TrReadOperator (tr, ":");
1151 else if (TrIsOperator (tr, ";"))
1152 TrReadOperator (tr, ";");
1153 else if (TrIsOperator (tr, "|"))
1154 TrReadOperator (tr, "|");
1155 if (type == ET_FP) {
1156 if (! TrReadFloat (tr, -HUGE_VAL, HUGE_VAL, out)) {
1157 fprintf (stderr, "Error: Bad read from file '%s'.\n", filename);
1158 return (0);
1160 } else {
1161 if (! TrReadInt (tr, -(1 << (bits - 1)), (1 << (bits - 1)) - 1, & v)) {
1162 fprintf (stderr, "Error: Bad read from file '%s'.\n", filename);
1163 return (0);
1165 (* out) = v / ((double) ((1 << (bits - 1)) - 1));
1167 return (1);
1170 // Read the RIFF/RIFX WAVE format chunk from a file, validating it against
1171 // the source parameters and data set metrics.
1172 static int ReadWaveFormat (FILE * fp, const ByteOrderT order, const uint hrirRate, SourceRefT * src) {
1173 uint4 fourCC, chunkSize;
1174 uint4 format, channels, rate, dummy, block, size, bits;
1176 chunkSize = 0;
1177 do {
1178 if (chunkSize > 0)
1179 fseek (fp, chunkSize, SEEK_CUR);
1180 if ((! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & fourCC)) ||
1181 (! ReadBin4 (fp, src -> mPath, order, 4, & chunkSize)))
1182 return (0);
1183 } while (fourCC != FOURCC_FMT);
1184 if ((! ReadBin4 (fp, src -> mPath, order, 2, & format)) ||
1185 (! ReadBin4 (fp, src -> mPath, order, 2, & channels)) ||
1186 (! ReadBin4 (fp, src -> mPath, order, 4, & rate)) ||
1187 (! ReadBin4 (fp, src -> mPath, order, 4, & dummy)) ||
1188 (! ReadBin4 (fp, src -> mPath, order, 2, & block)))
1189 return (0);
1190 block /= channels;
1191 if (chunkSize > 14) {
1192 if (! ReadBin4 (fp, src -> mPath, order, 2, & size))
1193 return (0);
1194 size /= 8;
1195 if (block > size)
1196 size = block;
1197 } else {
1198 size = block;
1200 if (format == WAVE_FORMAT_EXTENSIBLE) {
1201 fseek (fp, 2, SEEK_CUR);
1202 if (! ReadBin4 (fp, src -> mPath, order, 2, & bits))
1203 return (0);
1204 if (bits == 0)
1205 bits = 8 * size;
1206 fseek (fp, 4, SEEK_CUR);
1207 if (! ReadBin4 (fp, src -> mPath, order, 2, & format))
1208 return (0);
1209 fseek (fp, chunkSize - 26, SEEK_CUR);
1210 } else {
1211 bits = 8 * size;
1212 if (chunkSize > 14)
1213 fseek (fp, chunkSize - 16, SEEK_CUR);
1214 else
1215 fseek (fp, chunkSize - 14, SEEK_CUR);
1217 if ((format != WAVE_FORMAT_PCM) && (format != WAVE_FORMAT_IEEE_FLOAT)) {
1218 fprintf (stderr, "Error: Unsupported WAVE format in file '%s'.\n", src -> mPath);
1219 return (0);
1221 if (src -> mChannel >= channels) {
1222 fprintf (stderr, "Error: Missing source channel in WAVE file '%s'.\n", src -> mPath);
1223 return (0);
1225 if (rate != hrirRate) {
1226 fprintf (stderr, "Error: Mismatched source sample rate in WAVE file '%s'.\n", src -> mPath);
1227 return (0);
1229 if (format == WAVE_FORMAT_PCM) {
1230 if ((size < 2) || (size > 4)) {
1231 fprintf (stderr, "Error: Unsupported sample size in WAVE file '%s'.\n", src -> mPath);
1232 return (0);
1234 if ((bits < 16) || (bits > (8 * size))) {
1235 fprintf (stderr, "Error: Bad significant bits in WAVE file '%s'.\n", src -> mPath);
1236 return (0);
1238 src -> mType = ET_INT;
1239 } else {
1240 if ((size != 4) && (size != 8)) {
1241 fprintf (stderr, "Error: Unsupported sample size in WAVE file '%s'.\n", src -> mPath);
1242 return (0);
1244 src -> mType = ET_FP;
1246 src -> mSize = size;
1247 src -> mBits = (int) bits;
1248 src -> mSkip = channels;
1249 return (1);
1252 // Read a RIFF/RIFX WAVE data chunk, converting all elements to doubles.
1253 static int ReadWaveData (FILE * fp, const SourceRefT * src, const ByteOrderT order, const size_t n, double * hrir) {
1254 int pre, post, skip;
1255 size_t i;
1257 pre = (int) (src -> mSize * src -> mChannel);
1258 post = (int) (src -> mSize * (src -> mSkip - src -> mChannel - 1));
1259 skip = 0;
1260 for (i = 0; i < n; i ++) {
1261 skip += pre;
1262 if (skip > 0)
1263 fseek (fp, skip, SEEK_CUR);
1264 if (! ReadBinAsDouble (fp, src -> mPath, order, src -> mType, src -> mSize, src -> mBits, & hrir [i]))
1265 return (0);
1266 skip = post;
1268 if (skip > 0)
1269 fseek (fp, skip, SEEK_CUR);
1270 return (1);
1273 // Read the RIFF/RIFX WAVE list or data chunk, converting all elements to
1274 // doubles.
1275 static int ReadWaveList (FILE * fp, const SourceRefT * src, const ByteOrderT order, const size_t n, double * hrir) {
1276 uint4 fourCC, chunkSize, listSize, count;
1277 size_t block, skip, offset, i;
1278 double lastSample;
1280 for (;;) {
1281 if ((! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & fourCC)) ||
1282 (! ReadBin4 (fp, src -> mPath, order, 4, & chunkSize)))
1283 return (0);
1284 if (fourCC == FOURCC_DATA) {
1285 block = src -> mSize * src -> mSkip;
1286 count = chunkSize / block;
1287 if (count < (src -> mOffset + n)) {
1288 fprintf (stderr, "Error: Bad read from file '%s'.\n", src -> mPath);
1289 return (0);
1291 fseek (fp, src -> mOffset * block, SEEK_CUR);
1292 if (! ReadWaveData (fp, src, order, n, & hrir [0]))
1293 return (0);
1294 return (1);
1295 } else if (fourCC == FOURCC_LIST) {
1296 if (! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & fourCC))
1297 return (0);
1298 chunkSize -= 4;
1299 if (fourCC == FOURCC_WAVL)
1300 break;
1302 if (chunkSize > 0)
1303 fseek (fp, chunkSize, SEEK_CUR);
1305 listSize = chunkSize;
1306 block = src -> mSize * src -> mSkip;
1307 skip = src -> mOffset;
1308 offset = 0;
1309 lastSample = 0.0;
1310 while ((offset < n) && (listSize > 8)) {
1311 if ((! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & fourCC)) ||
1312 (! ReadBin4 (fp, src -> mPath, order, 4, & chunkSize)))
1313 return (0);
1314 listSize -= 8 + chunkSize;
1315 if (fourCC == FOURCC_DATA) {
1316 count = chunkSize / block;
1317 if (count > skip) {
1318 fseek (fp, skip * block, SEEK_CUR);
1319 chunkSize -= skip * block;
1320 count -= skip;
1321 skip = 0;
1322 if (count > (n - offset))
1323 count = n - offset;
1324 if (! ReadWaveData (fp, src, order, count, & hrir [offset]))
1325 return (0);
1326 chunkSize -= count * block;
1327 offset += count;
1328 lastSample = hrir [offset - 1];
1329 } else {
1330 skip -= count;
1331 count = 0;
1333 } else if (fourCC == FOURCC_SLNT) {
1334 if (! ReadBin4 (fp, src -> mPath, order, 4, & count))
1335 return (0);
1336 chunkSize -= 4;
1337 if (count > skip) {
1338 count -= skip;
1339 skip = 0;
1340 if (count > (n - offset))
1341 count = n - offset;
1342 for (i = 0; i < count; i ++)
1343 hrir [offset + i] = lastSample;
1344 offset += count;
1345 } else {
1346 skip -= count;
1347 count = 0;
1350 if (chunkSize > 0)
1351 fseek (fp, chunkSize, SEEK_CUR);
1353 if (offset < n) {
1354 fprintf (stderr, "Error: Bad read from file '%s'.\n", src -> mPath);
1355 return (0);
1357 return (1);
1360 // Load a source HRIR from a RIFF/RIFX WAVE file.
1361 static int LoadWaveSource (FILE * fp, SourceRefT * src, const uint hrirRate, const size_t n, double * hrir) {
1362 uint4 fourCC, dummy;
1363 ByteOrderT order;
1365 if ((! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & fourCC)) ||
1366 (! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & dummy)))
1367 return (0);
1368 if (fourCC == FOURCC_RIFF) {
1369 order = BO_LITTLE;
1370 } else if (fourCC == FOURCC_RIFX) {
1371 order = BO_BIG;
1372 } else {
1373 fprintf (stderr, "Error: No RIFF/RIFX chunk in file '%s'.\n", src -> mPath);
1374 return (0);
1376 if (! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & fourCC))
1377 return (0);
1378 if (fourCC != FOURCC_WAVE) {
1379 fprintf (stderr, "Error: Not a RIFF/RIFX WAVE file '%s'.\n", src -> mPath);
1380 return (0);
1382 if (! ReadWaveFormat (fp, order, hrirRate, src))
1383 return (0);
1384 if (! ReadWaveList (fp, src, order, n, hrir))
1385 return (0);
1386 return (1);
1389 // Load a source HRIR from a binary file.
1390 static int LoadBinarySource (FILE * fp, const SourceRefT * src, const ByteOrderT order, const size_t n, double * hrir) {
1391 size_t i;
1393 fseek (fp, src -> mOffset, SEEK_SET);
1394 for (i = 0; i < n; i ++) {
1395 if (! ReadBinAsDouble (fp, src -> mPath, order, src -> mType, src -> mSize, src -> mBits, & hrir [i]))
1396 return (0);
1397 if (src -> mSkip > 0)
1398 fseek (fp, src -> mSkip, SEEK_CUR);
1400 return (1);
1403 // Load a source HRIR from an ASCII text file containing a list of elements
1404 // separated by whitespace or common list operators (',', ';', ':', '|').
1405 static int LoadAsciiSource (FILE * fp, const SourceRefT * src, const size_t n, double * hrir) {
1406 TokenReaderT tr;
1407 size_t i, j;
1408 double dummy;
1410 TrSetup (fp, NULL, & tr);
1411 for (i = 0; i < src -> mOffset; i ++) {
1412 if (! ReadAsciiAsDouble (& tr, src -> mPath, src -> mType, src -> mBits, & dummy))
1413 return (0);
1415 for (i = 0; i < n; i ++) {
1416 if (! ReadAsciiAsDouble (& tr, src -> mPath, src -> mType, src -> mBits, & hrir [i]))
1417 return (0);
1418 for (j = 0; j < src -> mSkip; j ++) {
1419 if (! ReadAsciiAsDouble (& tr, src -> mPath, src -> mType, src -> mBits, & dummy))
1420 return (0);
1423 return (1);
1426 // Load a source HRIR from a supported file type.
1427 static int LoadSource (SourceRefT * src, const uint hrirRate, const size_t n, double * hrir) {
1428 FILE * fp = NULL;
1429 int result;
1431 if (src -> mFormat == SF_ASCII)
1432 fp = fopen (src -> mPath, "r");
1433 else
1434 fp = fopen (src -> mPath, "rb");
1435 if (fp == NULL) {
1436 fprintf (stderr, "Error: Could not open source file '%s'.\n", src -> mPath);
1437 return (0);
1439 if (src -> mFormat == SF_WAVE)
1440 result = LoadWaveSource (fp, src, hrirRate, n, hrir);
1441 else if (src -> mFormat == SF_BIN_LE)
1442 result = LoadBinarySource (fp, src, BO_LITTLE, n, hrir);
1443 else if (src -> mFormat == SF_BIN_BE)
1444 result = LoadBinarySource (fp, src, BO_BIG, n, hrir);
1445 else
1446 result = LoadAsciiSource (fp, src, n, hrir);
1447 fclose (fp);
1448 return (result);
1451 // Calculate the magnitude response of an HRIR and average it with any
1452 // existing responses for its elevation and azimuth.
1453 static void AverageHrirMagnitude (const double * hrir, const double f, const uint ei, const uint ai, const HrirDataT * hData) {
1454 double * re = NULL, * im = NULL;
1455 size_t n, m, i, j;
1457 n = hData -> mFftSize;
1458 re = CreateArray (n);
1459 im = CreateArray (n);
1460 for (i = 0; i < hData -> mIrPoints; i ++) {
1461 re [i] = hrir [i];
1462 im [i] = 0.0;
1464 for (; i < n; i ++) {
1465 re [i] = 0.0;
1466 im [i] = 0.0;
1468 FftForward (n, re, im, re, im);
1469 MagnitudeResponse (n, re, im, re);
1470 m = 1 + (n / 2);
1471 j = (hData -> mEvOffset [ei] + ai) * hData -> mIrSize;
1472 for (i = 0; i < m; i ++)
1473 hData -> mHrirs [j + i] = Lerp (hData -> mHrirs [j + i], re [i], f);
1474 DestroyArray (im);
1475 DestroyArray (re);
1478 /* Calculate the contribution of each HRIR to the diffuse-field average based
1479 * on the area of its surface patch. All patches are centered at the HRIR
1480 * coordinates on the unit sphere and are measured by solid angle.
1482 static void CalculateDfWeights (const HrirDataT * hData, double * weights) {
1483 uint ei;
1484 double evs, sum, ev, up_ev, down_ev, solidAngle;
1486 evs = 90.0 / (hData -> mEvCount - 1);
1487 sum = 0.0;
1488 for (ei = hData -> mEvStart; ei < hData -> mEvCount; ei ++) {
1489 // For each elevation, calculate the upper and lower limits of the
1490 // patch band.
1491 ev = -90.0 + (ei * 2.0 * evs);
1492 if (ei < (hData -> mEvCount - 1))
1493 up_ev = (ev + evs) * M_PI / 180.0;
1494 else
1495 up_ev = M_PI / 2.0;
1496 if (ei > 0)
1497 down_ev = (ev - evs) * M_PI / 180.0;
1498 else
1499 down_ev = -M_PI / 2.0;
1500 // Calculate the area of the patch band.
1501 solidAngle = 2.0 * M_PI * (sin (up_ev) - sin (down_ev));
1502 // Each weight is the area of one patch.
1503 weights [ei] = solidAngle / hData -> mAzCount [ei];
1504 // Sum the total surface area covered by the HRIRs.
1505 sum += solidAngle;
1507 // Normalize the weights given the total surface coverage.
1508 for (ei = hData -> mEvStart; ei < hData -> mEvCount; ei ++)
1509 weights [ei] /= sum;
1512 /* Calculate the diffuse-field average from the given magnitude responses of
1513 * the HRIR set. Weighting can be applied to compensate for the varying
1514 * surface area covered by each HRIR. The final average can then be limited
1515 * by the specified magnitude range (in positive dB; 0.0 to skip).
1517 static void CalculateDiffuseFieldAverage (const HrirDataT * hData, const int weighted, const double limit, double * dfa) {
1518 double * weights = NULL;
1519 uint ei, ai;
1520 size_t count, step, start, end, m, j, i;
1521 double weight;
1523 weights = CreateArray (hData -> mEvCount);
1524 if (weighted) {
1525 // Use coverage weighting to calculate the average.
1526 CalculateDfWeights (hData, weights);
1527 } else {
1528 // If coverage weighting is not used, the weights still need to be
1529 // averaged by the number of HRIRs.
1530 count = 0;
1531 for (ei = hData -> mEvStart; ei < hData -> mEvCount; ei ++)
1532 count += hData -> mAzCount [ei];
1533 for (ei = hData -> mEvStart; ei < hData -> mEvCount; ei ++)
1534 weights [ei] = 1.0 / count;
1536 ei = hData -> mEvStart;
1537 ai = 0;
1538 step = hData -> mIrSize;
1539 start = hData -> mEvOffset [ei] * step;
1540 end = hData -> mIrCount * step;
1541 m = 1 + (hData -> mFftSize / 2);
1542 for (i = 0; i < m; i ++)
1543 dfa [i] = 0.0;
1544 for (j = start; j < end; j += step) {
1545 // Get the weight for this HRIR's contribution.
1546 weight = weights [ei];
1547 // Add this HRIR's weighted power average to the total.
1548 for (i = 0; i < m; i ++)
1549 dfa [i] += weight * hData -> mHrirs [j + i] * hData -> mHrirs [j + i];
1550 // Determine the next weight to use.
1551 ai ++;
1552 if (ai >= hData -> mAzCount [ei]) {
1553 ei ++;
1554 ai = 0;
1557 // Finish the average calculation and keep it from being too small.
1558 for (i = 0; i < m; i ++)
1559 dfa [i] = fmax (sqrt (dfa [i]), EPSILON);
1560 // Apply a limit to the magnitude range of the diffuse-field average if
1561 // desired.
1562 if (limit > 0.0)
1563 LimitMagnitudeResponse (hData -> mFftSize, limit, dfa, dfa);
1564 DestroyArray (weights);
1567 // Perform diffuse-field equalization on the magnitude responses of the HRIR
1568 // set using the given average response.
1569 static void DiffuseFieldEqualize (const double * dfa, const HrirDataT * hData) {
1570 size_t step, start, end, m, j, i;
1572 step = hData -> mIrSize;
1573 start = hData -> mEvOffset [hData -> mEvStart] * step;
1574 end = hData -> mIrCount * step;
1575 m = 1 + (hData -> mFftSize / 2);
1576 for (j = start; j < end; j += step) {
1577 for (i = 0; i < m; i ++)
1578 hData -> mHrirs [j + i] /= dfa [i];
1582 // Perform minimum-phase reconstruction using the magnitude responses of the
1583 // HRIR set.
1584 static void ReconstructHrirs (const HrirDataT * hData) {
1585 double * re = NULL, * im = NULL;
1586 size_t step, start, end, n, j, i;
1588 step = hData -> mIrSize;
1589 start = hData -> mEvOffset [hData -> mEvStart] * step;
1590 end = hData -> mIrCount * step;
1591 n = hData -> mFftSize;
1592 re = CreateArray (n);
1593 im = CreateArray (n);
1594 for (j = start; j < end; j += step) {
1595 MinimumPhase (n, & hData -> mHrirs [j], re, im);
1596 FftInverse (n, re, im, re, im);
1597 for (i = 0; i < hData -> mIrPoints; i ++)
1598 hData -> mHrirs [j + i] = re [i];
1600 DestroyArray (im);
1601 DestroyArray (re);
1604 /* Given an elevation index and an azimuth, calculate the indices of the two
1605 * HRIRs that bound the coordinate along with a factor for calculating the
1606 * continous HRIR using interpolation.
1608 static void CalcAzIndices(const HrirDataT *hData, const uint ei, const double az, size_t *j0, size_t *j1, double *jf)
1610 double af;
1611 uint ai;
1613 af = ((2.0 * M_PI) + az) * hData -> mAzCount [ei] / (2.0 * M_PI);
1614 ai = ((uint) af) % hData -> mAzCount [ei];
1615 af -= floor (af);
1616 (* j0) = hData -> mEvOffset [ei] + ai;
1617 (* j1) = hData -> mEvOffset [ei] + ((ai + 1) % hData -> mAzCount [ei]);
1618 (* jf) = af;
1621 /* Attempt to synthesize any missing HRIRs at the bottom elevations. Right
1622 * now this just blends the lowest elevation HRIRs together and applies some
1623 * attenuation and high frequency damping. It is a simple, if inaccurate
1624 * model.
1626 static void SynthesizeHrirs (HrirDataT * hData) {
1627 uint oi, a, e;
1628 size_t step, n, i, j;
1629 double of;
1630 size_t j0, j1;
1631 double jf;
1632 double lp [4], s0, s1;
1634 if (hData -> mEvStart <= 0)
1635 return;
1636 step = hData -> mIrSize;
1637 oi = hData -> mEvStart;
1638 n = hData -> mIrPoints;
1639 for (i = 0; i < n; i ++)
1640 hData -> mHrirs [i] = 0.0;
1641 for (a = 0; a < hData -> mAzCount [oi]; a ++) {
1642 j = (hData -> mEvOffset [oi] + a) * step;
1643 for (i = 0; i < n; i ++)
1644 hData -> mHrirs [i] += hData -> mHrirs [j + i] / hData -> mAzCount [oi];
1646 for (e = 1; e < hData -> mEvStart; e ++) {
1647 of = ((double) e) / hData -> mEvStart;
1648 for (a = 0; a < hData -> mAzCount [e]; a ++) {
1649 j = (hData -> mEvOffset [e] + a) * step;
1650 CalcAzIndices (hData, oi, a * 2.0 * M_PI / hData -> mAzCount [e], & j0, & j1, & jf);
1651 j0 *= step;
1652 j1 *= step;
1653 lp [0] = 0.0;
1654 lp [1] = 0.0;
1655 lp [2] = 0.0;
1656 lp [3] = 0.0;
1657 for (i = 0; i < n; i ++) {
1658 s0 = hData -> mHrirs [i];
1659 s1 = Lerp (hData -> mHrirs [j0 + i], hData -> mHrirs [j1 + i], jf);
1660 s0 = Lerp (s0, s1, of);
1661 lp [0] = Lerp (s0, lp [0], 0.15 - (0.15 * of));
1662 lp [1] = Lerp (lp [0], lp [1], 0.15 - (0.15 * of));
1663 lp [2] = Lerp (lp [1], lp [2], 0.15 - (0.15 * of));
1664 lp [3] = Lerp (lp [2], lp [3], 0.15 - (0.15 * of));
1665 hData -> mHrirs [j + i] = lp [3];
1669 lp [0] = 0.0;
1670 lp [1] = 0.0;
1671 lp [2] = 0.0;
1672 lp [3] = 0.0;
1673 for (i = 0; i < n; i ++) {
1674 s0 = hData -> mHrirs [i];
1675 lp [0] = Lerp (s0, lp [0], 0.15);
1676 lp [1] = Lerp (lp [0], lp [1], 0.15);
1677 lp [2] = Lerp (lp [1], lp [2], 0.15);
1678 lp [3] = Lerp (lp [2], lp [3], 0.15);
1679 hData -> mHrirs [i] = lp [3];
1681 hData -> mEvStart = 0;
1684 // The following routines assume a full set of HRIRs for all elevations.
1686 // Normalize the HRIR set and slightly attenuate the result.
1687 static void NormalizeHrirs (const HrirDataT * hData) {
1688 size_t step, end, n, j, i;
1689 double maxLevel;
1691 step = hData -> mIrSize;
1692 end = hData -> mIrCount * step;
1693 n = hData -> mIrPoints;
1694 maxLevel = 0.0;
1695 for (j = 0; j < end; j += step) {
1696 for (i = 0; i < n; i ++)
1697 maxLevel = fmax (fabs (hData -> mHrirs [j + i]), maxLevel);
1699 maxLevel = 1.01 * maxLevel;
1700 for (j = 0; j < end; j += step) {
1701 for (i = 0; i < n; i ++)
1702 hData -> mHrirs [j + i] /= maxLevel;
1706 // Calculate the left-ear time delay using a spherical head model.
1707 static double CalcLTD (const double ev, const double az, const double rad, const double dist) {
1708 double azp, dlp, l, al;
1710 azp = asin (cos (ev) * sin (az));
1711 dlp = sqrt ((dist * dist) + (rad * rad) + (2.0 * dist * rad * sin (azp)));
1712 l = sqrt ((dist * dist) - (rad * rad));
1713 al = (0.5 * M_PI) + azp;
1714 if (dlp > l)
1715 dlp = l + (rad * (al - acos (rad / dist)));
1716 return (dlp / 343.3);
1719 // Calculate the effective head-related time delays for the each HRIR, now
1720 // that they are minimum-phase.
1721 static void CalculateHrtds (HrirDataT * hData) {
1722 double minHrtd, maxHrtd;
1723 uint e, a, j;
1724 double t;
1726 minHrtd = 1000.0;
1727 maxHrtd = -1000.0;
1728 for (e = 0; e < hData -> mEvCount; e ++) {
1729 for (a = 0; a < hData -> mAzCount [e]; a ++) {
1730 j = hData -> mEvOffset [e] + a;
1731 t = CalcLTD ((-90.0 + (e * 180.0 / (hData -> mEvCount - 1))) * M_PI / 180.0,
1732 (a * 360.0 / hData -> mAzCount [e]) * M_PI / 180.0,
1733 hData -> mRadius, hData -> mDistance);
1734 hData -> mHrtds [j] = t;
1735 maxHrtd = fmax (t, maxHrtd);
1736 minHrtd = fmin (t, minHrtd);
1739 maxHrtd -= minHrtd;
1740 for (j = 0; j < hData -> mIrCount; j ++)
1741 hData -> mHrtds [j] -= minHrtd;
1742 hData -> mMaxHrtd = maxHrtd;
1745 // Store the OpenAL Soft HRTF data set.
1746 static int StoreMhr (const HrirDataT * hData, const char * filename) {
1747 FILE * fp = NULL;
1748 uint e;
1749 size_t step, end, n, j, i;
1750 int hpHist, v;
1752 if ((fp = fopen (filename, "wb")) == NULL) {
1753 fprintf (stderr, "Error: Could not open MHR file '%s'.\n", filename);
1754 return (0);
1756 if (! WriteAscii (MHR_FORMAT, fp, filename))
1757 return (0);
1758 if (! WriteBin4 (BO_LITTLE, 4, (uint4) hData -> mIrRate, fp, filename))
1759 return (0);
1760 if (! WriteBin4 (BO_LITTLE, 1, (uint4) hData -> mIrPoints, fp, filename))
1761 return (0);
1762 if (! WriteBin4 (BO_LITTLE, 1, (uint4) hData -> mEvCount, fp, filename))
1763 return (0);
1764 for (e = 0; e < hData -> mEvCount; e ++) {
1765 if (! WriteBin4 (BO_LITTLE, 1, (uint4) hData -> mAzCount [e], fp, filename))
1766 return (0);
1768 step = hData -> mIrSize;
1769 end = hData -> mIrCount * step;
1770 n = hData -> mIrPoints;
1771 srand (0x31DF840C);
1772 for (j = 0; j < end; j += step) {
1773 hpHist = 0;
1774 for (i = 0; i < n; i ++) {
1775 v = HpTpdfDither (32767.0 * hData -> mHrirs [j + i], & hpHist);
1776 if (! WriteBin4 (BO_LITTLE, 2, (uint4) v, fp, filename))
1777 return (0);
1780 for (j = 0; j < hData -> mIrCount; j ++) {
1781 v = (int) fmin (round (hData -> mIrRate * hData -> mHrtds [j]), MAX_HRTD);
1782 if (! WriteBin4 (BO_LITTLE, 1, (uint4) v, fp, filename))
1783 return (0);
1785 fclose (fp);
1786 return (1);
1789 // Store the OpenAL Soft built-in table.
1790 static int StoreTable (const HrirDataT * hData, const char * filename) {
1791 FILE * fp = NULL;
1792 size_t step, end, n, j, i;
1793 int hpHist, v;
1794 char text [128 + 1];
1796 if ((fp = fopen (filename, "wb")) == NULL) {
1797 fprintf (stderr, "Error: Could not open table file '%s'.\n", filename);
1798 return (0);
1800 snprintf (text, 128, "/* Elevation metrics */\n"
1801 "static const ALubyte defaultAzCount[%u] = { ", hData -> mEvCount);
1802 if (! WriteAscii (text, fp, filename))
1803 return (0);
1804 for (i = 0; i < hData -> mEvCount; i ++) {
1805 snprintf (text, 128, "%u, ", hData -> mAzCount [i]);
1806 if (! WriteAscii (text, fp, filename))
1807 return (0);
1809 snprintf (text, 128, "};\n"
1810 "static const ALushort defaultEvOffset[%u] = { ", hData -> mEvCount);
1811 if (! WriteAscii (text, fp, filename))
1812 return (0);
1813 for (i = 0; i < hData -> mEvCount; i ++) {
1814 snprintf (text, 128, "%u, ", hData -> mEvOffset [i]);
1815 if (! WriteAscii (text, fp, filename))
1816 return (0);
1818 step = hData -> mIrSize;
1819 end = hData -> mIrCount * step;
1820 n = hData -> mIrPoints;
1821 snprintf (text, 128, "};\n\n"
1822 "/* HRIR Coefficients */\n"
1823 "static const ALshort defaultCoeffs[%zu] =\n{\n", hData -> mIrCount * n);
1824 if (! WriteAscii (text, fp, filename))
1825 return (0);
1826 srand (0x31DF840C);
1827 for (j = 0; j < end; j += step) {
1828 if (! WriteAscii (" ", fp, filename))
1829 return (0);
1830 hpHist = 0;
1831 for (i = 0; i < n; i ++) {
1832 v = HpTpdfDither (32767.0 * hData -> mHrirs [j + i], & hpHist);
1833 snprintf (text, 128, "%+d, ", v);
1834 if (! WriteAscii (text, fp, filename))
1835 return (0);
1837 if (! WriteAscii ("\n", fp, filename))
1838 return (0);
1840 snprintf (text, 128, "};\n\n"
1841 "/* HRIR Delays */\n"
1842 "static const ALubyte defaultDelays[%d] =\n{\n"
1843 " ", hData -> mIrCount);
1844 if (! WriteAscii (text, fp, filename))
1845 return (0);
1846 for (j = 0; j < hData -> mIrCount; j ++) {
1847 v = (int) fmin (round (hData -> mIrRate * hData -> mHrtds [j]), MAX_HRTD);
1848 snprintf (text, 128, "%d, ", v);
1849 if (! WriteAscii (text, fp, filename))
1850 return (0);
1852 if (! WriteAscii ("\n};\n\n"
1853 "/* Default HRTF Definition */\n", fp, filename))
1854 return (0);
1855 snprintf (text, 128, "static const struct Hrtf DefaultHrtf = {\n"
1856 " %u, %zu, %u, defaultAzCount, defaultEvOffset,\n",
1857 hData -> mIrRate, hData -> mIrPoints, hData -> mEvCount);
1858 if (! WriteAscii (text, fp, filename))
1859 return (0);
1860 if (! WriteAscii (" defaultCoeffs, defaultDelays, NULL\n"
1861 "};\n", fp, filename))
1862 return (0);
1863 fclose (fp);
1864 return (1);
1867 // Process the data set definition to read and validate the data set metrics.
1868 static int ProcessMetrics (TokenReaderT * tr, const size_t fftSize, const size_t truncSize, HrirDataT * hData) {
1869 char ident [MAX_IDENT_LEN + 1];
1870 uint line, col;
1871 int intVal;
1872 size_t points;
1873 double fpVal;
1874 int hasRate = 0, hasPoints = 0, hasAzimuths = 0;
1875 int hasRadius = 0, hasDistance = 0;
1877 while (! (hasRate && hasPoints && hasAzimuths && hasRadius && hasDistance)) {
1878 TrIndication (tr, & line, & col);
1879 if (! TrReadIdent (tr, MAX_IDENT_LEN, ident))
1880 return (0);
1881 if (strcasecmp (ident, "rate") == 0) {
1882 if (hasRate) {
1883 TrErrorAt (tr, line, col, "Redefinition of 'rate'.\n");
1884 return (0);
1886 if (! TrReadOperator (tr, "="))
1887 return (0);
1888 if (! TrReadInt (tr, MIN_RATE, MAX_RATE, & intVal))
1889 return (0);
1890 hData -> mIrRate = intVal;
1891 hasRate = 1;
1892 } else if (strcasecmp (ident, "points") == 0) {
1893 if (hasPoints) {
1894 TrErrorAt (tr, line, col, "Redefinition of 'points'.\n");
1895 return (0);
1897 if (! TrReadOperator (tr, "="))
1898 return (0);
1899 TrIndication (tr, & line, & col);
1900 if (! TrReadInt (tr, MIN_POINTS, MAX_POINTS, & intVal))
1901 return (0);
1902 points = (size_t) intVal;
1903 if ((fftSize > 0) && (points > fftSize)) {
1904 TrErrorAt (tr, line, col, "Value exceeds the overriden FFT size.\n");
1905 return (0);
1907 if (points < truncSize) {
1908 TrErrorAt (tr, line, col, "Value is below the truncation size.\n");
1909 return (0);
1911 hData -> mIrPoints = points;
1912 hData -> mFftSize = fftSize;
1913 if (fftSize <= 0) {
1914 points = 1;
1915 while (points < (4 * hData -> mIrPoints))
1916 points <<= 1;
1917 hData -> mFftSize = points;
1918 hData -> mIrSize = 1 + (points / 2);
1919 } else {
1920 hData -> mFftSize = fftSize;
1921 hData -> mIrSize = 1 + (fftSize / 2);
1922 if (points > hData -> mIrSize)
1923 hData -> mIrSize = points;
1925 hasPoints = 1;
1926 } else if (strcasecmp (ident, "azimuths") == 0) {
1927 if (hasAzimuths) {
1928 TrErrorAt (tr, line, col, "Redefinition of 'azimuths'.\n");
1929 return (0);
1931 if (! TrReadOperator (tr, "="))
1932 return (0);
1933 hData -> mIrCount = 0;
1934 hData -> mEvCount = 0;
1935 hData -> mEvOffset [0] = 0;
1936 for (;;) {
1937 if (! TrReadInt (tr, MIN_AZ_COUNT, MAX_AZ_COUNT, & intVal))
1938 return (0);
1939 hData -> mAzCount [hData -> mEvCount] = intVal;
1940 hData -> mIrCount += intVal;
1941 hData -> mEvCount ++;
1942 if (! TrIsOperator (tr, ","))
1943 break;
1944 if (hData -> mEvCount >= MAX_EV_COUNT) {
1945 TrError (tr, "Exceeded the maximum of %d elevations.\n", MAX_EV_COUNT);
1946 return (0);
1948 hData -> mEvOffset [hData -> mEvCount] = hData -> mEvOffset [hData -> mEvCount - 1] + intVal;
1949 TrReadOperator (tr, ",");
1951 if (hData -> mEvCount < MIN_EV_COUNT) {
1952 TrErrorAt (tr, line, col, "Did not reach the minimum of %d azimuth counts.\n", MIN_EV_COUNT);
1953 return (0);
1955 hasAzimuths = 1;
1956 } else if (strcasecmp (ident, "radius") == 0) {
1957 if (hasRadius) {
1958 TrErrorAt (tr, line, col, "Redefinition of 'radius'.\n");
1959 return (0);
1961 if (! TrReadOperator (tr, "="))
1962 return (0);
1963 if (! TrReadFloat (tr, MIN_RADIUS, MAX_RADIUS, & fpVal))
1964 return (0);
1965 hData -> mRadius = fpVal;
1966 hasRadius = 1;
1967 } else if (strcasecmp (ident, "distance") == 0) {
1968 if (hasDistance) {
1969 TrErrorAt (tr, line, col, "Redefinition of 'distance'.\n");
1970 return (0);
1972 if (! TrReadOperator (tr, "="))
1973 return (0);
1974 if (! TrReadFloat (tr, MIN_DISTANCE, MAX_DISTANCE, & fpVal))
1975 return (0);
1976 hData -> mDistance = fpVal;
1977 hasDistance = 1;
1978 } else {
1979 TrErrorAt (tr, line, col, "Expected a metric name.\n");
1980 return (0);
1982 TrSkipWhitespace (tr);
1984 return (1);
1987 // Parse an index pair from the data set definition.
1988 static int ReadIndexPair (TokenReaderT * tr, const HrirDataT * hData, uint * ei, uint * ai) {
1989 int intVal;
1991 if (! TrReadInt (tr, 0, hData -> mEvCount, & intVal))
1992 return (0);
1993 (* ei) = (uint) intVal;
1994 if (! TrReadOperator (tr, ","))
1995 return (0);
1996 if (! TrReadInt (tr, 0, hData -> mAzCount [(* ei)], & intVal))
1997 return (0);
1998 (* ai) = (uint) intVal;
1999 return (1);
2002 // Match the source format from a given identifier.
2003 static SourceFormatT MatchSourceFormat (const char * ident) {
2004 if (strcasecmp (ident, "wave") == 0)
2005 return (SF_WAVE);
2006 else if (strcasecmp (ident, "bin_le") == 0)
2007 return (SF_BIN_LE);
2008 else if (strcasecmp (ident, "bin_be") == 0)
2009 return (SF_BIN_BE);
2010 else if (strcasecmp (ident, "ascii") == 0)
2011 return (SF_ASCII);
2012 return (SF_NONE);
2015 // Match the source element type from a given identifier.
2016 static ElementTypeT MatchElementType (const char * ident) {
2017 if (strcasecmp (ident, "int") == 0)
2018 return (ET_INT);
2019 else if (strcasecmp (ident, "fp") == 0)
2020 return (ET_FP);
2021 return (ET_NONE);
2024 // Parse and validate a source reference from the data set definition.
2025 static int ReadSourceRef (TokenReaderT * tr, SourceRefT * src) {
2026 uint line, col;
2027 char ident [MAX_IDENT_LEN + 1];
2028 int intVal;
2030 TrIndication (tr, & line, & col);
2031 if (! TrReadIdent (tr, MAX_IDENT_LEN, ident))
2032 return (0);
2033 src -> mFormat = MatchSourceFormat (ident);
2034 if (src -> mFormat == SF_NONE) {
2035 TrErrorAt (tr, line, col, "Expected a source format.\n");
2036 return (0);
2038 if (! TrReadOperator (tr, "("))
2039 return (0);
2040 if (src -> mFormat == SF_WAVE) {
2041 if (! TrReadInt (tr, 0, MAX_WAVE_CHANNELS, & intVal))
2042 return (0);
2043 src -> mType = ET_NONE;
2044 src -> mSize = 0;
2045 src -> mBits = 0;
2046 src -> mChannel = (uint) intVal;
2047 src -> mSkip = 0;
2048 } else {
2049 TrIndication (tr, & line, & col);
2050 if (! TrReadIdent (tr, MAX_IDENT_LEN, ident))
2051 return (0);
2052 src -> mType = MatchElementType (ident);
2053 if (src -> mType == ET_NONE) {
2054 TrErrorAt (tr, line, col, "Expected a source element type.\n");
2055 return (0);
2057 if ((src -> mFormat == SF_BIN_LE) || (src -> mFormat == SF_BIN_BE)) {
2058 if (! TrReadOperator (tr, ","))
2059 return (0);
2060 if (src -> mType == ET_INT) {
2061 if (! TrReadInt (tr, MIN_BIN_SIZE, MAX_BIN_SIZE, & intVal))
2062 return (0);
2063 src -> mSize = intVal;
2064 if (TrIsOperator (tr, ",")) {
2065 TrReadOperator (tr, ",");
2066 TrIndication (tr, & line, & col);
2067 if (! TrReadInt (tr, 0x80000000, 0x7FFFFFFF, & intVal))
2068 return (0);
2069 if ((abs (intVal) < MIN_BIN_BITS) || ((uint)abs(intVal) > (8 * src -> mSize))) {
2070 TrErrorAt (tr, line, col, "Expected a value of (+/-) %d to %d.\n", MIN_BIN_BITS, 8 * src -> mSize);
2071 return (0);
2073 src -> mBits = intVal;
2074 } else {
2075 src -> mBits = 8 * src -> mSize;
2077 } else {
2078 TrIndication (tr, & line, & col);
2079 if (! TrReadInt (tr, 0x80000000, 0x7FFFFFFF, & intVal))
2080 return (0);
2081 if ((intVal != 4) && (intVal != 8)) {
2082 TrErrorAt (tr, line, col, "Expected a value of 4 or 8.\n");
2083 return (0);
2085 src -> mSize = (uint) intVal;
2086 src -> mBits = 0;
2088 } else if ((src -> mFormat == SF_ASCII) && (src -> mType == ET_INT)) {
2089 if (! TrReadOperator (tr, ","))
2090 return (0);
2091 if (! TrReadInt (tr, MIN_ASCII_BITS, MAX_ASCII_BITS, & intVal))
2092 return (0);
2093 src -> mSize = 0;
2094 src -> mBits = intVal;
2095 } else {
2096 src -> mSize = 0;
2097 src -> mBits = 0;
2099 if (TrIsOperator (tr, ";")) {
2100 TrReadOperator (tr, ";");
2101 if (! TrReadInt (tr, 0, 0x7FFFFFFF, & intVal))
2102 return (0);
2103 src -> mSkip = (uint) intVal;
2104 } else {
2105 src -> mSkip = 0;
2108 if (! TrReadOperator (tr, ")"))
2109 return (0);
2110 if (TrIsOperator (tr, "@")) {
2111 TrReadOperator (tr, "@");
2112 if (! TrReadInt (tr, 0, 0x7FFFFFFF, & intVal))
2113 return (0);
2114 src -> mOffset = (uint) intVal;
2115 } else {
2116 src -> mOffset = 0;
2118 if (! TrReadOperator (tr, ":"))
2119 return (0);
2120 if (! TrReadString (tr, MAX_PATH_LEN, src -> mPath))
2121 return (0);
2122 return (1);
2125 // Process the list of sources in the data set definition.
2126 static int ProcessSources (TokenReaderT * tr, HrirDataT * hData) {
2127 uint * setCount = NULL, * setFlag = NULL;
2128 double * hrir = NULL;
2129 uint line, col, ei, ai;
2130 SourceRefT src;
2131 double factor;
2133 setCount = (uint *) calloc (hData -> mEvCount, sizeof (uint));
2134 setFlag = (uint *) calloc (hData -> mIrCount, sizeof (uint));
2135 hrir = CreateArray (hData -> mIrPoints);
2136 while (TrIsOperator (tr, "[")) {
2137 TrIndication (tr, & line, & col);
2138 TrReadOperator (tr, "[");
2139 if (ReadIndexPair (tr, hData, & ei, & ai)) {
2140 if (TrReadOperator (tr, "]")) {
2141 if (! setFlag [hData -> mEvOffset [ei] + ai]) {
2142 if (TrReadOperator (tr, "=")) {
2143 factor = 1.0;
2144 for (;;) {
2145 if (ReadSourceRef (tr, & src)) {
2146 if (LoadSource (& src, hData -> mIrRate, hData -> mIrPoints, hrir)) {
2147 AverageHrirMagnitude (hrir, 1.0 / factor, ei, ai, hData);
2148 factor += 1.0;
2149 if (! TrIsOperator (tr, "+"))
2150 break;
2151 TrReadOperator (tr, "+");
2152 continue;
2155 DestroyArray (hrir);
2156 free (setFlag);
2157 free (setCount);
2158 return (0);
2160 setFlag [hData -> mEvOffset [ei] + ai] = 1;
2161 setCount [ei] ++;
2162 continue;
2164 } else {
2165 TrErrorAt (tr, line, col, "Redefinition of source.\n");
2169 DestroyArray (hrir);
2170 free (setFlag);
2171 free (setCount);
2172 return (0);
2174 ei = 0;
2175 while ((ei < hData -> mEvCount) && (setCount [ei] < 1))
2176 ei ++;
2177 if (ei < hData -> mEvCount) {
2178 hData -> mEvStart = ei;
2179 while ((ei < hData -> mEvCount) && (setCount [ei] == hData -> mAzCount [ei]))
2180 ei ++;
2181 if (ei >= hData -> mEvCount) {
2182 if (! TrLoad (tr)) {
2183 DestroyArray (hrir);
2184 free (setFlag);
2185 free (setCount);
2186 return (1);
2187 } else {
2188 TrError (tr, "Errant data at end of source list.\n");
2190 } else {
2191 TrError (tr, "Missing sources for elevation index %d.\n", ei);
2193 } else {
2194 TrError (tr, "Missing source references.\n");
2196 DestroyArray (hrir);
2197 free (setFlag);
2198 free (setCount);
2199 return (0);
2202 /* Parse the data set definition and process the source data, storing the
2203 * resulting data set as desired. If the input name is NULL it will read
2204 * from standard input.
2206 static int ProcessDefinition (const char * inName, const size_t fftSize, const int equalize, const int surface, const double limit, const size_t truncSize, const OutputFormatT outFormat, const char * outName) {
2207 FILE * fp = NULL;
2208 TokenReaderT tr;
2209 HrirDataT hData;
2210 double * dfa = NULL;
2211 char rateStr [8 + 1], expName [MAX_PATH_LEN];
2213 hData.mIrRate = 0;
2214 hData.mIrPoints = 0;
2215 hData.mFftSize = 0;
2216 hData.mIrSize = 0;
2217 hData.mIrCount = 0;
2218 hData.mEvCount = 0;
2219 hData.mRadius = 0;
2220 hData.mDistance = 0;
2222 fprintf (stdout, "Reading HRIR definition...\n");
2223 if (inName != NULL) {
2224 fp = fopen (inName, "r");
2225 if (fp == NULL) {
2226 fprintf (stderr, "Error: Could not open definition file '%s'\n", inName);
2227 return (0);
2229 TrSetup (fp, inName, & tr);
2230 } else {
2231 fp = stdin;
2232 TrSetup (fp, "<stdin>", & tr);
2234 if (! ProcessMetrics (& tr, fftSize, truncSize, & hData)) {
2235 if (inName != NULL)
2236 fclose (fp);
2237 return (0);
2239 hData . mHrirs = CreateArray (hData . mIrCount * hData . mIrSize);
2240 hData . mHrtds = CreateArray (hData . mIrCount);
2241 if (! ProcessSources (& tr, & hData)) {
2242 DestroyArray (hData . mHrtds);
2243 DestroyArray (hData . mHrirs);
2244 if (inName != NULL)
2245 fclose (fp);
2246 return (0);
2248 if (inName != NULL)
2249 fclose (fp);
2250 if (equalize) {
2251 dfa = CreateArray (1 + (hData . mFftSize / 2));
2252 fprintf (stdout, "Calculating diffuse-field average...\n");
2253 CalculateDiffuseFieldAverage (& hData, surface, limit, dfa);
2254 fprintf (stdout, "Performing diffuse-field equalization...\n");
2255 DiffuseFieldEqualize (dfa, & hData);
2256 DestroyArray (dfa);
2258 fprintf (stdout, "Performing minimum phase reconstruction...\n");
2259 ReconstructHrirs (& hData);
2260 fprintf (stdout, "Truncating minimum-phase HRIRs...\n");
2261 hData . mIrPoints = truncSize;
2262 fprintf (stdout, "Synthesizing missing elevations...\n");
2263 SynthesizeHrirs (& hData);
2264 fprintf (stdout, "Normalizing final HRIRs...\n");
2265 NormalizeHrirs (& hData);
2266 fprintf (stdout, "Calculating impulse delays...\n");
2267 CalculateHrtds (& hData);
2268 snprintf (rateStr, 8, "%u", hData . mIrRate);
2269 StrSubst (outName, "%r", rateStr, MAX_PATH_LEN, expName);
2270 switch (outFormat) {
2271 case OF_MHR :
2272 fprintf (stdout, "Creating MHR data set file...\n");
2273 if (! StoreMhr (& hData, expName))
2274 return (0);
2275 break;
2276 case OF_TABLE :
2277 fprintf (stderr, "Creating OpenAL Soft table file...\n");
2278 if (! StoreTable (& hData, expName))
2279 return (0);
2280 break;
2281 default :
2282 break;
2284 DestroyArray (hData . mHrtds);
2285 DestroyArray (hData . mHrirs);
2286 return (1);
2289 // Standard command line dispatch.
2290 int main (const int argc, const char * argv []) {
2291 const char * inName = NULL, * outName = NULL;
2292 OutputFormatT outFormat;
2293 int argi;
2294 size_t fftSize;
2295 int equalize, surface;
2296 double limit;
2297 size_t truncSize;
2298 char * end = NULL;
2300 if (argc < 2) {
2301 fprintf (stderr, "Error: No command specified. See '%s -h' for help.\n", argv [0]);
2302 return (-1);
2304 if ((strcmp (argv [1], "--help") == 0) || (strcmp (argv [1], "-h") == 0)) {
2305 fprintf (stdout, "HRTF Processing and Composition Utility\n\n");
2306 fprintf (stdout, "Usage: %s <command> [<option>...]\n\n", argv [0]);
2307 fprintf (stdout, "Commands:\n");
2308 fprintf (stdout, " -m, --make-mhr Makes an OpenAL Soft compatible HRTF data set.\n");
2309 fprintf (stdout, " Defaults output to: ./oalsoft_hrtf_%%r.mhr\n");
2310 fprintf (stdout, " -t, --make-tab Makes the built-in table used when compiling OpenAL Soft.\n");
2311 fprintf (stdout, " Defaults output to: ./hrtf_tables.inc\n");
2312 fprintf (stdout, " -h, --help Displays this help information.\n\n");
2313 fprintf (stdout, "Options:\n");
2314 fprintf (stdout, " -f=<points> Override the FFT window size (defaults to the first power-\n");
2315 fprintf (stdout, " of-two that fits four times the number of HRIR points).\n");
2316 fprintf (stdout, " -e={on|off} Toggle diffuse-field equalization (default: %s).\n", (DEFAULT_EQUALIZE ? "on" : "off"));
2317 fprintf (stdout, " -s={on|off} Toggle surface-weighted diffuse-field average (default: %s).\n", (DEFAULT_SURFACE ? "on" : "off"));
2318 fprintf (stdout, " -l={<dB>|none} Specify a limit to the magnitude range of the diffuse-field\n");
2319 fprintf (stdout, " average (default: %.2f).\n", DEFAULT_LIMIT);
2320 fprintf (stdout, " -w=<points> Specify the size of the truncation window that's applied\n");
2321 fprintf (stdout, " after minimum-phase reconstruction (default: %d).\n", DEFAULT_TRUNCSIZE);
2322 fprintf (stdout, " -i=<filename> Specify an HRIR definition file to use (defaults to stdin).\n");
2323 fprintf (stdout, " -o=<filename> Specify an output file. Overrides command-selected default.\n");
2324 fprintf (stdout, " Use of '%%r' will be substituted with the data set sample rate.\n");
2325 return (0);
2327 if ((strcmp (argv [1], "--make-mhr") == 0) || (strcmp (argv [1], "-m") == 0)) {
2328 if (argc > 3)
2329 outName = argv [3];
2330 else
2331 outName = "./oalsoft_hrtf_%r.mhr";
2332 outFormat = OF_MHR;
2333 } else if ((strcmp (argv [1], "--make-tab") == 0) || (strcmp (argv [1], "-t") == 0)) {
2334 if (argc > 3)
2335 outName = argv [3];
2336 else
2337 outName = "./hrtf_tables.inc";
2338 outFormat = OF_TABLE;
2339 } else {
2340 fprintf (stderr, "Error: Invalid command '%s'.\n", argv [1]);
2341 return (-1);
2343 argi = 2;
2344 fftSize = 0;
2345 equalize = DEFAULT_EQUALIZE;
2346 surface = DEFAULT_SURFACE;
2347 limit = DEFAULT_LIMIT;
2348 truncSize = DEFAULT_TRUNCSIZE;
2349 while (argi < argc) {
2350 if (strncmp (argv [argi], "-f=", 3) == 0) {
2351 fftSize = strtoul (& argv [argi] [3], & end, 10);
2352 if ((end [0] != '\0') || (fftSize & (fftSize - 1)) || (fftSize < MIN_FFTSIZE) || (fftSize > MAX_FFTSIZE)) {
2353 fprintf (stderr, "Error: Expected a power-of-two value from %d to %d for '-f'.\n", MIN_FFTSIZE, MAX_FFTSIZE);
2354 return (-1);
2356 } else if (strncmp (argv [argi], "-e=", 3) == 0) {
2357 if (strcmp (& argv [argi] [3], "on") == 0) {
2358 equalize = 1;
2359 } else if (strcmp (& argv [argi] [3], "off") == 0) {
2360 equalize = 0;
2361 } else {
2362 fprintf (stderr, "Error: Expected 'on' or 'off' for '-e'.\n");
2363 return (-1);
2365 } else if (strncmp (argv [argi], "-s=", 3) == 0) {
2366 if (strcmp (& argv [argi] [3], "on") == 0) {
2367 surface = 1;
2368 } else if (strcmp (& argv [argi] [3], "off") == 0) {
2369 surface = 0;
2370 } else {
2371 fprintf (stderr, "Error: Expected 'on' or 'off' for '-s'.\n");
2372 return (-1);
2374 } else if (strncmp (argv [argi], "-l=", 3) == 0) {
2375 if (strcmp (& argv [argi] [3], "none") == 0) {
2376 limit = 0.0;
2377 } else {
2378 limit = strtod (& argv [argi] [3], & end);
2379 if ((end [0] != '\0') || (limit < MIN_LIMIT) || (limit > MAX_LIMIT)) {
2380 fprintf (stderr, "Error: Expected 'none' or a value from %.2f to %.2f for '-l'.\n", MIN_LIMIT, MAX_LIMIT);
2381 return (-1);
2384 } else if (strncmp (argv [argi], "-w=", 3) == 0) {
2385 truncSize = strtoul (& argv [argi] [3], & end, 10);
2386 if ((end [0] != '\0') || (truncSize < MIN_TRUNCSIZE) || (truncSize > MAX_TRUNCSIZE) || (truncSize % MOD_TRUNCSIZE)) {
2387 fprintf (stderr, "Error: Expected a value from %d to %d in multiples of %d for '-w'.\n", MIN_TRUNCSIZE, MAX_TRUNCSIZE, MOD_TRUNCSIZE);
2388 return (-1);
2390 } else if (strncmp (argv [argi], "-i=", 3) == 0) {
2391 inName = & argv [argi] [3];
2392 } else if (strncmp (argv [argi], "-o=", 3) == 0) {
2393 outName = & argv [argi] [3];
2394 } else {
2395 fprintf (stderr, "Error: Invalid option '%s'.\n", argv [argi]);
2396 return (-1);
2398 argi ++;
2400 if (! ProcessDefinition (inName, fftSize, equalize, surface, limit, truncSize, outFormat, outName))
2401 return (-1);
2402 fprintf (stdout, "Operation completed.\n");
2403 return (0);