Simplify setting a fontsound link
[openal-soft.git] / utils / makehrtf.c
blob7c836b3385a4d90d4b795bea2fcf67549377141d
1 /*
2 * HRTF utility for producing and demonstrating the process of creating an
3 * OpenAL Soft compatible HRIR data set.
5 * Copyright (C) 2011-2014 Christopher Fitzgerald
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 * Or visit: http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
23 * --------------------------------------------------------------------------
25 * A big thanks goes out to all those whose work done in the field of
26 * binaural sound synthesis using measured HRTFs makes this utility and the
27 * OpenAL Soft implementation possible.
29 * The algorithm for diffuse-field equalization was adapted from the work
30 * done by Rio Emmanuel and Larcher Veronique of IRCAM and Bill Gardner of
31 * MIT Media Laboratory. It operates as follows:
33 * 1. Take the FFT of each HRIR and only keep the magnitude responses.
34 * 2. Calculate the diffuse-field power-average of all HRIRs weighted by
35 * their contribution to the total surface area covered by their
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
52 * The formulae for calculating the Kaiser window metrics are from the
53 * the textbook:
55 * Discrete-Time Signal Processing
56 * Alan V. Oppenheim and Ronald W. Schafer
57 * Prentice-Hall Signal Processing Series
58 * 1999
61 #include "config.h"
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <stdarg.h>
66 #include <string.h>
67 #include <ctype.h>
68 #include <math.h>
69 #ifdef HAVE_STRINGS_H
70 #include <strings.h>
71 #endif
73 // Rely (if naively) on OpenAL's header for the types used for serialization.
74 #include "AL/al.h"
75 #include "AL/alext.h"
77 #ifndef M_PI
78 #define M_PI (3.14159265358979323846)
79 #endif
81 #ifndef HUGE_VAL
82 #define HUGE_VAL (1.0 / 0.0)
83 #endif
85 // The epsilon used to maintain signal stability.
86 #define EPSILON (1e-15)
88 // Constants for accessing the token reader's ring buffer.
89 #define TR_RING_BITS (16)
90 #define TR_RING_SIZE (1 << TR_RING_BITS)
91 #define TR_RING_MASK (TR_RING_SIZE - 1)
93 // The token reader's load interval in bytes.
94 #define TR_LOAD_SIZE (TR_RING_SIZE >> 2)
96 // The maximum identifier length used when processing the data set
97 // definition.
98 #define MAX_IDENT_LEN (16)
100 // The maximum path length used when processing filenames.
101 #define MAX_PATH_LEN (256)
103 // The limits for the sample 'rate' metric in the data set definition and for
104 // resampling.
105 #define MIN_RATE (32000)
106 #define MAX_RATE (96000)
108 // The limits for the HRIR 'points' metric in the data set definition.
109 #define MIN_POINTS (16)
110 #define MAX_POINTS (8192)
112 // The limits to the number of 'azimuths' listed in the data set definition.
113 #define MIN_EV_COUNT (5)
114 #define MAX_EV_COUNT (128)
116 // The limits for each of the 'azimuths' listed in the data set definition.
117 #define MIN_AZ_COUNT (1)
118 #define MAX_AZ_COUNT (128)
120 // The limits for the listener's head 'radius' in the data set definition.
121 #define MIN_RADIUS (0.05)
122 #define MAX_RADIUS (0.15)
124 // The limits for the 'distance' from source to listener in the definition
125 // file.
126 #define MIN_DISTANCE (0.5)
127 #define MAX_DISTANCE (2.5)
129 // The maximum number of channels that can be addressed for a WAVE file
130 // source listed in the data set definition.
131 #define MAX_WAVE_CHANNELS (65535)
133 // The limits to the byte size for a binary source listed in the definition
134 // file.
135 #define MIN_BIN_SIZE (2)
136 #define MAX_BIN_SIZE (4)
138 // The minimum number of significant bits for binary sources listed in the
139 // data set definition. The maximum is calculated from the byte size.
140 #define MIN_BIN_BITS (16)
142 // The limits to the number of significant bits for an ASCII source listed in
143 // the data set definition.
144 #define MIN_ASCII_BITS (16)
145 #define MAX_ASCII_BITS (32)
147 // The limits to the FFT window size override on the command line.
148 #define MIN_FFTSIZE (512)
149 #define MAX_FFTSIZE (16384)
151 // The limits to the equalization range limit on the command line.
152 #define MIN_LIMIT (2.0)
153 #define MAX_LIMIT (120.0)
155 // The limits to the truncation window size on the command line.
156 #define MIN_TRUNCSIZE (8)
157 #define MAX_TRUNCSIZE (128)
159 // The limits to the custom head radius on the command line.
160 #define MIN_CUSTOM_RADIUS (0.05)
161 #define MAX_CUSTOM_RADIUS (0.15)
163 // The truncation window size must be a multiple of the below value to allow
164 // for vectorized convolution.
165 #define MOD_TRUNCSIZE (8)
167 // The defaults for the command line options.
168 #define DEFAULT_EQUALIZE (1)
169 #define DEFAULT_SURFACE (1)
170 #define DEFAULT_LIMIT (24.0)
171 #define DEFAULT_TRUNCSIZE (32)
172 #define DEFAULT_HEAD_MODEL (HM_DATASET)
173 #define DEFAULT_CUSTOM_RADIUS (0.0)
175 // The four-character-codes for RIFF/RIFX WAVE file chunks.
176 #define FOURCC_RIFF (0x46464952) // 'RIFF'
177 #define FOURCC_RIFX (0x58464952) // 'RIFX'
178 #define FOURCC_WAVE (0x45564157) // 'WAVE'
179 #define FOURCC_FMT (0x20746D66) // 'fmt '
180 #define FOURCC_DATA (0x61746164) // 'data'
181 #define FOURCC_LIST (0x5453494C) // 'LIST'
182 #define FOURCC_WAVL (0x6C766177) // 'wavl'
183 #define FOURCC_SLNT (0x746E6C73) // 'slnt'
185 // The supported wave formats.
186 #define WAVE_FORMAT_PCM (0x0001)
187 #define WAVE_FORMAT_IEEE_FLOAT (0x0003)
188 #define WAVE_FORMAT_EXTENSIBLE (0xFFFE)
190 // The maximum propagation delay value supported by OpenAL Soft.
191 #define MAX_HRTD (63.0)
193 // The OpenAL Soft HRTF format marker. It stands for minimum-phase head
194 // response protocol 01.
195 #define MHR_FORMAT ("MinPHR01")
197 // Byte order for the serialization routines.
198 enum ByteOrderT {
199 BO_NONE = 0,
200 BO_LITTLE ,
201 BO_BIG
204 // Source format for the references listed in the data set definition.
205 enum SourceFormatT {
206 SF_NONE = 0,
207 SF_WAVE , // RIFF/RIFX WAVE file.
208 SF_BIN_LE , // Little-endian binary file.
209 SF_BIN_BE , // Big-endian binary file.
210 SF_ASCII // ASCII text file.
213 // Element types for the references listed in the data set definition.
214 enum ElementTypeT {
215 ET_NONE = 0,
216 ET_INT , // Integer elements.
217 ET_FP // Floating-point elements.
220 // Head model used for calculating the impulse delays.
221 enum HeadModelT {
222 HM_NONE = 0,
223 HM_DATASET , // Measure the onset from the dataset.
224 HM_SPHERE // Calculate the onset using a spherical head model.
227 // Desired output format from the command line.
228 enum OutputFormatT {
229 OF_NONE = 0,
230 OF_MHR , // OpenAL Soft MHR data set file.
231 OF_TABLE // OpenAL Soft built-in table file (used when compiling).
234 // Unsigned integer type.
235 typedef unsigned int uint;
237 // Serialization types. The trailing digit indicates the number of bits.
238 typedef ALubyte uint8;
240 typedef ALint int32;
241 typedef ALuint uint32;
242 typedef ALuint64SOFT uint64;
244 typedef enum ByteOrderT ByteOrderT;
245 typedef enum SourceFormatT SourceFormatT;
246 typedef enum ElementTypeT ElementTypeT;
247 typedef enum HeadModelT HeadModelT;
248 typedef enum OutputFormatT OutputFormatT;
250 typedef struct TokenReaderT TokenReaderT;
251 typedef struct SourceRefT SourceRefT;
252 typedef struct HrirDataT HrirDataT;
253 typedef struct ResamplerT ResamplerT;
255 // Token reader state for parsing the data set definition.
256 struct TokenReaderT {
257 FILE * mFile;
258 const char * mName;
259 uint mLine,
260 mColumn;
261 char mRing [TR_RING_SIZE];
262 size_t mIn,
263 mOut;
266 // Source reference state used when loading sources.
267 struct SourceRefT {
268 SourceFormatT mFormat;
269 ElementTypeT mType;
270 uint mSize;
271 int mBits;
272 uint mChannel,
273 mSkip,
274 mOffset;
275 char mPath [MAX_PATH_LEN + 1];
278 // The HRIR metrics and data set used when loading, processing, and storing
279 // the resulting HRTF.
280 struct HrirDataT {
281 uint mIrRate,
282 mIrCount,
283 mIrSize,
284 mIrPoints,
285 mFftSize,
286 mEvCount,
287 mEvStart,
288 mAzCount [MAX_EV_COUNT],
289 mEvOffset [MAX_EV_COUNT];
290 double mRadius,
291 mDistance,
292 * mHrirs,
293 * mHrtds,
294 mMaxHrtd;
297 // The resampler metrics and FIR filter.
298 struct ResamplerT {
299 uint mP,
303 double * mF;
306 /* Token reader routines for parsing text files. Whitespace is not
307 * significant. It can process tokens as identifiers, numbers (integer and
308 * floating-point), strings, and operators. Strings must be encapsulated by
309 * double-quotes and cannot span multiple lines.
312 // Setup the reader on the given file. The filename can be NULL if no error
313 // output is desired.
314 static void TrSetup (FILE * fp, const char * filename, TokenReaderT * tr) {
315 const char * name = NULL;
316 char ch;
318 tr -> mFile = fp;
319 name = filename;
320 // If a filename was given, store a pointer to the base name.
321 if (filename != NULL) {
322 while ((ch = (* filename)) != '\0') {
323 if ((ch == '/') || (ch == '\\'))
324 name = filename + 1;
325 filename ++;
328 tr -> mName = name;
329 tr -> mLine = 1;
330 tr -> mColumn = 1;
331 tr -> mIn = 0;
332 tr -> mOut = 0;
335 // Prime the reader's ring buffer, and return a result indicating that there
336 // is text to process.
337 static int TrLoad (TokenReaderT * tr) {
338 size_t toLoad, in, count;
340 toLoad = TR_RING_SIZE - (tr -> mIn - tr -> mOut);
341 if ((toLoad >= TR_LOAD_SIZE) && (! feof (tr -> mFile))) {
342 // Load TR_LOAD_SIZE (or less if at the end of the file) per read.
343 toLoad = TR_LOAD_SIZE;
344 in = tr -> mIn & TR_RING_MASK;
345 count = TR_RING_SIZE - in;
346 if (count < toLoad) {
347 tr -> mIn += fread (& tr -> mRing [in], 1, count, tr -> mFile);
348 tr -> mIn += fread (& tr -> mRing [0], 1, toLoad - count, tr -> mFile);
349 } else {
350 tr -> mIn += fread (& tr -> mRing [in], 1, toLoad, tr -> mFile);
352 if (tr -> mOut >= TR_RING_SIZE) {
353 tr -> mOut -= TR_RING_SIZE;
354 tr -> mIn -= TR_RING_SIZE;
357 if (tr -> mIn > tr -> mOut)
358 return (1);
359 return (0);
362 // Error display routine. Only displays when the base name is not NULL.
363 static void TrErrorVA (const TokenReaderT * tr, uint line, uint column, const char * format, va_list argPtr) {
364 if (tr -> mName != NULL) {
365 fprintf (stderr, "Error (%s:%u:%u): ", tr -> mName, line, column);
366 vfprintf (stderr, format, argPtr);
370 // Used to display an error at a saved line/column.
371 static void TrErrorAt (const TokenReaderT * tr, uint line, uint column, const char * format, ...) {
372 va_list argPtr;
374 va_start (argPtr, format);
375 TrErrorVA (tr, line, column, format, argPtr);
376 va_end (argPtr);
379 // Used to display an error at the current line/column.
380 static void TrError (const TokenReaderT * tr, const char * format, ...) {
381 va_list argPtr;
383 va_start (argPtr, format);
384 TrErrorVA (tr, tr -> mLine, tr -> mColumn, format, argPtr);
385 va_end (argPtr);
388 // Skips to the next line.
389 static void TrSkipLine (TokenReaderT * tr) {
390 char ch;
392 while (TrLoad (tr)) {
393 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
394 tr -> mOut ++;
395 if (ch == '\n') {
396 tr -> mLine ++;
397 tr -> mColumn = 1;
398 break;
400 tr -> mColumn ++;
404 // Skips to the next token.
405 static int TrSkipWhitespace (TokenReaderT * tr) {
406 char ch;
408 while (TrLoad (tr)) {
409 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
410 if (isspace (ch)) {
411 tr -> mOut ++;
412 if (ch == '\n') {
413 tr -> mLine ++;
414 tr -> mColumn = 1;
415 } else {
416 tr -> mColumn ++;
418 } else if (ch == '#') {
419 TrSkipLine (tr);
420 } else {
421 return (1);
424 return (0);
427 // Get the line and/or column of the next token (or the end of input).
428 static void TrIndication (TokenReaderT * tr, uint * line, uint * column) {
429 TrSkipWhitespace (tr);
430 if (line != NULL)
431 (* line) = tr -> mLine;
432 if (column != NULL)
433 (* column) = tr -> mColumn;
436 // Checks to see if a token is the given operator. It does not display any
437 // errors and will not proceed to the next token.
438 static int TrIsOperator (TokenReaderT * tr, const char * op) {
439 size_t out, len;
440 char ch;
442 if (! TrSkipWhitespace (tr))
443 return (0);
444 out = tr -> mOut;
445 len = 0;
446 while ((op [len] != '\0') && (out < tr -> mIn)) {
447 ch = tr -> mRing [out & TR_RING_MASK];
448 if (ch != op [len])
449 break;
450 len ++;
451 out ++;
453 if (op [len] == '\0')
454 return (1);
455 return (0);
458 /* The TrRead*() routines obtain the value of a matching token type. They
459 * display type, form, and boundary errors and will proceed to the next
460 * token.
463 // Reads and validates an identifier token.
464 static int TrReadIdent (TokenReaderT * tr, const uint maxLen, char * ident) {
465 uint col, len;
466 char ch;
468 col = tr -> mColumn;
469 if (TrSkipWhitespace (tr)) {
470 col = tr -> mColumn;
471 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
472 if ((ch == '_') || isalpha (ch)) {
473 len = 0;
474 do {
475 if (len < maxLen)
476 ident [len] = ch;
477 len ++;
478 tr -> mOut ++;
479 if (! TrLoad (tr))
480 break;
481 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
482 } while ((ch == '_') || isdigit (ch) || isalpha (ch));
483 tr -> mColumn += len;
484 if (len > maxLen) {
485 TrErrorAt (tr, tr -> mLine, col, "Identifier is too long.\n");
486 return (0);
488 ident [len] = '\0';
489 return (1);
492 TrErrorAt (tr, tr -> mLine, col, "Expected an identifier.\n");
493 return (0);
496 // Reads and validates (including bounds) an integer token.
497 static int TrReadInt (TokenReaderT * tr, const int loBound, const int hiBound, int * value) {
498 uint col, digis, len;
499 char ch, temp [64 + 1];
501 col = tr -> mColumn;
502 if (TrSkipWhitespace (tr)) {
503 col = tr -> mColumn;
504 len = 0;
505 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
506 if ((ch == '+') || (ch == '-')) {
507 temp [len] = ch;
508 len ++;
509 tr -> mOut ++;
511 digis = 0;
512 while (TrLoad (tr)) {
513 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
514 if (! isdigit (ch))
515 break;
516 if (len < 64)
517 temp [len] = ch;
518 len ++;
519 digis ++;
520 tr -> mOut ++;
522 tr -> mColumn += len;
523 if ((digis > 0) && (ch != '.') && (! isalpha (ch))) {
524 if (len > 64) {
525 TrErrorAt (tr, tr -> mLine, col, "Integer is too long.");
526 return (0);
528 temp [len] = '\0';
529 (* value) = strtol (temp, NULL, 10);
530 if (((* value) < loBound) || ((* value) > hiBound)) {
531 TrErrorAt (tr, tr -> mLine, col, "Expected a value from %d to %d.\n", loBound, hiBound);
532 return (0);
534 return (1);
537 TrErrorAt (tr, tr -> mLine, col, "Expected an integer.\n");
538 return (0);
541 // Reads and validates (including bounds) a float token.
542 static int TrReadFloat (TokenReaderT * tr, const double loBound, const double hiBound, double * value) {
543 uint col, digis, len;
544 char ch, temp [64 + 1];
546 col = tr -> mColumn;
547 if (TrSkipWhitespace (tr)) {
548 col = tr -> mColumn;
549 len = 0;
550 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
551 if ((ch == '+') || (ch == '-')) {
552 temp [len] = ch;
553 len ++;
554 tr -> mOut ++;
556 digis = 0;
557 while (TrLoad (tr)) {
558 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
559 if (! isdigit (ch))
560 break;
561 if (len < 64)
562 temp [len] = ch;
563 len ++;
564 digis ++;
565 tr -> mOut ++;
567 if (ch == '.') {
568 if (len < 64)
569 temp [len] = ch;
570 len ++;
571 tr -> mOut ++;
573 while (TrLoad (tr)) {
574 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
575 if (! isdigit (ch))
576 break;
577 if (len < 64)
578 temp [len] = ch;
579 len ++;
580 digis ++;
581 tr -> mOut ++;
583 if (digis > 0) {
584 if ((ch == 'E') || (ch == 'e')) {
585 if (len < 64)
586 temp [len] = ch;
587 len ++;
588 digis = 0;
589 tr -> mOut ++;
590 if ((ch == '+') || (ch == '-')) {
591 if (len < 64)
592 temp [len] = ch;
593 len ++;
594 tr -> mOut ++;
596 while (TrLoad (tr)) {
597 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
598 if (! isdigit (ch))
599 break;
600 if (len < 64)
601 temp [len] = ch;
602 len ++;
603 digis ++;
604 tr -> mOut ++;
607 tr -> mColumn += len;
608 if ((digis > 0) && (ch != '.') && (! isalpha (ch))) {
609 if (len > 64) {
610 TrErrorAt (tr, tr -> mLine, col, "Float is too long.");
611 return (0);
613 temp [len] = '\0';
614 (* value) = strtod (temp, NULL);
615 if (((* value) < loBound) || ((* value) > hiBound)) {
616 TrErrorAt (tr, tr -> mLine, col, "Expected a value from %f to %f.\n", loBound, hiBound);
617 return (0);
619 return (1);
621 } else {
622 tr -> mColumn += len;
625 TrErrorAt (tr, tr -> mLine, col, "Expected a float.\n");
626 return (0);
629 // Reads and validates a string token.
630 static int TrReadString (TokenReaderT * tr, const uint maxLen, char * text) {
631 uint col, len;
632 char ch;
634 col = tr -> mColumn;
635 if (TrSkipWhitespace (tr)) {
636 col = tr -> mColumn;
637 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
638 if (ch == '\"') {
639 tr -> mOut ++;
640 len = 0;
641 while (TrLoad (tr)) {
642 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
643 tr -> mOut ++;
644 if (ch == '\"')
645 break;
646 if (ch == '\n') {
647 TrErrorAt (tr, tr -> mLine, col, "Unterminated string at end of line.\n");
648 return (0);
650 if (len < maxLen)
651 text [len] = ch;
652 len ++;
654 if (ch != '\"') {
655 tr -> mColumn += 1 + len;
656 TrErrorAt (tr, tr -> mLine, col, "Unterminated string at end of input.\n");
657 return (0);
659 tr -> mColumn += 2 + len;
660 if (len > maxLen) {
661 TrErrorAt (tr, tr -> mLine, col, "String is too long.\n");
662 return (0);
664 text [len] = '\0';
665 return (1);
668 TrErrorAt (tr, tr -> mLine, col, "Expected a string.\n");
669 return (0);
672 // Reads and validates the given operator.
673 static int TrReadOperator (TokenReaderT * tr, const char * op) {
674 uint col, len;
675 char ch;
677 col = tr -> mColumn;
678 if (TrSkipWhitespace (tr)) {
679 col = tr -> mColumn;
680 len = 0;
681 while ((op [len] != '\0') && TrLoad (tr)) {
682 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
683 if (ch != op [len])
684 break;
685 len ++;
686 tr -> mOut ++;
688 tr -> mColumn += len;
689 if (op [len] == '\0')
690 return (1);
692 TrErrorAt (tr, tr -> mLine, col, "Expected '%s' operator.\n", op);
693 return (0);
696 /* Performs a string substitution. Any case-insensitive occurrences of the
697 * pattern string are replaced with the replacement string. The result is
698 * truncated if necessary.
700 static int StrSubst (const char * in, const char * pat, const char * rep, const size_t maxLen, char * out) {
701 size_t inLen, patLen, repLen;
702 size_t si, di;
703 int truncated;
705 inLen = strlen (in);
706 patLen = strlen (pat);
707 repLen = strlen (rep);
708 si = 0;
709 di = 0;
710 truncated = 0;
711 while ((si < inLen) && (di < maxLen)) {
712 if (patLen <= (inLen - si)) {
713 if (strncasecmp (& in [si], pat, patLen) == 0) {
714 if (repLen > (maxLen - di)) {
715 repLen = maxLen - di;
716 truncated = 1;
718 strncpy (& out [di], rep, repLen);
719 si += patLen;
720 di += repLen;
723 out [di] = in [si];
724 si ++;
725 di ++;
727 if (si < inLen)
728 truncated = 1;
729 out [di] = '\0';
730 return (! truncated);
733 // Provide missing math routines for MSVC versions < 1800 (Visual Studio 2013).
734 #if defined(_MSC_VER) && _MSC_VER < 1800
735 static double round (double val) {
736 if (val < 0.0)
737 return (ceil (val - 0.5));
738 return (floor (val + 0.5));
741 static double fmin (double a, double b) {
742 return ((a < b) ? a : b);
745 static double fmax (double a, double b) {
746 return ((a > b) ? a : b);
748 #endif
750 // Simple clamp routine.
751 static double Clamp (const double val, const double lower, const double upper) {
752 return (fmin (fmax (val, lower), upper));
755 // Performs linear interpolation.
756 static double Lerp (const double a, const double b, const double f) {
757 return (a + (f * (b - a)));
760 // Performs a high-passed triangular probability density function dither from
761 // a double to an integer. It assumes the input sample is already scaled.
762 static int HpTpdfDither (const double in, int * hpHist) {
763 const double PRNG_SCALE = 1.0 / (RAND_MAX + 1.0);
764 int prn;
765 double out;
767 prn = rand ();
768 out = round (in + (PRNG_SCALE * (prn - (* hpHist))));
769 (* hpHist) = prn;
770 return ((int) out);
773 // Allocates an array of doubles.
774 static double *CreateArray(const size_t n)
776 double *a;
778 a = calloc(n, sizeof(double));
779 if(a == NULL)
781 fprintf(stderr, "Error: Out of memory.\n");
782 exit(-1);
784 return a;
787 // Frees an array of doubles.
788 static void DestroyArray(double *a)
789 { free(a); }
791 // Complex number routines. All outputs must be non-NULL.
793 // Magnitude/absolute value.
794 static double ComplexAbs (const double r, const double i) {
795 return (sqrt ((r * r) + (i * i)));
798 // Multiply.
799 static void ComplexMul (const double aR, const double aI, const double bR, const double bI, double * outR, double * outI) {
800 (* outR) = (aR * bR) - (aI * bI);
801 (* outI) = (aI * bR) + (aR * bI);
804 // Base-e exponent.
805 static void ComplexExp (const double inR, const double inI, double * outR, double * outI) {
806 double e;
808 e = exp (inR);
809 (* outR) = e * cos (inI);
810 (* outI) = e * sin (inI);
813 /* Fast Fourier transform routines. The number of points must be a power of
814 * two. In-place operation is possible only if both the real and imaginary
815 * parts are in-place together.
818 // Performs bit-reversal ordering.
819 static void FftArrange (const uint n, const double * inR, const double * inI, double * outR, double * outI) {
820 uint rk, k, m;
821 double tempR, tempI;
823 if ((inR == outR) && (inI == outI)) {
824 // Handle in-place arrangement.
825 rk = 0;
826 for (k = 0; k < n; k ++) {
827 if (rk > k) {
828 tempR = inR [rk];
829 tempI = inI [rk];
830 outR [rk] = inR [k];
831 outI [rk] = inI [k];
832 outR [k] = tempR;
833 outI [k] = tempI;
835 m = n;
836 while (rk & (m >>= 1))
837 rk &= ~m;
838 rk |= m;
840 } else {
841 // Handle copy arrangement.
842 rk = 0;
843 for (k = 0; k < n; k ++) {
844 outR [rk] = inR [k];
845 outI [rk] = inI [k];
846 m = n;
847 while (rk & (m >>= 1))
848 rk &= ~m;
849 rk |= m;
854 // Performs the summation.
855 static void FftSummation (const uint n, const double s, double * re, double * im) {
856 double pi;
857 uint m, m2;
858 double vR, vI, wR, wI;
859 uint i, k, mk;
860 double tR, tI;
862 pi = s * M_PI;
863 for (m = 1, m2 = 2; m < n; m <<= 1, m2 <<= 1) {
864 // v = Complex (-2.0 * sin (0.5 * pi / m) * sin (0.5 * pi / m), -sin (pi / m))
865 vR = sin (0.5 * pi / m);
866 vR = -2.0 * vR * vR;
867 vI = -sin (pi / m);
868 // w = Complex (1.0, 0.0)
869 wR = 1.0;
870 wI = 0.0;
871 for (i = 0; i < m; i ++) {
872 for (k = i; k < n; k += m2) {
873 mk = k + m;
874 // t = ComplexMul (w, out [km2])
875 tR = (wR * re [mk]) - (wI * im [mk]);
876 tI = (wR * im [mk]) + (wI * re [mk]);
877 // out [mk] = ComplexSub (out [k], t)
878 re [mk] = re [k] - tR;
879 im [mk] = im [k] - tI;
880 // out [k] = ComplexAdd (out [k], t)
881 re [k] += tR;
882 im [k] += tI;
884 // t = ComplexMul (v, w)
885 tR = (vR * wR) - (vI * wI);
886 tI = (vR * wI) + (vI * wR);
887 // w = ComplexAdd (w, t)
888 wR += tR;
889 wI += tI;
894 // Performs a forward FFT.
895 static void FftForward (const uint n, const double * inR, const double * inI, double * outR, double * outI) {
896 FftArrange (n, inR, inI, outR, outI);
897 FftSummation (n, 1.0, outR, outI);
900 // Performs an inverse FFT.
901 static void FftInverse (const uint n, const double * inR, const double * inI, double * outR, double * outI) {
902 double f;
903 uint i;
905 FftArrange (n, inR, inI, outR, outI);
906 FftSummation (n, -1.0, outR, outI);
907 f = 1.0 / n;
908 for (i = 0; i < n; i ++) {
909 outR [i] *= f;
910 outI [i] *= f;
914 /* Calculate the complex helical sequence (or discrete-time analytical
915 * signal) of the given input using the Hilbert transform. Given the
916 * negative natural logarithm of a signal's magnitude response, the imaginary
917 * components can be used as the angles for minimum-phase reconstruction.
919 static void Hilbert (const uint n, const double * in, double * outR, double * outI) {
920 uint i;
922 if (in == outR) {
923 // Handle in-place operation.
924 for (i = 0; i < n; i ++)
925 outI [i] = 0.0;
926 } else {
927 // Handle copy operation.
928 for (i = 0; i < n; i ++) {
929 outR [i] = in [i];
930 outI [i] = 0.0;
933 FftForward (n, outR, outI, outR, outI);
934 /* Currently the Fourier routines operate only on point counts that are
935 * powers of two. If that changes and n is odd, the following conditional
936 * should be: i < (n + 1) / 2.
938 for (i = 1; i < (n / 2); i ++) {
939 outR [i] *= 2.0;
940 outI [i] *= 2.0;
942 // If n is odd, the following increment should be skipped.
943 i ++;
944 for (; i < n; i ++) {
945 outR [i] = 0.0;
946 outI [i] = 0.0;
948 FftInverse (n, outR, outI, outR, outI);
951 /* Calculate the magnitude response of the given input. This is used in
952 * place of phase decomposition, since the phase residuals are discarded for
953 * minimum phase reconstruction. The mirrored half of the response is also
954 * discarded.
956 static void MagnitudeResponse (const uint n, const double * inR, const double * inI, double * out) {
957 const uint m = 1 + (n / 2);
958 uint i;
960 for (i = 0; i < m; i ++)
961 out [i] = fmax (ComplexAbs (inR [i], inI [i]), EPSILON);
964 /* Apply a range limit (in dB) to the given magnitude response. This is used
965 * to adjust the effects of the diffuse-field average on the equalization
966 * process.
968 static void LimitMagnitudeResponse (const uint n, const double limit, const double * in, double * out) {
969 const uint m = 1 + (n / 2);
970 double halfLim;
971 uint i, lower, upper;
972 double ave;
974 halfLim = limit / 2.0;
975 // Convert the response to dB.
976 for (i = 0; i < m; i ++)
977 out [i] = 20.0 * log10 (in [i]);
978 // Use six octaves to calculate the average magnitude of the signal.
979 lower = ((uint) ceil (n / pow (2.0, 8.0))) - 1;
980 upper = ((uint) floor (n / pow (2.0, 2.0))) - 1;
981 ave = 0.0;
982 for (i = lower; i <= upper; i ++)
983 ave += out [i];
984 ave /= upper - lower + 1;
985 // Keep the response within range of the average magnitude.
986 for (i = 0; i < m; i ++)
987 out [i] = Clamp (out [i], ave - halfLim, ave + halfLim);
988 // Convert the response back to linear magnitude.
989 for (i = 0; i < m; i ++)
990 out [i] = pow (10.0, out [i] / 20.0);
993 /* Reconstructs the minimum-phase component for the given magnitude response
994 * of a signal. This is equivalent to phase recomposition, sans the missing
995 * residuals (which were discarded). The mirrored half of the response is
996 * reconstructed.
998 static void MinimumPhase (const uint n, const double * in, double * outR, double * outI) {
999 const uint m = 1 + (n / 2);
1000 double * mags = NULL;
1001 uint i;
1002 double aR, aI;
1004 mags = CreateArray (n);
1005 for (i = 0; i < m; i ++) {
1006 mags [i] = fmax (in [i], EPSILON);
1007 outR [i] = -log (mags [i]);
1009 for (; i < n; i ++) {
1010 mags [i] = mags [n - i];
1011 outR [i] = outR [n - i];
1013 Hilbert (n, outR, outR, outI);
1014 // Remove any DC offset the filter has.
1015 outR [0] = 0.0;
1016 outI [0] = 0.0;
1017 for (i = 1; i < n; i ++) {
1018 ComplexExp (0.0, outI [i], & aR, & aI);
1019 ComplexMul (mags [i], 0.0, aR, aI, & outR [i], & outI [i]);
1021 DestroyArray (mags);
1024 /* This is the normalized cardinal sine (sinc) function.
1026 * sinc(x) = { 1, x = 0
1027 * { sin(pi x) / (pi x), otherwise.
1029 static double Sinc (const double x) {
1030 if (fabs (x) < EPSILON)
1031 return (1.0);
1032 return (sin (M_PI * x) / (M_PI * x));
1035 /* The zero-order modified Bessel function of the first kind, used for the
1036 * Kaiser window.
1038 * I_0(x) = sum_{k=0}^inf (1 / k!)^2 (x / 2)^(2 k)
1039 * = sum_{k=0}^inf ((x / 2)^k / k!)^2
1041 static double BesselI_0 (const double x) {
1042 double term, sum, x2, y, last_sum;
1043 int k;
1045 // Start at k=1 since k=0 is trivial.
1046 term = 1.0;
1047 sum = 1.0;
1048 x2 = x / 2.0;
1049 k = 1;
1050 // Let the integration converge until the term of the sum is no longer
1051 // significant.
1052 do {
1053 y = x2 / k;
1054 k ++;
1055 last_sum = sum;
1056 term *= y * y;
1057 sum += term;
1058 } while (sum != last_sum);
1059 return (sum);
1062 /* Calculate a Kaiser window from the given beta value and a normalized k
1063 * [-1, 1].
1065 * w(k) = { I_0(B sqrt(1 - k^2)) / I_0(B), -1 <= k <= 1
1066 * { 0, elsewhere.
1068 * Where k can be calculated as:
1070 * k = i / l, where -l <= i <= l.
1072 * or:
1074 * k = 2 i / M - 1, where 0 <= i <= M.
1076 static double Kaiser (const double b, const double k) {
1077 double k2;
1079 k2 = Clamp (k, -1.0, 1.0);
1080 if ((k < -1.0) || (k > 1.0))
1081 return (0.0);
1082 k2 *= k2;
1083 return (BesselI_0 (b * sqrt (1.0 - k2)) / BesselI_0 (b));
1086 // Calculates the greatest common divisor of a and b.
1087 static uint Gcd (const uint a, const uint b) {
1088 uint x, y, z;
1090 x = a;
1091 y = b;
1092 while (y > 0) {
1093 z = y;
1094 y = x % y;
1095 x = z;
1097 return (x);
1100 /* Calculates the size (order) of the Kaiser window. Rejection is in dB and
1101 * the transition width is normalized frequency (0.5 is nyquist).
1103 * M = { ceil((r - 7.95) / (2.285 2 pi f_t)), r > 21
1104 * { ceil(5.79 / 2 pi f_t), r <= 21.
1107 static uint CalcKaiserOrder (const double rejection, const double transition) {
1108 double w_t;
1110 w_t = 2.0 * M_PI * transition;
1111 if (rejection > 21.0)
1112 return ((uint) ceil ((rejection - 7.95) / (2.285 * w_t)));
1113 return ((uint) ceil (5.79 / w_t));
1116 // Calculates the beta value of the Kaiser window. Rejection is in dB.
1117 static double CalcKaiserBeta (const double rejection) {
1118 if (rejection > 50.0)
1119 return (0.1102 * (rejection - 8.7));
1120 else if (rejection >= 21.0)
1121 return ((0.5842 * pow (rejection - 21.0, 0.4)) +
1122 (0.07886 * (rejection - 21.0)));
1123 else
1124 return (0.0);
1127 /* Calculates a point on the Kaiser-windowed sinc filter for the given half-
1128 * width, beta, gain, and cutoff. The point is specified in non-normalized
1129 * samples, from 0 to M, where M = (2 l + 1).
1131 * w(k) 2 p f_t sinc(2 f_t x)
1133 * x -- centered sample index (i - l)
1134 * k -- normalized and centered window index (x / l)
1135 * w(k) -- window function (Kaiser)
1136 * p -- gain compensation factor when sampling
1137 * f_t -- normalized center frequency (or cutoff; 0.5 is nyquist)
1139 static double SincFilter (const int l, const double b, const double gain, const double cutoff, const int i) {
1140 return (Kaiser (b, ((double) (i - l)) / l) * 2.0 * gain * cutoff * Sinc (2.0 * cutoff * (i - l)));
1143 /* This is a polyphase sinc-filtered resampler.
1145 * Upsample Downsample
1147 * p/q = 3/2 p/q = 3/5
1149 * M-+-+-+-> M-+-+-+->
1150 * -------------------+ ---------------------+
1151 * p s * f f f f|f| | p s * f f f f f |
1152 * | 0 * 0 0 0|0|0 | | 0 * 0 0 0 0|0| |
1153 * v 0 * 0 0|0|0 0 | v 0 * 0 0 0|0|0 |
1154 * s * f|f|f f f | s * f f|f|f f |
1155 * 0 * |0|0 0 0 0 | 0 * 0|0|0 0 0 |
1156 * --------+=+--------+ 0 * |0|0 0 0 0 |
1157 * d . d .|d|. d . d ----------+=+--------+
1158 * d . . . .|d|. . . .
1159 * q->
1160 * q-+-+-+->
1162 * P_f(i,j) = q i mod p + pj
1163 * P_s(i,j) = floor(q i / p) - j
1164 * d[i=0..N-1] = sum_{j=0}^{floor((M - 1) / p)} {
1165 * { f[P_f(i,j)] s[P_s(i,j)], P_f(i,j) < M
1166 * { 0, P_f(i,j) >= M. }
1169 // Calculate the resampling metrics and build the Kaiser-windowed sinc filter
1170 // that's used to cut frequencies above the destination nyquist.
1171 static void ResamplerSetup (ResamplerT * rs, const uint srcRate, const uint dstRate) {
1172 uint gcd, l;
1173 double cutoff, width, beta;
1174 int i;
1176 gcd = Gcd (srcRate, dstRate);
1177 rs -> mP = dstRate / gcd;
1178 rs -> mQ = srcRate / gcd;
1179 /* The cutoff is adjusted by half the transition width, so the transition
1180 * ends before the nyquist (0.5). Both are scaled by the downsampling
1181 * factor.
1183 if (rs -> mP > rs -> mQ) {
1184 cutoff = 0.45 / rs -> mP;
1185 width = 0.1 / rs -> mP;
1186 } else {
1187 cutoff = 0.45 / rs -> mQ;
1188 width = 0.1 / rs -> mQ;
1190 // A rejection of -180 dB is used for the stop band.
1191 l = CalcKaiserOrder (180.0, width) / 2;
1192 beta = CalcKaiserBeta (180.0);
1193 rs -> mM = (2 * l) + 1;
1194 rs -> mL = l;
1195 rs -> mF = CreateArray (rs -> mM);
1196 for (i = 0; i < ((int) rs -> mM); i ++)
1197 rs -> mF [i] = SincFilter ((int) l, beta, rs -> mP, cutoff, i);
1200 // Clean up after the resampler.
1201 static void ResamplerClear (ResamplerT * rs) {
1202 DestroyArray (rs -> mF);
1203 rs -> mF = NULL;
1206 // Perform the upsample-filter-downsample resampling operation using a
1207 // polyphase filter implementation.
1208 static void ResamplerRun (ResamplerT * rs, const uint inN, const double * in, const uint outN, double * out) {
1209 const uint p = rs -> mP, q = rs -> mQ, m = rs -> mM, l = rs -> mL;
1210 const double * f = rs -> mF;
1211 double * work = NULL;
1212 uint i;
1213 double r;
1214 uint j_f, j_s;
1216 if (outN == 0)
1217 return;
1219 // Handle in-place operation.
1220 if (in == out)
1221 work = CreateArray (outN);
1222 else
1223 work = out;
1224 // Resample the input.
1225 for (i = 0; i < outN; i ++) {
1226 r = 0.0;
1227 // Input starts at l to compensate for the filter delay. This will
1228 // drop any build-up from the first half of the filter.
1229 j_f = (l + (q * i)) % p;
1230 j_s = (l + (q * i)) / p;
1231 while (j_f < m) {
1232 // Only take input when 0 <= j_s < inN. This single unsigned
1233 // comparison catches both cases.
1234 if (j_s < inN)
1235 r += f [j_f] * in [j_s];
1236 j_f += p;
1237 j_s --;
1239 work [i] = r;
1241 // Clean up after in-place operation.
1242 if (in == out) {
1243 for (i = 0; i < outN; i ++)
1244 out [i] = work [i];
1245 DestroyArray (work);
1249 // Read a binary value of the specified byte order and byte size from a file,
1250 // storing it as a 32-bit unsigned integer.
1251 static int ReadBin4 (FILE * fp, const char * filename, const ByteOrderT order, const uint bytes, uint32 * out) {
1252 uint8 in [4];
1253 uint32 accum;
1254 uint i;
1256 if (fread (in, 1, bytes, fp) != bytes) {
1257 fprintf (stderr, "Error: Bad read from file '%s'.\n", filename);
1258 return (0);
1260 accum = 0;
1261 switch (order) {
1262 case BO_LITTLE :
1263 for (i = 0; i < bytes; i ++)
1264 accum = (accum << 8) | in [bytes - i - 1];
1265 break;
1266 case BO_BIG :
1267 for (i = 0; i < bytes; i ++)
1268 accum = (accum << 8) | in [i];
1269 break;
1270 default :
1271 break;
1273 (* out) = accum;
1274 return (1);
1277 // Read a binary value of the specified byte order from a file, storing it as
1278 // a 64-bit unsigned integer.
1279 static int ReadBin8 (FILE * fp, const char * filename, const ByteOrderT order, uint64 * out) {
1280 uint8 in [8];
1281 uint64 accum;
1282 uint i;
1284 if (fread (in, 1, 8, fp) != 8) {
1285 fprintf (stderr, "Error: Bad read from file '%s'.\n", filename);
1286 return (0);
1288 accum = 0ULL;
1289 switch (order) {
1290 case BO_LITTLE :
1291 for (i = 0; i < 8; i ++)
1292 accum = (accum << 8) | in [8 - i - 1];
1293 break;
1294 case BO_BIG :
1295 for (i = 0; i < 8; i ++)
1296 accum = (accum << 8) | in [i];
1297 break;
1298 default :
1299 break;
1301 (* out) = accum;
1302 return (1);
1305 // Write an ASCII string to a file.
1306 static int WriteAscii (const char * out, FILE * fp, const char * filename) {
1307 size_t len;
1309 len = strlen (out);
1310 if (fwrite (out, 1, len, fp) != len) {
1311 fclose (fp);
1312 fprintf (stderr, "Error: Bad write to file '%s'.\n", filename);
1313 return (0);
1315 return (1);
1318 // Write a binary value of the given byte order and byte size to a file,
1319 // loading it from a 32-bit unsigned integer.
1320 static int WriteBin4 (const ByteOrderT order, const uint bytes, const uint32 in, FILE * fp, const char * filename) {
1321 uint8 out [4];
1322 uint i;
1324 switch (order) {
1325 case BO_LITTLE :
1326 for (i = 0; i < bytes; i ++)
1327 out [i] = (in >> (i * 8)) & 0x000000FF;
1328 break;
1329 case BO_BIG :
1330 for (i = 0; i < bytes; i ++)
1331 out [bytes - i - 1] = (in >> (i * 8)) & 0x000000FF;
1332 break;
1333 default :
1334 break;
1336 if (fwrite (out, 1, bytes, fp) != bytes) {
1337 fprintf (stderr, "Error: Bad write to file '%s'.\n", filename);
1338 return (0);
1340 return (1);
1343 /* Read a binary value of the specified type, byte order, and byte size from
1344 * a file, converting it to a double. For integer types, the significant
1345 * bits are used to normalize the result. The sign of bits determines
1346 * whether they are padded toward the MSB (negative) or LSB (positive).
1347 * Floating-point types are not normalized.
1349 static int ReadBinAsDouble (FILE * fp, const char * filename, const ByteOrderT order, const ElementTypeT type, const uint bytes, const int bits, double * out) {
1350 union {
1351 uint32 ui;
1352 int32 i;
1353 float f;
1354 } v4;
1355 union {
1356 uint64 ui;
1357 double f;
1358 } v8;
1360 (* out) = 0.0;
1361 if (bytes > 4) {
1362 if (! ReadBin8 (fp, filename, order, & v8 . ui))
1363 return (0);
1364 if (type == ET_FP)
1365 (* out) = v8 . f;
1366 } else {
1367 if (! ReadBin4 (fp, filename, order, bytes, & v4 . ui))
1368 return (0);
1369 if (type == ET_FP) {
1370 (* out) = (double) v4 . f;
1371 } else {
1372 if (bits > 0)
1373 v4 . ui >>= (8 * bytes) - ((uint) bits);
1374 else
1375 v4 . ui &= (0xFFFFFFFF >> (32 + bits));
1376 if (v4 . ui & ((uint) (1 << (abs (bits) - 1))))
1377 v4 . ui |= (0xFFFFFFFF << abs (bits));
1378 (* out) = v4 . i / ((double) (1 << (abs (bits) - 1)));
1381 return (1);
1384 /* Read an ascii value of the specified type from a file, converting it to a
1385 * double. For integer types, the significant bits are used to normalize the
1386 * result. The sign of the bits should always be positive. This also skips
1387 * up to one separator character before the element itself.
1389 static int ReadAsciiAsDouble (TokenReaderT * tr, const char * filename, const ElementTypeT type, const uint bits, double * out) {
1390 int v;
1392 if (TrIsOperator (tr, ","))
1393 TrReadOperator (tr, ",");
1394 else if (TrIsOperator (tr, ":"))
1395 TrReadOperator (tr, ":");
1396 else if (TrIsOperator (tr, ";"))
1397 TrReadOperator (tr, ";");
1398 else if (TrIsOperator (tr, "|"))
1399 TrReadOperator (tr, "|");
1400 if (type == ET_FP) {
1401 if (! TrReadFloat (tr, -HUGE_VAL, HUGE_VAL, out)) {
1402 fprintf (stderr, "Error: Bad read from file '%s'.\n", filename);
1403 return (0);
1405 } else {
1406 if (! TrReadInt (tr, -(1 << (bits - 1)), (1 << (bits - 1)) - 1, & v)) {
1407 fprintf (stderr, "Error: Bad read from file '%s'.\n", filename);
1408 return (0);
1410 (* out) = v / ((double) ((1 << (bits - 1)) - 1));
1412 return (1);
1415 // Read the RIFF/RIFX WAVE format chunk from a file, validating it against
1416 // the source parameters and data set metrics.
1417 static int ReadWaveFormat (FILE * fp, const ByteOrderT order, const uint hrirRate, SourceRefT * src) {
1418 uint32 fourCC, chunkSize;
1419 uint32 format, channels, rate, dummy, block, size, bits;
1421 chunkSize = 0;
1422 do {
1423 if (chunkSize > 0)
1424 fseek (fp, (long) chunkSize, SEEK_CUR);
1425 if ((! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & fourCC)) ||
1426 (! ReadBin4 (fp, src -> mPath, order, 4, & chunkSize)))
1427 return (0);
1428 } while (fourCC != FOURCC_FMT);
1429 if ((! ReadBin4 (fp, src -> mPath, order, 2, & format)) ||
1430 (! ReadBin4 (fp, src -> mPath, order, 2, & channels)) ||
1431 (! ReadBin4 (fp, src -> mPath, order, 4, & rate)) ||
1432 (! ReadBin4 (fp, src -> mPath, order, 4, & dummy)) ||
1433 (! ReadBin4 (fp, src -> mPath, order, 2, & block)))
1434 return (0);
1435 block /= channels;
1436 if (chunkSize > 14) {
1437 if (! ReadBin4 (fp, src -> mPath, order, 2, & size))
1438 return (0);
1439 size /= 8;
1440 if (block > size)
1441 size = block;
1442 } else {
1443 size = block;
1445 if (format == WAVE_FORMAT_EXTENSIBLE) {
1446 fseek (fp, 2, SEEK_CUR);
1447 if (! ReadBin4 (fp, src -> mPath, order, 2, & bits))
1448 return (0);
1449 if (bits == 0)
1450 bits = 8 * size;
1451 fseek (fp, 4, SEEK_CUR);
1452 if (! ReadBin4 (fp, src -> mPath, order, 2, & format))
1453 return (0);
1454 fseek (fp, (long) (chunkSize - 26), SEEK_CUR);
1455 } else {
1456 bits = 8 * size;
1457 if (chunkSize > 14)
1458 fseek (fp, (long) (chunkSize - 16), SEEK_CUR);
1459 else
1460 fseek (fp, (long) (chunkSize - 14), SEEK_CUR);
1462 if ((format != WAVE_FORMAT_PCM) && (format != WAVE_FORMAT_IEEE_FLOAT)) {
1463 fprintf (stderr, "Error: Unsupported WAVE format in file '%s'.\n", src -> mPath);
1464 return (0);
1466 if (src -> mChannel >= channels) {
1467 fprintf (stderr, "Error: Missing source channel in WAVE file '%s'.\n", src -> mPath);
1468 return (0);
1470 if (rate != hrirRate) {
1471 fprintf (stderr, "Error: Mismatched source sample rate in WAVE file '%s'.\n", src -> mPath);
1472 return (0);
1474 if (format == WAVE_FORMAT_PCM) {
1475 if ((size < 2) || (size > 4)) {
1476 fprintf (stderr, "Error: Unsupported sample size in WAVE file '%s'.\n", src -> mPath);
1477 return (0);
1479 if ((bits < 16) || (bits > (8 * size))) {
1480 fprintf (stderr, "Error: Bad significant bits in WAVE file '%s'.\n", src -> mPath);
1481 return (0);
1483 src -> mType = ET_INT;
1484 } else {
1485 if ((size != 4) && (size != 8)) {
1486 fprintf (stderr, "Error: Unsupported sample size in WAVE file '%s'.\n", src -> mPath);
1487 return (0);
1489 src -> mType = ET_FP;
1491 src -> mSize = size;
1492 src -> mBits = (int) bits;
1493 src -> mSkip = channels;
1494 return (1);
1497 // Read a RIFF/RIFX WAVE data chunk, converting all elements to doubles.
1498 static int ReadWaveData (FILE * fp, const SourceRefT * src, const ByteOrderT order, const uint n, double * hrir) {
1499 int pre, post, skip;
1500 uint i;
1502 pre = (int) (src -> mSize * src -> mChannel);
1503 post = (int) (src -> mSize * (src -> mSkip - src -> mChannel - 1));
1504 skip = 0;
1505 for (i = 0; i < n; i ++) {
1506 skip += pre;
1507 if (skip > 0)
1508 fseek (fp, skip, SEEK_CUR);
1509 if (! ReadBinAsDouble (fp, src -> mPath, order, src -> mType, src -> mSize, src -> mBits, & hrir [i]))
1510 return (0);
1511 skip = post;
1513 if (skip > 0)
1514 fseek (fp, skip, SEEK_CUR);
1515 return (1);
1518 // Read the RIFF/RIFX WAVE list or data chunk, converting all elements to
1519 // doubles.
1520 static int ReadWaveList (FILE * fp, const SourceRefT * src, const ByteOrderT order, const uint n, double * hrir) {
1521 uint32 fourCC, chunkSize, listSize, count;
1522 uint block, skip, offset, i;
1523 double lastSample;
1525 for (;;) {
1526 if ((! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & fourCC)) ||
1527 (! ReadBin4 (fp, src -> mPath, order, 4, & chunkSize)))
1528 return (0);
1529 if (fourCC == FOURCC_DATA) {
1530 block = src -> mSize * src -> mSkip;
1531 count = chunkSize / block;
1532 if (count < (src -> mOffset + n)) {
1533 fprintf (stderr, "Error: Bad read from file '%s'.\n", src -> mPath);
1534 return (0);
1536 fseek (fp, (long) (src -> mOffset * block), SEEK_CUR);
1537 if (! ReadWaveData (fp, src, order, n, & hrir [0]))
1538 return (0);
1539 return (1);
1540 } else if (fourCC == FOURCC_LIST) {
1541 if (! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & fourCC))
1542 return (0);
1543 chunkSize -= 4;
1544 if (fourCC == FOURCC_WAVL)
1545 break;
1547 if (chunkSize > 0)
1548 fseek (fp, (long) chunkSize, SEEK_CUR);
1550 listSize = chunkSize;
1551 block = src -> mSize * src -> mSkip;
1552 skip = src -> mOffset;
1553 offset = 0;
1554 lastSample = 0.0;
1555 while ((offset < n) && (listSize > 8)) {
1556 if ((! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & fourCC)) ||
1557 (! ReadBin4 (fp, src -> mPath, order, 4, & chunkSize)))
1558 return (0);
1559 listSize -= 8 + chunkSize;
1560 if (fourCC == FOURCC_DATA) {
1561 count = chunkSize / block;
1562 if (count > skip) {
1563 fseek (fp, (long) (skip * block), SEEK_CUR);
1564 chunkSize -= skip * block;
1565 count -= skip;
1566 skip = 0;
1567 if (count > (n - offset))
1568 count = n - offset;
1569 if (! ReadWaveData (fp, src, order, count, & hrir [offset]))
1570 return (0);
1571 chunkSize -= count * block;
1572 offset += count;
1573 lastSample = hrir [offset - 1];
1574 } else {
1575 skip -= count;
1576 count = 0;
1578 } else if (fourCC == FOURCC_SLNT) {
1579 if (! ReadBin4 (fp, src -> mPath, order, 4, & count))
1580 return (0);
1581 chunkSize -= 4;
1582 if (count > skip) {
1583 count -= skip;
1584 skip = 0;
1585 if (count > (n - offset))
1586 count = n - offset;
1587 for (i = 0; i < count; i ++)
1588 hrir [offset + i] = lastSample;
1589 offset += count;
1590 } else {
1591 skip -= count;
1592 count = 0;
1595 if (chunkSize > 0)
1596 fseek (fp, (long) chunkSize, SEEK_CUR);
1598 if (offset < n) {
1599 fprintf (stderr, "Error: Bad read from file '%s'.\n", src -> mPath);
1600 return (0);
1602 return (1);
1605 // Load a source HRIR from a RIFF/RIFX WAVE file.
1606 static int LoadWaveSource (FILE * fp, SourceRefT * src, const uint hrirRate, const uint n, double * hrir) {
1607 uint32 fourCC, dummy;
1608 ByteOrderT order;
1610 if ((! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & fourCC)) ||
1611 (! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & dummy)))
1612 return (0);
1613 if (fourCC == FOURCC_RIFF) {
1614 order = BO_LITTLE;
1615 } else if (fourCC == FOURCC_RIFX) {
1616 order = BO_BIG;
1617 } else {
1618 fprintf (stderr, "Error: No RIFF/RIFX chunk in file '%s'.\n", src -> mPath);
1619 return (0);
1621 if (! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & fourCC))
1622 return (0);
1623 if (fourCC != FOURCC_WAVE) {
1624 fprintf (stderr, "Error: Not a RIFF/RIFX WAVE file '%s'.\n", src -> mPath);
1625 return (0);
1627 if (! ReadWaveFormat (fp, order, hrirRate, src))
1628 return (0);
1629 if (! ReadWaveList (fp, src, order, n, hrir))
1630 return (0);
1631 return (1);
1634 // Load a source HRIR from a binary file.
1635 static int LoadBinarySource (FILE * fp, const SourceRefT * src, const ByteOrderT order, const uint n, double * hrir) {
1636 uint i;
1638 fseek (fp, (long) src -> mOffset, SEEK_SET);
1639 for (i = 0; i < n; i ++) {
1640 if (! ReadBinAsDouble (fp, src -> mPath, order, src -> mType, src -> mSize, src -> mBits, & hrir [i]))
1641 return (0);
1642 if (src -> mSkip > 0)
1643 fseek (fp, (long) src -> mSkip, SEEK_CUR);
1645 return (1);
1648 // Load a source HRIR from an ASCII text file containing a list of elements
1649 // separated by whitespace or common list operators (',', ';', ':', '|').
1650 static int LoadAsciiSource (FILE * fp, const SourceRefT * src, const uint n, double * hrir) {
1651 TokenReaderT tr;
1652 uint i, j;
1653 double dummy;
1655 TrSetup (fp, NULL, & tr);
1656 for (i = 0; i < src -> mOffset; i ++) {
1657 if (! ReadAsciiAsDouble (& tr, src -> mPath, src -> mType, (uint) src -> mBits, & dummy))
1658 return (0);
1660 for (i = 0; i < n; i ++) {
1661 if (! ReadAsciiAsDouble (& tr, src -> mPath, src -> mType, (uint) src -> mBits, & hrir [i]))
1662 return (0);
1663 for (j = 0; j < src -> mSkip; j ++) {
1664 if (! ReadAsciiAsDouble (& tr, src -> mPath, src -> mType, (uint) src -> mBits, & dummy))
1665 return (0);
1668 return (1);
1671 // Load a source HRIR from a supported file type.
1672 static int LoadSource (SourceRefT * src, const uint hrirRate, const uint n, double * hrir) {
1673 FILE * fp = NULL;
1674 int result;
1676 if (src -> mFormat == SF_ASCII)
1677 fp = fopen (src -> mPath, "r");
1678 else
1679 fp = fopen (src -> mPath, "rb");
1680 if (fp == NULL) {
1681 fprintf (stderr, "Error: Could not open source file '%s'.\n", src -> mPath);
1682 return (0);
1684 if (src -> mFormat == SF_WAVE)
1685 result = LoadWaveSource (fp, src, hrirRate, n, hrir);
1686 else if (src -> mFormat == SF_BIN_LE)
1687 result = LoadBinarySource (fp, src, BO_LITTLE, n, hrir);
1688 else if (src -> mFormat == SF_BIN_BE)
1689 result = LoadBinarySource (fp, src, BO_BIG, n, hrir);
1690 else
1691 result = LoadAsciiSource (fp, src, n, hrir);
1692 fclose (fp);
1693 return (result);
1696 // Calculate the onset time of an HRIR and average it with any existing
1697 // timing for its elevation and azimuth.
1698 static void AverageHrirOnset (const double * hrir, const double f, const uint ei, const uint ai, const HrirDataT * hData) {
1699 double mag;
1700 uint n, i, j;
1702 mag = 0.0;
1703 n = hData -> mIrPoints;
1704 for (i = 0; i < n; i ++)
1705 mag = fmax (fabs (hrir [i]), mag);
1706 mag *= 0.15;
1707 for (i = 0; i < n; i ++) {
1708 if (fabs (hrir [i]) >= mag)
1709 break;
1711 j = hData -> mEvOffset [ei] + ai;
1712 hData -> mHrtds [j] = Lerp (hData -> mHrtds [j], ((double) i) / hData -> mIrRate, f);
1715 // Calculate the magnitude response of an HRIR and average it with any
1716 // existing responses for its elevation and azimuth.
1717 static void AverageHrirMagnitude (const double * hrir, const double f, const uint ei, const uint ai, const HrirDataT * hData) {
1718 double * re = NULL, * im = NULL;
1719 uint n, m, i, j;
1721 n = hData -> mFftSize;
1722 re = CreateArray (n);
1723 im = CreateArray (n);
1724 for (i = 0; i < hData -> mIrPoints; i ++) {
1725 re [i] = hrir [i];
1726 im [i] = 0.0;
1728 for (; i < n; i ++) {
1729 re [i] = 0.0;
1730 im [i] = 0.0;
1732 FftForward (n, re, im, re, im);
1733 MagnitudeResponse (n, re, im, re);
1734 m = 1 + (n / 2);
1735 j = (hData -> mEvOffset [ei] + ai) * hData -> mIrSize;
1736 for (i = 0; i < m; i ++)
1737 hData -> mHrirs [j + i] = Lerp (hData -> mHrirs [j + i], re [i], f);
1738 DestroyArray (im);
1739 DestroyArray (re);
1742 /* Calculate the contribution of each HRIR to the diffuse-field average based
1743 * on the area of its surface patch. All patches are centered at the HRIR
1744 * coordinates on the unit sphere and are measured by solid angle.
1746 static void CalculateDfWeights (const HrirDataT * hData, double * weights) {
1747 uint ei;
1748 double evs, sum, ev, up_ev, down_ev, solidAngle;
1750 evs = 90.0 / (hData -> mEvCount - 1);
1751 sum = 0.0;
1752 for (ei = hData -> mEvStart; ei < hData -> mEvCount; ei ++) {
1753 // For each elevation, calculate the upper and lower limits of the
1754 // patch band.
1755 ev = -90.0 + (ei * 2.0 * evs);
1756 if (ei < (hData -> mEvCount - 1))
1757 up_ev = (ev + evs) * M_PI / 180.0;
1758 else
1759 up_ev = M_PI / 2.0;
1760 if (ei > 0)
1761 down_ev = (ev - evs) * M_PI / 180.0;
1762 else
1763 down_ev = -M_PI / 2.0;
1764 // Calculate the area of the patch band.
1765 solidAngle = 2.0 * M_PI * (sin (up_ev) - sin (down_ev));
1766 // Each weight is the area of one patch.
1767 weights [ei] = solidAngle / hData -> mAzCount [ei];
1768 // Sum the total surface area covered by the HRIRs.
1769 sum += solidAngle;
1771 // Normalize the weights given the total surface coverage.
1772 for (ei = hData -> mEvStart; ei < hData -> mEvCount; ei ++)
1773 weights [ei] /= sum;
1776 /* Calculate the diffuse-field average from the given magnitude responses of
1777 * the HRIR set. Weighting can be applied to compensate for the varying
1778 * surface area covered by each HRIR. The final average can then be limited
1779 * by the specified magnitude range (in positive dB; 0.0 to skip).
1781 static void CalculateDiffuseFieldAverage (const HrirDataT * hData, const int weighted, const double limit, double * dfa) {
1782 double * weights = NULL;
1783 uint ei, ai, count, step, start, end, m, j, i;
1784 double weight;
1786 weights = CreateArray (hData -> mEvCount);
1787 if (weighted) {
1788 // Use coverage weighting to calculate the average.
1789 CalculateDfWeights (hData, weights);
1790 } else {
1791 // If coverage weighting is not used, the weights still need to be
1792 // averaged by the number of HRIRs.
1793 count = 0;
1794 for (ei = hData -> mEvStart; ei < hData -> mEvCount; ei ++)
1795 count += hData -> mAzCount [ei];
1796 for (ei = hData -> mEvStart; ei < hData -> mEvCount; ei ++)
1797 weights [ei] = 1.0 / count;
1799 ei = hData -> mEvStart;
1800 ai = 0;
1801 step = hData -> mIrSize;
1802 start = hData -> mEvOffset [ei] * step;
1803 end = hData -> mIrCount * step;
1804 m = 1 + (hData -> mFftSize / 2);
1805 for (i = 0; i < m; i ++)
1806 dfa [i] = 0.0;
1807 for (j = start; j < end; j += step) {
1808 // Get the weight for this HRIR's contribution.
1809 weight = weights [ei];
1810 // Add this HRIR's weighted power average to the total.
1811 for (i = 0; i < m; i ++)
1812 dfa [i] += weight * hData -> mHrirs [j + i] * hData -> mHrirs [j + i];
1813 // Determine the next weight to use.
1814 ai ++;
1815 if (ai >= hData -> mAzCount [ei]) {
1816 ei ++;
1817 ai = 0;
1820 // Finish the average calculation and keep it from being too small.
1821 for (i = 0; i < m; i ++)
1822 dfa [i] = fmax (sqrt (dfa [i]), EPSILON);
1823 // Apply a limit to the magnitude range of the diffuse-field average if
1824 // desired.
1825 if (limit > 0.0)
1826 LimitMagnitudeResponse (hData -> mFftSize, limit, dfa, dfa);
1827 DestroyArray (weights);
1830 // Perform diffuse-field equalization on the magnitude responses of the HRIR
1831 // set using the given average response.
1832 static void DiffuseFieldEqualize (const double * dfa, const HrirDataT * hData) {
1833 uint step, start, end, m, j, i;
1835 step = hData -> mIrSize;
1836 start = hData -> mEvOffset [hData -> mEvStart] * step;
1837 end = hData -> mIrCount * step;
1838 m = 1 + (hData -> mFftSize / 2);
1839 for (j = start; j < end; j += step) {
1840 for (i = 0; i < m; i ++)
1841 hData -> mHrirs [j + i] /= dfa [i];
1845 // Perform minimum-phase reconstruction using the magnitude responses of the
1846 // HRIR set.
1847 static void ReconstructHrirs (const HrirDataT * hData) {
1848 double * re = NULL, * im = NULL;
1849 uint step, start, end, n, j, i;
1851 step = hData -> mIrSize;
1852 start = hData -> mEvOffset [hData -> mEvStart] * step;
1853 end = hData -> mIrCount * step;
1854 n = hData -> mFftSize;
1855 re = CreateArray (n);
1856 im = CreateArray (n);
1857 for (j = start; j < end; j += step) {
1858 MinimumPhase (n, & hData -> mHrirs [j], re, im);
1859 FftInverse (n, re, im, re, im);
1860 for (i = 0; i < hData -> mIrPoints; i ++)
1861 hData -> mHrirs [j + i] = re [i];
1863 DestroyArray (im);
1864 DestroyArray (re);
1867 // Resamples the HRIRs for use at the given sampling rate.
1868 static void ResampleHrirs (const uint rate, HrirDataT * hData) {
1869 ResamplerT rs;
1870 uint n, step, start, end, j;
1872 ResamplerSetup (& rs, hData -> mIrRate, rate);
1873 n = hData -> mIrPoints;
1874 step = hData -> mIrSize;
1875 start = hData -> mEvOffset [hData -> mEvStart] * step;
1876 end = hData -> mIrCount * step;
1877 for (j = start; j < end; j += step)
1878 ResamplerRun (& rs, n, & hData -> mHrirs [j], n, & hData -> mHrirs [j]);
1879 ResamplerClear (& rs);
1880 hData -> mIrRate = rate;
1883 /* Given an elevation index and an azimuth, calculate the indices of the two
1884 * HRIRs that bound the coordinate along with a factor for calculating the
1885 * continous HRIR using interpolation.
1887 static void CalcAzIndices (const HrirDataT * hData, const uint ei, const double az, uint * j0, uint * j1, double * jf) {
1888 double af;
1889 uint ai;
1891 af = ((2.0 * M_PI) + az) * hData -> mAzCount [ei] / (2.0 * M_PI);
1892 ai = ((uint) af) % hData -> mAzCount [ei];
1893 af -= floor (af);
1894 (* j0) = hData -> mEvOffset [ei] + ai;
1895 (* j1) = hData -> mEvOffset [ei] + ((ai + 1) % hData -> mAzCount [ei]);
1896 (* jf) = af;
1899 // Synthesize any missing onset timings at the bottom elevations. This just
1900 // blends between slightly exaggerated known onsets. Not an accurate model.
1901 static void SynthesizeOnsets (HrirDataT * hData) {
1902 uint oi, e, a, j0, j1;
1903 double t, of, jf;
1905 oi = hData -> mEvStart;
1906 t = 0.0;
1907 for (a = 0; a < hData -> mAzCount [oi]; a ++)
1908 t += hData -> mHrtds [hData -> mEvOffset [oi] + a];
1909 hData -> mHrtds [0] = 1.32e-4 + (t / hData -> mAzCount [oi]);
1910 for (e = 1; e < hData -> mEvStart; e ++) {
1911 of = ((double) e) / hData -> mEvStart;
1912 for (a = 0; a < hData -> mAzCount [e]; a ++) {
1913 CalcAzIndices (hData, oi, a * 2.0 * M_PI / hData -> mAzCount [e], & j0, & j1, & jf);
1914 hData -> mHrtds [hData -> mEvOffset [e] + a] = Lerp (hData -> mHrtds [0], Lerp (hData -> mHrtds [j0], hData -> mHrtds [j1], jf), of);
1919 /* Attempt to synthesize any missing HRIRs at the bottom elevations. Right
1920 * now this just blends the lowest elevation HRIRs together and applies some
1921 * attenuation and high frequency damping. It is a simple, if inaccurate
1922 * model.
1924 static void SynthesizeHrirs (HrirDataT * hData) {
1925 uint oi, a, e, step, n, i, j;
1926 double of, b;
1927 uint j0, j1;
1928 double jf;
1929 double lp [4], s0, s1;
1931 if (hData -> mEvStart <= 0)
1932 return;
1933 step = hData -> mIrSize;
1934 oi = hData -> mEvStart;
1935 n = hData -> mIrPoints;
1936 for (i = 0; i < n; i ++)
1937 hData -> mHrirs [i] = 0.0;
1938 for (a = 0; a < hData -> mAzCount [oi]; a ++) {
1939 j = (hData -> mEvOffset [oi] + a) * step;
1940 for (i = 0; i < n; i ++)
1941 hData -> mHrirs [i] += hData -> mHrirs [j + i] / hData -> mAzCount [oi];
1943 for (e = 1; e < hData -> mEvStart; e ++) {
1944 of = ((double) e) / hData -> mEvStart;
1945 b = (1.0 - of) * (3.5e-6 * hData -> mIrRate);
1946 for (a = 0; a < hData -> mAzCount [e]; a ++) {
1947 j = (hData -> mEvOffset [e] + a) * step;
1948 CalcAzIndices (hData, oi, a * 2.0 * M_PI / hData -> mAzCount [e], & j0, & j1, & jf);
1949 j0 *= step;
1950 j1 *= step;
1951 lp [0] = 0.0;
1952 lp [1] = 0.0;
1953 lp [2] = 0.0;
1954 lp [3] = 0.0;
1955 for (i = 0; i < n; i ++) {
1956 s0 = hData -> mHrirs [i];
1957 s1 = Lerp (hData -> mHrirs [j0 + i], hData -> mHrirs [j1 + i], jf);
1958 s0 = Lerp (s0, s1, of);
1959 lp [0] = Lerp (s0, lp [0], b);
1960 lp [1] = Lerp (lp [0], lp [1], b);
1961 lp [2] = Lerp (lp [1], lp [2], b);
1962 lp [3] = Lerp (lp [2], lp [3], b);
1963 hData -> mHrirs [j + i] = lp [3];
1967 b = 3.5e-6 * hData -> mIrRate;
1968 lp [0] = 0.0;
1969 lp [1] = 0.0;
1970 lp [2] = 0.0;
1971 lp [3] = 0.0;
1972 for (i = 0; i < n; i ++) {
1973 s0 = hData -> mHrirs [i];
1974 lp [0] = Lerp (s0, lp [0], b);
1975 lp [1] = Lerp (lp [0], lp [1], b);
1976 lp [2] = Lerp (lp [1], lp [2], b);
1977 lp [3] = Lerp (lp [2], lp [3], b);
1978 hData -> mHrirs [i] = lp [3];
1980 hData -> mEvStart = 0;
1983 // The following routines assume a full set of HRIRs for all elevations.
1985 // Normalize the HRIR set and slightly attenuate the result.
1986 static void NormalizeHrirs (const HrirDataT * hData) {
1987 uint step, end, n, j, i;
1988 double maxLevel;
1990 step = hData -> mIrSize;
1991 end = hData -> mIrCount * step;
1992 n = hData -> mIrPoints;
1993 maxLevel = 0.0;
1994 for (j = 0; j < end; j += step) {
1995 for (i = 0; i < n; i ++)
1996 maxLevel = fmax (fabs (hData -> mHrirs [j + i]), maxLevel);
1998 maxLevel = 1.01 * maxLevel;
1999 for (j = 0; j < end; j += step) {
2000 for (i = 0; i < n; i ++)
2001 hData -> mHrirs [j + i] /= maxLevel;
2005 // Calculate the left-ear time delay using a spherical head model.
2006 static double CalcLTD (const double ev, const double az, const double rad, const double dist) {
2007 double azp, dlp, l, al;
2009 azp = asin (cos (ev) * sin (az));
2010 dlp = sqrt ((dist * dist) + (rad * rad) + (2.0 * dist * rad * sin (azp)));
2011 l = sqrt ((dist * dist) - (rad * rad));
2012 al = (0.5 * M_PI) + azp;
2013 if (dlp > l)
2014 dlp = l + (rad * (al - acos (rad / dist)));
2015 return (dlp / 343.3);
2018 // Calculate the effective head-related time delays for each minimum-phase
2019 // HRIR.
2020 static void CalculateHrtds (const HeadModelT model, const double radius, HrirDataT * hData) {
2021 double minHrtd, maxHrtd;
2022 uint e, a, j;
2023 double t;
2025 minHrtd = 1000.0;
2026 maxHrtd = -1000.0;
2027 for (e = 0; e < hData -> mEvCount; e ++) {
2028 for (a = 0; a < hData -> mAzCount [e]; a ++) {
2029 j = hData -> mEvOffset [e] + a;
2030 if (model == HM_DATASET) {
2031 t = hData -> mHrtds [j] * radius / hData -> mRadius;
2032 } else {
2033 t = CalcLTD ((-90.0 + (e * 180.0 / (hData -> mEvCount - 1))) * M_PI / 180.0,
2034 (a * 360.0 / hData -> mAzCount [e]) * M_PI / 180.0,
2035 radius, hData -> mDistance);
2037 hData -> mHrtds [j] = t;
2038 maxHrtd = fmax (t, maxHrtd);
2039 minHrtd = fmin (t, minHrtd);
2042 maxHrtd -= minHrtd;
2043 for (j = 0; j < hData -> mIrCount; j ++)
2044 hData -> mHrtds [j] -= minHrtd;
2045 hData -> mMaxHrtd = maxHrtd;
2048 // Store the OpenAL Soft HRTF data set.
2049 static int StoreMhr (const HrirDataT * hData, const char * filename) {
2050 FILE * fp = NULL;
2051 uint e, step, end, n, j, i;
2052 int hpHist, v;
2054 if ((fp = fopen (filename, "wb")) == NULL) {
2055 fprintf (stderr, "Error: Could not open MHR file '%s'.\n", filename);
2056 return (0);
2058 if (! WriteAscii (MHR_FORMAT, fp, filename))
2059 return (0);
2060 if (! WriteBin4 (BO_LITTLE, 4, (uint32) hData -> mIrRate, fp, filename))
2061 return (0);
2062 if (! WriteBin4 (BO_LITTLE, 1, (uint32) hData -> mIrPoints, fp, filename))
2063 return (0);
2064 if (! WriteBin4 (BO_LITTLE, 1, (uint32) hData -> mEvCount, fp, filename))
2065 return (0);
2066 for (e = 0; e < hData -> mEvCount; e ++) {
2067 if (! WriteBin4 (BO_LITTLE, 1, (uint32) hData -> mAzCount [e], fp, filename))
2068 return (0);
2070 step = hData -> mIrSize;
2071 end = hData -> mIrCount * step;
2072 n = hData -> mIrPoints;
2073 srand (0x31DF840C);
2074 for (j = 0; j < end; j += step) {
2075 hpHist = 0;
2076 for (i = 0; i < n; i ++) {
2077 v = HpTpdfDither (32767.0 * hData -> mHrirs [j + i], & hpHist);
2078 if (! WriteBin4 (BO_LITTLE, 2, (uint32) v, fp, filename))
2079 return (0);
2082 for (j = 0; j < hData -> mIrCount; j ++) {
2083 v = (int) fmin (round (hData -> mIrRate * hData -> mHrtds [j]), MAX_HRTD);
2084 if (! WriteBin4 (BO_LITTLE, 1, (uint32) v, fp, filename))
2085 return (0);
2087 fclose (fp);
2088 return (1);
2091 // Store the OpenAL Soft built-in table.
2092 static int StoreTable (const HrirDataT * hData, const char * filename) {
2093 FILE * fp = NULL;
2094 uint step, end, n, j, i;
2095 int hpHist, v;
2096 char text [128 + 1];
2098 if ((fp = fopen (filename, "wb")) == NULL) {
2099 fprintf (stderr, "Error: Could not open table file '%s'.\n", filename);
2100 return (0);
2102 snprintf (text, 128, "/* Elevation metrics */\n"
2103 "static const ALubyte defaultAzCount[%u] = { ", hData -> mEvCount);
2104 if (! WriteAscii (text, fp, filename))
2105 return (0);
2106 for (i = 0; i < hData -> mEvCount; i ++) {
2107 snprintf (text, 128, "%u, ", hData -> mAzCount [i]);
2108 if (! WriteAscii (text, fp, filename))
2109 return (0);
2111 snprintf (text, 128, "};\n"
2112 "static const ALushort defaultEvOffset[%u] = { ", hData -> mEvCount);
2113 if (! WriteAscii (text, fp, filename))
2114 return (0);
2115 for (i = 0; i < hData -> mEvCount; i ++) {
2116 snprintf (text, 128, "%u, ", hData -> mEvOffset [i]);
2117 if (! WriteAscii (text, fp, filename))
2118 return (0);
2120 step = hData -> mIrSize;
2121 end = hData -> mIrCount * step;
2122 n = hData -> mIrPoints;
2123 snprintf (text, 128, "};\n\n"
2124 "/* HRIR Coefficients */\n"
2125 "static const ALshort defaultCoeffs[%u] =\n{\n", hData -> mIrCount * n);
2126 if (! WriteAscii (text, fp, filename))
2127 return (0);
2128 srand (0x31DF840C);
2129 for (j = 0; j < end; j += step) {
2130 if (! WriteAscii (" ", fp, filename))
2131 return (0);
2132 hpHist = 0;
2133 for (i = 0; i < n; i ++) {
2134 v = HpTpdfDither (32767.0 * hData -> mHrirs [j + i], & hpHist);
2135 snprintf (text, 128, " %+d,", v);
2136 if (! WriteAscii (text, fp, filename))
2137 return (0);
2139 if (! WriteAscii ("\n", fp, filename))
2140 return (0);
2142 snprintf (text, 128, "};\n\n"
2143 "/* HRIR Delays */\n"
2144 "static const ALubyte defaultDelays[%u] =\n{\n"
2145 " ", hData -> mIrCount);
2146 if (! WriteAscii (text, fp, filename))
2147 return (0);
2148 for (j = 0; j < hData -> mIrCount; j ++) {
2149 v = (int) fmin (round (hData -> mIrRate * hData -> mHrtds [j]), MAX_HRTD);
2150 snprintf (text, 128, " %d,", v);
2151 if (! WriteAscii (text, fp, filename))
2152 return (0);
2154 if (! WriteAscii ("\n};\n\n"
2155 "/* Default HRTF Definition */\n", fp, filename))
2156 return (0);
2157 snprintf (text, 128, "static const struct Hrtf DefaultHrtf = {\n"
2158 " %u, %u, %u, defaultAzCount, defaultEvOffset,\n",
2159 hData -> mIrRate, hData -> mIrPoints, hData -> mEvCount);
2160 if (! WriteAscii (text, fp, filename))
2161 return (0);
2162 if (! WriteAscii (" defaultCoeffs, defaultDelays, NULL\n"
2163 "};\n", fp, filename))
2164 return (0);
2165 fclose (fp);
2166 return (1);
2169 // Process the data set definition to read and validate the data set metrics.
2170 static int ProcessMetrics (TokenReaderT * tr, const uint fftSize, const uint truncSize, HrirDataT * hData) {
2171 char ident [MAX_IDENT_LEN + 1];
2172 uint line, col;
2173 int intVal;
2174 uint points;
2175 double fpVal;
2176 int hasRate = 0, hasPoints = 0, hasAzimuths = 0;
2177 int hasRadius = 0, hasDistance = 0;
2179 while (! (hasRate && hasPoints && hasAzimuths && hasRadius && hasDistance)) {
2180 TrIndication (tr, & line, & col);
2181 if (! TrReadIdent (tr, MAX_IDENT_LEN, ident))
2182 return (0);
2183 if (strcasecmp (ident, "rate") == 0) {
2184 if (hasRate) {
2185 TrErrorAt (tr, line, col, "Redefinition of 'rate'.\n");
2186 return (0);
2188 if (! TrReadOperator (tr, "="))
2189 return (0);
2190 if (! TrReadInt (tr, MIN_RATE, MAX_RATE, & intVal))
2191 return (0);
2192 hData -> mIrRate = (uint) intVal;
2193 hasRate = 1;
2194 } else if (strcasecmp (ident, "points") == 0) {
2195 if (hasPoints) {
2196 TrErrorAt (tr, line, col, "Redefinition of 'points'.\n");
2197 return (0);
2199 if (! TrReadOperator (tr, "="))
2200 return (0);
2201 TrIndication (tr, & line, & col);
2202 if (! TrReadInt (tr, MIN_POINTS, MAX_POINTS, & intVal))
2203 return (0);
2204 points = (uint) intVal;
2205 if ((fftSize > 0) && (points > fftSize)) {
2206 TrErrorAt (tr, line, col, "Value exceeds the overriden FFT size.\n");
2207 return (0);
2209 if (points < truncSize) {
2210 TrErrorAt (tr, line, col, "Value is below the truncation size.\n");
2211 return (0);
2213 hData -> mIrPoints = points;
2214 hData -> mFftSize = fftSize;
2215 if (fftSize <= 0) {
2216 points = 1;
2217 while (points < (4 * hData -> mIrPoints))
2218 points <<= 1;
2219 hData -> mFftSize = points;
2220 hData -> mIrSize = 1 + (points / 2);
2221 } else {
2222 hData -> mFftSize = fftSize;
2223 hData -> mIrSize = 1 + (fftSize / 2);
2224 if (points > hData -> mIrSize)
2225 hData -> mIrSize = points;
2227 hasPoints = 1;
2228 } else if (strcasecmp (ident, "azimuths") == 0) {
2229 if (hasAzimuths) {
2230 TrErrorAt (tr, line, col, "Redefinition of 'azimuths'.\n");
2231 return (0);
2233 if (! TrReadOperator (tr, "="))
2234 return (0);
2235 hData -> mIrCount = 0;
2236 hData -> mEvCount = 0;
2237 hData -> mEvOffset [0] = 0;
2238 for (;;) {
2239 if (! TrReadInt (tr, MIN_AZ_COUNT, MAX_AZ_COUNT, & intVal))
2240 return (0);
2241 hData -> mAzCount [hData -> mEvCount] = (uint) intVal;
2242 hData -> mIrCount += (uint) intVal;
2243 hData -> mEvCount ++;
2244 if (! TrIsOperator (tr, ","))
2245 break;
2246 if (hData -> mEvCount >= MAX_EV_COUNT) {
2247 TrError (tr, "Exceeded the maximum of %d elevations.\n", MAX_EV_COUNT);
2248 return (0);
2250 hData -> mEvOffset [hData -> mEvCount] = hData -> mEvOffset [hData -> mEvCount - 1] + ((uint) intVal);
2251 TrReadOperator (tr, ",");
2253 if (hData -> mEvCount < MIN_EV_COUNT) {
2254 TrErrorAt (tr, line, col, "Did not reach the minimum of %d azimuth counts.\n", MIN_EV_COUNT);
2255 return (0);
2257 hasAzimuths = 1;
2258 } else if (strcasecmp (ident, "radius") == 0) {
2259 if (hasRadius) {
2260 TrErrorAt (tr, line, col, "Redefinition of 'radius'.\n");
2261 return (0);
2263 if (! TrReadOperator (tr, "="))
2264 return (0);
2265 if (! TrReadFloat (tr, MIN_RADIUS, MAX_RADIUS, & fpVal))
2266 return (0);
2267 hData -> mRadius = fpVal;
2268 hasRadius = 1;
2269 } else if (strcasecmp (ident, "distance") == 0) {
2270 if (hasDistance) {
2271 TrErrorAt (tr, line, col, "Redefinition of 'distance'.\n");
2272 return (0);
2274 if (! TrReadOperator (tr, "="))
2275 return (0);
2276 if (! TrReadFloat (tr, MIN_DISTANCE, MAX_DISTANCE, & fpVal))
2277 return (0);
2278 hData -> mDistance = fpVal;
2279 hasDistance = 1;
2280 } else {
2281 TrErrorAt (tr, line, col, "Expected a metric name.\n");
2282 return (0);
2284 TrSkipWhitespace (tr);
2286 return (1);
2289 // Parse an index pair from the data set definition.
2290 static int ReadIndexPair (TokenReaderT * tr, const HrirDataT * hData, uint * ei, uint * ai) {
2291 int intVal;
2293 if (! TrReadInt (tr, 0, (int) hData -> mEvCount, & intVal))
2294 return (0);
2295 (* ei) = (uint) intVal;
2296 if (! TrReadOperator (tr, ","))
2297 return (0);
2298 if (! TrReadInt (tr, 0, (int) hData -> mAzCount [(* ei)], & intVal))
2299 return (0);
2300 (* ai) = (uint) intVal;
2301 return (1);
2304 // Match the source format from a given identifier.
2305 static SourceFormatT MatchSourceFormat (const char * ident) {
2306 if (strcasecmp (ident, "wave") == 0)
2307 return (SF_WAVE);
2308 else if (strcasecmp (ident, "bin_le") == 0)
2309 return (SF_BIN_LE);
2310 else if (strcasecmp (ident, "bin_be") == 0)
2311 return (SF_BIN_BE);
2312 else if (strcasecmp (ident, "ascii") == 0)
2313 return (SF_ASCII);
2314 return (SF_NONE);
2317 // Match the source element type from a given identifier.
2318 static ElementTypeT MatchElementType (const char * ident) {
2319 if (strcasecmp (ident, "int") == 0)
2320 return (ET_INT);
2321 else if (strcasecmp (ident, "fp") == 0)
2322 return (ET_FP);
2323 return (ET_NONE);
2326 // Parse and validate a source reference from the data set definition.
2327 static int ReadSourceRef (TokenReaderT * tr, SourceRefT * src) {
2328 uint line, col;
2329 char ident [MAX_IDENT_LEN + 1];
2330 int intVal;
2332 TrIndication (tr, & line, & col);
2333 if (! TrReadIdent (tr, MAX_IDENT_LEN, ident))
2334 return (0);
2335 src -> mFormat = MatchSourceFormat (ident);
2336 if (src -> mFormat == SF_NONE) {
2337 TrErrorAt (tr, line, col, "Expected a source format.\n");
2338 return (0);
2340 if (! TrReadOperator (tr, "("))
2341 return (0);
2342 if (src -> mFormat == SF_WAVE) {
2343 if (! TrReadInt (tr, 0, MAX_WAVE_CHANNELS, & intVal))
2344 return (0);
2345 src -> mType = ET_NONE;
2346 src -> mSize = 0;
2347 src -> mBits = 0;
2348 src -> mChannel = (uint) intVal;
2349 src -> mSkip = 0;
2350 } else {
2351 TrIndication (tr, & line, & col);
2352 if (! TrReadIdent (tr, MAX_IDENT_LEN, ident))
2353 return (0);
2354 src -> mType = MatchElementType (ident);
2355 if (src -> mType == ET_NONE) {
2356 TrErrorAt (tr, line, col, "Expected a source element type.\n");
2357 return (0);
2359 if ((src -> mFormat == SF_BIN_LE) || (src -> mFormat == SF_BIN_BE)) {
2360 if (! TrReadOperator (tr, ","))
2361 return (0);
2362 if (src -> mType == ET_INT) {
2363 if (! TrReadInt (tr, MIN_BIN_SIZE, MAX_BIN_SIZE, & intVal))
2364 return (0);
2365 src -> mSize = (uint) intVal;
2366 if (TrIsOperator (tr, ",")) {
2367 TrReadOperator (tr, ",");
2368 TrIndication (tr, & line, & col);
2369 if (! TrReadInt (tr, -2147483647 - 1, 2147483647, & intVal))
2370 return (0);
2371 if ((abs (intVal) < MIN_BIN_BITS) || (((uint) abs (intVal)) > (8 * src -> mSize))) {
2372 TrErrorAt (tr, line, col, "Expected a value of (+/-) %d to %d.\n", MIN_BIN_BITS, 8 * src -> mSize);
2373 return (0);
2375 src -> mBits = intVal;
2376 } else {
2377 src -> mBits = (int) (8 * src -> mSize);
2379 } else {
2380 TrIndication (tr, & line, & col);
2381 if (! TrReadInt (tr, -2147483647 - 1, 2147483647, & intVal))
2382 return (0);
2383 if ((intVal != 4) && (intVal != 8)) {
2384 TrErrorAt (tr, line, col, "Expected a value of 4 or 8.\n");
2385 return (0);
2387 src -> mSize = (uint) intVal;
2388 src -> mBits = 0;
2390 } else if ((src -> mFormat == SF_ASCII) && (src -> mType == ET_INT)) {
2391 if (! TrReadOperator (tr, ","))
2392 return (0);
2393 if (! TrReadInt (tr, MIN_ASCII_BITS, MAX_ASCII_BITS, & intVal))
2394 return (0);
2395 src -> mSize = 0;
2396 src -> mBits = intVal;
2397 } else {
2398 src -> mSize = 0;
2399 src -> mBits = 0;
2401 if (TrIsOperator (tr, ";")) {
2402 TrReadOperator (tr, ";");
2403 if (! TrReadInt (tr, 0, 0x7FFFFFFF, & intVal))
2404 return (0);
2405 src -> mSkip = (uint) intVal;
2406 } else {
2407 src -> mSkip = 0;
2410 if (! TrReadOperator (tr, ")"))
2411 return (0);
2412 if (TrIsOperator (tr, "@")) {
2413 TrReadOperator (tr, "@");
2414 if (! TrReadInt (tr, 0, 0x7FFFFFFF, & intVal))
2415 return (0);
2416 src -> mOffset = (uint) intVal;
2417 } else {
2418 src -> mOffset = 0;
2420 if (! TrReadOperator (tr, ":"))
2421 return (0);
2422 if (! TrReadString (tr, MAX_PATH_LEN, src -> mPath))
2423 return (0);
2424 return (1);
2427 // Process the list of sources in the data set definition.
2428 static int ProcessSources (const HeadModelT model, TokenReaderT * tr, HrirDataT * hData) {
2429 uint * setCount = NULL, * setFlag = NULL;
2430 double * hrir = NULL;
2431 uint line, col, ei, ai;
2432 SourceRefT src;
2433 double factor;
2435 setCount = (uint *) calloc (hData -> mEvCount, sizeof (uint));
2436 setFlag = (uint *) calloc (hData -> mIrCount, sizeof (uint));
2437 hrir = CreateArray (hData -> mIrPoints);
2438 while (TrIsOperator (tr, "[")) {
2439 TrIndication (tr, & line, & col);
2440 TrReadOperator (tr, "[");
2441 if (ReadIndexPair (tr, hData, & ei, & ai)) {
2442 if (TrReadOperator (tr, "]")) {
2443 if (! setFlag [hData -> mEvOffset [ei] + ai]) {
2444 if (TrReadOperator (tr, "=")) {
2445 factor = 1.0;
2446 for (;;) {
2447 if (ReadSourceRef (tr, & src)) {
2448 if (LoadSource (& src, hData -> mIrRate, hData -> mIrPoints, hrir)) {
2449 if (model == HM_DATASET)
2450 AverageHrirOnset (hrir, 1.0 / factor, ei, ai, hData);
2451 AverageHrirMagnitude (hrir, 1.0 / factor, ei, ai, hData);
2452 factor += 1.0;
2453 if (! TrIsOperator (tr, "+"))
2454 break;
2455 TrReadOperator (tr, "+");
2456 continue;
2459 DestroyArray (hrir);
2460 free (setFlag);
2461 free (setCount);
2462 return (0);
2464 setFlag [hData -> mEvOffset [ei] + ai] = 1;
2465 setCount [ei] ++;
2466 continue;
2468 } else {
2469 TrErrorAt (tr, line, col, "Redefinition of source.\n");
2473 DestroyArray (hrir);
2474 free (setFlag);
2475 free (setCount);
2476 return (0);
2478 ei = 0;
2479 while ((ei < hData -> mEvCount) && (setCount [ei] < 1))
2480 ei ++;
2481 if (ei < hData -> mEvCount) {
2482 hData -> mEvStart = ei;
2483 while ((ei < hData -> mEvCount) && (setCount [ei] == hData -> mAzCount [ei]))
2484 ei ++;
2485 if (ei >= hData -> mEvCount) {
2486 if (! TrLoad (tr)) {
2487 DestroyArray (hrir);
2488 free (setFlag);
2489 free (setCount);
2490 return (1);
2491 } else {
2492 TrError (tr, "Errant data at end of source list.\n");
2494 } else {
2495 TrError (tr, "Missing sources for elevation index %d.\n", ei);
2497 } else {
2498 TrError (tr, "Missing source references.\n");
2500 DestroyArray (hrir);
2501 free (setFlag);
2502 free (setCount);
2503 return (0);
2506 /* Parse the data set definition and process the source data, storing the
2507 * resulting data set as desired. If the input name is NULL it will read
2508 * from standard input.
2510 static int ProcessDefinition (const char * inName, const uint outRate, const uint fftSize, const int equalize, const int surface, const double limit, const uint truncSize, const HeadModelT model, const double radius, const OutputFormatT outFormat, const char * outName) {
2511 FILE * fp = NULL;
2512 TokenReaderT tr;
2513 HrirDataT hData;
2514 double * dfa = NULL;
2515 char rateStr [8 + 1], expName [MAX_PATH_LEN];
2517 hData . mIrRate = 0;
2518 hData . mIrPoints = 0;
2519 hData . mFftSize = 0;
2520 hData . mIrSize = 0;
2521 hData . mIrCount = 0;
2522 hData . mEvCount = 0;
2523 hData . mRadius = 0;
2524 hData . mDistance = 0;
2525 fprintf (stdout, "Reading HRIR definition...\n");
2526 if (inName != NULL) {
2527 fp = fopen (inName, "r");
2528 if (fp == NULL) {
2529 fprintf (stderr, "Error: Could not open definition file '%s'\n", inName);
2530 return (0);
2532 TrSetup (fp, inName, & tr);
2533 } else {
2534 fp = stdin;
2535 TrSetup (fp, "<stdin>", & tr);
2537 if (! ProcessMetrics (& tr, fftSize, truncSize, & hData)) {
2538 if (inName != NULL)
2539 fclose (fp);
2540 return (0);
2542 hData . mHrirs = CreateArray (hData . mIrCount * hData . mIrSize);
2543 hData . mHrtds = CreateArray (hData . mIrCount);
2544 if (! ProcessSources (model, & tr, & hData)) {
2545 DestroyArray (hData . mHrtds);
2546 DestroyArray (hData . mHrirs);
2547 if (inName != NULL)
2548 fclose (fp);
2549 return (0);
2551 if (inName != NULL)
2552 fclose (fp);
2553 if (equalize) {
2554 dfa = CreateArray (1 + (hData . mFftSize / 2));
2555 fprintf (stdout, "Calculating diffuse-field average...\n");
2556 CalculateDiffuseFieldAverage (& hData, surface, limit, dfa);
2557 fprintf (stdout, "Performing diffuse-field equalization...\n");
2558 DiffuseFieldEqualize (dfa, & hData);
2559 DestroyArray (dfa);
2561 fprintf (stdout, "Performing minimum phase reconstruction...\n");
2562 ReconstructHrirs (& hData);
2563 if ((outRate != 0) && (outRate != hData . mIrRate)) {
2564 fprintf (stdout, "Resampling HRIRs...\n");
2565 ResampleHrirs (outRate, & hData);
2567 fprintf (stdout, "Truncating minimum-phase HRIRs...\n");
2568 hData . mIrPoints = truncSize;
2569 fprintf (stdout, "Synthesizing missing elevations...\n");
2570 if (model == HM_DATASET)
2571 SynthesizeOnsets (& hData);
2572 SynthesizeHrirs (& hData);
2573 fprintf (stdout, "Normalizing final HRIRs...\n");
2574 NormalizeHrirs (& hData);
2575 fprintf (stdout, "Calculating impulse delays...\n");
2576 CalculateHrtds (model, (radius > DEFAULT_CUSTOM_RADIUS) ? radius : hData . mRadius, & hData);
2577 snprintf (rateStr, 8, "%u", hData . mIrRate);
2578 StrSubst (outName, "%r", rateStr, MAX_PATH_LEN, expName);
2579 switch (outFormat) {
2580 case OF_MHR :
2581 fprintf (stdout, "Creating MHR data set file...\n");
2582 if (! StoreMhr (& hData, expName))
2583 return (0);
2584 break;
2585 case OF_TABLE :
2586 fprintf (stderr, "Creating OpenAL Soft table file...\n");
2587 if (! StoreTable (& hData, expName))
2588 return (0);
2589 break;
2590 default :
2591 break;
2593 DestroyArray (hData . mHrtds);
2594 DestroyArray (hData . mHrirs);
2595 return (1);
2598 // Standard command line dispatch.
2599 int main (const int argc, const char * argv []) {
2600 const char * inName = NULL, * outName = NULL;
2601 OutputFormatT outFormat;
2602 int argi;
2603 uint outRate, fftSize;
2604 int equalize, surface;
2605 double limit;
2606 uint truncSize;
2607 HeadModelT model;
2608 double radius;
2609 char * end = NULL;
2611 if (argc < 2) {
2612 fprintf (stderr, "Error: No command specified. See '%s -h' for help.\n", argv [0]);
2613 return (-1);
2615 if ((strcmp (argv [1], "--help") == 0) || (strcmp (argv [1], "-h") == 0)) {
2616 fprintf (stdout, "HRTF Processing and Composition Utility\n\n");
2617 fprintf (stdout, "Usage: %s <command> [<option>...]\n\n", argv [0]);
2618 fprintf (stdout, "Commands:\n");
2619 fprintf (stdout, " -m, --make-mhr Makes an OpenAL Soft compatible HRTF data set.\n");
2620 fprintf (stdout, " Defaults output to: ./oalsoft_hrtf_%%r.mhr\n");
2621 fprintf (stdout, " -t, --make-tab Makes the built-in table used when compiling OpenAL Soft.\n");
2622 fprintf (stdout, " Defaults output to: ./hrtf_tables.inc\n");
2623 fprintf (stdout, " -h, --help Displays this help information.\n\n");
2624 fprintf (stdout, "Options:\n");
2625 fprintf (stdout, " -r=<rate> Change the data set sample rate to the specified value and\n");
2626 fprintf (stdout, " resample the HRIRs accordingly.\n");
2627 fprintf (stdout, " -f=<points> Override the FFT window size (defaults to the first power-\n");
2628 fprintf (stdout, " of-two that fits four times the number of HRIR points).\n");
2629 fprintf (stdout, " -e={on|off} Toggle diffuse-field equalization (default: %s).\n", (DEFAULT_EQUALIZE ? "on" : "off"));
2630 fprintf (stdout, " -s={on|off} Toggle surface-weighted diffuse-field average (default: %s).\n", (DEFAULT_SURFACE ? "on" : "off"));
2631 fprintf (stdout, " -l={<dB>|none} Specify a limit to the magnitude range of the diffuse-field\n");
2632 fprintf (stdout, " average (default: %.2f).\n", DEFAULT_LIMIT);
2633 fprintf (stdout, " -w=<points> Specify the size of the truncation window that's applied\n");
2634 fprintf (stdout, " after minimum-phase reconstruction (default: %u).\n", DEFAULT_TRUNCSIZE);
2635 fprintf (stdout, " -d={dataset| Specify the model used for calculating the head-delay timing\n");
2636 fprintf (stdout, " sphere} values (default: %s).\n", ((DEFAULT_HEAD_MODEL == HM_DATASET) ? "dataset" : "sphere"));
2637 fprintf (stdout, " -c=<size> Use a customized head radius measured ear-to-ear in meters.\n");
2638 fprintf (stdout, " -i=<filename> Specify an HRIR definition file to use (defaults to stdin).\n");
2639 fprintf (stdout, " -o=<filename> Specify an output file. Overrides command-selected default.\n");
2640 fprintf (stdout, " Use of '%%r' will be substituted with the data set sample rate.\n");
2641 return (0);
2643 if ((strcmp (argv [1], "--make-mhr") == 0) || (strcmp (argv [1], "-m") == 0)) {
2644 if (argc > 3)
2645 outName = argv [3];
2646 else
2647 outName = "./oalsoft_hrtf_%r.mhr";
2648 outFormat = OF_MHR;
2649 } else if ((strcmp (argv [1], "--make-tab") == 0) || (strcmp (argv [1], "-t") == 0)) {
2650 if (argc > 3)
2651 outName = argv [3];
2652 else
2653 outName = "./hrtf_tables.inc";
2654 outFormat = OF_TABLE;
2655 } else {
2656 fprintf (stderr, "Error: Invalid command '%s'.\n", argv [1]);
2657 return (-1);
2659 argi = 2;
2660 outRate = 0;
2661 fftSize = 0;
2662 equalize = DEFAULT_EQUALIZE;
2663 surface = DEFAULT_SURFACE;
2664 limit = DEFAULT_LIMIT;
2665 truncSize = DEFAULT_TRUNCSIZE;
2666 model = DEFAULT_HEAD_MODEL;
2667 radius = DEFAULT_CUSTOM_RADIUS;
2668 while (argi < argc) {
2669 if (strncmp (argv [argi], "-r=", 3) == 0) {
2670 outRate = strtoul (& argv [argi] [3], & end, 10);
2671 if ((end [0] != '\0') || (outRate < MIN_RATE) || (outRate > MAX_RATE)) {
2672 fprintf (stderr, "Error: Expected a value from %u to %u for '-r'.\n", MIN_RATE, MAX_RATE);
2673 return (-1);
2675 } else if (strncmp (argv [argi], "-f=", 3) == 0) {
2676 fftSize = strtoul (& argv [argi] [3], & end, 10);
2677 if ((end [0] != '\0') || (fftSize & (fftSize - 1)) || (fftSize < MIN_FFTSIZE) || (fftSize > MAX_FFTSIZE)) {
2678 fprintf (stderr, "Error: Expected a power-of-two value from %u to %u for '-f'.\n", MIN_FFTSIZE, MAX_FFTSIZE);
2679 return (-1);
2681 } else if (strncmp (argv [argi], "-e=", 3) == 0) {
2682 if (strcmp (& argv [argi] [3], "on") == 0) {
2683 equalize = 1;
2684 } else if (strcmp (& argv [argi] [3], "off") == 0) {
2685 equalize = 0;
2686 } else {
2687 fprintf (stderr, "Error: Expected 'on' or 'off' for '-e'.\n");
2688 return (-1);
2690 } else if (strncmp (argv [argi], "-s=", 3) == 0) {
2691 if (strcmp (& argv [argi] [3], "on") == 0) {
2692 surface = 1;
2693 } else if (strcmp (& argv [argi] [3], "off") == 0) {
2694 surface = 0;
2695 } else {
2696 fprintf (stderr, "Error: Expected 'on' or 'off' for '-s'.\n");
2697 return (-1);
2699 } else if (strncmp (argv [argi], "-l=", 3) == 0) {
2700 if (strcmp (& argv [argi] [3], "none") == 0) {
2701 limit = 0.0;
2702 } else {
2703 limit = strtod (& argv [argi] [3], & end);
2704 if ((end [0] != '\0') || (limit < MIN_LIMIT) || (limit > MAX_LIMIT)) {
2705 fprintf (stderr, "Error: Expected 'none' or a value from %.2f to %.2f for '-l'.\n", MIN_LIMIT, MAX_LIMIT);
2706 return (-1);
2709 } else if (strncmp (argv [argi], "-w=", 3) == 0) {
2710 truncSize = strtoul (& argv [argi] [3], & end, 10);
2711 if ((end [0] != '\0') || (truncSize < MIN_TRUNCSIZE) || (truncSize > MAX_TRUNCSIZE) || (truncSize % MOD_TRUNCSIZE)) {
2712 fprintf (stderr, "Error: Expected a value from %u to %u in multiples of %u for '-w'.\n", MIN_TRUNCSIZE, MAX_TRUNCSIZE, MOD_TRUNCSIZE);
2713 return (-1);
2715 } else if (strncmp (argv [argi], "-d=", 3) == 0) {
2716 if (strcmp (& argv [argi] [3], "dataset") == 0) {
2717 model = HM_DATASET;
2718 } else if (strcmp (& argv [argi] [3], "sphere") == 0) {
2719 model = HM_SPHERE;
2720 } else {
2721 fprintf (stderr, "Error: Expected 'dataset' or 'sphere' for '-d'.\n");
2722 return (-1);
2724 } else if (strncmp (argv [argi], "-c=", 3) == 0) {
2725 radius = strtod (& argv [argi] [3], & end);
2726 if ((end [0] != '\0') || (radius < MIN_CUSTOM_RADIUS) || (radius > MAX_CUSTOM_RADIUS)) {
2727 fprintf (stderr, "Error: Expected a value from %.2f to %.2f for '-c'.\n", MIN_CUSTOM_RADIUS, MAX_CUSTOM_RADIUS);
2728 return (-1);
2730 } else if (strncmp (argv [argi], "-i=", 3) == 0) {
2731 inName = & argv [argi] [3];
2732 } else if (strncmp (argv [argi], "-o=", 3) == 0) {
2733 outName = & argv [argi] [3];
2734 } else {
2735 fprintf (stderr, "Error: Invalid option '%s'.\n", argv [argi]);
2736 return (-1);
2738 argi ++;
2740 if (! ProcessDefinition (inName, outRate, fftSize, equalize, surface, limit, truncSize, model, radius, outFormat, outName))
2741 return (-1);
2742 fprintf (stdout, "Operation completed.\n");
2743 return (0);