Multiply samples with the cubic coeffs before transposing
[openal-soft.git] / utils / makehrtf.c
blob0a1bd0438992c4d71448e4db5a81c02b18857587
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(size_t n)
776 double *a;
778 if(n == 0) n = 1;
779 a = calloc(n, sizeof(double));
780 if(a == NULL)
782 fprintf(stderr, "Error: Out of memory.\n");
783 exit(-1);
785 return a;
788 // Frees an array of doubles.
789 static void DestroyArray(double *a)
790 { free(a); }
792 // Complex number routines. All outputs must be non-NULL.
794 // Magnitude/absolute value.
795 static double ComplexAbs (const double r, const double i) {
796 return (sqrt ((r * r) + (i * i)));
799 // Multiply.
800 static void ComplexMul (const double aR, const double aI, const double bR, const double bI, double * outR, double * outI) {
801 (* outR) = (aR * bR) - (aI * bI);
802 (* outI) = (aI * bR) + (aR * bI);
805 // Base-e exponent.
806 static void ComplexExp (const double inR, const double inI, double * outR, double * outI) {
807 double e;
809 e = exp (inR);
810 (* outR) = e * cos (inI);
811 (* outI) = e * sin (inI);
814 /* Fast Fourier transform routines. The number of points must be a power of
815 * two. In-place operation is possible only if both the real and imaginary
816 * parts are in-place together.
819 // Performs bit-reversal ordering.
820 static void FftArrange (const uint n, const double * inR, const double * inI, double * outR, double * outI) {
821 uint rk, k, m;
822 double tempR, tempI;
824 if ((inR == outR) && (inI == outI)) {
825 // Handle in-place arrangement.
826 rk = 0;
827 for (k = 0; k < n; k ++) {
828 if (rk > k) {
829 tempR = inR [rk];
830 tempI = inI [rk];
831 outR [rk] = inR [k];
832 outI [rk] = inI [k];
833 outR [k] = tempR;
834 outI [k] = tempI;
836 m = n;
837 while (rk & (m >>= 1))
838 rk &= ~m;
839 rk |= m;
841 } else {
842 // Handle copy arrangement.
843 rk = 0;
844 for (k = 0; k < n; k ++) {
845 outR [rk] = inR [k];
846 outI [rk] = inI [k];
847 m = n;
848 while (rk & (m >>= 1))
849 rk &= ~m;
850 rk |= m;
855 // Performs the summation.
856 static void FftSummation (const uint n, const double s, double * re, double * im) {
857 double pi;
858 uint m, m2;
859 double vR, vI, wR, wI;
860 uint i, k, mk;
861 double tR, tI;
863 pi = s * M_PI;
864 for (m = 1, m2 = 2; m < n; m <<= 1, m2 <<= 1) {
865 // v = Complex (-2.0 * sin (0.5 * pi / m) * sin (0.5 * pi / m), -sin (pi / m))
866 vR = sin (0.5 * pi / m);
867 vR = -2.0 * vR * vR;
868 vI = -sin (pi / m);
869 // w = Complex (1.0, 0.0)
870 wR = 1.0;
871 wI = 0.0;
872 for (i = 0; i < m; i ++) {
873 for (k = i; k < n; k += m2) {
874 mk = k + m;
875 // t = ComplexMul (w, out [km2])
876 tR = (wR * re [mk]) - (wI * im [mk]);
877 tI = (wR * im [mk]) + (wI * re [mk]);
878 // out [mk] = ComplexSub (out [k], t)
879 re [mk] = re [k] - tR;
880 im [mk] = im [k] - tI;
881 // out [k] = ComplexAdd (out [k], t)
882 re [k] += tR;
883 im [k] += tI;
885 // t = ComplexMul (v, w)
886 tR = (vR * wR) - (vI * wI);
887 tI = (vR * wI) + (vI * wR);
888 // w = ComplexAdd (w, t)
889 wR += tR;
890 wI += tI;
895 // Performs a forward FFT.
896 static void FftForward (const uint n, const double * inR, const double * inI, double * outR, double * outI) {
897 FftArrange (n, inR, inI, outR, outI);
898 FftSummation (n, 1.0, outR, outI);
901 // Performs an inverse FFT.
902 static void FftInverse (const uint n, const double * inR, const double * inI, double * outR, double * outI) {
903 double f;
904 uint i;
906 FftArrange (n, inR, inI, outR, outI);
907 FftSummation (n, -1.0, outR, outI);
908 f = 1.0 / n;
909 for (i = 0; i < n; i ++) {
910 outR [i] *= f;
911 outI [i] *= f;
915 /* Calculate the complex helical sequence (or discrete-time analytical
916 * signal) of the given input using the Hilbert transform. Given the
917 * negative natural logarithm of a signal's magnitude response, the imaginary
918 * components can be used as the angles for minimum-phase reconstruction.
920 static void Hilbert (const uint n, const double * in, double * outR, double * outI) {
921 uint i;
923 if (in == outR) {
924 // Handle in-place operation.
925 for (i = 0; i < n; i ++)
926 outI [i] = 0.0;
927 } else {
928 // Handle copy operation.
929 for (i = 0; i < n; i ++) {
930 outR [i] = in [i];
931 outI [i] = 0.0;
934 FftForward (n, outR, outI, outR, outI);
935 /* Currently the Fourier routines operate only on point counts that are
936 * powers of two. If that changes and n is odd, the following conditional
937 * should be: i < (n + 1) / 2.
939 for (i = 1; i < (n / 2); i ++) {
940 outR [i] *= 2.0;
941 outI [i] *= 2.0;
943 // If n is odd, the following increment should be skipped.
944 i ++;
945 for (; i < n; i ++) {
946 outR [i] = 0.0;
947 outI [i] = 0.0;
949 FftInverse (n, outR, outI, outR, outI);
952 /* Calculate the magnitude response of the given input. This is used in
953 * place of phase decomposition, since the phase residuals are discarded for
954 * minimum phase reconstruction. The mirrored half of the response is also
955 * discarded.
957 static void MagnitudeResponse (const uint n, const double * inR, const double * inI, double * out) {
958 const uint m = 1 + (n / 2);
959 uint i;
961 for (i = 0; i < m; i ++)
962 out [i] = fmax (ComplexAbs (inR [i], inI [i]), EPSILON);
965 /* Apply a range limit (in dB) to the given magnitude response. This is used
966 * to adjust the effects of the diffuse-field average on the equalization
967 * process.
969 static void LimitMagnitudeResponse (const uint n, const double limit, const double * in, double * out) {
970 const uint m = 1 + (n / 2);
971 double halfLim;
972 uint i, lower, upper;
973 double ave;
975 halfLim = limit / 2.0;
976 // Convert the response to dB.
977 for (i = 0; i < m; i ++)
978 out [i] = 20.0 * log10 (in [i]);
979 // Use six octaves to calculate the average magnitude of the signal.
980 lower = ((uint) ceil (n / pow (2.0, 8.0))) - 1;
981 upper = ((uint) floor (n / pow (2.0, 2.0))) - 1;
982 ave = 0.0;
983 for (i = lower; i <= upper; i ++)
984 ave += out [i];
985 ave /= upper - lower + 1;
986 // Keep the response within range of the average magnitude.
987 for (i = 0; i < m; i ++)
988 out [i] = Clamp (out [i], ave - halfLim, ave + halfLim);
989 // Convert the response back to linear magnitude.
990 for (i = 0; i < m; i ++)
991 out [i] = pow (10.0, out [i] / 20.0);
994 /* Reconstructs the minimum-phase component for the given magnitude response
995 * of a signal. This is equivalent to phase recomposition, sans the missing
996 * residuals (which were discarded). The mirrored half of the response is
997 * reconstructed.
999 static void MinimumPhase (const uint n, const double * in, double * outR, double * outI) {
1000 const uint m = 1 + (n / 2);
1001 double * mags = NULL;
1002 uint i;
1003 double aR, aI;
1005 mags = CreateArray (n);
1006 for (i = 0; i < m; i ++) {
1007 mags [i] = fmax (in [i], EPSILON);
1008 outR [i] = -log (mags [i]);
1010 for (; i < n; i ++) {
1011 mags [i] = mags [n - i];
1012 outR [i] = outR [n - i];
1014 Hilbert (n, outR, outR, outI);
1015 // Remove any DC offset the filter has.
1016 outR [0] = 0.0;
1017 outI [0] = 0.0;
1018 for (i = 1; i < n; i ++) {
1019 ComplexExp (0.0, outI [i], & aR, & aI);
1020 ComplexMul (mags [i], 0.0, aR, aI, & outR [i], & outI [i]);
1022 DestroyArray (mags);
1025 /* This is the normalized cardinal sine (sinc) function.
1027 * sinc(x) = { 1, x = 0
1028 * { sin(pi x) / (pi x), otherwise.
1030 static double Sinc (const double x) {
1031 if (fabs (x) < EPSILON)
1032 return (1.0);
1033 return (sin (M_PI * x) / (M_PI * x));
1036 /* The zero-order modified Bessel function of the first kind, used for the
1037 * Kaiser window.
1039 * I_0(x) = sum_{k=0}^inf (1 / k!)^2 (x / 2)^(2 k)
1040 * = sum_{k=0}^inf ((x / 2)^k / k!)^2
1042 static double BesselI_0 (const double x) {
1043 double term, sum, x2, y, last_sum;
1044 int k;
1046 // Start at k=1 since k=0 is trivial.
1047 term = 1.0;
1048 sum = 1.0;
1049 x2 = x / 2.0;
1050 k = 1;
1051 // Let the integration converge until the term of the sum is no longer
1052 // significant.
1053 do {
1054 y = x2 / k;
1055 k ++;
1056 last_sum = sum;
1057 term *= y * y;
1058 sum += term;
1059 } while (sum != last_sum);
1060 return (sum);
1063 /* Calculate a Kaiser window from the given beta value and a normalized k
1064 * [-1, 1].
1066 * w(k) = { I_0(B sqrt(1 - k^2)) / I_0(B), -1 <= k <= 1
1067 * { 0, elsewhere.
1069 * Where k can be calculated as:
1071 * k = i / l, where -l <= i <= l.
1073 * or:
1075 * k = 2 i / M - 1, where 0 <= i <= M.
1077 static double Kaiser (const double b, const double k) {
1078 double k2;
1080 k2 = Clamp (k, -1.0, 1.0);
1081 if ((k < -1.0) || (k > 1.0))
1082 return (0.0);
1083 k2 *= k2;
1084 return (BesselI_0 (b * sqrt (1.0 - k2)) / BesselI_0 (b));
1087 // Calculates the greatest common divisor of a and b.
1088 static uint Gcd (const uint a, const uint b) {
1089 uint x, y, z;
1091 x = a;
1092 y = b;
1093 while (y > 0) {
1094 z = y;
1095 y = x % y;
1096 x = z;
1098 return (x);
1101 /* Calculates the size (order) of the Kaiser window. Rejection is in dB and
1102 * the transition width is normalized frequency (0.5 is nyquist).
1104 * M = { ceil((r - 7.95) / (2.285 2 pi f_t)), r > 21
1105 * { ceil(5.79 / 2 pi f_t), r <= 21.
1108 static uint CalcKaiserOrder (const double rejection, const double transition) {
1109 double w_t;
1111 w_t = 2.0 * M_PI * transition;
1112 if (rejection > 21.0)
1113 return ((uint) ceil ((rejection - 7.95) / (2.285 * w_t)));
1114 return ((uint) ceil (5.79 / w_t));
1117 // Calculates the beta value of the Kaiser window. Rejection is in dB.
1118 static double CalcKaiserBeta (const double rejection) {
1119 if (rejection > 50.0)
1120 return (0.1102 * (rejection - 8.7));
1121 else if (rejection >= 21.0)
1122 return ((0.5842 * pow (rejection - 21.0, 0.4)) +
1123 (0.07886 * (rejection - 21.0)));
1124 else
1125 return (0.0);
1128 /* Calculates a point on the Kaiser-windowed sinc filter for the given half-
1129 * width, beta, gain, and cutoff. The point is specified in non-normalized
1130 * samples, from 0 to M, where M = (2 l + 1).
1132 * w(k) 2 p f_t sinc(2 f_t x)
1134 * x -- centered sample index (i - l)
1135 * k -- normalized and centered window index (x / l)
1136 * w(k) -- window function (Kaiser)
1137 * p -- gain compensation factor when sampling
1138 * f_t -- normalized center frequency (or cutoff; 0.5 is nyquist)
1140 static double SincFilter (const int l, const double b, const double gain, const double cutoff, const int i) {
1141 return (Kaiser (b, ((double) (i - l)) / l) * 2.0 * gain * cutoff * Sinc (2.0 * cutoff * (i - l)));
1144 /* This is a polyphase sinc-filtered resampler.
1146 * Upsample Downsample
1148 * p/q = 3/2 p/q = 3/5
1150 * M-+-+-+-> M-+-+-+->
1151 * -------------------+ ---------------------+
1152 * p s * f f f f|f| | p s * f f f f f |
1153 * | 0 * 0 0 0|0|0 | | 0 * 0 0 0 0|0| |
1154 * v 0 * 0 0|0|0 0 | v 0 * 0 0 0|0|0 |
1155 * s * f|f|f f f | s * f f|f|f f |
1156 * 0 * |0|0 0 0 0 | 0 * 0|0|0 0 0 |
1157 * --------+=+--------+ 0 * |0|0 0 0 0 |
1158 * d . d .|d|. d . d ----------+=+--------+
1159 * d . . . .|d|. . . .
1160 * q->
1161 * q-+-+-+->
1163 * P_f(i,j) = q i mod p + pj
1164 * P_s(i,j) = floor(q i / p) - j
1165 * d[i=0..N-1] = sum_{j=0}^{floor((M - 1) / p)} {
1166 * { f[P_f(i,j)] s[P_s(i,j)], P_f(i,j) < M
1167 * { 0, P_f(i,j) >= M. }
1170 // Calculate the resampling metrics and build the Kaiser-windowed sinc filter
1171 // that's used to cut frequencies above the destination nyquist.
1172 static void ResamplerSetup (ResamplerT * rs, const uint srcRate, const uint dstRate) {
1173 uint gcd, l;
1174 double cutoff, width, beta;
1175 int i;
1177 gcd = Gcd (srcRate, dstRate);
1178 rs -> mP = dstRate / gcd;
1179 rs -> mQ = srcRate / gcd;
1180 /* The cutoff is adjusted by half the transition width, so the transition
1181 * ends before the nyquist (0.5). Both are scaled by the downsampling
1182 * factor.
1184 if (rs -> mP > rs -> mQ) {
1185 cutoff = 0.45 / rs -> mP;
1186 width = 0.1 / rs -> mP;
1187 } else {
1188 cutoff = 0.45 / rs -> mQ;
1189 width = 0.1 / rs -> mQ;
1191 // A rejection of -180 dB is used for the stop band.
1192 l = CalcKaiserOrder (180.0, width) / 2;
1193 beta = CalcKaiserBeta (180.0);
1194 rs -> mM = (2 * l) + 1;
1195 rs -> mL = l;
1196 rs -> mF = CreateArray (rs -> mM);
1197 for (i = 0; i < ((int) rs -> mM); i ++)
1198 rs -> mF [i] = SincFilter ((int) l, beta, rs -> mP, cutoff, i);
1201 // Clean up after the resampler.
1202 static void ResamplerClear (ResamplerT * rs) {
1203 DestroyArray (rs -> mF);
1204 rs -> mF = NULL;
1207 // Perform the upsample-filter-downsample resampling operation using a
1208 // polyphase filter implementation.
1209 static void ResamplerRun (ResamplerT * rs, const uint inN, const double * in, const uint outN, double * out) {
1210 const uint p = rs -> mP, q = rs -> mQ, m = rs -> mM, l = rs -> mL;
1211 const double * f = rs -> mF;
1212 double * work = NULL;
1213 uint i;
1214 double r;
1215 uint j_f, j_s;
1217 if (outN == 0)
1218 return;
1220 // Handle in-place operation.
1221 if (in == out)
1222 work = CreateArray (outN);
1223 else
1224 work = out;
1225 // Resample the input.
1226 for (i = 0; i < outN; i ++) {
1227 r = 0.0;
1228 // Input starts at l to compensate for the filter delay. This will
1229 // drop any build-up from the first half of the filter.
1230 j_f = (l + (q * i)) % p;
1231 j_s = (l + (q * i)) / p;
1232 while (j_f < m) {
1233 // Only take input when 0 <= j_s < inN. This single unsigned
1234 // comparison catches both cases.
1235 if (j_s < inN)
1236 r += f [j_f] * in [j_s];
1237 j_f += p;
1238 j_s --;
1240 work [i] = r;
1242 // Clean up after in-place operation.
1243 if (in == out) {
1244 for (i = 0; i < outN; i ++)
1245 out [i] = work [i];
1246 DestroyArray (work);
1250 // Read a binary value of the specified byte order and byte size from a file,
1251 // storing it as a 32-bit unsigned integer.
1252 static int ReadBin4 (FILE * fp, const char * filename, const ByteOrderT order, const uint bytes, uint32 * out) {
1253 uint8 in [4];
1254 uint32 accum;
1255 uint i;
1257 if (fread (in, 1, bytes, fp) != bytes) {
1258 fprintf (stderr, "Error: Bad read from file '%s'.\n", filename);
1259 return (0);
1261 accum = 0;
1262 switch (order) {
1263 case BO_LITTLE :
1264 for (i = 0; i < bytes; i ++)
1265 accum = (accum << 8) | in [bytes - i - 1];
1266 break;
1267 case BO_BIG :
1268 for (i = 0; i < bytes; i ++)
1269 accum = (accum << 8) | in [i];
1270 break;
1271 default :
1272 break;
1274 (* out) = accum;
1275 return (1);
1278 // Read a binary value of the specified byte order from a file, storing it as
1279 // a 64-bit unsigned integer.
1280 static int ReadBin8 (FILE * fp, const char * filename, const ByteOrderT order, uint64 * out) {
1281 uint8 in [8];
1282 uint64 accum;
1283 uint i;
1285 if (fread (in, 1, 8, fp) != 8) {
1286 fprintf (stderr, "Error: Bad read from file '%s'.\n", filename);
1287 return (0);
1289 accum = 0ULL;
1290 switch (order) {
1291 case BO_LITTLE :
1292 for (i = 0; i < 8; i ++)
1293 accum = (accum << 8) | in [8 - i - 1];
1294 break;
1295 case BO_BIG :
1296 for (i = 0; i < 8; i ++)
1297 accum = (accum << 8) | in [i];
1298 break;
1299 default :
1300 break;
1302 (* out) = accum;
1303 return (1);
1306 // Write an ASCII string to a file.
1307 static int WriteAscii (const char * out, FILE * fp, const char * filename) {
1308 size_t len;
1310 len = strlen (out);
1311 if (fwrite (out, 1, len, fp) != len) {
1312 fclose (fp);
1313 fprintf (stderr, "Error: Bad write to file '%s'.\n", filename);
1314 return (0);
1316 return (1);
1319 // Write a binary value of the given byte order and byte size to a file,
1320 // loading it from a 32-bit unsigned integer.
1321 static int WriteBin4 (const ByteOrderT order, const uint bytes, const uint32 in, FILE * fp, const char * filename) {
1322 uint8 out [4];
1323 uint i;
1325 switch (order) {
1326 case BO_LITTLE :
1327 for (i = 0; i < bytes; i ++)
1328 out [i] = (in >> (i * 8)) & 0x000000FF;
1329 break;
1330 case BO_BIG :
1331 for (i = 0; i < bytes; i ++)
1332 out [bytes - i - 1] = (in >> (i * 8)) & 0x000000FF;
1333 break;
1334 default :
1335 break;
1337 if (fwrite (out, 1, bytes, fp) != bytes) {
1338 fprintf (stderr, "Error: Bad write to file '%s'.\n", filename);
1339 return (0);
1341 return (1);
1344 /* Read a binary value of the specified type, byte order, and byte size from
1345 * a file, converting it to a double. For integer types, the significant
1346 * bits are used to normalize the result. The sign of bits determines
1347 * whether they are padded toward the MSB (negative) or LSB (positive).
1348 * Floating-point types are not normalized.
1350 static int ReadBinAsDouble (FILE * fp, const char * filename, const ByteOrderT order, const ElementTypeT type, const uint bytes, const int bits, double * out) {
1351 union {
1352 uint32 ui;
1353 int32 i;
1354 float f;
1355 } v4;
1356 union {
1357 uint64 ui;
1358 double f;
1359 } v8;
1361 (* out) = 0.0;
1362 if (bytes > 4) {
1363 if (! ReadBin8 (fp, filename, order, & v8 . ui))
1364 return (0);
1365 if (type == ET_FP)
1366 (* out) = v8 . f;
1367 } else {
1368 if (! ReadBin4 (fp, filename, order, bytes, & v4 . ui))
1369 return (0);
1370 if (type == ET_FP) {
1371 (* out) = (double) v4 . f;
1372 } else {
1373 if (bits > 0)
1374 v4 . ui >>= (8 * bytes) - ((uint) bits);
1375 else
1376 v4 . ui &= (0xFFFFFFFF >> (32 + bits));
1377 if (v4 . ui & ((uint) (1 << (abs (bits) - 1))))
1378 v4 . ui |= (0xFFFFFFFF << abs (bits));
1379 (* out) = v4 . i / ((double) (1 << (abs (bits) - 1)));
1382 return (1);
1385 /* Read an ascii value of the specified type from a file, converting it to a
1386 * double. For integer types, the significant bits are used to normalize the
1387 * result. The sign of the bits should always be positive. This also skips
1388 * up to one separator character before the element itself.
1390 static int ReadAsciiAsDouble (TokenReaderT * tr, const char * filename, const ElementTypeT type, const uint bits, double * out) {
1391 int v;
1393 if (TrIsOperator (tr, ","))
1394 TrReadOperator (tr, ",");
1395 else if (TrIsOperator (tr, ":"))
1396 TrReadOperator (tr, ":");
1397 else if (TrIsOperator (tr, ";"))
1398 TrReadOperator (tr, ";");
1399 else if (TrIsOperator (tr, "|"))
1400 TrReadOperator (tr, "|");
1401 if (type == ET_FP) {
1402 if (! TrReadFloat (tr, -HUGE_VAL, HUGE_VAL, out)) {
1403 fprintf (stderr, "Error: Bad read from file '%s'.\n", filename);
1404 return (0);
1406 } else {
1407 if (! TrReadInt (tr, -(1 << (bits - 1)), (1 << (bits - 1)) - 1, & v)) {
1408 fprintf (stderr, "Error: Bad read from file '%s'.\n", filename);
1409 return (0);
1411 (* out) = v / ((double) ((1 << (bits - 1)) - 1));
1413 return (1);
1416 // Read the RIFF/RIFX WAVE format chunk from a file, validating it against
1417 // the source parameters and data set metrics.
1418 static int ReadWaveFormat (FILE * fp, const ByteOrderT order, const uint hrirRate, SourceRefT * src) {
1419 uint32 fourCC, chunkSize;
1420 uint32 format, channels, rate, dummy, block, size, bits;
1422 chunkSize = 0;
1423 do {
1424 if (chunkSize > 0)
1425 fseek (fp, (long) chunkSize, SEEK_CUR);
1426 if ((! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & fourCC)) ||
1427 (! ReadBin4 (fp, src -> mPath, order, 4, & chunkSize)))
1428 return (0);
1429 } while (fourCC != FOURCC_FMT);
1430 if ((! ReadBin4 (fp, src -> mPath, order, 2, & format)) ||
1431 (! ReadBin4 (fp, src -> mPath, order, 2, & channels)) ||
1432 (! ReadBin4 (fp, src -> mPath, order, 4, & rate)) ||
1433 (! ReadBin4 (fp, src -> mPath, order, 4, & dummy)) ||
1434 (! ReadBin4 (fp, src -> mPath, order, 2, & block)))
1435 return (0);
1436 block /= channels;
1437 if (chunkSize > 14) {
1438 if (! ReadBin4 (fp, src -> mPath, order, 2, & size))
1439 return (0);
1440 size /= 8;
1441 if (block > size)
1442 size = block;
1443 } else {
1444 size = block;
1446 if (format == WAVE_FORMAT_EXTENSIBLE) {
1447 fseek (fp, 2, SEEK_CUR);
1448 if (! ReadBin4 (fp, src -> mPath, order, 2, & bits))
1449 return (0);
1450 if (bits == 0)
1451 bits = 8 * size;
1452 fseek (fp, 4, SEEK_CUR);
1453 if (! ReadBin4 (fp, src -> mPath, order, 2, & format))
1454 return (0);
1455 fseek (fp, (long) (chunkSize - 26), SEEK_CUR);
1456 } else {
1457 bits = 8 * size;
1458 if (chunkSize > 14)
1459 fseek (fp, (long) (chunkSize - 16), SEEK_CUR);
1460 else
1461 fseek (fp, (long) (chunkSize - 14), SEEK_CUR);
1463 if ((format != WAVE_FORMAT_PCM) && (format != WAVE_FORMAT_IEEE_FLOAT)) {
1464 fprintf (stderr, "Error: Unsupported WAVE format in file '%s'.\n", src -> mPath);
1465 return (0);
1467 if (src -> mChannel >= channels) {
1468 fprintf (stderr, "Error: Missing source channel in WAVE file '%s'.\n", src -> mPath);
1469 return (0);
1471 if (rate != hrirRate) {
1472 fprintf (stderr, "Error: Mismatched source sample rate in WAVE file '%s'.\n", src -> mPath);
1473 return (0);
1475 if (format == WAVE_FORMAT_PCM) {
1476 if ((size < 2) || (size > 4)) {
1477 fprintf (stderr, "Error: Unsupported sample size in WAVE file '%s'.\n", src -> mPath);
1478 return (0);
1480 if ((bits < 16) || (bits > (8 * size))) {
1481 fprintf (stderr, "Error: Bad significant bits in WAVE file '%s'.\n", src -> mPath);
1482 return (0);
1484 src -> mType = ET_INT;
1485 } else {
1486 if ((size != 4) && (size != 8)) {
1487 fprintf (stderr, "Error: Unsupported sample size in WAVE file '%s'.\n", src -> mPath);
1488 return (0);
1490 src -> mType = ET_FP;
1492 src -> mSize = size;
1493 src -> mBits = (int) bits;
1494 src -> mSkip = channels;
1495 return (1);
1498 // Read a RIFF/RIFX WAVE data chunk, converting all elements to doubles.
1499 static int ReadWaveData (FILE * fp, const SourceRefT * src, const ByteOrderT order, const uint n, double * hrir) {
1500 int pre, post, skip;
1501 uint i;
1503 pre = (int) (src -> mSize * src -> mChannel);
1504 post = (int) (src -> mSize * (src -> mSkip - src -> mChannel - 1));
1505 skip = 0;
1506 for (i = 0; i < n; i ++) {
1507 skip += pre;
1508 if (skip > 0)
1509 fseek (fp, skip, SEEK_CUR);
1510 if (! ReadBinAsDouble (fp, src -> mPath, order, src -> mType, src -> mSize, src -> mBits, & hrir [i]))
1511 return (0);
1512 skip = post;
1514 if (skip > 0)
1515 fseek (fp, skip, SEEK_CUR);
1516 return (1);
1519 // Read the RIFF/RIFX WAVE list or data chunk, converting all elements to
1520 // doubles.
1521 static int ReadWaveList (FILE * fp, const SourceRefT * src, const ByteOrderT order, const uint n, double * hrir) {
1522 uint32 fourCC, chunkSize, listSize, count;
1523 uint block, skip, offset, i;
1524 double lastSample;
1526 for (;;) {
1527 if ((! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & fourCC)) ||
1528 (! ReadBin4 (fp, src -> mPath, order, 4, & chunkSize)))
1529 return (0);
1530 if (fourCC == FOURCC_DATA) {
1531 block = src -> mSize * src -> mSkip;
1532 count = chunkSize / block;
1533 if (count < (src -> mOffset + n)) {
1534 fprintf (stderr, "Error: Bad read from file '%s'.\n", src -> mPath);
1535 return (0);
1537 fseek (fp, (long) (src -> mOffset * block), SEEK_CUR);
1538 if (! ReadWaveData (fp, src, order, n, & hrir [0]))
1539 return (0);
1540 return (1);
1541 } else if (fourCC == FOURCC_LIST) {
1542 if (! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & fourCC))
1543 return (0);
1544 chunkSize -= 4;
1545 if (fourCC == FOURCC_WAVL)
1546 break;
1548 if (chunkSize > 0)
1549 fseek (fp, (long) chunkSize, SEEK_CUR);
1551 listSize = chunkSize;
1552 block = src -> mSize * src -> mSkip;
1553 skip = src -> mOffset;
1554 offset = 0;
1555 lastSample = 0.0;
1556 while ((offset < n) && (listSize > 8)) {
1557 if ((! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & fourCC)) ||
1558 (! ReadBin4 (fp, src -> mPath, order, 4, & chunkSize)))
1559 return (0);
1560 listSize -= 8 + chunkSize;
1561 if (fourCC == FOURCC_DATA) {
1562 count = chunkSize / block;
1563 if (count > skip) {
1564 fseek (fp, (long) (skip * block), SEEK_CUR);
1565 chunkSize -= skip * block;
1566 count -= skip;
1567 skip = 0;
1568 if (count > (n - offset))
1569 count = n - offset;
1570 if (! ReadWaveData (fp, src, order, count, & hrir [offset]))
1571 return (0);
1572 chunkSize -= count * block;
1573 offset += count;
1574 lastSample = hrir [offset - 1];
1575 } else {
1576 skip -= count;
1577 count = 0;
1579 } else if (fourCC == FOURCC_SLNT) {
1580 if (! ReadBin4 (fp, src -> mPath, order, 4, & count))
1581 return (0);
1582 chunkSize -= 4;
1583 if (count > skip) {
1584 count -= skip;
1585 skip = 0;
1586 if (count > (n - offset))
1587 count = n - offset;
1588 for (i = 0; i < count; i ++)
1589 hrir [offset + i] = lastSample;
1590 offset += count;
1591 } else {
1592 skip -= count;
1593 count = 0;
1596 if (chunkSize > 0)
1597 fseek (fp, (long) chunkSize, SEEK_CUR);
1599 if (offset < n) {
1600 fprintf (stderr, "Error: Bad read from file '%s'.\n", src -> mPath);
1601 return (0);
1603 return (1);
1606 // Load a source HRIR from a RIFF/RIFX WAVE file.
1607 static int LoadWaveSource (FILE * fp, SourceRefT * src, const uint hrirRate, const uint n, double * hrir) {
1608 uint32 fourCC, dummy;
1609 ByteOrderT order;
1611 if ((! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & fourCC)) ||
1612 (! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & dummy)))
1613 return (0);
1614 if (fourCC == FOURCC_RIFF) {
1615 order = BO_LITTLE;
1616 } else if (fourCC == FOURCC_RIFX) {
1617 order = BO_BIG;
1618 } else {
1619 fprintf (stderr, "Error: No RIFF/RIFX chunk in file '%s'.\n", src -> mPath);
1620 return (0);
1622 if (! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & fourCC))
1623 return (0);
1624 if (fourCC != FOURCC_WAVE) {
1625 fprintf (stderr, "Error: Not a RIFF/RIFX WAVE file '%s'.\n", src -> mPath);
1626 return (0);
1628 if (! ReadWaveFormat (fp, order, hrirRate, src))
1629 return (0);
1630 if (! ReadWaveList (fp, src, order, n, hrir))
1631 return (0);
1632 return (1);
1635 // Load a source HRIR from a binary file.
1636 static int LoadBinarySource (FILE * fp, const SourceRefT * src, const ByteOrderT order, const uint n, double * hrir) {
1637 uint i;
1639 fseek (fp, (long) src -> mOffset, SEEK_SET);
1640 for (i = 0; i < n; i ++) {
1641 if (! ReadBinAsDouble (fp, src -> mPath, order, src -> mType, src -> mSize, src -> mBits, & hrir [i]))
1642 return (0);
1643 if (src -> mSkip > 0)
1644 fseek (fp, (long) src -> mSkip, SEEK_CUR);
1646 return (1);
1649 // Load a source HRIR from an ASCII text file containing a list of elements
1650 // separated by whitespace or common list operators (',', ';', ':', '|').
1651 static int LoadAsciiSource (FILE * fp, const SourceRefT * src, const uint n, double * hrir) {
1652 TokenReaderT tr;
1653 uint i, j;
1654 double dummy;
1656 TrSetup (fp, NULL, & tr);
1657 for (i = 0; i < src -> mOffset; i ++) {
1658 if (! ReadAsciiAsDouble (& tr, src -> mPath, src -> mType, (uint) src -> mBits, & dummy))
1659 return (0);
1661 for (i = 0; i < n; i ++) {
1662 if (! ReadAsciiAsDouble (& tr, src -> mPath, src -> mType, (uint) src -> mBits, & hrir [i]))
1663 return (0);
1664 for (j = 0; j < src -> mSkip; j ++) {
1665 if (! ReadAsciiAsDouble (& tr, src -> mPath, src -> mType, (uint) src -> mBits, & dummy))
1666 return (0);
1669 return (1);
1672 // Load a source HRIR from a supported file type.
1673 static int LoadSource (SourceRefT * src, const uint hrirRate, const uint n, double * hrir) {
1674 FILE * fp = NULL;
1675 int result;
1677 if (src -> mFormat == SF_ASCII)
1678 fp = fopen (src -> mPath, "r");
1679 else
1680 fp = fopen (src -> mPath, "rb");
1681 if (fp == NULL) {
1682 fprintf (stderr, "Error: Could not open source file '%s'.\n", src -> mPath);
1683 return (0);
1685 if (src -> mFormat == SF_WAVE)
1686 result = LoadWaveSource (fp, src, hrirRate, n, hrir);
1687 else if (src -> mFormat == SF_BIN_LE)
1688 result = LoadBinarySource (fp, src, BO_LITTLE, n, hrir);
1689 else if (src -> mFormat == SF_BIN_BE)
1690 result = LoadBinarySource (fp, src, BO_BIG, n, hrir);
1691 else
1692 result = LoadAsciiSource (fp, src, n, hrir);
1693 fclose (fp);
1694 return (result);
1697 // Calculate the onset time of an HRIR and average it with any existing
1698 // timing for its elevation and azimuth.
1699 static void AverageHrirOnset (const double * hrir, const double f, const uint ei, const uint ai, const HrirDataT * hData) {
1700 double mag;
1701 uint n, i, j;
1703 mag = 0.0;
1704 n = hData -> mIrPoints;
1705 for (i = 0; i < n; i ++)
1706 mag = fmax (fabs (hrir [i]), mag);
1707 mag *= 0.15;
1708 for (i = 0; i < n; i ++) {
1709 if (fabs (hrir [i]) >= mag)
1710 break;
1712 j = hData -> mEvOffset [ei] + ai;
1713 hData -> mHrtds [j] = Lerp (hData -> mHrtds [j], ((double) i) / hData -> mIrRate, f);
1716 // Calculate the magnitude response of an HRIR and average it with any
1717 // existing responses for its elevation and azimuth.
1718 static void AverageHrirMagnitude (const double * hrir, const double f, const uint ei, const uint ai, const HrirDataT * hData) {
1719 double * re = NULL, * im = NULL;
1720 uint n, m, i, j;
1722 n = hData -> mFftSize;
1723 re = CreateArray (n);
1724 im = CreateArray (n);
1725 for (i = 0; i < hData -> mIrPoints; i ++) {
1726 re [i] = hrir [i];
1727 im [i] = 0.0;
1729 for (; i < n; i ++) {
1730 re [i] = 0.0;
1731 im [i] = 0.0;
1733 FftForward (n, re, im, re, im);
1734 MagnitudeResponse (n, re, im, re);
1735 m = 1 + (n / 2);
1736 j = (hData -> mEvOffset [ei] + ai) * hData -> mIrSize;
1737 for (i = 0; i < m; i ++)
1738 hData -> mHrirs [j + i] = Lerp (hData -> mHrirs [j + i], re [i], f);
1739 DestroyArray (im);
1740 DestroyArray (re);
1743 /* Calculate the contribution of each HRIR to the diffuse-field average based
1744 * on the area of its surface patch. All patches are centered at the HRIR
1745 * coordinates on the unit sphere and are measured by solid angle.
1747 static void CalculateDfWeights (const HrirDataT * hData, double * weights) {
1748 uint ei;
1749 double evs, sum, ev, up_ev, down_ev, solidAngle;
1751 evs = 90.0 / (hData -> mEvCount - 1);
1752 sum = 0.0;
1753 for (ei = hData -> mEvStart; ei < hData -> mEvCount; ei ++) {
1754 // For each elevation, calculate the upper and lower limits of the
1755 // patch band.
1756 ev = -90.0 + (ei * 2.0 * evs);
1757 if (ei < (hData -> mEvCount - 1))
1758 up_ev = (ev + evs) * M_PI / 180.0;
1759 else
1760 up_ev = M_PI / 2.0;
1761 if (ei > 0)
1762 down_ev = (ev - evs) * M_PI / 180.0;
1763 else
1764 down_ev = -M_PI / 2.0;
1765 // Calculate the area of the patch band.
1766 solidAngle = 2.0 * M_PI * (sin (up_ev) - sin (down_ev));
1767 // Each weight is the area of one patch.
1768 weights [ei] = solidAngle / hData -> mAzCount [ei];
1769 // Sum the total surface area covered by the HRIRs.
1770 sum += solidAngle;
1772 // Normalize the weights given the total surface coverage.
1773 for (ei = hData -> mEvStart; ei < hData -> mEvCount; ei ++)
1774 weights [ei] /= sum;
1777 /* Calculate the diffuse-field average from the given magnitude responses of
1778 * the HRIR set. Weighting can be applied to compensate for the varying
1779 * surface area covered by each HRIR. The final average can then be limited
1780 * by the specified magnitude range (in positive dB; 0.0 to skip).
1782 static void CalculateDiffuseFieldAverage (const HrirDataT * hData, const int weighted, const double limit, double * dfa) {
1783 double * weights = NULL;
1784 uint ei, ai, count, step, start, end, m, j, i;
1785 double weight;
1787 weights = CreateArray (hData -> mEvCount);
1788 if (weighted) {
1789 // Use coverage weighting to calculate the average.
1790 CalculateDfWeights (hData, weights);
1791 } else {
1792 // If coverage weighting is not used, the weights still need to be
1793 // averaged by the number of HRIRs.
1794 count = 0;
1795 for (ei = hData -> mEvStart; ei < hData -> mEvCount; ei ++)
1796 count += hData -> mAzCount [ei];
1797 for (ei = hData -> mEvStart; ei < hData -> mEvCount; ei ++)
1798 weights [ei] = 1.0 / count;
1800 ei = hData -> mEvStart;
1801 ai = 0;
1802 step = hData -> mIrSize;
1803 start = hData -> mEvOffset [ei] * step;
1804 end = hData -> mIrCount * step;
1805 m = 1 + (hData -> mFftSize / 2);
1806 for (i = 0; i < m; i ++)
1807 dfa [i] = 0.0;
1808 for (j = start; j < end; j += step) {
1809 // Get the weight for this HRIR's contribution.
1810 weight = weights [ei];
1811 // Add this HRIR's weighted power average to the total.
1812 for (i = 0; i < m; i ++)
1813 dfa [i] += weight * hData -> mHrirs [j + i] * hData -> mHrirs [j + i];
1814 // Determine the next weight to use.
1815 ai ++;
1816 if (ai >= hData -> mAzCount [ei]) {
1817 ei ++;
1818 ai = 0;
1821 // Finish the average calculation and keep it from being too small.
1822 for (i = 0; i < m; i ++)
1823 dfa [i] = fmax (sqrt (dfa [i]), EPSILON);
1824 // Apply a limit to the magnitude range of the diffuse-field average if
1825 // desired.
1826 if (limit > 0.0)
1827 LimitMagnitudeResponse (hData -> mFftSize, limit, dfa, dfa);
1828 DestroyArray (weights);
1831 // Perform diffuse-field equalization on the magnitude responses of the HRIR
1832 // set using the given average response.
1833 static void DiffuseFieldEqualize (const double * dfa, const HrirDataT * hData) {
1834 uint step, start, end, m, j, i;
1836 step = hData -> mIrSize;
1837 start = hData -> mEvOffset [hData -> mEvStart] * step;
1838 end = hData -> mIrCount * step;
1839 m = 1 + (hData -> mFftSize / 2);
1840 for (j = start; j < end; j += step) {
1841 for (i = 0; i < m; i ++)
1842 hData -> mHrirs [j + i] /= dfa [i];
1846 // Perform minimum-phase reconstruction using the magnitude responses of the
1847 // HRIR set.
1848 static void ReconstructHrirs (const HrirDataT * hData) {
1849 double * re = NULL, * im = NULL;
1850 uint step, start, end, n, j, i;
1852 step = hData -> mIrSize;
1853 start = hData -> mEvOffset [hData -> mEvStart] * step;
1854 end = hData -> mIrCount * step;
1855 n = hData -> mFftSize;
1856 re = CreateArray (n);
1857 im = CreateArray (n);
1858 for (j = start; j < end; j += step) {
1859 MinimumPhase (n, & hData -> mHrirs [j], re, im);
1860 FftInverse (n, re, im, re, im);
1861 for (i = 0; i < hData -> mIrPoints; i ++)
1862 hData -> mHrirs [j + i] = re [i];
1864 DestroyArray (im);
1865 DestroyArray (re);
1868 // Resamples the HRIRs for use at the given sampling rate.
1869 static void ResampleHrirs (const uint rate, HrirDataT * hData) {
1870 ResamplerT rs;
1871 uint n, step, start, end, j;
1873 ResamplerSetup (& rs, hData -> mIrRate, rate);
1874 n = hData -> mIrPoints;
1875 step = hData -> mIrSize;
1876 start = hData -> mEvOffset [hData -> mEvStart] * step;
1877 end = hData -> mIrCount * step;
1878 for (j = start; j < end; j += step)
1879 ResamplerRun (& rs, n, & hData -> mHrirs [j], n, & hData -> mHrirs [j]);
1880 ResamplerClear (& rs);
1881 hData -> mIrRate = rate;
1884 /* Given an elevation index and an azimuth, calculate the indices of the two
1885 * HRIRs that bound the coordinate along with a factor for calculating the
1886 * continous HRIR using interpolation.
1888 static void CalcAzIndices (const HrirDataT * hData, const uint ei, const double az, uint * j0, uint * j1, double * jf) {
1889 double af;
1890 uint ai;
1892 af = ((2.0 * M_PI) + az) * hData -> mAzCount [ei] / (2.0 * M_PI);
1893 ai = ((uint) af) % hData -> mAzCount [ei];
1894 af -= floor (af);
1895 (* j0) = hData -> mEvOffset [ei] + ai;
1896 (* j1) = hData -> mEvOffset [ei] + ((ai + 1) % hData -> mAzCount [ei]);
1897 (* jf) = af;
1900 // Synthesize any missing onset timings at the bottom elevations. This just
1901 // blends between slightly exaggerated known onsets. Not an accurate model.
1902 static void SynthesizeOnsets (HrirDataT * hData) {
1903 uint oi, e, a, j0, j1;
1904 double t, of, jf;
1906 oi = hData -> mEvStart;
1907 t = 0.0;
1908 for (a = 0; a < hData -> mAzCount [oi]; a ++)
1909 t += hData -> mHrtds [hData -> mEvOffset [oi] + a];
1910 hData -> mHrtds [0] = 1.32e-4 + (t / hData -> mAzCount [oi]);
1911 for (e = 1; e < hData -> mEvStart; e ++) {
1912 of = ((double) e) / hData -> mEvStart;
1913 for (a = 0; a < hData -> mAzCount [e]; a ++) {
1914 CalcAzIndices (hData, oi, a * 2.0 * M_PI / hData -> mAzCount [e], & j0, & j1, & jf);
1915 hData -> mHrtds [hData -> mEvOffset [e] + a] = Lerp (hData -> mHrtds [0], Lerp (hData -> mHrtds [j0], hData -> mHrtds [j1], jf), of);
1920 /* Attempt to synthesize any missing HRIRs at the bottom elevations. Right
1921 * now this just blends the lowest elevation HRIRs together and applies some
1922 * attenuation and high frequency damping. It is a simple, if inaccurate
1923 * model.
1925 static void SynthesizeHrirs (HrirDataT * hData) {
1926 uint oi, a, e, step, n, i, j;
1927 double of, b;
1928 uint j0, j1;
1929 double jf;
1930 double lp [4], s0, s1;
1932 if (hData -> mEvStart <= 0)
1933 return;
1934 step = hData -> mIrSize;
1935 oi = hData -> mEvStart;
1936 n = hData -> mIrPoints;
1937 for (i = 0; i < n; i ++)
1938 hData -> mHrirs [i] = 0.0;
1939 for (a = 0; a < hData -> mAzCount [oi]; a ++) {
1940 j = (hData -> mEvOffset [oi] + a) * step;
1941 for (i = 0; i < n; i ++)
1942 hData -> mHrirs [i] += hData -> mHrirs [j + i] / hData -> mAzCount [oi];
1944 for (e = 1; e < hData -> mEvStart; e ++) {
1945 of = ((double) e) / hData -> mEvStart;
1946 b = (1.0 - of) * (3.5e-6 * hData -> mIrRate);
1947 for (a = 0; a < hData -> mAzCount [e]; a ++) {
1948 j = (hData -> mEvOffset [e] + a) * step;
1949 CalcAzIndices (hData, oi, a * 2.0 * M_PI / hData -> mAzCount [e], & j0, & j1, & jf);
1950 j0 *= step;
1951 j1 *= step;
1952 lp [0] = 0.0;
1953 lp [1] = 0.0;
1954 lp [2] = 0.0;
1955 lp [3] = 0.0;
1956 for (i = 0; i < n; i ++) {
1957 s0 = hData -> mHrirs [i];
1958 s1 = Lerp (hData -> mHrirs [j0 + i], hData -> mHrirs [j1 + i], jf);
1959 s0 = Lerp (s0, s1, of);
1960 lp [0] = Lerp (s0, lp [0], b);
1961 lp [1] = Lerp (lp [0], lp [1], b);
1962 lp [2] = Lerp (lp [1], lp [2], b);
1963 lp [3] = Lerp (lp [2], lp [3], b);
1964 hData -> mHrirs [j + i] = lp [3];
1968 b = 3.5e-6 * hData -> mIrRate;
1969 lp [0] = 0.0;
1970 lp [1] = 0.0;
1971 lp [2] = 0.0;
1972 lp [3] = 0.0;
1973 for (i = 0; i < n; i ++) {
1974 s0 = hData -> mHrirs [i];
1975 lp [0] = Lerp (s0, lp [0], b);
1976 lp [1] = Lerp (lp [0], lp [1], b);
1977 lp [2] = Lerp (lp [1], lp [2], b);
1978 lp [3] = Lerp (lp [2], lp [3], b);
1979 hData -> mHrirs [i] = lp [3];
1981 hData -> mEvStart = 0;
1984 // The following routines assume a full set of HRIRs for all elevations.
1986 // Normalize the HRIR set and slightly attenuate the result.
1987 static void NormalizeHrirs (const HrirDataT * hData) {
1988 uint step, end, n, j, i;
1989 double maxLevel;
1991 step = hData -> mIrSize;
1992 end = hData -> mIrCount * step;
1993 n = hData -> mIrPoints;
1994 maxLevel = 0.0;
1995 for (j = 0; j < end; j += step) {
1996 for (i = 0; i < n; i ++)
1997 maxLevel = fmax (fabs (hData -> mHrirs [j + i]), maxLevel);
1999 maxLevel = 1.01 * maxLevel;
2000 for (j = 0; j < end; j += step) {
2001 for (i = 0; i < n; i ++)
2002 hData -> mHrirs [j + i] /= maxLevel;
2006 // Calculate the left-ear time delay using a spherical head model.
2007 static double CalcLTD (const double ev, const double az, const double rad, const double dist) {
2008 double azp, dlp, l, al;
2010 azp = asin (cos (ev) * sin (az));
2011 dlp = sqrt ((dist * dist) + (rad * rad) + (2.0 * dist * rad * sin (azp)));
2012 l = sqrt ((dist * dist) - (rad * rad));
2013 al = (0.5 * M_PI) + azp;
2014 if (dlp > l)
2015 dlp = l + (rad * (al - acos (rad / dist)));
2016 return (dlp / 343.3);
2019 // Calculate the effective head-related time delays for each minimum-phase
2020 // HRIR.
2021 static void CalculateHrtds (const HeadModelT model, const double radius, HrirDataT * hData) {
2022 double minHrtd, maxHrtd;
2023 uint e, a, j;
2024 double t;
2026 minHrtd = 1000.0;
2027 maxHrtd = -1000.0;
2028 for (e = 0; e < hData -> mEvCount; e ++) {
2029 for (a = 0; a < hData -> mAzCount [e]; a ++) {
2030 j = hData -> mEvOffset [e] + a;
2031 if (model == HM_DATASET) {
2032 t = hData -> mHrtds [j] * radius / hData -> mRadius;
2033 } else {
2034 t = CalcLTD ((-90.0 + (e * 180.0 / (hData -> mEvCount - 1))) * M_PI / 180.0,
2035 (a * 360.0 / hData -> mAzCount [e]) * M_PI / 180.0,
2036 radius, hData -> mDistance);
2038 hData -> mHrtds [j] = t;
2039 maxHrtd = fmax (t, maxHrtd);
2040 minHrtd = fmin (t, minHrtd);
2043 maxHrtd -= minHrtd;
2044 for (j = 0; j < hData -> mIrCount; j ++)
2045 hData -> mHrtds [j] -= minHrtd;
2046 hData -> mMaxHrtd = maxHrtd;
2049 // Store the OpenAL Soft HRTF data set.
2050 static int StoreMhr (const HrirDataT * hData, const char * filename) {
2051 FILE * fp = NULL;
2052 uint e, step, end, n, j, i;
2053 int hpHist, v;
2055 if ((fp = fopen (filename, "wb")) == NULL) {
2056 fprintf (stderr, "Error: Could not open MHR file '%s'.\n", filename);
2057 return (0);
2059 if (! WriteAscii (MHR_FORMAT, fp, filename))
2060 return (0);
2061 if (! WriteBin4 (BO_LITTLE, 4, (uint32) hData -> mIrRate, fp, filename))
2062 return (0);
2063 if (! WriteBin4 (BO_LITTLE, 1, (uint32) hData -> mIrPoints, fp, filename))
2064 return (0);
2065 if (! WriteBin4 (BO_LITTLE, 1, (uint32) hData -> mEvCount, fp, filename))
2066 return (0);
2067 for (e = 0; e < hData -> mEvCount; e ++) {
2068 if (! WriteBin4 (BO_LITTLE, 1, (uint32) hData -> mAzCount [e], fp, filename))
2069 return (0);
2071 step = hData -> mIrSize;
2072 end = hData -> mIrCount * step;
2073 n = hData -> mIrPoints;
2074 srand (0x31DF840C);
2075 for (j = 0; j < end; j += step) {
2076 hpHist = 0;
2077 for (i = 0; i < n; i ++) {
2078 v = HpTpdfDither (32767.0 * hData -> mHrirs [j + i], & hpHist);
2079 if (! WriteBin4 (BO_LITTLE, 2, (uint32) v, fp, filename))
2080 return (0);
2083 for (j = 0; j < hData -> mIrCount; j ++) {
2084 v = (int) fmin (round (hData -> mIrRate * hData -> mHrtds [j]), MAX_HRTD);
2085 if (! WriteBin4 (BO_LITTLE, 1, (uint32) v, fp, filename))
2086 return (0);
2088 fclose (fp);
2089 return (1);
2092 // Store the OpenAL Soft built-in table.
2093 static int StoreTable (const HrirDataT * hData, const char * filename) {
2094 FILE * fp = NULL;
2095 uint step, end, n, j, i;
2096 int hpHist, v;
2097 char text [128 + 1];
2099 if ((fp = fopen (filename, "wb")) == NULL) {
2100 fprintf (stderr, "Error: Could not open table file '%s'.\n", filename);
2101 return (0);
2103 snprintf (text, 128, "/* Elevation metrics */\n"
2104 "static const ALubyte defaultAzCount[%u] = { ", hData -> mEvCount);
2105 if (! WriteAscii (text, fp, filename))
2106 return (0);
2107 for (i = 0; i < hData -> mEvCount; i ++) {
2108 snprintf (text, 128, "%u, ", hData -> mAzCount [i]);
2109 if (! WriteAscii (text, fp, filename))
2110 return (0);
2112 snprintf (text, 128, "};\n"
2113 "static const ALushort defaultEvOffset[%u] = { ", hData -> mEvCount);
2114 if (! WriteAscii (text, fp, filename))
2115 return (0);
2116 for (i = 0; i < hData -> mEvCount; i ++) {
2117 snprintf (text, 128, "%u, ", hData -> mEvOffset [i]);
2118 if (! WriteAscii (text, fp, filename))
2119 return (0);
2121 step = hData -> mIrSize;
2122 end = hData -> mIrCount * step;
2123 n = hData -> mIrPoints;
2124 snprintf (text, 128, "};\n\n"
2125 "/* HRIR Coefficients */\n"
2126 "static const ALshort defaultCoeffs[%u] =\n{\n", hData -> mIrCount * n);
2127 if (! WriteAscii (text, fp, filename))
2128 return (0);
2129 srand (0x31DF840C);
2130 for (j = 0; j < end; j += step) {
2131 if (! WriteAscii (" ", fp, filename))
2132 return (0);
2133 hpHist = 0;
2134 for (i = 0; i < n; i ++) {
2135 v = HpTpdfDither (32767.0 * hData -> mHrirs [j + i], & hpHist);
2136 snprintf (text, 128, " %+d,", v);
2137 if (! WriteAscii (text, fp, filename))
2138 return (0);
2140 if (! WriteAscii ("\n", fp, filename))
2141 return (0);
2143 snprintf (text, 128, "};\n\n"
2144 "/* HRIR Delays */\n"
2145 "static const ALubyte defaultDelays[%u] =\n{\n"
2146 " ", hData -> mIrCount);
2147 if (! WriteAscii (text, fp, filename))
2148 return (0);
2149 for (j = 0; j < hData -> mIrCount; j ++) {
2150 v = (int) fmin (round (hData -> mIrRate * hData -> mHrtds [j]), MAX_HRTD);
2151 snprintf (text, 128, " %d,", v);
2152 if (! WriteAscii (text, fp, filename))
2153 return (0);
2155 if (! WriteAscii ("\n};\n\n"
2156 "/* Default HRTF Definition */\n", fp, filename))
2157 return (0);
2158 snprintf (text, 128, "static const struct Hrtf DefaultHrtf = {\n"
2159 " %u, %u, %u, defaultAzCount, defaultEvOffset,\n",
2160 hData -> mIrRate, hData -> mIrPoints, hData -> mEvCount);
2161 if (! WriteAscii (text, fp, filename))
2162 return (0);
2163 if (! WriteAscii (" defaultCoeffs, defaultDelays, NULL\n"
2164 "};\n", fp, filename))
2165 return (0);
2166 fclose (fp);
2167 return (1);
2170 // Process the data set definition to read and validate the data set metrics.
2171 static int ProcessMetrics (TokenReaderT * tr, const uint fftSize, const uint truncSize, HrirDataT * hData) {
2172 char ident [MAX_IDENT_LEN + 1];
2173 uint line, col;
2174 int intVal;
2175 uint points;
2176 double fpVal;
2177 int hasRate = 0, hasPoints = 0, hasAzimuths = 0;
2178 int hasRadius = 0, hasDistance = 0;
2180 while (! (hasRate && hasPoints && hasAzimuths && hasRadius && hasDistance)) {
2181 TrIndication (tr, & line, & col);
2182 if (! TrReadIdent (tr, MAX_IDENT_LEN, ident))
2183 return (0);
2184 if (strcasecmp (ident, "rate") == 0) {
2185 if (hasRate) {
2186 TrErrorAt (tr, line, col, "Redefinition of 'rate'.\n");
2187 return (0);
2189 if (! TrReadOperator (tr, "="))
2190 return (0);
2191 if (! TrReadInt (tr, MIN_RATE, MAX_RATE, & intVal))
2192 return (0);
2193 hData -> mIrRate = (uint) intVal;
2194 hasRate = 1;
2195 } else if (strcasecmp (ident, "points") == 0) {
2196 if (hasPoints) {
2197 TrErrorAt (tr, line, col, "Redefinition of 'points'.\n");
2198 return (0);
2200 if (! TrReadOperator (tr, "="))
2201 return (0);
2202 TrIndication (tr, & line, & col);
2203 if (! TrReadInt (tr, MIN_POINTS, MAX_POINTS, & intVal))
2204 return (0);
2205 points = (uint) intVal;
2206 if ((fftSize > 0) && (points > fftSize)) {
2207 TrErrorAt (tr, line, col, "Value exceeds the overridden FFT size.\n");
2208 return (0);
2210 if (points < truncSize) {
2211 TrErrorAt (tr, line, col, "Value is below the truncation size.\n");
2212 return (0);
2214 hData -> mIrPoints = points;
2215 hData -> mFftSize = fftSize;
2216 if (fftSize <= 0) {
2217 points = 1;
2218 while (points < (4 * hData -> mIrPoints))
2219 points <<= 1;
2220 hData -> mFftSize = points;
2221 hData -> mIrSize = 1 + (points / 2);
2222 } else {
2223 hData -> mFftSize = fftSize;
2224 hData -> mIrSize = 1 + (fftSize / 2);
2225 if (points > hData -> mIrSize)
2226 hData -> mIrSize = points;
2228 hasPoints = 1;
2229 } else if (strcasecmp (ident, "azimuths") == 0) {
2230 if (hasAzimuths) {
2231 TrErrorAt (tr, line, col, "Redefinition of 'azimuths'.\n");
2232 return (0);
2234 if (! TrReadOperator (tr, "="))
2235 return (0);
2236 hData -> mIrCount = 0;
2237 hData -> mEvCount = 0;
2238 hData -> mEvOffset [0] = 0;
2239 for (;;) {
2240 if (! TrReadInt (tr, MIN_AZ_COUNT, MAX_AZ_COUNT, & intVal))
2241 return (0);
2242 hData -> mAzCount [hData -> mEvCount] = (uint) intVal;
2243 hData -> mIrCount += (uint) intVal;
2244 hData -> mEvCount ++;
2245 if (! TrIsOperator (tr, ","))
2246 break;
2247 if (hData -> mEvCount >= MAX_EV_COUNT) {
2248 TrError (tr, "Exceeded the maximum of %d elevations.\n", MAX_EV_COUNT);
2249 return (0);
2251 hData -> mEvOffset [hData -> mEvCount] = hData -> mEvOffset [hData -> mEvCount - 1] + ((uint) intVal);
2252 TrReadOperator (tr, ",");
2254 if (hData -> mEvCount < MIN_EV_COUNT) {
2255 TrErrorAt (tr, line, col, "Did not reach the minimum of %d azimuth counts.\n", MIN_EV_COUNT);
2256 return (0);
2258 hasAzimuths = 1;
2259 } else if (strcasecmp (ident, "radius") == 0) {
2260 if (hasRadius) {
2261 TrErrorAt (tr, line, col, "Redefinition of 'radius'.\n");
2262 return (0);
2264 if (! TrReadOperator (tr, "="))
2265 return (0);
2266 if (! TrReadFloat (tr, MIN_RADIUS, MAX_RADIUS, & fpVal))
2267 return (0);
2268 hData -> mRadius = fpVal;
2269 hasRadius = 1;
2270 } else if (strcasecmp (ident, "distance") == 0) {
2271 if (hasDistance) {
2272 TrErrorAt (tr, line, col, "Redefinition of 'distance'.\n");
2273 return (0);
2275 if (! TrReadOperator (tr, "="))
2276 return (0);
2277 if (! TrReadFloat (tr, MIN_DISTANCE, MAX_DISTANCE, & fpVal))
2278 return (0);
2279 hData -> mDistance = fpVal;
2280 hasDistance = 1;
2281 } else {
2282 TrErrorAt (tr, line, col, "Expected a metric name.\n");
2283 return (0);
2285 TrSkipWhitespace (tr);
2287 return (1);
2290 // Parse an index pair from the data set definition.
2291 static int ReadIndexPair (TokenReaderT * tr, const HrirDataT * hData, uint * ei, uint * ai) {
2292 int intVal;
2294 if (! TrReadInt (tr, 0, (int) hData -> mEvCount, & intVal))
2295 return (0);
2296 (* ei) = (uint) intVal;
2297 if (! TrReadOperator (tr, ","))
2298 return (0);
2299 if (! TrReadInt (tr, 0, (int) hData -> mAzCount [(* ei)], & intVal))
2300 return (0);
2301 (* ai) = (uint) intVal;
2302 return (1);
2305 // Match the source format from a given identifier.
2306 static SourceFormatT MatchSourceFormat (const char * ident) {
2307 if (strcasecmp (ident, "wave") == 0)
2308 return (SF_WAVE);
2309 else if (strcasecmp (ident, "bin_le") == 0)
2310 return (SF_BIN_LE);
2311 else if (strcasecmp (ident, "bin_be") == 0)
2312 return (SF_BIN_BE);
2313 else if (strcasecmp (ident, "ascii") == 0)
2314 return (SF_ASCII);
2315 return (SF_NONE);
2318 // Match the source element type from a given identifier.
2319 static ElementTypeT MatchElementType (const char * ident) {
2320 if (strcasecmp (ident, "int") == 0)
2321 return (ET_INT);
2322 else if (strcasecmp (ident, "fp") == 0)
2323 return (ET_FP);
2324 return (ET_NONE);
2327 // Parse and validate a source reference from the data set definition.
2328 static int ReadSourceRef (TokenReaderT * tr, SourceRefT * src) {
2329 uint line, col;
2330 char ident [MAX_IDENT_LEN + 1];
2331 int intVal;
2333 TrIndication (tr, & line, & col);
2334 if (! TrReadIdent (tr, MAX_IDENT_LEN, ident))
2335 return (0);
2336 src -> mFormat = MatchSourceFormat (ident);
2337 if (src -> mFormat == SF_NONE) {
2338 TrErrorAt (tr, line, col, "Expected a source format.\n");
2339 return (0);
2341 if (! TrReadOperator (tr, "("))
2342 return (0);
2343 if (src -> mFormat == SF_WAVE) {
2344 if (! TrReadInt (tr, 0, MAX_WAVE_CHANNELS, & intVal))
2345 return (0);
2346 src -> mType = ET_NONE;
2347 src -> mSize = 0;
2348 src -> mBits = 0;
2349 src -> mChannel = (uint) intVal;
2350 src -> mSkip = 0;
2351 } else {
2352 TrIndication (tr, & line, & col);
2353 if (! TrReadIdent (tr, MAX_IDENT_LEN, ident))
2354 return (0);
2355 src -> mType = MatchElementType (ident);
2356 if (src -> mType == ET_NONE) {
2357 TrErrorAt (tr, line, col, "Expected a source element type.\n");
2358 return (0);
2360 if ((src -> mFormat == SF_BIN_LE) || (src -> mFormat == SF_BIN_BE)) {
2361 if (! TrReadOperator (tr, ","))
2362 return (0);
2363 if (src -> mType == ET_INT) {
2364 if (! TrReadInt (tr, MIN_BIN_SIZE, MAX_BIN_SIZE, & intVal))
2365 return (0);
2366 src -> mSize = (uint) intVal;
2367 if (TrIsOperator (tr, ",")) {
2368 TrReadOperator (tr, ",");
2369 TrIndication (tr, & line, & col);
2370 if (! TrReadInt (tr, -2147483647 - 1, 2147483647, & intVal))
2371 return (0);
2372 if ((abs (intVal) < MIN_BIN_BITS) || (((uint) abs (intVal)) > (8 * src -> mSize))) {
2373 TrErrorAt (tr, line, col, "Expected a value of (+/-) %d to %d.\n", MIN_BIN_BITS, 8 * src -> mSize);
2374 return (0);
2376 src -> mBits = intVal;
2377 } else {
2378 src -> mBits = (int) (8 * src -> mSize);
2380 } else {
2381 TrIndication (tr, & line, & col);
2382 if (! TrReadInt (tr, -2147483647 - 1, 2147483647, & intVal))
2383 return (0);
2384 if ((intVal != 4) && (intVal != 8)) {
2385 TrErrorAt (tr, line, col, "Expected a value of 4 or 8.\n");
2386 return (0);
2388 src -> mSize = (uint) intVal;
2389 src -> mBits = 0;
2391 } else if ((src -> mFormat == SF_ASCII) && (src -> mType == ET_INT)) {
2392 if (! TrReadOperator (tr, ","))
2393 return (0);
2394 if (! TrReadInt (tr, MIN_ASCII_BITS, MAX_ASCII_BITS, & intVal))
2395 return (0);
2396 src -> mSize = 0;
2397 src -> mBits = intVal;
2398 } else {
2399 src -> mSize = 0;
2400 src -> mBits = 0;
2402 if (TrIsOperator (tr, ";")) {
2403 TrReadOperator (tr, ";");
2404 if (! TrReadInt (tr, 0, 0x7FFFFFFF, & intVal))
2405 return (0);
2406 src -> mSkip = (uint) intVal;
2407 } else {
2408 src -> mSkip = 0;
2411 if (! TrReadOperator (tr, ")"))
2412 return (0);
2413 if (TrIsOperator (tr, "@")) {
2414 TrReadOperator (tr, "@");
2415 if (! TrReadInt (tr, 0, 0x7FFFFFFF, & intVal))
2416 return (0);
2417 src -> mOffset = (uint) intVal;
2418 } else {
2419 src -> mOffset = 0;
2421 if (! TrReadOperator (tr, ":"))
2422 return (0);
2423 if (! TrReadString (tr, MAX_PATH_LEN, src -> mPath))
2424 return (0);
2425 return (1);
2428 // Process the list of sources in the data set definition.
2429 static int ProcessSources (const HeadModelT model, TokenReaderT * tr, HrirDataT * hData) {
2430 uint * setCount = NULL, * setFlag = NULL;
2431 double * hrir = NULL;
2432 uint line, col, ei, ai;
2433 SourceRefT src;
2434 double factor;
2436 setCount = (uint *) calloc (hData -> mEvCount, sizeof (uint));
2437 setFlag = (uint *) calloc (hData -> mIrCount, sizeof (uint));
2438 hrir = CreateArray (hData -> mIrPoints);
2439 while (TrIsOperator (tr, "[")) {
2440 TrIndication (tr, & line, & col);
2441 TrReadOperator (tr, "[");
2442 if (ReadIndexPair (tr, hData, & ei, & ai)) {
2443 if (TrReadOperator (tr, "]")) {
2444 if (! setFlag [hData -> mEvOffset [ei] + ai]) {
2445 if (TrReadOperator (tr, "=")) {
2446 factor = 1.0;
2447 for (;;) {
2448 if (ReadSourceRef (tr, & src)) {
2449 if (LoadSource (& src, hData -> mIrRate, hData -> mIrPoints, hrir)) {
2450 if (model == HM_DATASET)
2451 AverageHrirOnset (hrir, 1.0 / factor, ei, ai, hData);
2452 AverageHrirMagnitude (hrir, 1.0 / factor, ei, ai, hData);
2453 factor += 1.0;
2454 if (! TrIsOperator (tr, "+"))
2455 break;
2456 TrReadOperator (tr, "+");
2457 continue;
2460 DestroyArray (hrir);
2461 free (setFlag);
2462 free (setCount);
2463 return (0);
2465 setFlag [hData -> mEvOffset [ei] + ai] = 1;
2466 setCount [ei] ++;
2467 continue;
2469 } else {
2470 TrErrorAt (tr, line, col, "Redefinition of source.\n");
2474 DestroyArray (hrir);
2475 free (setFlag);
2476 free (setCount);
2477 return (0);
2479 ei = 0;
2480 while ((ei < hData -> mEvCount) && (setCount [ei] < 1))
2481 ei ++;
2482 if (ei < hData -> mEvCount) {
2483 hData -> mEvStart = ei;
2484 while ((ei < hData -> mEvCount) && (setCount [ei] == hData -> mAzCount [ei]))
2485 ei ++;
2486 if (ei >= hData -> mEvCount) {
2487 if (! TrLoad (tr)) {
2488 DestroyArray (hrir);
2489 free (setFlag);
2490 free (setCount);
2491 return (1);
2492 } else {
2493 TrError (tr, "Errant data at end of source list.\n");
2495 } else {
2496 TrError (tr, "Missing sources for elevation index %d.\n", ei);
2498 } else {
2499 TrError (tr, "Missing source references.\n");
2501 DestroyArray (hrir);
2502 free (setFlag);
2503 free (setCount);
2504 return (0);
2507 /* Parse the data set definition and process the source data, storing the
2508 * resulting data set as desired. If the input name is NULL it will read
2509 * from standard input.
2511 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) {
2512 FILE * fp = NULL;
2513 TokenReaderT tr;
2514 HrirDataT hData;
2515 double * dfa = NULL;
2516 char rateStr [8 + 1], expName [MAX_PATH_LEN];
2518 hData . mIrRate = 0;
2519 hData . mIrPoints = 0;
2520 hData . mFftSize = 0;
2521 hData . mIrSize = 0;
2522 hData . mIrCount = 0;
2523 hData . mEvCount = 0;
2524 hData . mRadius = 0;
2525 hData . mDistance = 0;
2526 fprintf (stdout, "Reading HRIR definition...\n");
2527 if (inName != NULL) {
2528 fp = fopen (inName, "r");
2529 if (fp == NULL) {
2530 fprintf (stderr, "Error: Could not open definition file '%s'\n", inName);
2531 return (0);
2533 TrSetup (fp, inName, & tr);
2534 } else {
2535 fp = stdin;
2536 TrSetup (fp, "<stdin>", & tr);
2538 if (! ProcessMetrics (& tr, fftSize, truncSize, & hData)) {
2539 if (inName != NULL)
2540 fclose (fp);
2541 return (0);
2543 hData . mHrirs = CreateArray (hData . mIrCount * hData . mIrSize);
2544 hData . mHrtds = CreateArray (hData . mIrCount);
2545 if (! ProcessSources (model, & tr, & hData)) {
2546 DestroyArray (hData . mHrtds);
2547 DestroyArray (hData . mHrirs);
2548 if (inName != NULL)
2549 fclose (fp);
2550 return (0);
2552 if (inName != NULL)
2553 fclose (fp);
2554 if (equalize) {
2555 dfa = CreateArray (1 + (hData . mFftSize / 2));
2556 fprintf (stdout, "Calculating diffuse-field average...\n");
2557 CalculateDiffuseFieldAverage (& hData, surface, limit, dfa);
2558 fprintf (stdout, "Performing diffuse-field equalization...\n");
2559 DiffuseFieldEqualize (dfa, & hData);
2560 DestroyArray (dfa);
2562 fprintf (stdout, "Performing minimum phase reconstruction...\n");
2563 ReconstructHrirs (& hData);
2564 if ((outRate != 0) && (outRate != hData . mIrRate)) {
2565 fprintf (stdout, "Resampling HRIRs...\n");
2566 ResampleHrirs (outRate, & hData);
2568 fprintf (stdout, "Truncating minimum-phase HRIRs...\n");
2569 hData . mIrPoints = truncSize;
2570 fprintf (stdout, "Synthesizing missing elevations...\n");
2571 if (model == HM_DATASET)
2572 SynthesizeOnsets (& hData);
2573 SynthesizeHrirs (& hData);
2574 fprintf (stdout, "Normalizing final HRIRs...\n");
2575 NormalizeHrirs (& hData);
2576 fprintf (stdout, "Calculating impulse delays...\n");
2577 CalculateHrtds (model, (radius > DEFAULT_CUSTOM_RADIUS) ? radius : hData . mRadius, & hData);
2578 snprintf (rateStr, 8, "%u", hData . mIrRate);
2579 StrSubst (outName, "%r", rateStr, MAX_PATH_LEN, expName);
2580 switch (outFormat) {
2581 case OF_MHR :
2582 fprintf (stdout, "Creating MHR data set file...\n");
2583 if (! StoreMhr (& hData, expName))
2584 return (0);
2585 break;
2586 case OF_TABLE :
2587 fprintf (stderr, "Creating OpenAL Soft table file...\n");
2588 if (! StoreTable (& hData, expName))
2589 return (0);
2590 break;
2591 default :
2592 break;
2594 DestroyArray (hData . mHrtds);
2595 DestroyArray (hData . mHrirs);
2596 return (1);
2599 // Standard command line dispatch.
2600 int main (const int argc, const char * argv []) {
2601 const char * inName = NULL, * outName = NULL;
2602 OutputFormatT outFormat;
2603 int argi;
2604 uint outRate, fftSize;
2605 int equalize, surface;
2606 double limit;
2607 uint truncSize;
2608 HeadModelT model;
2609 double radius;
2610 char * end = NULL;
2612 if (argc < 2) {
2613 fprintf (stderr, "Error: No command specified. See '%s -h' for help.\n", argv [0]);
2614 return (-1);
2616 if ((strcmp (argv [1], "--help") == 0) || (strcmp (argv [1], "-h") == 0)) {
2617 fprintf (stdout, "HRTF Processing and Composition Utility\n\n");
2618 fprintf (stdout, "Usage: %s <command> [<option>...]\n\n", argv [0]);
2619 fprintf (stdout, "Commands:\n");
2620 fprintf (stdout, " -m, --make-mhr Makes an OpenAL Soft compatible HRTF data set.\n");
2621 fprintf (stdout, " Defaults output to: ./oalsoft_hrtf_%%r.mhr\n");
2622 fprintf (stdout, " -t, --make-tab Makes the built-in table used when compiling OpenAL Soft.\n");
2623 fprintf (stdout, " Defaults output to: ./hrtf_tables.inc\n");
2624 fprintf (stdout, " -h, --help Displays this help information.\n\n");
2625 fprintf (stdout, "Options:\n");
2626 fprintf (stdout, " -r=<rate> Change the data set sample rate to the specified value and\n");
2627 fprintf (stdout, " resample the HRIRs accordingly.\n");
2628 fprintf (stdout, " -f=<points> Override the FFT window size (defaults to the first power-\n");
2629 fprintf (stdout, " of-two that fits four times the number of HRIR points).\n");
2630 fprintf (stdout, " -e={on|off} Toggle diffuse-field equalization (default: %s).\n", (DEFAULT_EQUALIZE ? "on" : "off"));
2631 fprintf (stdout, " -s={on|off} Toggle surface-weighted diffuse-field average (default: %s).\n", (DEFAULT_SURFACE ? "on" : "off"));
2632 fprintf (stdout, " -l={<dB>|none} Specify a limit to the magnitude range of the diffuse-field\n");
2633 fprintf (stdout, " average (default: %.2f).\n", DEFAULT_LIMIT);
2634 fprintf (stdout, " -w=<points> Specify the size of the truncation window that's applied\n");
2635 fprintf (stdout, " after minimum-phase reconstruction (default: %u).\n", DEFAULT_TRUNCSIZE);
2636 fprintf (stdout, " -d={dataset| Specify the model used for calculating the head-delay timing\n");
2637 fprintf (stdout, " sphere} values (default: %s).\n", ((DEFAULT_HEAD_MODEL == HM_DATASET) ? "dataset" : "sphere"));
2638 fprintf (stdout, " -c=<size> Use a customized head radius measured ear-to-ear in meters.\n");
2639 fprintf (stdout, " -i=<filename> Specify an HRIR definition file to use (defaults to stdin).\n");
2640 fprintf (stdout, " -o=<filename> Specify an output file. Overrides command-selected default.\n");
2641 fprintf (stdout, " Use of '%%r' will be substituted with the data set sample rate.\n");
2642 return (0);
2644 if ((strcmp (argv [1], "--make-mhr") == 0) || (strcmp (argv [1], "-m") == 0)) {
2645 if (argc > 3)
2646 outName = argv [3];
2647 else
2648 outName = "./oalsoft_hrtf_%r.mhr";
2649 outFormat = OF_MHR;
2650 } else if ((strcmp (argv [1], "--make-tab") == 0) || (strcmp (argv [1], "-t") == 0)) {
2651 if (argc > 3)
2652 outName = argv [3];
2653 else
2654 outName = "./hrtf_tables.inc";
2655 outFormat = OF_TABLE;
2656 } else {
2657 fprintf (stderr, "Error: Invalid command '%s'.\n", argv [1]);
2658 return (-1);
2660 argi = 2;
2661 outRate = 0;
2662 fftSize = 0;
2663 equalize = DEFAULT_EQUALIZE;
2664 surface = DEFAULT_SURFACE;
2665 limit = DEFAULT_LIMIT;
2666 truncSize = DEFAULT_TRUNCSIZE;
2667 model = DEFAULT_HEAD_MODEL;
2668 radius = DEFAULT_CUSTOM_RADIUS;
2669 while (argi < argc) {
2670 if (strncmp (argv [argi], "-r=", 3) == 0) {
2671 outRate = strtoul (& argv [argi] [3], & end, 10);
2672 if ((end [0] != '\0') || (outRate < MIN_RATE) || (outRate > MAX_RATE)) {
2673 fprintf (stderr, "Error: Expected a value from %u to %u for '-r'.\n", MIN_RATE, MAX_RATE);
2674 return (-1);
2676 } else if (strncmp (argv [argi], "-f=", 3) == 0) {
2677 fftSize = strtoul (& argv [argi] [3], & end, 10);
2678 if ((end [0] != '\0') || (fftSize & (fftSize - 1)) || (fftSize < MIN_FFTSIZE) || (fftSize > MAX_FFTSIZE)) {
2679 fprintf (stderr, "Error: Expected a power-of-two value from %u to %u for '-f'.\n", MIN_FFTSIZE, MAX_FFTSIZE);
2680 return (-1);
2682 } else if (strncmp (argv [argi], "-e=", 3) == 0) {
2683 if (strcmp (& argv [argi] [3], "on") == 0) {
2684 equalize = 1;
2685 } else if (strcmp (& argv [argi] [3], "off") == 0) {
2686 equalize = 0;
2687 } else {
2688 fprintf (stderr, "Error: Expected 'on' or 'off' for '-e'.\n");
2689 return (-1);
2691 } else if (strncmp (argv [argi], "-s=", 3) == 0) {
2692 if (strcmp (& argv [argi] [3], "on") == 0) {
2693 surface = 1;
2694 } else if (strcmp (& argv [argi] [3], "off") == 0) {
2695 surface = 0;
2696 } else {
2697 fprintf (stderr, "Error: Expected 'on' or 'off' for '-s'.\n");
2698 return (-1);
2700 } else if (strncmp (argv [argi], "-l=", 3) == 0) {
2701 if (strcmp (& argv [argi] [3], "none") == 0) {
2702 limit = 0.0;
2703 } else {
2704 limit = strtod (& argv [argi] [3], & end);
2705 if ((end [0] != '\0') || (limit < MIN_LIMIT) || (limit > MAX_LIMIT)) {
2706 fprintf (stderr, "Error: Expected 'none' or a value from %.2f to %.2f for '-l'.\n", MIN_LIMIT, MAX_LIMIT);
2707 return (-1);
2710 } else if (strncmp (argv [argi], "-w=", 3) == 0) {
2711 truncSize = strtoul (& argv [argi] [3], & end, 10);
2712 if ((end [0] != '\0') || (truncSize < MIN_TRUNCSIZE) || (truncSize > MAX_TRUNCSIZE) || (truncSize % MOD_TRUNCSIZE)) {
2713 fprintf (stderr, "Error: Expected a value from %u to %u in multiples of %u for '-w'.\n", MIN_TRUNCSIZE, MAX_TRUNCSIZE, MOD_TRUNCSIZE);
2714 return (-1);
2716 } else if (strncmp (argv [argi], "-d=", 3) == 0) {
2717 if (strcmp (& argv [argi] [3], "dataset") == 0) {
2718 model = HM_DATASET;
2719 } else if (strcmp (& argv [argi] [3], "sphere") == 0) {
2720 model = HM_SPHERE;
2721 } else {
2722 fprintf (stderr, "Error: Expected 'dataset' or 'sphere' for '-d'.\n");
2723 return (-1);
2725 } else if (strncmp (argv [argi], "-c=", 3) == 0) {
2726 radius = strtod (& argv [argi] [3], & end);
2727 if ((end [0] != '\0') || (radius < MIN_CUSTOM_RADIUS) || (radius > MAX_CUSTOM_RADIUS)) {
2728 fprintf (stderr, "Error: Expected a value from %.2f to %.2f for '-c'.\n", MIN_CUSTOM_RADIUS, MAX_CUSTOM_RADIUS);
2729 return (-1);
2731 } else if (strncmp (argv [argi], "-i=", 3) == 0) {
2732 inName = & argv [argi] [3];
2733 } else if (strncmp (argv [argi], "-o=", 3) == 0) {
2734 outName = & argv [argi] [3];
2735 } else {
2736 fprintf (stderr, "Error: Invalid option '%s'.\n", argv [argi]);
2737 return (-1);
2739 argi ++;
2741 if (! ProcessDefinition (inName, outRate, fftSize, equalize, surface, limit, truncSize, model, radius, outFormat, outName))
2742 return (-1);
2743 fprintf (stdout, "Operation completed.\n");
2744 return (0);